@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,2238 @@
|
|
|
1
|
+
// `mallory serve`: canvases kept running by the headless runner, with
|
|
2
|
+
// webhook panes as HTTP endpoints (node:http, no framework), timer panes on
|
|
3
|
+
// their schedules and watch panes on allowed folders. The command line is
|
|
4
|
+
// src/headless/serve-cli.js; the security model is docs/guide/cli-and-serving.md's "Serving
|
|
5
|
+
// canvases" section.
|
|
6
|
+
//
|
|
7
|
+
// Each served canvas is a CanvasHost: its canvas, kept open in a headless
|
|
8
|
+
// session (HeadlessSession#open, src/run/run.js) as a live Canvas, and
|
|
9
|
+
// a queue. A request, a timer tick or a file event is a job; a canvas runs
|
|
10
|
+
// one job at a time (--concurrency 1, the default: its panes share state in
|
|
11
|
+
// one sandbox), and with --concurrency N, N jobs at a time in N lanes, each
|
|
12
|
+
// its own copy of the canvas in its own worker thread, sharing nothing (so
|
|
13
|
+
// such a canvas can't have timers, watch panes or kept state). The queue
|
|
14
|
+
// holds --queue jobs (64); a request beyond that gets 429.
|
|
15
|
+
//
|
|
16
|
+
// A request for webhook pane W: the pane's value becomes the request, the
|
|
17
|
+
// canvas reruns what depends on it, and the respond pane downstream of W
|
|
18
|
+
// answers as soon as it settles (its value: 200 with its body; skipped: 204;
|
|
19
|
+
// failed, or a pane before it failed: 500 with a generic message; not in
|
|
20
|
+
// time: 504). The job ends when the whole canvas has settled. A webhook with
|
|
21
|
+
// no respond pane answers 202 as soon as the request is queued.
|
|
22
|
+
//
|
|
23
|
+
// Isolated requests (--isolate, or a webhook's `isolate` setting): each
|
|
24
|
+
// runs in a new instance of the canvas (HeadlessSession#open in its own
|
|
25
|
+
// namespace) with its own state, closed once the job ends, as Noodl's cloud
|
|
26
|
+
// functions run each request in a fresh component with its own Model.Scope.
|
|
27
|
+
// --concurrency N of them run at once, each on a worker thread of its own
|
|
28
|
+
// that the next isolated request reuses (--isolate-threads: a new thread per
|
|
29
|
+
// request, one of the --spare-threads started ahead when there is one).
|
|
30
|
+
// The shared instance (the lanes above) is then only for the canvas's timers,
|
|
31
|
+
// watch panes and webhooks that aren't isolated.
|
|
32
|
+
//
|
|
33
|
+
// A2A push notifications (#541, src/headless/a2a-push.js): an A2A agent pane
|
|
34
|
+
// in the shared instance can have its agent POST task updates to
|
|
35
|
+
// /<canvas>/a2a-push/<id> (a reserved path), checked against the task's own
|
|
36
|
+
// secret before anything reaches the canvas; each update reruns the pane in a
|
|
37
|
+
// job of the queue ("a2a push <pane>"). Isolated instances don't get push.
|
|
38
|
+
import { createServer } from "node:http";
|
|
39
|
+
import { SHORT_PREFIX, resolveShortLink, shortLinkPage, missLimiter } from "./short-links.js";
|
|
40
|
+
import { createHmac, randomUUID } from "node:crypto";
|
|
41
|
+
import { createWsTickets, splitTicket } from "./ws-ticket.js";
|
|
42
|
+
import { sameSecret, scrubber, holdsSecret, isLoopback, loopbackHostHeader } from "./guard.js";
|
|
43
|
+
import { appendFile, chmod } from "node:fs/promises";
|
|
44
|
+
import { isDeepStrictEqual } from "node:util";
|
|
45
|
+
import { basename } from "node:path";
|
|
46
|
+
import { webhookSettings, webhookProblem, requestValue, rawRequestValue, resolveRoute, CATCH_ALL, encodeResponse, routeShape, respondSettings, respondProblem, BadRequest, malformedPath } from "../model/webhook.js";
|
|
47
|
+
import { routerSettings, routerProblem, routerEntries, routerRequestValue } from "../model/router.js";
|
|
48
|
+
import { portId } from "../model/ports.js";
|
|
49
|
+
import { StreamHub } from "./serve-stream.js";
|
|
50
|
+
import { watchSettings, watchProblem } from "../model/watch.js";
|
|
51
|
+
import { isPersisted, parseStateFile } from "../model/persist-state.js";
|
|
52
|
+
import { graphPanes, SEP } from "../model/subgraph.js";
|
|
53
|
+
import { repeatOn, keyLabel } from "../model/repeater.js";
|
|
54
|
+
import { disabledByGroups } from "../model/groups.js";
|
|
55
|
+
import { resolveWatchDir, watchFolder } from "./watch.js";
|
|
56
|
+
import { serveRootsSource } from "./mcp-roots.js";
|
|
57
|
+
import { paneType, trait, spendCapsOf } from "../panes/registry.js";
|
|
58
|
+
import { revisionOf } from "../run/publish.js";
|
|
59
|
+
import { collectCheckpoints, restoreCheckpoints, describeReceipt } from "../model/wait-persist.js";
|
|
60
|
+
import { waitingOf } from "../model/wait-clock.js";
|
|
61
|
+
import { MONITOR_PREFIX } from "../run/monitor.js";
|
|
62
|
+
import { OPERATOR_PREFIX } from "./operator.js";
|
|
63
|
+
import { parkStoreOver, createScheduler, createRunLimiter, acceptBundle, boundDoc, intersectHosts } from "./scheduled.js";
|
|
64
|
+
import { markUnattended } from "../autonomy/unattended.js";
|
|
65
|
+
import { parkedRequest, answerParked } from "../agent/run.js";
|
|
66
|
+
import { fingerprintOf } from "../agent/park.js";
|
|
67
|
+
import { createPeople } from "./people.js";
|
|
68
|
+
import { readRequest, transcript, openaiReply, anthropicReply, errorBody, haltStatus, modelList } from "./model-endpoint.js";
|
|
69
|
+
import { runServed, servedOutcome, approvals as machineApprovals } from "../machine/session.js";
|
|
70
|
+
import { mcpHandler, optedPanes, runTool, MCP_VERSIONS } from "./mcp-endpoint.js";
|
|
71
|
+
import { decideSettings, proposalRows } from "../model/decisions.js";
|
|
72
|
+
import { respondOutcome } from "../run/respond-outcome.js";
|
|
73
|
+
import { createPushRoutes, pushIdOf, PUSH_SEGMENT } from "./a2a-push.js";
|
|
74
|
+
import { servedExchange, servedBodyView, notifyServed } from "../model/proxy-log.js";
|
|
75
|
+
import { cleanWs, wsProblem } from "../model/ws-client.js";
|
|
76
|
+
import { createWsProxies, rejectUpgrade } from "./ws-proxy.js";
|
|
77
|
+
import { createWsEcho, ECHO_PATH } from "./ws-echo.js";
|
|
78
|
+
import { createConnectionLog } from "./ws-connections.js";
|
|
79
|
+
import { staticLookup, openChecked } from "./static-dirs.js";
|
|
80
|
+
import { createChannels, checkChannels } from "./channels/index.js";
|
|
81
|
+
import { createGateways } from "./gateways/index.js";
|
|
82
|
+
|
|
83
|
+
// ── what a canvas serves ────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
/** A canvas file's route: its name without the extension, lowercase letters, digits and "-" ("Daily Report.mallory.json" → "daily-report"). */
|
|
86
|
+
export function routeName(file) {
|
|
87
|
+
const base = basename(String(file)).replace(/\.((?:mallory|viaframe|miso)\.)?(json|ya?ml|md)$|\.rivet-project$|\.ipynb$|\.published$/i, "");
|
|
88
|
+
return (
|
|
89
|
+
base
|
|
90
|
+
.toLowerCase()
|
|
91
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
92
|
+
.replace(/^-+|-+$/g, "")
|
|
93
|
+
.slice(0, 64) || "canvas"
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Every pane inside a canvas's subgraph panes, at any depth. */
|
|
98
|
+
function innerPanes(panes) {
|
|
99
|
+
return panes.flatMap((p) => (p.type === "subgraph" ? [...graphPanes(p), ...innerPanes(graphPanes(p))] : []));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What a canvas serves: its webhooks ({ id, name, path, settings, respond:
|
|
104
|
+
* the respond pane downstream of it, or null }), its watch panes, whether it
|
|
105
|
+
* has timers or kept state, and the problems that stop it from being served
|
|
106
|
+
* (two webhooks with one path, a webhook that reaches two respond panes, …).
|
|
107
|
+
* `notes` are warnings. Only panes on the canvas itself are served.
|
|
108
|
+
*/
|
|
109
|
+
export function planCanvas(doc, { concurrency = 1, watchDirs = new Map(), isolate = false, decide = false } = {}) {
|
|
110
|
+
const off = disabledByGroups(Array.isArray(doc.groups) ? doc.groups : []);
|
|
111
|
+
const active = (p) => !p.disabled && !off.has(p.id);
|
|
112
|
+
const panes = doc.panes ?? [];
|
|
113
|
+
const byId = new Map(panes.map((p) => [p.id, p]));
|
|
114
|
+
const label = (p) => p.name || p.id;
|
|
115
|
+
const problems = [];
|
|
116
|
+
const notes = [];
|
|
117
|
+
const dependents = new Map();
|
|
118
|
+
for (const p of panes) for (const i of p.inputs ?? []) dependents.set(i.source, [...(dependents.get(i.source) ?? []), p.id]);
|
|
119
|
+
const below = (id, seeds = dependents.get(id) ?? []) => {
|
|
120
|
+
const seen = new Set();
|
|
121
|
+
const stack = [...seeds];
|
|
122
|
+
while (stack.length) {
|
|
123
|
+
const next = stack.pop();
|
|
124
|
+
if (seen.has(next)) continue;
|
|
125
|
+
seen.add(next);
|
|
126
|
+
stack.push(...(dependents.get(next) ?? []));
|
|
127
|
+
}
|
|
128
|
+
return seen;
|
|
129
|
+
};
|
|
130
|
+
const webhooks = [];
|
|
131
|
+
const paths = new Map(); // route shape -> the webhook and router routes that have it: [{ name, path, methods, router }]
|
|
132
|
+
for (const p of panes.filter((q) => trait(q.type, "delivered"))) if (!active(p)) notes.push(`${p.type} pane ${label(p)} is deactivated: it isn't served`);
|
|
133
|
+
for (const p of panes.filter((q) => q.type === "webhook" && active(q))) {
|
|
134
|
+
const problem = webhookProblem(p.webhook);
|
|
135
|
+
if (problem) {
|
|
136
|
+
problems.push(`webhook ${label(p)}: ${problem}`);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const settings = webhookSettings(p.webhook);
|
|
140
|
+
if (settings.path.split("/")[0] === PUSH_SEGMENT) problems.push(`webhook ${label(p)}: the path /${PUSH_SEGMENT}/… is kept for A2A push notifications: use another path`);
|
|
141
|
+
const shape = routeShape(settings.path);
|
|
142
|
+
const first = paths.get(shape)?.[0];
|
|
143
|
+
if (first) problems.push(`webhooks ${first.name} and ${label(p)} both have ${first.path === settings.path ? `the path /${settings.path}` : `the same route (/${first.path} and /${settings.path})`}`);
|
|
144
|
+
paths.set(shape, [...(paths.get(shape) ?? []), { name: label(p), path: settings.path, methods: settings.methods, router: false }]);
|
|
145
|
+
const responds = [...below(p.id)].filter((id) => byId.get(id)?.type === "respond");
|
|
146
|
+
if (responds.length > 1) problems.push(`webhook ${label(p)} reaches ${responds.length} respond panes (${responds.map((id) => label(byId.get(id))).join(", ")}): a request gets one response`);
|
|
147
|
+
const isolatedHook = Boolean(isolate || settings.isolate);
|
|
148
|
+
// An isolated request runs in a place of its own that is closed with it: an item it holds in a wait, decision or gate pane goes too (those are kept only in the shared instance).
|
|
149
|
+
// (With the operator page, a decision pane's proposal is kept for an approver while it waits: src/headless/operator.js.)
|
|
150
|
+
const holders = isolatedHook ? [...below(p.id)].map((id) => byId.get(id)).filter((q) => q && active(q) && waitingOf(q.type) && !(decide && q.type === "decision")) : [];
|
|
151
|
+
if (holders.length) notes.push(`webhook ${label(p)} is isolated and reaches ${holders.map((q) => `${q.type} pane ${label(q)}`).join(", ")}: an item held there is gone when the request ends (waits are kept only in the shared instance; leave the webhook out of --isolate to keep them)`);
|
|
152
|
+
webhooks.push({ id: p.id, key: p.id, name: label(p), path: settings.path, catchAll: settings.path === CATCH_ALL, settings, respond: responds[0] ?? null, isolated: isolatedHook });
|
|
153
|
+
}
|
|
154
|
+
// A router pane's routes are served like webhooks, one entry each (`output`: the route, the pane's output that takes the request).
|
|
155
|
+
for (const p of panes.filter((q) => q.type === "router" && active(q))) {
|
|
156
|
+
const problem = routerProblem(p.router);
|
|
157
|
+
if (problem) {
|
|
158
|
+
problems.push(`router ${label(p)}: ${problem}`);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const settings = routerSettings(p.router);
|
|
162
|
+
const isolatedHook = Boolean(isolate || settings.isolate);
|
|
163
|
+
for (const entry of routerEntries(p.router)) {
|
|
164
|
+
const name = `${label(p)}.${entry.name}`;
|
|
165
|
+
if (entry.path.split("/")[0] === PUSH_SEGMENT) problems.push(`router ${name}: the path /${PUSH_SEGMENT}/… is kept for A2A push notifications: use another path`);
|
|
166
|
+
const shape = routeShape(entry.path);
|
|
167
|
+
const clash = (paths.get(shape) ?? []).find((o) => o.methods.some((m) => entry.methods.includes(m)));
|
|
168
|
+
if (clash) problems.push(`${clash.router ? "router" : "webhook"} ${clash.name} and router ${name} both answer ${clash.methods.filter((m) => entry.methods.includes(m)).join(", ")} /${clash.path === entry.path ? entry.path : `${clash.path} and /${entry.path}`}`);
|
|
169
|
+
paths.set(shape, [...(paths.get(shape) ?? []), { name, path: entry.path, methods: entry.methods, router: true }]);
|
|
170
|
+
// What is wired to this route's output (or to the pane's main value, which carries every route), and below it.
|
|
171
|
+
const seeds = panes.filter((q) => q.inputs?.some((i) => i.source === p.id && (!i.output || i.output === entry.name))).map((q) => q.id);
|
|
172
|
+
const reached = below(p.id, seeds);
|
|
173
|
+
const responds = panes.filter((q) => q.type === "respond" && reached.has(q.id)).map((q) => q.id);
|
|
174
|
+
if (responds.length > 1) problems.push(`router ${name} reaches ${responds.length} respond panes (${responds.map((id) => label(byId.get(id))).join(", ")}): a request gets one response`);
|
|
175
|
+
const holders = isolatedHook ? panes.filter((q) => reached.has(q.id) && active(q) && waitingOf(q.type)) : [];
|
|
176
|
+
if (holders.length) notes.push(`router ${name} is isolated and reaches ${holders.map((q) => `${q.type} pane ${label(q)}`).join(", ")}: an item held there is gone when the request ends (waits are kept only in the shared instance)`);
|
|
177
|
+
webhooks.push({ id: p.id, key: `${p.id}#${entry.name}`, name, path: entry.path, output: entry.name, settings: { path: entry.path, methods: entry.methods, maxBodyKB: settings.maxBodyKB, headers: settings.headers, isolate: settings.isolate }, respond: responds[0] ?? null, isolated: isolatedHook });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// A respond pane that streams (server-sent events) goes on running after its request is answered, in the shared instance.
|
|
181
|
+
for (const p of panes.filter((q) => q.type === "respond" && active(q))) {
|
|
182
|
+
const problem = respondProblem(p.respond);
|
|
183
|
+
if (problem) problems.push(`respond pane ${label(p)}: ${problem}`);
|
|
184
|
+
else if (respondSettings(p.respond).stream) {
|
|
185
|
+
for (const w of webhooks.filter((x) => x.respond === p.id)) {
|
|
186
|
+
if (w.isolated) problems.push(`${w.output ? "router" : "webhook"} ${w.name} is isolated and streams from respond pane ${label(p)}: a stream needs the shared instance (leave isolate off for it)`);
|
|
187
|
+
else notes.push(`${w.output ? "router" : "webhook"} ${w.name} streams from respond pane ${label(p)}: every stream open on it shows the feed of the latest request, and ends when its client goes or after --stream-seconds`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const watches = [];
|
|
192
|
+
for (const p of panes.filter((q) => q.type === "watch" && active(q))) {
|
|
193
|
+
const problem = watchProblem(p.files);
|
|
194
|
+
if (problem) {
|
|
195
|
+
problems.push(`watch pane ${label(p)}: ${problem}`);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const settings = watchSettings(p.files);
|
|
199
|
+
if (!watchDirs.size) {
|
|
200
|
+
notes.push(`watch pane ${label(p)} won't fire: file watching is off (run mallory serve with --watch-dir ${settings.dir.split("/")[0]}=<folder>)`);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const where = resolveWatchDir(settings.dir, watchDirs);
|
|
204
|
+
if (where.problem) problems.push(`watch pane ${label(p)}: ${where.problem}`);
|
|
205
|
+
else watches.push({ id: p.id, name: label(p), settings, root: where.root, path: where.path });
|
|
206
|
+
}
|
|
207
|
+
// WebSocket proxies (wave P-F): a ws-client pane in proxy mode is a route that takes WebSocket upgrades at /<canvas>/<its path>. It reaches one fixed upstream, under --allow-host.
|
|
208
|
+
const wsProxies = [];
|
|
209
|
+
for (const p of panes.filter((q) => trait(q.type, "socketProxy") && active(q))) {
|
|
210
|
+
const problem = wsProblem(p.ws);
|
|
211
|
+
if (problem) {
|
|
212
|
+
problems.push(`websocket ${label(p)}: ${problem}`);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const s = cleanWs(p.ws);
|
|
216
|
+
if (s.mode !== "proxy") continue;
|
|
217
|
+
if (!s.proxy.path || !s.proxy.upstream) {
|
|
218
|
+
notes.push(`websocket proxy ${label(p)} has no path or upstream yet: nothing is served for it`);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const clash = wsProxies.find((x) => x.path === s.proxy.path) ?? webhooks.find((w) => w.path === s.proxy.path);
|
|
222
|
+
if (clash) problems.push(`websocket proxy ${label(p)} and ${clash.name} both answer /${s.proxy.path}`);
|
|
223
|
+
else wsProxies.push({ id: p.id, name: label(p), path: s.proxy.path, settings: s.proxy });
|
|
224
|
+
}
|
|
225
|
+
for (const p of innerPanes(panes)) if (paneType(p.type)?.server === "mallory serve") notes.push(`${p.type} pane ${label(p)} is inside a subgraph: only panes on the canvas itself are served`);
|
|
226
|
+
const all = [...panes, ...innerPanes(panes)];
|
|
227
|
+
const timers = all.some((p) => p.type === "timer");
|
|
228
|
+
const persisted = all.some((p) => isPersisted(p));
|
|
229
|
+
// The shared instance: the canvas kept running, for its timers, watch panes and webhooks that aren't isolated. A canvas
|
|
230
|
+
// whose webhooks are all isolated, with no timers or watch panes, has none. `lanes`: how many copies of it run side by side.
|
|
231
|
+
const why = [timers && "timer panes", panes.some((p) => p.type === "watch") && "watch panes", persisted && "kept state panes"].filter(Boolean);
|
|
232
|
+
const isolated = webhooks.some((w) => w.isolated);
|
|
233
|
+
const shared = !isolated || timers || panes.some((p) => p.type === "watch") || webhooks.some((w) => !w.isolated);
|
|
234
|
+
const lanes = !shared ? 0 : isolated && why.length ? 1 : concurrency;
|
|
235
|
+
if (lanes > 1 && why.length) problems.push(`--concurrency ${concurrency} runs requests in copies of the canvas that share nothing, so it can't have ${why.join(" or ")}: serve it with --concurrency 1, or isolate its webhooks (--isolate)`);
|
|
236
|
+
if (isolated && shared && lanes === 1 && concurrency > 1) notes.push(`its ${why.join(", ")}${webhooks.some((w) => !w.isolated) ? " and webhooks that aren't isolated" : ""} run one at a time in the canvas's shared instance; --concurrency ${concurrency} applies to isolated requests`);
|
|
237
|
+
const a2a = panes.some((p) => p.type === "a2a" && active(p)) || innerPanes(panes).some((p) => p.type === "a2a"); // A2A agent panes (in its subgraphs too) may take push notifications
|
|
238
|
+
return { webhooks, wsProxies, watches, timers, persisted, lanes, problems, notes, a2a };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export { sameSecret, scrubber, isLoopback }; // the shared checks live in src/headless/guard.js
|
|
242
|
+
|
|
243
|
+
// ── credentials ─────────────────────────────────────────────────────────────
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* How requests prove they may run the canvas: `Authorization: Bearer <token>`
|
|
247
|
+
* (`--token-env`), or an HMAC-SHA256 of the body in a header (`--hmac-env`,
|
|
248
|
+
* `--hmac-header`, default x-hub-signature-256, as `sha256=<hex>` or `<hex>`).
|
|
249
|
+
* Either one passes. Neither configured: every request may (loopback only).
|
|
250
|
+
*/
|
|
251
|
+
export function createAuth({ token, hmacSecret, hmacHeader = "x-hub-signature-256" } = {}) {
|
|
252
|
+
const header = String(hmacHeader).toLowerCase();
|
|
253
|
+
return {
|
|
254
|
+
required: Boolean(token || hmacSecret),
|
|
255
|
+
hmacHeader: header,
|
|
256
|
+
hasHmac: Boolean(hmacSecret),
|
|
257
|
+
hasBearer: Boolean(token),
|
|
258
|
+
bearer(headers) {
|
|
259
|
+
if (!token) return false;
|
|
260
|
+
const m = /^Bearer[ \t]+(\S+)[ \t]*$/i.exec(String(headers.authorization ?? ""));
|
|
261
|
+
return Boolean(m) && sameSecret(m[1], token);
|
|
262
|
+
},
|
|
263
|
+
hmac(headers, bytes) {
|
|
264
|
+
if (!hmacSecret) return false;
|
|
265
|
+
const given = String(headers[header] ?? "").trim().replace(/^sha256=/i, "").toLowerCase();
|
|
266
|
+
if (!/^[0-9a-f]{64}$/.test(given)) return false;
|
|
267
|
+
return sameSecret(given, createHmac("sha256", hmacSecret).update(bytes).digest("hex"));
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ── kept state (--state) ────────────────────────────────────────────────────
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* State panes' kept values for every served canvas: browser stores shared,
|
|
276
|
+
* canvas-scope values by pane name (one canvas: as `mallory run --state` reads
|
|
277
|
+
* them; several: under each canvas's route). `changed` until saved.
|
|
278
|
+
* `isolated(route)` is a store for one isolated request: a copy of the
|
|
279
|
+
* values as they are now, which its writes change and nothing else sees (the
|
|
280
|
+
* holder isn't changed, so nothing is written back). Pending waits (wait,
|
|
281
|
+
* decision and gate panes) are kept in a `waits` section, `{ "<canvas>": {
|
|
282
|
+
* "<pane id>": checkpoint } }, for every canvas (`waitsFor`, `setWaits`); the copies of the canvas past the first that
|
|
283
|
+
* --concurrency N runs (`lane` 1, 2, …: they share nothing, so each keeps its own) are in a `laneWaits` section,
|
|
284
|
+
* `{ "<canvas>": { "<lane>": { "<pane id>": checkpoint } } }`.
|
|
285
|
+
*/
|
|
286
|
+
export function stateHolder(json, { routes = [] } = {}) {
|
|
287
|
+
const data = parseStateFile(json);
|
|
288
|
+
data.waits ??= {};
|
|
289
|
+
data.laneWaits ??= {};
|
|
290
|
+
data.parks ??= {};
|
|
291
|
+
data.schedules ??= {};
|
|
292
|
+
const multi = routes.length > 1;
|
|
293
|
+
const storeOver = (d, route, onWrite) => {
|
|
294
|
+
const section = () => {
|
|
295
|
+
if (!multi) return d.canvas;
|
|
296
|
+
if (!d.canvas[route] || typeof d.canvas[route] !== "object" || Array.isArray(d.canvas[route])) d.canvas[route] = {};
|
|
297
|
+
return d.canvas[route];
|
|
298
|
+
};
|
|
299
|
+
const where = (ref) => (ref.scope === "browser" ? [d.browser, ref.name] : [section(), ref.paneName]);
|
|
300
|
+
return {
|
|
301
|
+
async access() {},
|
|
302
|
+
async read(ref) {
|
|
303
|
+
const [s, key] = where(ref);
|
|
304
|
+
return Object.hasOwn(s, key) ? JSON.stringify(s[key]) : undefined;
|
|
305
|
+
},
|
|
306
|
+
write(ref, text) {
|
|
307
|
+
const [s, key] = where(ref);
|
|
308
|
+
s[key] = JSON.parse(text);
|
|
309
|
+
onWrite();
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
};
|
|
313
|
+
const withoutTime = (value) => JSON.stringify(value, (k, v) => (k === "savedAt" ? undefined : v)); // a checkpoint that differs only by when it was made isn't a change
|
|
314
|
+
const holder = {
|
|
315
|
+
changed: false,
|
|
316
|
+
forCanvas: (route) => storeOver(data, route, () => (holder.changed = true)),
|
|
317
|
+
isolated: (route) => storeOver(structuredClone({ canvas: data.canvas, browser: data.browser }), route, () => {}),
|
|
318
|
+
/** The pending waits kept for a canvas's copy `lane` (0: the first, the shared instance) (`{ [pane id]: checkpoint }`, src/model/wait-persist.js), as they were last saved. */
|
|
319
|
+
waitsFor: (route, lane = 0) => structuredClone((lane ? data.laneWaits[route]?.[lane] : data.waits[route]) ?? {}),
|
|
320
|
+
/** The lane numbers past the first that have waits kept for a canvas. */
|
|
321
|
+
lanesWithWaits: (route) => Object.keys(data.laneWaits[route] ?? {}).map(Number),
|
|
322
|
+
/** Keep a canvas's pending waits for one of its copies (all of them: panes that wait no more are dropped). */
|
|
323
|
+
setWaits(route, panes, lane = 0) {
|
|
324
|
+
const section = lane ? (data.laneWaits[route] ??= {}) : data.waits;
|
|
325
|
+
const key = lane ? String(lane) : route;
|
|
326
|
+
if (withoutTime(section[key] ?? {}) === withoutTime(panes)) return void (lane && !Object.keys(section).length && delete data.laneWaits[route]);
|
|
327
|
+
if (Object.keys(panes).length) section[key] = panes;
|
|
328
|
+
else delete section[key];
|
|
329
|
+
if (lane && !Object.keys(section).length) delete data.laneWaits[route];
|
|
330
|
+
holder.changed = true;
|
|
331
|
+
},
|
|
332
|
+
/** The parked runs of a scheduled canvas (docs/design/scheduled-runs.md): `{ [pane key]: park record }` of one schedule, a copy. */
|
|
333
|
+
parksFor: (route, schedule) => structuredClone(data.parks[route]?.[schedule] ?? {}),
|
|
334
|
+
parkOf: (route, schedule, pane) => (Object.hasOwn(data.parks[route]?.[schedule] ?? {}, pane) ? structuredClone(data.parks[route][schedule][pane]) : undefined),
|
|
335
|
+
/** Keep (or, with undefined, drop) one parked run. */
|
|
336
|
+
setPark(route, schedule, pane, record) {
|
|
337
|
+
if (record === undefined) {
|
|
338
|
+
if (!Object.hasOwn(data.parks[route]?.[schedule] ?? {}, pane)) return;
|
|
339
|
+
delete data.parks[route][schedule][pane];
|
|
340
|
+
if (!Object.keys(data.parks[route][schedule]).length) delete data.parks[route][schedule];
|
|
341
|
+
if (!Object.keys(data.parks[route]).length) delete data.parks[route];
|
|
342
|
+
} else {
|
|
343
|
+
((data.parks[route] ??= {})[schedule] ??= {})[pane] = record;
|
|
344
|
+
}
|
|
345
|
+
holder.changed = true;
|
|
346
|
+
},
|
|
347
|
+
/** When a schedule last fired (epoch ms, newest last), for its runs-per-hour cap across a restart. */
|
|
348
|
+
firesOf: (schedule) => [...(data.schedules[schedule]?.fires ?? [])],
|
|
349
|
+
setFires(schedule, fires) {
|
|
350
|
+
data.schedules[schedule] = { fires: fires.slice(-120) };
|
|
351
|
+
holder.changed = true;
|
|
352
|
+
},
|
|
353
|
+
toJSON: () => ({ canvas: data.canvas, browser: data.browser, ...(Object.keys(data.waits).length ? { waits: data.waits } : {}), ...(Object.keys(data.laneWaits).length ? { laneWaits: data.laneWaits } : {}), ...(Object.keys(data.parks).length ? { parks: data.parks } : {}), ...(Object.keys(data.schedules).length ? { schedules: data.schedules } : {}) }),
|
|
354
|
+
};
|
|
355
|
+
return holder;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// ── spare worker threads (--isolate-threads) ───────────────────────────────
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Spare worker threads: with --isolate-threads, `size` sessions
|
|
362
|
+
* started ahead, each a sandbox thread with mallory's runtime loaded and nothing
|
|
363
|
+
* of any canvas run on it (a thread is canvas-agnostic, so one set serves
|
|
364
|
+
* every canvas). An isolated request takes the oldest one, and a replacement
|
|
365
|
+
* starts in the background; the request's thread is closed after it and never
|
|
366
|
+
* reused, so isolation is the same as with a thread started for the request.
|
|
367
|
+
* `take()` gives null when there is none (none wanted, or a burst took them
|
|
368
|
+
* all before their replacements started): the request then starts its own.
|
|
369
|
+
*/
|
|
370
|
+
export function sparePool(createSession, { size = 0, warn = () => {} } = {}) {
|
|
371
|
+
const spares = []; // { session, failed }, oldest first
|
|
372
|
+
let wanted = 0;
|
|
373
|
+
let closed = false;
|
|
374
|
+
let refilling = false;
|
|
375
|
+
const add = () => {
|
|
376
|
+
let session;
|
|
377
|
+
try {
|
|
378
|
+
session = createSession();
|
|
379
|
+
} catch (error) {
|
|
380
|
+
warn(`a spare worker thread didn't start: ${error.message}`);
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
const spare = { session, failed: false };
|
|
384
|
+
Promise.resolve(session.runtime?.ready).catch(() => (spare.failed = true)); // its sandbox didn't start: not handed out
|
|
385
|
+
spares.push(spare);
|
|
386
|
+
return true;
|
|
387
|
+
};
|
|
388
|
+
// Replacements start after the current turn, so the request that took a spare gets going first.
|
|
389
|
+
const refill = () => {
|
|
390
|
+
if (refilling || closed) return;
|
|
391
|
+
refilling = true;
|
|
392
|
+
setImmediate(() => {
|
|
393
|
+
refilling = false;
|
|
394
|
+
while (!closed && spares.length < wanted && add());
|
|
395
|
+
});
|
|
396
|
+
};
|
|
397
|
+
const drop = (spare) => spare.session.dispose().catch(() => {});
|
|
398
|
+
return {
|
|
399
|
+
/** How many are started (booted or booting). */
|
|
400
|
+
get count() {
|
|
401
|
+
return spares.length;
|
|
402
|
+
},
|
|
403
|
+
/** Keep `size` spares while `on` (some served webhook is isolated), none otherwise. */
|
|
404
|
+
want(on) {
|
|
405
|
+
wanted = on && !closed ? size : 0;
|
|
406
|
+
for (const spare of spares.splice(wanted)) drop(spare);
|
|
407
|
+
refill();
|
|
408
|
+
},
|
|
409
|
+
/** The oldest spare's session (its replacement starts), or null. */
|
|
410
|
+
take() {
|
|
411
|
+
if (closed) return null;
|
|
412
|
+
for (let spare; (spare = spares.shift()); ) {
|
|
413
|
+
if (spare.failed) {
|
|
414
|
+
drop(spare);
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
refill();
|
|
418
|
+
return spare.session;
|
|
419
|
+
}
|
|
420
|
+
refill();
|
|
421
|
+
return null;
|
|
422
|
+
},
|
|
423
|
+
/** Stop every spare (threads still starting finish starting, then stop). */
|
|
424
|
+
async close() {
|
|
425
|
+
closed = true;
|
|
426
|
+
wanted = 0;
|
|
427
|
+
await Promise.all(spares.splice(0).map(drop));
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// ── one served canvas ───────────────────────────────────────────────────────
|
|
433
|
+
|
|
434
|
+
const plainJSON = (value) => {
|
|
435
|
+
try {
|
|
436
|
+
const text = JSON.stringify(value);
|
|
437
|
+
return text !== undefined && isDeepStrictEqual(JSON.parse(text), value);
|
|
438
|
+
} catch {
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
export { respondOutcome }; // (src/run/respond-outcome.js: the browser's virtual server reads a respond pane the same way)
|
|
444
|
+
|
|
445
|
+
/** How many isolated requests' instances a canvas keeps open for approvers at once (more end with their request, as without the operator page). */
|
|
446
|
+
const MAX_HELD = 16;
|
|
447
|
+
const MAX_HELD_PER_PERSON = 4; // under --identity: one person's share of the instances kept open for approvers
|
|
448
|
+
const MAX_QUEUED_PER_PERSON = 16; // and of the queue
|
|
449
|
+
const SERVED_LOG_MAX = 500; // entries a canvas keeps of what it answered (the served log)
|
|
450
|
+
const HELD_POLL_MS = 250;
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* The decision panes with proposals waiting in a live canvas and in the subgraph panes inside it, in pane order:
|
|
454
|
+
* `{ address, names, canvas, id, pend }`. `address` is the ids of the subgraph panes down to the pane, then its own, joined by "/"
|
|
455
|
+
* (`sg/deep/d`; the namespace of the live canvas left off); `names` are their names; `canvas` and `id` are where the pane lives
|
|
456
|
+
* (an inner canvas's panes are its own). A repeater's live instances are walked: the address has the instance's segment
|
|
457
|
+
* (`rep/@a/d`) and the names its item's key (`rows › a › pane`).
|
|
458
|
+
* @param {{ canvas: object, ns: string }} live
|
|
459
|
+
*/
|
|
460
|
+
function* waitingDecisions(live) {
|
|
461
|
+
const local = (id) => (id.startsWith(live.ns) ? id.slice(live.ns.length) : id);
|
|
462
|
+
function* walk(canvas, ids, names) {
|
|
463
|
+
for (const [id, pane] of canvas.panes) {
|
|
464
|
+
if (!canvas.attached.has(id) || pane.disabled) continue;
|
|
465
|
+
if (pane.type === "decision" && canvas.decisions.has(id)) {
|
|
466
|
+
const pend = canvas.decisions.pending(id);
|
|
467
|
+
if (pend.instances.length) yield { address: [...ids, local(id)].join(SEP), names: [...names, pane.name || local(id)], canvas, id, pend };
|
|
468
|
+
} else if (pane.type === "subgraph") {
|
|
469
|
+
if (repeatOn(pane)) {
|
|
470
|
+
for (const inst of canvas.repeaters?.get(id)?.instances.values() ?? []) {
|
|
471
|
+
if (inst.state === "live" && !inst.canvas.disposed) yield* walk(inst.canvas, [...ids, local(id), inst.seg], [...names, pane.name || local(id), keyLabel(inst.key, inst.index)]);
|
|
472
|
+
}
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
const inner = canvas.subgraphs.get(id);
|
|
476
|
+
if (inner && !inner.disposed) yield* walk(inner, [...ids, local(id)], [...names, pane.name || local(id)]);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
yield* walk(live.canvas, [], []);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const hasWaitingDecision = (live) => !waitingDecisions(live).next().done;
|
|
484
|
+
|
|
485
|
+
/** What waits for a person in a copy now, as `{ text, pane }` (src/headless/mcp-endpoint.js says no to a call that adds one, or that acts on a pane that has one): a decision pane's proposal, a machine's approval card. */
|
|
486
|
+
function pendingApprovals(live) {
|
|
487
|
+
const out = [];
|
|
488
|
+
for (const { address, names, pend } of waitingDecisions(live)) for (const i of pend.instances) out.push({ text: `decision ${names.join(" › ")} (${address}, ${i.id})`, pane: address.split(SEP)[0] });
|
|
489
|
+
for (const p of machineApprovals.value.pending) if (p.canvas === live.canvas) out.push({ text: `approval for machine ${live.canvas.panes.get(p.id)?.name || p.id}`, pane: String(p.id).startsWith(live.ns) ? String(p.id).slice(live.ns.length) : String(p.id) });
|
|
490
|
+
return out;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** The canvas and pane id of the decision pane at `address` (see waitingDecisions) in a live canvas, or undefined. */
|
|
494
|
+
function locateDecision(live, address) {
|
|
495
|
+
const parts = String(address).split(SEP);
|
|
496
|
+
let canvas = live.canvas;
|
|
497
|
+
const walkable = parts.slice(0, -1);
|
|
498
|
+
for (let i = 0; i < walkable.length; i++) {
|
|
499
|
+
const seg = walkable[i];
|
|
500
|
+
const rep = canvas.repeaters?.get(live.ns + seg);
|
|
501
|
+
if (rep) {
|
|
502
|
+
// a repeater pane is followed by an instance's segment, which is not a subgraph pane's id (`@` never starts one)
|
|
503
|
+
const inst = rep.instances.get(walkable[++i]);
|
|
504
|
+
canvas = inst?.state === "live" ? inst.canvas : undefined;
|
|
505
|
+
} else canvas = canvas.subgraphs.get(live.ns + seg);
|
|
506
|
+
if (!canvas || canvas.disposed) return undefined;
|
|
507
|
+
}
|
|
508
|
+
const id = live.ns + parts.at(-1);
|
|
509
|
+
return canvas.attached.has(id) && canvas.decisions.has(id) ? { canvas, id } : undefined;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** The agent pane a parked run's key names, in a doc (the key is the pane's id; a pane inside a subgraph is not resumable here). */
|
|
513
|
+
const parkedPane = (doc, key) => (doc.panes ?? []).find((p) => p && String(p.id) === String(key));
|
|
514
|
+
|
|
515
|
+
/** What stops a canvas that runs only on its schedule: anything that would serve or run it outside a grant bundle. */
|
|
516
|
+
export function scheduledPlanProblem(plan) {
|
|
517
|
+
if (plan.webhooks?.length) return "a scheduled canvas can't have webhook or router panes: it runs only on its schedule";
|
|
518
|
+
if (plan.wsProxies?.length) return "a scheduled canvas can't proxy WebSockets: it runs only on its schedule";
|
|
519
|
+
if (plan.watches?.length) return "a scheduled canvas can't have watch panes: it runs only on its schedule";
|
|
520
|
+
if (plan.timers) return "a scheduled canvas can't have timer panes: it runs only on its schedule";
|
|
521
|
+
return "";
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
class CanvasHost {
|
|
525
|
+
constructor(server, { route, file, doc, plan, revision }) {
|
|
526
|
+
this.server = server;
|
|
527
|
+
this.revision = revision ?? { ...revisionOf(doc), published: false, pinned: false }; // what the monitor says this canvas runs
|
|
528
|
+
this.route = route;
|
|
529
|
+
this.file = file;
|
|
530
|
+
this.doc = doc; // as in the file (what a reload compares with)
|
|
531
|
+
this.plan = plan;
|
|
532
|
+
this.lanes = []; // the shared instance's copies (plan.lanes)
|
|
533
|
+
this.slots = []; // isolated requests' places: --concurrency of them, each with its own worker thread
|
|
534
|
+
this.servedLog = { entries: [], seq: 0, owners: new WeakMap() }; // the requests this canvas answered (RTE-10), newest last, redacted: a traffic pane set to the served log shows them
|
|
535
|
+
this.held = new Map(); // id -> an isolated request's instance kept open while a decision pane in it awaits an approver (--decide-env)
|
|
536
|
+
this.heldSeq = 0;
|
|
537
|
+
this.queue = [];
|
|
538
|
+
this.timerWaiting = new Set();
|
|
539
|
+
this.watchers = [];
|
|
540
|
+
this.next = null; // a reload waiting for every lane to be free
|
|
541
|
+
this.pumping = false;
|
|
542
|
+
this.closed = false;
|
|
543
|
+
// A route the operator gave a --grant: what its grant lets its runs reach and spend (bound in #bindDoc), and whether the grant is refusing it.
|
|
544
|
+
this.granted = server.options.grants?.routes.has(route) ? { hosts: [], refusal: null } : null;
|
|
545
|
+
this.scheduled = Boolean(server.options.schedules?.list.some((x) => x.canvas === route)); // runs only on its schedule, inside a grant bundle: no shared instance (docs/design/scheduled-runs.md)
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
async start() {
|
|
549
|
+
const lanes = this.scheduled ? 0 : (this.plan.lanes ?? this.server.options.concurrency);
|
|
550
|
+
for (let index = 0; index < lanes; index++) await this.#addLane(this.doc, "start");
|
|
551
|
+
// Waits kept for copies this server doesn't run (it was started with a smaller --concurrency): left in the file, said here.
|
|
552
|
+
for (const n of this.server.state.lanesWithWaits?.(this.route) ?? []) if (n >= lanes) this.server.warn(`${this.route}: kept waits of copy ${n + 1} were not restored: this server runs ${lanes} cop${lanes === 1 ? "y" : "ies"} of the canvas (they stay in the --state file for a start with a larger --concurrency)`);
|
|
553
|
+
this.#syncSlots();
|
|
554
|
+
this.#watchFolders();
|
|
555
|
+
this.#pump();
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** A worker session for this route: a --grant route gets one confined to its grant (below), any other the server's own. */
|
|
559
|
+
#newSession() {
|
|
560
|
+
return (this.granted && this.server.options.createRouteSession?.({ route: this.route, hosts: () => this.granted.hosts })) || this.server.options.createSession();
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* A --grant route's runs get the bounds a scheduled run's do (docs/design/scheduled-runs.md 5b): the canvas is bound by its grant (the cost cap shared out between its agent and
|
|
565
|
+
* machine panes, their wall clock capped, a pane the grant does not cover or a costed pane inside a subgraph or repeater refused), and its sessions reach only the grant's hosts that
|
|
566
|
+
* --allow-host also lists, never --allow-all-hosts or --allow-local. Returns the doc to open; when the grant is not good the doc as it is, no network, and a refusal that the route's
|
|
567
|
+
* authority repeats for every agent and machine pane.
|
|
568
|
+
*/
|
|
569
|
+
async #bindDoc(doc) {
|
|
570
|
+
const g = this.server.options.grants;
|
|
571
|
+
const id = g?.routes.get(this.route);
|
|
572
|
+
if (!id || !this.granted) return doc;
|
|
573
|
+
const state = this.granted;
|
|
574
|
+
state.hosts = [];
|
|
575
|
+
state.refusal = null;
|
|
576
|
+
try {
|
|
577
|
+
const now = this.server.options.clock.now();
|
|
578
|
+
const verdict = await g.provider?.resolve?.({ bundle: id, schedule: `route ${this.route}`, canvas: this.route, doc: structuredClone(doc), now });
|
|
579
|
+
const accepted = acceptBundle(verdict ?? { ok: false, code: "no-bundle", reason: "this server has no grants to check" }, { bundle: id, now });
|
|
580
|
+
if (!accepted.ok) return void (state.refusal = { code: accepted.code ?? "no-bundle", reason: accepted.reason }) ?? doc;
|
|
581
|
+
const bound = boundDoc(doc, accepted.bundle);
|
|
582
|
+
if (!bound.ok) return void (state.refusal = { code: "pane", reason: bound.reason }) ?? doc;
|
|
583
|
+
state.hosts = intersectHosts(g.serverHosts ?? [], Boolean(g.allowAll), accepted.bundle.hosts);
|
|
584
|
+
return bound.doc;
|
|
585
|
+
} catch (error) {
|
|
586
|
+
state.refusal = { code: "ledger", reason: `the grant could not be checked (${String(error?.message ?? error).slice(0, 120)})` };
|
|
587
|
+
return doc;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** The costed (agent and machine) panes of a running copy, by instance key. */
|
|
592
|
+
#costed(c) {
|
|
593
|
+
return [...c.attached].filter((id) => spendCapsOf(c.panes.get(id)?.type));
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** A new copy of the shared instance, started. */
|
|
597
|
+
async #addLane(doc, cause) {
|
|
598
|
+
doc = await this.#bindDoc(doc);
|
|
599
|
+
const lane = { index: this.lanes.length, session: this.#newSession(), live: null, busy: true };
|
|
600
|
+
this.lanes.push(lane);
|
|
601
|
+
this.#open(lane, doc);
|
|
602
|
+
await this.#run(lane, { kind: "start", cause });
|
|
603
|
+
lane.busy = false;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Isolated requests' places: --concurrency of them while a webhook is
|
|
608
|
+
* isolated, none otherwise. Each has its own worker thread, reused by one
|
|
609
|
+
* request after another (--isolate-threads: a new thread per request, a
|
|
610
|
+
* spare one when there is one).
|
|
611
|
+
*/
|
|
612
|
+
#syncSlots() {
|
|
613
|
+
const { concurrency, isolateThreads } = this.server.options;
|
|
614
|
+
const createSession = () => this.#newSession();
|
|
615
|
+
const want = this.plan.webhooks.some((w) => w.isolated) ? concurrency : 0;
|
|
616
|
+
while (this.slots.length < want) this.slots.push({ index: this.slots.length, session: isolateThreads ? null : createSession(), busy: false });
|
|
617
|
+
for (const slot of this.slots.splice(want)) {
|
|
618
|
+
if (slot.busy) slot.gone = true; // its request finishes first
|
|
619
|
+
else slot.session?.dispose().catch(() => {});
|
|
620
|
+
}
|
|
621
|
+
this.server.syncSpares();
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** Open the canvas in a lane (and seed what a reload carries over). */
|
|
625
|
+
#open(lane, doc, carry = { timers: [] }) {
|
|
626
|
+
const gate = (g) => this.#timerTick(g);
|
|
627
|
+
lane.live = lane.session.open(doc, { stateStore: this.server.state.forCanvas(this.route), timers: { live: true, gate }, serving: true, clock: this.server.options.canvasClock, mcpRoots: this.server.mcpRoots });
|
|
628
|
+
this.#background(lane.live, doc);
|
|
629
|
+
this.#keepHistory(lane.live);
|
|
630
|
+
// A2A push notifications for this copy's A2A agent panes: each update reruns the pane in a job on this copy.
|
|
631
|
+
if (this.server.push && this.plan.a2a) lane.live.canvas.a2aPush = this.server.push.source(this.route, { schedule: (fire, cause) => this.#pushJob(lane, fire, cause) });
|
|
632
|
+
this.#keepWaits(lane); // each copy's pending waits are kept (the copies of --concurrency N share nothing, so each keeps its own)
|
|
633
|
+
const clock = lane.live.canvas.timerClock;
|
|
634
|
+
for (const [id, value, missed] of carry.timers) {
|
|
635
|
+
clock.values.set(lane.live.key(id), value);
|
|
636
|
+
if (missed) clock.missed.set(lane.live.key(id), missed);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Every instance of a served canvas that is not a scheduled run is a background run as far as a model is concerned: a webhook or router request, a timer or interval pane, an
|
|
642
|
+
* --mcp tool, a --watch-dir reload, an A2A push, the start itself, a person's own approval through --decide-env or --identity (who answers a request, not who runs it).
|
|
643
|
+
* Each is marked unattended with THIS route's authority, which the operator named (--grant ROUTE=ID), never the canvas: its agent and machine panes then ask `begin()` before
|
|
644
|
+
* any model, and with no grant named they are refused with code `no-bundle`. `--allow-ungranted-agents` leaves a route with no grant as it was before (unmarked).
|
|
645
|
+
* Marked here, at the only two places a served instance is opened for requests, so no path (a lane, an isolated copy, a held copy, a reload) reaches a pane unmarked.
|
|
646
|
+
*/
|
|
647
|
+
#background(live, doc) {
|
|
648
|
+
const grants = this.server.options.grants ?? { routes: new Map(), provider: null, allowUngranted: false };
|
|
649
|
+
const bundle = grants.routes.get(this.route);
|
|
650
|
+
const refused = (code, reason, pane) => this.server.record({ at: new Date(this.server.options.clock.now()).toISOString(), canvas: this.route, cause: "background run", outcome: "refused", code, note: reason, error: reason, ...(pane ? { pane } : {}) });
|
|
651
|
+
if (!bundle) {
|
|
652
|
+
if (grants.allowUngranted) return;
|
|
653
|
+
markUnattended(live.canvas, {
|
|
654
|
+
begin: async ({ paneId }) => {
|
|
655
|
+
const reason = `An unattended run was refused: no grant is named for the route "${this.route}" (mallory serve --grant ${this.route}=GRANT_ID; mallory grant create makes one).`;
|
|
656
|
+
refused("no-bundle", reason, String(paneId).replace(/^r\d+:/, ""));
|
|
657
|
+
return { ok: false, code: "no-bundle", reason };
|
|
658
|
+
},
|
|
659
|
+
});
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (this.granted?.refusal) {
|
|
663
|
+
const { code, reason } = this.granted.refusal;
|
|
664
|
+
markUnattended(live.canvas, {
|
|
665
|
+
begin: async ({ paneId }) => {
|
|
666
|
+
const full = `An unattended run was refused: ${reason}.`.replace("..", ".");
|
|
667
|
+
refused(code, `${code}: ${full}`, String(paneId).replace(/^r\d+:/, ""));
|
|
668
|
+
return { ok: false, code, reason: full };
|
|
669
|
+
},
|
|
670
|
+
});
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
// The grant's authority pins the canvas as it is now (a reload gets a new one), so it is made when the first pane asks.
|
|
674
|
+
const snapshot = structuredClone(doc);
|
|
675
|
+
let made;
|
|
676
|
+
markUnattended(live.canvas, {
|
|
677
|
+
begin: async (request) => {
|
|
678
|
+
try {
|
|
679
|
+
made ??= grants.provider?.authority?.({ schedule: { id: `route ${this.route}`, canvas: this.route, bundle }, doc: snapshot, onRefused: (r) => refused(r.code, `${r.code}: ${r.reason}`, r.pane) });
|
|
680
|
+
if (!made) return { ok: false, code: "no-bundle", reason: "An unattended run was refused: this server has no grants to check (mallory grant keygen --state …)." };
|
|
681
|
+
return await (await made).begin(request);
|
|
682
|
+
} catch (error) {
|
|
683
|
+
return { ok: false, code: "ledger", reason: `An unattended run was refused: the grant could not be checked (${String(error?.message ?? error).slice(0, 120)}).` };
|
|
684
|
+
}
|
|
685
|
+
},
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** The traffic history (--traffic-history): a proxying http pane in this instance records its exchanges through it, and only it can (#968). */
|
|
690
|
+
#keepHistory(live, person) {
|
|
691
|
+
const adapter = this.server.options.trafficHistory?.(this.route, person); // (with --identity a person's records are kept under their own key)
|
|
692
|
+
if (adapter) live.canvas.trafficHistory = adapter;
|
|
693
|
+
const { owners } = this.servedLog;
|
|
694
|
+
// With --identity an instance sees only the served-log entries its own person's requests made (an operator's instance, only the untagged ones).
|
|
695
|
+
live.canvas.servedLog = { entries: () => (this.server.options.identity ? this.servedLog.entries.filter((e) => owners.get(e) === person) : this.servedLog.entries) };
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* The proxied sockets of one ws-client pane (`label`), as entries of the served log (src/headless/ws-proxy.js makes them, redacted): they replace the
|
|
700
|
+
* pane's earlier ones, a traffic pane set to the served log and the pane itself are run again, and the connections that have ended go to the
|
|
701
|
+
* traffic history (--traffic-history) once.
|
|
702
|
+
*/
|
|
703
|
+
recordSockets(label, entries, finished = []) {
|
|
704
|
+
if (this.closed) return;
|
|
705
|
+
const log = this.servedLog.entries;
|
|
706
|
+
for (let i = log.length - 1; i >= 0; i--) if (log[i].method === "WS" && log[i].pane === label) log.splice(i, 1);
|
|
707
|
+
log.push(...entries);
|
|
708
|
+
for (const lane of this.lanes) if (lane.live && !lane.live.canvas.disposed) notifyServed(lane.live.canvas);
|
|
709
|
+
if (finished.length) {
|
|
710
|
+
const adapter = this.server.options.trafficHistory?.(this.route);
|
|
711
|
+
const id = this.lanes[0]?.live?.canvas.id ?? this.route;
|
|
712
|
+
Promise.resolve(adapter?.record(id, finished)).catch(() => {});
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** A request the canvas answered, as an entry of the served log: made here, from the request and the reply the server saw (never from a pane). */
|
|
717
|
+
#logServed(job, entry) {
|
|
718
|
+
const served = job.served;
|
|
719
|
+
const log = this.servedLog;
|
|
720
|
+
const made = servedExchange({ id: `srv-${++log.seq}`, at: served.at, request: { method: job.request.method, target: served.target, host: served.host, headers: served.headers, bytes: served.bytes, ...(served.body ? { body: servedBodyView(served.body) } : {}) }, response: served.response(), route: served.route, ms: entry.ms, outcome: entry.outcome === "stuck" ? "timeout" : entry.outcome });
|
|
721
|
+
log.entries.push(made);
|
|
722
|
+
if (job.person) log.owners.set(made, job.person);
|
|
723
|
+
if (log.entries.length > SERVED_LOG_MAX) log.entries.splice(0, log.entries.length - SERVED_LOG_MAX);
|
|
724
|
+
for (const lane of this.lanes) if (lane.live && !lane.live.canvas.disposed) notifyServed(lane.live.canvas);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** A pushed A2A update's rerun, as a job on `lane` (the copy whose pane registered); a full queue tries again in a second. */
|
|
728
|
+
#pushJob(lane, fire, cause) {
|
|
729
|
+
if (this.closed || this.lanes[lane.index] !== lane) return;
|
|
730
|
+
const job = { kind: "push", lane: lane.index, cause, fire: () => lane.live && fire() };
|
|
731
|
+
if (!this.submit(job)) setTimeout(() => this.#pushJob(lane, fire, cause), 1000).unref?.();
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** Under --identity: how many of this person's requests hold a parked instance or wait in the queue. */
|
|
735
|
+
personLoad(person) {
|
|
736
|
+
const running = this.slots.filter((x) => x.person === person).length;
|
|
737
|
+
return { held: [...this.held.values()].filter((h) => !h.closed && h.owner === person).length + running, queued: this.queue.filter((j) => j.person === person).length };
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** Under --identity: may this person start another request? A reason when not (the caller answers 429). */
|
|
741
|
+
personQuota(person) {
|
|
742
|
+
const { held, queued } = this.personLoad(person);
|
|
743
|
+
if (this.server.options.operator && (held + queued >= MAX_HELD_PER_PERSON || this.held.size >= MAX_HELD)) return `too many of your requests are awaiting a decision (${MAX_HELD_PER_PERSON} at most): answer or cancel one first`;
|
|
744
|
+
if (queued >= MAX_QUEUED_PER_PERSON) return "too many of your requests are queued: wait for some to finish";
|
|
745
|
+
return undefined;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** Queue a job; false when the queue is full. */
|
|
749
|
+
submit(job) {
|
|
750
|
+
if (this.closed || this.queue.length >= this.server.options.queueSize) return false;
|
|
751
|
+
this.queue.push(job);
|
|
752
|
+
this.#pump();
|
|
753
|
+
return true;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* The machine panes of this canvas the person opted in to be served as models (`modelEndpoint`, `mallory serve --model-endpoint`):
|
|
758
|
+
* `[{ id, label, cell, maxChars }]`. A machine without the setting is never served. Read from the canvas as in its file.
|
|
759
|
+
*/
|
|
760
|
+
modelPanes() {
|
|
761
|
+
return (this.doc.panes ?? [])
|
|
762
|
+
.filter((p) => p && typeof p === "object" && p.machine && typeof p.machine === "object" && p.modelEndpoint && typeof p.modelEndpoint === "object")
|
|
763
|
+
.map((p) => {
|
|
764
|
+
const cells = Array.isArray(p.machine.tape?.cells) ? p.machine.tape.cells : [];
|
|
765
|
+
const cell = typeof p.modelEndpoint.cell === "string" && p.modelEndpoint.cell ? p.modelEndpoint.cell : cells[0]?.id;
|
|
766
|
+
return { id: p.id, label: String(p.name || p.id), cell, maxChars: p.machine.schema?.content?.maxChars };
|
|
767
|
+
})
|
|
768
|
+
.filter((m) => m.cell);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** The panes of this canvas that the person opted in to serve over MCP (`serveMcp: true`, or named by --mcp-panes): `[{ id, name, type }]`, read from the canvas as in its file. */
|
|
772
|
+
mcpPanes() {
|
|
773
|
+
return optedPanes(this.doc, this.server.options.mcp?.panes ?? []);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/** Run one of the MCP tools (src/headless/mcp-endpoint.js) as a job on the first copy: `{ tool, args }` resolves an MCP tool result (`isError` for any refusal). */
|
|
777
|
+
askMcp({ tool, args }) {
|
|
778
|
+
return new Promise((resolve) => {
|
|
779
|
+
const failed = (text) => resolve({ content: [{ type: "text", text }], isError: true });
|
|
780
|
+
const label = String(args?.pane ?? "").replace(/[^\x20-\x7e]/g, "?").slice(0, 60);
|
|
781
|
+
const job = { kind: "mcp", lane: 0, tool, args, cause: `mcp ${tool.replace(/^mallory_/, "")}${label ? ` ${label}` : ""}`, reply: (r) => (r?.content ? resolve(r) : failed(r?.kind === "gone" ? "The canvas is not running." : "The call took too long, and was stopped.")) };
|
|
782
|
+
if (!this.submit(job)) failed("The canvas is busy: too many calls are waiting.");
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** Run model `pane` for one request: the conversation goes into `cell`. Resolves `{ kind: "answer" | "halt" | "error" | "gone" | "busy" | "timeout", … }`. */
|
|
787
|
+
askModel({ pane, cell, text, request }) {
|
|
788
|
+
return new Promise((resolve) => {
|
|
789
|
+
const label = this.modelPanes().find((m) => m.id === pane)?.label ?? pane;
|
|
790
|
+
const job = { kind: "model", pane, inject: { [cell]: text }, cause: `model ${label}`, request, reply: resolve };
|
|
791
|
+
if (!this.submit(job)) resolve({ kind: "busy" });
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
get busy() {
|
|
796
|
+
return this.lanes.some((l) => l.busy) || this.slots.some((s) => s.busy) || [...this.held.values()].some((h) => h.busy) || this.queue.length > 0 || Boolean(this.next);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** Where a job runs: an isolated webhook's request in a slot, the rest on a lane; "gone" when nothing can run it now. */
|
|
800
|
+
#placeOf(job) {
|
|
801
|
+
if (job.isolated !== undefined) return this.held.has(job.isolated) ? "held" : "gone"; // (an operator's answer: the instance that holds the proposal)
|
|
802
|
+
if (job.kind === "webhook") {
|
|
803
|
+
const hook = this.plan.webhooks.find((h) => h.key === job.hook);
|
|
804
|
+
if (!hook) return "gone";
|
|
805
|
+
if (hook.isolated) return "slot";
|
|
806
|
+
}
|
|
807
|
+
if (job.lane !== undefined) return this.lanes[job.lane] ? "lane" : "gone"; // (an operator's answer: the copy that holds the proposal)
|
|
808
|
+
return this.lanes.length ? "lane" : "gone";
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** The first queued job that can start now, with the free lane or slot it starts on (or undefined). */
|
|
812
|
+
#startable() {
|
|
813
|
+
for (let i = 0; i < this.queue.length; i++) {
|
|
814
|
+
const place = this.#placeOf(this.queue[i]);
|
|
815
|
+
const job = this.queue[i];
|
|
816
|
+
const free = place === "gone" ? {} : (place === "held" ? [this.held.get(job.isolated)] : place === "slot" ? this.slots : job.lane !== undefined ? [this.lanes[job.lane]] : this.lanes).find((x) => !x.busy);
|
|
817
|
+
if (free) return { i, place, free };
|
|
818
|
+
}
|
|
819
|
+
return undefined;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
#pump() {
|
|
823
|
+
if (this.pumping || this.closed) return;
|
|
824
|
+
this.pumping = true;
|
|
825
|
+
queueMicrotask(async () => {
|
|
826
|
+
try {
|
|
827
|
+
await this.#drain();
|
|
828
|
+
} catch (error) {
|
|
829
|
+
this.server.warn(`${this.route}: ${error.message}`);
|
|
830
|
+
} finally {
|
|
831
|
+
this.pumping = false;
|
|
832
|
+
}
|
|
833
|
+
if (!this.closed && (this.next ? !this.lanes.some((l) => l.busy) : this.#startable())) this.#pump();
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
async #drain() {
|
|
838
|
+
for (;;) {
|
|
839
|
+
if (this.closed) return;
|
|
840
|
+
if (this.next) {
|
|
841
|
+
if (this.lanes.some((l) => l.busy)) return; // when the last one finishes, it pumps again
|
|
842
|
+
await this.#reloadNow();
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
const next = this.#startable();
|
|
846
|
+
if (!next) return;
|
|
847
|
+
const [job] = this.queue.splice(next.i, 1);
|
|
848
|
+
if (next.place === "gone") {
|
|
849
|
+
job.reply?.({ kind: "gone" });
|
|
850
|
+
continue;
|
|
851
|
+
}
|
|
852
|
+
const at = next.free;
|
|
853
|
+
at.busy = true;
|
|
854
|
+
(next.place === "held" ? this.#runHeld(at, job) : next.place === "slot" ? this.#runIsolated(at, job) : this.#run(at, job)).finally(() => {
|
|
855
|
+
at.busy = false;
|
|
856
|
+
if (at.gone) at.session?.dispose().catch(() => {});
|
|
857
|
+
this.#pump();
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/**
|
|
863
|
+
* An isolated request: a new instance of the canvas, as in its file,
|
|
864
|
+
* with its own state (kept state from a copy of the --state values, never
|
|
865
|
+
* written back), on the slot's worker thread (or, --isolate-threads, a
|
|
866
|
+
* spare thread started ahead, else a new one). Its timers don't tick and
|
|
867
|
+
* its watch panes get nothing. It is closed once the job ends: its runs,
|
|
868
|
+
* values, timers and onCleanup()s go with it (and its thread, with
|
|
869
|
+
* --isolate-threads).
|
|
870
|
+
*/
|
|
871
|
+
async #runIsolated(slot, job) {
|
|
872
|
+
const threads = !slot.session;
|
|
873
|
+
const doc = await this.#bindDoc(this.doc); // (before the session, so a --grant route's session starts with its grant's hosts)
|
|
874
|
+
const session = slot.session ?? (this.granted ? null : this.server.spares.take()) ?? this.#newSession(); // (a spare thread is the server's own, with the server's network: never for a --grant route)
|
|
875
|
+
const mode = threads ? "thread" : "instance";
|
|
876
|
+
let live;
|
|
877
|
+
let kept = false;
|
|
878
|
+
slot.person = job.person; // (counted against the person's share while it runs: personQuota)
|
|
879
|
+
try {
|
|
880
|
+
live = session.open(doc, { stateStore: this.server.state.isolated(this.route), timers: { live: true, gate: (g) => g.miss() }, serving: true, mcpRoots: this.server.mcpRoots });
|
|
881
|
+
this.#background(live, doc);
|
|
882
|
+
this.#keepHistory(live, job.person);
|
|
883
|
+
await this.#run({ live, session }, job, { isolated: mode });
|
|
884
|
+
kept = this.#hold({ live, session, threads, mode, owner: job.person });
|
|
885
|
+
slot.person = undefined;
|
|
886
|
+
} catch (error) {
|
|
887
|
+
job.reply?.({ kind: "error", error: error.message }); // a canvas that can't open (the sandbox didn't start)
|
|
888
|
+
this.server.warn(`${this.route}: ${job.cause}: ${error.message}`);
|
|
889
|
+
} finally {
|
|
890
|
+
slot.person = undefined;
|
|
891
|
+
if (!kept) {
|
|
892
|
+
live?.close();
|
|
893
|
+
if (threads) await session.dispose().catch(() => {});
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* One scheduled run (docs/design/scheduled-runs.md): a new instance of `doc` (the canvas as served, already bound by the grant bundle), on a session
|
|
900
|
+
* whose network is `allowHosts`, with its parks kept in `--state`; closed when the job ends. `resume`: `{ pane, choice, text? }` instead starts the
|
|
901
|
+
* instance so the parked run finds its record, and gives the person's answer. `authority`: what decides each pane's run (src/autonomy/enforce.js through the grant provider); null refuses all. Resolves `{ outcome, error? }`: "done", "error", "stuck", or for a
|
|
902
|
+
* resume "gone" or "stale".
|
|
903
|
+
*/
|
|
904
|
+
async runScheduled({ schedule, doc, allowHosts, deadlineMs, resume, authority = null }) {
|
|
905
|
+
const { server } = this;
|
|
906
|
+
const session = server.options.createScheduledSession({ allowHosts });
|
|
907
|
+
const job = { kind: "scheduled", cause: `schedule ${schedule.id}${resume ? " (answered)" : ""}`, deadlineMs, ...(resume ? { resume } : {}) };
|
|
908
|
+
let live;
|
|
909
|
+
try {
|
|
910
|
+
if (resume) {
|
|
911
|
+
// A pane changed since the park (or a kind of park we can't resume) is refused before an instance can start the run over.
|
|
912
|
+
const rec = server.state.parkOf(this.route, schedule.id, resume.pane);
|
|
913
|
+
if (!rec) return { outcome: "gone" };
|
|
914
|
+
const pane = parkedPane(doc, resume.pane);
|
|
915
|
+
if (!pane) return { outcome: "gone" };
|
|
916
|
+
if (rec.docFingerprint !== fingerprintOf(pane)) { // (the settings as served now against as served when it parked; the agent's own check, on the pane it builds, would start the run over)
|
|
917
|
+
server.state.setPark(this.route, schedule.id, resume.pane, undefined);
|
|
918
|
+
return { outcome: "stale" };
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
live = session.open(doc, { stateStore: server.state.isolated(this.route), timers: { live: true, gate: (g) => g.miss() }, serving: true });
|
|
922
|
+
// Nobody is here: every agent and machine pane of this instance asks `authority.begin()` before it asks a model anything, and with no authority (or one that refuses)
|
|
923
|
+
// none of them runs. This is the one place a scheduled run is opened, for a fire and for an answer to a parked run alike (test/scheduled-grant.test.mjs).
|
|
924
|
+
markUnattended(live.canvas, authority);
|
|
925
|
+
live.canvas.root.parkStore = parkStoreOver(server.state, this.route, schedule.id, { onChange: () => server.saveState(), tag: (pane) => { const p = parkedPane(doc, pane); return p ? { docFingerprint: fingerprintOf(p) } : {}; } });
|
|
926
|
+
live.canvas.servedLog = { entries: () => [] };
|
|
927
|
+
// Each agent or machine pane runs once (twice for the pane an answer resumes): a run past that would spend a new cap. The session is ended at once.
|
|
928
|
+
const c = live.canvas;
|
|
929
|
+
const costed = (doc.panes ?? []).filter((p) => p && spendCapsOf(p.type)).map((p) => live.key(String(p.id)));
|
|
930
|
+
const limiter = createRunLimiter({ keys: new Set(costed), resumed: resume ? live.key(resume.pane) : undefined, onOverrun: (key) => ((job.overrun = key), session.dispose().catch(() => {})) }); // (ending the session is what stops a run that is still going: closing the canvas does not)
|
|
931
|
+
c.addEventListener("state", (e) => {
|
|
932
|
+
const id = e.detail?.id;
|
|
933
|
+
if (id === undefined || !costed.includes(id)) return;
|
|
934
|
+
const v = c.stateOf(id)?.value;
|
|
935
|
+
if (v?.status === "running" && v.runId !== undefined) limiter.observe(id, v.runId);
|
|
936
|
+
});
|
|
937
|
+
await this.#run({ live }, job, { isolated: "instance" });
|
|
938
|
+
if (job.overrun) return { outcome: "overrun", error: `${job.overrun.replace(/^r\d+:/, "")} ran more often than its bundle allows` };
|
|
939
|
+
} catch (error) {
|
|
940
|
+
server.warn(`${this.route}: ${job.cause}: ${error.message}`);
|
|
941
|
+
return { outcome: "error", error: error.message };
|
|
942
|
+
} finally {
|
|
943
|
+
live?.close();
|
|
944
|
+
await session.dispose().catch(() => {});
|
|
945
|
+
}
|
|
946
|
+
if (resume && job.resumed === false) return { outcome: "gone" };
|
|
947
|
+
const entry = job.entry;
|
|
948
|
+
if (!entry) return { outcome: "error", error: "the run did not finish" };
|
|
949
|
+
return { outcome: entry.outcome, ...(entry.error ? { error: entry.error } : {}), ...(entry.outcome === "error" ? { error: entry.panes.find((p) => p.status === "error")?.error } : {}) };
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/** Give the person's answer to the parked agent pane `resume.pane` of a live instance; false when it isn't parked there. */
|
|
953
|
+
#answerPark(live, { pane, choice, text }) {
|
|
954
|
+
const c = live.canvas;
|
|
955
|
+
const id = live.key(pane);
|
|
956
|
+
if (!c.attached.has(id) || !parkedRequest(c, id)) return false;
|
|
957
|
+
return answerParked(c, id, choice, { text });
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* With the operator page (--decide-env), an isolated request's instance stays open while a decision pane in it
|
|
962
|
+
* awaits an approver, and closes once none does (answered, cancelled or timed out): its proposals end with it.
|
|
963
|
+
* Returns whether it was kept (false: the caller closes it, as for any isolated request).
|
|
964
|
+
*/
|
|
965
|
+
#hold({ live, session, threads, mode, owner }) {
|
|
966
|
+
if (this.closed || !this.server.options.operator || !hasWaitingDecision(live)) return false;
|
|
967
|
+
if (this.held.size >= MAX_HELD || (owner !== undefined && [...this.held.values()].filter((h) => !h.closed && h.owner === owner).length >= MAX_HELD_PER_PERSON)) {
|
|
968
|
+
this.server.warn(`${this.route}: ${MAX_HELD} isolated requests already await a decision: this one's proposal ends with its request`);
|
|
969
|
+
return false;
|
|
970
|
+
}
|
|
971
|
+
const entry = { id: `i${++this.heldSeq}`, live, session, threads, mode, owner, busy: false, closed: false, timer: null }; // (`owner`: the verified person whose request parked it, under --identity)
|
|
972
|
+
this.held.set(entry.id, entry);
|
|
973
|
+
this.#watchHeld(entry);
|
|
974
|
+
this.#announce();
|
|
975
|
+
return true;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/** Close a held instance once nothing in it awaits an approver (a deadline ends a proposal outside any job, so it is looked at on a timer). */
|
|
979
|
+
#watchHeld(entry) {
|
|
980
|
+
const { clock } = this.server.options;
|
|
981
|
+
const schedule = () => {
|
|
982
|
+
entry.timer = clock.setTimer(tick, HELD_POLL_MS);
|
|
983
|
+
entry.timer?.unref?.();
|
|
984
|
+
};
|
|
985
|
+
const tick = async () => {
|
|
986
|
+
entry.timer = null;
|
|
987
|
+
if (entry.closed || this.closed) return;
|
|
988
|
+
if (!entry.busy && !hasWaitingDecision(entry.live)) {
|
|
989
|
+
entry.busy = true; // an answer that arrives now finds it gone, not half closed
|
|
990
|
+
try {
|
|
991
|
+
await this.#closeIfDone(entry);
|
|
992
|
+
} finally {
|
|
993
|
+
entry.busy = false;
|
|
994
|
+
this.#pump();
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
if (!entry.closed && !this.closed) schedule();
|
|
998
|
+
};
|
|
999
|
+
schedule();
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** Close a held instance if no decision pane in it awaits an approver (the caller holds `entry.busy`): the panes after an ended proposal settle first. */
|
|
1003
|
+
async #closeIfDone(entry) {
|
|
1004
|
+
if (entry.closed || hasWaitingDecision(entry.live)) return false;
|
|
1005
|
+
const { clock, jobDeadlineMs } = this.server.options;
|
|
1006
|
+
await entry.live.settle(jobDeadlineMs, clock).catch(() => {});
|
|
1007
|
+
if (hasWaitingDecision(entry.live)) return false;
|
|
1008
|
+
await this.#closeHeld(entry);
|
|
1009
|
+
this.#announce();
|
|
1010
|
+
return true;
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
async #closeHeld(entry) {
|
|
1014
|
+
if (entry.closed) return;
|
|
1015
|
+
entry.closed = true;
|
|
1016
|
+
if (entry.timer !== null) this.server.options.clock.clearTimer?.(entry.timer);
|
|
1017
|
+
entry.timer = null;
|
|
1018
|
+
this.held.delete(entry.id);
|
|
1019
|
+
entry.live.close();
|
|
1020
|
+
if (entry.threads) await entry.session.dispose().catch(() => {});
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** An approver's answer to a held instance: the same job as on a lane, without starting the canvas again. */
|
|
1024
|
+
async #runHeld(entry, job) {
|
|
1025
|
+
try {
|
|
1026
|
+
await this.#run(entry, job, { isolated: entry.mode, held: true });
|
|
1027
|
+
await this.#closeIfDone(entry);
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
job.reply?.({ kind: "error", error: error.message });
|
|
1030
|
+
this.server.warn(`${this.route}: ${job.cause}: ${error.message}`);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Run one job on a lane: start it, wait for the canvas to settle, answer,
|
|
1036
|
+
* release, save state, log. `isolated`: the lane is a new instance made for
|
|
1037
|
+
* this job, which starts first (the run log's lines for that are the
|
|
1038
|
+
* request's too).
|
|
1039
|
+
*/
|
|
1040
|
+
async #run(lane, job, { isolated, held = false } = {}) {
|
|
1041
|
+
const live = lane.live;
|
|
1042
|
+
const c = live.canvas;
|
|
1043
|
+
const clock = this.server.options.clock;
|
|
1044
|
+
const startedAt = clock.now();
|
|
1045
|
+
const deadline = job.deadlineMs ?? this.server.options.jobDeadlineMs;
|
|
1046
|
+
const left = () => Math.max(1, startedAt + deadline - clock.now());
|
|
1047
|
+
// The last job's request was its own run's alone: its pane skips now, so a change this job makes upstream of what read it doesn't handle it again.
|
|
1048
|
+
// (A request an open stream holds stays the webhook's value until the last of its streams ends: the stream's feed reads it.)
|
|
1049
|
+
// (A pushed A2A update's rerun retires nothing: the task a request started goes on after it, and its pane keeps
|
|
1050
|
+
// reading that request until the next job of another kind.)
|
|
1051
|
+
const retiring = job.kind === "push" ? [] : [...new Set([...(lane.spent ?? []), ...(lane.ended ?? [])])].filter((key) => !lane.streaming?.get(key));
|
|
1052
|
+
if (job.kind !== "push") lane.ended?.clear();
|
|
1053
|
+
if (retiring.length) {
|
|
1054
|
+
for (const key of retiring) c.retire(key);
|
|
1055
|
+
lane.spent = [];
|
|
1056
|
+
await live.settle(left(), clock).catch(() => {});
|
|
1057
|
+
}
|
|
1058
|
+
live.logs.splice(0);
|
|
1059
|
+
live.caught.splice(0);
|
|
1060
|
+
const before = new Map([...c.attached].map((id) => [id, c.stateOf(id).value.runId]));
|
|
1061
|
+
const seq = live.seq;
|
|
1062
|
+
const revision = this.revision.id; // the revision this job starts on (a reload waits for the lanes)
|
|
1063
|
+
const delivered = [];
|
|
1064
|
+
let finalCheck = () => {};
|
|
1065
|
+
let stuck;
|
|
1066
|
+
// A --grant route's job (one webhook request, one timer tick, one MCP call, one watch event, the start) runs each of its agent and machine panes once: a second run would spend a new
|
|
1067
|
+
// cap each time, so the bound the grant puts on a job (its cost cap shared out between them) would not hold. The copy's worker is ended and the job ends as `overrun`.
|
|
1068
|
+
let overrun;
|
|
1069
|
+
let onSpend;
|
|
1070
|
+
if (this.granted) {
|
|
1071
|
+
const costed = this.#costed(c);
|
|
1072
|
+
const limiter = createRunLimiter({ keys: new Set(costed), onOverrun: (key) => ((overrun = key), lane.session.dispose().catch(() => {})) });
|
|
1073
|
+
onSpend = (e) => {
|
|
1074
|
+
const id = e.detail?.id;
|
|
1075
|
+
if (id === undefined || !costed.includes(id)) return;
|
|
1076
|
+
const v = c.stateOf(id)?.value;
|
|
1077
|
+
if (v?.status === "running" && v.runId !== undefined) limiter.observe(id, v.runId);
|
|
1078
|
+
};
|
|
1079
|
+
c.addEventListener("state", onSpend);
|
|
1080
|
+
}
|
|
1081
|
+
c.hint(job.cause, { strong: true }); // the run log's cause (src/model/runlog.js): "webhook /orders/new", "timer clock", …
|
|
1082
|
+
try {
|
|
1083
|
+
if (isolated && !held) {
|
|
1084
|
+
live.start();
|
|
1085
|
+
await live.settle(left(), clock);
|
|
1086
|
+
c.hint(job.cause, { strong: true });
|
|
1087
|
+
}
|
|
1088
|
+
if (job.kind === "start") {
|
|
1089
|
+
live.start();
|
|
1090
|
+
this.#restoreWaits(lane);
|
|
1091
|
+
} else if (job.kind === "timer" || job.kind === "push") job.fire();
|
|
1092
|
+
else if (job.kind === "scheduled") {
|
|
1093
|
+
// A resumed parked run: the instance has started, the agent pane found its record and is showing the question; the person's answer goes in now.
|
|
1094
|
+
if (job.resume) job.resumed = this.#answerPark(live, job.resume);
|
|
1095
|
+
}
|
|
1096
|
+
else if (job.kind === "webhook") {
|
|
1097
|
+
const hook = this.plan.webhooks.find((h) => h.key === job.hook);
|
|
1098
|
+
const key = hook && live.key(hook.id);
|
|
1099
|
+
const held = hook?.output ? portId(key, hook.output) : key; // what stays delivered (to a router: its route's output)
|
|
1100
|
+
if (!hook || !c.attached.has(key)) job.reply({ kind: "gone" });
|
|
1101
|
+
else {
|
|
1102
|
+
const rkey = hook.respond && live.key(hook.respond);
|
|
1103
|
+
if (rkey) {
|
|
1104
|
+
const runBefore = c.stateOf(rkey).value.runId;
|
|
1105
|
+
const check = (final) => {
|
|
1106
|
+
const outcome = respondOutcome(c.stateOf(rkey).value, runBefore, final);
|
|
1107
|
+
if (!outcome) return;
|
|
1108
|
+
c.removeEventListener("state", onState);
|
|
1109
|
+
job.reply(outcome.stream && !isolated ? { ...outcome, follow: (listener) => this.#follow(lane, held, rkey, listener), lane } : outcome);
|
|
1110
|
+
};
|
|
1111
|
+
const onState = (e) => e.detail?.id === rkey && check(false);
|
|
1112
|
+
c.addEventListener("state", onState);
|
|
1113
|
+
finalCheck = () => check(true);
|
|
1114
|
+
}
|
|
1115
|
+
c.deliver(key, job.value);
|
|
1116
|
+
delivered.push(held);
|
|
1117
|
+
}
|
|
1118
|
+
} else if (job.kind === "model") {
|
|
1119
|
+
// A request to `--model-endpoint`: the conversation goes onto the machine's tape and it runs once, under its own gates and caps; the reply is its final head cell.
|
|
1120
|
+
const key = live.key(job.pane);
|
|
1121
|
+
if (!c.attached.has(key)) job.reply({ kind: "gone" });
|
|
1122
|
+
else {
|
|
1123
|
+
runServed(c, key, job.inject);
|
|
1124
|
+
finalCheck = () => {
|
|
1125
|
+
const out = servedOutcome(c, key);
|
|
1126
|
+
job.reply(out.ok ? { kind: "answer", text: out.text, usage: out.usage } : out.haltKind ? { kind: "halt", haltKind: out.haltKind, reason: out.reason } : { kind: "error", error: out.error });
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
} else if (job.kind === "mcp") {
|
|
1130
|
+
// A call of `--mcp` (src/headless/mcp-endpoint.js): one of its tools, on this copy, in order with the rest. A refusal or a failure is the call's result, never the job's.
|
|
1131
|
+
let answered = false;
|
|
1132
|
+
const reply = (r) => {
|
|
1133
|
+
if (!answered) job.reply(r);
|
|
1134
|
+
answered = true;
|
|
1135
|
+
};
|
|
1136
|
+
try {
|
|
1137
|
+
reply(await runTool({ live, panes: this.mcpPanes(), tool: job.tool, args: job.args, route: this.route, pending: () => pendingApprovals(live) }));
|
|
1138
|
+
} catch (error) {
|
|
1139
|
+
reply({ content: [{ type: "text", text: `Error: ${String(error?.message ?? error).slice(0, 300)}` }], isError: true });
|
|
1140
|
+
}
|
|
1141
|
+
} else if (job.kind === "decision") {
|
|
1142
|
+
// An approver's answer from the operator page (src/headless/operator.js): the same checks as the editor's form.
|
|
1143
|
+
const { decision, values, prompt, voter, instance } = job.answer;
|
|
1144
|
+
const at = locateDecision(live, job.paneId);
|
|
1145
|
+
job.reply(at ? at.canvas.decisions.answer(at.id, { instance, decision, values, voter, prompt, source: "operator" }) : { kind: "gone" });
|
|
1146
|
+
} else if (job.kind === "watch") {
|
|
1147
|
+
const key = live.key(job.paneId);
|
|
1148
|
+
if (c.attached.has(key)) {
|
|
1149
|
+
c.deliver(key, job.value);
|
|
1150
|
+
delivered.push(key);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
await live.settle(left(), clock);
|
|
1154
|
+
finalCheck();
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
stuck = error;
|
|
1157
|
+
job.reply?.({ kind: "timeout" });
|
|
1158
|
+
} finally {
|
|
1159
|
+
if (onSpend) c.removeEventListener("state", onSpend);
|
|
1160
|
+
for (const key of delivered) if (!lane.streaming?.get(key)) c.release(key);
|
|
1161
|
+
}
|
|
1162
|
+
if (overrun) job.reply?.({ kind: "timeout" });
|
|
1163
|
+
if (overrun) stuck = new Error(`${String(overrun).replace(/^r\d+:/, "")} ran more often than its grant allows in one ${job.kind === "webhook" ? "request" : "job"}, so the run was closed`);
|
|
1164
|
+
if (!isolated && job.kind !== "push") lane.spent = stuck ? [] : delivered.filter((key) => !lane.streaming?.get(key)); // the requests this run handled: the next job makes their panes skip first
|
|
1165
|
+
const ran = [...c.attached].filter((id) => c.stateOf(id).value.runId !== before.get(id)); // the panes this job ran (or skipped, or held)
|
|
1166
|
+
const panes = ran.map((id) => live.state(id.slice(live.ns.length))).map(({ id, ...rest }) => rest);
|
|
1167
|
+
const errors = panes.filter((p) => p.status === "error");
|
|
1168
|
+
const tag = isolated ? { isolated } : {};
|
|
1169
|
+
const entry = {
|
|
1170
|
+
at: new Date(startedAt).toISOString(),
|
|
1171
|
+
canvas: this.route,
|
|
1172
|
+
cause: job.cause,
|
|
1173
|
+
...(job.request ? { request: job.request } : {}),
|
|
1174
|
+
...(job.person ? { person: job.person } : {}),
|
|
1175
|
+
...tag,
|
|
1176
|
+
...(job.http?.() ? { http: job.http() } : {}),
|
|
1177
|
+
outcome: overrun ? "overrun" : stuck ? "stuck" : errors.length ? "error" : "done",
|
|
1178
|
+
ms: clock.now() - startedAt,
|
|
1179
|
+
panes,
|
|
1180
|
+
...(live.logs.length ? { logs: live.logs.splice(0) } : {}),
|
|
1181
|
+
...(live.caught.length ? { caught: live.caught.splice(0) } : {}),
|
|
1182
|
+
...(stuck ? { error: stuck.message } : {}),
|
|
1183
|
+
};
|
|
1184
|
+
// The log file gets the run log's own lines ( 's format, as mallory run --log writes them), with the job's facts.
|
|
1185
|
+
const runs = this.server.options.logFile || this.server.options.monitor ? await live.runsSince(seq).catch(() => []) : [];
|
|
1186
|
+
this.server.options.monitor?.record(this.route, { at: entry.at, cause: entry.cause, outcome: entry.outcome, http: entry.http, isolated: Boolean(isolated), ms: entry.ms, revision }, runs);
|
|
1187
|
+
job.entry = entry;
|
|
1188
|
+
if (job.served) this.#logServed(job, entry);
|
|
1189
|
+
if (job.person) this.server.people.addRun(job.person, { at: entry.at, canvas: this.route, cause: entry.cause, http: entry.http, outcome: entry.outcome, ms: entry.ms });
|
|
1190
|
+
this.server.record(entry, runs.map((run) => ({ canvas: this.route, ...(entry.request ? { request: entry.request } : {}), ...tag, ...(entry.http ? { http: entry.http } : {}), outcome: entry.outcome, ...run })));
|
|
1191
|
+
if (isolated) return; // its state goes with it: nothing to save, nothing to start again
|
|
1192
|
+
this.#collectWaits(lane);
|
|
1193
|
+
this.#announce();
|
|
1194
|
+
await this.server.saveState();
|
|
1195
|
+
if (stuck && !this.closed) {
|
|
1196
|
+
// Runs still going after the deadline: start this lane's canvas again.
|
|
1197
|
+
this.server.streams.closeAll(lane);
|
|
1198
|
+
lane.live.close();
|
|
1199
|
+
if (overrun) lane.session = this.#newSession(); // (the copy's worker thread was ended to stop the run)
|
|
1200
|
+
this.#open(lane, await this.#bindDoc(this.doc));
|
|
1201
|
+
await this.#run(lane, { kind: "start", cause: "restart (stuck)" });
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/**
|
|
1206
|
+
* Follow a streaming respond pane in a copy of the canvas: `listener` hears each later run of the pane (a frame, an
|
|
1207
|
+
* error, or the end of the stream when it stops streaming); returns the function that stops listening. While any
|
|
1208
|
+
* stream follows, the request that opened it stays the webhook's value (`held`), so the feed it reads goes on.
|
|
1209
|
+
*/
|
|
1210
|
+
#follow(lane, held, rkey, listener) {
|
|
1211
|
+
const c = lane.live.canvas;
|
|
1212
|
+
let last = c.stateOf(rkey).value.runId;
|
|
1213
|
+
const onState = (e) => {
|
|
1214
|
+
if (e.detail?.id !== rkey) return;
|
|
1215
|
+
const state = c.stateOf(rkey).value;
|
|
1216
|
+
if (state.runId === last || state.stale) return;
|
|
1217
|
+
if (state.status === "done" && state.result?.response) {
|
|
1218
|
+
last = state.runId;
|
|
1219
|
+
listener(state.result.stream ? { kind: "frame", response: state.result.response } : { kind: "end" });
|
|
1220
|
+
} else if (state.status === "error") {
|
|
1221
|
+
last = state.runId;
|
|
1222
|
+
listener({ kind: "error" });
|
|
1223
|
+
} else if (state.status === "skipped") last = state.runId; // nothing to send this time
|
|
1224
|
+
};
|
|
1225
|
+
c.addEventListener("state", onState);
|
|
1226
|
+
lane.streaming ??= new Map();
|
|
1227
|
+
lane.streaming.set(held, (lane.streaming.get(held) ?? 0) + 1);
|
|
1228
|
+
let stopped = false;
|
|
1229
|
+
return () => {
|
|
1230
|
+
if (stopped) return;
|
|
1231
|
+
stopped = true;
|
|
1232
|
+
c.removeEventListener("state", onState);
|
|
1233
|
+
const left = (lane.streaming.get(held) ?? 1) - 1;
|
|
1234
|
+
if (left > 0) return lane.streaming.set(held, left);
|
|
1235
|
+
lane.streaming.delete(held);
|
|
1236
|
+
(lane.ended ??= new Set()).add(held); // the next job lets go of the request
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
// ── decisions for the operator page (--decide-env) ────────────────────────
|
|
1241
|
+
|
|
1242
|
+
/**
|
|
1243
|
+
* The proposals awaiting a person in this canvas's copies, in decision panes on the canvas and inside its subgraph panes,
|
|
1244
|
+
* and in the isolated requests' instances kept open for them: `[{ lane | isolated, pane, name, path, title, required, fields, prompt, instances }]`.
|
|
1245
|
+
* `pane` is the pane's address (its id; inside subgraph panes their ids and then its, joined by "/"), `path` its names for a person
|
|
1246
|
+
* (canvas › subgraph › pane, an isolated request's instance after the canvas). Rows are the pane's `show`, bounded; never the whole proposal.
|
|
1247
|
+
*/
|
|
1248
|
+
pendingDecisions(viewer = { all: true }) {
|
|
1249
|
+
const out = [];
|
|
1250
|
+
const add = (live, where, via) => {
|
|
1251
|
+
const c = live?.canvas;
|
|
1252
|
+
if (!c || c.disposed) return;
|
|
1253
|
+
for (const { address, names, canvas, id, pend } of waitingDecisions(live)) {
|
|
1254
|
+
const settings = decideSettings(canvas.waits.rawOf(id));
|
|
1255
|
+
out.push({ ...where, pane: address, name: names.at(-1), path: [this.route, ...via, ...names].join(" › "), title: pend.title, required: pend.required, fields: pend.fields, prompt: pend.prompt, instances: pend.instances.map((i) => ({ id: i.id, key: i.key, rows: proposalRows(settings, i.start), deadlineAt: i.deadlineAt ?? null, ballots: i.ballots })) });
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
// A verified person (`viewer.person`) sees only the instances their own requests parked; the operator's approvers (`all`) see every one.
|
|
1259
|
+
if (viewer.all) for (const lane of this.lanes) add(lane.live, { lane: lane.index }, []);
|
|
1260
|
+
for (const entry of this.held.values()) if (!entry.closed && (viewer.all || (viewer.person !== undefined && entry.owner === viewer.person))) add(entry.live, { isolated: entry.id }, [`isolated ${entry.id}`]);
|
|
1261
|
+
return out;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
/**
|
|
1265
|
+
* An approver's answer, queued as a job on the copy (`lane`) or the isolated request's instance (`isolated`) that holds the
|
|
1266
|
+
* proposal: resolves with CanvasDecisions.answer's result, or `{ kind }` when it couldn't run. `pane` is an address from pendingDecisions.
|
|
1267
|
+
*/
|
|
1268
|
+
decide({ lane, isolated, pane, instance, decision, values, prompt, voter, person }) {
|
|
1269
|
+
// `person` (a verified identity answering): only an instance their own request parked. Anything else is "gone", the same answer as for a proposal that doesn't exist.
|
|
1270
|
+
if (person !== undefined && (isolated === undefined || this.held.get(isolated)?.owner !== person)) return Promise.resolve({ kind: "gone" });
|
|
1271
|
+
const live = isolated !== undefined ? this.held.get(isolated)?.live : this.lanes[lane]?.live;
|
|
1272
|
+
const at = live && locateDecision(live, pane);
|
|
1273
|
+
if (!at) return Promise.resolve({ kind: "gone" });
|
|
1274
|
+
const name = at.canvas.panes.get(at.id)?.name || String(pane).split(SEP).at(-1);
|
|
1275
|
+
return new Promise((resolve) => {
|
|
1276
|
+
const job = { kind: "decision", ...(isolated !== undefined ? { isolated } : { lane }), paneId: pane, answer: { instance, decision, values, prompt, voter }, cause: `decision ${name} by ${voter}`, reply: (r) => (person !== undefined && r?.ok && this.server.people.addApproval(person, { at: new Date().toISOString(), canvas: this.route, pane: String(pane), decision, state: r.state }), resolve(r)) };
|
|
1277
|
+
if (!this.submit(job)) resolve({ kind: "busy" });
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
/** Tell the operator (the notification file) which proposals are waiting now. */
|
|
1282
|
+
#announce() {
|
|
1283
|
+
this.server.options.operator?.announce(this.route, this.pendingDecisions());
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// ── pending waits across a restart (--state) ──────────────────────────────
|
|
1287
|
+
|
|
1288
|
+
#strip = (lane) => (id) => (id.startsWith(lane.live.ns) ? id.slice(lane.live.ns.length) : id);
|
|
1289
|
+
|
|
1290
|
+
/** Keep a copy of the canvas's pending waits in the state holder as they change (a deadline that ends one runs outside any job). */
|
|
1291
|
+
#keepWaits(lane) {
|
|
1292
|
+
if (!this.lanes.includes(lane)) return; // (a request isolated in a place of its own keeps nothing)
|
|
1293
|
+
const c = lane.live.canvas;
|
|
1294
|
+
let timer = null;
|
|
1295
|
+
const later = () => {
|
|
1296
|
+
if (this.closed || timer !== null) return;
|
|
1297
|
+
const { clock } = this.server.options;
|
|
1298
|
+
timer = clock.setTimer(() => {
|
|
1299
|
+
timer = null;
|
|
1300
|
+
if (lane.live?.canvas !== c || c.disposed) return;
|
|
1301
|
+
this.#collectWaits(lane);
|
|
1302
|
+
this.server.saveState();
|
|
1303
|
+
}, 250);
|
|
1304
|
+
timer?.unref?.();
|
|
1305
|
+
};
|
|
1306
|
+
c.addEventListener("waits", later);
|
|
1307
|
+
c.addEventListener("wait", later);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
/** The canvas's pending waits into the state holder (written by saveState when it changed). */
|
|
1311
|
+
#collectWaits(lane) {
|
|
1312
|
+
const c = lane.live?.canvas;
|
|
1313
|
+
if (!c || c.disposed || !this.lanes.includes(lane)) return;
|
|
1314
|
+
this.server.state.setWaits(this.route, collectCheckpoints(c, { strip: this.#strip(lane) }), lane.index);
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
/** The kept waits back into the canvas that just started: each pane's checkpoint, or why it wasn't. Said on stdout (a receipt per pane). */
|
|
1318
|
+
#restoreWaits(lane) {
|
|
1319
|
+
if (!this.lanes.includes(lane)) return;
|
|
1320
|
+
const saved = this.server.state.waitsFor(this.route, lane.index);
|
|
1321
|
+
if (!Object.keys(saved).length) return;
|
|
1322
|
+
const live = lane.live;
|
|
1323
|
+
const at = new Date(this.server.options.clock.now()).toISOString().slice(11, 19);
|
|
1324
|
+
const receipts = restoreCheckpoints(live.canvas, saved, { strip: this.#strip(lane), add: (id) => live.ns + id });
|
|
1325
|
+
for (const r of receipts) {
|
|
1326
|
+
if (r.ok) this.server.options.stdout(`${at} ${this.route}${lane.index ? ` (copy ${lane.index + 1})` : ""} ${r.name}: ${describeReceipt(r)}`);
|
|
1327
|
+
else this.server.warn(`${this.route}${lane.index ? ` (copy ${lane.index + 1})` : ""}: ${r.name}: ${describeReceipt(r)}`);
|
|
1328
|
+
}
|
|
1329
|
+
this.#collectWaits(lane); // what was refused or has ended is no longer kept
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/** A timer's tick (TimerClock gate): queued, unless a tick of that timer is already waiting (then it is missed). */
|
|
1333
|
+
#timerTick(g) {
|
|
1334
|
+
const key = g.id;
|
|
1335
|
+
if (this.timerWaiting.has(key)) return g.miss();
|
|
1336
|
+
const name = g.canvas.panes.get(g.id)?.name || g.id;
|
|
1337
|
+
const job = {
|
|
1338
|
+
kind: "timer",
|
|
1339
|
+
cause: `timer ${name.replace(/^r\d+:/, "")}`,
|
|
1340
|
+
fire: () => {
|
|
1341
|
+
this.timerWaiting.delete(key);
|
|
1342
|
+
g.fire();
|
|
1343
|
+
},
|
|
1344
|
+
};
|
|
1345
|
+
if (this.submit(job)) this.timerWaiting.add(key);
|
|
1346
|
+
else g.miss();
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
#watchFolders() {
|
|
1350
|
+
for (const w of this.watchers.splice(0)) w.close();
|
|
1351
|
+
for (const w of this.plan.watches) {
|
|
1352
|
+
this.watchers.push(
|
|
1353
|
+
watchFolder({
|
|
1354
|
+
root: w.root,
|
|
1355
|
+
path: w.path,
|
|
1356
|
+
settings: w.settings,
|
|
1357
|
+
onError: (error) => this.server.warn(`${this.route}: watch pane ${w.name}: ${error.message}`),
|
|
1358
|
+
onEvent: (event) => {
|
|
1359
|
+
const value = { ...event, dir: w.settings.dir, id: randomUUID() };
|
|
1360
|
+
const ok = this.submit({ kind: "watch", cause: `watch ${w.settings.dir}/${event.name} ${event.event}`, paneId: w.id, value });
|
|
1361
|
+
if (!ok) this.server.record({ at: new Date().toISOString(), canvas: this.route, cause: `watch ${w.settings.dir}/${event.name} ${event.event}`, outcome: "dropped", note: "the queue is full" });
|
|
1362
|
+
},
|
|
1363
|
+
}),
|
|
1364
|
+
);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
/** The file changed and its new version checks out: reload once every lane is free (isolated requests in progress keep the version they started with). */
|
|
1369
|
+
reload(doc, plan, revision) {
|
|
1370
|
+
if (this.scheduled) {
|
|
1371
|
+
const why = scheduledPlanProblem(plan);
|
|
1372
|
+
if (why) return void this.server.warn(`${this.route}: the new version was not loaded: ${why}`);
|
|
1373
|
+
}
|
|
1374
|
+
this.next = { doc, plan, revision };
|
|
1375
|
+
this.#pump();
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
async #reloadNow() {
|
|
1379
|
+
const { doc, plan, revision } = this.next;
|
|
1380
|
+
this.next = null;
|
|
1381
|
+
const want = this.scheduled ? 0 : (plan.lanes ?? this.server.options.concurrency);
|
|
1382
|
+
for (const lane of this.lanes.splice(want)) {
|
|
1383
|
+
this.server.streams.closeAll(lane);
|
|
1384
|
+
lane.live.close();
|
|
1385
|
+
await lane.session.dispose();
|
|
1386
|
+
}
|
|
1387
|
+
for (const lane of this.lanes) {
|
|
1388
|
+
lane.busy = true;
|
|
1389
|
+
const carry = await this.#carry(lane, doc);
|
|
1390
|
+
carry.doc = await this.#bindDoc(carry.doc);
|
|
1391
|
+
this.#collectWaits(lane); // the reloaded canvas gets them back (or says why not)
|
|
1392
|
+
this.server.streams.closeAll(lane);
|
|
1393
|
+
lane.live.close();
|
|
1394
|
+
this.#open(lane, carry.doc, carry);
|
|
1395
|
+
await this.#run(lane, { kind: "start", cause: "reload" });
|
|
1396
|
+
lane.busy = false;
|
|
1397
|
+
}
|
|
1398
|
+
while (this.lanes.length < want) await this.#addLane(doc, "reload");
|
|
1399
|
+
this.doc = doc;
|
|
1400
|
+
this.plan = plan;
|
|
1401
|
+
this.revision = revision ?? { ...revisionOf(doc), published: false, pinned: false };
|
|
1402
|
+
this.#syncSlots();
|
|
1403
|
+
this.#watchFolders();
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
/**
|
|
1407
|
+
* What a reload keeps: each timer's last tick (when its schedule didn't
|
|
1408
|
+
* change) and each session state pane's value (when its initial code didn't
|
|
1409
|
+
* change and the value is plain JSON). Kept state panes read their store.
|
|
1410
|
+
*/
|
|
1411
|
+
async #carry(lane, newDoc) {
|
|
1412
|
+
const { live } = lane;
|
|
1413
|
+
const c = live.canvas;
|
|
1414
|
+
const old = new Map(this.doc.panes.map((p) => [p.id, p]));
|
|
1415
|
+
const doc = structuredClone(newDoc);
|
|
1416
|
+
const timers = [];
|
|
1417
|
+
for (const p of doc.panes) {
|
|
1418
|
+
const was = old.get(p.id);
|
|
1419
|
+
if (!was || was.type !== p.type) continue;
|
|
1420
|
+
const key = live.key(p.id);
|
|
1421
|
+
if (p.type === "timer" && isDeepStrictEqual(was.timer, p.timer) && c.timerClock.values.has(key)) timers.push([p.id, c.timerClock.values.get(key), c.timerClock.missed.get(key) ?? 0]);
|
|
1422
|
+
if (p.type === "state" && !isPersisted(p) && was.code === p.code && c.stateOf(key).value.status === "done") {
|
|
1423
|
+
try {
|
|
1424
|
+
const [value] = await c.runtime.clone([key]);
|
|
1425
|
+
if (plainJSON(value)) p.code = JSON.stringify(value);
|
|
1426
|
+
} catch {
|
|
1427
|
+
// not a value that can leave the sandbox: it starts again from its code
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
return { doc, timers };
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
async close() {
|
|
1435
|
+
this.closed = true;
|
|
1436
|
+
for (const w of this.watchers.splice(0)) w.close();
|
|
1437
|
+
for (const job of this.queue.splice(0)) job.reply?.({ kind: "gone" });
|
|
1438
|
+
const deadline = Date.now() + 10000;
|
|
1439
|
+
while ([...this.lanes, ...this.slots, ...this.held.values()].some((l) => l.busy) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 25));
|
|
1440
|
+
for (const lane of this.lanes) {
|
|
1441
|
+
this.#collectWaits(lane); // pending waits are kept for the next start
|
|
1442
|
+
this.server.streams.closeAll(lane);
|
|
1443
|
+
lane.live?.close();
|
|
1444
|
+
await lane.session.dispose();
|
|
1445
|
+
}
|
|
1446
|
+
for (const entry of [...this.held.values()]) await this.#closeHeld(entry); // (before its slot's thread goes)
|
|
1447
|
+
for (const slot of this.slots) await slot.session?.dispose().catch(() => {});
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// ── the HTTP server ─────────────────────────────────────────────────────────
|
|
1452
|
+
|
|
1453
|
+
const STATUS_TEXT = { 202: "accepted", 204: "", 400: "bad request", 401: "unauthorized", 403: "forbidden", 404: "not found", 405: "method not allowed", 413: "request body too large", 429: "too many requests", 500: "the canvas failed to answer", 503: "the canvas isn't available", 504: "the canvas didn't answer in time" };
|
|
1454
|
+
|
|
1455
|
+
/** Read a request's body, up to `limit` bytes (rejects with status 413 beyond). */
|
|
1456
|
+
function readBody(req, limit) {
|
|
1457
|
+
return new Promise((resolve, reject) => {
|
|
1458
|
+
const declared = Number(req.headers["content-length"]);
|
|
1459
|
+
if (Number.isFinite(declared) && declared > limit) return reject(Object.assign(new Error("too large"), { status: 413 }));
|
|
1460
|
+
const chunks = [];
|
|
1461
|
+
let size = 0;
|
|
1462
|
+
req.on("data", (chunk) => {
|
|
1463
|
+
size += chunk.length;
|
|
1464
|
+
if (size > limit) {
|
|
1465
|
+
req.removeAllListeners("data");
|
|
1466
|
+
reject(Object.assign(new Error("too large"), { status: 413 }));
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
chunks.push(chunk);
|
|
1470
|
+
});
|
|
1471
|
+
req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
|
|
1472
|
+
req.on("error", reject);
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
/**
|
|
1477
|
+
* Start serving canvases. Resolves once listening, with `{ url, port, host,
|
|
1478
|
+
* routes, close() }`.
|
|
1479
|
+
*
|
|
1480
|
+
* @param {{
|
|
1481
|
+
* canvases: { file: string, route: string, doc: object, plan: object }[],
|
|
1482
|
+
* host?: string, port?: number,
|
|
1483
|
+
* auth?: ReturnType<typeof createAuth>, cors?: string,
|
|
1484
|
+
* createSession: () => import("../run/run.js").HeadlessSession,
|
|
1485
|
+
* concurrency?: number, isolateThreads?: boolean, spareThreads?: number, queueSize?: number, requestTimeoutMs?: number, jobDeadlineMs?: number, maxBodyKB?: number,
|
|
1486
|
+
* clock?: { now: () => number, setTimer: Function, clearTimer: Function },
|
|
1487
|
+
* canvasClock?: { now: () => number, setTimer?: Function, clearTimer?: Function }, // (tests) the clock the served canvases' own deadlines run on, apart from the job clock above
|
|
1488
|
+
* watchDirs?: Map<string, string>,
|
|
1489
|
+
* state?: { holder: ReturnType<typeof stateHolder>, file?: string, readonly?: boolean, write?: Function },
|
|
1490
|
+
* logFile?: string, secrets?: string[],
|
|
1491
|
+
* version?: string, // what GET /health reports (the CLI passes the app's version; absent: null)
|
|
1492
|
+
* sockets?: { allowHosts?: string[], allowAllHosts?: boolean, allowLocal?: boolean, secrets?: Map<string, { value: string, hosts: string[] }>, resolve?: Function }, // the WebSocket proxies' reach (src/headless/ws-proxy.js): the same flags as the canvases' fetch
|
|
1493
|
+
* trafficHistory?: (route: string) => { record: Function }, // --traffic-history FILE: what a served canvas's `trafficHistory` is (src/headless/traffic-history-file.js): proxied exchanges, redacted, are recorded; nothing is read back by a canvas
|
|
1494
|
+
* mcp?: { panes: string[] }, // --mcp: the served canvases as an MCP server at /mcp (needs a bearer token); `panes`: --mcp-panes names, besides the panes' own serveMcp setting
|
|
1495
|
+
* historyApi?: ReturnType<typeof import("./history-api.js").historyApi>, // --traffic-history FILE: GET /history, /history/summary, /entry/:id, for the bearer token's holder
|
|
1496
|
+
* monitor?: ReturnType<typeof import("./monitor.js").createMonitor>, // the read-only status endpoint: its own token and origin
|
|
1497
|
+
* operator?: ReturnType<typeof import("./operator.js").createOperator>, // the decision pane operator page: approvers' own tokens, this computer only
|
|
1498
|
+
* remote?: { listen: { host: string, port: number }, identity: object, pages: object, names: string[] }, // --remote-listen (src/headless/runner-remote.js): the monitor, over TLS, to paired pages only
|
|
1499
|
+
* retained?: boolean, // the log file's capture policies are set (--retain …): a line with no run log behind it carries no pane values, console lines or error text
|
|
1500
|
+
* stdout?: (line: string) => void, stderr?: (line: string) => void,
|
|
1501
|
+
* }} options
|
|
1502
|
+
*/
|
|
1503
|
+
export async function startServe(options) {
|
|
1504
|
+
const opts = { host: "127.0.0.1", port: 8787, auth: createAuth(), concurrency: 1, isolateThreads: false, spareThreads: 2, queueSize: 64, requestTimeoutMs: 30000, jobDeadlineMs: 300000, maxStreams: 16, streamMs: 600000, maxBodyKB: 10240, watchDirs: new Map(), stdout: () => {}, stderr: () => {}, ...options };
|
|
1505
|
+
// The clock a job's deadline (jobDeadlineMs) and its time in the log are measured on: the real one, or a test's.
|
|
1506
|
+
opts.clock = { now: Date.now, setTimer: setTimeout, clearTimer: clearTimeout, ...options.clock };
|
|
1507
|
+
const serveStartedAt = opts.clock.now(); // /health's uptime
|
|
1508
|
+
const serveSession = randomUUID(); // /health's `session` (prism's): one id per run of this server, for the readers of the full body only; it opens nothing
|
|
1509
|
+
const wsConnections = createConnectionLog({ now: () => opts.clock.now() }); // GET /ws/connections
|
|
1510
|
+
const scrub = scrubber(opts.secrets ?? []);
|
|
1511
|
+
const binaryHoldsSecret = holdsSecret(opts.secrets ?? []);
|
|
1512
|
+
// --identity cf-access (src/headless/identity.js): a verified Cloudflare Access identity, per-person records, nothing else trusted (docs/design/serve-identity.md).
|
|
1513
|
+
const identity = opts.identity ?? null;
|
|
1514
|
+
if (identity) {
|
|
1515
|
+
for (const entry of opts.canvases) {
|
|
1516
|
+
const shared = entry.plan.webhooks.find((w) => !w.isolated);
|
|
1517
|
+
if (shared) throw new Error(`--identity: ${entry.route}'s webhook ${shared.name} is not isolated, so two people's requests would share one instance (set the route's isolate setting, or serve with --isolate)`);
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
const identityHosts = new Set((opts.identityHosts ?? []).map((h) => String(h).toLowerCase()));
|
|
1521
|
+
const holder = opts.state?.holder ?? stateHolder({}, { routes: opts.canvases.map((c) => c.route) });
|
|
1522
|
+
let logChain = Promise.resolve();
|
|
1523
|
+
let logFailed = false;
|
|
1524
|
+
let logPrivate = false;
|
|
1525
|
+
let saveChain = Promise.resolve();
|
|
1526
|
+
const server = {
|
|
1527
|
+
options: opts,
|
|
1528
|
+
people: createPeople(),
|
|
1529
|
+
state: holder,
|
|
1530
|
+
warn: (text) => opts.stderr(scrub(`mallory serve: ${text}`)),
|
|
1531
|
+
streams: new StreamHub({ max: opts.maxStreams, ms: opts.streamMs, scrub, warn: (text) => opts.stderr(scrub(`mallory serve: ${text}`)) }),
|
|
1532
|
+
/** A run (or a refused request): its line on stdout, errors on stderr, and the log file's lines (`lines`, else the entry itself). */
|
|
1533
|
+
record(entry, lines = [entry]) {
|
|
1534
|
+
const time = entry.at.slice(11, 19);
|
|
1535
|
+
const what = [entry.http ? `→ ${entry.http}` : null, entry.outcome, entry.ms !== undefined ? `${entry.ms} ms` : null].filter(Boolean).join(" ");
|
|
1536
|
+
opts.stdout(scrub(`${time} ${entry.canvas} ${entry.cause}${entry.isolated ? " (isolated)" : ""} ${what}`));
|
|
1537
|
+
for (const p of entry.panes ?? []) if (p.status === "error") opts.stderr(scrub(` ${p.name || p.type}: ${p.error}`));
|
|
1538
|
+
if (entry.error) opts.stderr(scrub(` ${entry.error}`));
|
|
1539
|
+
if (opts.logFile) {
|
|
1540
|
+
const plain = opts.retained ? (({ panes, logs, caught, error, ...rest }) => ({ ...rest, ...(panes ? { panes: panes.length } : {}) }))(entry) : entry; // summary: no pane values, console lines or error text
|
|
1541
|
+
const text = (lines.length ? lines : [plain]).map((l) => scrub(JSON.stringify(l))).join("\n");
|
|
1542
|
+
logChain = logChain
|
|
1543
|
+
.then(async () => {
|
|
1544
|
+
await appendFile(opts.logFile, `${text}\n`, { mode: 0o600 });
|
|
1545
|
+
if (!logPrivate) (await chmod(opts.logFile, 0o600), (logPrivate = true)); // (the log can quote what a run did: the operator's alone, whatever it was made as)
|
|
1546
|
+
})
|
|
1547
|
+
.catch((error) => {
|
|
1548
|
+
if (!logFailed) opts.stderr(`mallory serve: can't write the log ${opts.logFile}: ${error.message}`);
|
|
1549
|
+
logFailed = true;
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
},
|
|
1553
|
+
saveState() {
|
|
1554
|
+
if (!holder.changed || !opts.state?.file || opts.state.readonly) return saveChain;
|
|
1555
|
+
holder.changed = false;
|
|
1556
|
+
const data = holder.toJSON();
|
|
1557
|
+
saveChain = saveChain.then(() => opts.state.write(opts.state.file, data)).catch((error) => opts.stderr(`mallory serve: can't write ${opts.state.file}: ${error.message}`));
|
|
1558
|
+
return saveChain;
|
|
1559
|
+
},
|
|
1560
|
+
};
|
|
1561
|
+
|
|
1562
|
+
// A2A push routes (opts.a2aPush: { publicOrigin?, up? }, or false for none): URLs on the tunnel's public origin (no
|
|
1563
|
+
// tunnel token: the gate lets push paths through on their task's secret) while the tunnel is up (`up()`: a push sent
|
|
1564
|
+
// while it is down would be lost, so the pane streams or polls then), else on this listener (known once it listens,
|
|
1565
|
+
// before any canvas starts).
|
|
1566
|
+
let pushBase;
|
|
1567
|
+
server.push = opts.a2aPush === false ? null : createPushRoutes({ base: () => (opts.a2aPush?.publicOrigin ? (opts.a2aPush.up?.() === false ? undefined : opts.a2aPush.publicOrigin) : pushBase) });
|
|
1568
|
+
server.mcpRoots = serveRootsSource(opts.watchDirs, opts.mcpRootGrants); // the watched folders, offered to MCP servers as roots once approved (#545)
|
|
1569
|
+
const hosts = new Map();
|
|
1570
|
+
// Spare worker threads: only with --isolate-threads, while some served webhook is isolated (each host's slots say so).
|
|
1571
|
+
server.spares = sparePool(opts.createSession, { size: opts.isolateThreads ? opts.spareThreads : 0, warn: server.warn });
|
|
1572
|
+
server.syncSpares = () => server.spares.want([...hosts.values()].some((h) => h.slots.length > 0));
|
|
1573
|
+
if (opts.mcp) {
|
|
1574
|
+
if (!opts.auth.hasBearer) throw new Error("--mcp needs a bearer token (--token-env): its tools run panes");
|
|
1575
|
+
if (opts.canvases.some((c) => c.route === "mcp")) throw new Error('a canvas served as "mcp" would be shadowed by --mcp\'s /mcp: rename the file or serve it without --mcp');
|
|
1576
|
+
}
|
|
1577
|
+
// Scheduled runs (docs/design/scheduled-runs.md): the operator's schedules, each inside a grant bundle, with the parks kept in --state. Checked before anything is built.
|
|
1578
|
+
if (opts.schedules) {
|
|
1579
|
+
if (typeof opts.createScheduledSession !== "function") throw new Error("--schedule-file needs a session maker for scheduled runs (createScheduledSession)");
|
|
1580
|
+
if (!opts.state?.file || opts.state.readonly) throw new Error("--schedule-file needs --state file.json (not read-only): a run that parks, and the runs-per-hour count, are kept there across a restart");
|
|
1581
|
+
for (const sch of opts.schedules.list) {
|
|
1582
|
+
const entry = opts.canvases.find((c) => c.route === sch.canvas);
|
|
1583
|
+
if (!entry) throw new Error(`schedule ${sch.id}: ${sch.canvas} is not a served canvas`);
|
|
1584
|
+
const why = scheduledPlanProblem(entry.plan);
|
|
1585
|
+
if (why) throw new Error(`schedule ${sch.id}: ${sch.canvas}: ${why}`);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
for (const entry of opts.canvases) hosts.set(entry.route, new CanvasHost(server, entry));
|
|
1589
|
+
// Channel adapters (--channels-file; src/headless/channels/): checked before anything listens (a canvas that is served, a webhook that takes POST, the operator's grant), then
|
|
1590
|
+
// /_channels/<id> takes a platform's signed requests and runs the channel's webhook as if it had been called.
|
|
1591
|
+
let channels = null;
|
|
1592
|
+
if (opts.channels?.length) {
|
|
1593
|
+
const notes = checkChannels(opts.channels, { plans: new Map(opts.canvases.map((c) => [c.route, c.plan])), grants: opts.grants });
|
|
1594
|
+
for (const note of notes) opts.stdout(`mallory serve: ${note}`);
|
|
1595
|
+
const dispatchChannel = ({ canvas, path, body }) =>
|
|
1596
|
+
new Promise((resolve) => {
|
|
1597
|
+
const host = hosts.get(canvas);
|
|
1598
|
+
const hook = host && !host.closed ? resolveRoute(host.plan.webhooks, path, "POST").route : null;
|
|
1599
|
+
if (!hook) return resolve({ kind: "gone" });
|
|
1600
|
+
const id = randomUUID();
|
|
1601
|
+
const receivedAt = new Date().toISOString();
|
|
1602
|
+
const given = { method: "POST", path, search: "", headers: { "content-type": "application/json" }, bytes: Buffer.from(JSON.stringify(body)), allowHeaders: hook.settings.headers, id, receivedAt };
|
|
1603
|
+
let done = false;
|
|
1604
|
+
const timer = setTimeout(() => reply({ kind: "timeout" }), opts.requestTimeoutMs);
|
|
1605
|
+
const reply = (outcome) => {
|
|
1606
|
+
if (done) return;
|
|
1607
|
+
done = true;
|
|
1608
|
+
clearTimeout(timer);
|
|
1609
|
+
resolve(outcome);
|
|
1610
|
+
};
|
|
1611
|
+
const job = { kind: "webhook", cause: `channel → /${canvas}/${hook.path}`, hook: hook.key, value: hook.output ? routerRequestValue({ route: hook.output, ...given }) : requestValue(given), request: { id, method: "POST", path: `/${canvas}/${hook.path}` }, http: () => undefined, reply };
|
|
1612
|
+
if (!host.submit(job)) return reply({ kind: "busy" });
|
|
1613
|
+
if (!hook.respond) reply({ kind: "accepted" });
|
|
1614
|
+
});
|
|
1615
|
+
channels = createChannels({ channels: opts.channels, dispatch: dispatchChannel, record: (entry) => server.record(entry), now: () => opts.clock.now(), scrub, stderr: opts.stderr, ...(opts.channelFetch ? { fetch: opts.channelFetch } : {}), ...(opts.channelOptions ?? {}) });
|
|
1616
|
+
opts.monitor?.setChannels?.(() => channels.status()); // the Runner view's read-only Channels list
|
|
1617
|
+
}
|
|
1618
|
+
// Host gateways (--gateways-file; src/headless/gateways/): modules the person started with this server. /_gateway/<id>/<operation> is theirs; no request starts or changes one.
|
|
1619
|
+
const gateways = opts.gateways?.length ? createGateways({ modules: opts.gateways, record: (entry) => server.record(entry), now: () => opts.clock.now(), stderr: opts.stderr, ...(opts.gatewayOptions ?? {}) }) : null;
|
|
1620
|
+
// The canvases start once the listener listens (an A2A push URL names its port); requests wait for them.
|
|
1621
|
+
let started;
|
|
1622
|
+
const ready = new Promise((resolve) => (started = resolve));
|
|
1623
|
+
|
|
1624
|
+
const loopback = isLoopback(opts.host);
|
|
1625
|
+
/** `--static-dir` mounts (Map: mount -> real folder). A mount never shadows a canvas: the canvas keeps its route. */
|
|
1626
|
+
const staticMounts = opts.staticDirs instanceof Map ? opts.staticDirs : new Map();
|
|
1627
|
+
/** What the monitor says about each canvas served (the loopback monitor and the remote listener alike). */
|
|
1628
|
+
const canvasList = () => [...hosts.values()].map((h) => ({ route: h.route, name: typeof h.doc.name === "string" ? h.doc.name.slice(0, 80) : undefined, revision: h.revision, queue: { waiting: h.queue.length, limit: opts.queueSize, lanes: h.lanes.length + h.slots.length, busy: [...h.lanes, ...h.slots].filter((l) => l.busy).length } }));
|
|
1629
|
+
/** The full /health body (prism's, HIS-05). Names the routes only when `named`. Holds no token, key, header or path on disk. */
|
|
1630
|
+
const healthBody = (named) => {
|
|
1631
|
+
const list = [...hosts.values()];
|
|
1632
|
+
const webhooks = list.flatMap((h) => h.plan.webhooks.map((w) => `${h.route}/${w.path}`));
|
|
1633
|
+
const sockets = list.flatMap((h) => (h.plan.wsProxies ?? []).map((p) => p.settings.upstream));
|
|
1634
|
+
const origins = [...new Set(sockets.map((u) => String(u).replace(/^((?:wss?|https?):\/\/)[^/?#]*@/i, "$1").match(/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i)?.[0]).filter(Boolean))];
|
|
1635
|
+
return {
|
|
1636
|
+
ok: true,
|
|
1637
|
+
status: "ok", // (prism's spelling of ok)
|
|
1638
|
+
version: opts.version ?? null,
|
|
1639
|
+
uptime: Math.max(0, Math.floor((opts.clock.now() - serveStartedAt) / 1000)),
|
|
1640
|
+
canvases: list.length,
|
|
1641
|
+
mode: (sockets.length ? "proxy" : "serve") + (webhooks.length ? "+routes" : ""),
|
|
1642
|
+
...(origins.length ? { target: origins[0], targets: origins } : {}),
|
|
1643
|
+
captured: list.reduce((n, h) => n + h.servedLog.seq, 0),
|
|
1644
|
+
persist: Boolean(opts.trafficHistory),
|
|
1645
|
+
storageMode: opts.trafficHistory ? "server" : "memory", // prism's "browser" | "server" | "memory": here a --traffic-history file, or the served log in memory
|
|
1646
|
+
session: serveSession,
|
|
1647
|
+
maxHistory: SERVED_LOG_MAX,
|
|
1648
|
+
maxBodySize: opts.maxBodyKB * 1024,
|
|
1649
|
+
routes: webhooks.length,
|
|
1650
|
+
hasRoutes: webhooks.length > 0,
|
|
1651
|
+
...(named ? { routeNames: webhooks.slice(0, 200) } : {}),
|
|
1652
|
+
};
|
|
1653
|
+
};
|
|
1654
|
+
// Behind a tunnel every request is a loopback connection from the tunnel's own process, so with --identity "loopback" no longer means "this computer is asking".
|
|
1655
|
+
const trustLoopback = loopback && !identity;
|
|
1656
|
+
const hostOk = (value) => loopbackHostHeader(value, actualPort) || (identityHosts.size > 0 && identityHosts.has(String(value ?? "").toLowerCase()));
|
|
1657
|
+
const corsAllows = (origin) => Boolean(opts.cors && origin && (opts.cors === "*" || origin === opts.cors));
|
|
1658
|
+
|
|
1659
|
+
/**
|
|
1660
|
+
* POST /v1/chat/completions and /v1/messages, GET /v1/models. Everything is decided before a machine runs: the Host and web-page checks, the bearer
|
|
1661
|
+
* token (an HMAC does not stand in for it), then the model, the body and the conversation's fit. Then one request is one run, through the machine's
|
|
1662
|
+
* own gates and caps; anything but a clean end is an error in the caller's API shape. Nothing about the canvas is said to a caller without the token.
|
|
1663
|
+
*/
|
|
1664
|
+
const modelEndpoint = async ({ req, rawPath, tail, only, send, refuse, origin, site }) => {
|
|
1665
|
+
const shape = tail === "v1/messages" ? "anthropic" : "openai";
|
|
1666
|
+
const fail = (status, type, message, code, headers) => send(status, errorBody(shape, { type, message, code }), headers);
|
|
1667
|
+
// A web page never uses it, whatever --cors lets webhooks do (the general check above let an allowed origin through).
|
|
1668
|
+
if (origin || (site && site !== "none")) return refuse(403, {}, "requests from web pages are refused");
|
|
1669
|
+
if (!opts.auth.bearer(req.headers)) return refuse(401, { "www-authenticate": 'Bearer realm="mallory"' });
|
|
1670
|
+
const served = [...hosts.values()].filter((h) => !only || h.route === only).flatMap((h) => h.modelPanes().map((m) => ({ ...m, host: h, name: `${h.route}/${m.label}` })));
|
|
1671
|
+
if (tail === "v1/models") {
|
|
1672
|
+
if (req.method !== "GET" && req.method !== "HEAD") return fail(405, "invalid_request_error", "method not allowed", undefined, { allow: "GET" });
|
|
1673
|
+
return send(200, modelList(served.map((m) => m.name)));
|
|
1674
|
+
}
|
|
1675
|
+
if (req.method !== "POST") return fail(405, "invalid_request_error", "method not allowed", undefined, { allow: "POST" });
|
|
1676
|
+
let body;
|
|
1677
|
+
try {
|
|
1678
|
+
body = JSON.parse(Buffer.from(await readBody(req, opts.maxBodyKB * 1024)).toString("utf8"));
|
|
1679
|
+
} catch (error) {
|
|
1680
|
+
if (error.status === 413) {
|
|
1681
|
+
fail(413, "invalid_request_error", "request body too large", undefined, { connection: "close" });
|
|
1682
|
+
return;
|
|
1683
|
+
}
|
|
1684
|
+
return fail(400, "invalid_request_error", "the body is not valid JSON");
|
|
1685
|
+
}
|
|
1686
|
+
const read = readRequest(shape, body);
|
|
1687
|
+
if (read.problem) return fail(400, "invalid_request_error", read.problem);
|
|
1688
|
+
// The model: "<canvas>/<pane>", or the pane's name or id when one served pane has it.
|
|
1689
|
+
const same = (m, name) => name === m.name || name === `${m.host.route}/${m.id}` || (only && (name === m.label || name === m.id));
|
|
1690
|
+
let matches = served.filter((m) => same(m, read.model));
|
|
1691
|
+
if (!matches.length) matches = served.filter((m) => m.label === read.model || m.id === read.model);
|
|
1692
|
+
if (matches.length > 1) return fail(400, "invalid_request_error", `model: "${read.model}" names more than one machine; use <canvas>/<pane>`);
|
|
1693
|
+
const model = matches[0];
|
|
1694
|
+
if (!model) return fail(404, "not_found_error", `model: no machine is served as "${read.model}"`);
|
|
1695
|
+
const text = transcript(read.messages);
|
|
1696
|
+
if (Number.isInteger(model.maxChars) && text.length > model.maxChars) return fail(400, "invalid_request_error", `messages: the conversation is ${text.length} characters on the tape, and the cell takes ${model.maxChars}`);
|
|
1697
|
+
const id = randomUUID();
|
|
1698
|
+
const outcome = await model.host.askModel({ pane: model.id, cell: model.cell, text, request: { id, method: "POST", path: rawPath } });
|
|
1699
|
+
if (outcome.kind === "answer") return send(200, (shape === "anthropic" ? anthropicReply : openaiReply)({ id: id.replaceAll("-", ""), model: read.model, text: outcome.text, usage: outcome.usage }));
|
|
1700
|
+
if (outcome.kind === "halt") return fail(haltStatus(outcome.haltKind), "machine_halted", `the machine stopped (${outcome.haltKind}): ${outcome.reason}`, outcome.haltKind);
|
|
1701
|
+
if (outcome.kind === "busy") return fail(429, "rate_limit_error", "too many requests are waiting", undefined, { "retry-after": "1" });
|
|
1702
|
+
if (outcome.kind === "timeout") return fail(504, "timeout_error", "the machine did not finish in time");
|
|
1703
|
+
if (outcome.kind === "gone") return fail(404, "not_found_error", `model: no machine is served as "${read.model}"`);
|
|
1704
|
+
return fail(500, "api_error", `the machine could not run: ${outcome.error}`);
|
|
1705
|
+
};
|
|
1706
|
+
|
|
1707
|
+
/** POST /mcp. Everything is decided before a tool runs: the Host and web-page checks above, the bearer token (an HMAC does not stand in for it), the method, the type and the size of the body. */
|
|
1708
|
+
const mcp = opts.mcp
|
|
1709
|
+
? mcpHandler({
|
|
1710
|
+
version: opts.version ?? "0",
|
|
1711
|
+
canvases: () => [...hosts.values()].map((h) => ({ route: h.route, name: typeof h.doc.name === "string" ? h.doc.name.slice(0, 80) : undefined, panes: h.mcpPanes() })).filter((c) => c.panes.length),
|
|
1712
|
+
call: ({ route, tool, args }) => hosts.get(route).askMcp({ tool, args }),
|
|
1713
|
+
read: ({ route, pane }) => hosts.get(route).askMcp({ tool: "mallory_get_pane", args: { pane } }),
|
|
1714
|
+
})
|
|
1715
|
+
: null;
|
|
1716
|
+
const mcpRoute = async ({ req, send, refuse, origin, site }) => {
|
|
1717
|
+
if (origin || (site && site !== "none")) return refuse(403, {}, "requests from web pages are refused");
|
|
1718
|
+
if (!opts.auth.bearer(req.headers)) return refuse(401, { "www-authenticate": 'Bearer realm="mallory"' });
|
|
1719
|
+
if (req.method !== "POST") return refuse(405, { allow: "POST" }, "POST only: this server has no event stream and no session");
|
|
1720
|
+
const version = req.headers["mcp-protocol-version"];
|
|
1721
|
+
if (version !== undefined && !MCP_VERSIONS.includes(String(version))) return refuse(400, {}, `unsupported MCP protocol version (${MCP_VERSIONS.join(", ")})`);
|
|
1722
|
+
if (!/^application\/json(\s*;|$)/i.test(String(req.headers["content-type"] ?? ""))) return refuse(415, {}, "the body is application/json");
|
|
1723
|
+
let body;
|
|
1724
|
+
try {
|
|
1725
|
+
body = JSON.parse(Buffer.from(await readBody(req, 256 * 1024)).toString("utf8"));
|
|
1726
|
+
} catch (error) {
|
|
1727
|
+
if (error.status === 413) {
|
|
1728
|
+
refuse(413, { connection: "close" });
|
|
1729
|
+
return;
|
|
1730
|
+
}
|
|
1731
|
+
return send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "the body is not valid JSON" } });
|
|
1732
|
+
}
|
|
1733
|
+
const reply = await mcp.handle(body);
|
|
1734
|
+
return reply === null ? send(202, "") : send(200, reply);
|
|
1735
|
+
};
|
|
1736
|
+
|
|
1737
|
+
const shortMisses = missLimiter(undefined, () => opts.clock.now());
|
|
1738
|
+
const http = createServer(async (req, res) => {
|
|
1739
|
+
const receivedAt = new Date();
|
|
1740
|
+
const rawPath = String(req.url ?? "/").split("?")[0];
|
|
1741
|
+
const search = String(req.url ?? "").includes("?") ? String(req.url).slice(String(req.url).indexOf("?")) : "";
|
|
1742
|
+
const origin = req.headers.origin;
|
|
1743
|
+
const cors = corsAllows(origin) ? { "access-control-allow-origin": opts.cors === "*" ? "*" : origin, vary: "Origin" } : {};
|
|
1744
|
+
let answered = false;
|
|
1745
|
+
const send = (status, body, headers = {}) => {
|
|
1746
|
+
if (answered) return;
|
|
1747
|
+
answered = true;
|
|
1748
|
+
const payload = status === 204 ? "" : scrub(typeof body === "string" ? body : JSON.stringify(body ?? { error: STATUS_TEXT[status] ?? "error" }));
|
|
1749
|
+
const type = typeof body === "string" ? {} : status === 204 ? {} : { "content-type": "application/json; charset=utf-8" };
|
|
1750
|
+
res.writeHead(status, { ...type, "x-content-type-options": "nosniff", "cache-control": "no-store", ...cors, ...headers });
|
|
1751
|
+
res.end(payload);
|
|
1752
|
+
};
|
|
1753
|
+
const refuse = (status, extra = {}, note) => {
|
|
1754
|
+
send(status, { error: note ?? STATUS_TEXT[status] }, extra);
|
|
1755
|
+
server.record({ at: receivedAt.toISOString(), canvas: "-", cause: `${req.method} ${rawPath.startsWith(SHORT_PREFIX) ? "/s/…" : rawPath.slice(0, 200)}`, http: status, outcome: "refused", ...(note ? { note } : {}) });
|
|
1756
|
+
};
|
|
1757
|
+
// The verified identity of this request (once): `{ state: "absent" | "valid" | "invalid" | "unavailable", … }`; always "absent" without --identity.
|
|
1758
|
+
let who;
|
|
1759
|
+
const identify = () => (who ??= identity ? identity.verify(req.headers) : Promise.resolve({ state: "absent" }));
|
|
1760
|
+
// A refusal from identity: the caller is told only "unauthorized" (or that the keys are unavailable); the reason goes to the log.
|
|
1761
|
+
const identityRefuse = (verdict) => {
|
|
1762
|
+
const unavailable = verdict.state === "unavailable";
|
|
1763
|
+
send(unavailable ? 503 : 401, { error: unavailable ? "identity service unavailable" : "unauthorized" }, unavailable ? { "retry-after": "5" } : { "www-authenticate": 'Bearer realm="mallory"' });
|
|
1764
|
+
server.record({ at: receivedAt.toISOString(), canvas: "-", cause: `${req.method} ${rawPath.slice(0, 200)}`, http: unavailable ? 503 : 401, outcome: "refused", note: `identity: ${verdict.reason ?? "no identity"}` });
|
|
1765
|
+
};
|
|
1766
|
+
try {
|
|
1767
|
+
await ready;
|
|
1768
|
+
// DNS rebinding: a page on another name that resolves to this computer still says its own name.
|
|
1769
|
+
if (loopback && !hostOk(req.headers.host)) return refuse(403, {}, "unexpected Host header");
|
|
1770
|
+
if (malformedPath(rawPath)) return refuse(400, {}, "malformed path");
|
|
1771
|
+
// A short link (src/headless/short-links.js): `/s/<id>`, a capability URL for one published revision, read-only. Only while a published
|
|
1772
|
+
// folder is served (opts.shortLinks). Decided before the web-page check below, because a link is opened from anywhere (a chat, a mail
|
|
1773
|
+
// client: a cross-site navigation), and before the bearer token, because the id is the credential. GET and HEAD only. Every miss (wrong
|
|
1774
|
+
// shape, unknown, revoked, a revision file gone) is the same 404, and misses are counted: past the budget everyone waits.
|
|
1775
|
+
if (opts.shortLinks && rawPath.startsWith(SHORT_PREFIX) && rawPath.indexOf("/", SHORT_PREFIX.length) === -1) {
|
|
1776
|
+
const headers = { "referrer-policy": "no-referrer", "x-robots-tag": "noindex" };
|
|
1777
|
+
if (req.method !== "GET" && req.method !== "HEAD") return refuse(405, { allow: "GET, HEAD", ...headers });
|
|
1778
|
+
if (shortMisses.blocked()) return refuse(429, { "retry-after": String(shortMisses.retryAfter()), ...headers }, "too many unknown links");
|
|
1779
|
+
const hit = await resolveShortLink(opts.shortLinks.dirs(), rawPath.slice(SHORT_PREFIX.length));
|
|
1780
|
+
if (!hit) {
|
|
1781
|
+
shortMisses.miss();
|
|
1782
|
+
return refuse(404, headers); // one answer for every kind of miss; the log line carries the path's start only
|
|
1783
|
+
}
|
|
1784
|
+
server.record({ at: receivedAt.toISOString(), canvas: "-", cause: `${req.method} /s/…`, http: 200, outcome: "short link" });
|
|
1785
|
+
const json = new URLSearchParams(search).get("format") === "json" || String(req.headers.accept ?? "").split(",")[0].trim() === "application/json";
|
|
1786
|
+
return json
|
|
1787
|
+
? send(200, hit.text, { ...headers, "content-type": "application/json; charset=utf-8", "content-disposition": `inline; filename="${hit.revision}.mallory.json"` })
|
|
1788
|
+
: send(200, shortLinkPage(hit.doc, hit.revision, { created: hit.created }), { ...headers, "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" });
|
|
1789
|
+
}
|
|
1790
|
+
// A channel's platform (src/headless/channels/): its own signature decides, not the bearer token, and no web page (checked in `handle`).
|
|
1791
|
+
if (channels?.owns(rawPath) && !hosts.has("_channels")) return await channels.handle({ req, rawPath, readBody, send, refuse, origin, site: req.headers["sec-fetch-site"] });
|
|
1792
|
+
// A host gateway (src/headless/gateways/): its own grant decides, not the bearer token; a web page only where --cors allows its origin.
|
|
1793
|
+
if (gateways?.owns(rawPath) && !hosts.has("_gateway")) return await gateways.handle({ req, rawPath, readBody, send, refuse, origin, site: req.headers["sec-fetch-site"], pageAllowed: corsAllows(origin) });
|
|
1794
|
+
// The read-only monitor (src/headless/monitor.js): its own token and origin rules, decided before any canvas route.
|
|
1795
|
+
if (rawPath === MONITOR_PREFIX || rawPath.startsWith(`${MONITOR_PREFIX}/`)) {
|
|
1796
|
+
if (!opts.monitor) return refuse(404);
|
|
1797
|
+
// A streamed reply (the run feed): headers now, then a line at a time, scrubbed like every other reply, until either side ends it.
|
|
1798
|
+
const open = (headers) => {
|
|
1799
|
+
if (answered) return null;
|
|
1800
|
+
answered = true;
|
|
1801
|
+
res.writeHead(200, { "x-content-type-options": "nosniff", "cache-control": "no-store", "x-accel-buffering": "no", ...headers });
|
|
1802
|
+
res.flushHeaders();
|
|
1803
|
+
return {
|
|
1804
|
+
write: (line) => (res.destroyed || res.writableEnded ? false : (res.write(`${scrub(JSON.stringify(line))}\n`), true)),
|
|
1805
|
+
end: () => res.end(),
|
|
1806
|
+
onClose: (fn) => res.once("close", fn),
|
|
1807
|
+
buffered: () => res.writableLength,
|
|
1808
|
+
};
|
|
1809
|
+
};
|
|
1810
|
+
const result = opts.monitor.handle(req, (status, body, headers) => send(status, status === 204 ? "" : body, headers), { canvases: canvasList(), refresh: canvasList, open });
|
|
1811
|
+
if (result?.refused) server.record({ at: receivedAt.toISOString(), canvas: "-", cause: `${req.method} ${MONITOR_PREFIX}`, http: result.status, outcome: "refused", note: result.refused });
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
// The decision operator page (src/headless/operator.js): its own tokens, this computer only, its own page only.
|
|
1815
|
+
if (rawPath === OPERATOR_PREFIX || rawPath.startsWith(`${OPERATOR_PREFIX}/`)) {
|
|
1816
|
+
if (!opts.operator) return refuse(404);
|
|
1817
|
+
if (!loopback) return refuse(404);
|
|
1818
|
+
const ctx = {
|
|
1819
|
+
parked: (viewer) => scheduler?.parked(viewer) ?? [],
|
|
1820
|
+
answerParked: (a) => (scheduler ? scheduler.answer(a) : Promise.resolve({ kind: "gone" })),
|
|
1821
|
+
pending: (viewer) => [...hosts.values()].map((h) => ({ canvas: h.route, panes: h.pendingDecisions(viewer) })).filter((c) => c.panes.length),
|
|
1822
|
+
...(identity ? { identify } : {}),
|
|
1823
|
+
readBody,
|
|
1824
|
+
answer: async (a) => {
|
|
1825
|
+
const h = hosts.get(a.canvas);
|
|
1826
|
+
if (!h) return { kind: "gone" };
|
|
1827
|
+
return await h.decide(a);
|
|
1828
|
+
},
|
|
1829
|
+
};
|
|
1830
|
+
const result = await opts.operator.handle(req, (status, body, headers) => send(status, status === 204 ? "" : body, headers), ctx);
|
|
1831
|
+
if (result?.refused) server.record({ at: receivedAt.toISOString(), canvas: "-", cause: `${req.method} ${OPERATOR_PREFIX}`, http: result.status, outcome: "refused", note: result.refused });
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
// A web page's request (it says where it comes from): refused unless --cors allows that origin.
|
|
1835
|
+
const site = req.headers["sec-fetch-site"];
|
|
1836
|
+
// A static mount's own page loads its own files (sec-fetch-site: same-origin, no Origin on a GET): that, and only that, passes. Cross-site stays refused.
|
|
1837
|
+
const staticMount = staticMounts.has(rawPath.split("/")[1] ?? "") && (req.method === "GET" || req.method === "HEAD");
|
|
1838
|
+
if ((origin || (site && site !== "none" && !(staticMount && site === "same-origin"))) && !corsAllows(origin)) return refuse(403, {}, "requests from web pages are refused (mallory serve --cors <origin> allows one)");
|
|
1839
|
+
if (rawPath === "/healthz" && (req.method === "GET" || req.method === "HEAD")) return send(200, { ok: true });
|
|
1840
|
+
// /health (prism's, restored): ok, the version, the uptime and how many canvases are served, for a monitor on this computer. After the Host and
|
|
1841
|
+
// web-page checks above, like /healthz, and with no credential on this computer. Off it, the full body is for the bearer token and everyone
|
|
1842
|
+
// else gets {ok:true}. The full body is prism's too (HIS-05): mode, target, captured, persist, maxHistory, maxBodySize and routes, with no token, key,
|
|
1843
|
+
// header, path on disk or upstream credential. The route NAMES (canvas/path) are for a holder of the bearer token, or, when the server has no token,
|
|
1844
|
+
// this computer: a route list tells a stranger where to knock, so a server that has a token never shows it without one. A canvas served as
|
|
1845
|
+
// "health" keeps its route (it was there first).
|
|
1846
|
+
if (rawPath === "/health" && (req.method === "GET" || req.method === "HEAD") && !hosts.has("health")) {
|
|
1847
|
+
const bearer = opts.auth.required && opts.auth.bearer(req.headers);
|
|
1848
|
+
const full = trustLoopback || bearer;
|
|
1849
|
+
const named = opts.auth.required ? bearer : trustLoopback;
|
|
1850
|
+
return send(200, full ? healthBody(named) : { ok: true });
|
|
1851
|
+
}
|
|
1852
|
+
// /ws/connections (prism's, restored; WSK-03): the WebSocket connections taken, with counts, for the same readers as the full /health. Anyone else is told
|
|
1853
|
+
// it is not there. A canvas served as "ws" keeps its route.
|
|
1854
|
+
if (rawPath === "/ws/connections" && (req.method === "GET" || req.method === "HEAD") && !hosts.has("ws")) {
|
|
1855
|
+
if (!(trustLoopback || (opts.auth.required && opts.auth.bearer(req.headers)))) return refuse(404);
|
|
1856
|
+
return send(200, wsConnections.list());
|
|
1857
|
+
}
|
|
1858
|
+
// POST /ws-ticket (#997): a caller that holds the bearer token trades it for a ticket a browser can offer as a WebSocket subprotocol, which can't send
|
|
1859
|
+
// Authorization. Only with a token (nothing to trade without one); the answer for a canvas or proxy that isn't there is 404, whatever the caller asked.
|
|
1860
|
+
if (rawPath === "/ws-ticket" && !hosts.has("ws-ticket")) {
|
|
1861
|
+
if (!opts.auth.required) return refuse(404);
|
|
1862
|
+
if (req.method !== "POST") return refuse(405, { allow: "POST" });
|
|
1863
|
+
if (!opts.auth.bearer(req.headers)) return refuse(401, { "www-authenticate": 'Bearer realm="mallory"' });
|
|
1864
|
+
let asked;
|
|
1865
|
+
try {
|
|
1866
|
+
asked = JSON.parse(Buffer.from(await readBody(req, 4096)).toString("utf8"));
|
|
1867
|
+
} catch {
|
|
1868
|
+
return refuse(400, {}, "the body is not valid JSON");
|
|
1869
|
+
}
|
|
1870
|
+
if (!asked || typeof asked.canvas !== "string" || typeof asked.path !== "string") return refuse(400, {}, 'send {"canvas": "<route>", "path": "<proxy path>"}');
|
|
1871
|
+
const canvasHost = hosts.get(asked.canvas);
|
|
1872
|
+
if (!canvasHost || canvasHost.closed || !canvasHost.plan.wsProxies?.some((p) => p.path === asked.path)) return refuse(404);
|
|
1873
|
+
const made = wsTickets.mint({ route: asked.canvas, path: asked.path, origin });
|
|
1874
|
+
if (!made) return refuse(429, { "retry-after": "5" });
|
|
1875
|
+
return send(200, made, { "cache-control": "no-store" });
|
|
1876
|
+
}
|
|
1877
|
+
// The traffic history's read side (--traffic-history; src/headless/history-api.js): GET /history, /history/summary and /entry/:id. Only for the bearer
|
|
1878
|
+
// token's holder (a server with no token, or a caller without it, is told it is not there), after the Host and web-page checks above and never from a web page,
|
|
1879
|
+
// whatever --cors allows. A canvas served as "history" or "entry" keeps its route.
|
|
1880
|
+
if (opts.historyApi?.owns(rawPath) && !hosts.has(rawPath.split("/")[1])) {
|
|
1881
|
+
if (origin || (site && site !== "none")) return refuse(403, {}, "requests from web pages are refused");
|
|
1882
|
+
if (!(opts.auth.required && opts.auth.bearer(req.headers))) return refuse(opts.auth.required ? 401 : 404, opts.auth.required ? { "www-authenticate": 'Bearer realm="mallory"' } : {});
|
|
1883
|
+
let answer;
|
|
1884
|
+
try {
|
|
1885
|
+
answer = opts.historyApi.handle(req.method, rawPath, new URLSearchParams(search));
|
|
1886
|
+
} catch {
|
|
1887
|
+
answer = { status: 400, body: { error: "malformed request" } };
|
|
1888
|
+
}
|
|
1889
|
+
return send(answer.status, req.method === "HEAD" ? "" : answer.body, answer.headers);
|
|
1890
|
+
}
|
|
1891
|
+
// `--mcp` (src/headless/mcp-endpoint.js): off unless asked for, a bearer token on every request, never from a web page, POST only (no stream, no session).
|
|
1892
|
+
if (opts.mcp && rawPath === "/mcp") return await mcpRoute({ req, send, refuse, origin, site });
|
|
1893
|
+
// /_me (--identity): the verified person's own view, their runs and traffic. Nothing here takes a name or id from the request.
|
|
1894
|
+
if (identity && (rawPath === "/_me" || rawPath.startsWith("/_me/"))) {
|
|
1895
|
+
if (req.method !== "GET" && req.method !== "HEAD") return refuse(405, { allow: "GET, HEAD" });
|
|
1896
|
+
const verdict = await identify();
|
|
1897
|
+
if (verdict.state !== "valid") return identityRefuse(verdict.state === "absent" ? { state: "absent", reason: "no identity header" } : verdict);
|
|
1898
|
+
const me = verdict.person;
|
|
1899
|
+
if (rawPath === "/_me") return send(200, { person: { id: me.id, email: me.email } });
|
|
1900
|
+
if (rawPath === "/_me/runs") return send(200, { runs: server.people.runs(me.id), approvals: server.people.approvals(me.id) });
|
|
1901
|
+
if (rawPath === "/_me/traffic") {
|
|
1902
|
+
if (!opts.trafficHistoryRead) return send(200, { enabled: false, canvases: [] });
|
|
1903
|
+
const canvases = [];
|
|
1904
|
+
for (const route of hosts.keys()) canvases.push({ canvas: route, entries: (await opts.trafficHistoryRead(`${route}/@${me.id}`)).slice(-200) });
|
|
1905
|
+
return send(200, { enabled: true, canvases });
|
|
1906
|
+
}
|
|
1907
|
+
return refuse(404);
|
|
1908
|
+
}
|
|
1909
|
+
// `--model-endpoint` (src/headless/model-endpoint.js): off unless asked for, a bearer token on every request, never from a web page.
|
|
1910
|
+
if (opts.modelEndpoint) {
|
|
1911
|
+
const parts = rawPath.split("/");
|
|
1912
|
+
const prefixed = parts[1] === "v1" ? "" : parts[2] === "v1" && hosts.has(parts[1]) ? parts[1] : undefined;
|
|
1913
|
+
const tail = prefixed === undefined ? "" : parts.slice(prefixed === "" ? 1 : 2).join("/");
|
|
1914
|
+
const known = tail === "v1/chat/completions" || tail === "v1/messages" || tail === "v1/models";
|
|
1915
|
+
if (known && !(prefixed === "" && hosts.has("v1"))) return await modelEndpoint({ req, rawPath, tail, only: prefixed || undefined, send, refuse, origin, site });
|
|
1916
|
+
}
|
|
1917
|
+
const [, route = "", ...rest] = rawPath.split("/");
|
|
1918
|
+
// `--static-dir`: a folder the person named, read-only (src/headless/static-dirs.js). After the Host and web-page checks; with a token set, the bearer
|
|
1919
|
+
// token is needed (an HMAC can't sign a GET, so it never opens a folder).
|
|
1920
|
+
if (staticMounts.has(route) && !hosts.has(route)) {
|
|
1921
|
+
if (opts.auth.required && !opts.auth.bearer(req.headers)) return refuse(401, { "www-authenticate": 'Bearer realm="mallory"' });
|
|
1922
|
+
const got = await staticLookup(staticMounts.get(route), req.method, `/${rest.join("/")}`);
|
|
1923
|
+
if (got.status !== 200) return refuse(got.status, got.headers);
|
|
1924
|
+
const handle = await openChecked(got.file, got.size);
|
|
1925
|
+
if (!handle) return refuse(404);
|
|
1926
|
+
if (req.headers["if-none-match"] === got.headers.etag) {
|
|
1927
|
+
await handle.close();
|
|
1928
|
+
return send(304, "", { etag: got.headers.etag });
|
|
1929
|
+
}
|
|
1930
|
+
answered = true;
|
|
1931
|
+
res.writeHead(200, { ...got.headers, "x-content-type-options": "nosniff", "cross-origin-resource-policy": "same-origin" });
|
|
1932
|
+
if (req.method === "HEAD") {
|
|
1933
|
+
await handle.close();
|
|
1934
|
+
return res.end();
|
|
1935
|
+
}
|
|
1936
|
+
const stream = handle.createReadStream();
|
|
1937
|
+
stream.on("error", () => res.destroy());
|
|
1938
|
+
res.once("close", () => stream.destroy());
|
|
1939
|
+
stream.pipe(res);
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1942
|
+
const canvasHost = hosts.get(route);
|
|
1943
|
+
const asked = rest.join("/");
|
|
1944
|
+
// An A2A agent's push notification: the task's own secret, not the webhooks' credential, decides it.
|
|
1945
|
+
const pushId = canvasHost && server.push && canvasHost.plan.a2a ? pushIdOf(asked) : undefined;
|
|
1946
|
+
if (pushId) {
|
|
1947
|
+
if (req.method !== "POST") return refuse(405, { allow: "POST" });
|
|
1948
|
+
let bytes;
|
|
1949
|
+
try {
|
|
1950
|
+
bytes = await readBody(req, server.push.maxBytes);
|
|
1951
|
+
} catch (error) {
|
|
1952
|
+
if (error.status === 413) {
|
|
1953
|
+
refuse(413, { connection: "close" });
|
|
1954
|
+
res.on("finish", () => req.destroy());
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
throw error;
|
|
1958
|
+
}
|
|
1959
|
+
const got = server.push.handle(route, pushId, req.headers, bytes);
|
|
1960
|
+
if (got.refused) return refuse(got.status, {}, got.body.error);
|
|
1961
|
+
return send(got.status, got.body);
|
|
1962
|
+
}
|
|
1963
|
+
// A webhook of path * (a catch-all) answers what no other route does, last (src/model/webhook.js resolveRoute); a HEAD it
|
|
1964
|
+
// doesn't list is answered as a GET, without the body (`as`).
|
|
1965
|
+
const found = canvasHost ? resolveRoute(canvasHost.plan.webhooks, asked, req.method) : { route: null, as: null };
|
|
1966
|
+
const picked = found;
|
|
1967
|
+
const hook = found.route;
|
|
1968
|
+
// The methods a path answers: a router can answer one path with a route per method.
|
|
1969
|
+
const allowed = hook ? [...new Set(canvasHost.plan.webhooks.filter((w) => routeShape(w.path) === routeShape(hook.path)).flatMap((w) => w.settings.methods))] : [];
|
|
1970
|
+
// A CORS preflight (a page that --cors allows) is answered here; any other OPTIONS is a request like the rest, for a catch-all that lists it.
|
|
1971
|
+
if (req.method === "OPTIONS" && (corsAllows(origin) || !found.as)) {
|
|
1972
|
+
if (!hook || !corsAllows(origin)) return refuse(404);
|
|
1973
|
+
return send(204, "", { "access-control-allow-methods": allowed.join(", "), "access-control-allow-headers": ["content-type", "authorization", ...(opts.auth.hasHmac ? [opts.auth.hmacHeader] : [])].join(", "), "access-control-max-age": "600" });
|
|
1974
|
+
}
|
|
1975
|
+
// --identity: a token that claims to be a person and doesn't verify is refused outright (even beside a good bearer token), and a person's
|
|
1976
|
+
// verified token is a credential on its own. The operator's bearer token and HMAC still pass, as the operator (no person).
|
|
1977
|
+
let person;
|
|
1978
|
+
if (identity) {
|
|
1979
|
+
const verdict = await identify();
|
|
1980
|
+
if (verdict.state === "invalid" || verdict.state === "unavailable") return identityRefuse(verdict);
|
|
1981
|
+
if (verdict.state === "valid") person = verdict.person;
|
|
1982
|
+
}
|
|
1983
|
+
let authorized = identity ? person !== undefined || opts.auth.bearer(req.headers) : !opts.auth.required || opts.auth.bearer(req.headers);
|
|
1984
|
+
if (!authorized && !opts.auth.hasHmac) return refuse(401, { "www-authenticate": 'Bearer realm="mallory"' });
|
|
1985
|
+
if (!hook) return refuse(authorized ? 404 : 401);
|
|
1986
|
+
// 405 + allow tells which methods a path answers: only to a caller already authenticated. In HMAC-only mode the signature covers a
|
|
1987
|
+
// body that hasn't been read yet, so an unsigned caller gets 401 and learns nothing about the routes (#950 F5).
|
|
1988
|
+
if (!found.as) return authorized ? refuse(405, { allow: allowed.join(", ") }) : refuse(401);
|
|
1989
|
+
const asMethod = found.as; // the method the canvas sees (a HEAD answered by a GET route is a GET)
|
|
1990
|
+
let bytes;
|
|
1991
|
+
try {
|
|
1992
|
+
bytes = await readBody(req, Math.min(hook.settings.maxBodyKB, opts.maxBodyKB) * 1024);
|
|
1993
|
+
} catch (error) {
|
|
1994
|
+
if (error.status === 413) {
|
|
1995
|
+
refuse(413, { connection: "close" });
|
|
1996
|
+
res.on("finish", () => req.destroy());
|
|
1997
|
+
return;
|
|
1998
|
+
}
|
|
1999
|
+
throw error;
|
|
2000
|
+
}
|
|
2001
|
+
if (!authorized && !opts.auth.hmac(req.headers, bytes)) return refuse(401);
|
|
2002
|
+
authorized = true;
|
|
2003
|
+
const id = randomUUID();
|
|
2004
|
+
let value;
|
|
2005
|
+
try {
|
|
2006
|
+
const params = hook.path.includes(":") ? picked.params : undefined;
|
|
2007
|
+
const given = { method: asMethod, path: asked, params, search, headers: req.headers, bytes, allowHeaders: hook.settings.headers, id, receivedAt: receivedAt.toISOString() };
|
|
2008
|
+
// capture: "raw": the request as it came (headers in order, bytes), but for the credentials (RAW_HIDDEN, and the HMAC header).
|
|
2009
|
+
value = hook.settings.capture === "raw" && !hook.output ? rawRequestValue({ method: asMethod, path: asked, search, headers: req.rawHeaders, bytes, hide: opts.auth.hasHmac ? [opts.auth.hmacHeader] : [], id, receivedAt: given.receivedAt }) : hook.output ? routerRequestValue({ route: hook.output, ...given }) : requestValue(given);
|
|
2010
|
+
} catch (error) {
|
|
2011
|
+
if (error instanceof BadRequest) return refuse(error.status, {}, error.message);
|
|
2012
|
+
throw error;
|
|
2013
|
+
}
|
|
2014
|
+
let http = 0;
|
|
2015
|
+
let servedResponse; // what the client was sent, for the served log (sizes and headers; the body stays out)
|
|
2016
|
+
const timer = setTimeout(() => reply({ kind: "timeout" }), opts.requestTimeoutMs);
|
|
2017
|
+
const reply = (outcome) => {
|
|
2018
|
+
if (answered) return;
|
|
2019
|
+
clearTimeout(timer);
|
|
2020
|
+
if (outcome.kind === "response" && outcome.stream && outcome.follow && outcome.response.status === 200 && outcome.response.encoding !== "base64") {
|
|
2021
|
+
// A streaming respond pane: this response is the first frame; the connection stays open for the pane's later runs.
|
|
2022
|
+
if (server.streams.full) {
|
|
2023
|
+
http = 429;
|
|
2024
|
+
return send(429, { error: STATUS_TEXT[429] }, { "retry-after": "1" });
|
|
2025
|
+
}
|
|
2026
|
+
const { "content-type": _type, "cache-control": _cache, ...kept } = encodeResponse(outcome.response).headers;
|
|
2027
|
+
answered = true;
|
|
2028
|
+
http = 200;
|
|
2029
|
+
servedResponse = { status: 200, headers: { "content-type": "text/event-stream" }, bytes: 0 };
|
|
2030
|
+
server.streams.start({ res, headers: { ...kept, ...cors }, event: outcome.stream.event, first: outcome.response.body, follow: outcome.follow, tag: outcome.lane });
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
if (outcome.kind === "response") {
|
|
2034
|
+
const wire = encodeResponse(outcome.response);
|
|
2035
|
+
const binary = outcome.response.encoding === "base64";
|
|
2036
|
+
// Text is scrubbed of secrets. Bytes can't be, so a binary reply that holds a secret is refused (a 500; the log says why).
|
|
2037
|
+
if (binary && binaryHoldsSecret(wire.bytes)) {
|
|
2038
|
+
opts.stderr(`mallory serve: /${route}/${hook.path}: a binary reply holds a secret's bytes, so it was not sent`);
|
|
2039
|
+
return reply({ kind: "error" });
|
|
2040
|
+
}
|
|
2041
|
+
const text = binary ? undefined : scrub(new TextDecoder().decode(wire.bytes));
|
|
2042
|
+
const payload = binary ? Buffer.from(wire.bytes) : text;
|
|
2043
|
+
http = wire.status;
|
|
2044
|
+
servedResponse = { status: wire.status, headers: wire.headers, bytes: wire.bytes.length, ...(opts.servedBodies ? { body: servedBodyView(wire.bytes) } : {}) };
|
|
2045
|
+
answered = true;
|
|
2046
|
+
const noBody = wire.status === 204 || wire.status === 304;
|
|
2047
|
+
res.writeHead(wire.status, { ...wire.headers, ...(noBody ? {} : { "content-length": String(Buffer.byteLength(payload)) }), ...cors, "x-content-type-options": "nosniff" }); // (nosniff last: a canvas or upstream x-* header cannot turn it off)
|
|
2048
|
+
res.end(noBody ? "" : payload);
|
|
2049
|
+
return;
|
|
2050
|
+
}
|
|
2051
|
+
http = { skipped: 204, error: 500, timeout: 504, gone: 503, accepted: 202 }[outcome.kind] ?? 500;
|
|
2052
|
+
if (outcome.kind === "skipped") send(204, "");
|
|
2053
|
+
else if (outcome.kind === "accepted") send(202, { accepted: true, id });
|
|
2054
|
+
else send(http, { error: STATUS_TEXT[http], id }); // details stay in the log
|
|
2055
|
+
};
|
|
2056
|
+
const over = person ? canvasHost.personQuota(person.id) : undefined;
|
|
2057
|
+
if (over) return refuse(429, { "retry-after": "5" }, over);
|
|
2058
|
+
if (person && !hook.isolated) return refuse(503, {}, "this route is not isolated, so it can't serve a verified person"); // (a reload can change a route after start)
|
|
2059
|
+
const job = { kind: "webhook", ...(person ? { person: person.id } : {}), cause: hook.output ? `router /${route}/${hook.path} (${hook.output})` : `webhook /${route}/${hook.path}`, hook: hook.key, value, request: { id, method: req.method, path: `/${route}/${hook.path}` }, http: () => http || undefined, reply, served: { at: receivedAt.toISOString(), target: req.url, host: req.headers.host, headers: req.rawHeaders, bytes: bytes.length, ...(opts.servedBodies ? { body: bytes } : {}), route: hook.path, startedMs: receivedAt.getTime(), response: () => servedResponse } };
|
|
2060
|
+
if (!canvasHost.submit(job)) {
|
|
2061
|
+
clearTimeout(timer);
|
|
2062
|
+
return refuse(429, { "retry-after": "1" });
|
|
2063
|
+
}
|
|
2064
|
+
if (!hook.respond) reply({ kind: "accepted" });
|
|
2065
|
+
} catch (error) {
|
|
2066
|
+
opts.stderr(scrub(`mallory serve: ${error.message}`));
|
|
2067
|
+
send(500);
|
|
2068
|
+
}
|
|
2069
|
+
});
|
|
2070
|
+
// WebSocket upgrades (wave P-F): only a ws-client pane in proxy mode takes one, at /<canvas>/<its path>. The same front-door checks as a request:
|
|
2071
|
+
// Host (DNS rebinding), the page's Origin (only what --cors allows; "null" never), the bearer token; then the proxy's own (src/headless/ws-proxy.js).
|
|
2072
|
+
const wsProxy = createWsProxies({ net: { ...(opts.sockets ?? {}), restrictFor: (route) => (hosts.get(route)?.granted ? { hosts: () => hosts.get(route).granted.hosts } : null) }, stderr: (line) => opts.stderr(scrub(line)), connections: wsConnections });
|
|
2073
|
+
// GET /ws/echo (prism's, WSK-04): only with --ws-echo (opts.wsEcho). It passes the same front door as the proxies, then takes its own bounds.
|
|
2074
|
+
const wsEcho = opts.wsEcho ? createWsEcho({ connections: wsConnections, stderr: (line) => opts.stderr(scrub(line)) }) : null;
|
|
2075
|
+
const wsTickets = createWsTickets({ now: () => opts.clock.now() }); // #997: POST /ws-ticket mints one; an upgrade spends it
|
|
2076
|
+
http.on("upgrade", async (req, socket, head) => {
|
|
2077
|
+
const receivedAt = new Date().toISOString();
|
|
2078
|
+
const rawPath = String(req.url ?? "/").split("?")[0];
|
|
2079
|
+
socket.on("error", () => {});
|
|
2080
|
+
const refuse = (status, note) => server.record({ at: receivedAt, canvas: "-", cause: `UPGRADE ${rawPath.slice(0, 200)}`, http: status, outcome: "refused", ...(note ? { note } : {}) });
|
|
2081
|
+
const reject = (status, note) => (refuse(status, note), rejectUpgrade(socket, status));
|
|
2082
|
+
try {
|
|
2083
|
+
await ready;
|
|
2084
|
+
if (loopback && !hostOk(req.headers.host)) return reject(403, "unexpected Host header");
|
|
2085
|
+
if (malformedPath(rawPath)) return reject(400, "malformed path");
|
|
2086
|
+
// A web page says where it comes from; a socket has no preflight, so this is the whole check: refused unless --cors allows that very origin.
|
|
2087
|
+
const origin = req.headers.origin;
|
|
2088
|
+
const site = req.headers["sec-fetch-site"];
|
|
2089
|
+
if ((origin !== undefined || (site && site !== "none")) && (origin === "null" || !corsAllows(origin))) return reject(403, "sockets from web pages are refused (mallory serve --cors <origin> allows one)");
|
|
2090
|
+
// The bearer token, or a ticket from POST /ws-ticket offered as a subprotocol (a browser can't send Authorization). The ticket is read here and removed:
|
|
2091
|
+
// the proxy never sees it, never forwards it and never echoes it. One that is spent, expired, for another route, path or page, or offered twice, is a 401.
|
|
2092
|
+
if ((opts.auth.required || identity) && !opts.auth.bearer(req.headers)) {
|
|
2093
|
+
const offered = splitTicket(req.headers["sec-websocket-protocol"]);
|
|
2094
|
+
const [, ticketRoute = "", ...ticketRest] = rawPath.split("/");
|
|
2095
|
+
if (!offered.ticket || !wsTickets.take(offered.ticket, { route: ticketRoute, path: ticketRest.join("/"), origin })) return reject(401, "a WebSocket proxy needs the bearer token (an HMAC cannot sign an upgrade) or a ticket from POST /ws-ticket");
|
|
2096
|
+
if (offered.rest.length) req.headers["sec-websocket-protocol"] = offered.rest.join(", ");
|
|
2097
|
+
else delete req.headers["sec-websocket-protocol"];
|
|
2098
|
+
} else if (splitTicket(req.headers["sec-websocket-protocol"]).ticket !== undefined || splitTicket(req.headers["sec-websocket-protocol"]).many) {
|
|
2099
|
+
const offered = splitTicket(req.headers["sec-websocket-protocol"]); // the token holder offered one anyway: it is dropped, never forwarded
|
|
2100
|
+
if (offered.rest.length) req.headers["sec-websocket-protocol"] = offered.rest.join(", ");
|
|
2101
|
+
else delete req.headers["sec-websocket-protocol"];
|
|
2102
|
+
}
|
|
2103
|
+
if (rawPath === ECHO_PATH && wsEcho && !hosts.has("ws")) return await wsEcho.upgrade(req, socket, head, { refuse: (status, note) => server.record({ at: receivedAt, canvas: "-", cause: `UPGRADE ${rawPath}`, http: status, outcome: "refused", ...(note ? { note } : {}) }) });
|
|
2104
|
+
const [, route = "", ...rest] = rawPath.split("/");
|
|
2105
|
+
const canvasHost = hosts.get(route);
|
|
2106
|
+
const entry = canvasHost?.plan.wsProxies?.find((p) => p.path === rest.join("/"));
|
|
2107
|
+
if (!canvasHost || !entry || canvasHost.closed) return reject(404);
|
|
2108
|
+
await wsProxy.upgrade(req, socket, head, { host: canvasHost, entry, refuse: (status, note) => server.record({ at: receivedAt, canvas: route, cause: `UPGRADE ${rawPath.slice(0, 200)}`, http: status, outcome: "refused", ...(note ? { note } : {}) }) });
|
|
2109
|
+
} catch (error) {
|
|
2110
|
+
opts.stderr(scrub(`mallory serve: ${error.message}`));
|
|
2111
|
+
rejectUpgrade(socket, 502);
|
|
2112
|
+
}
|
|
2113
|
+
});
|
|
2114
|
+
http.requestTimeout = opts.requestTimeoutMs + 5000; // receiving one request
|
|
2115
|
+
http.headersTimeout = Math.min(http.requestTimeout, 15000);
|
|
2116
|
+
http.keepAliveTimeout = 5000;
|
|
2117
|
+
http.maxHeadersCount = 100;
|
|
2118
|
+
let actualPort = opts.port;
|
|
2119
|
+
await new Promise((resolve, reject) => {
|
|
2120
|
+
http.once("error", reject);
|
|
2121
|
+
http.listen(opts.port, opts.host, () => {
|
|
2122
|
+
http.off("error", reject);
|
|
2123
|
+
resolve();
|
|
2124
|
+
});
|
|
2125
|
+
});
|
|
2126
|
+
actualPort = http.address().port;
|
|
2127
|
+
pushBase = `http://${opts.host === "0.0.0.0" ? "127.0.0.1" : opts.host === "::" ? "[::1]" : opts.host.includes(":") ? `[${opts.host}]` : opts.host}:${actualPort}`;
|
|
2128
|
+
try {
|
|
2129
|
+
for (const h of hosts.values()) await h.start();
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
http.close();
|
|
2132
|
+
http.closeAllConnections?.();
|
|
2133
|
+
const spares = server.spares.close();
|
|
2134
|
+
for (const h of hosts.values()) await h.close().catch(() => {});
|
|
2135
|
+
await spares;
|
|
2136
|
+
throw error;
|
|
2137
|
+
} finally {
|
|
2138
|
+
started();
|
|
2139
|
+
}
|
|
2140
|
+
// Outbound channel connections (email, Slack Socket Mode, the Discord gateway) open once the canvases are up; a failure to connect is the channel's status, not the server's.
|
|
2141
|
+
await channels?.start();
|
|
2142
|
+
await gateways?.start();
|
|
2143
|
+
for (const g of gateways?.status() ?? []) opts.stdout(`mallory serve: gateway ${g.id} (${g.kind}) at /_gateway/${g.id}/<operation>, grant required`);
|
|
2144
|
+
// Scheduled runs start once the canvases are up. Nothing fires at start: the first fire is the first cron time after now.
|
|
2145
|
+
let scheduler;
|
|
2146
|
+
if (opts.schedules) {
|
|
2147
|
+
scheduler = createScheduler({
|
|
2148
|
+
schedules: opts.schedules.list,
|
|
2149
|
+
clock: opts.clock,
|
|
2150
|
+
holder,
|
|
2151
|
+
hostOf: (route) => hosts.get(route),
|
|
2152
|
+
provider: opts.schedules.bundles,
|
|
2153
|
+
serverHosts: opts.schedules.serverHosts ?? [],
|
|
2154
|
+
allowAll: Boolean(opts.schedules.allowAll),
|
|
2155
|
+
notifier: opts.schedules.notifier,
|
|
2156
|
+
record: (entry) => server.record(entry),
|
|
2157
|
+
save: () => server.saveState(),
|
|
2158
|
+
scrub,
|
|
2159
|
+
warn: server.warn,
|
|
2160
|
+
say: (text) => opts.stdout(scrub(text)),
|
|
2161
|
+
announce: (sch) => opts.operator?.noteParked({ schedule: sch.id, canvas: sch.canvas }),
|
|
2162
|
+
});
|
|
2163
|
+
scheduler.start();
|
|
2164
|
+
}
|
|
2165
|
+
// --remote-listen: a second, TLS-only listener for paired pages on other computers (src/headless/runner-remote.js).
|
|
2166
|
+
// It answers the monitor's read-only routes and pairing, nothing else; the listener above is unchanged.
|
|
2167
|
+
let remote;
|
|
2168
|
+
if (opts.remote) {
|
|
2169
|
+
if (!opts.monitor) {
|
|
2170
|
+
http.close();
|
|
2171
|
+
throw new Error("--remote-listen needs the monitor (--monitor-env)");
|
|
2172
|
+
}
|
|
2173
|
+
const { createRemoteRunner, startRemoteListener, allowedHostNames } = await import("./runner-remote.js");
|
|
2174
|
+
const hostNames = allowedHostNames({ listenHost: opts.remote.listen.host, names: opts.remote.names });
|
|
2175
|
+
const runner = createRemoteRunner({ identity: opts.remote.identity, pages: opts.remote.pages, origin: opts.monitor.origin, monitor: opts.monitor, hosts: hostNames, port: opts.remote.listen.port, scrub, stdout: opts.stdout, now: opts.remote.now ?? Date.now, limits: opts.remote.limits });
|
|
2176
|
+
let listener;
|
|
2177
|
+
try {
|
|
2178
|
+
listener = await startRemoteListener({ identity: opts.remote.identity, remote: runner, listen: opts.remote.listen, canvases: canvasList, stderr: opts.stderr });
|
|
2179
|
+
} catch (error) {
|
|
2180
|
+
http.close();
|
|
2181
|
+
throw error;
|
|
2182
|
+
}
|
|
2183
|
+
runner.setPort(listener.port);
|
|
2184
|
+
remote = { url: listener.url, port: listener.port, runner, close: listener.close, hosts: hostNames };
|
|
2185
|
+
}
|
|
2186
|
+
const shown = opts.host.includes(":") ? `[${opts.host}]` : opts.host;
|
|
2187
|
+
const url = `http://${shown}:${actualPort}`;
|
|
2188
|
+
const routes = [...hosts.values()].flatMap((h) => h.plan.webhooks.map((w) => ({ canvas: h.route, methods: w.settings.methods, path: `/${h.route}/${w.path}`, respond: w.respond ? true : false, isolated: w.isolated })));
|
|
2189
|
+
let closing;
|
|
2190
|
+
return {
|
|
2191
|
+
url,
|
|
2192
|
+
port: actualPort,
|
|
2193
|
+
host: opts.host,
|
|
2194
|
+
routes,
|
|
2195
|
+
/** The WebSocket proxies: `{ canvas, path, upstream }` (the upstream's host and path, no credentials). */
|
|
2196
|
+
sockets: [...hosts.values()].flatMap((h) => (h.plan.wsProxies ?? []).map((p) => ({ canvas: h.route, path: `/${h.route}/${p.path}`, upstream: p.settings.upstream.replace(/^(wss?:\/\/)[^/]*@/, "$1") }))),
|
|
2197
|
+
hosts,
|
|
2198
|
+
/** The panes served over --mcp, all canvases (0 when it is off). */
|
|
2199
|
+
get mcpPaneCount() {
|
|
2200
|
+
return opts.mcp ? [...hosts.values()].reduce((n, h) => n + h.mcpPanes().length, 0) : 0;
|
|
2201
|
+
},
|
|
2202
|
+
/** The scheduler (--schedule-file), or undefined: `fire(schedule)`, `parked(viewer)`, `answer(...)`. */
|
|
2203
|
+
scheduler,
|
|
2204
|
+
/** The remote listener (--remote-listen): `{ url, port, runner, close }`, or undefined. */
|
|
2205
|
+
remote,
|
|
2206
|
+
/** The spare worker threads (--isolate-threads): `count` started. */
|
|
2207
|
+
spares: server.spares,
|
|
2208
|
+
/** Reload a canvas from a new version of its file (checked by the caller). */
|
|
2209
|
+
reload(route, doc, plan, revision) {
|
|
2210
|
+
hosts.get(route)?.reload(doc, plan, revision);
|
|
2211
|
+
},
|
|
2212
|
+
close() {
|
|
2213
|
+
closing ??= (async () => {
|
|
2214
|
+
scheduler?.stop();
|
|
2215
|
+
for (let waited = 0; scheduler?.busy && waited < 100; waited++) await new Promise((r) => setTimeout(r, 50)); // a scheduled run in flight finishes (its deadline bounds it)
|
|
2216
|
+
server.streams.closeAll(); // so would an event stream
|
|
2217
|
+
wsProxy.closeAll(); // and a proxied socket
|
|
2218
|
+
wsEcho?.closeAll();
|
|
2219
|
+
await gateways?.stop(); // so do a module's connections, sockets and handler threads
|
|
2220
|
+
await channels?.stop(); // the outbound connections end first: nothing new reaches a canvas that is closing
|
|
2221
|
+
opts.monitor?.close?.(); // a stream held open would keep the server from closing
|
|
2222
|
+
await remote?.close();
|
|
2223
|
+
await new Promise((resolve) => {
|
|
2224
|
+
http.close(() => resolve());
|
|
2225
|
+
http.closeIdleConnections?.();
|
|
2226
|
+
setTimeout(() => http.closeAllConnections?.(), 2000).unref();
|
|
2227
|
+
});
|
|
2228
|
+
const spares = server.spares.close(); // nothing takes one now: the HTTP server is closed and so are the queues below
|
|
2229
|
+
for (const h of hosts.values()) await h.close();
|
|
2230
|
+
await spares;
|
|
2231
|
+
await server.saveState();
|
|
2232
|
+
await logChain;
|
|
2233
|
+
await opts.operator?.flush();
|
|
2234
|
+
})();
|
|
2235
|
+
return closing;
|
|
2236
|
+
},
|
|
2237
|
+
};
|
|
2238
|
+
}
|