@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
|
@@ -0,0 +1,1820 @@
|
|
|
1
|
+
// Agent panes (src/agent/): the page runs the loop; what must happen in here,
|
|
2
|
+
// as the agent pane, happens here: rendering its templates, describing and
|
|
3
|
+
// calling function tools, sending model requests through the pane's fetch
|
|
4
|
+
// (the network policy, secret() placeholders filled in on the page), and
|
|
5
|
+
// holding its on-device model session (through the AI bridge, so the page's
|
|
6
|
+
// permissions and token budgets apply; tracked like a pane's own sessions).
|
|
7
|
+
const agentChats = new Map(); // agent pane id -> { runId, session }
|
|
8
|
+
const agentCalls = new Map(); // agent pane id -> its model call in flight: { runId, stop(reason), cancelled? } (AGENT.cancel)
|
|
9
|
+
|
|
10
|
+
/** A JSON copy of a value for the page (functions and BigInts named, cycles refused). */
|
|
11
|
+
function plainCopy(value) {
|
|
12
|
+
if (value === undefined) return null;
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(JSON.stringify(value, (_, v) => (typeof v === "bigint" ? String(v) : typeof v === "function" ? `[function ${v.name || "anonymous"}]` : v)));
|
|
15
|
+
} catch {
|
|
16
|
+
return String(value);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function releaseAgentChat(id) {
|
|
21
|
+
const chat = agentChats.get(id);
|
|
22
|
+
agentChats.delete(id);
|
|
23
|
+
try {
|
|
24
|
+
chat?.session.destroy();
|
|
25
|
+
} catch {}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const AGENT = {
|
|
29
|
+
/** Render the system and prompt templates against the inputs, and describe the inputs that are functions. */
|
|
30
|
+
async prepare(id, runId, sources, names, { system, prompt, label }, forwardingConsole) {
|
|
31
|
+
if (latest.get(id) !== runId) releaseAgentChat(id);
|
|
32
|
+
latest.set(id, runId);
|
|
33
|
+
const render = async (body) => (body ? String(await run(id, sources, names, body, label, forwardingConsole, [])) : "");
|
|
34
|
+
const out = { system: await render(system), prompt: await render(prompt), functions: [], message: null };
|
|
35
|
+
sources.forEach((s, i) => {
|
|
36
|
+
const v = values.get(s);
|
|
37
|
+
if (typeof v === "function") out.functions.push({ name: names[i], source: String(v).slice(0, 4000), schema: v.schema && typeof v.schema === "object" ? plainCopy(v.schema) : null, description: typeof v.description === "string" ? v.description : null });
|
|
38
|
+
if (names[i] === "message") out.message = typeof v === "string" ? v : JSON.stringify(plainCopy(v));
|
|
39
|
+
});
|
|
40
|
+
return out;
|
|
41
|
+
},
|
|
42
|
+
/** Call a function tool (the value of `sources[0]`) with the model's arguments. */
|
|
43
|
+
async call(id, runId, [source], _, { args, positional }) {
|
|
44
|
+
const fn = values.get(source);
|
|
45
|
+
if (typeof fn !== "function") throw new Error("this tool's value isn't a function any more");
|
|
46
|
+
let value;
|
|
47
|
+
try {
|
|
48
|
+
value = await (Array.isArray(positional) ? fn(...positional.map((n) => args?.[n])) : fn(args ?? {}));
|
|
49
|
+
} catch (error) {
|
|
50
|
+
// A typed failure (a WASM tool's FuelExhaustedError: code "fuel-exhausted") reaches the agent with its code.
|
|
51
|
+
if (typeof error?.code === "string" && /^[a-z][a-z0-9-]{0,40}$/.test(error.code)) return { error: String(error.message ?? error), code: error.code };
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
if (isSkip(value)) return { error: `skipped${value.reason === undefined ? "" : `: ${skipReason(value)}`}` };
|
|
55
|
+
return { value: plainCopy(value) };
|
|
56
|
+
},
|
|
57
|
+
/**
|
|
58
|
+
* A model request, as the agent pane (through its fetch: the network policy,
|
|
59
|
+
* secret() placeholders). `stream`: the page shows the reply as it arrives
|
|
60
|
+
* (agentProgress): the body is read as it streams in, and reading
|
|
61
|
+
* stops when the run is superseded or cancelled (AGENT.cancel).
|
|
62
|
+
*/
|
|
63
|
+
async http(id, runId, _, __, { url, method, headers, body, stream }) {
|
|
64
|
+
const res = await sandboxFetch(url, { method, headers, body }, id);
|
|
65
|
+
if (!stream || !res.body) return { status: res.status, text: await res.text() };
|
|
66
|
+
const progress = agentProgress(id, runId);
|
|
67
|
+
const reader = res.body.getReader();
|
|
68
|
+
// A cancelled reader reads as done: `cancelled` tells that from the reply's end.
|
|
69
|
+
const call = {
|
|
70
|
+
runId,
|
|
71
|
+
cancelled: false,
|
|
72
|
+
stop(reason) {
|
|
73
|
+
call.cancelled = true;
|
|
74
|
+
reader.cancel(reason).catch(() => {});
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
agentCalls.set(id, call);
|
|
78
|
+
const decoder = new TextDecoder();
|
|
79
|
+
let text = "";
|
|
80
|
+
const add = (piece) => {
|
|
81
|
+
if (!piece) return;
|
|
82
|
+
text += piece;
|
|
83
|
+
progress(piece);
|
|
84
|
+
};
|
|
85
|
+
try {
|
|
86
|
+
for (;;) {
|
|
87
|
+
if (latest.get(id) !== runId || call.cancelled) throw new Error("superseded by a newer run");
|
|
88
|
+
const { done, value } = await reader.read();
|
|
89
|
+
if (call.cancelled) throw new Error("superseded by a newer run");
|
|
90
|
+
if (done) break;
|
|
91
|
+
add(decoder.decode(value, { stream: true }));
|
|
92
|
+
}
|
|
93
|
+
add(decoder.decode());
|
|
94
|
+
} catch (error) {
|
|
95
|
+
reader.cancel().catch(() => {});
|
|
96
|
+
throw error;
|
|
97
|
+
} finally {
|
|
98
|
+
if (agentCalls.get(id) === call) agentCalls.delete(id);
|
|
99
|
+
}
|
|
100
|
+
return { status: res.status, text };
|
|
101
|
+
},
|
|
102
|
+
/** Stop run `runId`'s model call in flight: its response body is cancelled, or its on-device prompt aborted. */
|
|
103
|
+
cancel(id, runId) {
|
|
104
|
+
const call = agentCalls.get(id);
|
|
105
|
+
if (!call || call.runId !== runId) return false;
|
|
106
|
+
call.stop(new DOMException("The agent's run was stopped", "AbortError"));
|
|
107
|
+
agentCalls.delete(id);
|
|
108
|
+
return true;
|
|
109
|
+
},
|
|
110
|
+
/** Chrome's on-device model, through the bridge: "availability", "start" (a session), "prompt", "end". */
|
|
111
|
+
async chrome(id, runId, _, __, { op, ...payload }) {
|
|
112
|
+
if (op === "availability") {
|
|
113
|
+
if (!aiRoot?.languageModel) return "unavailable";
|
|
114
|
+
return aiRoot.languageModel.availability(payload).catch(() => "unavailable");
|
|
115
|
+
}
|
|
116
|
+
if (op === "end") return releaseAgentChat(id);
|
|
117
|
+
if (op === "start") {
|
|
118
|
+
releaseAgentChat(id);
|
|
119
|
+
if (!aiRoot?.languageModel) throw new DOMException("Chrome's on-device language model isn't available here", "NotSupportedError");
|
|
120
|
+
// create() asks the page for this pane first (consent, a download's click), and is tracked like the pane's own sessions.
|
|
121
|
+
const session = await aiHelpersFor(id).LanguageModel.create(payload);
|
|
122
|
+
if (latest.get(id) !== runId) {
|
|
123
|
+
session.destroy();
|
|
124
|
+
throw new Error("superseded by a newer run");
|
|
125
|
+
}
|
|
126
|
+
agentChats.set(id, { runId, session, tools: Array.isArray(payload.tools) && payload.tools.length > 0 });
|
|
127
|
+
return { contextWindow: session.contextWindow ?? null };
|
|
128
|
+
}
|
|
129
|
+
const chat = agentChats.get(id);
|
|
130
|
+
if (!chat || chat.runId !== runId) throw new Error("superseded by a newer run");
|
|
131
|
+
const before = Number(chat.session.contextUsage ?? chat.session.inputUsage) || 0;
|
|
132
|
+
// AGENT.cancel aborts the prompt (the bridge aborts the platform's call).
|
|
133
|
+
const controller = new AbortController();
|
|
134
|
+
const call = { runId, stop: (reason) => controller.abort(reason) };
|
|
135
|
+
agentCalls.set(id, call);
|
|
136
|
+
let out;
|
|
137
|
+
try {
|
|
138
|
+
// `stream`: the page shows the reply as it arrives (agentProgress). Only
|
|
139
|
+
// for a session without tools: with tools, a reply's tool calls come as
|
|
140
|
+
// content items, which promptStreaming() doesn't promise to carry.
|
|
141
|
+
out = payload.stream && !chat.tools && typeof chat.session.promptStreaming === "function" ? await streamed(chat.session, payload.input, agentProgress(id, runId), controller.signal) : await chat.session.prompt(payload.input, { signal: controller.signal });
|
|
142
|
+
} finally {
|
|
143
|
+
if (agentCalls.get(id) === call) agentCalls.delete(id);
|
|
144
|
+
}
|
|
145
|
+
const after = Number(chat.session.contextUsage ?? chat.session.inputUsage) || 0;
|
|
146
|
+
return { out: plainCopy(out), used: Math.max(0, after - before) };
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
/** promptStreaming() read whole: its text chunks joined, each passed to `progress` too. */
|
|
151
|
+
async function streamed(session, input, progress, signal) {
|
|
152
|
+
let text = "";
|
|
153
|
+
for await (const chunk of session.promptStreaming(input, { signal })) {
|
|
154
|
+
const piece = typeof chunk === "string" ? chunk : String(chunk ?? "");
|
|
155
|
+
text += piece;
|
|
156
|
+
progress(piece);
|
|
157
|
+
}
|
|
158
|
+
return text;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* An agent pane's partial reply, to the page (runtime.js agentProgress), for
|
|
163
|
+
* its trace only: the pane's value is still set once, when its run ends.
|
|
164
|
+
* One message in flight at a time; text that arrives meanwhile goes in the next.
|
|
165
|
+
*/
|
|
166
|
+
function agentProgress(id, runId) {
|
|
167
|
+
let queued = "";
|
|
168
|
+
let sending = false;
|
|
169
|
+
const flush = () => {
|
|
170
|
+
if (sending || !queued) return;
|
|
171
|
+
const text = queued;
|
|
172
|
+
queued = "";
|
|
173
|
+
sending = true;
|
|
174
|
+
hostRef
|
|
175
|
+
.call("agentProgress", id, runId, text)
|
|
176
|
+
.catch(() => {})
|
|
177
|
+
.finally(() => {
|
|
178
|
+
sending = false;
|
|
179
|
+
flush();
|
|
180
|
+
});
|
|
181
|
+
};
|
|
182
|
+
return (text) => {
|
|
183
|
+
queued += text;
|
|
184
|
+
flush();
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Batched calls (runtime.js sendBatch): a repeater's instances make many
|
|
189
|
+
// small calls at once (a state pane, an item port, a row each), so the page
|
|
190
|
+
// sends them as one evaluation. Each op runs as it would alone, with a console
|
|
191
|
+
// that names its pane (CONSOLE_TAG, src/runtime/console-tag.js), since the
|
|
192
|
+
// evaluation's own console names none. The reply has the ops that settled
|
|
193
|
+
// within a task; the rest come back from batchMore, as they settle, so a slow
|
|
194
|
+
// op (a fetch, a sleep) never holds back the others' results.
|
|
195
|
+
const batches = new Map(); // batch id -> { left, done: [[index, ok, value | error]], wake }
|
|
196
|
+
const CONSOLE_LEVELS = new Set(["log", "warn", "error", "info", "debug"]);
|
|
197
|
+
|
|
198
|
+
/** `forwarding` (an evaluation's console) with every line credited to `pane` (a log() line already is). */
|
|
199
|
+
function paneConsole(forwarding, pane) {
|
|
200
|
+
if (!forwarding || pane == null) return forwarding;
|
|
201
|
+
const tag = CONSOLE_TAG + JSON.stringify({ pane: String(pane) });
|
|
202
|
+
return new Proxy(forwarding, {
|
|
203
|
+
get(target, prop) {
|
|
204
|
+
const f = target[prop];
|
|
205
|
+
if (!CONSOLE_LEVELS.has(prop) || typeof f !== "function") return f;
|
|
206
|
+
return (...args) => (typeof args[0] === "string" && args[0].startsWith(CONSOLE_TAG) ? f(...args) : f(tag, ...args));
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** An op's result as andbox's own reply would carry it (its serialize: JSON-like, else text). */
|
|
212
|
+
function batchValue(value) {
|
|
213
|
+
if (value === undefined || value === null) return value;
|
|
214
|
+
if (typeof value === "function") return "[Function]";
|
|
215
|
+
try {
|
|
216
|
+
JSON.stringify(value);
|
|
217
|
+
return value;
|
|
218
|
+
} catch {
|
|
219
|
+
return String(value);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The ops of batch `id` that settled: within a task of the call, or else at least one (waiting for it). */
|
|
224
|
+
async function batchTake(id) {
|
|
225
|
+
const entry = batches.get(id);
|
|
226
|
+
if (!entry) return { done: [], left: 0 };
|
|
227
|
+
await new Promise((resolve) => setTimeout(resolve, 0)); // the quick ones settle within a task
|
|
228
|
+
while (!entry.done.length && entry.left) {
|
|
229
|
+
await new Promise((resolve) => (entry.wake = resolve));
|
|
230
|
+
await new Promise((resolve) => setTimeout(resolve, 0)); // and any others that settle with it
|
|
231
|
+
}
|
|
232
|
+
const done = entry.done.splice(0);
|
|
233
|
+
if (!entry.left) batches.delete(id);
|
|
234
|
+
return { done, left: entry.left };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
globalThis.__mallory = {
|
|
238
|
+
html,
|
|
239
|
+
fromCopy, // a copy from a pane's own Worker, as it arrives
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* What a call's code threw, as a value: the page runtime wraps every
|
|
243
|
+
* call in a try whose catch returns this, so a rejected evaluation is only
|
|
244
|
+
* ever andbox ending the Worker (a timeout), never an error the code threw
|
|
245
|
+
* (one named AbortError or TimeoutError included).
|
|
246
|
+
*/
|
|
247
|
+
thrown(e) {
|
|
248
|
+
const error = { message: e?.message || String(e), name: e?.name || "Error", ...(e?.code ? { code: e.code } : {}), ...(typeof e?.stack === "string" ? { stack: e.stack } : {}) };
|
|
249
|
+
return new Map([["mallory:thrown", error]]);
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Run several calls' code at once: `ops` are functions of a console
|
|
254
|
+
* (each one call's code), `panes` the pane each is for. Resolves to
|
|
255
|
+
* `{ done: [[index, ok, value | { message, name, code?, stack? }]], left }`.
|
|
256
|
+
*/
|
|
257
|
+
batch(id, ops, panes, forwardingConsole) {
|
|
258
|
+
const entry = { left: ops.length, done: [], wake: null };
|
|
259
|
+
batches.set(id, entry);
|
|
260
|
+
ops.forEach((op, i) => {
|
|
261
|
+
let run;
|
|
262
|
+
try {
|
|
263
|
+
run = Promise.resolve(op(paneConsole(forwardingConsole, panes[i])));
|
|
264
|
+
} catch (error) {
|
|
265
|
+
run = Promise.reject(error);
|
|
266
|
+
}
|
|
267
|
+
run
|
|
268
|
+
.then(
|
|
269
|
+
(value) => [i, 1, batchValue(value)],
|
|
270
|
+
(e) => [i, 0, { message: e?.message || String(e), name: e?.name || "Error", ...(e?.code ? { code: e.code } : {}), ...(typeof e?.stack === "string" ? { stack: e.stack } : {}) }],
|
|
271
|
+
)
|
|
272
|
+
.then((result) => {
|
|
273
|
+
entry.done.push(result);
|
|
274
|
+
entry.left--;
|
|
275
|
+
const wake = entry.wake;
|
|
276
|
+
entry.wake = null;
|
|
277
|
+
wake?.();
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
return batchTake(id);
|
|
281
|
+
},
|
|
282
|
+
|
|
283
|
+
/** More of batch `id`'s results, as they settle. */
|
|
284
|
+
batchMore: (id) => batchTake(id),
|
|
285
|
+
|
|
286
|
+
/** Batches with ops still running. */
|
|
287
|
+
batchStats: () => ({ open: batches.size }),
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* An agent pane's part in the sandbox (see AGENT above): `op` is prepare,
|
|
291
|
+
* call, http, chrome or cancel. An abort or a timeout inside it (a model call
|
|
292
|
+
* cancelled, a session destroyed by a newer run, a bridge call's limit) fails
|
|
293
|
+
* the op as a plain Error: the page reads an AbortError or TimeoutError from
|
|
294
|
+
* an evaluation as the Worker being killed, and would restart it.
|
|
295
|
+
*/
|
|
296
|
+
async agent(id, runId, op, sources, names, payload, forwardingConsole) {
|
|
297
|
+
if (!Object.hasOwn(AGENT, op)) throw new Error(`unknown agent operation ${op}`);
|
|
298
|
+
try {
|
|
299
|
+
return await AGENT[op](id, runId, sources ?? [], names ?? [], payload ?? {}, forwardingConsole);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
if (error?.name !== "AbortError" && error?.name !== "TimeoutError") throw error;
|
|
302
|
+
throw new Error(latest.get(id) !== runId ? "superseded by a newer run" : `${error.name === "AbortError" ? "stopped" : "timed out"}: ${error.message}`);
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
/** Replace the variables panes see (`missing`: the requireEnv error, `{name}` replaced). */
|
|
307
|
+
setEnv(values, missing) {
|
|
308
|
+
const next = Object.create(null);
|
|
309
|
+
for (const [name, value] of Object.entries(values ?? {})) if (/^(?!__proto__$)[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name) && typeof value === "string") next[name] = value;
|
|
310
|
+
env = Object.freeze(next);
|
|
311
|
+
if (typeof missing === "string") envMissing = missing;
|
|
312
|
+
return Object.keys(next).length;
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
/** Stamp what panes send (events, channel sends) with this instant (ms since the epoch) instead of the real time; null goes back. */
|
|
316
|
+
setClock(ms) {
|
|
317
|
+
clockAt = Number.isFinite(ms) ? ms : null;
|
|
318
|
+
return clockAt;
|
|
319
|
+
},
|
|
320
|
+
|
|
321
|
+
/** Replace the shared modules package panes read as `pkg.module`: `[[id prefix, { specifier, package, version, name, problem? }], …]` (src/packages/module.js). */
|
|
322
|
+
setModules(tables) {
|
|
323
|
+
moduleTables = (Array.isArray(tables) ? tables : []).filter(([prefix, entry]) => typeof prefix === "string" && entry && typeof entry.specifier === "string").sort((a, b) => b[0].length - a[0].length);
|
|
324
|
+
return moduleTables.length;
|
|
325
|
+
},
|
|
326
|
+
|
|
327
|
+
/** Replace the files package panes read as `assets`: `[[id prefix, [{ name, type, data }]], …]` (src/packages/assets.js). */
|
|
328
|
+
setAssets(tables) {
|
|
329
|
+
assetTables = (Array.isArray(tables) ? tables : []).filter(([prefix, entries]) => typeof prefix === "string" && Array.isArray(entries)).sort((a, b) => b[0].length - a[0].length);
|
|
330
|
+
assetsCache.clear();
|
|
331
|
+
return assetTables.length;
|
|
332
|
+
},
|
|
333
|
+
|
|
334
|
+
/** Replace what panes' profile views are read with: `[[paneId, options], …]` (src/model/profile-settings.js). */
|
|
335
|
+
setProfileSettings(entries) {
|
|
336
|
+
profileSettings.clear();
|
|
337
|
+
for (const [id, options] of entries ?? []) if (options && typeof options === "object") profileSettings.set(String(id), options);
|
|
338
|
+
return profileSettings.size;
|
|
339
|
+
},
|
|
340
|
+
|
|
341
|
+
/** The codec panes of the open canvas, by name: `{ name: codec setting | null }` (null: two panes share the name). */
|
|
342
|
+
setCodecs(table) {
|
|
343
|
+
codecTable = table && typeof table === "object" ? table : {};
|
|
344
|
+
return Object.keys(codecTable).length;
|
|
345
|
+
},
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* One codec pane's run (src/model/canvas.js): decode `bytes` when it has some and encode `value` when it has one. Its value is
|
|
349
|
+
* keyed by the pane's output names; a codec error is the pane's error, with the schema's lines in the message.
|
|
350
|
+
*/
|
|
351
|
+
async codecRun(spec, input) {
|
|
352
|
+
if (!codecKit) throw new Error("this runtime has no codec support");
|
|
353
|
+
const out = { format: spec.format, ...(codecKit.core.SCHEMA_FORMATS.includes(spec.format) && spec.format !== "struct" ? { type: spec.type ?? "" } : {}) };
|
|
354
|
+
if (input.bytes !== undefined && input.bytes !== null) out.decoded = await codecKit.engine.decode(spec, input.bytes);
|
|
355
|
+
if (input.value !== undefined && input.value !== null) out.encoded = await codecKit.engine.encode(spec, input.value);
|
|
356
|
+
if (out.decoded === undefined && out.encoded === undefined) {
|
|
357
|
+
const found = await codecKit.engine.analyze(spec);
|
|
358
|
+
if (!found.ok) throw new codecKit.core.CodecError(`schema${found.errors[0].line ? ` line ${found.errors[0].line}` : ""}: ${found.errors[0].message}${found.errors.length > 1 ? ` (and ${found.errors.length - 1} more)` : ""}`, { errors: found.errors });
|
|
359
|
+
out.types = found.types;
|
|
360
|
+
}
|
|
361
|
+
return out;
|
|
362
|
+
},
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* A codec call from the page (the serial panel's decode, the pane's schema check): `op` is "decode", "encode" or "analyze";
|
|
366
|
+
* `spec` the codec setting, or the name of a codec pane. Answers `{ ok: true, … }` or `{ ok: false, message, errors? }` instead of throwing.
|
|
367
|
+
*/
|
|
368
|
+
async codecCall(op, request) {
|
|
369
|
+
try {
|
|
370
|
+
if (!codecKit) return { ok: false, message: "this runtime has no codec support" };
|
|
371
|
+
const named = typeof request.codec === "string";
|
|
372
|
+
const spec = named ? codecTable[request.codec] : request.codec;
|
|
373
|
+
if (!spec) return { ok: false, message: named ? `no codec pane is named "${request.codec}"${spec === null ? " (or two share the name)" : ""}` : "no codec" };
|
|
374
|
+
if (op === "analyze") {
|
|
375
|
+
const found = await codecKit.engine.analyze(spec); // the call worked (ok); whether the schema is fine is `errors`
|
|
376
|
+
return { ok: true, errors: found.errors, types: found.types };
|
|
377
|
+
}
|
|
378
|
+
if (op === "decode") return { ok: true, value: await codecKit.engine.decode(spec, request.bytes, { type: request.type }) };
|
|
379
|
+
if (op === "encode") return { ok: true, bytes: [...(await codecKit.engine.encode(spec, request.value, { type: request.type }))] };
|
|
380
|
+
return { ok: false, message: `unknown codec call ${op}` };
|
|
381
|
+
} catch (e) {
|
|
382
|
+
return { ok: false, message: String(e?.message ?? e), ...(e?.errors ? { errors: e.errors } : {}) };
|
|
383
|
+
}
|
|
384
|
+
},
|
|
385
|
+
|
|
386
|
+
/** Replace the evaluations in progress: `[[idPrefix, row], …]` (see evaluationOf). */
|
|
387
|
+
setEvaluations(entries) {
|
|
388
|
+
evaluations = new Map((entries ?? []).map(([prefix, row]) => [String(prefix), deepFreeze(row ?? null)]));
|
|
389
|
+
return evaluations.size;
|
|
390
|
+
},
|
|
391
|
+
|
|
392
|
+
/** This sandbox is a pane's own Worker: its inputs are copies; what needs the shared sandbox is forwarded to it by copy. */
|
|
393
|
+
ownWorker() {
|
|
394
|
+
ownMode = true;
|
|
395
|
+
return true;
|
|
396
|
+
},
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Copies of values for a pane in its own Worker: `sources` (Worker
|
|
400
|
+
* keys) named `names` (its inputs; the state panes its setters write to),
|
|
401
|
+
* checked first so a value that can't be copied says which input and which
|
|
402
|
+
* part of it. `event` (a reader of events): that event's key, whose
|
|
403
|
+
* stored event goes too. A Map: `{ keys, values, event? }`, as loadOwn takes it.
|
|
404
|
+
* `to` (`{ pane, ticket }`): it goes straight to that pane's own Worker
|
|
405
|
+
* on their channel instead, and this returns only that it went.
|
|
406
|
+
*/
|
|
407
|
+
copyOut(sources, names = [], event, to) {
|
|
408
|
+
const out = [];
|
|
409
|
+
const keys = [];
|
|
410
|
+
let binary = false;
|
|
411
|
+
sources.forEach((s, i) => {
|
|
412
|
+
// A setter's state pane (runtime.js ownReads, "…()'s state"): a setter wire doesn't wait for a value; without one, setX(fn) starts from undefined.
|
|
413
|
+
if (!values.has(s) && String(names[i] ?? "").endsWith(SETTER_STATE)) return;
|
|
414
|
+
if (!values.has(s)) throw new Error(`waiting for ${s}`);
|
|
415
|
+
keys.push(s);
|
|
416
|
+
const budget = { left: 200000 };
|
|
417
|
+
const problem = copyProblem(values.get(s), "", budget);
|
|
418
|
+
if (problem) throw new Error(`Input "${names[i] ?? s}" can't be copied into this pane's own Worker: it holds ${problem}. Functions, modules and class instances stay in the shared sandbox (${OWN_OFF}).`);
|
|
419
|
+
binary ||= Boolean(budget.binary);
|
|
420
|
+
out.push(toCopy(values.get(s)));
|
|
421
|
+
});
|
|
422
|
+
const reply = wrapped({ keys, values: out, ...(binary ? { binary } : {}) });
|
|
423
|
+
const stored = event == null ? undefined : eventStore.get(event);
|
|
424
|
+
if (stored) {
|
|
425
|
+
const problem = copyProblem(stored.payload);
|
|
426
|
+
if (problem) throw new Error(`The "${stored.name}" event can't be copied into this pane's own Worker: its payload holds ${problem} (${OWN_OFF}).`);
|
|
427
|
+
reply.set("event", { key: event, event: { ...stored, payload: toCopy(stored.payload) } });
|
|
428
|
+
}
|
|
429
|
+
if (!to) return reply;
|
|
430
|
+
const link = ownLinks.get(String(to.pane));
|
|
431
|
+
if (!link) throw new Error(LINK_GONE);
|
|
432
|
+
link.port.postMessage({ ticket: to.ticket, value: reply });
|
|
433
|
+
return wrapped({ sent: true });
|
|
434
|
+
},
|
|
435
|
+
|
|
436
|
+
/** The shared sandbox's end of the channel to pane `id`'s own Worker, replacing any it had. */
|
|
437
|
+
linkOwn(id, port) {
|
|
438
|
+
closeLink(ownLinks.get(id));
|
|
439
|
+
ownLinks.set(id, makeLink(port));
|
|
440
|
+
return true;
|
|
441
|
+
},
|
|
442
|
+
|
|
443
|
+
/** The channel to pane `id`'s own Worker goes (that Worker went). */
|
|
444
|
+
unlinkOwn(id) {
|
|
445
|
+
closeLink(ownLinks.get(id));
|
|
446
|
+
return ownLinks.delete(id);
|
|
447
|
+
},
|
|
448
|
+
|
|
449
|
+
/** What pane `id`'s own Worker sent on the channel with `ticket`: a Map as ownOut and ownValue make it. */
|
|
450
|
+
fromOwn(id, ticket, waitMs) {
|
|
451
|
+
return takeFrom(ownLinks.get(id), ticket, waitMs);
|
|
452
|
+
},
|
|
453
|
+
|
|
454
|
+
/** A copy pane `id`'s own Worker sent that nothing will store (a live value the page refused). */
|
|
455
|
+
dropFromOwn(id, ticket) {
|
|
456
|
+
return ownLinks.get(id)?.inbox.delete(ticket) ?? false;
|
|
457
|
+
},
|
|
458
|
+
|
|
459
|
+
/** A pane's own Worker: its end of the channel to the shared sandbox, replacing any it had. */
|
|
460
|
+
linkShared(port) {
|
|
461
|
+
closeLink(sharedLink);
|
|
462
|
+
sharedLink = makeLink(port);
|
|
463
|
+
return true;
|
|
464
|
+
},
|
|
465
|
+
|
|
466
|
+
/** A pane's own Worker: the copies the shared sandbox sent with `ticket`, as loadOwn takes them. */
|
|
467
|
+
fromShared(ticket, waitMs) {
|
|
468
|
+
return takeFrom(sharedLink, ticket, waitMs);
|
|
469
|
+
},
|
|
470
|
+
|
|
471
|
+
/** A pane's own Worker takes new copies of its inputs (a live pane set to resume, a for-each run): see loadOwn. */
|
|
472
|
+
ownInputs(payload) {
|
|
473
|
+
loadOwn(payload);
|
|
474
|
+
return true;
|
|
475
|
+
},
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Run a pane in its own Worker: `payload` holds copies of its inputs
|
|
479
|
+
* (loadOwn), then exec's arguments. Its value isn't kept here: it goes back
|
|
480
|
+
* as a copy, `{ out, effects, state? }` (ownOut's Map; effects: its run left
|
|
481
|
+
* something here that a restart of the shared sandbox can't put back; state:
|
|
482
|
+
* its `state` as JSON), or `{ result }` for a live run (an emitter's
|
|
483
|
+
* first value as ownOut's Map), a skip or a superseded run. It replies once
|
|
484
|
+
* its events and its setters' changes have reached the shared sandbox.
|
|
485
|
+
*/
|
|
486
|
+
async runOwn(payload, id, runId, sources, names, body, view, label, forwardingConsole, setterNames = [], skippedSources = [], fresh = false, extra = {}) {
|
|
487
|
+
loadOwn(payload);
|
|
488
|
+
const result = await afterEvents(id, () => globalThis.__mallory.execRun(id, runId, sources, names, body, view, label, forwardingConsole, setterNames, skippedSources, fresh, extra));
|
|
489
|
+
if (result?.live || result?.superseded || result?.skipped || !values.has(id)) return wrapped({ result });
|
|
490
|
+
return ownValue(id, extra?.stateBytes);
|
|
491
|
+
},
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Store what a pane's own Worker made: `payload` is ownOut's Map, a
|
|
495
|
+
* copy or a skip. Its events were sent from its own Worker, so none are
|
|
496
|
+
* made here. Returns its preview, or `{ skipped, reason }`.
|
|
497
|
+
*/
|
|
498
|
+
setOwn(id, runId, payload, view) {
|
|
499
|
+
eventOutputs.delete(id);
|
|
500
|
+
const value = fromOwn(payload);
|
|
501
|
+
if (isSkip(value)) {
|
|
502
|
+
latest.set(id, runId);
|
|
503
|
+
return skipped(id, value);
|
|
504
|
+
}
|
|
505
|
+
return globalThis.__mallory.set(id, runId, value, view);
|
|
506
|
+
},
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* What a pane in its own Worker sent: `list` as its Worker's
|
|
510
|
+
* flushEvents made it, each event with its `payload` and each channel send
|
|
511
|
+
* with its own. They are kept here, as this sandbox keeps its own panes'
|
|
512
|
+
* (event rings, channel payloads), and the list comes back as the page
|
|
513
|
+
* expects it from a pane here.
|
|
514
|
+
*/
|
|
515
|
+
ownEvents(id, list) {
|
|
516
|
+
const out = [];
|
|
517
|
+
for (const item of list ?? []) {
|
|
518
|
+
if (item?.channel !== undefined) {
|
|
519
|
+
values.set(item.key, fromCopy(item.payload));
|
|
520
|
+
let ring = channelRings.get(id);
|
|
521
|
+
if (!ring) channelRings.set(id, (ring = []));
|
|
522
|
+
ring.push(item.key);
|
|
523
|
+
while (ring.length > CHANNEL_KEEP) values.delete(ring.shift());
|
|
524
|
+
out.push({ channel: item.channel, scope: item.scope, key: item.key, at: item.at, bytes: item.bytes, ...(item.ack ? { ack: true } : {}) });
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
if (item?.marker) {
|
|
528
|
+
out.push({ name: item.name, key: item.key, marker: item.marker, at: item.at, source: item.source, bytes: 0, ...(item.ack ? { ack: true } : {}) }); // a batch boundary: nothing to keep
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
const node = `${id}#${item.name}`;
|
|
532
|
+
const event = Object.freeze({ name: item.name, payload: fromCopy(item.payload), at: item.at, source: item.source, ...(item.batch === undefined ? {} : { batch: Object.freeze({ key: item.batch }) }) });
|
|
533
|
+
const result = keepEvent(node, item.key, event, item.keep);
|
|
534
|
+
latest.set(node, (latest.get(node) ?? 0) + 1);
|
|
535
|
+
out.push({ name: item.name, key: item.key, result, at: item.at, source: item.source, bytes: approxBytes(event.payload), ...(item.batch === undefined ? {} : { batch: item.batch }), ...(item.ack ? { ack: true } : {}) });
|
|
536
|
+
}
|
|
537
|
+
return out;
|
|
538
|
+
},
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* A strict pane's inputs (src/runtime/strict.js) as one JSON text, `{ name: value }`: `sources`
|
|
542
|
+
* (Worker keys) named `names`. Each must come back exactly from JSON (storableJSON); one that
|
|
543
|
+
* doesn't (a Map, a function, a Blob, NaN) is refused, naming the input and the part.
|
|
544
|
+
*/
|
|
545
|
+
strictIn(sources, names = [], maxLength = 16 * 1024 * 1024) {
|
|
546
|
+
const parts = [];
|
|
547
|
+
let length = 2;
|
|
548
|
+
sources.forEach((s, i) => {
|
|
549
|
+
if (!values.has(s)) throw new Error(`waiting for ${s}`);
|
|
550
|
+
const name = names[i] ?? s;
|
|
551
|
+
let kept;
|
|
552
|
+
if (exporter?.storableJSON) kept = exporter.storableJSON(values.get(s), { maxLength });
|
|
553
|
+
else {
|
|
554
|
+
try {
|
|
555
|
+
kept = { ok: true, text: JSON.stringify(values.get(s)) };
|
|
556
|
+
} catch (error) {
|
|
557
|
+
kept = { ok: false, reason: error.message };
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (!kept?.ok || typeof kept.text !== "string") throw new Error(`Input "${name}" can't go into a strict pane: ${kept?.reason ?? "it isn't JSON"}. Strict panes take JSON only (numbers, strings, booleans, null, arrays and plain objects).`);
|
|
561
|
+
length += kept.text.length + name.length + 4;
|
|
562
|
+
if (length > maxLength) throw new Error(`The inputs of a strict pane are larger than ${Math.round(maxLength / 1048576)} MB as JSON.`);
|
|
563
|
+
parts.push(`${JSON.stringify(name)}:${kept.text}`);
|
|
564
|
+
});
|
|
565
|
+
return `{${parts.join(",")}}`;
|
|
566
|
+
},
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Put back an eval pane's `state` after a restart: `text` (JSON, as
|
|
570
|
+
* finish kept it) for code `body`, unless the pane already has one here (a
|
|
571
|
+
* pane's own Worker that a timeout of the shared sandbox didn't end).
|
|
572
|
+
*/
|
|
573
|
+
restoreState(id, body, text) {
|
|
574
|
+
if (typeof text !== "string" || paneStates.has(id)) return false;
|
|
575
|
+
paneStates.set(id, { body, value: JSON.parse(text) });
|
|
576
|
+
return true;
|
|
577
|
+
},
|
|
578
|
+
|
|
579
|
+
/** Run an eval pane and store its value (or, when it returns skip(…), drop it). */
|
|
580
|
+
exec(...args) {
|
|
581
|
+
return afterEvents(args[0], () => globalThis.__mallory.execRun(...args)); // its reply goes after its events
|
|
582
|
+
},
|
|
583
|
+
|
|
584
|
+
/** exec's run (exec replies with its result once the events it sent have reached the page). */
|
|
585
|
+
async execRun(id, runId, sources, names, body, view, label, forwardingConsole, setterNames = [], skippedSources = [], fresh = false, extra = {}) {
|
|
586
|
+
if (liveRuns.has(id) && liveRuns.get(id).runId !== runId) endLiveThenRetire(id, runId); // the live run it replaces: its finally, then its cleanups…
|
|
587
|
+
if (liveEnding.has(id)) await liveEnding.get(id); // …before this run's code
|
|
588
|
+
newRun(id, runId); // a new run: the sessions the last one made and its cleanups go
|
|
589
|
+
latest.set(id, runId);
|
|
590
|
+
if (fresh) paneStates.delete(id); // ▶ or run all: `state` starts again
|
|
591
|
+
else if (typeof extra?.restoreState === "string") globalThis.__mallory.restoreState(id, body, extra.restoreState); // its `state` from before a restart
|
|
592
|
+
// Its event outputs: emit.event(name, …) and values keyed by their names send on them.
|
|
593
|
+
if (extra?.events?.length) eventOutputs.set(id, { runId, names: extra.events.map(String), keep: Number(extra.keep) || 1002, label: label || id });
|
|
594
|
+
else eventOutputs.delete(id);
|
|
595
|
+
// Live outputs: a body that yields is a generator, one that mentions emit an emitter.
|
|
596
|
+
const kind = liveKind(body);
|
|
597
|
+
// `holding`: emits made while the code runs wait for its result, so the page gets the returned value first.
|
|
598
|
+
const entry = kind ? { runId, kind, view, sleeps: new Set(), sending: false, ended: false, count: 0, holding: true, forwardingConsole } : undefined;
|
|
599
|
+
if (entry) liveRuns.set(id, entry);
|
|
600
|
+
let value;
|
|
601
|
+
lastReads.set(id, { sources: [...sources], names: [...names], label: label || id });
|
|
602
|
+
try {
|
|
603
|
+
value = await run(id, sources, names, body, label, forwardingConsole, setterNames, undefined, skippedSources, { runId, withState: true, live: entry, generator: kind === "generator", event: extra?.event, eventInput: extra?.eventInput });
|
|
604
|
+
} catch (error) {
|
|
605
|
+
if (entry && liveRuns.get(id) === entry) endLive(id);
|
|
606
|
+
throw error;
|
|
607
|
+
}
|
|
608
|
+
if (latest.get(id) !== runId) return { superseded: true }; // superseded: its run (and any emit it held) ended with the newer one's start
|
|
609
|
+
if (entry) {
|
|
610
|
+
// Emits made from now on go out in order behind this result (the page applies none before it: src/model/live.js).
|
|
611
|
+
entry.holding = false;
|
|
612
|
+
// What it returned (unless undefined) is its first value, newer than any emit it held; else the held one goes next.
|
|
613
|
+
if (value !== undefined && kind === "emit") entry.pending = undefined;
|
|
614
|
+
else if (entry.pending) setTimeout(() => flushEmit(id, entry, forwardingConsole), 0);
|
|
615
|
+
if (entry.closing) setTimeout(() => closeEmits(id, entry), 0); // emit.close() while the code ran: after what it emitted
|
|
616
|
+
}
|
|
617
|
+
if (kind === "generator") {
|
|
618
|
+
entry.gen = value; // pulled by liveNext
|
|
619
|
+
return { live: "generator" };
|
|
620
|
+
}
|
|
621
|
+
if (kind === "emit") {
|
|
622
|
+
if (value === undefined) return { live: "emit" };
|
|
623
|
+
entry.count++;
|
|
624
|
+
if (ownMode) return { live: "emit", first: ownLive(id, value, "This pane's value") }; // a copy for the shared sandbox
|
|
625
|
+
if (isSkip(value)) return { live: "emit", first: skipped(id, value) };
|
|
626
|
+
values.set(id, value);
|
|
627
|
+
return { live: "emit", first: present(id, value, view, { sync: true }) };
|
|
628
|
+
}
|
|
629
|
+
if (isSkip(value)) return skipped(id, value);
|
|
630
|
+
values.set(id, value);
|
|
631
|
+
if (ownMode) {
|
|
632
|
+
// Its own Worker: the shared sandbox makes the preview from its copy (runOwn), so none is made here.
|
|
633
|
+
if (eventOutputs.has(id)) eventsFromValue(id, value);
|
|
634
|
+
return { own: true };
|
|
635
|
+
}
|
|
636
|
+
return present(id, value, view);
|
|
637
|
+
},
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* A live pane's next value: resume its generator until it yields.
|
|
641
|
+
* `resume`: its inputs changed (a pane set to resume), so its `inputs` view
|
|
642
|
+
* follows and the `yield` it waits at evaluates to the new inputs. Returns
|
|
643
|
+
* a preview (the value is stored), `{ skipped, reason }`, `{ done: true }`
|
|
644
|
+
* when it finished, or `{ superseded: true }` when the run ended meanwhile.
|
|
645
|
+
* Like exec, it replies once the events the step sent have reached the page.
|
|
646
|
+
*/
|
|
647
|
+
liveNext(...args) {
|
|
648
|
+
return afterEvents(args[0], () => globalThis.__mallory.liveStep(...args));
|
|
649
|
+
},
|
|
650
|
+
|
|
651
|
+
async liveStep(id, runId, resume = false, skippedSources = []) {
|
|
652
|
+
const entry = liveRuns.get(id);
|
|
653
|
+
if (!entry || entry.runId !== runId || entry.ended || !entry.gen) return { done: true };
|
|
654
|
+
const arg = resume ? liveInputs(entry, skippedSources) : undefined;
|
|
655
|
+
let step;
|
|
656
|
+
const done = codeRuns(id); // timers started while its code runs count against it
|
|
657
|
+
try {
|
|
658
|
+
step = await startsCode(id, () => entry.gen.next(arg));
|
|
659
|
+
} catch (error) {
|
|
660
|
+
if (liveRuns.get(id) === entry) liveRuns.delete(id); // a generator that threw is finished
|
|
661
|
+
entry.ended = true;
|
|
662
|
+
throw error;
|
|
663
|
+
} finally {
|
|
664
|
+
done();
|
|
665
|
+
}
|
|
666
|
+
if (entry.ended || liveRuns.get(id) !== entry || latest.get(id) !== runId) return { superseded: true };
|
|
667
|
+
if (step.done) {
|
|
668
|
+
liveRuns.delete(id); // finished by itself: its cleanups stay until its next run, as a plain run's do
|
|
669
|
+
entry.ended = true;
|
|
670
|
+
return { done: true };
|
|
671
|
+
}
|
|
672
|
+
entry.count++;
|
|
673
|
+
const value = withAssigned(step.value, entry.assigned); // outputs.name = …
|
|
674
|
+
if (ownMode) return ownLive(id, value, "yield"); // its own Worker: a copy for the shared sandbox
|
|
675
|
+
if (isSkip(value)) return skipped(id, value);
|
|
676
|
+
values.set(id, value);
|
|
677
|
+
return present(id, value, entry.view, { sync: true });
|
|
678
|
+
},
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* The canvas transport paused or played an emit pane's live run:
|
|
682
|
+
* while paused, its emits stay here, the latest winning (as while its code
|
|
683
|
+
* runs: `holding`), and emit.close() waits. Returns `{ pending }`: whether a
|
|
684
|
+
* value is waiting (on play it goes to the page next).
|
|
685
|
+
*/
|
|
686
|
+
livePause(id, runId, paused) {
|
|
687
|
+
const entry = liveRuns.get(id);
|
|
688
|
+
if (!entry || entry.runId !== runId || entry.ended) return { pending: false };
|
|
689
|
+
entry.paused = Boolean(paused);
|
|
690
|
+
const pending = Boolean(entry.pending);
|
|
691
|
+
if (!entry.paused) setTimeout(() => (entry.pending ? flushEmit(id, entry, entry.forwardingConsole) : closeEmits(id, entry)), 0);
|
|
692
|
+
return { pending };
|
|
693
|
+
},
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* A step of a paused emit pane: the value waiting, now (stored as its
|
|
697
|
+
* value; its preview, or `{ skipped, reason }`), `{ none: true }` when none
|
|
698
|
+
* waits, or `{ busy: true }` while one is on its way to the page.
|
|
699
|
+
*/
|
|
700
|
+
liveTake(id, runId) {
|
|
701
|
+
const entry = liveRuns.get(id);
|
|
702
|
+
if (!entry || entry.runId !== runId || entry.ended) return { none: true };
|
|
703
|
+
if (entry.sending) return { busy: true };
|
|
704
|
+
const taken = takePending(id, entry, entry.forwardingConsole);
|
|
705
|
+
if (!taken) return { none: true };
|
|
706
|
+
if (entry.closing) setTimeout(() => closeEmits(id, entry), 0);
|
|
707
|
+
return taken.result;
|
|
708
|
+
},
|
|
709
|
+
|
|
710
|
+
/** Tests (createRuntime's eventBatchGapMs): stretch the wait between a pane's event batches. */
|
|
711
|
+
setEventBatchGap(ms) {
|
|
712
|
+
eventBatchGapMs = Math.max(0, Number(ms) || 0);
|
|
713
|
+
return eventBatchGapMs;
|
|
714
|
+
},
|
|
715
|
+
|
|
716
|
+
/** A resume pane's inputs changed (an emitter: no generator to resume): its `inputs` view follows. */
|
|
717
|
+
liveInputs(id, runId, skippedSources = []) {
|
|
718
|
+
const entry = liveRuns.get(id);
|
|
719
|
+
if (!entry || entry.runId !== runId || entry.ended) return false;
|
|
720
|
+
liveInputs(entry, skippedSources);
|
|
721
|
+
return true;
|
|
722
|
+
},
|
|
723
|
+
|
|
724
|
+
/** End a live run (superseded, closed, deleted, enough values): its generator's `finally`, then its cleanups. */
|
|
725
|
+
async liveEnd(id, runId) {
|
|
726
|
+
const entry = liveRuns.get(id);
|
|
727
|
+
if (!entry || entry.runId !== runId) return false;
|
|
728
|
+
await endLiveThenRetire(id, runId + 1);
|
|
729
|
+
return true;
|
|
730
|
+
},
|
|
731
|
+
|
|
732
|
+
/** For-each: each input's array length (null when it isn't an array, or was skipped). */
|
|
733
|
+
eachLengths(id, runId, sources, skippedSources = [], fresh = false, restore) {
|
|
734
|
+
if (!(latest.get(id) >= runId)) {
|
|
735
|
+
// a new for-each run (its items share it)
|
|
736
|
+
releaseAI(id);
|
|
737
|
+
retire(id, runId);
|
|
738
|
+
if (fresh) {
|
|
739
|
+
paneStates.delete(id);
|
|
740
|
+
eachMemos.delete(id); // ▶ and run all run every item again
|
|
741
|
+
eachImports.delete(id);
|
|
742
|
+
} else if (restore) globalThis.__mallory.restoreState(id, restore.body, restore.text); // its `state` from before a restart
|
|
743
|
+
}
|
|
744
|
+
if (!(latest.get(id) > runId)) latest.set(id, runId);
|
|
745
|
+
const missing = missingInputs(sources, skippedSources);
|
|
746
|
+
if (missing.length) throw new Error(`waiting for ${missing.join(", ")}`);
|
|
747
|
+
return sources.map((s) => (!skippedSources.includes(s) && Array.isArray(values.get(s)) ? values.get(s).length : null));
|
|
748
|
+
},
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* A for-each pane's inputs as the next run would see them, without starting one: each input's array
|
|
752
|
+
* length (null when it isn't an array), or `waiting` with the inputs that have no value yet. It touches no run.
|
|
753
|
+
*/
|
|
754
|
+
eachPeek(sources, skippedSources = []) {
|
|
755
|
+
const waiting = missingInputs(sources, skippedSources);
|
|
756
|
+
if (waiting.length) return { waiting };
|
|
757
|
+
return { lengths: sources.map((s) => (!skippedSources.includes(s) && Array.isArray(values.get(s)) ? values.get(s).length : null)) };
|
|
758
|
+
},
|
|
759
|
+
|
|
760
|
+
/** The key matching a run would make (eachMatch), for the preview: `{ matched }`, or `{ error }` when an element has no key or a key twice. It touches no run. */
|
|
761
|
+
eachPeekMatch({ sources, names, over, spec, label, skipped: skippedSources = [] }) {
|
|
762
|
+
try {
|
|
763
|
+
const read = keyReader(String(spec), label);
|
|
764
|
+
const lists = over.map((i) => ({ input: i, name: names[i], list: skippedSources.includes(sources[i]) ? [] : values.get(sources[i]) ?? [] }));
|
|
765
|
+
return { matched: matchByKey(lists, read) };
|
|
766
|
+
} catch (err) {
|
|
767
|
+
return { error: String(err?.message ?? err) };
|
|
768
|
+
}
|
|
769
|
+
},
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* For-each matching by key: the rows (src/runtime/keys.js matchByKey) the iterated inputs' elements line up
|
|
773
|
+
* in, each element read for `spec` (a key path or expression). An element with no key, or a key an input has twice,
|
|
774
|
+
* is the pane's error naming the input and item.
|
|
775
|
+
*/
|
|
776
|
+
eachMatch(id, runId, { sources, names, over, spec, label, skipped: skippedSources = [] }) {
|
|
777
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
778
|
+
const read = keyReader(String(spec), label);
|
|
779
|
+
return matchByKey(
|
|
780
|
+
over.map((i) => ({ input: i, name: names[i], list: skippedSources.includes(sources[i]) ? [] : values.get(sources[i]) ?? [] })),
|
|
781
|
+
read,
|
|
782
|
+
);
|
|
783
|
+
},
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* Keyed for-each: which items of this run must run. Each item's key
|
|
787
|
+
* (`key`, see keyReader) is read from its element of the first iterated
|
|
788
|
+
* input, and its fingerprint is a content hash of what it is given (its
|
|
789
|
+
* elements of every iterated input; and its index when the code reads
|
|
790
|
+
* `index`). An item whose key the pane kept, with the same fingerprint, is
|
|
791
|
+
* reused: its kept result goes straight into this run's results. Kept
|
|
792
|
+
* results are thrown away when the code, the key, the inputs' names or
|
|
793
|
+
* order, which inputs are iterated, or the value of any input that isn't
|
|
794
|
+
* iterated changed (compared as the cut-off compares values: by content for
|
|
795
|
+
* JSON-like ones, by identity otherwise); on ▶ and run all (eachLengths
|
|
796
|
+
* `fresh`); and when the Worker restarts. Keys no longer in the input drop
|
|
797
|
+
* their results. An item that isn't JSON-like always runs.
|
|
798
|
+
* A missing or duplicate key runs every item by position, as without a key:
|
|
799
|
+
* `{ keyed: false, note }`. Otherwise `{ keyed: true, run: [index…],
|
|
800
|
+
* reused: [[index, { brief } | { skipped, reason }]…], note? }`.
|
|
801
|
+
* `binds[i]` is item i's itemBinding (src/model/foreach.js); `over` the
|
|
802
|
+
* iterated inputs' indexes.
|
|
803
|
+
*/
|
|
804
|
+
eachPlan(id, runId, { sources, names, over, binds, key: spec, match, matchKeys, body, label, skipped: skippedSources = [] }) {
|
|
805
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
806
|
+
const read = keyReader(String(spec), label); // a key expression that doesn't compile is the pane's error
|
|
807
|
+
const args = sources.map((s) => (skippedSources.includes(s) ? undefined : values.get(s)));
|
|
808
|
+
const count = binds.length;
|
|
809
|
+
const keys = new Array(count);
|
|
810
|
+
const seen = new Map(); // key -> item index
|
|
811
|
+
let problem;
|
|
812
|
+
// An item's key from its elements of the iterated inputs (`take(p)`: the element of the p-th bound input).
|
|
813
|
+
const keyOfItem = (i, take) => {
|
|
814
|
+
if (match === "cross" || match === "last") {
|
|
815
|
+
// Several inputs make the item: its key is each one's, so a repeated element still names a distinct item.
|
|
816
|
+
// An element without the key (an input of another shape) counts by its place in its own input; the fingerprint
|
|
817
|
+
// below still decides whether a kept result is reused.
|
|
818
|
+
return `j${JSON.stringify(binds[i].map(([, element], p) => (element < 0 ? null : keyText(read(take(p), i)) ?? `@${element}`)))}`;
|
|
819
|
+
}
|
|
820
|
+
return keyText(read(binds[i][0][1] < 0 ? undefined : take(0), i));
|
|
821
|
+
};
|
|
822
|
+
const heldElement = (i) => (p) => args[binds[i][p][0]][binds[i][p][1]];
|
|
823
|
+
for (let i = 0; i < count; i++) {
|
|
824
|
+
let key;
|
|
825
|
+
try {
|
|
826
|
+
key = matchKeys ? matchKeys[i] : keyOfItem(i, heldElement(i)); // matched by key: the match key names the item
|
|
827
|
+
} catch (error) {
|
|
828
|
+
problem = `item ${i}'s key failed: ${error?.message ?? error}`;
|
|
829
|
+
break;
|
|
830
|
+
}
|
|
831
|
+
if (key === undefined) problem = `item ${i} has no key`;
|
|
832
|
+
else if (seen.has(key)) problem = `items ${seen.get(key)} and ${i} have the same key ${showKey(key)}`;
|
|
833
|
+
if (problem) break;
|
|
834
|
+
seen.set(key, i);
|
|
835
|
+
keys[i] = key;
|
|
836
|
+
}
|
|
837
|
+
if (problem) {
|
|
838
|
+
eachMemos.delete(id);
|
|
839
|
+
return { keyed: false, note: `${problem}, so every item runs by position` };
|
|
840
|
+
}
|
|
841
|
+
const usesIndex = !names.includes("index") && /\bindex\b/.test(body);
|
|
842
|
+
const context = {
|
|
843
|
+
text: JSON.stringify([body, String(spec), sources, names, over, skippedSources, usesIndex, ...(match ? [match] : [])]),
|
|
844
|
+
inputs: sources.map((s, i) => (over.includes(i) || skippedSources.includes(s) ? null : fingerprintOf(values.get(s)))),
|
|
845
|
+
};
|
|
846
|
+
let memo = eachMemos.get(id);
|
|
847
|
+
// A failed-item retry: the checkpoint's completed results go back in the pane's kept ones, if what made
|
|
848
|
+
// them is still what this run has (the code, the key, the inputs). If not, nothing changes and the page says why.
|
|
849
|
+
const imported = eachImports.get(id);
|
|
850
|
+
eachImports.delete(id);
|
|
851
|
+
let retry;
|
|
852
|
+
if (imported) {
|
|
853
|
+
const refuse = (rejected) => ({ keyed: false, retry: { rejected } });
|
|
854
|
+
const { seed, edits } = imported;
|
|
855
|
+
if (matchKeys && Object.keys(edits).length) return refuse("a failed item's payload can't be edited when the items are matched by key (the edit could change which elements belong together)");
|
|
856
|
+
const live = memo && sameContext(memo.context, context);
|
|
857
|
+
if (!live) {
|
|
858
|
+
const was = { text: seed.context.text, inputs: seed.context.inputs.map((h) => (h === null ? null : { hash: h })) };
|
|
859
|
+
if (!sameContext(was, context)) return refuse(was.text !== context.text ? "the pane's code, key or inputs changed since that run" : "an input that isn't iterated changed since that run, and every item may depend on it");
|
|
860
|
+
memo = { context, entries: new Map() };
|
|
861
|
+
}
|
|
862
|
+
retry = { reused: 0, rerun: [], edited: [] };
|
|
863
|
+
const wanted = new Set();
|
|
864
|
+
for (const item of seed.items) {
|
|
865
|
+
if (item.state === "error" || !seen.has(item.key)) continue;
|
|
866
|
+
wanted.add(item.key);
|
|
867
|
+
// A result made from an edited payload (an earlier retry): the person accepted it for this item, so it counts as
|
|
868
|
+
// the item's result for what the input holds now (a later change to the item still runs it).
|
|
869
|
+
const accepted = item.edited ? itemFingerprint(sources, binds[seen.get(item.key)], skippedSources, usesIndex ? seen.get(item.key) : undefined) : undefined;
|
|
870
|
+
if (memo.entries.has(item.key)) {
|
|
871
|
+
if (accepted) memo.entries.get(item.key).fp = accepted;
|
|
872
|
+
continue; // still in this Worker
|
|
873
|
+
}
|
|
874
|
+
if (item.unsupported !== undefined || (item.state === "done" && item.value === undefined && item.skipped === undefined)) {
|
|
875
|
+
retry.rerun.push({ key: item.key, index: seen.get(item.key), why: item.unsupported ?? "its value wasn't kept" });
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
memo.entries.set(item.key, { fp: accepted ?? item.fp, value: item.skipped !== undefined ? skip(item.skipped === null ? undefined : item.skipped) : JSON.parse(item.value), item: undefined });
|
|
879
|
+
}
|
|
880
|
+
imported.wanted = wanted;
|
|
881
|
+
}
|
|
882
|
+
if (!memo || !sameContext(memo.context, context)) eachMemos.set(id, (memo = { context, entries: new Map() }));
|
|
883
|
+
for (const k of memo.entries.keys()) if (!seen.has(k)) memo.entries.delete(k); // removed keys drop their results
|
|
884
|
+
const run_ = { runId, results: new Array(count), keyed: true, keys, fps: new Array(count), memo, usesIndex };
|
|
885
|
+
// The failed items' edited payloads: each keeps its key, and runs with the edit instead of what the input holds.
|
|
886
|
+
const editedAt = new Map(); // item index -> the edited value
|
|
887
|
+
if (imported) {
|
|
888
|
+
for (const [k, text] of Object.entries(imported.edits)) {
|
|
889
|
+
const at = seen.get(k);
|
|
890
|
+
if (at === undefined) return { keyed: false, retry: { rejected: `the item ${showKey(k)} is no longer in the input, so its edit can't be used` } };
|
|
891
|
+
let value;
|
|
892
|
+
try {
|
|
893
|
+
value = JSON.parse(text);
|
|
894
|
+
} catch (error) {
|
|
895
|
+
return { keyed: false, retry: { rejected: `the edit of item ${showKey(k)} isn't JSON: ${error.message}` } };
|
|
896
|
+
}
|
|
897
|
+
// The payload is the item's element of the one iterated input, or an array of one element of each of several.
|
|
898
|
+
const parts = over.length === 1 ? [value] : value;
|
|
899
|
+
if (!Array.isArray(parts) || parts.length !== binds[at].length) return { keyed: false, retry: { rejected: `the edit of item ${showKey(k)} must be a JSON array with one element of each of the ${binds[at].length} iterated inputs` } };
|
|
900
|
+
let editedKey;
|
|
901
|
+
try {
|
|
902
|
+
editedKey = keyOfItem(at, (p) => parts[p]);
|
|
903
|
+
} catch {}
|
|
904
|
+
if (editedKey !== k) return { keyed: false, retry: { rejected: `the edit of item ${showKey(k)} changes its key, which names the item` } };
|
|
905
|
+
editedAt.set(at, parts);
|
|
906
|
+
}
|
|
907
|
+
run_.edits = editedAt;
|
|
908
|
+
}
|
|
909
|
+
eachRuns.set(id, run_);
|
|
910
|
+
// The keyed hint: one iterated list that keyed setters made from the one this pane last planned
|
|
911
|
+
// against. An item no keyed change touched since, and the same object its kept result was made from,
|
|
912
|
+
// is reused without being fingerprinted again.
|
|
913
|
+
const list = over.length === 1 && !usesIndex && !matchKeys && !skippedSources.includes(sources[over[0]]) ? values.get(sources[over[0]]) : undefined;
|
|
914
|
+
const touched = list ? keyedSince(memo.seen, list) : null;
|
|
915
|
+
let dirty = null;
|
|
916
|
+
if (touched) {
|
|
917
|
+
try {
|
|
918
|
+
dirty = new Set(touched.map((item) => keyText(read(item))));
|
|
919
|
+
} catch {
|
|
920
|
+
dirty = null; // a key expression that fails on an old item: fingerprint everything
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
memo.seen = Array.isArray(list) ? seqOf(list) : undefined;
|
|
924
|
+
const run = [];
|
|
925
|
+
const reused = [];
|
|
926
|
+
let hinted = 0;
|
|
927
|
+
for (let i = 0; i < count; i++) {
|
|
928
|
+
const element = list ? list[binds[i][0][1]] : undefined;
|
|
929
|
+
let kept = memo.entries.get(keys[i]);
|
|
930
|
+
if (editedAt.has(i)) {
|
|
931
|
+
run_.fps[i] = givenFingerprint(editedAt.get(i), usesIndex ? i : undefined);
|
|
932
|
+
retry.edited.push(keys[i]);
|
|
933
|
+
kept = undefined;
|
|
934
|
+
} else if (dirty && kept && kept.item !== undefined && kept.item === element && !dirty.has(keys[i])) {
|
|
935
|
+
run_.fps[i] = kept.fp;
|
|
936
|
+
hinted++;
|
|
937
|
+
} else {
|
|
938
|
+
const fp = itemFingerprint(sources, binds[i], skippedSources, usesIndex ? i : undefined);
|
|
939
|
+
run_.fps[i] = fp;
|
|
940
|
+
if (!fp || !kept || kept.fp !== fp) kept = undefined;
|
|
941
|
+
else if (list) kept.item = element; // an equal item: the next hint can trust this one by identity
|
|
942
|
+
}
|
|
943
|
+
if (kept) {
|
|
944
|
+
run_.results[i] = kept.value;
|
|
945
|
+
reused.push([i, isSkip(kept.value) ? { skipped: true, reason: skipReason(kept.value) } : { brief: brief(kept.value) }]);
|
|
946
|
+
if (retry) retry.reused++;
|
|
947
|
+
} else {
|
|
948
|
+
run.push(i);
|
|
949
|
+
// A completed item of the checkpoint that runs again: its input changed since (a failed one, or a new one, is expected to run).
|
|
950
|
+
if (retry && imported.wanted.has(keys[i]) && !retry.rerun.some((r) => r.key === keys[i])) retry.rerun.push({ key: keys[i], index: i, why: "what it is given changed since that run" });
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
if (retry) for (const r of retry.rerun) r.key = showKey(r.key);
|
|
954
|
+
if (retry) retry.edited = retry.edited.map(showKey);
|
|
955
|
+
return { keyed: true, run, reused, ...(retry ? { retry } : {}), ...(dirty ? { hinted } : {}), ...(usesIndex ? { note: "the code reads index, so a moved item runs again" } : {}) };
|
|
956
|
+
},
|
|
957
|
+
|
|
958
|
+
/**
|
|
959
|
+
* A failed-item checkpoint: what a keyed for-each pane's failed run
|
|
960
|
+
* can be resumed from. Called after the run failed, while its results are
|
|
961
|
+
* still here. For each item: a completed one's key, fingerprint and value
|
|
962
|
+
* (as JSON, or `unsupported` with the reason it can't be), a skip's reason,
|
|
963
|
+
* and a failed one's key and the payload it was given (what its element of
|
|
964
|
+
* each iterated input held). `failed`: the indexes of the failed items.
|
|
965
|
+
* Logical JSON state only: no closure or continuation is kept.
|
|
966
|
+
*/
|
|
967
|
+
eachExport(id, runId, { failed = [], maxBytes = 262144, sources = [], binds = [], skipped: skippedSources = [] } = {}) {
|
|
968
|
+
const run_ = eachRuns.get(id);
|
|
969
|
+
const memo = eachMemos.get(id);
|
|
970
|
+
if (!run_?.keyed || run_.runId !== runId || memo !== run_.memo) return { unavailable: "the run's results are no longer held (a newer run or a sandbox restart)" };
|
|
971
|
+
const bad = new Set(failed);
|
|
972
|
+
let budget = maxBytes;
|
|
973
|
+
const items = [];
|
|
974
|
+
for (let i = 0; i < run_.keys.length; i++) {
|
|
975
|
+
const key = run_.keys[i];
|
|
976
|
+
if (bad.has(i)) {
|
|
977
|
+
const given = binds[i]?.map(([input, element]) => (element < 0 || skippedSources.includes(sources[input]) ? undefined : values.get(sources[input])?.[element])) ?? [];
|
|
978
|
+
const json = checkpointJSON(given, Math.max(0, budget));
|
|
979
|
+
if (json.text !== undefined) budget -= json.text.length;
|
|
980
|
+
items.push({ key, index: i, state: "error", ...(json.text !== undefined ? { given: json.text } : { unsupported: json.why }) });
|
|
981
|
+
continue;
|
|
982
|
+
}
|
|
983
|
+
if (!(i in run_.results)) continue; // never started
|
|
984
|
+
const kept = memo.entries.get(key);
|
|
985
|
+
if (!kept) {
|
|
986
|
+
items.push({ key, index: i, state: "done", unsupported: "it isn't JSON-like, so it was never kept for reuse" });
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
if (isSkip(kept.value)) {
|
|
990
|
+
items.push({ key, index: i, state: "skipped", fp: kept.fp, skipped: skipReason(kept.value) ?? null });
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
const json = checkpointJSON(kept.value, Math.max(0, budget));
|
|
994
|
+
if (json.text !== undefined) budget -= json.text.length;
|
|
995
|
+
items.push({ key, index: i, state: "done", fp: kept.fp, ...(run_.edits?.has(i) ? { edited: true } : {}), ...(json.text !== undefined ? { value: json.text } : { unsupported: json.why }) });
|
|
996
|
+
}
|
|
997
|
+
const inputs = memo.context.inputs.map((fp) => (fp === null ? null : "hash" in fp ? fp.hash : "ref"));
|
|
998
|
+
return { items, context: { text: memo.context.text, inputs } };
|
|
999
|
+
},
|
|
1000
|
+
|
|
1001
|
+
/** A failed-item retry: the checkpoint (and the edited payloads, keyed by item key) the pane's next eachPlan resumes from. */
|
|
1002
|
+
eachImport(id, { seed, edits = {} }) {
|
|
1003
|
+
eachImports.set(id, { seed, edits });
|
|
1004
|
+
return true;
|
|
1005
|
+
},
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* For-each: run one item of an eval pane (its own evaluation, so the pane
|
|
1009
|
+
* timeout applies per item). Results are kept until eachFinish makes the
|
|
1010
|
+
* array the pane's value. Returns a one-line `brief` of the item's value,
|
|
1011
|
+
* or `{ skipped: true, reason }` for an item that returned skip(…): it is
|
|
1012
|
+
* left out of the array (for-each with skip is a filter-map).
|
|
1013
|
+
*/
|
|
1014
|
+
async execItem(id, runId, index, count, sources, names, bind, body, label, forwardingConsole, setterNames = [], skippedSources = []) {
|
|
1015
|
+
if (!(latest.get(id) > runId)) latest.set(id, runId);
|
|
1016
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
1017
|
+
if (liveKind(body)) throw new Error("a for-each pane can't be live: yield and emit work in a pane without for each");
|
|
1018
|
+
let run_ = eachRuns.get(id);
|
|
1019
|
+
if (!run_ || run_.runId !== runId) eachRuns.set(id, (run_ = { runId, results: new Array(count) }));
|
|
1020
|
+
// Keyed: the fingerprint of what this item is given now (run() binds the same values, before it awaits
|
|
1021
|
+
// anything), in case an input changed since eachPlan (a state setter): the result is kept with what made it.
|
|
1022
|
+
const edit = run_.edits?.has(index) ? { values: run_.edits.get(index) } : undefined; // a retry's edited payload: one element per iterated input
|
|
1023
|
+
const fp = run_.keyed && run_.fps[index] ? (edit ? givenFingerprint(edit.values, run_.usesIndex ? index : undefined) : itemFingerprint(sources, bind, skippedSources, run_.usesIndex ? index : undefined)) : null;
|
|
1024
|
+
// …and the item itself (one iterated input), which the keyed hint compares by identity next time.
|
|
1025
|
+
const item = fp && !edit && bind.length === 1 && bind[0][1] >= 0 && !skippedSources.includes(sources[bind[0][0]]) ? values.get(sources[bind[0][0]])?.[bind[0][1]] : undefined;
|
|
1026
|
+
const value = await run(id, sources, names, body, label, forwardingConsole, setterNames, { index, bind, edit }, skippedSources, { runId, withState: true });
|
|
1027
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
1028
|
+
run_.results[index] = value;
|
|
1029
|
+
// Kept for the next run, while the memo it was planned against is still the pane's.
|
|
1030
|
+
if (fp && eachMemos.get(id) === run_.memo) run_.memo.entries.set(run_.keys[index], { fp, value, item });
|
|
1031
|
+
if (isSkip(value)) return { skipped: true, reason: skipReason(value) };
|
|
1032
|
+
return { brief: brief(value) };
|
|
1033
|
+
},
|
|
1034
|
+
|
|
1035
|
+
/** For-each: the items' results (in item order) become the pane's value. `keyed`: the run was planned by eachPlan (its reused results are in it). */
|
|
1036
|
+
eachFinish(id, runId, count, view, keyed = false, { own = false, nest } = {}) {
|
|
1037
|
+
const run_ = eachRuns.get(id);
|
|
1038
|
+
if (latest.get(id) !== runId || (count && run_?.runId !== runId)) return { superseded: true };
|
|
1039
|
+
// Planned in a Worker that has restarted since: the reused results are gone with it.
|
|
1040
|
+
if (keyed && count && !run_.keyed) throw new Error("for each: the sandbox restarted during this run; run it again");
|
|
1041
|
+
eachRuns.delete(id);
|
|
1042
|
+
if (!run_?.keyed) eachMemos.delete(id); // run by position (no key, or a missing or duplicate one): nothing kept
|
|
1043
|
+
const results = Array.from({ length: count }, (_, i) => run_?.results[i]);
|
|
1044
|
+
const value = Array.isArray(nest) && nest.length > 1 ? nestResults(results, nest, isSkip) : results.filter((v) => !isSkip(v)); // a cross product grouped by its inputs (each.shape)
|
|
1045
|
+
values.set(id, value);
|
|
1046
|
+
return own ? { own: true } : present(id, value, view); // its own Worker: eachFinishOwn hands it back
|
|
1047
|
+
},
|
|
1048
|
+
|
|
1049
|
+
/** For-each in a pane's own Worker: eachFinish's array, handed back as runOwn hands a value back, once its items' setters' changes have landed. */
|
|
1050
|
+
async eachFinishOwn(id, runId, count, keyed = false, stateBytes = 0, nest = undefined) {
|
|
1051
|
+
await forwarded();
|
|
1052
|
+
const result = globalThis.__mallory.eachFinish(id, runId, count, "auto", keyed, { own: true, nest });
|
|
1053
|
+
if (result?.superseded) return wrapped({ result });
|
|
1054
|
+
return ownValue(id, stateBytes);
|
|
1055
|
+
},
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* Render an html pane's template (see templateBody in compile.js) against
|
|
1059
|
+
* its inputs and return the HTML string. Nothing is stored: the pane's value
|
|
1060
|
+
* is set afterwards, from what its frame shows (the form's object, or this HTML).
|
|
1061
|
+
*/
|
|
1062
|
+
async template(id, runId, sources, names, body, label, forwardingConsole) {
|
|
1063
|
+
newRun(id, runId);
|
|
1064
|
+
latest.set(id, runId);
|
|
1065
|
+
const value = await run(id, sources, names, body, label, forwardingConsole, [], undefined, [], { runId });
|
|
1066
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
1067
|
+
if (isSkip(value)) return skipped(id, value);
|
|
1068
|
+
// A files value among its inputs (the first) goes with the html: the frame mounts it, so the page's relative src, href
|
|
1069
|
+
// and url(...) load the folder's files (src/runtime/files-frame.js). A Map, so its bytes clone as they are (see wrapped).
|
|
1070
|
+
const folder = filesLib ? sources.map((s) => values.get(s)).find((v) => filesLib.isFiles(v)) : undefined;
|
|
1071
|
+
return folder ? wrapped({ html: part(value), folder }) : { html: part(value) };
|
|
1072
|
+
},
|
|
1073
|
+
|
|
1074
|
+
/**
|
|
1075
|
+
* A repeater (src/model/repeater.js): what names each item of its
|
|
1076
|
+
* list and what each item is, so the page can keep one instance per key.
|
|
1077
|
+
* `sources`/`names`: the repeater pane's inputs; `input`: the one to
|
|
1078
|
+
* iterate ("" the first array). Reads each item's key (`key`, as each.key
|
|
1079
|
+
* reads it; none: by position), a content hash of the item (null when it
|
|
1080
|
+
* isn't JSON-like: it always counts as changed) and, with `templateBy` (a
|
|
1081
|
+
* field or dotted path, never code), the item's template name. The keyed
|
|
1082
|
+
* hint: an item no keyed change touched since the last plan, and the
|
|
1083
|
+
* same object, keeps its last fingerprint without being hashed again.
|
|
1084
|
+
* A missing or duplicate key plans by position, with a note.
|
|
1085
|
+
* Returns `{ over, total, count, keyed, keys: (keyText | null)[], fps, templates?, note?, hinted? }`.
|
|
1086
|
+
*/
|
|
1087
|
+
repeatPlan(id, runId, { sources, names, input = "", key: spec = "", templateBy = "", max = 0, label }) {
|
|
1088
|
+
latest.set(id, runId);
|
|
1089
|
+
const missing = missingInputs(sources);
|
|
1090
|
+
if (missing.length) throw new Error(`waiting for ${missing.join(", ")}`);
|
|
1091
|
+
let over;
|
|
1092
|
+
if (input) {
|
|
1093
|
+
over = names.indexOf(input);
|
|
1094
|
+
if (over < 0) throw new Error(`for each: there is no input named "${input}"`);
|
|
1095
|
+
if (!Array.isArray(values.get(sources[over]))) throw new Error(`for each: input "${input}" isn't an array`);
|
|
1096
|
+
} else {
|
|
1097
|
+
over = sources.findIndex((s) => Array.isArray(values.get(s)));
|
|
1098
|
+
if (over < 0) throw new Error(names.length ? `for each: none of the inputs is an array (${names.join(", ")})` : "for each: connect an array input to repeat over");
|
|
1099
|
+
}
|
|
1100
|
+
const list = values.get(sources[over]);
|
|
1101
|
+
const total = list.length;
|
|
1102
|
+
const count = max > 0 ? Math.min(total, max) : total;
|
|
1103
|
+
let keys = new Array(count).fill(null);
|
|
1104
|
+
let note;
|
|
1105
|
+
let keyed = false;
|
|
1106
|
+
let read;
|
|
1107
|
+
if (spec) {
|
|
1108
|
+
read = keyReader(String(spec), label); // a key expression that doesn't compile is the pane's error
|
|
1109
|
+
const seen = new Map();
|
|
1110
|
+
let problem;
|
|
1111
|
+
for (let i = 0; i < count && !problem; i++) {
|
|
1112
|
+
let k;
|
|
1113
|
+
try {
|
|
1114
|
+
k = keyText(read(list[i], i));
|
|
1115
|
+
} catch (error) {
|
|
1116
|
+
problem = `item ${i}'s key failed: ${error?.message ?? error}`;
|
|
1117
|
+
break;
|
|
1118
|
+
}
|
|
1119
|
+
if (k === undefined) problem = `item ${i} has no key`;
|
|
1120
|
+
else if (seen.has(k)) problem = `items ${seen.get(k)} and ${i} have the same key ${showKey(k)}`;
|
|
1121
|
+
else {
|
|
1122
|
+
seen.set(k, i);
|
|
1123
|
+
keys[i] = k;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
if (problem) {
|
|
1127
|
+
keys = new Array(count).fill(null);
|
|
1128
|
+
note = `${problem}, so the instances follow positions`;
|
|
1129
|
+
} else keyed = true;
|
|
1130
|
+
}
|
|
1131
|
+
// Fingerprints, with the keyed hint for a keyed list (positions change meaning when items move).
|
|
1132
|
+
let memo = repeatMemos.get(id);
|
|
1133
|
+
if (!memo || memo.spec !== (keyed ? String(spec) : "")) repeatMemos.set(id, (memo = { spec: keyed ? String(spec) : "", entries: new Map() }));
|
|
1134
|
+
const touched = keyed ? keyedSince(memo.seen, list) : null;
|
|
1135
|
+
let dirty = null;
|
|
1136
|
+
if (touched) {
|
|
1137
|
+
try {
|
|
1138
|
+
dirty = new Set(touched.map((item) => keyText(read(item))));
|
|
1139
|
+
} catch {
|
|
1140
|
+
dirty = null; // a key expression that fails on an old item: hash everything
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
memo.seen = keyed ? seqOf(list) : undefined;
|
|
1144
|
+
const fps = new Array(count);
|
|
1145
|
+
const entries = new Map();
|
|
1146
|
+
let hinted = 0;
|
|
1147
|
+
for (let i = 0; i < count; i++) {
|
|
1148
|
+
const k = keyed ? keys[i] : `@${i}`;
|
|
1149
|
+
const kept = memo.entries.get(k);
|
|
1150
|
+
if (dirty && kept && kept.item === list[i] && !dirty.has(k)) {
|
|
1151
|
+
fps[i] = kept.fp;
|
|
1152
|
+
hinted++;
|
|
1153
|
+
} else fps[i] = contentHash(list[i]);
|
|
1154
|
+
entries.set(k, { fp: fps[i], item: list[i] });
|
|
1155
|
+
}
|
|
1156
|
+
memo.entries = entries; // removed keys go
|
|
1157
|
+
let templates;
|
|
1158
|
+
if (templateBy) {
|
|
1159
|
+
if (!KEY_PATH.test(String(templateBy))) throw new Error(`for each: templateBy is a field name or dotted path (got ${JSON.stringify(templateBy)})`);
|
|
1160
|
+
const path = String(templateBy).split(".");
|
|
1161
|
+
templates = list.slice(0, count).map((item) => {
|
|
1162
|
+
const v = path.reduce((at, step) => (at == null ? undefined : at[step]), item);
|
|
1163
|
+
return typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : null;
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
repeatLists.set(id, { source: sources[over], name: names[over], label: label || id });
|
|
1167
|
+
return { over, name: names[over], total, count, keyed, keys, fps, ...(templates ? { templates } : {}), ...(note ? { note } : {}), ...(dirty ? { hinted } : {}) };
|
|
1168
|
+
},
|
|
1169
|
+
|
|
1170
|
+
/**
|
|
1171
|
+
* A repeater instance's item port: store item `index` of list
|
|
1172
|
+
* `source` under `id`. With `key` (its keyText) and `spec`, the item is
|
|
1173
|
+
* found by its key when it isn't at `index` any more (the list changed
|
|
1174
|
+
* since the plan).
|
|
1175
|
+
*/
|
|
1176
|
+
pick(id, runId, source, index, key, spec, label, view) {
|
|
1177
|
+
latest.set(id, runId);
|
|
1178
|
+
if (!values.has(source)) throw new Error(`waiting for ${source}`);
|
|
1179
|
+
const list = values.get(source);
|
|
1180
|
+
if (!Array.isArray(list)) throw new Error("the list isn't an array any more");
|
|
1181
|
+
let i = index;
|
|
1182
|
+
if (key != null && spec) {
|
|
1183
|
+
const read = keyReader(String(spec), label);
|
|
1184
|
+
const at = (j) => {
|
|
1185
|
+
try {
|
|
1186
|
+
return keyText(read(list[j], j));
|
|
1187
|
+
} catch {
|
|
1188
|
+
return undefined;
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
if (at(i) !== key) i = list.findIndex((_, j) => at(j) === key);
|
|
1192
|
+
if (i < 0) throw new Error(`no item has the key ${showKey(key)} any more`);
|
|
1193
|
+
}
|
|
1194
|
+
if (!(i >= 0 && i < list.length)) throw new Error(`the list has no item ${index} any more`);
|
|
1195
|
+
values.set(id, list[i]);
|
|
1196
|
+
return present(id, list[i], view);
|
|
1197
|
+
},
|
|
1198
|
+
|
|
1199
|
+
/**
|
|
1200
|
+
* A repeater's value: its instances' values, in item order.
|
|
1201
|
+
* `items[i]` is `{ s: [source…], l?: [label…], k? }`: one source is the
|
|
1202
|
+
* instance's value; several make an object keyed by `l`. With `keyed`, the
|
|
1203
|
+
* value is an object keyed by each item's `k`.
|
|
1204
|
+
*/
|
|
1205
|
+
gather(id, runId, items, keyed, view) {
|
|
1206
|
+
latest.set(id, runId);
|
|
1207
|
+
const one = (it) => {
|
|
1208
|
+
if (!it.l) {
|
|
1209
|
+
if (!values.has(it.s[0])) throw new Error(`waiting for ${it.s[0]}`);
|
|
1210
|
+
return values.get(it.s[0]);
|
|
1211
|
+
}
|
|
1212
|
+
const out = {};
|
|
1213
|
+
it.s.forEach((s, j) => {
|
|
1214
|
+
if (values.has(s)) out[it.l[j]] = values.get(s);
|
|
1215
|
+
});
|
|
1216
|
+
return out;
|
|
1217
|
+
};
|
|
1218
|
+
let value;
|
|
1219
|
+
if (keyed) {
|
|
1220
|
+
value = {};
|
|
1221
|
+
for (const it of items) value[it.k] = one(it);
|
|
1222
|
+
} else value = items.map(one);
|
|
1223
|
+
values.set(id, value);
|
|
1224
|
+
const list = repeatLists.get(id);
|
|
1225
|
+
if (!keyed && list && items.every((it) => Number.isInteger(it.i))) repeatReads.set(id, { list, value, links: items.map((it) => it.i) });
|
|
1226
|
+
else repeatReads.delete(id);
|
|
1227
|
+
return present(id, value, view);
|
|
1228
|
+
},
|
|
1229
|
+
|
|
1230
|
+
/** Store a value computed on the page (text panes, input widgets). */
|
|
1231
|
+
set(id, runId, value, view) {
|
|
1232
|
+
latest.set(id, runId);
|
|
1233
|
+
values.set(id, value);
|
|
1234
|
+
return present(id, value, view);
|
|
1235
|
+
},
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* A media pane's "from URL": fetch it as the pane (through the canvas's
|
|
1239
|
+
* network policy, which can ask about the host and rerun the pane) and
|
|
1240
|
+
* store the media value.
|
|
1241
|
+
*/
|
|
1242
|
+
async mediaFromUrl(id, runId, url, meta, view) {
|
|
1243
|
+
latest.set(id, runId);
|
|
1244
|
+
if (!mediaLib) throw new Error("media isn't available in this sandbox");
|
|
1245
|
+
const res = await sandboxFetch(url, {}, id);
|
|
1246
|
+
if (!res.ok) throw new Error(`${url}: ${res.status} ${res.statusText}`.trim());
|
|
1247
|
+
const value = await mediaLib.fromBlob(await res.blob(), { ...meta, url });
|
|
1248
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
1249
|
+
values.set(id, value);
|
|
1250
|
+
return present(id, value, view);
|
|
1251
|
+
},
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* Run a state pane: evaluate its initial value the first time (or on
|
|
1255
|
+
* `reset`); afterwards keep whatever a setter last stored. An initial value
|
|
1256
|
+
* of skip(…) skips the pane until a setter stores a value.
|
|
1257
|
+
* A persisted state pane (src/model/persist-state.js): `restore` is the
|
|
1258
|
+
* stored JSON text, which replaces the value instead (unless `reset`), and
|
|
1259
|
+
* `persist` asks for the value as JSON text to store: `persist: { ok, text }`
|
|
1260
|
+
* or `{ ok: false, reason }` in the result. Media values in it:
|
|
1261
|
+
* `persist: "blobs"` (the page) keeps them as `{ $media, ref }` placeholders
|
|
1262
|
+
* with their Blobs beside the text (`persist: { ok, text, media, blobs }`),
|
|
1263
|
+
* and `restoreMedia` holds the Blobs to put back; any other `persist`
|
|
1264
|
+
* (a headless state file) writes their bytes inline as base64.
|
|
1265
|
+
*/
|
|
1266
|
+
async state(id, runId, body, reset, label, restore, persist, forwardingConsole, restoreMedia) {
|
|
1267
|
+
latest.set(id, runId);
|
|
1268
|
+
let missingMedia = 0;
|
|
1269
|
+
if (!reset && typeof restore === "string") {
|
|
1270
|
+
let value = JSON.parse(restore);
|
|
1271
|
+
if (exporter?.reviveStored) ({ value, missing: missingMedia } = exporter.reviveStored(value, persist === "blobs" ? { blobs: restoreMedia ?? {} } : { inline: true }));
|
|
1272
|
+
values.set(id, value);
|
|
1273
|
+
} else if (reset || !values.has(id)) {
|
|
1274
|
+
const params = forwardingConsole ? ["skip", "console"] : ["skip"];
|
|
1275
|
+
const fn = scoped(["log"], { log: paneLog(id, forwardingConsole) }, params, body, label || id);
|
|
1276
|
+
const done = codeRuns(id); // timers started while its code runs count against it
|
|
1277
|
+
nameCode(id, label || id);
|
|
1278
|
+
let value;
|
|
1279
|
+
try {
|
|
1280
|
+
value = await startsCode(id, () => fn(skip, forwardingConsole));
|
|
1281
|
+
} finally {
|
|
1282
|
+
done();
|
|
1283
|
+
}
|
|
1284
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
1285
|
+
if (isSkip(value)) return skipped(id, value);
|
|
1286
|
+
values.set(id, value);
|
|
1287
|
+
}
|
|
1288
|
+
const out = present(id, values.get(id), "auto");
|
|
1289
|
+
if (missingMedia) out.missingMedia = missingMedia;
|
|
1290
|
+
if (persist) {
|
|
1291
|
+
if (!exporter?.storableJSON) out.persist = { ok: false, reason: "keeping values isn't available in this sandbox" };
|
|
1292
|
+
else {
|
|
1293
|
+
const saved = exporter.storableJSON(values.get(id), { media: true });
|
|
1294
|
+
out.persist = saved.ok && saved.media && persist !== "blobs" ? await exporter.inlineMedia(saved) : saved;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
return out;
|
|
1298
|
+
},
|
|
1299
|
+
|
|
1300
|
+
/** A state pane's current value as the store keeps it (`state`'s `persist` result), without running anything (#801). */
|
|
1301
|
+
async persistState(id, persist) {
|
|
1302
|
+
if (!values.has(id)) return { ok: false, reason: "the pane has no value yet" };
|
|
1303
|
+
if (!exporter?.storableJSON) return { ok: false, reason: "keeping values isn't available in this sandbox" };
|
|
1304
|
+
const saved = exporter.storableJSON(values.get(id), { media: true });
|
|
1305
|
+
return saved.ok && saved.media && persist !== "blobs" ? await exporter.inlineMedia(saved) : saved;
|
|
1306
|
+
},
|
|
1307
|
+
|
|
1308
|
+
/** Replace a state pane's value from the page (a DOM pane's setter). */
|
|
1309
|
+
setState(id, value) {
|
|
1310
|
+
setterFor(id)(value);
|
|
1311
|
+
return true;
|
|
1312
|
+
},
|
|
1313
|
+
|
|
1314
|
+
/**
|
|
1315
|
+
* A keyed change to a state pane's list from the page: a frame's
|
|
1316
|
+
* setTodos.update(…), an agent's mallory_set_state with `op`. `request` is
|
|
1317
|
+
* applyKeyed's (an update from a frame carries the new `item`), `spec` the
|
|
1318
|
+
* state pane's key. Returns `{ change }`, or `{}` when nothing changed.
|
|
1319
|
+
*/
|
|
1320
|
+
changeState(id, request, spec, label) {
|
|
1321
|
+
if (label) setterLabels.set(id, label);
|
|
1322
|
+
if (spec !== undefined) stateKeys.set(id, spec);
|
|
1323
|
+
const { change } = changeState(id, request, spec);
|
|
1324
|
+
return change ? { change } : {};
|
|
1325
|
+
},
|
|
1326
|
+
|
|
1327
|
+
/** Keyed hints on or off (on by default): off, keyed for-each readers fingerprint every item (for measuring). */
|
|
1328
|
+
setKeyedHints(on) {
|
|
1329
|
+
keyedHints = Boolean(on);
|
|
1330
|
+
return keyedHints;
|
|
1331
|
+
},
|
|
1332
|
+
|
|
1333
|
+
/**
|
|
1334
|
+
* A select pane's run: join the rows of `source` (an array) with the
|
|
1335
|
+
* keys the page holds (`picked`, keyTexts) and store the selection value
|
|
1336
|
+
* (docs/guide/canvas-basics.md, "Selecting rows"). The reply is the value's preview plus
|
|
1337
|
+
* `selection`, what the pane draws: a table of the first rows (with each
|
|
1338
|
+
* row's key text and flag), what the selection holds after this data
|
|
1339
|
+
* (`held`), and the problems it found. Throws for a source that isn't an
|
|
1340
|
+
* array of rows.
|
|
1341
|
+
*/
|
|
1342
|
+
selectRun(id, runId, source, spec, picked, options = {}) {
|
|
1343
|
+
latest.set(id, runId);
|
|
1344
|
+
if (!values.has(source)) throw new Error("waiting for the rows to select from");
|
|
1345
|
+
const rows = values.get(source);
|
|
1346
|
+
const limit = SELECT_LIMIT;
|
|
1347
|
+
// A selection from outside (the `select` input), applied once per new version of it: a refused one is said, never applied.
|
|
1348
|
+
let outside;
|
|
1349
|
+
if (options.outside !== undefined && values.has(options.outside)) {
|
|
1350
|
+
const got = outsideKeys(values.get(options.outside), options.dataset ?? null);
|
|
1351
|
+
if (got.refused) outside = { applied: false, refused: got.refused };
|
|
1352
|
+
else if (options.applyOutside) (picked = got.texts), (outside = { applied: true, keys: got.texts });
|
|
1353
|
+
else outside = { applied: false };
|
|
1354
|
+
}
|
|
1355
|
+
const out = selectRows(rows, spec, picked, { missing: options.missing, limit });
|
|
1356
|
+
const value = {
|
|
1357
|
+
dataset: options.dataset ?? null,
|
|
1358
|
+
revision: options.revision ?? null,
|
|
1359
|
+
key: stateKeyOf(spec),
|
|
1360
|
+
mode: options.mode ?? "multiple",
|
|
1361
|
+
keys: out.keys,
|
|
1362
|
+
count: out.keys.length,
|
|
1363
|
+
selected: out.selected,
|
|
1364
|
+
complement: out.complement,
|
|
1365
|
+
dropped: out.dropped.map(showKey),
|
|
1366
|
+
problems: { duplicate: out.problems.duplicate, unkeyed: out.problems.unkeyed },
|
|
1367
|
+
};
|
|
1368
|
+
values.set(id, value);
|
|
1369
|
+
const reply = present(id, value, "inspect");
|
|
1370
|
+
// `reuse`: the page holds this table, its flags and its map for these very rows, so none of them is built or sent again.
|
|
1371
|
+
const shown = options.reuse ? undefined : toTable(rows.slice(0, limit), { maxRows: limit });
|
|
1372
|
+
reply.selection = {
|
|
1373
|
+
...(options.reuse ? {} : { table: shown ? { columns: shown.columns, rows: shown.rows } : null, flags: out.flags }),
|
|
1374
|
+
total: rows.length,
|
|
1375
|
+
gone: out.dropped,
|
|
1376
|
+
kept: options.missing === "keep" ? out.absent.length : 0,
|
|
1377
|
+
problems: { duplicate: out.problems.duplicate.length, unkeyed: out.problems.unkeyed },
|
|
1378
|
+
// The picked rows' keys as they are, only when a reader of the pane's `selection` event wants them.
|
|
1379
|
+
...(options.keys ? { keys: out.keys } : {}),
|
|
1380
|
+
...(outside ? { outside } : {}),
|
|
1381
|
+
// The map view: the first rows' geometry, bounded, drawn by the page.
|
|
1382
|
+
...(options.map && !options.reuse ? { geo: table?.geo ? table.geo.drawable(rows, { geometry: options.map.geometry, limit: SELECT_MAP_LIMIT }) : { problem: "the table helper isn't available in this runtime" } } : {}),
|
|
1383
|
+
};
|
|
1384
|
+
return reply;
|
|
1385
|
+
},
|
|
1386
|
+
|
|
1387
|
+
/** A row of an interactive table was clicked. */
|
|
1388
|
+
async rowClick(id, index) {
|
|
1389
|
+
const value = values.get(id);
|
|
1390
|
+
if (!isInteractiveTable(value)) return false;
|
|
1391
|
+
const rows = Array.isArray(value.data) ? value.data : Object.values(value.data);
|
|
1392
|
+
await value.onRowClick(rows[index], index);
|
|
1393
|
+
return true;
|
|
1394
|
+
},
|
|
1395
|
+
|
|
1396
|
+
/**
|
|
1397
|
+
* Every row of one profile problem in pane `id`'s current value: the on-demand full-table check behind the profile view's
|
|
1398
|
+
* "Find every row" (the profile itself keeps a few examples). Read in slices like the profile, with the pane's own profile
|
|
1399
|
+
* settings except that no sample bound applies; a newer run of the pane stops it. Resolves to `{ column, kind, rows, count,
|
|
1400
|
+
* truncated, complete, rowCount, selectable }` (`selectable`: the value is the table itself, so a position is a row of it), or `{ unavailable }`.
|
|
1401
|
+
*/
|
|
1402
|
+
async findProfileRows(id, column, kind, limit) {
|
|
1403
|
+
const value = values.get(id);
|
|
1404
|
+
const rows = rowsOfValue(value);
|
|
1405
|
+
if (!rows) return NOT_A_TABLE;
|
|
1406
|
+
if (!table?.async?.profile) return { unavailable: "this sandbox has no table helper" };
|
|
1407
|
+
profiling.get(id)?.abort();
|
|
1408
|
+
const controller = new AbortController();
|
|
1409
|
+
profiling.set(id, controller);
|
|
1410
|
+
try {
|
|
1411
|
+
const { profile } = await table.async.profile(rows, { ...profileOptionsOf(id), timeMs: FIND_BUDGET_MS, find: { column, kind, limit, every: true }, signal: controller.signal });
|
|
1412
|
+
return { ...profile.found, rowCount: profile.rowCount, selectable: Array.isArray(value) };
|
|
1413
|
+
} catch (error) {
|
|
1414
|
+
return { unavailable: error?.code === "aborted" ? "the check was stopped (the pane ran again or was removed)" : error?.message ?? String(error) };
|
|
1415
|
+
} finally {
|
|
1416
|
+
if (profiling.get(id) === controller) profiling.delete(id);
|
|
1417
|
+
}
|
|
1418
|
+
},
|
|
1419
|
+
|
|
1420
|
+
/** Import a module by URL and store its namespace (or default export). */
|
|
1421
|
+
async importModule(id, runId, url, useDefault, view) {
|
|
1422
|
+
latest.set(id, runId);
|
|
1423
|
+
const mod = await import(url);
|
|
1424
|
+
if (latest.get(id) !== runId) return { superseded: true };
|
|
1425
|
+
const value = useDefault && "default" in mod ? mod.default : mod;
|
|
1426
|
+
values.set(id, value);
|
|
1427
|
+
return present(id, value, view);
|
|
1428
|
+
},
|
|
1429
|
+
|
|
1430
|
+
/** Lazy expansion of a preview node. */
|
|
1431
|
+
expand(handle) {
|
|
1432
|
+
return inspector.expand(handle);
|
|
1433
|
+
},
|
|
1434
|
+
|
|
1435
|
+
/** Structured-clone copies of input values, for a DOM pane in another realm. */
|
|
1436
|
+
clone(sources) {
|
|
1437
|
+
const out = [];
|
|
1438
|
+
for (const s of sources) {
|
|
1439
|
+
if (!values.has(s)) throw new Error(`waiting for ${s}`);
|
|
1440
|
+
try {
|
|
1441
|
+
out.push(structuredClone(values.get(s)));
|
|
1442
|
+
} catch (error) {
|
|
1443
|
+
// A value nested thousands of levels deep overflows the stack of the copy: that is not a function or a class instance.
|
|
1444
|
+
if (error instanceof RangeError) throw new Error(`input "${s}" is nested too deeply to be sent to a DOM pane`);
|
|
1445
|
+
throw new Error(`input "${s}" can't be sent to a DOM pane (functions, modules and class instances stay in the main sandbox)`);
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
return wrapped({ values: out }); // a BigInt or a cycle in one would otherwise turn it into text (see wrapped)
|
|
1449
|
+
},
|
|
1450
|
+
|
|
1451
|
+
/** The pane was skipped (by its own run or an input's): drop its value, unless a newer run already started. */
|
|
1452
|
+
clear(id, runId) {
|
|
1453
|
+
if ((latest.get(id) ?? -Infinity) > runId) return;
|
|
1454
|
+
const live = liveRuns.get(id);
|
|
1455
|
+
// Skipped by its inputs: the run before goes (one that skipped itself keeps its own), a live one too.
|
|
1456
|
+
if (live && live.runId < runId) endLiveThenRetire(id, runId);
|
|
1457
|
+
else retire(id, runId);
|
|
1458
|
+
latest.set(id, runId);
|
|
1459
|
+
values.delete(id);
|
|
1460
|
+
fingerprints.delete(id);
|
|
1461
|
+
inspector.release(id);
|
|
1462
|
+
if (!liveRuns.has(id)) releaseAI(id); // a live run that yielded skip(…) goes on
|
|
1463
|
+
agentChats.delete(id);
|
|
1464
|
+
},
|
|
1465
|
+
|
|
1466
|
+
/**
|
|
1467
|
+
* The equality cut-off: is the value run `runId` stored the same as the one
|
|
1468
|
+
* stored by run `base` (the run whose value the readers last saw)? Records
|
|
1469
|
+
* this run's fingerprint either way.
|
|
1470
|
+
*/
|
|
1471
|
+
compare(id, runId, base) {
|
|
1472
|
+
return cutoffAnswer(id, runId, base);
|
|
1473
|
+
},
|
|
1474
|
+
|
|
1475
|
+
/**
|
|
1476
|
+
* What the page wants back with a pane's run, in the same reply:
|
|
1477
|
+
* the page runtime wraps the call that stores the run's value in this
|
|
1478
|
+
* (src/runtime/runtime.js withRun). `cutoff`: the equality cut-off's answer
|
|
1479
|
+
* against run `base`, as compare() gives it; `json`: the run log's full
|
|
1480
|
+
* value (`{ maxBytes, maxPreviewEntries }`). They go on the result as
|
|
1481
|
+
* `cutoff: { runId, unchanged | superseded }` and `captured: { runId, text |
|
|
1482
|
+
* tooBig | error }`; the canvas takes them off before anything else sees it.
|
|
1483
|
+
* A skip, a live run or a superseded one gets neither.
|
|
1484
|
+
*
|
|
1485
|
+
* `json.restoreBytes`: the page keeps the value to put back after a
|
|
1486
|
+
* restart, when it comes back exactly as it was from JSON (storableJSON, as
|
|
1487
|
+
* persisted state panes are kept) in at most that many characters, and its
|
|
1488
|
+
* run left nothing behind here that a restart would lose (onCleanup, a live
|
|
1489
|
+
* run, event outputs; `effects`: a pane's own Worker says its run did).
|
|
1490
|
+
* Then `captured` is `{ runId, text, restore: true }` (compact JSON the run
|
|
1491
|
+
* log reads too); `json.only: "restore"`: nothing else is wanted.
|
|
1492
|
+
*/
|
|
1493
|
+
finish(id, runId, result, { cutoff = false, base, json, effects = false, own = false, state } = {}) {
|
|
1494
|
+
if (!result || typeof result !== "object" || result.superseded || result.skipped || result.live) return result;
|
|
1495
|
+
if (cutoff) result.cutoff = { runId, ...cutoffAnswer(id, runId, base) };
|
|
1496
|
+
if (json && latest.get(id) === runId && values.has(id)) {
|
|
1497
|
+
const preview = result.preview;
|
|
1498
|
+
// Its `state`: kept as JSON with the value, or (when it can't be) the value isn't kept either. A pane's own Worker sent its own (`state`).
|
|
1499
|
+
const kept_ = json.restoreBytes ? (own ? (typeof state === "string" ? { text: state } : { none: true }) : stateJSON(id, json.restoreBytes)) : { none: true };
|
|
1500
|
+
if (kept_.text !== undefined) result.keptState = { runId, text: kept_.text };
|
|
1501
|
+
else if (json.restoreBytes) result.keptState = { runId, none: true };
|
|
1502
|
+
const small = !(json.maxPreviewEntries && typeof preview?.size === "number" && preview.size > json.maxPreviewEntries) && !(preview?.type === "string" && preview.size > json.restoreBytes);
|
|
1503
|
+
const kept = json.restoreBytes && small && exporter?.storableJSON && !effects && !kept_.lost && !leftBehind(id) ? exporter.storableJSON(values.get(id), { maxLength: json.restoreBytes }) : null;
|
|
1504
|
+
if (kept?.ok) result.captured = { runId, text: kept.text, restore: true };
|
|
1505
|
+
else if (json.only !== "restore") result.captured = { runId, ...runValueJSON(id, preview, json) };
|
|
1506
|
+
}
|
|
1507
|
+
return result;
|
|
1508
|
+
},
|
|
1509
|
+
|
|
1510
|
+
// ── events and wire operators ──
|
|
1511
|
+
|
|
1512
|
+
/** Drop event `key` from node `node`'s ring (the person removed the take it carried). */
|
|
1513
|
+
discardEvent(node, key) {
|
|
1514
|
+
return discardEvent(node, key);
|
|
1515
|
+
},
|
|
1516
|
+
|
|
1517
|
+
/** Store an event the page made (a tick, a click, a request) under `key` in node `node`'s ring. Returns its preview. */
|
|
1518
|
+
storeEvent(node, key, name, payload, at, source, keep, batch) {
|
|
1519
|
+
latest.set(node, (latest.get(node) ?? 0) + 1);
|
|
1520
|
+
return keepEvent(node, key, Object.freeze({ name, payload, at, source, ...(batch ? { batch: Object.freeze({ key: batch }) } : {}) }), keep);
|
|
1521
|
+
},
|
|
1522
|
+
|
|
1523
|
+
/**
|
|
1524
|
+
* A repeater's item event: `{ key, name, payload, …fields }` under
|
|
1525
|
+
* `key` in node `node`'s ring. The payload is Worker key `from`'s value (an
|
|
1526
|
+
* event pane code sent) or `payload` (one the page made); `value`
|
|
1527
|
+
* ({ s: keys, l?: names }) attaches the instance's value when it has one.
|
|
1528
|
+
*/
|
|
1529
|
+
storeItemEvent(node, key, name, fields, from, payload, value, at, source, keep, batch) {
|
|
1530
|
+
latest.set(node, (latest.get(node) ?? 0) + 1);
|
|
1531
|
+
const { key: itemKey, name: itemName, ...rest } = fields ?? {};
|
|
1532
|
+
const body = { key: itemKey, name: itemName, payload: from ? values.get(from) : payload, ...rest };
|
|
1533
|
+
if (value?.s?.length && value.s.every((k) => values.has(k))) body.value = value.l ? Object.fromEntries(value.l.map((l, i) => [l, values.get(value.s[i])])) : values.get(value.s[0]);
|
|
1534
|
+
return keepEvent(node, key, Object.freeze({ name, payload: Object.freeze(body), at, source, ...(batch ? { batch: Object.freeze({ key: batch }) } : {}) }), keep);
|
|
1535
|
+
},
|
|
1536
|
+
|
|
1537
|
+
/**
|
|
1538
|
+
* An event on a channel for a receiver's event output `node`, under
|
|
1539
|
+
* `key`: { name, payload, at, source, channel, scope }. The payload is Worker
|
|
1540
|
+
* key `from`'s value (pane code's send()) or `payload` (a send from the page).
|
|
1541
|
+
*/
|
|
1542
|
+
storeChannelEvent(node, key, name, channel, scope, from, payload, at, source, keep) {
|
|
1543
|
+
latest.set(node, (latest.get(node) ?? 0) + 1);
|
|
1544
|
+
return keepEvent(node, key, Object.freeze({ name, payload: from ? values.get(from) : payload, at, source, channel, scope }), keep);
|
|
1545
|
+
},
|
|
1546
|
+
|
|
1547
|
+
/** A paced channel send's answer, once the page sent it or dropped it: settles pane `id`'s `send(…, { ack: true })` promise for `key`. */
|
|
1548
|
+
settleSendAck(id, key, answer) {
|
|
1549
|
+
const box = eventOutbox.get(id);
|
|
1550
|
+
if (box) settleAck(box, key, answer);
|
|
1551
|
+
return true;
|
|
1552
|
+
},
|
|
1553
|
+
|
|
1554
|
+
/**
|
|
1555
|
+
* Push what crossed wire `wire` (Worker keys: values, or events for an event
|
|
1556
|
+
* wire) through its operators `ops` (one stage of them, the first at `at`).
|
|
1557
|
+
* Returns the keys of what came out, in order (it waits in wireItems).
|
|
1558
|
+
*/
|
|
1559
|
+
wirePush(wire, stage, ops, at, keys, kind, batch) {
|
|
1560
|
+
const st = wireStage(wire, stage, ops, at, kind, batch, true);
|
|
1561
|
+
const out = [];
|
|
1562
|
+
for (const key of keys) {
|
|
1563
|
+
let item;
|
|
1564
|
+
if (wireItems.has(key)) {
|
|
1565
|
+
item = wireItems.get(key);
|
|
1566
|
+
wireItems.delete(key);
|
|
1567
|
+
} else if (kind === "event") {
|
|
1568
|
+
if (!eventStore.has(key)) continue; // gone (a full ring, or a restart): nothing to push
|
|
1569
|
+
item = eventStore.get(key);
|
|
1570
|
+
} else {
|
|
1571
|
+
if (!values.has(key)) continue;
|
|
1572
|
+
item = values.get(key);
|
|
1573
|
+
}
|
|
1574
|
+
for (const next of st.push.step(item)) {
|
|
1575
|
+
const k = `${wire}@${++wireSeq}`;
|
|
1576
|
+
wireItems.set(k, next);
|
|
1577
|
+
out.push(k);
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
return out;
|
|
1581
|
+
},
|
|
1582
|
+
|
|
1583
|
+
/**
|
|
1584
|
+
* A finite batch ends on wire `wire`, at one stage of its operators: what the stage still holds for
|
|
1585
|
+
* batch `batch` comes out (`mode` "end"), comes out marked partial with `reason` ("partial": an event's
|
|
1586
|
+
* `batch.partial`), or goes ("discard"). The batch's state in this stage is gone afterwards.
|
|
1587
|
+
* Returns the keys of what came out, in order.
|
|
1588
|
+
*/
|
|
1589
|
+
wireComplete(wire, stage, kind, batch, mode, reason) {
|
|
1590
|
+
const stages = wireStates.get(wire);
|
|
1591
|
+
const slot = stageSlot(stage, batch);
|
|
1592
|
+
const st = stages?.get(slot);
|
|
1593
|
+
if (!st) return [];
|
|
1594
|
+
stages.delete(slot);
|
|
1595
|
+
if (mode === "discard") return [];
|
|
1596
|
+
const out = [];
|
|
1597
|
+
for (let next of st.push.complete()) {
|
|
1598
|
+
if (mode === "partial" && kind === "event") next = markPartial(next, batch, reason);
|
|
1599
|
+
const k = `${wire}@${++wireSeq}`;
|
|
1600
|
+
wireItems.set(k, next);
|
|
1601
|
+
out.push(k);
|
|
1602
|
+
}
|
|
1603
|
+
return out;
|
|
1604
|
+
},
|
|
1605
|
+
|
|
1606
|
+
/**
|
|
1607
|
+
* Push what crossed wire `wire` (Worker keys) into one window stage `op` (batch `batch`, or the wire's own state) at
|
|
1608
|
+
* time `now` (the page's clock). Returns `{ keys, bounds, held, since, next }`: the windows that closed (their keys, in
|
|
1609
|
+
* order, with where each opened and closed, how many it held and why), how many values the stage holds now and since when,
|
|
1610
|
+
* and when the page should look again (`next`, or null).
|
|
1611
|
+
*/
|
|
1612
|
+
wireWindow(wire, stage, op, at, keys, kind, batch, now) {
|
|
1613
|
+
const st = wireStage(wire, stage, [op], at, kind, batch, true);
|
|
1614
|
+
const out = [];
|
|
1615
|
+
for (const key of keys) {
|
|
1616
|
+
let item;
|
|
1617
|
+
if (wireItems.has(key)) {
|
|
1618
|
+
item = wireItems.get(key);
|
|
1619
|
+
wireItems.delete(key);
|
|
1620
|
+
} else if (kind === "event") {
|
|
1621
|
+
if (!eventStore.has(key)) continue; // gone (a full ring, or a restart)
|
|
1622
|
+
item = eventStore.get(key);
|
|
1623
|
+
} else {
|
|
1624
|
+
if (!values.has(key)) continue;
|
|
1625
|
+
item = values.get(key);
|
|
1626
|
+
}
|
|
1627
|
+
out.push(...st.push.add(item, now));
|
|
1628
|
+
}
|
|
1629
|
+
return windowResult(wire, st, out);
|
|
1630
|
+
},
|
|
1631
|
+
|
|
1632
|
+
/** Time has passed on wire `wire`'s window stage: the windows whose deadline came close, as wireWindow returns them. */
|
|
1633
|
+
wireWindowTick(wire, stage, op, at, kind, batch, now) {
|
|
1634
|
+
const st = wireStage(wire, stage, [op], at, kind, batch, false);
|
|
1635
|
+
return st ? windowResult(wire, st, st.push.tick(now)) : { keys: [], bounds: [], held: 0, since: null, next: null };
|
|
1636
|
+
},
|
|
1637
|
+
|
|
1638
|
+
/**
|
|
1639
|
+
* A finite batch ends on a window stage: the open window goes (`mode` "end"), or goes marked partial ("partial", with
|
|
1640
|
+
* `reason`, an event's `batch.partial`); the batch's state is gone afterwards. Returns `{ keys, bounds }`.
|
|
1641
|
+
*/
|
|
1642
|
+
wireWindowEnd(wire, stage, kind, batch, mode, reason, now) {
|
|
1643
|
+
const stages = wireStates.get(wire);
|
|
1644
|
+
const slot = stageSlot(stage, batch);
|
|
1645
|
+
const st = stages?.get(slot);
|
|
1646
|
+
if (!st) return { keys: [], bounds: [] };
|
|
1647
|
+
stages.delete(slot);
|
|
1648
|
+
const out = [];
|
|
1649
|
+
for (const emitted of st.push.complete(now)) {
|
|
1650
|
+
const item = mode === "partial" && kind === "event" ? markPartial(emitted.item, batch, reason) : emitted.item;
|
|
1651
|
+
out.push({ item, bound: emitted.bound });
|
|
1652
|
+
}
|
|
1653
|
+
const { keys, bounds } = windowResult(wire, st, out);
|
|
1654
|
+
return { keys, bounds };
|
|
1655
|
+
},
|
|
1656
|
+
|
|
1657
|
+
/** What came out of wire `wire`'s operators (`key`) becomes its value (an event wire: its next event). Returns its preview. */
|
|
1658
|
+
wireTake(wire, key, kind, keep, view, runId) {
|
|
1659
|
+
let item;
|
|
1660
|
+
if (wireItems.has(key)) {
|
|
1661
|
+
item = wireItems.get(key);
|
|
1662
|
+
wireItems.delete(key);
|
|
1663
|
+
} else if (kind === "event" && eventStore.has(key)) {
|
|
1664
|
+
item = eventStore.get(key); // straight from its source (only a debounce or throttle on the wire)
|
|
1665
|
+
key = `${wire}@${++wireSeq}`;
|
|
1666
|
+
} else if (kind !== "event" && values.has(key)) {
|
|
1667
|
+
item = values.get(key);
|
|
1668
|
+
} else throw new Error("what came through this wire is gone (the sandbox restarted?)");
|
|
1669
|
+
latest.set(wire, runId ?? (latest.get(wire) ?? 0) + 1); // the page's run of the wire node, when it says (its reply can carry the value to put back)
|
|
1670
|
+
if (kind === "event") return { ...keepEvent(wire, key, item, keep), key };
|
|
1671
|
+
values.set(wire, item);
|
|
1672
|
+
return present(wire, item, view);
|
|
1673
|
+
},
|
|
1674
|
+
|
|
1675
|
+
/** How big each of these events that came out of a wire's operators is (approximately, as the queues count it; 0 for one that is gone). */
|
|
1676
|
+
wireSizes(keys) {
|
|
1677
|
+
return (keys ?? []).map((key) => {
|
|
1678
|
+
const item = wireItems.get(key) ?? eventStore.get(key);
|
|
1679
|
+
return item && typeof item === "object" && "payload" in item ? approxBytes(item.payload) : 0;
|
|
1680
|
+
});
|
|
1681
|
+
},
|
|
1682
|
+
|
|
1683
|
+
/** A debounce or throttle on the page let these go: drop them here too. */
|
|
1684
|
+
wireDrop(keys) {
|
|
1685
|
+
for (const key of keys ?? []) wireItems.delete(key);
|
|
1686
|
+
return true;
|
|
1687
|
+
},
|
|
1688
|
+
|
|
1689
|
+
/** A wire's operators start again (changed, or gone): their state, and what waits from them. */
|
|
1690
|
+
wireReset(wire) {
|
|
1691
|
+
wireStates.delete(wire);
|
|
1692
|
+
for (const key of [...wireItems.keys()]) if (key.startsWith(`${wire}@`)) wireItems.delete(key);
|
|
1693
|
+
return true;
|
|
1694
|
+
},
|
|
1695
|
+
|
|
1696
|
+
forget(id) {
|
|
1697
|
+
lastReads.delete(id);
|
|
1698
|
+
repeatLists.delete(id);
|
|
1699
|
+
repeatReads.delete(id);
|
|
1700
|
+
// Events and wires: an event output's ring, a wire's operators, a pane's outbox.
|
|
1701
|
+
dropRing(id);
|
|
1702
|
+
dropChannelRing(id); // what it sent on channels
|
|
1703
|
+
wireStates.delete(id);
|
|
1704
|
+
for (const key of [...wireItems.keys()]) if (key.startsWith(`${id}@`)) wireItems.delete(key);
|
|
1705
|
+
eventOutputs.delete(id);
|
|
1706
|
+
const box = eventOutbox.get(id);
|
|
1707
|
+
eventOutbox.delete(id);
|
|
1708
|
+
if (box) {
|
|
1709
|
+
const gone = box.list.splice(0);
|
|
1710
|
+
unanswered(box, gone, "the pane went before the event was delivered");
|
|
1711
|
+
for (const key of [...(box.acks?.keys() ?? [])]) settleAck(box, key, { accepted: false, reason: "the pane went before the event was answered", unanswered: true });
|
|
1712
|
+
handed(box, gone.length); // what waited here goes nowhere now (a batch on its way still lands)
|
|
1713
|
+
}
|
|
1714
|
+
// Deleted, or its canvas closed: a live run's generator returns (its finally runs), then its cleanups run.
|
|
1715
|
+
const live = liveRuns.get(id);
|
|
1716
|
+
if (live) endLiveThenRetire(id, live.runId + 1);
|
|
1717
|
+
retire(id, live ? live.runId : undefined); // any older run's
|
|
1718
|
+
paneStates.delete(id);
|
|
1719
|
+
midiStates.get(id)?.input?.end(); // its raw MIDI input, if it opened one
|
|
1720
|
+
midiStates.delete(id);
|
|
1721
|
+
// Its timers run on, as before (an onCleanup stops them); they no longer count against it.
|
|
1722
|
+
for (const [name, ids] of codeNames) if (ids.delete(id) && !ids.size) codeNames.delete(name);
|
|
1723
|
+
if (paneTimers.delete(id)) {
|
|
1724
|
+
for (const [handle, owners] of timerOwners) {
|
|
1725
|
+
if (!owners.includes(id)) continue;
|
|
1726
|
+
const rest = owners.filter((o) => o !== id);
|
|
1727
|
+
if (rest.length) timerOwners.set(handle, rest);
|
|
1728
|
+
else timerOwners.delete(handle);
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
closeLink(ownLinks.get(id)); // the channel to its own Worker
|
|
1732
|
+
ownLinks.delete(id);
|
|
1733
|
+
releaseAI(id);
|
|
1734
|
+
agentCalls.get(id)?.stop(new DOMException("The agent pane was removed", "AbortError")); // its model request or prompt in flight
|
|
1735
|
+
agentCalls.delete(id);
|
|
1736
|
+
agentChats.delete(id);
|
|
1737
|
+
fingerprints.delete(id);
|
|
1738
|
+
values.delete(id);
|
|
1739
|
+
eachRuns.delete(id);
|
|
1740
|
+
eachMemos.delete(id);
|
|
1741
|
+
eachImports.delete(id);
|
|
1742
|
+
repeatMemos.delete(id);
|
|
1743
|
+
setters.delete(id);
|
|
1744
|
+
stateKeys.delete(id);
|
|
1745
|
+
setterLabels.delete(id);
|
|
1746
|
+
latest.delete(id);
|
|
1747
|
+
inspector.release(id);
|
|
1748
|
+
},
|
|
1749
|
+
|
|
1750
|
+
has: (id) => values.has(id),
|
|
1751
|
+
|
|
1752
|
+
/** How much the Worker holds (for leak checks: src/debug/lifecycle.js, test/lifecycle.test.mjs). */
|
|
1753
|
+
stats: () => ({ values: values.size, events: eventStore.size, heldRemoved: heldRemovedCount(), latest: latest.size, setters: setters.size, eachRuns: eachRuns.size, eachMemos: eachMemos.size, repeatMemos: repeatMemos.size, handles: inspector.size, aiSessions: [...aiSessions.values()].reduce((n, set) => n + set.size, 0), agentChats: agentChats.size, paneStates: paneStates.size, cleanups: cleanups.size, liveRuns: liveRuns.size, links: ownLinks.size, timers: timerOwners.size }),
|
|
1754
|
+
|
|
1755
|
+
/** The compile cache: how many compiled panes it holds, and its hits and misses so far. */
|
|
1756
|
+
compileStats: () => ({ size: compiled.size, max: COMPILE_CACHE_MAX, ...compileStats }),
|
|
1757
|
+
|
|
1758
|
+
/**
|
|
1759
|
+
* What a pane's value can be exported as (src/export/value.js describeValue),
|
|
1760
|
+
* or `{ present: false }`. `scalars`: an array of plain values counts as a
|
|
1761
|
+
* one-column table (for-each results).
|
|
1762
|
+
*/
|
|
1763
|
+
exportInfo(id, { scalars = false } = {}) {
|
|
1764
|
+
if (!values.has(id)) return { present: false };
|
|
1765
|
+
if (!exporter) return { present: true, kind: "opaque", reason: "exporting isn't available in this sandbox", table: false };
|
|
1766
|
+
const value = values.get(id);
|
|
1767
|
+
return { present: true, ...exporter.describeValue(value, { scalars }), ...(tensorLib?.isTensor(value) ? { tensor: { shape: [...value.shape], dtype: value.dtype } } : {}) };
|
|
1768
|
+
},
|
|
1769
|
+
|
|
1770
|
+
/**
|
|
1771
|
+
* A pane's value as text, converted here so a large value never blocks the
|
|
1772
|
+
* page: "json", "csv", "tsv", "string", "html" (see exportText), or
|
|
1773
|
+
* "preview": a deep preview tree the page prints as text.
|
|
1774
|
+
*/
|
|
1775
|
+
exportValue(id, format, { scalars = false, runId, maxBytes } = {}) {
|
|
1776
|
+
// The run log (src/model/runlog.js) asks for the value of one run: a newer run's isn't it.
|
|
1777
|
+
if (runId !== undefined && latest.get(id) !== runId) return { stale: true };
|
|
1778
|
+
if (!values.has(id)) throw new Error("This pane has no value to export.");
|
|
1779
|
+
const value = values.get(id);
|
|
1780
|
+
if (format === "preview") return { preview: serialize(value, { depth: 6, maxEntries: 1000, maxString: 1000000 }) };
|
|
1781
|
+
// A tensor as a NumPy .npy file: bytes, not text (the page makes the download of them).
|
|
1782
|
+
if (format === "npy") {
|
|
1783
|
+
if (!tensorLib?.isTensor(value)) throw new Error("This pane's value isn't a tensor.");
|
|
1784
|
+
return { bytes: tensorLib.toNpy(value) };
|
|
1785
|
+
}
|
|
1786
|
+
// A table as a Parquet file: bytes, made here where the value lives (the page makes the download of them).
|
|
1787
|
+
if (format === "parquet") {
|
|
1788
|
+
if (!dataframeCore || !exporter) throw new Error("Parquet isn't available in this sandbox.");
|
|
1789
|
+
const rows = exporter.rowObjects(value, { scalars });
|
|
1790
|
+
if (!rows) throw new Error("This pane's value isn't a table (an array of row objects).");
|
|
1791
|
+
// Cancellable (cancelExport): the write yields between row groups, where the abort lands. A newer export of the pane replaces it.
|
|
1792
|
+
parquetExports.get(id)?.abort();
|
|
1793
|
+
const controller = new AbortController();
|
|
1794
|
+
parquetExports.set(id, controller);
|
|
1795
|
+
return dataframeCore
|
|
1796
|
+
.createDataframe({ load: () => sandboxImport("mallory:codec/dataframe") })
|
|
1797
|
+
.writeParquet(rows, { detail: true, signal: controller.signal, onProgress: (progress) => (controller.progress = progress) }) // exportProgress reads it
|
|
1798
|
+
.then(({ bytes, notes }) => ({ bytes, rows: rows.length, notes }))
|
|
1799
|
+
.finally(() => parquetExports.get(id) === controller && parquetExports.delete(id));
|
|
1800
|
+
}
|
|
1801
|
+
if (!exporter) throw new Error("Exporting isn't available in this sandbox.");
|
|
1802
|
+
const out = exporter.exportText(value, format, { scalars });
|
|
1803
|
+
if (maxBytes && out.text.length > maxBytes) return { tooBig: out.text.length };
|
|
1804
|
+
return out;
|
|
1805
|
+
},
|
|
1806
|
+
|
|
1807
|
+
/** How far pane `id`'s Parquet export has got: `{ rows, total }` after its first row group, null before that or when none is written. */
|
|
1808
|
+
exportProgress(id) {
|
|
1809
|
+
return parquetExports.get(id)?.progress ?? null;
|
|
1810
|
+
},
|
|
1811
|
+
|
|
1812
|
+
/** Stop pane `id`'s Parquet export, if one is being written: it fails with an AbortError. True when there was one. */
|
|
1813
|
+
cancelExport(id) {
|
|
1814
|
+
const controller = parquetExports.get(id);
|
|
1815
|
+
if (!controller) return false;
|
|
1816
|
+
parquetExports.delete(id);
|
|
1817
|
+
controller.abort(new DOMException("The export was cancelled", "AbortError"));
|
|
1818
|
+
return true;
|
|
1819
|
+
},
|
|
1820
|
+
};
|