@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
@@ -0,0 +1,1323 @@
1
+ // mallory's agent tools: list, read, add, change, connect, run and delete panes
2
+ // on the current canvas. Every change goes through the same Canvas methods the
3
+ // UI uses (createPane, update, connect, disconnect, deletePane, run, runAll,
4
+ // setState), so every tool call that changes the canvas is one step in its undo
5
+ // history ("the agent's change: code of sum", Canvas#agentStep) and the
6
+ // screen updates as if a person had done it. Values come back as text made
7
+ // from the sandbox's previews; nothing here touches the DOM, so the tools run
8
+ // under Node against a fake runtime too. What needs the page (opening
9
+ // canvases and subgraphs, running tests, effects frames, arranging) goes
10
+ // through `host`, which src/webmcp/index.js wires to the same app methods the
11
+ // commands use.
12
+ //
13
+ // Each tool is a spec (toolFromSpec, at the end): name, title, description,
14
+ // input schema, readOnly / destructive / untrusted, run. Commands name the tool
15
+ // that does what they do (`agent: { tool }` on the command, src/agents.js); a
16
+ // tool no command maps to says in `agentOnly` what a person uses instead.
17
+ // What depends on the pane types (add_pane's types, the pane settings
18
+ // add_pane and update_pane take, which types have which, the lists of types
19
+ // in descriptions) is built from the pane type records (src/panes/), so it is
20
+ // written once, there.
21
+ //
22
+ // Deliberately NOT here, ever: network permission rules (allowing or blocking
23
+ // hosts, the network mode, the local network), on-device AI permissions (the
24
+ // AI mode, a canvas's allow or block, model downloads), variables (env) and
25
+ // API keys. An agent in the page must not grant itself network access or the
26
+ // model, or read the person's values; its panes meet the same network and AI
27
+ // prompts as anyone's (an agent may write panes that use on-device AI) and get
28
+ // only secret() placeholders. test/coverage.test.mjs fails if a tool, an
29
+ // argument or an import here reaches for them.
30
+ import { isScenePatch, validateScene, SceneError } from "../scene/pixi-scene.js";
31
+ import { editScene, newScene } from "../scene/scene-edit.js";
32
+ import { describeHints } from "../model/size-hints.js";
33
+ import { sanitizeName } from "../model/canvas.js";
34
+ import { routeProblem } from "../model/wire-route.js";
35
+ import { profileProblems, cleanProfileSettings } from "../model/profile-settings.js";
36
+ import { plotProblems, cleanPlotSettings } from "../model/plot-series.js";
37
+ import { graphProblem } from "../model/graph-settings.js";
38
+ import { geometrySettingsProblem } from "../model/geometry-settings.js";
39
+ import { applyEdit, scoreProblem } from "../model/score-edit.js";
40
+ import { agentStartScore } from "../model/score-library.js";
41
+ import { PANE_FIELDS, paneType } from "../panes/registry.js";
42
+ import { lowerOnlyProblem } from "../model/person-only.js";
43
+ import { persistContent } from "../model/persist-state.js";
44
+ import { selectionProblem } from "../model/selection.js";
45
+ import { queueBytesProblem, queueExpireProblem, queuePolicyProblem, DEFAULT_POLICY } from "../model/queue-book.js";
46
+ import { listWords } from "../panes/fields.js";
47
+ import { checkArgs, resolvePane, resolveInputs, placeOnGrid } from "./args.js";
48
+ import { stateSummary, deepenPreview, previewToText, tableToText, profileToText, lineageToText, CAPTURE_HIDDEN } from "./text.js";
49
+ import { hiddenText, isLogSource } from "./hidden.js";
50
+ import { enterAgentCall } from "../model/agent-runs.js";
51
+ import { portsOf, outputIds, graphPanes } from "../model/subgraph.js";
52
+ import { compositeFaces, compositeOn, compositeProblem } from "../model/composite.js";
53
+ import { innermostGroup, parentOf } from "../model/groups.js";
54
+ import { COLORS, isColor } from "../panes/colors.js";
55
+ import { customProblems, spriteProblems, transitionProblem, gifPlan } from "../effects/extras.js";
56
+ import { checkUniforms, normalizeUniforms, checkShaderSettings } from "../shader/model.js";
57
+ import { checkCommon, checkBuffers, checkImageBuffers, normalizeBuffers } from "../shader/passes.js";
58
+ import { checkChannels, normalizeChannels } from "../shader/channels.js";
59
+ import { describeRender } from "../audio/plan.js";
60
+ import { agentRecordEdit } from "../audio/takes.js";
61
+ import { cleanDsp } from "../audio/patch.js";
62
+ import { cleanSignals } from "../runtime/frame-signals.js";
63
+ import { isMedia, describeMedia } from "../media/contract.js";
64
+ import { cleanErrorPolicy } from "../model/errors.js";
65
+ import { DIRTY_WORDS } from "../model/partial.js";
66
+ import { mergeControl } from "../model/controls.js";
67
+ import { planPromote } from "../model/promote.js";
68
+ import { insertLinked, linkStatus, linkSource, planReplace, acceptReplacement, deprecationOfDoc, portProblems, linkedTemplate, templatesOf, planTemplateUpdate, acceptTemplateUpdate, planTemplateReplace, acceptTemplateReplacement } from "../model/links.js";
69
+ import { normalizeRepeat, repeatProblem, repeatOn, instancesOf, ITEM_EVENTS } from "../model/repeater.js";
70
+ import { parsePanePath } from "../packages/package.js";
71
+ import { replacementFor, REPLACEMENT_WORDS } from "../packages/deprecation.js";
72
+ import { formatDiff, diffCanvases } from "../model/diff.js";
73
+ import { timerSettings, timerProblem, setWhen } from "../model/timers.js";
74
+ import { deviceSettings, deviceProblem } from "../device/model.js";
75
+ import { automationSettings, automationProblems, defaultAutomation, setDuration, secondsOf } from "../model/automation.js";
76
+ import { waitProblem } from "../model/waits.js";
77
+ import { decideProblem } from "../model/decisions.js";
78
+ import { gateProblem } from "../model/windows.js";
79
+ import { chartProblem } from "../model/statecharts.js";
80
+ import { codecProblem, cleanCodec } from "../codec/core.js";
81
+ import { cleanHttp, httpProblem } from "../model/http-tools.js";
82
+ import { trafficProblem } from "../model/traffic.js";
83
+ import { agentGoalsPatch } from "../model/goals.js";
84
+ import { agentLedgerPatch } from "../model/ledger-pane.js";
85
+ import { mergeVerdict, verdictProblem } from "../verdict/engine.js";
86
+ import { sampleProblem } from "../model/sample-settings.js";
87
+ import { wsProblem } from "../model/ws-client.js";
88
+ import { mapProblem, actionMapSettings, PRESETS } from "../actions/map.js";
89
+ import { inputLogProblem, inputLogSettings } from "../input/player.js";
90
+ import { waitingOf } from "../model/wait-clock.js";
91
+ import { pinInfo } from "./tools/run-tools.js";
92
+ import { contextContent, contextInfo, isContextNode } from "../model/context.js";
93
+ import { transportSource } from "./tools/transport-tools.js";
94
+ import { operatorsProblem, describeOperators } from "../model/wire-ops.js";
95
+ import { webhookProblem, respondProblem } from "../model/webhook.js";
96
+ import { routerProblem } from "../model/router.js";
97
+ import { companionProblem } from "../model/companion-pane.js";
98
+ import { watchProblem } from "../model/watch.js";
99
+ import { validateOutputs, cleanOutputs, outputsOf } from "../model/ports.js";
100
+ import { outputSuggestions, infersOutputs } from "../model/infer-outputs.js";
101
+ import { typeProblem, cleanType, typeText } from "../model/types.js";
102
+ import { cleanSwitch } from "../model/switch.js";
103
+ import { cleanSplit, splitProblem, cohortReport, keyReport, reassignment } from "../model/split.js";
104
+ import { channelsOf, channelsInside, validateReceive, cleanReceive, paneKey } from "../model/channels.js";
105
+ import { strictProblems } from "../runtime/strict.js";
106
+ import { coreTools } from "./tools/core.js";
107
+ import { runsTools } from "./tools/runs.js";
108
+ import { editTools } from "./tools/edit.js";
109
+ import { reshapeTools } from "./tools/reshape.js";
110
+ import { liveTools } from "./tools/live.js";
111
+ import { testsTools } from "./tools/tests.js";
112
+ import { subgraphsTools } from "./tools/subgraphs.js";
113
+ import { devicesTools } from "./tools/devices.js";
114
+ import { trafficTools } from "./tools/traffic-tools.js";
115
+ import { machineTools } from "./tools/machine-tools.js";
116
+ import { mediaTools } from "./tools/media.js";
117
+ import { canvasesTools } from "./tools/canvases.js";
118
+ import { versionsTools } from "./tools/versions.js";
119
+ import { mediaFromUrlArg, timerStatus, checkSettings, checkSchemaOf, flattenSettings, round, resultText, toolResult } from "./tools/shared.js";
120
+ export { IMAGE, schemaShape, briefSetting, settingFor, checkSettings, toolResult } from "./tools/shared.js";
121
+
122
+ /**
123
+ * @param {{
124
+ * getCanvas: () => import("../model/canvas.js").Canvas | null | undefined,
125
+ * examples?: { slug: string, title: string, category?: string, blurb?: string, tags?: string[], network?: string[], doc?: object }[],
126
+ * openExample?: (slug: string) => void | Promise<void>,
127
+ * paneDefaults?: (type: string) => object,
128
+ * snapRect?: (rect: { x, y, width?, height? }, canvas?) => { x, y },
129
+ * select?: (id: string) => void,
130
+ * refresh?: (id: string, keys: string[]) => void,
131
+ * renderControl?: (id: string, action: string, args: object) => Promise<object>,
132
+ * listCanvases?: () => { id: string, name: string, panes: number, updated: number }[],
133
+ * loadCanvas?: (id: string) => object | undefined,
134
+ * openCanvas?: (id: string) => void | Promise<void>,
135
+ * newCanvas?: (name?: string) => void | Promise<void>,
136
+ * saveCanvas?: () => boolean,
137
+ * fileLinkStatus?: () => { linked: boolean, state?: string, autosave?: boolean } | undefined, // read-only: is the open canvas saved to a file on the person's disk
138
+ * rootCanvas?: () => object | null | undefined,
139
+ * openSubgraph?: (id: string) => void,
140
+ * leaveSubgraph?: (all?: boolean) => void,
141
+ * subgraphPath?: () => string[],
142
+ * saveSubgraph?: (id: string) => string | undefined,
143
+ * runTests?: (tests: object[]) => Promise<object[] | undefined>,
144
+ * testResult?: (test: object) => object | string | undefined,
145
+ * lastEvaluation?: (test: object) => Promise<object | undefined>, // the last evaluation's summary kept in this browser (src/tests/eval-history.js)
146
+ * testsChanged?: () => void,
147
+ * effects?: { status: (id: string) => object | undefined, render: (id: string) => void, frame: (id: string) => Promise<Blob> },
148
+ * arrange?: (op: string, ids: string[], options?: { hub?: string }) => number,
149
+ * snapHub?: () => string | undefined,
150
+ * arrangeGroup?: (ids: string[]) => number,
151
+ * setSelection?: (ids: string[]) => void,
152
+ * zoomTo?: (ids: string[]) => void,
153
+ * jumpToBookmark?: (name: string) => { ok: boolean, why?: string }, // viewport bookmarks (src/bookmark-commands.js)
154
+ * bookmarksReadOnly?: () => boolean, // true in a view of a linked pane or a repeater's instance: no bookmarks there
155
+ * wireArrivals?: (canvas: object) => { get: (dep: string) => { version: number, at: number, count: number } | undefined } | undefined, // src/ui/wire-inspector.js
156
+ * }} host `refresh` redraws a pane's controls after a tool changed its content (the UI only redraws what it changed itself).
157
+ * The rest are the app's own methods (src/webmcp/index.js); a tool whose host method is missing says it isn't available.
158
+ */
159
+ export function createTools(host) {
160
+ const canvas = () => {
161
+ const c = host.getCanvas();
162
+ if (!c) throw new Error("No canvas is open.");
163
+ return c;
164
+ };
165
+ const visible = (c) => c.order().map((id) => c.panes.get(id));
166
+ const find = (c, ref) => resolvePane(visible(c), ref);
167
+ const nameOf = (c, id) => (String(id).includes("#") ? c.labelOf(id) : c.panes.get(id)?.name || id); // "route.large": an output
168
+ const requireTrusted = (c, verb) => {
169
+ if (!c.trusted.value) {
170
+ throw new Error(`This canvas came from a link or file, so it is paused and nothing on it runs until the person using mallory presses "Run it" in the banner. Ask them to review it and press "Run it" before you ${verb}.`);
171
+ }
172
+ };
173
+
174
+ /** Where links look for their canvases (src/model/links.js): the saved canvases, and the open canvas's library. */
175
+ // A deprecation notice with where its replacement stands among the installed packages. Reading only: nothing is installed or fetched.
176
+ const noticeWithReplacement = (dep, paneId) => {
177
+ if (!dep) return undefined;
178
+ const rep = replacementFor(dep, paneId, { installed: (name) => (host.listPackages?.() ?? []).some((e) => e.name === name && e.pkg), source: (ref) => host.packagePane?.(ref) });
179
+ const { replacement, ...rest } = dep;
180
+ return { ...rest, ...(rep ? { replacement: { path: rep.path, state: rep.state, ...(rep.state === "ready" ? {} : { note: REPLACEMENT_WORDS[rep.state] }) } } : {}) };
181
+ };
182
+ const linkWhere = (c) => ({ loadCanvas: (id) => host.loadCanvas?.(id), loadPackage: (ref) => host.packagePane?.(ref), library: (host.rootCanvas?.() ?? c?.root ?? c)?.library ?? {}, packageModules: (host.rootCanvas?.() ?? c?.root ?? c)?.packageModules ?? {} });
183
+
184
+ function inputsOf(c, pane) {
185
+ // A source grouped into a subgraph pane is read through it (`from` names the subgraph pane).
186
+ return pane.inputs.map((input) => {
187
+ const { node } = c.homeOf(input.source);
188
+ const port = Object.fromEntries(["output", "type", "convert", "description", "operators", "route"].filter((k) => input[k] !== undefined).map((k) => [k, input[k]]));
189
+ // A wire to an output its source doesn't have (any more) waits.
190
+ const gone = input.output && c.attached.has(input.source) && !c.outputsOf(input.source).some((o) => o.name === input.output);
191
+ const setter = Boolean(c.writeTarget(input)); // a setter wire: write-only
192
+ return { name: input.name, from: nameOf(c, node), source: input.source, ...port, ...(setter ? { setter } : {}), ...(c.attached.has(node) || isContextNode(node) ? {} : { missing: true }), ...(gone ? { missingOutput: true } : {}) };
193
+ });
194
+ }
195
+
196
+ /** "x", "x ← total", "x ← split.small", "price: number ← p". */
197
+ const inputWords = (i) => `${i.name}${i.type !== undefined ? `: ${typeText(i.type)}` : ""}${i.name === i.from && !i.output ? "" : ` ← ${i.from}${i.output ? `.${i.output}` : ""}`}${i.operators?.length ? ` | ${describeOperators(i.operators)}` : ""}`;
198
+
199
+ /** A pane's outputs for agents: [{ name, type?, description?, error?, status }] (status: done / skipped / …, this run). */
200
+ const outputsInfo = (c, id) =>
201
+ c.outputsOf(id).map((o) => {
202
+ if (o.setter) return { name: o.name, setter: true, description: o.description }; // a state pane's setter: no value, no run
203
+ const s = c.stateOf(`${id}#${o.name}`).value;
204
+ return { name: o.name, ...(o.type !== undefined ? { type: o.type } : {}), ...(o.description ? { description: o.description } : {}), ...(o.error ? { error: true } : {}), status: s.status, ...(s.status === "skipped" && s.skip?.reason ? { reason: s.skip.reason } : {}), ...(s.status === "error" ? { message: s.error?.message } : {}) };
205
+ });
206
+
207
+ /** Throws a readable error unless `port` ({ output?, type?, convert?, description? }) fits source pane `source`. */
208
+ function checkPort(c, source, port) {
209
+ if (port.output !== undefined) {
210
+ const outs = c.outputsOf(source).map((o) => o.name);
211
+ if (!outs.includes(port.output)) throw new Error(`${nameOf(c, source)} has no output "${port.output}". ${outs.length ? `Its outputs: ${outs.join(", ")}.` : "It has none: give it some with mallory_update_pane outputs."}`);
212
+ }
213
+ if (port.type !== undefined && typeProblem(port.type)) throw new Error(`type: ${typeProblem(port.type)}.`);
214
+ if (port.convert && port.type === undefined) throw new Error("convert needs a type to convert to.");
215
+ if (port.operators !== undefined && operatorsProblem(port.operators)) throw new Error(`${operatorsProblem(port.operators)}.`);
216
+ }
217
+
218
+ /** A pane's inputs with types set by name (update_pane's inputTypes): a type, { type?, convert?, description? }, or null. */
219
+ function typedInputs(c, pane, byName) {
220
+ const names = pane.inputs.map((i) => i.name);
221
+ for (const name of Object.keys(byName)) if (!names.includes(name)) throw new Error(`${pane.name || pane.id} has no input "${name}". Its inputs: ${names.join(", ") || "none"}.`);
222
+ return pane.inputs.map((input) => {
223
+ if (!Object.hasOwn(byName, input.name)) return input;
224
+ const value = byName[input.name];
225
+ const { type, convert, description, ...rest } = input;
226
+ if (value === null) return description ? { ...rest, description } : rest;
227
+ // { type?, convert?, description? }, or else the type itself (a name, or a JSON Schema with keys of its own).
228
+ const portForm = value && typeof value === "object" && Object.keys(value).length > 0 && Object.keys(value).every((k) => ["type", "convert", "description"].includes(k));
229
+ const port = portForm ? { type, convert, description, ...value } : { type: value, convert, description };
230
+ checkPort(c, input.source, { type: port.type, convert: port.convert });
231
+ return { ...rest, ...Object.fromEntries(Object.entries(port).filter(([, v]) => v !== undefined && v !== null && v !== false && v !== "")) };
232
+ });
233
+ }
234
+
235
+ /** [{ name, route }] for update_pane's inputRoutes, checked before anything changes (null: the default curve). */
236
+ function routedInputs(pane, byName) {
237
+ const names = pane.inputs.map((i) => i.name);
238
+ return Object.entries(byName).map(([name, route]) => {
239
+ if (!names.includes(name)) throw new Error(`${pane.name || pane.id} has no input "${name}". Its inputs: ${names.join(", ") || "none"}.`);
240
+ const problem = routeProblem(route === null ? undefined : route);
241
+ if (problem) throw new Error(`inputRoutes.${name}: ${problem}.`);
242
+ return { name, route: route === null ? undefined : route };
243
+ });
244
+ }
245
+
246
+ function summary(c, id, { maxLength = 160 } = {}) {
247
+ const pane = c.panes.get(id);
248
+ const workspace = c.workspaces.length > 1 ? { workspace: c.workspaceOf(id) } : {}; // src/model/workspaces.js: only once there are two
249
+ if (pane.type === "note") return { id, type: pane.type, name: pane.name, ...workspace, text: String(pane.text ?? "").slice(0, maxLength) };
250
+ const group = innermostGroup(liveGroups(c), id);
251
+ return {
252
+ id,
253
+ type: pane.type,
254
+ name: pane.name,
255
+ ...workspace,
256
+ ...(pane.description ? { description: String(pane.description).slice(0, maxLength) } : {}),
257
+ ...(group ? { group: group.name } : {}),
258
+ ...(c.isDisabled(id) ? { deactivated: true } : {}),
259
+ ...(pane.pin ? { pinned: true } : {}),
260
+ inputs: inputsOf(c, pane).map(inputWords),
261
+ ...(c.outputsOf(id).length ? { outputs: c.outputsOf(id).map((o) => o.name) } : {}),
262
+ ...stateSummary(c.stateOf(id).value, { maxLength, nameOf: (s) => nameOf(c, s), hidden: hiddenText(c, id) ?? false }),
263
+ };
264
+ }
265
+
266
+ /** The canvas's groups (frames) that have panes on it. */
267
+ const liveGroups = (c) => c.groups.filter((g) => g.panes.some((id) => c.attached.has(id)));
268
+ /** A group as agents see it. */
269
+ const groupSummary = (c, g) => {
270
+ const panes = g.panes.filter((id) => c.attached.has(id));
271
+ const parent = parentOf(c.groups, g.id, (id) => c.attached.has(id));
272
+ return {
273
+ id: g.id,
274
+ name: g.name,
275
+ color: g.color,
276
+ panes: panes.map((id) => nameOf(c, id)),
277
+ ...(parent ? { inside: parent.name } : {}),
278
+ collapsed: panes.every((id) => c.panes.get(id)?.collapsed),
279
+ ...(g.disabled ? { deactivated: true } : {}),
280
+ ...(g.description ? { description: g.description } : {}),
281
+ };
282
+ };
283
+ /** A group by name or id. */
284
+ function findGroup(c, ref) {
285
+ const groups = liveGroups(c);
286
+ const byId = groups.find((g) => g.id === ref);
287
+ if (byId) return byId;
288
+ const named = groups.filter((g) => g.name === ref);
289
+ if (named.length === 1) return named[0];
290
+ if (named.length > 1) throw new Error(`${named.length} groups are called "${ref}": use its id (${named.map((g) => g.id).join(", ")}).`);
291
+ throw new Error(`No group "${ref}". Groups: ${groups.map((g) => `${g.name} (${g.id})`).join(", ") || "none"} (see mallory_list_panes).`);
292
+ }
293
+
294
+ /** What a pane type's agentStatus gets next to the pane and the canvas (src/panes/registry.js). `model` is what a record can't import: src/model/ reads the registry when it loads. */
295
+ const statusTools = { host, nameOf, timerStatus, mediaOf, linkWhere, noticeWithReplacement, repeaterInfo, model: { graphPanes, outputIds, portsOf, compositeFaces, compositeOn, compositeProblem, linkStatus, portProblems, repeatOn } };
296
+
297
+ async function detail(c, id, { depth = 3, maxLength = 8000, splitKeys, splitChange } = {}) {
298
+ const pane = c.panes.get(id);
299
+ const state = c.stateOf(id).value;
300
+ const out = { id, type: pane.type, name: pane.name };
301
+ for (const key of ["code", "mode", "text", "widget", "url", "view", "autorun", "each", "takesSkips", "ownWorker", "strict", "runsWithoutEvent", "queueLimit", "queueBytes", "queueExpireMs", "queuePolicy", "cutoff", "rate", "onError", "scope", "keep", "render", "effects", "workWidth", "gpu", "liveFrames", "keepMetadata", "produces", "swatches", "transition", "sprite", "gif", "define", "audio", "timer", "waitFor", "decide", "gate", "chart", "codec", "scene", "actionMap", "webhook", "router", "respond", "companion", "files", "color", "description", "showDescription", "selection", "dsp"]) if (pane[key] !== undefined && pane[key] !== "") out[key] = pane[key];
302
+ const settings = { ...out }; // the pane's own content: what its author wrote, not what it computed
303
+ // What is special about its type for an agent (the record's agentStatus, src/panes/registry.js); `after` fields win over the generic ones below.
304
+ // (Awaited only when it is async: a synchronous detail reads the run state in the same tick as the call, as it always did.)
305
+ let given = paneType(pane.type)?.agentStatus?.(pane, c, statusTools);
306
+ if (given?.then) given = await given;
307
+ const { after: statusAfter, ...status } = given ?? {};
308
+ Object.assign(out, status);
309
+ if (waitingOf(pane.type) && c.waits) out.waits = c.waits.status(id); // pending waits with their deadlines, outcome counts, its outcome ports
310
+ const queue = c.events?.queueStatus(id); // a reader of events: what waits for it, sizes (approximate), oldest, budgets, policy, and what was lost
311
+ if (queue) out.queue = queue;
312
+ const source = c.transport?.source(c, id); // a live source: paused or not
313
+ if (source) out.transport = (({ pane: _, name: __, ...rest }) => rest)(transportSource(source));
314
+ if (pane.strict && state.result?.strict) out.strictRun = state.result.strict; // the fuel its last strict run used, of its budget
315
+ if (c.root.ownBreakpoints?.isStopped(c, id)) out.stoppedAtBreakpoint = true; // a person's breakpoint holds its run: mallory_breakpoints says more
316
+ if (c.isDisabled(id)) out.deactivated = pane.disabled ? true : `by group "${c.groupsOf(id).find((g) => g.disabled)?.name}"`;
317
+ const groups = c.groupsOf(id).map((g) => g.name);
318
+ if (groups.length) out.groups = groups;
319
+ if (pane.module) out.module = pane.module;
320
+ if (pane.pin) out.pinned = pinInfo(pane); // it doesn't run: its pinned value goes downstream (src/model/pin.js)
321
+ out.inputs = inputsOf(c, pane);
322
+ // Named outputs (src/model/ports.js): each one's type, description and what it did this run.
323
+ const outputs = outputsInfo(c, id);
324
+ if (outputs.length) out.outputs = outputs;
325
+ // Outputs its code sets that it doesn't declare, and declared ones it no longer sets (frame panes' emit.event too): accept with mallory_update_pane { acceptOutputs }.
326
+ const found = infersOutputs(pane) ? outputSuggestions(pane) : undefined;
327
+ if (found && (found.add.length || found.notSet.length || found.cantInfer.length || found.notes.length)) {
328
+ out.suggestedOutputs = Object.fromEntries(Object.entries(found).filter(([, v]) => v.length));
329
+ }
330
+ if (pane.switch) out.switch = pane.switch;
331
+ if (pane.split) {
332
+ out.split = pane.split;
333
+ out.splitSample = cohortReport(pane.split); // what the fixed sample cohort of 200 keys does with these weights
334
+ // For keys the agent names: the same counts for them, and what a change of settings would do to them (nothing is applied or stored).
335
+ if (splitKeys) out.splitReport = keyReport(pane.split, splitKeys);
336
+ if (splitChange) {
337
+ const merged = { ...pane.split, ...splitChange }; // only the keys passed change; branches replace the whole list
338
+ const problem = splitProblem(merged);
339
+ if (problem) throw new Error(`splitChange: ${problem}.`);
340
+ out.splitChange = reassignment(pane.split, merged, splitKeys ?? undefined);
341
+ }
342
+ } else if (splitKeys || splitChange) throw new Error("splitKeys and splitChange: this pane isn't a weighted split (see mallory_update_pane's split).");
343
+ const channels = channelsInfo(c, id, pane); // named event channels
344
+ if (channels) out.channels = channels;
345
+ if (pane.description) out.description = pane.description;
346
+ const setters = c.settersOf(id).map((s) => s.name);
347
+ if (setters.length) out.setters = setters;
348
+ Object.assign(out, contextInfo(c, id)); // the context it shares, where the ones it reads come from
349
+ // What reads it: panes, and panes reading one of its outputs ("report (error)").
350
+ out.usedBy = [...new Set(c.flow.dependents(id).flatMap((d) => (d.includes("#") ? c.flow.dependents(d).map((u) => `${nameOf(c, u)} (${d.slice(d.indexOf("#") + 1)})`) : [nameOf(c, d)])))];
351
+ out.rect = c.rectOf(id);
352
+ if (c.isPinned(id)) out.pinnedInPlace = true; // the person's lock: update_pane refuses x, y and width, arrange leaves it where it is
353
+ if (pane.inputHeight !== undefined) out.inputHeight = pane.inputHeight; // the divider between its input and its preview (src/model/input-split.js)
354
+ const sizeHints = describeHints(pane);
355
+ if (sizeHints) out.sizeHints = sizeHints; // its type's limits, aspect ratio or cell size (src/model/size-hints.js)
356
+ const asked = c.sizeRequest(id);
357
+ if (asked && (asked.requested.width !== asked.actual.width || asked.requested.height !== asked.actual.height)) out.sizeAsked = asked; // the last resize the hints changed
358
+ const hidden = hiddenText(c, id); // made from a live camera, microphone or screen, or a capture log the person has not let agents read: its value, media and tables stay out
359
+ Object.assign(out, stateSummary(state, { maxLength, nameOf: (s) => nameOf(c, s), hidden }));
360
+ const last = c.runs?.lastSettledRun(id);
361
+ if (last) out.lastRunMs = Math.round(last.duration * 10) / 10;
362
+ // Out of date (src/model/partial.js): manual mode, auto off, or a partial run left it behind.
363
+ const dirty = c.dirty?.value.get(id);
364
+ if (dirty) {
365
+ out.dirty = true;
366
+ out.dirtyReason = dirty.kind === "upstream" ? `${DIRTY_WORDS.upstream} (${nameOf(c, dirty.from)})` : DIRTY_WORDS[dirty.kind];
367
+ }
368
+ if (state.unchanged) out.unchanged = true; // its last run's value equaled the one before (only pass changes)
369
+ // A live pane: its run is still making values (yield or emit), how many so far, and what an input change does.
370
+ const live = c.liveOf?.(id);
371
+ if (state.live || live?.runId === state.runId) out.live = { running: Boolean(state.live), values: live?.count ?? 0, onInputChange: pane.live === "resume" ? "resume" : "restart" };
372
+ // Values arriving faster than the pane runs: its last runs were each replaced by a newer value.
373
+ const outpaced = c.runs?.outpaced(id);
374
+ if (outpaced) out.outpaced = { supersededRuns: outpaced.superseded };
375
+ const result = hidden ? undefined : state.result;
376
+ if (state.status === "done" && result?.preview && depth > 1) {
377
+ const deep = await deepenPreview(result.preview, (handle) => c.expand(handle), { depth });
378
+ out.value = previewToText(deep, { maxLength });
379
+ }
380
+ if (result?.table && ["table", "plot"].includes(pane.view)) out.table = tableToText(result.table);
381
+ if (result?.profile && pane.view === "profile") out.profile = profileToText(result.profile);
382
+ if (result?.lineage && pane.view === "lineage") out.lineage = lineageToText(result.lineage);
383
+ Object.assign(out, statusAfter);
384
+ if (hidden) {
385
+ // Hidden (src/webmcp/hidden.js): its structure and how it ended, and nothing it computed, nor an error, skip, log, queue or pin that quotes it.
386
+ const structure = ["groups", "deactivated", "module", "rect", "usedBy", "setters", "inputHeight", "pinnedInPlace", "sizeHints"];
387
+ return {
388
+ ...settings,
389
+ ...Object.fromEntries(structure.filter((k) => out[k] !== undefined).map((k) => [k, out[k]])),
390
+ // what the record says of the pane: for a live capture its stream's state (no sample, as before); for a log only what it says of its own settings
391
+ ...(hidden === CAPTURE_HIDDEN ? status : isLogSource(pane) ? Object.fromEntries(["summary", "problem"].filter((k) => status[k] !== undefined).map((k) => [k, status[k]])) : {}),
392
+ ...(pane.pin ? { pinned: true } : {}),
393
+ inputs: (out.inputs ?? []).map(({ name, from, source }) => ({ name, from, source })),
394
+ ...(out.outputs ? { outputs: out.outputs.map((o) => o.name) } : {}),
395
+ status: state.status ?? "idle",
396
+ value: hidden,
397
+ };
398
+ }
399
+ const logs = c.logsOf(id).value;
400
+ if (logs.length) out.logs = logs.slice(-20).map((l) => (l.level === "log" ? l.text : `[${l.level}] ${l.text}`));
401
+ if (!c.trusted.value) out.paused = true;
402
+ return out;
403
+ }
404
+
405
+ /**
406
+ * Wait until `done()` holds or nothing on the canvas is running, or time
407
+ * runs out (false). dataflow starts queued runs in a microtask, and a
408
+ * queued run that can't start yet sits behind one that is running, so
409
+ * "nothing running" a task after a change means everything has settled.
410
+ * Woken by the canvas's run state changes (src/model/flow-idle.js), never
411
+ * by polling a timer: a hidden tab runs timers once a second, or once a
412
+ * minute, and agents often drive a page from a background tab. Only
413
+ * the deadline is a timer.
414
+ */
415
+ async function waitFor(c, timeoutMs, done = () => false) {
416
+ if (!timeoutMs || !c.trusted.value) return true;
417
+ const stop = new AbortController();
418
+ const timer = setTimeout(() => stop.abort(), timeoutMs);
419
+ try {
420
+ // A pane held at a person's breakpoint won't move until someone resumes it: return early (false) rather than
421
+ // block to the deadline. The tool's result then lists the stops (stoppedResult).
422
+ const breakpoints = c.root.ownBreakpoints;
423
+ const waits = [c.flow.until(done, { signal: stop.signal })];
424
+ if (breakpoints) waits.push(breakpoints.until(() => breakpoints.stops.size > 0, { signal: stop.signal }).then(() => false));
425
+ return await Promise.race(waits);
426
+ } finally {
427
+ clearTimeout(timer);
428
+ stop.abort(); // the loser stops listening
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Wait for pane `id` to finish the run that starts after this call (or for
434
+ * the canvas to go quiet). A skip that spreads to the pane settles it without
435
+ * a run: its version stays and only its runId moves.
436
+ */
437
+ function waitForPane(c, id, timeoutMs) {
438
+ const start = c.stateOf(id).value;
439
+ return waitFor(c, timeoutMs, () => {
440
+ const s = c.stateOf(id).value;
441
+ // An unchanged run (only pass changes) settles without a new version.
442
+ return (s.version > start.version && SETTLED.has(s.status)) || ((s.status === "skipped" || s.unchanged) && s.runId > start.runId);
443
+ });
444
+ }
445
+
446
+ const waitForAll = (c, timeoutMs) => waitFor(c, timeoutMs);
447
+
448
+ /** An audio pane's rendered WAV, described (from the value itself when the sandbox hands over a copy). */
449
+ async function mediaOf(c, id) {
450
+ const info = c.stateOf(id).value.result?.media ?? {};
451
+ let value;
452
+ try {
453
+ [value] = (await c.runtime.clone?.([id])) ?? [];
454
+ } catch {
455
+ // no copy: describe it from the run's numbers
456
+ }
457
+ const out = { type: info.type, duration: info.duration, sampleRate: info.sampleRate, channels: info.channels, bytes: info.bytes };
458
+ if (typeof info.peak === "number") out.peakDb = info.peak > 0 ? Math.round(200 * Math.log10(info.peak)) / 10 : null;
459
+ // "audio/wav 4.00 s, 689.1 kB · 44.1 kHz · stereo"
460
+ const format = describeRender(isMedia(value) ? value : info).split(" · ").slice(1).join(" · ");
461
+ out.description = isMedia(value) ? `${describeMedia(value)} · ${format}` : describeRender(info);
462
+ return out;
463
+ }
464
+
465
+ async function afterChange(c, id, { wait = true, timeoutMs = 10000 } = {}) {
466
+ const settled = wait ? await waitForPane(c, id, timeoutMs) : true;
467
+ const out = await detail(c, id, { depth: 3, maxLength: 2000 });
468
+ delete out.rect;
469
+ if (!c.trusted.value) out.note = "The canvas is paused (it came from a link or file): nothing runs until the person presses \"Run it\".";
470
+ else if (!settled) out.note = `Still running after ${timeoutMs} ms; check again with mallory_get_pane.`;
471
+ else if (out.stale || (out.autorun === false && out.status === "idle")) out.note = "This is a click-to-run pane (autorun off): run it with mallory_run_pane.";
472
+ return out;
473
+ }
474
+
475
+ /** mallory_add_pane { library }: a pane of an installed package as a linked subgraph pane (src/model/links.js), its inputs wired by name. */
476
+ async function addLibraryPane(c, args) {
477
+ if (args.type !== undefined && args.type !== "subgraph") throw new Error(`A package pane is a subgraph pane: leave out type (or pass "subgraph"), not "${args.type}".`);
478
+ const other = Object.keys(args).filter((k) => !["library", "type", "inputs", "x", "y", "width", "name", "wait", "timeoutMs"].includes(k));
479
+ if (other.length) throw new Error(`A package pane takes library, name, inputs, x, y and width (set its parameters afterwards with mallory_update_pane's params), not ${other.join(", ")}.`);
480
+ const ref = parsePanePath(args.library);
481
+ if (!ref) throw new Error(`"${args.library}" isn't "<package>/<pane>" (see mallory_list_library).`);
482
+ const found = host.packagePane?.(ref);
483
+ if (!found) throw new Error(`"${args.library}" isn't an installed package pane (see mallory_list_library). Installing packages is the person's ("Pane packages…").`);
484
+ if (found.flagged) throw new Error(`${ref.package} is flagged (${found.flagged}): ask the person to reinstall it.`);
485
+ const sources = resolveInputs(visible(c), args.inputs ?? []);
486
+ const at = args.x !== undefined && args.y !== undefined ? { x: args.x, y: args.y } : { ...placeNear(c, sources.map((s) => s.source), { width: args.width }), ...(args.x !== undefined ? { x: args.x } : {}), ...(args.y !== undefined ? { y: args.y } : {}) };
487
+ const id = insertLinked(c, found.doc, at);
488
+ const patch = {};
489
+ if (args.name !== undefined) patch.name = sanitizeName(args.name, c.panes.get(id).name);
490
+ if (args.width !== undefined) patch.width = Math.round(args.width);
491
+ if (sources.length) patch.inputs = sources.map(({ source, name }) => ({ name: sanitizeName(name ?? c.panes.get(source).name, "value"), source }));
492
+ if (Object.keys(patch).length) c.update(id, patch);
493
+ host.select?.(id);
494
+ const out = await afterChange(c, id, args);
495
+ return { inserted: `${ref.package}/${ref.pane}`, version: found.doc.package?.version, ...out };
496
+ }
497
+
498
+ /** Where a new pane goes: right of its sources, else below every pane; on the person's grid (square or polar) as a drag would put it. */
499
+ function placeNear(c, sources, size = {}) {
500
+ const place = (p) => placeOnGrid(host, c, p, size);
501
+ const rects = c.visible.map((id) => c.rectOf(id)).filter(Boolean);
502
+ if (sources.length) {
503
+ const r = sources.map((s) => c.rectOf(s)).filter(Boolean);
504
+ if (r.length) return place({ x: Math.max(...r.map((q) => q.x + q.width)) + 60, y: Math.min(...r.map((q) => q.y)) });
505
+ }
506
+ if (!rects.length) return place({ x: 0, y: 0 });
507
+ return place({ x: Math.min(...rects.map((q) => q.x)), y: Math.max(...rects.map((q) => q.y + (q.height || 160))) + 40 });
508
+ }
509
+
510
+ /** The inner pane ids a subgraph pane's `composite` list names (ids or names), or a readable refusal. */
511
+ function compositeIds(pane, given) {
512
+ const names = Array.isArray(given) ? given : [];
513
+ const inner = graphPanes(pane);
514
+ return names.map((ref) => {
515
+ const hit = inner.find((p) => p.id === ref) ?? inner.find((p) => p.name === ref);
516
+ if (!hit) throw new Error(`composite: no pane “${ref}” inside ${pane.name || pane.id} (inside: ${inner.map((p) => p.name || p.id).join(", ") || "nothing"}).`);
517
+ return hit.id;
518
+ });
519
+ }
520
+
521
+ /**
522
+ * The content change for a pane of `type` from a tool's arguments. A
523
+ * setting the type doesn't have is refused (the types come from their
524
+ * records, src/panes/); module, useDefault and widget are only checked
525
+ * here (the tools merge them with the pane's).
526
+ */
527
+ function contentPatch(type, args, current) {
528
+ // A css-signals list: the reason in the tool's words. The audio pane is a pane of this canvas, by name or id.
529
+ const cleanSignalsArg = (list) => {
530
+ try {
531
+ return cleanSignals(list);
532
+ } catch (error) {
533
+ throw new Error(`signals: ${error.message}.`);
534
+ }
535
+ };
536
+ const audioPaneArg = (ref) => {
537
+ const found = find(canvas(), ref);
538
+ if (found.type !== "audio") throw new Error(`signalsAudio: "${ref}" isn't an audio pane.`);
539
+ return found.id;
540
+ };
541
+ const patch = {};
542
+ for (const { key, types, refuse } of PANE_FIELDS) {
543
+ if (args[key] === undefined) continue;
544
+ if (!types.includes(type)) throw new Error(refuse(type));
545
+ if (key === "name") patch.name = args.name.trim();
546
+ else if (key === "url") patch[type === "media" ? "media" : "url"] = type === "media" ? mediaFromUrlArg(args.url) : args.url;
547
+ else if (key === "each" && type === "subgraph") patch.each = repeatPatch(current, args.each);
548
+ else if (key === "each") {
549
+ const theirs = ["templateBy", "templates", "removal", "graceMs", "collect"].filter((k) => k in args.each);
550
+ if (theirs.length) throw new Error(`${listWords(theirs)}: a repeater's (a subgraph pane with for each), not an eval pane's.`);
551
+ patch.each = { ...(current?.each ?? { on: true, input: "", parallel: true, max: 0 }), ...args.each };
552
+ }
553
+ else if (key === "dsp") patch.dsp = args.dsp === null ? undefined : cleanDsp(args.dsp); // a DSP patch (src/audio/patch.js): the whole patch, checked; throws the reason
554
+ else if (key === "render" || key === "audio") {
555
+ patch[key] = { ...(current?.[key] ?? {}), ...args[key] }; // only the keys passed change
556
+ // Sending takes to other panes, keeping them in the browser and recording the microphone are the person's settings (src/audio/takes.js): an agent's record edit neither turns them on nor off.
557
+ if (key === "audio" && args.audio.record && typeof args.audio.record === "object") patch.audio.record = agentRecordEdit(current?.audio?.record, args.audio.record);
558
+ }
559
+ else if (key === "shader") {
560
+ const problems = checkShaderSettings(args.shader);
561
+ if (problems.length) throw new Error(`${problems.join("; ")}.`);
562
+ const next = { ...(current?.shader ?? {}), ...args.shader }; // only the keys passed change
563
+ if ("t" in args.shader && !("frame" in args.shader)) delete next.frame; // a new t sets the frame (round(t × fps)), unless the frame is given
564
+ patch.shader = next;
565
+ } else if (key === "uniforms") {
566
+ const problems = checkUniforms(args.uniforms).map((p) => p.message);
567
+ if (problems.length) throw new Error(`${problems.join("; ")}.`);
568
+ patch.uniforms = normalizeUniforms(args.uniforms); // defaults filled in, so the saved canvas says every range
569
+ } else if (key === "buffers") {
570
+ const uniforms = (Array.isArray(args.uniforms) ? args.uniforms : Array.isArray(current?.uniforms) ? current.uniforms : []).map((u) => u?.name);
571
+ const problems = [...checkBuffers(args.buffers, { uniforms }).map((p) => p.message), ...checkImageBuffers(args.channels ?? current?.channels, args.buffers).map((p) => p.message)];
572
+ if (problems.length) throw new Error(`${problems.join("; ")}.`);
573
+ patch.buffers = normalizeBuffers(args.buffers, { uniforms }); // defaults filled in (float unless byte), in the order they run
574
+ } else if (key === "common") {
575
+ const problems = checkCommon(args.common).map((p) => p.message);
576
+ if (problems.length) throw new Error(`${problems.join("; ")}.`);
577
+ patch.common = args.common;
578
+ } else if (key === "channels") {
579
+ const uniforms = (Array.isArray(args.uniforms) ? args.uniforms : Array.isArray(current?.uniforms) ? current.uniforms : []).map((u) => u?.name);
580
+ const problems = checkChannels(args.channels, { uniforms }).map((p) => p.message);
581
+ if (problems.length) throw new Error(`${problems.join("; ")}.`);
582
+ patch.channels = normalizeChannels(args.channels, { uniforms }); // defaults filled in, so the saved canvas says every filter and wrap
583
+ }
584
+ else if (key === "strict") {
585
+ // Strict mode (src/runtime/strict.js): true or {} on with the defaults, an object changes only the keys passed, false or null off.
586
+ if (args.strict === null || args.strict === false) patch.strict = undefined;
587
+ else {
588
+ const next = args.strict === true ? { ...(current?.strict ?? {}) } : { ...(current?.strict ?? {}), ...args.strict };
589
+ const problems = strictProblems(next);
590
+ if (problems.length) throw new Error(`${problems.join("; ")}.`);
591
+ patch.strict = next;
592
+ if (current?.ownWorker) patch.ownWorker = undefined; // strict and its own Worker are two isolations: one at a time
593
+ }
594
+ }
595
+ else if (key === "selection") {
596
+ const problem = selectionProblem(args.selection);
597
+ if (problem) throw new Error(problem);
598
+ patch.selection = args.selection === null ? undefined : { ...(current?.selection ?? {}), ...args.selection }; // a select pane's settings: only the keys passed change, null resets
599
+ }
600
+ else if (key === "profile") {
601
+ // The profile view's settings: a part the view can't use is refused here, not dropped when the view runs. null and {} go back to the defaults.
602
+ const problems = profileProblems(args.profile);
603
+ if (problems.length) throw new Error(problems.join(" "));
604
+ patch.profile = cleanProfileSettings(args.profile);
605
+ }
606
+ else if (key === "plot") {
607
+ // The plot view's settings: refused here when a part can't be used, null and {} go back to every numeric column on one axis.
608
+ const problems = plotProblems(args.plot);
609
+ if (problems.length) throw new Error(problems.join(" "));
610
+ patch.plot = cleanPlotSettings(args.plot);
611
+ }
612
+ else if (key === "score") {
613
+ // A whole Score: refused with the validator's message when it isn't one (src/model/score-edit.js).
614
+ const problem = scoreProblem({ score: args.score });
615
+ if (problem) throw new Error(`score: ${problem}.`);
616
+ patch.score = args.score;
617
+ }
618
+ else if (key === "edit") {
619
+ // One named edit command on the pane's score (add notes, transpose, quantize, set tempo…): the new score, or the reason it can't be.
620
+ const base = patch.score ?? current?.score ?? agentStartScore();
621
+ try {
622
+ patch.score = applyEdit(base, args.edit).score;
623
+ } catch (error) {
624
+ throw new Error(`edit: ${error.message}`);
625
+ }
626
+ }
627
+ else if (key === "sprite") {
628
+ // The effects pane's sprite source: only the keys passed change, null removes it; checked here, not when it runs.
629
+ const next = args.sprite === null ? null : { ...(current?.sprite ?? {}), ...args.sprite };
630
+ const problem = spriteProblems(next);
631
+ if (problem) throw new Error(`${problem}.`);
632
+ patch.sprite = next ?? undefined;
633
+ } else if (key === "gif") {
634
+ const next = { ...(current?.gif ?? {}), ...args.gif };
635
+ try {
636
+ gifPlan(next, { width: 1, height: 1 }); // the limits that don't depend on the picture
637
+ } catch (error) {
638
+ throw new Error(`gif: ${error.message}.`);
639
+ }
640
+ patch.gif = next;
641
+ } else if (key === "transition") {
642
+ const problem = transitionProblem(args.transition);
643
+ if (problem) throw new Error(`${problem}.`);
644
+ patch.transition = String(args.transition ?? "").trim() || undefined;
645
+ } else if (key === "define") {
646
+ const problem = customProblems(args.define);
647
+ if (problem) throw new Error(`${problem}.`);
648
+ patch.define = args.define || undefined; // "" and null remove the custom effects
649
+ }
650
+ else if (key === "signals") patch.signals = args.signals === null || !args.signals.length ? undefined : cleanSignalsArg(args.signals); // css-signals sources (src/runtime/frame-signals.js): [] or null publishes none
651
+ else if (key === "signalsAudio") patch.signalsAudio = args.signalsAudio === null || args.signalsAudio === "" ? undefined : audioPaneArg(args.signalsAudio); // the audio pane the audio signal reads
652
+ else if (key === "persist") patch.persist = persistContent(args.persist); // "session" clears it
653
+ else if (key === "context") patch.context = contextContent(args.context); // "" stops sharing it
654
+ else if (key === "key") patch.key = args.key.trim() || undefined; // a state pane's item key: "" is the default, id
655
+ else if (key === "onError") patch.onError = cleanErrorPolicy(args.onError); // {} (or nothing left) is the default policy
656
+ else if (key === "watch") patch.watch = args.watch.map((ref) => find(canvas(), ref).id);
657
+ else if (key === "timer") patch.timer = timerPatch(current?.timer, args.timer, canvas().timerClock?.now?.() ?? Date.now());
658
+ else if (key === "device") patch.device = devicePatch(current?.device, args.device, canvas(), find);
659
+ else if (key === "automation") patch.automation = automationPatch(current?.automation, args.automation);
660
+ else if (key === "waitFor") patch.waitFor = waitPatch(current?.waitFor, args.waitFor);
661
+ else if (key === "decide") patch.decide = decidePatch(current?.decide, args.decide);
662
+ else if (key === "queueBytes" || key === "queueExpireMs" || key === "queuePolicy") {
663
+ // An event reader's queue budgets: null, and drop-oldest, are the defaults (nothing is saved).
664
+ const problem = { queueBytes: queueBytesProblem, queueExpireMs: queueExpireProblem, queuePolicy: queuePolicyProblem }[key](args[key]);
665
+ if (problem) throw new Error(`${problem}.`);
666
+ patch[key] = args[key] === null || args[key] === DEFAULT_POLICY ? undefined : args[key];
667
+ }
668
+ else if (key === "gate") patch.gate = gatePatch(current?.gate, args.gate);
669
+ else if (key === "chart") patch.chart = chartPatch(current?.chart, args.chart);
670
+ else if (key === "scene") patch.scene = scenePatch(current?.scene, args.scene);
671
+ else if (key === "codec") patch.codec = codecPatch(current?.codec, args.codec);
672
+ else if (key === "http") patch.http = httpPatch(current?.http, args.http);
673
+ else if (key === "sample") patch.sample = mergedSettings(current?.sample, args.sample, (m) => (sampleProblem(m) ? sampleProblem(m) : ""));
674
+ else if (key === "ledger") patch.ledger = agentLedgerPatch(current?.ledger, args.ledger); // an agent proposes, a person signs: nothing else is accepted
675
+ else if (key === "goals") patch.goals = agentGoalsPatch(current?.goals, args.goals); // an agent proposes, a person accepts: `items` is refused
676
+ else if (key === "verdict") patch.verdict = (() => {
677
+ const merged = mergeVerdict(current?.verdict, args.verdict);
678
+ const problem = verdictProblem(merged);
679
+ if (problem) throw new Error(`${problem}.`);
680
+ return merged;
681
+ })();
682
+ else if (key === "graph") {
683
+ const problem = graphProblem(args.graph); // what a reload would refuse: an oversize edge list, positions that aren't pairs
684
+ if (problem) throw new Error(`graph: ${problem}.`);
685
+ patch.graph = args.graph;
686
+ }
687
+ else if (key === "geometry") {
688
+ const problem = geometrySettingsProblem({ geometry: args.geometry }); // what a reload would refuse: a cycle, a dangling id, a bad colour, mode or unit
689
+ if (problem) throw new Error(`geometry: ${problem}.`);
690
+ patch.geometry = args.geometry;
691
+ }
692
+ else if (key === "traffic") patch.traffic = mergedSettings(current?.traffic, args.traffic, (m) => (trafficProblem(m) ? `traffic: ${trafficProblem(m)}` : ""));
693
+ else if (key === "ws") patch.ws = wsPatch(current?.ws, args.ws);
694
+ else if (key === "actionMap") patch.actionMap = actionMapPatch(current?.actionMap, args.actionMap);
695
+ else if (key === "inputLog") patch.inputLog = inputLogPatch(current?.inputLog, args.inputLog);
696
+ else if (key === "color" && !isColor(args.color)) throw new Error(`A note's color is one of ${COLORS.join(", ")}, or "#rrggbb".`);
697
+ else if (key === "params") {
698
+ // Only the names passed change; null takes one back to its port's own value.
699
+ const next = { ...(current?.params ?? {}) };
700
+ for (const [name, value] of Object.entries(args.params)) value === null ? delete next[name] : (next[name] = value);
701
+ patch.params = Object.keys(next).length ? next : undefined;
702
+ }
703
+ else if (key === "composite") {
704
+ // Show or hide the composite view: a boolean here; a list of inner panes chooses them, which update_pane does after the patch (compositeIds).
705
+ if (typeof args.composite === "boolean") patch.composite = args.composite ? true : undefined;
706
+ else if (!current) throw new Error("composite: add the pane first, then choose its panes with mallory_update_pane's composite: [pane names].");
707
+ else compositeIds(current, args.composite); // refuses a name that isn't inside
708
+ }
709
+ else if (key === "promote") {
710
+ // Promote free parameters to the canvas around: done by update_pane after the patch (promoteControl); checked first so nothing changes on a refusal.
711
+ if (!current) throw new Error("promote: add the pane first, then promote its parameters with mallory_update_pane's promote: [names].");
712
+ if (!Array.isArray(args.promote) || !args.promote.length) throw new Error("promote: a list of parameter names.");
713
+ for (const name of args.promote) planPromote(canvas(), current.id, name);
714
+ }
715
+ else if (key === "webhook") patch.webhook = mergedSettings(current?.webhook, args.webhook, webhookProblem);
716
+ else if (key === "respond") patch.respond = mergedSettings(current?.respond, args.respond, respondProblem);
717
+ else if (key === "router") patch.router = mergedSettings(current?.router, args.router, routerProblem);
718
+ else if (key === "companion") patch.companion = mergedSettings(current?.companion, args.companion, companionProblem);
719
+ else if (key === "files") patch.files = mergedSettings(current?.files, args.files, watchProblem);
720
+ else if (key === "outputs") {
721
+ validateOutputs(args.outputs, "outputs"); // a readable refusal rather than a quietly dropped output
722
+ patch.outputs = cleanOutputs(args.outputs) ?? [];
723
+ } else if (key === "control") patch.control = mergeControl(current?.control, args.control); // how a control is organized: draws differently, runs nothing
724
+ else if (key === "valueType") {
725
+ if (args.valueType !== null && typeProblem(args.valueType)) throw new Error(`valueType: ${typeProblem(args.valueType)}.`);
726
+ patch.valueType = args.valueType === null ? undefined : cleanType(args.valueType);
727
+ } else if (key === "switch") patch.switch = args.switch === null ? undefined : cleanSwitch(args.switch);
728
+ else if (key === "split") {
729
+ if (args.split === null) patch.split = undefined;
730
+ else {
731
+ const merged = { ...(current?.split ?? {}), ...args.split }; // only the keys passed change; branches replace the whole list
732
+ const problem = splitProblem(merged);
733
+ if (problem) throw new Error(`split: ${problem}.`);
734
+ patch.split = cleanSplit(merged);
735
+ }
736
+ }
737
+ else if (key === "receive") {
738
+ validateReceive(args.receive); // a named event channel: a readable refusal
739
+ patch.receive = args.receive === null ? undefined : cleanReceive(args.receive);
740
+ }
741
+ else if (!["module", "useDefault", "widget"].includes(key)) patch[key] = args[key];
742
+ }
743
+ // Caps (a record's lowerOnly): lowered, or set where there was none, never raised or removed.
744
+ for (const key of paneType(type)?.lowerOnly ?? []) {
745
+ if (args[key] === undefined) continue;
746
+ const problem = lowerOnlyProblem(key, args[key], current?.[key]);
747
+ if (problem) throw new Error(problem);
748
+ }
749
+ const editProblem = paneType(type)?.editProblem?.(args, current);
750
+ if (editProblem) throw new Error(editProblem);
751
+ return patch;
752
+ }
753
+
754
+ /**
755
+ * A repeater's `each` (src/model/repeater.js) from update_pane's: merged into
756
+ * the pane's, templates named by a function canvas (name or id) or a package
757
+ * pane ("<package>/<pane>") resolved to linked templates (null removes one).
758
+ */
759
+ function repeatPatch(current, given) {
760
+ const own = ["parallel", "ratePerMinute", "recover", "match", "inputs", "matchKey", "unmatched", "crossMax", "shape"].filter((k) => k in given);
761
+ if (own.length) throw new Error(`${listWords(own)}: an eval pane's for-each setting; a repeater's instances all run at once.`);
762
+ const problem = repeatProblem(given);
763
+ if (problem) throw new Error(problem);
764
+ const base = current?.each && typeof current.each === "object" ? current.each : {};
765
+ const next = { ...base, ...given };
766
+ if (given.on && base.key === undefined && given.key === undefined) next.key = "id"; // items named by id unless a key is given
767
+ if ("templates" in given) {
768
+ const templates = { ...(base.templates ?? {}) };
769
+ for (const [name, ref] of Object.entries(given.templates ?? {})) {
770
+ if (ref === null) {
771
+ delete templates[name];
772
+ continue;
773
+ }
774
+ const path = parsePanePath(ref);
775
+ let doc;
776
+ if (path && String(ref).includes("/")) {
777
+ const found = host.packagePane?.(path);
778
+ if (!found) throw new Error(`templates.${name}: "${ref}" isn't an installed package pane (see mallory_list_library).`);
779
+ if (found.flagged) throw new Error(`templates.${name}: ${path.package} is flagged (${found.flagged}): ask the person to reinstall it.`);
780
+ doc = found.doc;
781
+ } else {
782
+ const entry = findSaved(String(ref));
783
+ doc = host.loadCanvas?.(entry.id);
784
+ if (!doc) throw new Error(`templates.${name}: that canvas isn't saved in this browser.`);
785
+ if (doc.trusted === false) throw new Error(`templates.${name}: "${doc.name}" came from a link or file and hasn't been run: ask the person to review it first.`);
786
+ }
787
+ templates[name] = linkedTemplate(canvas(), doc); // refuses a loop
788
+ }
789
+ next.templates = templates;
790
+ }
791
+ const clean = normalizeRepeat(next);
792
+ return {
793
+ on: clean.on,
794
+ input: clean.input,
795
+ max: clean.max,
796
+ key: clean.key ?? "",
797
+ ...(clean.batch ? { batch: clean.batch } : {}),
798
+ ...(clean.templateBy ? { templateBy: clean.templateBy } : {}),
799
+ ...(clean.templates ? { templates: clean.templates } : {}),
800
+ ...(clean.removal !== "drop" ? { removal: clean.removal } : {}),
801
+ ...(clean.graceMs ? { graceMs: clean.graceMs } : {}),
802
+ ...(clean.collect !== "array" ? { collect: clean.collect } : {}),
803
+ ...(clean.expose ? { expose: clean.expose } : {}),
804
+ };
805
+ }
806
+
807
+ /**
808
+ * A pane's named event channels for get_pane: what it receives (and
809
+ * how many it got), what its code sends on (and how many it sent), and for a
810
+ * subgraph pane what is inside it. Undefined when it has none.
811
+ */
812
+ function channelsInfo(c, id, pane) {
813
+ const { receives, sends } = channelsOf(pane);
814
+ const log = c.root.channelLog;
815
+ const key = paneKey(c, id);
816
+ const mine = log?.of(key) ?? { sent: {}, received: 0 };
817
+ const found = Object.keys(mine.sent).filter((ch) => !sends.some((s) => s.channel === ch)); // sent by running, not as written
818
+ const inside = pane.type === "subgraph" ? channelsInside(pane) : { sends: [], receives: [] };
819
+ if (!receives && !sends.length && !found.length && !inside.sends.length && !inside.receives.length) return undefined;
820
+ return {
821
+ ...(receives ? { receives, received: mine.received, output: "received" } : {}),
822
+ ...(sends.length || found.length ? { sends: [...sends.map((s) => ({ ...s, sent: mine.sent[s.channel] ?? 0 })), ...found.map((ch) => ({ channel: ch, sent: mine.sent[ch], found: "by running" }))] } : {}),
823
+ ...(inside.sends.length || inside.receives.length
824
+ ? { inside: { sends: inside.sends.map(({ channel, scope, depth }) => ({ channel, scope, depth })), receives: inside.receives.map(({ channel, consume, depth }) => ({ channel, ...(consume ? { consume } : {}), depth })) } }
825
+ : {}),
826
+ };
827
+ }
828
+
829
+ /** A repeater for get_pane: its settings, instances (the first few, by key) and what the last change did. */
830
+ function repeaterInfo(c, id, pane) {
831
+ const each = normalizeRepeat(pane.each);
832
+ const list = instancesOf(c, id);
833
+ const live = list.filter((i) => i.state === "live");
834
+ const last = c.repeaters?.get(id)?.last ?? c.stateOf(id).value.result?.repeat;
835
+ const count = (s) => list.filter((i) => i.state === s).length;
836
+ return {
837
+ repeatsOver: c.repeaters?.get(id)?.listName ?? (each.input || "the first array input"),
838
+ key: each.key ?? "(by position)",
839
+ instances: live.length,
840
+ ...(count("leaving") ? { leaving: count("leaving") } : {}),
841
+ ...(count("kept") ? { keptForLater: count("kept") } : {}),
842
+ keys: live.slice(0, 50).map((i) => ({ key: i.key, index: i.index, status: i.status, ...(i.template ? { template: i.template } : {}) })),
843
+ ...(live.length > 50 ? { moreKeys: live.length - 50 } : {}),
844
+ ...(last ? { lastChange: last } : {}),
845
+ collect: each.collect,
846
+ removal: each.removal,
847
+ ...(each.graceMs ? { graceMs: each.graceMs } : {}),
848
+ ...(each.templateBy ? { templateBy: each.templateBy, templates: Object.fromEntries(Object.entries(each.templates ?? {}).map(([n, t]) => [n, t.ref?.package ? `${t.ref.package}/${t.ref.name}` : (t.ref?.name ?? t.name ?? n)])) } : {}),
849
+ ...templateUpdates(c, pane),
850
+ ...templateNotices(c, pane),
851
+ ...(each.expose ? { exposed: each.expose.map((e) => ({ output: e.name, reads: e.output ? `${e.pane}.${e.output}` : e.pane, value: "{ <item key>: its value in that instance }" })) } : {}),
852
+ itemEvents: itemEventsInfo(c, id, pane, each),
853
+ open: "mallory_open_subgraph with instance: <key> views one instance (edits there aren't kept); without it, the template.",
854
+ };
855
+ }
856
+
857
+ /** A repeater's linked templates whose source changed, for get_pane: `{ templateUpdates: [key] }`, or {}. */
858
+ function templateUpdates(c, pane) {
859
+ const where = linkWhere(c);
860
+ const keys = templatesOf(pane).filter(({ content }) => linkStatus(content, where)?.update).map((t) => t.key);
861
+ return keys.length ? { templateUpdates: keys, update: "mallory_update_linked with templateKey: <key> shows what changed; accept: true uses it" } : {};
862
+ }
863
+
864
+ /** A repeater's linked templates whose package pane is deprecated, for get_pane: `{ templateDeprecated: { <key>: notice } }`, or {}. */
865
+ function templateNotices(c, pane) {
866
+ const where = linkWhere(c);
867
+ const found = templatesOf(pane).flatMap(({ key, content }) => {
868
+ const dep = linkStatus(content, where)?.deprecated;
869
+ return dep ? [[key, noticeWithReplacement(dep, content.ref.pane)]] : [];
870
+ });
871
+ return found.length ? { templateDeprecated: Object.fromEntries(found), moveIt: "mallory_update_linked with templateKey: <key> and replace: true previews moving that template to its replacement; accept: true does it (when the replacement is installed)" } : {};
872
+ }
873
+
874
+ /**
875
+ * update_linked with `templateKey` and `replace`: a repeater template's move to
876
+ * the replacement its author names, previewed, or (accept) applied only when
877
+ * the replacement is already installed. As replaceDeprecated; installing is the person's.
878
+ */
879
+ async function replaceDeprecatedTemplate(c, p, args) {
880
+ const key = String(args.templateKey);
881
+ const found = templatesOf(p).find((t) => t.key === key);
882
+ if (!found) throw new Error(`"${p.name || p.id}" has no linked template "${key}"${templatesOf(p).length ? ` (its templates: ${templatesOf(p).map((t) => t.key).join(", ")})` : ""}.`);
883
+ const { ref } = found.content;
884
+ const source = linkSource(ref, linkWhere(c));
885
+ const dep = deprecationOfDoc(source?.doc);
886
+ const label = { pane: p.name || p.id, template: key };
887
+ if (!dep) return { ...label, deprecated: false, note: "Its package doesn't mark this template's pane as deprecated." };
888
+ const rep = replacementFor(dep, ref.pane, { installed: (name) => (host.listPackages?.() ?? []).some((e) => e.name === name && e.pkg), source: (r) => host.packagePane?.(r) });
889
+ const notice = noticeWithReplacement(dep, ref.pane);
890
+ if (!rep) return { ...label, deprecated: notice, note: "Its author names no replacement." };
891
+ if (rep.state !== "ready") {
892
+ const why = `The replacement ${rep.path} is ${REPLACEMENT_WORDS[rep.state]}.`;
893
+ if (args.accept) throw new Error(`${why} Installing or reinstalling a package is the person's decision ("Pane packages…"): tell them. Nothing was changed.`);
894
+ return { ...label, deprecated: notice, note: `${why} Nothing can be previewed; tell the person.` };
895
+ }
896
+ const plan = planTemplateReplace(p, key, rep.doc, { rootId: c.root.id });
897
+ const preview = {
898
+ replacement: rep.path,
899
+ inputs: plan.ports,
900
+ ...(plan.flagged.length ? { wiresThisTemplateNoLongerTakes: plan.flagged.map((f) => f.name) } : {}),
901
+ ...(plan.lostOutputs.length ? { exposedPanesGone: plan.lostOutputs.map((o) => `${o.name} (${o.pane})`) } : {}),
902
+ diff: formatDiff(diffCanvases({ panes: found.content.graph.panes }, { panes: plan.graph.panes })),
903
+ };
904
+ if (!args.accept) return { ...label, deprecated: notice, replace: preview, accept: "mallory_update_linked with templateKey, replace: true and accept: true does it (one undo step; a snapshot first): every instance of the template follows in place." };
905
+ await host.beforeLinkUpdate?.(); // a snapshot of the canvas as it was
906
+ acceptTemplateReplacement(c, p.id, key, rep.doc);
907
+ const out = await afterChange(c, p.id, args);
908
+ return { replaced: p.name || p.id, template: key, with: rep.path, ...preview, ...out };
909
+ }
910
+
911
+ /** update_linked with `templateKey`: a repeater's linked template, reviewed or accepted. */
912
+ async function updateTemplate(c, p, args) {
913
+ const key = String(args.templateKey);
914
+ if (args.detach) throw new Error("A template can't be detached: remove it with mallory_update_pane each.templates { <key>: null }, or edit the canvas it follows.");
915
+ const found = templatesOf(p).find((t) => t.key === key);
916
+ if (!found) throw new Error(`"${p.name || p.id}" has no linked template "${key}"${templatesOf(p).length ? ` (its templates: ${templatesOf(p).map((t) => t.key).join(", ")})` : ""}.`);
917
+ const { ref } = found.content;
918
+ const source = linkSource(ref, linkWhere(c));
919
+ const label = { pane: p.name || p.id, template: key };
920
+ if (!source) return { ...label, linkedTo: ref.name, update: false, note: `"${ref.name}" isn't saved in this browser and the canvas carries no other version: the template runs its own copy.` };
921
+ if (source.hash === ref.hash) return { ...label, linkedTo: source.doc.name, update: false, note: "It uses the latest version." };
922
+ const plan = planTemplateUpdate(p, key, source.doc, { rootId: c.root.id });
923
+ const changes = { from: source.from === "canvas" ? "the saved canvas" : source.from === "package" ? "the installed package" : "this canvas's library (it came with its file or link)", inputs: plan.ports, ...(plan.flagged.length ? { wiresThisTemplateNoLongerTakes: plan.flagged.map((f) => f.name) } : {}), ...(plan.lostOutputs.length ? { exposedPanesGone: plan.lostOutputs.map((o) => `${o.name} (${o.pane})`) } : {}), diff: formatDiff(diffCanvases({ panes: found.content.graph.panes }, { panes: plan.graph.panes })) };
924
+ if (!args.accept) return { ...label, linkedTo: source.doc.name, update: true, changes, accept: "mallory_update_linked with templateKey and accept: true uses it: every instance of it follows in place." };
925
+ if (!["canvas", "package"].includes(source.from) || !source.trusted) throw new Error(source.flagged ? `The installed ${ref.package} is flagged (${source.flagged}): ask the person to reinstall it.` : `This version of "${source.doc.name}" came with a file or link and hasn't been run: ask the person to review it and press "use new version" on the repeater.`);
926
+ await host.beforeLinkUpdate?.(); // a snapshot of the canvas as it was
927
+ acceptTemplateUpdate(c, p.id, key, source.doc);
928
+ const out = await afterChange(c, p.id, args);
929
+ return { updated: p.name || p.id, template: key, linkedTo: source.doc.name, changes, ...out };
930
+ }
931
+
932
+ /**
933
+ * update_linked with `replace`: a deprecated package pane's move to the
934
+ * replacement its author names. Without `accept` it previews (inputs matched by
935
+ * name and type); with it, it applies only when the replacement is already
936
+ * installed and not flagged. Installing a package is the person's (WHY_NOT.PACKAGES).
937
+ */
938
+ async function replaceDeprecated(c, p, args) {
939
+ const source = linkSource(p.ref, linkWhere(c));
940
+ const dep = deprecationOfDoc(source?.doc);
941
+ const label = { pane: p.name || p.id };
942
+ if (!dep) return { ...label, deprecated: false, note: "Its package doesn't mark this pane as deprecated." };
943
+ const rep = replacementFor(dep, p.ref.pane, { installed: (name) => (host.listPackages?.() ?? []).some((e) => e.name === name && e.pkg), source: (ref) => host.packagePane?.(ref) });
944
+ const notice = noticeWithReplacement(dep, p.ref.pane);
945
+ if (!rep) return { ...label, deprecated: notice, note: "Its author names no replacement." };
946
+ if (rep.state !== "ready") {
947
+ const why = `The replacement ${rep.path} is ${REPLACEMENT_WORDS[rep.state]}.`;
948
+ if (args.accept) throw new Error(`${why} Installing or reinstalling a package is the person's decision ("Pane packages…"): tell them. Nothing was changed.`);
949
+ return { ...label, deprecated: notice, note: `${why} Nothing can be previewed; tell the person.` };
950
+ }
951
+ const plan = planReplace(p, rep.doc, { rootId: c.root.id, panes: [...c.attached].map((pid) => c.panes.get(pid)).filter(Boolean) });
952
+ const preview = {
953
+ replacement: rep.path,
954
+ inputs: plan.ports.map((x) => ({ name: x.name, status: x.status, type: x.from, ...(x.status === "retyped" ? { nowTakes: x.to } : {}), ...(x.wired ? { wired: true } : {}), ...(x.wireFits === false ? { wireCarries: x.wireType, wireMismatch: true } : {}) })),
955
+ ...(plan.settings.some((x) => x.status !== "kept") ? { settings: plan.settings.filter((x) => x.status !== "kept").map((x) => ({ name: x.name, status: x.status, ...(x.to ? { nowTakes: x.to } : {}) })) } : {}),
956
+ ...(plan.outputsAdded.length ? { outputsAdded: plan.outputsAdded } : {}),
957
+ ...(plan.outputsRemoved.length ? { outputsRemoved: plan.outputsRemoved } : {}),
958
+ ...(plan.readers.some((r) => r.status !== "same") ? { readersAffected: plan.readers.filter((r) => r.status !== "same").map((r) => ({ pane: r.name, input: r.input, output: r.output, status: r.status, ...(r.to ? { nowGets: r.to } : {}) })) } : {}),
959
+ ...(plan.added.length ? { newInputsUnwired: plan.added } : {}),
960
+ ...(plan.droppedParams.length ? { parametersDropped: plan.droppedParams } : {}),
961
+ ...(plan.flagged.length ? { wiresToNoInput: plan.flagged.map((f) => f.name) } : {}),
962
+ ...(plan.lostOutputs.length ? { outputsNoLongerMade: plan.lostOutputs.map((o) => o.name) } : {}),
963
+ diff: formatDiff(diffCanvases({ panes: p.graph?.panes ?? [] }, { panes: plan.graph.panes })),
964
+ };
965
+ if (!args.accept) return { ...label, deprecated: notice, replace: preview, accept: "mallory_update_linked with replace: true and accept: true does it (one undo step; a snapshot first). Nothing is rewired for you." };
966
+ await host.beforeLinkUpdate?.(); // a snapshot of the canvas as it was
967
+ acceptReplacement(c, p.id, rep.doc);
968
+ const out = await afterChange(c, p.id, args);
969
+ return { replaced: p.name || p.id, with: rep.path, ...preview, ...out };
970
+ }
971
+
972
+ /** A repeater's item events for get_pane: its event output, what can send on it (the templates' event outputs) and what reads it. */
973
+ function itemEventsInfo(c, id, pane, each) {
974
+ const from = new Set();
975
+ for (const t of [pane, ...Object.values(each.templates ?? {})]) for (const p of graphPanes(t)) for (const o of outputsOf(p)) if (o.type === "event") from.add(`${p.name || p.id}.${o.name}`);
976
+ const readers = c.flow.dependents(`${id}#${ITEM_EVENTS}`).map((d) => nameOf(c, d.includes("##") ? d.slice(0, d.indexOf("##")) : d));
977
+ return {
978
+ output: ITEM_EVENTS,
979
+ carries: "{ key, name, payload, index, pane, removing?, value? }: one event per event an instance's panes send (name is their event output's), queued in order, never coalesced; an instance in its grace period sends with removing: true, a kept (parked) one sends nothing",
980
+ from: [...from],
981
+ readBy: [...new Set(readers)],
982
+ ...(from.size ? {} : { note: "no pane in the template has an event output yet: give one an output of type event (emit.event('name', payload) in its code)" }),
983
+ };
984
+ }
985
+
986
+ // What the tool groups (src/webmcp/tools/*.js) share: the host and the helpers above.
987
+ const ctx = { host, canvas, visible, find, nameOf, requireTrusted, noticeWithReplacement, linkWhere, inputsOf, inputWords, outputsInfo, checkPort, typedInputs, routedInputs, summary, liveGroups, groupSummary, findGroup, detail, waitFor, waitForPane, waitForAll, mediaOf, afterChange, addLibraryPane, placeNear, compositeIds, contentPatch, repeatPatch, channelsInfo, repeaterInfo, templateUpdates, templateNotices, replaceDeprecatedTemplate, updateTemplate, replaceDeprecated, itemEventsInfo, savedCanvases, findSaved, lastResult, downstream, stoppedResult };
988
+ const tools = [coreTools, editTools, reshapeTools, subgraphsTools, liveTools, devicesTools, runsTools, trafficTools, machineTools, testsTools, versionsTools, mediaTools, canvasesTools].flatMap((group) => group(ctx));
989
+
990
+ /** A saved canvas by id or name (names may repeat: then the most recent). */
991
+ function savedCanvases() {
992
+ if (!host.listCanvases) throw new Error("Saved canvases aren't available here.");
993
+ return host.listCanvases();
994
+ }
995
+ function findSaved(ref) {
996
+ const list = savedCanvases();
997
+ const hit = list.find((e) => e.id === ref) ?? list.find((e) => e.name === ref) ?? list.find((e) => String(e.name).toLowerCase() === String(ref).toLowerCase());
998
+ if (!hit) throw new Error(`No saved canvas "${ref}". Saved: ${list.map((e) => `${e.name} (${e.id})`).join(", ") || "none"}.`);
999
+ return hit;
1000
+ }
1001
+
1002
+ function lastResult(test) {
1003
+ const r = host.testResult?.(test);
1004
+ if (r === "running") return { last: "running" };
1005
+ return r ? { last: resultText(r) } : {};
1006
+ }
1007
+
1008
+ async function downstream(c, id, args, extra = {}) {
1009
+ const timeoutMs = args.wait === false ? 0 : (args.timeoutMs ?? 10000);
1010
+ const ok = await waitForAll(c, timeoutMs);
1011
+ const out = { ...summary(c, id, { maxLength: 2000 }), ...extra };
1012
+ // Everything downstream, not just direct users, in run order.
1013
+ const seen = new Set();
1014
+ const visit = (from) => c.flow.dependents(from).forEach((d) => seen.has(d) || (seen.add(d), visit(d)));
1015
+ visit(id);
1016
+ const users = c.flow.order([...seen]).filter((d) => c.panes.has(d)); // not a named output's own node (pick#selected)
1017
+ if (users.length) out.downstream = users.map((d) => summary(c, d, { maxLength: 400 }));
1018
+ if (!ok) out.note = `Some panes were still running after ${timeoutMs} ms.`;
1019
+ if (!c.trusted.value) out.note = "The canvas is paused (it came from a link or file): nothing runs until the person presses \"Run it\".";
1020
+ return out;
1021
+ }
1022
+
1023
+ /**
1024
+ * A result whose wait ended with "still running" while panes are stopped at a person's breakpoint: say so, and list
1025
+ * the stops (the pane, what stopped it), instead of a timeout note. mallory_breakpoints has the inputs and resumes them.
1026
+ */
1027
+ function stoppedResult(c, result) {
1028
+ const b = c?.root?.ownBreakpoints;
1029
+ if (!b?.stops.size || !result || typeof result !== "object" || !/still (running|rendering|recording)/i.test(result.note ?? "")) return result;
1030
+ const stopped = b.list().map(({ stop, pane, name, stoppedBy }) => ({ stop, pane, name, stoppedBy }));
1031
+ return { ...result, note: `Stopped at a breakpoint (${stopped.map((s) => s.name).join(", ")}): the run waits for the person, or for mallory_breakpoints continue, step or skip. See \`stopped\`.`, stopped };
1032
+ }
1033
+
1034
+ // A run that a tool starts is the agent's in the run log ("agent mallory_update_pane"), and what it changes on the
1035
+ // canvas is one undo step, with words that say an agent made it (Canvas#agentStep).
1036
+ for (const spec of tools) {
1037
+ if (spec.readOnly) continue;
1038
+ const run = spec.run;
1039
+ spec.run = function (args) {
1040
+ const c = host.getCanvas();
1041
+ c?.hint?.(`agent ${PREFIX}${spec.name}`, { strong: true });
1042
+ let out;
1043
+ const call = () => (out = run.call(this, args));
1044
+ if (!c?.agentStep || NO_STEP.has(spec.name)) call();
1045
+ else {
1046
+ const label = (ref) => {
1047
+ try {
1048
+ return (find(c, ref).name || find(c, ref).id) ?? String(ref);
1049
+ } catch {
1050
+ return String(ref);
1051
+ }
1052
+ };
1053
+ const names = { pane: label(args?.pane ?? args?.id ?? args?.to), from: args?.from === undefined ? undefined : label(args.from), to: args?.to === undefined ? undefined : label(args.to) };
1054
+ const had = new Set(c.panes.keys());
1055
+ // The step is what the tool changes before it first awaits, so a person's edit while it waits is a step of its own (#469).
1056
+ // A tool that edits after an await (EDITS_AFTER_AWAIT) keeps its step open until it settles: it returns the promise agentStep makes.
1057
+ out = c.agentStep(() => agentWords(spec.name, args ?? {}, { ...names, added: [...c.panes].filter(([id]) => !had.has(id)).map(([, p]) => p.name || p.id) }), call, { late: EDITS_AFTER_AWAIT.has(spec.name) || Boolean(spec.late?.(args ?? {})) });
1058
+ }
1059
+ return out?.then ? out.then((r) => stoppedResult(host.getCanvas?.(), r)) : out;
1060
+ };
1061
+ }
1062
+ // Every tool call is an agent's: while one runs the canvas says so, and a replay pane (a request taken from a capture log) is never sent (src/model/runners/http-send.js).
1063
+ const asAgent = (tool) => {
1064
+ const inner = tool.handler;
1065
+ tool.handler = async function (args) {
1066
+ let leave = () => {};
1067
+ try {
1068
+ leave = enterAgentCall(host.getCanvas?.());
1069
+ } catch {
1070
+ /* no canvas open: nothing to mark */
1071
+ }
1072
+ try {
1073
+ return await inner.call(this, args);
1074
+ } finally {
1075
+ leave();
1076
+ }
1077
+ };
1078
+ return tool;
1079
+ };
1080
+ const RUNS = new Set(["mallory_run_all", "mallory_run_pane", "mallory_retry_failed"]); // the tools that run panes at once (a replay pane is never sent by them)
1081
+ return tools.map(toolFromSpec).map((t) => (RUNS.has(t.name) ? asAgent(t) : t));
1082
+ }
1083
+
1084
+ export const PREFIX = "mallory_";
1085
+
1086
+ const SETTLED = new Set(["done", "skipped", "error"]);
1087
+
1088
+ /**
1089
+ * A timer pane's settings after an agent's change: only the keys passed change; a schedule that can't run is refused. `when` (a once
1090
+ * timer's time as a phrase) is read now, against `now`, and the instant stored with it; a phrase that isn't understood is refused.
1091
+ */
1092
+ function timerPatch(current, change, now = Date.now()) {
1093
+ const { when, ...rest } = change ?? {};
1094
+ let merged = timerSettings({ ...(current ?? {}), ...rest });
1095
+ if (when !== undefined) {
1096
+ const read = setWhen(merged, when, { now });
1097
+ if (!read.ok) throw new Error(`timer: when "${String(when).trim()}": ${read.error}.`);
1098
+ merged = read.settings;
1099
+ }
1100
+ const problem = timerProblem(merged);
1101
+ if (problem) throw new Error(problem);
1102
+ return merged;
1103
+ }
1104
+
1105
+ /** An automation pane's timeline after an agent's change: only the keys passed change (lanes and cues are replaced as whole lists); a timeline that can't work is refused with every reason. */
1106
+ function automationPatch(current, change) {
1107
+ // A new duration alone pulls the keyframes and cues beyond it in to the end (as the pane's own length field does).
1108
+ const { duration: given, ...rest } = change ?? {};
1109
+ const duration = secondsOf(given); // words ("90 seconds") are read once
1110
+ const base = automationSettings(current ?? defaultAutomation());
1111
+ const start = duration !== undefined && Number.isFinite(duration) && duration > 0 && !("lanes" in rest) && !("cues" in rest) ? setDuration(base, duration).settings : { ...base, ...(duration !== undefined ? { duration } : {}) };
1112
+ const merged = { ...start, ...rest };
1113
+ const problems = automationProblems(merged, 4);
1114
+ if (problems.length) throw new Error(`automation: ${problems.join("; ")}.`);
1115
+ return automationSettings(merged);
1116
+ }
1117
+
1118
+ /** A wait pane's settings after an agent's change: only the keys passed change (a list replaces its list); settings that can't work are refused. */
1119
+ function waitPatch(current, change) {
1120
+ const merged = { ...(current ?? {}), ...change };
1121
+ const problem = waitProblem(merged);
1122
+ if (problem) throw new Error(`waitFor: ${problem}.`);
1123
+ return merged;
1124
+ }
1125
+
1126
+ /** A decision pane's settings after an agent's change: only the keys passed change (a list replaces its list); settings that can't work are refused. It describes the question; answering it is the person's. */
1127
+ function decidePatch(current, change) {
1128
+ const merged = { ...(current ?? {}), ...change };
1129
+ const problem = decideProblem(merged);
1130
+ if (problem) throw new Error(`decide: ${problem}.`);
1131
+ return merged;
1132
+ }
1133
+
1134
+ /** A time-window gate's settings after an agent's change: only the keys passed change; a window that can't work (no such zone, start equal to end) is refused. */
1135
+ function gatePatch(current, change) {
1136
+ const merged = { ...(current ?? {}), ...change };
1137
+ const problem = gateProblem(merged);
1138
+ if (problem) throw new Error(`gate: ${problem}.`);
1139
+ return merged;
1140
+ }
1141
+
1142
+ /** A statechart's machine after an agent's change: only the keys passed change; a machine that can't run (an unknown target, an unreachable state, a conflict) is refused with every problem. */
1143
+ function chartPatch(current, change) {
1144
+ const merged = { ...(current ?? {}), ...change };
1145
+ const problem = chartProblem(merged);
1146
+ if (problem) throw new Error(`chart: ${problem}.`);
1147
+ return merged;
1148
+ }
1149
+
1150
+ /** A scene pane's scene after an agent's change: a whole scene (checked) or a patch applied to the current one (one edit: rev goes up by one); the validator's message when it is refused. */
1151
+ function scenePatch(current, change) {
1152
+ const result = isScenePatch(change) ? editScene(current ?? newScene(), change) : (() => {
1153
+ const checked = validateScene(change);
1154
+ return checked.ok ? { ok: true, scene: change } : { ok: false, message: new SceneError(checked.errors).message };
1155
+ })();
1156
+ if (!result.ok) throw new Error(`scene: ${result.message}.`);
1157
+ return result.scene;
1158
+ }
1159
+
1160
+ /** An http pane's settings after an agent's change: only the keys passed change (compose merges); a literal credential or a setting that can't work is refused. */
1161
+ function httpPatch(current, change) {
1162
+ // A replay pane's request is what the person saw in the log: an agent cannot change what a person's "send these" would then send.
1163
+ if (current?.fromLog === true && (change?.compose !== undefined || change?.mode !== undefined || change?.rules !== undefined)) throw new Error("http: this pane's request was taken from a capture log. An agent can't change it (the person edits it, or makes a new pane).");
1164
+ // send: only the limits change; whether it sends on every run (send.auto) is the person's to turn on, so an agent's value for it is dropped.
1165
+ const send = change?.send ? { send: { ...(current?.send ?? {}), ...change.send, auto: current?.send?.auto === true } } : {};
1166
+ // tap: only how many entries show changes; whether bodies are kept, and how many bytes of each, are the person's to set (a body can hold anything).
1167
+ const tap = change?.tap ? { tap: { ...(current?.tap ?? {}), ...(change.tap.limit !== undefined ? { limit: change.tap.limit } : {}), bodies: current?.tap?.bodies === true, ...(current?.tap?.bodyBytes !== undefined ? { bodyBytes: current.tap.bodyBytes } : {}) } } : {};
1168
+ // proxy: where a served request is forwarded is the person's alone (upstream, targets, credential headers, bodies): an agent's value for it is dropped, the person's stays.
1169
+ const proxy = current?.proxy !== undefined ? { proxy: current.proxy } : {};
1170
+ const { proxy: _dropped, fromLog: _marker, ...rest } = change ?? {};
1171
+ const sticky = current?.fromLog === true ? { fromLog: true } : {}; // made from a capture log: no agent clears that
1172
+ const merged = { ...(current ?? {}), ...rest, ...sticky, ...(change?.compose ? { compose: { ...(current?.compose ?? {}), ...change.compose } } : {}), ...send, ...tap, ...proxy };
1173
+ const problem = httpProblem(merged);
1174
+ if (problem) throw new Error(`http: ${problem}.`);
1175
+ return cleanHttp(merged);
1176
+ }
1177
+
1178
+ /** A ws-client pane's settings after an agent's change: only how many frames it keeps (keep, bytes); where it connects, its mode, auto-connect and every proxy setting are the person's, so an agent's value for them is dropped. */
1179
+ function wsPatch(current, change) {
1180
+ const merged = { ...(current ?? {}), ...(change?.keep !== undefined ? { keep: change.keep } : {}), ...(change?.bytes !== undefined ? { bytes: change.bytes } : {}) };
1181
+ const problem = wsProblem(merged);
1182
+ if (problem) throw new Error(`ws: ${problem}.`);
1183
+ return merged;
1184
+ }
1185
+
1186
+ /** A codec pane's codec after an agent's change: only the keys passed change (limits merge too); a setting that can't work is refused. */
1187
+ function codecPatch(current, change) {
1188
+ const merged = { ...(current ?? {}), ...change, ...(change.limits ? { limits: { ...(current?.limits ?? {}), ...change.limits } } : {}) };
1189
+ const problem = codecProblem(merged);
1190
+ if (problem) throw new Error(`codec: ${problem}.`);
1191
+ return cleanCodec(merged);
1192
+ }
1193
+
1194
+ /** An action map pane's map after an agent's change: `preset` replaces the actions with a layout, `actions` replaces the list; a map that can't work is refused. */
1195
+ function actionMapPatch(current, change) {
1196
+ const { preset, ...rest } = change ?? {};
1197
+ if (preset !== undefined && !PRESETS[preset]) throw new Error(`actionMap: preset must be one of ${Object.keys(PRESETS).join(", ")}.`);
1198
+ const merged = { ...(preset !== undefined ? structuredClone(PRESETS[preset].map) : current ?? { actions: [] }), ...rest };
1199
+ const problem = mapProblem(merged);
1200
+ if (problem) throw new Error(`actionMap: ${problem}.`);
1201
+ return actionMapSettings(merged);
1202
+ }
1203
+
1204
+ /**
1205
+ * An input log pane's settings after an agent's change: only the keys passed change, `log: null` removes the log; settings
1206
+ * that can't work are refused. The keyboard mark of a recorded log stays (a log from a keyboard stays out of share links)
1207
+ * until the log is removed.
1208
+ */
1209
+ function inputLogPatch(current, change) {
1210
+ const merged = { ...inputLogSettings(current), ...(change ?? {}) };
1211
+ if (merged.log === null) {
1212
+ delete merged.log;
1213
+ delete merged.keyboard;
1214
+ }
1215
+ const problem = inputLogProblem(merged);
1216
+ if (problem) throw new Error(`inputLog: ${problem}.`);
1217
+ return inputLogSettings(merged);
1218
+ }
1219
+
1220
+ /** A webhook pane's (`webhook`), router pane's (`router`) or watch pane's (`files`) settings after an agent's change: only the keys passed change, `test` merges too; a setting that can't work is refused. */
1221
+ function mergedSettings(current, change, problemOf) {
1222
+ const merged = { ...(current ?? {}), ...change, ...(change.test ? { test: { ...(current?.test ?? {}), ...change.test } } : {}) };
1223
+ const problem = problemOf(merged);
1224
+ if (problem) throw new Error(problem);
1225
+ return merged;
1226
+ }
1227
+
1228
+ /**
1229
+ * A device pane's setting after an agent's change: only the keys passed change, and `target` (a pane's id or
1230
+ * name) is stored as that pane's id. A pane that isn't on this canvas is refused.
1231
+ */
1232
+ function devicePatch(current, change, canvas, find) {
1233
+ const merged = { ...(current ?? {}), ...(change ?? {}) };
1234
+ if (change && "target" in change && String(change.target ?? "").trim()) merged.target = find(canvas, String(change.target).trim()).id;
1235
+ else if (change && "target" in change) merged.target = "";
1236
+ const settings = deviceSettings(merged);
1237
+ const problem = deviceProblem(settings);
1238
+ if (problem) throw new Error(`${problem}.`);
1239
+ return settings;
1240
+ }
1241
+
1242
+ /**
1243
+ * A tool as a model context takes it ({ name, title, description,
1244
+ * inputSchema, annotations } and the handler callTool runs), from its spec:
1245
+ * { name, title, description (text, or parts joined with spaces), input (a
1246
+ * JSON Schema), readOnly?, destructive?, untrusted? (its result carries text
1247
+ * from the canvas), agentOnly?, run(args) }. A tool that no command maps to
1248
+ * (the commands' `agent.tool`, src/commands.js) says in `agentOnly` what a
1249
+ * person uses instead; test/coverage.test.mjs holds both to that.
1250
+ */
1251
+ function toolFromSpec({ name, title, description, input, readOnly = false, destructive = false, untrusted = false, agentOnly, settings = false, run }) {
1252
+ // A tool that takes pane settings lists one open `settings` argument, not each type's and setting's (#855); callTool
1253
+ // flattens it and checks the call against the whole schema (`checkSchema`) and every setting's full shape.
1254
+ const listed = settings ? new Set(Object.keys(input.properties)) : null;
1255
+ const normalize = settings ? (args) => flattenSettings(args, listed) : null;
1256
+ return {
1257
+ ...(settings ? { checkSettings, checkSchema: checkSchemaOf(input, settings.types), normalize } : {}),
1258
+ name: PREFIX + name,
1259
+ title,
1260
+ description: Array.isArray(description) ? description.filter(Boolean).join(" ") : description,
1261
+ inputSchema: settings ? { ...input, additionalProperties: true } : input,
1262
+ annotations: { readOnlyHint: readOnly, ...(destructive ? { destructiveHint: true } : {}), ...(untrusted ? { untrustedContentHint: true } : {}) },
1263
+ ...(agentOnly ? { agentOnly } : {}),
1264
+ handler: normalize ? (args) => run(normalize(args)) : run,
1265
+ };
1266
+ }
1267
+
1268
+ /** Tools that edit the canvas after an await (they wait for the host's snapshot first), so their one undo step stays open until they settle (Canvas#agentStep). A spec can also say per call (`late(args)`): input_log's branch reads a pane's value first, its other actions never edit. */
1269
+ export const EDITS_AFTER_AWAIT = new Set(["update_linked"]);
1270
+
1271
+ /** Tools that don't edit the canvas in place, or that step through the history or swap the canvas (or the subgraph shown): never an undo step of their own. */
1272
+ export const NO_STEP = new Set(["undo", "redo", "restore_version", "open_canvas", "new_canvas", "open_example", "import_canvas", "open_subgraph", "leave_subgraph"]);
1273
+
1274
+ /**
1275
+ * The words of the undo step an agent's tool call makes, from its arguments and the names of the panes it named and
1276
+ * made: "the agent's change: code of sum", so "Undid the agent's change: code of sum." reads as a sentence and says
1277
+ * whose change it was.
1278
+ */
1279
+ function agentWords(tool, args, names) {
1280
+ const outName = names.added[0];
1281
+ const changed = Object.keys(args).filter((k) => !["pane", "id", "wait", "timeoutMs"].includes(k));
1282
+ const said = {
1283
+ update_pane: () => `${changed.join(", ") || "settings"} of ${names.pane}`,
1284
+ add_pane: () => `new ${args.type ?? ""} pane${outName ? ` ${outName}` : ""}`.replace("new pane", "new pane"),
1285
+ delete_pane: () => `removing ${names.pane}`,
1286
+ connect: () => `wire from ${names.from} to ${names.to}`,
1287
+ disconnect: () => `removing the wire ${args.input ?? names.from ?? "input"} into ${names.to}`,
1288
+ set_input: () => `value of ${names.pane}`,
1289
+ insert_pane: () => `new pane ${outName ?? ""} on the wire into ${names.to}`.replace("pane on", "pane on"),
1290
+ change_pane_type: () => `type of ${names.pane}, now ${args.type}`,
1291
+ duplicate_panes: () => `copies ${names.added.join(", ") || "of panes"}`,
1292
+ group_panes: () => `grouping ${(args.panes ?? []).length} panes into ${outName ?? "a subgraph pane"}`,
1293
+ paste_panes: () => `pasted ${names.added.join(", ") || "panes"}`,
1294
+ workspaces: () => `workspaces (${String(args.action ?? "change").replace(/_/g, " ")})`,
1295
+ input_log: () => `${args.action ?? "change"} of the input log in ${names.pane}`,
1296
+ }[tool];
1297
+ const target = args.pane || args.id || args.to ? names.pane : "";
1298
+ return `the agent's change: ${said ? said() : `${tool.replace(/_/g, " ")}${target ? ` on ${target}` : ""}`}`;
1299
+ }
1300
+
1301
+ /** A failure the agent can read (and correct), instead of an opaque rejection. */
1302
+ export function toolError(error) {
1303
+ return { content: [{ type: "text", text: `Error: ${error?.message ?? String(error)}` }], isError: true };
1304
+ }
1305
+
1306
+ /** Validate arguments, call the handler, and shape the result or the error. */
1307
+ export async function callTool(tool, args) {
1308
+ const input = args && typeof args === "object" ? args : {};
1309
+ const problems = [];
1310
+ let checked = input;
1311
+ try {
1312
+ checked = tool.normalize ? tool.normalize(input) : input; // `settings: { … }` becomes the top-level arguments
1313
+ } catch (error) {
1314
+ problems.push(error.message);
1315
+ }
1316
+ if (!problems.length) problems.push(...checkArgs(tool.checkSchema ?? tool.inputSchema, checked), ...(tool.checkSettings ? tool.checkSettings(checked) : []));
1317
+ if (problems.length) return toolError(new Error(`Invalid arguments for ${tool.name}: ${problems.join("; ")}.`));
1318
+ try {
1319
+ return toolResult(await tool.handler(checked));
1320
+ } catch (error) {
1321
+ return toolError(error);
1322
+ }
1323
+ }