@kenkaiiii/gg-engine 0.0.0-stage → 7.0.0

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 (850) hide show
  1. package/LICENSE +661 -0
  2. package/NOTICE +43 -0
  3. package/README.md +53 -2
  4. package/assets/skills/bulletproof/SKILL.md +132 -0
  5. package/assets/skills/bulletproof/references/agent-surface.md +113 -0
  6. package/assets/skills/bulletproof/references/attack-classes.md +226 -0
  7. package/assets/skills/bulletproof/references/audit-protocol.md +232 -0
  8. package/assets/skills/bulletproof/references/platform-playbooks.md +196 -0
  9. package/assets/skills/bulletproof/references/provenance.md +146 -0
  10. package/assets/skills/bulletproof/references/secure-defaults.md +137 -0
  11. package/assets/skills/bulletproof/references/supply-chain.md +84 -0
  12. package/assets/skills/bulletproof/references/threat-landscape.md +66 -0
  13. package/assets/skills/bulletproof/references/verification.md +74 -0
  14. package/assets/skills/compliance-guard/SKILL.md +115 -0
  15. package/assets/skills/compliance-guard/references/artifacts.md +199 -0
  16. package/assets/skills/compliance-guard/references/eu-uk.md +162 -0
  17. package/assets/skills/compliance-guard/references/exposure-triage.md +177 -0
  18. package/assets/skills/compliance-guard/references/full-review.md +155 -0
  19. package/assets/skills/compliance-guard/references/lawsuit-vectors.md +153 -0
  20. package/assets/skills/compliance-guard/references/provenance.md +135 -0
  21. package/assets/skills/compliance-guard/references/sector-gates.md +187 -0
  22. package/assets/skills/compliance-guard/references/security-baseline.md +117 -0
  23. package/assets/skills/compliance-guard/references/trigger-map.md +177 -0
  24. package/assets/skills/compliance-guard/references/us.md +194 -0
  25. package/assets/skills/durable/SKILL.md +114 -0
  26. package/assets/skills/durable/references/agent-db-safety.md +76 -0
  27. package/assets/skills/durable/references/backups-and-runtime.md +93 -0
  28. package/assets/skills/durable/references/migrations-and-schema.md +87 -0
  29. package/assets/skills/gg-guide/SKILL.md +43 -0
  30. package/assets/skills/gg-guide/references/chat-motion-goals.md +217 -0
  31. package/assets/skills/gg-guide/references/checklist-and-safety.md +177 -0
  32. package/assets/skills/gg-guide/references/code-mode.md +269 -0
  33. package/assets/skills/gg-guide/references/getting-started.md +290 -0
  34. package/assets/skills/gg-guide/references/ken-and-autopilot.md +172 -0
  35. package/assets/skills/gg-guide/references/mcp-and-skills.md +204 -0
  36. package/assets/skills/gg-guide/references/models-and-sign-in.md +200 -0
  37. package/assets/skills/gg-guide/references/sessions-and-history.md +213 -0
  38. package/assets/skills/gg-guide/references/settings.md +193 -0
  39. package/assets/skills/gg-guide/references/troubleshooting-and-data.md +186 -0
  40. package/assets/skills/lean/SKILL.md +117 -0
  41. package/assets/skills/lean/references/memory-and-processes.md +99 -0
  42. package/assets/skills/lean/references/playbooks.md +134 -0
  43. package/dist/app-error.d.ts +22 -0
  44. package/dist/app-error.js +41 -0
  45. package/dist/app-error.js.map +1 -0
  46. package/dist/config.d.ts +90 -0
  47. package/dist/config.js +240 -0
  48. package/dist/config.js.map +1 -0
  49. package/dist/core/acceptance-checks.d.ts +48 -0
  50. package/dist/core/acceptance-checks.js +151 -0
  51. package/dist/core/acceptance-checks.js.map +1 -0
  52. package/dist/core/action-threats.d.ts +68 -0
  53. package/dist/core/action-threats.js +894 -0
  54. package/dist/core/action-threats.js.map +1 -0
  55. package/dist/core/agent-notifications.d.ts +79 -0
  56. package/dist/core/agent-notifications.js +125 -0
  57. package/dist/core/agent-notifications.js.map +1 -0
  58. package/dist/core/agent-session/helpers.d.ts +26 -0
  59. package/dist/core/agent-session/helpers.js +47 -0
  60. package/dist/core/agent-session/helpers.js.map +1 -0
  61. package/dist/core/agent-session/mcp-tools.d.ts +87 -0
  62. package/dist/core/agent-session/mcp-tools.js +227 -0
  63. package/dist/core/agent-session/mcp-tools.js.map +1 -0
  64. package/dist/core/agent-session/run-loop-monitor.d.ts +63 -0
  65. package/dist/core/agent-session/run-loop-monitor.js +164 -0
  66. package/dist/core/agent-session/run-loop-monitor.js.map +1 -0
  67. package/dist/core/agent-session/transcript-markers.d.ts +57 -0
  68. package/dist/core/agent-session/transcript-markers.js +166 -0
  69. package/dist/core/agent-session/transcript-markers.js.map +1 -0
  70. package/dist/core/agent-session/verification-tracker.d.ts +71 -0
  71. package/dist/core/agent-session/verification-tracker.js +295 -0
  72. package/dist/core/agent-session/verification-tracker.js.map +1 -0
  73. package/dist/core/agent-session.d.ts +1401 -0
  74. package/dist/core/agent-session.js +5160 -0
  75. package/dist/core/agent-session.js.map +1 -0
  76. package/dist/core/agents.d.ts +63 -0
  77. package/dist/core/agents.js +160 -0
  78. package/dist/core/agents.js.map +1 -0
  79. package/dist/core/ask-user.d.ts +163 -0
  80. package/dist/core/ask-user.js +178 -0
  81. package/dist/core/ask-user.js.map +1 -0
  82. package/dist/core/auto-update.d.ts +32 -0
  83. package/dist/core/auto-update.js +218 -0
  84. package/dist/core/auto-update.js.map +1 -0
  85. package/dist/core/autopilot-cycle.d.ts +127 -0
  86. package/dist/core/autopilot-cycle.js +182 -0
  87. package/dist/core/autopilot-cycle.js.map +1 -0
  88. package/dist/core/autopilot-gate.d.ts +106 -0
  89. package/dist/core/autopilot-gate.js +192 -0
  90. package/dist/core/autopilot-gate.js.map +1 -0
  91. package/dist/core/autopilot-verdict.d.ts +55 -0
  92. package/dist/core/autopilot-verdict.js +226 -0
  93. package/dist/core/autopilot-verdict.js.map +1 -0
  94. package/dist/core/blocked-packages-file.d.ts +33 -0
  95. package/dist/core/blocked-packages-file.js +274 -0
  96. package/dist/core/blocked-packages-file.js.map +1 -0
  97. package/dist/core/bundled-agents.d.ts +2 -0
  98. package/dist/core/bundled-agents.js +253 -0
  99. package/dist/core/bundled-agents.js.map +1 -0
  100. package/dist/core/cache-diagnostics.d.ts +72 -0
  101. package/dist/core/cache-diagnostics.js +200 -0
  102. package/dist/core/cache-diagnostics.js.map +1 -0
  103. package/dist/core/cache-expiry.d.ts +89 -0
  104. package/dist/core/cache-expiry.js +117 -0
  105. package/dist/core/cache-expiry.js.map +1 -0
  106. package/dist/core/checklist-detection.d.ts +8 -0
  107. package/dist/core/checklist-detection.js +238 -0
  108. package/dist/core/checklist-detection.js.map +1 -0
  109. package/dist/core/checklist-git.d.ts +19 -0
  110. package/dist/core/checklist-git.js +54 -0
  111. package/dist/core/checklist-git.js.map +1 -0
  112. package/dist/core/checklist-items.d.ts +182 -0
  113. package/dist/core/checklist-items.js +228 -0
  114. package/dist/core/checklist-items.js.map +1 -0
  115. package/dist/core/checklist-prompt.d.ts +14 -0
  116. package/dist/core/checklist-prompt.js +64 -0
  117. package/dist/core/checklist-prompt.js.map +1 -0
  118. package/dist/core/checklist-snapshot.d.ts +7 -0
  119. package/dist/core/checklist-snapshot.js +46 -0
  120. package/dist/core/checklist-snapshot.js.map +1 -0
  121. package/dist/core/checklist-store.d.ts +45 -0
  122. package/dist/core/checklist-store.js +278 -0
  123. package/dist/core/checklist-store.js.map +1 -0
  124. package/dist/core/checkout-record.d.ts +22 -0
  125. package/dist/core/checkout-record.js +68 -0
  126. package/dist/core/checkout-record.js.map +1 -0
  127. package/dist/core/checkpoint-store.d.ts +109 -0
  128. package/dist/core/checkpoint-store.js +260 -0
  129. package/dist/core/checkpoint-store.js.map +1 -0
  130. package/dist/core/claude-code/complete.d.ts +35 -0
  131. package/dist/core/claude-code/complete.js +125 -0
  132. package/dist/core/claude-code/complete.js.map +1 -0
  133. package/dist/core/claude-code/events.d.ts +67 -0
  134. package/dist/core/claude-code/events.js +460 -0
  135. package/dist/core/claude-code/events.js.map +1 -0
  136. package/dist/core/claude-code/live-session.d.ts +94 -0
  137. package/dist/core/claude-code/live-session.js +525 -0
  138. package/dist/core/claude-code/live-session.js.map +1 -0
  139. package/dist/core/claude-code/loop.d.ts +9 -0
  140. package/dist/core/claude-code/loop.js +15 -0
  141. package/dist/core/claude-code/loop.js.map +1 -0
  142. package/dist/core/claude-code/session-sync.d.ts +28 -0
  143. package/dist/core/claude-code/session-sync.js +53 -0
  144. package/dist/core/claude-code/session-sync.js.map +1 -0
  145. package/dist/core/claude-code/tool-bridge.d.ts +49 -0
  146. package/dist/core/claude-code/tool-bridge.js +352 -0
  147. package/dist/core/claude-code/tool-bridge.js.map +1 -0
  148. package/dist/core/claude-code/transcripts.d.ts +39 -0
  149. package/dist/core/claude-code/transcripts.js +195 -0
  150. package/dist/core/claude-code/transcripts.js.map +1 -0
  151. package/dist/core/code-retrieval-chunkers.d.ts +26 -0
  152. package/dist/core/code-retrieval-chunkers.js +264 -0
  153. package/dist/core/code-retrieval-chunkers.js.map +1 -0
  154. package/dist/core/code-retrieval.d.ts +18 -0
  155. package/dist/core/code-retrieval.js +124 -0
  156. package/dist/core/code-retrieval.js.map +1 -0
  157. package/dist/core/codex-request-shape.d.ts +7 -0
  158. package/dist/core/codex-request-shape.js +19 -0
  159. package/dist/core/codex-request-shape.js.map +1 -0
  160. package/dist/core/compaction/active-context.d.ts +16 -0
  161. package/dist/core/compaction/active-context.js +20 -0
  162. package/dist/core/compaction/active-context.js.map +1 -0
  163. package/dist/core/compaction/compactor.d.ts +281 -0
  164. package/dist/core/compaction/compactor.js +1451 -0
  165. package/dist/core/compaction/compactor.js.map +1 -0
  166. package/dist/core/compaction/plan-step-policy.d.ts +46 -0
  167. package/dist/core/compaction/plan-step-policy.js +57 -0
  168. package/dist/core/compaction/plan-step-policy.js.map +1 -0
  169. package/dist/core/compaction/policy.d.ts +36 -0
  170. package/dist/core/compaction/policy.js +144 -0
  171. package/dist/core/compaction/policy.js.map +1 -0
  172. package/dist/core/compaction/query-aware-selector.d.ts +32 -0
  173. package/dist/core/compaction/query-aware-selector.js +202 -0
  174. package/dist/core/compaction/query-aware-selector.js.map +1 -0
  175. package/dist/core/compaction/token-estimator.d.ts +36 -0
  176. package/dist/core/compaction/token-estimator.js +180 -0
  177. package/dist/core/compaction/token-estimator.js.map +1 -0
  178. package/dist/core/compaction/tool-result-pruner.d.ts +90 -0
  179. package/dist/core/compaction/tool-result-pruner.js +238 -0
  180. package/dist/core/compaction/tool-result-pruner.js.map +1 -0
  181. package/dist/core/completion-review.d.ts +24 -0
  182. package/dist/core/completion-review.js +2 -0
  183. package/dist/core/completion-review.js.map +1 -0
  184. package/dist/core/context-files.d.ts +8 -0
  185. package/dist/core/context-files.js +46 -0
  186. package/dist/core/context-files.js.map +1 -0
  187. package/dist/core/context-limits.d.ts +40 -0
  188. package/dist/core/context-limits.js +43 -0
  189. package/dist/core/context-limits.js.map +1 -0
  190. package/dist/core/custom-commands.d.ts +18 -0
  191. package/dist/core/custom-commands.js +57 -0
  192. package/dist/core/custom-commands.js.map +1 -0
  193. package/dist/core/destructive-git-guard.d.ts +113 -0
  194. package/dist/core/destructive-git-guard.js +874 -0
  195. package/dist/core/destructive-git-guard.js.map +1 -0
  196. package/dist/core/display-items.d.ts +8 -0
  197. package/dist/core/display-items.js +2 -0
  198. package/dist/core/display-items.js.map +1 -0
  199. package/dist/core/encode-cwd.d.ts +41 -0
  200. package/dist/core/encode-cwd.js +53 -0
  201. package/dist/core/encode-cwd.js.map +1 -0
  202. package/dist/core/env-delta.d.ts +34 -0
  203. package/dist/core/env-delta.js +84 -0
  204. package/dist/core/env-delta.js.map +1 -0
  205. package/dist/core/event-bus.d.ts +178 -0
  206. package/dist/core/event-bus.js +171 -0
  207. package/dist/core/event-bus.js.map +1 -0
  208. package/dist/core/extensions/loader.d.ts +7 -0
  209. package/dist/core/extensions/loader.js +68 -0
  210. package/dist/core/extensions/loader.js.map +1 -0
  211. package/dist/core/extensions/plugin-bundles.d.ts +13 -0
  212. package/dist/core/extensions/plugin-bundles.js +45 -0
  213. package/dist/core/extensions/plugin-bundles.js.map +1 -0
  214. package/dist/core/extensions/types.d.ts +18 -0
  215. package/dist/core/extensions/types.js +2 -0
  216. package/dist/core/extensions/types.js.map +1 -0
  217. package/dist/core/foreign-session-import.d.ts +119 -0
  218. package/dist/core/foreign-session-import.js +598 -0
  219. package/dist/core/foreign-session-import.js.map +1 -0
  220. package/dist/core/foreign-transcript-blocks.d.ts +50 -0
  221. package/dist/core/foreign-transcript-blocks.js +151 -0
  222. package/dist/core/foreign-transcript-blocks.js.map +1 -0
  223. package/dist/core/frontmatter.d.ts +22 -0
  224. package/dist/core/frontmatter.js +90 -0
  225. package/dist/core/frontmatter.js.map +1 -0
  226. package/dist/core/goal-run-marker.d.ts +32 -0
  227. package/dist/core/goal-run-marker.js +178 -0
  228. package/dist/core/goal-run-marker.js.map +1 -0
  229. package/dist/core/goal-summary.d.ts +15 -0
  230. package/dist/core/goal-summary.js +110 -0
  231. package/dist/core/goal-summary.js.map +1 -0
  232. package/dist/core/goals-store.d.ts +208 -0
  233. package/dist/core/goals-store.js +577 -0
  234. package/dist/core/goals-store.js.map +1 -0
  235. package/dist/core/hashline.d.ts +51 -0
  236. package/dist/core/hashline.js +76 -0
  237. package/dist/core/hashline.js.map +1 -0
  238. package/dist/core/idle-wake.d.ts +62 -0
  239. package/dist/core/idle-wake.js +103 -0
  240. package/dist/core/idle-wake.js.map +1 -0
  241. package/dist/core/index.d.ts +15 -0
  242. package/dist/core/index.js +15 -0
  243. package/dist/core/index.js.map +1 -0
  244. package/dist/core/injection-detect.d.ts +39 -0
  245. package/dist/core/injection-detect.js +241 -0
  246. package/dist/core/injection-detect.js.map +1 -0
  247. package/dist/core/installed-threats.d.ts +23 -0
  248. package/dist/core/installed-threats.js +71 -0
  249. package/dist/core/installed-threats.js.map +1 -0
  250. package/dist/core/internal-diagnostics.d.ts +159 -0
  251. package/dist/core/internal-diagnostics.js +495 -0
  252. package/dist/core/internal-diagnostics.js.map +1 -0
  253. package/dist/core/keep-awake.d.ts +88 -0
  254. package/dist/core/keep-awake.js +251 -0
  255. package/dist/core/keep-awake.js.map +1 -0
  256. package/dist/core/ken-ask-answer.d.ts +24 -0
  257. package/dist/core/ken-ask-answer.js +96 -0
  258. package/dist/core/ken-ask-answer.js.map +1 -0
  259. package/dist/core/ken-context.d.ts +119 -0
  260. package/dist/core/ken-context.js +447 -0
  261. package/dist/core/ken-context.js.map +1 -0
  262. package/dist/core/ken-model.d.ts +45 -0
  263. package/dist/core/ken-model.js +26 -0
  264. package/dist/core/ken-model.js.map +1 -0
  265. package/dist/core/ken-prompt.d.ts +21 -0
  266. package/dist/core/ken-prompt.js +370 -0
  267. package/dist/core/ken-prompt.js.map +1 -0
  268. package/dist/core/language-detector.d.ts +41 -0
  269. package/dist/core/language-detector.js +293 -0
  270. package/dist/core/language-detector.js.map +1 -0
  271. package/dist/core/live-preview.d.ts +26 -0
  272. package/dist/core/live-preview.js +80 -0
  273. package/dist/core/live-preview.js.map +1 -0
  274. package/dist/core/local-endpoint-store.d.ts +53 -0
  275. package/dist/core/local-endpoint-store.js +221 -0
  276. package/dist/core/local-endpoint-store.js.map +1 -0
  277. package/dist/core/logger.d.ts +21 -0
  278. package/dist/core/logger.js +94 -0
  279. package/dist/core/logger.js.map +1 -0
  280. package/dist/core/loop-breaker.d.ts +89 -0
  281. package/dist/core/loop-breaker.js +204 -0
  282. package/dist/core/loop-breaker.js.map +1 -0
  283. package/dist/core/lsp/client.d.ts +206 -0
  284. package/dist/core/lsp/client.js +685 -0
  285. package/dist/core/lsp/client.js.map +1 -0
  286. package/dist/core/lsp/edit-telemetry.d.ts +26 -0
  287. package/dist/core/lsp/edit-telemetry.js +52 -0
  288. package/dist/core/lsp/edit-telemetry.js.map +1 -0
  289. package/dist/core/lsp/format.d.ts +11 -0
  290. package/dist/core/lsp/format.js +30 -0
  291. package/dist/core/lsp/format.js.map +1 -0
  292. package/dist/core/lsp/jsonrpc.d.ts +68 -0
  293. package/dist/core/lsp/jsonrpc.js +153 -0
  294. package/dist/core/lsp/jsonrpc.js.map +1 -0
  295. package/dist/core/lsp/manager.d.ts +188 -0
  296. package/dist/core/lsp/manager.js +576 -0
  297. package/dist/core/lsp/manager.js.map +1 -0
  298. package/dist/core/lsp/pool.d.ts +114 -0
  299. package/dist/core/lsp/pool.js +259 -0
  300. package/dist/core/lsp/pool.js.map +1 -0
  301. package/dist/core/lsp/project-root.d.ts +9 -0
  302. package/dist/core/lsp/project-root.js +75 -0
  303. package/dist/core/lsp/project-root.js.map +1 -0
  304. package/dist/core/lsp/reference-project.d.ts +6 -0
  305. package/dist/core/lsp/reference-project.js +110 -0
  306. package/dist/core/lsp/reference-project.js.map +1 -0
  307. package/dist/core/lsp/servers.d.ts +44 -0
  308. package/dist/core/lsp/servers.js +289 -0
  309. package/dist/core/lsp/servers.js.map +1 -0
  310. package/dist/core/lsp/test-support.d.ts +17 -0
  311. package/dist/core/lsp/test-support.js +27 -0
  312. package/dist/core/lsp/test-support.js.map +1 -0
  313. package/dist/core/mcp/catalog-cache.d.ts +64 -0
  314. package/dist/core/mcp/catalog-cache.js +166 -0
  315. package/dist/core/mcp/catalog-cache.js.map +1 -0
  316. package/dist/core/mcp/client.d.ts +317 -0
  317. package/dist/core/mcp/client.js +1168 -0
  318. package/dist/core/mcp/client.js.map +1 -0
  319. package/dist/core/mcp/content.d.ts +23 -0
  320. package/dist/core/mcp/content.js +194 -0
  321. package/dist/core/mcp/content.js.map +1 -0
  322. package/dist/core/mcp/defaults.d.ts +26 -0
  323. package/dist/core/mcp/defaults.js +81 -0
  324. package/dist/core/mcp/defaults.js.map +1 -0
  325. package/dist/core/mcp/deferred-catalog.d.ts +53 -0
  326. package/dist/core/mcp/deferred-catalog.js +117 -0
  327. package/dist/core/mcp/deferred-catalog.js.map +1 -0
  328. package/dist/core/mcp/elicitation-bridge.d.ts +40 -0
  329. package/dist/core/mcp/elicitation-bridge.js +36 -0
  330. package/dist/core/mcp/elicitation-bridge.js.map +1 -0
  331. package/dist/core/mcp/index.d.ts +16 -0
  332. package/dist/core/mcp/index.js +10 -0
  333. package/dist/core/mcp/index.js.map +1 -0
  334. package/dist/core/mcp/loopback.d.ts +26 -0
  335. package/dist/core/mcp/loopback.js +66 -0
  336. package/dist/core/mcp/loopback.js.map +1 -0
  337. package/dist/core/mcp/oauth-provider.d.ts +55 -0
  338. package/dist/core/mcp/oauth-provider.js +106 -0
  339. package/dist/core/mcp/oauth-provider.js.map +1 -0
  340. package/dist/core/mcp/oauth-store.d.ts +44 -0
  341. package/dist/core/mcp/oauth-store.js +76 -0
  342. package/dist/core/mcp/oauth-store.js.map +1 -0
  343. package/dist/core/mcp/parse-add-command.d.ts +50 -0
  344. package/dist/core/mcp/parse-add-command.js +391 -0
  345. package/dist/core/mcp/parse-add-command.js.map +1 -0
  346. package/dist/core/mcp/resolve-stdio.d.ts +77 -0
  347. package/dist/core/mcp/resolve-stdio.js +359 -0
  348. package/dist/core/mcp/resolve-stdio.js.map +1 -0
  349. package/dist/core/mcp/shared-pool.d.ts +157 -0
  350. package/dist/core/mcp/shared-pool.js +236 -0
  351. package/dist/core/mcp/shared-pool.js.map +1 -0
  352. package/dist/core/mcp/store.d.ts +100 -0
  353. package/dist/core/mcp/store.js +202 -0
  354. package/dist/core/mcp/store.js.map +1 -0
  355. package/dist/core/mcp/tool-guard.d.ts +58 -0
  356. package/dist/core/mcp/tool-guard.js +215 -0
  357. package/dist/core/mcp/tool-guard.js.map +1 -0
  358. package/dist/core/mcp/types.d.ts +57 -0
  359. package/dist/core/mcp/types.js +2 -0
  360. package/dist/core/mcp/types.js.map +1 -0
  361. package/dist/core/message-images.d.ts +11 -0
  362. package/dist/core/message-images.js +52 -0
  363. package/dist/core/message-images.js.map +1 -0
  364. package/dist/core/model-unavailable.d.ts +14 -0
  365. package/dist/core/model-unavailable.js +23 -0
  366. package/dist/core/model-unavailable.js.map +1 -0
  367. package/dist/core/network-guard.d.ts +28 -0
  368. package/dist/core/network-guard.js +251 -0
  369. package/dist/core/network-guard.js.map +1 -0
  370. package/dist/core/node-debugger.d.ts +148 -0
  371. package/dist/core/node-debugger.js +642 -0
  372. package/dist/core/node-debugger.js.map +1 -0
  373. package/dist/core/opencode-catalog-store.d.ts +20 -0
  374. package/dist/core/opencode-catalog-store.js +82 -0
  375. package/dist/core/opencode-catalog-store.js.map +1 -0
  376. package/dist/core/openrouter-catalog-store.d.ts +24 -0
  377. package/dist/core/openrouter-catalog-store.js +140 -0
  378. package/dist/core/openrouter-catalog-store.js.map +1 -0
  379. package/dist/core/package-cooldown.d.ts +69 -0
  380. package/dist/core/package-cooldown.js +297 -0
  381. package/dist/core/package-cooldown.js.map +1 -0
  382. package/dist/core/package-threats.d.ts +92 -0
  383. package/dist/core/package-threats.js +1339 -0
  384. package/dist/core/package-threats.js.map +1 -0
  385. package/dist/core/parked-requests.d.ts +43 -0
  386. package/dist/core/parked-requests.js +34 -0
  387. package/dist/core/parked-requests.js.map +1 -0
  388. package/dist/core/persistent-shell.d.ts +81 -0
  389. package/dist/core/persistent-shell.js +452 -0
  390. package/dist/core/persistent-shell.js.map +1 -0
  391. package/dist/core/plan-delta.d.ts +23 -0
  392. package/dist/core/plan-delta.js +36 -0
  393. package/dist/core/plan-delta.js.map +1 -0
  394. package/dist/core/plan-handoff.d.ts +38 -0
  395. package/dist/core/plan-handoff.js +21 -0
  396. package/dist/core/plan-handoff.js.map +1 -0
  397. package/dist/core/plan-submission-gate.d.ts +28 -0
  398. package/dist/core/plan-submission-gate.js +27 -0
  399. package/dist/core/plan-submission-gate.js.map +1 -0
  400. package/dist/core/platform-clis.d.ts +15 -0
  401. package/dist/core/platform-clis.js +299 -0
  402. package/dist/core/platform-clis.js.map +1 -0
  403. package/dist/core/process-gate.d.ts +61 -0
  404. package/dist/core/process-gate.js +103 -0
  405. package/dist/core/process-gate.js.map +1 -0
  406. package/dist/core/process-manager.d.ts +242 -0
  407. package/dist/core/process-manager.js +902 -0
  408. package/dist/core/process-manager.js.map +1 -0
  409. package/dist/core/progress/engine.d.ts +22 -0
  410. package/dist/core/progress/engine.js +131 -0
  411. package/dist/core/progress/engine.js.map +1 -0
  412. package/dist/core/progress/git-xp.d.ts +15 -0
  413. package/dist/core/progress/git-xp.js +100 -0
  414. package/dist/core/progress/git-xp.js.map +1 -0
  415. package/dist/core/progress/ranks.d.ts +31 -0
  416. package/dist/core/progress/ranks.js +310 -0
  417. package/dist/core/progress/ranks.js.map +1 -0
  418. package/dist/core/progress/rebuild.d.ts +8 -0
  419. package/dist/core/progress/rebuild.js +125 -0
  420. package/dist/core/progress/rebuild.js.map +1 -0
  421. package/dist/core/progress/store.d.ts +34 -0
  422. package/dist/core/progress/store.js +200 -0
  423. package/dist/core/progress/store.js.map +1 -0
  424. package/dist/core/progress/types.d.ts +56 -0
  425. package/dist/core/progress/types.js +2 -0
  426. package/dist/core/progress/types.js.map +1 -0
  427. package/dist/core/project-discovery.d.ts +64 -0
  428. package/dist/core/project-discovery.js +908 -0
  429. package/dist/core/project-discovery.js.map +1 -0
  430. package/dist/core/project-files.d.ts +15 -0
  431. package/dist/core/project-files.js +37 -0
  432. package/dist/core/project-files.js.map +1 -0
  433. package/dist/core/project-health-scan.d.ts +109 -0
  434. package/dist/core/project-health-scan.js +673 -0
  435. package/dist/core/project-health-scan.js.map +1 -0
  436. package/dist/core/project-health-score.d.ts +41 -0
  437. package/dist/core/project-health-score.js +257 -0
  438. package/dist/core/project-health-score.js.map +1 -0
  439. package/dist/core/prompt-command-expansion.d.ts +13 -0
  440. package/dist/core/prompt-command-expansion.js +48 -0
  441. package/dist/core/prompt-command-expansion.js.map +1 -0
  442. package/dist/core/prompt-commands.d.ts +13 -0
  443. package/dist/core/prompt-commands.js +370 -0
  444. package/dist/core/prompt-commands.js.map +1 -0
  445. package/dist/core/radio-players.d.ts +28 -0
  446. package/dist/core/radio-players.js +132 -0
  447. package/dist/core/radio-players.js.map +1 -0
  448. package/dist/core/radio.d.ts +42 -0
  449. package/dist/core/radio.js +499 -0
  450. package/dist/core/radio.js.map +1 -0
  451. package/dist/core/regrounding.d.ts +37 -0
  452. package/dist/core/regrounding.js +89 -0
  453. package/dist/core/regrounding.js.map +1 -0
  454. package/dist/core/resolve-start.d.ts +28 -0
  455. package/dist/core/resolve-start.js +35 -0
  456. package/dist/core/resolve-start.js.map +1 -0
  457. package/dist/core/run-claim.d.ts +36 -0
  458. package/dist/core/run-claim.js +46 -0
  459. package/dist/core/run-claim.js.map +1 -0
  460. package/dist/core/run-lifecycle.d.ts +58 -0
  461. package/dist/core/run-lifecycle.js +104 -0
  462. package/dist/core/run-lifecycle.js.map +1 -0
  463. package/dist/core/run-status.d.ts +17 -0
  464. package/dist/core/run-status.js +28 -0
  465. package/dist/core/run-status.js.map +1 -0
  466. package/dist/core/runtime-mode.d.ts +21 -0
  467. package/dist/core/runtime-mode.js +43 -0
  468. package/dist/core/runtime-mode.js.map +1 -0
  469. package/dist/core/sandbox-domains.d.ts +13 -0
  470. package/dist/core/sandbox-domains.js +76 -0
  471. package/dist/core/sandbox-domains.js.map +1 -0
  472. package/dist/core/sandbox-feedback.d.ts +21 -0
  473. package/dist/core/sandbox-feedback.js +69 -0
  474. package/dist/core/sandbox-feedback.js.map +1 -0
  475. package/dist/core/sandbox.d.ts +106 -0
  476. package/dist/core/sandbox.js +383 -0
  477. package/dist/core/sandbox.js.map +1 -0
  478. package/dist/core/semantic-loop-check.d.ts +58 -0
  479. package/dist/core/semantic-loop-check.js +103 -0
  480. package/dist/core/semantic-loop-check.js.map +1 -0
  481. package/dist/core/session-compaction.d.ts +23 -0
  482. package/dist/core/session-compaction.js +54 -0
  483. package/dist/core/session-compaction.js.map +1 -0
  484. package/dist/core/session-export.d.ts +97 -0
  485. package/dist/core/session-export.js +368 -0
  486. package/dist/core/session-export.js.map +1 -0
  487. package/dist/core/session-history.d.ts +160 -0
  488. package/dist/core/session-history.js +467 -0
  489. package/dist/core/session-history.js.map +1 -0
  490. package/dist/core/session-manager.d.ts +510 -0
  491. package/dist/core/session-manager.js +1368 -0
  492. package/dist/core/session-manager.js.map +1 -0
  493. package/dist/core/session-preview.d.ts +12 -0
  494. package/dist/core/session-preview.js +58 -0
  495. package/dist/core/session-preview.js.map +1 -0
  496. package/dist/core/session-storage.d.ts +78 -0
  497. package/dist/core/session-storage.js +659 -0
  498. package/dist/core/session-storage.js.map +1 -0
  499. package/dist/core/session-summary-index.d.ts +51 -0
  500. package/dist/core/session-summary-index.js +192 -0
  501. package/dist/core/session-summary-index.js.map +1 -0
  502. package/dist/core/settings-manager.d.ts +113 -0
  503. package/dist/core/settings-manager.js +281 -0
  504. package/dist/core/settings-manager.js.map +1 -0
  505. package/dist/core/shared-checkout-guard.d.ts +78 -0
  506. package/dist/core/shared-checkout-guard.js +219 -0
  507. package/dist/core/shared-checkout-guard.js.map +1 -0
  508. package/dist/core/shell-path.d.ts +13 -0
  509. package/dist/core/shell-path.js +175 -0
  510. package/dist/core/shell-path.js.map +1 -0
  511. package/dist/core/shell-threats-popular-packages.d.ts +11 -0
  512. package/dist/core/shell-threats-popular-packages.js +675 -0
  513. package/dist/core/shell-threats-popular-packages.js.map +1 -0
  514. package/dist/core/shell-threats.d.ts +21 -0
  515. package/dist/core/shell-threats.js +235 -0
  516. package/dist/core/shell-threats.js.map +1 -0
  517. package/dist/core/shell.d.ts +54 -0
  518. package/dist/core/shell.js +99 -0
  519. package/dist/core/shell.js.map +1 -0
  520. package/dist/core/shutdown.d.ts +70 -0
  521. package/dist/core/shutdown.js +144 -0
  522. package/dist/core/shutdown.js.map +1 -0
  523. package/dist/core/skill-scan.d.ts +112 -0
  524. package/dist/core/skill-scan.js +781 -0
  525. package/dist/core/skill-scan.js.map +1 -0
  526. package/dist/core/skills.d.ts +80 -0
  527. package/dist/core/skills.js +270 -0
  528. package/dist/core/skills.js.map +1 -0
  529. package/dist/core/slash-commands.d.ts +58 -0
  530. package/dist/core/slash-commands.js +242 -0
  531. package/dist/core/slash-commands.js.map +1 -0
  532. package/dist/core/steering.d.ts +47 -0
  533. package/dist/core/steering.js +65 -0
  534. package/dist/core/steering.js.map +1 -0
  535. package/dist/core/steroids.d.ts +66 -0
  536. package/dist/core/steroids.js +243 -0
  537. package/dist/core/steroids.js.map +1 -0
  538. package/dist/core/stream-diag-level.d.ts +3 -0
  539. package/dist/core/stream-diag-level.js +24 -0
  540. package/dist/core/stream-diag-level.js.map +1 -0
  541. package/dist/core/stream-rules.d.ts +30 -0
  542. package/dist/core/stream-rules.js +151 -0
  543. package/dist/core/stream-rules.js.map +1 -0
  544. package/dist/core/subagent-manager.d.ts +239 -0
  545. package/dist/core/subagent-manager.js +1059 -0
  546. package/dist/core/subagent-manager.js.map +1 -0
  547. package/dist/core/subagent-policy.d.ts +9 -0
  548. package/dist/core/subagent-policy.js +41 -0
  549. package/dist/core/subagent-policy.js.map +1 -0
  550. package/dist/core/subagent-receipt.d.ts +54 -0
  551. package/dist/core/subagent-receipt.js +274 -0
  552. package/dist/core/subagent-receipt.js.map +1 -0
  553. package/dist/core/subagent-store.d.ts +41 -0
  554. package/dist/core/subagent-store.js +284 -0
  555. package/dist/core/subagent-store.js.map +1 -0
  556. package/dist/core/subagent-turn-record.d.ts +18 -0
  557. package/dist/core/subagent-turn-record.js +82 -0
  558. package/dist/core/subagent-turn-record.js.map +1 -0
  559. package/dist/core/tasks-store.d.ts +31 -0
  560. package/dist/core/tasks-store.js +97 -0
  561. package/dist/core/tasks-store.js.map +1 -0
  562. package/dist/core/telegram-config.d.ts +20 -0
  563. package/dist/core/telegram-config.js +52 -0
  564. package/dist/core/telegram-config.js.map +1 -0
  565. package/dist/core/telegram.d.ts +114 -0
  566. package/dist/core/telegram.js +275 -0
  567. package/dist/core/telegram.js.map +1 -0
  568. package/dist/core/temp-paths.d.ts +5 -0
  569. package/dist/core/temp-paths.js +50 -0
  570. package/dist/core/temp-paths.js.map +1 -0
  571. package/dist/core/test-impact.d.ts +73 -0
  572. package/dist/core/test-impact.js +467 -0
  573. package/dist/core/test-impact.js.map +1 -0
  574. package/dist/core/threat-feed.d.ts +65 -0
  575. package/dist/core/threat-feed.js +334 -0
  576. package/dist/core/threat-feed.js.map +1 -0
  577. package/dist/core/trophies/catalog-more.d.ts +2 -0
  578. package/dist/core/trophies/catalog-more.js +837 -0
  579. package/dist/core/trophies/catalog-more.js.map +1 -0
  580. package/dist/core/trophies/catalog.d.ts +4 -0
  581. package/dist/core/trophies/catalog.js +649 -0
  582. package/dist/core/trophies/catalog.js.map +1 -0
  583. package/dist/core/trophies/engine.d.ts +70 -0
  584. package/dist/core/trophies/engine.js +347 -0
  585. package/dist/core/trophies/engine.js.map +1 -0
  586. package/dist/core/trophies/store.d.ts +17 -0
  587. package/dist/core/trophies/store.js +113 -0
  588. package/dist/core/trophies/store.js.map +1 -0
  589. package/dist/core/trophies/types.d.ts +87 -0
  590. package/dist/core/trophies/types.js +74 -0
  591. package/dist/core/trophies/types.js.map +1 -0
  592. package/dist/core/ui-adoption.d.ts +32 -0
  593. package/dist/core/ui-adoption.js +302 -0
  594. package/dist/core/ui-adoption.js.map +1 -0
  595. package/dist/core/ui-compatibility.d.ts +10 -0
  596. package/dist/core/ui-compatibility.js +51 -0
  597. package/dist/core/ui-compatibility.js.map +1 -0
  598. package/dist/core/ui-registry.d.ts +101 -0
  599. package/dist/core/ui-registry.js +292 -0
  600. package/dist/core/ui-registry.js.map +1 -0
  601. package/dist/core/user-shell-context.d.ts +8 -0
  602. package/dist/core/user-shell-context.js +12 -0
  603. package/dist/core/user-shell-context.js.map +1 -0
  604. package/dist/core/verification-evidence.d.ts +49 -0
  605. package/dist/core/verification-evidence.js +816 -0
  606. package/dist/core/verification-evidence.js.map +1 -0
  607. package/dist/core/verification-gate.d.ts +77 -0
  608. package/dist/core/verification-gate.js +504 -0
  609. package/dist/core/verification-gate.js.map +1 -0
  610. package/dist/core/verification-snapshot.d.ts +7 -0
  611. package/dist/core/verification-snapshot.js +109 -0
  612. package/dist/core/verification-snapshot.js.map +1 -0
  613. package/dist/core/verify-commands.d.ts +34 -0
  614. package/dist/core/verify-commands.js +203 -0
  615. package/dist/core/verify-commands.js.map +1 -0
  616. package/dist/core/voice-transcriber.d.ts +32 -0
  617. package/dist/core/voice-transcriber.js +114 -0
  618. package/dist/core/voice-transcriber.js.map +1 -0
  619. package/dist/core/workspace-guard.d.ts +56 -0
  620. package/dist/core/workspace-guard.js +334 -0
  621. package/dist/core/workspace-guard.js.map +1 -0
  622. package/dist/index.d.ts +15 -0
  623. package/dist/index.js +21 -0
  624. package/dist/index.js.map +1 -0
  625. package/dist/session.d.ts +44 -0
  626. package/dist/session.js +105 -0
  627. package/dist/session.js.map +1 -0
  628. package/dist/system-prompt.d.ts +104 -0
  629. package/dist/system-prompt.js +480 -0
  630. package/dist/system-prompt.js.map +1 -0
  631. package/dist/test-support/fake-home.d.ts +19 -0
  632. package/dist/test-support/fake-home.js +37 -0
  633. package/dist/test-support/fake-home.js.map +1 -0
  634. package/dist/test-support/keep-alive.d.ts +14 -0
  635. package/dist/test-support/keep-alive.js +17 -0
  636. package/dist/test-support/keep-alive.js.map +1 -0
  637. package/dist/test-support/slow-git.d.ts +1 -0
  638. package/dist/test-support/slow-git.js +21 -0
  639. package/dist/test-support/slow-git.js.map +1 -0
  640. package/dist/test-support/system-tools.d.ts +6 -0
  641. package/dist/test-support/system-tools.js +36 -0
  642. package/dist/test-support/system-tools.js.map +1 -0
  643. package/dist/tools/ask-user.d.ts +34 -0
  644. package/dist/tools/ask-user.js +99 -0
  645. package/dist/tools/ask-user.js.map +1 -0
  646. package/dist/tools/background-watch-lint.d.ts +18 -0
  647. package/dist/tools/background-watch-lint.js +102 -0
  648. package/dist/tools/background-watch-lint.js.map +1 -0
  649. package/dist/tools/bash-read-evidence.d.ts +23 -0
  650. package/dist/tools/bash-read-evidence.js +180 -0
  651. package/dist/tools/bash-read-evidence.js.map +1 -0
  652. package/dist/tools/bash.d.ts +64 -0
  653. package/dist/tools/bash.js +552 -0
  654. package/dist/tools/bash.js.map +1 -0
  655. package/dist/tools/browser-api.d.ts +27 -0
  656. package/dist/tools/browser-api.js +449 -0
  657. package/dist/tools/browser-api.js.map +1 -0
  658. package/dist/tools/browser-sandbox.d.ts +16 -0
  659. package/dist/tools/browser-sandbox.js +158 -0
  660. package/dist/tools/browser-sandbox.js.map +1 -0
  661. package/dist/tools/browser-session.d.ts +84 -0
  662. package/dist/tools/browser-session.js +304 -0
  663. package/dist/tools/browser-session.js.map +1 -0
  664. package/dist/tools/browser-snapshot.d.ts +19 -0
  665. package/dist/tools/browser-snapshot.js +109 -0
  666. package/dist/tools/browser-snapshot.js.map +1 -0
  667. package/dist/tools/browser.d.ts +11 -0
  668. package/dist/tools/browser.js +106 -0
  669. package/dist/tools/browser.js.map +1 -0
  670. package/dist/tools/checklist.d.ts +49 -0
  671. package/dist/tools/checklist.js +154 -0
  672. package/dist/tools/checklist.js.map +1 -0
  673. package/dist/tools/compress.d.ts +56 -0
  674. package/dist/tools/compress.js +226 -0
  675. package/dist/tools/compress.js.map +1 -0
  676. package/dist/tools/debug.d.ts +54 -0
  677. package/dist/tools/debug.js +230 -0
  678. package/dist/tools/debug.js.map +1 -0
  679. package/dist/tools/document-text.d.ts +6 -0
  680. package/dist/tools/document-text.js +154 -0
  681. package/dist/tools/document-text.js.map +1 -0
  682. package/dist/tools/edit-diff.d.ts +123 -0
  683. package/dist/tools/edit-diff.js +476 -0
  684. package/dist/tools/edit-diff.js.map +1 -0
  685. package/dist/tools/edit-targets.d.ts +10 -0
  686. package/dist/tools/edit-targets.js +31 -0
  687. package/dist/tools/edit-targets.js.map +1 -0
  688. package/dist/tools/edit.d.ts +38 -0
  689. package/dist/tools/edit.js +695 -0
  690. package/dist/tools/edit.js.map +1 -0
  691. package/dist/tools/enter-plan.d.ts +7 -0
  692. package/dist/tools/enter-plan.js +20 -0
  693. package/dist/tools/enter-plan.js.map +1 -0
  694. package/dist/tools/exit-plan.d.ts +7 -0
  695. package/dist/tools/exit-plan.js +51 -0
  696. package/dist/tools/exit-plan.js.map +1 -0
  697. package/dist/tools/find.d.ts +17 -0
  698. package/dist/tools/find.js +100 -0
  699. package/dist/tools/find.js.map +1 -0
  700. package/dist/tools/generate-image.d.ts +83 -0
  701. package/dist/tools/generate-image.js +625 -0
  702. package/dist/tools/generate-image.js.map +1 -0
  703. package/dist/tools/grep-scan.d.ts +96 -0
  704. package/dist/tools/grep-scan.js +283 -0
  705. package/dist/tools/grep-scan.js.map +1 -0
  706. package/dist/tools/grep.d.ts +48 -0
  707. package/dist/tools/grep.js +1013 -0
  708. package/dist/tools/grep.js.map +1 -0
  709. package/dist/tools/html-extract.d.ts +57 -0
  710. package/dist/tools/html-extract.js +130 -0
  711. package/dist/tools/html-extract.js.map +1 -0
  712. package/dist/tools/index.d.ts +198 -0
  713. package/dist/tools/index.js +216 -0
  714. package/dist/tools/index.js.map +1 -0
  715. package/dist/tools/live-preview.d.ts +23 -0
  716. package/dist/tools/live-preview.js +41 -0
  717. package/dist/tools/live-preview.js.map +1 -0
  718. package/dist/tools/ls.d.ts +9 -0
  719. package/dist/tools/ls.js +59 -0
  720. package/dist/tools/ls.js.map +1 -0
  721. package/dist/tools/operations.d.ts +86 -0
  722. package/dist/tools/operations.js +117 -0
  723. package/dist/tools/operations.js.map +1 -0
  724. package/dist/tools/overflow.d.ts +17 -0
  725. package/dist/tools/overflow.js +68 -0
  726. package/dist/tools/overflow.js.map +1 -0
  727. package/dist/tools/path-utils.d.ts +30 -0
  728. package/dist/tools/path-utils.js +74 -0
  729. package/dist/tools/path-utils.js.map +1 -0
  730. package/dist/tools/pdf-extract.d.ts +17 -0
  731. package/dist/tools/pdf-extract.js +43 -0
  732. package/dist/tools/pdf-extract.js.map +1 -0
  733. package/dist/tools/prompt-hints.d.ts +46 -0
  734. package/dist/tools/prompt-hints.js +171 -0
  735. package/dist/tools/prompt-hints.js.map +1 -0
  736. package/dist/tools/read-only-bash.d.ts +31 -0
  737. package/dist/tools/read-only-bash.js +338 -0
  738. package/dist/tools/read-only-bash.js.map +1 -0
  739. package/dist/tools/read-tracker.d.ts +43 -0
  740. package/dist/tools/read-tracker.js +120 -0
  741. package/dist/tools/read-tracker.js.map +1 -0
  742. package/dist/tools/read.d.ts +18 -0
  743. package/dist/tools/read.js +316 -0
  744. package/dist/tools/read.js.map +1 -0
  745. package/dist/tools/redaction-guard.d.ts +10 -0
  746. package/dist/tools/redaction-guard.js +55 -0
  747. package/dist/tools/redaction-guard.js.map +1 -0
  748. package/dist/tools/routine-output.d.ts +39 -0
  749. package/dist/tools/routine-output.js +281 -0
  750. package/dist/tools/routine-output.js.map +1 -0
  751. package/dist/tools/safe-env.d.ts +1 -0
  752. package/dist/tools/safe-env.js +79 -0
  753. package/dist/tools/safe-env.js.map +1 -0
  754. package/dist/tools/session-stats.d.ts +26 -0
  755. package/dist/tools/session-stats.js +51 -0
  756. package/dist/tools/session-stats.js.map +1 -0
  757. package/dist/tools/side-web-search.d.ts +34 -0
  758. package/dist/tools/side-web-search.js +146 -0
  759. package/dist/tools/side-web-search.js.map +1 -0
  760. package/dist/tools/skill.d.ts +12 -0
  761. package/dist/tools/skill.js +94 -0
  762. package/dist/tools/skill.js.map +1 -0
  763. package/dist/tools/source-path.d.ts +8 -0
  764. package/dist/tools/source-path.js +135 -0
  765. package/dist/tools/source-path.js.map +1 -0
  766. package/dist/tools/steroids.d.ts +44 -0
  767. package/dist/tools/steroids.js +356 -0
  768. package/dist/tools/steroids.js.map +1 -0
  769. package/dist/tools/subagent-control.d.ts +5 -0
  770. package/dist/tools/subagent-control.js +211 -0
  771. package/dist/tools/subagent-control.js.map +1 -0
  772. package/dist/tools/subagent-shared.d.ts +115 -0
  773. package/dist/tools/subagent-shared.js +182 -0
  774. package/dist/tools/subagent-shared.js.map +1 -0
  775. package/dist/tools/subagent.d.ts +37 -0
  776. package/dist/tools/subagent.js +406 -0
  777. package/dist/tools/subagent.js.map +1 -0
  778. package/dist/tools/task-output.d.ts +10 -0
  779. package/dist/tools/task-output.js +74 -0
  780. package/dist/tools/task-output.js.map +1 -0
  781. package/dist/tools/task-send.d.ts +11 -0
  782. package/dist/tools/task-send.js +36 -0
  783. package/dist/tools/task-send.js.map +1 -0
  784. package/dist/tools/task-stop.d.ts +8 -0
  785. package/dist/tools/task-stop.js +15 -0
  786. package/dist/tools/task-stop.js.map +1 -0
  787. package/dist/tools/tasks.d.ts +15 -0
  788. package/dist/tools/tasks.js +94 -0
  789. package/dist/tools/tasks.js.map +1 -0
  790. package/dist/tools/tool-search.d.ts +26 -0
  791. package/dist/tools/tool-search.js +81 -0
  792. package/dist/tools/tool-search.js.map +1 -0
  793. package/dist/tools/tool-tiers.d.ts +65 -0
  794. package/dist/tools/tool-tiers.js +121 -0
  795. package/dist/tools/tool-tiers.js.map +1 -0
  796. package/dist/tools/truncate.d.ts +39 -0
  797. package/dist/tools/truncate.js +242 -0
  798. package/dist/tools/truncate.js.map +1 -0
  799. package/dist/tools/ui-adopt.d.ts +16 -0
  800. package/dist/tools/ui-adopt.js +66 -0
  801. package/dist/tools/ui-adopt.js.map +1 -0
  802. package/dist/tools/ui-registry.d.ts +15 -0
  803. package/dist/tools/ui-registry.js +39 -0
  804. package/dist/tools/ui-registry.js.map +1 -0
  805. package/dist/tools/verification-review.d.ts +2 -0
  806. package/dist/tools/verification-review.js +41 -0
  807. package/dist/tools/verification-review.js.map +1 -0
  808. package/dist/tools/web-fetch.d.ts +52 -0
  809. package/dist/tools/web-fetch.js +986 -0
  810. package/dist/tools/web-fetch.js.map +1 -0
  811. package/dist/tools/web-search.d.ts +35 -0
  812. package/dist/tools/web-search.js +926 -0
  813. package/dist/tools/web-search.js.map +1 -0
  814. package/dist/tools/write.d.ts +16 -0
  815. package/dist/tools/write.js +196 -0
  816. package/dist/tools/write.js.map +1 -0
  817. package/dist/types.d.ts +44 -0
  818. package/dist/types.js +2 -0
  819. package/dist/types.js.map +1 -0
  820. package/dist/utils/commit-message.d.ts +25 -0
  821. package/dist/utils/commit-message.js +72 -0
  822. package/dist/utils/commit-message.js.map +1 -0
  823. package/dist/utils/git.d.ts +102 -0
  824. package/dist/utils/git.js +325 -0
  825. package/dist/utils/git.js.map +1 -0
  826. package/dist/utils/github-ci.d.ts +9 -0
  827. package/dist/utils/github-ci.js +138 -0
  828. package/dist/utils/github-ci.js.map +1 -0
  829. package/dist/utils/github.d.ts +19 -0
  830. package/dist/utils/github.js +67 -0
  831. package/dist/utils/github.js.map +1 -0
  832. package/dist/utils/image.d.ts +166 -0
  833. package/dist/utils/image.js +673 -0
  834. package/dist/utils/image.js.map +1 -0
  835. package/dist/utils/open-browser.d.ts +13 -0
  836. package/dist/utils/open-browser.js +31 -0
  837. package/dist/utils/open-browser.js.map +1 -0
  838. package/dist/utils/plan-steps.d.ts +90 -0
  839. package/dist/utils/plan-steps.js +209 -0
  840. package/dist/utils/plan-steps.js.map +1 -0
  841. package/dist/utils/process.d.ts +48 -0
  842. package/dist/utils/process.js +175 -0
  843. package/dist/utils/process.js.map +1 -0
  844. package/dist/utils/prompt-enhancer.d.ts +34 -0
  845. package/dist/utils/prompt-enhancer.js +178 -0
  846. package/dist/utils/prompt-enhancer.js.map +1 -0
  847. package/dist/utils/text.d.ts +61 -0
  848. package/dist/utils/text.js +68 -0
  849. package/dist/utils/text.js.map +1 -0
  850. package/package.json +87 -3
@@ -0,0 +1,1168 @@
1
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
2
+ import { Client, OAuthError, OAuthErrorCode, ProtocolError, SdkError, SdkErrorCode, SdkHttpError, StreamableHTTPClientTransport, SSEClientTransport, UnauthorizedError, } from "@modelcontextprotocol/client";
3
+ import { z } from "zod";
4
+ import http from "node:http";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { log } from "@kenkaiiii/gg-core";
8
+ import { McpOAuthProvider, MCP_OAUTH_CALLBACK_PORT, MCP_OAUTH_CALLBACK_PATH, } from "./oauth-provider.js";
9
+ import { McpOAuthStore } from "./oauth-store.js";
10
+ import { isLocalhost, alternateLoopback, isNetworkError } from "./loopback.js";
11
+ import { toToolResult } from "./content.js";
12
+ import { resolveStdioCommand } from "./resolve-stdio.js";
13
+ import { checkMcpLaunch } from "../package-threats.js";
14
+ import { launchCooldownEnv } from "../package-cooldown.js";
15
+ import { McpCatalogCache } from "./catalog-cache.js";
16
+ import { McpToolGuard } from "./tool-guard.js";
17
+ import { isShareableServer, sharedMcpPool, } from "./shared-pool.js";
18
+ /**
19
+ * How long a stdio server may sit with no call in flight before its process is
20
+ * stopped. It is respawned transparently on the next call.
21
+ *
22
+ * 15 min, deliberately longer than pi-mcp-adapter's 10 min default: one pooled
23
+ * child here serves every window in the daemon, so a premature stop is paid as
24
+ * a cold start (`npx`/node boot + handshake, often seconds) by whichever chat
25
+ * calls next. 15 min still covers the read/think/edit pauses inside one task
26
+ * while reclaiming servers a session touched once and moved on from.
27
+ */
28
+ export const MCP_DEFAULT_IDLE_TIMEOUT_MS = 15 * 60_000;
29
+ /**
30
+ * Default per-call window without a response or progress notification. Equal
31
+ * to the SDK's own `DEFAULT_REQUEST_TIMEOUT_MSEC`; `config.timeout` overrides.
32
+ */
33
+ export const MCP_DEFAULT_CALL_TIMEOUT_MS = 60_000;
34
+ /**
35
+ * Default hard cap on one tool call, however much progress it reports — so a
36
+ * server stuck in a progress loop cannot hold a turn forever. Generous because
37
+ * the tools that report progress are the long ones (builds, crawls, renders);
38
+ * `config.maxTotalTimeout` overrides.
39
+ */
40
+ export const MCP_DEFAULT_MAX_TOTAL_TIMEOUT_MS = 30 * 60_000;
41
+ /**
42
+ * A failed MCP tool call. Thrown (not returned as text) so the agent loop
43
+ * records the result as an error: the app shows it as failed and receipts,
44
+ * the loop breaker and verification all see a failure, not a success whose
45
+ * text happens to say "error". The message is what the model reads.
46
+ */
47
+ export class McpToolError extends Error {
48
+ name = "McpToolError";
49
+ }
50
+ /** Text parts of a tool result, joined, for an error message. */
51
+ function resultText(result) {
52
+ if (typeof result === "string")
53
+ return result;
54
+ if (typeof result.content === "string")
55
+ return result.content;
56
+ return result.content
57
+ .map((part) => (part.type === "text" ? part.text : ""))
58
+ .filter(Boolean)
59
+ .join("\n");
60
+ }
61
+ export class MCPClientManager {
62
+ servers = [];
63
+ /**
64
+ * Per-server connection settlement, so a caller holding a cached-only tool
65
+ * can wait for the live client instead of failing or hanging forever.
66
+ */
67
+ connections = new Map();
68
+ /**
69
+ * In-flight session rebuilds, keyed by server name. N tool calls to the same
70
+ * server all 404 at once when its session expires; without coalescing each
71
+ * would spawn its own reconnect and they would race to replace each other in
72
+ * `this.servers`. Sharing one promise means exactly one reconnect per outage.
73
+ */
74
+ reconnecting = new Map();
75
+ /**
76
+ * Claims on process-wide shared connections, keyed by server name. Held so
77
+ * `dispose` can hand them back: the pooled child only exits once the LAST
78
+ * manager holding it releases, so leaking a claim here would pin the process
79
+ * for the daemon's lifetime — the exact bug sharing is meant to fix.
80
+ */
81
+ sharedHandles = new Map();
82
+ catalogCache;
83
+ /** Scans + pins each server's tool descriptions before exposure (gg-safe S2). */
84
+ toolGuard;
85
+ /** Tools hidden by the guard on the latest connect, per server. */
86
+ hiddenTools = new Map();
87
+ /**
88
+ * Opt into the 2026-07-28 revision. Off by default: `mode: "auto"` probes with
89
+ * `server/discover` before falling back to `initialize`, and a legacy stdio
90
+ * server that ignores pre-`initialize` requests pays the full probe timeout.
91
+ */
92
+ modernProtocol;
93
+ /**
94
+ * Host callback for server-initiated `elicitation/create`. Absent means we
95
+ * declare no elicitation capability at all — which is protocol-legal and is
96
+ * how the CLI runs, since it has nowhere to render the form.
97
+ */
98
+ onElicit;
99
+ /**
100
+ * Pool backing `shared: true` servers. Defaults to the daemon-wide singleton;
101
+ * injectable so tests can exercise sharing without touching global state.
102
+ */
103
+ pool;
104
+ /**
105
+ * Fired when a connected server's transport closes on its own — a crashed or
106
+ * exited child, not our own `dispose`. The pool uses it to drop a dead
107
+ * connection so the next session rebuilds instead of inheriting a corpse.
108
+ */
109
+ onServerClosed;
110
+ /** Set while `dispose` runs, so our own teardown is not reported as a death. */
111
+ disposing = false;
112
+ /** Idle period before a stdio server is stopped; 0 disables idle shutdown. */
113
+ idleTimeoutMs;
114
+ /** Idle bookkeeping per server name, for servers eligible for idle shutdown. */
115
+ idle = new Map();
116
+ /**
117
+ * Clients we closed ON PURPOSE for idleness. Their `onclose` must not be
118
+ * reported as a death — that would make the pool evict a connection whose
119
+ * tools are still published and which will respawn on the next call.
120
+ */
121
+ idleStopped = new WeakSet();
122
+ /** Servers the user removed mid-session: their already-published tools refuse calls. */
123
+ removed = new Set();
124
+ constructor(opts = {}) {
125
+ this.catalogCache = opts.catalogCache ?? new McpCatalogCache();
126
+ // Pins sit beside the catalog cache, so a test that isolates the cache
127
+ // isolates the pins too (and the real ~/.gg is never touched).
128
+ this.toolGuard =
129
+ opts.toolGuard ??
130
+ new McpToolGuard(path.join(path.dirname(this.catalogCache.path), "mcp-tool-pins.json"));
131
+ this.modernProtocol = opts.modernProtocol ?? false;
132
+ this.onElicit = opts.onElicit;
133
+ this.pool = opts.sharedPool ?? sharedMcpPool;
134
+ this.onServerClosed = opts.onServerClosed;
135
+ this.idleTimeoutMs = opts.idleTimeoutMs ?? MCP_DEFAULT_IDLE_TIMEOUT_MS;
136
+ }
137
+ /**
138
+ * Does this server get stopped when idle?
139
+ *
140
+ * Only stdio servers: idle shutdown exists to reclaim a child PROCESS, and an
141
+ * HTTP server has none on our side. Closing one would save nothing locally
142
+ * while throwing away its `Mcp-Session-Id` (server-side state) and forcing a
143
+ * fresh handshake — possibly an OAuth refresh — on the next call.
144
+ * `keepAlive: true` opts a stdio server out for state held in its process.
145
+ */
146
+ idleEligible(config) {
147
+ return this.idleTimeoutMs > 0 && Boolean(config.command) && config.keepAlive !== true;
148
+ }
149
+ idleState(name) {
150
+ let state = this.idle.get(name);
151
+ if (!state) {
152
+ state = { inFlight: 0 };
153
+ this.idle.set(name, state);
154
+ }
155
+ return state;
156
+ }
157
+ /** (Re)start the idle countdown for a server, unless a call is in flight. */
158
+ armIdleTimer(config) {
159
+ if (this.disposing || !this.idleEligible(config))
160
+ return;
161
+ const state = this.idleState(config.name);
162
+ if (state.timer)
163
+ clearTimeout(state.timer);
164
+ state.timer = undefined;
165
+ if (state.inFlight > 0)
166
+ return;
167
+ state.timer = setTimeout(() => {
168
+ state.timer = undefined;
169
+ void this.stopIdleServer(config.name);
170
+ }, this.idleTimeoutMs);
171
+ // An idle countdown must never be what keeps the CLI/daemon alive.
172
+ state.timer.unref?.();
173
+ }
174
+ /**
175
+ * Stop an idle server's process, keeping its published tools. The entry is
176
+ * removed from `this.servers` synchronously, so a call landing during the
177
+ * close sees "not running" and respawns rather than using a closing client.
178
+ */
179
+ async stopIdleServer(name) {
180
+ const state = this.idle.get(name);
181
+ if (this.disposing || !state || state.inFlight > 0 || state.restarting)
182
+ return;
183
+ const server = this.servers.find((s) => s.name === name);
184
+ if (!server)
185
+ return;
186
+ this.servers = this.servers.filter((s) => s !== server);
187
+ this.idleStopped.add(server.client);
188
+ log("INFO", "mcp", `Stopping idle MCP server "${name}" (restarts on next call)`);
189
+ try {
190
+ await server.client.close();
191
+ }
192
+ catch {
193
+ // Already gone; nothing to reclaim.
194
+ }
195
+ }
196
+ /**
197
+ * Make sure an idle-stopped server is running again before a call. Concurrent
198
+ * calls share one respawn. The fresh tool list is persisted to the catalog
199
+ * cache by `connectServer` but NOT republished: the model keeps the tools it
200
+ * already has, so a stop/restart cycle never churns the prompt.
201
+ */
202
+ async ensureRunning(config) {
203
+ if (this.servers.some((s) => s.name === config.name))
204
+ return;
205
+ const state = this.idleState(config.name);
206
+ if (!state.restarting) {
207
+ log("INFO", "mcp", `Restarting idle-stopped MCP server "${config.name}"`);
208
+ state.restarting = this.connectServer(config, { restart: true }).then(() => {
209
+ state.restarting = undefined;
210
+ }, (err) => {
211
+ state.restarting = undefined;
212
+ throw err;
213
+ });
214
+ }
215
+ await state.restarting;
216
+ }
217
+ /** Is this server's connection currently live? Diagnostic/test use. */
218
+ isServerRunning(name) {
219
+ return this.servers.some((s) => s.name === name);
220
+ }
221
+ /**
222
+ * Build a `Client` for one server, declaring elicitation support and wiring
223
+ * the handler when the host can actually prompt the user.
224
+ *
225
+ * Form mode only. URL mode would have us open a browser tab in the middle of
226
+ * a tool call with no user gesture behind it — the SDK rejects URL-mode
227
+ * requests for us when the `url` capability is undeclared.
228
+ */
229
+ createClient(serverName, negotiate) {
230
+ const handler = this.onElicit;
231
+ if (!handler)
232
+ return new Client({ name: "ggcoder", version: "1.0.0" }, negotiate);
233
+ const client = new Client({ name: "ggcoder", version: "1.0.0" }, { ...negotiate, capabilities: { elicitation: { form: {} } } });
234
+ client.setRequestHandler("elicitation/create", async (request) => {
235
+ const params = request.params;
236
+ if (params.mode === "url") {
237
+ // Unreachable while `url` stays undeclared, but a server that ignores
238
+ // capabilities must get a clean decline rather than a thrown handler.
239
+ return { action: "decline" };
240
+ }
241
+ return handler({
242
+ server: serverName,
243
+ message: params.message,
244
+ requestedSchema: params.requestedSchema,
245
+ });
246
+ });
247
+ return client;
248
+ }
249
+ /**
250
+ * Version-negotiation options for a real (non-probe) connect. `probe()` is
251
+ * spawn-per-invocation and deliberately never negotiates: a legacy stdio
252
+ * server that ignores the discovery request would stall it for the whole
253
+ * probe timeout, turning "validate this server" into a 30s hang.
254
+ *
255
+ * The probe timeout is transport-aware because the SDK's timeout VERDICT is:
256
+ *
257
+ * - **stdio** — silence on a local pipe means a legacy server, and the SDK
258
+ * falls back to `initialize`. The probe runs on a disposable sibling
259
+ * process, so the fallback is clean. Waiting the full connect timeout to
260
+ * reach a conclusion we can draw in seconds is pure dead time, so cap it
261
+ * short.
262
+ * - **HTTP** — silence means an outage, and the SDK REJECTS the connect
263
+ * rather than falling back. A short timeout would therefore turn a slow
264
+ * cold start into a hard connection failure, so inherit the full connect
265
+ * timeout and let the normal timeout handling deal with a real outage.
266
+ */
267
+ negotiationOptions(transport) {
268
+ if (!this.modernProtocol)
269
+ return {};
270
+ return {
271
+ versionNegotiation: {
272
+ mode: "auto",
273
+ ...(transport === "stdio" ? { probe: { timeoutMs: STDIO_PROBE_TIMEOUT_MS } } : {}),
274
+ },
275
+ };
276
+ }
277
+ /**
278
+ * Claim the pooled connection for a shared server and adopt its tools.
279
+ *
280
+ * Shaped like `connectServer` (resolve tools / throw on failure) so the
281
+ * caller's `allSettled` handling is identical for both kinds. The pool
282
+ * reports failure in-band, so it is rethrown here with the message the pool
283
+ * already formatted.
284
+ */
285
+ async connectShared(config) {
286
+ const handle = await this.pool.acquire(config,
287
+ // The pooled connection is just another manager with sharing switched
288
+ // off, so it takes the normal connect path instead of recursing into the
289
+ // pool. Its elicit handler is the pool's dispatcher, NOT this session's:
290
+ // the connection is shared, so each request has to be routed to whichever
291
+ // session actually provoked it.
292
+ (opts) => {
293
+ const manager = new MCPClientManager({
294
+ catalogCache: opts.catalogCache,
295
+ modernProtocol: opts.modernProtocol,
296
+ onElicit: opts.onElicit,
297
+ sharedPool: this.pool,
298
+ // Let the pool retire this connection if its server exits.
299
+ onServerClosed: opts.onClosed,
300
+ // Idle shutdown lives in the pooled manager: it sees every session's
301
+ // calls, so "no call in flight" means none from ANY window.
302
+ idleTimeoutMs: this.idleTimeoutMs,
303
+ });
304
+ return {
305
+ connect: async (target) => {
306
+ const [result] = await manager.connectAllDetailed([{ ...target, shared: false }]);
307
+ return (result ?? {
308
+ name: target.name,
309
+ ok: false,
310
+ toolCount: 0,
311
+ tools: [],
312
+ error: "connection produced no result",
313
+ });
314
+ },
315
+ dispose: () => manager.dispose(),
316
+ };
317
+ }, {
318
+ catalogCache: this.catalogCache,
319
+ modernProtocol: this.modernProtocol,
320
+ onElicit: this.onElicit,
321
+ });
322
+ if (!handle.result.ok) {
323
+ // Nothing was claimed on a failed connect, but releasing is idempotent
324
+ // and keeps this path honest if that ever changes.
325
+ await handle.release();
326
+ throw new Error(handle.result.error ?? "connection failed");
327
+ }
328
+ this.sharedHandles.set(config.name, handle);
329
+ this.hiddenTools.set(config.name, handle.result.hidden ?? []);
330
+ // Wrap each pooled tool so a call from THIS session is attributable while
331
+ // it runs. The pool needs that to answer "which window asked?" when the
332
+ // server elicits mid-call; without it a shared server could only ever
333
+ // cancel its prompts.
334
+ return handle.result.tools.map((tool) => ({
335
+ ...tool,
336
+ execute: async (args, context) => {
337
+ this.assertNotRemoved(config.name);
338
+ const endCall = handle.beginCall();
339
+ try {
340
+ return await tool.execute(args, context);
341
+ }
342
+ finally {
343
+ endCall();
344
+ }
345
+ },
346
+ }));
347
+ }
348
+ /** Get-or-create the settlement record for one server name. */
349
+ connectionSlot(name) {
350
+ const existing = this.connections.get(name);
351
+ if (existing)
352
+ return existing;
353
+ let settle;
354
+ const promise = new Promise((resolve) => {
355
+ settle = resolve;
356
+ });
357
+ const slot = { promise, settle };
358
+ this.connections.set(name, slot);
359
+ return slot;
360
+ }
361
+ /**
362
+ * Resolve once a server's connection attempt has settled. Returns `ok:false`
363
+ * with the failure reason when that server could not connect, and times out
364
+ * rather than hanging when no attempt is ever made (e.g. a server that was
365
+ * removed from the config since the catalog cache was written).
366
+ */
367
+ async whenConnected(name, timeoutMs = 30_000) {
368
+ if (this.removed.has(name))
369
+ return { ok: false, error: "the server was removed" };
370
+ if (this.servers.some((server) => server.name === name))
371
+ return { ok: true };
372
+ const slot = this.connectionSlot(name);
373
+ let timer;
374
+ const timeout = new Promise((resolve) => {
375
+ timer = setTimeout(() => resolve({ ok: false, error: `timed out after ${timeoutMs}ms` }), timeoutMs);
376
+ timer.unref?.();
377
+ });
378
+ try {
379
+ return await Promise.race([slot.promise, timeout]);
380
+ }
381
+ finally {
382
+ if (timer)
383
+ clearTimeout(timer);
384
+ }
385
+ }
386
+ async connectAll(configs) {
387
+ const results = await this.connectAllDetailed(configs);
388
+ return results.flatMap((r) => r.tools);
389
+ }
390
+ /**
391
+ * Connect every enabled server and return one result per server (success →
392
+ * ok + toolCount; failure → ok:false with a human-readable error string).
393
+ * Keeps successfully connected servers in `this.servers`.
394
+ *
395
+ * Shareable servers — stdio, unless opted out with `shared: false` — are not
396
+ * connected here at all: they are claimed from the process-wide pool, so every
397
+ * session in the daemon multiplexes over one child process instead of spawning
398
+ * its own. The split is invisible to callers — results and tools come back in
399
+ * the same shape, `whenConnected` settles for both kinds, and `dispose`
400
+ * releases the pooled claims — so sharing applies wherever a manager is used
401
+ * (sessions, CLI, subagents) without each call site opting in.
402
+ */
403
+ async connectAllDetailed(configs) {
404
+ const enabled = configs.filter((c) => c.enabled !== false);
405
+ if (enabled.length === 0)
406
+ return [];
407
+ // Claim a settlement slot for every server up front, so a `whenConnected`
408
+ // caller that arrives before a slow server's turn still waits on the right
409
+ // promise instead of creating a second one.
410
+ for (const config of enabled) {
411
+ this.removed.delete(config.name);
412
+ this.connectionSlot(config.name);
413
+ }
414
+ const settled = await Promise.allSettled(enabled.map((c) => (isShareableServer(c) ? this.connectShared(c) : this.connectServer(c))));
415
+ const results = settled.map((result, i) => {
416
+ const name = enabled[i].name;
417
+ if (result.status === "fulfilled") {
418
+ const hidden = this.hiddenTools.get(name) ?? [];
419
+ return {
420
+ name,
421
+ ok: true,
422
+ toolCount: result.value.length,
423
+ tools: result.value,
424
+ ...(hidden.length > 0 ? { hidden } : {}),
425
+ };
426
+ }
427
+ const requiresAuth = isUnauthorized(result.reason);
428
+ const error = requiresAuth ? "Requires login." : formatConnectError(result.reason);
429
+ log("WARN", "mcp", `Failed to connect to MCP server "${name}"`, { error });
430
+ return { name, ok: false, toolCount: 0, tools: [], error, requiresAuth };
431
+ });
432
+ // Release anyone waiting on a cached-only tool from these servers.
433
+ for (const result of results) {
434
+ this.connectionSlot(result.name).settle(result.ok ? { ok: true } : { ok: false, error: result.error ?? "connection failed" });
435
+ }
436
+ const connected = results.filter((r) => r.ok).length;
437
+ const toolCount = results.reduce((sum, r) => sum + r.toolCount, 0);
438
+ log("INFO", "mcp", `Connected ${connected} MCP server(s), ${toolCount} tool(s)`);
439
+ return results;
440
+ }
441
+ /**
442
+ * Connect a single server, list its tools, then close that client so the
443
+ * probe connection doesn't accumulate in `this.servers`. Used to validate a
444
+ * server before persisting it.
445
+ */
446
+ async probe(config) {
447
+ try {
448
+ const tools = await this.connectServer(config, { probe: true });
449
+ const server = this.servers.find((s) => s.name === config.name);
450
+ if (server) {
451
+ this.servers = this.servers.filter((s) => s !== server);
452
+ try {
453
+ await server.client.close();
454
+ }
455
+ catch {
456
+ // Ignore close errors during probe teardown.
457
+ }
458
+ }
459
+ return { name: config.name, ok: true, toolCount: tools.length, tools };
460
+ }
461
+ catch (err) {
462
+ const requiresAuth = isUnauthorized(err);
463
+ const error = requiresAuth ? "Requires login." : formatConnectError(err);
464
+ return { name: config.name, ok: false, toolCount: 0, tools: [], error, requiresAuth };
465
+ }
466
+ }
467
+ /**
468
+ * Run the interactive OAuth login for one remote MCP server end-to-end:
469
+ * start a loopback callback server, let the SDK open the browser via
470
+ * `onAuthorizationUrl`, capture the redirect, exchange the code, then verify
471
+ * the authorized connection by listing tools. Tokens are persisted by the
472
+ * provider so later (non-interactive) connects succeed silently.
473
+ *
474
+ * `onAuthorizationUrl` is invoked with the authorize URL so the host can open
475
+ * it (the gg-app broadcasts it to the webview, which opens the system
476
+ * browser; the CLI prints it). Never throws — returns `{ ok:false, error }`.
477
+ */
478
+ async login(config, onAuthorizationUrl, timeoutMs = 180_000) {
479
+ if (!config.url) {
480
+ return { ok: false, toolCount: 0, error: "Login is only supported for HTTP MCP servers." };
481
+ }
482
+ const url = new URL(config.url);
483
+ const store = new McpOAuthStore();
484
+ // Fresh PKCE/state for this attempt so a previous half-finished login can't
485
+ // poison the exchange.
486
+ await store.patch(config.name, { codeVerifier: undefined, state: undefined });
487
+ // The whole callback query string, not just `code`: v2's finishAuth reads
488
+ // `iss` from it and validates the issuer (RFC 9207) before redeeming the
489
+ // code, which is the defense against an authorization-server mix-up.
490
+ let codeResolve;
491
+ let codeReject;
492
+ const codePromise = new Promise((resolve, reject) => {
493
+ codeResolve = resolve;
494
+ codeReject = reject;
495
+ });
496
+ const callbackPort = config.oauth?.callbackPort ?? MCP_OAUTH_CALLBACK_PORT;
497
+ const provider = new McpOAuthProvider({
498
+ serverName: config.name,
499
+ store,
500
+ onRedirect: (authUrl) => onAuthorizationUrl(authUrl.toString()),
501
+ clientId: config.oauth?.clientId,
502
+ callbackPort,
503
+ });
504
+ const expectedState = await provider.state();
505
+ // Loopback server that receives the OAuth redirect. Bound to the fixed
506
+ // callback port that the registered redirect_uri points at.
507
+ const server = http.createServer((req, res) => {
508
+ const reqUrl = new URL(req.url || "", `http://localhost:${callbackPort}`);
509
+ if (reqUrl.pathname !== MCP_OAUTH_CALLBACK_PATH) {
510
+ res.statusCode = 404;
511
+ res.end("Not found");
512
+ return;
513
+ }
514
+ const err = reqUrl.searchParams.get("error");
515
+ const code = reqUrl.searchParams.get("code");
516
+ const state = reqUrl.searchParams.get("state");
517
+ res.writeHead(200, { "Content-Type": "text/html" });
518
+ if (err) {
519
+ res.end(`<html><body><h1>Login failed</h1><p>${escapeHtml(err)}</p></body></html>`);
520
+ codeReject?.(new Error(`Authorization failed: ${err}`));
521
+ return;
522
+ }
523
+ if (!code) {
524
+ res.end("<html><body><h1>Login failed</h1><p>No authorization code.</p></body></html>");
525
+ codeReject?.(new Error("No authorization code in callback."));
526
+ return;
527
+ }
528
+ if (state !== expectedState) {
529
+ res.end("<html><body><h1>Login failed</h1><p>State mismatch.</p></body></html>");
530
+ codeReject?.(new Error("OAuth state mismatch."));
531
+ return;
532
+ }
533
+ res.end("<html><body><h1>Login successful!</h1><p>You can close this tab and return to GG Coder.</p></body></html>");
534
+ codeResolve?.(reqUrl.searchParams);
535
+ });
536
+ try {
537
+ await new Promise((resolve, reject) => {
538
+ server.once("error", reject);
539
+ server.listen(callbackPort, "127.0.0.1", () => resolve());
540
+ });
541
+ }
542
+ catch (err) {
543
+ const msg = err instanceof Error ? err.message : String(err);
544
+ const hint = msg.includes("EADDRINUSE") || msg.includes("in use")
545
+ ? `Port ${callbackPort} is in use — close whatever is using it and retry.`
546
+ : msg;
547
+ return { ok: false, toolCount: 0, error: `Could not start login callback server: ${hint}` };
548
+ }
549
+ const overallTimeout = setTimeout(() => {
550
+ codeReject?.(new Error("Login timed out waiting for the browser callback."));
551
+ }, timeoutMs);
552
+ overallTimeout.unref();
553
+ try {
554
+ // First connect triggers the redirect (browser opens) then throws
555
+ // UnauthorizedError — that's the expected, not a failure.
556
+ const loginTransport = new StreamableHTTPClientTransport(url, {
557
+ requestInit: config.headers ? { headers: config.headers } : undefined,
558
+ authProvider: provider,
559
+ });
560
+ const loginClient = new Client({ name: "ggcoder", version: "1.0.0" });
561
+ try {
562
+ await loginClient.connect(loginTransport);
563
+ // Already authorized (had valid tokens) — nothing more to do.
564
+ const { tools } = await loginClient.listTools();
565
+ await loginClient.close().catch(() => { });
566
+ return { ok: true, toolCount: tools.length };
567
+ }
568
+ catch (err) {
569
+ if (!isUnauthorized(err))
570
+ throw err;
571
+ }
572
+ const callbackParams = await codePromise;
573
+ // Exchange the code for tokens (persisted via provider.saveTokens).
574
+ await loginTransport.finishAuth(callbackParams);
575
+ await loginClient.close().catch(() => { });
576
+ // Verify the authorized connection on a fresh transport + list tools.
577
+ const verifyTransport = new StreamableHTTPClientTransport(url, {
578
+ requestInit: config.headers ? { headers: config.headers } : undefined,
579
+ authProvider: provider,
580
+ });
581
+ const verifyClient = new Client({ name: "ggcoder", version: "1.0.0" });
582
+ await verifyClient.connect(verifyTransport);
583
+ const { tools } = await verifyClient.listTools();
584
+ await verifyClient.close().catch(() => { });
585
+ return { ok: true, toolCount: tools.length };
586
+ }
587
+ catch (err) {
588
+ return { ok: false, toolCount: 0, error: formatConnectError(err) };
589
+ }
590
+ finally {
591
+ clearTimeout(overallTimeout);
592
+ server.close();
593
+ // Clear the now-consumed in-flight PKCE/state so the store only keeps tokens.
594
+ await store.patch(config.name, { codeVerifier: undefined, state: undefined });
595
+ }
596
+ }
597
+ async connectServer(config, opts = {}) {
598
+ const timeout = config.timeout ?? 30_000;
599
+ // `command` is what actually selects the stdio path further down.
600
+ const negotiate = opts.probe
601
+ ? {}
602
+ : this.negotiationOptions(config.command ? "stdio" : "http");
603
+ // A server we already know speaks the 2025 handshake skips the discovery
604
+ // probe entirely. Only the legacy verdict is reusable from an era string:
605
+ // adopting a 'modern' verdict needs the full DiscoverResult, so those still
606
+ // probe (a modern server answers immediately, so that costs nothing).
607
+ const prior = "versionNegotiation" in negotiate && (await this.cachedEra(config)) === "legacy"
608
+ ? { kind: "legacy" }
609
+ : undefined;
610
+ const connectOptions = { timeout, ...(prior ? { prior } : {}) };
611
+ let client;
612
+ let transport;
613
+ if (config.command) {
614
+ // Stdio transport for local processes.
615
+ // cwd is forced to homedir so the user's working directory can't
616
+ // affect resolution. e.g. running ggcoder from a folder whose
617
+ // package.json names the same package as the MCP server makes
618
+ // `npx -y <pkg>` self-resolve to the local source (no built bin
619
+ // shim) and fail with "command not found".
620
+ //
621
+ // For an `npx -y <pkg>` of a package that ships as a ggcoder dependency
622
+ // rewrite to a direct
623
+ // `node <binScript>` invocation. `npx` otherwise spawns a ~100 MB Node
624
+ // wrapper whose only job is to resolve+launch the real server, doubling
625
+ // memory per connection. Non-resolvable / non-npx commands pass through
626
+ // unchanged. Mirrors the LSP `process.execPath`+bin pattern.
627
+ // Same package guard as bash installs: a flagged `npx`/`uvx` package is
628
+ // never started (P7). Throws like any other connect failure.
629
+ const packageBlocked = await checkMcpLaunch(config.command, config.args ?? []);
630
+ if (packageBlocked) {
631
+ log("WARN", "mcp", `not starting "${config.name}": ${packageBlocked}`);
632
+ throw new Error(`MCP server "${config.name}" not started. ${packageBlocked}`);
633
+ }
634
+ const cooldownEnv = await launchCooldownEnv(config.command, config.args ?? [], os.homedir());
635
+ const resolved = resolveStdioCommand(config.command, config.args);
636
+ transport = new StdioClientTransport({
637
+ command: resolved.command,
638
+ args: resolved.args,
639
+ env: { ...process.env, ...cooldownEnv, ...config.env },
640
+ cwd: os.homedir(),
641
+ stderr: "pipe",
642
+ });
643
+ // Capture stderr so a crashing server doesn't fail silently — when the
644
+ // child closes the pipe before completing handshake, the SDK throws
645
+ // the opaque "-32000 Connection closed" but the real cause (stack
646
+ // trace, missing dep, port conflict) was just printed to stderr.
647
+ const stderrChunks = [];
648
+ transport.stderr?.on("data", (chunk) => {
649
+ stderrChunks.push(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
650
+ });
651
+ client = this.createClient(config.name, negotiate);
652
+ try {
653
+ await client.connect(transport, connectOptions);
654
+ }
655
+ catch (err) {
656
+ const stderr = stderrChunks.join("").slice(-4000);
657
+ if (stderr.trim()) {
658
+ log("WARN", "mcp", `stdio child stderr for "${config.name}"`, { stderr });
659
+ }
660
+ throw err;
661
+ }
662
+ }
663
+ else {
664
+ // HTTP transport (Streamable HTTP or SSE). See connectHttp for the
665
+ // transport-selection + auth logic.
666
+ if (!config.url)
667
+ throw new Error(`MCP server "${config.name}" needs a command or a url`);
668
+ const url = new URL(config.url);
669
+ const isLocal = isLocalhost(url);
670
+ try {
671
+ const r = await this.connectHttp(url, config, isLocal, negotiate, connectOptions);
672
+ client = r.client;
673
+ transport = r.transport;
674
+ }
675
+ catch (err) {
676
+ // Windows 11 resolves `localhost` → ::1 (IPv6) first; if the server
677
+ // binds IPv4-only (127.0.0.1) the first fetch gets ECONNREFUSED.
678
+ // Retry once with the alternate loopback hostname. macOS resolves
679
+ // both stacks so this only bites Windows/Linux in practice.
680
+ const alt = isLocal ? alternateLoopback(url.hostname) : undefined;
681
+ if (!alt || !isNetworkError(err))
682
+ throw err;
683
+ log("INFO", "mcp", `localhost connect failed for "${config.name}", retrying as ${alt}`, {
684
+ error: String(err),
685
+ });
686
+ const altUrl = new URL(url);
687
+ altUrl.hostname = alt;
688
+ const r = await this.connectHttp(altUrl, config, isLocal, negotiate, connectOptions);
689
+ client = r.client;
690
+ transport = r.transport;
691
+ }
692
+ }
693
+ this.servers.push({ name: config.name, client, transport, lastCallTime: 0, config });
694
+ // Report an unexpected close. A stdio child that crashes has no recovery
695
+ // path (`canRecoverSession` excludes stdio deliberately: respawning one
696
+ // mid-call would be a surprise), so the only safe response is to let the
697
+ // owner drop this connection and rebuild on the next use. That matters most
698
+ // for a POOLED connection, where a corpse would otherwise be handed to every
699
+ // session in the daemon, including ones that connect later.
700
+ client.onclose = () => {
701
+ if (this.disposing || this.idleStopped.has(client))
702
+ return;
703
+ log("WARN", "mcp", `MCP server "${config.name}" closed unexpectedly`);
704
+ this.onServerClosed?.(config.name);
705
+ };
706
+ const listed = await client.listTools(undefined, { timeout });
707
+ // gg-safe S2: hide poisoned / shadowing / rug-pulled tools before anything
708
+ // (catalog cache, deferred catalog, model) sees them.
709
+ const guarded = await this.toolGuard.filter(config.name, client.getServerVersion()?.version, listed.tools);
710
+ const tools = guarded.tools;
711
+ this.hiddenTools.set(config.name, guarded.hidden);
712
+ // Start the idle countdown (a no-op for HTTP / keepAlive / a call in
713
+ // flight). A probe connection is closed right away, so it never idles.
714
+ if (!opts.probe)
715
+ this.armIdleTimer(config);
716
+ if (opts.restart) {
717
+ // A respawn after idle shutdown only revives the process; the tools the
718
+ // model already has stay as they are (see `ensureRunning`). A server whose
719
+ // list changed meanwhile is logged — its new list lands on next session.
720
+ log("INFO", "mcp", `MCP server "${config.name}" restarted`, {
721
+ tools: String(tools.length),
722
+ });
723
+ }
724
+ // Persist the live tool list so the NEXT cold start can answer tool_search
725
+ // before this server has finished connecting. Awaited (a small serialized
726
+ // JSON write) so the entry is on disk before the connect is reported done —
727
+ // otherwise a session that starts right after would still see a cold cache.
728
+ // A failed write must never fail the connect.
729
+ try {
730
+ await this.catalogCache.save(config, tools.map((tool) => ({
731
+ name: `mcp__${config.name}__${tool.name}`,
732
+ description: tool.description ?? "",
733
+ rawInputSchema: tool.inputSchema,
734
+ })), this.negotiatedEra(client));
735
+ }
736
+ catch {
737
+ // Cache is an optimization; a connected server is still fully usable.
738
+ }
739
+ // Per-call deadlines (see MCP_DEFAULT_* above). `timeout` is the window
740
+ // WITHOUT a response or progress; every progress notification restarts it
741
+ // (`resetTimeoutOnProgress`), up to the hard `maxTotalTimeout` cap. The
742
+ // SDK checks the cap when progress arrives, so the worst case for a call is
743
+ // the cap plus one silent window.
744
+ const callTimeout = config.timeout ?? MCP_DEFAULT_CALL_TIMEOUT_MS;
745
+ const maxTotalTimeout = Math.max(config.maxTotalTimeout ?? MCP_DEFAULT_MAX_TOTAL_TIMEOUT_MS, callTimeout);
746
+ return tools.map((tool) => {
747
+ const toolName = `mcp__${config.name}__${tool.name}`;
748
+ const runCall = async (args, context) => {
749
+ const server = this.servers.find((s) => s.name === config.name);
750
+ if (server) {
751
+ const elapsed = Date.now() - server.lastCallTime;
752
+ const minGap = 2_000;
753
+ if (elapsed < minGap) {
754
+ await new Promise((r) => setTimeout(r, minGap - elapsed));
755
+ }
756
+ server.lastCallTime = Date.now();
757
+ }
758
+ // Resolve the client from `this.servers` on every attempt rather than
759
+ // closing over the one from connect time: a session rebuild (or an idle
760
+ // respawn) swaps the entry, and a stale capture would keep calling the
761
+ // dead client.
762
+ const liveClient = () => this.servers.find((s) => s.name === config.name)?.client ?? client;
763
+ // The client the attempt actually ran against, so a failure can be
764
+ // attributed to "my client was replaced" vs "the server hung up".
765
+ let attemptClient = liveClient();
766
+ const callOnce = async () => {
767
+ attemptClient = liveClient();
768
+ const result = await attemptClient.callTool({ name: tool.name, arguments: args }, {
769
+ timeout: callTimeout,
770
+ maxTotalTimeout,
771
+ resetTimeoutOnProgress: true,
772
+ // The SDK only attaches a progressToken (and so only gets progress
773
+ // at all) when `onprogress` is set. Forward it as a tool update so
774
+ // the UI can show the call is alive.
775
+ onprogress: (progress) => {
776
+ context?.onUpdate?.({ type: "mcp_progress", ...progress });
777
+ },
778
+ ...(context?.signal ? { signal: context.signal } : {}),
779
+ });
780
+ if (!("content" in result) || !Array.isArray(result.content)) {
781
+ return "(empty response)";
782
+ }
783
+ const converted = await toToolResult(result.content, toolName);
784
+ // The server ran the tool and reports it failed (MCP `isError`).
785
+ if ("isError" in result && result.isError === true) {
786
+ throw new McpToolError(resultText(converted) || "MCP tool reported an error");
787
+ }
788
+ return converted;
789
+ };
790
+ try {
791
+ return await callOnce();
792
+ }
793
+ catch (err) {
794
+ if (err instanceof McpToolError)
795
+ throw err;
796
+ // An expired HTTP session is recoverable exactly once: rebuild the
797
+ // connection and replay the call. A second failure is a real error.
798
+ if (this.canRecoverSession(config, err, attemptClient, context?.signal)) {
799
+ try {
800
+ await this.reconnectServer(config);
801
+ if (!context?.signal?.aborted)
802
+ return await callOnce();
803
+ }
804
+ catch (retryErr) {
805
+ if (retryErr instanceof McpToolError)
806
+ throw retryErr;
807
+ throw new McpToolError(`MCP tool error: ${formatConnectError(retryErr)}`);
808
+ }
809
+ }
810
+ const msg = err instanceof Error ? err.message : String(err);
811
+ if (msg.includes("Too Many R") || msg.includes("429")) {
812
+ throw new McpToolError("Rate limited — too many requests. Wait a moment before searching again.");
813
+ }
814
+ throw new McpToolError(`MCP tool error: ${msg}`);
815
+ }
816
+ };
817
+ return {
818
+ name: toolName,
819
+ description: tool.description ?? "",
820
+ parameters: z.record(z.string(), z.unknown()),
821
+ rawInputSchema: tool.inputSchema,
822
+ // Hosts that gate calls on read-only / destructive hints need these.
823
+ ...(tool.annotations ? { annotations: tool.annotations } : {}),
824
+ // The agent loop's own per-tool deadline (5 min by default) would
825
+ // otherwise preempt a long tool that is legitimately reporting
826
+ // progress, so declare the real worst case.
827
+ timeoutMs: maxTotalTimeout + callTimeout,
828
+ execute: async (args, context) => {
829
+ // Counted synchronously, before any await, so an idle timer that
830
+ // fires while this call is still starting cannot stop the server.
831
+ this.assertNotRemoved(config.name);
832
+ const idle = this.idleEligible(config) ? this.idleState(config.name) : undefined;
833
+ if (idle) {
834
+ idle.inFlight += 1;
835
+ if (idle.timer)
836
+ clearTimeout(idle.timer);
837
+ idle.timer = undefined;
838
+ }
839
+ try {
840
+ if (idle)
841
+ await this.ensureRunning(config);
842
+ return await runCall(args, context);
843
+ }
844
+ catch (err) {
845
+ if (err instanceof McpToolError)
846
+ throw err;
847
+ throw new McpToolError(`MCP tool error: ${formatConnectError(err)}`);
848
+ }
849
+ finally {
850
+ if (idle) {
851
+ idle.inFlight = Math.max(0, idle.inFlight - 1);
852
+ if (idle.inFlight === 0)
853
+ this.armIdleTimer(config);
854
+ }
855
+ }
856
+ },
857
+ };
858
+ });
859
+ }
860
+ /**
861
+ * Is this failure a recoverable expired HTTP session?
862
+ *
863
+ * Stdio servers are excluded: they have no HTTP session to expire, so a 404
864
+ * from one means something else entirely and respawning the child process
865
+ * mid-call would be a surprise. An already-aborted call is excluded too —
866
+ * reconnecting to replay work the user cancelled resurrects it.
867
+ */
868
+ canRecoverSession(config, err, attemptClient, signal) {
869
+ if (config.command)
870
+ return false;
871
+ if (signal?.aborted)
872
+ return false;
873
+ if (isSessionExpired(err))
874
+ return true;
875
+ // A sibling call that hit the same expired session may already have torn
876
+ // the transport down underneath us, which surfaces as a generic "connection
877
+ // closed" rather than the 404. Recover only when the client we called has
878
+ // genuinely been retired — otherwise this is a real disconnect and a retry
879
+ // would just fail again.
880
+ const current = this.servers.find((s) => s.name === config.name)?.client;
881
+ return current !== attemptClient && this.isConnectionClosed(err);
882
+ }
883
+ /** A local "the transport went away mid-request" failure, as the SDK reports it. */
884
+ isConnectionClosed(reason) {
885
+ return SdkError.isInstance(reason) && reason.code === SdkErrorCode.ConnectionClosed;
886
+ }
887
+ /**
888
+ * Rebuild one server's connection from its stored config, replacing the dead
889
+ * entry in `this.servers`. Concurrent callers share a single rebuild.
890
+ *
891
+ * Rejects if the reconnect itself fails, so the caller reports a real error
892
+ * rather than retrying against a client that was never replaced.
893
+ */
894
+ async reconnectServer(config) {
895
+ const inFlight = this.reconnecting.get(config.name);
896
+ if (inFlight)
897
+ return inFlight;
898
+ const attempt = (async () => {
899
+ log("INFO", "mcp", `MCP session expired for "${config.name}", reconnecting`);
900
+ const dead = this.servers.find((s) => s.name === config.name);
901
+ if (dead) {
902
+ this.servers = this.servers.filter((s) => s !== dead);
903
+ try {
904
+ await dead.client.close();
905
+ }
906
+ catch {
907
+ // The session is already gone server-side; a failed close is expected.
908
+ }
909
+ }
910
+ await this.connectServer(config);
911
+ })();
912
+ this.reconnecting.set(config.name, attempt);
913
+ try {
914
+ await attempt;
915
+ }
916
+ finally {
917
+ this.reconnecting.delete(config.name);
918
+ }
919
+ }
920
+ /**
921
+ * Connect a single HTTP (Streamable HTTP or SSE) server and return the live
922
+ * client + transport. Transport selection:
923
+ * - `transport === "sse"` → legacy SSE directly (Playwright MCP `--port`).
924
+ * - otherwise → Streamable HTTP first, SSE fallback for older servers.
925
+ *
926
+ * An OAuth provider is attached only for REMOTE servers — localhost never
927
+ * needs OAuth and attaching it there is dead weight that can misdiagnose a
928
+ * protocol mismatch as a login requirement.
929
+ */
930
+ async connectHttp(url, config, isLocal, negotiate, connectOptions) {
931
+ const reqInit = config.headers ? { headers: config.headers } : undefined;
932
+ const authProvider = isLocal
933
+ ? undefined
934
+ : new McpOAuthProvider({
935
+ serverName: config.name,
936
+ clientId: config.oauth?.clientId,
937
+ callbackPort: config.oauth?.callbackPort,
938
+ });
939
+ const sseTransport = () => new SSEClientTransport(url, {
940
+ eventSourceInit: config.headers ? { fetch: createHeaderFetch(config.headers) } : undefined,
941
+ requestInit: reqInit,
942
+ authProvider,
943
+ });
944
+ if (config.transport === "sse") {
945
+ const transport = sseTransport();
946
+ const client = this.createClient(config.name, negotiate);
947
+ await client.connect(transport, connectOptions);
948
+ return { client, transport };
949
+ }
950
+ try {
951
+ const transport = new StreamableHTTPClientTransport(url, {
952
+ requestInit: reqInit,
953
+ authProvider,
954
+ });
955
+ const client = this.createClient(config.name, negotiate);
956
+ await client.connect(transport, connectOptions);
957
+ return { client, transport };
958
+ }
959
+ catch (streamableErr) {
960
+ // For localhost, always try the SSE fallback — a 401 from localhost is
961
+ // almost certainly a protocol mismatch (e.g. Playwright MCP serves SSE),
962
+ // not an auth requirement. For remote servers, a 401 means OAuth is needed
963
+ // so skip the fallback and surface "requires login".
964
+ if (!isLocal && isUnauthorized(streamableErr))
965
+ throw streamableErr;
966
+ log("INFO", "mcp", `StreamableHTTP failed for "${config.name}", trying SSE fallback`, {
967
+ error: String(streamableErr),
968
+ });
969
+ const transport = sseTransport();
970
+ const client = this.createClient(config.name, negotiate);
971
+ await client.connect(transport, connectOptions);
972
+ return { client, transport };
973
+ }
974
+ }
975
+ /**
976
+ * Protocol era actually negotiated with a server, as the SDK reports it.
977
+ * Undefined before a connect completes; with negotiation off the SDK always
978
+ * settles on `legacy` (the 2025 `initialize` handshake).
979
+ */
980
+ negotiatedEra(client) {
981
+ return client.getProtocolEra() ?? "legacy";
982
+ }
983
+ /** Previously negotiated era for this exact server config, if still cached. */
984
+ async cachedEra(config) {
985
+ try {
986
+ return await this.catalogCache.protocolEraFor(config);
987
+ }
988
+ catch {
989
+ return undefined;
990
+ }
991
+ }
992
+ /**
993
+ * Drop one server mid-session (the user removed or replaced it). Its child
994
+ * process or pooled claim is released, and tools already handed out refuse
995
+ * further calls until a later connect brings the server back.
996
+ */
997
+ async disconnect(name) {
998
+ this.removed.add(name);
999
+ const state = this.idle.get(name);
1000
+ if (state?.timer)
1001
+ clearTimeout(state.timer);
1002
+ await state?.restarting?.catch(() => { });
1003
+ this.idle.delete(name);
1004
+ this.connections.delete(name);
1005
+ this.reconnecting.delete(name);
1006
+ this.hiddenTools.delete(name);
1007
+ const handle = this.sharedHandles.get(name);
1008
+ this.sharedHandles.delete(name);
1009
+ await handle?.release();
1010
+ const owned = this.servers.filter((s) => s.name === name);
1011
+ this.servers = this.servers.filter((s) => s.name !== name);
1012
+ for (const server of owned) {
1013
+ // Closed on purpose: not a death to report.
1014
+ this.idleStopped.add(server.client);
1015
+ try {
1016
+ await server.client.close();
1017
+ }
1018
+ catch {
1019
+ // Already gone.
1020
+ }
1021
+ }
1022
+ }
1023
+ assertNotRemoved(name) {
1024
+ if (this.removed.has(name)) {
1025
+ throw new McpToolError(`MCP server "${name}" was removed from the user's configuration; its tools no longer work.`);
1026
+ }
1027
+ }
1028
+ async dispose() {
1029
+ // Our own teardown closes transports too; flag it so those closes are not
1030
+ // reported as unexpected deaths.
1031
+ this.disposing = true;
1032
+ this.connections.clear();
1033
+ this.reconnecting.clear();
1034
+ // Idle countdowns must not outlive the manager (they are unref'd, but a
1035
+ // late fire would still try to close a client we are about to close).
1036
+ for (const state of this.idle.values()) {
1037
+ if (state.timer)
1038
+ clearTimeout(state.timer);
1039
+ state.timer = undefined;
1040
+ }
1041
+ // A respawn racing teardown would add a child after we closed the rest.
1042
+ await Promise.allSettled([...this.idle.values()].map((state) => state.restarting).filter(Boolean));
1043
+ this.idle.clear();
1044
+ // Hand back pooled claims first. These are references, not connections —
1045
+ // the shared child survives if another session still holds it, and exits
1046
+ // when this was the last claim.
1047
+ const handles = [...this.sharedHandles.values()];
1048
+ this.sharedHandles.clear();
1049
+ await Promise.all(handles.map((handle) => handle.release()));
1050
+ for (const server of this.servers) {
1051
+ try {
1052
+ await server.client.close();
1053
+ }
1054
+ catch {
1055
+ // Ignore close errors
1056
+ }
1057
+ }
1058
+ this.servers = [];
1059
+ }
1060
+ }
1061
+ /**
1062
+ * Turn a thrown connection error into a short human-readable string.
1063
+ *
1064
+ * v2 splits the old `McpError` into `ProtocolError` (a JSON-RPC error that
1065
+ * crossed the wire) and `SdkError` (a purely local failure: timeout, closed
1066
+ * connection, HTTP status). Matching the typed classes gives far better wording
1067
+ * than sniffing message text, which survives only as the fallback for errors
1068
+ * thrown before the SDK's machinery engages (raw fetch failures).
1069
+ */
1070
+ function formatConnectError(reason) {
1071
+ if (SdkHttpError.isInstance(reason)) {
1072
+ if (reason.status === 429)
1073
+ return "Rate limited (429) — try again in a moment.";
1074
+ const statusText = reason.statusText ? ` ${reason.statusText}` : "";
1075
+ return `Server responded with HTTP ${reason.status}${statusText}.`;
1076
+ }
1077
+ if (SdkError.isInstance(reason)) {
1078
+ if (reason.code === SdkErrorCode.RequestTimeout) {
1079
+ return "Timed out waiting for the server to respond.";
1080
+ }
1081
+ if (reason.code === SdkErrorCode.ConnectionClosed) {
1082
+ return "Connection closed before the server finished starting up.";
1083
+ }
1084
+ return reason.message;
1085
+ }
1086
+ if (OAuthError.isInstance(reason))
1087
+ return `OAuth error (${reason.code}): ${reason.message}`;
1088
+ if (ProtocolError.isInstance(reason))
1089
+ return reason.message;
1090
+ const msg = reason instanceof Error ? reason.message : String(reason);
1091
+ if (msg.includes("Too Many R") || msg.includes("429")) {
1092
+ return "Rate limited (429) — try again in a moment.";
1093
+ }
1094
+ return msg;
1095
+ }
1096
+ /**
1097
+ * How long to wait for a stdio server to answer `server/discover` before
1098
+ * concluding it is a 2025-era server. A local child that has not replied in
1099
+ * this window is not going to; the SDK then falls back to `initialize`.
1100
+ */
1101
+ const STDIO_PROBE_TIMEOUT_MS = 2_500;
1102
+ /** OAuth failures that mean the saved credentials can no longer be used. */
1103
+ const REAUTH_OAUTH_CODES = [
1104
+ OAuthErrorCode.InvalidToken,
1105
+ OAuthErrorCode.InvalidGrant,
1106
+ OAuthErrorCode.InvalidClient,
1107
+ OAuthErrorCode.AccessDenied,
1108
+ ];
1109
+ /**
1110
+ * Whether an error means the remote server has dropped our HTTP session.
1111
+ *
1112
+ * `StreamableHTTPClientTransport.send` handles 401/403 (it re-runs auth) but
1113
+ * returns a bare `SdkHttpError{status:404}` when the `Mcp-Session-Id` we are
1114
+ * carrying is no longer known to the server — which is exactly what happens
1115
+ * after a server restart or an idle-session sweep on a long desktop session.
1116
+ * The SDK has no recovery for it, so we rebuild the connection ourselves.
1117
+ */
1118
+ function isSessionExpired(reason) {
1119
+ return SdkHttpError.isInstance(reason) && reason.status === 404;
1120
+ }
1121
+ /**
1122
+ * Whether a connect error means the server needs OAuth login. The SDK throws
1123
+ * its typed `UnauthorizedError` when auth is required, a `SdkHttpError` for a
1124
+ * bare 401, and an `OAuthError` when the token endpoint rejects the saved
1125
+ * credentials. A raw 401 from before the auth machinery engages can still
1126
+ * surface as a plain message — so the string check remains as a fallback.
1127
+ */
1128
+ function isUnauthorized(reason) {
1129
+ if (UnauthorizedError.isInstance(reason))
1130
+ return true;
1131
+ if (SdkHttpError.isInstance(reason))
1132
+ return reason.status === 401;
1133
+ // Token/grant/client codes mean "log in again"; the rest (server_error,
1134
+ // temporarily_unavailable, …) are transient, not an auth gap.
1135
+ if (OAuthError.isInstance(reason))
1136
+ return REAUTH_OAUTH_CODES.includes(reason.code);
1137
+ const msg = reason instanceof Error ? reason.message : String(reason);
1138
+ return (msg.includes("Unauthorized") ||
1139
+ msg.includes("401") ||
1140
+ msg.toLowerCase().includes("invalid_token"));
1141
+ }
1142
+ /** Minimal HTML-escape for echoing an OAuth error string into the callback page. */
1143
+ function escapeHtml(value) {
1144
+ return value
1145
+ .replace(/&/g, "&amp;")
1146
+ .replace(/</g, "&lt;")
1147
+ .replace(/>/g, "&gt;")
1148
+ .replace(/"/g, "&quot;");
1149
+ }
1150
+ /**
1151
+ * Create a custom fetch wrapper that injects extra headers into every request.
1152
+ * Used for SSEClientTransport's eventSourceInit to pass auth headers
1153
+ * on the initial SSE GET connection (which doesn't use requestInit).
1154
+ *
1155
+ * The incoming headers may be a Web Standard `Headers` instance (v2 uses it
1156
+ * throughout) or a plain object. Spreading a `Headers` yields `{}`, silently
1157
+ * dropping the SDK's own auth header — so normalize through `Headers`, which
1158
+ * accepts both shapes, and merge with `set()` rather than bracket access.
1159
+ */
1160
+ function createHeaderFetch(extraHeaders) {
1161
+ return (url, init) => {
1162
+ const headers = new Headers(init?.headers);
1163
+ for (const [name, value] of Object.entries(extraHeaders))
1164
+ headers.set(name, value);
1165
+ return fetch(url, { ...init, headers });
1166
+ };
1167
+ }
1168
+ //# sourceMappingURL=client.js.map