airlock-bot 0.3.1 → 0.4.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 (474) hide show
  1. package/README.md +46 -33
  2. package/airlock.service +1 -0
  3. package/dist/airlock/context.d.ts.map +1 -1
  4. package/dist/airlock/context.js +5 -3
  5. package/dist/airlock/context.js.map +1 -1
  6. package/dist/airlock/tools.d.ts +15 -3
  7. package/dist/airlock/tools.d.ts.map +1 -1
  8. package/dist/airlock/tools.js +29 -1
  9. package/dist/airlock/tools.js.map +1 -1
  10. package/dist/allowlist/engine.d.ts +3 -0
  11. package/dist/allowlist/engine.d.ts.map +1 -1
  12. package/dist/allowlist/engine.js +46 -2
  13. package/dist/allowlist/engine.js.map +1 -1
  14. package/dist/audit/db.d.ts +22 -1
  15. package/dist/audit/db.d.ts.map +1 -1
  16. package/dist/audit/db.js +77 -10
  17. package/dist/audit/db.js.map +1 -1
  18. package/dist/audit/logger.d.ts +7 -2
  19. package/dist/audit/logger.d.ts.map +1 -1
  20. package/dist/audit/logger.js +18 -3
  21. package/dist/audit/logger.js.map +1 -1
  22. package/dist/audit/redactor.d.ts.map +1 -1
  23. package/dist/audit/redactor.js +6 -6
  24. package/dist/audit/redactor.js.map +1 -1
  25. package/dist/backend/airlock-adapter.d.ts +20 -2
  26. package/dist/backend/airlock-adapter.d.ts.map +1 -1
  27. package/dist/backend/airlock-adapter.js +443 -10
  28. package/dist/backend/airlock-adapter.js.map +1 -1
  29. package/dist/backend/cli/adapter.d.ts +4 -2
  30. package/dist/backend/cli/adapter.d.ts.map +1 -1
  31. package/dist/backend/cli/adapter.js +36 -11
  32. package/dist/backend/cli/adapter.js.map +1 -1
  33. package/dist/backend/cli/builder.d.ts +1 -1
  34. package/dist/backend/cli/builder.d.ts.map +1 -1
  35. package/dist/backend/cli/builder.js +28 -12
  36. package/dist/backend/cli/builder.js.map +1 -1
  37. package/dist/backend/exec-adapter.d.ts +1 -1
  38. package/dist/backend/exec-adapter.d.ts.map +1 -1
  39. package/dist/backend/exec-adapter.js +1 -5
  40. package/dist/backend/exec-adapter.js.map +1 -1
  41. package/dist/backend/factory.d.ts +2 -0
  42. package/dist/backend/factory.d.ts.map +1 -1
  43. package/dist/backend/factory.js +19 -5
  44. package/dist/backend/factory.js.map +1 -1
  45. package/dist/backend/http-adapter.d.ts +6 -3
  46. package/dist/backend/http-adapter.d.ts.map +1 -1
  47. package/dist/backend/http-adapter.js +24 -10
  48. package/dist/backend/http-adapter.js.map +1 -1
  49. package/dist/backend/mcp-adapter.d.ts +7 -2
  50. package/dist/backend/mcp-adapter.d.ts.map +1 -1
  51. package/dist/backend/mcp-adapter.js +74 -16
  52. package/dist/backend/mcp-adapter.js.map +1 -1
  53. package/dist/backend/openapi/adapter.d.ts +8 -2
  54. package/dist/backend/openapi/adapter.d.ts.map +1 -1
  55. package/dist/backend/openapi/adapter.js +196 -17
  56. package/dist/backend/openapi/adapter.js.map +1 -1
  57. package/dist/backend/openapi/parser.d.ts +15 -1
  58. package/dist/backend/openapi/parser.d.ts.map +1 -1
  59. package/dist/backend/openapi/parser.js +153 -11
  60. package/dist/backend/openapi/parser.js.map +1 -1
  61. package/dist/backend/types.d.ts +12 -1
  62. package/dist/backend/types.d.ts.map +1 -1
  63. package/dist/config/loader.d.ts.map +1 -1
  64. package/dist/config/loader.js +334 -50
  65. package/dist/config/loader.js.map +1 -1
  66. package/dist/config/mutator.d.ts.map +1 -1
  67. package/dist/config/mutator.js +13 -3
  68. package/dist/config/mutator.js.map +1 -1
  69. package/dist/config/profiles.d.ts +2 -1
  70. package/dist/config/profiles.d.ts.map +1 -1
  71. package/dist/config/profiles.js +50 -2
  72. package/dist/config/profiles.js.map +1 -1
  73. package/dist/config/provider-credentials.d.ts +4 -0
  74. package/dist/config/provider-credentials.d.ts.map +1 -0
  75. package/dist/config/provider-credentials.js +48 -0
  76. package/dist/config/provider-credentials.js.map +1 -0
  77. package/dist/config/schema.d.ts +2829 -8642
  78. package/dist/config/schema.d.ts.map +1 -1
  79. package/dist/config/schema.js +337 -122
  80. package/dist/config/schema.js.map +1 -1
  81. package/dist/config/watcher.d.ts.map +1 -1
  82. package/dist/config/watcher.js +3 -0
  83. package/dist/config/watcher.js.map +1 -1
  84. package/dist/config/yaml-merge.d.ts +9 -0
  85. package/dist/config/yaml-merge.d.ts.map +1 -0
  86. package/dist/config/yaml-merge.js +54 -0
  87. package/dist/config/yaml-merge.js.map +1 -0
  88. package/dist/configure-agent/cli.d.ts +26 -0
  89. package/dist/configure-agent/cli.d.ts.map +1 -1
  90. package/dist/configure-agent/cli.js +70 -35
  91. package/dist/configure-agent/cli.js.map +1 -1
  92. package/dist/configure-cli/cli.d.ts +6 -0
  93. package/dist/configure-cli/cli.d.ts.map +1 -1
  94. package/dist/configure-cli/cli.js +45 -14
  95. package/dist/configure-cli/cli.js.map +1 -1
  96. package/dist/configure-web/assistant.d.ts +49 -0
  97. package/dist/configure-web/assistant.d.ts.map +1 -0
  98. package/dist/configure-web/assistant.js +312 -0
  99. package/dist/configure-web/assistant.js.map +1 -0
  100. package/dist/configure-web/changes.d.ts +214 -0
  101. package/dist/configure-web/changes.d.ts.map +1 -0
  102. package/dist/configure-web/changes.js +317 -0
  103. package/dist/configure-web/changes.js.map +1 -0
  104. package/dist/configure-web/cli.d.ts +33 -11
  105. package/dist/configure-web/cli.d.ts.map +1 -1
  106. package/dist/configure-web/cli.js +704 -151
  107. package/dist/configure-web/cli.js.map +1 -1
  108. package/dist/discover/cli.js +2 -2
  109. package/dist/discover/cli.js.map +1 -1
  110. package/dist/discover/index.d.ts.map +1 -1
  111. package/dist/discover/index.js +16 -22
  112. package/dist/discover/index.js.map +1 -1
  113. package/dist/discover/openapi.d.ts.map +1 -1
  114. package/dist/discover/openapi.js +2 -0
  115. package/dist/discover/openapi.js.map +1 -1
  116. package/dist/discover/strategies/completion.d.ts.map +1 -1
  117. package/dist/discover/strategies/completion.js +19 -2
  118. package/dist/discover/strategies/completion.js.map +1 -1
  119. package/dist/discover/strategies/fig.d.ts +10 -1
  120. package/dist/discover/strategies/fig.d.ts.map +1 -1
  121. package/dist/discover/strategies/fig.js +24 -10
  122. package/dist/discover/strategies/fig.js.map +1 -1
  123. package/dist/discover/strategies/help-parser.d.ts.map +1 -1
  124. package/dist/discover/strategies/help-parser.js +9 -6
  125. package/dist/discover/strategies/help-parser.js.map +1 -1
  126. package/dist/events/payload-inspector.d.ts +25 -0
  127. package/dist/events/payload-inspector.d.ts.map +1 -0
  128. package/dist/events/payload-inspector.js +210 -0
  129. package/dist/events/payload-inspector.js.map +1 -0
  130. package/dist/events/protocol.d.ts +227 -0
  131. package/dist/events/protocol.d.ts.map +1 -0
  132. package/dist/events/protocol.js +422 -0
  133. package/dist/events/protocol.js.map +1 -0
  134. package/dist/events/registry.d.ts +57 -0
  135. package/dist/events/registry.d.ts.map +1 -0
  136. package/dist/events/registry.js +179 -0
  137. package/dist/events/registry.js.map +1 -0
  138. package/dist/events/schema-validator.d.ts +13 -0
  139. package/dist/events/schema-validator.d.ts.map +1 -0
  140. package/dist/events/schema-validator.js +54 -0
  141. package/dist/events/schema-validator.js.map +1 -0
  142. package/dist/events/service.d.ts +97 -0
  143. package/dist/events/service.d.ts.map +1 -0
  144. package/dist/events/service.js +918 -0
  145. package/dist/events/service.js.map +1 -0
  146. package/dist/events/stream-manager.d.ts +58 -0
  147. package/dist/events/stream-manager.d.ts.map +1 -0
  148. package/dist/events/stream-manager.js +94 -0
  149. package/dist/events/stream-manager.js.map +1 -0
  150. package/dist/events/upstream-client.d.ts +88 -0
  151. package/dist/events/upstream-client.d.ts.map +1 -0
  152. package/dist/events/upstream-client.js +437 -0
  153. package/dist/events/upstream-client.js.map +1 -0
  154. package/dist/gateway.d.ts +14 -0
  155. package/dist/gateway.d.ts.map +1 -1
  156. package/dist/gateway.js +208 -33
  157. package/dist/gateway.js.map +1 -1
  158. package/dist/hitl/api.d.ts.map +1 -1
  159. package/dist/hitl/api.js +9 -2
  160. package/dist/hitl/api.js.map +1 -1
  161. package/dist/hitl/approval-dashboard.d.ts +5 -0
  162. package/dist/hitl/approval-dashboard.d.ts.map +1 -1
  163. package/dist/hitl/approval-dashboard.js +107 -20
  164. package/dist/hitl/approval-dashboard.js.map +1 -1
  165. package/dist/hitl/approval-stream.d.ts +2 -0
  166. package/dist/hitl/approval-stream.d.ts.map +1 -1
  167. package/dist/hitl/approval-stream.js +11 -0
  168. package/dist/hitl/approval-stream.js.map +1 -1
  169. package/dist/hitl/engine.d.ts +154 -4
  170. package/dist/hitl/engine.d.ts.map +1 -1
  171. package/dist/hitl/engine.js +616 -102
  172. package/dist/hitl/engine.js.map +1 -1
  173. package/dist/hitl/formatter.d.ts.map +1 -1
  174. package/dist/hitl/formatter.js +60 -10
  175. package/dist/hitl/formatter.js.map +1 -1
  176. package/dist/hitl/grant-api.d.ts +32 -0
  177. package/dist/hitl/grant-api.d.ts.map +1 -0
  178. package/dist/hitl/grant-api.js +249 -0
  179. package/dist/hitl/grant-api.js.map +1 -0
  180. package/dist/hitl/grants.d.ts +153 -0
  181. package/dist/hitl/grants.d.ts.map +1 -0
  182. package/dist/hitl/grants.js +273 -0
  183. package/dist/hitl/grants.js.map +1 -0
  184. package/dist/hitl/parser.d.ts +9 -0
  185. package/dist/hitl/parser.d.ts.map +1 -1
  186. package/dist/hitl/parser.js +60 -4
  187. package/dist/hitl/parser.js.map +1 -1
  188. package/dist/hitl/provider-factory.js +6 -1
  189. package/dist/hitl/provider-factory.js.map +1 -1
  190. package/dist/hitl/providers/composite.d.ts +0 -1
  191. package/dist/hitl/providers/composite.d.ts.map +1 -1
  192. package/dist/hitl/providers/composite.js +0 -3
  193. package/dist/hitl/providers/composite.js.map +1 -1
  194. package/dist/hitl/providers/dashboard.d.ts +1 -0
  195. package/dist/hitl/providers/dashboard.d.ts.map +1 -1
  196. package/dist/hitl/providers/dashboard.js +9 -2
  197. package/dist/hitl/providers/dashboard.js.map +1 -1
  198. package/dist/hitl/providers/ios.d.ts +0 -1
  199. package/dist/hitl/providers/ios.d.ts.map +1 -1
  200. package/dist/hitl/providers/ios.js +94 -39
  201. package/dist/hitl/providers/ios.js.map +1 -1
  202. package/dist/hitl/providers/macos.d.ts +2 -0
  203. package/dist/hitl/providers/macos.d.ts.map +1 -1
  204. package/dist/hitl/providers/macos.js +90 -3
  205. package/dist/hitl/providers/macos.js.map +1 -1
  206. package/dist/hitl/providers/openclaw.js +3 -9
  207. package/dist/hitl/providers/openclaw.js.map +1 -1
  208. package/dist/hitl/providers/stdio.js +3 -9
  209. package/dist/hitl/providers/stdio.js.map +1 -1
  210. package/dist/hitl/providers/telegram.d.ts.map +1 -1
  211. package/dist/hitl/providers/telegram.js +6 -10
  212. package/dist/hitl/providers/telegram.js.map +1 -1
  213. package/dist/hitl/providers/tui.d.ts +1 -1
  214. package/dist/hitl/providers/tui.d.ts.map +1 -1
  215. package/dist/hitl/providers/tui.js +91 -31
  216. package/dist/hitl/providers/tui.js.map +1 -1
  217. package/dist/hitl/providers/types.d.ts +38 -3
  218. package/dist/hitl/providers/types.d.ts.map +1 -1
  219. package/dist/hitl/runtime.d.ts +18 -0
  220. package/dist/hitl/runtime.d.ts.map +1 -0
  221. package/dist/hitl/runtime.js +60 -0
  222. package/dist/hitl/runtime.js.map +1 -0
  223. package/dist/hook/api.d.ts +6 -1
  224. package/dist/hook/api.d.ts.map +1 -1
  225. package/dist/hook/api.js +51 -12
  226. package/dist/hook/api.js.map +1 -1
  227. package/dist/index.js +15 -3
  228. package/dist/index.js.map +1 -1
  229. package/dist/introspect/cli.d.ts.map +1 -1
  230. package/dist/introspect/cli.js +5 -2
  231. package/dist/introspect/cli.js.map +1 -1
  232. package/dist/mcp-apps/ui.d.ts +69 -0
  233. package/dist/mcp-apps/ui.d.ts.map +1 -0
  234. package/dist/mcp-apps/ui.js +143 -0
  235. package/dist/mcp-apps/ui.js.map +1 -0
  236. package/dist/middleware/audit-args.d.ts +7 -0
  237. package/dist/middleware/audit-args.d.ts.map +1 -0
  238. package/dist/middleware/audit-args.js +23 -0
  239. package/dist/middleware/audit-args.js.map +1 -0
  240. package/dist/middleware/chain-builder.d.ts +2 -2
  241. package/dist/middleware/chain-builder.d.ts.map +1 -1
  242. package/dist/middleware/chain-builder.js +7 -3
  243. package/dist/middleware/chain-builder.js.map +1 -1
  244. package/dist/middleware/core/allowlist.d.ts.map +1 -1
  245. package/dist/middleware/core/allowlist.js +8 -5
  246. package/dist/middleware/core/allowlist.js.map +1 -1
  247. package/dist/middleware/core/arg-policy.d.ts +1 -0
  248. package/dist/middleware/core/arg-policy.d.ts.map +1 -1
  249. package/dist/middleware/core/arg-policy.js +34 -37
  250. package/dist/middleware/core/arg-policy.js.map +1 -1
  251. package/dist/middleware/core/command-policy.d.ts +4 -1
  252. package/dist/middleware/core/command-policy.d.ts.map +1 -1
  253. package/dist/middleware/core/command-policy.js +50 -4
  254. package/dist/middleware/core/command-policy.js.map +1 -1
  255. package/dist/middleware/core/exec-policy.d.ts.map +1 -1
  256. package/dist/middleware/core/exec-policy.js +5 -5
  257. package/dist/middleware/core/exec-policy.js.map +1 -1
  258. package/dist/middleware/core/execute.d.ts +5 -1
  259. package/dist/middleware/core/execute.d.ts.map +1 -1
  260. package/dist/middleware/core/execute.js +18 -15
  261. package/dist/middleware/core/execute.js.map +1 -1
  262. package/dist/middleware/core/hitl-gate.d.ts +4 -1
  263. package/dist/middleware/core/hitl-gate.d.ts.map +1 -1
  264. package/dist/middleware/core/hitl-gate.js +153 -45
  265. package/dist/middleware/core/hitl-gate.js.map +1 -1
  266. package/dist/middleware/core/rate-limiter.d.ts.map +1 -1
  267. package/dist/middleware/core/rate-limiter.js +23 -7
  268. package/dist/middleware/core/rate-limiter.js.map +1 -1
  269. package/dist/middleware/core/schema-validator.d.ts +3 -0
  270. package/dist/middleware/core/schema-validator.d.ts.map +1 -1
  271. package/dist/middleware/core/schema-validator.js +31 -12
  272. package/dist/middleware/core/schema-validator.js.map +1 -1
  273. package/dist/middleware/core/upload-policy.d.ts +18 -0
  274. package/dist/middleware/core/upload-policy.d.ts.map +1 -0
  275. package/dist/middleware/core/upload-policy.js +98 -0
  276. package/dist/middleware/core/upload-policy.js.map +1 -0
  277. package/dist/middleware/detectors/injection-detector.d.ts.map +1 -1
  278. package/dist/middleware/detectors/injection-detector.js +8 -6
  279. package/dist/middleware/detectors/injection-detector.js.map +1 -1
  280. package/dist/middleware/detectors/sensitivity-classifier.d.ts.map +1 -1
  281. package/dist/middleware/detectors/sensitivity-classifier.js +19 -5
  282. package/dist/middleware/detectors/sensitivity-classifier.js.map +1 -1
  283. package/dist/middleware/post/untrusted-envelope.d.ts.map +1 -1
  284. package/dist/middleware/post/untrusted-envelope.js +4 -1
  285. package/dist/middleware/post/untrusted-envelope.js.map +1 -1
  286. package/dist/middleware/response.d.ts +33 -0
  287. package/dist/middleware/response.d.ts.map +1 -0
  288. package/dist/middleware/response.js +110 -0
  289. package/dist/middleware/response.js.map +1 -0
  290. package/dist/middleware/types.d.ts +13 -0
  291. package/dist/middleware/types.d.ts.map +1 -1
  292. package/dist/mobile/api.d.ts.map +1 -1
  293. package/dist/mobile/api.js +57 -34
  294. package/dist/mobile/api.js.map +1 -1
  295. package/dist/mobile/apns.d.ts +39 -2
  296. package/dist/mobile/apns.d.ts.map +1 -1
  297. package/dist/mobile/apns.js +84 -83
  298. package/dist/mobile/apns.js.map +1 -1
  299. package/dist/pool/client-credentials.d.ts +2 -0
  300. package/dist/pool/client-credentials.d.ts.map +1 -1
  301. package/dist/pool/client-credentials.js +18 -3
  302. package/dist/pool/client-credentials.js.map +1 -1
  303. package/dist/pool/credential-health.d.ts +2 -2
  304. package/dist/pool/credential-health.d.ts.map +1 -1
  305. package/dist/pool/credential-health.js +7 -2
  306. package/dist/pool/credential-health.js.map +1 -1
  307. package/dist/pool/http-client.d.ts +105 -16
  308. package/dist/pool/http-client.d.ts.map +1 -1
  309. package/dist/pool/http-client.js +712 -116
  310. package/dist/pool/http-client.js.map +1 -1
  311. package/dist/pool/oauth-callback-router.d.ts +35 -0
  312. package/dist/pool/oauth-callback-router.d.ts.map +1 -0
  313. package/dist/pool/oauth-callback-router.js +84 -0
  314. package/dist/pool/oauth-callback-router.js.map +1 -0
  315. package/dist/pool/oauth-cli.d.ts +10 -0
  316. package/dist/pool/oauth-cli.d.ts.map +1 -0
  317. package/dist/pool/oauth-cli.js +318 -0
  318. package/dist/pool/oauth-cli.js.map +1 -0
  319. package/dist/pool/oauth-lock.d.ts +149 -0
  320. package/dist/pool/oauth-lock.d.ts.map +1 -0
  321. package/dist/pool/oauth-lock.js +575 -0
  322. package/dist/pool/oauth-lock.js.map +1 -0
  323. package/dist/pool/oauth-provider.d.ts +231 -27
  324. package/dist/pool/oauth-provider.d.ts.map +1 -1
  325. package/dist/pool/oauth-provider.js +802 -142
  326. package/dist/pool/oauth-provider.js.map +1 -1
  327. package/dist/pool/oauth-refresh.d.ts +94 -0
  328. package/dist/pool/oauth-refresh.d.ts.map +1 -0
  329. package/dist/pool/oauth-refresh.js +477 -0
  330. package/dist/pool/oauth-refresh.js.map +1 -0
  331. package/dist/pool/oauth-store.d.ts +304 -0
  332. package/dist/pool/oauth-store.d.ts.map +1 -0
  333. package/dist/pool/oauth-store.js +684 -0
  334. package/dist/pool/oauth-store.js.map +1 -0
  335. package/dist/pool/pool.d.ts +37 -4
  336. package/dist/pool/pool.d.ts.map +1 -1
  337. package/dist/pool/pool.js +170 -8
  338. package/dist/pool/pool.js.map +1 -1
  339. package/dist/pool/required-mcps.d.ts +7 -0
  340. package/dist/pool/required-mcps.d.ts.map +1 -1
  341. package/dist/pool/required-mcps.js +40 -2
  342. package/dist/pool/required-mcps.js.map +1 -1
  343. package/dist/pool/sse-client.d.ts +17 -3
  344. package/dist/pool/sse-client.d.ts.map +1 -1
  345. package/dist/pool/sse-client.js +59 -6
  346. package/dist/pool/sse-client.js.map +1 -1
  347. package/dist/pool/status.d.ts +53 -0
  348. package/dist/pool/status.d.ts.map +1 -1
  349. package/dist/pool/stdio-client.d.ts +23 -3
  350. package/dist/pool/stdio-client.d.ts.map +1 -1
  351. package/dist/pool/stdio-client.js +84 -6
  352. package/dist/pool/stdio-client.js.map +1 -1
  353. package/dist/registry/airlock-policy.d.ts +1 -1
  354. package/dist/registry/airlock-policy.d.ts.map +1 -1
  355. package/dist/registry/airlock-policy.js +1 -1
  356. package/dist/registry/airlock-policy.js.map +1 -1
  357. package/dist/registry/registry.d.ts +22 -2
  358. package/dist/registry/registry.d.ts.map +1 -1
  359. package/dist/registry/registry.js +176 -22
  360. package/dist/registry/registry.js.map +1 -1
  361. package/dist/registry/sanitizer.d.ts +5 -0
  362. package/dist/registry/sanitizer.d.ts.map +1 -1
  363. package/dist/registry/sanitizer.js +17 -13
  364. package/dist/registry/sanitizer.js.map +1 -1
  365. package/dist/security/request.d.ts +19 -0
  366. package/dist/security/request.d.ts.map +1 -1
  367. package/dist/security/request.js +35 -1
  368. package/dist/security/request.js.map +1 -1
  369. package/dist/stdio-mode.d.ts.map +1 -1
  370. package/dist/stdio-mode.js +237 -50
  371. package/dist/stdio-mode.js.map +1 -1
  372. package/dist/tools/api.d.ts.map +1 -1
  373. package/dist/tools/api.js +49 -15
  374. package/dist/tools/api.js.map +1 -1
  375. package/dist/tools/exec.d.ts +1 -1
  376. package/dist/tools/exec.d.ts.map +1 -1
  377. package/dist/tools/http.d.ts +7 -3
  378. package/dist/tools/http.d.ts.map +1 -1
  379. package/dist/tools/http.js +179 -25
  380. package/dist/tools/http.js.map +1 -1
  381. package/dist/transport/agent-server.d.ts +29 -2
  382. package/dist/transport/agent-server.d.ts.map +1 -1
  383. package/dist/transport/agent-server.js +190 -32
  384. package/dist/transport/agent-server.js.map +1 -1
  385. package/dist/transport/http-server.d.ts +17 -2
  386. package/dist/transport/http-server.d.ts.map +1 -1
  387. package/dist/transport/http-server.js +109 -96
  388. package/dist/transport/http-server.js.map +1 -1
  389. package/dist/transport/keepalive.d.ts +11 -13
  390. package/dist/transport/keepalive.d.ts.map +1 -1
  391. package/dist/transport/keepalive.js +11 -13
  392. package/dist/transport/keepalive.js.map +1 -1
  393. package/dist/transport/oauth-callback.d.ts +19 -0
  394. package/dist/transport/oauth-callback.d.ts.map +1 -0
  395. package/dist/transport/oauth-callback.js +30 -0
  396. package/dist/transport/oauth-callback.js.map +1 -0
  397. package/dist/transport/session-limiter.d.ts +10 -3
  398. package/dist/transport/session-limiter.d.ts.map +1 -1
  399. package/dist/transport/session-limiter.js +13 -3
  400. package/dist/transport/session-limiter.js.map +1 -1
  401. package/dist/transport/sse-server.d.ts.map +1 -1
  402. package/dist/transport/sse-server.js +54 -24
  403. package/dist/transport/sse-server.js.map +1 -1
  404. package/dist/transport/stdio-server.d.ts +6 -0
  405. package/dist/transport/stdio-server.d.ts.map +1 -1
  406. package/dist/transport/stdio-server.js +19 -7
  407. package/dist/transport/stdio-server.js.map +1 -1
  408. package/dist/types.d.ts +0 -4
  409. package/dist/types.d.ts.map +1 -1
  410. package/dist/uploads/api.d.ts +20 -0
  411. package/dist/uploads/api.d.ts.map +1 -0
  412. package/dist/uploads/api.js +280 -0
  413. package/dist/uploads/api.js.map +1 -0
  414. package/dist/uploads/refs.d.ts +48 -0
  415. package/dist/uploads/refs.d.ts.map +1 -0
  416. package/dist/uploads/refs.js +273 -0
  417. package/dist/uploads/refs.js.map +1 -0
  418. package/dist/uploads/resolve.d.ts +117 -0
  419. package/dist/uploads/resolve.d.ts.map +1 -0
  420. package/dist/uploads/resolve.js +581 -0
  421. package/dist/uploads/resolve.js.map +1 -0
  422. package/dist/uploads/store.d.ts +224 -0
  423. package/dist/uploads/store.d.ts.map +1 -0
  424. package/dist/uploads/store.js +1908 -0
  425. package/dist/uploads/store.js.map +1 -0
  426. package/dist/util/atomic-file.d.ts +6 -0
  427. package/dist/util/atomic-file.d.ts.map +1 -1
  428. package/dist/util/atomic-file.js +42 -2
  429. package/dist/util/atomic-file.js.map +1 -1
  430. package/dist/util/is-record.d.ts +3 -0
  431. package/dist/util/is-record.d.ts.map +1 -0
  432. package/dist/util/is-record.js +5 -0
  433. package/dist/util/is-record.js.map +1 -0
  434. package/dist/util/stable-json.d.ts +3 -0
  435. package/dist/util/stable-json.d.ts.map +1 -0
  436. package/dist/util/stable-json.js +10 -0
  437. package/dist/util/stable-json.js.map +1 -0
  438. package/dist/util/tool-name.d.ts +9 -0
  439. package/dist/util/tool-name.d.ts.map +1 -0
  440. package/dist/util/tool-name.js +14 -0
  441. package/dist/util/tool-name.js.map +1 -0
  442. package/dist/web/assets/airlock-shield-fPu067nB.png +0 -0
  443. package/dist/web/assets/favicon-DL7sWXGq.png +0 -0
  444. package/dist/web/assets/index-B_qY7DgQ.js +225 -0
  445. package/dist/web/assets/index-Bc_jHlFK.css +1 -0
  446. package/dist/web/assets/inter-cyrillic-ext-opsz-normal-CfYZpDVp.woff2 +0 -0
  447. package/dist/web/assets/inter-cyrillic-opsz-normal-BFQXbQ-f.woff2 +0 -0
  448. package/dist/web/assets/inter-greek-ext-opsz-normal-BmPQvyvo.woff2 +0 -0
  449. package/dist/web/assets/inter-greek-opsz-normal-BM0NlUE_.woff2 +0 -0
  450. package/dist/web/assets/inter-latin-ext-opsz-normal-DpK-iCPk.woff2 +0 -0
  451. package/dist/web/assets/inter-latin-opsz-normal-BwkfbSeq.woff2 +0 -0
  452. package/dist/web/assets/inter-vietnamese-opsz-normal-Ci9T9ieq.woff2 +0 -0
  453. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  454. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  455. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  456. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  457. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  458. package/dist/web/index.html +17 -0
  459. package/examples/airlock.yaml +3 -1
  460. package/examples/claude-code-setup.md +1 -1
  461. package/examples/docker-compose.yaml +3 -1
  462. package/examples/docker-gateway.yaml +2 -1
  463. package/examples/gateway.yaml +1 -1
  464. package/examples/profiles.yaml +5 -2
  465. package/examples/sandbox-presets.yaml +4 -1
  466. package/extensions/openclaw/index.ts +3 -3
  467. package/extensions/openclaw/openclaw.plugin.json +4 -4
  468. package/package.json +25 -10
  469. package/schema.json +2819 -2029
  470. package/dist/transport/mcp-normalizer.d.ts +0 -9
  471. package/dist/transport/mcp-normalizer.d.ts.map +0 -1
  472. package/dist/transport/mcp-normalizer.js +0 -12
  473. package/dist/transport/mcp-normalizer.js.map +0 -1
  474. package/extensions/openclaw/package-lock.json +0 -8548
@@ -1,10 +1,12 @@
1
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
- import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
3
- import { auth, UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import { StreamableHTTPClientTransport, auth, extractWWWAuthenticateParams, UnauthorizedError, } from '@modelcontextprotocol/client';
3
+ import { EventsAwareClient, wrapFetchWithEventHeaders, } from '../events/upstream-client.js';
4
4
  import { FileOAuthProvider } from './oauth-provider.js';
5
5
  import { ClientCredentialsTokenSource } from './client-credentials.js';
6
+ import { OAUTH_SHUTDOWN_DRAIN_MS, oauthFetch, refreshGrant, } from './oauth-refresh.js';
6
7
  import { childLogger } from '../util/logger.js';
7
8
  import { VERSION } from '../version.js';
9
+ import { upstreamClientCapabilities } from '../mcp-apps/ui.js';
8
10
  const log = childLogger('http-client');
9
11
  const BACKOFF_STEPS = [1000, 2000, 4000, 8000, 16000, 30000];
10
12
  const MAX_RECONNECT_ATTEMPTS = BACKOFF_STEPS.length;
@@ -16,9 +18,43 @@ const REFRESH_BUFFER_MS = 5 * 60 * 1000;
16
18
  // re-evaluate — long-lived tokens (e.g. a 1-year access token) chain 24h checks until near expiry.
17
19
  const MAX_REFRESH_TIMER_MS = 24 * 60 * 60 * 1000;
18
20
  // Floor so a token already at/near expiry doesn't schedule a busy 0ms loop on connect.
19
- const MIN_REFRESH_TIMER_MS = 5 * 1000;
20
- // Backoff before retrying a transiently-failed proactive refresh (network blip, 5xx).
21
- const REFRESH_RETRY_MS = 60 * 1000;
21
+ let minRefreshTimerMs = 5 * 1000;
22
+ /** Test hook: lower the proactive-refresh timer floor (default 5 s). */
23
+ export function setProactiveRefreshFloorMs(ms = 5 * 1000) {
24
+ minRefreshTimerMs = ms;
25
+ }
26
+ /** A refresh outcome whose access token is usable now (persisted or still being written). */
27
+ function tokenUsable(outcome) {
28
+ return outcome.kind === 'refreshed' || outcome.kind === 'unpersisted';
29
+ }
30
+ // Refresh retry backoff: 1m, 2m, 4m … capped at 30m, forever. Applies to transient failures and
31
+ // to issuer rejections alike — a grant is never given up on automatically.
32
+ let REFRESH_RETRY_MS = 60 * 1000;
33
+ /** Test hook: shorten the base refresh retry delay (default 60 s). */
34
+ export function setRefreshRetryBaseMs(ms = 60 * 1000) {
35
+ REFRESH_RETRY_MS = ms;
36
+ }
37
+ const MAX_REFRESH_RETRY_MS = 30 * 60 * 1000;
38
+ // After an ambiguous exchange (answer lost) retry the same endpoint quickly once: issuers with a
39
+ // refresh-token reuse grace window (commonly 30–60 s) then still accept the presented token.
40
+ const AMBIGUOUS_RETRY_MS = 5 * 1000;
41
+ // A reactive 401 right after a successful refresh is answered by retrying, not by refreshing again.
42
+ const RECENT_REFRESH_MS = 5 * 1000;
43
+ /** Whether an HTTP fetch payload is strictly an MCP `notifications/cancelled` frame. */
44
+ function isCancellationFetch(init) {
45
+ if (typeof init?.body !== 'string')
46
+ return false;
47
+ try {
48
+ const parsed = JSON.parse(init.body);
49
+ return (typeof parsed === 'object' &&
50
+ parsed !== null &&
51
+ !Array.isArray(parsed) &&
52
+ parsed.method === 'notifications/cancelled');
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
22
58
  /** Extract a short, human-readable reason from a connection error. */
23
59
  function friendlyError(err) {
24
60
  const msg = err instanceof Error ? err.message : String(err);
@@ -27,7 +63,7 @@ function friendlyError(err) {
27
63
  return `DNS lookup failed for ${host ?? 'unknown host'}`;
28
64
  }
29
65
  if (msg.includes('InvalidGrantError') || err?.constructor?.name === 'InvalidGrantError') {
30
- return 'OAuth grant expired — re-authentication required';
66
+ return 'OAuth issuer rejected the grant (invalid_grant)';
31
67
  }
32
68
  if (msg.includes('ECONNREFUSED'))
33
69
  return 'connection refused';
@@ -71,14 +107,43 @@ export class HttpMcpClient {
71
107
  ready = false;
72
108
  reconnectTimer;
73
109
  refreshTimer;
110
+ /** Absolute time the pending refreshTimer fires (proactive refresh or retry). */
111
+ refreshDeadline;
74
112
  readyListeners = new Set();
113
+ eventsListChangedListeners = new Set();
114
+ sendGuardStorage = new AsyncLocalStorage();
75
115
  awaitingAuth = false;
76
116
  connecting = false;
77
117
  reconnectExhausted = false;
78
118
  lastError;
79
119
  /** Sticky until a successful reconnect; unlike awaitingAuth it survives callback/listener errors. */
80
120
  authorizationRequired = false;
81
- constructor(id, url, headers, oauth = false, oauthCallbackPort = 18432, clientId, clientSecret, oauthCallbackUrl, clientCredentials, requestTimeoutMs = 60_000) {
121
+ // OAuth grant health (see OAuthGrantHealth). Never paged; surfaced through status and /health.
122
+ oauthState = 'ok';
123
+ refreshFailures = 0;
124
+ lastRefreshError;
125
+ lastRefreshErrorAt;
126
+ lastRefreshAt;
127
+ nextRefreshRetryAt;
128
+ oauthIssuer;
129
+ issuerChanged;
130
+ authorizationPending = false;
131
+ lastRecordedOutcome;
132
+ lastRecordedOutcomeAt = 0;
133
+ /** From the latest 401 challenge: where the PRM lives and which scope the resource wants. */
134
+ challengeResourceMetadataUrl;
135
+ challengeScope;
136
+ flowAbort;
137
+ /** Wakes the auth flow's current wait so it re-evaluates (e.g. after taking the writer lock). */
138
+ flowWake;
139
+ unsubscribeWriterAcquired;
140
+ maintenanceArming = false;
141
+ oauthMaxRefreshIntervalMs;
142
+ /** Declare MCP Apps support upstream (the provider's `mcp_apps` setting). */
143
+ mcpApps;
144
+ /** Consecutive ambiguous refresh failures (drives the one quick retry). */
145
+ ambiguousFailures = 0;
146
+ constructor(id, url, headers, oauth = false, oauthCallbackPort = 18432, clientId, clientSecret, oauthCallbackUrl, clientCredentials, requestTimeoutMs = 60_000, options = {}) {
82
147
  this.id = id;
83
148
  this.url = url;
84
149
  this.headers = headers;
@@ -88,9 +153,16 @@ export class HttpMcpClient {
88
153
  this.clientSecret = clientSecret;
89
154
  this.oauthCallbackUrl = oauthCallbackUrl;
90
155
  this.requestTimeoutMs = requestTimeoutMs;
156
+ this.mcpApps = options.mcpApps === true;
91
157
  if (this.oauth) {
92
- this.oauthProvider = new FileOAuthProvider(this.id, this.oauthCallbackPort, this.clientId, this.clientSecret, this.oauthCallbackUrl);
158
+ this.oauthProvider = new FileOAuthProvider(this.id, this.oauthCallbackPort, this.clientId, this.clientSecret, this.oauthCallbackUrl, {
159
+ storage: options.oauthStorage ?? 'writer',
160
+ storeDir: options.oauthStoreDir,
161
+ callbackMode: options.oauthCallbackMode,
162
+ callbackRouter: options.oauthCallbackRouter,
163
+ });
93
164
  }
165
+ this.oauthMaxRefreshIntervalMs = options.oauthMaxRefreshIntervalMs;
94
166
  // App-identity auth. Mutually exclusive with `oauth` (the loader rejects both together), so
95
167
  // these two never fight over the Authorization header.
96
168
  if (clientCredentials) {
@@ -100,7 +172,15 @@ export class HttpMcpClient {
100
172
  onReady(cb) {
101
173
  this.readyListeners.add(cb);
102
174
  }
175
+ onEventsListChanged(cb) {
176
+ this.eventsListChangedListeners.add(cb);
177
+ }
103
178
  async connect() {
179
+ if (this.stopped)
180
+ return;
181
+ // Grant maintenance does not depend on the MCP endpoint: a down resource server must never let
182
+ // the refresh token reach its inactivity limit.
183
+ this.ensureGrantMaintenance();
104
184
  // Don't reconnect while waiting for the user to complete the browser OAuth flow
105
185
  if (this.awaitingAuth) {
106
186
  log.debug({ id: this.id }, 'Skipping connect — already awaiting OAuth');
@@ -120,13 +200,32 @@ export class HttpMcpClient {
120
200
  transportOpts.requestInit = { headers: this.headers };
121
201
  }
122
202
  if (this.oauthProvider) {
123
- transportOpts.authProvider = this.oauthProvider;
124
- }
125
- if (this.tokenSource) {
126
- transportOpts.fetch = this.clientCredentialsFetch();
203
+ // A minimal AuthProvider, deliberately NOT the OAuthClientProvider: handing the transport the
204
+ // full provider makes it run the SDK's auth() on every 401, which refreshes on its own terms
205
+ // and deletes credentials on invalid_grant / issuer mismatch. Airlock owns refresh instead.
206
+ transportOpts.authProvider = this.oauthAuthProvider();
127
207
  }
208
+ const guardedFetch = this
209
+ .tokenSource
210
+ ? this.clientCredentialsFetch()
211
+ : (url, init) => {
212
+ if (!isCancellationFetch(init)) {
213
+ this.sendGuardStorage.getStore()?.();
214
+ }
215
+ return fetch(url, init);
216
+ };
217
+ transportOpts.fetch = wrapFetchWithEventHeaders(guardedFetch);
128
218
  this.transport = new StreamableHTTPClientTransport(new URL(this.url), transportOpts);
129
- this.client = new Client({ name: 'airlock', version: VERSION });
219
+ // Probe with server/discover and speak 2026-07-28 (stateless) to upstreams that support it;
220
+ // anything else falls back to the 2025 initialize handshake, unchanged from before.
221
+ this.client = new EventsAwareClient({ name: 'airlock', version: VERSION }, {
222
+ versionNegotiation: { mode: 'auto' },
223
+ capabilities: upstreamClientCapabilities(this.mcpApps),
224
+ });
225
+ this.client.onEventsListChanged?.(() => {
226
+ for (const cb of this.eventsListChangedListeners)
227
+ cb();
228
+ });
130
229
  this.connecting = true;
131
230
  this.transport.onclose = () => {
132
231
  this.ready = false;
@@ -180,7 +279,7 @@ export class HttpMcpClient {
180
279
  this.connecting = false;
181
280
  this.lastError = friendlyError(err);
182
281
  if (isAuthRequiredError(err) && this.oauthProvider) {
183
- this.startOAuthFlow(true);
282
+ this.startOAuthFlow();
184
283
  return;
185
284
  }
186
285
  log.error({ id: this.id, reason: friendlyError(err) }, 'MCP HTTP connect failed');
@@ -203,7 +302,14 @@ export class HttpMcpClient {
203
302
  const source = this.tokenSource;
204
303
  return async (url, init) => {
205
304
  const send = async (force) => {
305
+ const skipGuard = isCancellationFetch(init);
306
+ if (!skipGuard) {
307
+ this.sendGuardStorage.getStore()?.();
308
+ }
206
309
  const token = await source.getToken(force);
310
+ if (!skipGuard) {
311
+ this.sendGuardStorage.getStore()?.();
312
+ }
207
313
  const headers = new Headers(init?.headers);
208
314
  headers.set('Authorization', `Bearer ${token}`);
209
315
  return fetch(url, { ...init, headers });
@@ -221,89 +327,388 @@ export class HttpMcpClient {
221
327
  return send(true);
222
328
  };
223
329
  }
330
+ /** The transport's view of OAuth: current access token, and Airlock-owned refresh on 401. */
331
+ oauthAuthProvider() {
332
+ const provider = this.oauthProvider;
333
+ return {
334
+ token: async () => (await provider.tokens())?.access_token,
335
+ onUnauthorized: async (ctx) => {
336
+ const challenge = extractWWWAuthenticateParams(ctx.response);
337
+ if (challenge.resourceMetadataUrl) {
338
+ this.challengeResourceMetadataUrl = challenge.resourceMetadataUrl;
339
+ }
340
+ if (challenge.scope)
341
+ this.challengeScope = challenge.scope;
342
+ // Another trigger refreshed moments ago: let the transport retry with the new token.
343
+ if (this.lastRefreshAt && Date.now() - this.lastRefreshAt < RECENT_REFRESH_MS)
344
+ return;
345
+ const outcome = await this.refreshNow('reactive');
346
+ if (!tokenUsable(outcome)) {
347
+ if (outcome.kind === 'rejected' || outcome.kind === 'failed')
348
+ this.scheduleRefreshRetry();
349
+ throw new UnauthorizedError(this.outcomeReason(outcome));
350
+ }
351
+ },
352
+ };
353
+ }
354
+ /** Refresh the stored grant (single-flight per token file) and record the outcome. */
355
+ async refreshNow(trigger) {
356
+ const outcome = await refreshGrant(this.oauthProvider, this.url, {
357
+ resourceMetadataUrl: this.challengeResourceMetadataUrl,
358
+ });
359
+ this.recordRefreshOutcome(outcome, trigger);
360
+ return outcome;
361
+ }
362
+ recordRefreshOutcome(outcome, trigger) {
363
+ // Single-flight: concurrent triggers receive the same outcome object; count it once.
364
+ if (outcome === this.lastRecordedOutcome)
365
+ return;
366
+ const now = Date.now();
367
+ this.lastRecordedOutcome = outcome;
368
+ this.lastRecordedOutcomeAt = now;
369
+ if ('issuerChange' in outcome && outcome.issuerChange) {
370
+ this.issuerChanged = {
371
+ ...outcome.issuerChange,
372
+ migrated: tokenUsable(outcome) && 'migrated' in outcome && outcome.migrated === true,
373
+ at: now,
374
+ };
375
+ }
376
+ if (outcome.kind !== 'failed' || !outcome.ambiguous)
377
+ this.ambiguousFailures = 0;
378
+ switch (outcome.kind) {
379
+ case 'refreshed':
380
+ this.refreshFailures = 0;
381
+ this.nextRefreshRetryAt = undefined;
382
+ this.lastRefreshAt = now;
383
+ this.oauthIssuer = outcome.issuer ?? this.oauthIssuer;
384
+ this.oauthState = 'ok';
385
+ this.lastRefreshError = undefined;
386
+ this.lastRefreshErrorAt = undefined;
387
+ log.info({ id: this.id, trigger, issuer: outcome.issuer, persistence: outcome.persistence }, 'Refreshed OAuth access token');
388
+ this.rearmAfterExchange();
389
+ return;
390
+ case 'unpersisted':
391
+ // Usable from memory, not on disk: persistence_pending (reported live from the provider).
392
+ this.refreshFailures = 0;
393
+ this.nextRefreshRetryAt = undefined;
394
+ this.lastRefreshAt = now;
395
+ this.oauthIssuer = outcome.issuer ?? this.oauthIssuer;
396
+ this.oauthState = 'ok';
397
+ this.lastRefreshError = outcome.message;
398
+ this.lastRefreshErrorAt = now;
399
+ log.warn({ id: this.id, trigger, issuer: outcome.issuer }, outcome.message);
400
+ this.rearmAfterExchange();
401
+ return;
402
+ case 'rejected':
403
+ this.oauthState = 'grant_rejected';
404
+ this.refreshFailures++;
405
+ this.lastRefreshError =
406
+ outcome.code === 'endpoint_retired'
407
+ ? `endpoint_retired: ${outcome.message} (the grant stays pinned to that endpoint until a refresh there succeeds, or a new authorization or restore replaces it)`
408
+ : outcome.afterAmbiguous
409
+ ? `issuer rejected the stored refresh grant after an earlier exchange whose answer was lost; that exchange probably consumed it, so browser re-authorization is likely required (${outcome.message})`
410
+ : `issuer rejected the stored refresh grant (${outcome.message})`;
411
+ this.lastRefreshErrorAt = now;
412
+ this.oauthIssuer = outcome.issuer ?? this.oauthIssuer;
413
+ log.warn({
414
+ id: this.id,
415
+ trigger,
416
+ code: outcome.code,
417
+ issuer: outcome.issuer,
418
+ consecutiveFailures: this.refreshFailures,
419
+ issuerChanged: outcome.issuerChange,
420
+ }, 'OAuth issuer rejected the stored refresh grant; grant kept on disk, refresh will be retried with backoff');
421
+ return;
422
+ case 'failed':
423
+ this.oauthState = outcome.ambiguous ? 'refresh_ambiguous' : 'refresh_failing';
424
+ this.refreshFailures++;
425
+ if (outcome.ambiguous)
426
+ this.ambiguousFailures++;
427
+ this.lastRefreshError = outcome.ambiguous
428
+ ? `refresh answer lost; the issuer may have rotated the refresh token (${outcome.message})`
429
+ : outcome.message;
430
+ this.lastRefreshErrorAt = now;
431
+ log.warn({
432
+ id: this.id,
433
+ trigger,
434
+ reason: outcome.message,
435
+ issuer: outcome.issuer,
436
+ consecutiveFailures: this.refreshFailures,
437
+ }, 'OAuth token refresh failed; stored grant kept, retrying with backoff');
438
+ return;
439
+ case 'no_grant':
440
+ this.oauthState = 'missing';
441
+ return;
442
+ case 'read_only':
443
+ this.oauthState = 'read_only';
444
+ this.lastRefreshError = outcome.reason;
445
+ log.debug({ id: this.id, trigger, reason: outcome.reason }, 'Not refreshing OAuth token');
446
+ return;
447
+ }
448
+ }
224
449
  /**
225
- * Run the full browser OAuth flow: wait for the user to authorize in the
226
- * browser, finish the auth exchange, then reconnect with fresh tokens.
450
+ * Every successful exchange — proactive, reactive (401) or auth-flow — recomputes the proactive
451
+ * deadline from the new token's lifetime (recordRefreshOutcome runs once per exchange).
227
452
  */
228
- async runOAuthFlow(authorizationPrepared) {
229
- this.awaitingAuth = true;
453
+ rearmAfterExchange() {
454
+ if (this.stopped || !this.oauthProvider || this.oauthProvider.storageMode !== 'writer')
455
+ return;
456
+ void this.scheduleProactiveRefresh({ reset: true }).catch((err) => log.debug({ id: this.id, reason: friendlyError(err) }, 'Failed to re-arm token refresh'));
457
+ }
458
+ outcomeReason(outcome) {
459
+ switch (outcome.kind) {
460
+ case 'refreshed':
461
+ return 'OAuth token refreshed';
462
+ case 'unpersisted':
463
+ return `OAuth token refreshed but not yet written to disk (${outcome.message})`;
464
+ case 'rejected':
465
+ return `OAuth issuer rejected the stored grant (${outcome.message}); grant kept, refresh retrying with backoff, browser re-authorization available`;
466
+ case 'failed':
467
+ return outcome.ambiguous
468
+ ? `OAuth token refresh answer lost (${outcome.message}); the issuer may have rotated the refresh token; retrying the same endpoint`
469
+ : `OAuth token refresh failing (${outcome.message}); grant kept, retrying with backoff`;
470
+ case 'no_grant':
471
+ return 'OAuth authorization required';
472
+ case 'read_only':
473
+ return `OAuth access token not usable and this process does not refresh it (${outcome.reason})`;
474
+ }
475
+ }
476
+ refreshBackoffMs() {
477
+ const exponent = Math.max(0, this.refreshFailures - 1);
478
+ return Math.min(REFRESH_RETRY_MS * 2 ** Math.min(exponent, 16), MAX_REFRESH_RETRY_MS);
479
+ }
480
+ /** Retry the refresh later. Never gives up; the delay grows to 30 minutes. */
481
+ scheduleRefreshRetry(delay = this.ambiguousFailures === 1 ? AMBIGUOUS_RETRY_MS : this.refreshBackoffMs()) {
482
+ if (this.stopped || !this.oauthProvider)
483
+ return;
484
+ if (this.refreshTimer)
485
+ clearTimeout(this.refreshTimer);
486
+ this.nextRefreshRetryAt = Date.now() + delay;
487
+ this.refreshDeadline = this.nextRefreshRetryAt;
488
+ this.refreshTimer = setTimeout(() => {
489
+ this.refreshTimer = undefined;
490
+ this.refreshDeadline = undefined;
491
+ this.nextRefreshRetryAt = undefined;
492
+ void this.proactiveRefresh();
493
+ }, delay);
494
+ this.refreshTimer.unref?.();
495
+ }
496
+ /**
497
+ * Interactive-authorization fallback. Runs while the provider is unusable:
498
+ * 1. try a refresh of the stored grant (a 401 often races a refresh that would succeed);
499
+ * 2. prepare a browser authorization — staged as `pending`, never touching the stored grant;
500
+ * 3. wait for the callback code, or for the token file to change (our own background refresh
501
+ * retry succeeding, another process, or an operator restore) — whichever comes first.
502
+ * Then reconnect. Background refresh retries keep running throughout.
503
+ */
504
+ async runOAuthFlow() {
505
+ const provider = this.oauthProvider;
506
+ const abort = new AbortController();
507
+ this.flowAbort = abort;
230
508
  try {
231
- if (!authorizationPrepared) {
232
- const result = await auth(this.oauthProvider, { serverUrl: this.url });
233
- if (result === 'AUTHORIZED') {
234
- // The reactive 401 raced a usable refresh token. Reconnect without asking the operator
235
- // to complete a browser flow that is no longer necessary.
236
- this.awaitingAuth = false;
237
- const oldTransport = this.transport;
238
- if (oldTransport)
239
- oldTransport.onclose = undefined;
240
- await oldTransport?.close();
241
- await this.connect();
509
+ let first = true;
510
+ while (!this.stopped && !abort.signal.aborted) {
511
+ // The 401 that started this flow usually just ran a refresh; don't hit the issuer twice.
512
+ const recent = first &&
513
+ this.lastRecordedOutcome &&
514
+ Date.now() - this.lastRecordedOutcomeAt < RECENT_REFRESH_MS
515
+ ? this.lastRecordedOutcome
516
+ : undefined;
517
+ first = false;
518
+ // A just-refreshed token that the server still answers with 401 is not fixed by another
519
+ // refresh (that would loop, spending a rotating token each time). Back off instead.
520
+ const freshTokenRejected = recent !== undefined && tokenUsable(recent);
521
+ const outcome = recent ?? (await this.refreshNow('auth-required'));
522
+ if (this.stopped || abort.signal.aborted)
242
523
  return;
243
- }
244
- }
245
- // Usually the callback completes this process's flow. A CLI/helper may instead finish OAuth
246
- // and replace the shared credential file. Notice that replacement and recover immediately;
247
- // previously this client waited forever until Airlock was restarted.
248
- while (true) {
249
- log.info({ id: this.id }, 'OAuth authorization required, waiting for browser flow');
250
- const previousTokenVersion = await this.oauthProvider.tokenVersion();
251
- const tokenChangeAbort = new AbortController();
252
- const outcome = await Promise.race([
253
- this.oauthProvider.waitForAuthCode().then((code) => ({ code })),
254
- this.oauthProvider.waitForTokenChange(previousTokenVersion, tokenChangeAbort.signal).then(() => ({ credentialsChanged: true })),
255
- ]);
256
- tokenChangeAbort.abort();
257
- if ('code' in outcome) {
258
- await this.transport.finishAuth(outcome.code);
524
+ if (tokenUsable(outcome) && !freshTokenRejected)
259
525
  break;
526
+ if (outcome.kind === 'rejected' || outcome.kind === 'failed') {
527
+ if (!this.refreshTimer)
528
+ this.scheduleRefreshRetry();
260
529
  }
261
- this.oauthProvider.stopCallbackServer();
262
- const result = await auth(this.oauthProvider, { serverUrl: this.url });
263
- if (result === 'AUTHORIZED') {
264
- const oldTransport = this.transport;
265
- if (oldTransport)
266
- oldTransport.onclose = undefined;
267
- await oldTransport?.close();
268
- await this.connectAfterOAuth();
530
+ if (outcome.kind === 'read_only' &&
531
+ provider.storageMode === 'writer' &&
532
+ !this.refreshTimer) {
533
+ // Another Airlock process owns the store; check again later in case it goes away.
534
+ this.scheduleRefreshRetry(REFRESH_RETRY_MS);
535
+ }
536
+ this.lastError = freshTokenRejected
537
+ ? 'MCP server rejected a freshly refreshed OAuth token'
538
+ : this.outcomeReason(outcome);
539
+ let prepared = false;
540
+ if (outcome.kind !== 'read_only' && provider.canHandleAuthCallback?.() === false) {
541
+ this.lastError = `Provider "${this.id}" uses oauth_callback_mode: gateway, which needs the Airlock gateway's HTTP listener`;
542
+ log.warn({ id: this.id }, 'Skipping interactive OAuth flow: oauth_callback_mode: gateway requires the gateway HTTP listener; waiting for token update');
543
+ }
544
+ else if (outcome.kind !== 'read_only') {
545
+ try {
546
+ const result = await this.prepareAuthorization();
547
+ if (this.stopped || abort.signal.aborted)
548
+ return;
549
+ if (result === 'AUTHORIZED')
550
+ break; // non-interactive grant obtained; just reconnect
551
+ prepared = true;
552
+ }
553
+ catch (err) {
554
+ if (this.stopped || abort.signal.aborted)
555
+ return;
556
+ log.warn({ id: this.id, reason: friendlyError(err) }, 'Could not prepare browser OAuth authorization; will retry');
557
+ }
558
+ }
559
+ this.authorizationPending = prepared;
560
+ if (prepared) {
561
+ log.info({ id: this.id }, 'OAuth authorization required, waiting for browser flow');
562
+ }
563
+ const previousTokenVersion = await provider.tokenVersion();
564
+ if (this.stopped || abort.signal.aborted)
565
+ return;
566
+ const waitAbort = new AbortController();
567
+ const onFlowAbort = () => waitAbort.abort();
568
+ abort.signal.addEventListener('abort', onFlowAbort, { once: true });
569
+ const waits = [
570
+ // Re-evaluate at once when something changes what this flow can do (this process just
571
+ // took the writer lock, a background refresh found no grant to refresh).
572
+ new Promise((resolve) => {
573
+ this.flowWake = () => resolve({ retry: true });
574
+ }),
575
+ provider
576
+ .waitForTokenChange(previousTokenVersion, waitAbort.signal)
577
+ .then(() => ({ credentialsChanged: true })),
578
+ ];
579
+ if (prepared) {
580
+ waits.push(provider.waitForAuthCode().then((code) => ({ code }), (err) => {
581
+ if (waitAbort.signal.aborted || this.stopped) {
582
+ return { retry: true };
583
+ }
584
+ const reason = friendlyError(err);
585
+ this.lastError = reason;
586
+ log.warn({ id: this.id, reason }, 'OAuth callback failed; preparing a new authorization later');
587
+ return sleep(this.refreshBackoffMs(), waitAbort.signal).then(() => ({
588
+ retry: true,
589
+ }));
590
+ }));
591
+ }
592
+ else {
593
+ // Never wait unboundedly: a read-only wait (another process owns the store) is
594
+ // re-evaluated at least every minute, and at once when this process takes the lock.
595
+ const delay = outcome.kind === 'read_only' ? REFRESH_RETRY_MS : this.refreshBackoffMs();
596
+ waits.push(sleep(delay, waitAbort.signal).then(() => ({ retry: true })));
597
+ }
598
+ const result = await Promise.race(waits);
599
+ this.flowWake = undefined;
600
+ waitAbort.abort();
601
+ abort.signal.removeEventListener('abort', onFlowAbort);
602
+ if (this.stopped || abort.signal.aborted)
269
603
  return;
604
+ if ('code' in result) {
605
+ try {
606
+ await this.finishAuthorization(result.code);
607
+ break;
608
+ }
609
+ catch (err) {
610
+ this.lastError = friendlyError(err);
611
+ log.warn({ id: this.id, reason: this.lastError }, 'OAuth authorization code exchange failed; stored grant kept');
612
+ continue;
613
+ }
270
614
  }
271
- // The replacement was not usable. auth() prepared a fresh authorization request; wait for
272
- // that callback (or another external replacement) without latching stale state.
615
+ provider.stopCallbackServer();
616
+ if ('credentialsChanged' in result) {
617
+ log.info({ id: this.id }, 'OAuth credentials changed on disk; reconnecting');
618
+ break;
619
+ }
620
+ // retry: loop again (refresh + re-prepare)
273
621
  }
274
622
  }
275
623
  catch (err) {
624
+ if (this.stopped)
625
+ return;
276
626
  this.lastError = friendlyError(err);
277
627
  throw err;
278
628
  }
279
629
  finally {
280
630
  this.awaitingAuth = false;
631
+ this.authorizationPending = false;
632
+ provider.stopCallbackServer();
633
+ if (this.flowAbort === abort)
634
+ this.flowAbort = undefined;
281
635
  }
282
- // Tokens are now persisted by the provider. Reconnect with a fresh
283
- // transport — the old one was already started and cannot be reused.
284
- await this.connectAfterOAuth();
285
- }
286
- /** Reconnect while runOAuthFlow still owns the awaitingAuth latch. */
287
- async connectAfterOAuth() {
288
- this.awaitingAuth = false;
636
+ if (this.stopped || abort.signal.aborted)
637
+ return;
638
+ // Credentials are persisted. Reconnect with a fresh transport — the old one was already
639
+ // started and cannot be reused.
640
+ this.client?.closeEventStreams?.('events/stream: upstream reconnecting after OAuth');
641
+ const oldTransport = this.transport;
642
+ if (oldTransport)
643
+ oldTransport.onclose = undefined;
644
+ await oldTransport?.close();
289
645
  await this.connect();
290
646
  }
647
+ /** Stage a new browser authorization. The stored grant stays usable for refresh meanwhile. */
648
+ async prepareAuthorization() {
649
+ const provider = this.oauthProvider;
650
+ await provider.beginAuthorization();
651
+ const result = await auth(provider, {
652
+ serverUrl: this.url,
653
+ forceReauthorization: true,
654
+ fetchFn: oauthFetch,
655
+ ...(this.challengeResourceMetadataUrl
656
+ ? { resourceMetadataUrl: this.challengeResourceMetadataUrl }
657
+ : {}),
658
+ ...(this.challengeScope ? { scope: this.challengeScope } : {}),
659
+ });
660
+ return result;
661
+ }
662
+ /** Exchange the callback code; on success the provider commits the new grant. */
663
+ async finishAuthorization(code) {
664
+ const provider = this.oauthProvider;
665
+ if (this.stopped || provider.closing)
666
+ throw new Error('Airlock is shutting down');
667
+ // Serialized with refresh exchanges of the same grant: a refresh in flight finishes (and
668
+ // commits coherently) before the new grant replaces it, never after.
669
+ // Checked again at dispatch: a code exchange queued behind a refresh must not be sent once
670
+ // shutdown has begun (its result could not be committed before exit).
671
+ const fetchFn = (input, init) => {
672
+ if (provider.closing && (init?.method ?? 'GET').toUpperCase() === 'POST') {
673
+ return Promise.reject(new Error('Airlock is shutting down; OAuth request not sent'));
674
+ }
675
+ return oauthFetch(input, init);
676
+ };
677
+ const result = await provider.runExclusive(() => auth(provider, {
678
+ serverUrl: this.url,
679
+ authorizationCode: code,
680
+ fetchFn,
681
+ ...(this.challengeResourceMetadataUrl
682
+ ? { resourceMetadataUrl: this.challengeResourceMetadataUrl }
683
+ : {}),
684
+ ...(this.challengeScope ? { scope: this.challengeScope } : {}),
685
+ }));
686
+ if (result !== 'AUTHORIZED')
687
+ throw new UnauthorizedError('Failed to authorize');
688
+ this.oauthState = 'ok';
689
+ this.refreshFailures = 0;
690
+ this.lastRefreshError = undefined;
691
+ this.lastRefreshErrorAt = undefined;
692
+ this.issuerChanged = undefined;
693
+ this.lastRefreshAt = Date.now();
694
+ log.info({ id: this.id }, 'OAuth authorization completed');
695
+ }
291
696
  /**
292
- * Move the provider to an honest auth_required state and start exactly one callback listener.
293
- * The SDK has already generated the authorization URL/PKCE verifier by the time it surfaces an
294
- * UnauthorizedError (including JSON-RPC "Unauthorized" failures), so this completes that flow.
697
+ * Move the provider to an honest auth_required state and start exactly one authorization flow.
698
+ * Refresh retries already scheduled keep running: they may recover the stored grant on their own.
295
699
  */
296
- startOAuthFlow(authorizationPrepared = false) {
700
+ startOAuthFlow() {
297
701
  if (!this.oauthProvider || this.stopped)
298
702
  return;
299
703
  this.ready = false;
300
704
  this.connecting = false;
301
705
  this.authorizationRequired = true;
302
- this.lastError = 'OAuth authorization required';
303
- if (this.refreshTimer) {
304
- clearTimeout(this.refreshTimer);
305
- this.refreshTimer = undefined;
306
- }
706
+ const recent = this.lastRecordedOutcome && Date.now() - this.lastRecordedOutcomeAt < RECENT_REFRESH_MS
707
+ ? this.lastRecordedOutcome
708
+ : undefined;
709
+ this.lastError =
710
+ recent && !tokenUsable(recent) ? this.outcomeReason(recent) : 'OAuth authorization required';
711
+ this.client?.closeEventStreams?.('events/stream: upstream OAuth authorization required');
307
712
  if (this.reconnectTimer) {
308
713
  clearTimeout(this.reconnectTimer);
309
714
  this.reconnectTimer = undefined;
@@ -313,7 +718,7 @@ export class HttpMcpClient {
313
718
  // Set this synchronously before launching the promise so concurrent failed tool calls cannot
314
719
  // race multiple callback servers onto the same provider port.
315
720
  this.awaitingAuth = true;
316
- void this.runOAuthFlow(authorizationPrepared).catch((oauthErr) => {
721
+ void this.runOAuthFlow().catch((oauthErr) => {
317
722
  this.lastError = friendlyError(oauthErr);
318
723
  log.error({ id: this.id, reason: this.lastError }, 'OAuth flow failed');
319
724
  });
@@ -323,20 +728,35 @@ export class HttpMcpClient {
323
728
  * itself after each refresh, and chains sub-timers for tokens whose lifetime exceeds the
324
729
  * setTimeout ceiling. No-op for non-OAuth providers or tokens without a refresh_token/expiry.
325
730
  */
326
- async scheduleProactiveRefresh() {
731
+ async scheduleProactiveRefresh(opts = {}) {
327
732
  if (!this.oauthProvider)
328
733
  return;
329
- if (this.refreshTimer) {
330
- clearTimeout(this.refreshTimer);
331
- this.refreshTimer = undefined;
734
+ // Unless a refresh just completed (`reset`), never push a pending deadline later: a reconnect
735
+ // or a re-arm may only bring the next refresh (or retry) forward.
736
+ const pending = () => !opts.reset && this.refreshTimer !== undefined && this.refreshDeadline !== undefined;
737
+ if (this.refreshFailures > 0) {
738
+ // Already failing: keep the backoff deadline instead of hammering (or postponing).
739
+ if (pending())
740
+ return;
741
+ this.scheduleRefreshRetry();
742
+ return;
332
743
  }
333
- const untilRefresh = await this.oauthProvider.msUntilRefresh(REFRESH_BUFFER_MS);
744
+ const untilRefresh = await this.oauthProvider.msUntilRefresh(REFRESH_BUFFER_MS, this.oauthMaxRefreshIntervalMs);
745
+ // stop() may have run while the grant was being read; never arm a timer after shutdown.
746
+ if (this.stopped)
747
+ return;
334
748
  if (untilRefresh === undefined)
335
749
  return;
336
750
  const beyondCeiling = untilRefresh > MAX_REFRESH_TIMER_MS;
337
- const delay = Math.max(Math.min(untilRefresh, MAX_REFRESH_TIMER_MS), MIN_REFRESH_TIMER_MS);
751
+ const delay = Math.max(Math.min(untilRefresh, MAX_REFRESH_TIMER_MS), minRefreshTimerMs);
752
+ if (pending() && Date.now() + delay >= this.refreshDeadline)
753
+ return;
754
+ if (this.refreshTimer)
755
+ clearTimeout(this.refreshTimer);
756
+ this.refreshDeadline = Date.now() + delay;
338
757
  this.refreshTimer = setTimeout(() => {
339
758
  this.refreshTimer = undefined;
759
+ this.refreshDeadline = undefined;
340
760
  // Still far from expiry — just re-evaluate rather than refreshing early.
341
761
  if (beyondCeiling) {
342
762
  void this.scheduleProactiveRefresh().catch((err) => log.debug({ id: this.id, reason: friendlyError(err) }, 'Failed to re-arm token refresh'));
@@ -348,36 +768,130 @@ export class HttpMcpClient {
348
768
  this.refreshTimer.unref?.();
349
769
  }
350
770
  /**
351
- * Refresh the access token via the stored refresh_token, ahead of expiry. On success the new token
352
- * is persisted and picked up on the transport's next request (it reads tokens per-request), so no
353
- * reconnect is needed; then re-arm the schedule. If the refresh_token itself is no longer valid,
354
- * `auth()` returns 'REDIRECT' — interactive re-auth is required and the reactive path / manual
355
- * re-auth will handle it, so don't loop here.
771
+ * Refresh the access token via the stored refresh_token, ahead of expiry (many OAuth servers
772
+ * signal expiry with an application-level error rather than HTTP 401, so a reactive refresh
773
+ * would never fire). Also the retry path for failed refreshes. Never discards the grant: an
774
+ * issuer rejection is retried with backoff exactly like an outage.
356
775
  */
357
776
  async proactiveRefresh() {
358
- if (this.stopped || this.awaitingAuth || !this.oauthProvider)
777
+ if (this.stopped || !this.oauthProvider)
359
778
  return;
779
+ let outcome;
360
780
  try {
361
- const result = await auth(this.oauthProvider, { serverUrl: this.url });
362
- if (result === 'AUTHORIZED') {
363
- log.info({ id: this.id }, 'Proactively refreshed OAuth token before expiry');
364
- await this.scheduleProactiveRefresh();
365
- }
366
- else {
367
- log.warn({ id: this.id }, 'Proactive token refresh needs interactive re-authorization (refresh token invalid)');
368
- this.startOAuthFlow(true);
369
- }
781
+ outcome = await this.refreshNow('proactive');
370
782
  }
371
783
  catch (err) {
372
- log.warn({ id: this.id, reason: friendlyError(err) }, 'Proactive token refresh failed; retrying');
373
- if (!this.stopped) {
374
- this.refreshTimer = setTimeout(() => {
375
- this.refreshTimer = undefined;
376
- void this.proactiveRefresh();
377
- }, REFRESH_RETRY_MS);
378
- this.refreshTimer.unref?.();
379
- }
784
+ // Defensive: refreshGrant reports failures as outcomes, but never let a bug stop retries.
785
+ outcome = { kind: 'failed', message: friendlyError(err) };
786
+ this.recordRefreshOutcome(outcome, 'proactive');
787
+ }
788
+ if (this.stopped)
789
+ return;
790
+ switch (outcome.kind) {
791
+ case 'refreshed':
792
+ case 'unpersisted':
793
+ if (!this.ready && !this.awaitingAuth && !this.connecting) {
794
+ // A reactive auth failure may have suspended the connection before the issuer recovered.
795
+ const oldTransport = this.transport;
796
+ if (oldTransport)
797
+ oldTransport.onclose = undefined;
798
+ await oldTransport?.close().catch(() => { });
799
+ await this.connect().catch((err) => log.warn({ id: this.id, reason: friendlyError(err) }, 'Reconnect after refresh failed'));
800
+ }
801
+ // Re-arm whatever the reconnect did: maintenance must never depend on the MCP endpoint.
802
+ if (!this.stopped)
803
+ await this.scheduleProactiveRefresh({ reset: true });
804
+ return;
805
+ case 'rejected':
806
+ case 'failed':
807
+ this.scheduleRefreshRetry();
808
+ return;
809
+ case 'read_only':
810
+ if (this.oauthProvider.storageMode === 'writer')
811
+ this.scheduleRefreshRetry(REFRESH_RETRY_MS);
812
+ return;
813
+ case 'no_grant':
814
+ if (!this.ready && !this.awaitingAuth)
815
+ this.startOAuthFlow();
816
+ else
817
+ this.flowWake?.(); // a waiting flow re-evaluates and prepares authorization
818
+ return;
819
+ }
820
+ }
821
+ /**
822
+ * Arm grant maintenance (proactive refresh / retries) for a writer-capable OAuth provider,
823
+ * independent of MCP connectivity, and re-evaluate a waiting auth flow whenever this process
824
+ * acquires the OAuth writer lock.
825
+ */
826
+ ensureGrantMaintenance() {
827
+ const provider = this.oauthProvider;
828
+ if (!provider || provider.storageMode !== 'writer' || this.stopped)
829
+ return;
830
+ if (!this.unsubscribeWriterAcquired) {
831
+ this.unsubscribeWriterAcquired = provider.onWriterAcquired?.(() => {
832
+ if (this.stopped)
833
+ return;
834
+ this.flowWake?.();
835
+ if (!this.refreshTimer)
836
+ void this.scheduleProactiveRefresh().catch(() => { });
837
+ });
380
838
  }
839
+ if (!this.refreshTimer && !this.maintenanceArming) {
840
+ this.maintenanceArming = true;
841
+ void this.scheduleProactiveRefresh()
842
+ .catch((err) => log.debug({ id: this.id, reason: friendlyError(err) }, 'Failed to schedule token refresh'))
843
+ .finally(() => {
844
+ this.maintenanceArming = false;
845
+ });
846
+ }
847
+ }
848
+ /** OAuth grant health for status and /health; undefined for non-OAuth providers. */
849
+ getOAuthHealth() {
850
+ if (!this.oauthProvider)
851
+ return undefined;
852
+ const iso = (ms) => (ms ? new Date(ms).toISOString() : undefined);
853
+ const provider = this.oauthProvider;
854
+ const persistencePending = provider.persistencePending === true;
855
+ const marker = provider.exchangeMarker;
856
+ let state = this.oauthState;
857
+ if (persistencePending)
858
+ state = 'persistence_pending';
859
+ else if (marker && state === 'ok')
860
+ state = 'refresh_ambiguous';
861
+ return {
862
+ state,
863
+ storage: this.oauthProvider.storageMode,
864
+ consecutiveFailures: this.refreshFailures,
865
+ ...(this.lastRefreshError ? { lastError: this.lastRefreshError } : {}),
866
+ ...(this.lastRefreshErrorAt ? { lastErrorAt: iso(this.lastRefreshErrorAt) } : {}),
867
+ ...(this.lastRefreshAt ? { lastRefreshAt: iso(this.lastRefreshAt) } : {}),
868
+ ...(this.nextRefreshRetryAt ? { nextRetryAt: iso(this.nextRefreshRetryAt) } : {}),
869
+ ...(this.oauthIssuer ? { issuer: this.oauthIssuer } : {}),
870
+ ...(this.issuerChanged
871
+ ? { issuerChanged: { ...this.issuerChanged, at: iso(this.issuerChanged.at) } }
872
+ : {}),
873
+ authorizationPending: this.authorizationPending,
874
+ persistencePending,
875
+ ...(marker
876
+ ? {
877
+ exchange: {
878
+ state: marker.state === 'in_flight' ? 'interrupted' : 'ambiguous',
879
+ since: iso(marker.at ?? marker.startedAt),
880
+ tokenEndpoint: marker.tokenEndpoint,
881
+ },
882
+ }
883
+ : {}),
884
+ };
885
+ }
886
+ /** Only grant states that need attention are attached to connection status. */
887
+ oauthStatusDetail() {
888
+ const health = this.getOAuthHealth();
889
+ if (!health)
890
+ return {};
891
+ const notable = (health.state !== 'ok' && health.state !== 'missing') ||
892
+ health.issuerChanged !== undefined ||
893
+ health.exchange !== undefined;
894
+ return notable ? { oauth: health } : {};
381
895
  }
382
896
  async listTools() {
383
897
  return this.withSessionRetry('listTools', async () => {
@@ -387,14 +901,57 @@ export class HttpMcpClient {
387
901
  return result.tools;
388
902
  });
389
903
  }
390
- async callTool(name, args, requestMeta) {
904
+ async callTool(name, args, requestMeta, beforeSend) {
391
905
  return this.withSessionRetry('callTool', async () => {
392
906
  if (!this.client || !this.ready)
393
907
  throw new Error(`MCP ${this.id} not connected`);
394
908
  const request = requestMeta
395
909
  ? { name, arguments: args, _meta: requestMeta }
396
910
  : { name, arguments: args };
397
- return this.client.callTool(request, undefined, { timeout: this.requestTimeoutMs });
911
+ const invoke = () => {
912
+ beforeSend?.();
913
+ return this.client.callTool(request, { timeout: this.requestTimeoutMs });
914
+ };
915
+ return beforeSend ? this.sendGuardStorage.run(beforeSend, invoke) : invoke();
916
+ });
917
+ }
918
+ supportsEvents() {
919
+ return Boolean(this.client && this.ready && this.client.supportsEvents());
920
+ }
921
+ async listEvents() {
922
+ return this.withSessionRetry('listEvents', async () => {
923
+ if (!this.client || !this.ready)
924
+ throw new Error(`MCP ${this.id} not connected`);
925
+ return this.client.listEvents({ timeout: this.requestTimeoutMs });
926
+ });
927
+ }
928
+ async pollEvents(params, options) {
929
+ return this.withSessionRetry('pollEvents', async () => {
930
+ if (!this.client || !this.ready)
931
+ throw new Error(`MCP ${this.id} not connected`);
932
+ return this.client.pollEvents(params, {
933
+ timeout: this.requestTimeoutMs,
934
+ signal: options?.signal,
935
+ inputSchema: options?.inputSchema,
936
+ });
937
+ });
938
+ }
939
+ async openEventStream(params, callbacks, options) {
940
+ return this.withSessionRetry('openEventStream', async () => {
941
+ if (!this.client || !this.ready)
942
+ throw new Error(`MCP ${this.id} not connected`);
943
+ return this.client.openEventStream(params, callbacks, {
944
+ ackTimeoutMs: this.requestTimeoutMs,
945
+ ...options,
946
+ });
947
+ });
948
+ }
949
+ /** Read one upstream resource (MCP Apps views are fetched this way). */
950
+ async readResource(uri) {
951
+ return this.withSessionRetry('readResource', async () => {
952
+ if (!this.client || !this.ready)
953
+ throw new Error(`MCP ${this.id} not connected`);
954
+ return this.client.readResource({ uri }, { timeout: this.requestTimeoutMs });
398
955
  });
399
956
  }
400
957
  getServerInfo() {
@@ -409,9 +966,13 @@ export class HttpMcpClient {
409
966
  }
410
967
  getConnectionStatus() {
411
968
  if (this.ready)
412
- return { status: 'up' };
969
+ return { status: 'up', ...this.oauthStatusDetail() };
413
970
  if (this.authorizationRequired) {
414
- return { status: 'auth_required', reason: this.lastError ?? 'OAuth authorization required' };
971
+ return {
972
+ status: 'auth_required',
973
+ reason: this.lastError ?? 'OAuth authorization required',
974
+ ...this.oauthStatusDetail(),
975
+ };
415
976
  }
416
977
  // A rejected client secret is a credential problem, not an outage — say so, or it hides among
417
978
  // the reconnect noise below and reads as "the provider is down".
@@ -446,6 +1007,7 @@ export class HttpMcpClient {
446
1007
  throw err;
447
1008
  log.warn({ id: this.id, operation, reason: friendlyError(err) }, 'HTTP MCP session invalid, reconnecting');
448
1009
  this.ready = false;
1010
+ this.client?.closeEventStreams?.('events/stream: upstream session invalid, reconnecting');
449
1011
  const oldTransport = this.transport;
450
1012
  if (oldTransport)
451
1013
  oldTransport.onclose = undefined;
@@ -458,25 +1020,59 @@ export class HttpMcpClient {
458
1020
  }
459
1021
  async stop() {
460
1022
  this.stopped = true;
461
- if (this.reconnectTimer) {
462
- clearTimeout(this.reconnectTimer);
463
- this.reconnectTimer = undefined;
464
- }
1023
+ this.unsubscribeWriterAcquired?.();
1024
+ this.flowWake = undefined;
1025
+ this.flowAbort?.abort();
1026
+ this.oauthProvider?.stop();
1027
+ this.tokenSource?.stop();
465
1028
  if (this.refreshTimer) {
466
1029
  clearTimeout(this.refreshTimer);
467
1030
  this.refreshTimer = undefined;
468
1031
  }
469
- this.oauthProvider?.stopCallbackServer();
1032
+ // Admit no new token exchange, and let one already sent finish its durable commit (or hand its
1033
+ // successor off) before this process gives up the writer lock and exits.
1034
+ if (this.oauthProvider?.storageMode === 'writer') {
1035
+ await this.oauthProvider.close?.(OAUTH_SHUTDOWN_DRAIN_MS);
1036
+ }
1037
+ this.client?.closeEventStreams?.('events/stream: upstream client stopped');
1038
+ if (this.reconnectTimer) {
1039
+ clearTimeout(this.reconnectTimer);
1040
+ this.reconnectTimer = undefined;
1041
+ }
470
1042
  // Release the session server-side before closing locally. transport.close() only tears down
471
1043
  // OUR end; without the DELETE that terminateSession() sends, the server keeps the session in
472
1044
  // memory forever. Servers that bound their session table then leak a slot on every gateway
473
1045
  // restart and every CLI invocation, and eventually refuse all new sessions until restarted.
474
- // Best-effort: a server that can't be reached (or answers 405, which the SDK treats as "not
475
- // supported" per spec) must never block or fail shutdown.
476
- await this.transport?.terminateSession().catch((err) => {
477
- log.debug({ id: this.id, reason: friendlyError(err) }, 'HTTP MCP session terminate failed');
478
- });
1046
+ // Best-effort: a server that can't be reached (or hangs on DELETE, or answers 405 which the
1047
+ // SDK treats as "not supported" per spec) must never block or fail shutdown/reload.
1048
+ if (this.transport) {
1049
+ let terminateTimer;
1050
+ await Promise.race([
1051
+ this.transport.terminateSession().catch((err) => {
1052
+ log.debug({ id: this.id, reason: friendlyError(err) }, 'HTTP MCP session terminate failed');
1053
+ }),
1054
+ new Promise((resolve) => {
1055
+ terminateTimer = setTimeout(resolve, 2500);
1056
+ terminateTimer.unref?.();
1057
+ }),
1058
+ ]).finally(() => {
1059
+ if (terminateTimer)
1060
+ clearTimeout(terminateTimer);
1061
+ });
1062
+ }
479
1063
  await this.transport?.close();
480
1064
  }
481
1065
  }
1066
+ function sleep(ms, signal) {
1067
+ return new Promise((resolve) => {
1068
+ if (signal.aborted)
1069
+ return resolve();
1070
+ const timer = setTimeout(resolve, ms);
1071
+ timer.unref?.();
1072
+ signal.addEventListener('abort', () => {
1073
+ clearTimeout(timer);
1074
+ resolve();
1075
+ }, { once: true });
1076
+ });
1077
+ }
482
1078
  //# sourceMappingURL=http-client.js.map