@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.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
package/src/run/run.js
ADDED
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
// Running a canvas without the editor: the real Canvas model and dataflow on
|
|
2
|
+
// a sandbox runtime, with no views. Works anywhere the runtime does: under
|
|
3
|
+
// Node (src/headless/node.js, the `mallory` CLI) and on the page (canvas tests,
|
|
4
|
+
// src/tests/ui.js, with a second sandbox so the open canvas is untouched).
|
|
5
|
+
//
|
|
6
|
+
// Pane types that need a browser page (DOM, html, effects, shader, embed, render,
|
|
7
|
+
// audio: their records say `headless: { skip }`) are skipped; panes that read
|
|
8
|
+
// them wait.
|
|
9
|
+
import { lockChanges, cleanImportLock } from "../model/import-lock.js";
|
|
10
|
+
import { Canvas, widgetValue } from "../model/canvas.js";
|
|
11
|
+
import { validate } from "../persist.js";
|
|
12
|
+
import { previewText, toJSONSafe, mediaForJSON } from "./values.js";
|
|
13
|
+
import { describeForContent, toBase64 } from "../media/persist.js";
|
|
14
|
+
import { kindOf as mediaKindOf } from "../media/contract.js";
|
|
15
|
+
import { virtualClock, advanceCanvas } from "../model/virtual-clock.js";
|
|
16
|
+
import { collectHolds } from "../model/wait-clock.js";
|
|
17
|
+
import { renameGraph, ownsRuntimeId, canvasFor, innerCanvases, SEP } from "../model/subgraph.js";
|
|
18
|
+
import { nextTask } from "../model/turns.js";
|
|
19
|
+
import { stripPins } from "../model/pin.js";
|
|
20
|
+
import { expandFixtures } from "../model/decisions.js";
|
|
21
|
+
import { approvalsProblem, createApprovalScript } from "../gate/scripted.js";
|
|
22
|
+
import { runJSON, configPolicy } from "../model/runlog.js";
|
|
23
|
+
import { retentionFor } from "../model/retention.js";
|
|
24
|
+
import { PANE_RECORDS, typesWhere, inDataflow, trait } from "../panes/registry.js";
|
|
25
|
+
import { listWords } from "../panes/fields.js";
|
|
26
|
+
import { disabledByGroups, remapGroups } from "../model/groups.js";
|
|
27
|
+
import { parseConsoleArgs, consoleText } from "../runtime/console-tag.js";
|
|
28
|
+
import { previewToJSON } from "../model/value-path.js";
|
|
29
|
+
import { webhookSettings, requestInput, normalizePath, matchRoute, CATCH_ALL } from "../model/webhook.js";
|
|
30
|
+
import { routerSettings } from "../model/router.js";
|
|
31
|
+
import { watchSettings, WATCH_EVENTS } from "../model/watch.js";
|
|
32
|
+
import { coerceValue, unitsEngine } from "../model/types.js";
|
|
33
|
+
import { isPadKind, padProblem, padValue } from "../model/widget-values.js";
|
|
34
|
+
import { readWhen, storedWhen } from "../model/when.js";
|
|
35
|
+
import { storedQuantity } from "../model/quantity-widget.js";
|
|
36
|
+
import { storedGrid } from "../model/grid-widget.js";
|
|
37
|
+
import { storedMath } from "../model/math-widget.js";
|
|
38
|
+
import { outputsOf, portId } from "../model/ports.js";
|
|
39
|
+
import { SerialControls } from "../model/serial-controls.js";
|
|
40
|
+
import { article, paneKindError } from "../util/text.js";
|
|
41
|
+
|
|
42
|
+
/** Pane types a headless run skips, and why (their records' `headless`, src/panes/). */
|
|
43
|
+
export const SKIPPED_TYPES = Object.fromEntries(PANE_RECORDS.filter((r) => r.headless.skip).map((r) => [r.type, r.headless.skip]));
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Skipped types whose pane stays on the canvas anyway (`headless: { skip, held: true }`): nothing is ever read from
|
|
47
|
+
* them without a person, so they sit there skipped, as in a page where nobody has started them, and a pane that
|
|
48
|
+
* takes skips (eval's `takesSkips`) runs on without them instead of waiting on a pane that is not there.
|
|
49
|
+
*/
|
|
50
|
+
const HELD_TYPES = new Set(PANE_RECORDS.filter((r) => r.headless.skip && r.headless.held).map((r) => r.type));
|
|
51
|
+
const runsHeadless = (pane) => !SKIPPED_TYPES[pane.type] || HELD_TYPES.has(pane.type);
|
|
52
|
+
|
|
53
|
+
/** Pane types a headless run runs. */
|
|
54
|
+
export const HANDLED_TYPES = typesWhere((r) => r.headless === "run");
|
|
55
|
+
|
|
56
|
+
/** Pane types `inputs` can set: their records' `runInput`. */
|
|
57
|
+
export const INPUT_TYPES = typesWhere((r) => r.runInput);
|
|
58
|
+
|
|
59
|
+
const label = (pane) => pane.name || pane.id;
|
|
60
|
+
const TRUE = new Set(["true", "1", "yes", "on"]);
|
|
61
|
+
const FALSE = new Set(["false", "0", "no", "off", ""]);
|
|
62
|
+
|
|
63
|
+
/** Find a pane by name, else by id. Throws a readable error for an unknown or ambiguous name. */
|
|
64
|
+
export function findPane(doc, key, role = "pane") {
|
|
65
|
+
const named = doc.panes.filter((p) => p.name && p.name === key);
|
|
66
|
+
if (named.length > 1) throw new Error(`${role} "${key}": ${named.length} panes have that name`);
|
|
67
|
+
const pane = named[0] ?? doc.panes.find((p) => p.id === key);
|
|
68
|
+
if (!pane) {
|
|
69
|
+
const names = doc.panes.filter((p) => p.name).map((p) => p.name);
|
|
70
|
+
throw new Error(`${role} "${key}": no pane has that name${names.length ? ` (panes: ${names.join(", ")})` : ""}`);
|
|
71
|
+
}
|
|
72
|
+
return pane;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Set a pane from an input value. Input panes take the value their widget
|
|
77
|
+
* kind holds (numbers for number and range, booleans for checkbox, one of the
|
|
78
|
+
* options for select, any JSON value for json and form); text panes take
|
|
79
|
+
* text; state panes take the value as their initial value.
|
|
80
|
+
*/
|
|
81
|
+
export function applyInput(pane, value) {
|
|
82
|
+
const name = label(pane);
|
|
83
|
+
if (trait(pane.type, "textValue")) {
|
|
84
|
+
pane.text = typeof value === "string" ? value : JSON.stringify(value);
|
|
85
|
+
return pane;
|
|
86
|
+
}
|
|
87
|
+
if (pane.type === "state") {
|
|
88
|
+
pane.code = value === undefined ? "undefined" : JSON.stringify(value);
|
|
89
|
+
return pane;
|
|
90
|
+
}
|
|
91
|
+
if (pane.type === "media") {
|
|
92
|
+
pane.media = mediaInput(name, value);
|
|
93
|
+
return pane;
|
|
94
|
+
}
|
|
95
|
+
if (pane.type === "webhook") {
|
|
96
|
+
// The test request's body: text as text/plain, any other value as JSON. A value with only a method, path, query,
|
|
97
|
+
// headers and body (and a method a webhook answers) is the whole request.
|
|
98
|
+
const s = webhookSettings(pane.webhook);
|
|
99
|
+
const whole = requestInput(value);
|
|
100
|
+
if (whole) {
|
|
101
|
+
for (const [k, kind] of [["headers", "object"], ["query", "object"]]) if (whole[k] !== undefined && (!whole[k] || typeof whole[k] !== kind || Array.isArray(whole[k]))) throw new Error(`input "${name}": a request's ${k} are an object of names and values`);
|
|
102
|
+
if (whole.path !== undefined && typeof whole.path !== "string") throw new Error(`input "${name}": a request's path is text`);
|
|
103
|
+
// A path names a route this webhook answers: a path it doesn't match would be answered by
|
|
104
|
+
// the route anyway and the input would look applied when it wasn't.
|
|
105
|
+
if (typeof whole.path === "string" && s.path !== CATCH_ALL && !matchRoute(s.path, normalizePath(whole.path))) throw new Error(`input "${name}": the request path "${whole.path}" isn't webhook "${name}"'s route, which is /${s.path}; a webhook answers only its own route, so pass a path in the query (or a body) for the canvas's own code to read`);
|
|
106
|
+
const body = whole.body;
|
|
107
|
+
const text = typeof body === "string";
|
|
108
|
+
const test = { ...s.test, method: whole.method.toUpperCase(), query: whole.query ? String(new URLSearchParams(Object.entries(whole.query).map(([k, v]) => [k, String(v)]))) : "", contentType: text ? "text/plain" : "application/json", body: text ? body : JSON.stringify(body ?? null) };
|
|
109
|
+
if (whole.path !== undefined) test.path = whole.path;
|
|
110
|
+
else delete test.path;
|
|
111
|
+
if (whole.headers) test.headers = Object.fromEntries(Object.entries(whole.headers).map(([k, v]) => [k.toLowerCase(), String(v)]));
|
|
112
|
+
else delete test.headers;
|
|
113
|
+
pane.webhook = { ...pane.webhook, test };
|
|
114
|
+
return pane;
|
|
115
|
+
}
|
|
116
|
+
const text = typeof value === "string";
|
|
117
|
+
pane.webhook = { ...pane.webhook, test: { ...s.test, contentType: text ? "text/plain" : "application/json", body: text ? value : JSON.stringify(value ?? null) } };
|
|
118
|
+
return pane;
|
|
119
|
+
}
|
|
120
|
+
if (pane.type === "router") {
|
|
121
|
+
// The test request: a whole request, { method, path, query, headers, body }, routed through the table.
|
|
122
|
+
const whole = requestInput(value);
|
|
123
|
+
if (!whole) throw new Error(`input "${name}": a router takes a whole request: { method, path, query?, headers?, body? }`);
|
|
124
|
+
for (const [k, kind] of [["headers", "object"], ["query", "object"]]) if (whole[k] !== undefined && (!whole[k] || typeof whole[k] !== kind || Array.isArray(whole[k]))) throw new Error(`input "${name}": a request's ${k} are an object of names and values`);
|
|
125
|
+
if (whole.path !== undefined && typeof whole.path !== "string") throw new Error(`input "${name}": a request's path is text`);
|
|
126
|
+
const { headers: _headers, ...rest } = routerSettings(pane.router).test;
|
|
127
|
+
const text = typeof whole.body === "string";
|
|
128
|
+
const test = { ...rest, method: whole.method.toUpperCase(), path: normalizePath(whole.path ?? ""), query: whole.query ? String(new URLSearchParams(Object.entries(whole.query).map(([k, v]) => [k, String(v)]))) : "", contentType: text ? "text/plain" : "application/json", body: text ? whole.body : whole.body === undefined ? "" : JSON.stringify(whole.body) };
|
|
129
|
+
if (whole.headers) test.headers = Object.fromEntries(Object.entries(whole.headers).map(([k, v]) => [k.toLowerCase(), String(v)]));
|
|
130
|
+
pane.router = { ...pane.router, test };
|
|
131
|
+
return pane;
|
|
132
|
+
}
|
|
133
|
+
if (pane.type === "watch") {
|
|
134
|
+
// The test event: a file name, or { name, event, size }.
|
|
135
|
+
const s = watchSettings(pane.files);
|
|
136
|
+
const event = typeof value === "string" ? { name: value } : value && typeof value === "object" ? value : null;
|
|
137
|
+
if (!event || (event.event !== undefined && !WATCH_EVENTS.includes(event.event))) throw new Error(`input "${name}": a watch pane takes a file name, or { name, event (${WATCH_EVENTS.join(", ")}), size }`);
|
|
138
|
+
pane.files = { ...pane.files, test: { ...s.test, ...event } };
|
|
139
|
+
return pane;
|
|
140
|
+
}
|
|
141
|
+
if (pane.type !== "input") throw new Error(`input "${name}": it is ${article(pane.type)} ${pane.type} pane; inputs set ${listWords(INPUT_TYPES)} panes`);
|
|
142
|
+
// A declared type (src/model/types.js) converts first: "40" for a number, '[1,2]' for an array<number>.
|
|
143
|
+
if (pane.valueType !== undefined) {
|
|
144
|
+
try {
|
|
145
|
+
value = coerceValue(value, pane.valueType, unitsEngine);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
throw new Error(`input "${name}": ${error.message}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const widget = { ...pane.widget };
|
|
151
|
+
const kind = widget.kind;
|
|
152
|
+
if (kind === "number" || kind === "range") {
|
|
153
|
+
const n = typeof value === "string" && value.trim() === "" ? NaN : Number(value);
|
|
154
|
+
if (!Number.isFinite(n)) throw new Error(`input "${name}": expected a number, got ${JSON.stringify(value)}`);
|
|
155
|
+
widget.value = n;
|
|
156
|
+
} else if (kind === "checkbox") {
|
|
157
|
+
const text = String(value).trim().toLowerCase();
|
|
158
|
+
if (typeof value === "boolean") widget.value = value;
|
|
159
|
+
else if (TRUE.has(text)) widget.value = true;
|
|
160
|
+
else if (FALSE.has(text)) widget.value = false;
|
|
161
|
+
else throw new Error(`input "${name}": expected true or false, got ${JSON.stringify(value)}`);
|
|
162
|
+
} else if (kind === "select") {
|
|
163
|
+
const options = String(widget.options ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
164
|
+
const text = String(value);
|
|
165
|
+
if (options.length && !options.includes(text)) throw new Error(`input "${name}": ${JSON.stringify(text)} isn't one of its options (${options.join(", ")})`);
|
|
166
|
+
widget.value = text;
|
|
167
|
+
} else if (isPadKind(kind)) {
|
|
168
|
+
// An XY pad or curve: an object, or JSON text of one (`--input pad='{"x":0.2,"y":0.8}'`).
|
|
169
|
+
let given = value;
|
|
170
|
+
if (typeof given === "string") {
|
|
171
|
+
try {
|
|
172
|
+
given = JSON.parse(given);
|
|
173
|
+
} catch {
|
|
174
|
+
throw new Error(`input "${name}": expected JSON for ${kind === "xy" ? "{ x, y }" : "{ interpolation, points: [{ x, y }, …] }"}, got ${JSON.stringify(value)}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const problem = padProblem({ ...widget, value: given });
|
|
178
|
+
if (problem) throw new Error(`input "${name}": ${problem}`);
|
|
179
|
+
widget.value = padValue({ ...widget, value: given });
|
|
180
|
+
} else if (kind === "when") {
|
|
181
|
+
// A time in words ("tomorrow 9am", an ISO time), read now and stored as an instant; the stored form is kept as it is.
|
|
182
|
+
const stored = storedWhen(value);
|
|
183
|
+
const read = stored ? { ok: true, value: typeof value === "string" ? value : JSON.stringify(value) } : readWhen(typeof value === "string" ? value : value?.text ?? "", { zone: widget.zone ?? "" });
|
|
184
|
+
if (!read.ok) throw new Error(`input "${name}": ${read.error}`);
|
|
185
|
+
widget.value = read.value;
|
|
186
|
+
} else if (kind === "math") {
|
|
187
|
+
// LaTeX text, or { latex }, checked by the adapter that reads it as an expression; the stored form is the LaTeX.
|
|
188
|
+
try {
|
|
189
|
+
widget.value = storedMath(value);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
throw new Error(`input "${name}": ${error.message}`);
|
|
192
|
+
}
|
|
193
|
+
} else if (kind === "grid") {
|
|
194
|
+
// Grid text (WxH:bits), rows of 0 and 1, a list of live cells, or JSON text of one of those; the stored form is the canonical text.
|
|
195
|
+
try {
|
|
196
|
+
let given = value;
|
|
197
|
+
if (typeof given === "string" && /^\s*\[/.test(given)) given = JSON.parse(given);
|
|
198
|
+
widget.value = storedGrid(given, widget);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
throw new Error(`input "${name}": ${error.message}`);
|
|
201
|
+
}
|
|
202
|
+
} else if (kind === "quantity") {
|
|
203
|
+
// Text such as "5 km" or { value, unit }, read against the widget's dimension and unit; the stored form is the text.
|
|
204
|
+
try {
|
|
205
|
+
widget.value = storedQuantity(value, widget);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
throw new Error(`input "${name}": ${error.message}`);
|
|
208
|
+
}
|
|
209
|
+
} else if (kind === "json" || kind === "form") {
|
|
210
|
+
widget.value = JSON.stringify(value === undefined ? null : value);
|
|
211
|
+
} else {
|
|
212
|
+
widget.value = typeof value === "string" ? value : JSON.stringify(value);
|
|
213
|
+
}
|
|
214
|
+
pane.widget = widget;
|
|
215
|
+
widgetValue(widget); // throws now, not mid-run, if it can't be read
|
|
216
|
+
return pane;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* A media pane's content from an input value: an http(s) URL (fetched when it
|
|
221
|
+
* runs, through the network rules), a data: URL, or `{ data, type, name? }`
|
|
222
|
+
* with base64 bytes (the CLI's `--input photo=@file.png` makes this).
|
|
223
|
+
*/
|
|
224
|
+
export function mediaInput(name, value) {
|
|
225
|
+
if (typeof value === "string" && /^https?:\/\//i.test(value)) return { source: "url", url: value, stored: "url" };
|
|
226
|
+
let data;
|
|
227
|
+
let type;
|
|
228
|
+
let fileName;
|
|
229
|
+
if (typeof value === "string" && /^data:/i.test(value)) {
|
|
230
|
+
const comma = value.indexOf(",");
|
|
231
|
+
const head = value.slice(5, comma);
|
|
232
|
+
type = head.replace(/;base64$/i, "").split(";")[0];
|
|
233
|
+
const body = value.slice(comma + 1);
|
|
234
|
+
data = /;base64$/i.test(head) ? body : toBase64(new TextEncoder().encode(decodeURIComponent(body)));
|
|
235
|
+
} else if (value && typeof value === "object" && typeof value.data === "string") {
|
|
236
|
+
({ data, type = "", name: fileName } = value);
|
|
237
|
+
} else {
|
|
238
|
+
throw new Error(`input "${name}": a media pane takes an http(s) URL, a data: URL, or { data (base64), type, name } (on the command line, name=@file)`);
|
|
239
|
+
}
|
|
240
|
+
const size = Math.floor((data.length * 3) / 4) - (data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0);
|
|
241
|
+
const kind = mediaKindOf(type); // the one rule (a MIDI type is a file)
|
|
242
|
+
// Inline regardless of size: this copy of the canvas only lives for the run.
|
|
243
|
+
return { ...describeForContent({ $media: kind, blob: { type, size }, ...(fileName ? { name: fileName } : {}) }, { source: "data" }), stored: "inline", data };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** A copy of `doc` with `inputs` ({ paneName: value }) applied. */
|
|
247
|
+
export function applyInputs(doc, inputs = {}) {
|
|
248
|
+
const copy = structuredClone(doc);
|
|
249
|
+
for (const [key, value] of Object.entries(inputs ?? {})) applyInput(findPane(copy, key, "input"), value);
|
|
250
|
+
return copy;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* An output to report: a pane by name (or id), or "pane.output", one of its
|
|
255
|
+
* named outputs (src/model/ports.js), as `{ ...pane, port }`. A pane whose
|
|
256
|
+
* name has a dot in it wins over the output reading.
|
|
257
|
+
*/
|
|
258
|
+
export function findOutput(doc, key) {
|
|
259
|
+
const dot = key.lastIndexOf(".");
|
|
260
|
+
if (dot > 0 && !doc.panes.some((p) => p.name === key || p.id === key)) {
|
|
261
|
+
const pane = findPane(doc, key.slice(0, dot), "output");
|
|
262
|
+
const port = key.slice(dot + 1);
|
|
263
|
+
const names = outputsOf(pane).map((o) => o.name);
|
|
264
|
+
if (!names.includes(port)) throw new Error(`output "${key}": ${label(pane)} has no output "${port}"${names.length ? ` (its outputs: ${names.join(", ")})` : ""}`);
|
|
265
|
+
return { ...pane, port };
|
|
266
|
+
}
|
|
267
|
+
return findPane(doc, key, "output");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** The panes a run reports by default: named panes no other pane reads (DOM, html and embed panes aside: they are skipped, and so is their reading; notes have no value). */
|
|
271
|
+
export function defaultOutputs(doc) {
|
|
272
|
+
const read = new Set(doc.panes.filter((p) => !SKIPPED_TYPES[p.type]).flatMap((p) => (p.inputs ?? []).map((i) => i.source)));
|
|
273
|
+
return doc.panes.filter((p) => p.name && !read.has(p.id) && !SKIPPED_TYPES[p.type] && inDataflow(p.type)).map((p) => p.name);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* A canvas as a headless run sees it: notes left out (they hold no value),
|
|
278
|
+
* and a deactivated group's panes deactivated themselves, inside subgraphs
|
|
279
|
+
* too. Groups stay (a catch pane can listen to its group's panes); otherwise
|
|
280
|
+
* they are cosmetic.
|
|
281
|
+
*/
|
|
282
|
+
export function runnableDoc(doc) {
|
|
283
|
+
const flatten = (panes, groups) => {
|
|
284
|
+
const off = disabledByGroups(Array.isArray(groups) ? groups : []);
|
|
285
|
+
return panes
|
|
286
|
+
.filter((p) => inDataflow(p.type))
|
|
287
|
+
.map((p) => {
|
|
288
|
+
const out = off.has(p.id) ? { ...p, disabled: true } : p;
|
|
289
|
+
if (p.type !== "subgraph" || !p.graph) return out;
|
|
290
|
+
return { ...out, graph: { ...p.graph, panes: flatten(p.graph.panes ?? [], p.graph.groups) } };
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
return { ...doc, panes: flatten(doc.panes, doc.groups) };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* One sandbox runtime and the canvases run on it. Each run gets its own pane
|
|
298
|
+
* id namespace (`r1:`, `r2:`, …), so runs never see each other's values; the
|
|
299
|
+
* runtime (and modules it has imported) is reused.
|
|
300
|
+
*
|
|
301
|
+
* const session = new HeadlessSession((hooks) => createRuntime({ ...hooks, sources, network }));
|
|
302
|
+
* const { values, states, logs } = await session.run(doc, { inputs: { price: 40 } });
|
|
303
|
+
* await session.dispose();
|
|
304
|
+
*/
|
|
305
|
+
export class HeadlessSession {
|
|
306
|
+
#runs = new Set();
|
|
307
|
+
#count = 0;
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* @param {(hooks: { onStateChanged: Function, onConsole: Function, onRestart: Function }) => object} makeRuntime
|
|
311
|
+
* builds the runtime (see createRuntime in src/runtime/runtime.js) with these hooks.
|
|
312
|
+
* @param {{ checkUrl?: (url: string, context: object) => void, resolveImport?: Function, relockImports?: boolean }} [options]
|
|
313
|
+
* `checkUrl`: the network check for import panes; `resolveImport`: how they resolve a spec (the
|
|
314
|
+
* package sources, src/model/imports.js createImportResolver; default: the defaults);
|
|
315
|
+
* `relockImports`: they ignore the canvas's import lock and resolve again (`--update-imports`);
|
|
316
|
+
* `packageAssets(ref)`: the files (`[{ name, type, data }]`) of the package a linked pane's `ref` names (src/packages/assets.js).
|
|
317
|
+
* `packageModule(ref)`: the shared module (`{ package, version, name, source, integrity }`) of that package (src/packages/module.js), for a canvas that doesn't carry it.
|
|
318
|
+
*/
|
|
319
|
+
constructor(makeRuntime, { checkUrl, resolveImport, relockImports = false, retention, packageAssets, packageModule } = {}) {
|
|
320
|
+
this.checkUrl = checkUrl;
|
|
321
|
+
this.canvasOptions = { checkUrl, ...(resolveImport ? { resolveImport } : {}), ...(packageAssets ? { packageAssets } : {}), ...(packageModule ? { packageModule } : {}), relockImports };
|
|
322
|
+
this.retentionSpec = retention; // capture policies for the run log (src/model/retention.js): { default?, panes? }
|
|
323
|
+
this.spendCap = 0; // the cap (micro-dollars) for each run's simulated x402 payments, unless a run names its own (`--spend-cap`)
|
|
324
|
+
this.runtime = makeRuntime({
|
|
325
|
+
onStateChanged: (id, changes) => this.#owner(id)?.canvas.stateChanged(id, changes),
|
|
326
|
+
onConsole: (runtimeId, level, args) => {
|
|
327
|
+
// andbox names the pane (consoleId); a log() value also names it in its tag (src/runtime/console-tag.js).
|
|
328
|
+
const parsed = parseConsoleArgs(args);
|
|
329
|
+
const paneId = parsed.pane ?? runtimeId;
|
|
330
|
+
const text = consoleText(parsed);
|
|
331
|
+
// log(label, value): the value as JSON too (as it was logged: 6 levels, 100 entries each).
|
|
332
|
+
let value = {};
|
|
333
|
+
if (parsed.value) {
|
|
334
|
+
const json = previewToJSON(parsed.value.preview);
|
|
335
|
+
value = { ...(parsed.value.label !== undefined ? { label: parsed.value.label } : {}), value: json.value, ...(json.truncated ? { truncated: true } : {}) };
|
|
336
|
+
}
|
|
337
|
+
const run = paneId == null ? undefined : this.#owner(paneId);
|
|
338
|
+
// The sandbox's own messages (no pane) go to every run in progress.
|
|
339
|
+
for (const r of run ? [run] : this.#runs) r.logs.push({ pane: paneId == null ? null : r.label(paneId), level, text, ...value });
|
|
340
|
+
// …and to the pane's console, as on the page, so the run log has them (src/model/runlog.js).
|
|
341
|
+
const found = run && canvasFor(run.canvas, String(paneId));
|
|
342
|
+
if (found) {
|
|
343
|
+
const lines = found.canvas.logsOf(found.id);
|
|
344
|
+
lines.value = [...lines.value, { level, text }].slice(-50);
|
|
345
|
+
}
|
|
346
|
+
},
|
|
347
|
+
onRestart: (reason) => {
|
|
348
|
+
for (const r of this.#runs) r.restarted = reason.message;
|
|
349
|
+
// Every canvas running on it puts back the values it can and reruns the rest, as on the page; the pane that timed out fails.
|
|
350
|
+
for (const r of this.#runs) r.canvas.onRuntimeRestart(reason);
|
|
351
|
+
},
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
#owner(id) {
|
|
356
|
+
for (const r of this.#runs) if (ownsRuntimeId(r.canvas, id)) return r; // `g/x`: pane x inside subgraph pane g
|
|
357
|
+
return undefined;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Run a canvas once: apply `inputs`, run every pane (click-to-run ones too,
|
|
362
|
+
* like ▶▶), wait until nothing is running, and read `outputs`.
|
|
363
|
+
*
|
|
364
|
+
* @param {object} doc a canvas (.mallory.json)
|
|
365
|
+
* @param {{ inputs?: Record<string, unknown>, outputs?: string[], deadlineMs?: number, mediaData?: boolean, state?: object, ticks?: number, usePins?: boolean, log?: boolean, onlyNeeded?: boolean, clock?: object }} [options]
|
|
366
|
+
* `outputs` are pane names (or ids); default: every named pane no other pane reads.
|
|
367
|
+
* `state` is a store adapter for persisted state panes (src/model/persist-state.js
|
|
368
|
+
* fileStateStore, `mallory run --state`); without it every state pane starts from its initial value.
|
|
369
|
+
* Timer panes tick once (tick 0) and nothing is scheduled; `ticks: N` fires every timer N - 1 more
|
|
370
|
+
* times, one tick after another, waiting for the canvas to settle after each (`mallory run --tick N`).
|
|
371
|
+
* Tick 0 comes once the canvas has settled without it: until then each timer is skipped (no tick
|
|
372
|
+
* yet), as on a page before its schedule's first tick, so everything is built (a repeater's instances,
|
|
373
|
+
* the receivers in them) before tick 0 and what it sends reaches all of it, every time.
|
|
374
|
+
* `onlyNeeded` runs only the outputs and the panes they read (directly or not); the rest stay idle.
|
|
375
|
+
* Media values come back as `{ $media, type, size, … }`; `mediaData` adds `data` (base64 of the bytes).
|
|
376
|
+
* `evaluation: { row }`: this run is one row of an evaluation (src/tests/evaluate.js), so its
|
|
377
|
+
* panes see `isEvaluating` true and `evalRow` (the row); other runs see false.
|
|
378
|
+
* Pinned values (src/model/pin.js) are ignored, as production runs ignore n8n's pins, unless `usePins`.
|
|
379
|
+
* `approvals: { entries, strict?, source? }`: the person's scripted answers to approval requests (src/gate/scripted.js),
|
|
380
|
+
* for agent panes' cards and gate approvals, which a run nobody watches otherwise refuses; the result's `approvals`
|
|
381
|
+
* says what each request got (`answered`, with "unanswered" for one the script had no answer for) and which of the
|
|
382
|
+
* first `strict` entries never answered (`unused`).
|
|
383
|
+
* `spendCap` (micro-dollars; the session's `spendCap` by default, `mallory run --spend-cap`): the cap for this run's
|
|
384
|
+
* simulated x402 payments (src/x402/pay.js). Without one every payment request is refused without asking; with one,
|
|
385
|
+
* a request within it still needs a scripted approval (`pay@x402`). The result's `payments` lists each request.
|
|
386
|
+
* `holds` adds `holds`: { [pane id]: [{ key, outcome, startedAt, endedAt, heldMs }] }, how long wait, decision and gate instances waited (for the cost report).
|
|
387
|
+
* `log` adds `runs`: the run log of this run (src/model/runlog.js runJSON), one entry per canvas run.
|
|
388
|
+
* `unattended` (a test's `unattended: true`): the canvas is marked as run by nobody, and nothing here can hold a grant, so every agent pane is refused (docs/design/grant-bundle.md).
|
|
389
|
+
* `clock` (tests) is the canvas's clock (Canvas's `clock`).
|
|
390
|
+
* `virtualNow` (ms since the epoch, `mallory run --virtual-now`): the canvas's clock is a virtual one
|
|
391
|
+
* (src/model/virtual-clock.js) standing at that instant, so a time-window gate is decided there and a rerun gives the
|
|
392
|
+
* same answer. `advanceMs` (`--advance`): once the events and decision fixtures are in, that much virtual time
|
|
393
|
+
* passes: statechart delays that come due fire, and wait, decision and gate deadlines end their instances, in order,
|
|
394
|
+
* each at its own instant; then the canvas settles. Without it a headless run's deadlines and delays never pass.
|
|
395
|
+
* `events`: `[{ to, name?, payload? }]` sent once the canvas has settled, in order (a burst), out of
|
|
396
|
+
* pane `to`'s event output `name` (its only one when left out); the run then waits for them.
|
|
397
|
+
* `{ channel, payload?, scope?, from? }` sends on a named channel instead (src/model/channels.js).
|
|
398
|
+
* Events panes make during the run are delivered anyway.
|
|
399
|
+
* `yields` (default 1): a live pane (code with yield or emit) stops after this many values
|
|
400
|
+
* (its generator's `finally` runs), and the run waits for that; outputs report the last one.
|
|
401
|
+
* An animation (a live run that asks for frames, a States preset's tween) has virtual frames
|
|
402
|
+
* (no waiting for real time) and goes on to its end unless `yields` is given.
|
|
403
|
+
* @returns {Promise<{ ok: boolean, values: Record<string, unknown>, types: Record<string, string>,
|
|
404
|
+
* previews: string[], states: object[], logs: object[], caught?: object[], restarted?: string }>}
|
|
405
|
+
* `caught`: the error events catch panes caught, `{ catch, paneName, message, name, line?, at, attempt, inputs, handled? }`.
|
|
406
|
+
* `values` holds JSON-safe values by pane name; a value that can't leave the
|
|
407
|
+
* sandbox (a function, a module) is its preview text and is listed in
|
|
408
|
+
* `previews`. `ok` is true when every output pane finished.
|
|
409
|
+
*/
|
|
410
|
+
async run(doc, { inputs = {}, outputs, deadlineMs = 300000, mediaData = false, evaluation, state, ticks = 1, usePins = false, log = false, onlyNeeded = false, clock, virtualNow, advanceMs = 0, yields, events = [], decisions = [], approvals, holds = false, assets, module, spendCap = this.spendCap, mcpRoots, unattended = false } = {}) {
|
|
411
|
+
validate(doc);
|
|
412
|
+
// The person's scripted approvals (a test's own, the CLI's flags): `{ entries, strict?, source? }` (src/gate/scripted.js).
|
|
413
|
+
let script = null;
|
|
414
|
+
if (approvals?.entries?.length) {
|
|
415
|
+
const problem = approvalsProblem(approvals.entries, approvals.source ?? "approvals");
|
|
416
|
+
if (problem) throw new Error(problem);
|
|
417
|
+
script = createApprovalScript(approvals.entries, { strict: approvals.strict ?? approvals.entries.length, source: approvals.source ?? "script" });
|
|
418
|
+
}
|
|
419
|
+
if (advanceMs > 0 && virtualNow === undefined && typeof clock?.set !== "function") throw new Error("advancing time needs a virtual clock (--virtual-now)");
|
|
420
|
+
if (virtualNow !== undefined) clock ??= virtualClock(virtualNow);
|
|
421
|
+
const applied = applyInputs(usePins ? doc : { ...doc, panes: stripPins(doc.panes) }, inputs);
|
|
422
|
+
const wanted = outputs?.length ? outputs : defaultOutputs(applied);
|
|
423
|
+
// "split.small": one of a pane's named outputs (src/model/ports.js).
|
|
424
|
+
const outputPanes = wanted.map((key) => findOutput(applied, key));
|
|
425
|
+
|
|
426
|
+
const ns = `r${++this.#count}:`;
|
|
427
|
+
const runnable = runnableDoc(applied).panes
|
|
428
|
+
.filter(runsHeadless)
|
|
429
|
+
.map((p) => ({ ...p, id: ns + p.id, inputs: (p.inputs ?? []).map((i) => ({ ...i, source: ns + i.source })) }))
|
|
430
|
+
// Panes outside a subgraph may read panes inside it by id (src/model/subgraph.js): rename those too.
|
|
431
|
+
.map((p) => (p.type === "subgraph" ? { ...p, graph: renameGraph(p.graph ?? { panes: [] }, (id) => ns + id), output: p.output ? ns + p.output : p.output } : p));
|
|
432
|
+
// No debounce or throttle: inputs are set once (src/model/rate.js).
|
|
433
|
+
const canvas = new Canvas({ runtime: this.runtime, doc: { ...applied, panes: runnable, groups: remapGroups(applied.groups, (id) => ns + id) }, trusted: false, ...this.canvasOptions, retention: retentionFor(this.retentionSpec, applied, ns, configPolicy), stateStore: state, timers: { live: false, held: true }, pacing: false, clock, yields: yields ?? 1, frames: { virtual: true, yields } });
|
|
434
|
+
if (script) canvas.approvalScript = script; // read through canvas.root by agent panes, MCP calls and the gate (never on the page's live canvas)
|
|
435
|
+
if (unattended === true) canvas.unattended = true; // a canvas test: run as a schedule would, with no grant authority (src/agent/run.js refuses every agent run)
|
|
436
|
+
if (mcpRoots) canvas.mcpRoots = mcpRoots; // the folders an MCP server pane may offer as roots (src/mcp/roots.js): a test's, or mallory serve's watched folders
|
|
437
|
+
// x402 payments (src/x402/pay.js): this run's own budget, in memory. Its cap is the person's (`--spend-cap`), else none:
|
|
438
|
+
// a challenge is then refused without asking, as one over the cap is; within it, only the approvals script answers.
|
|
439
|
+
canvas.paymentBudget = { capMicros: Number.isInteger(spendCap) && spendCap > 0 ? spendCap : 0, spentMicros: 0 };
|
|
440
|
+
const byId = new Map(applied.panes.map((p) => [p.id, p]));
|
|
441
|
+
const run = { canvas, logs: [], caught: [], restarted: undefined, label: (id) => insideLabel(canvas, String(id)) ?? label(byId.get(String(id).slice(ns.length)) ?? { id }) };
|
|
442
|
+
this.#runs.add(run);
|
|
443
|
+
if (assets?.length) this.runtime.setAssets?.(ns, assets); // a package pane's own tests: the files its panes read as `assets`
|
|
444
|
+
if (module) this.runtime.setModule?.(ns, module); // ...and its package's shared module, as `pkg.module` (src/packages/module.js)
|
|
445
|
+
const evaluating = Boolean(evaluation && this.runtime.setEvaluation);
|
|
446
|
+
// Catch panes (src/panes/catch.js), on this canvas and inside its subgraphs: what each caught.
|
|
447
|
+
canvas.addEventListener("caught", ({ detail }) => {
|
|
448
|
+
const { pane, runId, ...event } = detail.event;
|
|
449
|
+
run.caught.push({ catch: detail.name, ...event, paneName: event.paneName.startsWith(ns) ? event.paneName.slice(ns.length) : event.paneName });
|
|
450
|
+
});
|
|
451
|
+
// On a virtual clock, what pane code sends is stamped with it too (event.at): the Workers hear it ahead of their next call.
|
|
452
|
+
const stamped = clock && (virtualNow !== undefined || typeof clock.set === "function") && typeof clock.now === "function" && this.runtime.setClock;
|
|
453
|
+
try {
|
|
454
|
+
if (stamped) this.runtime.setClock(clock.now());
|
|
455
|
+
if (evaluating) await this.runtime.setEvaluation(ns, evaluation.row ?? {});
|
|
456
|
+
canvas.trusted.value = true;
|
|
457
|
+
canvas.flow.resume();
|
|
458
|
+
if (onlyNeeded) canvas.runNeeded(outputPanes.map((p) => ns + p.id)); // run up to the outputs (src/model/partial.js)
|
|
459
|
+
else canvas.runAll();
|
|
460
|
+
await settle(canvas, deadlineMs);
|
|
461
|
+
// Tick 0, once the canvas has settled without it: the timers that were asked to run (skipped: no tick yet).
|
|
462
|
+
canvas.timerClock.release();
|
|
463
|
+
if (fireTimers(canvas, { tick: 0, asked: true })) await settle(canvas, deadlineMs);
|
|
464
|
+
for (let tick = 1; tick < ticks; tick++) {
|
|
465
|
+
if (!fireTimers(canvas, { tick })) break; // no timer panes: more ticks change nothing
|
|
466
|
+
await settle(canvas, deadlineMs);
|
|
467
|
+
}
|
|
468
|
+
// Events sent in (a test's `events`): a burst, in order, then wait for their readers.
|
|
469
|
+
if (events?.length) {
|
|
470
|
+
for (const e of events) {
|
|
471
|
+
if (e?.serialReplay !== undefined) {
|
|
472
|
+
// A recording saved in the canvas's serial settings, framed and decoded like a device's bytes (no port is opened).
|
|
473
|
+
if (!canvas.serial?.channel) throw new Error(`serial replay "${e.serialReplay}": the canvas's serial settings name no channel to send packets on`);
|
|
474
|
+
const controls = new SerialControls(canvas);
|
|
475
|
+
try {
|
|
476
|
+
controls.replay(String(e.serialReplay));
|
|
477
|
+
await controls.settled(); // frames a codec pane is still decoding
|
|
478
|
+
} finally {
|
|
479
|
+
controls.dispose();
|
|
480
|
+
}
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
if (e?.channel !== undefined) {
|
|
484
|
+
// On a named channel: from the canvas (or pane `from`), with its scope.
|
|
485
|
+
const from = e.from === undefined ? undefined : ns + findPane(applied, String(e.from), "channel send").id;
|
|
486
|
+
const sent = canvas.sendChannel(String(e.channel), e.payload ?? null, { scope: e.scope, from, source: "test" });
|
|
487
|
+
if (!sent.sent) throw new Error(`channel "${e.channel}": ${sent.reason}`);
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
const pane = findPane(applied, String(e?.to ?? ""), "event");
|
|
491
|
+
// A batch marker or an event of a batch: the same sends as emit.batch and emit.event(…, { batch }).
|
|
492
|
+
const sent = e.marker
|
|
493
|
+
? canvas.sendBatchMarker(ns + pane.id, e.name, e.marker, { batch: e.batch, source: "test", ...(e.reason === undefined ? {} : { reason: e.reason }), ...(e.onError === undefined ? {} : { onError: e.onError }), ...(e.onCancel === undefined ? {} : { onCancel: e.onCancel }) })
|
|
494
|
+
: canvas.sendEvent(ns + pane.id, e.name, e.payload ?? null, { source: "test", ...(e.batch === undefined ? {} : { batch: e.batch }) });
|
|
495
|
+
if (!sent.sent) throw new Error(`event to "${e.to}": ${sent.reason}`);
|
|
496
|
+
}
|
|
497
|
+
await settle(canvas, deadlineMs);
|
|
498
|
+
}
|
|
499
|
+
// Decision fixtures: the operator's answers, given up front. They go through the same form checks as a person's.
|
|
500
|
+
if (decisions?.length) {
|
|
501
|
+
for (const d of expandFixtures(decisions)) {
|
|
502
|
+
const pane = findPane(applied, String(d?.pane ?? ""), "decision");
|
|
503
|
+
if (pane.type !== "decision") throw new Error(paneKindError(`decision for "${d.pane}": it is`, pane.type, "decision"));
|
|
504
|
+
const pend = canvas.decisions.pending(ns + pane.id);
|
|
505
|
+
// Without a key the fixture would silently decide the oldest of several: it must say so (oldest: true) or name one.
|
|
506
|
+
if (d.key === undefined && !d.oldest && pend.instances.length > 1) throw new Error(`decision for "${d.pane}": ${pend.instances.length} proposals await a decision (${pend.instances.map((i) => i.key || i.id).join(", ")}); give "key" to pick one, or "oldest": true to take the oldest on purpose`);
|
|
507
|
+
const inst = d.key === undefined ? pend.instances[0] : pend.instances.find((i) => i.key === String(d.key));
|
|
508
|
+
if (!inst) throw new Error(`decision for "${d.pane}": nothing awaits a decision${d.key === undefined ? "" : ` with key ${d.key}`}`);
|
|
509
|
+
const r = canvas.decisions.answer(ns + pane.id, { instance: inst.id, decision: d.decision, values: d.values, voter: d.voter, answerId: d.answerId, source: "fixture" });
|
|
510
|
+
if (!r.ok) throw new Error(`decision for "${d.pane}": ${r.reason}${r.errors ? ` (${Object.entries(r.errors).map(([k, v]) => `${k}: ${v}`).join(", ")})` : ""}`);
|
|
511
|
+
if (r.state === "duplicate") throw new Error(`decision for "${d.pane}": not counted: ${r.reason}`); // a fixture that adds nothing is a mistake, not a no-op
|
|
512
|
+
}
|
|
513
|
+
await settle(canvas, deadlineMs);
|
|
514
|
+
}
|
|
515
|
+
// Virtual time passing (--advance): delays and deadlines that come due inside it, in order.
|
|
516
|
+
if (advanceMs > 0) {
|
|
517
|
+
await advanceCanvas([canvas, ...allCanvases(canvas)], advanceMs, { settle: () => settle(canvas, deadlineMs) });
|
|
518
|
+
await settle(canvas, deadlineMs);
|
|
519
|
+
}
|
|
520
|
+
// A decision pane that still has a proposal awaiting a person needs input: there is no one to ask.
|
|
521
|
+
const needsInput = applied.panes
|
|
522
|
+
.filter((p) => p.type === "decision")
|
|
523
|
+
.map((p) => ({ pane: label(p), form: canvas.decisions.pending(ns + p.id) }))
|
|
524
|
+
.filter(({ form }) => form.instances.length)
|
|
525
|
+
.map(({ pane, form }) => ({ pane, title: form.title, fields: form.fields.map((f) => f.name), required: form.required, instances: form.instances.map((i) => ({ id: i.id, key: i.key, proposal: i.start, approvals: i.ballots.length })) }));
|
|
526
|
+
const states = applied.panes.filter((p) => inDataflow(p.type)).map((p) => this.#state(p, canvas, ns, byId));
|
|
527
|
+
const values = {};
|
|
528
|
+
const types = {};
|
|
529
|
+
const previews = [];
|
|
530
|
+
for (const pane of outputPanes) {
|
|
531
|
+
const key = pane.port ? `${label(pane)}.${pane.port}` : label(pane);
|
|
532
|
+
const node = pane.port ? portId(ns + pane.id, pane.port) : ns + pane.id;
|
|
533
|
+
const state = canvas.stateValue(node);
|
|
534
|
+
if (SKIPPED_TYPES[pane.type] || state.status !== "done") continue;
|
|
535
|
+
const preview = state.result?.preview;
|
|
536
|
+
types[key] = preview?.type ?? "undefined";
|
|
537
|
+
try {
|
|
538
|
+
const [copy] = await this.runtime.clone([node]);
|
|
539
|
+
values[key] = toJSONSafe(await mediaForJSON(copy, { data: mediaData }));
|
|
540
|
+
} catch {
|
|
541
|
+
values[key] = previewText(preview);
|
|
542
|
+
previews.push(key);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
const portStates = outputPanes.filter((p) => p.port).map((p) => this.#portState(p, canvas, ns));
|
|
546
|
+
states.push(...portStates);
|
|
547
|
+
const ok = !needsInput.length && outputPanes.every((p) => (p.port ? portStates.find((s) => s.id === `${p.id}#${p.port}`) : states.find((s) => s.id === p.id))?.status === "done");
|
|
548
|
+
let runs;
|
|
549
|
+
if (log) {
|
|
550
|
+
await canvas.runLog.flush(); // full values still being read
|
|
551
|
+
runs = canvas.runLog.runs.map((r) => plainRun(r, ns));
|
|
552
|
+
}
|
|
553
|
+
// How long each wait, decision or gate instance waited (src/model/wait-clock.js collectHolds), by path (a pane id, `sub/inner`
|
|
554
|
+
// inside a subgraph or repeater): what `mallory run --cost` reports as held time. Each run line of the log carries the holds
|
|
555
|
+
// of the instances that started in it (`holds`, even when empty: a log that has the field records them), a hold whose
|
|
556
|
+
// run isn't known (an instance started by hand) in the newest run.
|
|
557
|
+
let heldBy;
|
|
558
|
+
if (holds || runs) {
|
|
559
|
+
const all = collectHolds(canvas, { strip: (id) => (String(id).startsWith(ns) ? String(id).slice(ns.length) : String(id)) });
|
|
560
|
+
if (holds) heldBy = Object.fromEntries(Object.entries(all).map(([path, list]) => [path, list.map(({ run, ...rest }) => rest)]));
|
|
561
|
+
if (runs) {
|
|
562
|
+
for (const r of runs) r.holds = [];
|
|
563
|
+
for (const [pane, list] of Object.entries(all)) {
|
|
564
|
+
for (const { run, ...rest } of list) (runs.find((r) => r.id === run) ?? runs.at(-1))?.holds.push({ pane, ...rest });
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
// Re-locking (--update-imports): what changed in the import lock (src/model/import-lock.js).
|
|
569
|
+
const relocked = this.canvasOptions.relockImports ? { imports: lockChanges(cleanImportLock(doc.imports), canvas.importLock) } : {};
|
|
570
|
+
// What the script answered, what it couldn't (each refused), and its own answers no request used.
|
|
571
|
+
const scripted = script ? { approvals: { answered: script.log.map((a) => ({ ...a, tool: String(a.tool).startsWith(ns) ? String(a.tool).slice(ns.length) : a.tool })), unused: script.unused() } } : {};
|
|
572
|
+
// The x402 payment requests the run met, and what each got (simulated: nothing real is ever paid).
|
|
573
|
+
const paid = canvas.paymentBudget?.log?.length ? { payments: canvas.paymentBudget.log.map((p) => ({ ...p, pane: String(p.pane).startsWith(ns) ? String(p.pane).slice(ns.length) : p.pane })) } : {};
|
|
574
|
+
return { ok, values, types, previews, states, logs: run.logs, ...scripted, ...paid, ...(needsInput.length ? { needsInput } : {}), ...relocked, ...(runs ? { runs } : {}), ...(heldBy ? { holds: heldBy } : {}), ...(run.caught.length ? { caught: run.caught } : {}), ...(ticks > 1 ? { ticks } : {}), ...(run.restarted ? { restarted: run.restarted } : {}) };
|
|
575
|
+
} finally {
|
|
576
|
+
this.#runs.delete(run);
|
|
577
|
+
canvas.dispose();
|
|
578
|
+
if (assets?.length) this.runtime.setAssets?.(ns, null);
|
|
579
|
+
if (module) this.runtime.setModule?.(ns, null);
|
|
580
|
+
if (stamped) this.runtime.setClock(null);
|
|
581
|
+
if (evaluating) await this.runtime.setEvaluation(ns, null);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Open a canvas and keep it running, for `mallory serve` (src/headless/serve.js):
|
|
587
|
+
* like run(), in its own pane-id namespace, but nothing is read out and
|
|
588
|
+
* nothing is closed until `close()`. `start()` trusts it and runs every pane
|
|
589
|
+
* (click-to-run ones too); `settle()` waits until nothing is running. Its
|
|
590
|
+
* console lines collect in `logs` (the last 500; take them with
|
|
591
|
+
* `logs.splice(0)`), what its catch panes catch in `caught`. A sandbox restart
|
|
592
|
+
* starts it over (Canvas#onRuntimeRestart). Pins are ignored, as in run().
|
|
593
|
+
* `runsSince(seq)` reads its run log (src/model/runlog.js) as JSON: the canvas
|
|
594
|
+
* runs after `seq` (the log's `seq` before them), up to `until` if given. `options` go to the
|
|
595
|
+
* Canvas (`stateStore`, `timers`, `serving`, `clock`: a test's).
|
|
596
|
+
* @returns {{ canvas: Canvas, ns: string, key: (id: string) => string, logs: object[], caught: object[], start: () => void, settle: (deadlineMs?: number, clock?: { setTimer?: Function, clearTimer?: Function }) => Promise<void>, state: (id: string) => object, seq: number, runsSince: (seq: number, until?: number) => Promise<object[]>, close: () => void }}
|
|
597
|
+
*/
|
|
598
|
+
open(doc, { stateStore, timers, serving = true, clock, mcpRoots } = {}) {
|
|
599
|
+
validate(doc);
|
|
600
|
+
const ns = `r${++this.#count}:`;
|
|
601
|
+
const panes = namespacePanes(runnableDoc({ ...doc, panes: stripPins(doc.panes) }).panes.filter(runsHeadless), ns);
|
|
602
|
+
// A live pane gives its first value and stops: a respond pane it feeds answers with that.
|
|
603
|
+
const canvas = new Canvas({ runtime: this.runtime, doc: { ...doc, panes, groups: remapGroups(doc.groups, (id) => ns + id) }, trusted: false, ...this.canvasOptions, retention: retentionFor(this.retentionSpec, doc, ns, configPolicy), stateStore, timers, serving, clock, yields: 1 });
|
|
604
|
+
if (mcpRoots) canvas.mcpRoots = mcpRoots; // mallory serve's watched folders, offered to MCP servers as roots (src/headless/mcp-roots.js)
|
|
605
|
+
const byId = new Map(doc.panes.map((p) => [p.id, p]));
|
|
606
|
+
const logs = bounded(500);
|
|
607
|
+
const caught = bounded(100);
|
|
608
|
+
const run = { canvas, live: true, logs, caught, restarted: undefined, label: (id) => insideLabel(canvas, String(id)) ?? label(byId.get(String(id).slice(ns.length)) ?? { id }) };
|
|
609
|
+
this.#runs.add(run);
|
|
610
|
+
canvas.addEventListener("caught", ({ detail }) => {
|
|
611
|
+
const { pane, runId, ...event } = detail.event;
|
|
612
|
+
caught.push({ catch: detail.name, ...event, paneName: event.paneName.startsWith(ns) ? event.paneName.slice(ns.length) : event.paneName });
|
|
613
|
+
});
|
|
614
|
+
return {
|
|
615
|
+
canvas,
|
|
616
|
+
ns,
|
|
617
|
+
run,
|
|
618
|
+
logs,
|
|
619
|
+
caught,
|
|
620
|
+
key: (id) => ns + id,
|
|
621
|
+
start() {
|
|
622
|
+
canvas.trusted.value = true;
|
|
623
|
+
canvas.flow.resume();
|
|
624
|
+
canvas.runAll();
|
|
625
|
+
canvas.timerClock.syncTree(); // timers start only now (live ones: their schedules)
|
|
626
|
+
},
|
|
627
|
+
settle: (deadlineMs = 300000, clock) => settle(canvas, deadlineMs, clock),
|
|
628
|
+
state: (id) => this.#state(byId.get(id) ?? { id, type: "missing" }, canvas, ns, byId),
|
|
629
|
+
get seq() {
|
|
630
|
+
return canvas.runLog.seq;
|
|
631
|
+
},
|
|
632
|
+
async runsSince(seq, until = Infinity) {
|
|
633
|
+
await canvas.runLog.flush(); // full values still being read
|
|
634
|
+
return canvas.runLog.runs.filter((r) => r.seq > seq && r.seq <= until && r.end !== undefined).map((r) => plainRun(r, ns));
|
|
635
|
+
},
|
|
636
|
+
close: () => {
|
|
637
|
+
this.#runs.delete(run);
|
|
638
|
+
canvas.dispose();
|
|
639
|
+
},
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** A named output's state, as an entry of `states` (`id` "split#small", `name` "split.small"). */
|
|
644
|
+
#portState(pane, canvas, ns) {
|
|
645
|
+
const state = canvas.stateValue(portId(ns + pane.id, pane.port));
|
|
646
|
+
const out = { id: `${pane.id}#${pane.port}`, name: `${label(pane)}.${pane.port}`, type: "output", status: state.status };
|
|
647
|
+
if (state.status === "skipped" && state.skip?.reason !== undefined) out.note = String(state.skip.reason);
|
|
648
|
+
if (state.status === "error") out.error = state.error?.message ?? String(state.error);
|
|
649
|
+
if (state.status === "waiting" || state.status === "idle") out.note = `waiting for ${label(pane)}`;
|
|
650
|
+
return out;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
#state(pane, canvas, ns, byId) {
|
|
654
|
+
const base = { id: pane.id, name: pane.name ?? "", type: pane.type };
|
|
655
|
+
if (SKIPPED_TYPES[pane.type]) return { ...base, status: "skipped", note: SKIPPED_TYPES[pane.type] };
|
|
656
|
+
const state = canvas.stateValue(ns + pane.id);
|
|
657
|
+
const out = { ...base, status: state.status };
|
|
658
|
+
const live = canvas.liveOf(ns + pane.id); // a live pane: how many values it made
|
|
659
|
+
if (live) out.yields = live.count;
|
|
660
|
+
const last = canvas.runs.lastSettledRun(ns + pane.id); // how long its last run took (the `ms` metric)
|
|
661
|
+
if (last?.duration !== undefined) out.ms = Math.round(last.duration * 10) / 10;
|
|
662
|
+
if (state.status === "error") {
|
|
663
|
+
out.error = state.cycle ? "this pane is on a cycle" : (state.error?.message ?? String(state.error));
|
|
664
|
+
if (state.error?.line) out.line = state.error.line;
|
|
665
|
+
}
|
|
666
|
+
if (state.status === "skipped" && state.skip?.reason !== undefined) out.note = String(state.skip.reason); // why (an agent pane: "needs Chrome's built-in AI")
|
|
667
|
+
// Error policies (src/model/errors.js): how many tries it took, and a value that is the fallback.
|
|
668
|
+
const attempts = state.status === "error" ? state.error?.attempts : state.result?.attempts;
|
|
669
|
+
if (attempts > 1) out.attempts = attempts;
|
|
670
|
+
if (state.status === "done" && state.result?.fallback) out.fallback = state.result.fallback.message;
|
|
671
|
+
if (pane.type === "decision") {
|
|
672
|
+
const n = canvas.decisions.pending(ns + pane.id).instances.length;
|
|
673
|
+
if (n) out.note = `needs input: ${n} proposal${n === 1 ? "" : "s"} awaiting a decision`;
|
|
674
|
+
}
|
|
675
|
+
if (state.status === "waiting" || state.status === "idle") {
|
|
676
|
+
const blocked = (pane.inputs ?? [])
|
|
677
|
+
.map((i) => byId.get(i.source) ?? { id: i.source, missing: true })
|
|
678
|
+
.filter((src) => src.missing || SKIPPED_TYPES[src.type] || canvas.stateValue(ns + src.id).status !== "done")
|
|
679
|
+
.map((src) => (src.missing ? `${src.id} (not on the canvas)` : `${label(src)} (${SKIPPED_TYPES[src.type] ? "skipped" : canvas.stateValue(ns + src.id).status})`));
|
|
680
|
+
if (blocked.length) out.note = `waiting for ${blocked.join(", ")}`;
|
|
681
|
+
}
|
|
682
|
+
return out;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** Stop the sandbox (a Node process exits only after this). */
|
|
686
|
+
async dispose() {
|
|
687
|
+
await Promise.resolve(this.runtime.ready).catch(() => {}); // a sandbox still starting would outlive dispose()
|
|
688
|
+
await this.runtime.dispose?.();
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** A logged run as JSON (runJSON), with pane ids out of the run's namespace. */
|
|
693
|
+
function plainRun(run, ns) {
|
|
694
|
+
const unprefix = (id) => (String(id).startsWith(ns) ? String(id).slice(ns.length) : String(id));
|
|
695
|
+
return JSON.parse(JSON.stringify(runJSON(run), (k, x) => (["pane", "source", "inner", "parent"].includes(k) && typeof x === "string" ? unprefix(x) : k === "panes" && Array.isArray(x) ? x.map(unprefix) : x)));
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** Panes renamed into a run's namespace (`r1:` + id), their inputs and the panes inside their subgraphs too. */
|
|
699
|
+
export function namespacePanes(panes, ns) {
|
|
700
|
+
return panes
|
|
701
|
+
.map((p) => ({ ...p, id: ns + p.id, inputs: (p.inputs ?? []).map((i) => ({ ...i, source: ns + i.source })) }))
|
|
702
|
+
.map((p) => (p.type === "subgraph" ? { ...p, graph: renameGraph(p.graph ?? { panes: [] }, (id) => ns + id), output: p.output ? ns + p.output : p.output } : p));
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** An array that keeps only its last `max` entries. */
|
|
706
|
+
function bounded(max) {
|
|
707
|
+
const list = [];
|
|
708
|
+
list.push = (...items) => {
|
|
709
|
+
Array.prototype.push.apply(list, items);
|
|
710
|
+
if (list.length > max) list.splice(0, list.length - max);
|
|
711
|
+
return list.length;
|
|
712
|
+
};
|
|
713
|
+
return list;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** "group › tip" for a pane inside a subgraph pane (sandbox id `g/x`), else undefined. */
|
|
717
|
+
function insideLabel(canvas, id) {
|
|
718
|
+
if (!id.includes(SEP)) return undefined;
|
|
719
|
+
const parts = id.split(SEP);
|
|
720
|
+
const names = [];
|
|
721
|
+
let c = canvas;
|
|
722
|
+
let rep = null; // a repeater's instance `g/@k/…` (src/model/repeater.js)
|
|
723
|
+
for (const part of parts) {
|
|
724
|
+
if (rep && part.startsWith("@")) {
|
|
725
|
+
names.push(part.slice(1));
|
|
726
|
+
c = rep.subgraphs.get(part);
|
|
727
|
+
rep = null;
|
|
728
|
+
continue;
|
|
729
|
+
}
|
|
730
|
+
names.push(c?.panes.get(part)?.name || part.replace(/^r\d+:/, ""));
|
|
731
|
+
rep = c?.repeaters?.get(part) ?? null;
|
|
732
|
+
c = c?.subgraphs.get(part);
|
|
733
|
+
}
|
|
734
|
+
return names.join(" › ");
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Every canvas inside `canvas` (its subgraphs' and repeaters' instances, at any depth). */
|
|
738
|
+
function allCanvases(canvas) {
|
|
739
|
+
return [...innerCanvases(canvas)].flatMap((inner) => [inner, ...allCanvases(inner)]);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* Fire every timer pane on a canvas and in its subgraphs (one tick, named `tick N` in the run log). `asked`: only
|
|
744
|
+
* the timers that were asked to run (not idle: a partial run leaves the others alone). Returns how many fired.
|
|
745
|
+
*/
|
|
746
|
+
export function fireTimers(canvas, { tick, asked = false } = {}) {
|
|
747
|
+
let fired = 0;
|
|
748
|
+
const ids = canvas.timerClock.ids().filter((id) => !asked || canvas.flow.get(id)?.status !== "idle");
|
|
749
|
+
if (ids.length && tick !== undefined) canvas.runLog?.hint(`tick ${tick}`);
|
|
750
|
+
for (const id of ids) if (canvas.fireTimer(id).fired) fired++;
|
|
751
|
+
// Automation panes: each tick after tick 0 advances their playhead by their `step` (a replay of N ticks is exact: no clock).
|
|
752
|
+
if (tick > 0) for (const id of canvas.automation.sources().filter((p) => !asked || canvas.flow.get(p)?.status !== "idle")) if (canvas.automation.step(id)) fired++;
|
|
753
|
+
for (const inner of innerCanvases(canvas)) fired += fireTimers(inner, { tick, asked }); // repeater instances too
|
|
754
|
+
return fired;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Wait for a canvas's dataflow and its subgraphs' to go idle (a timer ticking inside a subgraph runs there first).
|
|
759
|
+
* The canvases inside are waited for together: one after another, a repeater's hundreds of instances took a timer's turn each.
|
|
760
|
+
*/
|
|
761
|
+
async function idleTree(canvas) {
|
|
762
|
+
await canvas.flow.idle();
|
|
763
|
+
await Promise.all([...innerCanvases(canvas)].map(idleTree));
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** Is a pane running on this canvas or inside one of its subgraphs? A live run still making its values counts. */
|
|
767
|
+
const runningIn = (canvas) => canvas.visible.some((id) => canvas.stateValue(id).status === "running" || canvas.stateValue(id).live) || Boolean(canvas.events?.busy) || [...innerCanvases(canvas)].some(runningIn);
|
|
768
|
+
|
|
769
|
+
/** Is a dataflow node running on this canvas or inside one of its subgraphs? */
|
|
770
|
+
const flowRunningIn = (canvas) => canvas.hasRunning() || [...innerCanvases(canvas)].some(flowRunningIn);
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* The next run state change on this canvas or inside it, or a 0 ms timer,
|
|
774
|
+
* whichever comes first: what is left once the dataflow is idle (a live run
|
|
775
|
+
* still open, an event waiting in a wire's debounce) ends with a change, or,
|
|
776
|
+
* for an event a wire drops, only shows on the next look.
|
|
777
|
+
*/
|
|
778
|
+
function changeIn(canvas) {
|
|
779
|
+
return new Promise((resolve) => {
|
|
780
|
+
const offs = [];
|
|
781
|
+
const done = () => {
|
|
782
|
+
clearTimeout(timer);
|
|
783
|
+
for (const off of offs) off();
|
|
784
|
+
resolve();
|
|
785
|
+
};
|
|
786
|
+
const watch = (c) => {
|
|
787
|
+
offs.push(c.flow.subscribe(done));
|
|
788
|
+
for (const inner of innerCanvases(c)) watch(inner);
|
|
789
|
+
};
|
|
790
|
+
const timer = setTimeout(done, 0);
|
|
791
|
+
watch(canvas);
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Wait until nothing is queued or running, including reruns a state setter
|
|
797
|
+
* causes. The deadline is a timer on `clock` (`{ setTimer, clearTimer }`, the
|
|
798
|
+
* real one by default; a test's clock makes it fire when the test says).
|
|
799
|
+
* Between looks it waits for the dataflow (src/model/flow-idle.js) and the next
|
|
800
|
+
* task, never a timer while a pane runs: on a page in a hidden tab (the Tests
|
|
801
|
+
* dialog, an agent's mallory_run_tests) Chrome runs timers once a second.
|
|
802
|
+
*/
|
|
803
|
+
export async function settle(canvas, deadlineMs, { setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
|
|
804
|
+
let timer;
|
|
805
|
+
const deadline = new Promise((_, reject) => {
|
|
806
|
+
timer = setTimer(() => reject(new Error(`the canvas was still running after ${Math.round(deadlineMs / 1000)}s`)), deadlineMs);
|
|
807
|
+
});
|
|
808
|
+
try {
|
|
809
|
+
for (let quiet = 0; quiet < 2; ) {
|
|
810
|
+
await Promise.race([idleTree(canvas), deadline]);
|
|
811
|
+
await Promise.race([nextTask(), deadline]);
|
|
812
|
+
const busy = runningIn(canvas);
|
|
813
|
+
quiet = busy ? 0 : quiet + 1;
|
|
814
|
+
// Busy with nothing in the dataflow running (a live run open, a wire's debounce): wait for a change, not a spin.
|
|
815
|
+
if (busy && !flowRunningIn(canvas)) await Promise.race([changeIn(canvas), deadline]);
|
|
816
|
+
}
|
|
817
|
+
} finally {
|
|
818
|
+
clearTimer(timer);
|
|
819
|
+
}
|
|
820
|
+
}
|