context-mode 1.0.168 → 2.0.0-next.5

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 (395) hide show
  1. package/.claude-plugin/marketplace.json +4 -22
  2. package/.claude-plugin/plugin.json +9 -24
  3. package/SHA256SUMS +31 -0
  4. package/claude-code/skills/ctx-doctor/SKILL.md +6 -0
  5. package/claude-code/skills/ctx-stats/SKILL.md +6 -0
  6. package/claude-code/skills/ctx-upgrade/SKILL.md +6 -0
  7. package/cli.mjs +6744 -0
  8. package/copilot/plugin.json +14 -0
  9. package/fixtures/hook-roundtrip.json +22 -0
  10. package/gemini-extension.json +14 -0
  11. package/hook.mjs +202 -0
  12. package/hooks/claude-code.json +50 -0
  13. package/hooks/codex.json +50 -0
  14. package/hooks/copilot-cli.json +33 -0
  15. package/hooks/hooks.json +16 -111
  16. package/hooks/kiro.json +69 -0
  17. package/hooks/qwen.json +50 -0
  18. package/hooks/vscode.json +40 -0
  19. package/hooks/zcode.json +53 -0
  20. package/opencode/plugin.js +22456 -0
  21. package/package.json +29 -114
  22. package/pi/index.js +50841 -0
  23. package/pi/skills/ctx-doctor/SKILL.md +6 -0
  24. package/pi/skills/ctx-stats/SKILL.md +6 -0
  25. package/pi/skills/ctx-upgrade/SKILL.md +6 -0
  26. package/qwen-extension.json +15 -0
  27. package/run.mjs +5633 -0
  28. package/search.mjs +5633 -0
  29. package/server.mjs +48198 -0
  30. package/skills/ctx-doctor/SKILL.md +3 -19
  31. package/skills/ctx-stats/SKILL.md +3 -23
  32. package/skills/ctx-upgrade/SKILL.md +3 -28
  33. package/.codex-plugin/hooks.json +0 -65
  34. package/.codex-plugin/mcp.json +0 -13
  35. package/.codex-plugin/plugin.json +0 -31
  36. package/.openclaw-plugin/index.ts +0 -12
  37. package/.openclaw-plugin/openclaw.plugin.json +0 -38
  38. package/.openclaw-plugin/package.json +0 -28
  39. package/LICENSE +0 -94
  40. package/README.md +0 -1619
  41. package/bin/statusline.mjs +0 -378
  42. package/build/adapters/antigravity/index.d.ts +0 -51
  43. package/build/adapters/antigravity/index.js +0 -169
  44. package/build/adapters/antigravity-cli/index.d.ts +0 -51
  45. package/build/adapters/antigravity-cli/index.js +0 -342
  46. package/build/adapters/base.d.ts +0 -92
  47. package/build/adapters/base.js +0 -135
  48. package/build/adapters/claude-code/config.d.ts +0 -8
  49. package/build/adapters/claude-code/config.js +0 -8
  50. package/build/adapters/claude-code/hooks.d.ts +0 -106
  51. package/build/adapters/claude-code/hooks.js +0 -183
  52. package/build/adapters/claude-code/index.d.ts +0 -80
  53. package/build/adapters/claude-code/index.js +0 -569
  54. package/build/adapters/claude-code-base.d.ts +0 -49
  55. package/build/adapters/claude-code-base.js +0 -113
  56. package/build/adapters/client-map.d.ts +0 -10
  57. package/build/adapters/client-map.js +0 -42
  58. package/build/adapters/codex/config.d.ts +0 -8
  59. package/build/adapters/codex/config.js +0 -8
  60. package/build/adapters/codex/hooks.d.ts +0 -55
  61. package/build/adapters/codex/hooks.js +0 -64
  62. package/build/adapters/codex/index.d.ts +0 -87
  63. package/build/adapters/codex/index.js +0 -992
  64. package/build/adapters/codex/paths.d.ts +0 -1
  65. package/build/adapters/codex/paths.js +0 -12
  66. package/build/adapters/codex/usage.d.ts +0 -107
  67. package/build/adapters/codex/usage.js +0 -227
  68. package/build/adapters/copilot-base.d.ts +0 -94
  69. package/build/adapters/copilot-base.js +0 -297
  70. package/build/adapters/copilot-cli/hooks.d.ts +0 -33
  71. package/build/adapters/copilot-cli/hooks.js +0 -64
  72. package/build/adapters/copilot-cli/index.d.ts +0 -48
  73. package/build/adapters/copilot-cli/index.js +0 -341
  74. package/build/adapters/cursor/config.d.ts +0 -4
  75. package/build/adapters/cursor/config.js +0 -4
  76. package/build/adapters/cursor/hooks.d.ts +0 -55
  77. package/build/adapters/cursor/hooks.js +0 -82
  78. package/build/adapters/cursor/index.d.ts +0 -64
  79. package/build/adapters/cursor/index.js +0 -517
  80. package/build/adapters/detect.d.ts +0 -136
  81. package/build/adapters/detect.js +0 -623
  82. package/build/adapters/gemini-cli/config.d.ts +0 -8
  83. package/build/adapters/gemini-cli/config.js +0 -8
  84. package/build/adapters/gemini-cli/hooks.d.ts +0 -83
  85. package/build/adapters/gemini-cli/hooks.js +0 -115
  86. package/build/adapters/gemini-cli/index.d.ts +0 -80
  87. package/build/adapters/gemini-cli/index.js +0 -483
  88. package/build/adapters/jetbrains-copilot/config.d.ts +0 -8
  89. package/build/adapters/jetbrains-copilot/config.js +0 -8
  90. package/build/adapters/jetbrains-copilot/hooks.d.ts +0 -59
  91. package/build/adapters/jetbrains-copilot/hooks.js +0 -87
  92. package/build/adapters/jetbrains-copilot/index.d.ts +0 -31
  93. package/build/adapters/jetbrains-copilot/index.js +0 -131
  94. package/build/adapters/kimi/config.d.ts +0 -8
  95. package/build/adapters/kimi/config.js +0 -8
  96. package/build/adapters/kimi/hooks.d.ts +0 -28
  97. package/build/adapters/kimi/hooks.js +0 -34
  98. package/build/adapters/kimi/index.d.ts +0 -66
  99. package/build/adapters/kimi/index.js +0 -537
  100. package/build/adapters/kimi/paths.d.ts +0 -21
  101. package/build/adapters/kimi/paths.js +0 -52
  102. package/build/adapters/kimi/usage.d.ts +0 -82
  103. package/build/adapters/kimi/usage.js +0 -217
  104. package/build/adapters/kiro/hooks.d.ts +0 -61
  105. package/build/adapters/kiro/hooks.js +0 -94
  106. package/build/adapters/kiro/index.d.ts +0 -61
  107. package/build/adapters/kiro/index.js +0 -301
  108. package/build/adapters/omp/index.d.ts +0 -65
  109. package/build/adapters/omp/index.js +0 -182
  110. package/build/adapters/omp/plugin.d.ts +0 -81
  111. package/build/adapters/omp/plugin.js +0 -331
  112. package/build/adapters/omp/usage.d.ts +0 -49
  113. package/build/adapters/omp/usage.js +0 -110
  114. package/build/adapters/openclaw/config.d.ts +0 -8
  115. package/build/adapters/openclaw/config.js +0 -8
  116. package/build/adapters/openclaw/hooks.d.ts +0 -50
  117. package/build/adapters/openclaw/hooks.js +0 -61
  118. package/build/adapters/openclaw/index.d.ts +0 -74
  119. package/build/adapters/openclaw/index.js +0 -439
  120. package/build/adapters/openclaw/mcp-tools.d.ts +0 -54
  121. package/build/adapters/openclaw/mcp-tools.js +0 -207
  122. package/build/adapters/openclaw/plugin.d.ts +0 -141
  123. package/build/adapters/openclaw/plugin.js +0 -818
  124. package/build/adapters/openclaw/session-db.d.ts +0 -55
  125. package/build/adapters/openclaw/session-db.js +0 -88
  126. package/build/adapters/openclaw/usage.d.ts +0 -34
  127. package/build/adapters/openclaw/usage.js +0 -52
  128. package/build/adapters/openclaw/workspace-router.d.ts +0 -29
  129. package/build/adapters/openclaw/workspace-router.js +0 -64
  130. package/build/adapters/opencode/config.d.ts +0 -8
  131. package/build/adapters/opencode/config.js +0 -8
  132. package/build/adapters/opencode/hooks.d.ts +0 -38
  133. package/build/adapters/opencode/hooks.js +0 -50
  134. package/build/adapters/opencode/index.d.ts +0 -67
  135. package/build/adapters/opencode/index.js +0 -463
  136. package/build/adapters/opencode/plugin.d.ts +0 -184
  137. package/build/adapters/opencode/plugin.js +0 -558
  138. package/build/adapters/opencode/zod3tov4.d.ts +0 -1
  139. package/build/adapters/opencode/zod3tov4.js +0 -132
  140. package/build/adapters/pi/extension.d.ts +0 -81
  141. package/build/adapters/pi/extension.js +0 -861
  142. package/build/adapters/pi/index.d.ts +0 -57
  143. package/build/adapters/pi/index.js +0 -173
  144. package/build/adapters/pi/mcp-bridge.d.ts +0 -268
  145. package/build/adapters/pi/mcp-bridge.js +0 -894
  146. package/build/adapters/qwen-code/hooks.d.ts +0 -26
  147. package/build/adapters/qwen-code/hooks.js +0 -29
  148. package/build/adapters/qwen-code/index.d.ts +0 -40
  149. package/build/adapters/qwen-code/index.js +0 -361
  150. package/build/adapters/qwen-code/usage.d.ts +0 -90
  151. package/build/adapters/qwen-code/usage.js +0 -222
  152. package/build/adapters/types.d.ts +0 -360
  153. package/build/adapters/types.js +0 -118
  154. package/build/adapters/vscode-copilot/config.d.ts +0 -8
  155. package/build/adapters/vscode-copilot/config.js +0 -8
  156. package/build/adapters/vscode-copilot/hooks.d.ts +0 -71
  157. package/build/adapters/vscode-copilot/hooks.js +0 -98
  158. package/build/adapters/vscode-copilot/index.d.ts +0 -32
  159. package/build/adapters/vscode-copilot/index.js +0 -222
  160. package/build/adapters/zed/index.d.ts +0 -40
  161. package/build/adapters/zed/index.js +0 -163
  162. package/build/cache-heal.d.ts +0 -48
  163. package/build/cache-heal.js +0 -150
  164. package/build/cli.d.ts +0 -34
  165. package/build/cli.js +0 -1827
  166. package/build/concurrency/runPool.d.ts +0 -36
  167. package/build/concurrency/runPool.js +0 -51
  168. package/build/db-base.d.ts +0 -179
  169. package/build/db-base.js +0 -569
  170. package/build/executor.d.ts +0 -72
  171. package/build/executor.js +0 -678
  172. package/build/exit-classify.d.ts +0 -19
  173. package/build/exit-classify.js +0 -12
  174. package/build/fetch-cache.d.ts +0 -13
  175. package/build/fetch-cache.js +0 -15
  176. package/build/lifecycle.d.ts +0 -124
  177. package/build/lifecycle.js +0 -278
  178. package/build/openclaw/mcp-tools.d.ts +0 -54
  179. package/build/openclaw/mcp-tools.js +0 -198
  180. package/build/openclaw/workspace-router.d.ts +0 -29
  181. package/build/openclaw/workspace-router.js +0 -64
  182. package/build/openclaw-plugin.d.ts +0 -130
  183. package/build/openclaw-plugin.js +0 -626
  184. package/build/opencode-plugin.d.ts +0 -122
  185. package/build/opencode-plugin.js +0 -375
  186. package/build/pi-extension.d.ts +0 -14
  187. package/build/pi-extension.js +0 -451
  188. package/build/routing-block.d.ts +0 -8
  189. package/build/routing-block.js +0 -86
  190. package/build/runPool.d.ts +0 -36
  191. package/build/runPool.js +0 -51
  192. package/build/runtime.d.ts +0 -71
  193. package/build/runtime.js +0 -659
  194. package/build/search/auto-memory.d.ts +0 -47
  195. package/build/search/auto-memory.js +0 -170
  196. package/build/search/ctx-search-schema.d.ts +0 -90
  197. package/build/search/ctx-search-schema.js +0 -135
  198. package/build/search/flood-guard.d.ts +0 -57
  199. package/build/search/flood-guard.js +0 -80
  200. package/build/search/unified.d.ts +0 -56
  201. package/build/search/unified.js +0 -104
  202. package/build/security.d.ts +0 -206
  203. package/build/security.js +0 -780
  204. package/build/server.d.ts +0 -184
  205. package/build/server.js +0 -4542
  206. package/build/session/analytics.d.ts +0 -745
  207. package/build/session/analytics.js +0 -2369
  208. package/build/session/db.d.ts +0 -468
  209. package/build/session/db.js +0 -1308
  210. package/build/session/error-classifier.d.ts +0 -87
  211. package/build/session/error-classifier.js +0 -303
  212. package/build/session/event-emit.d.ts +0 -48
  213. package/build/session/event-emit.js +0 -101
  214. package/build/session/extract.d.ts +0 -333
  215. package/build/session/extract.js +0 -2688
  216. package/build/session/model-prices.json +0 -429
  217. package/build/session/persist-tool-calls.d.ts +0 -54
  218. package/build/session/persist-tool-calls.js +0 -105
  219. package/build/session/pricing.d.ts +0 -64
  220. package/build/session/pricing.js +0 -151
  221. package/build/session/project-attribution.d.ts +0 -73
  222. package/build/session/project-attribution.js +0 -245
  223. package/build/session/purge.d.ts +0 -138
  224. package/build/session/purge.js +0 -240
  225. package/build/session/snapshot.d.ts +0 -46
  226. package/build/session/snapshot.js +0 -532
  227. package/build/store-directory.d.ts +0 -56
  228. package/build/store-directory.js +0 -254
  229. package/build/store.d.ts +0 -147
  230. package/build/store.js +0 -1714
  231. package/build/tool-naming.d.ts +0 -4
  232. package/build/tool-naming.js +0 -24
  233. package/build/truncate.d.ts +0 -57
  234. package/build/truncate.js +0 -142
  235. package/build/types.d.ts +0 -117
  236. package/build/types.js +0 -20
  237. package/build/util/claude-config.d.ts +0 -32
  238. package/build/util/claude-config.js +0 -84
  239. package/build/util/hook-config.d.ts +0 -27
  240. package/build/util/hook-config.js +0 -76
  241. package/build/util/jsonc.d.ts +0 -14
  242. package/build/util/jsonc.js +0 -104
  243. package/build/util/plugin-cache-integrity.d.ts +0 -51
  244. package/build/util/plugin-cache-integrity.js +0 -146
  245. package/build/util/project-dir.d.ts +0 -149
  246. package/build/util/project-dir.js +0 -340
  247. package/build/util/sibling-mcp.d.ts +0 -79
  248. package/build/util/sibling-mcp.js +0 -181
  249. package/cli.bundle.mjs +0 -1235
  250. package/configs/antigravity/GEMINI.md +0 -68
  251. package/configs/antigravity/mcp_config.json +0 -7
  252. package/configs/antigravity-cli/hooks/hooks.json +0 -37
  253. package/configs/antigravity-cli/hooks.json +0 -37
  254. package/configs/antigravity-cli/mcp_config.json +0 -10
  255. package/configs/antigravity-cli/plugin.json +0 -14
  256. package/configs/antigravity-cli/rules/context-mode.md +0 -77
  257. package/configs/antigravity-cli/skills/context-mode/SKILL.md +0 -77
  258. package/configs/claude-code/CLAUDE.md +0 -91
  259. package/configs/codex/AGENTS.md +0 -99
  260. package/configs/codex/config.toml +0 -8
  261. package/configs/codex/hooks.json +0 -47
  262. package/configs/copilot-cli/.github/plugin/plugin.json +0 -23
  263. package/configs/copilot-cli/.mcp.json +0 -12
  264. package/configs/copilot-cli/README.md +0 -47
  265. package/configs/copilot-cli/hooks.json +0 -41
  266. package/configs/copilot-cli/skills/context-mode/SKILL.md +0 -38
  267. package/configs/cursor/context-mode.mdc +0 -76
  268. package/configs/cursor/hooks.json +0 -21
  269. package/configs/cursor/mcp.json +0 -7
  270. package/configs/gemini-cli/GEMINI.md +0 -88
  271. package/configs/gemini-cli/mcp.json +0 -7
  272. package/configs/gemini-cli/settings.json +0 -60
  273. package/configs/jetbrains-copilot/copilot-instructions.md +0 -80
  274. package/configs/jetbrains-copilot/hooks.json +0 -16
  275. package/configs/jetbrains-copilot/mcp.json +0 -7
  276. package/configs/kilo/AGENTS.md +0 -84
  277. package/configs/kilo/kilo.json +0 -6
  278. package/configs/kimi/hooks.json +0 -54
  279. package/configs/kiro/KIRO.md +0 -84
  280. package/configs/kiro/agent.json +0 -18
  281. package/configs/kiro/mcp.json +0 -7
  282. package/configs/omp/SYSTEM.md +0 -85
  283. package/configs/omp/mcp.json +0 -7
  284. package/configs/openclaw/AGENTS.md +0 -87
  285. package/configs/openclaw/openclaw.json +0 -13
  286. package/configs/opencode/AGENTS.md +0 -84
  287. package/configs/opencode/opencode.json +0 -6
  288. package/configs/pi/AGENTS.md +0 -3
  289. package/configs/qwen-code/QWEN.md +0 -91
  290. package/configs/vscode-copilot/copilot-instructions.md +0 -80
  291. package/configs/vscode-copilot/hooks.json +0 -16
  292. package/configs/vscode-copilot/mcp.json +0 -7
  293. package/configs/zed/AGENTS.md +0 -68
  294. package/hooks/antigravity-cli/payload.mjs +0 -98
  295. package/hooks/antigravity-cli/posttooluse.mjs +0 -138
  296. package/hooks/antigravity-cli/pretooluse.mjs +0 -78
  297. package/hooks/antigravity-cli/stop.mjs +0 -58
  298. package/hooks/auto-injection.mjs +0 -102
  299. package/hooks/cache-heal-utils.mjs +0 -379
  300. package/hooks/codex/platform.mjs +0 -1
  301. package/hooks/codex/posttooluse.mjs +0 -66
  302. package/hooks/codex/precompact.mjs +0 -70
  303. package/hooks/codex/pretooluse.mjs +0 -42
  304. package/hooks/codex/sessionstart.mjs +0 -121
  305. package/hooks/codex/stop.mjs +0 -138
  306. package/hooks/codex/userpromptsubmit.mjs +0 -75
  307. package/hooks/copilot-cli/posttooluse.mjs +0 -79
  308. package/hooks/copilot-cli/precompact.mjs +0 -66
  309. package/hooks/copilot-cli/pretooluse.mjs +0 -41
  310. package/hooks/copilot-cli/sessionstart.mjs +0 -121
  311. package/hooks/copilot-cli/stop.mjs +0 -59
  312. package/hooks/copilot-cli/userpromptsubmit.mjs +0 -77
  313. package/hooks/core/codex-caps.mjs +0 -112
  314. package/hooks/core/formatters.mjs +0 -356
  315. package/hooks/core/mcp-ready.mjs +0 -109
  316. package/hooks/core/platform-detect.mjs +0 -49
  317. package/hooks/core/routing.mjs +0 -1017
  318. package/hooks/core/stdin.mjs +0 -90
  319. package/hooks/core/tool-naming.mjs +0 -57
  320. package/hooks/cursor/afteragentresponse.mjs +0 -74
  321. package/hooks/cursor/hooks.json +0 -31
  322. package/hooks/cursor/posttooluse.mjs +0 -72
  323. package/hooks/cursor/pretooluse.mjs +0 -26
  324. package/hooks/cursor/sessionstart.mjs +0 -97
  325. package/hooks/cursor/stop.mjs +0 -48
  326. package/hooks/ensure-deps.mjs +0 -254
  327. package/hooks/formatters/claude-code.mjs +0 -113
  328. package/hooks/formatters/cursor.mjs +0 -37
  329. package/hooks/formatters/gemini-cli.mjs +0 -55
  330. package/hooks/formatters/vscode-copilot.mjs +0 -55
  331. package/hooks/gemini-cli/aftermodel.mjs +0 -70
  332. package/hooks/gemini-cli/aftertool.mjs +0 -61
  333. package/hooks/gemini-cli/beforeagent.mjs +0 -99
  334. package/hooks/gemini-cli/beforetool.mjs +0 -27
  335. package/hooks/gemini-cli/precompress.mjs +0 -55
  336. package/hooks/gemini-cli/sessionstart.mjs +0 -137
  337. package/hooks/heal-partial-install.mjs +0 -712
  338. package/hooks/jetbrains-copilot/posttooluse.mjs +0 -61
  339. package/hooks/jetbrains-copilot/precompact.mjs +0 -55
  340. package/hooks/jetbrains-copilot/pretooluse.mjs +0 -27
  341. package/hooks/jetbrains-copilot/sessionstart.mjs +0 -124
  342. package/hooks/kimi/platform.mjs +0 -1
  343. package/hooks/kimi/posttooluse.mjs +0 -72
  344. package/hooks/kimi/precompact.mjs +0 -80
  345. package/hooks/kimi/pretooluse.mjs +0 -42
  346. package/hooks/kimi/sessionend.mjs +0 -61
  347. package/hooks/kimi/sessionstart.mjs +0 -113
  348. package/hooks/kimi/stop.mjs +0 -132
  349. package/hooks/kimi/userpromptsubmit.mjs +0 -90
  350. package/hooks/kiro/agentspawn.mjs +0 -97
  351. package/hooks/kiro/posttooluse.mjs +0 -51
  352. package/hooks/kiro/pretooluse.mjs +0 -64
  353. package/hooks/kiro/userpromptsubmit.mjs +0 -88
  354. package/hooks/normalize-hooks.mjs +0 -323
  355. package/hooks/platform-bridge.mjs +0 -340
  356. package/hooks/posttooluse.mjs +0 -187
  357. package/hooks/precompact.mjs +0 -100
  358. package/hooks/pretooluse.mjs +0 -227
  359. package/hooks/qwen-code/platform.mjs +0 -1
  360. package/hooks/qwen-code/stop.mjs +0 -168
  361. package/hooks/routing-block.mjs +0 -105
  362. package/hooks/run-hook.mjs +0 -95
  363. package/hooks/security.bundle.mjs +0 -2
  364. package/hooks/session-attribution.bundle.mjs +0 -1
  365. package/hooks/session-db.bundle.mjs +0 -144
  366. package/hooks/session-directive.mjs +0 -520
  367. package/hooks/session-extract.bundle.mjs +0 -3
  368. package/hooks/session-helpers.mjs +0 -428
  369. package/hooks/session-loaders.mjs +0 -448
  370. package/hooks/session-snapshot.bundle.mjs +0 -32
  371. package/hooks/sessionstart.mjs +0 -464
  372. package/hooks/stop.mjs +0 -82
  373. package/hooks/suppress-stderr.mjs +0 -25
  374. package/hooks/userpromptsubmit.mjs +0 -108
  375. package/hooks/vscode-copilot/posttooluse.mjs +0 -61
  376. package/hooks/vscode-copilot/precompact.mjs +0 -55
  377. package/hooks/vscode-copilot/pretooluse.mjs +0 -27
  378. package/hooks/vscode-copilot/sessionstart.mjs +0 -129
  379. package/openclaw.plugin.json +0 -38
  380. package/scripts/heal-better-sqlite3.mjs +0 -430
  381. package/scripts/heal-installed-plugins.mjs +0 -598
  382. package/scripts/plugin-cache-integrity.mjs +0 -248
  383. package/scripts/postinstall.mjs +0 -384
  384. package/server.bundle.mjs +0 -1161
  385. package/skills/.ignore +0 -7
  386. package/skills/context-mode/SKILL.md +0 -300
  387. package/skills/context-mode/references/anti-patterns.md +0 -283
  388. package/skills/context-mode/references/patterns-javascript.md +0 -298
  389. package/skills/context-mode/references/patterns-python.md +0 -304
  390. package/skills/context-mode/references/patterns-shell.md +0 -277
  391. package/skills/ctx-index/SKILL.md +0 -46
  392. package/skills/ctx-insight/SKILL.md +0 -24
  393. package/skills/ctx-purge/SKILL.md +0 -49
  394. package/skills/ctx-search/SKILL.md +0 -35
  395. package/start.mjs +0 -616
package/cli.bundle.mjs DELETED
@@ -1,1235 +0,0 @@
1
- #!/usr/bin/env node
2
- var GC=Object.create;var jd=Object.defineProperty;var JC=Object.getOwnPropertyDescriptor;var XC=Object.getOwnPropertyNames;var YC=Object.getPrototypeOf,QC=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),_e=(t,e)=>{for(var n in e)jd(t,n,{get:e[n],enumerable:!0})},eO=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of XC(e))!QC.call(t,o)&&o!==n&&jd(t,o,{get:()=>e[o],enumerable:!(r=JC(e,o))||r.enumerable});return t};var xi=(t,e,n)=>(n=t!=null?GC(YC(t)):{},eO(e||!t||!t.__esModule?jd(n,"default",{value:t,enumerable:!0}):n,t));var Zd=L((a9,Vb)=>{"use strict";var Bd={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},lO={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},dO={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?Bd.up():"");return t&&(e+=Bd.left),e}};Vb.exports={cursor:Bd,scroll:lO,erase:dO,beep:"\x07"}});var Qb=L((B9,Jd)=>{var Sc=process||{},Xb=Sc.argv||[],xc=Sc.env||{},MO=!(xc.NO_COLOR||Xb.includes("--no-color"))&&(!!xc.FORCE_COLOR||Xb.includes("--color")||Sc.platform==="win32"||(Sc.stdout||{}).isTTY&&xc.TERM!=="dumb"||!!xc.CI),jO=(t,e,n=t)=>r=>{let o=""+r,s=o.indexOf(e,t.length);return~s?t+LO(o,e,n,s)+e:t+o+e},LO=(t,e,n,r)=>{let o="",s=0;do o+=t.substring(s,r)+n,s=r+e.length,r=t.indexOf(e,s);while(~r);return o+t.substring(s)},Yb=(t=MO)=>{let e=t?jO:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Jd.exports=Yb();Jd.exports.createColors=Yb});function ki(t,e){let n=process.execPath.replace(/\\/g,"/");if(Yr(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Xd.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function qe(t,e){if(Yr(e?.platform))return ki(t,e);let r=Yd().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function vc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Yr(t){return!!t&&zO.has(t)}var Xd,zO,Rn=v(()=>{"use strict";Qo();Xd=new Set(["node","bun","deno"]),zO=new Set(["opencode","kilo"])});var ix={};_e(ix,{buildCommand:()=>rp,detectRuntimes:()=>Qr,getAvailableLanguages:()=>Ti,getRuntimeSummary:()=>Ei,hasBunRuntime:()=>hr,isAllowlistedShell:()=>tx,resetHookRuntimeCache:()=>qO,resolveHookRuntime:()=>Yd,resolveJavascriptRuntime:()=>sx});import{execFileSync as tp,execSync as es}from"node:child_process";import{existsSync as ts}from"node:fs";function ep(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function tx(t){return FO.test(ep(t))}function HO(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function UO(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function Ge(t){try{let e=wi?`where ${t}`:`command -v ${t}`;return es(e,{stdio:"pipe"}),!0}catch{return!1}}function Qd(t){if(wi)try{let n=es(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Ge(t))return!1;try{return wi?es(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):tp(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function np(){if(Ge("bun"))return!0;for(let t of rx())if(ts(t))return!0;return!1}function nx(){for(let e of rx())if(ts(e))return e;if(Ge("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return wi?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function rx(){let t=process.env.HOME??process.env.USERPROFILE??"";if(wi){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function ox(){let t;try{t=es("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of BO)if(ts(r))return r;return e}}return null}function ZO(t=ox()){return t??(Ge("sh")?"sh":Ge("pwsh")?"pwsh":Ge("powershell")?"powershell":"cmd.exe")}function Wt(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return es(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return tp(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function sx(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??Ge,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Xd.has(o)&&ts(n)?n:r("node")?"node":null}function Qr(){let e=np()?nx():null,n=process.env.SHELL,r=process.platform==="win32",o=r?ox():null,s=n&&ts(n)&&tx(n)&&!(r&&HO(n))&&!(r&&o&&UO(n))?n:null;return{javascript:sx(e),typescript:e||(Ge("tsx")?"tsx":Ge("ts-node")?"ts-node":null),python:Qd("python3")?"python3":Qd("python")?"python":Qd("py")?"py":null,shell:s??(r?ZO(o):Ge("bash")?"bash":"sh"),ruby:Ge("ruby")?"ruby":null,go:Ge("go")?"go":null,rust:Ge("rustc")?"rustc":null,php:Ge("php")?"php":null,perl:Ge("perl")?"perl":null,r:Ge("Rscript")?"Rscript":Ge("r")?"r":null,elixir:Ge("elixir")?"elixir":null,csharp:Ge("dotnet-script")?"dotnet-script":null}}function hr(){return np()}function qO(){Ft=null}function VO(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function WO(){return ts(process.execPath)?{path:process.execPath,isBun:!1}:Ge("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Yd(){if(Ft)return Ft;let t=WO();try{if(!np())return Ft=t,Ft;let e=nx(),n;try{if(process.platform==="win32"){let r=es(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=tp(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ft=t,Ft}return VO(n)?(Ft={path:e,isBun:!0},Ft):(Ft=t,Ft)}catch{return Ft=t,Ft}}function Ei(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Wt(t.javascript)})${n?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${Wt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Wt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Wt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Wt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Wt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Wt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Wt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Wt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Wt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Wt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Wt(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
- `)}function Ti(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function rp(t,e,n){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return ex.test(ep(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return ex.test(ep(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var FO,ex,wi,BO,Ft,Qo=v(()=>{"use strict";Rn();FO=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,ex=/^bun(\.exe)?$/i;wi=process.platform==="win32";BO=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Ft=null});function KO(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function GO(t){let e=vc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function kc(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of KO(s)){let a=GO(i);a&&n.add(a)}return[...n]}var op=v(()=>{"use strict";Rn()});var ax,cx=v(()=>{"use strict";ax={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});var ap={};_e(ap,{BunSQLiteAdapter:()=>wc,NodeSQLiteAdapter:()=>Ec,SQLiteBase:()=>Pi,applyWALPragmas:()=>rs,cleanOrphanedWALFiles:()=>os,closeDB:()=>ss,defaultDBPath:()=>ip,deleteDBFiles:()=>Tc,hasModernSqlite:()=>dx,isSQLiteCorruptionError:()=>$c,loadDatabase:()=>nt,nodeSqliteHasFts5:()=>lx,renameCorruptDB:()=>px,withRetry:()=>gr});import{createRequire as JO}from"node:module";import{existsSync as XO,unlinkSync as ux,renameSync as YO}from"node:fs";import{tmpdir as QO}from"node:os";import{join as eI}from"node:path";function lx(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function dx(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function nt(){if(!ns){let t=JO(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;ns=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new wc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(dx()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&lx(e)?ns=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new Ec(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:ns=t("better-sqlite3")}else ns=t("better-sqlite3")}return ns}function rs(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function os(t){if(!XO(t))for(let e of["-wal","-shm"])try{ux(t+e)}catch{}}function Tc(t){for(let e of["","-wal","-shm"])try{ux(t+e)}catch{}}function ss(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ip(t="context-mode"){return eI(QO(),`${t}-${process.pid}.db`)}function gr(t,e=[100,500,2e3]){let n;for(let r=0;r<=e.length;r++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(n=o instanceof Error?o:new Error(s),r<e.length){let i=e[r],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${n?.message}`)}function $c(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function px(t){let e=Date.now();for(let n of["","-wal","-shm"])try{YO(t+n,`${t}${n}.corrupt-${e}`)}catch{}}var wc,Ec,ns,$i,sp,Pi,yr=v(()=>{"use strict";wc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r)n+=i,i===r&&(r=null);else if(i==="'"||i==='"')n+=i,r=i;else if(i===";"){let a=n.trim();a&&this.#e.prepare(a).run(),n=""}else n+=i}let o=n.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},Ec=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},ns=null;$i=Symbol.for("__context_mode_live_dbs_v3__"),sp=(()=>{let t=globalThis;return t[$i]||(t[$i]=new Set,process.on("exit",()=>{for(let e of t[$i])ss(e);t[$i].clear()})),t[$i]})(),Pi=class{#e;#t;constructor(e){let n=nt();this.#e=e,os(e);let r;try{r=new n(e,{timeout:3e4}),rs(r)}catch(o){let s=o instanceof Error?o.message:String(o);if($c(s)){px(e),os(e);try{r=new n(e,{timeout:3e4}),rs(r)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=r,sp.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){sp.delete(this.#t),ss(this.#t)}withRetry(e){return gr(e)}cleanup(){sp.delete(this.#t),ss(this.#t),Tc(this.#e)}}});var Tx={};_e(Tx,{SessionDB:()=>Gt,StorageDirectoryError:()=>Kt,_resetWorktreeSuffixCacheForTests:()=>yI,applyMissingSessionEventsColumns:()=>lp,clearStorageDirectoryCheckCacheForTests:()=>dI,describeStorageDirectorySource:()=>Ci,ensureSessionEventsSchema:()=>dp,ensureWritableStorageDir:()=>Sr,formatStorageDirectoryError:()=>us,getWorktreeSuffix:()=>Oi,hashProjectDirCanonical:()=>rt,hashProjectDirLegacy:()=>On,normalizeWorktreePath:()=>br,resolveContentStorageDir:()=>eo,resolveContentStorePath:()=>up,resolveDefaultSessionDir:()=>Oc,resolveSessionDbPath:()=>ls,resolveSessionPath:()=>Ex,resolveSessionStorageDir:()=>xr,resolveStatsStorageDir:()=>cs});import{createHash as Ri}from"node:crypto";import{execFileSync as tI}from"node:child_process";import{accessSync as nI,constants as rI,existsSync as Cc,mkdirSync as oI,realpathSync as sI,renameSync as cp}from"node:fs";import{homedir as _x}from"node:os";import{dirname as iI,isAbsolute as bx,join as _r,resolve as as}from"node:path";function Oc(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):_r(aI(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function aI(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?fx(r.trim()):fx(t,_x())}function fx(t,e){return t.startsWith("~")?as(_x(),t.replace(/^~[/\\]?/,"")):bx(t)?as(t):e?as(e,t):as(t)}function cI(t,e,n){return new Kt(t,e,Cn,void 0,[`Invalid ${Cn} for context-mode ${t} directory: ${n}`,kx()].join(`
4
- `))}function Sx(t){let e=process.env[Cn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:Cn,ignoredReason:"empty"};if(!bx(n))throw cI(t,n,`${Cn} must be an absolute path.`);return{kind:"override",root:as(n)}}function uI(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function vx(t,e){let n=Sx(t);return n.kind!=="override"?null:{kind:t,path:_r(n.root,e),envVar:Cn,source:"override"}}function lI(t,e,n){return{kind:t,path:as(e()),envVar:null,source:"default",...n}}function xr(t){let e=Sx("session");return e.kind==="override"?{kind:"session",path:_r(e.root,xx),envVar:Cn,source:"override"}:lI("session",t,uI(e))}function eo(t){let e=vx("content",mx);if(e)return e;let n=xr(t);return{kind:"content",path:_r(iI(n.path),mx),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function cs(t){let e=vx("stats",xx);if(e)return e;let n=xr(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function us(t){return t.message}function Ci(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function dI(){Rc.clear()}function Sr(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=Rc.get(e);if(n instanceof Kt)throw n;if(n===t.path)return n;try{return oI(t.path,{recursive:!0}),nI(t.path,rI.W_OK),Rc.set(e,t.path),t.path}catch(r){let o=new Kt(t.kind,fI(r)??t.path,Cn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Rc.set(e,o),o}}function pI(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,mI(n),kx()].filter(Boolean).join(`
5
- `)}function mI(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function kx(){return`Set ${Cn} to a writable absolute path.`}function fI(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function br(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function hx(t){let e=t;try{e=sI.native(t)}catch{}let n=br(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function wx(t,e){return tI("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function hI(t){let e=wx(t,["rev-parse","--show-toplevel"]);return e.length>0?br(e):null}function gI(t){let e=wx(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?br(e):null}function Oi(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(is&&is.projectDir===t&&is.envSuffix===e)return is.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=hI(t),o=gI(t);if(r&&o){let s=hx(r),i=hx(o);s!==i&&(n=`__${Ri("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return is={projectDir:t,envSuffix:e,suffix:n},n}function yI(){is=void 0}function On(t){return Ri("sha256").update(br(t)).digest("hex").slice(0,16)}function rt(t){let e=br(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Ri("sha256").update(n).digest("hex").slice(0,16)}function up(t){let{projectDir:e,contentDir:n}=t,r=rt(e),o=_r(n,`${r}.db`);if(Cc(o))return o;let s=On(e);if(s===r)return o;let i=_r(n,`${s}.db`);if(Cc(i))try{cp(i,o);for(let a of["-wal","-shm"])try{cp(i+a,o+a)}catch{}}catch{}return o}function ls(t){return Ex({...t,ext:".db"})}function Ex(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??Oi(e),s=rt(e),i=_r(n,`${s}${o}${r}`);if(Cc(i))return i;let a=On(e);if(a===s)return i;let c=_r(n,`${a}${o}${r}`);if(Cc(c))try{cp(c,i)}catch{}return i}function Pc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function lp(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of _I)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function dp(t,e){let n=null;try{n=new e(t),lp(n)}catch{}finally{try{n?.close()}catch{}}}var Cn,xx,mx,Kt,Rc,is,gx,yx,U,_I,Gt,Jt=v(()=>{"use strict";yr();Cn="CONTEXT_MODE_DIR",xx="sessions",mx="content",Kt=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=Cn,o,s,i={}){super(s??pI(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},Rc=new Map;gx=1e3,yx=5;U={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",getUsageCursor:"getUsageCursor",setUsageCursor:"setUsageCursor",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},_I=[["project_dir","TEXT NOT NULL DEFAULT ''"],["attribution_source","TEXT NOT NULL DEFAULT 'unknown'"],["attribution_confidence","REAL NOT NULL DEFAULT 0"],["bytes_avoided","INTEGER NOT NULL DEFAULT 0"],["bytes_returned","INTEGER NOT NULL DEFAULT 0"]];Gt=class extends Pi{constructor(e){super(e?.dbPath??ip("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=this.db.pragma("table_xinfo(session_events)").find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
6
- CREATE TABLE IF NOT EXISTS session_events (
7
- id INTEGER PRIMARY KEY AUTOINCREMENT,
8
- session_id TEXT NOT NULL,
9
- type TEXT NOT NULL,
10
- category TEXT NOT NULL,
11
- priority INTEGER NOT NULL DEFAULT 2,
12
- data TEXT NOT NULL,
13
- project_dir TEXT NOT NULL DEFAULT '',
14
- attribution_source TEXT NOT NULL DEFAULT 'unknown',
15
- attribution_confidence REAL NOT NULL DEFAULT 0,
16
- bytes_avoided INTEGER NOT NULL DEFAULT 0,
17
- bytes_returned INTEGER NOT NULL DEFAULT 0,
18
- source_hook TEXT NOT NULL,
19
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
20
- data_hash TEXT NOT NULL DEFAULT ''
21
- );
22
-
23
- CREATE INDEX IF NOT EXISTS idx_session_events_session ON session_events(session_id);
24
- CREATE INDEX IF NOT EXISTS idx_session_events_type ON session_events(session_id, type);
25
- CREATE INDEX IF NOT EXISTS idx_session_events_priority ON session_events(session_id, priority);
26
-
27
- CREATE TABLE IF NOT EXISTS session_meta (
28
- session_id TEXT PRIMARY KEY,
29
- project_dir TEXT NOT NULL,
30
- started_at TEXT NOT NULL DEFAULT (datetime('now')),
31
- last_event_at TEXT,
32
- event_count INTEGER NOT NULL DEFAULT 0,
33
- compact_count INTEGER NOT NULL DEFAULT 0
34
- );
35
-
36
- CREATE TABLE IF NOT EXISTS session_resume (
37
- id INTEGER PRIMARY KEY AUTOINCREMENT,
38
- session_id TEXT NOT NULL UNIQUE,
39
- snapshot TEXT NOT NULL,
40
- event_count INTEGER NOT NULL,
41
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
42
- consumed INTEGER NOT NULL DEFAULT 0
43
- );
44
-
45
- CREATE TABLE IF NOT EXISTS tool_calls (
46
- session_id TEXT NOT NULL,
47
- tool TEXT NOT NULL,
48
- calls INTEGER NOT NULL DEFAULT 0,
49
- bytes_returned INTEGER NOT NULL DEFAULT 0,
50
- updated_at TEXT NOT NULL DEFAULT (datetime('now')),
51
- PRIMARY KEY (session_id, tool)
52
- );
53
-
54
- CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
55
- `);try{lp(this.db)}catch{}try{this.db.pragma("table_xinfo(session_meta)").some(n=>n.name==="usage_cursor")||this.db.exec("ALTER TABLE session_meta ADD COLUMN usage_cursor TEXT")}catch{}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(U.insertEvent,`INSERT INTO session_events (
56
- session_id, type, category, priority, data,
57
- project_dir, attribution_source, attribution_confidence,
58
- bytes_avoided, bytes_returned,
59
- source_hook, data_hash
60
- )
61
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(U.getEvents,`SELECT id, session_id, type, category, priority, data,
62
- project_dir, attribution_source, attribution_confidence,
63
- bytes_avoided, bytes_returned,
64
- source_hook, created_at, data_hash
65
- FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(U.getEventsByType,`SELECT id, session_id, type, category, priority, data,
66
- project_dir, attribution_source, attribution_confidence,
67
- bytes_avoided, bytes_returned,
68
- source_hook, created_at, data_hash
69
- FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(U.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
70
- project_dir, attribution_source, attribution_confidence,
71
- bytes_avoided, bytes_returned,
72
- source_hook, created_at, data_hash
73
- FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(U.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
74
- project_dir, attribution_source, attribution_confidence,
75
- bytes_avoided, bytes_returned,
76
- source_hook, created_at, data_hash
77
- FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(U.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(U.getLatestAttributedProject,`SELECT project_dir
78
- FROM session_events
79
- WHERE session_id = ? AND project_dir != ''
80
- ORDER BY id DESC
81
- LIMIT 1`),e(U.checkDuplicate,`SELECT 1 FROM (
82
- SELECT type, data_hash FROM session_events
83
- WHERE session_id = ? ORDER BY id DESC LIMIT ?
84
- ) AS recent
85
- WHERE recent.type = ? AND recent.data_hash = ?
86
- LIMIT 1`),e(U.evictLowestPriority,`DELETE FROM session_events WHERE id = (
87
- SELECT id FROM session_events WHERE session_id = ?
88
- ORDER BY priority ASC, id ASC LIMIT 1
89
- )`),e(U.updateMetaLastEvent,`UPDATE session_meta
90
- SET last_event_at = datetime('now'), event_count = event_count + 1
91
- WHERE session_id = ?`),e(U.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(U.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
92
- FROM session_meta WHERE session_id = ?`),e(U.getSessionRollup,`SELECT
93
- COUNT(*) AS tool_calls,
94
- COALESCE(SUM(CASE WHEN category = 'error' THEN 1 ELSE 0 END), 0) AS errors,
95
- COUNT(DISTINCT type) AS unique_tools,
96
- COUNT(DISTINCT CASE WHEN category = 'file' THEN data END) AS unique_files,
97
- CASE WHEN SUM(CASE WHEN type = 'git_commit' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END AS has_commit,
98
- CAST(COALESCE((MAX(strftime('%s', created_at)) - MIN(strftime('%s', created_at))) / 60.0, 0) AS INTEGER) AS duration_min,
99
- COALESCE(SUM(CASE WHEN type = 'external_ref' THEN 1 ELSE 0 END), 0) AS sources_indexed,
100
- CAST(COALESCE(SUM(bytes_avoided) / 1024.0, 0) AS INTEGER) AS total_chunks,
101
- COALESCE(SUM(CASE WHEN type IN ('file_search', 'file_glob') THEN 1 ELSE 0 END), 0) AS search_queries
102
- FROM session_events
103
- WHERE session_id = ?`),e(U.getMaxFileEdits,`SELECT COALESCE(MAX(c), 0) AS max_file_edits
104
- FROM (
105
- SELECT COUNT(*) AS c
106
- FROM session_events
107
- WHERE session_id = ? AND category = 'file' AND type IN ('file_edit', 'file_write')
108
- GROUP BY data
109
- )`),e(U.getLatestCommitMessage,`SELECT data
110
- FROM session_events
111
- WHERE session_id = ? AND type = 'git_commit'
112
- ORDER BY id DESC
113
- LIMIT 1`),e(U.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(U.getUsageCursor,"SELECT usage_cursor FROM session_meta WHERE session_id = ?"),e(U.setUsageCursor,"UPDATE session_meta SET usage_cursor = ? WHERE session_id = ?"),e(U.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
114
- VALUES (?, ?, ?)
115
- ON CONFLICT(session_id) DO UPDATE SET
116
- snapshot = excluded.snapshot,
117
- event_count = excluded.event_count,
118
- created_at = datetime('now'),
119
- consumed = 0`),e(U.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(U.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(U.claimLatestUnconsumedResume,`UPDATE session_resume
120
- SET consumed = 1
121
- WHERE id = (
122
- SELECT id FROM session_resume
123
- WHERE consumed = 0
124
- AND session_id != ?
125
- ORDER BY created_at DESC, id DESC
126
- LIMIT 1
127
- )
128
- RETURNING session_id, snapshot`),e(U.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(U.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(U.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(U.searchEvents,`SELECT id, session_id, category, type, data, created_at
129
- FROM session_events
130
- WHERE (project_dir = ? OR project_dir = '')
131
- AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
132
- AND (? IS NULL OR category = ?)
133
- ORDER BY id ASC
134
- LIMIT ?`),e(U.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(U.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
135
- VALUES (?, ?, 1, ?)
136
- ON CONFLICT(session_id, tool) DO UPDATE SET
137
- calls = calls + 1,
138
- bytes_returned = bytes_returned + excluded.bytes_returned,
139
- updated_at = datetime('now')`),e(U.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
140
- COALESCE(SUM(bytes_returned), 0) AS bytes_returned
141
- FROM tool_calls WHERE session_id = ?`),e(U.getToolCallByTool,`SELECT tool, calls, bytes_returned
142
- FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(U.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
143
- COALESCE(SUM(bytes_returned), 0) AS bytes_returned
144
- FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Ri("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=Pc(s?.bytesAvoided),p=Pc(s?.bytesReturned),h=this.db.transaction(()=>{if(this.stmt(U.checkDuplicate).get(e,yx,n.type,i))return;this.stmt(U.getEventCount).get(e).cnt>=gx&&this.stmt(U.evictLowestPriority).run(e),this.stmt(U.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,p,r,i),this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>h())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Ri("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],p=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),h=p===""?"":br(p),m=String(d?.source??c.attribution_source??"unknown"),f=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(f)?Math.max(0,Math.min(1,f)):0,y=s?.[u],_=Pc(y?.bytesAvoided),b=Pc(y?.bytesReturned);return{event:c,dataHash:l,projectDir:h,attributionSource:m,attributionConfidence:g,bytesAvoided:_,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(U.getEventCount).get(e).cnt;for(let u of i)this.stmt(U.checkDuplicate).get(e,yx,u.event.type,u.dataHash)||(c>=gx?this.stmt(U.evictLowestPriority).run(e):c++,this.stmt(U.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,r,u.dataHash));this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(U.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(U.getEventsByType).all(e,o,r):s!==void 0?this.stmt(U.getEventsByPriority).all(e,s,r):this.stmt(U.getEvents).all(e,r)}getEventCount(e){return this.stmt(U.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(U.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(U.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(U.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=br(e);return this.db.prepare(`SELECT DISTINCT session_id
145
- FROM session_events
146
- WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(U.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(U.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(U.getSessionRollup).get(e),r=this.stmt(U.getMaxFileEdits).get(e),o=this.stmt(U.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(U.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(U.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(U.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(U.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(U.getResume).get(e)??null}markResumeConsumed(e){this.stmt(U.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(U.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(U.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(U.getToolCallTotals).get(e),r=this.stmt(U.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(U.deleteEvents).run(e),this.stmt(U.deleteResume).run(e),this.stmt(U.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(U.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as ds,resolve as $x}from"node:path";import{accessSync as bI,copyFileSync as xI,constants as SI,mkdirSync as vI}from"node:fs";import{homedir as pp}from"node:os";function ht(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?$x(pp(),e.replace(/^~[/\\]?/,"")):$x(e)}var Se,it=v(()=>{"use strict";Jt();Se=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=ht(),n=e?ds(e,"context-mode","sessions"):ds(pp(),...this.sessionDirSegments,"context-mode","sessions");return vI(n,{recursive:!0}),n}getConfigDir(e){return ds(pp(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=ht(),r=n?ds(n,"context-mode","memory"):ds(this.getConfigDir(),"memory");return e?ds(r,rt(e)):r}backupSettings(){let e=this.getSettingsPath();try{bI(e,SI.R_OK);let n=e+".bak";return xI(e,n),n}catch{return null}}}});var ps,mp=v(()=>{"use strict";it();ps=class extends Se{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as fp}from"node:fs";import{join as hp}from"node:path";async function kI(){if(ms)return ms;if(fs)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return ms=r,ms}catch(r){e=r}return fs=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return fs=t instanceof Error?t.message:String(t),null}}function wI(t){let e=[];return fp(hp(t,"start.mjs"))||e.push("start.mjs"),!fp(hp(t,"server.bundle.mjs"))&&!fp(hp(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Px(t){if(ms){let e=ms.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(fs){let e=wI(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${fs}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${fs}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ms,fs,Rx=v(()=>{"use strict";ms=null,fs=null;kI()});function Ii(t,e){let n=to[e],r=yp(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function yp(t,e){if(e){let n=to[t];return qe(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function _p(t){let e=vc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function Ix(t){let e=Object.values(to);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Xt,EI,gp,Cx,TI,bV,to,Ox,xV,Ax=v(()=>{"use strict";Rn();Xt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},EI="mcp__",gp=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",EI],Cx=gp.join("|"),TI=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],bV=TI.join("|"),to={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Ox=[Xt.PRE_TOOL_USE,Xt.SESSION_START],xV=[Xt.POST_TOOL_USE,Xt.PRE_COMPACT,Xt.USER_PROMPT_SUBMIT,Xt.STOP]});var xp={};_e(xp,{ClaudeCodeAdapter:()=>bp});import{readFileSync as Ic,writeFileSync as Nx,existsSync as Dx,readdirSync as $I,chmodSync as PI,accessSync as RI,mkdirSync as CI,constants as OI}from"node:fs";import{resolve as Ac,join as vr}from"node:path";import{homedir as Mx}from"node:os";var bp,Sp=v(()=>{"use strict";mp();it();kr();Rx();Rn();Ax();bp=class extends ps{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return Be()}getSessionDir(){let e=ht(),n=e?vr(e,"context-mode","sessions"):vr(this.getConfigDir(),"context-mode","sessions");return CI(n,{recursive:!0}),n}getSettingsPath(){return vr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=qe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...gp].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=Ic(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Nx(this.getSettingsPath(),JSON.stringify(e,null,2)+`
147
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Xt.PRE_TOOL_USE);n.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,Xt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(to).map(([o,s])=>{let i=vr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>Dx(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>Px(e)};return[...n,r]}readPluginHooks(e){let n=[vr(e,"hooks","hooks.json"),vr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=Ic(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Ii(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Ii(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=vr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Ic(n,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),Be(),Ac(Mx(),".claude"),Ac(Mx(),".config","claude")]));for(let n of e){let r=Ac(n,"plugins","cache","context-mode","context-mode");try{let s=$I(r).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(h=>{let m=h;if(!Ix(m))return!0;let f=m.hooks??[];return f.every(y=>!y.command||!_p(y.command))?!0:f.every(y=>{let _=y.command?_p(y.command):null;return _?Dx(_):!0})}),p=l.length-d.length;p>0&&(r[u]=d,o.push(`Removed ${p} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&Ox.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(to),d=p=>p!=null&&(l.some(h=>p.includes(h))||p.includes("context-mode hook"));for(let p of Object.keys(r)){let h=r[p];if(!Array.isArray(h))continue;let m=0;for(let g of h){let y=g,_=y.hooks??[],b=_.length;y.hooks=_.filter(S=>!d(S.command)),m+=b-y.hooks.length}let f=h.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(m>0||f.length!==h.length)&&(r[p]=f,m>0&&o.push(`Removed ${m} duplicate ${p} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Xt.PRE_TOOL_USE,Xt.SESSION_START];for(let u of c){let l=yp(u,e);if(u===Xt.PRE_TOOL_USE){let d={matcher:Cx,hooks:[{type:"command",command:l}]},p=r.PreToolUse;if(p&&Array.isArray(p)){let h=p.findIndex(m=>Ii(m,u));h>=0?(p[h]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=p}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},p=r[u];if(p&&Array.isArray(p)){let h=p.findIndex(m=>Ii(m,u));h>=0?(p[h]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r[u]=p}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(to)){let o=Ac(e,"hooks",r);try{RI(o,OI.R_OK),PI(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=vr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Ic(r,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=n,a.lastUpdated=new Date().toISOString();Nx(r,JSON.stringify(o,null,2)+`
148
- `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function wr(t,e){let n=Nc[t];return e&&n?qe(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var be,jx,Nc,IV,AV,Lx=v(()=>{"use strict";Rn();be={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",AFTER_MODEL:"AfterModel",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},jx="mcp__(?!.*context-mode)",Nc={[be.BEFORE_AGENT]:"beforeagent.mjs",[be.BEFORE_TOOL]:"beforetool.mjs",[be.AFTER_TOOL]:"aftertool.mjs",[be.AFTER_MODEL]:"aftermodel.mjs",[be.PRE_COMPRESS]:"precompress.mjs",[be.SESSION_START]:"sessionstart.mjs"},IV=[be.BEFORE_TOOL,be.SESSION_START],AV=[be.AFTER_TOOL,be.AFTER_MODEL,be.PRE_COMPRESS]});var Hx={};_e(Hx,{GeminiCLIAdapter:()=>kp});import{readFileSync as vp,writeFileSync as zx,mkdirSync as II,accessSync as AI,chmodSync as NI,existsSync as DI,constants as MI}from"node:fs";import{resolve as Ai,join as Fx}from"node:path";import{homedir as Dc}from"node:os";var kp,Ux=v(()=>{"use strict";it();Lx();kp=class extends Se{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Ai(Dc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[be.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:wr(be.BEFORE_AGENT,e)}]}],[be.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${jx}`,hooks:[{type:"command",command:wr(be.BEFORE_TOOL,e)}]}],[be.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:wr(be.AFTER_TOOL,e)}]}],[be.AFTER_MODEL]:[{matcher:"",hooks:[{type:"command",command:wr(be.AFTER_MODEL,e)}]}],[be.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:wr(be.PRE_COMPRESS,e)}]}],[be.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:wr(be.SESSION_START,e)}]}]}}readSettings(){try{let e=vp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Ai(Dc(),".gemini");II(n,{recursive:!0}),zx(this.getSettingsPath(),JSON.stringify(e,null,2)+`
149
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[be.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[be.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(Nc).map(([n,r])=>{let o=Fx(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>DI(o)?{status:"OK",detail:o}:{status:"FAIL",detail:`not found at ${o}`}}})}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=Ai(Dc(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(vp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:be.BEFORE_AGENT},{name:be.BEFORE_TOOL},{name:be.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:wr(i.name,e)}]},u=r[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(h=>h.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=Fx(e,"hooks","gemini-cli");for(let o of Object.values(Nc)){let s=Ai(r,o);try{AI(s,MI.R_OK),NI(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Ai(Dc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(vp(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),zx(r,JSON.stringify(o,null,2)+`
150
- `,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});function Ni(t){let e="",n=!1,r=!1,o=!1;for(let c=0;c<t.length;c++){let u=t[c],l=t[c+1];if(o){u==="*"&&l==="/"&&(o=!1,c++);continue}if(r){e+=u,r=!1;continue}if(u==="\\"){e+=u,r=n;continue}if(u==='"'){n=!n,e+=u;continue}if(!n&&u==="/"&&l==="/"){for(;c<t.length&&t[c]!==`
151
- `;)c++;c<t.length&&(e+=`
152
- `);continue}if(!n&&u==="/"&&l==="*"){o=!0,c++;continue}e+=u}let s="",i=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a){s+=u,a=!1;continue}if(u==="\\"){s+=u,a=i;continue}if(u==='"'){i=!i,s+=u;continue}if(!i&&u===","){let l=c+1;for(;l<e.length&&(e[l]===" "||e[l]===" "||e[l]==="\r"||e[l]===`
153
- `);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function Kn(t){for(let e of[t,Ni(t)])try{return JSON.parse(e)}catch{}}var Di=v(()=>{"use strict"});var no,HV,UV,Bx=v(()=>{"use strict";no={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},HV=[no.BEFORE,no.AFTER],UV=[no.COMPACTING]});var qx={};_e(qx,{OpenCodeAdapter:()=>wp});import{readFileSync as Zx,writeFileSync as jI,mkdirSync as LI,copyFileSync as zI,accessSync as FI,existsSync as HI,constants as UI}from"node:fs";import{resolve as Ht,join as Gn}from"node:path";import{homedir as Er}from"node:os";var wp,Vx=v(()=>{"use strict";it();Di();Bx();wp=class extends Se{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Ht(`${this.platform}.jsonc`);return HI(e)?e:Ht(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ht("kilo.jsonc"),Ht("kilo.json"),Ht(".kilo","kilo.jsonc"),Ht(".kilo","kilo.json"),Ht(".kilocode","kilo.jsonc"),Ht(".kilocode","kilo.json"),Gn(Er(),".config","kilo","kilo.jsonc"),Gn(Er(),".config","kilo","kilo.json")]:[Ht("opencode.jsonc"),Ht("opencode.json"),Ht(".opencode","opencode.jsonc"),Ht(".opencode","opencode.json"),Gn(Er(),".config","opencode","opencode.jsonc"),Gn(Er(),".config","opencode","opencode.json")]}getSessionDir(){let e=ht(),n=e?Gn(e,"context-mode","sessions"):Gn(this.getConfigDir(),"context-mode","sessions");return LI(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Gn(Er(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Gn(Er(),".config"),Gn(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[no.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[no.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[no.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(Er()))),r=null,o;for(let s of e)try{let i=Zx(s,"utf-8"),a=s.endsWith(".jsonc")?Ni(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){jI(this.getSettingsPath(),JSON.stringify(e,null,2)+`
154
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)?n.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):n.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(r)&&n.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),n}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Ht(Er(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(Zx(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=n.plugin??[];o.some(i=>i.includes("context-mode"))?r.push("context-mode already in plugin array"):(o.push("context-mode"),r.push("Added context-mode to plugin array")),n.plugin=o;let s=n.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{FI(this.settingsPath,UI.R_OK);let n=this.settingsPath+".bak";return zI(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){let n=e.plugin;return Array.isArray(n)&&n.some(r=>typeof r=="string"&&r.includes("context-mode"))}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var ro,JV,XV,Wx=v(()=>{"use strict";ro={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},JV=[ro.TOOL_CALL_BEFORE,ro.TOOL_CALL_AFTER],XV=[ro.COMMAND_NEW]});var Kx={};_e(Kx,{OpenClawAdapter:()=>Pp});import{readFileSync as Ep,writeFileSync as BI,copyFileSync as ZI,accessSync as qI,constants as VI}from"node:fs";import{resolve as Jn,join as Tp}from"node:path";import{homedir as $p}from"node:os";var Pp,Gx=v(()=>{"use strict";it();Wx();Pp=class extends Se{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Jn("openclaw.json")}getConfigDir(e){return Jn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Tp(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[ro.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Jn("openclaw.json"),Jn(".openclaw","openclaw.json"),Tp($p(),".openclaw","openclaw.json")];for(let n of e)try{let r=Ep(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Jn("openclaw.json");BI(n,JSON.stringify(e,null,2)+`
155
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Jn($p(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(Ep(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Jn("node_modules","context-mode","package.json"),n=JSON.parse(Ep(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[Jn("openclaw.json"),Jn(".openclaw","openclaw.json"),Tp($p(),".openclaw","openclaw.json")];for(let n of e)try{qI(n,VI.R_OK);let r=n+".bak";return ZI(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as Jx}from"node:os";import{resolve as Rp}from"node:path";function Xx(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Rp(Jx(),t.replace(/^~[/\\]?/,"")):Rp(t):Rp(Jx(),".codex")}var Yx=v(()=>{"use strict"});var iS={};_e(iS,{CodexAdapter:()=>Ip,parseCodexContextModePluginRoot:()=>jc,probeCodexCliVersion:()=>oS});import{execFileSync as rS}from"node:child_process";import{existsSync as WI,readFileSync as hs,writeFileSync as Qx,accessSync as KI,copyFileSync as GI,constants as JI,mkdirSync as Cp}from"node:fs";import{resolve as Mc,dirname as Op,join as Xn}from"node:path";import{fileURLToPath as XI}from"node:url";function oS(t=rS){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function jc(t){for(let e of t.split(/\r?\n/)){let n=e.match(/^\s*context-mode@context-mode\s+installed,\s+enabled\s+\S+\s+(.+?)\s*$/);if(n?.[1])return n[1].trim()}return null}function Lc(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(`
156
- `):null}function sS(t){let e=Lc(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function eA(t){let e=Lc(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function eS(t){let e=Lc(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function tS(t){return Lc(t,"mcp_servers.context-mode")!==null}function tA(t){if(sS(t))return{text:t,changed:!1};let e=t.includes(`\r
157
- `)?`\r
158
- `:`
159
- `,n=t.split(/\r?\n/),r=n.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(r===-1){let s=t.length>0&&!t.endsWith(`
160
- `)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s<n.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(n[s]??"")){o=s;break}for(let s=r+1;s<o;s++)if(/^\s*hooks\s*=/.test(n[s]??""))return n[s]="hooks = true",{text:n.join(e),changed:!0};return n.splice(r+1,0,"hooks = true"),{text:n.join(e),changed:!0}}function nS(t,e){let n=t.includes(`\r
161
- `)?`\r
162
- `:`
163
- `,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(n),removed:s}}function nA(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var YI,oo,QI,Ip,Ap=v(()=>{"use strict";it();Jt();Yx();YI="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",oo={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},QI={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};Ip=class extends Se{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??rS}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return Xx()}getSettingsPath(){return Xn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=ht(),n=e?Xn(e,"context-mode","sessions"):Xn(this.getConfigDir(),"context-mode","sessions");return Cp(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=ht(),r=n?Xn(n,"context-mode","memories"):Xn(this.getConfigDir(),"memories");return e?Xn(r,rt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:YI,hooks:[{type:"command",command:oo.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:oo.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:oo.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:oo.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:oo.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:oo.Stop}]}]}}readSettings(){try{return{_raw_toml:hs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=oS(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=hs(this.getSettingsPath(),"utf-8"),s=!0;let h=sS(o),m=!h&&eA(o);n.push({check:"Codex hooks feature flag",status:h?"pass":"fail",message:h?`[features].hooks enabled in ${this.getSettingsPath()}`:m?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...h?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:"context-mode@context-mode is enabled, but `codex plugin list` did not report its runtime root",fix:"Restart Codex or verify `codex plugin list` shows context-mode@context-mode installed and enabled"}),c&&!u){let h=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Xn(h,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&tS(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode is enabled; Codex may start both plugin and standalone MCP surfaces",fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let h=Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by context-mode@context-mode plugin`}));return n.concat(h)}return l.reason==="missing"?n.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let d=u?Object.keys(i).map(h=>({check:`${h} hook`,status:"pass",message:`${h} hook provided by context-mode@context-mode plugin`})):Object.entries(i).map(([h,m])=>{let f=l.config.hooks?.[h],g=m[0],y=Array.isArray(f)&&f.some(b=>this.isExpectedHookEntry(h,b,g)),_=h==="PreCompact"?"warn":"fail";return{check:`${h} hook`,status:y?"pass":_,message:y?`${h} hook configured in ${this.getHooksPath()}`:h==="PreCompact"?`${h} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${h} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),p=[];for(let h of Object.keys(i)){let m=l.config.hooks?.[h];if(!Array.isArray(m))continue;let f=m.filter(g=>this.isManagedContextModeEntry(h,g)).length;f>1?p.push({check:`${h} duplicates`,status:"warn",message:`${f} context-mode entries found for ${h} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&f===1&&p.push({check:`${h} plugin duplicate`,status:"warn",message:`${h} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return n.concat(d,p)}checkPluginRegistration(){try{let e=hs(this.getSettingsPath(),"utf-8"),n=eS(e),r=tS(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:"context-mode@context-mode plugin enabled"}:r?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=hs(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let m=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${m}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let m of Object.keys(l))this.removeManagedHookEntries(u,m,r);else for(let[m,f]of Object.entries(l))this.upsertManagedHookEntry(u,m,f[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let p=tA(s).text,h=p!==s;if(a){let m=nS(p,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));m.removed.length>0&&(p=m.text,r.push("Removed standalone Codex context-mode MCP registration"));let f=this.pruneStaleUserHookTrustState(p,u);f.removed.length>0&&(p=f.text,r.push(`Removed ${f.removed.length} stale Codex hook trust entr${f.removed.length===1?"y":"ies"}`))}if(p!==s){let m=p.includes(`\r
164
- `)?`\r
165
- `:`
166
- `,f=p.endsWith(`
167
- `)?p:`${p}${m}`;Cp(Op(o),{recursive:!0}),Qx(o,f,"utf-8"),h&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{KI(n,JI.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Mc(Op(XI(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return hs(e,"utf-8")}catch{return`# context-mode
168
-
169
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return Xn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return GI(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(hs(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();Cp(Op(n),{recursive:!0}),Qx(n,JSON.stringify(e,null,2)+`
170
- `,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return WI(Xn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&eS(n),s=Mc(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return jc(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(Mc(e))===this.normalizeCommand(Mc(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return nS(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=nA(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),p=o[u.pop()??""];if(u.join(":")!==r||!p||!Number.isInteger(d)||!Number.isInteger(l))return!1;let m=n[p]?.[d];return!m||!Array.isArray(m.hooks)||!m.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(oo[e]??""),s=QI[e]??[];return r.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as aS,writeFileSync as rA,mkdirSync as oA,accessSync as sA,chmodSync as iA,constants as aA}from"node:fs";import{resolve as zc,join as cA}from"node:path";var Tr,Fc=v(()=>{"use strict";it();Tr=class extends Se{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return zc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=aS(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=aS(zc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();oA(zc(".github","hooks"),{recursive:!0}),rA(n,JSON.stringify(e,null,2)+`
171
- `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=cA(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=zc(r,o);try{sA(s,aA.R_OK),iA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function cS(t,e){if(!Np[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,Np,_3,b3,uS=v(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Np={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},_3=[Yt.PRE_TOOL_USE,Yt.SESSION_START],b3=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var dS={};_e(dS,{VSCodeCopilotAdapter:()=>jp});import{readFileSync as Dp,mkdirSync as lS,accessSync as uA,existsSync as lA,constants as dA}from"node:fs";import{resolve as gs,join as Mi}from"node:path";import{homedir as Mp}from"node:os";var jp,pS=v(()=>{"use strict";Fc();it();uS();jp=class extends Tr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:Np,buildHookCommand:cS};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=ht();if(e){let s=Mi(e,"context-mode","sessions");return lS(s,{recursive:!0}),s}let n=gs(".github","context-mode","sessions"),r=Mi(Mp(),".vscode","context-mode","sessions"),o=lA(gs(".github"))?n:r;return lS(o,{recursive:!0}),o}getConfigDir(e){return gs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=gs(".github","hooks");try{uA(r,dA.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=gs(r,"context-mode.json");try{let s=Dp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=gs(".vscode","mcp.json"),n=Dp(e,"utf-8"),o=JSON.parse(n).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Mi(Mp(),".vscode","extensions"),Mi(Mp(),".vscode-insiders","extensions")];for(let n of e)try{let r=Dp(Mi(n,"extensions.json"),"utf-8"),s=JSON.parse(r).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function mS(t,e){if(!Lp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,Lp,$3,P3,fS=v(()=>{"use strict";Qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Lp={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},$3=[Qt.PRE_TOOL_USE,Qt.SESSION_START],P3=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var hS={};_e(hS,{JetBrainsCopilotAdapter:()=>zp});import{readFileSync as pA}from"node:fs";import{resolve as mA}from"node:path";var zp,gS=v(()=>{"use strict";Fc();fS();zp=class extends Tr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:Lp,buildHookCommand:mS};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return mA(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=pA(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[Qt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function yS(t,e){let n=Fp[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var St,Fp,D3,M3,_S=v(()=>{"use strict";St={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Fp={[St.PRE_TOOL_USE]:"pretooluse.mjs",[St.POST_TOOL_USE]:"posttooluse.mjs",[St.PRE_COMPACT]:"precompact.mjs",[St.SESSION_START]:"sessionstart.mjs",[St.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[St.STOP]:"stop.mjs"},D3=[St.PRE_TOOL_USE,St.SESSION_START],M3=[St.POST_TOOL_USE,St.PRE_COMPACT,St.USER_PROMPT_SUBMIT,St.STOP]});var wS={};_e(wS,{CopilotCliAdapter:()=>Up,copilotCliHome:()=>Uc,copilotCliMcpConfigPath:()=>Hc});import{existsSync as bS,mkdirSync as xS,readFileSync as Hp,writeFileSync as fA}from"node:fs";import{homedir as SS}from"node:os";import{dirname as hA,join as ys,resolve as kS}from"node:path";function vS(){return process.env[gA]==="1"}function yA(t){return kS(t,"configs","copilot-cli","hooks.json")}function _A(t){return Kn(Hp(t,"utf-8"))??{}}function bA(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function Uc(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?ys(SS(),t.replace(/^~[/\\]?/,"")):kS(t):ys(SS(),".copilot")}function Hc(){return ys(Uc(),"mcp-config.json")}var gA,Up,ES=v(()=>{"use strict";Fc();it();Di();_S();gA="CONTEXT_MODE_COPILOT_PLUGIN";Up=class extends Tr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:St,HOOK_SCRIPTS:Fp,buildHookCommand:yS};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return ys(Uc(),"hooks","context-mode.json")}getConfigDir(e){return Uc()}getSessionDir(){let e=ht(),n=e?ys(e,"context-mode","sessions"):ys(this.getConfigDir(),"context-mode","sessions");return xS(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();xS(hA(n),{recursive:!0}),fA(n,JSON.stringify(e,null,2)+`
172
- `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=Hp(this.getSettingsPath(),"utf-8");return Kn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=vS(),o=r?yA(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=_A(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(St)){let l=bA(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(vS())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=Hp(Hc(),"utf-8");return"context-mode"in((Kn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${Hc()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return bS(Hc())||bS(this.getSettingsPath())?"standalone":"not installed"}}});function ji(t,e){let n=Bp[e],r=en(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function en(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ve,Bp,xA,SA,Zp,TS,$S,PS=v(()=>{"use strict";ve={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Bp={[ve.PRE_TOOL_USE]:"pretooluse.mjs",[ve.POST_TOOL_USE]:"posttooluse.mjs",[ve.SESSION_START]:"sessionstart.mjs",[ve.STOP]:"stop.mjs",[ve.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},xA="MCP:(?!ctx_)",SA=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",xA],Zp=SA.join("|"),TS=[ve.PRE_TOOL_USE],$S=[ve.POST_TOOL_USE]});var AS={};_e(AS,{CursorAdapter:()=>qp});import{readFileSync as Bc,writeFileSync as vA,mkdirSync as kA,accessSync as RS,chmodSync as wA,constants as CS,existsSync as OS,readdirSync as EA}from"node:fs";import{execSync as TA}from"node:child_process";import{resolve as so,join as io}from"node:path";import{homedir as Zc}from"node:os";var IS,qp,NS=v(()=>{"use strict";it();kr();PS();IS="/Library/Application Support/Cursor/hooks.json",qp=class extends Se{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return so(".cursor","hooks.json")}getConfigDir(e){return so(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ve.PRE_TOOL_USE]:[{type:"command",command:en(ve.PRE_TOOL_USE),matcher:Zp,loop_limit:null,failClosed:!1}],[ve.POST_TOOL_USE]:[{type:"command",command:en(ve.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ve.SESSION_START]:[{type:"command",command:en(ve.SESSION_START),loop_limit:null,failClosed:!1}],[ve.STOP]:[{type:"command",command:en(ve.STOP),loop_limit:null,failClosed:!1}],[ve.AFTER_AGENT_RESPONSE]:[{type:"command",command:en(ve.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=Bc(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();kA(so(".cursor"),{recursive:!0}),vA(n,JSON.stringify(e,null,2)+`
173
- `,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of TS){let a=s[i],c=Array.isArray(a)&&a.some(u=>ji(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of $S){let a=s[i],c=Array.isArray(a)&&a.some(u=>ji(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}OS(IS)&&n.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&n.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>ji(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[io(Zc(),".cursor","plugins","local"),io(Zc(),".cursor","plugins","cache")],n=[];for(let r of e){try{RS(r,CS.F_OK)}catch{continue}let o=[];try{o=EA(r)}catch{continue}for(let s of o){let i=io(r,s,".cursor-plugin","plugin.json");try{let a=Bc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[so(".cursor","mcp.json"),io(Zc(),".cursor","mcp.json")];for(let r of e)try{let o=Bc(r,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return TA("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,ve.PRE_TOOL_USE,{type:"command",command:en(ve.PRE_TOOL_USE),matcher:Zp,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ve.POST_TOOL_USE,{type:"command",command:en(ve.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ve.SESSION_START,{type:"command",command:en(ve.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ve.STOP,{type:"command",command:en(ve.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ve.AFTER_AGENT_RESPONSE,{type:"command",command:en(ve.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=io(e,"hooks","cursor");for(let o of Object.values(Bp)){let s=so(r,o);try{RS(s,CS.R_OK),wA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),io(Zc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(IS),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let n=Bc(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[so(".claude","settings.json"),so(".claude","settings.local.json"),io(Be(),"settings.json")].some(n=>OS(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>ji(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var MS={};_e(MS,{AntigravityAdapter:()=>Li});import{readFileSync as qc,writeFileSync as $A,mkdirSync as PA}from"node:fs";import{resolve as Vc,dirname as DS}from"node:path";import{fileURLToPath as RA}from"node:url";import{homedir as Vp}from"node:os";var Li,Wp=v(()=>{"use strict";it();Li=class extends Se{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Vc(Vp(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Vc(Vp(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=qc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();PA(DS(n),{recursive:!0}),$A(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=qc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=Vc(Vp(),".gemini","extensions","context-mode","package.json");return JSON.parse(qc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Vc(DS(RA(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return qc(e,"utf-8")}catch{return`# context-mode
174
-
175
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var qS={};_e(qS,{AntigravityCliAdapter:()=>Qp,antigravityCliConfigDir:()=>BS,antigravityCliHooksPath:()=>Gp,antigravityCliMcpConfigPath:()=>US,antigravityCliPluginDir:()=>Gc});import{mkdirSync as CA,readFileSync as Wc,writeFileSync as OA}from"node:fs";import{dirname as IA,resolve as ao}from"node:path";import{homedir as Kc}from"node:os";function US(){return ao(Kc(),".gemini","config","mcp_config.json")}function BS(){return ao(Kc(),".gemini","antigravity-cli")}function Gp(){return ao(Kc(),".gemini","config","hooks.json")}function Gc(){return ao(Kc(),".gemini","config","plugins","context-mode")}function AA(){return ao(Gc(),"mcp_config.json")}function NA(){return ao(Gc(),"hooks.json")}function jS(t){for(let e of t)try{if("context-mode"in((Kn(Wc(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function In(t){return t&&typeof t=="object"?t:{}}function LS(t){let e=In(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function zS(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function ZS(t,e){let n=In(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>In(o).command===e)}function FS(t,e){return JSON.stringify(t).includes(e)}function DA(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function HS(t,e){return Array.isArray(t)&&t.some(n=>ZS(n,e))}function MA(t){return Array.isArray(t)&&t.some(e=>{let n=In(e);return DA(n.matcher)&&ZS(e,Jp)})}function jA(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(Kn(Wc(n,"utf-8"))??{}).hooks??{},s=MA(o.PreToolUse),i=HS(o.PostToolUse,Xp),a=HS(o.Stop,Yp);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function zA(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function Kp(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!FS(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!FS(a,r)),n],!0)}var Jp,LA,Xp,Yp,Qp,VS=v(()=>{"use strict";Wp();Di();Jp="context-mode hook antigravity-cli pretooluse",LA="run_command|view_file|grep_search|web_fetch|read_url_content",Xp="context-mode hook antigravity-cli posttooluse",Yp="context-mode hook antigravity-cli stop";Qp=class extends Li{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return US()}getConfigDir(e){return BS()}parsePreToolUseInput(e){let n=In(e),r=In(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:In(r.args),sessionId:zS(n),projectDir:LS(n),raw:e}}parsePostToolUseInput(e){let n=In(e),r=In(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:In(r.args),toolOutput:o,isError:o.length>0,sessionId:zS(n),projectDir:LS(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:zA(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=jS([AA(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}getInstalledVersion(){try{let e=Kn(Wc(ao(Gc(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return jS([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=Gp(),o={};try{o=Kn(Wc(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:LA,hooks:[{type:"command",command:Jp}]},a={matcher:"",hooks:[{type:"command",command:Xp}]},c={matcher:"",hooks:[{type:"command",command:Yp}]},u=Kp(s,"PreToolUse",i,Jp),l=Kp(s,"PostToolUse",a,Xp),d=Kp(s,"Stop",c,Yp);return(u||l||d)&&(o.hooks=s,CA(IA(r),{recursive:!0}),OA(r,JSON.stringify(o,null,2)+`
176
- `,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=jA([NA(),Gp()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli\` or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}]}}});function Jc(t,e){let n=WS[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function _s(t,e){let n=WS[t];return e&&n?qe(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var ze,WS,FA,HA,em,lW,dW,KS=v(()=>{"use strict";Rn();ze={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},WS={[ze.PRE_TOOL_USE]:"pretooluse.mjs",[ze.POST_TOOL_USE]:"posttooluse.mjs",[ze.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[ze.AGENT_SPAWN]:"agentspawn.mjs"},FA="@(?!context-mode/)",HA=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",FA],em=HA.join("|"),lW=[ze.PRE_TOOL_USE,ze.AGENT_SPAWN],dW=[ze.POST_TOOL_USE,ze.USER_PROMPT_SUBMIT]});var YS={};_e(YS,{KiroAdapter:()=>tm});import{readFileSync as bs,writeFileSync as GS,mkdirSync as JS}from"node:fs";import{resolve as co,dirname as XS}from"node:path";import{fileURLToPath as UA}from"node:url";import{homedir as Xc}from"node:os";var tm,QS=v(()=>{"use strict";it();KS();tm=class extends Se{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return co(Xc(),".kiro","settings","mcp.json")}getConfigDir(e){return co(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[ze.PRE_TOOL_USE]:[{matcher:em,hooks:[{type:"command",command:_s(ze.PRE_TOOL_USE,e)}]}],[ze.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:_s(ze.POST_TOOL_USE,e)}]}],[ze.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:_s(ze.AGENT_SPAWN,e)}]}],[ze.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:_s(ze.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=bs(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();JS(XS(n),{recursive:!0}),GS(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=co(Xc(),".kiro","agents","default.json");try{let s=JSON.parse(bs(r,"utf-8")).hooks??{};for(let i of[ze.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Jc(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[ze.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>Jc(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=bs(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=co(Xc(),".kiro","extensions","context-mode","package.json");return JSON.parse(bs(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=co(Xc(),".kiro","agents"),o=co(r,"default.json");try{JS(r,{recursive:!0});let s={};try{s=JSON.parse(bs(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[ze.PRE_TOOL_USE,em],[ze.POST_TOOL_USE,"*"],[ze.AGENT_SPAWN,"*"],[ze.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Jc(d,c))||(l.push({matcher:u,command:_s(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,GS(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=co(XS(UA(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return bs(e,"utf-8")}catch{return`# context-mode
177
-
178
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var nv={};_e(nv,{ZedAdapter:()=>rm});import{readFileSync as nm,writeFileSync as BA,mkdirSync as ZA}from"node:fs";import{resolve as ev,dirname as tv}from"node:path";import{fileURLToPath as qA}from"node:url";import{homedir as VA}from"node:os";var rm,rv=v(()=>{"use strict";it();rm=class extends Se{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return ev(VA(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=nm(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();ZA(tv(n),{recursive:!0}),BA(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=nm(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=ev(tv(qA(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return nm(e,"utf-8")}catch{return`# context-mode
179
-
180
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var om,ov=v(()=>{"use strict";om="mcp__(?!.*context-mode)"});var av={};_e(av,{QwenCodeAdapter:()=>sm});import{readFileSync as WA,writeFileSync as KA,existsSync as GA}from"node:fs";import{resolve as sv,join as JA}from"node:path";import{homedir as iv}from"node:os";var sm,cv=v(()=>{"use strict";mp();ov();Rn();sm=class extends ps{constructor(){super([".qwen"])}name="Qwen Code";paradigm="json-stdio";projectDirEnvVar="QWEN_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getSettingsPath(){return sv(iv(),".qwen","settings.json")}getInstructionFiles(){return["QWEN.md"]}generateHookConfig(e){return{PreToolUse:[{matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",om].join("|"),hooks:[{type:"command",command:qe(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:qe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:qe(`${e}/hooks/qwen-code/stop.mjs`)}]}]}}readSettings(){try{let e=WA(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){KA(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit","Stop"]){let i=Array.isArray(o[s])&&o[s].length>0;n.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let p=l.hooks??[];return p.some(m=>m.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(m.command))?p.every(m=>{if(!m.command)return!0;let f=m.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=m.command.match(/node\s+"?([^"]+\.mjs)"?/),y=f||g;return y?GA(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",om].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""},{name:"Stop",script:"qwen-code/stop.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:qe(`${e}/hooks/${a}`)}]},l=r[i];if(l&&Array.isArray(l)){let d=l.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:sv(JA(iv(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var uv={};_e(uv,{OMPAdapter:()=>cm});import{readFileSync as im,writeFileSync as XA,mkdirSync as YA}from"node:fs";import{resolve as am,dirname as QA}from"node:path";import{homedir as eN}from"node:os";var cm,lv=v(()=>{"use strict";it();cm=class extends Se{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??am(eN(),".omp","agent")}getSettingsPath(){return am(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=im(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();YA(QA(n),{recursive:!0}),XA(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=im(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:`Add context-mode to mcpServers in ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){try{let e=am(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(im(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
181
-
182
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var dv={};_e(dv,{PiAdapter:()=>pm});import{readFileSync as um,writeFileSync as tN,mkdirSync as nN}from"node:fs";import{resolve as lm,dirname as rN}from"node:path";import{homedir as dm}from"node:os";var pm,pv=v(()=>{"use strict";it();pm=class extends Se{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return lm(dm(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=um(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();nN(rN(n),{recursive:!0}),tN(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=lm(dm(),".pi","extensions","context-mode","package.json");try{return JSON.parse(um(e,"utf-8"))?.name==="context-mode"?{check:"Pi extension registration",status:"pass",message:`context-mode extension installed at ${e}`}:{check:"Pi extension registration",status:"warn",message:`Unexpected package at ${e}`}}catch{return{check:"Pi extension registration",status:"fail",message:`context-mode not found at ${e}`,fix:"Run: context-mode upgrade"}}}getInstalledVersion(){try{let e=lm(dm(),".pi","extensions","context-mode","package.json");return JSON.parse(um(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
183
-
184
- Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});import{homedir as mv}from"node:os";import{resolve as mm,join as BW}from"node:path";function fv(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?mm(mv(),t.replace(/^~[/\\]?/,"")):mm(t):mm(mv(),".kimi-code")}var hv=v(()=>{"use strict"});var xv={};_e(xv,{KimiAdapter:()=>hm,probeKimiCliVersion:()=>bv});import{execFileSync as oN}from"node:child_process";import{readFileSync as zi,writeFileSync as sN,accessSync as iN,copyFileSync as aN,constants as cN,mkdirSync as gv}from"node:fs";import{resolve as uN,dirname as yv,join as uo}from"node:path";import{fileURLToPath as lN}from"node:url";function bv(t=oN){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","kimi --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("kimi",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function _v(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)continue;let s=o.match(/^\s*(\w+)\s*=\s*(?:"([^"]*)"|(\d+))\s*(?:#.*)?$/);if(s){let i=s[1],a=s[2],c=s[3];a!==void 0?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function mN(t){let e=["[[hooks]]"];return e.push(`event = "${t.event}"`),t.matcher&&e.push(`matcher = "${t.matcher}"`),e.push(`command = "${t.command}"`),t.timeout!==void 0&&e.push(`timeout = ${t.timeout}`),e.join(`
185
- `)}function fm(t){return t.command.includes("context-mode hook kimi")}function fN(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var dN,$r,pN,hm,Sv=v(()=>{"use strict";it();Jt();hv();dN="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",$r={PreToolUse:"context-mode hook kimi pretooluse",PostToolUse:"context-mode hook kimi posttooluse",SessionStart:"context-mode hook kimi sessionstart",SessionEnd:"context-mode hook kimi sessionend",PreCompact:"context-mode hook kimi precompact",UserPromptSubmit:"context-mode hook kimi userpromptsubmit",Stop:"context-mode hook kimi stop"},pN={PreToolUse:["hooks/pretooluse.mjs","hooks/kimi/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/kimi/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/kimi/sessionstart.mjs"],SessionEnd:["hooks/sessionend.mjs","hooks/kimi/sessionend.mjs"],PreCompact:["hooks/precompact.mjs","hooks/kimi/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/kimi/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/kimi/stop.mjs"]};hm=class extends Se{constructor(){super([".kimi-code"])}name="Kimi Code CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return fv()}getSettingsPath(){return uo(this.getConfigDir(),"config.toml")}getMcpPath(){return uo(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=ht(),n=e?uo(e,"context-mode","sessions"):uo(this.getConfigDir(),"context-mode","sessions");return gv(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=ht(),r=n?uo(n,"context-mode","memory"):uo(this.getConfigDir(),"memory");return e?uo(r,rt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:dN,hooks:[{type:"command",command:$r.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:$r.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:$r.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:$r.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:$r.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:$r.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:$r.Stop}]}]}}readSettings(){try{return{_raw_toml:zi(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=bv();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=zi(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=_v(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(p=>p.event===a&&this.isExpectedHookEntry(a,p,u)),d=a==="PreCompact"?"warn":"fail";n.push({check:`${a} hook`,status:l?"pass":d,message:l?`${a} hook configured in ${this.getSettingsPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Kimi build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:l?void 0:`Update ${this.getSettingsPath()} to include the managed ${a} [[hooks]] entry`})}for(let a of Object.keys(i)){let c=s.filter(u=>u.event===a&&fm(u)).length;c>1&&n.push({check:`${a} duplicates`,status:"warn",message:`${c} context-mode entries found for ${a} in ${this.getSettingsPath()}; Kimi will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return n}checkPluginRegistration(){try{let e=zi(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in mcp.json"}:o?{check:"MCP registration",status:"fail",message:"mcpServers section exists but context-mode not found",fix:`Add context-mode to mcpServers in ${this.getMcpPath()}`}:{check:"MCP registration",status:"fail",message:"No mcpServers section in mcp.json",fix:`Add mcpServers.context-mode to ${this.getMcpPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getMcpPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=[],r=this.generateHookConfig(""),o="";try{o=zi(this.getSettingsPath(),"utf-8")}catch{o=""}let s=_v(o),i=s.filter(l=>!fm(l)),a=[];for(let[l,d]of Object.entries(r)){let p=fN(l,d[0]);p&&a.push(p)}let c=s.some(fm),u=this.rebuildToml(o,i,a);return u!==o&&(gv(yv(this.getSettingsPath()),{recursive:!0}),sN(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{iN(n,cN.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=uN(yv(lN(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return zi(e,"utf-8")}catch{return`# context-mode
186
-
187
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return aN(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=($r[e]??"").replace(/\\/g,"/"),s=pN[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){let o=e.split(/\r?\n/),s=[],i=!1;for(let c of o){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(c)){i=!0;continue}if(i){/^\s*\[/.test(c)&&(i=!1,s.push(c));continue}s.push(c)}for(;s.length>0&&s[s.length-1]==="";)s.pop();s.length>0&&s.push("");let a=[...n,...r];if(a.length>0)for(let c of a)s.push(mN(c)),s.push("");return s.join(`
188
- `)}}});var ym={};_e(ym,{PLATFORM_ENV_VARS:()=>xs,__resetClaudeCodePluginCacheForTests:()=>yN,__seedClaudeCodePluginCacheMissForTests:()=>_N,detectPlatform:()=>Qe,foreignIdentificationEnv:()=>vN,foreignWorkspaceEnv:()=>SN,getAdapter:()=>Hi,getEnvVarNames:()=>xN,getSessionDirSegments:()=>Fi,workspaceEnvVarsFor:()=>gm});import{existsSync as Ye,readFileSync as hN}from"node:fs";import{resolve as Fe}from"node:path";import{homedir as vv}from"node:os";function gN(){if(lo!==null)return lo!=="miss"&&lo.hasCM;try{let t=Fe(vv(),".claude","plugins","installed_plugins.json"),e=hN(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return lo={hasCM:o},o}catch{return lo="miss",!1}}function yN(){lo=null}function _N(){lo="miss"}function xN(t){return(xs.get(t)??[]).map(e=>e.name)}function gm(t){return(xs.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function SN(t){let e=new Set;for(let[n,r]of xs)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function vN(t){let e=new Set;for(let[n,r]of xs)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function Fi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function Qe(t){if(t?.name){let s=ax[t.name];if(s)return{platform:s,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of xs)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&gN()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=vv(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?Fe(n,s.replace(/^~[/\\]?/,"")):Fe(s):Fe(n,".copilot")})(),o=Ye(Fe(r,"mcp-config.json"))||Ye(Fe(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Ye(Fe(n,".local","bin","agy"))||Ye(Fe(n,".gemini","antigravity-cli"))||Ye(Fe(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:Ye(Fe(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ye(Fe(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ye(Fe(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ye(Fe(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ye(Fe(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ye(Fe(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ye(Fe(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ye(Fe(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Ye(Fe(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ye(Fe(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ye(Fe(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ye(Fe(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ye(Fe(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ye(Fe(n,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function Hi(t){let e=t??Qe().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Sp(),xp));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(Ux(),Hx));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(Vx(),qx));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(Gx(),Kx));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Ap(),iS));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(pS(),dS));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(gS(),hS));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(ES(),wS));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(NS(),AS));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(Wp(),MS));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(VS(),qS));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(QS(),YS));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(rv(),nv));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(cv(),av));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(lv(),uv));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(pv(),dv));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(Sv(),xv));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Sp(),xp));return new n}}}var lo,bN,xs,po=v(()=>{"use strict";cx();lo=null;bN=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"},{name:"PI_CODING_AGENT",role:"identification"}]]],xs=new Map(bN)});import{resolve as Ui}from"node:path";import{homedir as _m}from"node:os";function Be(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Ui(_m(),e.replace(/^~[/\\]?/,"")):Ui(e):Ui(_m(),".claude")}function kN(t=process.env){return Ui(Be(t),"settings.json")}function bm(t=process.env){let e=[],n=Qe();if(n.platform!=="claude-code"){let o=Fi(n.platform);o&&o.length>0&&e.push(Ui(_m(),...o,"settings.json"))}let r=kN(t);return e.includes(r)||e.push(r),e}var kr=v(()=>{"use strict";po()});import{readdirSync as wN,statSync as EN,lstatSync as TN,realpathSync as kv,existsSync as $N,readFileSync as PN}from"node:fs";import{join as Ev,extname as RN,relative as Tv,sep as CN,resolve as ON}from"node:path";function MN(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];r==="*"?t[n+1]==="*"?(e+=".*",n++):e+="[^/]*":r==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(r)?e+="\\"+r:e+=r}return new RegExp(`^${e}$`)}function wv(t,e){if(e.length===0)return!1;let n=t.split("/").pop()??t;for(let r of e){if(!r.includes("/")&&!r.includes("*")){if(n===r||t.split("/").includes(r))return!0;continue}let o=MN(r);if(o.test(t)||o.test(n))return!0}return!1}function jN(t){let e=Ev(t,".gitignore");if(!$N(e))return[];try{return PN(e,"utf-8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function LN(t,e){return Tv(t,e).split(CN).join("/")}function $v(t,e={}){let{include:n,exclude:r,maxDepth:o=NN,maxFiles:s=DN,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=kv(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:AN).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...IN,...r??[],...a?jN(u):[]],p=n??[],h=[],m=new Set([u]),f=0,g=!1;function y(_,b){if(g||b>o)return;let S;try{S=wN(_,{withFileTypes:!0})}catch{return}for(let E of S){if(g)return;let A=Ev(_,E.name),x=LN(u,A);if(wv(x,d))continue;let T=E.isDirectory(),P=E.isFile(),N=!1;try{N=TN(A).isSymbolicLink()}catch{continue}if(N){if(!c)continue;let C;try{C=kv(A)}catch{continue}let F=Tv(u,C);if((F.startsWith("..")||ON(F)===C)&&F.startsWith("..")||m.has(C))continue;m.add(C);try{let W=EN(C);T=W.isDirectory(),P=W.isFile()}catch{continue}}if(T){y(A,b+1);continue}if(!P)continue;let R=RN(A).toLowerCase();if(l.includes(R)&&!(p.length>0&&!wv(x,p))){if(f++,h.length>=s){g=!0;return}h.push(A)}}}return y(u,0),{files:h,capped:g,totalSeen:f}}var IN,AN,NN,DN,Pv=v(()=>{"use strict";IN=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],AN=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],NN=5,DN=200});import{readFileSync as Rv,readdirSync as Dv,unlinkSync as Sm,existsSync as xm,statSync as Qc,openSync as Cv,fstatSync as Ov,closeSync as Iv}from"node:fs";import{createHash as Av}from"node:crypto";import{tmpdir as Mv}from"node:os";import{join as vm}from"node:path";function jv(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function zN(t,e="AND"){let n=jv(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!Ss.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function FN(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=jv(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!Ss.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function HN(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function UN(t){return t<=4?1:t<=12?2:3}function km(){let t=Mv(),e=0;try{let n=Dv(t);for(let r of n){let o=r.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=vm(t,r);for(let a of["","-wal","-shm"])try{Sm(i+a)}catch{}e++}}}catch{}return e}function wm(t,e){let n=0;try{if(!xm(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=Dv(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=vm(t,s),c=Qc(i).mtimeMs<r;if(!c){let u=i+"-wal";if(xm(u))try{let l=Qc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Sm(i+u)}catch{}n++}}catch{}}catch{}return n}function WN(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function KN(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,p=d+n;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=p&&(r++,u++)}}return r}function GN(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,n=new Array(e.length).fill(0),r=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][n[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<r&&(r=a),n[i]++,n[i]>=e[i].length)break}return r}var Ss,Yc,BN,ZN,qN,Nv,VN,vs,Em=v(()=>{"use strict";yr();Pv();Ss=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);Yc=4096,BN=3,ZN=200,qN=5e3,Nv=80,VN=.5;vs=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#f;#h;#g;#y;#_;#b;#x;#S;#v;#k;#w;#E;#T;#$;#P;#R;#C;#O;#I;#A;#N;#D;#M;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=nt();this.#t=e??vm(Mv(),`context-mode-${process.pid}.db`),os(this.#t);let r;try{r=new n(this.#t,{timeout:3e4}),rs(r)}catch(o){let s=o instanceof Error?o.message:String(o);if($c(s)){Tc(this.#t),os(this.#t);try{r=new n(this.#t,{timeout:3e4}),rs(r)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=r,this.#B(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Sm(this.#t+e)}catch{}}#B(){this.#e.exec(`
189
- CREATE TABLE IF NOT EXISTS sources (
190
- id INTEGER PRIMARY KEY AUTOINCREMENT,
191
- label TEXT NOT NULL,
192
- chunk_count INTEGER NOT NULL DEFAULT 0,
193
- code_chunk_count INTEGER NOT NULL DEFAULT 0,
194
- indexed_at TEXT NOT NULL DEFAULT (datetime('now')),
195
- file_path TEXT,
196
- content_hash TEXT
197
- );
198
-
199
- CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
200
- title,
201
- content,
202
- source_id UNINDEXED,
203
- content_type UNINDEXED,
204
- source_category UNINDEXED,
205
- session_id UNINDEXED,
206
- event_id UNINDEXED,
207
- timestamp UNINDEXED,
208
- tokenize='porter unicode61'
209
- );
210
-
211
- CREATE VIRTUAL TABLE IF NOT EXISTS chunks_trigram USING fts5(
212
- title,
213
- content,
214
- source_id UNINDEXED,
215
- content_type UNINDEXED,
216
- source_category UNINDEXED,
217
- session_id UNINDEXED,
218
- event_id UNINDEXED,
219
- timestamp UNINDEXED,
220
- tokenize='trigram'
221
- );
222
-
223
- CREATE TABLE IF NOT EXISTS vocabulary (
224
- word TEXT PRIMARY KEY
225
- );
226
-
227
- CREATE INDEX IF NOT EXISTS idx_sources_label ON sources(label);
228
- `);try{let e=this.#e.prepare("SELECT name FROM pragma_table_xinfo('chunks')").all(),n=new Set(e.map(r=>r.name));e.length>0&&!n.has("source_category")&&(this.#e.exec("DROP TABLE IF EXISTS chunks"),this.#e.exec("DROP TABLE IF EXISTS chunks_trigram"),this.#e.exec(`
229
- CREATE VIRTUAL TABLE chunks USING fts5(
230
- title,
231
- content,
232
- source_id UNINDEXED,
233
- content_type UNINDEXED,
234
- source_category UNINDEXED,
235
- session_id UNINDEXED,
236
- event_id UNINDEXED,
237
- timestamp UNINDEXED,
238
- tokenize='porter unicode61'
239
- );
240
- CREATE VIRTUAL TABLE chunks_trigram USING fts5(
241
- title,
242
- content,
243
- source_id UNINDEXED,
244
- content_type UNINDEXED,
245
- source_category UNINDEXED,
246
- session_id UNINDEXED,
247
- event_id UNINDEXED,
248
- timestamp UNINDEXED,
249
- tokenize='trigram'
250
- );
251
- `))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#Z(){this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#f=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#h=this.#e.prepare(`
252
- SELECT
253
- chunks.title,
254
- chunks.content,
255
- chunks.content_type,
256
- chunks.timestamp,
257
- sources.label,
258
- bm25(chunks, 5.0, 1.0) AS rank,
259
- highlight(chunks, 1, char(2), char(3)) AS highlighted,
260
- chunks.session_id
261
- FROM chunks
262
- JOIN sources ON sources.id = chunks.source_id
263
- WHERE chunks MATCH ?
264
- ORDER BY rank
265
- LIMIT ?
266
- `),this.#g=this.#e.prepare(`
267
- SELECT
268
- chunks.title,
269
- chunks.content,
270
- chunks.content_type,
271
- chunks.timestamp,
272
- sources.label,
273
- bm25(chunks, 5.0, 1.0) AS rank,
274
- highlight(chunks, 1, char(2), char(3)) AS highlighted,
275
- chunks.session_id
276
- FROM chunks
277
- JOIN sources ON sources.id = chunks.source_id
278
- WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\'
279
- ORDER BY rank
280
- LIMIT ?
281
- `),this.#y=this.#e.prepare(`
282
- SELECT
283
- chunks.title,
284
- chunks.content,
285
- chunks.content_type,
286
- chunks.timestamp,
287
- sources.label,
288
- bm25(chunks, 5.0, 1.0) AS rank,
289
- highlight(chunks, 1, char(2), char(3)) AS highlighted,
290
- chunks.session_id
291
- FROM chunks
292
- JOIN sources ON sources.id = chunks.source_id
293
- WHERE chunks MATCH ? AND sources.label = ?
294
- ORDER BY rank
295
- LIMIT ?
296
- `),this.#_=this.#e.prepare(`
297
- SELECT
298
- chunks_trigram.title,
299
- chunks_trigram.content,
300
- chunks_trigram.content_type,
301
- chunks_trigram.timestamp,
302
- sources.label,
303
- bm25(chunks_trigram, 5.0, 1.0) AS rank,
304
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
305
- chunks_trigram.session_id
306
- FROM chunks_trigram
307
- JOIN sources ON sources.id = chunks_trigram.source_id
308
- WHERE chunks_trigram MATCH ?
309
- ORDER BY rank
310
- LIMIT ?
311
- `),this.#b=this.#e.prepare(`
312
- SELECT
313
- chunks_trigram.title,
314
- chunks_trigram.content,
315
- chunks_trigram.content_type,
316
- chunks_trigram.timestamp,
317
- sources.label,
318
- bm25(chunks_trigram, 5.0, 1.0) AS rank,
319
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
320
- chunks_trigram.session_id
321
- FROM chunks_trigram
322
- JOIN sources ON sources.id = chunks_trigram.source_id
323
- WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\'
324
- ORDER BY rank
325
- LIMIT ?
326
- `),this.#x=this.#e.prepare(`
327
- SELECT
328
- chunks_trigram.title,
329
- chunks_trigram.content,
330
- chunks_trigram.content_type,
331
- chunks_trigram.timestamp,
332
- sources.label,
333
- bm25(chunks_trigram, 5.0, 1.0) AS rank,
334
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
335
- chunks_trigram.session_id
336
- FROM chunks_trigram
337
- JOIN sources ON sources.id = chunks_trigram.source_id
338
- WHERE chunks_trigram MATCH ? AND sources.label = ?
339
- ORDER BY rank
340
- LIMIT ?
341
- `),this.#v=this.#e.prepare(`
342
- SELECT
343
- chunks.title,
344
- chunks.content,
345
- chunks.content_type,
346
- chunks.timestamp,
347
- sources.label,
348
- bm25(chunks, 5.0, 1.0) AS rank,
349
- highlight(chunks, 1, char(2), char(3)) AS highlighted,
350
- chunks.session_id
351
- FROM chunks
352
- JOIN sources ON sources.id = chunks.source_id
353
- WHERE chunks MATCH ? AND chunks.content_type = ?
354
- ORDER BY rank
355
- LIMIT ?
356
- `),this.#k=this.#e.prepare(`
357
- SELECT
358
- chunks.title,
359
- chunks.content,
360
- chunks.content_type,
361
- chunks.timestamp,
362
- sources.label,
363
- bm25(chunks, 5.0, 1.0) AS rank,
364
- highlight(chunks, 1, char(2), char(3)) AS highlighted,
365
- chunks.session_id
366
- FROM chunks
367
- JOIN sources ON sources.id = chunks.source_id
368
- WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks.content_type = ?
369
- ORDER BY rank
370
- LIMIT ?
371
- `),this.#w=this.#e.prepare(`
372
- SELECT
373
- chunks.title,
374
- chunks.content,
375
- chunks.content_type,
376
- chunks.timestamp,
377
- sources.label,
378
- bm25(chunks, 5.0, 1.0) AS rank,
379
- highlight(chunks, 1, char(2), char(3)) AS highlighted,
380
- chunks.session_id
381
- FROM chunks
382
- JOIN sources ON sources.id = chunks.source_id
383
- WHERE chunks MATCH ? AND sources.label = ? AND chunks.content_type = ?
384
- ORDER BY rank
385
- LIMIT ?
386
- `),this.#E=this.#e.prepare(`
387
- SELECT
388
- chunks_trigram.title,
389
- chunks_trigram.content,
390
- chunks_trigram.content_type,
391
- chunks_trigram.timestamp,
392
- sources.label,
393
- bm25(chunks_trigram, 5.0, 1.0) AS rank,
394
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
395
- chunks_trigram.session_id
396
- FROM chunks_trigram
397
- JOIN sources ON sources.id = chunks_trigram.source_id
398
- WHERE chunks_trigram MATCH ? AND chunks_trigram.content_type = ?
399
- ORDER BY rank
400
- LIMIT ?
401
- `),this.#T=this.#e.prepare(`
402
- SELECT
403
- chunks_trigram.title,
404
- chunks_trigram.content,
405
- chunks_trigram.content_type,
406
- chunks_trigram.timestamp,
407
- sources.label,
408
- bm25(chunks_trigram, 5.0, 1.0) AS rank,
409
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
410
- chunks_trigram.session_id
411
- FROM chunks_trigram
412
- JOIN sources ON sources.id = chunks_trigram.source_id
413
- WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks_trigram.content_type = ?
414
- ORDER BY rank
415
- LIMIT ?
416
- `),this.#$=this.#e.prepare(`
417
- SELECT
418
- chunks_trigram.title,
419
- chunks_trigram.content,
420
- chunks_trigram.content_type,
421
- chunks_trigram.timestamp,
422
- sources.label,
423
- bm25(chunks_trigram, 5.0, 1.0) AS rank,
424
- highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
425
- chunks_trigram.session_id
426
- FROM chunks_trigram
427
- JOIN sources ON sources.id = chunks_trigram.source_id
428
- WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
429
- ORDER BY rank
430
- LIMIT ?
431
- `),this.#S=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#P=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#R=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
432
- FROM chunks c
433
- JOIN sources s ON s.id = c.source_id
434
- WHERE c.source_id = ?
435
- ORDER BY c.rowid`),this.#C=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#O=this.#e.prepare("SELECT content FROM chunks WHERE source_id = ?"),this.#A=this.#e.prepare("SELECT label, chunk_count, code_chunk_count, indexed_at, file_path, content_hash FROM sources WHERE label = ?"),this.#I=this.#e.prepare(`
436
- SELECT
437
- (SELECT COUNT(*) FROM sources) AS sources,
438
- (SELECT COUNT(*) FROM chunks) AS chunks,
439
- (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
440
- `),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let p=Cv(r,"r");try{if(!Ov(p).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=Rv(p,"utf-8")}finally{Iv(p)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?Av("sha256").update(a).digest("hex"):void 0;return gr(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=$v(n,i),c=0,u=0,l=0,d=0;for(let p of a.files){if(s&&s(p)){l++;continue}try{let h=r?`${r}:${p}`:p,m=this.index({path:p,source:h,attribution:o});c++,u+=m.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:r??n}}indexPlainText(e,n,r=20,o,s=Yc){if(!e||e.trim().length===0)return this.#d([],n,"",void 0,void 0,o);let i=this.#J(e,r,s);return gr(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}indexJSON(e,n,r=Yc,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];return this.#U(s,[],i,r),i.length===0?this.indexPlainText(e,n,void 0,o,r):gr(()=>this.#d(i,n,e,void 0,void 0,o))}#d(e,n,r,o,s,i){let a=e.filter(p=>p.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(n),this.#l.run(n),this.#f.run(n),e.length===0){let f=this.#o.run(n,o??null,s??null);return Number(f.lastInsertRowid)}let p=this.#s.run(n,e.length,a,o??null,s??null),h=Number(p.lastInsertRowid),m=new Date().toISOString();for(let f of e){let g=f.hasCode?"code":"prose";this.#a.run(f.title,f.content,h,g,null,c,u,m),this.#c.run(f.title,f.content,h,g,null,c,u,m)}return h})();return r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#H(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=zN(e,o),c,u;return r&&s?(c=i==="exact"?this.#w:this.#k,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#v,u=[a,s,n]):(c=this.#h,u=[a,n]),gr(()=>this.#L(c.all(...u)))}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=FN(e,o);if(!a)return[];let c,u;return r&&s?(c=i==="exact"?this.#$:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#x:this.#b,u=[a,this.#p(r,i),n]):s?(c=this.#E,u=[a,s,n]):(c=this.#_,u=[a,n]),gr(()=>this.#L(c.all(...u)))}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=UN(n.length),o=this.#S.all(n.length-r,n.length+r),s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=HN(n,u);l<i&&(i=l,s=u)}let c=a?null:i<=r?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(n,c),c}#z(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"OR",o,s),l=new Map,d=p=>`${p.source}::${p.title}`;for(let[p,h]of c.entries()){let m=d(h),f=l.get(m);f?f.score+=1/(60+p+1):l.set(m,{result:h,score:1/(60+p+1)})}for(let[p,h]of u.entries()){let m=d(h),f=l.get(m);f?f.score+=1/(60+p+1):l.set(m,{result:h,score:1/(60+p+1)})}return Array.from(l.values()).sort((p,h)=>h.score-p.score).slice(0,n).map(({result:p,score:h})=>({...p,rank:-h}))}#F(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!Ss.has(i)),s=o.length>0?o:r;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(h=>a.includes(h)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,p=0;if(s.length>=2){let h=i.content.toLowerCase(),m=s.map(f=>WN(h,f));if(!m.some(f=>f.length===0)){d=1/(1+GN(m)/Math.max(h.length,1));let g=KN(m,s);p=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#z(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#F(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(f=>f.length>=3&&!Ss.has(f)),p=d.join(" "),m=d.map(f=>this.fuzzyCorrect(f)??f).join(" ");if(m!==p){let f=this.#z(m,a,r,o,s),g=c?f.filter(c):f;if(g.length>0)return this.#F(g.slice(0,n),m).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let n of e)try{if(!xm(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=Qc(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=Cv(n.file_path,"r"),i;try{if(!Ov(s).isFile())continue;i=Rv(s,"utf-8")}finally{Iv(s)}if(Av("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let n=this.#A.get(e);return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){return this.#P.all()}getIndexState(){let e=this.#e.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS total_chunks, COUNT(*) AS total_sources, MAX(indexed_at) AS last_indexed_at FROM sources").get();return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){return this.#R.all(e).map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r=this.#C.get(e);if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#O.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!Ss.has(p)));for(let p of d)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let p=Math.log(o/d),h=Math.min(l.length/20,.5),m=/[_]/.test(l),f=l.length>=12,g=m?1.5:f?.8:0;return{word:l,score:p+h+g}}).sort((l,d)=>d.score-l.score).slice(0,n).map(l=>l.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#N.run(o),this.#D.run(o),this.#M.run(o)))(e).changes}getDBSizeBytes(){try{return Qc(this.#t).size}catch{return 0}}#H(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#H(),ss(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!Ss.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=Yc){let r=[],o=e.split(`
441
- `),s=[],i=[],a="",c=()=>{let l=i.join(`
442
- `).trim();if(l.length===0)return;let d=this.#ee(s,a),p=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=n){r.push({title:d,content:l,hasCode:p}),i=[];return}let h=l.split(/\n\n+/),m=[],f=1,g=()=>{if(m.length===0)return;let y=m.join(`
443
-
444
- `).trim();if(y.length===0)return;let _=h.length>1?`${d} (${f})`:d;f++,r.push({title:_,content:y,hasCode:y.includes("```")}),m=[]};for(let y of h){m.push(y);let _=m.join(`
445
-
446
- `);Buffer.byteLength(_)>n&&m.length>1&&(m.pop(),g(),m=[y])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let h=d[1].length,m=d[2].trim();for(;s.length>0&&s[s.length-1].level>=h;)s.pop();s.push({level:h,text:m}),a=m,i.push(l),u++;continue}let p=l.match(/^(`{3,})(.*)?$/);if(p){let h=p[1],m=[l];for(u++;u<o.length;){if(m.push(o[u]),o[u].startsWith(h)&&o[u].trim()===h){u++;break}u++}i.push(...m);continue}i.push(l),u++}return c(),r}#G(e,n){if(Buffer.byteLength(e)<=n)return e;let r="",o=0;for(let s of e){let i=Buffer.byteLength(s);if(o+i>n)break;r+=s,o+=i}return r.length===0?[...e][0]??"":r}#m(e,n,r){let o=[],s=[],i=1,a=()=>{if(s.length===0)return;let c=s.join(`
447
- `),u=i===1?n:`${n} (${i})`;o.push({title:u,content:c}),i++,s=[]};for(let c of e){if(Buffer.byteLength(c)>r){a();let l=c,d=1;for(;l.length>0;){let p=this.#G(l,r);if(p.length<l.length){let m=p.lastIndexOf(" "),f=p.lastIndexOf(`
448
- `),g=Math.max(m,f);g>p.length*VN&&(p=p.slice(0,g))}let h=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:h,content:p}),l=l.slice(p.length),d++,i++}continue}let u=s.length>0?s.join(`
449
- `)+`
450
- `+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=Yc){let o=e.split(/\n\s*\n/);if(o.length>=BN&&o.length<=ZN&&o.every(u=>Buffer.byteLength(u)<qN))return o.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let p=d.split(`
451
- `)[0].slice(0,Nv)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:p,content:d}]:this.#m(d.split(`
452
- `),p,r)});let s=e.split(`
453
- `);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#m(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u<s.length;u+=c){let l=s.slice(u,u+n);if(l.length===0)break;let d=u+1,p=Math.min(u+l.length,s.length),h=l[0]?.trim().slice(0,Nv),m=l.join(`
454
- `);if(Buffer.byteLength(m)<=r)i.push({title:h||`Lines ${d}-${p}`,content:m});else{let f=this.#m(l,h||`Lines ${d}-${p}`,r);i.push(...f)}}return i}#U(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){r.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}}});import{readFileSync as zv,realpathSync as $m}from"node:fs";import{relative as JN,resolve as mo,sep as XN}from"node:path";function Fv(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function YN(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function QN(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Lv(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function eD(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=QN(o),a=Lv(s);n=`^${i}(\\s${a})?$`}else n=`^${Lv(t)}$`;return new RegExp(n,e?"i":"")}function tD(t,e=!1){let n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?r+2<t.length&&t[r+2]==="/"?(n+="(.*/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),r++);return new RegExp(`^${n}$`,e?"i":"")}function nD(t,e,n=!1){for(let r of e){let o=Fv(r);if(o&&eD(o,n).test(t))return r}return null}function Hv(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function rD(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a<t.length;a++){let c=t[a],u=Hv(t,a);c==="'"&&!o&&!s&&!u?(r=!r,n+=c):c==='"'&&!r&&!s&&!u?(o=!o,n+=c):c==="`"&&!r&&!o&&!u?(s=!s,n+=c):!r&&!o&&!s?c==="$"&&t[a+1]==="("&&!u?(i++,n+=c+t[a+1],a++):i>0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===`
455
- `||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function Uv(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c<t.length;c++){let u=t[c],l=Hv(t,c);if(u==="'"&&!r&&o===-1&&!l)n=!n;else if(u==='"'&&!n&&o===-1&&!l)r=!r;else if(u==="`"&&!n&&!r&&!l)if(o===-1)o=c+1;else{let d=t.slice(o,c);e.push(d),e.push(...Uv(d)),o=-1}else if(!n&&o===-1){if(u==="$"&&t[c+1]==="("&&!l)t[c+2]==="("?(a+=2,c+=2):(s.push(c+2),i.push(a),a++,c++);else if(u==="("&&!l)a++;else if(u===")"&&!l&&(a>0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),p=t.slice(d,c);e.push(p)}}}return e}function Bv(t){let e=[],n=rD(t);for(let r of n){e.push(r);for(let o of Uv(r))e.push(...Bv(o))}return e}function Tm(t){let e;try{e=zv(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Fv(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function Pm(t,e){let n=[];if(t){let o=mo(t,".claude","settings.local.json"),s=Tm(o);s&&n.push(s);let i=mo(t,".claude","settings.json"),a=Tm(i);a&&n.push(a)}let r=e!==void 0?[e]:bm();for(let o of r){let s=Tm(o);s&&n.push(s)}return n}function fo(t,e,n){return Rm(t,"deny",e,n)}function Rm(t,e,n,r){let o=[],s=a=>{let c;try{c=zv(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.[e];if(!Array.isArray(l))return[];let d=[];for(let p of l){if(typeof p!="string")continue;let h=YN(p);h&&h.tool===t&&d.push(h.glob)}return d};if(n){let a=s(mo(n,".claude","settings.local.json"));a!==null&&o.push(a);let c=s(mo(n,".claude","settings.json"));c!==null&&o.push(c)}let i=r!==void 0?[r]:bm();for(let a of i){let c=s(a);c!==null&&o.push(c)}return o}function Cm(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=Bv(t);for(let o of r)for(let s of e){let i=nD(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Pr(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=mo(r,t);s.add(o(i));try{s.add(o($m(i)))}catch{}}for(let i of e)for(let a of i){let c=tD(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function oD(t,e,n=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let r=mo(e),o=mo(e,t),s=(i,a)=>{let c=i,u=a;if(n&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=JN(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+XN)||sD(l))};if(!s(r,o))return!1;try{let i=$m(r),a=$m(o);if(!s(i,a))return!1}catch{}return!0}function sD(t){if(t.startsWith("/"))return!0;if(t.length>=3&&t[1]===":"&&(t[2]==="\\"||t[2]==="/")){let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122}return!1}function Zv(t,e,n=[],r=process.platform==="win32"||process.platform==="darwin"){return oD(t,e,r)?{allowed:!0,reason:"inside"}:n.some(o=>o.length>0)&&Pr(t,n,r,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}function aD(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function qv(t,e){let n=iD[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...aD(t)),r}var iD,Om=v(()=>{"use strict";kr();iD={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});var Kv={};_e(Kv,{healClaudeJsonMcpArgs:()=>vD,healInstalledPlugins:()=>bD,healMcpJsonArgs:()=>SD,healPluginJsonMcpServers:()=>eu,healSettingsEnabledPlugins:()=>xD,sweepStaleMcpJson:()=>tu});import{existsSync as Yn,readFileSync as ks,writeFileSync as Zi,readdirSync as gD,unlinkSync as yD,statSync as _D}from"node:fs";import{resolve as vt,sep as ho}from"node:path";function bD({registryPath:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!Yn(t))return{healed:[],skipped:"no-registry"};let r;try{r=ks(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(r)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}if(!o||typeof o!="object")return{healed:[],error:"bad-shape"};let s=o.plugins&&o.plugins[n]||[];if(!Array.isArray(s)||s.length===0)return{healed:[],skipped:"no-entry"};let i=[],a=null;for(let c of s){if(!c||typeof c!="object")continue;let u=c.installPath;if(!u||typeof u!="string")continue;let l=vt(u),d=vt(e)+ho;if(!l.startsWith(d))continue;let p=vt(u,".claude-plugin","plugin.json");if(!Yn(p))continue;let h=null;try{let m=JSON.parse(ks(p,"utf-8"));m&&typeof m.version=="string"&&m.version&&(h=m.version)}catch{continue}h&&(a=h,c.version!==h&&(c.version=h,i.includes("entry-version")||i.push("entry-version")))}if(a){(!o.enabledPlugins||typeof o.enabledPlugins!="object"||Array.isArray(o.enabledPlugins))&&(o.enabledPlugins={});let c=o.enabledPlugins[n];(c==null||c===!1||c==="")&&(o.enabledPlugins[n]=!0,i.push("enabled-plugins"))}if(i.length>0)try{Zi(t,JSON.stringify(o,null,2)+`
456
- `,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function xD({settingsPath:t,pluginKey:e}){if(!t||!Yn(t))return{healed:[],skipped:"no-settings"};let n;try{n=ks(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let r;try{r=JSON.parse(n)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!r.enabledPlugins||typeof r.enabledPlugins!="object"||Array.isArray(r.enabledPlugins))&&(r.enabledPlugins={});let s=r.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(r.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{Zi(t,JSON.stringify(r,null,2)+`
457
- `,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function eu({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=vt(t),o=vt(e)+ho;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=vt(t,".claude-plugin","plugin.json");if(!Yn(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=ks(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,h=p.map(f=>typeof f!="string"||f===Bi?f:/[/\\]start\.mjs$/.test(f)?Bi:f);if(h.some((f,g)=>f!==p[g])){l.args=h,d.push("plugin-json-args");try{Zi(s,JSON.stringify(a,null,2)+`
458
- `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function SD({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=vt(t),o=vt(e)+ho;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=vt(t,".mcp.json");if(!Yn(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=ks(s,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=n.split("@")[0],l=c[u];if(!l||typeof l!="object"||!Array.isArray(l.args))return{healed:[],skipped:"no-our-server"};let d=[],p=l.args,h=p.map(f=>typeof f!="string"||f===Bi?f:f==="./start.mjs"||f==="start.mjs"||/[/\\]start\.mjs$/.test(f)?Bi:f);if(h.some((f,g)=>f!==p[g])){l.args=h,d.push("mcp-json-args");try{Zi(s,JSON.stringify(a,null,2)+`
459
- `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:d}}function vD({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:n}){if(!t||!Yn(t))return{healed:[],skipped:"no-claude-json"};let r;try{r=ks(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(r)}catch(l){return{healed:[],error:`parse-failed: ${l&&l.message||l}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=vt(n),c=a+ho,u=!1;for(let l of Object.values(s))if(!(!l||typeof l!="object"||!Array.isArray(l.args)))for(let d=0;d<l.args.length;d++){let p=l.args[d];if(typeof p!="string")continue;let h=p.replace(/\\/g,"/");if(!h.startsWith(i+"/"))continue;let m=h.slice(i.length+1),f=m.indexOf("/");if(f<0)continue;let g=m.slice(f+1),y=vt(n,g);y!==a&&!(y+ho).startsWith(c)||y!==p&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{Zi(t,JSON.stringify(o,null,2),"utf-8")}catch(l){return{healed:[],error:`write-failed: ${l&&l.message||l}`}}return{healed:["claude-json-mcp-args"]}}function tu({pluginCacheRoot:t,pluginKey:e}){let n=[];if(!t||!e)return{removed:n,skipped:"missing-args"};let r=vt(t);if(!Yn(r))return{removed:n,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:n,skipped:"bad-plugin-key"};let i=vt(r,o,s),a=r+ho;if(!i.startsWith(a))return{removed:n,skipped:"outside-cache-root"};if(!Yn(i))return{removed:n,skipped:"no-plugin-dir"};let c=[];try{c=gD(i)}catch{return{removed:n,skipped:"readdir-failed"}}for(let u of c){let l=vt(i,u);if(!l.startsWith(i+ho))continue;try{if(!_D(l).isDirectory())continue}catch{continue}let d=vt(l,".mcp.json");if(Yn(d))try{yD(d),n.push(d)}catch{}}return{removed:n}}var Bi,Im=v(()=>{"use strict";Bi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,Am,z,An,qi=v(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Am||(Am={}));z=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),An=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}}});var I,ED,Ct,nu=v(()=>{qi();I=ce.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ED=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ct=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Ct.create=t=>new Ct(t)});var TD,Qn,Nm=v(()=>{nu();qi();TD=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===z.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ce.assertNever(t)}return{message:n}},Qn=TD});function $D(t){Jv=t}function ws(){return Jv}var Jv,ru=v(()=>{Nm();Jv=Qn});function M(t,e){let n=ws(),r=Vi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Qn?void 0:Qn].filter(o=>!!o)});t.common.issues.push(r)}var Vi,PD,at,G,go,gt,ou,su,Rr,Es,Dm=v(()=>{ru();Nm();Vi=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},PD=[];at=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return G;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return G;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},G=Object.freeze({status:"aborted"}),go=t=>({status:"dirty",value:t}),gt=t=>({status:"valid",value:t}),ou=t=>t.status==="aborted",su=t=>t.status==="dirty",Rr=t=>t.status==="valid",Es=t=>typeof Promise<"u"&&t instanceof Promise});var Xv=v(()=>{});var B,Yv=v(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function nk(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function qD(t){return new RegExp(`^${nk(t)}$`)}function rk(t){let e=`${tk}T${nk(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function VD(t,e){return!!((e==="v4"||!e)&&LD.test(t)||(e==="v6"||!e)&&FD.test(t))}function WD(t,e){if(!ND.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function KD(t,e){return!!((e==="v4"||!e)&&zD.test(t)||(e==="v6"||!e)&&HD.test(t))}function GD(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Ts(t){if(t instanceof It){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Ot.create(Ts(r))}return new It({...t._def,shape:()=>e})}else return t instanceof nr?new nr({...t._def,type:Ts(t.element)}):t instanceof Ot?Ot.create(Ts(t.unwrap())):t instanceof Dn?Dn.create(Ts(t.unwrap())):t instanceof Nn?Nn.create(t.items.map(e=>Ts(e))):t}function jm(t,e){let n=An(t),r=An(e);if(t===e)return{valid:!0,data:t};if(n===z.object&&r===z.object){let o=ce.objectKeys(e),s=ce.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=jm(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===z.array&&r===z.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=jm(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===z.date&&r===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function ok(t,e){return new $o({values:t,typeName:D.ZodEnum,...te(e)})}function ek(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function sk(t,e={},n){return t?Or.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=ek(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=ek(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Or.create()}var tn,Qv,re,RD,CD,OD,ID,AD,ND,DD,MD,jD,Mm,LD,zD,FD,HD,UD,BD,tk,ZD,Cr,yo,_o,bo,xo,$s,So,vo,Or,tr,fn,Ps,nr,It,ko,er,iu,wo,Nn,au,Rs,Cs,cu,Eo,To,$o,Po,Ir,nn,Ot,Dn,Ro,Co,Os,JD,Wi,Ki,Oo,XD,D,YD,ik,ak,QD,eM,ck,tM,nM,rM,oM,sM,iM,aM,cM,uM,Lm,lM,dM,pM,mM,fM,hM,gM,yM,_M,bM,xM,SM,vM,kM,wM,EM,TM,$M,PM,RM,CM,OM,IM,AM,uk=v(()=>{nu();ru();Yv();Dm();qi();tn=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Qv=(t,e)=>{if(Rr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Ct(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return An(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:An(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new at,ctx:{common:e.parent.common,data:e.data,parsedType:An(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Es(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Qv(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Rr(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Rr(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:An(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(Es(o)?o:Promise.resolve(o));return Qv(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:I.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new nn({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ot.create(this,this._def)}nullable(){return Dn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nr.create(this)}promise(){return Ir.create(this,this._def)}or(e){return ko.create([this,e],this._def)}and(e){return wo.create(this,e,this._def)}transform(e){return new nn({...te(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Ro({...te(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new Wi({typeName:D.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Co({...te(this._def),innerType:this,catchValue:n,typeName:D.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ki.create(this,e)}readonly(){return Oo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},RD=/^c[^\s-]{8,}$/i,CD=/^[0-9a-z]+$/,OD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ID=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,AD=/^[a-z0-9_-]{21}$/i,ND=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,DD=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,MD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",LD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zD=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,FD=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,HD=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,UD=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tk="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ZD=new RegExp(`^${tk}$`);Cr=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:z.string,received:s.parsedType}),G}let r=new at,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")MD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"email",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Mm||(Mm=new RegExp(jD,"u")),Mm.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"emoji",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")ID.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"uuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")AD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"nanoid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")RD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")CD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid2",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")OD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ulid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),M(o,{validation:"url",code:I.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"regex",code:I.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?rk(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?ZD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?qD(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?DD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"duration",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?VD(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ip",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?WD(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"jwt",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?KD(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cidr",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?UD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?BD.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64url",code:I.invalid_string,message:s.message}),r.dirty()):ce.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:I.invalid_string,...B.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...B.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...B.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...B.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...B.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...B.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...B.errToObj(n)})}nonempty(e){return this.min(1,B.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Cr.create=t=>new Cr({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...te(t)});yo=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:z.number,received:s.parsedType}),G}let r,o=new at;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?GD(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};yo.create=t=>new yo({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...te(t)});_o=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let r,o=new at;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:z.bigint,received:n.parsedType}),G}gte(e,n){return this.setLimit("min",e,!0,B.toString(n))}gt(e,n){return this.setLimit("min",e,!1,B.toString(n))}lte(e,n){return this.setLimit("max",e,!0,B.toString(n))}lt(e,n){return this.setLimit("max",e,!1,B.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};_o.create=t=>new _o({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...te(t)});bo=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.boolean,received:r.parsedType}),G}return gt(e.data)}};bo.create=t=>new bo({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...te(t)});xo=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:z.date,received:s.parsedType}),G}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_date}),G}let r=new at,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ce.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:B.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:B.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};xo.create=t=>new xo({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...te(t)});$s=class extends re{_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.symbol,received:r.parsedType}),G}return gt(e.data)}};$s.create=t=>new $s({typeName:D.ZodSymbol,...te(t)});So=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.undefined,received:r.parsedType}),G}return gt(e.data)}};So.create=t=>new So({typeName:D.ZodUndefined,...te(t)});vo=class extends re{_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.null,received:r.parsedType}),G}return gt(e.data)}};vo.create=t=>new vo({typeName:D.ZodNull,...te(t)});Or=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return gt(e.data)}};Or.create=t=>new Or({typeName:D.ZodAny,...te(t)});tr=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gt(e.data)}};tr.create=t=>new tr({typeName:D.ZodUnknown,...te(t)});fn=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:z.never,received:n.parsedType}),G}};fn.create=t=>new fn({typeName:D.ZodNever,...te(t)});Ps=class extends re{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.void,received:r.parsedType}),G}return gt(e.data)}};Ps.create=t=>new Ps({typeName:D.ZodVoid,...te(t)});nr=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==z.array)return M(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),G;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(M(n,{code:i?I.too_big:I.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(M(n,{code:I.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(M(n,{code:I.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new tn(n,i,n.path,a)))).then(i=>at.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new tn(n,i,n.path,a)));return at.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:B.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};nr.create=(t,e)=>new nr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...te(e)});It=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=ce.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return M(u,{code:I.invalid_type,expected:z.object,received:u.parsedType}),G}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof fn&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new tn(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof fn){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(M(o,{code:I.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new tn(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>at.mergeObjectSync(r,u)):at.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return B.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:B.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ce.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ce.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Ts(this)}partial(e){let n={};for(let r of ce.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ce.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ot;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return ok(ce.objectKeys(this.shape))}};It.create=(t,e)=>new It({shape:()=>t,unknownKeys:"strip",catchall:fn.create(),typeName:D.ZodObject,...te(e)});It.strictCreate=(t,e)=>new It({shape:()=>t,unknownKeys:"strict",catchall:fn.create(),typeName:D.ZodObject,...te(e)});It.lazycreate=(t,e)=>new It({shape:t,unknownKeys:"strip",catchall:fn.create(),typeName:D.ZodObject,...te(e)});ko=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ct(a.ctx.common.issues));return M(n,{code:I.invalid_union,unionErrors:i}),G}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ct(c));return M(n,{code:I.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};ko.create=(t,e)=>new ko({options:t,typeName:D.ZodUnion,...te(e)});er=t=>t instanceof Eo?er(t.schema):t instanceof nn?er(t.innerType()):t instanceof To?[t.value]:t instanceof $o?t.options:t instanceof Po?ce.objectValues(t.enum):t instanceof Ro?er(t._def.innerType):t instanceof So?[void 0]:t instanceof vo?[null]:t instanceof Ot?[void 0,...er(t.unwrap())]:t instanceof Dn?[null,...er(t.unwrap())]:t instanceof Wi||t instanceof Oo?er(t.unwrap()):t instanceof Co?er(t._def.innerType):[],iu=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return M(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),G;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(M(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=er(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...te(r)})}};wo=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(ou(s)||ou(i))return G;let a=jm(s.value,i.value);return a.valid?((su(s)||su(i))&&n.dirty(),{status:n.value,value:a.data}):(M(r,{code:I.invalid_intersection_types}),G)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};wo.create=(t,e,n)=>new wo({left:t,right:e,typeName:D.ZodIntersection,...te(n)});Nn=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return M(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),G;if(r.data.length<this._def.items.length)return M(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new tn(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>at.mergeArray(n,i)):at.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Nn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:t,typeName:D.ZodTuple,rest:null,...te(e)})};au=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return M(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),G;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new tn(r,a,r.path,a)),value:i._parse(new tn(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?at.mergeObjectAsync(n,o):at.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:D.ZodRecord,...te(r)}):new t({keyType:Cr.create(),valueType:e,typeName:D.ZodRecord,...te(n)})}},Rs=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return M(r,{code:I.invalid_type,expected:z.map,received:r.parsedType}),G;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new tn(r,a,r.path,[u,"key"])),value:s._parse(new tn(r,c,r.path,[u,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Rs.create=(t,e,n)=>new Rs({valueType:e,keyType:t,typeName:D.ZodMap,...te(n)});Cs=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return M(r,{code:I.invalid_type,expected:z.set,received:r.parsedType}),G;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(M(r,{code:I.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(M(r,{code:I.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return G;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new tn(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:B.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:B.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Cs.create=(t,e)=>new Cs({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...te(e)});cu=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.function)return M(n,{code:I.invalid_type,expected:z.function,received:n.parsedType}),G;function r(a,c){return Vi({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ws(),Qn].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function o(a,c){return Vi({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ws(),Qn].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Ir){let a=this;return gt(async function(...c){let u=new Ct([]),l=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(r(c,h)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw u.addIssue(o(d,h)),u})})}else{let a=this;return gt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ct([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ct([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Nn.create(e).rest(tr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Nn.create([]).rest(tr.create()),returns:n||tr.create(),typeName:D.ZodFunction,...te(r)})}},Eo=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Eo.create=(t,e)=>new Eo({getter:t,typeName:D.ZodLazy,...te(e)});To=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};To.create=(t,e)=>new To({value:t,typeName:D.ZodLiteral,...te(e)});$o=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:ce.joinValues(r),received:n.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{received:n.data,code:I.invalid_enum_value,options:r}),G}return gt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};$o.create=ok;Po=class extends re{_parse(e){let n=ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let o=ce.objectValues(n);return M(r,{expected:ce.joinValues(o),received:r.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(n);return M(r,{received:r.data,code:I.invalid_enum_value,options:o}),G}return gt(e.data)}get enum(){return this._def.values}};Po.create=(t,e)=>new Po({values:t,typeName:D.ZodNativeEnum,...te(e)});Ir=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.promise&&n.common.async===!1)return M(n,{code:I.invalid_type,expected:z.promise,received:n.parsedType}),G;let r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return gt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Ir.create=(t,e)=>new Ir({type:t,typeName:D.ZodPromise,...te(e)});nn=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{M(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?G:c.status==="dirty"?go(c.value):n.value==="dirty"?go(c.value):c});{if(n.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?G:a.status==="dirty"?go(a.value):n.value==="dirty"?go(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Rr(i))return G;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Rr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):G);ce.assertNever(o)}};nn.create=(t,e,n)=>new nn({schema:t,typeName:D.ZodEffects,effect:e,...te(n)});nn.createWithPreprocess=(t,e,n)=>new nn({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...te(n)});Ot=class extends re{_parse(e){return this._getType(e)===z.undefined?gt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ot.create=(t,e)=>new Ot({innerType:t,typeName:D.ZodOptional,...te(e)});Dn=class extends re{_parse(e){return this._getType(e)===z.null?gt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Dn.create=(t,e)=>new Dn({innerType:t,typeName:D.ZodNullable,...te(e)});Ro=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Ro.create=(t,e)=>new Ro({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Co=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Es(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ct(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ct(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Co.create=(t,e)=>new Co({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Os=class extends re{_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:z.nan,received:r.parsedType}),G}return{status:"valid",value:e.data}}};Os.create=t=>new Os({typeName:D.ZodNaN,...te(t)});JD=Symbol("zod_brand"),Wi=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Ki=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?G:s.status==="dirty"?(n.dirty(),go(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?G:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:D.ZodPipeline})}},Oo=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Rr(o)&&(o.value=Object.freeze(o.value)),o);return Es(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Oo.create=(t,e)=>new Oo({innerType:t,typeName:D.ZodReadonly,...te(e)});XD={object:It.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));YD=(t,e={message:`Input not instance of ${t.name}`})=>sk(n=>n instanceof t,e),ik=Cr.create,ak=yo.create,QD=Os.create,eM=_o.create,ck=bo.create,tM=xo.create,nM=$s.create,rM=So.create,oM=vo.create,sM=Or.create,iM=tr.create,aM=fn.create,cM=Ps.create,uM=nr.create,Lm=It.create,lM=It.strictCreate,dM=ko.create,pM=iu.create,mM=wo.create,fM=Nn.create,hM=au.create,gM=Rs.create,yM=Cs.create,_M=cu.create,bM=Eo.create,xM=To.create,SM=$o.create,vM=Po.create,kM=Ir.create,wM=nn.create,EM=Ot.create,TM=Dn.create,$M=nn.createWithPreprocess,PM=Ki.create,RM=()=>ik().optional(),CM=()=>ak().optional(),OM=()=>ck().optional(),IM={string:(t=>Cr.create({...t,coerce:!0})),number:(t=>yo.create({...t,coerce:!0})),boolean:(t=>bo.create({...t,coerce:!0})),bigint:(t=>_o.create({...t,coerce:!0})),date:(t=>xo.create({...t,coerce:!0}))},AM=G});var j={};_e(j,{BRAND:()=>JD,DIRTY:()=>go,EMPTY_PATH:()=>PD,INVALID:()=>G,NEVER:()=>AM,OK:()=>gt,ParseStatus:()=>at,Schema:()=>re,ZodAny:()=>Or,ZodArray:()=>nr,ZodBigInt:()=>_o,ZodBoolean:()=>bo,ZodBranded:()=>Wi,ZodCatch:()=>Co,ZodDate:()=>xo,ZodDefault:()=>Ro,ZodDiscriminatedUnion:()=>iu,ZodEffects:()=>nn,ZodEnum:()=>$o,ZodError:()=>Ct,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>cu,ZodIntersection:()=>wo,ZodIssueCode:()=>I,ZodLazy:()=>Eo,ZodLiteral:()=>To,ZodMap:()=>Rs,ZodNaN:()=>Os,ZodNativeEnum:()=>Po,ZodNever:()=>fn,ZodNull:()=>vo,ZodNullable:()=>Dn,ZodNumber:()=>yo,ZodObject:()=>It,ZodOptional:()=>Ot,ZodParsedType:()=>z,ZodPipeline:()=>Ki,ZodPromise:()=>Ir,ZodReadonly:()=>Oo,ZodRecord:()=>au,ZodSchema:()=>re,ZodSet:()=>Cs,ZodString:()=>Cr,ZodSymbol:()=>$s,ZodTransformer:()=>nn,ZodTuple:()=>Nn,ZodType:()=>re,ZodUndefined:()=>So,ZodUnion:()=>ko,ZodUnknown:()=>tr,ZodVoid:()=>Ps,addIssueToContext:()=>M,any:()=>sM,array:()=>uM,bigint:()=>eM,boolean:()=>ck,coerce:()=>IM,custom:()=>sk,date:()=>tM,datetimeRegex:()=>rk,defaultErrorMap:()=>Qn,discriminatedUnion:()=>pM,effect:()=>wM,enum:()=>SM,function:()=>_M,getErrorMap:()=>ws,getParsedType:()=>An,instanceof:()=>YD,intersection:()=>mM,isAborted:()=>ou,isAsync:()=>Es,isDirty:()=>su,isValid:()=>Rr,late:()=>XD,lazy:()=>bM,literal:()=>xM,makeIssue:()=>Vi,map:()=>gM,nan:()=>QD,nativeEnum:()=>vM,never:()=>aM,null:()=>oM,nullable:()=>TM,number:()=>ak,object:()=>Lm,objectUtil:()=>Am,oboolean:()=>OM,onumber:()=>CM,optional:()=>EM,ostring:()=>RM,pipeline:()=>PM,preprocess:()=>$M,promise:()=>kM,quotelessJson:()=>ED,record:()=>hM,set:()=>yM,setErrorMap:()=>$D,strictObject:()=>lM,string:()=>ik,symbol:()=>nM,transformer:()=>wM,tuple:()=>fM,undefined:()=>rM,union:()=>dM,unknown:()=>iM,util:()=>ce,void:()=>cM});var uu=v(()=>{ru();Dm();Xv();qi();uk();nu()});var Gi=v(()=>{uu()});function $(t,e,n){function r(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Ut(t){return t&&Object.assign(lu,t),lu}var DM,rr,lu,Is=v(()=>{DM=Object.freeze({status:"aborted"});rr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},lu={}});var ue={};_e(ue,{BIGINT_FORMAT_RANGES:()=>dk,Class:()=>Fm,NUMBER_FORMAT_RANGES:()=>Wm,aborted:()=>Ao,allowsEval:()=>Zm,assert:()=>FM,assertEqual:()=>MM,assertIs:()=>LM,assertNever:()=>zM,assertNotEqual:()=>jM,assignProp:()=>Bm,cached:()=>Yi,captureStackTrace:()=>pu,cleanEnum:()=>QM,cleanRegex:()=>ea,clone:()=>Bt,createTransparentProxy:()=>VM,defineLazy:()=>Te,esc:()=>Io,escapeRegex:()=>Ar,extend:()=>GM,finalizeIssue:()=>hn,floatSafeRemainder:()=>Um,getElementAtPath:()=>HM,getEnumValues:()=>Xi,getLengthableOrigin:()=>ta,getParsedType:()=>qM,getSizableOrigin:()=>pk,isObject:()=>As,isPlainObject:()=>Ns,issue:()=>Km,joinValues:()=>du,jsonStringifyReplacer:()=>Hm,merge:()=>JM,normalizeParams:()=>J,nullish:()=>Qi,numKeys:()=>ZM,omit:()=>KM,optionalKeys:()=>Vm,partial:()=>XM,pick:()=>WM,prefixIssues:()=>Mn,primitiveTypes:()=>lk,promiseAllObject:()=>UM,propertyKeyTypes:()=>qm,randomString:()=>BM,required:()=>YM,stringifyPrimitive:()=>mu,unwrapMessage:()=>Ji});function MM(t){return t}function jM(t){return t}function LM(t){}function zM(t){throw new Error}function FM(t){}function Xi(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function du(t,e="|"){return t.map(n=>mu(n)).join(e)}function Hm(t,e){return typeof e=="bigint"?e.toString():e}function Yi(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Qi(t){return t==null}function ea(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Um(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Te(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Bm(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function HM(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function UM(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function BM(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Io(t){return JSON.stringify(t)}function As(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ns(t){if(As(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(As(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ZM(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function Ar(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function J(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function VM(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function mu(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Vm(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function WM(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return Bt(t,{...t._zod.def,shape:n,checks:[]})}function KM(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return Bt(t,{...t._zod.def,shape:n,checks:[]})}function GM(t,e){if(!Ns(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return Bm(this,"shape",r),r},checks:[]};return Bt(t,n)}function JM(t,e){return Bt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Bm(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function XM(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return Bt(e,{...e._zod.def,shape:o,checks:[]})}function YM(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return Bt(e,{...e._zod.def,shape:o,checks:[]})}function Ao(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Mn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Ji(t){return typeof t=="string"?t:t?.message}function hn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=Ji(t.inst?._zod.def?.error?.(t))??Ji(e?.error?.(t))??Ji(n.customError?.(t))??Ji(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function pk(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ta(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Km(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function QM(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var pu,Zm,qM,qm,lk,Wm,dk,Fm,jn=v(()=>{pu=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Zm=Yi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});qM=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},qm=new Set(["string","number","symbol"]),lk=new Set(["string","number","bigint","boolean","symbol","undefined"]);Wm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},dk={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Fm=class{constructor(...e){}}});function Gm(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function Jm(t,e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),r}var mk,fu,na,Xm=v(()=>{Is();jn();mk=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Hm,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},fu=$("$ZodError",mk),na=$("$ZodError",mk,{Parent:Error})});var Ym,Qm,ef,tf,nf,No,rf,Do,of=v(()=>{Is();Xm();jn();Ym=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new rr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>hn(c,s,Ut())));throw pu(a,o?.callee),a}return i.value},Qm=Ym(na),ef=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>hn(c,s,Ut())));throw pu(a,o?.callee),a}return i.value},tf=ef(na),nf=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new rr;return s.issues.length?{success:!1,error:new(t??fu)(s.issues.map(i=>hn(i,o,Ut())))}:{success:!0,data:s.value}},No=nf(na),rf=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>hn(i,o,Ut())))}:{success:!0,data:s.value}},Do=rf(na)});function kk(){return new RegExp(t1,"u")}function Ak(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Nk(t){return new RegExp(`^${Ak(t)}$`)}function Dk(t){let e=Ak({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Ok}T(?:${r})$`)}var fk,hk,gk,yk,_k,bk,xk,Sk,sf,vk,t1,wk,Ek,Tk,$k,Pk,af,Rk,Ck,Ok,Ik,Mk,jk,Lk,zk,Fk,Hk,Uk,gu=v(()=>{fk=/^[cC][^\s-]{8,}$/,hk=/^[0-9a-z]+$/,gk=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,yk=/^[0-9a-vA-V]{20}$/,_k=/^[A-Za-z0-9]{27}$/,bk=/^[a-zA-Z0-9_-]{21}$/,xk=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Sk=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,sf=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,vk=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,t1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";wk=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ek=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Tk=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,$k=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Pk=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,af=/^[A-Za-z0-9_-]*$/,Rk=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Ck=/^\+(?:[0-9]){6,14}[0-9]$/,Ok="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ik=new RegExp(`^${Ok}$`);Mk=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},jk=/^\d+$/,Lk=/^-?\d+(?:\.\d+)?/i,zk=/true|false/i,Fk=/null/i,Hk=/^[^A-Z]*$/,Uk=/^[^a-z]*$/});var ct,Bk,cf,uf,Zk,qk,Vk,Wk,Kk,ra,Gk,Jk,Xk,Yk,Qk,e0,t0,yu=v(()=>{Is();gu();jn();ct=$("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Bk={number:"number",bigint:"bigint",object:"date"},cf=$("$ZodCheckLessThan",(t,e)=>{ct.init(t,e);let n=Bk[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),uf=$("$ZodCheckGreaterThan",(t,e)=>{ct.init(t,e);let n=Bk[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Zk=$("$ZodCheckMultipleOf",(t,e)=>{ct.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Um(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),qk=$("$ZodCheckNumberFormat",(t,e)=>{ct.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Wm[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=jk)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Vk=$("$ZodCheckMaxLength",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Qi(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=ta(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wk=$("$ZodCheckMinLength",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Qi(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=ta(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Kk=$("$ZodCheckLengthEquals",(t,e)=>{var n;ct.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Qi(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=ta(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),ra=$("$ZodCheckStringFormat",(t,e)=>{var n,r;ct.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Gk=$("$ZodCheckRegex",(t,e)=>{ra.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Jk=$("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Hk),ra.init(t,e)}),Xk=$("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Uk),ra.init(t,e)}),Yk=$("$ZodCheckIncludes",(t,e)=>{ct.init(t,e);let n=Ar(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Qk=$("$ZodCheckStartsWith",(t,e)=>{ct.init(t,e);let n=new RegExp(`^${Ar(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),e0=$("$ZodCheckEndsWith",(t,e)=>{ct.init(t,e);let n=new RegExp(`.*${Ar(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),t0=$("$ZodCheckOverwrite",(t,e)=>{ct.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var _u,lf=v(()=>{_u=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
460
- `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`
461
- `))}}});var r0,df=v(()=>{r0={major:4,minor:0,patch:0}});function y0(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function n1(t){if(!af.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return y0(n)}function r1(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function o0(t,e,n){t.issues.length&&e.issues.push(...Mn(n,t.issues)),e.value[n]=t.value}function bu(t,e,n){t.issues.length&&e.issues.push(...Mn(n,t.issues)),e.value[n]=t.value}function s0(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Mn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function i0(t,e,n,r){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(s=>hn(s,r,Ut())))}),e}function pf(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ns(t)&&Ns(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=pf(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=pf(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function a0(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Ao(t))return t;let r=pf(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}function c0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function u0(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function l0(t,e,n){return Ao(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}function d0(t){return t.value=Object.freeze(t.value),t}function p0(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(Km(o))}}var ke,oa,$e,mf,ff,hf,gf,yf,_f,bf,xf,Sf,vf,kf,m0,f0,h0,g0,wf,Ef,Tf,$f,Pf,Rf,Cf,Of,xu,If,Af,Nf,Df,Mf,jf,Su,vu,Lf,zf,Ff,Hf,Uf,Bf,Zf,qf,Vf,Wf,Kf,Gf,Jf,Xf,Yf,_0=v(()=>{yu();Is();lf();of();gu();jn();df();jn();ke=$("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=r0;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Ao(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new rr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=Ao(s,d)))});else{if(s.issues.length===d)continue;c||(c=Ao(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new rr;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=No(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Do(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),oa=$("$ZodString",(t,e)=>{ke.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Mk(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),$e=$("$ZodStringFormat",(t,e)=>{ra.init(t,e),oa.init(t,e)}),mf=$("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Sk),$e.init(t,e)}),ff=$("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=sf(r))}else e.pattern??(e.pattern=sf());$e.init(t,e)}),hf=$("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=vk),$e.init(t,e)}),gf=$("$ZodURL",(t,e)=>{$e.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Rk.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),yf=$("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=kk()),$e.init(t,e)}),_f=$("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=bk),$e.init(t,e)}),bf=$("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=fk),$e.init(t,e)}),xf=$("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=hk),$e.init(t,e)}),Sf=$("$ZodULID",(t,e)=>{e.pattern??(e.pattern=gk),$e.init(t,e)}),vf=$("$ZodXID",(t,e)=>{e.pattern??(e.pattern=yk),$e.init(t,e)}),kf=$("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=_k),$e.init(t,e)}),m0=$("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Dk(e)),$e.init(t,e)}),f0=$("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ik),$e.init(t,e)}),h0=$("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Nk(e)),$e.init(t,e)}),g0=$("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=xk),$e.init(t,e)}),wf=$("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=wk),$e.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),Ef=$("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ek),$e.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Tf=$("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Tk),$e.init(t,e)}),$f=$("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=$k),$e.init(t,e),t._zod.check=n=>{let[r,o]=n.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});Pf=$("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Pk),$e.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{y0(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});Rf=$("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=af),$e.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{n1(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Cf=$("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ck),$e.init(t,e)});Of=$("$ZodJWT",(t,e)=>{$e.init(t,e),t._zod.check=n=>{r1(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),xu=$("$ZodNumber",(t,e)=>{ke.init(t,e),t._zod.pattern=t._zod.bag.pattern??Lk,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),If=$("$ZodNumber",(t,e)=>{qk.init(t,e),xu.init(t,e)}),Af=$("$ZodBoolean",(t,e)=>{ke.init(t,e),t._zod.pattern=zk,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),Nf=$("$ZodNull",(t,e)=>{ke.init(t,e),t._zod.pattern=Fk,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),Df=$("$ZodUnknown",(t,e)=>{ke.init(t,e),t._zod.parse=n=>n}),Mf=$("$ZodNever",(t,e)=>{ke.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});jf=$("$ZodArray",(t,e)=>{ke.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?s.push(c.then(u=>o0(u,n,i))):o0(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});Su=$("$ZodObject",(t,e)=>{ke.init(t,e);let n=Yi(()=>{let d=Object.keys(e.shape);for(let h of d)if(!(e.shape[h]instanceof ke))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let p=Vm(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});Te(t._zod,"propValues",()=>{let d=e.shape,p={};for(let h in d){let m=d[h]._zod;if(m.values){p[h]??(p[h]=new Set);for(let f of m.values)p[h].add(f)}}return p});let r=d=>{let p=new _u(["shape","payload","ctx"]),h=n.value,m=_=>{let b=Io(_);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");let f=Object.create(null),g=0;for(let _ of h.keys)f[_]=`key_${g++}`;p.write("const newResult = {}");for(let _ of h.keys)if(h.optionalKeys.has(_)){let b=f[_];p.write(`const ${b} = ${m(_)};`);let S=Io(_);p.write(`
462
- if (${b}.issues.length) {
463
- if (input[${S}] === undefined) {
464
- if (${S} in input) {
465
- newResult[${S}] = undefined;
466
- }
467
- } else {
468
- payload.issues = payload.issues.concat(
469
- ${b}.issues.map((iss) => ({
470
- ...iss,
471
- path: iss.path ? [${S}, ...iss.path] : [${S}],
472
- }))
473
- );
474
- }
475
- } else if (${b}.value === undefined) {
476
- if (${S} in input) newResult[${S}] = undefined;
477
- } else {
478
- newResult[${S}] = ${b}.value;
479
- }
480
- `)}else{let b=f[_];p.write(`const ${b} = ${m(_)};`),p.write(`
481
- if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
482
- ...iss,
483
- path: iss.path ? [${Io(_)}, ...iss.path] : [${Io(_)}]
484
- })));`),p.write(`newResult[${Io(_)}] = ${b}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,b)=>y(d,_,b)},o,s=As,i=!lu.jitless,c=i&&Zm.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=n.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=r(e.shape)),d=o(d,p);else{d.value={};let b=l.shape;for(let S of l.keys){let E=b[S],A=E._zod.run({value:h[S],issues:[]},p),x=E._zod.optin==="optional"&&E._zod.optout==="optional";A instanceof Promise?m.push(A.then(T=>x?s0(T,d,S,h):bu(T,d,S))):x?s0(A,d,S,h):bu(A,d,S)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let f=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(h)){if(g.has(b))continue;if(_==="never"){f.push(b);continue}let S=y.run({value:h[b],issues:[]},p);S instanceof Promise?m.push(S.then(E=>bu(E,d,b))):bu(S,d,b)}return f.length&&d.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),m.length?Promise.all(m).then(()=>d):d}});vu=$("$ZodUnion",(t,e)=>{ke.init(t,e),Te(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Te(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Te(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Te(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>ea(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>i0(i,n,t,r)):i0(s,n,t,r)}}),Lf=$("$ZodDiscriminatedUnion",(t,e)=>{vu.init(t,e);let n=t._zod.parse;Te(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let r=Yi(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!As(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),zf=$("$ZodIntersection",(t,e)=>{ke.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>a0(n,c,u)):a0(n,s,i)}});Ff=$("$ZodRecord",(t,e)=>{ke.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Ns(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...Mn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Mn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>hn(u,r,Ut())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...Mn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...Mn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Hf=$("$ZodEnum",(t,e)=>{ke.init(t,e);let n=Xi(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>qm.has(typeof r)).map(r=>typeof r=="string"?Ar(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Uf=$("$ZodLiteral",(t,e)=>{ke.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Ar(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),Bf=$("$ZodTransform",(t,e)=>{ke.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new rr;return n.value=o,n}}),Zf=$("$ZodOptional",(t,e)=>{ke.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Te(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ea(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),qf=$("$ZodNullable",(t,e)=>{ke.init(t,e),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ea(n.source)}|null)$`):void 0}),Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Vf=$("$ZodDefault",(t,e)=>{ke.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>c0(s,e)):c0(o,e)}});Wf=$("$ZodPrefault",(t,e)=>{ke.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Kf=$("$ZodNonOptional",(t,e)=>{ke.init(t,e),Te(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>u0(s,t)):u0(o,t)}});Gf=$("$ZodCatch",(t,e)=>{ke.init(t,e),t._zod.optin="optional",Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>hn(i,r,Ut()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>hn(s,r,Ut()))},input:n.value}),n.issues=[]),n)}}),Jf=$("$ZodPipe",(t,e)=>{ke.init(t,e),Te(t._zod,"values",()=>e.in._zod.values),Te(t._zod,"optin",()=>e.in._zod.optin),Te(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>l0(s,e,r)):l0(o,e,r)}});Xf=$("$ZodReadonly",(t,e)=>{ke.init(t,e),Te(t._zod,"propValues",()=>e.innerType._zod.propValues),Te(t._zod,"values",()=>e.innerType._zod.values),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(d0):d0(o)}});Yf=$("$ZodCustom",(t,e)=>{ct.init(t,e),ke.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>p0(s,n,r,t));p0(o,n,r,t)}})});function b0(){return{localeError:s1()}}var o1,s1,x0=v(()=>{jn();o1=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},s1=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${o1(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${mu(r.values[0])}`:`Invalid option: expected one of ${du(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${du(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});var ku=v(()=>{});function S0(){return new sa}var sa,Nr,eh=v(()=>{sa=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Nr=S0()});function th(t,e){return new t({type:"string",...J(e)})}function nh(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function wu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function rh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function oh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function sh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function ih(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function ah(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function ch(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function uh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function lh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function dh(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function ph(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function mh(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function fh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function hh(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function gh(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function yh(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function _h(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function bh(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function xh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function Sh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function vh(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function v0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function k0(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function w0(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function E0(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function kh(t,e){return new t({type:"number",checks:[],...J(e)})}function wh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function Eh(t,e){return new t({type:"boolean",...J(e)})}function Th(t,e){return new t({type:"null",...J(e)})}function $h(t){return new t({type:"unknown"})}function Ph(t,e){return new t({type:"never",...J(e)})}function Eu(t,e){return new cf({check:"less_than",...J(e),value:t,inclusive:!1})}function ia(t,e){return new cf({check:"less_than",...J(e),value:t,inclusive:!0})}function Tu(t,e){return new uf({check:"greater_than",...J(e),value:t,inclusive:!1})}function aa(t,e){return new uf({check:"greater_than",...J(e),value:t,inclusive:!0})}function $u(t,e){return new Zk({check:"multiple_of",...J(e),value:t})}function Pu(t,e){return new Vk({check:"max_length",...J(e),maximum:t})}function Ds(t,e){return new Wk({check:"min_length",...J(e),minimum:t})}function Ru(t,e){return new Kk({check:"length_equals",...J(e),length:t})}function Rh(t,e){return new Gk({check:"string_format",format:"regex",...J(e),pattern:t})}function Ch(t){return new Jk({check:"string_format",format:"lowercase",...J(t)})}function Oh(t){return new Xk({check:"string_format",format:"uppercase",...J(t)})}function Ih(t,e){return new Yk({check:"string_format",format:"includes",...J(e),includes:t})}function Ah(t,e){return new Qk({check:"string_format",format:"starts_with",...J(e),prefix:t})}function Nh(t,e){return new e0({check:"string_format",format:"ends_with",...J(e),suffix:t})}function Mo(t){return new t0({check:"overwrite",tx:t})}function Dh(t){return Mo(e=>e.normalize(t))}function Mh(){return Mo(t=>t.trim())}function jh(){return Mo(t=>t.toLowerCase())}function Lh(){return Mo(t=>t.toUpperCase())}function T0(t,e,n){return new t({type:"array",element:e,...J(n)})}function zh(t,e,n){let r=J(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Fh(t,e,n){return new t({type:"custom",check:"custom",fn:e,...J(n)})}var $0=v(()=>{yu();jn()});var P0=v(()=>{});function Hh(t,e){if(t instanceof sa){let r=new Cu(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new Cu(e);return n.process(t),n.emit(t,e)}function et(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return et(o.element,n);case"object":{for(let s in o.shape)if(et(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(et(s,n))return!0;return!1}case"intersection":return et(o.left,n)||et(o.right,n);case"tuple":{for(let s of o.items)if(et(s,n))return!0;return!!(o.rest&&et(o.rest,n))}case"record":return et(o.keyType,n)||et(o.valueType,n);case"map":return et(o.keyType,n)||et(o.valueType,n);case"set":return et(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return et(o.innerType,n);case"lazy":return et(o.getter(),n);case"default":return et(o.innerType,n);case"prefault":return et(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return et(o.in,n)||et(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Cu,R0=v(()=>{eh();jn();Cu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Nr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let m=h;m.type="string";let{minimum:f,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof f=="number"&&(m.minLength=f),typeof g=="number"&&(m.maxLength=g),y&&(m.format=s[y]??y,m.format===""&&delete m.format),b&&(m.contentEncoding=b),_&&_.size>0){let S=[..._];S.length===1?m.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let m=h,{minimum:f,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof S=="number"&&(m.exclusiveMinimum=S),typeof f=="number"&&(m.minimum=f,typeof S=="number"&&(S>=f?delete m.minimum:delete m.exclusiveMinimum)),typeof b=="number"&&(m.exclusiveMaximum=b),typeof g=="number"&&(m.maximum=g,typeof b=="number"&&(b<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{let m=h;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(m.minItems=f),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=h;m.type="object",m.properties={};let f=o.shape;for(let _ in f)m.properties[_]=this.process(f[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(_=>{let b=o.shape[_]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=h;m.anyOf=o.options.map((f,g)=>this.process(f,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=h,f=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,_=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];m.allOf=_;break}case"tuple":{let m=h;m.type="array";let f=o.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?m.prefixItems=f:m.items=f,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=h;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=h,f=Xi(o.entries);f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),m.enum=f;break}case"literal":{let m=h,f=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];m.type=g===null?"null":typeof g,m.const=g}else f.every(g=>typeof g=="number")&&(m.type="number"),f.every(g=>typeof g=="string")&&(m.type="string"),f.every(g=>typeof g=="boolean")&&(m.type="string"),f.every(g=>g===null)&&(m.type="null"),m.enum=f;break}case"file":{let m=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),_?_.length===1?(f.contentMediaType=_[0],Object.assign(m,f)):m.anyOf=_.map(b=>({...f,contentMediaType:b})):Object.assign(m,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);h.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=h;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=f.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&et(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){let f=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(f)return{ref:g(f)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let h=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:h+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);let m=d.schema;for(let f in m)delete m[f];m.$ref=p};if(r.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
485
-
486
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(r.external){let h=r.external.registry.get(l[0])?.id;if(e!==l[0]&&h){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),h=p.def??p.schema,m={...h};if(p.ref===null)return;let f=p.ref;if(p.ref=null,f){a(f,d);let g=this.seen.get(f).schema;g.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,m))}p.isParent||this.override({zodSchema:l,jsonSchema:h,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var C0=v(()=>{});var kt=v(()=>{Is();of();Xm();_0();yu();df();jn();gu();ku();eh();lf();P0();$0();R0();C0()});var Uh=v(()=>{kt()});function Bh(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new H1(n)}var F1,H1,O0=v(()=>{kt();kt();Uh();F1=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ke.init(t,e),t.def=e,t.parse=(n,r)=>Qm(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>No(t,n,r),t.parseAsync=async(n,r)=>tf(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Do(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Bt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))}),H1=$("ZodMiniObject",(t,e)=>{Su.init(t,e),F1.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var I0=v(()=>{});var A0=v(()=>{});var N0=v(()=>{});var D0=v(()=>{kt();Uh();O0();I0();kt();ku();A0();N0()});var M0=v(()=>{D0()});var Zh=v(()=>{M0()});function rn(t){return!!t._zod}function Lo(t){let e=Object.values(t);if(e.length===0)return Bh({});let n=e.every(rn),r=e.every(o=>!rn(o));if(n)return Bh(t);if(r)return Lm(t);throw new Error("Mixed Zod versions detected in object shape.")}function Dr(t,e){return rn(t)?No(t,e):t.safeParse(e)}async function Ou(t,e){return rn(t)?await Do(t,e):await t.safeParseAsync(e)}function Mr(t){if(!t)return;let e;if(rn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ms(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Lo(t)}}if(rn(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Iu(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function L0(t){return t.description}function z0(t){if(rn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Au(t){if(rn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var ca=v(()=>{Gi();Zh()});var qh=v(()=>{kt()});var ua={};_e(ua,{ZodISODate:()=>H0,ZodISODateTime:()=>F0,ZodISODuration:()=>B0,ZodISOTime:()=>U0,date:()=>Wh,datetime:()=>Vh,duration:()=>Gh,time:()=>Kh});function Vh(t){return v0(F0,t)}function Wh(t){return k0(H0,t)}function Kh(t){return w0(U0,t)}function Gh(t){return E0(B0,t)}var F0,H0,U0,B0,Jh=v(()=>{kt();Xh();F0=$("ZodISODateTime",(t,e)=>{m0.init(t,e),Ne.init(t,e)});H0=$("ZodISODate",(t,e)=>{f0.init(t,e),Ne.init(t,e)});U0=$("ZodISOTime",(t,e)=>{h0.init(t,e),Ne.init(t,e)});B0=$("ZodISODuration",(t,e)=>{g0.init(t,e),Ne.init(t,e)})});var Z0,uK,la,Yh=v(()=>{kt();kt();Z0=(t,e)=>{fu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Jm(t,n)},flatten:{value:n=>Gm(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},uK=$("ZodError",Z0),la=$("ZodError",Z0,{Parent:Error})});var q0,V0,W0,K0,Qh=v(()=>{kt();Yh();q0=Ym(la),V0=ef(la),W0=nf(la),K0=rf(la)});function w(t){return th(X1,t)}function ye(t){return kh(Q0,t)}function J0(t){return wh(hj,t)}function ot(t){return Eh(gj,t)}function ew(t){return Th(yj,t)}function De(){return $h(_j)}function xj(t){return Ph(bj,t)}function le(t,e){return T0(Sj,t,e)}function H(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new tw(n)}function wt(t,e){return new tw({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ue.normalizeParams(e)})}function Ce(t,e){return new nw({type:"union",options:t,...ue.normalizeParams(e)})}function ng(t,e,n){return new vj({type:"union",options:e,discriminator:t,...ue.normalizeParams(n)})}function Du(t,e){return new kj({type:"intersection",left:t,right:e})}function Pe(t,e,n){return new wj({type:"record",keyType:t,valueType:e,...ue.normalizeParams(n)})}function At(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new eg({type:"enum",entries:n,...ue.normalizeParams(e)})}function q(t,e){return new Ej({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function rw(t){return new Tj({type:"transform",transform:t})}function Me(t){return new ow({type:"optional",innerType:t})}function X0(t){return new $j({type:"nullable",innerType:t})}function Rj(t,e){return new Pj({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Oj(t,e){return new Cj({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Ij(t,e){return new sw({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function Nj(t,e){return new Aj({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function tg(t,e){return new Dj({type:"pipe",in:t,out:e})}function jj(t){return new Mj({type:"readonly",innerType:t})}function Lj(t){let e=new ct({check:"custom"});return e._zod.check=t,e}function aw(t,e){return zh(iw,t??(()=>!0),e)}function zj(t,e={}){return Fh(iw,t,e)}function Fj(t){let e=Lj(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ue.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ue.issue(o))}},t(n.value,n)));return e}function rg(t,e){return tg(rw(t),e)}var He,Y0,X1,Ne,Y1,G0,Nu,Q1,ej,tj,nj,rj,oj,sj,ij,aj,cj,uj,lj,dj,pj,mj,fj,Q0,hj,gj,yj,_j,bj,Sj,tw,nw,vj,kj,wj,eg,Ej,Tj,ow,$j,Pj,Cj,sw,Aj,Dj,Mj,iw,Xh=v(()=>{kt();kt();qh();Jh();Qh();He=$("ZodType",(t,e)=>(ke.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Bt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>q0(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>W0(t,n,r),t.parseAsync=async(n,r)=>V0(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>K0(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(zj(n,r)),t.superRefine=n=>t.check(Fj(n)),t.overwrite=n=>t.check(Mo(n)),t.optional=()=>Me(t),t.nullable=()=>X0(t),t.nullish=()=>Me(X0(t)),t.nonoptional=n=>Ij(t,n),t.array=()=>le(t),t.or=n=>Ce([t,n]),t.and=n=>Du(t,n),t.transform=n=>tg(t,rw(n)),t.default=n=>Rj(t,n),t.prefault=n=>Oj(t,n),t.catch=n=>Nj(t,n),t.pipe=n=>tg(t,n),t.readonly=()=>jj(t),t.describe=n=>{let r=t.clone();return Nr.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Nr.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Nr.get(t);let r=t.clone();return Nr.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Y0=$("_ZodString",(t,e)=>{oa.init(t,e),He.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Rh(...r)),t.includes=(...r)=>t.check(Ih(...r)),t.startsWith=(...r)=>t.check(Ah(...r)),t.endsWith=(...r)=>t.check(Nh(...r)),t.min=(...r)=>t.check(Ds(...r)),t.max=(...r)=>t.check(Pu(...r)),t.length=(...r)=>t.check(Ru(...r)),t.nonempty=(...r)=>t.check(Ds(1,...r)),t.lowercase=r=>t.check(Ch(r)),t.uppercase=r=>t.check(Oh(r)),t.trim=()=>t.check(Mh()),t.normalize=(...r)=>t.check(Dh(...r)),t.toLowerCase=()=>t.check(jh()),t.toUpperCase=()=>t.check(Lh())}),X1=$("ZodString",(t,e)=>{oa.init(t,e),Y0.init(t,e),t.email=n=>t.check(nh(Y1,n)),t.url=n=>t.check(ah(Q1,n)),t.jwt=n=>t.check(vh(fj,n)),t.emoji=n=>t.check(ch(ej,n)),t.guid=n=>t.check(wu(G0,n)),t.uuid=n=>t.check(rh(Nu,n)),t.uuidv4=n=>t.check(oh(Nu,n)),t.uuidv6=n=>t.check(sh(Nu,n)),t.uuidv7=n=>t.check(ih(Nu,n)),t.nanoid=n=>t.check(uh(tj,n)),t.guid=n=>t.check(wu(G0,n)),t.cuid=n=>t.check(lh(nj,n)),t.cuid2=n=>t.check(dh(rj,n)),t.ulid=n=>t.check(ph(oj,n)),t.base64=n=>t.check(bh(dj,n)),t.base64url=n=>t.check(xh(pj,n)),t.xid=n=>t.check(mh(sj,n)),t.ksuid=n=>t.check(fh(ij,n)),t.ipv4=n=>t.check(hh(aj,n)),t.ipv6=n=>t.check(gh(cj,n)),t.cidrv4=n=>t.check(yh(uj,n)),t.cidrv6=n=>t.check(_h(lj,n)),t.e164=n=>t.check(Sh(mj,n)),t.datetime=n=>t.check(Vh(n)),t.date=n=>t.check(Wh(n)),t.time=n=>t.check(Kh(n)),t.duration=n=>t.check(Gh(n))});Ne=$("ZodStringFormat",(t,e)=>{$e.init(t,e),Y0.init(t,e)}),Y1=$("ZodEmail",(t,e)=>{hf.init(t,e),Ne.init(t,e)}),G0=$("ZodGUID",(t,e)=>{mf.init(t,e),Ne.init(t,e)}),Nu=$("ZodUUID",(t,e)=>{ff.init(t,e),Ne.init(t,e)}),Q1=$("ZodURL",(t,e)=>{gf.init(t,e),Ne.init(t,e)}),ej=$("ZodEmoji",(t,e)=>{yf.init(t,e),Ne.init(t,e)}),tj=$("ZodNanoID",(t,e)=>{_f.init(t,e),Ne.init(t,e)}),nj=$("ZodCUID",(t,e)=>{bf.init(t,e),Ne.init(t,e)}),rj=$("ZodCUID2",(t,e)=>{xf.init(t,e),Ne.init(t,e)}),oj=$("ZodULID",(t,e)=>{Sf.init(t,e),Ne.init(t,e)}),sj=$("ZodXID",(t,e)=>{vf.init(t,e),Ne.init(t,e)}),ij=$("ZodKSUID",(t,e)=>{kf.init(t,e),Ne.init(t,e)}),aj=$("ZodIPv4",(t,e)=>{wf.init(t,e),Ne.init(t,e)}),cj=$("ZodIPv6",(t,e)=>{Ef.init(t,e),Ne.init(t,e)}),uj=$("ZodCIDRv4",(t,e)=>{Tf.init(t,e),Ne.init(t,e)}),lj=$("ZodCIDRv6",(t,e)=>{$f.init(t,e),Ne.init(t,e)}),dj=$("ZodBase64",(t,e)=>{Pf.init(t,e),Ne.init(t,e)}),pj=$("ZodBase64URL",(t,e)=>{Rf.init(t,e),Ne.init(t,e)}),mj=$("ZodE164",(t,e)=>{Cf.init(t,e),Ne.init(t,e)}),fj=$("ZodJWT",(t,e)=>{Of.init(t,e),Ne.init(t,e)}),Q0=$("ZodNumber",(t,e)=>{xu.init(t,e),He.init(t,e),t.gt=(r,o)=>t.check(Tu(r,o)),t.gte=(r,o)=>t.check(aa(r,o)),t.min=(r,o)=>t.check(aa(r,o)),t.lt=(r,o)=>t.check(Eu(r,o)),t.lte=(r,o)=>t.check(ia(r,o)),t.max=(r,o)=>t.check(ia(r,o)),t.int=r=>t.check(J0(r)),t.safe=r=>t.check(J0(r)),t.positive=r=>t.check(Tu(0,r)),t.nonnegative=r=>t.check(aa(0,r)),t.negative=r=>t.check(Eu(0,r)),t.nonpositive=r=>t.check(ia(0,r)),t.multipleOf=(r,o)=>t.check($u(r,o)),t.step=(r,o)=>t.check($u(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});hj=$("ZodNumberFormat",(t,e)=>{If.init(t,e),Q0.init(t,e)});gj=$("ZodBoolean",(t,e)=>{Af.init(t,e),He.init(t,e)});yj=$("ZodNull",(t,e)=>{Nf.init(t,e),He.init(t,e)});_j=$("ZodUnknown",(t,e)=>{Df.init(t,e),He.init(t,e)});bj=$("ZodNever",(t,e)=>{Mf.init(t,e),He.init(t,e)});Sj=$("ZodArray",(t,e)=>{jf.init(t,e),He.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Ds(n,r)),t.nonempty=n=>t.check(Ds(1,n)),t.max=(n,r)=>t.check(Pu(n,r)),t.length=(n,r)=>t.check(Ru(n,r)),t.unwrap=()=>t.element});tw=$("ZodObject",(t,e)=>{Su.init(t,e),He.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:De()}),t.loose=()=>t.clone({...t._zod.def,catchall:De()}),t.strict=()=>t.clone({...t._zod.def,catchall:xj()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ue.extend(t,n),t.merge=n=>ue.merge(t,n),t.pick=n=>ue.pick(t,n),t.omit=n=>ue.omit(t,n),t.partial=(...n)=>ue.partial(ow,t,n[0]),t.required=(...n)=>ue.required(sw,t,n[0])});nw=$("ZodUnion",(t,e)=>{vu.init(t,e),He.init(t,e),t.options=e.options});vj=$("ZodDiscriminatedUnion",(t,e)=>{nw.init(t,e),Lf.init(t,e)});kj=$("ZodIntersection",(t,e)=>{zf.init(t,e),He.init(t,e)});wj=$("ZodRecord",(t,e)=>{Ff.init(t,e),He.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});eg=$("ZodEnum",(t,e)=>{Hf.init(t,e),He.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new eg({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new eg({...e,checks:[],...ue.normalizeParams(o),entries:s})}});Ej=$("ZodLiteral",(t,e)=>{Uf.init(t,e),He.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});Tj=$("ZodTransform",(t,e)=>{Bf.init(t,e),He.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ue.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ue.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});ow=$("ZodOptional",(t,e)=>{Zf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});$j=$("ZodNullable",(t,e)=>{qf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});Pj=$("ZodDefault",(t,e)=>{Vf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});Cj=$("ZodPrefault",(t,e)=>{Wf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});sw=$("ZodNonOptional",(t,e)=>{Kf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});Aj=$("ZodCatch",(t,e)=>{Gf.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});Dj=$("ZodPipe",(t,e)=>{Jf.init(t,e),He.init(t,e),t.in=e.in,t.out=e.out});Mj=$("ZodReadonly",(t,e)=>{Xf.init(t,e),He.init(t,e)});iw=$("ZodCustom",(t,e)=>{Yf.init(t,e),He.init(t,e)})});var cw=v(()=>{});var uw=v(()=>{});var lw=v(()=>{kt();Xh();qh();Yh();Qh();cw();kt();x0();ku();Jh();uw();Ut(b0())});var dw=v(()=>{lw()});var pw=v(()=>{dw()});function Rw(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Cw(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var sg,mw,jr,ju,tt,fw,hw,EK,Bj,Zj,ig,Zt,da,gw,ut,on,sn,lt,Lu,yw,ag,_w,bw,cg,pa,K,ug,xw,Sw,TK,zu,qj,Fu,Vj,ma,js,vw,Wj,Kj,Gj,Jj,Xj,Yj,lg,Qj,eL,dg,Hu,tL,nL,Uu,rL,fa,ha,oL,ga,Ls,sL,ya,Bu,Zu,qu,$K,Vu,Wu,Ku,kw,ww,Ew,pg,Tw,_a,zs,$w,iL,Fs,aL,Hs,cL,mg,uL,Gu,lL,dL,pL,mL,fL,hL,gL,yL,_L,bL,Us,xL,SL,Ju,fg,hg,gg,vL,kL,wL,yg,EL,TL,$L,PL,RL,Pw,zo,CL,Xu,PK,OL,Bs,IL,RK,ba,AL,_g,NL,DL,ML,jL,LL,zL,FL,Mu,HL,UL,BL,xa,bg,ZL,qL,VL,WL,KL,GL,JL,XL,YL,QL,ez,tz,nz,rz,oz,sz,iz,az,Zs,cz,uz,lz,Yu,dz,pz,mz,xg,fz,CK,OK,IK,AK,NK,DK,Z,og,Fo=v(()=>{pw();sg="2025-11-25",mw=[sg,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],jr="io.modelcontextprotocol/related-task",ju="2.0",tt=aw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),fw=Ce([w(),ye().int()]),hw=w(),EK=wt({ttl:ye().optional(),pollInterval:ye().optional()}),Bj=H({ttl:ye().optional()}),Zj=H({taskId:w()}),ig=wt({progressToken:fw.optional(),[jr]:Zj.optional()}),Zt=H({_meta:ig.optional()}),da=Zt.extend({task:Bj.optional()}),gw=t=>da.safeParse(t).success,ut=H({method:w(),params:Zt.loose().optional()}),on=H({_meta:ig.optional()}),sn=H({method:w(),params:on.loose().optional()}),lt=wt({_meta:ig.optional()}),Lu=Ce([w(),ye().int()]),yw=H({jsonrpc:q(ju),id:Lu,...ut.shape}).strict(),ag=t=>yw.safeParse(t).success,_w=H({jsonrpc:q(ju),...sn.shape}).strict(),bw=t=>_w.safeParse(t).success,cg=H({jsonrpc:q(ju),id:Lu,result:lt}).strict(),pa=t=>cg.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(K||(K={}));ug=H({jsonrpc:q(ju),id:Lu.optional(),error:H({code:ye().int(),message:w(),data:De().optional()})}).strict(),xw=t=>ug.safeParse(t).success,Sw=Ce([yw,_w,cg,ug]),TK=Ce([cg,ug]),zu=lt.strict(),qj=on.extend({requestId:Lu.optional(),reason:w().optional()}),Fu=sn.extend({method:q("notifications/cancelled"),params:qj}),Vj=H({src:w(),mimeType:w().optional(),sizes:le(w()).optional(),theme:At(["light","dark"]).optional()}),ma=H({icons:le(Vj).optional()}),js=H({name:w(),title:w().optional()}),vw=js.extend({...js.shape,...ma.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),Wj=Du(H({applyDefaults:ot().optional()}),Pe(w(),De())),Kj=rg(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Du(H({form:Wj.optional(),url:tt.optional()}),Pe(w(),De()).optional())),Gj=wt({list:tt.optional(),cancel:tt.optional(),requests:wt({sampling:wt({createMessage:tt.optional()}).optional(),elicitation:wt({create:tt.optional()}).optional()}).optional()}),Jj=wt({list:tt.optional(),cancel:tt.optional(),requests:wt({tools:wt({call:tt.optional()}).optional()}).optional()}),Xj=H({experimental:Pe(w(),tt).optional(),sampling:H({context:tt.optional(),tools:tt.optional()}).optional(),elicitation:Kj.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:Gj.optional(),extensions:Pe(w(),tt).optional()}),Yj=Zt.extend({protocolVersion:w(),capabilities:Xj,clientInfo:vw}),lg=ut.extend({method:q("initialize"),params:Yj}),Qj=H({experimental:Pe(w(),tt).optional(),logging:tt.optional(),completions:tt.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:Jj.optional(),extensions:Pe(w(),tt).optional()}),eL=lt.extend({protocolVersion:w(),capabilities:Qj,serverInfo:vw,instructions:w().optional()}),dg=sn.extend({method:q("notifications/initialized"),params:on.optional()}),Hu=ut.extend({method:q("ping"),params:Zt.optional()}),tL=H({progress:ye(),total:Me(ye()),message:Me(w())}),nL=H({...on.shape,...tL.shape,progressToken:fw}),Uu=sn.extend({method:q("notifications/progress"),params:nL}),rL=Zt.extend({cursor:hw.optional()}),fa=ut.extend({params:rL.optional()}),ha=lt.extend({nextCursor:hw.optional()}),oL=At(["working","input_required","completed","failed","cancelled"]),ga=H({taskId:w(),status:oL,ttl:Ce([ye(),ew()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:Me(ye()),statusMessage:Me(w())}),Ls=lt.extend({task:ga}),sL=on.merge(ga),ya=sn.extend({method:q("notifications/tasks/status"),params:sL}),Bu=ut.extend({method:q("tasks/get"),params:Zt.extend({taskId:w()})}),Zu=lt.merge(ga),qu=ut.extend({method:q("tasks/result"),params:Zt.extend({taskId:w()})}),$K=lt.loose(),Vu=fa.extend({method:q("tasks/list")}),Wu=ha.extend({tasks:le(ga)}),Ku=ut.extend({method:q("tasks/cancel"),params:Zt.extend({taskId:w()})}),kw=lt.merge(ga),ww=H({uri:w(),mimeType:Me(w()),_meta:Pe(w(),De()).optional()}),Ew=ww.extend({text:w()}),pg=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Tw=ww.extend({blob:pg}),_a=At(["user","assistant"]),zs=H({audience:le(_a).optional(),priority:ye().min(0).max(1).optional(),lastModified:ua.datetime({offset:!0}).optional()}),$w=H({...js.shape,...ma.shape,uri:w(),description:Me(w()),mimeType:Me(w()),size:Me(ye()),annotations:zs.optional(),_meta:Me(wt({}))}),iL=H({...js.shape,...ma.shape,uriTemplate:w(),description:Me(w()),mimeType:Me(w()),annotations:zs.optional(),_meta:Me(wt({}))}),Fs=fa.extend({method:q("resources/list")}),aL=ha.extend({resources:le($w)}),Hs=fa.extend({method:q("resources/templates/list")}),cL=ha.extend({resourceTemplates:le(iL)}),mg=Zt.extend({uri:w()}),uL=mg,Gu=ut.extend({method:q("resources/read"),params:uL}),lL=lt.extend({contents:le(Ce([Ew,Tw]))}),dL=sn.extend({method:q("notifications/resources/list_changed"),params:on.optional()}),pL=mg,mL=ut.extend({method:q("resources/subscribe"),params:pL}),fL=mg,hL=ut.extend({method:q("resources/unsubscribe"),params:fL}),gL=on.extend({uri:w()}),yL=sn.extend({method:q("notifications/resources/updated"),params:gL}),_L=H({name:w(),description:Me(w()),required:Me(ot())}),bL=H({...js.shape,...ma.shape,description:Me(w()),arguments:Me(le(_L)),_meta:Me(wt({}))}),Us=fa.extend({method:q("prompts/list")}),xL=ha.extend({prompts:le(bL)}),SL=Zt.extend({name:w(),arguments:Pe(w(),w()).optional()}),Ju=ut.extend({method:q("prompts/get"),params:SL}),fg=H({type:q("text"),text:w(),annotations:zs.optional(),_meta:Pe(w(),De()).optional()}),hg=H({type:q("image"),data:pg,mimeType:w(),annotations:zs.optional(),_meta:Pe(w(),De()).optional()}),gg=H({type:q("audio"),data:pg,mimeType:w(),annotations:zs.optional(),_meta:Pe(w(),De()).optional()}),vL=H({type:q("tool_use"),name:w(),id:w(),input:Pe(w(),De()),_meta:Pe(w(),De()).optional()}),kL=H({type:q("resource"),resource:Ce([Ew,Tw]),annotations:zs.optional(),_meta:Pe(w(),De()).optional()}),wL=$w.extend({type:q("resource_link")}),yg=Ce([fg,hg,gg,wL,kL]),EL=H({role:_a,content:yg}),TL=lt.extend({description:w().optional(),messages:le(EL)}),$L=sn.extend({method:q("notifications/prompts/list_changed"),params:on.optional()}),PL=H({title:w().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),RL=H({taskSupport:At(["required","optional","forbidden"]).optional()}),Pw=H({...js.shape,...ma.shape,description:w().optional(),inputSchema:H({type:q("object"),properties:Pe(w(),tt).optional(),required:le(w()).optional()}).catchall(De()),outputSchema:H({type:q("object"),properties:Pe(w(),tt).optional(),required:le(w()).optional()}).catchall(De()).optional(),annotations:PL.optional(),execution:RL.optional(),_meta:Pe(w(),De()).optional()}),zo=fa.extend({method:q("tools/list")}),CL=ha.extend({tools:le(Pw)}),Xu=lt.extend({content:le(yg).default([]),structuredContent:Pe(w(),De()).optional(),isError:ot().optional()}),PK=Xu.or(lt.extend({toolResult:De()})),OL=da.extend({name:w(),arguments:Pe(w(),De()).optional()}),Bs=ut.extend({method:q("tools/call"),params:OL}),IL=sn.extend({method:q("notifications/tools/list_changed"),params:on.optional()}),RK=H({autoRefresh:ot().default(!0),debounceMs:ye().int().nonnegative().default(300)}),ba=At(["debug","info","notice","warning","error","critical","alert","emergency"]),AL=Zt.extend({level:ba}),_g=ut.extend({method:q("logging/setLevel"),params:AL}),NL=on.extend({level:ba,logger:w().optional(),data:De()}),DL=sn.extend({method:q("notifications/message"),params:NL}),ML=H({name:w().optional()}),jL=H({hints:le(ML).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),LL=H({mode:At(["auto","required","none"]).optional()}),zL=H({type:q("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:le(yg).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:Pe(w(),De()).optional()}),FL=ng("type",[fg,hg,gg]),Mu=ng("type",[fg,hg,gg,vL,zL]),HL=H({role:_a,content:Ce([Mu,le(Mu)]),_meta:Pe(w(),De()).optional()}),UL=da.extend({messages:le(HL),modelPreferences:jL.optional(),systemPrompt:w().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le(w()).optional(),metadata:tt.optional(),tools:le(Pw).optional(),toolChoice:LL.optional()}),BL=ut.extend({method:q("sampling/createMessage"),params:UL}),xa=lt.extend({model:w(),stopReason:Me(At(["endTurn","stopSequence","maxTokens"]).or(w())),role:_a,content:FL}),bg=lt.extend({model:w(),stopReason:Me(At(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:_a,content:Ce([Mu,le(Mu)])}),ZL=H({type:q("boolean"),title:w().optional(),description:w().optional(),default:ot().optional()}),qL=H({type:q("string"),title:w().optional(),description:w().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:At(["email","uri","date","date-time"]).optional(),default:w().optional()}),VL=H({type:At(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),WL=H({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),default:w().optional()}),KL=H({type:q("string"),title:w().optional(),description:w().optional(),oneOf:le(H({const:w(),title:w()})),default:w().optional()}),GL=H({type:q("string"),title:w().optional(),description:w().optional(),enum:le(w()),enumNames:le(w()).optional(),default:w().optional()}),JL=Ce([WL,KL]),XL=H({type:q("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({type:q("string"),enum:le(w())}),default:le(w()).optional()}),YL=H({type:q("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:H({anyOf:le(H({const:w(),title:w()}))}),default:le(w()).optional()}),QL=Ce([XL,YL]),ez=Ce([GL,JL,QL]),tz=Ce([ez,ZL,qL,VL]),nz=da.extend({mode:q("form").optional(),message:w(),requestedSchema:H({type:q("object"),properties:Pe(w(),tz),required:le(w()).optional()})}),rz=da.extend({mode:q("url"),message:w(),elicitationId:w(),url:w().url()}),oz=Ce([nz,rz]),sz=ut.extend({method:q("elicitation/create"),params:oz}),iz=on.extend({elicitationId:w()}),az=sn.extend({method:q("notifications/elicitation/complete"),params:iz}),Zs=lt.extend({action:At(["accept","decline","cancel"]),content:rg(t=>t===null?void 0:t,Pe(w(),Ce([w(),ye(),ot(),le(w())])).optional())}),cz=H({type:q("ref/resource"),uri:w()}),uz=H({type:q("ref/prompt"),name:w()}),lz=Zt.extend({ref:Ce([uz,cz]),argument:H({name:w(),value:w()}),context:H({arguments:Pe(w(),w()).optional()}).optional()}),Yu=ut.extend({method:q("completion/complete"),params:lz});dz=lt.extend({completion:wt({values:le(w()).max(100),total:Me(ye().int()),hasMore:Me(ot())})}),pz=H({uri:w().startsWith("file://"),name:w().optional(),_meta:Pe(w(),De()).optional()}),mz=ut.extend({method:q("roots/list"),params:Zt.optional()}),xg=lt.extend({roots:le(pz)}),fz=sn.extend({method:q("notifications/roots/list_changed"),params:on.optional()}),CK=Ce([Hu,lg,Yu,_g,Ju,Us,Fs,Hs,Gu,mL,hL,Bs,zo,Bu,qu,Vu,Ku]),OK=Ce([Fu,Uu,dg,fz,ya]),IK=Ce([zu,xa,bg,Zs,xg,Zu,Wu,Ls]),AK=Ce([Hu,BL,sz,mz,Bu,qu,Vu,Ku]),NK=Ce([Fu,Uu,DL,yL,dL,IL,$L,ya,az]),DK=Ce([zu,eL,dz,TL,xL,aL,cL,lL,Xu,CL,Zu,Wu,Ls]),Z=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===K.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new og(o.elicitations,n)}return new t(e,n,r)}},og=class extends Z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Lr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Ow=v(()=>{});var Aw,Iw,Nw,Qu=v(()=>{Aw=Symbol("Let zodToJsonSchema decide on which parser to use"),Iw={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Nw=t=>typeof t=="string"?{...Iw,name:t}:{...Iw,...t}});var Dw,Sg=v(()=>{Qu();Dw=t=>{let e=Nw(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function vg(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function de(t,e,n,r,o){t[e]=n,vg(t,e,r,o)}var zr=v(()=>{});var el,tl=v(()=>{el=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?el(e,t.currentPath):e.join("/")}}var an=v(()=>{tl()});function Mw(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(n.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(n,"minItems",t.exactLength.value,t.exactLength.message,e),de(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var kg=v(()=>{Gi();zr();Je()});function jw(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var wg=v(()=>{zr()});function Lw(){return{type:"boolean"}}var Eg=v(()=>{});function nl(t,e){return Y(t.type._def,e)}var rl=v(()=>{Je()});var zw,Tg=v(()=>{Je();zw=(t,e)=>Y(t.innerType._def,e)});function $g(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>$g(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return hz(t,e)}}var hz,Pg=v(()=>{zr();hz=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":de(n,"minimum",r.value,r.message,e);break;case"max":de(n,"maximum",r.value,r.message,e);break}return n}});function Fw(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Rg=v(()=>{Je()});function Hw(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):je(e)}var Cg=v(()=>{Je();an()});function Uw(t){return{type:"string",enum:Array.from(t.values)}}var Og=v(()=>{});function Bw(t,e){let n=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(gz(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}var gz,Ig=v(()=>{Je();gz=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Zw(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var Ag=v(()=>{});function ol(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":yn(n,"email",r.message,e);break;case"format:idn-email":yn(n,"idn-email",r.message,e);break;case"pattern:zod":Et(n,gn.email,r.message,e);break}break;case"url":yn(n,"uri",r.message,e);break;case"uuid":yn(n,"uuid",r.message,e);break;case"regex":Et(n,r.regex,r.message,e);break;case"cuid":Et(n,gn.cuid,r.message,e);break;case"cuid2":Et(n,gn.cuid2,r.message,e);break;case"startsWith":Et(n,RegExp(`^${Dg(r.value,e)}`),r.message,e);break;case"endsWith":Et(n,RegExp(`${Dg(r.value,e)}$`),r.message,e);break;case"datetime":yn(n,"date-time",r.message,e);break;case"date":yn(n,"date",r.message,e);break;case"time":yn(n,"time",r.message,e);break;case"duration":yn(n,"duration",r.message,e);break;case"length":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Et(n,RegExp(Dg(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&yn(n,"ipv4",r.message,e),r.version!=="v4"&&yn(n,"ipv6",r.message,e);break}case"base64url":Et(n,gn.base64url,r.message,e);break;case"jwt":Et(n,gn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Et(n,gn.ipv4Cidr,r.message,e),r.version!=="v4"&&Et(n,gn.ipv6Cidr,r.message,e);break}case"emoji":Et(n,gn.emoji(),r.message,e);break;case"ulid":{Et(n,gn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{yn(n,"binary",r.message,e);break}case"contentEncoding:base64":{de(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Et(n,gn.base64,r.message,e);break}}break}case"nanoid":Et(n,gn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Dg(t,e){return e.patternStrategy==="escape"?_z(t):t}function _z(t){let e="";for(let n=0;n<t.length;n++)yz.has(t[n])||(e+="\\"),e+=t[n];return e}function yn(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):de(t,"format",e,n,r)}function Et(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:qw(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):de(t,"pattern",qw(e,r),n,r)}function qw(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
487
- ]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
488
- ]))`;continue}}if(n.s&&r[c]==="."){o+=i?`${r[c]}\r
489
- `:`[${r[c]}\r
490
- ]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Ng,gn,yz,sl=v(()=>{zr();gn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ng===void 0&&(Ng=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ng),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};yz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function il(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=ol(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=nl(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var al=v(()=>{Gi();Je();sl();rl();an()});function Vw(t,e){if(e.mapStrategy==="record")return il(t,e);let n=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),r=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Mg=v(()=>{Je();al();an()});function Ww(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var jg=v(()=>{});function Kw(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var Lg=v(()=>{an()});function Gw(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zg=v(()=>{});function Xw(t,e){if(e.target==="openApi3")return Jw(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Sa&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Sa[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return Jw(t,e)}var Sa,Jw,cl=v(()=>{Je();Sa={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Jw=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>Y(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function Yw(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Sa[t.innerType._def.typeName],nullable:!0}:{type:[Sa[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Fg=v(()=>{Je();cl()});function Qw(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",vg(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var Hg=v(()=>{zr()});function eE(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=xz(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Y(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=bz(t,e);return i!==void 0&&(r.additionalProperties=i),r}function bz(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function xz(t){try{return t.isOptional()}catch{return!0}}var Ug=v(()=>{Je()});var tE,Bg=v(()=>{Je();an();tE=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:je(e)},n]}:je(e)}});var nE,Zg=v(()=>{Je();nE=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let n=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}}});function rE(t,e){return Y(t.type._def,e)}var qg=v(()=>{Je()});function oE(t,e){let r={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Vg=v(()=>{zr();Je()});function sE(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Wg=v(()=>{Je()});function iE(t){return{not:je(t)}}var Kg=v(()=>{an()});function aE(t){return je(t)}var Gg=v(()=>{an()});var cE,Jg=v(()=>{Je();cE=(t,e)=>Y(t.innerType._def,e)});var uE,Xg=v(()=>{Gi();an();kg();wg();Eg();rl();Tg();Pg();Rg();Cg();Og();Ig();Ag();Mg();jg();Lg();zg();Fg();Hg();Ug();Bg();Zg();qg();al();Vg();sl();Wg();Kg();cl();Gg();Jg();uE=(t,e,n)=>{switch(e){case D.ZodString:return ol(t,n);case D.ZodNumber:return Qw(t,n);case D.ZodObject:return eE(t,n);case D.ZodBigInt:return jw(t,n);case D.ZodBoolean:return Lw();case D.ZodDate:return $g(t,n);case D.ZodUndefined:return iE(n);case D.ZodNull:return Gw(n);case D.ZodArray:return Mw(t,n);case D.ZodUnion:case D.ZodDiscriminatedUnion:return Xw(t,n);case D.ZodIntersection:return Bw(t,n);case D.ZodTuple:return sE(t,n);case D.ZodRecord:return il(t,n);case D.ZodLiteral:return Zw(t,n);case D.ZodEnum:return Uw(t);case D.ZodNativeEnum:return Ww(t);case D.ZodNullable:return Yw(t,n);case D.ZodOptional:return tE(t,n);case D.ZodMap:return Vw(t,n);case D.ZodSet:return oE(t,n);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return rE(t,n);case D.ZodNaN:case D.ZodNever:return Kw(n);case D.ZodEffects:return Hw(t,n);case D.ZodAny:return je(n);case D.ZodUnknown:return aE(n);case D.ZodDefault:return Fw(t,n);case D.ZodBranded:return nl(t,n);case D.ZodReadonly:return cE(t,n);case D.ZodCatch:return zw(t,n);case D.ZodPipeline:return nE(t,n);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(r=>{})(e)}}});function Y(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Aw)return a}if(r&&!n){let a=Sz(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=uE(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&vz(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Sz,vz,Je=v(()=>{Qu();Xg();tl();an();Sz=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:el(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},vz=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var lE=v(()=>{});var Yg,Qg=v(()=>{Je();Sg();an();Yg=(t,e)=>{let n=Dw(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??je(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??je(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var dE=v(()=>{Qu();Sg();zr();tl();Je();lE();an();kg();wg();Eg();rl();Tg();Pg();Rg();Cg();Og();Ig();Ag();Mg();jg();Lg();zg();Fg();Hg();Ug();Bg();Zg();qg();Jg();al();Vg();sl();Wg();Kg();cl();Gg();Xg();Qg();Qg()});function kz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ey(t,e){return rn(t)?Hh(t,{target:kz(e?.target),io:e?.pipeStrategy??"input"}):Yg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ty(t){let n=Mr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Au(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function ny(t,e){let n=Dr(t,e);if(!n.success)throw n.error;return n.data}var ry=v(()=>{Zh();ca();dE()});function pE(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function mE(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];pE(i)&&pE(s)?n[o]={...i,...s}:n[o]=s}return n}var wz,ul,fE=v(()=>{ca();Fo();Ow();ry();wz=6e4,ul=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Fu,n=>{this._oncancel(n)}),this.setNotificationHandler(Uu,n=>{this._onprogress(n)}),this.setRequestHandler(Hu,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Bu,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(qu,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new Z(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new Z(K.InvalidParams,`Task not found: ${s}`);if(!Lr(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(Lr(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[jr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Vu,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Z(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ku,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new Z(K.InvalidParams,`Task not found: ${n.params.taskId}`);if(Lr(o.status))throw new Z(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new Z(K.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(K.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),pa(s)||xw(s)?this._onresponse(s):ag(s)?this._onrequest(s,i):bw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=Z.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[jr]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:K.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=gw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new Z(K.ConnectionClosed,"Request was cancelled");let h={...p,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let m=h.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,h)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:K.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,o=Number(n),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),pa(e))r(e);else{let i=new Z(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(pa(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,n))}}if(s||this._progressHandlers.delete(n),pa(e))o(e);else{let i=Z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Ls,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},Lr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new Z(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(K.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:p};r?.onprogress&&(this._progressHandlers.set(p,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[jr]:c}});let m=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let b=_ instanceof Z?_:new Z(K.RequestTimeout,String(_));l(b)};this._responseHandlers.set(p,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=Dr(n,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{m(r?.signal?.reason)});let f=r?.timeout??wz,g=()=>m(Z.fromError(K.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(p,f,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let S=this._responseHandlers.get(p);S?S(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Zu,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Wu,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},kw,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[jr]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[jr]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[jr]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=ty(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=ny(e,o);return Promise.resolve(n(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=ty(e);this._notificationHandlers.set(r,o=>{let s=ny(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&ag(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(K.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new Z(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new Z(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new Z(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=ya.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Lr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new Z(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Lr(a.status))throw new Z(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=ya.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Lr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}}});var wa=L(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var va=class{};he._CodeOrName=va;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ho=class extends va{constructor(e){if(super(),!he.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};he.Name=Ho;var cn=class extends va{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Ho&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=cn;he.nil=new cn("");function hE(t,...e){let n=[t[0]],r=0;for(;r<e.length;)sy(n,e[r]),n.push(t[++r]);return new cn(n)}he._=hE;var oy=new cn("+");function gE(t,...e){let n=[ka(t[0])],r=0;for(;r<e.length;)n.push(oy),sy(n,e[r]),n.push(oy,ka(t[++r]));return Ez(n),new cn(n)}he.str=gE;function sy(t,e){e instanceof cn?t.push(...e._items):e instanceof Ho?t.push(e):t.push(Pz(e))}he.addCodeArg=sy;function Ez(t){let e=1;for(;e<t.length-1;){if(t[e]===oy){let n=Tz(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Tz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ho||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ho))return`"${t}${e.slice(1)}`}function $z(t,e){return e.emptyStr()?t:t.emptyStr()?e:gE`${t}${e}`}he.strConcat=$z;function Pz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ka(Array.isArray(t)?t.join(","):t)}function Rz(t){return new cn(ka(t))}he.stringify=Rz;function ka(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=ka;function Cz(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new cn(`.${t}`):hE`[${t}]`}he.getProperty=Cz;function Oz(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new cn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=Oz;function Iz(t){return new cn(t.toString())}he.regexpCode=Iz});var cy=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.ValueScope=Dt.ValueScopeName=Dt.Scope=Dt.varKinds=Dt.UsedValueState=void 0;var Nt=wa(),iy=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ll;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ll||(Dt.UsedValueState=ll={}));Dt.varKinds={const:new Nt.Name("const"),let:new Nt.Name("let"),var:new Nt.Name("var")};var dl=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Nt.Name?e:this.name(e)}name(e){return new Nt.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Dt.Scope=dl;var pl=class extends Nt.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Nt._)`.${new Nt.Name(n)}[${r}]`}};Dt.ValueScopeName=pl;var Az=(0,Nt._)`\n`,ay=class extends dl{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Az:Nt.nil}}get(){return this._scope}name(e){return new pl(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Nt._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=Nt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ll.Started);let l=n(u);if(l){let d=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const;s=(0,Nt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Nt._)`${s}${l}${this.opts._n}`;else throw new iy(u);c.set(u,ll.Completed)})}return s}};Dt.ValueScope=ay});var oe=L(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.or=se.and=se.not=se.CodeGen=se.operators=se.varKinds=se.ValueScopeName=se.ValueScope=se.Scope=se.Name=se.regexpCode=se.stringify=se.getProperty=se.nil=se.strConcat=se.str=se._=void 0;var pe=wa(),_n=cy(),Fr=wa();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Fr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Fr.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return Fr.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Fr.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return Fr.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Fr.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return Fr.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Fr.Name}});var gl=cy();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return gl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return gl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return gl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return gl.varKinds}});se.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};var or=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},uy=class extends or{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?_n.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Vs(this.rhs,e,n)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},ml=class extends or{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vs(this.rhs,e,n),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return hl(e,this.rhs)}},ly=class extends ml{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},dy=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},py=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},my=class extends or{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},fy=class extends or{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Vs(this.code,e,n),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},Ea=class extends or{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(Nz(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Zo(e,n.names),{})}},sr=class extends Ea{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},hy=class extends Ea{},qs=class extends sr{};qs.kind="else";var Uo=class t extends sr{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new qs(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(yE(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Vs(this.condition,e,n),this}get names(){let e=super.names;return hl(e,this.condition),this.else&&Zo(e,this.else.names),e}};Uo.kind="if";var Bo=class extends sr{};Bo.kind="for";var gy=class extends Bo{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Vs(this.iteration,e,n),this}get names(){return Zo(super.names,this.iteration.names)}},yy=class extends Bo{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?_n.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=hl(super.names,this.from);return hl(e,this.to)}},fl=class extends Bo{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Vs(this.iterable,e,n),this}get names(){return Zo(super.names,this.iterable.names)}},Ta=class extends sr{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ta.kind="func";var $a=class extends Ea{render(e){return"return "+super.render(e)}};$a.kind="return";var _y=class extends sr{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Zo(e,this.catch.names),this.finally&&Zo(e,this.finally.names),e}},Pa=class extends sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Pa.kind="catch";var Ra=class extends sr{render(e){return"finally"+super.render(e)}};Ra.kind="finally";var by=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
491
- `:""},this._extScope=e,this._scope=new _n.Scope({parent:e}),this._nodes=[new hy]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new uy(e,s,r)),s}const(e,n,r){return this._def(_n.varKinds.const,e,n,r)}let(e,n,r){return this._def(_n.varKinds.let,e,n,r)}var(e,n,r){return this._def(_n.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ml(e,n,r))}add(e,n){return this._leafNode(new ly(e,se.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new fy(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,pe.addCodeArg)(n,o));return n.push("}"),new pe._Code(n)}if(e,n,r){if(this._blockNode(new Uo(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Uo(e))}else(){return this._elseNode(new qs)}endIf(){return this._endBlockNode(Uo,qs)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new gy(e),n)}forRange(e,n,r,o,s=this.opts.es5?_n.varKinds.var:_n.varKinds.let){let i=this._scope.toName(e);return this._for(new yy(s,i,n,r),()=>o(i))}forOf(e,n,r,o=_n.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof pe.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),r(s)})}return this._for(new fl("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?_n.varKinds.var:_n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new fl("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Bo)}label(e){return this._leafNode(new dy(e))}break(e){return this._leafNode(new py(e))}return(e){let n=new $a;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($a)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new _y;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new Pa(s),n(s)}return r&&(this._currNode=o.finally=new Ra,this.code(r)),this._endBlockNode(Pa,Ra)}throw(e){return this._leafNode(new my(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=pe.nil,r,o){return this._blockNode(new Ta(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ta)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Uo))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};se.CodeGen=by;function Zo(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function hl(t,e){return e instanceof pe._CodeOrName?Zo(t,e.names):t}function Vs(t,e,n){if(t instanceof pe.Name)return r(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=r(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function Nz(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function yE(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${xy(t)}`}se.not=yE;var Dz=_E(se.operators.AND);function Mz(...t){return t.reduce(Dz)}se.and=Mz;var jz=_E(se.operators.OR);function Lz(...t){return t.reduce(jz)}se.or=Lz;function _E(t){return(e,n)=>e===pe.nil?n:n===pe.nil?e:(0,pe._)`${xy(e)} ${t} ${xy(n)}`}function xy(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=L(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.checkStrictMode=ae.getErrorPath=ae.Type=ae.useFunc=ae.setEvaluated=ae.evaluatedPropsToName=ae.mergeEvaluated=ae.eachItem=ae.unescapeJsonPointer=ae.escapeJsonPointer=ae.escapeFragment=ae.unescapeFragment=ae.schemaRefOrVal=ae.schemaHasRulesButRef=ae.schemaHasRules=ae.checkUnknownRules=ae.alwaysValidSchema=ae.toHash=void 0;var Ee=oe(),zz=wa();function Fz(t){let e={};for(let n of t)e[n]=!0;return e}ae.toHash=Fz;function Hz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(SE(t,e),!vE(e,t.self.RULES.all))}ae.alwaysValidSchema=Hz;function SE(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||EE(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=SE;function vE(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ae.schemaHasRules=vE;function Uz(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ae.schemaHasRulesButRef=Uz;function Bz({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Ee._)`${n}`}return(0,Ee._)`${t}${e}${(0,Ee.getProperty)(r)}`}ae.schemaRefOrVal=Bz;function Zz(t){return kE(decodeURIComponent(t))}ae.unescapeFragment=Zz;function qz(t){return encodeURIComponent(vy(t))}ae.escapeFragment=qz;function vy(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=vy;function kE(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=kE;function Vz(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ae.eachItem=Vz;function bE({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ee.Name?(s instanceof Ee.Name?t(o,s,i):e(o,s,i),i):s instanceof Ee.Name?(e(o,i,s),s):n(s,i);return a===Ee.Name&&!(c instanceof Ee.Name)?r(o,c):c}}ae.mergeEvaluated={props:bE({mergeNames:(t,e,n)=>t.if((0,Ee._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,Ee._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,Ee._)`${n} || {}`).code((0,Ee._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,Ee._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,Ee._)`${n} || {}`),ky(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:wE}),items:bE({mergeNames:(t,e,n)=>t.if((0,Ee._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,Ee._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,Ee._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,Ee._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function wE(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,Ee._)`{}`);return e!==void 0&&ky(t,n,e),n}ae.evaluatedPropsToName=wE;function ky(t,e,n){Object.keys(n).forEach(r=>t.assign((0,Ee._)`${e}${(0,Ee.getProperty)(r)}`,!0))}ae.setEvaluated=ky;var xE={};function Wz(t,e){return t.scopeValue("func",{ref:e,code:xE[e.code]||(xE[e.code]=new zz._Code(e.code))})}ae.useFunc=Wz;var Sy;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Sy||(ae.Type=Sy={}));function Kz(t,e,n){if(t instanceof Ee.Name){let r=e===Sy.Num;return n?r?(0,Ee._)`"[" + ${t} + "]"`:(0,Ee._)`"['" + ${t} + "']"`:r?(0,Ee._)`"/" + ${t}`:(0,Ee._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Ee.getProperty)(t).toString():"/"+vy(t)}ae.getErrorPath=Kz;function EE(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=EE});var ir=L(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var yt=oe(),Gz={data:new yt.Name("data"),valCxt:new yt.Name("valCxt"),instancePath:new yt.Name("instancePath"),parentData:new yt.Name("parentData"),parentDataProperty:new yt.Name("parentDataProperty"),rootData:new yt.Name("rootData"),dynamicAnchors:new yt.Name("dynamicAnchors"),vErrors:new yt.Name("vErrors"),errors:new yt.Name("errors"),this:new yt.Name("this"),self:new yt.Name("self"),scope:new yt.Name("scope"),json:new yt.Name("json"),jsonPos:new yt.Name("jsonPos"),jsonLen:new yt.Name("jsonLen"),jsonPart:new yt.Name("jsonPart")};wy.default=Gz});var Ca=L(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.extendErrors=_t.resetErrorsCount=_t.reportExtraError=_t.reportError=_t.keyword$DataError=_t.keywordError=void 0;var fe=oe(),yl=me(),Tt=ir();_t.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};_t.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function Jz(t,e=_t.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=PE(t,e,n);r??(i||a)?TE(s,c):$E(o,(0,fe._)`[${c}]`)}_t.reportError=Jz;function Xz(t,e=_t.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=PE(t,e,n);TE(o,a),s||i||$E(r,Tt.default.vErrors)}_t.reportExtraError=Xz;function Yz(t,e){t.assign(Tt.default.errors,e),t.if((0,fe._)`${Tt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${Tt.default.vErrors}.length`,e),()=>t.assign(Tt.default.vErrors,null)))}_t.resetErrorsCount=Yz;function Qz({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Tt.default.errors,a=>{t.const(i,(0,fe._)`${Tt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(Tt.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,n),t.assign((0,fe._)`${i}.data`,r))})}_t.extendErrors=Qz;function TE(t,e){let n=t.const("err",e);t.if((0,fe._)`${Tt.default.vErrors} === null`,()=>t.assign(Tt.default.vErrors,(0,fe._)`[${n}]`),(0,fe._)`${Tt.default.vErrors}.push(${n})`),t.code((0,fe._)`${Tt.default.errors}++`)}function $E(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,fe._)`new ${t.ValidationError}(${e})`):(n.assign((0,fe._)`${r}.errors`,e),n.return(!1))}var qo={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function PE(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,fe._)`{}`:eF(t,e,n)}function eF(t,e,n={}){let{gen:r,it:o}=t,s=[tF(o,n),nF(t,n)];return rF(t,e,s),r.object(...s)}function tF({errorPath:t},{instancePath:e}){let n=e?(0,fe.str)`${t}${(0,yl.getErrorPath)(e,yl.Type.Str)}`:t;return[Tt.default.instancePath,(0,fe.strConcat)(Tt.default.instancePath,n)]}function nF({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,fe.str)`${e}/${t}`;return n&&(o=(0,fe.str)`${o}${(0,yl.getErrorPath)(n,yl.Type.Str)}`),[qo.schemaPath,o]}function rF(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([qo.keyword,o],[qo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&r.push([qo.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([qo.schema,i],[qo.parentSchema,(0,fe._)`${l}${d}`],[Tt.default.data,s]),u&&r.push([qo.propertyName,u])}});var CE=L(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.boolOrEmptySchema=Ws.topBoolOrEmptySchema=void 0;var oF=Ca(),sF=oe(),iF=ir(),aF={message:"boolean schema is false"};function cF(t){let{gen:e,schema:n,validateName:r}=t;n===!1?RE(t,!1):typeof n=="object"&&n.$async===!0?e.return(iF.default.data):(e.assign((0,sF._)`${r}.errors`,null),e.return(!0))}Ws.topBoolOrEmptySchema=cF;function uF(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),RE(t)):n.var(e,!0)}Ws.boolOrEmptySchema=uF;function RE(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,oF.reportError)(o,aF,void 0,e)}});var Ey=L(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getRules=Ks.isJSONType=void 0;var lF=["string","number","integer","boolean","null","object","array"],dF=new Set(lF);function pF(t){return typeof t=="string"&&dF.has(t)}Ks.isJSONType=pF;function mF(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ks.getRules=mF});var Ty=L(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.shouldUseRule=Hr.shouldUseGroup=Hr.schemaHasRulesForType=void 0;function fF({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&OE(t,r)}Hr.schemaHasRulesForType=fF;function OE(t,e){return e.rules.some(n=>IE(t,n))}Hr.shouldUseGroup=OE;function IE(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Hr.shouldUseRule=IE});var Oa=L(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.reportTypeError=bt.checkDataTypes=bt.checkDataType=bt.coerceAndCheckDataType=bt.getJSONTypes=bt.getSchemaTypes=bt.DataType=void 0;var hF=Ey(),gF=Ty(),yF=Ca(),ne=oe(),AE=me(),Gs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gs||(bt.DataType=Gs={}));function _F(t){let e=NE(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}bt.getSchemaTypes=_F;function NE(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(hF.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}bt.getJSONTypes=NE;function bF(t,e){let{gen:n,data:r,opts:o}=t,s=xF(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,gF.schemaHasRulesForType)(t,e[0]));if(i){let a=Py(e,r,o.strictNumbers,Gs.Wrong);n.if(a,()=>{s.length?SF(t,e,s):Ry(t)})}return i}bt.coerceAndCheckDataType=bF;var DE=new Set(["string","number","integer","boolean","null"]);function xF(t,e){return e?t.filter(n=>DE.has(n)||e==="array"&&n==="array"):[]}function SF(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(Py(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(let u of n)(DE.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Ry(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),vF(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null
492
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ne._)`+${o}`);return;case"integer":r.elseIf((0,ne._)`${i} === "boolean" || ${o} === null
493
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ne._)`+${o}`);return;case"boolean":r.elseIf((0,ne._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ne._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ne._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ne._)`${i} === "string" || ${i} === "number"
494
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function vF({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function $y(t,e,n,r=Gs.Correct){let o=r===Gs.Correct?ne.operators.EQ:ne.operators.NEQ,s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===Gs.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}bt.checkDataType=$y;function Py(t,e,n,r){if(t.length===1)return $y(t[0],e,n,r);let o,s=(0,AE.toHash)(t);if(s.array&&s.object){let i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(let i in s)o=(0,ne.and)(o,$y(i,e,n,r));return o}bt.checkDataTypes=Py;var kF={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function Ry(t){let e=wF(t);(0,yF.reportError)(e,kF)}bt.reportTypeError=Ry;function wF(t){let{gen:e,data:n,schema:r}=t,o=(0,AE.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var jE=L(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.assignDefaults=void 0;var Js=oe(),EF=me();function TF(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)ME(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>ME(t,s,o.default))}_l.assignDefaults=TF;function ME(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Js._)`${s}${(0,Js.getProperty)(e)}`;if(o){(0,EF.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Js._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Js._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Js._)`${a} = ${(0,Js.stringify)(n)}`)}});var un=L(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.validateUnion=we.validateArray=we.usePattern=we.callValidateCode=we.schemaProperties=we.allSchemaProperties=we.noPropertyInData=we.propertyInData=we.isOwnProperty=we.hasPropFunc=we.reportMissingProp=we.checkMissingProp=we.checkReportMissingProp=void 0;var Oe=oe(),Cy=me(),Ur=ir(),$F=me();function PF(t,e){let{gen:n,data:r,it:o}=t;n.if(Iy(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Oe._)`${e}`},!0),t.error()})}we.checkReportMissingProp=PF;function RF({gen:t,data:e,it:{opts:n}},r,o){return(0,Oe.or)(...r.map(s=>(0,Oe.and)(Iy(t,e,s,n.ownProperties),(0,Oe._)`${o} = ${s}`)))}we.checkMissingProp=RF;function CF(t,e){t.setParams({missingProperty:e},!0),t.error()}we.reportMissingProp=CF;function LE(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Oe._)`Object.prototype.hasOwnProperty`})}we.hasPropFunc=LE;function Oy(t,e,n){return(0,Oe._)`${LE(t)}.call(${e}, ${n})`}we.isOwnProperty=Oy;function OF(t,e,n,r){let o=(0,Oe._)`${e}${(0,Oe.getProperty)(n)} !== undefined`;return r?(0,Oe._)`${o} && ${Oy(t,e,n)}`:o}we.propertyInData=OF;function Iy(t,e,n,r){let o=(0,Oe._)`${e}${(0,Oe.getProperty)(n)} === undefined`;return r?(0,Oe.or)(o,(0,Oe.not)(Oy(t,e,n))):o}we.noPropertyInData=Iy;function zE(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}we.allSchemaProperties=zE;function IF(t,e){return zE(e).filter(n=>!(0,Cy.alwaysValidSchema)(t,e[n]))}we.schemaProperties=IF;function AF({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Oe._)`${t}, ${e}, ${r}${o}`:e,d=[[Ur.default.instancePath,(0,Oe.strConcat)(Ur.default.instancePath,s)],[Ur.default.parentData,i.parentData],[Ur.default.parentDataProperty,i.parentDataProperty],[Ur.default.rootData,Ur.default.rootData]];i.opts.dynamicRef&&d.push([Ur.default.dynamicAnchors,Ur.default.dynamicAnchors]);let p=(0,Oe._)`${l}, ${n.object(...d)}`;return c!==Oe.nil?(0,Oe._)`${a}.call(${c}, ${p})`:(0,Oe._)`${a}(${p})`}we.callValidateCode=AF;var NF=(0,Oe._)`new RegExp`;function DF({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Oe._)`${o.code==="new RegExp"?NF:(0,$F.useFunc)(t,o)}(${n}, ${r})`})}we.usePattern=DF;function MF(t){let{gen:e,data:n,keyword:r,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Oe._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Cy.Type.Num},s),e.if((0,Oe.not)(s),a)})}}we.validateArray=MF;function jF(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Cy.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Oe._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Oe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}we.validateUnion=jF});var UE=L(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.validateKeywordUsage=Ln.validSchemaType=Ln.funcKeywordCode=Ln.macroKeywordCode=void 0;var $t=oe(),Vo=ir(),LF=un(),zF=Ca();function FF(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=HE(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:$t.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ln.macroKeywordCode=FF;function HF(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;BF(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=HE(r,o,u),d=r.let("valid");t.block$data(d,p),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function p(){if(e.errors===!1)f(),e.modifying&&FE(t),g(()=>t.error());else{let y=e.async?h():m();e.modifying&&FE(t),g(()=>UF(t,y))}}function h(){let y=r.let("ruleErrs",null);return r.try(()=>f((0,$t._)`await `),_=>r.assign(d,!1).if((0,$t._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,$t._)`${_}.errors`),()=>r.throw(_))),y}function m(){let y=(0,$t._)`${l}.errors`;return r.assign(y,null),f($t.nil),y}function f(y=e.async?(0,$t._)`await `:$t.nil){let _=c.opts.passContext?Vo.default.this:Vo.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,$t._)`${y}${(0,LF.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;r.if((0,$t.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}Ln.funcKeywordCode=HF;function FE(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,$t._)`${r.parentData}[${r.parentDataProperty}]`))}function UF(t,e){let{gen:n}=t;n.if((0,$t._)`Array.isArray(${e})`,()=>{n.assign(Vo.default.vErrors,(0,$t._)`${Vo.default.vErrors} === null ? ${e} : ${Vo.default.vErrors}.concat(${e})`).assign(Vo.default.errors,(0,$t._)`${Vo.default.vErrors}.length`),(0,zF.extendErrors)(t)},()=>t.error())}function BF({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function HE(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,$t.stringify)(n)})}function ZF(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ln.validSchemaType=ZF;function qF({schema:t,opts:e,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Ln.validateKeywordUsage=qF});var ZE=L(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.extendSubschemaMode=Br.extendSubschemaData=Br.getSubschema=void 0;var zn=oe(),BE=me();function VF(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,zn._)`${t.schemaPath}${(0,zn.getProperty)(e)}${(0,zn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,BE.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Br.getSubschema=VF;function WF(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,zn._)`${e.data}${(0,zn.getProperty)(n)}`,!0);c(p),t.errorPath=(0,zn.str)`${u}${(0,BE.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,zn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof zn.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Br.extendSubschemaData=WF;function KF(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Br.extendSubschemaMode=KF});var Ay=L((X8,qE)=>{"use strict";qE.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var WE=L((Y8,VE)=>{"use strict";var Zr=VE.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};bl(e,r,o,t,"",t)};Zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Zr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function bl(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in Zr.arrayKeywords)for(var p=0;p<d.length;p++)bl(t,e,n,d[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in Zr.propsKeywords){if(d&&typeof d=="object")for(var h in d)bl(t,e,n,d[h],o+"/"+l+"/"+GF(h),s,o,l,r,h)}else(l in Zr.keywords||t.allKeys&&!(l in Zr.skipKeywords))&&bl(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function GF(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ia=L(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getSchemaRefs=Mt.resolveUrl=Mt.normalizeId=Mt._getFullPath=Mt.getFullPath=Mt.inlineRef=void 0;var JF=me(),XF=Ay(),YF=WE(),QF=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function eH(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ny(t):e?KE(t)<=e:!1}Mt.inlineRef=eH;var tH=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ny(t){for(let e in t){if(tH.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Ny)||typeof n=="object"&&Ny(n))return!0}return!1}function KE(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!QF.has(n)&&(typeof t[n]=="object"&&(0,JF.eachItem)(t[n],r=>e+=KE(r)),e===1/0))return 1/0}return e}function GE(t,e="",n){n!==!1&&(e=Xs(e));let r=t.parse(e);return JE(t,r)}Mt.getFullPath=GE;function JE(t,e){return t.serialize(e).split("#")[0]+"#"}Mt._getFullPath=JE;var nH=/#\/?$/;function Xs(t){return t?t.replace(nH,""):""}Mt.normalizeId=Xs;function rH(t,e,n){return n=Xs(n),t.resolve(e,n)}Mt.resolveUrl=rH;var oH=/^[a-z_][-a-z0-9._]*$/i;function sH(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Xs(t[n]||e),s={"":o},i=GE(r,o,!1),a={},c=new Set;return YF(t,{allKeys:!0},(d,p,h,m)=>{if(m===void 0)return;let f=i+p,g=s[m];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(b){let S=this.opts.uriResolver.resolve;if(b=Xs(g?S(g,b):b),c.has(b))throw l(b);c.add(b);let E=this.refs[b];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,b):b!==Xs(f)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=f),b}function _(b){if(typeof b=="string"){if(!oH.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,p,h){if(p!==void 0&&!XF(d,p))throw l(h)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Mt.getSchemaRefs=sH});var Da=L(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.getData=qr.KeywordCxt=qr.validateFunctionCode=void 0;var tT=CE(),XE=Oa(),My=Ty(),xl=Oa(),iH=jE(),Na=UE(),Dy=ZE(),V=oe(),ee=ir(),aH=Ia(),ar=me(),Aa=Ca();function cH(t){if(oT(t)&&(sT(t),rT(t))){dH(t);return}nT(t,()=>(0,tT.topBoolOrEmptySchema)(t))}qr.validateFunctionCode=cH;function nT({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,V._)`${ee.default.data}, ${ee.default.valCxt}`,r.$async,()=>{t.code((0,V._)`"use strict"; ${YE(n,o)}`),lH(t,o),t.code(s)}):t.func(e,(0,V._)`${ee.default.data}, ${uH(o)}`,r.$async,()=>t.code(YE(n,o)).code(s))}function uH(t){return(0,V._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,V._)`, ${ee.default.dynamicAnchors}={}`:V.nil}}={}`}function lH(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,V._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,V._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,V._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,V._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,V._)`""`),t.var(ee.default.parentData,(0,V._)`undefined`),t.var(ee.default.parentDataProperty,(0,V._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,V._)`{}`)})}function dH(t){let{schema:e,opts:n,gen:r}=t;nT(t,()=>{n.$comment&&e.$comment&&aT(t),gH(t),r.let(ee.default.vErrors,null),r.let(ee.default.errors,0),n.unevaluated&&pH(t),iT(t),bH(t)})}function pH(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,V._)`${n}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function YE(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${n} */`:V.nil}function mH(t,e){if(oT(t)&&(sT(t),rT(t))){fH(t,e);return}(0,tT.boolOrEmptySchema)(t,e)}function rT({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function oT(t){return typeof t.schema!="boolean"}function fH(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&aT(t),yH(t),_H(t);let s=r.const("_errs",ee.default.errors);iT(t,s),r.var(e,(0,V._)`${s} === ${ee.default.errors}`)}function sT(t){(0,ar.checkUnknownRules)(t),hH(t)}function iT(t,e){if(t.opts.jtd)return QE(t,[],!1,e);let n=(0,XE.getSchemaTypes)(t.schema),r=(0,XE.coerceAndCheckDataType)(t,n);QE(t,n,!r,e)}function hH(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ar.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function gH(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ar.checkStrictMode)(t,"default is ignored in the schema root")}function yH(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,aH.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function _H(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function aT({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)t.code((0,V._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function bH(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,V._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,V._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,V._)`${r}.errors`,ee.default.vErrors),s.unevaluated&&xH(t),e.return((0,V._)`${ee.default.errors} === 0`))}function xH({gen:t,evaluated:e,props:n,items:r}){n instanceof V.Name&&t.assign((0,V._)`${e}.props`,n),r instanceof V.Name&&t.assign((0,V._)`${e}.items`,r)}function QE(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ar.schemaHasRulesButRef)(s,l))){o.block(()=>uT(t,"$ref",l.all.$ref.definition));return}c.jtd||SH(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,My.shouldUseGroup)(s,p)&&(p.type?(o.if((0,xl.checkDataType)(p.type,i,c.strictNumbers)),eT(t,p),e.length===1&&e[0]===p.type&&n&&(o.else(),(0,xl.reportTypeError)(t)),o.endIf()):eT(t,p),a||o.if((0,V._)`${ee.default.errors} === ${r||0}`))}}function eT(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,iH.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,My.shouldUseRule)(r,s)&&uT(t,s.keyword,s.definition,e.type)})}function SH(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(vH(t,e),t.opts.allowUnionTypes||kH(t,e),wH(t,t.dataTypes))}function vH(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{cT(t.dataTypes,n)||jy(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),TH(t,e)}}function kH(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&jy(t,"use allowUnionTypes to allow union type keyword")}function wH(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,My.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>EH(e,i))&&jy(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function EH(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function cT(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function TH(t,e){let n=[];for(let r of t.dataTypes)cT(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function jy(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ar.checkStrictMode)(t,e,t.opts.strictTypes)}var Sl=class{constructor(e,n,r){if((0,Na.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ar.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",lT(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Na.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,n,r){this.failResult((0,V.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,V.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,V._)`${n} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?Aa.reportExtraError:Aa.reportError)(this,this.def.error,n)}$dataError(){(0,Aa.reportError)(this,this.def.$dataError||Aa.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Aa.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=V.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=V.nil,n=V.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,V.or)((0,V._)`${o} === undefined`,n)),e!==V.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(r.length){if(!(n instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,V._)`${(0,xl.checkDataTypes)(c,n,s.opts.strictNumbers,xl.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${n})`}return V.nil}}subschema(e,n){let r=(0,Dy.getSubschema)(this.it,e);(0,Dy.extendSubschemaData)(r,this.it,e),(0,Dy.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return mH(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ar.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ar.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,V.Name)),!0}};qr.KeywordCxt=Sl;function uT(t,e,n,r){let o=new Sl(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Na.funcKeywordCode)(o,n):"macro"in n?(0,Na.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Na.funcKeywordCode)(o,n)}var $H=/^\/(?:[^~]|~0|~1)*$/,PH=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lT(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!$H.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=PH.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,V._)`${s}${(0,V.getProperty)((0,ar.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}qr.getData=lT});var vl=L(zy=>{"use strict";Object.defineProperty(zy,"__esModule",{value:!0});var Ly=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};zy.default=Ly});var Ma=L(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});var Fy=Ia(),Hy=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Fy.resolveUrl)(e,n,r),this.missingSchema=(0,Fy.normalizeId)((0,Fy.getFullPath)(e,this.missingRef))}};Uy.default=Hy});var wl=L(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.resolveSchema=ln.getCompilingSchema=ln.resolveRef=ln.compileSchema=ln.SchemaEnv=void 0;var bn=oe(),RH=vl(),Wo=ir(),xn=Ia(),dT=me(),CH=Da(),Ys=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,xn.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};ln.SchemaEnv=Ys;function Zy(t){let e=pT.call(this,t);if(e)return e;let n=(0,xn.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new bn.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:RH.default,code:(0,bn._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Wo.default.data,parentData:Wo.default.parentData,parentDataProperty:Wo.default.parentDataProperty,dataNames:[Wo.default.data],dataPathArr:[bn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,bn.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:bn.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,bn._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,CH.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Wo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let h=new Function(`${Wo.default.self}`,`${Wo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:f}=u;h.evaluated={props:m instanceof bn.Name?void 0:m,items:f instanceof bn.Name?void 0:f,dynamicProps:m instanceof bn.Name,dynamicItems:f instanceof bn.Name},h.source&&(h.source.evaluated=(0,bn.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}ln.compileSchema=Zy;function OH(t,e,n){var r;n=(0,xn.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=NH.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Ys({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=IH.call(this,s)}ln.resolveRef=OH;function IH(t){return(0,xn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Zy.call(this,t)}function pT(t){for(let e of this._compilations)if(AH(e,t))return e}ln.getCompilingSchema=pT;function AH(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function NH(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||kl.call(this,t,e)}function kl(t,e){let n=this.opts.uriResolver.parse(e),r=(0,xn._getFullPath)(this.opts.uriResolver,n),o=(0,xn.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return By.call(this,n,t);let s=(0,xn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=kl.call(this,t,i);return typeof a?.schema!="object"?void 0:By.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Zy.call(this,i),s===(0,xn.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,xn.resolveUrl)(this.opts.uriResolver,o,u)),new Ys({schema:a,schemaId:c,root:t,baseId:o})}return By.call(this,n,i)}}ln.resolveSchema=kl;var DH=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function By(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,dT.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!DH.has(a)&&u&&(e=(0,xn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,dT.schemaHasRulesButRef)(n,this.RULES)){let a=(0,xn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=kl.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Ys({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var mT=L((oX,MH)=>{MH.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Vy=L((sX,yT)=>{"use strict";var jH=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),hT=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function qy(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var LH=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fT(t){return t.length=0,!0}function zH(t,e,n){if(t.length){let r=qy(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function FH(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=zH;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=fT}else{o.push(u);continue}}return o.length&&(a===fT?n.zone=o.join(""):i?r.push(o.join("")):r.push(qy(o))),n.address=r.join(""),n}function gT(t){if(HH(t,":")<2)return{host:t,isIPV6:!1};let e=FH(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function HH(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function UH(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function BH(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function ZH(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!hT(n)){let r=gT(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}yT.exports={nonSimpleDomain:LH,recomposeAuthority:ZH,normalizeComponentEncoding:BH,removeDotSegments:UH,isIPv4:hT,isUUID:jH,normalizeIPv6:gT,stringArrayToHexStripped:qy}});var vT=L((iX,ST)=>{"use strict";var{isUUID:qH}=Vy(),VH=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,WH=["http","https","ws","wss","urn","urn:uuid"];function KH(t){return WH.indexOf(t)!==-1}function Wy(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function _T(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function bT(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function GH(t){return t.secure=Wy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function JH(t){if((t.port===(Wy(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function XH(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(VH);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=Ky(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function YH(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=Ky(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function QH(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!qH(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function eU(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var xT={scheme:"http",domainHost:!0,parse:_T,serialize:bT},tU={scheme:"https",domainHost:xT.domainHost,parse:_T,serialize:bT},El={scheme:"ws",domainHost:!0,parse:GH,serialize:JH},nU={scheme:"wss",domainHost:El.domainHost,parse:El.parse,serialize:El.serialize},rU={scheme:"urn",parse:XH,serialize:YH,skipNormalize:!0},oU={scheme:"urn:uuid",parse:QH,serialize:eU,skipNormalize:!0},Tl={http:xT,https:tU,ws:El,wss:nU,urn:rU,"urn:uuid":oU};Object.setPrototypeOf(Tl,null);function Ky(t){return t&&(Tl[t]||Tl[t.toLowerCase()])||void 0}ST.exports={wsIsSecure:Wy,SCHEMES:Tl,isValidSchemeName:KH,getSchemeHandler:Ky}});var ET=L((aX,Pl)=>{"use strict";var{normalizeIPv6:sU,removeDotSegments:ja,recomposeAuthority:iU,normalizeComponentEncoding:$l,isIPv4:aU,nonSimpleDomain:cU}=Vy(),{SCHEMES:uU,getSchemeHandler:kT}=vT();function lU(t,e){return typeof t=="string"?t=Fn(cr(t,e),e):typeof t=="object"&&(t=cr(Fn(t,e),e)),t}function dU(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=wT(cr(t,r),cr(e,r),r,!0);return r.skipEscape=!0,Fn(o,r)}function wT(t,e,n,r){let o={};return r||(t=cr(Fn(t,n),n),e=cr(Fn(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ja(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ja(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ja(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ja(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function pU(t,e,n){return typeof t=="string"?(t=unescape(t),t=Fn($l(cr(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Fn($l(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Fn($l(cr(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Fn($l(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Fn(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],s=kT(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let i=iU(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=ja(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var mU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function cr(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let s=t.match(mU);if(s){if(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5]),r.host)if(aU(r.host)===!1){let c=sU(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let i=kT(n.scheme||r.scheme);if(!n.unicodeSupport&&(!i||!i.unicodeSupport)&&r.host&&(n.domainHost||i&&i.domainHost)&&o===!1&&cU(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),i&&i.parse&&i.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var Gy={SCHEMES:uU,normalize:lU,resolve:dU,resolveComponent:wT,equal:pU,serialize:Fn,parse:cr};Pl.exports=Gy;Pl.exports.default=Gy;Pl.exports.fastUri=Gy});var $T=L(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var TT=ET();TT.code='require("ajv/dist/runtime/uri").default';Jy.default=TT});var DT=L(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.CodeGen=dt.Name=dt.nil=dt.stringify=dt.str=dt._=dt.KeywordCxt=void 0;var fU=Da();Object.defineProperty(dt,"KeywordCxt",{enumerable:!0,get:function(){return fU.KeywordCxt}});var Qs=oe();Object.defineProperty(dt,"_",{enumerable:!0,get:function(){return Qs._}});Object.defineProperty(dt,"str",{enumerable:!0,get:function(){return Qs.str}});Object.defineProperty(dt,"stringify",{enumerable:!0,get:function(){return Qs.stringify}});Object.defineProperty(dt,"nil",{enumerable:!0,get:function(){return Qs.nil}});Object.defineProperty(dt,"Name",{enumerable:!0,get:function(){return Qs.Name}});Object.defineProperty(dt,"CodeGen",{enumerable:!0,get:function(){return Qs.CodeGen}});var hU=vl(),IT=Ma(),gU=Ey(),La=wl(),yU=oe(),za=Ia(),Rl=Oa(),Yy=me(),PT=mT(),_U=$T(),AT=(t,e)=>new RegExp(t,e);AT.code="new RegExp";var bU=["removeAdditional","useDefaults","coerceTypes"],xU=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),SU={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},vU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},RT=200;function kU(t){var e,n,r,o,s,i,a,c,u,l,d,p,h,m,f,g,y,_,b,S,E,A,x,T,P;let N=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,C=R===!0||R===void 0?1:R||0,F=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:AT,W=(o=t.uriResolver)!==null&&o!==void 0?o:_U.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:N)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:N)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:N)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:N)!==null&&p!==void 0?p:"log",strictRequired:(m=(h=t.strictRequired)!==null&&h!==void 0?h:N)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:C,regExp:F}:{optimize:C,regExp:F},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:RT,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:RT,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(A=t.validateSchema)!==null&&A!==void 0?A:!0,validateFormats:(x=t.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(T=t.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:W}}var Fa=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...kU(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new yU.ValueScope({scope:{},prefixes:xU,es5:n,lines:r}),this.logger=RU(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,gU.getRules)(),CT.call(this,SU,e,"NOT SUPPORTED"),CT.call(this,vU,e,"DEPRECATED","warn"),this._metaOpts=$U.call(this),e.formats&&EU.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&TU.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),wU.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=PT;r==="id"&&(o={...PT},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof IT.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return n=(0,za.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let n;for(;typeof(n=OT.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new La.SchemaEnv({schema:{},schemaId:r});if(n=La.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=OT.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,za.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(OU.call(this,r,n),!n)return(0,Yy.eachItem)(r,s=>Xy.call(this,s)),this;AU.call(this,n);let o={...n,type:(0,Rl.getJSONTypes)(n.type),schemaType:(0,Rl.getJSONTypes)(n.schemaType)};return(0,Yy.eachItem)(r,o.type.length===0?s=>Xy.call(this,s,o):s=>o.type.forEach(i=>Xy.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=NT(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,za.normalizeId)(i||r);let u=za.getSchemaRefs.call(this,e,r);return c=new La.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):La.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{La.compileSchema.call(this,e)}finally{this.opts=n}}};Fa.ValidationError=hU.default;Fa.MissingRefError=IT.default;dt.default=Fa;function CT(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function OT(t){return t=(0,za.normalizeId)(t),this.schemas[t]||this.refs[t]}function wU(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function EU(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function TU(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function $U(){let t={...this.opts};for(let e of bU)delete t[e];return t}var PU={log(){},warn(){},error(){}};function RU(t){if(t===!1)return PU;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var CU=/^[a-z_$][a-z0-9_$:-]*$/i;function OU(t,e){let{RULES:n}=this;if((0,Yy.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!CU.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Xy(t,e,n){var r;let o=e?.post;if(n&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Rl.getJSONTypes)(e.type),schemaType:(0,Rl.getJSONTypes)(e.schemaType)}};e.before?IU.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function IU(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function AU(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=NT(e)),t.validateSchema=this.compile(e,!0))}var NU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function NT(t){return{anyOf:[t,NU]}}});var MT=L(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var DU={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Qy.default=DU});var FT=L(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.callRef=Ko.getValidate=void 0;var MU=Ma(),jT=un(),jt=oe(),ei=ir(),LT=wl(),Cl=me(),jU={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=LT.resolveRef.call(c,u,o,n);if(l===void 0)throw new MU.default(r.opts.uriResolver,o,n);if(l instanceof LT.SchemaEnv)return p(l);return h(l);function d(){if(s===u)return Ol(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Ol(t,(0,jt._)`${m}.validate`,u,u.$async)}function p(m){let f=zT(t,m);Ol(t,f,m,m.$async)}function h(m){let f=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,jt.stringify)(m)}:{ref:m}),g=e.name("valid"),y=t.subschema({schema:m,dataTypes:[],schemaPath:jt.nil,topSchemaRef:f,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function zT(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,jt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Ko.getValidate=zT;function Ol(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ei.default.this:jt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,jt._)`await ${(0,jT.callValidateCode)(t,e,u)}`),h(e),i||o.assign(m,!0)},f=>{o.if((0,jt._)`!(${f} instanceof ${s.ValidationError})`,()=>o.throw(f)),p(f),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,jT.callValidateCode)(t,e,u),()=>h(e),()=>p(e))}function p(m){let f=(0,jt._)`${m}.errors`;o.assign(ei.default.vErrors,(0,jt._)`${ei.default.vErrors} === null ? ${f} : ${ei.default.vErrors}.concat(${f})`),o.assign(ei.default.errors,(0,jt._)`${ei.default.vErrors}.length`)}function h(m){var f;if(!s.opts.unevaluated)return;let g=(f=n?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Cl.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,jt._)`${m}.evaluated.props`);s.props=Cl.mergeEvaluated.props(o,y,s.props,jt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Cl.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,jt._)`${m}.evaluated.items`);s.items=Cl.mergeEvaluated.items(o,y,s.items,jt.Name)}}}Ko.callRef=Ol;Ko.default=jU});var HT=L(e_=>{"use strict";Object.defineProperty(e_,"__esModule",{value:!0});var LU=MT(),zU=FT(),FU=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",LU.default,zU.default];e_.default=FU});var UT=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var Il=oe(),Vr=Il.operators,Al={maximum:{okStr:"<=",ok:Vr.LTE,fail:Vr.GT},minimum:{okStr:">=",ok:Vr.GTE,fail:Vr.LT},exclusiveMaximum:{okStr:"<",ok:Vr.LT,fail:Vr.GTE},exclusiveMinimum:{okStr:">",ok:Vr.GT,fail:Vr.LTE}},HU={message:({keyword:t,schemaCode:e})=>(0,Il.str)`must be ${Al[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Il._)`{comparison: ${Al[t].okStr}, limit: ${e}}`},UU={keyword:Object.keys(Al),type:"number",schemaType:"number",$data:!0,error:HU,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Il._)`${n} ${Al[e].fail} ${r} || isNaN(${n})`)}};t_.default=UU});var BT=L(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var Ha=oe(),BU={message:({schemaCode:t})=>(0,Ha.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ha._)`{multipleOf: ${t}}`},ZU={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:BU,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ha._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ha._)`${i} !== parseInt(${i})`;t.fail$data((0,Ha._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};n_.default=ZU});var qT=L(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});function ZT(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}r_.default=ZT;ZT.code='require("ajv/dist/runtime/ucs2length").default'});var VT=L(o_=>{"use strict";Object.defineProperty(o_,"__esModule",{value:!0});var Go=oe(),qU=me(),VU=qT(),WU={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Go.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Go._)`{limit: ${t}}`},KU={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:WU,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Go.operators.GT:Go.operators.LT,i=o.opts.unicode===!1?(0,Go._)`${n}.length`:(0,Go._)`${(0,qU.useFunc)(t.gen,VU.default)}(${n})`;t.fail$data((0,Go._)`${i} ${s} ${r}`)}};o_.default=KU});var WT=L(s_=>{"use strict";Object.defineProperty(s_,"__esModule",{value:!0});var GU=un(),JU=me(),ti=oe(),XU={message:({schemaCode:t})=>(0,ti.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ti._)`{pattern: ${t}}`},YU={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XU,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ti._)`new RegExp`:(0,JU.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ti._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,ti._)`!${l}`)}else{let c=(0,GU.usePattern)(t,o);t.fail$data((0,ti._)`!${c}.test(${n})`)}}};s_.default=YU});var KT=L(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});var Ua=oe(),QU={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ua.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ua._)`{limit: ${t}}`},e2={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:QU,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ua.operators.GT:Ua.operators.LT;t.fail$data((0,Ua._)`Object.keys(${n}).length ${o} ${r}`)}};i_.default=e2});var GT=L(a_=>{"use strict";Object.defineProperty(a_,"__esModule",{value:!0});var Ba=un(),Za=oe(),t2=me(),n2={message:({params:{missingProperty:t}})=>(0,Za.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Za._)`{missingProperty: ${t}}`},r2={keyword:"required",type:"object",schemaType:"array",$data:!0,error:n2,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:m}=t.it;for(let f of n)if(h?.[f]===void 0&&!m.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,t2.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Za.nil,d);else for(let h of n)(0,Ba.checkReportMissingProp)(t,h)}function l(){let h=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(h,m)),t.ok(m)}else e.if((0,Ba.checkMissingProp)(t,n,h)),(0,Ba.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",r,h=>{t.setParams({missingProperty:h}),e.if((0,Ba.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function p(h,m){t.setParams({missingProperty:h}),e.forOf(h,r,()=>{e.assign(m,(0,Ba.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Za.not)(m),()=>{t.error(),e.break()})},Za.nil)}}};a_.default=r2});var JT=L(c_=>{"use strict";Object.defineProperty(c_,"__esModule",{value:!0});var qa=oe(),o2={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,qa.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,qa._)`{limit: ${t}}`},s2={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:o2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?qa.operators.GT:qa.operators.LT;t.fail$data((0,qa._)`${n}.length ${o} ${r}`)}};c_.default=s2});var Nl=L(u_=>{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});var XT=Ay();XT.code='require("ajv/dist/runtime/equal").default';u_.default=XT});var YT=L(d_=>{"use strict";Object.defineProperty(d_,"__esModule",{value:!0});var l_=Oa(),pt=oe(),i2=me(),a2=Nl(),c2={message:({params:{i:t,j:e}})=>(0,pt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pt._)`{i: ${t}, j: ${e}}`},u2={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:c2,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,l_.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,pt._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,pt._)`${n}.length`),f=e.let("j");t.setParams({i:m,j:f}),e.assign(c,!0),e.if((0,pt._)`${m} > 1`,()=>(d()?p:h)(m,f))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,f){let g=e.name("item"),y=(0,l_.checkDataTypes)(u,g,a.opts.strictNumbers,l_.DataType.Wrong),_=e.const("indices",(0,pt._)`{}`);e.for((0,pt._)`;${m}--;`,()=>{e.let(g,(0,pt._)`${n}[${m}]`),e.if(y,(0,pt._)`continue`),u.length>1&&e.if((0,pt._)`typeof ${g} == "string"`,(0,pt._)`${g} += "_"`),e.if((0,pt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(f,(0,pt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,pt._)`${_}[${g}] = ${m}`)})}function h(m,f){let g=(0,i2.useFunc)(e,a2.default),y=e.name("outer");e.label(y).for((0,pt._)`;${m}--;`,()=>e.for((0,pt._)`${f} = ${m}; ${f}--;`,()=>e.if((0,pt._)`${g}(${n}[${m}], ${n}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};d_.default=u2});var QT=L(m_=>{"use strict";Object.defineProperty(m_,"__esModule",{value:!0});var p_=oe(),l2=me(),d2=Nl(),p2={message:"must be equal to constant",params:({schemaCode:t})=>(0,p_._)`{allowedValue: ${t}}`},m2={keyword:"const",$data:!0,error:p2,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,p_._)`!${(0,l2.useFunc)(e,d2.default)}(${n}, ${o})`):t.fail((0,p_._)`${s} !== ${n}`)}};m_.default=m2});var e$=L(f_=>{"use strict";Object.defineProperty(f_,"__esModule",{value:!0});var Va=oe(),f2=me(),h2=Nl(),g2={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Va._)`{allowedValues: ${t}}`},y2={keyword:"enum",schemaType:"array",$data:!0,error:g2,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,f2.useFunc)(e,h2.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);l=(0,Va.or)(...o.map((m,f)=>p(h,f)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,h=>e.if((0,Va._)`${u()}(${n}, ${h})`,()=>e.assign(l,!0).break()))}function p(h,m){let f=o[m];return typeof f=="object"&&f!==null?(0,Va._)`${u()}(${n}, ${h}[${m}])`:(0,Va._)`${n} === ${f}`}}};f_.default=y2});var t$=L(h_=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});var _2=UT(),b2=BT(),x2=VT(),S2=WT(),v2=KT(),k2=GT(),w2=JT(),E2=YT(),T2=QT(),$2=e$(),P2=[_2.default,b2.default,x2.default,S2.default,v2.default,k2.default,w2.default,E2.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},T2.default,$2.default];h_.default=P2});var y_=L(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.validateAdditionalItems=void 0;var Jo=oe(),g_=me(),R2={message:({params:{len:t}})=>(0,Jo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Jo._)`{limit: ${t}}`},C2={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:R2,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,g_.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}n$(t,r)}};function n$(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Jo._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Jo._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,g_.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Jo._)`${a} <= ${e.length}`);n.if((0,Jo.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:g_.Type.Num},u),i.allErrors||n.if((0,Jo.not)(u),()=>n.break())})}}Wa.validateAdditionalItems=n$;Wa.default=C2});var __=L(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.validateTuple=void 0;var r$=oe(),Dl=me(),O2=un(),I2={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return o$(t,"additionalItems",e);n.items=!0,!(0,Dl.alwaysValidSchema)(n,e)&&t.ok((0,O2.validateArray)(t))}};function o$(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Dl.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,r$._)`${s}.length`);n.forEach((d,p)=>{(0,Dl.alwaysValidSchema)(a,d)||(r.if((0,r$._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:h}=a,m=n.length,f=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!f){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Dl.checkStrictMode)(a,g,p.strictTuples)}}}Ka.validateTuple=o$;Ka.default=I2});var s$=L(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var A2=__(),N2={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,A2.validateTuple)(t,"items")};b_.default=N2});var a$=L(x_=>{"use strict";Object.defineProperty(x_,"__esModule",{value:!0});var i$=oe(),D2=me(),M2=un(),j2=y_(),L2={message:({params:{len:t}})=>(0,i$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,i$._)`{limit: ${t}}`},z2={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:L2,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,D2.alwaysValidSchema)(r,e)&&(o?(0,j2.validateAdditionalItems)(t,o):t.ok((0,M2.validateArray)(t)))}};x_.default=z2});var c$=L(S_=>{"use strict";Object.defineProperty(S_,"__esModule",{value:!0});var dn=oe(),Ml=me(),F2={message:({params:{min:t,max:e}})=>e===void 0?(0,dn.str)`must contain at least ${t} valid item(s)`:(0,dn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dn._)`{minContains: ${t}}`:(0,dn._)`{minContains: ${t}, maxContains: ${e}}`},H2={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:F2,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,dn._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ml.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ml.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ml.alwaysValidSchema)(s,n)){let f=(0,dn._)`${l} >= ${i}`;a!==void 0&&(f=(0,dn._)`${f} && ${l} <= ${a}`),t.pass(f);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dn._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>m(g)))}function h(f,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Ml.Type.Num,compositeRule:!0},f),g()})}function m(f){e.code((0,dn._)`${f}++`),a===void 0?e.if((0,dn._)`${f} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dn._)`${f} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dn._)`${f} >= ${i}`,()=>e.assign(d,!0)))}}};S_.default=H2});var d$=L(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.validateSchemaDeps=Hn.validatePropertyDeps=Hn.error=void 0;var v_=oe(),U2=me(),Ga=un();Hn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,v_.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,v_._)`{property: ${t},
495
- missingProperty: ${r},
496
- depsCount: ${e},
497
- deps: ${n}}`};var B2={keyword:"dependencies",type:"object",schemaType:"object",error:Hn.error,code(t){let[e,n]=Z2(t);u$(t,e),l$(t,n)}};function Z2({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function u$(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ga.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Ga.checkReportMissingProp)(t,u)}):(n.if((0,v_._)`${c} && (${(0,Ga.checkMissingProp)(t,a,s)})`),(0,Ga.reportMissingProp)(t,s),n.else())}}Hn.validatePropertyDeps=u$;function l$(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,U2.alwaysValidSchema)(s,e[a])||(n.if((0,Ga.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}Hn.validateSchemaDeps=l$;Hn.default=B2});var m$=L(k_=>{"use strict";Object.defineProperty(k_,"__esModule",{value:!0});var p$=oe(),q2=me(),V2={message:"property name must be valid",params:({params:t})=>(0,p$._)`{propertyName: ${t.propertyName}}`},W2={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:V2,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,q2.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,p$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};k_.default=W2});var E_=L(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var jl=un(),Sn=oe(),K2=ir(),Ll=me(),G2={message:"must NOT have additional properties",params:({params:t})=>(0,Sn._)`{additionalProperty: ${t.additionalProperty}}`},J2={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:G2,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Ll.alwaysValidSchema)(i,n))return;let u=(0,jl.allSchemaProperties)(r.properties),l=(0,jl.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Sn._)`${s} === ${K2.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let _=(0,Ll.schemaRefOrVal)(i,r.properties,"properties");y=(0,jl.isOwnProperty)(e,_,g)}else u.length?y=(0,Sn.or)(...u.map(_=>(0,Sn._)`${g} === ${_}`)):y=Sn.nil;return l.length&&(y=(0,Sn.or)(y,...l.map(_=>(0,Sn._)`${(0,jl.usePattern)(t,_)}.test(${g})`))),(0,Sn.not)(y)}function h(g){e.code((0,Sn._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Ll.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,Sn.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,Sn.not)(y),()=>e.break()))}}function f(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:Ll.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};w_.default=J2});var g$=L($_=>{"use strict";Object.defineProperty($_,"__esModule",{value:!0});var X2=Da(),f$=un(),T_=me(),h$=E_(),Y2={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&h$.default.code(new X2.KeywordCxt(s,h$.default,"additionalProperties"));let i=(0,f$.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=T_.mergeEvaluated.props(e,(0,T_.toHash)(i),s.props));let a=i.filter(d=>!(0,T_.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,f$.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};$_.default=Y2});var x$=L(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var y$=un(),zl=oe(),_$=me(),b$=me(),Q2={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,y$.allSchemaProperties)(n),c=a.filter(f=>(0,_$.alwaysValidSchema)(s,n[f]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof zl.Name)&&(s.props=(0,b$.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let f of a)u&&h(f),s.allErrors?m(f):(e.var(l,!0),m(f),e.if(l))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,_$.checkStrictMode)(s,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function m(f){e.forIn("key",r,g=>{e.if((0,zl._)`${(0,y$.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:b$.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,zl._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,zl.not)(l),()=>e.break())})})}}};P_.default=Q2});var S$=L(R_=>{"use strict";Object.defineProperty(R_,"__esModule",{value:!0});var eB=me(),tB={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,eB.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};R_.default=tB});var v$=L(C_=>{"use strict";Object.defineProperty(C_,"__esModule",{value:!0});var nB=un(),rB={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:nB.validateUnion,error:{message:"must match a schema in anyOf"}};C_.default=rB});var k$=L(O_=>{"use strict";Object.defineProperty(O_,"__esModule",{value:!0});var Fl=oe(),oB=me(),sB={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Fl._)`{passingSchemas: ${t.passing}}`},iB={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:sB,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,oB.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Fl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Fl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Fl.Name)})})}}};O_.default=iB});var w$=L(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var aB=me(),cB={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,aB.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};I_.default=cB});var $$=L(A_=>{"use strict";Object.defineProperty(A_,"__esModule",{value:!0});var Hl=oe(),T$=me(),uB={message:({params:t})=>(0,Hl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Hl._)`{failingKeyword: ${t.ifClause}}`},lB={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:uB,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,T$.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=E$(r,"then"),s=E$(r,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Hl.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Hl._)`${l}`):t.setParams({ifClause:l})}}}};function E$(t,e){let n=t.schema[e];return n!==void 0&&!(0,T$.alwaysValidSchema)(t,n)}A_.default=lB});var P$=L(N_=>{"use strict";Object.defineProperty(N_,"__esModule",{value:!0});var dB=me(),pB={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,dB.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};N_.default=pB});var R$=L(D_=>{"use strict";Object.defineProperty(D_,"__esModule",{value:!0});var mB=y_(),fB=s$(),hB=__(),gB=a$(),yB=c$(),_B=d$(),bB=m$(),xB=E_(),SB=g$(),vB=x$(),kB=S$(),wB=v$(),EB=k$(),TB=w$(),$B=$$(),PB=P$();function RB(t=!1){let e=[kB.default,wB.default,EB.default,TB.default,$B.default,PB.default,bB.default,xB.default,_B.default,SB.default,vB.default];return t?e.push(fB.default,gB.default):e.push(mB.default,hB.default),e.push(yB.default),e}D_.default=RB});var C$=L(M_=>{"use strict";Object.defineProperty(M_,"__esModule",{value:!0});var Ve=oe(),CB={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},OB={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CB,code(t,e){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():h();function p(){let m=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),f=n.const("fDef",(0,Ve._)`${m}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Ve._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>n.assign(g,(0,Ve._)`${f}.type || "string"`).assign(y,(0,Ve._)`${f}.validate`),()=>n.assign(g,(0,Ve._)`"string"`).assign(y,f)),t.fail$data((0,Ve.or)(_(),b()));function _(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${y}`}function b(){let S=l.$async?(0,Ve._)`(${f}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Ve._)`${y}(${r})`,E=(0,Ve._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${r}))`;return(0,Ve._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function h(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[f,g,y]=b(m);f===e&&t.pass(S());function _(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(E){let A=E instanceof RegExp?(0,Ve.regexpCode)(E):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,x=n.scopeValue("formats",{key:s,ref:E,code:A});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Ve._)`${x}.validate`]:["string",E,x]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${y}(${r})`}return typeof g=="function"?(0,Ve._)`${y}(${r})`:(0,Ve._)`${y}.test(${r})`}}}};M_.default=OB});var O$=L(j_=>{"use strict";Object.defineProperty(j_,"__esModule",{value:!0});var IB=C$(),AB=[IB.default];j_.default=AB});var I$=L(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.contentVocabulary=ni.metadataVocabulary=void 0;ni.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ni.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var N$=L(L_=>{"use strict";Object.defineProperty(L_,"__esModule",{value:!0});var NB=HT(),DB=t$(),MB=R$(),jB=O$(),A$=I$(),LB=[NB.default,DB.default,(0,MB.default)(),jB.default,A$.metadataVocabulary,A$.contentVocabulary];L_.default=LB});var M$=L(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});Ul.DiscrError=void 0;var D$;(function(t){t.Tag="tag",t.Mapping="mapping"})(D$||(Ul.DiscrError=D$={}))});var L$=L(F_=>{"use strict";Object.defineProperty(F_,"__esModule",{value:!0});var ri=oe(),z_=M$(),j$=wl(),zB=Ma(),FB=me(),HB={message:({params:{discrError:t,tagName:e}})=>t===z_.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,ri._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},UB={keyword:"discriminator",type:"object",schemaType:"object",error:HB,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,ri._)`${n}${(0,ri.getProperty)(a)}`);e.if((0,ri._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:z_.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let h=p();e.if(!1);for(let m in h)e.elseIf((0,ri._)`${u} === ${m}`),e.assign(c,d(h[m]));e.else(),t.error(!1,{discrError:z_.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(h){let m=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},m);return t.mergeEvaluated(f,ri.Name),m}function p(){var h;let m={},f=y(o),g=!0;for(let S=0;S<i.length;S++){let E=i[S];if(E?.$ref&&!(0,FB.schemaHasRulesButRef)(E,s.self.RULES)){let x=E.$ref;if(E=j$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),E instanceof j$.SchemaEnv&&(E=E.schema),E===void 0)throw new zB.default(s.opts.uriResolver,s.baseId,x)}let A=(h=E?.properties)===null||h===void 0?void 0:h[a];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(E)),_(A,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function _(S,E){if(S.const)b(S.const,E);else if(S.enum)for(let A of S.enum)b(A,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(S,E){if(typeof S!="string"||S in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[S]=E}}}};F_.default=UB});var z$=L((GX,BB)=>{BB.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var U_=L((Ie,H_)=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.MissingRefError=Ie.ValidationError=Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=Ie.Ajv=void 0;var ZB=DT(),qB=N$(),VB=L$(),F$=z$(),WB=["/properties"],Bl="http://json-schema.org/draft-07/schema",oi=class extends ZB.default{_addVocabularies(){super._addVocabularies(),qB.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(VB.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(F$,WB):F$;this.addMetaSchema(e,Bl,!1),this.refs["http://json-schema.org/schema"]=Bl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Bl)?Bl:void 0)}};Ie.Ajv=oi;H_.exports=Ie=oi;H_.exports.Ajv=oi;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.default=oi;var KB=Da();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return KB.KeywordCxt}});var si=oe();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return si._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return si.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return si.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return si.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return si.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return si.CodeGen}});var GB=vl();Object.defineProperty(Ie,"ValidationError",{enumerable:!0,get:function(){return GB.default}});var JB=Ma();Object.defineProperty(Ie,"MissingRefError",{enumerable:!0,get:function(){return JB.default}})});var K$=L(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.formatNames=Bn.fastFormats=Bn.fullFormats=void 0;function Un(t,e){return{validate:t,compare:e}}Bn.fullFormats={date:Un(Z$,V_),time:Un(Z_(!0),W_),"date-time":Un(H$(!0),V$),"iso-time":Un(Z_(),q$),"iso-date-time":Un(H$(),W$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nZ,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:uZ,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:rZ,int32:{type:"number",validate:iZ},int64:{type:"number",validate:aZ},float:{type:"number",validate:B$},double:{type:"number",validate:B$},password:!0,binary:!0};Bn.fastFormats={...Bn.fullFormats,date:Un(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,V_),time:Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,W_),"date-time":Un(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,V$),"iso-time":Un(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,q$),"iso-date-time":Un(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,W$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Bn.formatNames=Object.keys(Bn.fullFormats);function XB(t){return t%4===0&&(t%100!==0||t%400===0)}var YB=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,QB=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Z$(t){let e=YB.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&XB(n)?29:QB[r])}function V_(t,e){if(t&&e)return t>e?1:t<e?-1:0}var B_=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Z_(t){return function(n){let r=B_.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function W_(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function q$(t,e){if(!(t&&e))return;let n=B_.exec(t),r=B_.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var q_=/t|\s/i;function H$(t){let e=Z_(t);return function(r){let o=r.split(q_);return o.length===2&&Z$(o[0])&&e(o[1])}}function V$(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function W$(t,e){if(!(t&&e))return;let[n,r]=t.split(q_),[o,s]=e.split(q_),i=V_(n,o);if(i!==void 0)return i||W_(r,s)}var eZ=/\/|:/,tZ=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function nZ(t){return eZ.test(t)&&tZ.test(t)}var U$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function rZ(t){return U$.lastIndex=0,U$.test(t)}var oZ=-(2**31),sZ=2**31-1;function iZ(t){return Number.isInteger(t)&&t<=sZ&&t>=oZ}function aZ(t){return Number.isInteger(t)}function B$(){return!0}var cZ=/[^\\]\\Z/;function uZ(t){if(cZ.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var G$=L(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.formatLimitDefinition=void 0;var lZ=U_(),vn=oe(),Wr=vn.operators,Zl={formatMaximum:{okStr:"<=",ok:Wr.LTE,fail:Wr.GT},formatMinimum:{okStr:">=",ok:Wr.GTE,fail:Wr.LT},formatExclusiveMaximum:{okStr:"<",ok:Wr.LT,fail:Wr.GTE},formatExclusiveMinimum:{okStr:">",ok:Wr.GT,fail:Wr.LTE}},dZ={message:({keyword:t,schemaCode:e})=>(0,vn.str)`should be ${Zl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vn._)`{comparison: ${Zl[t].okStr}, limit: ${e}}`};ii.formatLimitDefinition={keyword:Object.keys(Zl),type:"string",schemaType:"string",$data:!0,error:dZ,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new lZ.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,vn._)`${p}[${c.schemaCode}]`);t.fail$data((0,vn.or)((0,vn._)`typeof ${h} != "object"`,(0,vn._)`${h} instanceof RegExp`,(0,vn._)`typeof ${h}.compare != "function"`,d(h)))}function l(){let p=c.schema,h=a.formats[p];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:h,code:i.code.formats?(0,vn._)`${i.code.formats}${(0,vn.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,vn._)`${p}.compare(${n}, ${r}) ${Zl[o].fail} 0`}},dependencies:["format"]};var pZ=t=>(t.addKeyword(ii.formatLimitDefinition),t);ii.default=pZ});var Q$=L((Ja,Y$)=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var ai=K$(),mZ=G$(),K_=oe(),J$=new K_.Name("fullFormats"),fZ=new K_.Name("fastFormats"),G_=(t,e={keywords:!0})=>{if(Array.isArray(e))return X$(t,e,ai.fullFormats,J$),t;let[n,r]=e.mode==="fast"?[ai.fastFormats,fZ]:[ai.fullFormats,J$],o=e.formats||ai.formatNames;return X$(t,o,n,r),e.keywords&&(0,mZ.default)(t),t};G_.get=(t,e="full")=>{let r=(e==="fast"?ai.fastFormats:ai.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function X$(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,K_._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}Y$.exports=Ja=G_;Object.defineProperty(Ja,"__esModule",{value:!0});Ja.default=G_});function hZ(){let t=new eP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,tP.default)(t),t}var eP,tP,ql,nP=v(()=>{eP=xi(U_(),1),tP=xi(Q$(),1);ql=class{constructor(e){this._ajv=e??hZ()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var Vl,rP=v(()=>{Fo();Vl=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},xa,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Zs,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function oP(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function sP(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var iP=v(()=>{});var Wl,aP=v(()=>{fE();Fo();nP();ca();rP();iP();Wl=class extends ul{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ba.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new ql,this.setRequestHandler(lg,r=>this._oninitialize(r)),this.setNotificationHandler(dg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(_g,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=ba.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Vl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mE(this._capabilities,e)}setRequestHandler(e,n){let o=Mr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(rn(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Dr(Bs,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Z(K.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let m=Dr(Ls,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new Z(K.InvalidParams,`Invalid task creation result: ${f}`)}return m.data}let h=Dr(Xu,p);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new Z(K.InvalidParams,`Invalid tools/call result: ${m}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){sP(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&oP(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:mw.includes(n)?n:sg,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},zu)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},bg,n):this.request({method:"sampling/createMessage",params:e},xa,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Zs,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Zs,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(K.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},xg,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function J_(t){return!!t&&typeof t=="object"&&uP in t}function lP(t){return t[uP]?.complete}var uP,cP,dP=v(()=>{uP=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(cP||(cP={}))});var pP=v(()=>{});function yZ(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!gZ.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function _Z(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function X_(t){let e=yZ(t);return _Z(t,e.warnings),e.isValid}var gZ,mP=v(()=>{gZ=/^[A-Za-z0-9._-]{1,128}$/});var Kl,fP=v(()=>{Kl=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}}});var Gl=v(()=>{uu();uu()});function yP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function _P(t){return"_def"in t||"_zod"in t||yP(t)}function Y_(t){return typeof t!="object"||t===null||_P(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(yP)}function hP(t){if(t){if(Y_(t))return Lo(t);if(!_P(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function xZ(t){let e=Mr(t);return e?Object.entries(e).map(([n,r])=>{let o=L0(r),s=z0(r);return{name:n,description:o,required:!s}}):[]}function Kr(t){let n=Mr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Au(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function gP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Jl,bZ,Xa,bP=v(()=>{aP();ca();ry();Fo();dP();pP();mP();fP();Gl();Jl=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Wl(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Kl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Kr(zo)),this.server.assertCanSetRequestHandler(Kr(Bs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=Ms(n.inputSchema);return o?ey(o,{strictUnions:!0,pipeStrategy:"input"}):bZ})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=Ms(n.outputSchema);o&&(r.outputSchema=ey(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Bs,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new Z(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof Z&&r.code===K.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=Ms(e.inputSchema)??e.inputSchema,i=await Ou(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Iu(a);throw new Z(K.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new Z(K.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=Ms(e.outputSchema),s=await Ou(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Iu(i);throw new Z(K.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await r.taskStore.getTask(c);if(!d)throw new Z(K.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Kr(Yu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Yu,async e=>{switch(e.params.ref.type){case"ref/prompt":return Rw(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Cw(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Xa;let s=Mr(r.argsSchema)?.[e.params.argument.name];if(!J_(s))return Xa;let i=lP(s);if(!i)return Xa;let a=await i(e.params.argument.value,e.params.context);return gP(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return Xa;throw new Z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Xa;let s=await o(e.params.argument.value,e.params.context);return gP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Kr(Fs)),this.server.assertCanSetRequestHandler(Kr(Hs)),this.server.assertCanSetRequestHandler(Kr(Gu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Fs,async(e,n)=>{let r=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Hs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Gu,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new Z(K.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new Z(K.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Kr(Us)),this.server.assertCanSetRequestHandler(Kr(Ju)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?xZ(n.argsSchema):void 0}))})),this.server.setRequestHandler(Ju,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=Ms(r.argsSchema),s=await Ou(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Iu(c);throw new Z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==r&&(delete this._registeredResources[r],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Lo(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Lo(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof Ot?c._def?.innerType:c;return J_(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){X_(e);let l={title:n,description:r,inputSchema:hP(o),outputSchema:hP(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&X_(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Lo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Lo(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(Y_(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Y_(n[0])&&(i=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},bZ={type:"object",properties:{}};Xa={completion:{values:[],hasMore:!1}}});function SZ(t){return Sw.parse(JSON.parse(t))}function xP(t){return JSON.stringify(t)+`
498
- `}var Xl,SP=v(()=>{Fo();Xl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
499
- `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),SZ(n)}clear(){this._buffer=void 0}}});import vP from"node:process";var Yl,kP=v(()=>{SP();Yl=class{constructor(e=vP.stdin,n=vP.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Xl,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{this.onerror?.(r)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=xP(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var DP={};_e(DP,{PolyglotExecutor:()=>ci,buildPowerShellScriptContent:()=>AP,buildScriptFilename:()=>CP,buildShellScriptContent:()=>IP,buildSpawnOptions:()=>OP,rewriteWindowsBuildTools:()=>NP});import{spawn as wP,execSync as vZ,execFileSync as PP}from"node:child_process";import{mkdtempSync as kZ,writeFileSync as EP,rmSync as wZ,existsSync as TP}from"node:fs";import{join as Ql,resolve as RP}from"node:path";import{tmpdir as EZ}from"node:os";function CP(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${TZ[t]}`}function OP(t){return{windowsHide:t==="win32"}}function $Z(t){return`'${t.replace(/'/g,"'\\''")}'`}function IP(t,e,n){return n==="win32"||!e?t:`export PATH=${$Z(e)}
500
- ${t}`}function PZ(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function AP(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
501
- `)}function NP(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
502
- `]),r="",o=!0,s=0;for(;s<t.length;){let i=t[s];if(o&&(i===" "||i===" ")){r+=i,s++;continue}if(o&&t.startsWith("mvn",s)){let a=t[s+3];if(a===void 0||a===" "||a===" "||a===`
503
- `){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function $P(t){try{wZ(t,{recursive:!0,force:!0,maxRetries:Lt?8:2,retryDelay:100})}catch{}}function Q_(t){if(Lt&&t.pid)try{vZ(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Lt,TZ,RZ,ci,eb=v(()=>{"use strict";Qo();Lt=process.platform==="win32",TZ={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};RZ=(()=>{if(Lt)return process.env.TEMP??process.env.TMP??EZ();try{let t=PP(process.platform==="darwin"?"getconf":"mktemp",process.platform==="darwin"?["DARWIN_USER_TEMP_DIR"]:["-u","-d"],{env:{...process.env,TMPDIR:void 0},encoding:"utf-8"}).trim(),e=process.platform==="darwin"?t:RP(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();ci=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Qr()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Lt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=kZ(Ql(RZ,".ctx-mode-"));try{let c=this.#a(a,r,n),u=rp(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||$P(a),d}catch(c){throw $P(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=RP(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main
504
-
505
- import "fmt"
506
-
507
- func main() {
508
- ${n}
509
- }
510
- `),r==="php"&&!n.trimStart().startsWith("<?")&&(n=`<?php
511
- ${n}`),r==="elixir"&&TP(Ql(this.#s,"mix.exs"))&&(n=`Path.wildcard(Path.join(${JSON.stringify(Ql(this.#s,"_build/dev/lib"))}, "*/ebin"))
512
- |> Enum.each(&Code.prepend_path/1)
513
-
514
- ${n}`);let o=Ql(e,CP(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=NP(n,process.platform),a=Lt&&PZ(s)?AP(i):i;EP(o,IP(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else EP(o,n,"utf-8");return o}async#c(e,n,r){let o=Lt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{PP("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
515
- ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=Lt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;Lt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Lt?e.slice(1).map(b=>b.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!Lt,...OP(process.platform)},d;if(a){let b=[c,...u].map(S=>/\s/.test(S)?JSON.stringify(S):S).join(" ");d=wP(b,[],{...l,shell:!0})}else d=wP(c,u,{...l,shell:!1});let p=!1,h=!1,m=o===void 0?void 0:setTimeout(()=>{if(p=!0,s){h=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let b=Buffer.concat(f).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");i({stdout:b,stderr:S,exitCode:0,timedOut:!0,backgrounded:!0})}else Q_(d)},o),f=[],g=[],y=0,_=!1;d.stdout.on("data",b=>{y+=b.length,y<=this.#e?f.push(b):_||(_=!0,Q_(d))}),d.stderr.on("data",b=>{y+=b.length,y<=this.#e?g.push(b):_||(_=!0,Q_(d))}),d.on("close",b=>{if(clearTimeout(m),h)return;let S=Buffer.concat(f).toString("utf-8"),E=Buffer.concat(g).toString("utf-8");_&&(E+=`
516
- [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:E,exitCode:p?1:b??1,timedOut:p})}),d.on("error",b=>{clearTimeout(m),!h&&i({stdout:"",stderr:b.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Lt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Lt?"":"/usr/local/bin:/usr/bin:/bin"),Lt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=Lt?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(TP(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
517
- const file_path = FILE_CONTENT_PATH;
518
- const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
519
- ${r}`;case"python":return`FILE_CONTENT_PATH = ${o}
520
- file_path = FILE_CONTENT_PATH
521
- with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
522
- FILE_CONTENT = _f.read()
523
- ${r}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
524
- file_path=${s}
525
- FILE_CONTENT=$(cat ${s})
526
- ${r}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
527
- file_path = FILE_CONTENT_PATH
528
- FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
529
- ${r}`;case"go":return`package main
530
-
531
- import (
532
- "fmt"
533
- "os"
534
- )
535
-
536
- var FILE_CONTENT_PATH = ${o}
537
- var file_path = FILE_CONTENT_PATH
538
-
539
- func main() {
540
- b, _ := os.ReadFile(FILE_CONTENT_PATH)
541
- FILE_CONTENT := string(b)
542
- _ = FILE_CONTENT
543
- _ = fmt.Sprint()
544
- ${r}
545
- }
546
- `;case"rust":return`#![allow(unused_variables)]
547
- use std::fs;
548
-
549
- fn main() {
550
- let file_content_path = ${o};
551
- let file_path = file_content_path;
552
- let file_content = fs::read_to_string(file_content_path).unwrap();
553
- ${r}
554
- }
555
- `;case"php":return`<?php
556
- $FILE_CONTENT_PATH = ${o};
557
- $file_path = $FILE_CONTENT_PATH;
558
- $FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
559
- ${r}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
560
- my $file_path = $FILE_CONTENT_PATH;
561
- open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
562
- my $FILE_CONTENT = do { local $/; <$fh> };
563
- close($fh);
564
- ${r}`;case"r":return`FILE_CONTENT_PATH <- ${o}
565
- file_path <- FILE_CONTENT_PATH
566
- FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
567
- FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
568
- ${r}`;case"elixir":return`file_content_path = ${o}
569
- file_path = file_content_path
570
- file_content = File.read!(file_content_path)
571
- ${r}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
572
- var file_path = FILE_CONTENT_PATH;
573
- var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
574
- ${r}`}}}});import{cpus as CZ}from"node:os";async function tb(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,CZ().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let h=l++;if(h>=t.length)return;try{let m=await t[h].run();u[h]={status:"fulfilled",value:m}}catch(m){u[h]={status:"rejected",reason:m}}o?.(h,u[h])}}let p=[];for(let h=0;h<a;h++)p.push(d());return await Promise.allSettled(p),{settled:u,effectiveConcurrency:a,capped:c}}var MP=v(()=>{"use strict"});function nb(t,e){return t===void 0?e:`${t}::${e}`}var jP=v(()=>{"use strict"});function rb(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n}
575
-
576
- stdout:
577
- ${r}
578
-
579
- stderr:
580
- ${o}`}}var LP=v(()=>{"use strict"});import{execFileSync as OZ}from"node:child_process";function IZ(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=OZ("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function AZ(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??IZ,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}function DZ(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function MZ(t=process.env){let e=Number.parseInt(t.CONTEXT_MODE_BRIDGE_DEPTH??"",10);if(!Number.isFinite(e)||e<=0)return 0;let n=t.CONTEXT_MODE_BRIDGE_IDLE_MS;if(n!==void 0){let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:0}return 18e4}function jZ(t){return`[context-mode] Released an idle MCP helper after ${Math.round(t/1e3)}s of inactivity to free memory; it reconnects automatically on next use. (#854)`}function ob(){Ya=Date.now()}function zP(){ed++,Ya=Date.now()}function FP(){ed>0&&ed--,Ya=Date.now()}function HP(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{ob()}catch{}return e(n,r)})}function UP(t){let e=t.checkIntervalMs??DZ(),n=t.isParentAlive??NZ,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let l of i)process.on(l,o);let a=()=>{n()||o()};process.stdin.isTTY||process.stdin.on("end",a);let c=t.bridgeIdleMs??MZ(),u;return c>0&&(Ya=Date.now(),u=setInterval(()=>{ed===0&&Date.now()-Ya>=c&&(process.stderr.write(jZ(c)+`
581
- `),o())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{r=!0,clearInterval(s),u&&clearInterval(u);for(let l of i)process.removeListener(l,o);process.stdin.removeListener("end",a)}}var NZ,Ya,ed,BP=v(()=>{"use strict";NZ=AZ();Ya=Date.now(),ed=0});function ZP(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}var qP=v(()=>{"use strict"});import{existsSync as sb,unlinkSync as LZ}from"node:fs";import{join as Qa}from"node:path";function ib(t,e){try{return LZ(t),e.push(t),!0}catch{return!1}}function td(t,e){let n=!1;for(let r of zZ)ib(`${t}${r}`,e)&&r===""&&(n=!0);return n}function VP(t){let{projectDir:e,sessionsDir:n,storePath:r,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let b=Oi(e),S=rt(e),E=On(e),A=S===E?[S]:[S,E],x=!1;for(let N of A){let R=Qa(n,`${N}${b}.db`);if(!sb(R))continue;let C=null;try{C=new Gt({dbPath:R});let F=C.getEvents(a).length;C.deleteSession(a),F>0&&(x=!0)}catch{}finally{try{C?.close()}catch{}}}x&&u.push(`session rows for ${a}`);let T=[];if(r&&sb(r)&&T.push(r),o){let N=rt(e),R=On(e),C=N===R?[N]:[N,R];for(let F of C){let W=Qa(o,`${F}.db`);sb(W)&&!T.includes(W)&&T.push(W)}}let P=!1;for(let N of T)try{let R=nt(),C=new R(N,{timeout:3e4});try{let F=C.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;C.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),C.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),F>0&&(P=!0)}finally{try{C.close()}catch{}}}catch{}return P&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let p=!1;if(r&&td(r,l)&&(p=!0),o){let b=rt(e),S=On(e),E=b===S?[b]:[b,S];for(let A of E){let x=Qa(o,`${A}.db`);td(x,l)&&(p=!0)}}if(p&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let b=Qa(s,`${i}.db`);td(b,l)}let h=Oi(e),m=rt(e),f=On(e),g=m===f?[m]:[m,f],y=!1,_=!1;for(let b of g){let S=Qa(n,`${b}${h}`);td(`${S}.db`,l)&&(y=!0),ib(`${S}-events.md`,l)&&(_=!0),ib(`${S}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}var zZ,WP=v(()=>{"use strict";yr();Jt();zZ=["","-wal","-shm"]});import{existsSync as FZ}from"node:fs";function ab(t,e){try{if(!FZ(t))return;let n=new Gt({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function KP(t){ab(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function GP(t){ab(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function JP(t){ab(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var XP=v(()=>{"use strict";Jt()});import{existsSync as YP}from"node:fs";function QP(t,e,n){try{if(!YP(t))return;let r=new Gt({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function eR(t){try{if(!YP(t))return null;let e=new Gt({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}var tR=v(()=>{"use strict";Jt()});import{existsSync as cb,readFileSync as HZ,readdirSync as UZ,statSync as BZ}from"node:fs";import{join as ui,isAbsolute as ZZ}from"node:path";function oR(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?rR(n,a):null)??r??Be(),l=o?.getMemoryDir(n),d=ui(u,"memory"),p=n?ui(d,rt(n)):d,h=l?rR(n,l):p,m=[];if(n)for(let f of i){let g=ui(n,f);cb(g)&&m.push({path:g,label:`project/${f}`})}if(u&&u!==n)for(let f of i){let g=ui(u,f);cb(g)&&m.push({path:g,label:`user/${f}`})}if(h&&cb(h))try{let f=UZ(h).filter(g=>g.endsWith(".md"));for(let g of f)m.push({path:ui(h,g),label:`memory/${g}`})}catch(f){nR&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
582
- `)}for(let f of m){if(s.length>=e)break;try{let g;try{if(g=BZ(f.path),g.size>1e6)continue}catch{continue}let y=HZ(f.path,"utf-8"),_=y.toLowerCase();for(let b of t){if(s.length>=e)break;let E=b.toLowerCase().split(/\s+/).filter(x=>x.length>=3);if(E.some(x=>{try{return new RegExp(`\\b${x.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(x)}})){let x=E.reduce((F,W)=>{let ge=_.indexOf(W);return ge>=0&&(F<0||ge<F)?ge:F},-1),T=Math.max(0,x-200),P=Math.min(y.length,x+500),N=y.lastIndexOf(`
583
-
584
- `,T),R=y.indexOf(`
585
-
586
- `,P);N>=0&&(T=N+2),R>=0&&(P=R);let C=y.slice(T,P).trim();s.push({title:`[auto-memory] ${f.label}`,content:C,source:f.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){nR&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
587
- `)}}return s.slice(0,e)}function rR(t,e){return e?ZZ(e)||!t?e:ui(t,e):t??""}var nR,sR=v(()=>{"use strict";kr();Jt();nR=process.env.DEBUG?.includes("context-mode")});function iR(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,p=[],h=new Date().toISOString(),m;if(typeof d=="string"&&a)try{m=new Set(a.getSessionIdsForProject(d))}catch(f){nd&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${f}
588
- `)}try{let f=r.searchWithFallback(e,n,s,i,"like",m);p.push(...f.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||h,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(f){nd&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
589
- `)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,n,c||"",s);p.push(...f.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(f){nd&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
590
- `)}try{let f=oR([e],n,c,u,l);p.push(...f)}catch(f){nd&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
591
- `)}}for(let f of p)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((f,g)=>(f.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,n)}var nd,aR=v(()=>{"use strict";sR();nd=process.env.DEBUG?.includes("context-mode")});function qZ(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function cR(t){let e=t?{project:j.string().optional().describe("Project scope. Default (omit): this session's project \u2014 auto-resolved from the host adapter. 'global': span every project in the shared store (cross-project recall). <absolute-path>: scope to that specific project directory.")}:{};return j.object({queries:j.preprocess(qZ,j.array(j.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:j.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:j.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:j.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:j.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory."),...e})}function uR(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var ub,lR=v(()=>{"use strict";Gl();ub=!!process.env.CONTEXT_MODE_PROJECT_DIR});var rd,dR=v(()=>{"use strict";rd=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStart<n&&(n=o.windowStart,e=r);e!==void 0&&this.#t.delete(e)}}});import*as Xe from"node:fs";import*as pR from"node:os";import*as li from"node:path";function od(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function KZ(t){if(!Xe.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Xe.readdirSync(t.projectsRoot)){let o=li.join(t.projectsRoot,r),s;try{s=Xe.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Xe.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=li.join(o,a);try{let u=Xe.statSync(c).mtimeMs;u>n&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Xe.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Xe.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
592
- `).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{Xe.closeSync(r)}}catch{}}function GZ(t){let e=t?.codexHome??process.env.CODEX_HOME??li.join(pR.homedir(),".codex"),n=li.join(e,"sessions");if(!Xe.existsSync(n))return null;let r=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Xe.readdirSync(u)}catch{return}d.sort().reverse();for(let p of d){if(s>=o)return;s++;let h=li.join(u,p),m;try{m=Xe.statSync(h)}catch{continue}if(m.isDirectory()){l<r&&c(h,l+1);continue}if(!m.isFile()||!p.endsWith(".jsonl"))continue;let f=m.mtimeMs;f>a&&(a=f,i=h)}};try{c(n,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Xe.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Xe.readSync(u,l,0,l.length,0),p=l.subarray(0,d).toString("utf-8");for(let h of p.split(`
593
- `).slice(0,10))if(h.trim())try{let m=JSON.parse(h),f=m?.meta?.cwd??(m?.type==="session_meta"?m?.payload?.cwd:void 0);if(typeof f!="string"||f.length===0)continue;return od(f)?null:f}catch{return null}}finally{Xe.closeSync(u)}}catch{return null}return null}function mR(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...gm(a),...VZ]:WZ;for(let l of u){let d=e[l];if(d&&!od(d))return d}if(o){let l=KZ({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!od(l))return l}if(a==="codex"){let l=GZ({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!od(r)?r:n}var VZ,WZ,fR=v(()=>{"use strict";po();VZ=["CONTEXT_MODE_PROJECT_DIR"],WZ=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"]});import{execFileSync as JZ}from"node:child_process";import{existsSync as ur,readdirSync as di,statSync as XZ}from"node:fs";import{homedir as ud}from"node:os";import{join as qt,sep as YZ}from"node:path";function vR(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function eq(t){let e=t?.home??ud();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=qt(e,...o,"context-mode");return{name:r,sessionsDir:qt(s,"sessions"),contentDir:qt(s,"content")}})}function tq(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function ec(t){let e=Be(),n=t?.sessionsDir??qt(e,"context-mode","sessions"),r=t?.memoryRoot??qt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(ur(n)){let h=[];try{h=di(n).filter(m=>m.endsWith(".db"))}catch{}if(h.length>0){let m=null;try{m=t?.loadDatabase?t.loadDatabase():nt()}catch{}if(m)for(let f of h){let g=qt(n,f);try{let y=new m(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),b=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=b?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let E of S)E.category&&(u[E.category]=(u[E.category]??0)+(E.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let E=S.t.endsWith("Z")?S.t:S.t+"Z",A=Date.parse(E);Number.isFinite(A)&&A<a&&(a=A)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let E of S)E.p&&c.add(E.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,p={};if(ur(r)){let h=[];try{h=di(r).filter(m=>{try{return XZ(qt(r,m)).isDirectory()}catch{return!1}})}catch{}for(let m of h){let f=qt(r,m,"memory");if(!ur(f))continue;let g=[];try{g=di(f).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=tq(y);p[_]=(p[_]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:p,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function kR(t){let e=t.sessionsDir??qt(ud(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!ur(e))return r;let o=[];try{o=di(e).filter(b=>!(!b.endsWith(".db")||t.worktreeHash&&!b.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():nt()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,p=0,h=0,m=new Map,f=b=>Math.floor(b/864e5)*864e5;for(let b of o){let S=qt(e,b),E=!1;try{let A=new s(S,{readonly:!0});try{let x=A.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let P of x)P.category&&(i[P.category]=(i[P.category]??0)+(P.cnt??0),a+=P.cnt??0,E=!0);let T=A.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if(T?.mn){let P=Date.parse(T.mn+(T.mn.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P<d&&(d=P)}if(T?.mx){let P=Date.parse(T.mx+(T.mx.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P>p&&(p=P)}try{let P=A.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let N of P){if(!N.sec)continue;let R=parseInt(N.sec,10)*1e3;if(!Number.isFinite(R))continue;let C=f(R),F=m.get(C)??{count:0,rescueBytes:0};F.count+=N.cnt??0,m.set(C,F)}}catch{}try{let P=A.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(n);if(P?.bytes&&(u+=P.bytes),P?.n&&(l+=P.n),P?.lastSec){let N=parseInt(P.lastSec,10)*1e3;if(Number.isFinite(N)&&N>h&&(h=N),Number.isFinite(N)&&(P?.bytes??0)>0){let R=f(N),C=m.get(R)??{count:0,rescueBytes:0};C.rescueBytes=Math.max(C.rescueBytes,P.bytes),m.set(R,C)}}}catch{}}finally{A.close()}}catch{}E&&c++}let g=d<p?(p-d)/864e5:0,y=Object.entries(i).filter(([,b])=>b>0).map(([b,S])=>({category:b,count:S,label:id[b]||b})).sort((b,S)=>S.count-b.count),_=[...m.entries()].sort((b,S)=>b[0]-S[0]).map(([b,S])=>({ms:b,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:p>0?p:0,lastRescueMs:h>0?h:void 0,byDay:_}}function nq(t,e,n){if(!t||!e||!ur(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():nt()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
594
- FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function wR(t,e){if(!t||!ur(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():nt()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
595
- FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function tc(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??qt(ud(),".claude","context-mode","sessions");if(!ur(n))return e;let r=[];try{r=di(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():nt()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let p=qt(n,d);dp(p,o);try{let h=new o(p,{readonly:!0});try{if(t.sessionId){let m=h.prepare(`SELECT
596
- COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
597
- COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
598
- COALESCE(SUM(bytes_returned), 0) AS bytes_returned
599
- FROM session_events WHERE session_id = ?`).get(t.sessionId);m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);f?.bytes&&(c+=Number(f.bytes))}catch{}try{let f=h.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
600
- WHERE session_id = ? AND tool IN ('ctx_search', 'ctx_fetch_and_index')`).get(t.sessionId);f?.bytes&&(a+=Number(f.bytes))}catch{}}else if(t.projectDir){let m=h.prepare(`SELECT
601
- COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
602
- COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
603
- COALESCE(SUM(bytes_returned), 0) AS bytes_returned
604
- FROM session_events
605
- WHERE session_id IN (
606
- SELECT session_id FROM session_meta WHERE project_dir = ?
607
- )`).get(t.projectDir);m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
608
- FROM session_resume
609
- WHERE session_id IN (
610
- SELECT session_id FROM session_meta WHERE project_dir = ?
611
- )`).get(t.projectDir);f?.bytes&&(c+=Number(f.bytes))}catch{}try{let f=h.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes
612
- FROM tool_calls
613
- WHERE session_id IN (
614
- SELECT session_id FROM session_meta WHERE project_dir = ?
615
- )
616
- AND tool IN ('ctx_search', 'ctx_fetch_and_index')`).get(t.projectDir);f?.bytes&&(a+=Number(f.bytes))}catch{}}else{let m=h.prepare(`SELECT
617
- COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
618
- COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
619
- COALESCE(SUM(bytes_returned), 0) AS bytes_returned
620
- FROM session_events`).get();m&&(s+=Number(m.data_bytes??0),i+=Number(m.bytes_avoided??0),a+=Number(m.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}try{let f=h.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
621
- WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();f?.bytes&&(a+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=nq(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}function oq(t,e,n){let r={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!ur(t.sessionsDir))return r;let o=[];try{o=di(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=qt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let h=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(r.eventCount+=Number(h.cnt??0),r.dataBytes+=Number(h.bytes??0));try{let m=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.sessionCount+=Number(m?.cnt??0)}catch{}try{let m=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();m?.bytes&&(r.rescueBytes+=Number(m.bytes))}catch{}try{let m=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(m?.mn){let f=Date.parse(m.mn+(m.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<r.firstMs&&(r.firstMs=f)}if(m?.mx){let f=Date.parse(m.mx+(m.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>r.lastMs&&(r.lastMs=f)}}catch{}try{let m=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of m)f.p&&i.add(f.p)}catch{}try{let m=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of m)f.s&&a.add(f.s)}catch{}}finally{p.close()}}catch{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function ld(t){let e=eq({home:t?.home}),n=t?.loadDatabase??nt,r={...rq,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!ur(c.sessionsDir))continue;let u=oq(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function ad(t){return sq[t]??t}function mt(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function iq(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function sd(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function aq(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!sd(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=JZ("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!sd(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!sd(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return sd(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function hR(t){let e=ud();return e?t===e?"~":t.startsWith(e+YZ)?"~"+t.slice(e.length):t:t}function cq(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*nc(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),h=(e*1/1e6).toFixed(2),m=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,f=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return m&&f?g.push(` $${o(r)} of ${f} tokens your team didn't burn.`):m?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${mt(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),m||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function uq(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*xR,h=Math.round((e.snapshotBytes??0)/4),m=p+h,f=o?.conversation?.totalSavedTokens??0,g=Math.max(m,f),y=(n?.totalEvents??0)*xR,_=Math.round((n?.rescueBytes??0)/4),b=y+_,S=o?.lifetime?.totalSavedTokens??0,E=Math.max(b,S),A=o?.lifetime?.bytesReturned??0,x=o?.lifetime?.bytesAvoided??0,T=A+x>0?Math.max(1,Math.floor(A/4)):Math.max(1,Math.round(E*.02)),P=r?.totalBytes&&r.totalBytes>0?r.totalBytes:E*4,N=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,R=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,C=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,F=C>0?Math.max(1,Math.round((c-C)/864e5)):0,W=r?.totalSessions??n?.totalSessions??1,ge=r?.perAdapter.filter(Ue=>Ue.isReal).length??0,Le;if(r&&ge>=2)Le=`across ${ge} AI tools`;else if(r&&ge===1){let Ue=r.perAdapter.find(pn=>pn.isReal);Le=`in ${Ue?ad(Ue.name):"Claude Code"}`}else Le="in Claude Code";F>0?d.push(` Across ${F} days you ran ${kn(W)} conversations ${Le}.`):d.push(` You ran ${kn(W)} conversations ${Le}.`);let st=F>0?P/F:0;d.push(` context-mode kept ${mt(P)} out of your context window \u2014 about ${mt(st)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let $n=e.firstEventMs&&e.firstEventMs>0?gR(e.firstEventMs,i,a):"";if($n?d.push(` This conversation started ${$n} in ${hR(s)}.`):d.push(` This conversation lives in ${hR(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ue=e.lastRescueMs&&e.lastRescueMs>0?gR(e.lastRescueMs,i,a):"",pn=Math.round(e.snapshotBytes/1024);Ue?d.push(` On ${Ue}, /compact fired \u2014 ${pn} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${pn} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let pc=o?.conversation,mc=pc?.bytesAvoided??0,Dd=pc?.bytesReturned??0;if(mc+Dd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ue=mc+Dd,pn=Math.max(1,Dd),mn=Math.max(1,Math.floor(Ue/4)),Wn=Math.max(1,Math.floor(pn/4)),Md=Gr(mn,mn,32),VC=Gr(Wn,mn,32),WC=(1-Wn/mn)*100,KC=Math.max(1,Math.round(mn/Wn));d.push(` Without context-mode ${mt(Ue).padStart(8)} ${Md} ${kn(mn).padStart(7)} tokens`),d.push(` With context-mode ${mt(pn).padStart(8)} ${VC} ${kn(Wn).padStart(7)} tokens`),d.push(` ${WC.toFixed(0)}% kept out of context \xB7 your AI ran ${KC}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ue=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${mt(N)} built up \u2014 ${Ue} days, ${e.byDay.length} active:`),d.push(""),d.push(...dq(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let UC=e.byCategory.reduce((Ue,pn)=>Ue+pn.count,0).toLocaleString(i);d.push(` ${UC} things \u2014 files, errors, decisions, agent runs:`),d.push("");let BC=e.byCategory[0]?.count??1;for(let Ue of e.byCategory)d.push(` ${Ue.label.padEnd(26)} ${String(Ue.count).padStart(5)} ${Gr(Ue.count,BC,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Ob=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Ib=C>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(C)):"",Ab=n?.distinctProjects??0,ZC=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${mt(N)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Ob?` \xB7 started ${Ob}`:""}.`),d.push(` All your work: ${mt(P)} kept out \xB7 ${ZC.toLocaleString(i)} captures across ${Ab} project${Ab===1?"":"s"}${Ib?` \xB7 since ${Ib}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...cq(P,E,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Ue=Object.entries(n.autoMemoryByPrefix).sort((mn,Wn)=>Wn[1]-mn[1]),pn=Ue.length>0?Ue[0][1]:1;for(let[mn,Wn]of Ue){let Md=ER[mn]??mn;d.push(` ${Md.padEnd(26)} ${String(Wn).padStart(2)} ${Gr(Wn,pn,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let qC=u?`v${u}`:"context-mode";return d.push(` ${qC}`),u&&l&&l!=="unknown"&&vR(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),lq(d)}function lq(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function dq(t,e,n){if(t.length===0)return[];let r=[...t].sort((p,h)=>p.ms-h.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let p of r)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of r){let h=Math.round((p.ms-o.ms)/i*(c-1)),m="\u25CF";p===a&&(m="\u2588"),(p.rescueBytes??0)>0&&(m="\u25C6"),u[h]=m}let l=p=>{let h=new Intl.DateTimeFormat(e,{timeZone:n,month:"short",day:"numeric"}).formatToParts(new Date(p)),m=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${m} ${f}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of r){let h=l(p.ms).padEnd(7),m=`${p.count} captures`,f=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${h} ${m}${f}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function gR(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),s=d=>o.find(p=>p.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${n})`}function kn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function nc(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 5/1e6}function cd(t){return`$${((Number.isFinite(t)&&t>0?t:0)*nc()).toFixed(2)}`}function Gr(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function yR(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(f=>f.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let f=i>=2?" everywhere":"";o.push(` All your work${f} \xB7 ${kn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${kn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&n>0?1:c,g=f===1?"1 session":`${kn(f)} sessions`,y=a*256+n;o.push(` ${kn(a)} events \xB7 ${g} \xB7 ~${cd(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:id[f]||f})).sort((f,g)=>g.count-f.count):d=(t.by_category??[]).filter(f=>f&&f.count>0);let p=d.slice(0,r),h=p.length>0?p[0].count:1;for(let f of p)o.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Gr(f.count,h,30)}`);let m=Math.max(0,d.length-r);return m>0&&o.push(` ... ${m} more categor${m===1?"y":"ies"}`),o}function _R(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=ER[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${Gr(s,r,20)}`)}return e}function bR(t,e){let n=[],r=cd(t),o=(e?.totalEvents??0)*256+t,s=cd(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}function SR(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?kn(u.eventCount):"\u2014",p=mt(u.dataBytes),h=mt(l);r.push(` ${ad(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${h.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>ad(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function dd(t,e,n,r){let o=[],s=iq(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(A=>A.isReal).length??0;if(l&&d>0){let A=l.totalSessions||i?.totalSessions||0,x=i?.firstEventMs??0,T=x>0?Math.max(1,Math.round((Date.now()-x)/864e5)):0,P=T>0?`Across ${T} day${T===1?"":"s"} `:"",N=A>0?`you ran ${kn(A)} conversation${A===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let C=l.perAdapter.find(F=>F.isReal);R=`in ${C?ad(C.name):"Claude Code"}`}o.push(`${P}${N}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let A=aq(),x=r?.cwd??process.cwd(),T=r?.now??Date.now(),P=r?.locale??A.locale,N=r?.tz??A.tz;return o.push(...uq({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:x,locale:P,tz:N,now:T,version:e,latestVersion:n})),o.join(`
622
- `)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,m=t.savings.total_calls,f=p+h,g=f>0?p/f*100:0,y=Math.round(p/4),_=h>0?Math.max(1,Math.round(f/Math.max(h,1))):0;if(p===0){o.push(`context-mode ${s} ${m} calls`),o.push(""),m===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${mt(h)} entered context | 0 tokens saved`),o.push(...yR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...SR(l)),o.push(..._R(i)),o.push(...bR(0,i)),o.push("");let A=e?`v${e}`:"context-mode";return o.push(A),e&&n&&n!=="unknown"&&vR(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
623
- `)}o.push(`${kn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${cd(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${Gr(f,f)}| ${mt(f)}`),o.push(`With context-mode |${Gr(h,f)}| ${mt(h)}`),o.push(""),_>=2?o.push(`${mt(p)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${mt(p)} kept out of your conversation. Never entered context.`),o.push("");let b=[`${m} calls`];t.cache&&t.cache.hits>0&&b.push(`${t.cache.hits} cache hits (+${mt(t.cache.bytes_saved)})`),o.push(b.join(" \xB7 "));let S=t.savings.by_tool.filter(A=>A.calls>0);if(S.length>=2){o.push("");let A=S.map(x=>{let T=x.context_kb*1024,P=g<100?T/(1-g/100):T,N=Math.max(0,P-T);return{...x,returnedBytes:T,estimatedSaved:N}}).sort((x,T)=>T.estimatedSaved-x.estimatedSaved);for(let x of A){let T=x.tool.length>22?x.tool.slice(0,19)+"...":x.tool;o.push(` ${T.padEnd(22)} ${String(x.calls).padStart(4)} calls ${mt(x.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let A=a.filter(x=>x.median_concurrency!=null&&(x.max_concurrency??1)>1);if(A.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let x of A){let T=x.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${T.padEnd(22)} ${x.calls} batches \xB7 ${x.median_concurrency} typical, ${x.max_concurrency} peak`)}}}o.push(...yR(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...SR(l)),o.push(..._R(i)),o.push(...bR(y,i)),o.push("");let E=e?`v${e}`:"context-mode";return o.push(E),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
624
- `)}var id,QZ,pi,rq,ER,sq,b7,xR,TR=v(()=>{"use strict";yr();Jt();kr();id={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},QZ={file:"Restored after compact \u2014 no need to re-read",rule:"Your project instructions survive context resets",prompt:"Continues exactly where you left off",decision:"Applied automatically \u2014 won\u2019t ask again",task:"Picks up from where it stopped",error:"Tracked and monitored across compacts",git:"Branch, commit, and repo state preserved",env:"Runtime config carried forward",mcp:"Tool usage patterns remembered",subagent:"Delegation history preserved",skill:"Skill invocations tracked"},pi=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=n.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}n.set(i,a)}let r=[];for(let[o,s]of n){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((C,F)=>C+F,0),s=Object.values(e.calls).reduce((C,F)=>C+F,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(C=>({tool:C,calls:e.calls[C]||0,context_kb:Math.round((e.bytesReturned[C]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[C]||0)/4)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),m,f=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||f>0){let C=a+e.cacheBytesSaved,F=C/Math.max(o,1),W=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ge=e.cacheHits+f,Le=ge>0?e.cacheHits/ge:0;m={hits:e.cacheHits,misses:f,hit_rate:Le,bytes_saved:e.cacheBytesSaved,ttl_hours_left:W,total_with_cache:C,total_savings_ratio:F}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,S=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),E=S?!S.consumed:!1,A=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),x=new Map;for(let C of A){x.has(C.category)||x.set(C.category,new Set);let F=x.get(C.category);if(F.size<5){let W=C.data;C.category==="file"?W=C.data.split("/").pop()||C.data:(C.category==="prompt"||C.category==="user-prompt")&&(W=W.length>50?W.slice(0,47)+"...":W),W.length>40&&(W=W.slice(0,37)+"..."),F.add(W)}}let T=y.map(C=>({category:C.category,count:C.cnt,label:id[C.category]||C.category,preview:x.get(C.category)?Array.from(x.get(C.category)).join(", "):"",why:QZ[C.category]||"Survives context resets"})),P=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),R=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(C=>C.cnt>0).map(C=>({category:C.category,count:C.cnt,label:id[C.category]||C.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:m,session:{id:r,uptime_min:h},continuity:{total_events:g,by_category:T,compact_count:b,resume_ready:E},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:R}}}};rq={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};ER={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},sq={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};b7=5/1e6;xR=256});var dC={};_e(dC,{AGY_DEFAULT_EXEC_TIMEOUT_MS:()=>rC,REGISTERED_CTX_TOOLS:()=>ZR,__resetSuppressionDiagnosticForTests:()=>Tq,browserOpenArgv:()=>cC,buildBatchNodeOptionsPrefix:()=>tC,buildFetchCode:()=>aC,classifyIp:()=>sc,currentAttribution:()=>pr,emitSuppressionDiagnostic:()=>WR,extractSnippet:()=>Sb,formatBatchQueryResults:()=>eC,getProjectDir:()=>Rt,installStrictClientSchemaCompat:()=>GR,killProcessOnPort:()=>lC,openBrowserSync:()=>uC,positionsFromHighlight:()=>QR,registerEmptyToolsListHandler:()=>KR,resolveExecTimeout:()=>Td,resolveSessionIdFromSessionDB:()=>JR,runBatchCommands:()=>sC,sanitizeSchemaForStrictClients:()=>xd,server:()=>Re,shouldSuppressMcpToolsForNativePluginHost:()=>qR,withProjectDirOverride:()=>Rq});import{createRequire as MR}from"node:module";import{existsSync as Ke,unlinkSync as hi,readdirSync as jR,readFileSync as ic,writeFileSync as _d,writeSync as pq,renameSync as mq,rmSync as LR,mkdirSync as fq,statSync as zR,symlinkSync as hq,lstatSync as FR,realpathSync as HR}from"node:fs";import{spawnSync as bd}from"node:child_process";import{join as zt,dirname as yi,resolve as Pt,sep as gq,isAbsolute as yq}from"node:path";import{fileURLToPath as _q}from"node:url";import{homedir as gi,tmpdir as _b,cpus as bq}from"node:os";import{request as xq}from"node:https";import{AsyncLocalStorage as Sq}from"node:async_hooks";function UR(){return Ke(Pt(hd,"package.json"))?hd:yi(hd)}function vq(t){try{let e=process.platform==="win32"?bd("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):bd("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=jc(String(e.stdout));if(n&&Ke(Pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function BR(t){let e=UR();return t==="codex"?vq(e):e}function qR(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??Qe().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??kq(n);return wq(r)&&Eq(r)}function kq(t){let e=t==="kilo"?"kilo":"opencode",n=[Pt(`${e}.json`),Pt(`${e}.jsonc`),Pt(`.${e}`,`${e}.json`),Pt(`.${e}`,`${e}.jsonc`),zt(gi(),".config",e,`${e}.json`),zt(gi(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!Ke(r))continue;return JSON.parse(Ni(ic(r,"utf8")))}catch{}return null}function wq(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function Eq(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function WR(t={}){if(fb)return;fb=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
625
- `)}function Tq(){fb=!1}function KR(t=Re){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(zo,async()=>({tools:[]}))}function Pq(t,e){return async n=>{zP();try{return await e(n)}catch(r){let o=Nq(r);if(o)try{return X(t,o)}catch(s){if(s instanceof Kt)return o;throw s}throw r}finally{FP()}}}async function Rq(t,e){let n=typeof t=="string"?{projectDir:t}:t;return bb.run(n,e)}function xd(t){if(Array.isArray(t))return t.map(xd);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=xd(r)}return e}function GR(t=Re){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(zo,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=xd(i.inputSchema)}catch{}}return s})}catch{}}function pr(){let t=bb.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??JR();if(e)return{sessionId:e}}function JR(t){let e=Date.now();if(!t?.bypassCache&&pd&&e-pd.checkedAt<2e3)return pd.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??We(),o=ls({projectDir:n,sessionsDir:r});if(!Ke(o))return;let s=nt(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(pd={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function Cq(t){try{let e=We();if(!Ke(e))return;let n=jR(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=zt(e,r);try{t.index({path:o,source:"session-events",attribution:pr()}),hi(o)}catch{}}}catch{}}async function Oq(){if(En)return En;try{let{getAdapter:t}=await Promise.resolve().then(()=>(po(),ym)),e=Qe();return await t(e.platform)}catch{return null}}function mi(){if(En)return En.getSessionDir();try{let t=Qe(),e=Fi(t.platform);if(e)return Oc({configDir:zt(...e),configDirEnv:Iq(e)})}catch{}return Oc({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function Iq(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function We(){return Sr(xr(mi))}function Rt(){let t=bb.getStore();if(t)return t.projectDir;let e,n,r;try{let o=Qe().platform;n=o,o==="claude-code"&&(e=zt(gi(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??zt(gi(),".codex"))}catch{}return mR({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function Aq(t){return yq(t)?t:Pt(Rt(),t)}function oc(){return ls({projectDir:Rt(),sessionsDir:We()})}function Sd(){let t=Sr(eo(mi));return up({projectDir:Rt(),contentDir:t})}function Zn(){if(!wn){let t=Sd();wn=new vs(t),wn.setDenyChecker(e=>{try{let n=Rt(),r=fo("Read",n);return Pr(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=yi(Sd());wm(e,14),wn.cleanupStaleSources(14);let n=zt(gi(),".context-mode","content");Ke(n)&&wm(n,0)}catch{}km()}return Cq(wn),wn}function Nq(t){return t instanceof Kt?{content:[{type:"text",text:us(t)}],isError:!0}:null}async function PR(){return new Promise(t=>{let e=xq("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function jq(){let t=En?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function Lq(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function zq(){return!dr||dr==="unknown"?!1:Lq(dr,lr)}function Fq(){if(!zq())return!1;let t=Date.now();if(md>=Dq){if(t-$R<Mq)return!1;md=0}return md===0&&($R=t),md++,!0}function Hq(){if(!RR){RR=!0;try{let t=Be(),e=Pt(t,"plugins","installed_plugins.json");if(!Ke(e))return;let n=JSON.parse(ic(e,"utf-8")),r=Pt(t,"plugins","cache"),o;try{o=HR(r)}catch{o=r}let s=UR();for(let[i,a]of Object.entries(n.plugins??{}))if(i==="context-mode@context-mode")for(let c of a){let u=c.installPath;if(!u||Ke(u)||!Pt(u).startsWith(o+gq))continue;try{FR(u).isSymbolicLink()&&hi(u)}catch{}let l=yi(u);Ke(l)||fq(l,{recursive:!0}),Ke(s)&&hq(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function X(t,e){if(ob(),Hq(),Fq()&&e.content.length>0){let r=jq();e.content[0].text=`\u26A0\uFE0F context-mode v${lr} outdated \u2192 v${dr} available. Upgrade: ${r}
626
-
627
- `+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+n,vd(),setImmediate(()=>QP(oc(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>KP({sessionDbPath:oc(),toolName:t,bytesReturned:n})),e}function Tn(t,e="unknown"){ie.bytesIndexed+=t,vd(),t>0&&setImmediate(()=>GP({sessionDbPath:oc(),source:e,bytesAvoided:t}))}function Wq(t){return Vq.test(t)?t:`pid-${process.ppid}`}function XR(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=Wq(t),n=Sr(cs(mi));return zt(n,`stats-${e}.json`)}function vd(){let t=Date.now();if(!(t-hb<Uq)){hb=t;try{let e=Object.values(ie.bytesReturned).reduce((d,p)=>d+p,0),n=Object.values(ie.calls).reduce((d,p)=>d+p,0),r=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=fd?.tokens??0;if(!fd||t-fd.computedAt>Zq)try{a=(ec({sessionsDir:We()})?.totalEvents??0)*qq,fd={tokens:a,computedAt:t}}catch{}let c={schemaVersion:Bq,version:lr,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*nc()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*nc()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ie.calls,...ie.bytesReturned}).map(d=>[d,{calls:ie.calls[d]||0,bytes:ie.bytesReturned[d]||0}]))},u=XR(),l=`${u}.tmp`;_d(l,JSON.stringify(c)),mq(l,u)}catch{}}}function xb(t,e){try{let n=Pm(process.env.CLAUDE_PROJECT_DIR),r=Cm(t,n);if(r.decision==="deny")return X(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function YR(t,e,n){try{let r=qv(t,e);if(r.length===0)return null;let o=Pm(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=Cm(s,o);if(i.decision==="deny")return X(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function Kq(t,e){try{let n=Rt(),r=Rm("Read","allow",n);return Zv(t,n,r).allowed?null:X(e,{content:[{type:"text",text:`File access blocked: "${t}" resolves outside the project root (${n}). context-mode confines ${e} to the workspace so it cannot be used to bypass the host's sandbox/permission controls (issue #852). To intentionally process a file outside the project, add a host allow rule, e.g. "permissions": { "allow": ["Read(${t})"] } in your settings.`}],isError:!0})}catch{}return null}function gb(t,e){try{let n=Rt(),r=fo("Read",n),o=Pr(t,r,process.platform==="win32",n);if(o.denied)return X(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function QR(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===Xq){for(e.push(n),r++;r<t.length&&t[r]!==Yq;)n++,r++;r<t.length&&r++}else n++,r++;return e}function Sb(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of QR(r))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let p=l.indexOf(d);for(;p!==-1;)o.push(p),p=l.indexOf(d,p+1)}}if(o.length===0)return t.slice(0,n)+`
628
- \u2026`;o.sort((u,l)=>u-l);let s=300,i=[];for(let u of o){let l=Math.max(0,u-s),d=Math.min(t.length,u+s);i.length>0&&l<=i[i.length-1][1]?i[i.length-1][1]=d:i.push([l,d])}let a=[],c=0;for(let[u,l]of i){if(c>=n)break;let d=t.slice(u,Math.min(l,u+(n-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
629
-
630
- `)}function eC(t,e,n,r=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:n;for(let c of e){if(i>r){s.push(`## ${c}
631
- (output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
632
- `);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=Sb(l.content,c,3e3,l.highlighted);s.push(`### ${l.title}`),s.push(d),s.push(""),i+=d.length+l.title.length}continue}s.push("No matching sections found."),s.push("")}return o==="global"?s.push(`
633
- > **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function Qq(t){return`'${t.replace(/'/g,"'\\''")}'`}function e4(t){return`'${t.replace(/'/g,"''")}'`}function tC(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${e4(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${Qq(n)} `}function nC(t){let e=t.replace(/\s+/g," ").trim();return e.length<=CR?e:e.slice(0,CR)+"\u2026"}function Td(t){if(t!==void 0)return t;if(Qe().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:rC}function t4(t){return t.length<=OR?t:t.slice(0,OR)+`
634
- \u2026 (truncated)`}function oC(t,e,n){let r=n?`path=${n}
635
- `:"",o=`\`\`\`${t}
636
- ${t4(e)}
637
- \`\`\``;return`${r}${o}
638
-
639
- `}function IR(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=nC(e);return`# ${t}
640
-
641
- $ ${a}
642
-
643
- ${o}
644
- `}function AR(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
645
- `)?"":`
646
- `}${n}`:n:e}async function sC(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let p=[],h=Date.now(),m=!1;for(let f=0;f<t.length;f++){let g=t[f],y;if(r!==void 0){let b=Date.now()-h,S=r-b;if(S<=0){p.push(`# ${g.label}
647
-
648
- (skipped \u2014 batch timeout exceeded)
649
- `),m=!0;continue}y=S}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(p.push(IR(g.label,g.command,AR(_),a)),_.timedOut){m=!0;for(let b=f+1;b<t.length;b++)p.push(`# ${t[b].label}
650
-
651
- (skipped \u2014 batch timeout exceeded)
652
- `);break}}return{outputs:p,timedOut:m}}let c=t.map(p=>({run:async()=>{let h=await n.execute({language:"shell",code:`${s}${p.command}`,timeout:r,cwd:i}),m=IR(p.label,p.command,AR(h),a);return{output:h.timedOut?m.replace(/\n$/,"")+`
653
- (timed out after ${r??"?"}ms)
654
- `:m,timedOut:!!h.timedOut}}})),{settled:u}=await tb(c,{concurrency:o}),l=new Array(t.length),d=!1;for(let p=0;p<u.length;p++){let h=u[p];if(h.status==="fulfilled")l[p]=h.value.output,h.value.timedOut&&(d=!0);else{let m=h.reason instanceof Error?h.reason.message:String(h.reason);l[p]=`# ${t[p].label}
655
-
656
- (executor error: ${m})
657
- `}}return{outputs:l,timedOut:d}}function iC(t,e){let n=Zn();Tn(Buffer.byteLength(t));let r=n.index({content:t,source:e,attribution:pr()});return{content:[{type:"text",text:`Indexed ${r.totalChunks} sections (${r.codeChunks} with code) from: ${r.label}
658
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${r.label}" to scope results.`}]}}function fi(t,e,n,r=5){let o=t.split(`
659
- `).length,s=Buffer.byteLength(t),i=Zn(),a=i.indexPlainText(t,n,void 0,pr()),c=i.searchWithFallback(e,r,n),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${n}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
660
- `)}let l=[`Indexed ${a.totalChunks} sections from "${n}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let p=d.content.split(`
661
- `)[0].slice(0,120);l.push(` - ${d.title}: ${p}`)}return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),l.join(`
662
- `)}function vb(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}function o4(){try{return pr()?.sessionId??"__default__"}catch{return"__default__"}}function kb(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function wb(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function s4(t){let e=kb(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}function i4(){return lb||(lb=MR(import.meta.url).resolve("turndown")),lb}function a4(){return db||(db=MR(import.meta.url).resolve("turndown-plugin-gfm")),db}function aC(t,e){let n=JSON.stringify(i4()),r=JSON.stringify(a4()),o=JSON.stringify(e),s=sc.toString(),i=sc.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
663
- var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
664
- const TurndownService = require(${n});
665
- const { gfm } = require(${r});
666
- const fs = require('fs');
667
- const dns = require('no' + 'de:dns');
668
- const dnsPromises = require('no' + 'de:dns/promises');
669
- const url = ${JSON.stringify(t)};
670
- const outputPath = ${o};
671
-
672
- // Strip proxy env vars from this subprocess only. A configured outbound
673
- // proxy (HTTP_PROXY / HTTPS_PROXY / ALL_PROXY) would route fetch through
674
- // an arbitrary target \u2014 DNS resolution happens at the proxy and the
675
- // in-subprocess DNS rebinding guard never sees the rebound IP. The
676
- // sandbox fetch path has no legitimate need for an upstream proxy.
677
- delete process.env.HTTP_PROXY;
678
- delete process.env.HTTPS_PROXY;
679
- delete process.env.ALL_PROXY;
680
- delete process.env.http_proxy;
681
- delete process.env.https_proxy;
682
- delete process.env.all_proxy;
683
- delete process.env.npm_config_proxy;
684
- delete process.env.npm_config_https_proxy;
685
-
686
- ${a}
687
-
688
- const STRICT = ${JSON.stringify(c)};
689
-
690
- // SSRF rebinding defense: every dns.lookup call inside this subprocess
691
- // (including the one undici performs to connect the fetch socket) is
692
- // re-validated against the same policy ssrfGuard runs in the parent.
693
- // Even if a hostname rebinds between the parent's pre-flight check and
694
- // the subprocess's actual connect, the connect-time lookup re-classifies
695
- // every returned record and aborts before TCP if any verdict is "block".
696
- const _origLookup = dns.lookup;
697
- dns.lookup = function patchedLookup(hostname, options, callback) {
698
- if (typeof options === 'function') { callback = options; options = {}; }
699
- if (typeof options === 'number') { options = { family: options }; }
700
- const wantAll = options && options.all;
701
- const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
702
- _origLookup(hostname, opts, function(err, records) {
703
- if (err) return callback(err);
704
- if (!Array.isArray(records)) {
705
- records = [{ address: records, family: (options && options.family) || 4 }];
706
- }
707
- for (var i = 0; i < records.length; i++) {
708
- var verdict = classifyIp(records[i].address);
709
- if (verdict === 'block' || (STRICT && verdict === 'private')) {
710
- return callback(new Error(
711
- 'SSRF blocked at connect-time: ' + hostname +
712
- ' resolves to ' + records[i].address +
713
- ' (' + verdict + ')'
714
- ));
715
- }
716
- }
717
- if (wantAll) callback(null, records);
718
- else callback(null, records[0].address, records[0].family);
719
- });
720
- };
721
-
722
- // dns/promises is a separate function reference. Patching dns.lookup does
723
- // NOT affect dnsPromises.lookup. Today undici's connect path uses callback
724
- // dns.lookup so default fetch is covered, but the invariant is fragile \u2014
725
- // any future undici switch (or user code calling dnsPromises.lookup
726
- // directly) would bypass the guard. Patch both to keep the contract.
727
- const _origPromisesLookup = dnsPromises.lookup;
728
- dnsPromises.lookup = async function patchedPromisesLookup(hostname, options) {
729
- const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
730
- const records = await _origPromisesLookup(hostname, opts);
731
- const list = Array.isArray(records) ? records : [records];
732
- for (var i = 0; i < list.length; i++) {
733
- var verdict = classifyIp(list[i].address);
734
- if (verdict === 'block' || (STRICT && verdict === 'private')) {
735
- throw new Error(
736
- 'SSRF blocked at connect-time: ' + hostname +
737
- ' resolves to ' + list[i].address + ' (' + verdict + ')'
738
- );
739
- }
740
- }
741
- return options && options.all
742
- ? list
743
- : { address: list[0].address, family: list[0].family };
744
- };
745
-
746
- // dns.resolve4 / dns.resolve6 use a different code path (no getaddrinfo,
747
- // no /etc/hosts) than dns.lookup \u2014 they must be patched separately or the
748
- // guard is trivially bypassed by any caller using dns.resolve* directly.
749
- ['resolve4', 'resolve6'].forEach(function patchResolve(name) {
750
- const _origResolve = dns[name];
751
- dns[name] = function patchedResolve(hostname, options, cb) {
752
- if (typeof options === 'function') { cb = options; options = undefined; }
753
- _origResolve.call(dns, hostname, options || {}, function(err, addrs) {
754
- if (err) return cb(err);
755
- var withTtl = options && options.ttl;
756
- for (var i = 0; i < addrs.length; i++) {
757
- var ip = withTtl ? addrs[i].address : addrs[i];
758
- var v = classifyIp(ip);
759
- if (v === 'block' || (STRICT && v === 'private')) {
760
- return cb(new Error(
761
- 'SSRF blocked at connect-time: ' + hostname +
762
- ' resolves to ' + ip + ' (' + v + ')'
763
- ));
764
- }
765
- }
766
- cb(null, addrs);
767
- });
768
- };
769
- });
770
-
771
- // Generic dns.resolve is a polymorphic dispatcher (rrtype-driven). Internally
772
- // Node delegates to dns.resolve4/dns.resolve6 for A/AAAA, but the patches
773
- // above hook the *exported* references \u2014 Node's internal dispatcher holds
774
- // captured originals and bypasses our patch. Patch the wrapper explicitly:
775
- // classify A/AAAA records the same way; pass through CNAME/MX/TXT/SRV/etc.
776
- const _origResolveGeneric = dns.resolve;
777
- dns.resolve = function patchedResolveGeneric(hostname, rrtype, cb) {
778
- if (typeof rrtype === 'function') { cb = rrtype; rrtype = 'A'; }
779
- _origResolveGeneric.call(dns, hostname, rrtype, function(err, records) {
780
- if (err) return cb(err);
781
- if ((rrtype === 'A' || rrtype === 'AAAA') && Array.isArray(records)) {
782
- for (var i = 0; i < records.length; i++) {
783
- var ip = records[i];
784
- var v = classifyIp(ip);
785
- if (v === 'block' || (STRICT && v === 'private')) {
786
- return cb(new Error(
787
- 'SSRF blocked at connect-time: ' + hostname +
788
- ' resolves to ' + ip + ' (' + v + ')'
789
- ));
790
- }
791
- }
792
- }
793
- cb(null, records);
794
- });
795
- };
796
-
797
- function emit(ct, content) {
798
- // Write content to file to bypass executor stdout truncation (100KB limit).
799
- // Only the content-type marker goes to stdout.
800
- fs.writeFileSync(outputPath, content);
801
- console.log('__CM_CT__:' + ct);
802
- }
803
-
804
- // Manual redirect handling: a 3xx Location header can rebind the subprocess
805
- // fetch to an alternate host the parent's pre-flight ssrfGuard never saw.
806
- // Even with the connect-time DNS patch, a redirect target that is a literal
807
- // IP (e.g. http://169.254.169.254/) skips getaddrinfo entirely. Walk the
808
- // chain manually so every hop runs through classifyIp before the next fetch.
809
- const MAX_REDIRECTS = 5;
810
- async function fetchWithManualRedirect(initialUrl) {
811
- let currentUrl = initialUrl;
812
- for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
813
- const resp = await fetch(currentUrl, { redirect: 'manual' });
814
- if (resp.status < 300 || resp.status >= 400) return resp;
815
- const location = resp.headers.get('location') || resp.headers.get('Location');
816
- if (!location) return resp;
817
- if (redirectCount === MAX_REDIRECTS) {
818
- throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
819
- }
820
- let nextParsed;
821
- try { nextParsed = new URL(location, currentUrl); } catch (e) {
822
- throw new Error('SSRF blocked: invalid redirect Location: ' + location);
823
- }
824
- if (nextParsed.protocol !== 'http:' && nextParsed.protocol !== 'https:') {
825
- throw new Error('SSRF blocked: redirect to non-http(s) scheme ' + nextParsed.protocol);
826
- }
827
- // If the redirect target is a literal IP, classify it directly \u2014 no DNS
828
- // lookup will fire and the connect-time guard would never see it.
829
- const hostname = nextParsed.hostname.replace(/^[|]$/g, '');
830
- const isIpLiteral = /^[0-9.]+$/.test(hostname) || hostname.includes(':');
831
- if (isIpLiteral) {
832
- const verdict = classifyIp(hostname);
833
- if (verdict === 'block' || (STRICT && verdict === 'private')) {
834
- throw new Error('SSRF blocked: redirect to ' + hostname + ' (' + verdict + ')');
835
- }
836
- } else {
837
- // Hostname target: resolve and classify every record. The patched
838
- // dns.lookup also fires on the next fetch's connect, but checking
839
- // here gives a clearer error and short-circuits before TCP setup.
840
- const records = await dnsPromises.lookup(hostname, { all: true, verbatim: true });
841
- for (const rec of records) {
842
- const verdict = classifyIp(rec.address);
843
- if (verdict === 'block' || (STRICT && verdict === 'private')) {
844
- throw new Error(
845
- 'SSRF blocked: redirect target ' + hostname +
846
- ' resolves to ' + rec.address + ' (' + verdict + ')'
847
- );
848
- }
849
- }
850
- }
851
- currentUrl = nextParsed.toString();
852
- }
853
- throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
854
- }
855
-
856
- // Subprocess response-body size cap. A malicious or unexpectedly large
857
- // endpoint reachable through ctx_fetch_and_index would otherwise stream
858
- // gigabytes into resp.text(), then into outputPath, then into the parent
859
- // MCP server's heap via readFileSync. 50 MB is far above typical web
860
- // page / API response sizes (~1-5 MB) but bounded enough to keep parent
861
- // heap survivable. Cap both early via Content-Length and after the read.
862
- const MAX_FETCH_BYTES = 50 * 1024 * 1024;
863
- async function safeText(resp) {
864
- const cl = parseInt(resp.headers.get('content-length') || '0', 10);
865
- if (cl > MAX_FETCH_BYTES) {
866
- throw new Error('Response too large: Content-Length ' + cl + ' exceeds ' + MAX_FETCH_BYTES);
867
- }
868
- const text = await resp.text();
869
- if (text.length > MAX_FETCH_BYTES) {
870
- throw new Error('Response too large: ' + text.length + ' bytes exceeds ' + MAX_FETCH_BYTES);
871
- }
872
- return text;
873
- }
874
-
875
- async function main() {
876
- const resp = await fetchWithManualRedirect(url);
877
- if (!resp.ok) { console.error("HTTP " + resp.status); process.exit(1); }
878
- const contentType = resp.headers.get('content-type') || '';
879
-
880
- // --- JSON responses ---
881
- if (contentType.includes('application/json') || contentType.includes('+json')) {
882
- const text = await safeText(resp);
883
- try {
884
- const pretty = JSON.stringify(JSON.parse(text), null, 2);
885
- emit('json', pretty);
886
- } catch {
887
- emit('text', text);
888
- }
889
- return;
890
- }
891
-
892
- // --- HTML responses (default for text/html, application/xhtml+xml) ---
893
- if (contentType.includes('text/html') || contentType.includes('application/xhtml')) {
894
- const html = await safeText(resp);
895
- const td = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' });
896
- td.use(gfm);
897
- td.remove(['script', 'style', 'nav', 'header', 'footer', 'noscript']);
898
- emit('html', td.turndown(html));
899
- return;
900
- }
901
-
902
- // --- Everything else: plain text, CSV, XML, etc. ---
903
- const text = await safeText(resp);
904
- emit('text', text);
905
- }
906
- main();
907
- `}function u4(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}async function l4(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=sc(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&n)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function sc(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?sc(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function d4(t,e,n,r){let o=await l4(t);if(o)return o;if(!n&&r!==0){let i=Zn(),a=nb(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??c4;if(l<d){let p=Math.floor(l/36e5),h=Math.floor(l/(60*1e3)),m=p>0?`${p}h ago`:h>0?`${h}m ago`:"just now",f=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:f,ageStr:m,ttlStr:u4(d)}}}}let s=zt(_b(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=aC(t,s),a=await ac.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",p=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${p}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=zR(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=ic(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{LR(s)}catch{}}}function p4(t){let e=Zn(),n=nb(t.source,t.url),r=pr(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,n,void 0,r):o=e.index({content:t.markdown,source:n,attribution:r}),Tn(Buffer.byteLength(t.markdown));let s=t.markdown.length>NR?ZP(t.markdown,NR)+`
908
-
909
- \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function pb(t,e){if(!Ke(e))return;let n=0;try{for(let r of jR(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(ic(zt(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function DR(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function cC(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function uC(t,e=process.platform,n=bd){let r=cC(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:rc});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function lC(t,e=process.platform,n=bd){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:rc});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],p=u[2],h=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(h)&&i.add(h))}for(let a of i){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:rc});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:rc});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:rc});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}async function m4(){let t=km();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?_b():"/tmp",n=zt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{ac.cleanupBackgrounded(),wn&&wn.close();try{hi(Ed)}catch{}try{hi(n)}catch{}r&&clearInterval(r)},s=async()=>{try{hb=0,vd()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),UP({onShutdown:()=>s()});let i=new Yl;await Re.connect(i),HP(i);try{_d(n,String(process.pid))}catch{}r=setInterval(()=>{try{_d(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(po(),ym)),u=Re.server.getClientVersion(),l=a(u??void 0);En=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=eR(oc());if(a){for(let[c,u]of Object.entries(a.calls))ie.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ie.bytesReturned[c]=u;a.sessionStart>0&&(ie.sessionStart=a.sessionStart)}}catch{}PR().then(a=>{a!=="unknown"&&(dr=a)}),setInterval(()=>{PR().then(a=>{a!=="unknown"&&(dr=a)})},3600*1e3).unref(),setInterval(()=>vd(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${lr} running on stdio`),console.error(`Detected runtimes:
910
- ${Ei(Xo)}`),hr()||(console.error(`
911
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var hd,lr,Xo,gd,Re,ZR,VR,fb,$q,bb,ac,Ed,wn,pd,En,ie,dr,md,$R,Dq,Mq,RR,Uq,Bq,Zq,qq,hb,fd,Vq,Gq,Jq,Xq,Yq,CR,rC,OR,kd,wd,n4,yb,yd,r4,lb,db,c4,NR,rc,mb,pC=v(()=>{"use strict";bP();kP();Gl();eb();MP();Em();jP();Om();Qo();LP();BP();qP();Jt();WP();XP();tR();aR();lR();dR();Rn();po();Ap();op();Di();kr();fR();yr();TR();Fo();hd=yi(_q(import.meta.url)),lr=(()=>{for(let t of["../package.json","./package.json"]){let e=Pt(hd,t);if(Ke(e))try{return JSON.parse(ic(e,"utf8")).version}catch{}}return"unknown"})();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
912
- `)}),process.on("uncaughtException",t=>{try{pq(2,`[context-mode] uncaughtException: ${t?.message??t}
913
- `)}finally{process.exit(1)}}));Xo=Qr(),gd=Ti(Xo),Re=new Jl({name:"context-mode",version:lr}),ZR=[];VR=qR(),fb=!1;$q=Re.registerTool.bind(Re);Re.registerTool=(...t)=>{let[e,n,r]=t;if(VR){WR();return}let o=Pq(e,r);return ZR.push({name:e,config:n,handler:o}),t[2]=o,$q(...t)};VR&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&KR(Re);bb=new Sq;Re.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Re.server.setRequestHandler(Us,async()=>({prompts:[]}));Re.server.setRequestHandler(Fs,async()=>({resources:[]}));Re.server.setRequestHandler(Hs,async()=>({resourceTemplates:[]}));ac=new ci({runtimes:Xo,projectRoot:()=>Rt()}),Ed=zt(_b(),`cm-fs-preload-${process.pid}.js`);_d(Ed,`(function(){var __cm_fs=0;process.on('exit',function(){if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch(e){}});try{var f=require('fs');var ors=f.readFileSync;f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};}catch(e){}})();
914
- `);process.on("exit",()=>{try{hi(Ed)}catch{}});wn=null;En=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};dr=null,md=0,$R=0,Dq=3,Mq=3600*1e3;RR=!1;Uq=500,Bq=2,Zq=3e4,qq=256,hb=0,Vq=/^[A-Za-z0-9._-]+$/;Gq=gd.join(", "),Jq=hr()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",Xq="",Yq="";CR=500;rC=12e4;OR=2e3;Re.registerTool("ctx_execute",{title:"Run code in a sandbox (executes the supplied code)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${Jq} Languages: ${Gq}.
915
-
916
- Think-in-Code \u2014 the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.
917
-
918
- Concrete shape \u2014 analyze 47 source files without reading any of them:
919
- ctx_execute(language: "javascript", code: \`
920
- const fs = require('fs');
921
- const files = fs.readdirSync('src').filter(f => f.endsWith('.ts'));
922
- files.forEach(f => {
923
- const lines = fs.readFileSync('src/'+f,'utf8').split('\\\\n').length;
924
- console.log(f + ': ' + lines + ' lines');
925
- });
926
- \`)
927
- // 47 files analyzed, 15,314 LoC summarized \u2014 output ~3.6 KB instead of 47 Read() calls = ~700 KB.
928
-
929
- WHEN:
930
- - You intend to derive an answer FROM data (filter, count, aggregate, parse, compare, transform) \u2014 do the derivation in code and print only the answer
931
- - Output shape or size cannot be predicted before execution (recursive finds, repo-wide greps, list endpoints, query results, log scans)
932
- - You would otherwise read raw output and then mentally compute \u2014 that compute belongs here, in code, where its inputs stay out of your conversation
933
- - You need to keep a long-running process alive (dev server, watcher, daemon) \u2014 pass \`background: true\` to detach on timeout instead of killing the process
934
- - The output may legitimately be large but you only want recall-by-topic later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed into the knowledge base and only the section titles + previews come back, retrievable via ctx_search
935
-
936
- WHEN NOT:
937
- - Single observational command whose entire short output you intend to consume verbatim (whoami, pwd, git status on a clean tree) \u2014 Bash is simpler
938
- - File mutations (Edit/Write) or navigation (cd/ls) \u2014 Bash is the right surface
939
- - You already know the output is one short fixed line and you want to read it as-is
940
-
941
- RETURNS:
942
- Only what your code prints. Wrap risky calls in try/catch \u2014 uncaught errors go to stderr and may leak more than intended. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.
943
-
944
- EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('npm test', {encoding:'utf8', stdio:['ignore','pipe','pipe']}); console.log(out.split('\\\\n').filter(l => /(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))/i.test(l)).slice(0, 60).join('\\\\n'))")
945
- EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:j.object({language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:j.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:j.preprocess(wb,j.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),cwd:j.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),intent:j.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
946
-
947
- TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=xb(e,"execute");if(i)return i}else{let i=YR(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
948
- // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
949
- let __cm_fs=0;
950
- process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
951
- (function(){
952
- try{
953
- var f=typeof require!=='undefined'?require('fs'):null;
954
- if(!f)return;
955
- var ors=f.readFileSync;
956
- f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};
957
- var orf=f.readFile;
958
- if(orf)f.readFile=function(){var a=Array.from(arguments),cb=a.pop();orf.apply(this,a.concat([function(e,d){if(!e&&d){if(Buffer.isBuffer(d))__cm_fs+=d.length;else if(typeof d==='string')__cm_fs+=Buffer.byteLength(d);}cb(e,d);}]));};
959
- }catch{}
960
- })();
961
- let __cm_net=0;
962
- // Report network bytes on process exit \u2014 works with both promise and callback patterns.
963
- // process.on('exit') fires after all I/O completes, unlike .finally() which fires
964
- // when __cm_main() resolves (immediately for callback-based http.get without await).
965
- process.on('exit',()=>{if(__cm_net>0)try{process.stderr.write('__CM_NET__:'+__cm_net+'\\n')}catch{}});
966
- ;(function(__cm_req){
967
- // Intercept globalThis.fetch
968
- const __cm_f=globalThis.fetch;
969
- globalThis.fetch=async(...a)=>{const r=await __cm_f(...a);
970
- try{const cl=r.clone();const b=await cl.arrayBuffer();__cm_net+=b.byteLength}catch{}
971
- return r};
972
- // Shadow CJS require with http/https network tracking.
973
- const __cm_hc=new Map();
974
- const __cm_hm=new Set(['http','https','node:http','node:https']);
975
- function __cm_wf(m,origFn){return function(...a){
976
- const li=a.length-1;
977
- if(li>=0&&typeof a[li]==='function'){const oc=a[li];a[li]=function(res){
978
- res.on('data',function(c){__cm_net+=c.length});oc(res);};}
979
- const req=origFn.apply(m,a);
980
- const oOn=req.on.bind(req);
981
- req.on=function(ev,cb,...r){
982
- if(ev==='response'){return oOn(ev,function(res){
983
- res.on('data',function(c){__cm_net+=c.length});cb(res);
984
- },...r);}
985
- return oOn(ev,cb,...r);
986
- };
987
- return req;
988
- }}
989
- var require=__cm_req?function(id){
990
- const m=__cm_req(id);
991
- if(!__cm_hm.has(id))return m;
992
- const k=id.replace('node:','');
993
- if(__cm_hc.has(k))return __cm_hc.get(k);
994
- const w=Object.create(m);
995
- if(typeof m.get==='function')w.get=__cm_wf(m,m.get);
996
- if(typeof m.request==='function')w.request=__cm_wf(m,m.request);
997
- __cm_hc.set(k,w);return w;
998
- }:__cm_req;
999
- if(__cm_req){if(__cm_req.resolve)require.resolve=__cm_req.resolve;
1000
- if(__cm_req.cache)require.cache=__cm_req.cache;}
1001
- async function __cm_main(){
1002
- ${e}
1003
- }
1004
- __cm_main().catch(e=>{console.error(e);process.exitCode=1});${r?`
1005
- setInterval(()=>{},2147483647);`:""}
1006
- })(typeof require!=='undefined'?require:null);`);let a=Td(n),c=await ac.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=oC(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ie.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ie.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let h=c.stdout?.trim();return c.backgrounded&&h?X("ctx_execute",{content:[{type:"text",text:`${u}${h}
1007
-
1008
- _(process backgrounded after ${a}ms \u2014 still running)_`}]}):h?X("ctx_execute",{content:[{type:"text",text:`${u}${h}
1009
-
1010
- _(timed out after ${a}ms \u2014 partial output shown above)_`}]}):X("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms
1011
-
1012
- stderr:
1013
- ${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:h,output:m}=rb({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(m)>kd?(Tn(Buffer.byteLength(m)),X("ctx_execute",{content:[{type:"text",text:`${u}${fi(m,s,h?`execute:${t}:error`:`execute:${t}`)}`}],isError:h})):Buffer.byteLength(m)>wd?(Tn(Buffer.byteLength(m)),X("ctx_execute",{content:[{type:"text",text:`${u}${fi(m,"errors failures exceptions",h?`execute:${t}:error`:`execute:${t}`)}`}],isError:h})):X("ctx_execute",{content:[{type:"text",text:`${u}${m}`}],isError:h})}let p=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(p)>kd)return Tn(Buffer.byteLength(p)),X("ctx_execute",{content:[{type:"text",text:`${u}${fi(p,s,`execute:${t}`)}`}]});if(Buffer.byteLength(p)>wd){let h=iC(p,`execute:${t}`),m={...h,content:h.content.map((f,g)=>g===0&&f.type==="text"?{...f,text:`${u}${f.text}`}:f)};return X("ctx_execute",m)}return X("ctx_execute",{content:[{type:"text",text:`${u}${p}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return X("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});kd=5e3,wd=102400;Re.registerTool("ctx_execute_file",{title:"Run code over a file (executes code, reads the given path)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
1014
-
1015
- Think-in-Code applied to file-level analysis: Reading the whole file means every byte enters your conversation memory and costs reasoning capacity for the rest of the session. Running code over it here lets you keep the raw bytes out and only the derived answer in. Same principle as ctx_execute, scoped to one named file via the FILE_CONTENT variable.
1016
-
1017
- WHEN:
1018
- - You want to KNOW SOMETHING ABOUT a file (line count, matches of a pattern, parsed structure, statistical aggregate) without needing to SEE all of it
1019
- - The file is structured (CSV, JSON, log, code) and a code-level derivation is cheaper than reading verbatim
1020
- - The file is large enough that reading the full content would burn meaningful conversation memory you need for the actual work
1021
- - The derivation may itself produce a large output you want recall-by-topic on later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed and only matching sections come back, retrievable via ctx_search
1022
-
1023
- WHEN NOT:
1024
- - You intend to EDIT the file \u2014 use Read so the subsequent Edit can match the exact text
1025
- - You only need one specific line and you know its offset \u2014 Read with offset/limit is the simplest path
1026
- - The file is small AND you will consume all of it for understanding/editing \u2014 Read directly
1027
-
1028
- RETURNS:
1029
- Only what your code prints. The FILE_CONTENT variable holds the raw bytes inside the sandbox; nothing else leaves. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout.
1030
-
1031
- EXAMPLE: ctx_execute_file(path: "huge.log", language: "javascript", code: "const errs = FILE_CONTENT.split('\\\\n').filter(l => /ERROR|FATAL/.test(l)); console.log(\`\${errs.length} error lines\`); console.log(errs.slice(-5).join('\\\\n'))")
1032
- EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:j.object({path:j.string().describe("Absolute file path or relative to project root"),language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:j.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:j.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:n,timeout:r,intent:o})=>{let s=Kq(t,"ctx_execute_file");if(s)return s;let i=gb(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=xb(n,"execute_file");if(a)return a}else{let a=YR(n,e,"execute_file");if(a)return a}try{let a=Td(r),c=await ac.executeFile({path:t,language:e,code:n,timeout:a}),u=oC(e,n,t);if(c.timedOut)return X("ctx_execute_file",{content:[{type:"text",text:`${u}Timed out processing ${t} after ${a}ms`}],isError:!0});if(c.exitCode!==0){let{isError:d,output:p}=rb({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(p)>kd?(Tn(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${fi(p,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(p)>wd?(Tn(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${fi(p,"errors failures exceptions",d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):X("ctx_execute_file",{content:[{type:"text",text:`${u}${p}`}],isError:d})}let l=c.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>kd)return Tn(Buffer.byteLength(l)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${fi(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>wd){let d=iC(l,`file:${t}`),p={...d,content:d.content.map((h,m)=>m===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return X("ctx_execute_file",p)}return X("ctx_execute_file",{content:[{type:"text",text:`${u}${l}`}]})}catch(a){let c=a instanceof Error?a.message:String(a);return X("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${c}`}],isError:!0})}});Re.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
1033
-
1034
- WHEN:
1035
- - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
1036
- - API references (endpoint details, parameter specs, response schemas)
1037
- - MCP tools/list output (exact tool signatures and descriptions)
1038
- - Skill prompts and instructions that are too large to keep verbatim in conversation
1039
- - README files, migration guides, changelog entries
1040
- - Any content with code examples you may need to reference precisely later
1041
-
1042
- WHEN NOT:
1043
- - Log files, test output, CSV, or build output \u2014 use ctx_execute_file, which processes in-sandbox without persisting bytes
1044
- - Single-use ephemeral content you will not query later \u2014 keep it inline if it fits, or ctx_execute_file it
1045
-
1046
- RETURNS:
1047
- Indexing metadata: chunk counts (total, code-bearing), source label, and the exact ctx_search call shape to query the indexed content. Raw content is NOT echoed back \u2014 it lives in storage, retrievable via ctx_search(source: "<label>"). When \`path\` is provided, a content hash is stored so ctx_search results auto-flag staleness on future calls.
1048
-
1049
- EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
1050
- EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:j.object({content:j.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:j.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:j.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:j.array(j.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:j.array(j.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:j.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:j.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:j.array(j.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:j.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:j.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:n,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return X("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=gb(e,"ctx_index");if(l)return l}try{let l=e?Aq(e):void 0;if(l&&Ke(l)&&FR(l).isSymbolicLink()){let m;try{m=HR(l)}catch{return X("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(m!==l){let f=gb(m,"ctx_index");if(f)return f}}if(l&&Ke(l)&&zR(l).isDirectory()){let h=Zn(),m=Rt(),f=fo("Read",m),g=process.platform==="win32",y=A=>{try{return Pr(A,f,g,m).denied}catch{return!1}},_=h.indexDirectory({path:l,source:n??l,attribution:pr(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),b=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",S=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",E=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return X("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${b}${S}${E}
1051
- Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)Tn(Buffer.byteLength(t));else if(l)try{let h=await import("fs");Tn(h.readFileSync(l).byteLength)}catch{}let p=Zn().index({content:t,path:l,source:n??l,attribution:pr()});return X("ctx_index",{content:[{type:"text",text:`Indexed ${p.totalChunks} sections (${p.codeChunks} with code) from: ${p.label}
1052
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${p.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return X("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});n4=vb("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),yb=vb("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),yd=vb("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),r4=new rd({windowMs:n4,softCapAfter:yb,blockAfter:yd});Re.registerTool("ctx_search",{title:"Search Indexed Content",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:cR(ub)},async t=>{try{let e=Zn(),n=t.sort||"relevance";if(n!=="timeline"&&e.getStats().chunks===0)return X("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
1053
-
1054
- ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
1055
- \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
1056
- \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
1057
- \u2022 ctx_index(content, source) \u2014 manually index text content
1058
-
1059
- After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let r=t,o=[];if(Array.isArray(r.queries)&&r.queries.length>0?o.push(...r.queries):typeof r.query=="string"&&r.query.length>0&&o.push(r.query),o.length===0)return X("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=uR(c,ub,()=>Rt()),l=Date.now(),d=r4.record(o4(),l),p=d.count;if(d.blocked)return X("ctx_search",{content:[{type:"text",text:`BLOCKED: ${p} search calls in ${Math.round((l-d.windowStart)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let h=d.softCapped?1:Math.min(s,2),m=40*1024,f=0,g=[],y=null;if(n==="timeline"||typeof u=="string")try{let T=We(),P=Rt(),N=ls({projectDir:P,sessionsDir:T});Ke(N)&&(y=new Gt({dbPath:N}))}catch{}let b;if(typeof u=="string"&&y)try{b=new Set(y.getSessionIdsForProject(u))}catch{}let S=En?.getConfigDir()??Be();try{for(let T of o){if(f>m){g.push(`## ${T}
1060
- (output cap reached)
1061
- `);continue}let P;if(n==="timeline"?P=iR({query:T,limit:h,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:Rt(),configDir:S,adapter:En??void 0,projectScope:u}):P=e.searchWithFallback(T,h,i,a,"like",b),P.length===0){g.push(`## ${T}
1062
- No results found.`);continue}let N=P.map((R,C)=>{let F=R.origin||"current-session",W=R.timestamp?R.timestamp.slice(0,16).replace("T"," "):"",ge=`--- [${F}${W?" | "+W:""} | ${R.source}] ---`,Le=`### ${R.title}`,st=Sb(R.content,T,1500,R.highlighted);return`${ge}
1063
- ${Le}
1064
-
1065
- ${st}`}).join(`
1066
-
1067
- `);g.push(`## ${T}
1068
-
1069
- ${N}`),f+=N.length}}finally{try{y?.close()}catch{}}let E=g.join(`
1070
-
1071
- ---
1072
-
1073
- `);e.lastRefreshCount>0&&(E=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
1074
-
1075
- `+E);let A=Math.max(0,yd-p),x=Math.max(0,yb-p);if(p>=yb?E+=`
1076
-
1077
- \u26A0 search call #${p}/${yd} in this window. Results limited to ${h}/query. ${A} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:E+=`
1078
-
1079
- > Throttle: call #${p}/${yd} in this window. ${x} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,E.trim().length===0){let T=e.listSources(),P=T.length>0?`
1080
- Indexed sources: ${T.map(N=>`"${N.label}" (${N.chunkCount} sections)`).join(", ")}`:"";return X("ctx_search",{content:[{type:"text",text:`No results found.${P}`}]})}return X("ctx_search",{content:[{type:"text",text:E}]})}catch(e){let n=e instanceof Error?e.message:String(e);return X("ctx_search",{content:[{type:"text",text:`Search error: ${n}`}],isError:!0})}});lb=null,db=null;c4=1440*60*1e3,NR=3072;Re.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
1081
-
1082
- Caching: every fetch is cached on disk and reused for repeat calls within the TTL window. The default TTL is 24 hours; override per-call with the \`ttl\` parameter (milliseconds, \`ttl: 0\` bypasses cache like \`force: true\`). Stored content older than 14 days is cleaned up on startup.
1083
-
1084
- WHEN:
1085
- - You need web content (docs, changelogs, API references, spec pages) and the raw page bytes should NOT enter your conversation
1086
- - Multi-URL research (library evaluation, migration scans, doc comparisons): pass the \`requests\` array and a \`concurrency\` value 2-8 for parallel I/O
1087
- - You want repeat lookups against the same URL to be cheap (TTL cache hits return only a hint, no re-fetch)
1088
- - You want a long-lived cache window (override \`ttl\` upward for stable specs) or a guaranteed-fresh fetch (\`ttl: 0\` or \`force: true\`)
1089
-
1090
- WHEN NOT:
1091
- - You already have the content locally \u2014 store it via the inline index tool
1092
- - The page is SPA-rendered (JavaScript-required to materialize content) \u2014 this is a plain HTTP fetch, no headless browser
1093
-
1094
- RETURNS:
1095
- Per-source preview windows extracted around indexable headings plus indexing metadata (chunk counts, source labels, cache state). Raw content is NOT echoed back \u2014 retrieve any section on-demand via ctx_search(source: "<label>"). Concurrency parallelizes the fetch phase up to your chosen value (capped by the host's logical CPU count); the FTS5 write phase always runs serially because SQLite is a single-writer store. Net latency = max(fetch latency across the pool) + sum(per-source index write time). Cache hits skip both phases and return a small freshness hint instead of re-fetching. Use 4-8 for stable I/O-bound batches; lower the value when the target host enforces a per-IP rate limit you cannot raise.
1096
-
1097
- EXAMPLE: ctx_fetch_and_index(
1098
- requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
1099
- concurrency: 5
1100
- )`,inputSchema:j.object({url:j.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:j.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:j.preprocess(kb,j.array(j.object({url:j.string().describe("URL to fetch"),source:j.string().optional().describe("Label for this URL's indexed content")})).min(1)).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:j.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:j.preprocess(wb,j.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:j.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:n,concurrency:r,force:o,ttl:s})=>{let i=n||(t?[{url:t,source:e}]:[]);if(i.length===0)return X("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!n&&i.length===1,c=r??1,u=i.map(R=>({run:()=>d4(R.url,R.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:p}=await tb(u,{concurrency:c,capByCpuCount:!a&&c>1}),h=[];for(let R=0;R<l.length;R++){let C=l[R];if(C.status==="rejected"){let W=C.reason instanceof Error?C.reason.message:String(C.reason);h.push({kind:"job_error",url:i[R].url,error:W});continue}let F=C.value;if(F.kind==="cached"){ie.cacheHits++,ie.cacheBytesSaved+=F.estimatedBytes;let W=F.estimatedBytes,ge=F.label;setImmediate(()=>JP({sessionDbPath:oc(),source:ge,bytesAvoided:W})),h.push({kind:"cached",label:F.label,chunkCount:F.chunkCount,ageStr:F.ageStr,ttlStr:F.ttlStr})}else F.kind==="fetch_error"?h.push({kind:"fetch_error",url:F.url,error:F.error,reason:F.reason}):(ie.cacheMisses++,h.push({kind:"fetched",indexed:p4(F)}))}if(a){let R=h[0];if(R.kind==="cached")return X("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${R.label}** \u2014 ${R.chunkCount} sections, indexed ${R.ageStr} (fresh, TTL: ${R.ttlStr}).
1101
- To refresh: call ctx_fetch_and_index again with \`force: true\`.
1102
-
1103
- You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
1104
- Use: ctx_search(queries: [...], source: "${R.label}")`}]});if(R.kind==="fetched"){let C=(R.indexed.totalBytes/1024).toFixed(1),F=[`Fetched and indexed **${R.indexed.totalChunks} sections** (${C}KB) from: ${R.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${R.indexed.label}") for specific lookups.`,"","---","",R.indexed.preview].join(`
1105
- `);return X("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if(R.kind==="fetch_error"){let C=R.reason==="empty"?`Fetched ${R.url} but got empty content`:R.reason==="read"?`Fetched ${R.url} but could not read subprocess output`:R.reason==="exit"?`Failed to fetch ${R.url}: ${R.error}`:`Fetch error: ${R.error}`;return X("ctx_fetch_and_index",{content:[{type:"text",text:C}],isError:!0})}return X("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${R.error}`}],isError:!0})}let m=384,f=[],g=0,y=0,_=0,b=0,S=0,E=[];for(let R of h)if(R.kind==="cached")_++,f.push(`- [cache] ${R.label} \u2014 ${R.chunkCount} sections (${R.ageStr}, TTL: ${R.ttlStr})`);else if(R.kind==="fetched"){b++,g+=R.indexed.totalChunks,y+=R.indexed.totalBytes;let C=(R.indexed.totalBytes/1024).toFixed(1);f.push(`- [new] ${R.indexed.label} \u2014 ${R.indexed.totalChunks} sections (${C}KB)`);let F=R.indexed.preview.length>m?R.indexed.preview.slice(0,m).trimEnd()+"\u2026":R.indexed.preview;E.push(`### ${R.indexed.label}
1106
-
1107
- ${F}`)}else S++,f.push(`- [err] ${R.url}: ${R.error}`);let A=(y/1024).toFixed(1),x=p?` cap=${d}/${bq().length}cpu`:"",T=(R,C,F)=>`${R} ${R===1?C:F}`,N=[`fetched ${i.length} c=${d}${x}. ok=${b} cache=${_} err=${S}. ${T(g,"section","sections")} ${A}KB.`,"",...f,"",'ctx_search(queries: [...], source: "<label>") for full content.',...E.length>0?["","---","",...E]:[]].join(`
1108
- `);return X("ctx_fetch_and_index",{content:[{type:"text",text:N}],isError:S===i.length})});Re.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
1109
-
1110
- Concurrency parallelizes the FETCH phase (run-the-commands). The DERIVATION phase \u2014 turning raw output into an answer \u2014 still belongs in code: add a processing command that consumes the indexed output and prints only the answer, so the raw bytes never enter your conversation (Think-in-Code, same principle as the sandbox tool).
1111
-
1112
- WHEN:
1113
- - You have 3+ related commands you would otherwise run sequentially (multi-issue lookups, git log + git diff + git blame, multi-file reads, multi-region cloud queries)
1114
- - You want to gather AND query in one round trip \u2014 pass \`queries\` so the matching sections come back inline
1115
- - You want to parallelize I/O-bound work \u2014 pass \`concurrency\` 2-8 (network calls, gh CLI, cloud APIs, multi-repo git reads)
1116
- - The combined output is large enough that piping it through ctx_search later would itself be expensive \u2014 let auto-index + inline queries do both in one shot
1117
-
1118
- WHEN NOT:
1119
- - Single command with no follow-up query \u2014 run it in the sandbox tool directly
1120
- - CPU-bound or stateful commands \u2014 keep concurrency at 1 (npm test, build, lint, port-binding servers, lock-file holders, anything that races on the same resource)
1121
-
1122
- RETURNS:
1123
- Auto-indexed section list per command label, plus top matches per query (when \`queries\` is passed). Raw output is NOT echoed in full \u2014 only the matched windows. Concurrency>1 switches each command to its own per-command timeout (no shared budget); concurrency=1 preserves the legacy shared-budget cascading-skip-on-timeout path. Use 4-8 for I/O-bound batches; keep at 1 for CPU work or shared-state commands; lower the value when target hosts enforce per-IP rate limits.
1124
-
1125
- EXAMPLE: ctx_batch_execute(
1126
- commands: [
1127
- {label: "issue 1", command: "gh issue view 1"},
1128
- {label: "issue 2", command: "gh issue view 2"},
1129
- {label: "summarize", command: "echo done"}
1130
- ],
1131
- queries: ["root cause", "proposed fix"],
1132
- concurrency: 2
1133
- )`,inputSchema:j.object({commands:j.preprocess(s4,j.array(j.object({label:j.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:j.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:j.preprocess(kb,j.array(j.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:j.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:j.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip."),cwd:j.string().optional().describe("Optional working directory for all shell commands in this batch."),query_scope:j.enum(["batch","global"]).optional().default("batch").describe("Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands \u2014 useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) \u2014 useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.")})},async({commands:t,queries:e,timeout:n,concurrency:r,cwd:o,query_scope:s})=>{for(let i of t){let a=xb(i.command,"batch_execute");if(a)return a}try{let i=tC(Xo.shell,Ed),a=Td(n),{outputs:c,timedOut:u}=await sC(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:x=>{ie.bytesSandboxed+=x}},ac),l=c.join(`
1134
- `),d=Buffer.byteLength(l),p=l.split(`
1135
- `).length;if(u&&c.length===0)return X("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});Tn(d);let h=Zn(),m=`batch:${t.map(x=>x.label).join(",").slice(0,80)}`,f=h.index({content:l,source:m,attribution:pr()}),g=["## Commands",""];for(let x of t)g.push(`- ${x.label}: \`${nC(x.command)}\``);let y=h.getChunksBySource(f.sourceId),_=["## Indexed Sections",""],b=[];for(let x of y){let T=Buffer.byteLength(x.content);_.push(`- ${x.title} (${(T/1024).toFixed(1)}KB)`),b.push(x.title)}let S=eC(h,e,m,void 0,s),E=h.getDistinctiveTerms?h.getDistinctiveTerms(f.sourceId):[],A=[`Executed ${t.length} commands (${p} lines, ${(d/1024).toFixed(1)}KB). Indexed ${f.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...S,E.length>0?`
1136
- Searchable terms for follow-up: ${E.join(", ")}`:""].join(`
1137
- `);return X("ctx_batch_execute",{content:[{type:"text",text:A}]})}catch(i){let a=i instanceof Error?i.message:String(i);return X("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});Re.registerTool("ctx_stats",{title:"Session Statistics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:j.object({})},async()=>{let t;try{let e=Rt(),n=rt(e),r=ls({projectDir:e,sessionsDir:We()});if(Ke(r)){let o=nt(),s=new o(r,{readonly:!0});try{let i=new pi(s),a=i.queryAll(ie),c=i.getMcpToolUsage(),u=ec({sessionsDir:We()}),l;try{l=ld()}catch{}let d,p;try{let m=process.env.CLAUDE_SESSION_ID;if(m||(m=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),m){d=kR({sessionId:m,sessionsDir:We(),worktreeHash:n});let f=Sd(),g;try{let S=nt(),E=(await import("node:fs")).readdirSync(We()).filter(x=>x.endsWith(".db")&&(!n||x.startsWith(n))),A;for(let x of E)try{let T=new S((await import("node:path")).join(We(),x),{readonly:!0});try{let P=T.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(m);if(P?.project_dir){A=P.project_dir;break}}finally{T.close()}}catch{}g=A?tc({projectDir:A,sessionsDir:We(),worktreeHash:n,contentDbPath:f}):tc({sessionId:m,sessionsDir:We(),worktreeHash:n,contentDbPath:f})}catch{g=tc({sessionId:m,sessionsDir:We(),worktreeHash:n,contentDbPath:f})}let y=tc({sessionsDir:We()}),_=wR(f),b={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};p={conversation:g,lifetime:b}}}catch{}En?.name==="Pi"&&pb(u,We());let h;try{h=Zn().getIndexState()}catch{}t=dd(a,lr,dr,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:p,indexState:h,cwd:e})}finally{s.close()}}else{let s=new pi(DR()).queryAll(ie),i=ec({sessionsDir:We()});En?.name==="Pi"&&pb(i,We());let a;try{a=ld()}catch{}let c;try{c=Zn().getIndexState()}catch{}t=dd(s,lr,dr,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new pi(DR()).queryAll(ie),r;try{r=ec({sessionsDir:We()})}catch{}En?.name==="Pi"&&r&&pb(r,We());let o;try{o=ld()}catch{}t=dd(n,lr,dr,r||o?{lifetime:r,multiAdapter:o}:void 0)}return X("ctx_stats",{content:[{type:"text",text:t}]})});Re.registerTool("ctx_doctor",{title:"Run Diagnostics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:j.object({})},async()=>{let t=["context-mode doctor",""],e;try{e=Qe(Re.server.getClientVersion()??void 0).platform}catch{e=Qe().platform}let n=BR(e),r=11,o=(gd.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${gd.length}/${r} (${o}%) \u2014 ${gd.join(", ")}`),hr()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=xr(mi),i=eo(mi),a=cs(mi);t.push(`[OK] Storage sessions: ${s.path} (${Ci(s)})`),t.push(`[OK] Storage content: ${i.path} (${Ci(i)})`),t.push(`[OK] Storage stats: ${a.path} (${Ci(a)})`);{let u=new ci({runtimes:Xo});try{let l=await u.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(l.exitCode===0&&l.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=l.stderr?.trim()?` (${l.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${l.exitCode}${d}`)}}catch(l){t.push(`[FAIL] Server test: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{u.cleanupBackgrounded()}}{let u;try{let l=nt();u=new l(":memory:"),u.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),u.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=u.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();d&&d.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(l){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{try{u?.close()}catch{}}}let c=await Oq();if(c){for(let l of c.validateHooks(n)){let d=l.status==="pass"?"[OK]":l.status==="warn"?"[WARN]":"[FAIL]",p=l.fix?` \u2014 fix: ${l.fix}`:"";t.push(`${d} ${l.check}: ${l.message}${p}`)}let u=kc(c,n);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=Pt(n,l);Ke(d)?t.push(`[OK] Hook script: PASS \u2014 ${d}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${d}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${lr}`),X("ctx_doctor",{content:[{type:"text",text:t.join(`
1138
- `)}]})});Re.registerTool("ctx_upgrade",{title:"Upgrade Plugin",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:j.object({})},async()=>{let t="",e,n;try{let c=Re.server.getClientVersion(),u=Qe(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=Yr(u.platform)&&Xo.javascript?{platform:u.platform,jsRuntime:Xo.javascript}:void 0}catch{try{n=Qe().platform}catch{}}let r=BR(n),o=Pt(r,"cli.bundle.mjs"),s=Pt(r,"build","cli.js");try{let c=We(),u=zt(yi(c),"insight-cache");Ke(u)&&(lC(4747),LR(u,{recursive:!0,force:!0}))}catch{}let i;if(Ke(o))i=`${ki(o,e)} upgrade${t}`;else if(Ke(s))i=`${ki(s,e)} upgrade${t}`;else{let u=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync,lstatSync}from"node:fs";','import{join,resolve,sep}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(r)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"const PW=resolve(P)+sep;const TW=resolve(T)+sep;","const noSymlink=(src)=>{try{return !lstatSync(src).isSymbolicLink()}catch{return false}};","for(const item of items){const from=resolve(T,item);const to=resolve(P,item);if(!(to+sep).startsWith(PW))continue;if(!(from+sep).startsWith(TW))continue;if(!noSymlink(from))continue;if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true,filter:noSymlink});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
1139
- `),l=Pt(r,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=ki(l,e)}let a=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",i,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
1140
- `);return X("ctx_upgrade",{content:[{type:"text",text:a}]})});Re.registerTool("ctx_purge",{title:"Purge Knowledge Base",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
1141
-
1142
- WHEN:
1143
- - User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
1144
- - User explicitly asks to reset the whole project ('reset everything', 'wipe the knowledge base')
1145
-
1146
- WHEN NOT:
1147
- - User says 'reset', 'clear', or 'wipe' without naming a scope -> ask which scope before calling
1148
- - User wants to free memory or improve performance -> recommend ctx_stats first, do not purge
1149
-
1150
- SCOPES (pass exactly one):
1151
- - Per-session: ctx_purge(confirm: true, sessionId: "<uuid>") deletes that session's events (auto-captured decisions, errors, plans, user prompts, rejected approaches, etc.) and per-session FTS5 chunks; sibling sessions and stats file are preserved.
1152
- - Per-project: ctx_purge(confirm: true, scope: "project") wipes FTS5 knowledge base, every session DB row, events markdown, and resets the stats file. Use ctx_stats first to preview category counts before purging.
1153
-
1154
- CONTRACT:
1155
- - confirm:true is required; confirm:false returns 'purge cancelled'.
1156
- - sessionId and scope:'project' together return 'ambiguous - pick one'.
1157
- - scope:'session' without sessionId throws (sessionId required).
1158
- - Bare {confirm:true} is deprecated: maps to scope:'project' with a stderr warning; will hard-error in a future major.
1159
-
1160
- RETURNS:
1161
- A summary of removed rows + the resolved scope.
1162
-
1163
- EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
1164
- EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:j.object({confirm:j.preprocess(wb,j.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:j.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:j.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:n})=>{if(e&&n==="project")return X("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return X("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let r=n??(e?"session":"project");!n&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=Sd()}catch{}if(wn){try{wn.cleanup()}catch{}wn=null}let s=o?yi(o):void 0,{deleted:i}=VP({projectDir:Rt(),sessionsDir:We(),storePath:o,contentDir:s,legacyContentDir:zt(gi(),".context-mode","content"),contentHash:On(Rt()),scope:r,sessionId:e});if(r==="project"){ie.calls={},ie.bytesReturned={},ie.bytesIndexed=0,ie.bytesSandboxed=0,ie.cacheHits=0,ie.cacheBytesSaved=0,ie.sessionStart=Date.now(),i.push("session stats");try{let c=XR();Ke(c)&&hi(c)}catch{}}let a=r==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return X("ctx_purge",{content:[{type:"text",text:a}]})});rc=5e3;mb="https://context-mode.com/insight";Re.registerTool("ctx_insight",{title:"Open Insight Dashboard",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},description:"Opens the context-mode Insight dashboard (https://context-mode.com/insight) in your default browser \u2014 a dashboard launcher for the hosted analytics layer, not a Q&A engine. Insight surfaces per-engineer productive rate, retry waste, blocker detection, and role-narrowed views for CTO, EM, IC, CISO, FinOps, and DevOps. For natural-language queries over your indexed content, use ctx_search.",inputSchema:j.object({})},async()=>{let t=uC(mb),e=t.ok?`Opening Insight in your browser: ${mb}`:`Could not auto-open your browser (${t.reason}).
1165
- Open Insight manually: ${mb}`;return X("ctx_insight",{content:[{type:"text",text:e}]})});GR();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&m4().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var xC={};_e(xC,{needsHookNormalization:()=>uc,normalizeHooksJson:()=>yC,normalizeHooksJsonOnly:()=>bC,normalizeHooksOnStartup:()=>f4,normalizePluginJson:()=>_C});import{existsSync as mC,readFileSync as fC,writeFileSync as hC}from"node:fs";import{resolve as gC}from"node:path";function Jr(t){return String(t).replace(/\\/g,"/")}function Eb(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(Jr(t));return e?e[1]:null}function Tb(t,e){if(!e||!t||typeof t!="string")return!1;let n=Jr(t);$d.lastIndex=0;let r;for(;(r=$d.exec(n))!==null;)if(r[1]!==e)return!0;return!1}function uc(t,e){return!t||typeof t!="string"?!1:t.includes(cc)?!0:Tb(t,Eb(e))}function yC(t,e,n){if(!uc(t,n))return t;let r=Jr(e),o=Jr(n),s=Eb(n),i;try{i=JSON.parse(t)}catch{return t}let a=i?.hooks;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(Array.isArray(l))for(let d of l){let p=d?.hooks;if(Array.isArray(p))for(let h of p){if(typeof h?.command!="string")continue;let m=h.command.includes(cc),f=Tb(h.command,s);if(!m&&!f)continue;let g=h.command;m&&(g=g.replaceAll(cc,o),g=g.replace(/^\s*node\s+/,`"${r}" `)),f&&(g=Jr(g).replace($d,`context-mode/context-mode/${s}`)),h.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function _C(t,e,n){if(!uc(t,n))return t;let r=Jr(e),o=Jr(n),s=Eb(n),i;try{i=JSON.parse(t)}catch{return t}let a=i?.mcpServers;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let l=a[u];if(!(!l||typeof l!="object")){if(Array.isArray(l.args)){let d=l.args,p=d.map(h=>{if(typeof h!="string")return h;let m=h;return m.includes(cc)&&(m=m.replaceAll(cc,o)),Tb(m,s)&&(m=Jr(m).replace($d,`context-mode/context-mode/${s}`)),m});p.some((h,m)=>h!==d[m])&&(l.args=p,c=!0)}l.command==="node"&&c&&(l.command=r)}}return c?JSON.stringify(i,null,2):t}function bC({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}){let o=n||e;if(!(r!=="win32"&&r!=="linux"&&!(n&&n!==e))&&!(!t||!o))try{let a=gC(t,"hooks","hooks.json");if(mC(a)){let c=fC(a,"utf-8");if(uc(c,t)){let u=yC(c,o,t);u!==c&&hC(a,u,"utf-8")}}}catch{}}function f4({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}){if(bC({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}),!(r!=="win32"&&r!=="linux")&&!(!t||!e))try{let o=gC(t,".claude-plugin","plugin.json");if(mC(o)){let s=fC(o,"utf-8");if(uc(s,t)){let i=_C(s,e,t);i!==s&&hC(o,i,"utf-8")}}}catch{}}var cc,$d,SC=v(()=>{"use strict";cc="${CLAUDE_PLUGIN_ROOT}",$d=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});var RC={};_e(RC,{buildHookCommand:()=>TC,ensureShebangAndExecBit:()=>PC,extractNodePath:()=>wC,isStaleNodePath:()=>EC,rewriteShellSnapshots:()=>$C,selfHealCacheHealHook:()=>x4,selfHealShellSnapshots:()=>S4});import{existsSync as lc,readFileSync as $b,writeFileSync as Pb,chmodSync as h4,statSync as kC,readdirSync as g4,renameSync as y4,unlinkSync as _4}from"node:fs";import{join as b4}from"node:path";function vC(t){return String(t).replace(/\\/g,"/")}function wC(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e)return null;let n;if(e.startsWith('"')){let o=e.indexOf('"',1);if(o===-1)return null;n=e.slice(1,o)}else{let o=e.search(/\s/);n=o===-1?e:e.slice(0,o)}if(!n)return null;let r=n.split(/[\\/]/).pop()??"";return/^node(\.exe)?$/i.test(r)?n:null}function EC(t){let e=wC(t);if(!e)return!1;try{return!lc(e)}catch{return!1}}function TC({scriptPath:t,platform:e,nodePath:n}){if(!t||typeof t!="string")throw new TypeError("buildHookCommand: scriptPath is required");let r=vC(t);if(e==="win32"){if(!n||typeof n!="string")throw new TypeError("buildHookCommand: nodePath is required on win32");return`"${vC(n)}" "${r}"`}return`"${r}"`}function x4({settingsPath:t,scriptPath:e,platform:n,nodePath:r}){if(!t||!lc(t))return"missing-settings";let o;try{o=$b(t,"utf-8")}catch{return"noop"}let s;try{s=JSON.parse(o)}catch{return"noop"}let i=s?.hooks;if(!i||typeof i!="object")return"noop";let a=Array.isArray(i.SessionStart)?i.SessionStart:null;if(!a)return"noop";let c=!1;for(let u of a){let l=u?.hooks;if(Array.isArray(l))for(let d of l)typeof d?.command=="string"&&d.command.includes("context-mode-cache-heal")&&EC(d.command)&&(d.command=TC({scriptPath:e,platform:n,nodePath:r}),c=!0)}if(!c)return"noop";if(n!=="win32"&&e&&lc(e))try{PC(e)}catch{}try{Pb(t,JSON.stringify(s,null,2)+`
1166
- `,"utf-8")}catch{return"noop"}return"healed"}function $C({snapshotsDir:t,currentVersion:e}){let n={rewritten:[]};if(!t||typeof t!="string"||!e||typeof e!="string")return n;let r;try{if(!lc(t))return n;r=g4(t)}catch{return n}let o=/(context-mode[/\\]context-mode[/\\])([^/\\]+)([/\\]bin)/g;for(let s of r){if(!s.endsWith(".sh"))continue;let i=b4(t,s),a;try{if(!kC(i).isFile())continue;a=$b(i,"utf-8")}catch{continue}let c=!1,u=a.replace(o,(d,p,h,m)=>h===e?d:(c=!0,`${p}${e}${m}`));if(!c)continue;let l=`${i}.tmp-${process.pid}-${Date.now()}`;try{Pb(l,u,"utf-8"),y4(l,i),n.rewritten.push(i)}catch{try{_4(l)}catch{}}}return n}function S4({snapshotsDir:t,pluginCacheRoot:e,currentVersion:n}){return $C({snapshotsDir:t,currentVersion:n})}function PC(t){if(!(!t||!lc(t)))try{let e=$b(t,"utf-8");e.startsWith("#!")||Pb(t,`#!/usr/bin/env node
1167
- ${e}`,"utf-8"),(kC(t).mode&511)!==493&&h4(t,493)}catch{}}var CC=v(()=>{"use strict"});import{stdout as pO,stdin as mO}from"node:process";import*as mr from"node:readline";var Nb=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,Db=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Mb=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var Ld=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,fc=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,hc=/\t{1,1000}/y,zd=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),gc=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,tO=new RegExp("\\p{M}+","gu"),nO={limit:1/0,ellipsis:""},jb=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?jb(o,nO,n).width:0),i=n.ansiWidth??0,a=n.controlWidth??0,c=n.tabWidth??8,u=n.ambiguousWidth??1,l=n.emojiWidth??2,d=n.fullWidthWidth??2,p=n.regularWidth??1,h=n.wideWidth??2,m=0,f=0,g=t.length,y=0,_=!1,b=g,S=Math.max(0,r-s),E=0,A=0,x=0,T=0;e:for(;;){if(A>E||f>=g&&f>m){let P=t.slice(E,A)||t.slice(m,f);y=0;for(let N of P.replaceAll(tO,"")){let R=N.codePointAt(0)||0;if(Db(R)?T=d:Mb(R)?T=h:u!==p&&Nb(R)?T=u:T=p,x+T>S&&(b=Math.min(b,Math.max(E,m)+y)),x+T>r){_=!0;break e}y+=N.length,x+=T}E=A=0}if(f>=g)break;if(gc.lastIndex=f,gc.test(t)){if(y=gc.lastIndex-f,T=y*p,x+T>S&&(b=Math.min(b,f+Math.floor((S-x)/p))),x+T>r){_=!0;break}x+=T,E=m,A=f,f=m=gc.lastIndex;continue}if(Ld.lastIndex=f,Ld.test(t)){if(x+i>S&&(b=Math.min(b,f)),x+i>r){_=!0;break}x+=i,E=m,A=f,f=m=Ld.lastIndex;continue}if(fc.lastIndex=f,fc.test(t)){if(y=fc.lastIndex-f,T=y*a,x+T>S&&(b=Math.min(b,f+Math.floor((S-x)/a))),x+T>r){_=!0;break}x+=T,E=m,A=f,f=m=fc.lastIndex;continue}if(hc.lastIndex=f,hc.test(t)){if(y=hc.lastIndex-f,T=y*c,x+T>S&&(b=Math.min(b,f+Math.floor((S-x)/c))),x+T>r){_=!0;break}x+=T,E=m,A=f,f=m=hc.lastIndex;continue}if(zd.lastIndex=f,zd.test(t)){if(x+l>S&&(b=Math.min(b,f)),x+l>r){_=!0;break}x+=l,E=m,A=f,f=m=zd.lastIndex;continue}f+=1}return{width:_?S:x,index:_?b:g,truncated:_,ellipsed:_&&r>=s}},Lb=jb;var rO={limit:1/0,ellipsis:"",ellipsisWidth:0},oO=(t,e={})=>Lb(t,rO,e).width,xt=oO;var yc="\x1B",Bb="\x9B",sO=39,Hd="\x07",Zb="[",iO="]",qb="m",Ud=`${iO}8;;`,zb=new RegExp(`(?:\\${Zb}(?<code>\\d+)m|\\${Ud}(?<uri>.*)${Hd})`,"y"),Fb=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},Hb=t=>`${yc}${Zb}${t}${qb}`,Ub=t=>`${yc}${Ud}${t}${Hd}`,Fd=(t,e,n)=>{let r=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:xt(i),c=r.next(),u=r.next(),l=0;for(;!c.done;){let d=c.value,p=xt(d);a+p<=n?t[t.length-1]+=d:(t.push(d),a=0),(d===yc||d===Bb)&&(o=!0,s=e.startsWith(Ud,l+1)),o?s?d===Hd&&(o=!1,s=!1):d===qb&&(o=!1):(a+=p,a===n&&!u.done&&(t.push(""),a=0)),c=u,u=r.next(),l+=d.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},aO=t=>{let e=t.split(" "),n=e.length;for(;n&&!xt(e[n-1]);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},cO=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(n.trim!==!1){let m=a.at(-1)??"",f=m.trimStart();m.length!==f.length&&(a[a.length-1]=f,c=xt(f))}d!==0&&(c>=e&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),c=0),(c||n.trim===!1)&&(a[a.length-1]+=" ",c++));let h=xt(p);if(n.hard&&h>e){let m=e-c,f=1+Math.floor((h-m-1)/e);Math.floor((h-1)/e)<f&&a.push(""),Fd(a,p,e),c=xt(a.at(-1)??"");continue}if(c+h>e&&c&&h){if(n.wordWrap===!1&&c<e){Fd(a,p,e),c=xt(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>e&&n.wordWrap===!1){Fd(a,p,e),c=xt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=h}n.trim!==!1&&(a=a.map(d=>aO(d)));let u=a.join(`
1168
- `),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(r+=p,!l)l=p>="\uD800"&&p<="\uDBFF";else continue;if(p===yc||p===Bb){zb.lastIndex=d+1;let m=zb.exec(u)?.groups;if(m?.code!==void 0){let f=Number.parseFloat(m.code);o=f===sO?void 0:f}else m?.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}if(u[d+1]===`
1169
- `){s&&(r+=Ub(""));let h=o?Fb(o):void 0;o&&h&&(r+=Hb(h))}else p===`
1170
- `&&(o&&Fb(o)&&(r+=Hb(o)),s&&(r+=Ub(s)))}return r},uO=/\r?\n/;function Yo(t,e,n){return String(t).normalize().split(uO).map(r=>cO(r,e,n)).join(`
1171
- `)}var Si=xi(Zd(),1);import{ReadStream as Wb}from"node:tty";var fO=["up","down","left","right","space","enter","cancel"],hO=["January","February","March","April","May","June","July","August","September","October","November","December"],Pn={actions:new Set(fO),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...hO],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Kb(t,e){if(typeof t=="string")return Pn.aliases.get(t)===e;for(let n of t)if(n!==void 0&&Kb(n,e))return!0;return!1}var gO=globalThis.process.platform.startsWith("win");function Gb({input:t=mO,output:e=pO,overwrite:n=!0,hideCursor:r=!0}={}){let o=mr.createInterface({input:t,output:e,prompt:"",tabSize:1});mr.emitKeypressEvents(t,o),t instanceof Wb&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(Kb([u,a,c],"cancel")){r&&e.write(Si.cursor.show),process.exit(0);return}if(!n)return;mr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{mr.clearLine(e,1,()=>{t.once("keypress",s)})})};return r&&e.write(Si.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),r&&e.write(Si.cursor.show),t instanceof Wb&&t.isTTY&&!gO&&t.setRawMode(!1),o.terminal=!1,o.close()}}var qd=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Ae,stripVTControlCharacters as T9}from"node:util";import Vt from"node:process";var vi=xi(Zd(),1);function _O(){return Vt.platform!=="win32"?Vt.env.TERM!=="linux":!!Vt.env.CI||!!Vt.env.WT_SESSION||!!Vt.env.TERMINUS_SUBLIME||Vt.env.ConEmuTask==="{cmd::Cmder}"||Vt.env.TERM_PROGRAM==="Terminus-Sublime"||Vt.env.TERM_PROGRAM==="vscode"||Vt.env.TERM==="xterm-256color"||Vt.env.TERM==="alacritty"||Vt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Vd=_O(),bO=()=>process.env.CI==="true";var xe=(t,e)=>Vd?t:e,C9=xe("\u25C6","*"),xO=xe("\u25A0","x"),SO=xe("\u25B2","x"),Wd=xe("\u25C7","o"),vO=xe("\u250C","T"),fr=xe("\u2502","|"),kO=xe("\u2514","\u2014"),O9=xe("\u2510","T"),I9=xe("\u2518","\u2014"),A9=xe("\u25CF",">"),N9=xe("\u25CB"," "),D9=xe("\u25FB","[\u2022]"),M9=xe("\u25FC","[+]"),j9=xe("\u25FB","[ ]"),L9=xe("\u25AA","\u2022"),Jb=xe("\u2500","-"),wO=xe("\u256E","+"),EO=xe("\u251C","+"),TO=xe("\u256F","+"),$O=xe("\u2570","+"),z9=xe("\u256D","+"),PO=xe("\u25CF","\u2022"),RO=xe("\u25C6","*"),CO=xe("\u25B2","!"),OO=xe("\u25A0","x");var O={message:(t=[],{symbol:e=Ae("gray",fr),secondarySymbol:n=Ae("gray",fr),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Pn.withGuide,c=a?n:"",u=a?`${e} `:"",l=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
1172
- `);if(d.length>0){let[p,...h]=d;p.length>0?i.push(`${u}${p}`):i.push(a?e:"");for(let m of h)m.length>0?i.push(`${l}${m}`):i.push(a?n:"")}r.write(`${i.join(`
1173
- `)}
1174
- `)},info:(t,e)=>{O.message(t,{...e,symbol:Ae("blue",PO)})},success:(t,e)=>{O.message(t,{...e,symbol:Ae("green",RO)})},step:(t,e)=>{O.message(t,{...e,symbol:Ae("green",Wd)})},warn:(t,e)=>{O.message(t,{...e,symbol:Ae("yellow",CO)})},warning:(t,e)=>{O.warn(t,e)},error:(t,e)=>{O.message(t,{...e,symbol:Ae("red",OO)})}};var Kd=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Pn.withGuide?`${Ae("gray",vO)} `:"";n.write(`${r}${t}
1175
- `)},_c=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Pn.withGuide?`${Ae("gray",fr)}
1176
- ${Ae("gray",kO)} `:"";n.write(`${r}${t}
1177
-
1178
- `)};var IO=t=>Ae("dim",t),AO=(t,e,n)=>{let r={hard:!0,trim:!1},o=Yo(t,e,r).split(`
1179
- `),s=o.reduce((c,u)=>Math.max(xt(u),c),0),i=o.map(n).reduce((c,u)=>Math.max(xt(u),c),0),a=e-(i-s);return Yo(t,a,r)},bc=(t="",e="",n)=>{let r=n?.output??Vt.stdout,o=n?.withGuide??Pn.withGuide,s=n?.format??IO,i=["",...AO(t,qd(r)-6,s).split(`
1180
- `).map(s),""],a=xt(e),c=Math.max(i.reduce((p,h)=>{let m=xt(h);return m>p?m:p},0),a)+2,u=i.map(p=>`${Ae("gray",fr)} ${p}${" ".repeat(c-xt(p))}${Ae("gray",fr)}`).join(`
1181
- `),l=o?`${Ae("gray",fr)}
1182
- `:"",d=o?EO:$O;r.write(`${l}${Ae("green",Wd)} ${Ae("reset",e)} ${Ae("gray",Jb.repeat(Math.max(c-a-1,1))+wO)}
1183
- ${u}
1184
- ${Ae("gray",d+Jb.repeat(c+2)+TO)}
1185
- `)};var NO=t=>Ae("magenta",t),Gd=({indicator:t="dots",onCancel:e,output:n=process.stdout,cancelMessage:r,errorMessage:o,frames:s=Vd?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=Vd?80:120,signal:a,...c}={})=>{let u=bO(),l,d,p=!1,h=!1,m="",f,g=performance.now(),y=qd(n),_=c?.styleFrame??NO,b=W=>{let ge=W>1?o??Pn.messages.error:r??Pn.messages.cancel;h=W===1,p&&(F(ge,W),h&&typeof e=="function"&&e())},S=()=>b(2),E=()=>b(1),A=()=>{process.on("uncaughtExceptionMonitor",S),process.on("unhandledRejection",S),process.on("SIGINT",E),process.on("SIGTERM",E),process.on("exit",b),a&&a.addEventListener("abort",E)},x=()=>{process.removeListener("uncaughtExceptionMonitor",S),process.removeListener("unhandledRejection",S),process.removeListener("SIGINT",E),process.removeListener("SIGTERM",E),process.removeListener("exit",b),a&&a.removeEventListener("abort",E)},T=()=>{if(f===void 0)return;u&&n.write(`
1186
- `);let W=Yo(f,y,{hard:!0,trim:!1}).split(`
1187
- `);W.length>1&&n.write(vi.cursor.up(W.length-1)),n.write(vi.cursor.to(0)),n.write(vi.erase.down())},P=W=>W.replace(/\.+$/,""),N=W=>{let ge=(performance.now()-W)/1e3,Le=Math.floor(ge/60),st=Math.floor(ge%60);return Le>0?`[${Le}m ${st}s]`:`[${st}s]`},R=c.withGuide??Pn.withGuide,C=(W="")=>{p=!0,l=Gb({output:n}),m=P(W),g=performance.now(),R&&n.write(`${Ae("gray",fr)}
1188
- `);let ge=0,Le=0;A(),d=setInterval(()=>{if(u&&m===f)return;T(),f=m;let st=_(s[ge]),$n;if(u)$n=`${st} ${m}...`;else if(t==="timer")$n=`${st} ${m} ${N(g)}`;else{let mc=".".repeat(Math.floor(Le)).slice(0,3);$n=`${st} ${m}${mc}`}let pc=Yo($n,y,{hard:!0,trim:!1});n.write(pc),ge=ge+1<s.length?ge+1:0,Le=Le<4?Le+.125:0},i)},F=(W="",ge=0,Le=!1)=>{if(!p)return;p=!1,clearInterval(d),T();let st=ge===0?Ae("green",Wd):ge===1?Ae("red",xO):Ae("red",SO);m=W??m,Le||(t==="timer"?n.write(`${st} ${m} ${N(g)}
1189
- `):n.write(`${st} ${m}
1190
- `)),x(),l()};return{start:C,stop:(W="")=>F(W,0),message:(W="")=>{m=P(W??m)},cancel:(W="")=>F(W,1),error:(W="")=>F(W,2),clear:()=>F("",0,!0),get isCancelled(){return h}}},F9={light:xe("\u2500","-"),heavy:xe("\u2501","="),block:xe("\u2588","#")};var H9=`${Ae("gray",fr)} `;var k=xi(Qb(),1);Qo();op();kr();Jt();Em();Om();import{execFileSync as _i,execSync as v4,execFile as k4}from"node:child_process";import{readFileSync as qn,cpSync as OC,accessSync as NC,existsSync as Ze,readdirSync as w4,rmSync as Pd,closeSync as E4,openSync as T4,chmodSync as $4,lstatSync as P4,realpathSync as Od,statSync as DC,constants as MC}from"node:fs";import{request as R4}from"node:https";import{resolve as Q,dirname as jC,join as dc,sep as Vn,basename as C4,isAbsolute as O4}from"node:path";import{tmpdir as I4,devNull as A4,homedir as Id}from"node:os";import{fileURLToPath as N4,pathToFileURL as Ad}from"node:url";import{execFileSync as cD}from"node:child_process";var uD="node.*plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs",lD=`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs' } | Select-Object -ExpandProperty ProcessId`,dD=(t,e)=>cD(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),pD=t=>{try{return process.kill(t,0),!0}catch{return!1}},mD=(t,e)=>{process.kill(t,e)};function fD(t){let e=new Set;for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||!/^\d+$/.test(r))continue;let o=Number.parseInt(r,10);Number.isFinite(o)&&o>0&&e.add(o)}return[...e]}function Vv(t){let e=t.platform??process.platform,n=t.runCommand??dD,r="";try{e==="win32"?r=n("powershell",["-NoProfile","-Command",lD]):r=n("pgrep",["-f",uD])}catch{return[]}return fD(r).filter(o=>o!==t.ownPid&&o!==t.ownPpid)}function hD(t){return new Promise(e=>{setTimeout(e,t)})}async function Wv(t){let e=t.timeoutMs??1500,n=t.pollIntervalMs??100,r=t.isAlive??pD,o=t.sendSignal??mD,s={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return s;let i=new Set,a=new Set;for(let d of t.pids){r(d)&&(i.add(d),a.add(d));try{o(d,"SIGTERM")}catch(p){p?.code!=="ESRCH"&&a.delete(d)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await hD(n);for(let d of[...a])r(d)||(a.delete(d),u++)}let l=0;for(let d of a){try{o(d,"SIGKILL")}catch(p){if(p?.code==="ESRCH"){u++;continue}continue}i.has(d)&&l++}return{terminatedBySigterm:u,terminatedBySigkill:l,totalKilled:u+l}}Im();import{existsSync as kD}from"node:fs";import{execSync as wD,execFileSync as T6,spawnSync as $6}from"node:child_process";function Gv({platform:t=process.platform,existsSync:e=kD,exec:n=wD,now:r=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let o="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(o))return null;let i=n(`"${o}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=r()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
1191
- `)}catch{}return null}return i[1]}catch{return null}}po();Rn();function D4(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}var M4={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs",stop:"hooks/stop.mjs"},"gemini-cli":{beforeagent:"hooks/gemini-cli/beforeagent.mjs",beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},"copilot-cli":{pretooluse:"hooks/copilot-cli/pretooluse.mjs",posttooluse:"hooks/copilot-cli/posttooluse.mjs",precompact:"hooks/copilot-cli/precompact.mjs",sessionstart:"hooks/copilot-cli/sessionstart.mjs",userpromptsubmit:"hooks/copilot-cli/userpromptsubmit.mjs",stop:"hooks/copilot-cli/stop.mjs"},"antigravity-cli":{pretooluse:"hooks/antigravity-cli/pretooluse.mjs",posttooluse:"hooks/antigravity-cli/posttooluse.mjs",stop:"hooks/antigravity-cli/stop.mjs"},kimi:{pretooluse:"hooks/kimi/pretooluse.mjs",posttooluse:"hooks/kimi/posttooluse.mjs",precompact:"hooks/kimi/precompact.mjs",sessionstart:"hooks/kimi/sessionstart.mjs",sessionend:"hooks/kimi/sessionend.mjs",userpromptsubmit:"hooks/kimi/userpromptsubmit.mjs",stop:"hooks/kimi/stop.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function j4(t,e){try{E4(2),T4(A4,"w")}catch{process.stderr.write=(()=>!0)}let n=M4[t]?.[e];n||process.exit(0);let r=bi();await import(Ad(dc(r,n)).href)}var ft=process.argv.slice(2);function L4(){console.log(["Usage:"," context-mode Start MCP server (stdio)"," context-mode index <path> Index a file or directory into the FTS5 knowledge base"," context-mode search <query...> Search the current project's FTS5 knowledge base"," context-mode doctor Diagnose runtime issues, hooks, FTS5, version"," context-mode upgrade Fix hooks, permissions, and settings"," context-mode hook <platform> <event> Dispatch a configured hook script"," context-mode statusline Print Claude Code status line","","Index options:"," --source <label> Source label (default: project:<directory-name> or path)"," --project <path> Project identity for the content DB (default: indexed dir or cwd)"," --max-depth <n> Directory recursion depth (default: 5)"," --max-files <n> Directory file cap (default: 200)"," --ext <.ts,.md> Comma-separated extension allowlist"," --include <glob> Directory include pattern (repeatable)"," --exclude <glob> Directory exclude pattern (repeatable)"," --no-gitignore Do not apply .gitignore during directory walks"," --follow-symlinks Follow directory symlinks inside the root","","Search options:"," --project <path> Project identity for the content DB (default: cwd)"," --source <label> Filter to a source label (partial match)"," --limit <n> Results to show (default: 3)"," --type <code|prose> Filter by content type","","Environment:"," CONTEXT_MODE_DIR=/absolute/path Override sessions/content storage root; empty is ignored, non-empty must be absolute"].join(`
1192
- `))}if(ft[0]==="--help"||ft[0]==="-h"||ft[0]==="help")L4();else if(ft[0]==="index")V4(ft.slice(1)).then(t=>process.exit(t));else if(ft[0]==="search")W4(ft.slice(1)).then(t=>process.exit(t));else if(ft[0]==="doctor")K4().then(t=>process.exit(t));else if(ft[0]==="upgrade"){let t=ft.indexOf("--platform"),e=t>=0&&ft[t+1]?ft[t+1]:void 0;J4(e?{platform:e}:void 0).catch(n=>{let r=n instanceof Error?n.message:String(n);O.error(k.default.red(r)),process.exit(1)})}else ft[0]==="hook"?j4(ft[1],ft[2]):ft[0]==="insight"?G4():ft[0]==="statusline"?X4():Promise.resolve().then(()=>(pC(),dC));function RQ(t){return t.replace(/\\/g,"/")}var Nd=process.platform==="win32";function Rd(t,e={}){_i(Nd?"npm.cmd":"npm",t,{...e,...Nd?{shell:!0}:{}})}function CQ(t,e={}){let n={...e,...Nd?{shell:!0}:{}};v4(Nd?t.replace(/^npm /,"npm.cmd "):t,n)}function z4(t,e=process.platform,n=k4){let r={stdio:"ignore"},o=()=>console.error(`
1193
- Could not auto-open browser. Open manually: ${t}`),s=D4(t,e),i=!1;for(let{cmd:a,args:c}of s)try{n(a,c,r),i=!0;break}catch{}i||o()}function F4(){let t=N4(import.meta.url),e=jC(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?Q(e,".."):e}function H4(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;return n?Q(n,t,...e):Q(Id(),"AppData","Local",t,...e)}return Q(Id(),".cache",t,...e)}function bi(){let t=Qe().platform;return Yr(t)?H4(t):F4()}function LC(){try{return JSON.parse(qn(Q(bi(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function U4(){return new Promise(t=>{let e=R4("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function Cd(t){return t.envVar?t.envVar:"adapter default"}function zC(t){let e=[],n={};for(let r=0;r<t.length;r++){let o=t[r];if(!o.startsWith("--")||o==="--"){e.push(o);continue}let s=o.slice(2),i=s.indexOf("="),a=i>=0?s.slice(0,i):s,c=i>=0?s.slice(i+1):void 0,u=t[r+1],l=c!==void 0?c:u&&!u.startsWith("--")?(r++,u):!0;if(a==="include"||a==="exclude"){let d=n[a];n[a]=Array.isArray(d)?[...d,String(l)]:[String(l)]}else n[a]=l}return{positional:e,flags:n}}function Xr(t,e){let n=t[e];if(typeof n=="string"&&n.length>0)return n}function IC(t,e){return t[e]===!0||t[e]==="true"}function AC(t,e){let n=t[e];if(Array.isArray(n))return n.filter(Boolean);if(typeof n=="string"&&n.length>0)return[n]}function Cb(t,e,n={}){let r=Xr(t,e);if(!r)return;let o=Number(r),s=n.min??1;if(!Number.isInteger(o)||o<s)throw new Error(`--${e} must be an integer >= ${s}`);return o}function B4(t){let e=Xr(t,"ext")??Xr(t,"extensions");if(!e)return;let n=e.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith(".")?r:`.${r}`);return n.length>0?n:void 0}function FC(t,e){return t?Q(t):Q(e)}async function HC(t){let e=await Hi(Qe().platform),n=eo(()=>e.getSessionDir()),r=Sr(n),{resolveContentStorePath:o}=await Promise.resolve().then(()=>(Jt(),Tx)),s=o({projectDir:t,contentDir:r});return{store:new vs(s),dbPath:s,contentDir:r}}function Z4(t){try{if(DC(t).isDirectory())return`project:${C4(t)||t}`}catch{}return t}function q4(t,e){let n=fo("Read",e);if(Pr(t,n,process.platform==="win32",e).denied)throw new Error(`Read denied by policy: ${t}`)}async function V4(t){try{let e=zC(t),n=e.positional[0];if(!n||n==="-h"||n==="--help")return console.log("Usage: context-mode index <path> [--source label] [--project path] [--max-files n] [--max-depth n] [--ext .ts,.md]"),n?0:1;let r=O4(n)?Q(n):Q(process.cwd(),n);if(!Ze(r))throw new Error(`Path does not exist: ${r}`);let o=DC(r),s=FC(Xr(e.flags,"project"),o.isDirectory()?r:jC(r)),i=Xr(e.flags,"source")??Z4(r),{store:a,dbPath:c}=await HC(s);try{if(q4(r,s),o.isDirectory()){let u=fo("Read",s),l=a.indexDirectory({path:r,source:i,include:AC(e.flags,"include"),exclude:AC(e.flags,"exclude"),maxDepth:Cb(e.flags,"max-depth",{min:0}),maxFiles:Cb(e.flags,"max-files"),extensions:B4(e.flags),respectGitignore:!IC(e.flags,"no-gitignore"),followSymlinks:IC(e.flags,"follow-symlinks"),perFileDeny:m=>{try{return Pr(m,u,process.platform==="win32",s).denied}catch{return!1}}}),d=l.capped?` (cap reached at ${l.filesIndexed} files)`:"",p=l.denied>0?`; ${l.denied} denied`:"",h=l.failed>0?`; ${l.failed} failed`:"";console.log(`Indexed ${l.filesIndexed} files (${l.totalChunks} sections) from ${r}${d}${p}${h}`)}else{let u=a.index({path:r,source:i});console.log(`Indexed ${u.totalChunks} sections (${u.codeChunks} with code) from ${r}`)}return console.log(`Source: ${i}`),console.log(`Project: ${s}`),console.log(`DB: ${c}`),0}finally{a.close()}}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`context-mode index: ${n}`),1}}async function W4(t){try{let e=zC(t),n=e.positional.join(" ").trim();if(!n||n==="-h"||n==="--help")return console.log("Usage: context-mode search <query...> [--source label] [--project path] [--limit n] [--type code|prose]"),n?0:1;let r=FC(Xr(e.flags,"project"),process.cwd()),{store:o,dbPath:s}=await HC(r);try{let i=Cb(e.flags,"limit")??3,a=Xr(e.flags,"type");if(a&&a!=="code"&&a!=="prose")throw new Error("--type must be code or prose");let c=o.searchWithFallback(n,i,Xr(e.flags,"source"),a);if(c.length===0)return console.log(`No matches for: ${n}`),console.log(`Project: ${r}`),console.log(`DB: ${s}`),0;for(let[u,l]of c.entries()){let d=l.content.replace(/\s+/g," ").trim(),p=d.length>500?`${d.slice(0,500)}...`:d;console.log(`## ${u+1}. ${l.title}`),console.log(`Source: ${l.source}`),console.log(`Type: ${l.contentType}`),console.log(p),console.log("")}return 0}finally{o.close()}}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`context-mode search: ${n}`),1}}function Rb(t){try{return Sr(t),O.success(k.default.green(`Storage ${t.kind}: PASS`)+k.default.dim(` \u2014 ${t.path} (${Cd(t)})`)),0}catch(e){if(e instanceof Kt)return O.error(k.default.red(`Storage ${t.kind}: FAIL`)+k.default.dim(` \u2014 ${us(e)}`)),1;throw e}}async function K4(){process.stdout.isTTY&&console.clear();let t=Qe(),e=await Hi(t.platform);Kd(k.default.bgMagenta(k.default.white(" context-mode doctor "))),O.info(`Platform: ${k.default.cyan(e.name)}`+k.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let n=0;try{let y=xr(()=>e.getSessionDir()),_=eo(()=>y.path),b=cs(()=>y.path);bc([`sessions: ${y.path} (${Cd(y)})`,`content: ${_.path} (${Cd(_)})`,`stats: ${b.path} (${Cd(b)})`].join(`
1194
- `),"Storage paths"),n+=Rb(y),n+=Rb(_),n+=Rb(b)}catch(y){if(y instanceof Kt)n++,O.error(k.default.red(`Storage ${y.kind}: FAIL`)+k.default.dim(` \u2014 ${us(y)}`));else throw y}let r=Gd();r.start("Running diagnostics");let o,s;try{o=Qr(),s=Ti(o)}catch{return r.stop("Diagnostics partial"),O.warn(k.default.yellow("Could not detect runtimes")+k.default.dim(" \u2014 module may be missing, restart session after upgrade")),_c(k.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}r.stop("Diagnostics complete"),bc(Ei(o),"Runtimes");{let{hasModernSqlite:y}=await Promise.resolve().then(()=>(yr(),ap));process.platform==="linux"&&!y()&&!hr()&&(n++,O.error(k.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+k.default.dim(`
1195
- context-mode requires Node.js >= 22.5 (or Bun) on Linux to avoid the
1196
- V8 madvise(MADV_DONTNEED) SIGSEGV in better-sqlite3 (1-4/hour).
1197
- Refs: https://github.com/nodejs/node/issues/62515
1198
- https://github.com/mksglu/context-mode/issues/564
1199
- Fix: nvm install 22.5 && nvm use 22.5 && npm install -g context-mode
1200
- Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}hr()?O.success(k.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):O.warn(k.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(s.length/i*100).toFixed(0);s.length<2?(n++,O.error(k.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+k.default.dim(` \u2014 ${s.join(", ")||"none"}`))):O.info(`Language coverage: ${s.length}/${i} (${a}%)`+k.default.dim(` \u2014 ${s.join(", ")}`)),O.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(eb(),DP)),b=await new y({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(b.exitCode===0&&b.stdout.trim()==="ok")O.success(k.default.green("Server test: PASS"));else{n++;let S=b.stderr?.trim()?` (${b.stderr.trim().slice(0,200)})`:"";O.error(k.default.red("Server test: FAIL")+` \u2014 exit ${b.exitCode}${S}`)}}catch(y){let _=y instanceof Error?y.message:String(y);_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?O.warn(k.default.yellow("Server test: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(n++,O.error(k.default.red("Server test: FAIL")+` \u2014 ${_}`))}O.step(`Checking ${e.name} hooks configuration...`);let c=bi(),u=e.validateHooks(c);for(let y of u)y.status==="pass"?O.success(k.default.green(`${y.check}: PASS`)+` \u2014 ${y.message}`):y.status==="warn"?O.warn(k.default.yellow(`${y.check}: WARN`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
1201
- Run: ${y.fix}`):"")):O.error(k.default.red(`${y.check}: FAIL`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
1202
- Run: ${y.fix}`):""));O.step("Checking hook scripts...");let l=e.getHealthChecks?.(c)??[];if(l.length>0)for(let y of l){let _=y.check();_.status==="OK"?O.success(k.default.green(`${y.name}: PASS`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):"")):O.error(k.default.red(`${y.name}: FAIL`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):""))}else{let y=kc(e,c);if(y.length===0)O.success(k.default.green("Hook scripts: PASS")+k.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let _ of y){let b=Q(c,_);try{NC(b,MC.R_OK),O.success(k.default.green("Hook script exists: PASS")+k.default.dim(` \u2014 ${b}`))}catch{O.error(k.default.red("Hook script exists: FAIL")+k.default.dim(` \u2014 not found at ${b}`))}}}O.step(`Checking ${e.name} plugin registration...`);let d=e.checkPluginRegistration();d.status==="pass"?O.success(k.default.green("Plugin enabled: PASS")+k.default.dim(` \u2014 ${d.message}`)):O.warn(k.default.yellow("Plugin enabled: WARN")+` \u2014 ${d.message}`),O.step("Checking team-shared hook configs in your workspace...");{let E=function(x){return!!(x.startsWith("/")||/^[A-Za-z]:[/\\]/.test(x)||x.includes("\\\\")||x.includes("fnm_multishells")||x.includes("process.execPath"))},A=function(x,T){if(typeof x=="string")T(x);else if(Array.isArray(x))for(let P of x)A(P,T);else if(x&&typeof x=="object")for(let P of Object.values(x))A(P,T)};var f=E,g=A;let y=process.cwd(),_=[".github/hooks/context-mode.json",".cursor/hooks.json",".jetbrains/copilot/hooks.json"],b=0,S=0;for(let x of _){let T=Q(y,x);if(Ze(T)){S++;try{let P=JSON.parse(qn(T,"utf-8")),N=[];if(A(P,R=>{E(R)&&N.push(R)}),N.length>0){n++,b++;let R=N[0].length>100?N[0].slice(0,97)+"...":N[0];O.error(k.default.red("Hook config: FAIL")+` \u2014 ${x} has your machine's local paths baked in`+k.default.dim(`
1203
- This file is committed to git, so teammates and CI will get your path and the hooks will break for them.
1204
- Found ${N.length} hard-coded path(s), e.g.: ${R}
1205
- Fix: run /context-mode:ctx-upgrade \u2014 it rewrites the file to a portable form that works on every machine.
1206
- Details: https://github.com/mksglu/context-mode/issues/613`))}else O.success(k.default.green("Hook config: PASS")+k.default.dim(` \u2014 ${x} is portable (no hard-coded paths)`))}catch(P){let N=P instanceof Error?P.message:String(P);O.warn(k.default.yellow("Hook config: WARN")+` \u2014 ${x} is not valid JSON`+k.default.dim(`
1207
- Doctor cannot scan it for portability issues until the file parses.
1208
- Fix: open the file and check it in a JSON validator, or delete it and run /context-mode:ctx-upgrade to regenerate.
1209
- Parser said: ${N.slice(0,160)}`))}}}S===0&&O.info(k.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}O.step("Checking for leftover .mcp.json files from older versions...");{let y=dc(Id(),".claude","plugins","cache","context-mode","context-mode");if(!Ze(y))O.info(k.default.dim("Leftover .mcp.json check: SKIP \u2014 no plugin cache exists yet (Claude Code has not installed context-mode here)"));else{let _=0,b=[];try{let S=w4(y);for(let E of S){let A=dc(y,E,".mcp.json");Ze(A)&&(_++,b.length<5&&b.push(E))}}catch(S){let E=S instanceof Error?S.message:String(S);O.warn(k.default.yellow("Leftover .mcp.json check: WARN")+" \u2014 could not read the plugin cache directory"+k.default.dim(`
1210
- Path: ${y}
1211
- Reason: ${E.slice(0,160)}
1212
- Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),_=0}_===0?O.success(k.default.green("Leftover .mcp.json check: PASS")+k.default.dim(" \u2014 no old .mcp.json files in the plugin cache")):O.warn(k.default.yellow("Leftover .mcp.json check: WARN")+` \u2014 found ${_} old .mcp.json file(s) left over from previous context-mode versions`+k.default.dim(`
1213
- These are harmless but should be cleaned up so they cannot confuse Claude Code after an auto-update.
1214
- Versions affected: ${b.join(", ")}${_>b.length?", ...":""}
1215
- Fix: run /context-mode:ctx-upgrade \u2014 it sweeps these files automatically on the next run.
1216
- Details: https://github.com/mksglu/context-mode/issues/609`))}}O.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(yr(),ap))).loadDatabase(),_=new y(":memory:");_.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),_.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let b=_.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();_.close(),b&&b.content==="hello world"?O.success(k.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(n++,O.error(k.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(y){let _=y instanceof Error?y.message:String(y),b=bi(),S=Q(b,"node_modules","better-sqlite3");!Ze(S)?(n++,O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+k.default.dim(" \u2014 package-missing")+k.default.dim(`
1217
- Path: ${S}
1218
- Root cause: npm silently skipped better-sqlite3 because the package's \`engines\` field excluded the running Node (issue #514, e.g. Node 26 vs better-sqlite3@12.x).
1219
- Try (primary): cd "${b}" && npm install better-sqlite3 --no-optional
1220
- Try (fallback): /context-mode:ctx-upgrade`))):_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?O.warn(k.default.yellow("FTS5 / better-sqlite3: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(n++,(/Could not locate the bindings file/i.test(_)||/bindings\.node/i.test(_)||/\bbindings\b/i.test(_))&&process.platform==="win32"?O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+k.default.dim(`
1221
- Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
1222
- Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
1223
- Try (fallback): npm rebuild better-sqlite3`)):O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+k.default.dim(`
1224
- Try: npm rebuild better-sqlite3`)))}O.step("Checking versions...");let p=LC(),h=await U4(),m=e.getInstalledVersion();return h==="unknown"?O.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, could not reach npm registry`):p===h?O.success(k.default.green("npm (MCP): PASS")+` \u2014 v${p}`):O.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, latest v${h}`+k.default.dim(`
1225
- Run: /context-mode:ctx-upgrade`)),m==="standalone"?O.info(k.default.dim(`${e.name}: standalone MCP mode`)+" \u2014 no platform plugin version to compare"):m==="not installed"?O.info(k.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):h!=="unknown"&&m===h?O.success(k.default.green(`${e.name}: PASS`)+` \u2014 v${m}`):h!=="unknown"?O.warn(k.default.yellow(`${e.name}: WARN`)+` \u2014 v${m}, latest v${h}`+k.default.dim(`
1226
- Run: /context-mode:ctx-upgrade`)):O.info(`${e.name}: v${m}`+k.default.dim(" \u2014 could not verify against npm registry")),n>0?(_c(k.default.red(`Diagnostics failed \u2014 ${n} critical issue(s) found`)),1):(_c(s.length>=4?k.default.green("Diagnostics complete!"):k.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function G4(){let t="https://context-mode.com/insight";console.log(`
1227
- context-mode Insight
1228
- ${t}
1229
- `),z4(t)}async function J4(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:Qe(),n=await Hi(e.platform);Kd(k.default.bgCyan(k.default.black(" context-mode upgrade "))),O.info(`Platform: ${k.default.cyan(n.name)}`+k.default.dim(` (${e.confidence} confidence)`));let r=bi(),o=[],s=Gd(),i=Q(Be(),"plugins","marketplaces","context-mode");if(Ze(dc(i,".git"))){s.start("Syncing marketplace clone");try{_i("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(k.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),O.info(k.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):(_i("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),_i("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(k.default.green("Marketplace clone synced")),o.push("Marketplace clone updated to upstream"))}catch(p){let h=p instanceof Error?p.message:String(p);s.stop(k.default.yellow("Marketplace sync skipped")),O.warn(k.default.yellow("git refresh on marketplace failed")+` \u2014 ${h}`),O.info(k.default.dim(" Continuing \u2014 cache dir update will still happen."))}}O.step("Pulling latest from GitHub...");let a=LC(),c=dc(I4(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{_i("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let p=c,m=JSON.parse(qn(Q(p,"package.json"),"utf-8")).version??"unknown";if(m===a)O.success(k.default.green("Already on latest")+` \u2014 v${a}`),Pd(c,{recursive:!0,force:!0});else{O.info(`Update available: ${k.default.yellow("v"+a)} \u2192 ${k.default.green("v"+m)}`);try{let x=Vv({ownPid:process.pid,ownPpid:process.ppid});if(x.length>0){let T=await Wv({pids:x});if(T.totalKilled>0){let P=T.totalKilled===1?"sibling MCP server":"sibling MCP servers";O.info(k.default.dim(`Stopped ${T.totalKilled} ${P} (SIGTERM: ${T.terminatedBySigterm}, SIGKILL: ${T.terminatedBySigkill})`))}}}catch{}s.start("Installing dependencies & building");let f=Gv();Rd(["install","--no-audit","--no-fund"],{cwd:p,stdio:"pipe",timeout:12e4,...f?{env:{...process.env,npm_config_msvs_version:f}}:{}}),Rd(["run","build"],{cwd:p,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let y=[...JSON.parse(qn(Q(p,"package.json"),"utf-8")).files||[],"src","package.json"],_=Q(r)+Vn,b=Q(p)+Vn,S=x=>{try{return!P4(x).isSymbolicLink()}catch{return!1}};for(let x of y){let T=Q(p,x),P=Q(r,x);if((P+Vn).startsWith(_)&&(T+Vn).startsWith(b)&&S(T)&&Ze(T))try{Pd(P,{recursive:!0,force:!0}),OC(T,P,{recursive:!0,filter:S})}catch{}}try{let x;try{let{resolveHookRuntime:P}=await Promise.resolve().then(()=>(Qo(),ix)),N=P();N.isBun&&(x=N.path)}catch{}(await Promise.resolve().then(()=>(SC(),xC))).normalizeHooksJsonOnly({pluginRoot:r,nodePath:process.execPath,jsRuntimePath:x,platform:process.platform})}catch{}try{if(e.platform==="claude-code"){let{rewriteShellSnapshots:x}=await Promise.resolve().then(()=>(CC(),RC)),T=Q(Be(),"shell-snapshots"),P=x({snapshotsDir:T,currentVersion:m});P.rewritten.length>0&&O.info(k.default.dim(` Healed ${P.rewritten.length} stale shell snapshot(s) \u2014 Bash tool calls in the active session will pick up v${m} immediately`))}}catch{}s.stop(k.default.green(`Updated in-place to v${m}`));let E=Q(r,".claude-plugin","plugin.json"),A=null;try{let x=JSON.parse(qn(E,"utf-8"));x&&typeof x.version=="string"&&(A=x.version)}catch{}if(A!==m)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${A??"<missing>"}" but newVersion is "${m}". Refusing to bump registry.`);n.updatePluginRegistry(r,m),O.info(k.default.dim(" Registry synced to "+r));try{let x=Q(Be(),"plugins","installed_plugins.json");if(Ze(x)){let P=JSON.parse(qn(x,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let N of P){let R=N?.installPath;if(typeof R!="string"||!R)continue;if(!Ze(R))throw new Error(`installPath does not exist on disk: ${R}`);let C=Q(R,".claude-plugin","plugin.json");if(!Ze(C))throw new Error(`missing plugin.json manifest at ${C}`);let F=JSON.parse(qn(C,"utf-8"));if(F?.version!==N.version)throw new Error(`version mismatch \u2014 registry says "${N.version}" but ${C} says "${F?.version}"`)}}}catch(x){let T=x instanceof Error?x.message:String(x);throw new Error(`Registry consistency check failed: ${T}`)}try{let x=Q(Be(),"plugins","cache"),T="context-mode@context-mode",P=eu({pluginRoot:r,pluginCacheRoot:x,pluginKey:T});if(P&&P.error)throw new Error(P.error);let N=eu({pluginRoot:r,pluginCacheRoot:x,pluginKey:T});if(N&&Array.isArray(N.healed)&&N.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${N.healed.join(",")})`)}catch(x){let T=x instanceof Error?x.message:String(x);throw new Error(`plugin.json drift check failed: ${T}`)}try{let x=Q(Be(),"plugins","cache"),T="context-mode@context-mode",P=tu({pluginCacheRoot:x,pluginKey:T});P&&P.removed&&P.removed.length>0&&O.info(k.default.dim(` Swept ${P.removed.length} stale .mcp.json file(s) from cache`));let N=tu({pluginCacheRoot:x,pluginKey:T});if(N&&Array.isArray(N.removed)&&N.removed.length>0)throw new Error(`.mcp.json sweep drift: ${N.removed.length} file(s) still present after first pass`)}catch(x){let T=x instanceof Error?x.message:String(x);throw new Error(`.mcp.json sweep check failed: ${T}`)}try{let{healClaudeJsonMcpArgs:x}=await Promise.resolve().then(()=>(Im(),Kv)),T=Q(Id(),".claude.json"),P=Q(Be(),"plugins","cache","context-mode","context-mode"),N=x({dotClaudeJsonPath:T,pluginCacheParent:P,newPluginRoot:r});N.healed&&N.healed.length>0&&O.info(k.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+m))}catch{}try{let x=Q(i,".claude-plugin","plugin.json");if(Ze(x)){let T=JSON.parse(qn(x,"utf-8"));T?.version!==m&&(O.warn(k.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${T?.version}" but expected "${m}"`),O.info(k.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(s.start("Installing production dependencies"),Rd(["install","--production","--no-audit","--no-fund"],{cwd:r,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),!Yr(e.platform)){s.start("Verifying native addon ABI");let x=Q(r,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let P=Q(r,"hooks","ensure-deps.mjs");if(!Ze(P))throw new Error(`missing ${P}`);await import(`${Ad(P).href}?upgrade=${Date.now()}`),Ze(x)?(s.stop(k.default.green("Native addons OK")+k.default.dim(" \u2014 ABI cache present")),o.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(k.default.yellow("Native addon ABI cache missing")),O.warn(k.default.dim(` Try manually: cd "${r}" && npm rebuild better-sqlite3`)))}catch(P){let N=P instanceof Error?P.message:String(P);s.stop(k.default.yellow("Native addon ABI bootstrap unavailable")),O.warn(k.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${N}`+k.default.dim(`
1230
- Try manually: cd "${r}" && npm rebuild better-sqlite3`))}let T=Q(r,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Ze(T))try{let P=Q(r,"scripts","heal-better-sqlite3.mjs");if(Ze(P)){let N=await import(`${Ad(P).href}?upgrade=${Date.now()}`);typeof N.healBetterSqlite3Binding=="function"&&N.healBetterSqlite3Binding(r)}}catch{}Ze(T)||(process.exitCode=1,O.error(k.default.red("better-sqlite3 native binding: MISSING")+k.default.dim(`
1231
- Path: ${T}`)+k.default.dim(`
1232
- Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+k.default.dim(`
1233
- Try (primary): cd "${r}" && npm install better-sqlite3 --no-optional`)+k.default.dim(`
1234
- Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{Rd(["install","-g",r,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(k.default.green("npm global updated")),o.push("Updated npm global package")}catch{s.stop(k.default.yellow("npm global update skipped")),O.info(k.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}Pd(c,{recursive:!0,force:!0});try{let x=Be(),T=Q(x,"plugins","installed_plugins.json");if(Ze(T)){let P=Q(x,"plugins","cache"),N;try{N=Od(P)}catch{N=P}let R=N+Vn,F=JSON.parse(qn(T,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(F))for(let W of F){let ge=W?.installPath;if(typeof ge!="string"||!ge||ge===r)continue;let Le=Q(ge);if(!(Le+Vn).startsWith(R)||!Ze(Le))continue;let st;try{st=Od(Le)}catch{continue}if(!(st+Vn).startsWith(R))continue;let $n=Q(p,"skills");Ze($n)&&(OC($n,Q(st,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}catch{}o.push(`Updated v${a} \u2192 v${m}`),O.success(k.default.green("Plugin reinstalled from GitHub!")+k.default.dim(` \u2014 v${m}`))}}catch(p){let h=p instanceof Error?p.message:String(p);s.stop(k.default.red("Update failed")),O.error(k.default.red("GitHub pull failed")+` \u2014 ${h}`),process.exitCode=1,O.warn(k.default.yellow("In-place files were NOT updated")+k.default.dim(" \u2014 old version is still on disk; hooks/settings will still be refreshed.")),O.info(k.default.dim(" Recovery: re-run /ctx-upgrade once network is stable, or run /context-mode:ctx-doctor for a full health check."));try{Pd(c,{recursive:!0,force:!0})}catch{}}O.step(`Backing up ${n.name} settings...`);let u=n.backupSettings();u?.endsWith(".bak")?(O.success(k.default.green("Backup created")+k.default.dim(" -> "+u)),o.push("Backed up settings")):u?O.success(k.default.green("Backup skipped")+k.default.dim(" \u2014 no changes needed")):O.warn(k.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),O.step(`Configuring ${n.name} hooks...`);try{let p=n.configureAllHooks(r);for(let h of p)O.info(k.default.dim(` ${h}`)),o.push(h);O.success(k.default.green("Hooks configured")+k.default.dim(` \u2014 ${n.name}`))}catch(p){let h=p instanceof Error?p.message:String(p);throw new Error(`Hook configuration failed: ${h}`)}O.step("Setting hook script permissions...");let l=n.setHookPermissions(r);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let h=Q(r,p);try{NC(h,MC.F_OK),$4(h,493),l.push(h)}catch{}}l.length>0?(O.success(k.default.green("Permissions set")+k.default.dim(` \u2014 ${l.length} hook script(s)`)),o.push(`Set ${l.length} hook scripts as executable`)):O.error(k.default.red("No hook scripts found")+k.default.dim(" \u2014 expected in "+Q(r,"hooks"))),o.length>0?bc(o.map(p=>k.default.green(" + ")+p).join(`
1235
- `),"Changes Applied"):O.info(k.default.dim("No changes were needed."));let d=n.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";O.warn(k.default.yellow("Restart for new MCP tools to take effect.")+k.default.dim(` (${d})`)),O.step("Running doctor to verify..."),console.log();try{let p=Q(r,"cli.bundle.mjs"),h=Q(r,"build","cli.js"),m=Ze(p)?p:h;_i("node",[m,"doctor"],{stdio:"inherit",timeout:3e4,cwd:r,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{O.warn(k.default.yellow("Doctor had warnings")+k.default.dim(` \u2014 restart your ${n.name} session to pick up the new version`))}}function X4(){let t=Be(),e=[Q(bi(),"bin","statusline.mjs"),Q(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let r=Q(t,"plugins","installed_plugins.json");if(Ze(r)){let o=Q(t,"plugins","cache"),s;try{s=Od(o)}catch{s=o}let i=s+Vn,c=JSON.parse(qn(r,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(c))for(let u of c){let l=u?.installPath;if(typeof l!="string"||!l)continue;let d=Q(l);if(!(d+Vn).startsWith(i))continue;let p;try{p=Od(d)}catch{continue}(p+Vn).startsWith(i)&&e.push(Q(p,"bin","statusline.mjs"))}}}catch{}let n=e.find(r=>Ze(r));n||process.exit(0),import(Ad(n).href).catch(()=>{process.exit(0)})}export{CQ as npmExec,Rd as npmExecFile,z4 as openInBrowser,RQ as toUnixPath};