@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,1397 @@
1
+ // The `mallory` command line. This file is `run`, `test` and `simulate`; main() hands every other subcommand to its own file:
2
+ // `mallory cost` src/headless/cost-cli.js (the cost of a run log, pane by pane)
3
+ // `mallory diff` src/headless/diff-cli.js (what changed between two canvases)
4
+ // `mallory machine` src/headless/machine-cli.js (validate, step, run, fork, diff, merge, trace, bench, lint ... a machine pane)
5
+ // `mallory convert` src/headless/convert-cli.js (another format, or another tool's file)
6
+ // `mallory deprecations` src/headless/deprecations-cli.js (a pane package's deprecation notices)
7
+ // `mallory pkg` src/headless/pkg-cli.js (check, test, pack, new, keygen, sign, trust, serve a pane package)
8
+ // `mallory serve` src/headless/serve-cli.js (webhook, timer and watch panes, kept running)
9
+ // `mallory grant` src/headless/grant-cli.js (grants for serve's unattended scheduled runs)
10
+ // `mallory publish` src/headless/publish.js (an immutable published revision for `serve --published`)
11
+ // `mallory render` src/headless/render-cli.js (an animated pane to mp4, webm or gif)
12
+ // `mallory companion` src/headless/companion-cli.js (the optional local helper server)
13
+ // `mallory room-relay` src/headless/room-relay.js (a meeting place for rooms)
14
+ // That is 15 subcommands with `run`, `test` and `simulate`; the reference for each is docs/guide/cli-and-serving.md, "CLI reference".
15
+ // Canvases can be in any format mallory reads (src/formats/). Argument parsing and
16
+ // output formatting are pure (tested under node --test); `main` does the I/O.
17
+ import { moduleFor } from "../packages/module.js";
18
+ import { readFile, writeFile, rename, readdir, stat } from "node:fs/promises";
19
+ import { importCanvas, canvasLikeName } from "../formats/registry.js";
20
+ import { resolveLinks } from "../model/links.js";
21
+ import { parsePackage, paneDoc, integrityOf, isPackageName, looksLikePackage, packageSignature } from "../packages/package.js";
22
+ import { trustDecision, trustRefusal, pinAfter } from "../packages/trust.js";
23
+ import { openTrustFile } from "./trust-file.js";
24
+ import { validateTests } from "../tests/matchers.js";
25
+ import { formatReport, runTests } from "../tests/run.js";
26
+ import { REPORTERS, formatWith, reportFromRun } from "../tests/reporters.js";
27
+ import { reportHtml } from "../tests/report.js";
28
+ import { isEvaluation } from "../tests/evaluate.js";
29
+ import { parseDataset } from "../tests/dataset.js";
30
+ import { parsePredictions, withSavedPredictions } from "../tests/compare.js";
31
+ import { envFromProcess, parseEnvPair } from "../env/env.js";
32
+ import { findPane } from "../run/run.js";
33
+ import { channelProblem, scopeProblem } from "../model/channel-names.js";
34
+ import { typeFromName } from "../media/mime.js";
35
+ import { toBase64 } from "../media/persist.js";
36
+ import { basename, join } from "node:path";
37
+ import { tensorSummary, statsLine, num } from "../model/tensor-view.js";
38
+ import { DTYPES } from "../tensor/tensor.js";
39
+ import { fileStateStore, parseStateFile } from "../model/persist-state.js";
40
+ import { parseSources } from "../sources/config.js";
41
+ import { lockEntryText } from "../model/import-lock.js";
42
+ import { parsePaneRetention } from "../model/retention.js";
43
+ import { hasChartTests, docChartTests } from "../model/statecharts.js";
44
+ import { parseCompanionEndpoint, MODULE_ID } from "../run/companion.js";
45
+ import { ffmpegFlagProblem, ffmpegFromFlags } from "./ffmpeg-exec.js";
46
+ import { parseVirtualNow, parseDuration } from "../model/virtual-clock.js";
47
+ import { approvalsProblem } from "../gate/scripted.js";
48
+ import { parseUsd, formatUsd, MAX_CAP_MICROS } from "../x402/challenge.js";
49
+
50
+ export const HELP = `mallory: run a mallory canvas (.mallory.json, .mallory.yaml, .mallory.md) from the command line.
51
+
52
+ Usage:
53
+ mallory run <canvas> [--input name=value]... [--output name]... [options]
54
+ mallory run <canvas> --describe [--json]
55
+ mallory test <canvas> [--test name]... [--dataset file] [--predictions name=file]... [--report file] [options]
56
+ mallory cost <log.jsonl> [--json] [--last n] [--sort column]
57
+ mallory run <canvas> --cost [--json]
58
+ mallory simulate <canvas> <pane> [--frame N] [--hash] [--input name=value]... [--json] [options]
59
+ mallory diff <before> <after> [--json] [--exit-code]
60
+ mallory machine validate|run|step|init|fork|diff|merge|trace|bench|suite|report|serve|import|export|lint|otel …
61
+ mallory convert <in> <out> [--to format] [--from format]
62
+ mallory deprecations <package> [--output file] [--json]
63
+ mallory pkg check|test|pack|new …
64
+ mallory serve <canvas>... [--port 8787] [--host 127.0.0.1] [options]
65
+ mallory grant keygen|rotate|create|list|revoke|ceilings|routines --state PATH …
66
+ mallory publish <canvas> [--review] [--note text]
67
+ mallory render <canvas> --pane <name> -o out.mp4|webm|gif [--seconds N] [--fps F] [--size WxH]
68
+ mallory companion <module>… --origin <page> [--port 8788]
69
+ mallory room-relay [--port 8790] [--host 127.0.0.1]
70
+
71
+ run Runs every pane (click-to-run ones too) and prints the outputs: the
72
+ panes named with --output, or else every named pane no other pane
73
+ reads. With exactly one --output and no --json it prints just that
74
+ value (text as is, anything else as JSON). A tensor prints as a
75
+ summary (dtype, shape, min/max/mean/std, the first values), alone or
76
+ inside an object; --json has the whole value. Exits 1 if an output pane
77
+ failed, waited or was skipped. With --describe it runs nothing and
78
+ prints the canvas's signature: its inputs and outputs, with types.
79
+ test Runs the canvas's saved tests. Exits 1 if any test fails, 2 if there
80
+ are none. A test with a dataset is an evaluation: it runs once per row
81
+ and fails when a "pass" threshold isn't met (docs/guide/cli-and-serving.md,
82
+ "Evaluations").
83
+ simulate Prints the state of a simulation render pane (simulate on, docs/guide/graphics.md
84
+ "Simulations and checkpoints") after N steps: --frame N (default 0, the
85
+ state init makes) at the pane's fps, seed and size, with its inputs as
86
+ the canvas computes them (--input sets input panes, as for run). Render
87
+ panes aren't drawn here, but stepping is pure, so this is the state a
88
+ draw at that frame would get; --json adds the pane, frame, t, fps and
89
+ seed. A test can expect it too: "expect": { "balls@120": … }.
90
+ diff Prints what changed between two canvases, pane by pane (code as
91
+ unified diffs). See mallory diff --help.
92
+ machine Drives a machine pane from the terminal: validate, run or step it (offline), scaffold one from a template, fork, diff and
93
+ merge machines, inspect, replay, fork and resume its traces, run its tests, read or write a llmtm/v1 machine, lint it.
94
+ See mallory machine --help.
95
+ deprecations Prints the deprecation notices of a pane package file as Markdown to
96
+ publish beside it, without installing it. See mallory deprecations --help.
97
+ pkg Author tooling for pane packages: check a package as an install does,
98
+ test its panes in an isolated sandbox (--reporter tap|junit|json),
99
+ pack one from a folder of canvases, or start one from a template.
100
+ See mallory pkg --help.
101
+ convert Writes a canvas in another format (Mallory JSON, YAML or a Markdown
102
+ notebook), or imports a Rivet, Node-RED, n8n or Jupyter file. See
103
+ mallory convert --help.
104
+ serve Keeps canvases running: webhook panes answer HTTP requests (on
105
+ 127.0.0.1 unless told otherwise), timer panes tick on schedule and
106
+ watch panes fire on files in allowed folders. See mallory serve --help.
107
+ grant Makes, lists and revokes the signed grants that serve's scheduled
108
+ (unattended) runs need, and sets their spending ceilings. See
109
+ mallory grant --help.
110
+
111
+ render Draws a render pane frame by frame, offline, and encodes it to mp4, webm or gif with
112
+ ffmpeg.wasm, bounded by seconds, fps, frames and size. See mallory render --help.
113
+ publish Makes the canvas file (the draft) an immutable published revision that
114
+ mallory serve --published runs, after a review of what changed, what it
115
+ asks for and its tests; --rollback goes back to an earlier one. See
116
+ mallory publish --help.
117
+
118
+ companion Starts the optional local helper server a canvas's panes can use
119
+ (vetted modules from this repo's companion/ folder, Node 26): loopback
120
+ only, one named web page, a pairing code shown here. See
121
+ mallory companion --help.
122
+
123
+ room-relay Starts a meeting place for mallory rooms (live editing with other
124
+ people) between browsers on different origins or computers. It forwards
125
+ sealed messages and reads none. See mallory room-relay --help.
126
+
127
+ A canvas file can be in any format mallory reads: .mallory.json, .mallory.yaml /
128
+ .mallory.yml, .mallory.md, or another tool's file (a .rivet-project, a Node-RED
129
+ flow or n8n workflow .json, a Jupyter .ipynb), which is imported first (what
130
+ it couldn't keep is printed on stderr).
131
+
132
+ Options:
133
+ --input, -i name=value Set an input, text, state or media pane (by name)
134
+ before running. The value is parsed as JSON when it
135
+ can be (40, true, "x", [1,2]), else taken as text.
136
+ A media pane takes name=@file (a file's bytes), an
137
+ http(s) URL (fetched under the network rules) or a
138
+ data: URL.
139
+ --output, -o name A pane to report (repeatable); pane.output for one
140
+ of its named outputs (split.small).
141
+ --describe Print the canvas's signature instead of running it:
142
+ the inputs --input sets (with their types,
143
+ defaults and descriptions) and the outputs a run
144
+ reports (with their named outputs). An input with
145
+ a declared type converts its --input value to it.
146
+ --frame N With simulate: the frame (steps from init) to print.
147
+ --hash With simulate: print the hash of that state (16 hex digits)
148
+ instead of the state. Same machine, same result; an input
149
+ log wired into the pane is replayed first.
150
+ --tick N, --ticks N Timer panes tick once (tick 0, once the rest of
151
+ the canvas has settled) in a run, and nothing
152
+ waits for their schedule; --tick N runs N
153
+ ticks in sequence (every timer fires, then the
154
+ canvas settles) and reports the values after the
155
+ last. For testing canvases that count or poll.
156
+ --virtual-now T Run on a virtual clock that stands at T (an ISO 8601
157
+ date-time with a zone, like 2026-10-14T12:00:00Z, or
158
+ milliseconds since 1970): a time-window gate is
159
+ decided at T, so a run answers the same whenever it
160
+ is run. Without --advance a wait's, decision's or
161
+ gate's deadline never passes in a headless run.
162
+ --advance D With --virtual-now: once the events and decision
163
+ fixtures are in, D of virtual time passes (a number
164
+ and a unit: 500ms, 30s, 90m, 2h, 1d, 1h30m).
165
+ Deadlines that fall inside it end their waits in
166
+ order, each at its own instant (a gate whose
167
+ window opens releases its items; maxWaitMs expires
168
+ them; a statechart's delays fire), then the canvas
169
+ settles and the outputs are read.
170
+ --yields N A live pane (code with yield or emit) gives its
171
+ first value and stops; --yields N takes N values
172
+ (each one runs the panes that read it), then stops
173
+ it (its finally runs). Outputs report the last.
174
+ An animation (code that awaits frame(), a states
175
+ preset's tween) runs to its end on virtual frames
176
+ unless --yields is given.
177
+ --event pane[.name]=value
178
+ Once the canvas has settled, send an event out of
179
+ the pane's event output (repeatable, sent in order:
180
+ a burst); value is JSON or text, as for --input.
181
+ Events panes make during the run are delivered
182
+ anyway, and the run waits for their readers.
183
+ --decision pane={"decision":"approve","values":{…}}
184
+ The operator's answer to a decision pane,
185
+ given up front: decision is approve, reject or
186
+ cancel; values fill its form (checked like a
187
+ person's); key picks a proposal ("oldest": true takes
188
+ the oldest on purpose; with several waiting and
189
+ neither, the run fails); voter and answerId name
190
+ an approver, voters: ["ann","bob"] answers once
191
+ for each (a pane wanting several). Repeatable,
192
+ applied in order after the canvas settles. Without
193
+ a fixture that satisfies it, a decision pane with
194
+ a proposal awaiting a person makes the run report
195
+ "needs input" (stderr, \`needsInput\` in --json)
196
+ and exit 1: nothing answers for the operator.
197
+ --decisions file.json The same, from a JSON array of those objects, each
198
+ with "pane".
199
+ --approve tool[@server] Scripted approvals: your answer, given up front, to the
200
+ --deny tool[@server][=reason]
201
+ --amend tool[@server]={"name":value,…}
202
+ next call of that tool that waits for approval (an
203
+ agent pane's card, or a gate policy's approve rule):
204
+ approve it, deny it (the model is told, with the
205
+ reason), or approve it with these arguments over the
206
+ model's. tool may use * (lookup_*); server is the
207
+ gate's (agent, or an MCP server pane's name). Each
208
+ answers one call, in order. Repeatable. Without an
209
+ answer such a call is refused, as nobody is here to
210
+ approve it. The audit marks these rows "scripted".
211
+ With test, they follow each test's own "approvals".
212
+ --approvals file.json The same, from a JSON array of { tool, decision:
213
+ "approve" | "deny" | "amend", server?, args?, reason?,
214
+ times?, repeat? } (repeat: true answers every call).
215
+ --spend-cap dollars The cap for x402 payment requests (an HTTP 402 with a
216
+ price) in this run, like 0.50. Payments are simulated:
217
+ nothing is signed, paid or settled. Without a cap
218
+ every request is refused; within it each still needs
219
+ a scripted answer (--approve pay@x402).
220
+ --send channel[@scope]=value
221
+ The same, on a named event channel: every
222
+ receiver its scope reaches (canvas, the default;
223
+ parent, children or siblings) gets it, in order
224
+ with the --event ones.
225
+ --serial-replay name Once the canvas has settled, replay the serial recording
226
+ (fixture) of that name from the canvas's serial settings
227
+ through its framing, format and channel, as a device
228
+ would send it: every receiver of the channel gets the
229
+ packets, in order with the --event and --send ones.
230
+ Repeatable. No port is opened and no device is needed.
231
+ --only-needed Run only the output panes and the panes they read
232
+ (directly or not); every other pane stays idle.
233
+ --test, -t name Run only this test (repeatable).
234
+ --dataset file The rows for the evaluation being run, instead of
235
+ its own (CSV, JSON or JSON Lines). With more than
236
+ one evaluation, pick one with --test.
237
+ --predictions name=file Saved predictions for the comparison of the evaluation
238
+ being run, as a candidate called name: a file of
239
+ { key, actual } (JSON, JSON Lines or CSV), any size.
240
+ Replaces a saved candidate of that name, or adds one.
241
+ Repeatable; with more than one comparison, pick one
242
+ with --test.
243
+ --parallel n Evaluation rows run at a time (default 4).
244
+ --report file Also write the results as JSON to this file.
245
+ --html file Also write the results as a standalone HTML report (per-run and
246
+ per-case tables, no script, no network) to this file.
247
+ --baseline file A report written earlier (--report, or --json): each
248
+ agent evaluation matrix is compared with the one of
249
+ the same name there, and a cell that passed then and
250
+ fails now is a regression (listed, and the exit code
251
+ is 1); fixed cells and cost changes are listed too.
252
+ --reporter tap|junit|json
253
+ Print the results for a CI step: TAP 13 (a subtest per
254
+ test, with a plan), JUnit XML (a suite named after the
255
+ canvas file), or the JSON --json prints. For run, a
256
+ point per pane (done passes, skipped is skipped).
257
+ Exit codes are the same.
258
+ --state file.json Persisted state panes (keep: canvas or a browser
259
+ store) start from the values in this file:
260
+ { "canvas": { "<pane name>": value },
261
+ "browser": { "<store name>": value } }.
262
+ After a run that succeeded (every output finished,
263
+ no pane failed) the new values are written back; a
264
+ missing file starts empty. An --input for a state
265
+ pane wins over the file.
266
+ --state-readonly With --state: read the file, never write it.
267
+ --lib dir Canvases for linked subgraph panes, in any format
268
+ mallory reads, matched by canvas id, then by name.
269
+ Repeatable; a file works too. A linked pane uses
270
+ the version found here, else the one in the
271
+ canvas's library, else the copy it holds; what
272
+ changed is printed on stderr. A pane package
273
+ (.mallory-pkg.json) in it counts as --pkg.
274
+ --pkg file A pane package (.mallory-pkg.json or .yaml) for the
275
+ linked subgraph panes that use its panes, matched
276
+ by package and pane id. Repeatable. Without it they
277
+ use the canvas's library, else their own copy.
278
+ A package whose publisher signature doesn't match
279
+ its contents is refused.
280
+ --trust-file file Publisher keys pinned per package name (docs/guide/settings-and-storage.md,
281
+ "Publisher trust"): a signed --pkg or --lib package
282
+ pins its key here the first time; one signed by
283
+ another key, or no longer signed, is refused until
284
+ mallory pkg trust re-pins it. A missing file
285
+ starts empty.
286
+ --json Print one JSON object: { ok, values, types, states, logs,
287
+ caught? (what catch panes caught) } for run, { pass, passed, failed, results } for test.
288
+ --log-format text|json How run prints console output to stderr: "[pane] text"
289
+ lines (default), or one JSON object per line:
290
+ { pane, level, text }, plus { label, value } for a
291
+ value logged with log(label, value).
292
+ --media-data Media values (images, sound, video, files) print as
293
+ { $media, type, size, ... }; this adds "data", the
294
+ bytes as base64.
295
+ --use-pins Pinned panes keep their pinned values (they don't
296
+ run). Without it a run ignores pins and runs every
297
+ pane. A test uses pins when it says "pins": true.
298
+ --cost Report what the run cost, pane by pane: runs, total and
299
+ p50/p95 runtime, time spent waiting (kept apart from
300
+ runtime), and for wait, decision and gate panes how
301
+ long they held (start to outcome; unknown, never 0, when
302
+ nothing ended). The table goes to stderr, or with --json
303
+ is the "cost" object. mallory cost <log.jsonl> reports
304
+ a log written with --log (mallory cost --help).
305
+ --log file.jsonl Write the run log: one canvas run per line, with
306
+ each pane's inputs, output (its full JSON up to
307
+ 64 KB), error, console lines and timing. For test,
308
+ the lines of each test carry its name (and an
309
+ evaluation's, a line per row, its "row" too).
310
+ --retain MODE What the run log (--log) keeps of values: full (the
311
+ default), redacted (previews only, with --retain-pane
312
+ paths hidden) or summary (status, timing and source
313
+ ids only: no inputs, outputs, console lines or error
314
+ messages). Applies to every pane unless one has
315
+ its own.
316
+ --retain-pane PANE=MODE[:path,path]
317
+ One pane's own mode (repeatable); a pane takes the
318
+ stricter of this and --retain. redacted takes
319
+ dotted paths into its value (user.email, items.*.token,
320
+ **.password). A name that matches no pane is an error.
321
+ --drop-text Keep no console lines or error messages in the log.
322
+ --sample-runs N Keep the values of only every Nth run in the log
323
+ (the others keep status, timing and ids).
324
+ --sample-items N Show only the first N items of a list in the log's
325
+ previews; a value with a longer list is not kept
326
+ whole.
327
+ --allow-host host Let panes fetch from and import from this host;
328
+ *.example.com for its subdomains. Repeatable.
329
+ Without it panes can't reach the network at all,
330
+ package CDNs included: an import pane needs
331
+ --allow-host esm.sh (or cdn.jsdelivr.net, which
332
+ mport then prefers).
333
+ --companion URL Let this run use modules of a mallory companion
334
+ on this computer (an address like
335
+ http://localhost:8788). Needs
336
+ --companion-token-env NAME (the variable holding
337
+ the token the companion was started with, via its
338
+ --token-env) and --companion-module ID for each
339
+ module it may use (repeatable). Off by default: a
340
+ run, mallory test and verify use stand-ins.
341
+ --allow-ffmpeg PATH Let pane code run ffmpeg: ffmpegRun(graph) runs a
342
+ filtergraph on the program at PATH (the full path of
343
+ a file named ffmpeg), as an argument list with no
344
+ shell, on files in --ffmpeg-dir only, with no
345
+ environment variables, one at a time under the pane
346
+ timeout. Needs --ffmpeg-dir. Off by default.
347
+ --ffmpeg-dir DIR The one folder ffmpegRun reads inputs from and
348
+ writes its output to; a name that leaves it (.., an
349
+ absolute path elsewhere, a symlink out) is refused.
350
+ --ffmpeg-overwrite Let ffmpegRun replace an output file that exists
351
+ (otherwise it refuses).
352
+ --sources file.json Package sources for import panes: the routes and
353
+ CDNs, mirrors or servers that serve npm specs (the
354
+ JSON ⚙ settings → package sources exports; see the
355
+ docs/guide/settings-and-storage.md, "Package sources"). Without it: esm.sh,
356
+ then jsDelivr. Their hosts still need --allow-host.
357
+ --update-imports Import panes ignore the canvas's import lock (the
358
+ exact versions it saved) and resolve their ranges
359
+ again; what changed is printed on stderr. The file
360
+ isn't rewritten: save the canvas from the editor
361
+ ("Update imports…") to keep the new versions.
362
+ --allow-all-hosts Let panes reach every public host.
363
+ --allow-local Also allow this computer and the local network
364
+ --isolate-panes Run each pane's Worker in a child process, so one huge allocation ends that pane only (about +100 ms)
365
+ (with --allow-host or --allow-all-hosts).
366
+ --env NAME=value A variable panes read as env.NAME (repeatable);
367
+ wins over MALLORY_ENV_NAME.
368
+ --guards-file FILE The operator's rules for agent panes: hooks, delegation caps and
369
+ safety switches (mode 600; a bad file stops the run). Without
370
+ it: delegation depth 2 and 3 at once, the sanitizer and leak
371
+ detector on, no hooks.
372
+ --timeout seconds How long one pane may run (default 15).
373
+ --help, -h This help.
374
+
375
+ API keys: secret("NAME") in a pane uses the environment variable
376
+ MALLORY_SECRET_NAME, sent only to the hosts in MALLORY_SECRET_NAME_HOSTS (comma
377
+ separated), or else to the --allow-host hosts. MALLORY_SECRET_NAME_KIND says how
378
+ fetch(url, { auth: "NAME" }) sends it: bearer, header:x-api-key, query:key,
379
+ basic:USERNAME, basic-username or preset:anthropic (also openai, google-ai,
380
+ github, huggingface, whose hosts are then the default). Values are never
381
+ printed and are scrubbed from what comes back; canvas code can't read the
382
+ environment.
383
+
384
+ Variables: env.NAME in a pane is the --env NAME=value flag or else the
385
+ environment variable MALLORY_ENV_NAME (undefined when neither is set;
386
+ requireEnv("NAME") throws instead). Unlike API keys, panes can read these
387
+ values, so don't put keys in them. Values are never printed by mallory itself.
388
+
389
+ DOM, html and embed panes need a browser: they are skipped, and panes that
390
+ read them wait.
391
+
392
+ Only run canvases you trust. mallory runs a canvas's code in a Node worker
393
+ thread, which is not a security boundary: code that tries can read your files,
394
+ start programs and use the network directly. The network rules above govern
395
+ panes' fetch and imports; they don't contain hostile code.`;
396
+
397
+ export class UsageError extends Error {}
398
+
399
+ /** A value from the command line: JSON when it parses (40, true, "x", [1]), else the text itself. */
400
+ export function parseValue(text) {
401
+ try {
402
+ return JSON.parse(text);
403
+ } catch {
404
+ return text;
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Parse `mallory` arguments (without `node` and the script).
410
+ * @returns {{ command: "run" | "test" | "help", file?: string, inputs: Record<string, unknown>, outputs: string[],
411
+ * tests: string[], json: boolean, allowHosts: string[], allowAllHosts: boolean, allowLocal: boolean, timeoutMs: number,
412
+ * env: Record<string, string> }} `env`: the --env flags only (see envFor for MALLORY_ENV_*)
413
+ */
414
+ export function parseArgs(argv) {
415
+ const out = { command: "help", file: undefined, describe: false, inputs: {}, outputs: [], tests: [], dataset: undefined, predictions: [], report: undefined, reporter: undefined, parallel: undefined, json: false, logFormat: "text", onlyNeeded: false, mediaData: false, usePins: false, log: undefined, cost: false, allowHosts: [], allowAllHosts: false, allowLocal: false, timeoutMs: 15000, env: {}, stateFile: undefined, stateReadonly: false, ticks: 1, virtualNow: undefined, advanceMs: 0, yields: 1, frame: 0, events: [], lib: [], pkg: [], trustFile: undefined, sources: undefined, updateImports: false };
416
+ const args = [...argv];
417
+ const positional = [];
418
+ const take = (flag, inline) => {
419
+ if (inline !== undefined) return inline;
420
+ if (!args.length || (args[0].startsWith("-") && args[0] !== "-")) throw new UsageError(`${flag} needs a value`);
421
+ return args.shift();
422
+ };
423
+ while (args.length) {
424
+ const arg = args.shift();
425
+ if (arg === "--") {
426
+ positional.push(...args.splice(0));
427
+ break;
428
+ }
429
+ const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
430
+ const flag = eq > 0 ? arg.slice(0, eq) : arg;
431
+ const inline = eq > 0 ? arg.slice(eq + 1) : undefined;
432
+ switch (flag) {
433
+ case "-h":
434
+ case "--help":
435
+ return { ...out, command: "help" };
436
+ case "-i":
437
+ case "--input": {
438
+ const pair = take(flag, inline);
439
+ const at = pair.indexOf("=");
440
+ if (at <= 0) throw new UsageError(`--input takes name=value (got "${pair}")`);
441
+ out.inputs[pair.slice(0, at)] = parseValue(pair.slice(at + 1));
442
+ break;
443
+ }
444
+ case "--event": {
445
+ const pair = take(flag, inline);
446
+ const at = pair.indexOf("=");
447
+ const target = at < 0 ? pair : pair.slice(0, at);
448
+ if (!target) throw new UsageError(`--event takes pane[.name]=value (got "${pair}")`);
449
+ const dot = target.lastIndexOf(".");
450
+ out.events.push({ to: dot > 0 ? target.slice(0, dot) : target, ...(dot > 0 ? { name: target.slice(dot + 1) } : {}), payload: at < 0 ? null : parseValue(pair.slice(at + 1)) });
451
+ break;
452
+ }
453
+ case "--decision": {
454
+ // pane=JSON: { decision: "approve" | "reject" | "cancel", values?, key?, voter?, answerId? } (the operator's answer, given up front).
455
+ const pair = take(flag, inline);
456
+ const at = pair.indexOf("=");
457
+ if (at <= 0) throw new UsageError(`--decision takes pane={"decision":"approve",…} (got "${pair}")`);
458
+ const answer = parseValue(pair.slice(at + 1));
459
+ if (!answer || typeof answer !== "object" || Array.isArray(answer)) throw new UsageError(`--decision ${pair.slice(0, at)}: the answer is a JSON object like {"decision":"approve","values":{…}}`);
460
+ (out.decisions ??= []).push({ pane: pair.slice(0, at), ...answer });
461
+ break;
462
+ }
463
+ case "--decisions": {
464
+ (out.decisionFiles ??= []).push(take(flag, inline));
465
+ break;
466
+ }
467
+ case "--approve":
468
+ case "--deny":
469
+ case "--amend": {
470
+ // Scripted approvals (src/gate/scripted.js): tool[@server], a deny's =reason, an amend's ={…} arguments.
471
+ const value = take(flag, inline);
472
+ const at = value.indexOf("=");
473
+ const target = at < 0 ? value : value.slice(0, at);
474
+ const [tool, server] = target.split("@");
475
+ const decision = flag.slice(2);
476
+ const entry = { tool, ...(server ? { server } : {}), decision };
477
+ if (decision === "amend") {
478
+ if (at < 0) throw new UsageError(`--amend takes tool[@server]={"name":value,…} (got "${value}")`);
479
+ entry.args = parseValue(value.slice(at + 1));
480
+ } else if (at >= 0) {
481
+ if (decision !== "deny") throw new UsageError(`--approve takes tool[@server] (got "${value}")`);
482
+ entry.reason = value.slice(at + 1);
483
+ }
484
+ const problem = approvalsProblem([entry], flag);
485
+ if (problem) throw new UsageError(problem.replace(`${flag}: answer 1`, flag));
486
+ (out.approvals ??= []).push(entry);
487
+ break;
488
+ }
489
+ case "--spend-cap": {
490
+ // The cap for simulated x402 payments (src/x402/pay.js), in dollars: the person's, never the canvas's.
491
+ const value = take(flag, inline);
492
+ const micros = parseUsd(value);
493
+ if (micros === null) throw new UsageError(`--spend-cap takes an amount in dollars, like 0.50 (at most ${formatUsd(MAX_CAP_MICROS)}; got "${value}")`);
494
+ out.spendCap = micros;
495
+ break;
496
+ }
497
+ case "--approvals": {
498
+ (out.approvalFiles ??= []).push(take(flag, inline));
499
+ break;
500
+ }
501
+ case "--send": {
502
+ const pair = take(flag, inline);
503
+ const at = pair.indexOf("=");
504
+ const target = at < 0 ? pair : pair.slice(0, at);
505
+ const [channel, scope] = target.split("@");
506
+ const problem = channelProblem(channel) || scopeProblem(scope);
507
+ if (problem) throw new UsageError(`--send takes channel[@scope]=value: ${problem} (got "${pair}")`);
508
+ out.events.push({ channel, ...(scope ? { scope } : {}), payload: at < 0 ? null : parseValue(pair.slice(at + 1)) });
509
+ break;
510
+ }
511
+ case "--serial-replay":
512
+ out.events.push({ serialReplay: take(flag, inline) });
513
+ break;
514
+ case "-o":
515
+ case "--output":
516
+ out.outputs.push(...take(flag, inline).split(",").map((s) => s.trim()).filter(Boolean));
517
+ break;
518
+ case "-t":
519
+ case "--test":
520
+ out.tests.push(take(flag, inline));
521
+ break;
522
+ case "--dataset":
523
+ out.dataset = take(flag, inline);
524
+ break;
525
+ case "--baseline":
526
+ out.baseline = take(flag, inline);
527
+ break;
528
+ case "--predictions": {
529
+ const value = take(flag, inline);
530
+ const at = value.indexOf("=");
531
+ if (at < 1 || at === value.length - 1) throw new UsageError(`--predictions takes name=file (got "${value}")`);
532
+ const name = value.slice(0, at);
533
+ if (out.predictions.some((p) => p.name === name)) throw new UsageError(`--predictions names "${name}" twice`);
534
+ out.predictions.push({ name, file: value.slice(at + 1) });
535
+ break;
536
+ }
537
+ case "--report":
538
+ out.report = take(flag, inline);
539
+ break;
540
+ case "--html":
541
+ out.html = take(flag, inline);
542
+ break;
543
+ case "--reporter": {
544
+ const reporter = take(flag, inline).toLowerCase();
545
+ if (!REPORTERS.includes(reporter)) throw new UsageError(`--reporter takes ${REPORTERS.slice(0, -1).join(", ")} or ${REPORTERS.at(-1)} (got "${reporter}")`);
546
+ out.reporter = reporter;
547
+ break;
548
+ }
549
+ case "--parallel": {
550
+ const raw = take(flag, inline);
551
+ const n = Number(raw);
552
+ if (!Number.isInteger(n) || n < 1) throw new UsageError(`--parallel takes a whole number of at least 1 (got "${raw}")`);
553
+ out.parallel = n;
554
+ break;
555
+ }
556
+ case "--guards-file":
557
+ out.guardsFile = take(flag, inline);
558
+ break;
559
+ case "--env": {
560
+ let pair;
561
+ try {
562
+ pair = parseEnvPair(take(flag, inline));
563
+ } catch (error) {
564
+ throw error instanceof UsageError ? error : new UsageError(error.message);
565
+ }
566
+ out.env[pair[0]] = pair[1];
567
+ break;
568
+ }
569
+ case "--json":
570
+ out.json = true;
571
+ break;
572
+ case "--describe":
573
+ out.describe = true;
574
+ break;
575
+ case "--state":
576
+ out.stateFile = take(flag, inline);
577
+ break;
578
+ case "--state-readonly":
579
+ out.stateReadonly = true;
580
+ break;
581
+ case "--log-format": {
582
+ const format = take(flag, inline);
583
+ if (format !== "text" && format !== "json") throw new UsageError(`--log-format takes text or json (got "${format}")`);
584
+ out.logFormat = format;
585
+ break;
586
+ }
587
+ case "--only-needed":
588
+ out.onlyNeeded = true;
589
+ break;
590
+ case "--lib":
591
+ out.lib.push(take(flag, inline));
592
+ break;
593
+ case "--pkg":
594
+ out.pkg.push(take(flag, inline));
595
+ break;
596
+ case "--trust-file":
597
+ out.trustFile = take(flag, inline);
598
+ break;
599
+ case "--media-data":
600
+ out.mediaData = true;
601
+ break;
602
+ case "--use-pins":
603
+ out.usePins = true;
604
+ break;
605
+ case "--log":
606
+ out.log = take(flag, inline);
607
+ break;
608
+ case "--cost":
609
+ out.cost = true;
610
+ break;
611
+ case "--retain":
612
+ case "--retain-pane":
613
+ case "--sample-runs":
614
+ case "--sample-items":
615
+ retentionFlag(out, flag, take(flag, inline));
616
+ break;
617
+ case "--drop-text":
618
+ retentionFlag(out, flag);
619
+ break;
620
+ case "--allow-host":
621
+ out.allowHosts.push(...take(flag, inline).split(",").map((s) => s.trim().toLowerCase()).filter(Boolean));
622
+ break;
623
+ case "--allow-all-hosts":
624
+ out.allowAllHosts = true;
625
+ break;
626
+ case "--allow-local":
627
+ out.allowLocal = true;
628
+ break;
629
+ case "--isolate-panes":
630
+ out.isolatePanes = true;
631
+ break;
632
+ case "--sources":
633
+ out.sources = take(flag, inline);
634
+ break;
635
+ case "--allow-ffmpeg":
636
+ out.allowFfmpeg = take(flag, inline);
637
+ break;
638
+ case "--ffmpeg-dir":
639
+ out.ffmpegDir = take(flag, inline);
640
+ break;
641
+ case "--ffmpeg-overwrite":
642
+ out.ffmpegOverwrite = true;
643
+ break;
644
+ case "--companion":
645
+ out.companion = take(flag, inline);
646
+ break;
647
+ case "--companion-token-env": {
648
+ const name = take(flag, inline);
649
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new UsageError("--companion-token-env takes the name of an environment variable (the value itself never goes on the command line)");
650
+ out.companionTokenEnv = name;
651
+ break;
652
+ }
653
+ case "--companion-module":
654
+ (out.companionModules ??= []).push(take(flag, inline));
655
+ break;
656
+ case "--update-imports":
657
+ out.updateImports = true;
658
+ break;
659
+ case "--tick":
660
+ case "--ticks": {
661
+ const raw = take(flag, inline);
662
+ const n = Number(raw);
663
+ if (!Number.isInteger(n) || n < 1 || n > 10000) throw new UsageError(`--tick takes a whole number of ticks from 1 to 10000 (got "${raw}")`);
664
+ out.ticks = n;
665
+ break;
666
+ }
667
+ case "--virtual-now": {
668
+ const raw = take(flag, inline);
669
+ try {
670
+ out.virtualNow = parseVirtualNow(raw);
671
+ } catch (error) {
672
+ throw new UsageError(`--virtual-now: ${error.message}`);
673
+ }
674
+ break;
675
+ }
676
+ case "--advance": {
677
+ const raw = take(flag, inline);
678
+ try {
679
+ out.advanceMs = parseDuration(raw);
680
+ } catch (error) {
681
+ throw new UsageError(`--advance: ${error.message}`);
682
+ }
683
+ break;
684
+ }
685
+ case "--hash":
686
+ out.hash = true;
687
+ break;
688
+ case "--frame": {
689
+ const raw = take(flag, inline);
690
+ const n = Number(raw);
691
+ if (!Number.isSafeInteger(n) || n < 0 || raw.trim() === "") throw new UsageError(`--frame takes a whole number of 0 or more (got "${raw}")`);
692
+ out.frame = n;
693
+ out.frameGiven = true;
694
+ break;
695
+ }
696
+ case "--yields": {
697
+ const raw = take(flag, inline);
698
+ const n = Number(raw);
699
+ if (!Number.isInteger(n) || n < 1 || n > 100000) throw new UsageError(`--yields takes a whole number of values from 1 to 100000 (got "${raw}")`);
700
+ out.yields = n;
701
+ out.yieldsGiven = true; // an animation goes on to its end unless --yields is given
702
+ break;
703
+ }
704
+ case "--timeout": {
705
+ const raw = take(flag, inline);
706
+ const seconds = Number(raw);
707
+ if (!Number.isFinite(seconds) || seconds <= 0) throw new UsageError(`--timeout takes a number of seconds (got "${raw}")`);
708
+ out.timeoutMs = Math.round(seconds * 1000);
709
+ break;
710
+ }
711
+ default:
712
+ if (arg.startsWith("-") && arg !== "-") throw new UsageError(`unknown option ${flag}`);
713
+ positional.push(arg);
714
+ }
715
+ }
716
+ const [command, file, ...rest] = positional;
717
+ if (!command || command === "help") return { ...out, command: "help" };
718
+ if (command !== "run" && command !== "test" && command !== "simulate") throw new UsageError(`unknown command "${command}" (use run, test, simulate, cost, diff, machine, convert, deprecations, pkg, serve, grant, publish, render, companion or room-relay)`);
719
+ if (!file) throw new UsageError(`mallory ${command} needs a canvas file${command === "simulate" ? " and the pane" : ""}`);
720
+ const simPane = command === "simulate" ? rest[0] : undefined;
721
+ const extra = command === "simulate" ? rest.slice(1) : rest;
722
+ if (command === "simulate" && !simPane) throw new UsageError("mallory simulate needs a canvas file and the pane (mallory simulate canvas.mallory.json \"balls\" --frame 120)");
723
+ if (out.frameGiven && command !== "simulate") throw new UsageError("--frame is for mallory simulate");
724
+ if (out.hash && command !== "simulate") throw new UsageError("--hash is for mallory simulate");
725
+ if (command === "simulate" && (out.outputs.length || out.tests.length || out.dataset || out.predictions.length || out.report || out.parallel || out.stateFile || out.events.length || out.decisions?.length || out.decisionFiles?.length || out.approvals?.length || out.approvalFiles?.length || out.spendCap !== undefined || out.baseline || out.companion !== undefined || out.describe)) throw new UsageError("mallory simulate takes a canvas, a pane, --frame, --input and the network and library options (not run's or test's)");
726
+ if (extra.length) throw new UsageError(`unexpected argument "${extra[0]}"`);
727
+ if (command === "test" && (Object.keys(out.inputs).length || out.outputs.length)) throw new UsageError("mallory test takes its inputs and outputs from the canvas's tests");
728
+ if (out.reporter && command === "simulate") throw new UsageError("--reporter is for mallory test and mallory run");
729
+ if (out.reporter && out.json && out.reporter !== "json") throw new UsageError("--reporter and --json both choose the output (--reporter json is --json)");
730
+ if (out.reporter && out.describe) throw new UsageError("--reporter doesn't go with --describe");
731
+ if (command !== "test" && out.html) throw new UsageError("--html is for mallory test");
732
+ if (command === "run" && (out.dataset || out.predictions.length || out.report || out.parallel || out.baseline)) throw new UsageError("--dataset, --predictions, --parallel, --report and --baseline are for mallory test");
733
+ if (command === "test" && out.stateFile) throw new UsageError("mallory test starts every state pane from its initial value (no --state)");
734
+ if (out.cost && command !== "run") throw new UsageError("--cost is for mallory run (mallory cost <log> reports a run log)");
735
+ if (out.stateReadonly && !out.stateFile) throw new UsageError("--state-readonly goes with --state file.json");
736
+ if (command === "test" && out.ticks !== 1) throw new UsageError("--tick is for mallory run");
737
+ if (command === "test" && (out.virtualNow !== undefined || out.advanceMs)) throw new UsageError("--virtual-now and --advance are for mallory run");
738
+ if (out.advanceMs && out.virtualNow === undefined) throw new UsageError("--advance goes with --virtual-now (the instant the run starts at)");
739
+ if (command === "test" && out.yields !== 1) throw new UsageError("--yields is for mallory run (a test says its own: \"yields\": N)");
740
+ if (command === "test" && (out.decisions?.length || out.decisionFiles?.length)) throw new UsageError("--decision and --decisions are for mallory run");
741
+ if (command !== "run" && out.events.some((e) => e.serialReplay !== undefined)) throw new UsageError("--serial-replay is for mallory run");
742
+ if (command === "test" && out.events.length) throw new UsageError("--event and --send are for mallory run (a test says its own: \"events\": [{ to, name, payload }] or [{ channel, payload }])");
743
+ if (out.companion !== undefined || out.companionTokenEnv || out.companionModules) {
744
+ // Opt in, for a run only: verify and canvas tests stay on stand-ins. The command line is the consent.
745
+ if (command !== "run") throw new UsageError("--companion is for mallory run (mallory test and verify use the panes' stand-ins)");
746
+ if (out.companion === undefined || !out.companionTokenEnv || !out.companionModules?.length) throw new UsageError("--companion URL goes with --companion-token-env NAME and at least one --companion-module ID (the modules this run may use)");
747
+ const parsed = parseCompanionEndpoint(out.companion);
748
+ if (!parsed.ok) throw new UsageError(`--companion: ${parsed.reason}`);
749
+ for (const id of out.companionModules) if (!MODULE_ID.test(id)) throw new UsageError(`--companion-module takes a module id like echo (got "${id}")`);
750
+ out.companion = parsed.origin;
751
+ }
752
+ if (ffmpegFlagProblem(out)) throw new UsageError(ffmpegFlagProblem(out));
753
+ if (out.allowFfmpeg !== undefined && command !== "run") throw new UsageError("--allow-ffmpeg is for mallory run and mallory serve (mallory test and simulate don't start programs)");
754
+ if (out.describe && command !== "run") throw new UsageError("--describe is for mallory run");
755
+ if (out.describe && Object.keys(out.inputs).length) throw new UsageError("--describe runs nothing, so it takes no --input");
756
+ return { ...out, command, file, ...(simPane ? { pane: simPane } : {}) };
757
+ }
758
+
759
+ /**
760
+ * `--sources file.json`: package sources for import panes (src/sources/config.js),
761
+ * checked; `note` gets their warnings. A file that isn't sources is a usage error.
762
+ */
763
+ export async function readSources(file, note = () => {}) {
764
+ let text;
765
+ try {
766
+ text = await readFile(file, "utf8");
767
+ } catch (error) {
768
+ throw new UsageError(`--sources ${file}: ${error.code === "ENOENT" ? "no such file" : error.message}`);
769
+ }
770
+ try {
771
+ const { sources, warnings } = parseSources(text);
772
+ for (const w of warnings) note(`--sources ${file}: ${w}`);
773
+ return sources;
774
+ } catch (error) {
775
+ throw new UsageError(`--sources ${file}: ${error.message}`);
776
+ }
777
+ }
778
+
779
+ /** What --update-imports changed, a line each: "imports: d3@7 7.8.0 (esm.sh) → 7.9.0 (esm.sh)". */
780
+ export const importChangeLines = (changes = []) => (changes.length ? changes.map((c) => `imports: ${c.key} ${lockEntryText(c.before)} → ${lockEntryText(c.after)}`) : ["imports: nothing changed"]);
781
+
782
+ /** The variables for a run: MALLORY_ENV_* from the environment, then --env flags (which win). */
783
+ export const envFor = (options, processEnv = process.env) => ({ ...envFromProcess(processEnv), ...options.env });
784
+
785
+ /** How one value prints on its own line: text as is, anything else as JSON. */
786
+ export const printable = (value) => (typeof value === "string" ? value : JSON.stringify(value));
787
+
788
+ /** A tensor as a run reports it (plain JSON: `{ kind, shape, dtype, data }` with `data` a list)? */
789
+ const isTensorValue = (v) => Boolean(v) && typeof v === "object" && v.kind === "tensor" && Array.isArray(v.shape) && v.shape.every(Number.isInteger) && typeof v.dtype === "string" && v.dtype in DTYPES && Array.isArray(v.data);
790
+
791
+ /** A tensor's own lines, as the page's tensor preview words them: the summary, the statistics and the first values. */
792
+ function tensorLines(t) {
793
+ const data = t.data.map((x) => (typeof x === "string" ? Number(x) : x));
794
+ let min = Infinity;
795
+ let max = -Infinity;
796
+ let total = 0;
797
+ let finite = 0;
798
+ let nan = 0;
799
+ let inf = 0;
800
+ for (const v of data) {
801
+ if (Number.isNaN(v)) nan++;
802
+ else if (!Number.isFinite(v)) inf++;
803
+ else {
804
+ finite++;
805
+ total += v;
806
+ if (v < min) min = v;
807
+ if (v > max) max = v;
808
+ }
809
+ }
810
+ const mean = finite ? total / finite : NaN;
811
+ let sq = 0;
812
+ for (const v of data) if (Number.isFinite(v)) sq += (v - mean) ** 2;
813
+ const info = { dtype: t.dtype, shape: t.shape, elements: data.length, bytes: data.length * DTYPES[t.dtype].size, min: finite ? min : NaN, max: finite ? max : NaN, mean, std: finite ? Math.sqrt(sq / finite) : NaN, nan, inf };
814
+ const shown = TENSOR_VALUES_SHOWN;
815
+ const first = `data [${data.slice(0, shown).map(num).join(", ")}${data.length > shown ? ", …" : ""}]`;
816
+ return { head: `tensor ${tensorSummary(info)}`, rest: [statsLine(info), first].filter(Boolean) };
817
+ }
818
+
819
+ const TENSOR_VALUES_SHOWN = 6;
820
+
821
+ /**
822
+ * How a value prints in the human report: a tensor as a summary (shape, dtype, statistics, the first values), a
823
+ * tensor inside an object or list as a one-line summary, anything else as printable() does. The whole value is
824
+ * what --json prints.
825
+ */
826
+ export function describeValue(value, { name } = {}) {
827
+ const prefix = name === undefined ? "" : `${name} = `;
828
+ if (isTensorValue(value)) {
829
+ const { head, rest } = tensorLines(value);
830
+ return [`${prefix}${head}`, ...rest.map((l) => ` ${l}`)].join("\n");
831
+ }
832
+ const text = typeof value === "string" ? value : JSON.stringify(value, (_key, v) => (isTensorValue(v) ? tensorLines(v).head : v));
833
+ return `${prefix}${name === undefined || typeof value !== "string" ? text : JSON.stringify(value)}`;
834
+ }
835
+
836
+ /** The human report of a run: `name = value` lines (stdout), notes about panes that didn't finish (stderr). */
837
+ export function formatRun(result, { single, logFormat = "text" } = {}) {
838
+ const out = [];
839
+ const err = [];
840
+ for (const entry of result.logs) {
841
+ const { pane, level, text } = entry;
842
+ err.push(logFormat === "json" ? JSON.stringify({ ...entry, pane: pane ?? "sandbox" }) : `[${pane ?? "sandbox"}${level === "log" ? "" : ` ${level}`}] ${text}`);
843
+ }
844
+ const names = Object.keys(result.values);
845
+ if (single && names.length === 1) out.push(describeValue(result.values[names[0]]));
846
+ else for (const name of names) out.push(`${describeValue(result.values[name], { name })}${result.previews.includes(name) ? " (preview)" : ""}`);
847
+ for (const s of result.states) {
848
+ const who = s.name || s.id;
849
+ if (s.status === "done") {
850
+ if (s.fallback !== undefined) err.push(`${who}: fallback value, after: ${s.fallback}`);
851
+ continue;
852
+ }
853
+ if (s.status === "error") err.push(`${who}: error${s.line ? ` (line ${s.line})` : ""}: ${s.error}`);
854
+ else if (s.status === "skipped") err.push(`${who}: skipped (${s.note})`);
855
+ else err.push(`${who}: ${s.note ?? s.status}`);
856
+ }
857
+ for (const n of result.needsInput ?? []) err.push(`${n.pane}: needs input: “${n.title}” awaits a decision (${n.instances.map((i) => i.key || i.id).join(", ")}); pass --decision ${n.pane}='{"decision":"approve"${n.fields.length ? `,"values":{${n.fields.map((f) => `"${f}":…`).join(",")}}` : ""}}'`);
858
+ for (const c of result.caught ?? []) err.push(`[${c.catch}] caught from ${c.paneName}${c.attempt > 1 ? ` after ${c.attempt} attempts` : ""}${c.handled ? ` (${c.handled})` : ""}: ${c.message}`);
859
+ if (result.restarted) err.push(`(${result.restarted})`);
860
+ return { stdout: out.join("\n"), stderr: err.join("\n") };
861
+ }
862
+
863
+ /** `--input photo=@cat.png` for a media pane: the file's bytes as `{ data, type, name }`. */
864
+ export async function readMediaFiles(doc, inputs) {
865
+ const out = { ...inputs };
866
+ for (const [key, value] of Object.entries(inputs)) {
867
+ if (typeof value !== "string" || !value.startsWith("@")) continue;
868
+ let pane;
869
+ try {
870
+ pane = findPane(doc, key, "input");
871
+ } catch {
872
+ continue; // reported when the inputs are applied
873
+ }
874
+ if (pane.type !== "media") continue;
875
+ const path = value.slice(1);
876
+ let bytes;
877
+ try {
878
+ bytes = await readFile(path);
879
+ } catch (error) {
880
+ throw new Error(`input "${key}": can't read ${path}: ${error.code === "ENOENT" ? "no such file" : error.message}`);
881
+ }
882
+ out[key] = { data: toBase64(new Uint8Array(bytes)), type: typeFromName(path) || "application/octet-stream", name: basename(path) };
883
+ }
884
+ return out;
885
+ }
886
+
887
+ /** `--dataset file`: its rows, for the one evaluation being run (`{ testName: { rows } }`). */
888
+ /** The scripted approvals of a run or a test run: the flags' answers, then each --approvals file's, in order. */
889
+ export async function readApprovals(options) {
890
+ const list = [...(options.approvals ?? [])];
891
+ for (const file of options.approvalFiles ?? []) {
892
+ let parsed;
893
+ try {
894
+ parsed = JSON.parse(await readFile(file, "utf8"));
895
+ } catch (error) {
896
+ throw new Error(`--approvals ${file}: ${error.message}`);
897
+ }
898
+ const problem = approvalsProblem(parsed, `--approvals ${file}`);
899
+ if (problem) throw new Error(problem);
900
+ list.push(...parsed);
901
+ }
902
+ return list;
903
+ }
904
+
905
+ async function readDataset(doc, options) {
906
+ const label = (t, i) => t.name || `test ${i + 1}`;
907
+ const chosen = doc.tests.map((t, i) => ({ t, name: label(t, i) })).filter(({ t, name }) => isEvaluation(t) && (!options.tests.length || options.tests.includes(name)));
908
+ if (!chosen.length) throw new UsageError(`--dataset: ${options.tests.length ? "none of the tests named is an evaluation" : `${options.file} has no evaluations (tests with a dataset)`}`);
909
+ if (chosen.length > 1) throw new UsageError(`--dataset: ${options.file} has ${chosen.length} evaluations (${chosen.map((c) => `"${c.name}"`).join(", ")}); pick one with --test`);
910
+ let text;
911
+ try {
912
+ text = await readFile(options.dataset, "utf8");
913
+ } catch (error) {
914
+ throw new UsageError(`can't read ${options.dataset}: ${error.code === "ENOENT" ? "no such file" : error.message}`);
915
+ }
916
+ try {
917
+ return { [chosen[0].name]: { rows: parseDataset(text, { name: options.dataset }) } };
918
+ } catch (error) {
919
+ throw new UsageError(`${options.dataset}: ${error.message}`);
920
+ }
921
+ }
922
+
923
+ /** `--predictions name=file`: each file's predictions, for the one comparison being run (`{ testName: { candidate: [{ key, actual }] } }`). */
924
+ async function readPredictions(doc, options) {
925
+ const label = (t, i) => t.name || `test ${i + 1}`;
926
+ const chosen = doc.tests.map((t, i) => ({ t, name: label(t, i) })).filter(({ t, name }) => isEvaluation(t) && t.compare && (!options.tests.length || options.tests.includes(name)));
927
+ if (!chosen.length) throw new UsageError(`--predictions: ${options.tests.length ? "none of the tests named is an evaluation with a compare block" : `${options.file} has no evaluation with a compare block`}`);
928
+ if (chosen.length > 1) throw new UsageError(`--predictions: ${options.file} has ${chosen.length} comparisons (${chosen.map((c) => `"${c.name}"`).join(", ")}); pick one with --test`);
929
+ const byName = {};
930
+ for (const { name, file } of options.predictions) {
931
+ let text;
932
+ try {
933
+ text = await readFile(file, "utf8");
934
+ } catch (error) {
935
+ throw new UsageError(`can't read ${file}: ${error.code === "ENOENT" ? "no such file" : error.message}`);
936
+ }
937
+ try {
938
+ byName[name] = parsePredictions(text, { name: file });
939
+ } catch (error) {
940
+ throw new UsageError(`${file}: ${error.message}`);
941
+ }
942
+ }
943
+ try {
944
+ withSavedPredictions(chosen[0].t, byName); // refuses a pane's name and too many candidates now, not mid-run
945
+ } catch (error) {
946
+ throw new UsageError(`--predictions: ${error.message}`);
947
+ }
948
+ return { [chosen[0].name]: byName };
949
+ }
950
+
951
+ /** A state file's contents (src/model/persist-state.js parseStateFile); a missing file is empty. */
952
+ export async function readStateFile(file) {
953
+ let text;
954
+ try {
955
+ text = await readFile(file, "utf8");
956
+ } catch (error) {
957
+ if (error.code === "ENOENT") return parseStateFile({});
958
+ throw new UsageError(`can't read ${file}: ${error.message}`);
959
+ }
960
+ try {
961
+ return parseStateFile(JSON.parse(text));
962
+ } catch (error) {
963
+ throw new UsageError(`${file}: ${error instanceof SyntaxError ? `isn't JSON: ${error.message}` : error.message}`);
964
+ }
965
+ }
966
+
967
+ /** Write a state file whole (a temporary file, then a rename, so a crash never leaves half of one). */
968
+ export async function writeStateFile(file, data) {
969
+ const tmp = `${file}.${process.pid}.tmp`;
970
+ await writeFile(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 }); // (parked scheduled runs hold conversations: the owner reads it)
971
+ await rename(tmp, file);
972
+ }
973
+
974
+ /**
975
+ * `--retain MODE`, `--retain-pane PANE=MODE[:paths]`, `--drop-text`, `--sample-runs N` and `--sample-items N` (the run
976
+ * log's capture policies, src/model/retention.js), recorded on `out`. Shared
977
+ * with `mallory serve`.
978
+ */
979
+ export function retentionFlag(out, flag, value) {
980
+ if (flag === "--drop-text") out.retain = { ...out.retain, dropText: true };
981
+ else if (flag === "--sample-runs" || flag === "--sample-items") {
982
+ const n = Number(value);
983
+ const [lo, hi] = flag === "--sample-runs" ? [2, 1000] : [1, 1000];
984
+ if (!Number.isInteger(n) || n < lo || n > hi) throw new UsageError(`${flag} takes a whole number from ${lo} to ${hi} (got "${value}")`);
985
+ out.retain = { ...out.retain, [flag === "--sample-runs" ? "sampleEvery" : "sampleItems"]: n };
986
+ } else if (flag === "--retain") {
987
+ if (!["full", "redacted", "summary"].includes(value)) throw new UsageError(`--retain takes full, redacted or summary (got "${value}")`);
988
+ out.retain = { ...out.retain, mode: value };
989
+ } else {
990
+ try {
991
+ const [name, policy] = parsePaneRetention(value);
992
+ out.retainPanes = { ...out.retainPanes, [name]: policy };
993
+ } catch (error) {
994
+ throw new UsageError(`--retain-pane: ${error.message}`);
995
+ }
996
+ }
997
+ }
998
+
999
+ /** The capture policies the flags asked for: `{ default?, panes? }`, or undefined for none. */
1000
+ export function retentionOf(options) {
1001
+ if (!options.retain && !options.retainPanes) return undefined;
1002
+ return { ...(options.retain ? { default: options.retain } : {}), ...(options.retainPanes ? { panes: options.retainPanes } : {}) };
1003
+ }
1004
+
1005
+ /** Did a run succeed, for writing state back: every output finished and no pane failed (n8n's rule for static data). */
1006
+ export const runSucceeded = (result) => Boolean(result.ok) && !result.states.some((s) => s.status === "error");
1007
+
1008
+ /** Write the run log file (`--log`); a failure is reported, not fatal: the run's own result still counts. */
1009
+ async function writeLog(file, text, stderr) {
1010
+ try {
1011
+ await writeFile(file, text);
1012
+ } catch (error) {
1013
+ stderr(`mallory: can't write the run log to ${file}: ${error.message}`);
1014
+ }
1015
+ }
1016
+
1017
+ export async function load(file) {
1018
+ let text;
1019
+ try {
1020
+ text = await readFile(file, "utf8");
1021
+ } catch (error) {
1022
+ throw new UsageError(`can't read ${file}: ${error.code === "ENOENT" ? "no such file" : error.message}`);
1023
+ }
1024
+ // Any format mallory reads (src/formats/): .mallory.json, .mallory.yaml, .mallory.md, or another tool's file.
1025
+ let imported;
1026
+ try {
1027
+ imported = importCanvas(text, { name: file });
1028
+ validateTests(imported.doc.tests);
1029
+ } catch (error) {
1030
+ throw new UsageError(`${file}: ${error.message}`);
1031
+ }
1032
+ return imported;
1033
+ }
1034
+
1035
+ /**
1036
+ * A package's panes as `--lib` entries: each pane a canvas doc with the id a link to it has (`pkg:<package>/<pane>`), and the package's files (`assets`) a linked pane reads.
1037
+ * Its publisher signature is checked first (src/packages/trust.js): an invalid one is refused, and with a trust file (`trust`, trust-file.js)
1038
+ * the name's pinned key is too (the first signed copy pins it; `note` says so).
1039
+ */
1040
+ async function packageLib(text, file, { trust, note = () => {} } = {}) {
1041
+ const { pkg } = parsePackage(text);
1042
+ const decision = trustDecision(await packageSignature(text), trust?.pins.get(pkg.name));
1043
+ const refusal = trustRefusal(pkg.name, decision);
1044
+ if (refusal) throw new Error(trust && decision.block === "accept" ? `${refusal} (trust file ${trust.path})` : refusal);
1045
+ const after = pinAfter(decision);
1046
+ if (trust && after.set) {
1047
+ trust.pins.set(pkg.name, after.set);
1048
+ note(`pinned ${pkg.name} to ${after.set.fingerprint} in ${trust.path} (trust on first use)`);
1049
+ }
1050
+ const integrity = await integrityOf(text);
1051
+ return pkg.panes.map((pane) => ({ doc: paneDoc(pkg, pane.id, integrity), file: `${file} (${pkg.name}@${pkg.packageVersion} ${pane.id})`, ...(pkg.assets ? { assets: pkg.assets.map(({ name, type, data }) => ({ name, type, data })) } : {}) }));
1052
+ }
1053
+
1054
+ /**
1055
+ * `--pkg file`: pane packages (src/packages/package.js), for linked subgraph
1056
+ * panes that use their panes. A file that isn't one is a usage error.
1057
+ * @returns {Promise<{ doc: object, file: string }[]>}
1058
+ */
1059
+ export async function readPkgs(paths, { trust, note } = {}) {
1060
+ const out = [];
1061
+ for (const path of paths) {
1062
+ let text;
1063
+ try {
1064
+ text = await readFile(path, "utf8");
1065
+ } catch (error) {
1066
+ throw new UsageError(`--pkg ${path}: ${error.code === "ENOENT" ? "no such file" : error.message}`);
1067
+ }
1068
+ try {
1069
+ out.push(...(await packageLib(text, path, { trust, note })));
1070
+ } catch (error) {
1071
+ throw new UsageError(`--pkg ${path}: ${error.message}`);
1072
+ }
1073
+ }
1074
+ return out;
1075
+ }
1076
+
1077
+ /** Everything `--lib` and `--pkg` give a run (src/model/links.js resolveLinks): packages first, so a pane id beats a canvas of the same id. */
1078
+ export async function libFor(options, note = () => {}) {
1079
+ if (!options.lib?.length && !options.pkg?.length) return [];
1080
+ let trust;
1081
+ if (options.trustFile) {
1082
+ try {
1083
+ trust = await openTrustFile(options.trustFile);
1084
+ } catch (error) {
1085
+ throw new UsageError(`--trust-file: ${error.message}`);
1086
+ }
1087
+ }
1088
+ const out = [...(await readPkgs(options.pkg ?? [], { trust, note })), ...(await readLib(options.lib ?? [], note, { trust }))];
1089
+ if (trust?.changed) await trust.save();
1090
+ return out;
1091
+ }
1092
+
1093
+ /**
1094
+ * `--lib dir` (or a file): the canvases in it, in any format mallory reads, for
1095
+ * linked subgraph panes (src/model/links.js resolveLinks), and the panes of
1096
+ * any pane package in it (as --pkg). Files that aren't canvases are left
1097
+ * out; `note` says why for the ones that look like one.
1098
+ * @returns {Promise<{ doc: object, file: string }[]>}
1099
+ */
1100
+ export async function readLib(paths, note = () => {}, { trust } = {}) {
1101
+ const out = [];
1102
+ for (const path of paths) {
1103
+ let info;
1104
+ try {
1105
+ info = await stat(path);
1106
+ } catch (error) {
1107
+ throw new UsageError(`--lib ${path}: ${error.code === "ENOENT" ? "no such file or directory" : error.message}`);
1108
+ }
1109
+ const files = info.isDirectory() ? (await readdir(path)).filter((n) => canvasLikeName(n) || isPackageName(n)).sort().map((name) => join(path, name)) : [path];
1110
+ for (const file of files) {
1111
+ try {
1112
+ const text = await readFile(file, "utf8");
1113
+ if (isPackageName(file) || looksLikePackage(text)) {
1114
+ out.push(...(await packageLib(text, file, { trust, note })));
1115
+ continue;
1116
+ }
1117
+ const { doc } = importCanvas(text, { name: file });
1118
+ out.push({ doc, file });
1119
+ } catch (error) {
1120
+ note(`--lib ${file}: left out (${error.message})`);
1121
+ }
1122
+ }
1123
+ }
1124
+ return out;
1125
+ }
1126
+
1127
+ /**
1128
+ * Run the CLI. Returns the exit code: 0 success, 1 a failed output or test,
1129
+ * 2 a usage error (bad arguments, an unreadable canvas, no tests).
1130
+ * @param {string[]} argv
1131
+ * @param {{ stdout?: (text: string) => void, stderr?: (text: string) => void, createSession?: Function }} [io]
1132
+ */
1133
+ export async function main(argv, io = {}) {
1134
+ const { stdout = (t) => process.stdout.write(`${t}\n`), stderr = (t) => process.stderr.write(`${t}\n`), createSession } = io;
1135
+ const command = argv.findIndex((a) => !a.startsWith("-"));
1136
+ if (argv[command] === "serve") return (await import("./serve-cli.js")).serveMain(argv.toSpliced(command, 1), { ...io, stdout, stderr });
1137
+ if (argv[command] === "grant") return (await import("./grant-cli.js")).grantMain(argv.toSpliced(command, 1), { ...io, stdout, stderr });
1138
+ if (argv[command] === "companion") return (await import("./companion-cli.js")).companionMain(argv.toSpliced(command, 1), { ...io, stdout, stderr });
1139
+ if (argv[command] === "room-relay") return (await import("./room-relay.js")).roomRelayMain(argv.toSpliced(command, 1), { stdout, stderr });
1140
+ if (argv[command] === "render") return (await import("./render-cli.js")).renderMain(argv.toSpliced(command, 1), { stdout, stderr });
1141
+ if (argv[command] === "publish") return (await import("./publish.js")).publishMain(argv.toSpliced(command, 1), { ...io, stdout, stderr });
1142
+ if (argv[command] === "cost") return (await import("./cost-cli.js")).costMain(argv.toSpliced(command, 1), { stdout, stderr });
1143
+ if (argv[command] === "machine") return (await import("./machine-cli.js")).machineMain(argv.toSpliced(command, 1), { ...io, stdout, stderr });
1144
+ if (argv[command] === "diff") return (await import("./diff-cli.js")).diffMain(argv.toSpliced(command, 1), { stdout, stderr });
1145
+ if (argv[command] === "pkg") return (await import("./pkg-cli.js")).pkgMain(argv.toSpliced(command, 1), { ...io, stdout, stderr });
1146
+ if (argv[command] === "deprecations") return (await import("./deprecations-cli.js")).deprecationsMain(argv.toSpliced(command, 1), { stdout, stderr });
1147
+ if (argv[command] === "convert") return (await import("./convert-cli.js")).convertMain(argv.toSpliced(command, 1), { stdout, stderr });
1148
+ let options;
1149
+ try {
1150
+ options = parseArgs(argv);
1151
+ } catch (error) {
1152
+ if (!(error instanceof UsageError)) throw error;
1153
+ stderr(`mallory: ${error.message}\nRun mallory --help for usage.`);
1154
+ return 2;
1155
+ }
1156
+ if (options.command === "help") {
1157
+ stdout(HELP);
1158
+ return 0;
1159
+ }
1160
+ let doc;
1161
+ let datasets = {};
1162
+ let predictions = {};
1163
+ let state;
1164
+ let sources;
1165
+ const assetsByPackage = new Map(); // "<package>@<version>" -> the files its panes read as `assets` (--pkg, --lib)
1166
+ const modulesByPackage = new Map(); // "<package>@<version>" -> its shared module, `pkg.module` (--pkg; a canvas's carried copy comes first)
1167
+ try {
1168
+ const imported = await load(options.file);
1169
+ doc = imported.doc;
1170
+ for (const note of imported.notes) stderr(`mallory: ${options.file}: ${note}`); // what an import from another tool couldn't keep
1171
+ if (options.command === "test" && !doc.tests?.length && !hasChartTests(doc)) throw new UsageError(`${options.file} has no tests`);
1172
+ // Linked subgraph panes: the newest version given (--lib, then the canvas's library), else their own copy.
1173
+ const lib = await libFor(options, (t) => stderr(`mallory: ${t}`));
1174
+ for (const entry of lib) if (entry.assets) assetsByPackage.set(`${entry.doc.package.name}@${entry.doc.package.version}`, entry.assets);
1175
+ for (const entry of lib) if (entry.doc.packageModule) modulesByPackage.set(`${entry.doc.package.name}@${entry.doc.package.version}`, moduleFor(entry.doc.package.name, entry.doc.package.version, entry.doc.packageModule));
1176
+ const linked = resolveLinks(doc, { lib });
1177
+ doc = linked.doc;
1178
+ for (const note of linked.notes) stderr(`mallory: ${note}`);
1179
+ if (options.dataset) datasets = await readDataset(doc, options);
1180
+ if (options.predictions.length) predictions = await readPredictions(doc, options);
1181
+ if (options.stateFile) state = fileStateStore(await readStateFile(options.stateFile), { skipRead: Object.keys(options.inputs) });
1182
+ if (options.sources) sources = await readSources(options.sources, (t) => stderr(`mallory: ${t}`));
1183
+ } catch (error) {
1184
+ if (!(error instanceof UsageError)) throw error;
1185
+ stderr(`mallory: ${error.message}`);
1186
+ return 2;
1187
+ }
1188
+ // Scripted approvals: --approve, --deny and --amend, then each --approvals file (a JSON array of { tool, decision, … }).
1189
+ let approvals;
1190
+ try {
1191
+ approvals = await readApprovals(options);
1192
+ } catch (error) {
1193
+ stderr(`mallory: ${error.message}`);
1194
+ return 2;
1195
+ }
1196
+ if (options.describe) {
1197
+ // The signature only: nothing runs, so no sandbox starts.
1198
+ const { describeCanvas, formatSignature } = await import("../run/describe.js");
1199
+ let sig;
1200
+ try {
1201
+ sig = describeCanvas(doc, { outputs: options.outputs });
1202
+ } catch (error) {
1203
+ stderr(`mallory: ${error.message}`);
1204
+ return 2;
1205
+ }
1206
+ stdout(options.json ? JSON.stringify(sig, null, 2) : formatSignature(sig));
1207
+ return 0;
1208
+ }
1209
+ let ffmpeg;
1210
+ try {
1211
+ ffmpeg = ffmpegFromFlags(options);
1212
+ } catch (error) {
1213
+ stderr(`mallory: ${error.message}`);
1214
+ return 2;
1215
+ }
1216
+ let companion;
1217
+ if (options.companion) {
1218
+ // Opt-in (--companion): the person's flags are the consent; the token comes from the named environment variable.
1219
+ const token = process.env[options.companionTokenEnv];
1220
+ if (!token) {
1221
+ stderr(`mallory: --companion-token-env ${options.companionTokenEnv}: that environment variable isn't set`);
1222
+ return 2;
1223
+ }
1224
+ try {
1225
+ companion = await (await import("./companion-client.js")).connectCompanion({ url: options.companion, token, modules: options.companionModules });
1226
+ } catch (error) {
1227
+ stderr(`mallory: --companion: ${error.message}`);
1228
+ return 2;
1229
+ }
1230
+ stderr(`mallory: companion at ${companion.origin}: ${companion.grants.length ? `using ${companion.grants.join(", ")}` : "no module is usable"}${companion.unavailable.length ? `; unavailable: ${companion.unavailable.join(", ")}` : ""}`);
1231
+ }
1232
+ // The operator's guards for agent panes (--guards-file; src/headless/guards.js): a bad file stops the run. Without one, the safe defaults.
1233
+ {
1234
+ const guards = await import("./guards.js");
1235
+ try {
1236
+ guards.installGuards(options.guardsFile ? await guards.readGuardsFile(options.guardsFile) : guards.DEFAULT_GUARDS);
1237
+ guards.fingerprintSecrets(Object.entries(options.env).map(([name, value]) => ({ name: `env ${name}`, value })));
1238
+ } catch (error) {
1239
+ if (!(error instanceof guards.GuardFileError)) throw error;
1240
+ stderr(`mallory: ${error.message}`);
1241
+ return 2;
1242
+ }
1243
+ }
1244
+ const make = createSession ?? (await import("./node.js")).createNodeSession;
1245
+ const session = make({ timeoutMs: options.timeoutMs, allowHosts: options.allowHosts, allowAllHosts: options.allowAllHosts, allowLocal: options.allowLocal, ...(options.isolatePanes ? { isolate: true } : {}), env: envFor(options), ...(sources ? { sources } : {}), ...(options.updateImports ? { relockImports: true } : {}), ...(retentionOf(options) ? { retention: retentionOf(options) } : {}), ...(companion ? { companion } : {}), ...(ffmpeg ? { ffmpeg } : {}), ...(assetsByPackage.size ? { packageAssets: (ref) => assetsByPackage.get(`${ref.package}@${ref.version}`) } : {}), ...(modulesByPackage.size ? { packageModule: (ref) => modulesByPackage.get(`${ref.package}@${ref.version}`) } : {}) });
1246
+ if (options.spendCap) session.spendCap = options.spendCap; // every run and test of this command: the cap for simulated x402 payments
1247
+ try {
1248
+ if (options.command === "simulate") {
1249
+ let at;
1250
+ try {
1251
+ const { simulatePane } = await import("../sim/headless.js");
1252
+ at = await simulatePane(doc, options.pane, options.frame, session, { inputs: await readMediaFiles(doc, options.inputs), hash: options.hash === true });
1253
+ } catch (error) {
1254
+ stderr(`mallory: ${error.message}`);
1255
+ return 2;
1256
+ }
1257
+ stdout(options.hash && !options.json ? at.hash : JSON.stringify(options.json ? at : at.state, null, 2));
1258
+ return 0;
1259
+ }
1260
+ if (options.command === "run") {
1261
+ let result;
1262
+ try {
1263
+ const inputs = await readMediaFiles(doc, options.inputs);
1264
+ const decisions = [...(options.decisions ?? [])];
1265
+ for (const file of options.decisionFiles ?? []) {
1266
+ let list;
1267
+ try {
1268
+ list = JSON.parse(await readFile(file, "utf8"));
1269
+ } catch (error) {
1270
+ throw new Error(`--decisions ${file}: ${error.message}`);
1271
+ }
1272
+ if (!Array.isArray(list) || list.some((d) => !d || typeof d !== "object" || typeof d.pane !== "string")) throw new Error(`--decisions ${file}: a JSON array of { pane, decision, values?, … }`);
1273
+ decisions.push(...list);
1274
+ }
1275
+ result = await session.run(doc, { inputs, outputs: options.outputs, mediaData: options.mediaData, state, ticks: options.ticks, virtualNow: options.virtualNow, advanceMs: options.advanceMs, yields: options.yieldsGiven ? options.yields : undefined, events: options.events, decisions, ...(approvals.length ? { approvals: { entries: approvals, strict: 0, source: "the command line" } } : {}), usePins: options.usePins, log: Boolean(options.log) || options.cost, holds: options.cost, onlyNeeded: options.onlyNeeded });
1276
+ } catch (error) {
1277
+ stderr(`mallory: ${error.message}`);
1278
+ return 2;
1279
+ }
1280
+ if (state && !options.stateReadonly) {
1281
+ if (!runSucceeded(result)) stderr(`mallory: ${options.stateFile} not written: the run didn't succeed`);
1282
+ else if (state.changed) {
1283
+ try {
1284
+ await writeStateFile(options.stateFile, state.toJSON());
1285
+ } catch (error) {
1286
+ stderr(`mallory: can't write ${options.stateFile}: ${error.message}`);
1287
+ return 1;
1288
+ }
1289
+ }
1290
+ }
1291
+ if (options.updateImports && result.imports) for (const line of importChangeLines(result.imports)) stderr(`mallory: ${line}`);
1292
+ // What the scripted approvals answered (the calls they had no answer for were refused).
1293
+ for (const a of result.approvals?.answered ?? []) stderr(`mallory: approval for ${a.server === "agent" ? a.tool : `${a.server}.${a.tool}`}: ${a.decision === "unanswered" ? "no scripted answer, refused" : `${a.decision} (scripted answer ${a.entry})`}`);
1294
+ // The x402 payment requests (simulated) and what each got.
1295
+ for (const p of result.payments ?? []) stderr(`mallory: x402 payment (simulated) ${p.amount ?? ""}${p.payTo ? ` to ${p.payTo}` : ""} for ${p.from}: ${p.outcome}${p.reason ? ` (${p.reason})` : ""}`);
1296
+ let cost;
1297
+ if (options.cost) {
1298
+ // The cost report of this run (src/headless/cost-cli.js); the runs and holds it was made from are not part of the result.
1299
+ const { costOf } = await import("./cost-cli.js");
1300
+ cost = costOf(result.runs ?? [], { holds: result.holds ?? {} });
1301
+ const { holds, ...rest } = result;
1302
+ result = rest;
1303
+ }
1304
+ if (options.log) {
1305
+ const { runs = [], ...rest } = result;
1306
+ result = rest;
1307
+ await writeLog(options.log, runs.map((r) => JSON.stringify(r)).join("\n") + (runs.length ? "\n" : ""), stderr);
1308
+ } else if (options.cost) {
1309
+ const { runs, ...rest } = result;
1310
+ result = rest;
1311
+ }
1312
+ if (options.reporter === "tap" || options.reporter === "junit") {
1313
+ // The run as a report, a point per pane; console output and what failed still go to stderr.
1314
+ const text = formatRun(result, { single: false, logFormat: options.logFormat });
1315
+ if (text.stderr) stderr(text.stderr);
1316
+ stdout(formatWith(options.reporter, reportFromRun(result), { name: basename(options.file) }));
1317
+ if (cost) stderr(cost.text());
1318
+ } else if (options.json || options.reporter === "json") stdout(JSON.stringify(cost ? { ...result, cost: cost.json() } : result, null, 2));
1319
+ else {
1320
+ const text = formatRun(result, { single: options.outputs.length === 1, logFormat: options.logFormat });
1321
+ if (text.stderr) stderr(text.stderr);
1322
+ if (cost) stderr(cost.text());
1323
+ if (text.stdout) stdout(text.stdout);
1324
+ }
1325
+ return result.ok ? 0 : 1;
1326
+ }
1327
+ const report = await runTests(doc, session, { only: options.tests, datasets, predictions, ...(options.parallel ? { parallel: options.parallel } : {}), log: Boolean(options.log), ...(approvals.length ? { approvals } : {}) });
1328
+ // A statechart pane's saved event sequences run on virtual time, after the canvas's own tests.
1329
+ const chartRuns = docChartTests(doc, options.tests);
1330
+ if (chartRuns.length) {
1331
+ report.results.push(...chartRuns);
1332
+ report.passed = report.results.filter((r) => r.pass).length;
1333
+ report.failed = report.results.length - report.passed;
1334
+ report.pass = report.failed === 0;
1335
+ }
1336
+ if (options.log) {
1337
+ // A test's runs; an evaluation's rows, a line each (its row number too).
1338
+ const lines = report.results.flatMap((r) => [...(r.runs ?? []).map((run) => JSON.stringify({ test: r.name, ...run })), ...(r.rows ?? []).filter((row) => row.run).map((row) => JSON.stringify({ test: r.name, row: row.index + 1, ...row.run }))]);
1339
+ for (const r of report.results) {
1340
+ delete r.runs;
1341
+ for (const row of r.rows ?? []) delete row.run;
1342
+ }
1343
+ await writeLog(options.log, lines.join("\n") + (lines.length ? "\n" : ""), stderr);
1344
+ }
1345
+ if (options.tests.length && !report.results.length) {
1346
+ stderr(`mallory: no test named ${options.tests.map((t) => `"${t}"`).join(", ")}`);
1347
+ return 2;
1348
+ }
1349
+ // Regressions against an earlier report (--baseline): a matrix cell that passed then and fails now.
1350
+ let regressed = false;
1351
+ if (options.baseline) {
1352
+ let base;
1353
+ try {
1354
+ base = JSON.parse(await readFile(options.baseline, "utf8"));
1355
+ if (!Array.isArray(base?.results)) throw new Error("it isn't a mallory test report ({ pass, results })");
1356
+ } catch (error) {
1357
+ stderr(`mallory: --baseline ${options.baseline}: ${error.message}`);
1358
+ return 2;
1359
+ }
1360
+ const { compareMatrix, matrixSummary, formatMatrixComparison } = await import("../tests/matrix.js");
1361
+ const lines = [];
1362
+ for (const r of report.results.filter((x) => x.matrix)) {
1363
+ const before = base.results.find((x) => x.name === r.name && x.matrix);
1364
+ if (!before) {
1365
+ lines.push(` ${r.name}: not in the baseline`);
1366
+ continue;
1367
+ }
1368
+ const cmp = compareMatrix(matrixSummary(before), matrixSummary(r));
1369
+ r.baseline = cmp;
1370
+ if (cmp.regressions.length) regressed = true;
1371
+ lines.push(...formatMatrixComparison(r.name, cmp));
1372
+ }
1373
+ if (!options.json && !options.reporter) stderr(`mallory: compared with ${options.baseline}: ${regressed ? "regressions" : "no regressions"}${lines.length ? `\n${lines.join("\n")}` : ""}`);
1374
+ }
1375
+ stdout(options.reporter ? formatWith(options.reporter, report, { name: basename(options.file) }) : options.json ? JSON.stringify(report, null, 2) : formatReport(report));
1376
+ if (options.html) {
1377
+ try {
1378
+ await writeFile(options.html, reportHtml(report, { title: basename(options.file) }));
1379
+ } catch (error) {
1380
+ stderr(`mallory: can't write ${options.html}: ${error.message}`);
1381
+ return 2;
1382
+ }
1383
+ }
1384
+ if (options.report) {
1385
+ try {
1386
+ await writeFile(options.report, `${JSON.stringify(report, null, 2)}\n`);
1387
+ } catch (error) {
1388
+ stderr(`mallory: can't write ${options.report}: ${error.message}`);
1389
+ return 2;
1390
+ }
1391
+ }
1392
+ return report.pass && !regressed ? 0 : 1;
1393
+ } finally {
1394
+ await session.dispose();
1395
+ await companion?.close();
1396
+ }
1397
+ }