@johnhenry/mallory-cli 0.0.0-stage → 0.1.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 (760) hide show
  1. package/README.md +60 -2
  2. package/bin/mallory.mjs +51 -0
  3. package/package.json +51 -4
  4. package/src/a2a/client.js +511 -0
  5. package/src/a2a/demo-agent.js +396 -0
  6. package/src/a2a/hub.js +578 -0
  7. package/src/a2a/settings.js +88 -0
  8. package/src/a2a/task.js +358 -0
  9. package/src/acp/client.js +573 -0
  10. package/src/acp/demo-agent.js +332 -0
  11. package/src/acp/hub.js +632 -0
  12. package/src/acp/settings.js +78 -0
  13. package/src/actions/map.js +524 -0
  14. package/src/agent/cloud.js +77 -0
  15. package/src/agent/compact.js +84 -0
  16. package/src/agent/constants.js +39 -0
  17. package/src/agent/diff.js +101 -0
  18. package/src/agent/fork.js +159 -0
  19. package/src/agent/grounding.js +73 -0
  20. package/src/agent/guards.js +129 -0
  21. package/src/agent/local-transport.js +152 -0
  22. package/src/agent/loop.js +479 -0
  23. package/src/agent/park-store.js +77 -0
  24. package/src/agent/park.js +76 -0
  25. package/src/agent/ports.js +28 -0
  26. package/src/agent/providers.js +591 -0
  27. package/src/agent/restart.js +51 -0
  28. package/src/agent/router.js +380 -0
  29. package/src/agent/run.js +861 -0
  30. package/src/agent/tools.js +247 -0
  31. package/src/agent-library/engine.js +43 -0
  32. package/src/ai/bridge.js +155 -0
  33. package/src/ai/policy.js +131 -0
  34. package/src/aimatey/vendor.js +18 -0
  35. package/src/audio/container-duration.js +35 -0
  36. package/src/audio/instruments.js +776 -0
  37. package/src/audio/lanes.js +230 -0
  38. package/src/audio/patch.js +1410 -0
  39. package/src/audio/plan.js +276 -0
  40. package/src/audio/rack.js +1006 -0
  41. package/src/audio/sample-trim.js +293 -0
  42. package/src/audio/soundfont.js +243 -0
  43. package/src/audio/take-store.js +87 -0
  44. package/src/audio/takes.js +129 -0
  45. package/src/audio/wav.js +170 -0
  46. package/src/audio/zzfx.js +333 -0
  47. package/src/autonomy/bundle.js +207 -0
  48. package/src/autonomy/confine.js +61 -0
  49. package/src/autonomy/enforce.js +155 -0
  50. package/src/autonomy/file-kv.js +88 -0
  51. package/src/autonomy/ledger.js +203 -0
  52. package/src/autonomy/pins.js +50 -0
  53. package/src/autonomy/psl/index.js +32 -0
  54. package/src/autonomy/psl/suffixes.json +1 -0
  55. package/src/autonomy/record.js +28 -0
  56. package/src/autonomy/routines.js +107 -0
  57. package/src/autonomy/server.js +175 -0
  58. package/src/autonomy/signer-node.js +167 -0
  59. package/src/autonomy/store.js +43 -0
  60. package/src/autonomy/unattended.js +13 -0
  61. package/src/bytes/bytes.js +378 -0
  62. package/src/calc/syntax.js +125 -0
  63. package/src/calc/tex.js +28 -0
  64. package/src/calendar/vendor.js +2 -0
  65. package/src/clipboard.js +130 -0
  66. package/src/clsh/clsh.js +3417 -0
  67. package/src/codec/capnp.js +1804 -0
  68. package/src/codec/core.js +2043 -0
  69. package/src/codec/vendor/avro.js +136 -0
  70. package/src/codec/vendor/cbor.js +25 -0
  71. package/src/codec/vendor/flatbuffers.js +206 -0
  72. package/src/codec/vendor/msgpack.js +9 -0
  73. package/src/codec/vendor/protobuf.js +53 -0
  74. package/src/delegation/caps.js +60 -0
  75. package/src/delegation/config.js +32 -0
  76. package/src/device/model.js +246 -0
  77. package/src/device/recording.js +198 -0
  78. package/src/device/stream-model.js +151 -0
  79. package/src/documents/documents.js +1224 -0
  80. package/src/effects/catalog.js +63 -0
  81. package/src/effects/extras.js +133 -0
  82. package/src/effects/parse.js +339 -0
  83. package/src/embed/protocol.js +131 -0
  84. package/src/env/env.js +159 -0
  85. package/src/exact/vendor.js +45 -0
  86. package/src/example-meta.js +164 -0
  87. package/src/examples.js +94 -0
  88. package/src/export/canvas-image.js +217 -0
  89. package/src/export/expr-latex-lazy.js +8 -0
  90. package/src/export/formats.js +322 -0
  91. package/src/export/latex.js +183 -0
  92. package/src/export/pane.js +184 -0
  93. package/src/export/value.js +452 -0
  94. package/src/export/zip.js +214 -0
  95. package/src/ext/access.js +58 -0
  96. package/src/ext/btasks.js +225 -0
  97. package/src/ext/client.js +209 -0
  98. package/src/ext/tools.js +69 -0
  99. package/src/ext/view.js +105 -0
  100. package/src/ext/webmcp-tabs.js +299 -0
  101. package/src/files/archive.js +232 -0
  102. package/src/files/files.js +317 -0
  103. package/src/formats/json.js +24 -0
  104. package/src/formats/jupyter.js +188 -0
  105. package/src/formats/markdown.js +254 -0
  106. package/src/formats/n8n.js +276 -0
  107. package/src/formats/node-red.js +363 -0
  108. package/src/formats/registry.js +177 -0
  109. package/src/formats/rivet.js +259 -0
  110. package/src/formats/shared.js +98 -0
  111. package/src/formats/structure.js +182 -0
  112. package/src/formats/yaml.js +127 -0
  113. package/src/frame/frame.js +962 -0
  114. package/src/frame/vendor.js +1484 -0
  115. package/src/gate/audit.js +116 -0
  116. package/src/gate/gate.js +365 -0
  117. package/src/gate/policy.js +295 -0
  118. package/src/gate/scripted.js +110 -0
  119. package/src/gate/seams.js +32 -0
  120. package/src/gate/store.js +66 -0
  121. package/src/geometry/model.js +533 -0
  122. package/src/grant-key.js +149 -0
  123. package/src/graph/model.js +381 -0
  124. package/src/headless/a2a-push.js +123 -0
  125. package/src/headless/channels/config.js +142 -0
  126. package/src/headless/channels/connectors.js +283 -0
  127. package/src/headless/channels/index.js +257 -0
  128. package/src/headless/channels/mail.js +197 -0
  129. package/src/headless/channels/mailnet.js +223 -0
  130. package/src/headless/channels/platforms.js +194 -0
  131. package/src/headless/channels/replay.js +49 -0
  132. package/src/headless/cli.js +1397 -0
  133. package/src/headless/companion-client.js +182 -0
  134. package/src/headless/cost-cli.js +177 -0
  135. package/src/headless/deprecations-cli.js +102 -0
  136. package/src/headless/examples.js +48 -0
  137. package/src/headless/ffmpeg-exec.js +217 -0
  138. package/src/headless/gateways/config.js +213 -0
  139. package/src/headless/gateways/homeassistant.js +159 -0
  140. package/src/headless/gateways/index.js +121 -0
  141. package/src/headless/gateways/matter.js +150 -0
  142. package/src/headless/gateways/mqtt-client.js +177 -0
  143. package/src/headless/gateways/mqtt.js +70 -0
  144. package/src/headless/gateways/netway.js +226 -0
  145. package/src/headless/gateways/serverpod-worker.mjs +16 -0
  146. package/src/headless/gateways/serverpod.js +71 -0
  147. package/src/headless/gateways/util.js +27 -0
  148. package/src/headless/grant-cli.js +208 -0
  149. package/src/headless/guard.js +125 -0
  150. package/src/headless/guards.js +124 -0
  151. package/src/headless/machine-cli.js +853 -0
  152. package/src/headless/mcp-endpoint.js +287 -0
  153. package/src/headless/mcp-roots.js +38 -0
  154. package/src/headless/model-endpoint.js +88 -0
  155. package/src/headless/net.js +151 -0
  156. package/src/headless/node.js +263 -0
  157. package/src/headless/npm-tarball.js +29 -0
  158. package/src/headless/operator-page.js +112 -0
  159. package/src/headless/operator.js +242 -0
  160. package/src/headless/people.js +34 -0
  161. package/src/headless/pkg-cli.js +1103 -0
  162. package/src/headless/pkg-serve.js +138 -0
  163. package/src/headless/process-worker.js +88 -0
  164. package/src/headless/runner-remote.js +477 -0
  165. package/src/headless/sandbox-child.mjs +21 -0
  166. package/src/headless/scheduled.js +557 -0
  167. package/src/headless/serve-stream.js +97 -0
  168. package/src/headless/serve.js +2238 -0
  169. package/src/headless/short-links.js +158 -0
  170. package/src/headless/static-dirs.js +207 -0
  171. package/src/headless/trust-file.js +51 -0
  172. package/src/headless/watch.js +291 -0
  173. package/src/headless/ws-connect.js +65 -0
  174. package/src/headless/ws-connections.js +44 -0
  175. package/src/headless/ws-echo.js +150 -0
  176. package/src/headless/ws-proxy.js +354 -0
  177. package/src/headless/ws-ticket.js +48 -0
  178. package/src/hooks/config.js +50 -0
  179. package/src/hooks/engine.js +189 -0
  180. package/src/input/log.js +613 -0
  181. package/src/input/player.js +217 -0
  182. package/src/input/replay.js +209 -0
  183. package/src/jth/vendor.js +28 -0
  184. package/src/ledger/tx.js +94 -0
  185. package/src/machine/apply.js +193 -0
  186. package/src/machine/diff.js +168 -0
  187. package/src/machine/drive.js +296 -0
  188. package/src/machine/engine.js +478 -0
  189. package/src/machine/files-tool.js +76 -0
  190. package/src/machine/lint.js +139 -0
  191. package/src/machine/llmtm-trace.js +117 -0
  192. package/src/machine/llmtm.js +475 -0
  193. package/src/machine/otel.js +80 -0
  194. package/src/machine/pane-provider.js +51 -0
  195. package/src/machine/propose.js +159 -0
  196. package/src/machine/random.js +52 -0
  197. package/src/machine/risk.js +107 -0
  198. package/src/machine/session.js +1017 -0
  199. package/src/machine/shell-tool.js +45 -0
  200. package/src/machine/tape.js +349 -0
  201. package/src/machine/templates.js +104 -0
  202. package/src/machine/trace.js +664 -0
  203. package/src/machine/view.js +73 -0
  204. package/src/machine/vm-tool.js +47 -0
  205. package/src/machine/watchdog.js +46 -0
  206. package/src/mcp/app-args.js +51 -0
  207. package/src/mcp/app-run.js +56 -0
  208. package/src/mcp/apps.js +468 -0
  209. package/src/mcp/cache.js +232 -0
  210. package/src/mcp/client.js +507 -0
  211. package/src/mcp/demo-app.js +183 -0
  212. package/src/mcp/demo-server.js +602 -0
  213. package/src/mcp/elicitation.js +116 -0
  214. package/src/mcp/hub.js +1326 -0
  215. package/src/mcp/roots.js +139 -0
  216. package/src/mcp/sampling.js +105 -0
  217. package/src/mcp/settings.js +125 -0
  218. package/src/mcp/tape.js +292 -0
  219. package/src/mcp/uri-template.js +156 -0
  220. package/src/mcp/wsh-client.js +164 -0
  221. package/src/media/animated-codec.js +7 -0
  222. package/src/media/animated.js +623 -0
  223. package/src/media/compare-agent.js +70 -0
  224. package/src/media/compare-job.js +63 -0
  225. package/src/media/compare-page.js +296 -0
  226. package/src/media/compare-worker.js +14 -0
  227. package/src/media/compare.js +600 -0
  228. package/src/media/contract.js +62 -0
  229. package/src/media/decode-frame.js +57 -0
  230. package/src/media/decode-pool.js +188 -0
  231. package/src/media/ffmpeg-edit.js +344 -0
  232. package/src/media/ffmpeg-wasm-client.js +121 -0
  233. package/src/media/ffmpeg-wasm-session.js +79 -0
  234. package/src/media/ffmpeg-wasm.js +139 -0
  235. package/src/media/ffmpeg-worker.js +23 -0
  236. package/src/media/ffmpeg.js +903 -0
  237. package/src/media/helpers.js +419 -0
  238. package/src/media/keep.js +108 -0
  239. package/src/media/metadata-worker.js +16 -0
  240. package/src/media/metadata.js +2518 -0
  241. package/src/media/mime.js +102 -0
  242. package/src/media/page-decode.js +74 -0
  243. package/src/media/persist.js +114 -0
  244. package/src/media/png.js +226 -0
  245. package/src/media/sample-input.js +67 -0
  246. package/src/media/store.js +86 -0
  247. package/src/media/wav.js +109 -0
  248. package/src/midi/mappings.js +250 -0
  249. package/src/midi/message.js +125 -0
  250. package/src/model/action-hub.js +143 -0
  251. package/src/model/adapters.js +284 -0
  252. package/src/model/agent-runs.js +12 -0
  253. package/src/model/arrange.js +308 -0
  254. package/src/model/automation-clock.js +494 -0
  255. package/src/model/automation.js +653 -0
  256. package/src/model/batches.js +78 -0
  257. package/src/model/binary-view.js +195 -0
  258. package/src/model/breakpoints.js +392 -0
  259. package/src/model/calc-settings.js +65 -0
  260. package/src/model/calendar.js +254 -0
  261. package/src/model/canvas-id.js +5 -0
  262. package/src/model/canvas.js +5048 -0
  263. package/src/model/channel-names.js +29 -0
  264. package/src/model/channels.js +692 -0
  265. package/src/model/chart-clock.js +631 -0
  266. package/src/model/chart-code.js +69 -0
  267. package/src/model/codecs.js +60 -0
  268. package/src/model/companion-access.js +271 -0
  269. package/src/model/companion-pane.js +50 -0
  270. package/src/model/composite.js +324 -0
  271. package/src/model/context.js +380 -0
  272. package/src/model/controls.js +231 -0
  273. package/src/model/converter-presets.js +368 -0
  274. package/src/model/cost.js +580 -0
  275. package/src/model/curve-transform.js +122 -0
  276. package/src/model/cycles.js +176 -0
  277. package/src/model/debug-log.js +168 -0
  278. package/src/model/decision-clock.js +100 -0
  279. package/src/model/decisions.js +265 -0
  280. package/src/model/desk.js +87 -0
  281. package/src/model/device-hub.js +400 -0
  282. package/src/model/diff.js +445 -0
  283. package/src/model/emit-events.js +179 -0
  284. package/src/model/errors.js +238 -0
  285. package/src/model/event-presets.js +297 -0
  286. package/src/model/events.js +1303 -0
  287. package/src/model/explicit-setters.js +139 -0
  288. package/src/model/field-mapping.js +623 -0
  289. package/src/model/files-pane.js +263 -0
  290. package/src/model/flow-idle.js +89 -0
  291. package/src/model/foreach.js +549 -0
  292. package/src/model/frame-loop.js +71 -0
  293. package/src/model/frame-pressure.js +180 -0
  294. package/src/model/function-scaffold.js +1000 -0
  295. package/src/model/geometry-settings.js +54 -0
  296. package/src/model/goals.js +176 -0
  297. package/src/model/graph-settings.js +76 -0
  298. package/src/model/grid-widget.js +175 -0
  299. package/src/model/groups.js +332 -0
  300. package/src/model/hash.js +21 -0
  301. package/src/model/history.js +259 -0
  302. package/src/model/http-copy.js +88 -0
  303. package/src/model/http-send-companion.js +110 -0
  304. package/src/model/http-send.js +163 -0
  305. package/src/model/http-tap.js +521 -0
  306. package/src/model/http-tools.js +1138 -0
  307. package/src/model/import-lock.js +78 -0
  308. package/src/model/imports.js +258 -0
  309. package/src/model/infer-outputs.js +822 -0
  310. package/src/model/ink-connect.js +150 -0
  311. package/src/model/ink-diff.js +75 -0
  312. package/src/model/ink-gone.js +71 -0
  313. package/src/model/ink-route.js +120 -0
  314. package/src/model/ink-svg.js +206 -0
  315. package/src/model/ink.js +739 -0
  316. package/src/model/input-log-hub.js +456 -0
  317. package/src/model/input-split.js +69 -0
  318. package/src/model/json-schema-host.js +9 -0
  319. package/src/model/json-schema.js +368 -0
  320. package/src/model/jth.js +78 -0
  321. package/src/model/latex-expr.js +528 -0
  322. package/src/model/layout-history.js +120 -0
  323. package/src/model/lazy-map.js +88 -0
  324. package/src/model/ledger-pane.js +101 -0
  325. package/src/model/legacy-viaframe.js +90 -0
  326. package/src/model/lessons.js +448 -0
  327. package/src/model/links.js +981 -0
  328. package/src/model/live.js +411 -0
  329. package/src/model/math-widget.js +53 -0
  330. package/src/model/memory-settings.js +33 -0
  331. package/src/model/midi-controls.js +350 -0
  332. package/src/model/nl-time.js +408 -0
  333. package/src/model/notebook.js +137 -0
  334. package/src/model/pane-view-store.js +15 -0
  335. package/src/model/partial.js +115 -0
  336. package/src/model/pause-clock.js +53 -0
  337. package/src/model/peer-pane.js +32 -0
  338. package/src/model/persist-state.js +290 -0
  339. package/src/model/person-only.js +122 -0
  340. package/src/model/pin.js +209 -0
  341. package/src/model/plot-3d.js +213 -0
  342. package/src/model/plot-series.js +157 -0
  343. package/src/model/plot-settings.js +531 -0
  344. package/src/model/ports.js +312 -0
  345. package/src/model/presentation.js +222 -0
  346. package/src/model/preset-apply.js +316 -0
  347. package/src/model/preset-banks.js +335 -0
  348. package/src/model/preset-morph.js +263 -0
  349. package/src/model/preset-ops.js +205 -0
  350. package/src/model/preset-player.js +283 -0
  351. package/src/model/preset-states.js +172 -0
  352. package/src/model/profile-settings.js +109 -0
  353. package/src/model/promote.js +103 -0
  354. package/src/model/protected.js +10 -0
  355. package/src/model/proxy-log.js +230 -0
  356. package/src/model/proxy.js +367 -0
  357. package/src/model/quantity-widget.js +61 -0
  358. package/src/model/queue-book.js +359 -0
  359. package/src/model/quick-add.js +224 -0
  360. package/src/model/rate-limit.js +313 -0
  361. package/src/model/rate.js +95 -0
  362. package/src/model/recovery.js +216 -0
  363. package/src/model/rename-follow.js +113 -0
  364. package/src/model/repeater.js +1126 -0
  365. package/src/model/retention.js +664 -0
  366. package/src/model/route-edit.js +132 -0
  367. package/src/model/router.js +155 -0
  368. package/src/model/runaway.js +232 -0
  369. package/src/model/runlog.js +1033 -0
  370. package/src/model/runners/a2a.js +2 -0
  371. package/src/model/runners/acp.js +2 -0
  372. package/src/model/runners/actions.js +4 -0
  373. package/src/model/runners/agent.js +4 -0
  374. package/src/model/runners/audio.js +21 -0
  375. package/src/model/runners/automation.js +2 -0
  376. package/src/model/runners/calc.js +23 -0
  377. package/src/model/runners/catch.js +10 -0
  378. package/src/model/runners/codec.js +24 -0
  379. package/src/model/runners/companion-run.js +2 -0
  380. package/src/model/runners/device.js +7 -0
  381. package/src/model/runners/dom.js +13 -0
  382. package/src/model/runners/effects.js +2 -0
  383. package/src/model/runners/embed.js +11 -0
  384. package/src/model/runners/eval.js +2 -0
  385. package/src/model/runners/files.js +19 -0
  386. package/src/model/runners/geometry.js +23 -0
  387. package/src/model/runners/goals.js +18 -0
  388. package/src/model/runners/graph.js +23 -0
  389. package/src/model/runners/html.js +2 -0
  390. package/src/model/runners/http-proxy.js +185 -0
  391. package/src/model/runners/http-send.js +61 -0
  392. package/src/model/runners/http-static.js +83 -0
  393. package/src/model/runners/http-tap.js +26 -0
  394. package/src/model/runners/http.js +40 -0
  395. package/src/model/runners/import.js +2 -0
  396. package/src/model/runners/index.js +74 -0
  397. package/src/model/runners/input.js +14 -0
  398. package/src/model/runners/inputlog.js +7 -0
  399. package/src/model/runners/ledger.js +15 -0
  400. package/src/model/runners/machine.js +4 -0
  401. package/src/model/runners/mcp.js +2 -0
  402. package/src/model/runners/mcpapp.js +2 -0
  403. package/src/model/runners/media.js +18 -0
  404. package/src/model/runners/memory.js +28 -0
  405. package/src/model/runners/mesh-inspect.js +13 -0
  406. package/src/model/runners/peer.js +14 -0
  407. package/src/model/runners/plot.js +22 -0
  408. package/src/model/runners/render.js +14 -0
  409. package/src/model/runners/respond.js +2 -0
  410. package/src/model/runners/sample-soundfont.js +85 -0
  411. package/src/model/runners/sample.js +159 -0
  412. package/src/model/runners/scene.js +8 -0
  413. package/src/model/runners/score.js +24 -0
  414. package/src/model/runners/secret.js +10 -0
  415. package/src/model/runners/select.js +2 -0
  416. package/src/model/runners/shared.js +4 -0
  417. package/src/model/runners/shares.js +15 -0
  418. package/src/model/runners/shell.js +7 -0
  419. package/src/model/runners/skill.js +26 -0
  420. package/src/model/runners/state.js +2 -0
  421. package/src/model/runners/statechart.js +4 -0
  422. package/src/model/runners/subgraph.js +9 -0
  423. package/src/model/runners/tabs.js +25 -0
  424. package/src/model/runners/terminal.js +5 -0
  425. package/src/model/runners/text.js +4 -0
  426. package/src/model/runners/timer.js +7 -0
  427. package/src/model/runners/traffic.js +65 -0
  428. package/src/model/runners/trigger.js +2 -0
  429. package/src/model/runners/verdict.js +29 -0
  430. package/src/model/runners/vm.js +7 -0
  431. package/src/model/runners/wait.js +4 -0
  432. package/src/model/runners/ws-client.js +57 -0
  433. package/src/model/safe-regex.js +719 -0
  434. package/src/model/sample-settings.js +43 -0
  435. package/src/model/sample-source.js +47 -0
  436. package/src/model/saved-mapping.js +153 -0
  437. package/src/model/score-controllers.js +87 -0
  438. package/src/model/score-edit.js +399 -0
  439. package/src/model/score-instruments.js +300 -0
  440. package/src/model/score-library.js +407 -0
  441. package/src/model/score-markup.js +235 -0
  442. package/src/model/score-mix.js +248 -0
  443. package/src/model/score-patterns.js +276 -0
  444. package/src/model/score-selection.js +34 -0
  445. package/src/model/score-time.js +139 -0
  446. package/src/model/score-transforms.js +336 -0
  447. package/src/model/score-transport.js +192 -0
  448. package/src/model/selection.js +351 -0
  449. package/src/model/serial-controls.js +328 -0
  450. package/src/model/shares-pane.js +17 -0
  451. package/src/model/shell-pane.js +106 -0
  452. package/src/model/signature.js +1122 -0
  453. package/src/model/size-hints.js +106 -0
  454. package/src/model/size-ratio.js +12 -0
  455. package/src/model/skill-settings.js +23 -0
  456. package/src/model/snapping.js +466 -0
  457. package/src/model/split.js +375 -0
  458. package/src/model/spring-player.js +222 -0
  459. package/src/model/statecharts.js +1369 -0
  460. package/src/model/states-preset.js +208 -0
  461. package/src/model/static-route.js +100 -0
  462. package/src/model/step-words.js +45 -0
  463. package/src/model/subgraph.js +1042 -0
  464. package/src/model/switch.js +98 -0
  465. package/src/model/tabs-store.js +10 -0
  466. package/src/model/tensor-view.js +146 -0
  467. package/src/model/timer-clock.js +361 -0
  468. package/src/model/timers.js +422 -0
  469. package/src/model/timing.js +212 -0
  470. package/src/model/traffic-agent.js +111 -0
  471. package/src/model/traffic-store.js +20 -0
  472. package/src/model/traffic.js +665 -0
  473. package/src/model/transport.js +364 -0
  474. package/src/model/turns.js +86 -0
  475. package/src/model/types.js +425 -0
  476. package/src/model/value-path.js +138 -0
  477. package/src/model/versions.js +535 -0
  478. package/src/model/view-outputs.js +144 -0
  479. package/src/model/viewport-bookmarks.js +194 -0
  480. package/src/model/virtual-clock.js +85 -0
  481. package/src/model/vm-pane.js +258 -0
  482. package/src/model/wait-clock.js +715 -0
  483. package/src/model/wait-persist.js +248 -0
  484. package/src/model/waits.js +431 -0
  485. package/src/model/watch.js +80 -0
  486. package/src/model/webhook.js +496 -0
  487. package/src/model/when.js +48 -0
  488. package/src/model/widget-values.js +392 -0
  489. package/src/model/window-commands.js +278 -0
  490. package/src/model/windows.js +348 -0
  491. package/src/model/wire-inspect.js +343 -0
  492. package/src/model/wire-ops.js +324 -0
  493. package/src/model/wire-pipeline.js +378 -0
  494. package/src/model/wire-route.js +637 -0
  495. package/src/model/workspaces.js +122 -0
  496. package/src/model/ws-client.js +155 -0
  497. package/src/model/ws-demo.js +31 -0
  498. package/src/model/ws-frames.js +141 -0
  499. package/src/model/ws-hub.js +219 -0
  500. package/src/model/ws-served.js +13 -0
  501. package/src/model/xstate.js +374 -0
  502. package/src/narrative/narrative.js +1557 -0
  503. package/src/network/auth.js +224 -0
  504. package/src/network/csp-frame.js +197 -0
  505. package/src/network/declarative-shadow.js +27 -0
  506. package/src/network/frame-net-shim.js +962 -0
  507. package/src/network/hosts.js +157 -0
  508. package/src/network/policy.js +520 -0
  509. package/src/network/rtc-shim.js +418 -0
  510. package/src/network/secret-gate.js +78 -0
  511. package/src/network/secrets.js +261 -0
  512. package/src/network/sockets.js +287 -0
  513. package/src/network/store.js +186 -0
  514. package/src/network/streams.js +99 -0
  515. package/src/packages/asset-values.js +50 -0
  516. package/src/packages/assets.js +99 -0
  517. package/src/packages/deprecation.js +203 -0
  518. package/src/packages/fetch.js +152 -0
  519. package/src/packages/function-canvas.js +73 -0
  520. package/src/packages/module.js +120 -0
  521. package/src/packages/package.js +474 -0
  522. package/src/packages/published.js +27 -0
  523. package/src/packages/requires.js +83 -0
  524. package/src/packages/signing.js +145 -0
  525. package/src/packages/trust.js +107 -0
  526. package/src/panes/a2a.js +51 -0
  527. package/src/panes/acp.js +60 -0
  528. package/src/panes/actions.js +54 -0
  529. package/src/panes/agent.js +83 -0
  530. package/src/panes/audio.js +103 -0
  531. package/src/panes/automation.js +112 -0
  532. package/src/panes/calc.js +67 -0
  533. package/src/panes/catch.js +52 -0
  534. package/src/panes/codec.js +59 -0
  535. package/src/panes/colors.js +12 -0
  536. package/src/panes/companion.js +54 -0
  537. package/src/panes/decision.js +65 -0
  538. package/src/panes/device.js +56 -0
  539. package/src/panes/dom.js +37 -0
  540. package/src/panes/effects.js +118 -0
  541. package/src/panes/embed.js +30 -0
  542. package/src/panes/eval.js +186 -0
  543. package/src/panes/fields.js +299 -0
  544. package/src/panes/files.js +45 -0
  545. package/src/panes/gate.js +70 -0
  546. package/src/panes/geometry.js +64 -0
  547. package/src/panes/goals.js +75 -0
  548. package/src/panes/graph.js +66 -0
  549. package/src/panes/html.js +54 -0
  550. package/src/panes/http.js +82 -0
  551. package/src/panes/import.js +38 -0
  552. package/src/panes/input.js +124 -0
  553. package/src/panes/inputlog.js +66 -0
  554. package/src/panes/ledger.js +56 -0
  555. package/src/panes/machine.js +138 -0
  556. package/src/panes/mcp.js +85 -0
  557. package/src/panes/mcpapp.js +64 -0
  558. package/src/panes/media.js +38 -0
  559. package/src/panes/memory.js +46 -0
  560. package/src/panes/mesh-inspect.js +49 -0
  561. package/src/panes/note.js +38 -0
  562. package/src/panes/peer.js +44 -0
  563. package/src/panes/plot.js +196 -0
  564. package/src/panes/registry.js +475 -0
  565. package/src/panes/render.js +87 -0
  566. package/src/panes/respond.js +44 -0
  567. package/src/panes/router.js +84 -0
  568. package/src/panes/sample.js +75 -0
  569. package/src/panes/scene.js +55 -0
  570. package/src/panes/score.js +87 -0
  571. package/src/panes/secret.js +38 -0
  572. package/src/panes/select.js +67 -0
  573. package/src/panes/shader.js +166 -0
  574. package/src/panes/shared.js +33 -0
  575. package/src/panes/shares.js +43 -0
  576. package/src/panes/shell.js +47 -0
  577. package/src/panes/skill.js +44 -0
  578. package/src/panes/state.js +91 -0
  579. package/src/panes/statechart.js +63 -0
  580. package/src/panes/story.js +33 -0
  581. package/src/panes/subgraph.js +94 -0
  582. package/src/panes/tabs.js +52 -0
  583. package/src/panes/terminal.js +57 -0
  584. package/src/panes/text.js +36 -0
  585. package/src/panes/timer.js +55 -0
  586. package/src/panes/traffic.js +59 -0
  587. package/src/panes/verdict.js +62 -0
  588. package/src/panes/vm.js +46 -0
  589. package/src/panes/wait.js +61 -0
  590. package/src/panes/watch.js +57 -0
  591. package/src/panes/webhook.js +67 -0
  592. package/src/panes/ws-client.js +67 -0
  593. package/src/persist.js +281 -0
  594. package/src/plot/tex.js +19 -0
  595. package/src/plot/vendor.js +59 -0
  596. package/src/plot/view-vendor.js +5 -0
  597. package/src/privacy/levels.js +108 -0
  598. package/src/protocol/devtools.js +116 -0
  599. package/src/protocol/inspector.js +368 -0
  600. package/src/render/time.js +381 -0
  601. package/src/rooms/mesh-metrics.js +162 -0
  602. package/src/run/companion.js +355 -0
  603. package/src/run/describe.js +114 -0
  604. package/src/run/local-model.js +150 -0
  605. package/src/run/monitor.js +208 -0
  606. package/src/run/publish.js +360 -0
  607. package/src/run/respond-outcome.js +12 -0
  608. package/src/run/run.js +820 -0
  609. package/src/run/runner-pairing.js +243 -0
  610. package/src/run/values.js +122 -0
  611. package/src/runtime/compile.js +122 -0
  612. package/src/runtime/console-tag.js +64 -0
  613. package/src/runtime/frame-signals.js +126 -0
  614. package/src/runtime/iteration-push.js +19 -0
  615. package/src/runtime/keys.js +474 -0
  616. package/src/runtime/midi-input.js +170 -0
  617. package/src/runtime/person-waits.js +140 -0
  618. package/src/runtime/resource-timing.js +56 -0
  619. package/src/runtime/runtime.js +2150 -0
  620. package/src/runtime/sandbox-modules.js +163 -0
  621. package/src/runtime/spring.js +246 -0
  622. package/src/runtime/strict.js +215 -0
  623. package/src/runtime/transfer.js +75 -0
  624. package/src/runtime/tween.js +158 -0
  625. package/src/runtime/wasm-fuel.js +596 -0
  626. package/src/runtime/worker/00-prelude.js +88 -0
  627. package/src/runtime/worker/10-helpers.js +295 -0
  628. package/src/runtime/worker/20-io.js +645 -0
  629. package/src/runtime/worker/30-previews.js +210 -0
  630. package/src/runtime/worker/40-profile-lineage.js +278 -0
  631. package/src/runtime/worker/50-own-worker.js +233 -0
  632. package/src/runtime/worker/60-timers.js +172 -0
  633. package/src/runtime/worker/70-state-keyed.js +193 -0
  634. package/src/runtime/worker/80-each-compile-generators.js +619 -0
  635. package/src/runtime/worker/90-events-operators.js +655 -0
  636. package/src/runtime/worker/95-agents-batches.js +1820 -0
  637. package/src/runtime/worker/96-plot.js +47 -0
  638. package/src/runtime/worker/97-calc.js +28 -0
  639. package/src/runtime/worker/98-geometry.js +24 -0
  640. package/src/runtime/worker/99-graph.js +30 -0
  641. package/src/runtime/worker/99-shell.js +30 -0
  642. package/src/safety/config.js +57 -0
  643. package/src/safety/engine.js +324 -0
  644. package/src/scene/pixi-scene.js +806 -0
  645. package/src/scene/scene-assets.js +241 -0
  646. package/src/scene/scene-edit.js +319 -0
  647. package/src/secret/settings.js +41 -0
  648. package/src/security/multipart.js +257 -0
  649. package/src/security/redact.js +261 -0
  650. package/src/serial/broker.js +473 -0
  651. package/src/serial/config.js +185 -0
  652. package/src/serial/framers.js +389 -0
  653. package/src/serial/packets.js +64 -0
  654. package/src/shader/audio-texture.js +87 -0
  655. package/src/shader/channels.js +496 -0
  656. package/src/shader/common.js +90 -0
  657. package/src/shader/model.js +867 -0
  658. package/src/shader/passes.js +150 -0
  659. package/src/shader/shadertoy.js +198 -0
  660. package/src/shell/hub.js +287 -0
  661. package/src/sim/checkpoints.js +850 -0
  662. package/src/sim/compile.js +37 -0
  663. package/src/sim/fixed.js +377 -0
  664. package/src/sim/headless.js +205 -0
  665. package/src/sim/physics.js +399 -0
  666. package/src/smf-helper/vendor.js +2 -0
  667. package/src/sources/config.js +435 -0
  668. package/src/storage.js +153 -0
  669. package/src/table/table-geo.js +2344 -0
  670. package/src/table/table-lineage.js +808 -0
  671. package/src/table/table-quality.js +355 -0
  672. package/src/table/table-schema.js +392 -0
  673. package/src/table/table-sql.js +1650 -0
  674. package/src/table/table-stats.js +480 -0
  675. package/src/table/table.js +2102 -0
  676. package/src/tensor/tensor.js +1153 -0
  677. package/src/terminal/hub.js +715 -0
  678. package/src/terminal/screen.js +516 -0
  679. package/src/tests/capture.js +88 -0
  680. package/src/tests/compare.js +480 -0
  681. package/src/tests/dataset.js +170 -0
  682. package/src/tests/evaluate.js +286 -0
  683. package/src/tests/from-runs.js +99 -0
  684. package/src/tests/judge.js +134 -0
  685. package/src/tests/matchers.js +263 -0
  686. package/src/tests/matrix-spec.js +87 -0
  687. package/src/tests/matrix.js +397 -0
  688. package/src/tests/metrics.js +369 -0
  689. package/src/tests/no-value.js +42 -0
  690. package/src/tests/pane-check.js +45 -0
  691. package/src/tests/report.js +124 -0
  692. package/src/tests/reporters.js +140 -0
  693. package/src/tests/run.js +155 -0
  694. package/src/tilemap/tilemap.js +1122 -0
  695. package/src/units/units.js +3 -0
  696. package/src/util/bytes-text.js +21 -0
  697. package/src/util/num.js +10 -0
  698. package/src/util/regexp.js +2 -0
  699. package/src/util/text.js +38 -0
  700. package/src/verdict/engine.js +154 -0
  701. package/src/vm/guest-wsh.js +108 -0
  702. package/src/vm/hub.js +457 -0
  703. package/src/vm/image-files.js +4 -0
  704. package/src/vm/image.js +33 -0
  705. package/src/vm/image.lock.json +13 -0
  706. package/src/vm/link.js +266 -0
  707. package/src/vm/mount.js +212 -0
  708. package/src/vm/net.js +85 -0
  709. package/src/vm/pipe-ws.js +187 -0
  710. package/src/vm/v86-loader.js +11 -0
  711. package/src/webmcp/args.js +212 -0
  712. package/src/webmcp/hidden.js +218 -0
  713. package/src/webmcp/text.js +250 -0
  714. package/src/webmcp/tools/bookmark-tools.js +106 -0
  715. package/src/webmcp/tools/breakpoint-tools.js +48 -0
  716. package/src/webmcp/tools/canvases.js +208 -0
  717. package/src/webmcp/tools/context-tools.js +84 -0
  718. package/src/webmcp/tools/core.js +170 -0
  719. package/src/webmcp/tools/devices.js +41 -0
  720. package/src/webmcp/tools/edit.js +357 -0
  721. package/src/webmcp/tools/event-tools.js +145 -0
  722. package/src/webmcp/tools/image-tools.js +173 -0
  723. package/src/webmcp/tools/ink-tools.js +247 -0
  724. package/src/webmcp/tools/input-log-tools.js +163 -0
  725. package/src/webmcp/tools/live.js +166 -0
  726. package/src/webmcp/tools/machine-tools.js +74 -0
  727. package/src/webmcp/tools/media.js +161 -0
  728. package/src/webmcp/tools/midi-tools.js +32 -0
  729. package/src/webmcp/tools/preset-tools.js +184 -0
  730. package/src/webmcp/tools/quick-add-tools.js +95 -0
  731. package/src/webmcp/tools/reshape.js +152 -0
  732. package/src/webmcp/tools/run-tools.js +309 -0
  733. package/src/webmcp/tools/runs.js +101 -0
  734. package/src/webmcp/tools/scaffold-tools.js +161 -0
  735. package/src/webmcp/tools/serial-tools.js +36 -0
  736. package/src/webmcp/tools/shared.js +338 -0
  737. package/src/webmcp/tools/subgraphs.js +360 -0
  738. package/src/webmcp/tools/tests.js +170 -0
  739. package/src/webmcp/tools/traffic-tools.js +70 -0
  740. package/src/webmcp/tools/transport-tools.js +65 -0
  741. package/src/webmcp/tools/version-tools.js +126 -0
  742. package/src/webmcp/tools/versions.js +11 -0
  743. package/src/webmcp/tools/wire-tools.js +90 -0
  744. package/src/webmcp/tools/workspace-tools.js +93 -0
  745. package/src/webmcp/tools.js +1323 -0
  746. package/src/wsh/connect.js +347 -0
  747. package/src/wsh/demo-host.js +361 -0
  748. package/src/wsh/e2e.js +27 -0
  749. package/src/wsh/keys.js +154 -0
  750. package/src/wsh/known-hosts.js +39 -0
  751. package/src/wsh/private-key.js +95 -0
  752. package/src/wsh/reverse.js +34 -0
  753. package/src/wsh/settings.js +118 -0
  754. package/src/wsh/transfer.js +62 -0
  755. package/src/wsh/vendor.js +5 -0
  756. package/src/x402/challenge.js +171 -0
  757. package/src/x402/demo-server.js +127 -0
  758. package/src/x402/pay.js +125 -0
  759. package/src/x402/retry.js +95 -0
  760. package/src/x402/store.js +76 -0
package/src/mcp/hub.js ADDED
@@ -0,0 +1,1326 @@
1
+ // A canvas's MCP connections: one client (./client.js) per MCP server pane
2
+ // (src/panes/mcp.js), made when the pane first runs and made again when its
3
+ // URL or auth key changes. Kept on the canvas as `canvas.mcpHub` (hubOf),
4
+ // in memory only: a session id, a snapshot and the client go with the page.
5
+ //
6
+ // Requests go through the canvas's network policy exactly as a pane's own
7
+ // fetch does (`runtime.pageFetch`, credited to the server pane: a host the
8
+ // canvas hasn't allowed is refused and raises the network prompt, and allowing
9
+ // it reruns the pane); a secret() placeholder in the auth header is filled in
10
+ // there, for the key's own hosts. The in-page demo server (./demo-server.js)
11
+ // answers DEMO_URL without any request.
12
+ //
13
+ // Every tool call that isn't an agent pane's goes through the person's gate
14
+ // (src/gate/gate.js `beginCall`/`finish`), under the pane's gate server name
15
+ // (./settings.js gateServerOf), with an audit row and an approval when the
16
+ // policy says so: a call from another pane's code (`mcp.call` in the Worker,
17
+ // `fromPane`) and one from the pane's own form (`call`). An agent pane's
18
+ // calls (`rawCall`) are gated by its loop (src/agent/run.js), the same way.
19
+ // Resource reads and prompt gets aren't tool calls: the gate doesn't hold
20
+ // them. Nothing here is reachable from WebMCP (WHY_NOT.MCP, src/agents.js).
21
+ //
22
+ // Each connection has a query cache (./cache.js): `mcp.read(…, { maxAge })`
23
+ // and a read-only tool's `mcp.call(…, { maxAge })` answer from it while it is
24
+ // fresh, and a new answer shares the old one's unchanged parts.
25
+ //
26
+ // Live sources (#533), on the page only (`live`: never in a headless run):
27
+ // - a pane's `subscribe` URIs are cache subscribers: the first one sends
28
+ // resources/subscribe, the last one leaving resources/unsubscribe. The
29
+ // session's event stream (client.listen) is kept open while the server
30
+ // offers one, opened again after a drop (with every subscribed resource
31
+ // read again, since an update may have been missed) and after the server
32
+ // ends the session (subscribed again first). Each update is read and goes
33
+ // out on the pane's "resource" event; `…/list_changed` reruns the pane, so
34
+ // its value is the new list.
35
+ // - a pane's `watch` entries call a read-only tool again every `every`
36
+ // seconds, through the gate, and send each answer on its "watch" event.
37
+ // - the canvas transport (src/model/transport.js, kind "mcp") holds both:
38
+ // held, an update is remembered (not read) and a watch doesn't call; on
39
+ // play, each remembered update is read once and each due watch called once.
40
+ // - a pane that goes (deleted, deactivated, its settings changed, the canvas
41
+ // closed) takes its subscriptions, stream and timers with it.
42
+ //
43
+ // Tapes (#537): `startRecording` hears every request and answer of the
44
+ // pane's session; `stopRecording` makes the tape (./tape.js), redacted with
45
+ // the gate's rules for this server and the tape's own, and refuses a tape
46
+ // that still holds anything they match. A pane set to `replay` talks to a
47
+ // tape server instead of its URL. A connected pane that has a tape compares
48
+ // the server's contract with the tape's: its value's `drift`.
49
+ //
50
+ // Roots (#545, ./roots.js): a pane whose `roots` setting is on says so at
51
+ // initialize, and answers `roots/list` with the folders the person picked (or
52
+ // `mallory serve` watches) that they approved for this server, asked once
53
+ // through the gate (tool "roots"); a change to those sends
54
+ // `notifications/roots/list_changed`. A root gives the server no file access.
55
+ //
56
+ // Sampling (#545, ./sampling.js): a pane whose `sampling` setting is on says
57
+ // so at initialize, and the server's `sampling/createMessage` requests come
58
+ // to `#serverRequest`: each waits for the person's approval through the gate
59
+ // (tool "sampling", always asked), is answered by their own reply or the named
60
+ // agent pane's model, audited, kept in the pane's sampling log and sent on its
61
+ // "sampling" event. A tool call (or pane code's) that waits on one doesn't
62
+ // time out, and the calling pane's clock stops while the person decides.
63
+ //
64
+ // Elicitation (#545, ./elicitation.js): a pane whose `elicitation` setting is
65
+ // on says so at initialize, and the server's `elicitation/create` requests come
66
+ // to `#serverRequest` too: each is a form for the person through the gate (tool
67
+ // "elicitation", always asked), answered accept (with the form's answers,
68
+ // checked against the requested schema), decline or cancel, audited, kept in
69
+ // the pane's elicitation log and sent on its "elicitation" event. Only the
70
+ // person (or, headless, the approvals script) answers: never an agent.
71
+ //
72
+ // Resource templates (#545): a snapshot lists the server's
73
+ // `resources/templates/list`; `read(id, template, { params })` fills one in
74
+ // (./uri-template.js, RFC 6570) and reads the URI it makes.
75
+ //
76
+ // Protocol inspector (#534): every message on a connection's wire, its cache's
77
+ // events, its state changes, its event stream's drops and the waits before
78
+ // each reopen are reported to the canvas's inspector (src/protocol/inspector.js,
79
+ // which redacts them and keeps no body unless the person asked), and
80
+ // `inspect()` describes each connection now for it (registered as "mcp" below).
81
+ import { signal } from "@johnhenry/signalle";
82
+ import { createMcpClient, toolValue, resourceValue } from "./client.js";
83
+ import { demoServer, isDemoUrl } from "./demo-server.js";
84
+ import { createTabsServer, isTabsUrl } from "../ext/webmcp-tabs.js";
85
+ import { tabsAllowed } from "../ext/access.js";
86
+ import { payingTransport, rpcWhat } from "../x402/retry.js";
87
+ import { mcpSettings, mcpProblem, mcpHeaders, gateServerOf, liveSettings, watchKey, connectionKey, viaWsh, isDemoWsh, clientCapabilities } from "./settings.js";
88
+ import { createWshMcpClient } from "./wsh-client.js";
89
+ import { createQueryCache, stableKey } from "./cache.js";
90
+ import { createTapeServer, makeTape, redactTape, tapeRules, contractOf, contractDrift } from "./tape.js";
91
+ import { callSeams, stagesFor } from "../gate/seams.js";
92
+ import { beginCall, noteRefused } from "../gate/gate.js";
93
+ import { effectivePolicy } from "../gate/store.js";
94
+ import { checkArgs } from "../webmcp/args.js";
95
+ import { inspectorOf, registerProtocol } from "../protocol/inspector.js";
96
+ import { samplingSettings, samplingRequest, samplingArgs, samplingResult, findAgentPane, pageModels, SAMPLING_TOOL, SAMPLING_LOG } from "./sampling.js";
97
+ import { createProvider } from "../agent/providers.js";
98
+ import { McpError, TASK_DONE, cleanTask } from "./client.js";
99
+ import { refreshSecret } from "../network/secret-gate.js";
100
+ import { elicitationSettings, elicitationRequest, elicitationArgs, elicitationContent, elicitationResult, ELICITATION_TOOL, ELICITATION_LOG } from "./elicitation.js";
101
+ import { expandUriTemplate, isUriTemplate } from "./uri-template.js";
102
+ import { rootsSettings, rootsSourceOf, rootsArgs, approvedIds, visibleKey, asRoot, ROOTS_TOOL } from "./roots.js";
103
+
104
+ /** How long to wait before opening a dropped event stream again (ms): doubling from the first to the last. */
105
+ export const RECONNECT_MS = [1000, 30000];
106
+ const unref = (t) => (t?.unref?.(), t); // in Node: a cache's gc never keeps a run alive
107
+ const resKey = (uri) => `res:${uri}`;
108
+ const toolKey = (tool, args) => `tool:${tool}:${stableKey(args ?? {})}`;
109
+
110
+ /** The transport kind for the canvas transport: MCP server panes with live subscriptions or watches. */
111
+ export const MCP_SOURCE_KIND = {
112
+ sources: (canvas) => canvas.mcpHub?.liveIds() ?? [],
113
+ apply: (transport, canvas) => canvas.mcpHub?.resume(),
114
+ step: (transport, canvas, id) => canvas.mcpHub?.step(id) ?? false,
115
+ describe: (transport, canvas, id) => canvas.mcpHub?.describeLive(id) ?? {},
116
+ };
117
+
118
+ const EMPTY = [101, 204, 205, 304];
119
+
120
+ /** A network policy result (src/runtime/runtime.js hostFetch: `{ status, headers, body | stream }`) as a Response. */
121
+ export function asResponse(r) {
122
+ return new Response(EMPTY.includes(r.status) ? null : (r.stream ?? r.body ?? null), { status: r.status, statusText: r.statusText ?? "", headers: r.headers ?? [] });
123
+ }
124
+
125
+ /** The canvas's hub, made on first use. */
126
+ export function hubOf(canvas) {
127
+ canvas.mcpHub ??= new McpHub(canvas);
128
+ return canvas.mcpHub;
129
+ }
130
+
131
+ /** The MCP server pane named `name` that `canvas`'s panes can reach: on that canvas, else the ones around it. */
132
+ export function findServer(canvas, name) {
133
+ for (let c = canvas; c; c = c.parent) {
134
+ const hits = [...c.attached].filter((id) => c.panes.get(id)?.type === "mcp" && (c.panes.get(id).name || id) === name);
135
+ if (hits.length === 1) return { canvas: c, id: hits[0] };
136
+ if (hits.length > 1) throw new Error(`mcp: two MCP server panes are named "${name}": rename one`);
137
+ }
138
+ return undefined;
139
+ }
140
+
141
+ export class McpHub {
142
+ /**
143
+ * @param {object} canvas
144
+ * @param {{ live?: boolean, setTimer?: Function, clearTimer?: Function, now?: () => number }} [options] `live`: keep
145
+ * subscriptions and watches (default: the canvas's timers are live, i.e. on the page, not headless).
146
+ */
147
+ constructor(canvas, { live, setTimer = (fn, ms) => unref(setTimeout(fn, ms)), clearTimer = (t) => clearTimeout(t), now = () => Date.now() } = {}) {
148
+ this.canvas = canvas;
149
+ this.conns = new Map(); // pane id -> { key, client, status, snapshot?, error?, last?, cache, live, recording? }
150
+ this.ownLive = live;
151
+ this.setTimer = setTimer;
152
+ this.clearTimer = clearTimer;
153
+ this.now = now;
154
+ /** Bumped on every change, so pane bodies follow along. */
155
+ this.version = signal(0);
156
+ canvas.mcpHub ??= this; // the transport's kind finds it there
157
+ const transport = canvas.transport;
158
+ if (transport && !transport.kinds?.has("mcp")) transport.addKind("mcp", MCP_SOURCE_KIND);
159
+ }
160
+
161
+ /** Does this hub keep live sources (on the page; never headless)? */
162
+ get live() {
163
+ return this.ownLive ?? this.canvas.timerClock?.live !== false;
164
+ }
165
+
166
+ #bump() {
167
+ this.version.value = this.version.value + 1;
168
+ }
169
+
170
+ /** What a pane's connection is: `{ status: "idle" | "connecting" | "connected" | "error", snapshot?, error?, demo, last? }`. */
171
+ status(id) {
172
+ const conn = this.conns.get(id);
173
+ const pane = this.canvas.panes.get(id);
174
+ const s = mcpSettings(pane);
175
+ return {
176
+ status: conn?.status ?? "idle",
177
+ ...(conn?.snapshot ? { snapshot: conn.snapshot } : {}),
178
+ ...(conn?.error ? { error: conn.error } : {}),
179
+ ...(conn?.last ? { last: conn.last } : {}),
180
+ demo: (isDemoUrl(s.url) || isDemoWsh(s.url)) && !s.replay,
181
+ replay: s.replay,
182
+ ...(s.wsh && !s.replay ? { wsh: true } : {}),
183
+ ...(conn?.hostKeyChanged ? { hostKeyChanged: conn.hostKeyChanged } : {}),
184
+ ...(conn?.recording ? { recording: { since: conn.recording.since, exchanges: conn.recording.exchanges.length } } : {}),
185
+ ...(conn?.sampling?.length ? { sampling: conn.sampling } : {}),
186
+ ...(conn?.elicitation?.length ? { elicitation: conn.elicitation } : {}),
187
+ ...(conn?.roots ? { roots: conn.roots } : {}),
188
+ ...(conn?.tasks?.length ? { tasks: conn.tasks } : {}),
189
+ live: this.liveStatus(id),
190
+ };
191
+ }
192
+
193
+ /**
194
+ * What pane `id` keeps live: `{ stream, held, subscriptions: [{ uri, at?, error?, pending? }], watches: [{ tool, args,
195
+ * every, at?, error?, stale, why? }] }`. `stream`: "open", "connecting", "none" (the server offers none), or "off".
196
+ */
197
+ liveStatus(id) {
198
+ const live = this.conns.get(id)?.live;
199
+ const now = this.now();
200
+ if (!live) return { stream: "off", held: false, subscriptions: [], watches: [] };
201
+ return {
202
+ stream: live.stream,
203
+ held: this.#held(id),
204
+ subscriptions: [...live.subs.values()].map((x) => ({ uri: x.uri, ...(x.at ? { at: x.at } : {}), ...(x.error ? { error: x.error } : {}), ...(live.dirty.has(x.uri) ? { pending: true } : {}) })),
205
+ watches: [...live.watches.values()].map((w) => ({ tool: w.tool, args: w.args, every: w.every, ...(w.at ? { at: w.at } : {}), ...(w.error ? { error: w.error } : {}), ...(w.why ? { why: w.why } : {}), stale: Boolean(w.why || w.error || !w.at || now - w.at > w.every * 2000) })),
206
+ };
207
+ }
208
+
209
+ /** Every connected server on this canvas: [{ id, server (gate name), tools }] (the gate's matrix lists their tools). */
210
+ servers() {
211
+ return [...this.conns].filter(([id, c]) => c.snapshot && this.canvas.attached.has(id)).map(([id, c]) => ({ id, server: gateServerOf(this.canvas.panes.get(id), id), tools: c.snapshot.tools }));
212
+ }
213
+
214
+ #transport(id, url, pane) {
215
+ if (mcpSettings(pane).replay) return createTapeServer(pane.tape).fetch; // a tape: offline, no request
216
+ // An x402 challenge (an HTTP 402 with a price) is a payment decision through the tool gate (src/x402/pay.js): a
217
+ // tool call that meets one waits for the person (or is refused), and an approved one is sent again, once, with a
218
+ // simulated payment.
219
+ const paying = (fetch) => payingTransport(fetch, { decide: (challenge, init) => this.#pay(id, challenge, `mcp ${gateServerOf(this.canvas.panes.get(id), id)}: ${rpcWhat(init?.body)}`, init?.signal) });
220
+ if (isDemoUrl(url)) return paying(demoServer().fetch); // in the page: no request, no prompt
221
+ if (isTabsUrl(url)) return this.#tabsServer(id).fetch; // the browser extension's per-site tools and granted pages' WebMCP tools (src/ext/webmcp-tabs.js)
222
+ const runtime = this.canvas.runtime;
223
+ return paying(async (target, init) => {
224
+ if (typeof runtime.pageFetch !== "function") throw new Error("mcp: this run has no network to reach an MCP server with");
225
+ return asResponse(await runtime.pageFetch(target, { method: init.method, headers: init.headers, body: init.body }, { pane: id, signal: init.signal, stream: true }));
226
+ });
227
+ }
228
+
229
+ /**
230
+ * The tabs bridge for pane `id`: it reaches the page's link to the extension (a run with no page has none), only when the person let this pane use it
231
+ * (src/ext/access.js), and for an unattended run only the sites the signed grant names (src/autonomy/confine.js).
232
+ */
233
+ #tabsServer(id) {
234
+ const root = this.canvas.root ?? this.canvas;
235
+ return createTabsServer({
236
+ link: () => root.extensionLink ?? null,
237
+ allowed: () => tabsAllowed(root.id, this.canvas.panes.get(id)),
238
+ guard: (origin) => {
239
+ if (root.unattended !== true) return null;
240
+ // The page installs `hostGuard` on the root while a scheduler's run is attached (src/ui/autonomy-ui.js): no guard (a canvas test marked unattended, a run with no grant) allows no site.
241
+ let host = "";
242
+ try {
243
+ host = new URL(origin).hostname;
244
+ } catch {}
245
+ return host && typeof root.hostGuard === "function" && root.hostGuard(host) === true ? null : `the grant behind this unattended run does not name ${host || "that site"}`;
246
+ },
247
+ });
248
+ }
249
+
250
+ /** A payment challenge pane `id`'s server answered with: the person decides it (src/x402/pay.js). The calls waiting on it wait with it. */
251
+ async #pay(id, challenge, from, signal) {
252
+ const { decidePayment } = await import("../x402/pay.js");
253
+ const conn = this.conns.get(id);
254
+ const onWait = () => {
255
+ const releases = [...(conn?.waits ?? [])].map((fn) => fn?.()).filter((f) => typeof f === "function");
256
+ return () => releases.forEach((f) => f());
257
+ };
258
+ const release = conn?.client?.hold?.(); // the request waits for the person: the client's timeout doesn't run meanwhile
259
+ try {
260
+ return await decidePayment({ canvas: this.canvas, paneId: id, challenge, from, signal, onWait });
261
+ } finally {
262
+ release?.();
263
+ }
264
+ }
265
+
266
+ #conn(id) {
267
+ const pane = this.canvas.panes.get(id);
268
+ if (pane?.type !== "mcp") throw new Error(`mcp: there is no MCP server pane ${JSON.stringify(id)}`);
269
+ const problem = mcpProblem(pane);
270
+ if (problem) throw new Error(`mcp: ${problem}.`);
271
+ const { url } = mcpSettings(pane);
272
+ const key = connectionKey(pane);
273
+ let conn = this.conns.get(id);
274
+ if (!conn || conn.key !== key) {
275
+ if (conn) this.#close(conn);
276
+ conn = { key, status: "idle", live: null, recording: null, waits: new Set(), sampling: [], sampled: 0, elicitation: [], elicited: 0 };
277
+ conn.cache = createQueryCache({ setTimer: this.setTimer, clearTimer: this.clearTimer, now: this.now, onActive: (k) => this.#activeKey(id, conn, k), onIdle: (k) => this.#idleKey(id, conn, k), onEvent: (e) => this.#inspector()?.cache("mcp", this.canvas, id, e) });
278
+ const onTraffic = (t) => this.#inspector()?.traffic("mcp", this.canvas, id, t, { hide: [conn.client?.sessionId] });
279
+ const onExchange = (e) => {
280
+ const rec = conn.recording;
281
+ if (rec && rec.exchanges.length < 1000) rec.exchanges.push(e);
282
+ };
283
+ // Via wsh (#529): tools only, through a wsh session's MCP bridge (./wsh-client.js); else Streamable HTTP.
284
+ conn.client = viaWsh(pane)
285
+ ? createWshMcpClient({ canvas: this.canvas, id, onTraffic, onExchange })
286
+ : createMcpClient({ url, fetch: this.#transport(id, url, pane), headers: mcpHeaders(pane), capabilities: clientCapabilities(pane), onNotification: (m) => this.#notified(id, conn, m), onRequest: (method, params, ctx) => this.#serverRequest(id, conn, method, params, ctx), onTraffic, onExchange });
287
+ conn.client.onRestart = () => {
288
+ this.#inspector()?.retry("mcp", this.canvas, id, { reason: "the server ended the session: a new one began (subscriptions made again)", attempt: 1 });
289
+ this.#resubscribe(id, conn);
290
+ };
291
+ this.conns.set(id, conn);
292
+ }
293
+ return conn;
294
+ }
295
+
296
+ /** The canvas's protocol inspector (src/protocol/inspector.js). */
297
+ #inspector() {
298
+ try {
299
+ return inspectorOf(this.canvas);
300
+ } catch {
301
+ return null;
302
+ }
303
+ }
304
+
305
+ #state(id, state, lastError) {
306
+ this.#inspector()?.status("mcp", this.canvas, id, { state, ...(lastError !== undefined ? { lastError } : {}), hide: [this.conns.get(id)?.client?.sessionId] });
307
+ }
308
+
309
+ /**
310
+ * Each connection now, for the protocol inspector: [{ pane, state, session, server?, stream, retry, cache, ... }]. Never
311
+ * a session id, header, URL or key: `session` only says whether there is one.
312
+ */
313
+ inspect() {
314
+ const now = this.now();
315
+ return [...this.conns]
316
+ .filter(([id]) => this.canvas.attached?.has(id) && this.canvas.panes.get(id)?.type === "mcp")
317
+ .map(([id, c]) => {
318
+ const s = mcpSettings(this.canvas.panes.get(id));
319
+ const info = c.snapshot?.server;
320
+ const live = c.live;
321
+ const subscribed = new Set(c.cache?.active?.() ?? []);
322
+ return {
323
+ pane: id,
324
+ state: { idle: "idle", connecting: "connecting", connected: "ready", error: "error" }[c.status] ?? "idle",
325
+ session: Boolean(c.client?.sessionId),
326
+ transport: s.replay ? "tape" : isDemoUrl(s.url) ? "demo (in the page)" : isTabsUrl(s.url) ? "the browser extension (granted tabs)" : s.wsh ? (isDemoWsh(s.url) ? "wsh (the demo host in the page): tools only" : "wsh: tools only") : "Streamable HTTP",
327
+ ...(info ? { server: `${info.name}${info.version ? ` ${info.version}` : ""}`, protocolVersion: info.protocolVersion } : {}),
328
+ ...(c.error ? { lastError: c.error } : {}),
329
+ stream: live?.stream ?? "off",
330
+ ...(c.recording ? { recording: true } : {}),
331
+ retry: { requestTimeoutMs: 30000, sessionEnded: "a new session once, then the request again", streamReconnectMs: { base: RECONNECT_MS[0], max: RECONNECT_MS[1], factor: 2 }, ...(live?.failures ? { streamFailures: live.failures } : {}) },
332
+ cache: (c.cache?.entries?.() ?? []).map((e) => {
333
+ const kind = e.key.startsWith("res:") ? "resource" : e.key.startsWith("tool:") ? "tool" : "other";
334
+ const name = kind === "resource" ? e.key.slice(4) : kind === "tool" ? e.key.slice(5).split(":")[0] : e.key;
335
+ const keptLive = subscribed.has(e.key) && live?.stream === "open" && !live.dirty.has(name);
336
+ const stale = !e.hasValue || e.at === 0 || (!keptLive && !(Number(e.maxAge) > 0 && now - e.at <= Number(e.maxAge)));
337
+ return { key: e.key, tags: [kind, `${kind}:${name}`], at: e.at, stale, subscribers: e.subscribers, loading: e.loading, ...(keptLive ? { live: true } : {}), ...(e.error ? { error: e.error } : {}) };
338
+ }),
339
+ hide: [c.client?.sessionId],
340
+ };
341
+ });
342
+ }
343
+
344
+ /** A connection ends: its stream, timers and cache go, and its session is ended (the server forgets its subscriptions). */
345
+ #close(conn) {
346
+ conn.closed = true;
347
+ const id = [...this.conns].find(([, c]) => c === conn)?.[0];
348
+ if (id !== undefined && conn.status !== "idle") this.#state(id, "closed");
349
+ this.#stopLive(conn);
350
+ conn.cache?.clear();
351
+ conn.client.close();
352
+ }
353
+
354
+ /** Connect pane `id` (or refresh its lists): its snapshot `{ server, tools, resources, prompts }`. */
355
+ async connect(id, { signal } = {}) {
356
+ let conn;
357
+ try {
358
+ await this.#freshen(id); // an OAuth login's token near its expiry is replaced first (src/oauth/refresh.js); a plain key is left alone
359
+ conn = this.#conn(id);
360
+ } catch (error) {
361
+ this.conns.set(id, { key: null, client: { close() {} }, status: "error", error: error.message });
362
+ this.#state(id, "error", error.message);
363
+ this.#bump();
364
+ throw error;
365
+ }
366
+ conn.status = "connecting";
367
+ delete conn.error;
368
+ delete conn.hostKeyChanged;
369
+ this.#state(id, "connecting");
370
+ this.#bump();
371
+ try {
372
+ let snapshot = await this.#snapshotWithLogin(id, conn, signal);
373
+ if (this.conns.get(id) !== conn) throw Object.assign(new Error("superseded by a newer connection"), { name: "AbortError" });
374
+ const pane = this.canvas.panes.get(id);
375
+ // A tape to compare with: what changed in the server's contract since it was recorded (not when replaying it).
376
+ if (pane?.tape?.contract && !mcpSettings(pane).replay) {
377
+ const { breaking, compatible } = contractDrift(pane.tape.contract, contractOf(snapshot));
378
+ snapshot = { ...snapshot, drift: { breaking, compatible, since: String(pane.tape.recordedAt ?? "") } };
379
+ }
380
+ Object.assign(conn, { status: "connected", snapshot });
381
+ if (rootsSettings(pane).on) {
382
+ conn.rootsKey = visibleKey(rootsSourceOf(this.canvas), this.canvas.root.id, gateServerOf(pane, id)); // what its first roots/list would get
383
+ this.#watchRoots(); // a later change to that tells this server (list_changed)
384
+ }
385
+ this.#state(id, "ready");
386
+ this.syncLive(id);
387
+ return snapshot;
388
+ } catch (error) {
389
+ if (this.conns.get(id) === conn && error?.name !== "AbortError") {
390
+ Object.assign(conn, { status: "error", error: String(error?.message ?? error), ...(error?.hostKeyChanged ? { hostKeyChanged: error.hostKeyChanged } : {}) });
391
+ this.#state(id, "error", conn.error);
392
+ } else if (this.conns.get(id) === conn) {
393
+ conn.status = conn.snapshot ? "connected" : "idle";
394
+ this.#state(id, conn.snapshot ? "ready" : "idle");
395
+ }
396
+ throw error;
397
+ } finally {
398
+ this.#bump();
399
+ }
400
+ }
401
+
402
+ /** The name of the API key a pane logs in with, or "". */
403
+ #authKeyOf(id) {
404
+ const pane = this.canvas.panes.get(id);
405
+ return pane ? String(mcpSettings(pane).authKey ?? "") : "";
406
+ }
407
+
408
+ /**
409
+ * Before a connection or a call: when the pane's key is an OAuth login whose token is about to expire, replace it. Only
410
+ * "replaced or not" comes back, never a token. A refresh that failed is not an error here (the token may still be good): a
411
+ * 401 that follows reports it.
412
+ */
413
+ async #freshen(id) {
414
+ const name = this.#authKeyOf(id);
415
+ if (!name) return false;
416
+ try {
417
+ return await refreshSecret(name);
418
+ } catch {
419
+ return false;
420
+ }
421
+ }
422
+
423
+ /** `snapshot()`, and on a 401 for an OAuth login: refresh once and try again; if the login can't be refreshed, say so. */
424
+ async #snapshotWithLogin(id, conn, signal) {
425
+ try {
426
+ return await conn.client.snapshot({ signal });
427
+ } catch (error) {
428
+ const name = this.#authKeyOf(id);
429
+ if (error?.data?.status !== 401 || !name) throw error;
430
+ let fresh = false;
431
+ try {
432
+ fresh = await refreshSecret(name, { force: true });
433
+ } catch (refused) {
434
+ throw new Error(`${error.message}; the login for ${name} couldn't be renewed (${String(refused?.message ?? refused).slice(0, 200)}). Log in again in ⚙ settings → Connected apps.`);
435
+ }
436
+ if (!fresh) throw error;
437
+ return await conn.client.snapshot({ signal });
438
+ }
439
+ }
440
+
441
+ /** A connection that has its snapshot (connecting first when it hasn't). */
442
+ async #ready(id, signal) {
443
+ const conn = this.conns.get(id);
444
+ if (conn?.snapshot && conn.key === connectionKey(this.canvas.panes.get(id))) {
445
+ await this.#freshen(id); // a long-lived connection's token is renewed before the next call, too
446
+ return conn;
447
+ }
448
+ await this.connect(id, { signal });
449
+ return this.conns.get(id);
450
+ }
451
+
452
+ /** Pane `id`'s snapshot, connecting first when it has none (an agent pane's tools, src/agent/run.js mcpTools). */
453
+ async snapshot(id, { signal } = {}) {
454
+ return (await this.#ready(id, signal)).snapshot;
455
+ }
456
+
457
+ /** The tool `tool` of pane `id`, or an Error saying why not (audited as refused). */
458
+ async #tool(id, tool, args, signal) {
459
+ const conn = await this.#ready(id, signal);
460
+ const server = gateServerOf(this.canvas.panes.get(id), id);
461
+ const found = conn.snapshot.tools.find((t) => t.name === tool);
462
+ const refuse = (reason, message) => {
463
+ noteRefused({ canvasId: this.canvas.root.id, server, tool, args, reason });
464
+ return new Error(message);
465
+ };
466
+ if (!found) throw refuse("no such tool", `mcp: ${server} has no tool "${tool}" (it has ${conn.snapshot.tools.map((t) => t.name).join(", ") || "none"})`);
467
+ if (args === null || typeof args !== "object" || Array.isArray(args)) throw refuse("invalid arguments: not an object", `mcp: ${server}.${tool}: the arguments must be an object`);
468
+ const problems = checkArgs(found.inputSchema, args);
469
+ if (problems.length) throw refuse(`invalid arguments: ${problems.join("; ")}`, `mcp: ${server}.${tool}: ${problems.join("; ")}`);
470
+ return { conn, server, found };
471
+ }
472
+
473
+ #stage = stagesFor();
474
+
475
+ /** The person's hook rules and the safety stage for pane `id`'s calls (src/gate/seams.js): they can only refuse, hold or redact. No verdict risk: none applies to this pane. */
476
+ #seams(id) {
477
+ return callSeams(this.canvas, { paneId: id, safety: this.#stage(id) });
478
+ }
479
+
480
+ /**
481
+ * Call a tool through the gate: its value (./client.js toolValue), or a thrown Error with the gate's
482
+ * reason or the tool's. `origin` is { canvas, paneId }, the pane that made the call (its card shows there).
483
+ * `onWait`: the call is held for the person (an approval); returns a function for when it ends.
484
+ */
485
+ async call(id, tool, args = {}, { origin, signal, onWait, maxAge = 0, unattended = false, raw = false, via, task = false } = {}) {
486
+ const { conn, server, found } = await this.#tool(id, tool, args, signal);
487
+ // `unattended` (a watch's call): never held for the person; a tool that needs approval is refused.
488
+ // `via`: who asked, in words, when it isn't the pane's own code (an MCP app's page): the audit row says so.
489
+ const ticket = await beginCall({ canvasId: this.canvas.root.id, server, tool, destructive: found.destructive, args, signal, interactive: this.canvas.root.interactive === true && !unattended, script: this.canvas.root.approvalScript ?? null, origin: origin ?? { canvas: this.canvas, paneId: id }, onWait, via, ...this.#seams(id) });
490
+ if (raw) return await this.#rawResult(id, conn, found, tool, ticket, signal, onWait, task);
491
+ if (!ticket.ok) throw Object.assign(new Error(unattended && ticket.outcome === "auto-deny" && !this.canvas.root.approvalScript && /approval/.test(ticket.reason) ? `${server}.${tool} needs your approval, and a watch doesn't ask each time: allow it in the gate's policy to watch it` : ticket.reason), { gate: ticket.outcome });
492
+ let value;
493
+ // A sampling request the server sends while this call runs waits for the person: this call's caller waits with it.
494
+ if (onWait) conn.waits?.add(onWait);
495
+ try {
496
+ // A read-only tool's answer is cached by its arguments: a call within maxAge ms of the last one gets that answer
497
+ // (it is still a call the gate allowed and audits). Any other tool always reaches the server.
498
+ // A task (a tool that must be, or was asked to be, one) is never cached: each call is its own.
499
+ const asTask = this.#asTask(found, task);
500
+ const load = async () => toolValue(await this.#invoke(id, conn, found, tool, ticket.args, { signal, task }));
501
+ value = found.readOnly && !asTask ? (await conn.cache.fetch(toolKey(tool, ticket.args), load, { maxAge: Number(maxAge) > 0 ? Number(maxAge) : 0 })).value : await load();
502
+ } catch (error) {
503
+ conn.waits?.delete(onWait);
504
+ if (signal?.aborted) {
505
+ await ticket.finish({ error: "stopped", stopped: true });
506
+ throw error;
507
+ }
508
+ throw new Error((await ticket.finish({ error: String(error?.message ?? error) })).error);
509
+ }
510
+ conn.waits?.delete(onWait);
511
+ return (await ticket.finish({ value })).value; // redacted as the policy says
512
+ }
513
+
514
+ /**
515
+ * `call(…, { raw: true })`: the tool's CallToolResult as the server sent it (`{ content, structuredContent?, isError? }`,
516
+ * what an MCP app's page expects), never cached. A result marked isError is audited as an error and still returned.
517
+ */
518
+ async #rawResult(id, conn, found, tool, ticket, signal, onWait, task) {
519
+ if (!ticket.ok) throw Object.assign(new Error(ticket.reason), { gate: ticket.outcome });
520
+ if (onWait) conn.waits?.add(onWait);
521
+ let result;
522
+ try {
523
+ result = await this.#invoke(id, conn, found, tool, ticket.args, { signal, task });
524
+ } catch (error) {
525
+ if (signal?.aborted) {
526
+ await ticket.finish({ error: "stopped", stopped: true });
527
+ throw error;
528
+ }
529
+ throw new Error((await ticket.finish({ error: String(error?.message ?? error) })).error);
530
+ } finally {
531
+ conn.waits?.delete(onWait);
532
+ }
533
+ const clean = { content: Array.isArray(result?.content) ? result.content : [], ...(result?.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}), ...(result?.isError ? { isError: true } : {}) };
534
+ if (clean.isError) {
535
+ const text = clean.content.filter((c) => c?.type === "text").map((c) => String(c.text ?? "")).join("\n") || "the tool reported an error";
536
+ await ticket.finish({ error: text.slice(0, 2000) });
537
+ return clean;
538
+ }
539
+ return (await ticket.finish({ value: clean })).value; // redacted as the policy says
540
+ }
541
+
542
+ // ── Tasks (2025-11-25): long-running tool calls ───────────────────────────────────────────────────────────────────
543
+ // A tool whose `taskSupport` is "required" is called as a task, and one that is "optional" when the caller asks (`task: true`).
544
+ // The call is one call to the gate as ever (approval, audit, redaction); the polling and the result read after it are the
545
+ // protocol's own plumbing. The task list a panel shows is `status(id).tasks`; each change goes out on the pane's "task" event.
546
+
547
+ #asTask(found, task) {
548
+ return found?.taskSupport === "required" || (found?.taskSupport === "optional" && task === true);
549
+ }
550
+
551
+ /** The tool's CallToolResult: plainly, or as a task run to its end. */
552
+ async #invoke(id, conn, found, tool, args, { signal, task }) {
553
+ if (!this.#asTask(found, task)) return await conn.client.callTool(tool, args, { signal });
554
+ return await this.#runTask(id, conn, tool, args, signal);
555
+ }
556
+
557
+ #waitFor(ms, signal) {
558
+ return new Promise((resolve, reject) => {
559
+ if (signal?.aborted) return reject(signal.reason ?? Object.assign(new Error("stopped"), { name: "AbortError" }));
560
+ const timer = this.setTimer(() => {
561
+ signal?.removeEventListener("abort", onAbort);
562
+ resolve();
563
+ }, ms);
564
+ const onAbort = () => {
565
+ this.clearTimer(timer);
566
+ reject(signal.reason ?? Object.assign(new Error("stopped"), { name: "AbortError" }));
567
+ };
568
+ signal?.addEventListener("abort", onAbort, { once: true });
569
+ });
570
+ }
571
+
572
+ /** Keep the task in the connection's list (newest last, 50 at most) and say so on the pane's "task" event when it changed. */
573
+ #trackTask(id, conn, task, tool) {
574
+ conn.tasks ??= [];
575
+ const at = conn.tasks.findIndex((t) => t.taskId === task.taskId);
576
+ const before = at === -1 ? null : conn.tasks[at];
577
+ const next = { ...(before ?? {}), ...task, tool: tool ?? before?.tool ?? "" };
578
+ if (at === -1) conn.tasks = [...conn.tasks, next].slice(-50);
579
+ else conn.tasks = conn.tasks.map((t, i) => (i === at ? next : t));
580
+ if (!before || before.status !== next.status || before.statusMessage !== next.statusMessage) {
581
+ this.#emit(id, "task", { taskId: next.taskId, tool: next.tool, status: next.status, ...(next.statusMessage ? { statusMessage: next.statusMessage } : {}), at: this.now() });
582
+ this.#bump();
583
+ }
584
+ return next;
585
+ }
586
+
587
+ async #runTask(id, conn, tool, args, signal) {
588
+ const created = await conn.client.callToolTask(tool, args, { signal });
589
+ let task = this.#trackTask(id, conn, created, tool);
590
+ // A call that is stopped stops its task on the server too (best effort: a server without cancel just lets it run out).
591
+ const onStop = () => void conn.client.cancelTask(created.taskId).then((t) => this.#trackTask(id, conn, t, tool), () => {});
592
+ signal?.addEventListener("abort", onStop, { once: true });
593
+ try {
594
+ while (!TASK_DONE(task.status) && task.status !== "input_required") {
595
+ await this.#waitFor(task.pollInterval ?? 1000, signal);
596
+ task = this.#trackTask(id, conn, await conn.client.getTask(created.taskId, { signal }), tool);
597
+ }
598
+ if (task.status === "cancelled") throw new Error(`the task was cancelled${task.statusMessage ? `: ${task.statusMessage}` : ""}`);
599
+ // input_required: tasks/result waits for the server's own question (an elicitation the pane answers) and then the answer.
600
+ const result = await conn.client.getTaskResult(created.taskId, { signal });
601
+ if (task.status === "input_required") task = this.#trackTask(id, conn, await conn.client.getTask(created.taskId), tool);
602
+ return result;
603
+ } catch (error) {
604
+ if (!signal?.aborted && !TASK_DONE(task.status)) {
605
+ try {
606
+ this.#trackTask(id, conn, { ...task, status: "failed", statusMessage: String(error?.message ?? error).slice(0, 200) }, tool);
607
+ } catch {}
608
+ }
609
+ throw error;
610
+ } finally {
611
+ signal?.removeEventListener("abort", onStop);
612
+ }
613
+ }
614
+
615
+ /** Ask the server to stop task `taskId` of pane `id` (the Tasks panel's button). Resolves the task as the server now has it. */
616
+ async cancelTask(id, taskId, { signal } = {}) {
617
+ const conn = await this.#ready(id, signal);
618
+ if (!conn.snapshot.server.tasks?.cancel) throw new Error("mcp: this server doesn't let a client cancel tasks");
619
+ return this.#trackTask(id, conn, await conn.client.cancelTask(String(taskId), { signal }), undefined);
620
+ }
621
+
622
+ /** Read the server's own task list (tasks/list) into the pane's list; resolves it. */
623
+ async syncTasks(id, { signal } = {}) {
624
+ const conn = await this.#ready(id, signal);
625
+ if (!conn.snapshot.server.tasks?.list) return conn.tasks ?? [];
626
+ for (const t of await conn.client.listTasks({ signal })) this.#trackTask(id, conn, t, undefined);
627
+ return conn.tasks ?? [];
628
+ }
629
+
630
+ /** Read a resource as the server sent it (a ReadResourceResult: `{ contents }`), never cached: an MCP app's page and its own reads. */
631
+ async readResult(id, uri, { signal } = {}) {
632
+ if (typeof uri !== "string" || !uri) throw new Error("mcp: a resource's URI");
633
+ const conn = await this.#ready(id, signal);
634
+ const result = await conn.client.readResource(uri, { signal });
635
+ return { contents: Array.isArray(result?.contents) ? result.contents : [] };
636
+ }
637
+
638
+ /** A request from the server (other than ping): sampling or elicitation, when the pane offers it; anything else is refused. */
639
+ async #serverRequest(id, conn, method, params, { signal } = {}) {
640
+ const pane = this.canvas.panes.get(id);
641
+ if (method === "sampling/createMessage" && samplingSettings(pane).on) return await this.#sample(id, conn, params, signal);
642
+ if (method === "elicitation/create" && elicitationSettings(pane).on) return await this.#elicit(id, conn, params, signal);
643
+ if (method === "roots/list" && rootsSettings(pane).on) return await this.#roots(id, conn, signal);
644
+ throw new McpError(`the client doesn't support ${method}`, { code: -32601 });
645
+ }
646
+
647
+ /**
648
+ * Answer an elicitation request: the person answers the server's form through the gate (always asked): accept with
649
+ * their answers (checked against the requested schema), decline, or cancel. Logged in the pane
650
+ * (`status(id).elicitation`), audited, and sent on its "elicitation" event. A refusal by the gate's policy, or a run
651
+ * nobody watches with no script for it, is an error answer (code -1); the person's no is a decline, and dismissing it
652
+ * (or no answer in time, or the run stopping) a cancel.
653
+ */
654
+ async #elicit(id, conn, params, signal) {
655
+ const pane = this.canvas.panes.get(id);
656
+ const server = gateServerOf(pane, id);
657
+ let request;
658
+ try {
659
+ request = elicitationRequest(params);
660
+ } catch (error) {
661
+ noteRefused({ canvasId: this.canvas.root.id, server, tool: ELICITATION_TOOL, args: params, reason: error.message });
662
+ throw new McpError(error.message, { code: -32602 });
663
+ }
664
+ const entry = { n: ++conn.elicited, at: this.now(), request, status: "waiting" };
665
+ conn.elicitation = [...conn.elicitation, entry].slice(-ELICITATION_LOG);
666
+ const log = (patch) => {
667
+ Object.assign(entry, patch);
668
+ conn.elicitation = [...conn.elicitation]; // a new list, so a body redraws
669
+ this.#bump();
670
+ };
671
+ this.#bump();
672
+ this.#inspector()?.event("mcp", this.canvas, id, "elicitation", { status: "asked", fields: Object.keys(request.requestedSchema.properties).length });
673
+ const onWait = () => {
674
+ const releases = [...(conn.waits ?? [])].map((fn) => fn?.()).filter((f) => typeof f === "function");
675
+ return () => releases.forEach((f) => f());
676
+ };
677
+ const root = this.canvas.root;
678
+ const ticket = await beginCall({ canvasId: root.id, server, tool: ELICITATION_TOOL, args: elicitationArgs(request), needsAnswer: true, everyTime: true, signal, interactive: root.interactive === true, script: root.approvalScript ?? null, origin: { canvas: this.canvas, paneId: id }, onWait });
679
+ const done = (status, result, extra = {}) => {
680
+ log({ status, ...extra });
681
+ this.#inspector()?.event("mcp", this.canvas, id, "elicitation", { status });
682
+ this.#emit(id, "elicitation", { request, ...(result ? { action: result.action, ...(result.content ? { content: result.content } : {}) } : {}), ...(extra.error ? { error: extra.error } : {}), at: this.now() });
683
+ return result;
684
+ };
685
+ if (!ticket.ok) {
686
+ if (ticket.outcome === "denied") return done("declined", elicitationResult("decline"));
687
+ if (ticket.outcome === "cancelled" || ticket.outcome === "timeout") return done("cancelled", elicitationResult("cancel"));
688
+ done("refused", null, { error: ticket.reason });
689
+ throw new McpError(`the person using mallory didn't answer the elicitation request: ${ticket.reason}`, { code: -1 });
690
+ }
691
+ // The answers: the person's form (or the script's amend) as `content`; a plain scripted approve keeps the defaults.
692
+ const given = ticket.args && typeof ticket.args === "object" && "content" in ticket.args ? ticket.args.content : undefined;
693
+ const { content, problems } = elicitationContent(request.requestedSchema, given ?? elicitationArgs(request).content);
694
+ if (problems.length) {
695
+ const out = await ticket.finish({ error: `the answer doesn't fit the requested schema: ${problems.join("; ")}` });
696
+ done("error", null, { error: out.error });
697
+ throw new McpError(out.error, { code: -32602 });
698
+ }
699
+ const out = await ticket.finish({ value: { action: "accept", content } }); // redacted as the policy says, before it leaves for the server
700
+ const sent = out.value?.content && typeof out.value.content === "object" ? out.value.content : content;
701
+ return done("accepted", elicitationResult("accept", sent), { content: sent });
702
+ }
703
+
704
+ /**
705
+ * Answer a roots/list request (#545): the folders this canvas offers that the person approved for this server. Never
706
+ * asked before and there are folders: the gate asks the person (once; the answer is kept with the folders) which of
707
+ * them the server may see. Nothing picked, or the person's no: an empty list. A root gives the server no file access.
708
+ */
709
+ async #roots(id, conn, signal) {
710
+ const pane = this.canvas.panes.get(id);
711
+ const server = gateServerOf(pane, id);
712
+ const root = this.canvas.root;
713
+ const source = rootsSourceOf(this.canvas);
714
+ const all = source?.list(root.id) ?? [];
715
+ let ids = source?.grant(root.id, server);
716
+ let asked = false;
717
+ if (ids === undefined && all.length) {
718
+ asked = true;
719
+ this.#inspector()?.event("mcp", this.canvas, id, "roots", { status: "asked", folders: all.length });
720
+ const onWait = () => {
721
+ const releases = [...(conn.waits ?? [])].map((fn) => fn?.()).filter((f) => typeof f === "function");
722
+ return () => releases.forEach((f) => f());
723
+ };
724
+ conn.answeringRoots = true; // its own decision below isn't a change to tell it about
725
+ try {
726
+ const ticket = await beginCall({ canvasId: root.id, server, tool: ROOTS_TOOL, args: rootsArgs(all), needsAnswer: true, everyTime: true, signal, interactive: root.interactive === true, script: root.approvalScript ?? null, origin: { canvas: this.canvas, paneId: id }, onWait });
727
+ if (ticket.ok) {
728
+ ids = approvedIds(all, ticket.args);
729
+ source.setGrant(root.id, server, ids);
730
+ await ticket.finish({ value: { roots: all.filter((r) => ids.includes(r.id)).map(asRoot) } });
731
+ } else if (ticket.outcome === "denied" && !/policy|script/.test(ticket.reason ?? "")) {
732
+ ids = []; // the person said no: kept, so it isn't asked again (the pane's Roots section changes it)
733
+ source.setGrant(root.id, server, ids);
734
+ } else ids = []; // nobody answered, the run stopped, or the policy or a script refused it: none now, asked again next time
735
+ } finally {
736
+ conn.answeringRoots = false;
737
+ }
738
+ }
739
+ const given = new Set(ids ?? []);
740
+ const roots = all.filter((r) => given.has(r.id)).map(asRoot);
741
+ conn.rootsKey = visibleKey(source, root.id, server);
742
+ conn.roots = { at: this.now(), sent: roots, ...(asked ? { asked: true } : {}) };
743
+ this.#watchRoots();
744
+ this.#bump();
745
+ this.#inspector()?.event("mcp", this.canvas, id, "roots", { status: "answered", roots: roots.length });
746
+ return { roots };
747
+ }
748
+
749
+ /** Listen to the roots source once: a change to what a connected server would see sends it `notifications/roots/list_changed`. */
750
+ #watchRoots() {
751
+ if (this.#rootsOff) return;
752
+ const source = rootsSourceOf(this.canvas);
753
+ if (!source?.subscribe) return;
754
+ this.#rootsOff = source.subscribe(() => this.rootsChanged());
755
+ }
756
+
757
+ #rootsOff = null;
758
+
759
+ /** The folders or a server's grant changed: each connected server with roots on whose view changed is told so. Returns how many were. */
760
+ rootsChanged() {
761
+ const source = rootsSourceOf(this.canvas);
762
+ const root = this.canvas.root;
763
+ let n = 0;
764
+ for (const [id, conn] of this.conns) {
765
+ const pane = this.canvas.panes.get(id);
766
+ if (conn.closed || conn.answeringRoots || conn.status !== "connected" || !rootsSettings(pane).on || !this.canvas.attached.has(id)) continue;
767
+ const key = visibleKey(source, root.id, gateServerOf(pane, id));
768
+ if (key === (conn.rootsKey ?? "")) continue;
769
+ conn.rootsKey = key;
770
+ n++;
771
+ this.#inspector()?.event("mcp", this.canvas, id, "roots", { status: "list_changed" });
772
+ conn.client.notify?.("notifications/roots/list_changed").catch?.(() => {});
773
+ }
774
+ return n;
775
+ }
776
+
777
+ /** The elicitation requests pane `id`'s server sent this connection, newest last: `[{ n, at, request, status, content?, error? }]`. */
778
+ elicitationLog(id) {
779
+ return this.conns.get(id)?.elicitation ?? [];
780
+ }
781
+
782
+ /**
783
+ * Answer a sampling request: the person approves it through the gate (always asked), then their reply or the named
784
+ * agent pane's model answers. Logged in the pane (`status(id).sampling`), audited, and sent on its "sampling" event.
785
+ */
786
+ async #sample(id, conn, params, signal) {
787
+ const pane = this.canvas.panes.get(id);
788
+ const { agent } = samplingSettings(pane);
789
+ const server = gateServerOf(pane, id);
790
+ const request = samplingRequest(params);
791
+ const answeredBy = agent ? `agent pane ${agent}` : "you (your reply)";
792
+ const entry = { n: ++conn.sampled, at: this.now(), request, by: answeredBy, status: "waiting" };
793
+ conn.sampling = [...conn.sampling, entry].slice(-SAMPLING_LOG);
794
+ const log = (patch) => {
795
+ Object.assign(entry, patch);
796
+ conn.sampling = [...conn.sampling]; // a new list, so a body redraws
797
+ this.#bump();
798
+ };
799
+ this.#bump();
800
+ this.#inspector()?.event("mcp", this.canvas, id, "sampling", { status: "asked", messages: request.messages.length });
801
+ // The calls waiting on this answer (a form's, pane code's) wait for the person with it: their clocks stop.
802
+ const onWait = () => {
803
+ const releases = [...(conn.waits ?? [])].map((fn) => fn?.()).filter((f) => typeof f === "function");
804
+ return () => releases.forEach((f) => f());
805
+ };
806
+ const root = this.canvas.root;
807
+ const ticket = await beginCall({ canvasId: root.id, server, tool: SAMPLING_TOOL, args: samplingArgs(request, answeredBy), needsAnswer: true, everyTime: true, signal, interactive: root.interactive === true, script: root.approvalScript ?? null, origin: { canvas: this.canvas, paneId: id }, onWait });
808
+ if (!ticket.ok) {
809
+ log({ status: "refused", error: ticket.reason });
810
+ this.#inspector()?.event("mcp", this.canvas, id, "sampling", { status: "refused" });
811
+ this.#emit(id, "sampling", { request, error: ticket.reason, at: this.now() });
812
+ throw new McpError(`the person using mallory didn't approve the sampling request: ${ticket.reason}`, { code: -1 });
813
+ }
814
+ const reply = typeof ticket.args?.reply === "string" ? ticket.args.reply.trim() : "";
815
+ let text;
816
+ let model;
817
+ try {
818
+ if (reply) [text, model] = [reply, "person"];
819
+ else if (agent) ({ text, model } = await this.#modelAnswer(id, conn, agent, request, signal));
820
+ else throw new Error("approved without a reply: with no agent pane under sampling, the answer is the reply you write");
821
+ } catch (error) {
822
+ const out = await ticket.finish({ error: String(error?.message ?? error) });
823
+ log({ status: "error", error: out.error });
824
+ this.#inspector()?.event("mcp", this.canvas, id, "sampling", { status: "error" });
825
+ this.#emit(id, "sampling", { request, error: out.error, at: this.now() });
826
+ throw new McpError(`sampling failed: ${out.error}`, { code: -32603 });
827
+ }
828
+ const out = await ticket.finish({ value: { model, text } }); // redacted as the policy says, before it leaves for the server
829
+ const answer = typeof out.value?.text === "string" ? out.value.text : String(text);
830
+ log({ status: "answered", answer, model });
831
+ this.#inspector()?.event("mcp", this.canvas, id, "sampling", { status: "answered", model });
832
+ this.#emit(id, "sampling", { request, text: answer, model, at: this.now() });
833
+ return samplingResult(answer, model);
834
+ }
835
+
836
+ /** The named agent pane's model answers a sampling request (its provider, model, key's name or recording), on the page. */
837
+ async #modelAnswer(id, conn, agentName, request, signal) {
838
+ const found = findAgentPane(this.canvas, agentName);
839
+ if (!found) throw new Error(`there is no agent pane named "${agentName}" on this canvas to answer it`);
840
+ const ap = found.canvas.panes.get(found.id);
841
+ const kind = ap.provider ?? "chrome";
842
+ const history = request.messages.map((m) => ({ role: m.role, text: m.text }));
843
+ const system = request.systemPrompt ?? "";
844
+ if (kind === "chrome") {
845
+ if (typeof pageModels.chrome !== "function") throw new Error("Chrome's on-device model answers sampling only on the page, through mallory's on-device AI permissions");
846
+ return { text: String(await pageModels.chrome({ canvas: this.canvas, paneId: id, system, history, signal })), model: "on-device" };
847
+ }
848
+ const runtime = this.canvas.runtime;
849
+ // A recording replays its replies in turn, one per sampling request this connection answered with it.
850
+ const start = kind === "recorded" ? (conn.recordedNext ??= new Map()).get(found.id) ?? 0 : 0;
851
+ const provider = createProvider(kind, {
852
+ model: ap.model,
853
+ baseUrl: ap.baseUrl,
854
+ keyName: ap.keyName,
855
+ recorded: ap.recorded,
856
+ start,
857
+ // The model's request is the MCP server pane's own: the network policy, a secret() placeholder for its key.
858
+ transport: {
859
+ http: async (req) => {
860
+ if (typeof runtime.pageFetch !== "function") throw new Error("this run has no network to reach a model with");
861
+ const res = asResponse(await runtime.pageFetch(req.url, { method: req.method, headers: req.headers, body: req.body }, { pane: id, signal }));
862
+ return { status: res.status, text: await res.text() };
863
+ },
864
+ chrome: () => Promise.reject(new Error("unreachable")),
865
+ },
866
+ });
867
+ const turn = await provider.turn({ system, history, tools: [] });
868
+ if (kind === "recorded") conn.recordedNext.set(found.id, start + 1);
869
+ return { text: String(turn.text ?? ""), model: turn.model || provider.model || kind };
870
+ }
871
+
872
+ /** The sampling requests pane `id`'s server sent this connection, newest last: `[{ n, at, request, by, status, answer?, model?, error? }]`. */
873
+ samplingLog(id) {
874
+ return this.conns.get(id)?.sampling ?? [];
875
+ }
876
+
877
+ /** Call a tool without the gate: only for a caller that gates it itself (an agent pane's loop, src/agent/run.js). */
878
+ async rawCall(id, tool, args = {}, { signal } = {}) {
879
+ const conn = await this.#ready(id, signal);
880
+ return toolValue(await conn.client.callTool(tool, args, { signal }));
881
+ }
882
+
883
+ /**
884
+ * Read a resource: one text resource's text (JSON parsed), else its contents. With `params`, `uri` is a URI template
885
+ * (one of the server's resource templates, #545) filled in with them first.
886
+ */
887
+ async read(id, uri, { signal, maxAge = 0, params } = {}) {
888
+ if (typeof uri !== "string" || !uri) throw new Error("mcp.read(server, uri): a resource's URI");
889
+ if (params !== undefined) uri = expandUriTemplate(uri, params);
890
+ else if (isUriTemplate(uri)) throw new Error(`mcp.read: ${uri} is a URI template: give its params, like mcp.read(server, template, { params: { … } })`);
891
+ const conn = await this.#ready(id, signal);
892
+ // A subscribed resource is kept fresh by its updates, so its cached value is as good as a read.
893
+ const age = conn.cache.count(resKey(uri)) && conn.live?.stream === "open" && !conn.live.dirty.has(uri) ? Infinity : Number(maxAge) > 0 ? Number(maxAge) : 0;
894
+ return (await conn.cache.fetch(resKey(uri), async () => resourceValue(await conn.client.readResource(uri, { signal })), { maxAge: age })).value;
895
+ }
896
+
897
+ /** Get a prompt: `{ description?, messages }`. */
898
+ async prompt(id, name, args = {}, { signal } = {}) {
899
+ if (typeof name !== "string" || !name) throw new Error("mcp.prompt(server, name, args): a prompt's name");
900
+ const conn = await this.#ready(id, signal);
901
+ const result = await conn.client.getPrompt(name, args ?? {}, { signal });
902
+ return { ...(typeof result?.description === "string" ? { description: result.description } : {}), messages: Array.isArray(result?.messages) ? result.messages : [] };
903
+ }
904
+
905
+ /** The pane's own form ran something: remember it for its body (`last`), as `{ kind, name, args, value | error, at }`. */
906
+ remember(id, entry) {
907
+ const conn = this.conns.get(id);
908
+ if (!conn) return;
909
+ conn.last = entry;
910
+ this.#bump();
911
+ }
912
+
913
+ /**
914
+ * A request from pane code (`mcp.call`, `mcp.read`, `mcp.prompt`, `mcp.tools` in the Worker), from pane `paneId` of
915
+ * this canvas: `{ value }` or `{ error }`, never a throw. `server` is an MCP server pane's name.
916
+ */
917
+ async fromPane(paneId, server, op, request = {}, { signal, waiting } = {}) {
918
+ try {
919
+ if (typeof server !== "string" || !server) throw new Error("mcp: name an MCP server pane, like mcp.call(\"notes\", \"search\", { … })");
920
+ const found = findServer(this.canvas, server);
921
+ if (!found) throw new Error(`mcp: there is no MCP server pane named "${server}" on this canvas`);
922
+ const hub = hubOf(found.canvas);
923
+ const stop = new AbortController();
924
+ const onAbort = () => stop.abort(signal.reason);
925
+ signal?.addEventListener("abort", onAbort, { once: true });
926
+ try {
927
+ const maxAge = Number(request.maxAge) > 0 ? Number(request.maxAge) : 0;
928
+ if (op === "call") {
929
+ // A wait for the person stops the calling pane's sandbox clock; one as long as its timeout gives up.
930
+ const onWait = waiting ? () => waiting(() => stop.abort(new Error("nobody answered in time"))) : undefined;
931
+ return { value: await hub.call(found.id, String(request.tool ?? ""), request.args ?? {}, { origin: { canvas: this.canvas, paneId }, signal: stop.signal, onWait, maxAge }) };
932
+ }
933
+ if (op === "read") return { value: await hub.read(found.id, request.uri, { signal: stop.signal, maxAge, ...(request.params !== undefined ? { params: request.params } : {}) }) };
934
+ if (op === "prompt") return { value: await hub.prompt(found.id, request.name, request.args ?? {}, { signal: stop.signal }) };
935
+ if (op === "tools") return { value: structuredClone((await hub.#ready(found.id, stop.signal)).snapshot) };
936
+ throw new Error(`mcp: unknown request ${op}`);
937
+ } finally {
938
+ signal?.removeEventListener("abort", onAbort);
939
+ }
940
+ } catch (error) {
941
+ return { error: String(error?.message ?? error) };
942
+ }
943
+ }
944
+
945
+ /** Panes that went (deleted, or no longer MCP panes): their sessions end; the others' live sources follow their settings. */
946
+ sync() {
947
+ let changed = false;
948
+ for (const [id, conn] of this.conns) {
949
+ if (this.canvas.attached.has(id) && this.canvas.panes.get(id)?.type === "mcp") {
950
+ this.syncLive(id);
951
+ continue;
952
+ }
953
+ this.#close(conn);
954
+ this.conns.delete(id);
955
+ changed = true;
956
+ }
957
+ if (changed) this.#bump();
958
+ }
959
+
960
+ /** The canvas closed: every session ends. */
961
+ dispose() {
962
+ this.#rootsOff?.();
963
+ this.#rootsOff = null;
964
+ for (const conn of this.conns.values()) this.#close(conn);
965
+ this.conns.clear();
966
+ this.#bump();
967
+ }
968
+
969
+ // ── live sources (#533) ───────────────────────────────────────────────────
970
+
971
+ /** The panes with live subscriptions or watches now (the transport's sources). */
972
+ liveIds() {
973
+ return [...this.conns].filter(([, c]) => c.live && (c.live.subs.size || c.live.watches.size)).map(([id]) => id);
974
+ }
975
+
976
+ /** What the transport shows of pane `id`. */
977
+ describeLive(id) {
978
+ const live = this.conns.get(id)?.live;
979
+ return live ? { subscriptions: live.subs.size, watches: live.watches.size, ...(live.dirty.size ? { waiting: live.dirty.size } : {}) } : {};
980
+ }
981
+
982
+ /** May pane `id` keep anything live: the page, a trusted canvas, the pane on it and active, connected? */
983
+ #mayLive(id) {
984
+ const c = this.canvas;
985
+ const conn = this.conns.get(id);
986
+ return Boolean(this.live && !c.disposed && c.trusted?.value !== false && c.attached.has(id) && c.panes.get(id)?.type === "mcp" && !c.isDisabled?.(id) && !c.parked && conn?.snapshot && !conn.closed);
987
+ }
988
+
989
+ #held(id) {
990
+ return Boolean(this.canvas.root?.ownTransport?.holds(this.canvas, id));
991
+ }
992
+
993
+ #emit(id, name, payload) {
994
+ const c = this.canvas;
995
+ if (c.disposed || !c.attached.has(id)) return;
996
+ c.events?.builtin(id, name, payload);
997
+ }
998
+
999
+ /** Make pane `id`'s subscriptions and watches what its settings say (none when it may keep nothing live). */
1000
+ syncLive(id) {
1001
+ const conn = this.conns.get(id);
1002
+ if (!conn) return;
1003
+ if (!this.#mayLive(id)) {
1004
+ if (conn.live) (this.#stopLive(conn), this.#bump());
1005
+ return;
1006
+ }
1007
+ const want = liveSettings(this.canvas.panes.get(id));
1008
+ const live = (conn.live ??= { subs: new Map(), watches: new Map(), dirty: new Set(), due: new Set(), relist: false, stream: "off", stop: null, timer: null, failures: 0 });
1009
+ let changed = false;
1010
+ // Subscriptions: one cache subscriber each.
1011
+ const caps = conn.client.server?.capabilities?.resources ?? {};
1012
+ for (const [uri, sub] of live.subs) {
1013
+ if (want.subscribe.includes(uri)) continue;
1014
+ sub.off();
1015
+ live.subs.delete(uri);
1016
+ live.dirty.delete(uri);
1017
+ changed = true;
1018
+ }
1019
+ for (const uri of want.subscribe) {
1020
+ if (live.subs.has(uri)) continue;
1021
+ const sub = { uri, at: 0, error: caps.subscribe ? undefined : "the server doesn't offer subscriptions: read only once" };
1022
+ sub.off = conn.cache.subscribe(resKey(uri), (e) => {
1023
+ if (e.error !== undefined) Object.assign(sub, { error: e.error, at: e.at });
1024
+ else {
1025
+ Object.assign(sub, { at: e.at, error: caps.subscribe ? undefined : sub.error });
1026
+ if (e.changed || !sub.sent) this.#emit(id, "resource", { uri, value: e.value, at: new Date(e.at).toISOString() });
1027
+ sub.sent = true;
1028
+ }
1029
+ this.#bump();
1030
+ });
1031
+ live.subs.set(uri, sub);
1032
+ changed = true;
1033
+ this.#refresh(id, conn, uri);
1034
+ }
1035
+ // Watches: a timer each, for read-only tools only.
1036
+ const keys = new Set(want.watch.map(watchKey));
1037
+ for (const [key, w] of live.watches) {
1038
+ if (keys.has(key)) continue;
1039
+ this.clearTimer(w.timer);
1040
+ live.watches.delete(key);
1041
+ live.due.delete(key);
1042
+ changed = true;
1043
+ }
1044
+ for (const entry of want.watch) {
1045
+ const key = watchKey(entry);
1046
+ if (live.watches.has(key)) continue;
1047
+ const tool = conn.snapshot.tools.find((t) => t.name === entry.tool);
1048
+ const why = !tool ? `the server has no tool "${entry.tool}"` : !tool.readOnly ? `${entry.tool} isn't marked read-only by the server: only read-only tools are watched` : undefined;
1049
+ const w = { ...entry, key, timer: null, at: 0, ...(why ? { why } : {}) };
1050
+ live.watches.set(key, w);
1051
+ changed = true;
1052
+ if (!why) this.#poll(id, conn, w);
1053
+ }
1054
+ this.#ensureStream(id, conn);
1055
+ if (changed) this.#bump();
1056
+ }
1057
+
1058
+ #stopLive(conn) {
1059
+ const live = conn.live;
1060
+ if (!live) return;
1061
+ conn.live = null;
1062
+ live.stop?.abort();
1063
+ this.clearTimer(live.timer);
1064
+ for (const w of live.watches.values()) this.clearTimer(w.timer);
1065
+ for (const sub of live.subs.values()) sub.off();
1066
+ }
1067
+
1068
+ /** Read a subscribed resource again (an update came); held, it is remembered for play. */
1069
+ #refresh(id, conn, uri) {
1070
+ const live = conn.live;
1071
+ if (!live || !live.subs.has(uri)) return;
1072
+ if (this.#held(id)) {
1073
+ live.dirty.add(uri);
1074
+ this.#bump();
1075
+ return;
1076
+ }
1077
+ live.dirty.delete(uri);
1078
+ conn.cache.fetch(resKey(uri), async () => resourceValue(await conn.client.readResource(uri))).catch(() => {});
1079
+ }
1080
+
1081
+ /** A watch's call, then its next one in `every` seconds. Held, it is due on play. */
1082
+ #poll(id, conn, w) {
1083
+ const live = conn.live;
1084
+ if (!live || live.watches.get(w.key) !== w) return;
1085
+ this.clearTimer(w.timer);
1086
+ w.timer = this.setTimer(() => this.#poll(id, conn, w), w.every * 1000);
1087
+ if (this.#held(id)) {
1088
+ live.due.add(w.key);
1089
+ this.#bump();
1090
+ return;
1091
+ }
1092
+ live.due.delete(w.key);
1093
+ if (w.running) return; // the last call hasn't answered: this one is skipped
1094
+ w.running = true;
1095
+ this.call(id, w.tool, w.args, { origin: { canvas: this.canvas, paneId: id }, unattended: true })
1096
+ .then(
1097
+ (value) => {
1098
+ Object.assign(w, { at: this.now(), error: undefined });
1099
+ if (conn.live?.watches.get(w.key) === w) this.#emit(id, "watch", { tool: w.tool, args: w.args, value, at: new Date(w.at).toISOString() });
1100
+ },
1101
+ (error) => {
1102
+ Object.assign(w, { at: this.now(), error: String(error?.message ?? error) });
1103
+ if (conn.live?.watches.get(w.key) === w) this.#emit(id, "watch", { tool: w.tool, args: w.args, error: w.error, at: new Date(w.at).toISOString() });
1104
+ },
1105
+ )
1106
+ .finally(() => {
1107
+ w.running = false;
1108
+ this.#bump();
1109
+ });
1110
+ }
1111
+
1112
+ /** The cache's first subscriber to a resource: ask the server for its updates. */
1113
+ #activeKey(id, conn, key) {
1114
+ if (!key.startsWith("res:") || !conn.client.server?.capabilities?.resources?.subscribe) return;
1115
+ conn.client.subscribe(key.slice(4)).catch(() => {});
1116
+ }
1117
+
1118
+ /** …and the last one left: stop them (the session may have ended already). */
1119
+ #idleKey(id, conn, key) {
1120
+ if (!key.startsWith("res:") || conn.closed || !conn.client.server?.capabilities?.resources?.subscribe) return;
1121
+ conn.client.unsubscribe(key.slice(4)).catch(() => {});
1122
+ }
1123
+
1124
+ /** The server ended the session and a new one began: subscribe again, and read each again (updates were missed). */
1125
+ #resubscribe(id, conn) {
1126
+ for (const key of conn.cache.active()) this.#activeKey(id, conn, key);
1127
+ for (const uri of conn.live?.subs.keys() ?? []) this.#refresh(id, conn, uri);
1128
+ }
1129
+
1130
+ /** A notification from the server. */
1131
+ #notified(id, conn, m) {
1132
+ if (this.conns.get(id) === conn && m.method === "notifications/tasks/status") {
1133
+ try {
1134
+ this.#trackTask(id, conn, cleanTask(m.params), undefined);
1135
+ } catch {} // a task the server describes badly is ignored
1136
+ return;
1137
+ }
1138
+ if (this.conns.get(id) !== conn || !conn.live) return;
1139
+ if (m.method === "notifications/resources/updated" && typeof m.params?.uri === "string") return this.#refresh(id, conn, m.params.uri);
1140
+ if (/^notifications\/(tools|resources|prompts)\/list_changed$/.test(m.method)) {
1141
+ if (this.#held(id)) {
1142
+ conn.live.relist = true;
1143
+ this.#bump();
1144
+ } else this.#relist(id);
1145
+ }
1146
+ }
1147
+
1148
+ /** What the server offers changed: the pane runs again (its value is the new snapshot). */
1149
+ #relist(id) {
1150
+ const live = this.conns.get(id)?.live;
1151
+ if (live) live.relist = false;
1152
+ if (this.#mayLive(id)) this.canvas.run?.(id);
1153
+ }
1154
+
1155
+ /** Keep the session's event stream open while something needs it: subscriptions, or a server that says its lists change. */
1156
+ #ensureStream(id, conn) {
1157
+ const live = conn.live;
1158
+ if (!live || live.stop || live.stream === "none") return;
1159
+ const caps = conn.client.server?.capabilities ?? {};
1160
+ const wanted = live.subs.size > 0 || Boolean(caps.tools?.listChanged || caps.resources?.listChanged || caps.prompts?.listChanged);
1161
+ if (!wanted) return;
1162
+ const stop = new AbortController();
1163
+ live.stop = stop;
1164
+ live.stream = "connecting";
1165
+ let opened = 0;
1166
+ const loop = async () => {
1167
+ while (!stop.signal.aborted && conn.live === live) {
1168
+ try {
1169
+ const out = await conn.client.listen({
1170
+ signal: stop.signal,
1171
+ onOpen: () => {
1172
+ live.stream = "open";
1173
+ live.failures = 0;
1174
+ this.#inspector()?.event("mcp", this.canvas, id, "stream", { state: "open", ...(opened ? { reopened: true } : {}) });
1175
+ // After a drop, updates may have been missed: read what is subscribed again.
1176
+ if (opened++ > 0) for (const uri of live.subs.keys()) this.#refresh(id, conn, uri);
1177
+ this.#bump();
1178
+ },
1179
+ });
1180
+ if (!out.supported) {
1181
+ live.stream = "none";
1182
+ this.#inspector()?.event("mcp", this.canvas, id, "stream", { state: "none", why: "the server offers no event stream" });
1183
+ this.#bump();
1184
+ return;
1185
+ }
1186
+ } catch (error) {
1187
+ if (stop.signal.aborted) return;
1188
+ if (error?.expired) {
1189
+ try {
1190
+ await conn.client.restart();
1191
+ this.#resubscribe(id, conn);
1192
+ continue;
1193
+ } catch {}
1194
+ }
1195
+ }
1196
+ if (stop.signal.aborted || conn.live !== live) return;
1197
+ live.stream = "connecting";
1198
+ this.#bump();
1199
+ const wait = Math.min(RECONNECT_MS[1], RECONNECT_MS[0] * 2 ** Math.min(live.failures, 10));
1200
+ this.#inspector()?.retry("mcp", this.canvas, id, { reason: "the event stream dropped: opening it again", attempt: ++live.failures, delayMs: wait });
1201
+ await new Promise((resolve) => {
1202
+ live.timer = this.setTimer(resolve, wait);
1203
+ stop.signal.addEventListener("abort", resolve, { once: true });
1204
+ });
1205
+ }
1206
+ };
1207
+ loop().finally(() => {
1208
+ if (live.stop === stop && live.stream !== "none") (live.stream = "off"), (live.stop = null);
1209
+ });
1210
+ }
1211
+
1212
+ /** The transport played: what waited goes now (each remembered update read once, each due watch called once). */
1213
+ resume() {
1214
+ for (const [id, conn] of this.conns) {
1215
+ const live = conn.live;
1216
+ if (!live || this.#held(id)) continue;
1217
+ for (const uri of [...live.dirty]) this.#refresh(id, conn, uri);
1218
+ for (const key of [...live.due]) {
1219
+ const w = live.watches.get(key);
1220
+ if (w) this.#poll(id, conn, w);
1221
+ }
1222
+ if (live.relist) this.#relist(id);
1223
+ }
1224
+ this.#bump();
1225
+ }
1226
+
1227
+ /** A transport step for pane `id`: one waiting update, or one due watch. */
1228
+ step(id) {
1229
+ const conn = this.conns.get(id);
1230
+ const live = conn?.live;
1231
+ if (!live) return false;
1232
+ const uri = live.dirty.values().next().value;
1233
+ if (uri !== undefined) {
1234
+ live.dirty.delete(uri);
1235
+ conn.cache.fetch(resKey(uri), async () => resourceValue(await conn.client.readResource(uri))).catch(() => {});
1236
+ return true;
1237
+ }
1238
+ const key = live.due.values().next().value;
1239
+ if (key !== undefined) {
1240
+ live.due.delete(key);
1241
+ const w = live.watches.get(key);
1242
+ if (w && !w.running) {
1243
+ w.running = true;
1244
+ this.call(id, w.tool, w.args, { origin: { canvas: this.canvas, paneId: id }, unattended: true })
1245
+ .then((value) => (Object.assign(w, { at: this.now(), error: undefined }), this.#emit(id, "watch", { tool: w.tool, args: w.args, value, at: new Date(w.at).toISOString() })), (error) => Object.assign(w, { at: this.now(), error: String(error?.message ?? error) }))
1246
+ .finally(() => ((w.running = false), this.#bump()));
1247
+ }
1248
+ return true;
1249
+ }
1250
+ return false;
1251
+ }
1252
+
1253
+ // ── tapes (#537) ─────────────────────────────────────────────────────────
1254
+
1255
+ /** Start recording pane `id`'s session: the handshake and the lists are on the tape first. */
1256
+ async startRecording(id, { signal } = {}) {
1257
+ const pane = this.canvas.panes.get(id);
1258
+ if (mcpSettings(pane).replay) throw new Error("mcp: this pane replays a tape; turn replay off to record the server");
1259
+ const conn = await this.#ready(id, signal);
1260
+ conn.recording = { since: new Date(this.now()).toISOString(), exchanges: [] };
1261
+ if (conn.client.rawInit) conn.recording.exchanges.push({ method: "initialize", params: { protocolVersion: conn.client.server?.protocolVersion }, result: conn.client.rawInit });
1262
+ try {
1263
+ conn.snapshot = { ...(await conn.client.snapshot({ signal })), ...(conn.snapshot?.drift ? { drift: conn.snapshot.drift } : {}) };
1264
+ } catch (error) {
1265
+ conn.recording = null;
1266
+ throw error;
1267
+ }
1268
+ this.#bump();
1269
+ return { since: conn.recording.since };
1270
+ }
1271
+
1272
+ /**
1273
+ * Stop recording: the tape, redacted with the gate's rules for this server and the tape's own. Throws, keeping
1274
+ * nothing, when it still holds something a rule matches. `{ tape, cut, exchanges }`.
1275
+ */
1276
+ stopRecording(id) {
1277
+ const conn = this.conns.get(id);
1278
+ const rec = conn?.recording;
1279
+ if (!rec) throw new Error("mcp: this pane isn't recording");
1280
+ conn.recording = null;
1281
+ this.#bump();
1282
+ const { tape, cut } = makeTape({ exchanges: rec.exchanges, snapshot: conn.snapshot, recordedAt: rec.since });
1283
+ const server = gateServerOf(this.canvas.panes.get(id), id);
1284
+ const { gate } = effectivePolicy(this.canvas.root.id);
1285
+ const rules = tapeRules(Object.hasOwn(gate.servers, server) ? gate.servers[server].redact : []);
1286
+ const { tape: clean, leaks } = redactTape(tape, rules);
1287
+ if (leaks.length) throw new Error(`mcp: the tape wasn't kept: after redaction it still matches ${leaks.join(", ")} (a rule that matches its own replacement?)`);
1288
+ return { tape: clean, cut, exchanges: clean.exchanges.length };
1289
+ }
1290
+
1291
+ /** Is pane `id` recording? */
1292
+ recording(id) {
1293
+ return Boolean(this.conns.get(id)?.recording);
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * The MCP servers under a root canvas, for the gate's server list and matrix (src/ui/tool-gate-ui.js):
1299
+ * [{ server, tools }], every MCP server pane on it or in its open subgraphs by its gate name, with the
1300
+ * tools its connection lists (none before it connects).
1301
+ */
1302
+ export function canvasServers(root) {
1303
+ const out = new Map();
1304
+ const walk = (c) => {
1305
+ if (!c || c.disposed) return;
1306
+ for (const id of c.attached) {
1307
+ const pane = c.panes.get(id);
1308
+ if (pane?.type !== "mcp") continue;
1309
+ const server = gateServerOf(pane, id);
1310
+ const tools = c.mcpHub?.conns.get(id)?.snapshot?.tools ?? [];
1311
+ out.set(server, { server, tools: [...(out.get(server)?.tools ?? []), ...tools] });
1312
+ }
1313
+ for (const inner of c.subgraphs?.values() ?? []) walk(inner);
1314
+ };
1315
+ walk(root);
1316
+ return [...out.values()];
1317
+ }
1318
+
1319
+ // The protocol inspector's view of MCP server panes (src/protocol/inspector.js).
1320
+ registerProtocol({
1321
+ id: "mcp",
1322
+ label: "MCP",
1323
+ owns: (canvas, id) => canvas?.panes?.get(id)?.type === "mcp",
1324
+ server: (canvas, id) => gateServerOf(canvas.panes.get(id), id),
1325
+ connections: (canvas) => canvas.mcpHub?.inspect() ?? [],
1326
+ });