@johnhenry/mallory-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
package/src/agent/run.js
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
// Running an agent pane (src/panes/agent.js): gather its inputs, its tools
|
|
2
|
+
// and its memory, run the loop (./loop.js) against its provider
|
|
3
|
+
// (./providers.js), and store { text, data?, steps, usage } as its value.
|
|
4
|
+
//
|
|
5
|
+
// The loop runs here, on the page side of the model (the tools it calls are
|
|
6
|
+
// panes and canvas operations, and approvals are the person's). Everything
|
|
7
|
+
// that touches the outside runs in the sandbox as the agent pane
|
|
8
|
+
// (runtime.agent): its templates, its function tools, its model requests
|
|
9
|
+
// (the canvas's network policy; the key is a secret() placeholder filled in
|
|
10
|
+
// by the page) and its on-device model session (the AI bridge, with 's
|
|
11
|
+
// permissions, download prompt and token budgets).
|
|
12
|
+
//
|
|
13
|
+
// While it runs, `liveOf(canvas, id)` holds its trace (with the model's reply
|
|
14
|
+
// as it streams in) and the approvals it waits for; the pane's body
|
|
15
|
+
// (src/ui/agent-pane.js) draws them, on mallory's page, never in a sandboxed
|
|
16
|
+
// frame. An approval whose pane isn't on screen (collapsed, inside a closed
|
|
17
|
+
// subgraph, or in a subgraph an agent runs as a tool) is drawn with the
|
|
18
|
+
// network prompts instead (src/ui/agent-prompts.js, from `approvals`). Only a
|
|
19
|
+
// click on one of those cards answers an approval: no command or agent tool
|
|
20
|
+
// does. The pane's value is set once, when the run ends: the streamed text is
|
|
21
|
+
// the trace's alone.
|
|
22
|
+
import { skip } from "@johnhenry/dataflow";
|
|
23
|
+
import { signal as makeSignal } from "@johnhenry/signalle";
|
|
24
|
+
import { templateBody } from "../runtime/compile.js";
|
|
25
|
+
import { runLoop, AgentStop, Parked, brief } from "./loop.js";
|
|
26
|
+
import { restartPolicy, planRestart } from "./restart.js";
|
|
27
|
+
import { parkRecord, parkProblem, fingerprintOf, isExpired, memoryParkStore } from "./park.js";
|
|
28
|
+
import { canPrice, cleanPrice, DEFAULT_WATCHDOG, usd } from "./guards.js";
|
|
29
|
+
import { createProvider, TOOL_USE_OFF } from "./providers.js";
|
|
30
|
+
import { forkTurns, forkProblem, attemptStart, cannotReplayInto } from "./fork.js";
|
|
31
|
+
import { diffAgentRuns } from "./diff.js";
|
|
32
|
+
import { inputRole } from "./ports.js";
|
|
33
|
+
import { callSubgraph, functionTool, subgraphSchema, graphFetches, malloryTools, usesFetch } from "./tools.js";
|
|
34
|
+
import { graphPanes } from "../model/subgraph.js";
|
|
35
|
+
import { beginCall, noteRefused, AGENT_SERVER } from "../gate/gate.js";
|
|
36
|
+
import { callSeams } from "../gate/seams.js";
|
|
37
|
+
import { personsSafety } from "../safety/config.js";
|
|
38
|
+
import { narrowFor, tighter } from "../delegation/caps.js";
|
|
39
|
+
import { shapeRun } from "../agent-library/engine.js";
|
|
40
|
+
import { delegationSettings } from "../delegation/config.js";
|
|
41
|
+
import { scriptedDenial, unscripted } from "../gate/scripted.js";
|
|
42
|
+
import { cleanAttach, groundedMessage, groundingSummary } from "./grounding.js";
|
|
43
|
+
import { localTransport } from "./local-transport.js";
|
|
44
|
+
|
|
45
|
+
/** How many turns (a user message and the answer each) memory keeps. */
|
|
46
|
+
/** A tool that reaches outside the canvas's own content (the canvas-editing tools, an MCP server's): delegation hands these down only where the parent has them. A subgraph, a function and a question are the canvas's own. */
|
|
47
|
+
const isCapability = (tool) => !(["subgraph", "function", "question", "answer"].includes(tool.kind));
|
|
48
|
+
|
|
49
|
+
/** The verdict panes (src/panes/verdict.js) that can score this agent's calls: the ones on the canvas it runs in and on the root canvas. A verdict only ever tightens the tool gate. */
|
|
50
|
+
|
|
51
|
+
export const MEMORY_TURNS = 20;
|
|
52
|
+
|
|
53
|
+
/** How often (ms) the trace redraws while a reply streams in. */
|
|
54
|
+
export const STREAM_MS = 50;
|
|
55
|
+
|
|
56
|
+
// A template's text as a function body: ${…} interpolates (objects as JSON), everything else is literal.
|
|
57
|
+
const TEXT_TAG = "const __agentText = (s, ...v) => s.reduce((o, x, i) => o + x + (i < v.length ? (typeof v[i] === \"string\" ? v[i] : v[i] === undefined ? \"\" : JSON.stringify(v[i])) : \"\"), \"\");\n";
|
|
58
|
+
export const textBody = (text) => (String(text ?? "").trim() ? TEXT_TAG + templateBody(text).replace(/^return html`/, "return __agentText`") : "");
|
|
59
|
+
|
|
60
|
+
/** The live state of an agent pane's run: { runId, status, steps, pending: [{ key, tool, args, kind }] }. */
|
|
61
|
+
export function liveOf(canvas, id) {
|
|
62
|
+
canvas.agentLive ??= new Map();
|
|
63
|
+
let live = canvas.agentLive.get(id);
|
|
64
|
+
if (!live) canvas.agentLive.set(id, (live = makeSignal({ status: "idle", steps: [], pending: [] })));
|
|
65
|
+
return live;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The approvals waiting, per canvas: key -> resolve. */
|
|
69
|
+
const waiting = new WeakMap();
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Every approval waiting, on any canvas: `pending` is [{ canvas, id, key, tool,
|
|
73
|
+
* kind, args }]. It changes too when a pane body starts or stops showing a
|
|
74
|
+
* pane's cards (showApprovals), so the page can draw the waiting ones no body
|
|
75
|
+
* shows (src/ui/agent-prompts.js).
|
|
76
|
+
*/
|
|
77
|
+
export const approvals = makeSignal({ pending: [] });
|
|
78
|
+
const viewed = new WeakMap(); // canvas -> Map(id -> count)
|
|
79
|
+
|
|
80
|
+
/** A pane body now shows pane `id`'s approval cards; call the result when it stops. */
|
|
81
|
+
export function showApprovals(canvas, id) {
|
|
82
|
+
let map = viewed.get(canvas);
|
|
83
|
+
if (!map) viewed.set(canvas, (map = new Map()));
|
|
84
|
+
map.set(id, (map.get(id) ?? 0) + 1);
|
|
85
|
+
approvals.value = { ...approvals.value };
|
|
86
|
+
let done = false;
|
|
87
|
+
return () => {
|
|
88
|
+
if (done) return;
|
|
89
|
+
done = true;
|
|
90
|
+
const n = (map.get(id) ?? 1) - 1;
|
|
91
|
+
if (n > 0) map.set(id, n);
|
|
92
|
+
else map.delete(id);
|
|
93
|
+
approvals.value = { ...approvals.value };
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Is pane `id`'s body on screen to show its approval cards? */
|
|
98
|
+
export const approvalsShown = (canvas, id) => (viewed.get(canvas)?.get(id) ?? 0) > 0;
|
|
99
|
+
|
|
100
|
+
/** The approvals waiting under root canvas `root` that no pane body shows. */
|
|
101
|
+
export function offScreenApprovals(root) {
|
|
102
|
+
return approvals.value.pending.filter((p) => p.canvas.root === root && !approvalsShown(p.canvas, p.id));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The person answered an approval card: "approve", "always" (this tool, for
|
|
107
|
+
* the rest of this run) or "deny". Only the pane's card calls this.
|
|
108
|
+
*/
|
|
109
|
+
export function answerApproval(canvas, id, key, choice, { text } = {}) {
|
|
110
|
+
const resolve = waiting.get(canvas)?.get(`${id}|${key}`);
|
|
111
|
+
if (!resolve) return false;
|
|
112
|
+
if (choice === "later") return resolve({ park: true }), true; // "Not now": the run is kept (only offered when the pane allows parking)
|
|
113
|
+
const chose = choice === "approve" || choice === "always" ? choice : "deny";
|
|
114
|
+
// An approval of the agent's final answer may carry the person's edit of it (`approveAnswer`).
|
|
115
|
+
resolve(chose !== "deny" && typeof text === "string" ? { choice: chose, text } : chose);
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The pseudo-tool the person's approval of an agent's final answer is asked as (a pane's `approveAnswer`); a script answers it as tool "answer". */
|
|
120
|
+
const ANSWER = { name: "answer", kind: "answer", server: AGENT_SERVER, gateTool: "answer" };
|
|
121
|
+
|
|
122
|
+
let approvalSeq = 0;
|
|
123
|
+
|
|
124
|
+
// Forks asked for and not started yet, per canvas: pane id -> { turns, base, source: { runId, steps }, at, edited, runId? }.
|
|
125
|
+
// A fork is for the one run forkAgentRun's canvas.run starts (its dataflow run id, `runId`, set when that run
|
|
126
|
+
// starts): a run that doesn't reach runAgentPane (deactivated meanwhile, a breakpoint cancelled or skipped, an input
|
|
127
|
+
// that skipped, superseded) drops it, so a later ordinary run never replays it.
|
|
128
|
+
const forks = new WeakMap();
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Fork agent pane `id`'s last run at trace step index `at` (see ./fork.js):
|
|
132
|
+
* its earlier model replies and tool results are replayed as they were, with
|
|
133
|
+
* `edit` (a tool step's `{ result }` or `{ error }`, a model step's `{ text,
|
|
134
|
+
* calls }`) applied to that step, and the run goes on live from there as a new
|
|
135
|
+
* run of the pane. Only a run from this session can be forked (the trace is
|
|
136
|
+
* kept in memory while the page is open), and not while the pane runs. Throws
|
|
137
|
+
* an Error saying why it can't. Nothing here can approve a tool call: the
|
|
138
|
+
* live part asks the person as any run does.
|
|
139
|
+
*/
|
|
140
|
+
export function forkAgentRun(canvas, id, { at, edit } = {}) {
|
|
141
|
+
const pane = canvas.panes.get(id);
|
|
142
|
+
if (pane?.type !== "agent") throw new Error(`There is no agent pane ${JSON.stringify(id)}.`);
|
|
143
|
+
const live = liveOf(canvas, id).value;
|
|
144
|
+
if (live.status === "running") throw new Error("The agent is running: fork it once it has finished, or stop it first.");
|
|
145
|
+
if (!live.steps?.length || !live.base) throw new Error("This agent hasn't run in this session, so there is no trace to fork (a trace is kept in memory while the page is open).");
|
|
146
|
+
if (!["done", "stopped", "error"].includes(live.status)) throw new Error(`The agent's last run ended ${live.status}: there is no finished trace to fork.`);
|
|
147
|
+
const refusal = cannotReplayInto(pane.provider ?? "chrome");
|
|
148
|
+
if (refusal) throw new Error(refusal);
|
|
149
|
+
// No run would start now, so nothing would take the fork (or a much later run would).
|
|
150
|
+
if (canvas.flow.paused) throw new Error("The canvas is paused: run it first, then fork.");
|
|
151
|
+
if (canvas.isDisabled(id)) throw new Error("The agent pane is deactivated: activate it first, then fork.");
|
|
152
|
+
if (canvas.pinActive(id)) throw new Error("The agent pane is pinned (its pin stands in for a run): unpin it first, then fork.");
|
|
153
|
+
const { turns, edited } = forkTurns(live.steps, at, edit);
|
|
154
|
+
let map = forks.get(canvas);
|
|
155
|
+
if (!map) forks.set(canvas, (map = new Map()));
|
|
156
|
+
const fork = { turns, base: live.base, source: { runId: live.runId, steps: live.steps }, at, edited };
|
|
157
|
+
map.set(id, fork);
|
|
158
|
+
// Key it to the run canvas.run starts: the pane's first run after this one. When that run ends (or a later one
|
|
159
|
+
// does) without having taken it, it goes.
|
|
160
|
+
const after = canvas.flow.get(id)?.runId ?? 0;
|
|
161
|
+
const stop = canvas.flow.subscribe((node, state) => {
|
|
162
|
+
if (node !== id || !(state.runId > after)) return;
|
|
163
|
+
if (state.status === "running") fork.runId ??= state.runId;
|
|
164
|
+
else if (state.status !== "waiting") {
|
|
165
|
+
stop();
|
|
166
|
+
if (map.get(id) === fork) map.delete(id);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
canvas.hint(`fork ${pane.name || id} at step ${at + 1}`, { strong: true });
|
|
170
|
+
canvas.run(id);
|
|
171
|
+
return { ok: true, edited };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The fork set aside for run `runId` of pane `id`, taken; a fork set aside for another run goes (it was for that run only). */
|
|
175
|
+
const takeFork = (canvas, id, runId) => {
|
|
176
|
+
const map = forks.get(canvas);
|
|
177
|
+
const fork = map?.get(id);
|
|
178
|
+
if (!fork) return undefined;
|
|
179
|
+
map.delete(id);
|
|
180
|
+
return fork.runId === runId ? fork : undefined;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// ── parked runs (src/agent/park.js) ────────────────────────────────────────────────────────
|
|
184
|
+
|
|
185
|
+
const parkedByCanvas = new WeakMap(); // canvas -> Map(pane id -> { request, key })
|
|
186
|
+
const parkAnswers = new WeakMap(); // canvas -> Map(pane id -> { choice, text? }): the person's answer, for the run it starts
|
|
187
|
+
const parkTimers = new WeakMap(); // canvas -> Map(pane id -> timer)
|
|
188
|
+
const perMap = (weak, canvas) => weak.get(canvas) ?? (weak.set(canvas, new Map()), weak.get(canvas));
|
|
189
|
+
let parkSeq = 0;
|
|
190
|
+
|
|
191
|
+
/** What the parked run of agent pane `id` is waiting for: `{ kind, tool?, args?, question?, text? }`, or undefined when it isn't parked. */
|
|
192
|
+
export const parkedRequest = (canvas, id) => parkedByCanvas.get(canvas)?.get(id)?.request;
|
|
193
|
+
|
|
194
|
+
/** The canvas's store of parked runs: the page's IndexedDB (src/agent/park-store.js), else memory for this process. */
|
|
195
|
+
export async function parkStoreOf(canvas) {
|
|
196
|
+
const root = canvas.root;
|
|
197
|
+
if (root.parkStore) return root.parkStore;
|
|
198
|
+
if (root.interactive) {
|
|
199
|
+
try {
|
|
200
|
+
root.parkStore = (await import("./park-store.js")).browserParkStore;
|
|
201
|
+
} catch {
|
|
202
|
+
root.parkStore = memoryParkStore();
|
|
203
|
+
}
|
|
204
|
+
} else root.parkStore = memoryParkStore();
|
|
205
|
+
return root.parkStore;
|
|
206
|
+
}
|
|
207
|
+
export const parkKey = (canvas, id) => [canvas.root.id, canvas === canvas.root ? id : `${canvas.id}:${id}`];
|
|
208
|
+
|
|
209
|
+
/** Show the parked request as a card in the pane (and with the other approvals), and watch for its deadline. */
|
|
210
|
+
function showParked(canvas, id, live, runId, record) {
|
|
211
|
+
const key = `p${++parkSeq}`;
|
|
212
|
+
const r = record.request;
|
|
213
|
+
const card = {
|
|
214
|
+
key,
|
|
215
|
+
parked: true,
|
|
216
|
+
tool: r.kind === "approval" ? r.tool : r.kind === "answer" ? "answer" : "ask_person",
|
|
217
|
+
kind: r.kind === "approval" ? r.toolKind : r.kind,
|
|
218
|
+
args: r.kind === "approval" ? r.args : r.kind === "answer" ? { text: r.text } : { question: r.question },
|
|
219
|
+
};
|
|
220
|
+
perMap(parkedByCanvas, canvas).set(id, { request: r, key });
|
|
221
|
+
live.value = { ...live.value, runId, status: "parked", pending: [card], base: record.base };
|
|
222
|
+
approvals.value = { ...approvals.value, pending: [...approvals.value.pending.filter((p) => !(p.canvas === canvas && p.id === id)), { canvas, id, ...card }] };
|
|
223
|
+
const timers = perMap(parkTimers, canvas);
|
|
224
|
+
clearTimeout(timers.get(id));
|
|
225
|
+
const timer = setTimeout(() => {
|
|
226
|
+
timers.delete(id);
|
|
227
|
+
if (perMap(parkedByCanvas, canvas).has(id)) canvas.run(id); // the park is over: the run starts, finds it so, and ends with parkExpired
|
|
228
|
+
}, Math.max(0, record.deadlineAt - Date.now()));
|
|
229
|
+
timer.unref?.();
|
|
230
|
+
timers.set(id, timer);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function forgetParked(canvas, id) {
|
|
234
|
+
parkedByCanvas.get(canvas)?.delete(id);
|
|
235
|
+
clearTimeout(parkTimers.get(canvas)?.get(id));
|
|
236
|
+
parkTimers.get(canvas)?.delete(id);
|
|
237
|
+
approvals.value = { ...approvals.value, pending: approvals.value.pending.filter((p) => !(p.canvas === canvas && p.id === id && p.parked)) };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The person's answer to a parked run: "approve", "always" or "deny" (and `text`: the edit of an answer, or the answer to a question).
|
|
242
|
+
* The run goes on from where it stopped. Only a card calls this; no tool does. False when nothing is parked.
|
|
243
|
+
*/
|
|
244
|
+
export function answerParked(canvas, id, choice, { text } = {}) {
|
|
245
|
+
if (!parkedByCanvas.get(canvas)?.has(id)) return false;
|
|
246
|
+
const chose = choice === "approve" || choice === "always" ? choice : "deny";
|
|
247
|
+
perMap(parkAnswers, canvas).set(id, { choice: chose, ...(typeof text === "string" ? { text } : {}) });
|
|
248
|
+
forgetParked(canvas, id);
|
|
249
|
+
canvas.run(id);
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function askPerson(canvas, id, live, { tool, call, signal, canPark = false }) {
|
|
254
|
+
// Nobody is here to approve (a headless run, a canvas test): the person's approvals script answers (src/gate/scripted.js,
|
|
255
|
+
// set only by a headless run from a test's own field or the CLI's flags), else the call is refused, and the model told why.
|
|
256
|
+
if (!canvas.root.interactive) {
|
|
257
|
+
const script = canvas.root.approvalScript;
|
|
258
|
+
const server = tool.server ?? AGENT_SERVER;
|
|
259
|
+
const scripted = script?.answer({ server, tool: tool.gateTool ?? tool.name, names: [tool.name], args: call.args }) ?? null;
|
|
260
|
+
if (!scripted && !script && canPark) return Promise.resolve({ park: true }); // nobody is here, nothing is scripted: keep the run for later
|
|
261
|
+
if (!scripted) return Promise.resolve({ reason: script ? unscripted(server, tool.gateTool ?? tool.name) : tool.kind === "question" ? "Nobody is here to answer this question (this canvas is running headless or as a test)." : tool.kind === "answer" ? "The agent stopped: its answer needs a person's approval and nobody is here to give it (this canvas is running headless or as a test, with no approval script for \"answer\")." : "Nobody is here to approve this tool call (this canvas is running headless or as a test), so it wasn't run." });
|
|
262
|
+
if (scripted.decision === "deny") return Promise.resolve({ choice: "deny", scripted: true, source: script.source, reason: scriptedDenial(server, tool.gateTool ?? tool.name, scripted.reason) });
|
|
263
|
+
return Promise.resolve({ choice: "approve", scripted: true, source: script.source, ...(scripted.decision === "amend" ? { args: scripted.args } : {}) });
|
|
264
|
+
}
|
|
265
|
+
const key = `a${++approvalSeq}`;
|
|
266
|
+
let map = waiting.get(canvas);
|
|
267
|
+
if (!map) waiting.set(canvas, (map = new Map()));
|
|
268
|
+
return new Promise((resolve) => {
|
|
269
|
+
const done = (choice) => {
|
|
270
|
+
map.delete(`${id}|${key}`);
|
|
271
|
+
signal?.removeEventListener("abort", onAbort);
|
|
272
|
+
live.value = { ...live.value, pending: live.value.pending.filter((p) => p.key !== key) };
|
|
273
|
+
approvals.value = { ...approvals.value, pending: approvals.value.pending.filter((p) => !(p.canvas === canvas && p.id === id && p.key === key)) };
|
|
274
|
+
resolve(choice);
|
|
275
|
+
};
|
|
276
|
+
const onAbort = () => done("deny");
|
|
277
|
+
map.set(`${id}|${key}`, done);
|
|
278
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
279
|
+
const request = { key, tool: tool.name, kind: tool.kind, args: call.args, ...(canPark ? { canPark: true } : {}) };
|
|
280
|
+
live.value = { ...live.value, pending: [...live.value.pending, request] };
|
|
281
|
+
approvals.value = { ...approvals.value, pending: [...approvals.value.pending, { canvas, id, ...request }] };
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Does Chrome's on-device model really do tool use? Asked once per
|
|
286
|
+
// runtime, which on the page is once per page load (the browser doesn't
|
|
287
|
+
// change under it), and kept here in memory only: never in a canvas, its file
|
|
288
|
+
// or its share link. Panes that ask while a check is under way wait for it; a
|
|
289
|
+
// check that didn't finish (a refusal, a budget, a stop) isn't kept, and the
|
|
290
|
+
// next agent pane with tools asks again.
|
|
291
|
+
const toolUseChecks = new WeakMap(); // runtime -> { result } | { pending }
|
|
292
|
+
|
|
293
|
+
/** The tool-use check for `runtime`: `{ supported, by, detail, tokens?, earlier? }` (earlier: this page found it out before). */
|
|
294
|
+
export async function chromeToolUse(runtime, provider, signal) {
|
|
295
|
+
for (;;) {
|
|
296
|
+
if (signal?.aborted) throw Object.assign(new Error("superseded by a newer run"), { name: "AbortError" });
|
|
297
|
+
const known = toolUseChecks.get(runtime);
|
|
298
|
+
if (known?.result) return { ...known.result, earlier: true };
|
|
299
|
+
if (known?.pending) {
|
|
300
|
+
try {
|
|
301
|
+
return { ...(await untilAborted(known.pending, signal)), earlier: true };
|
|
302
|
+
} catch {
|
|
303
|
+
continue; // that pane's check didn't finish (or this run was stopped): check for this one
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const entry = { pending: provider.toolUse() };
|
|
307
|
+
toolUseChecks.set(runtime, entry);
|
|
308
|
+
try {
|
|
309
|
+
const result = await entry.pending;
|
|
310
|
+
if (toolUseChecks.get(runtime) === entry) toolUseChecks.set(runtime, { result });
|
|
311
|
+
return result;
|
|
312
|
+
} catch (error) {
|
|
313
|
+
if (toolUseChecks.get(runtime) === entry) toolUseChecks.delete(runtime);
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** `promise`, or an AbortError as soon as `signal` aborts (the promise goes on for whoever else waits on it). */
|
|
320
|
+
function untilAborted(promise, signal) {
|
|
321
|
+
if (!signal) return promise;
|
|
322
|
+
let onAbort;
|
|
323
|
+
const stopped = new Promise((_, reject) => signal.addEventListener("abort", (onAbort = () => reject(Object.assign(new Error("superseded by a newer run"), { name: "AbortError" }))), { once: true }));
|
|
324
|
+
return Promise.race([promise, stopped]).finally(() => signal.removeEventListener("abort", onAbort));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** The tool-use check as a step of the trace. */
|
|
328
|
+
function toolUseStep(check) {
|
|
329
|
+
const how = check.earlier ? "checked earlier on this page" : check.by === "availability" ? "LanguageModel.availability()" : "a test session with one tool";
|
|
330
|
+
return { type: "check", status: check.supported ? "done" : "error", text: `Chrome's tool use ${check.supported ? "works" : "is off"} (${how}): ${check.detail}`, ...(check.tokens && !check.earlier ? { tokens: { input: check.tokens, output: 0 } } : {}) };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Wait `ms` (a restart's backoff), or reject with an AbortError as soon as `signal` aborts (a newer run). */
|
|
334
|
+
function pause(ms, signal) {
|
|
335
|
+
return new Promise((resolve, reject) => {
|
|
336
|
+
const abort = () => reject(Object.assign(new Error("superseded by a newer run"), { name: "AbortError" }));
|
|
337
|
+
if (signal?.aborted) return abort();
|
|
338
|
+
const timer = setTimeout(() => (signal?.removeEventListener("abort", abort), resolve()), ms);
|
|
339
|
+
signal?.addEventListener("abort", () => (clearTimeout(timer), abort()), { once: true });
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The conversation memory a state pane holds: [{ role, text }]. Anything else is no memory. */
|
|
344
|
+
export function memoryTurns(value) {
|
|
345
|
+
if (!Array.isArray(value)) return [];
|
|
346
|
+
return value.filter((m) => m && (m.role === "user" || m.role === "assistant") && typeof m.text === "string").map((m) => ({ role: m.role, text: m.text }));
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Run agent pane `id` on `canvas` (the canvas model's #run, for type "agent"). */
|
|
350
|
+
export async function runAgentPane(canvas, id, ctx) {
|
|
351
|
+
// An unattended run (a schedule or a headless goal: `canvas.root.unattended`, set by src/autonomy/unattended.js, never by a document or a tool) runs only inside a
|
|
352
|
+
// grant the person signed in advance (docs/design/grant-bundle.md). `unat.auth` is its handle; the run is settled here, whatever way it ends.
|
|
353
|
+
const unat = canvas.root.unattended === true ? { auth: null, outcome: undefined, cost: undefined, unpriced: 0, carry: 0 } : null;
|
|
354
|
+
if (!unat) return runAgentPaneNow(canvas, id, ctx, null);
|
|
355
|
+
let failure;
|
|
356
|
+
try {
|
|
357
|
+
const result = await runAgentPaneNow(canvas, id, ctx, unat);
|
|
358
|
+
if (unat.outcome === undefined) unat.outcome = "aborted"; // a skip or a supersede says nothing about whether the routine works
|
|
359
|
+
return result;
|
|
360
|
+
} catch (error) {
|
|
361
|
+
failure = error;
|
|
362
|
+
const usage = error?.partial?.usage;
|
|
363
|
+
if (usage) Object.assign(unat, { cost: usage.cost, unpriced: usage.unpriced ?? 0 });
|
|
364
|
+
unat.outcome = error?.name === "AbortError" ? "aborted" : unat.outcome === "parked" ? "parked" : "failed";
|
|
365
|
+
throw error;
|
|
366
|
+
} finally {
|
|
367
|
+
if (unat.auth) {
|
|
368
|
+
const spent = typeof unat.cost === "number" ? Math.max(0, unat.cost - unat.carry) : undefined; // a resumed run carries what its earlier part spent; the ledger already has it
|
|
369
|
+
await unat.auth.settle({ outcome: unat.outcome ?? "failed", cost: spent, unpriced: unat.unpriced, reason: failure?.message });
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async function runAgentPaneNow(canvas, id, { runId, signal }, unat) {
|
|
375
|
+
const pane = canvas.panes.get(id);
|
|
376
|
+
const runtime = canvas.runtime;
|
|
377
|
+
const live = liveOf(canvas, id);
|
|
378
|
+
const label = pane.name || id;
|
|
379
|
+
let fork = takeFork(canvas, id, runId); // a fork asked for (forkAgentRun): this run replays the source's turns first
|
|
380
|
+
let forkOf = fork && { of: fork.source.runId, at: fork.at, edited: fork.edited };
|
|
381
|
+
// A parked run (src/agent/park.js) that the person answered goes on as a fork of itself would: its recorded turns are replayed, and the
|
|
382
|
+
// answer is given to the first request that matches the one it was parked on. These are set below, once the stored record is read.
|
|
383
|
+
let resumed = null; // { record, answer, used }
|
|
384
|
+
let reparked = false;
|
|
385
|
+
let restarts = 0; // how many times this run has been started again (src/agent/restart.js)
|
|
386
|
+
const canPark = Number(pane.parkMs) > 0 && !cannotReplayInto(pane.provider ?? "chrome");
|
|
387
|
+
const takePre = (kind, tool) => {
|
|
388
|
+
if (!resumed || resumed.used || resumed.record.request.kind !== kind || (tool !== undefined && resumed.record.request.tool !== tool)) return null;
|
|
389
|
+
resumed.used = true;
|
|
390
|
+
return resumed.answer;
|
|
391
|
+
};
|
|
392
|
+
live.value = { runId, status: "running", steps: [], pending: [], ...(forkOf ? { fork: forkOf } : {}) };
|
|
393
|
+
const finish = (status, extra = {}) => {
|
|
394
|
+
if (live.value.runId !== runId) return;
|
|
395
|
+
// A fork: how it differs from the run it came from, with the steps it has now.
|
|
396
|
+
const diff = fork && !fork.resume && live.value.steps.length ? diffAgentRuns({ steps: fork.source.steps, text: fork.base.answer, data: fork.base.data }, { steps: live.value.steps, text: extra.base?.answer, data: extra.base?.data }) : undefined;
|
|
397
|
+
live.value = { ...live.value, status, pending: [], ...extra, ...(forkOf ? { fork: { ...forkOf, ...(diff ? { diff: { identical: diff.identical, shared: diff.shared, ...(diff.firstDivergent ? { firstDivergent: diff.firstDivergent } : {}) } } : {}) } } : {}) };
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
try {
|
|
401
|
+
// A run parked earlier (and reloaded since): shown as its question, resumed by the person's answer, or over (its park ran out).
|
|
402
|
+
const store = await parkStoreOf(canvas);
|
|
403
|
+
const [storeCanvas, storePane] = parkKey(canvas, id);
|
|
404
|
+
let stored = await store.get(storeCanvas, storePane);
|
|
405
|
+
if (stored && parkProblem(stored)) {
|
|
406
|
+
await store.delete(storeCanvas, storePane);
|
|
407
|
+
stored = undefined;
|
|
408
|
+
}
|
|
409
|
+
if (stored) {
|
|
410
|
+
const answer = perMap(parkAnswers, canvas).get(id);
|
|
411
|
+
perMap(parkAnswers, canvas).delete(id);
|
|
412
|
+
forgetParked(canvas, id);
|
|
413
|
+
if (isExpired(stored, Date.now())) {
|
|
414
|
+
await store.delete(storeCanvas, storePane);
|
|
415
|
+
throw new AgentStop("parkExpired", `The run was parked for longer than its limit (${stored.parkMs} ms) without an answer, so it ended. Nothing it was waiting to do ran.`);
|
|
416
|
+
}
|
|
417
|
+
if (stored.fingerprint !== fingerprintOf(pane)) {
|
|
418
|
+
await store.delete(storeCanvas, storePane); // the pane changed while it was parked: that run is stale, this one starts over
|
|
419
|
+
stored = undefined;
|
|
420
|
+
} else if (!answer) {
|
|
421
|
+
showParked(canvas, id, live, runId, stored);
|
|
422
|
+
return skip("parked: waiting for a person's answer");
|
|
423
|
+
} else {
|
|
424
|
+
const problem = forkProblem(stored.steps, stored.at);
|
|
425
|
+
if (problem) throw new Error(`The parked run can't be resumed: ${problem}`);
|
|
426
|
+
resumed = { record: stored, answer, used: false };
|
|
427
|
+
restarts = stored.restarts ?? 0;
|
|
428
|
+
fork = { turns: forkTurns(stored.steps, stored.at).turns, base: stored.base, source: { runId: stored.runId, steps: stored.steps }, at: stored.at, edited: false, resume: true };
|
|
429
|
+
forkOf = null;
|
|
430
|
+
live.value = { runId, status: "running", steps: [], pending: [], base: stored.base };
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
// Unattended: the grant decides, before anything is asked of the model. No authority, or a refusal, is a stop (fail closed).
|
|
434
|
+
if (unat) {
|
|
435
|
+
const authority = canvas.root.autonomy;
|
|
436
|
+
if (!authority || typeof authority.begin !== "function") throw new AgentStop("autonomy", "The agent didn't start: it was asked to run unattended and nothing here can check a grant, so it was refused. Make a grant in settings and run it from a schedule.");
|
|
437
|
+
const got = await authority.begin({ canvasId: canvas.root.id, paneId: canvas === canvas.root ? id : `${canvas.id}:${id}`, pane: { maxCostUsd: pane.maxCostUsd, maxDurationMs: pane.maxDurationMs } });
|
|
438
|
+
if (!got?.ok) throw new AgentStop("autonomy", got?.reason ?? "The agent didn't start: its grant could not be checked.");
|
|
439
|
+
const sound = (n) => Number.isFinite(n) && n > 0;
|
|
440
|
+
if (!sound(got.caps?.maxCostUsd) || !sound(got.caps?.maxDurationMs) || typeof got.check !== "function" || typeof got.settle !== "function") {
|
|
441
|
+
await got.settle?.({ outcome: "failed", reason: "an unsound grant handle" }); // (fail closed: a handle without caps would mean no caps)
|
|
442
|
+
throw new AgentStop("autonomy", "The agent didn't start: its grant came back without the caps it must run inside.");
|
|
443
|
+
}
|
|
444
|
+
unat.auth = got;
|
|
445
|
+
unat.carry = Number(resumed?.record.usage?.cost) || 0;
|
|
446
|
+
}
|
|
447
|
+
// Inputs: values (variables, the message, function tools), subgraph tools, memory.
|
|
448
|
+
const roles = pane.inputs.map((input) => ({ input, role: inputRole(canvas, input) }));
|
|
449
|
+
const values = roles.filter((r) => r.role === "value");
|
|
450
|
+
const prep = await runtime.agent({
|
|
451
|
+
id,
|
|
452
|
+
runId,
|
|
453
|
+
op: "prepare",
|
|
454
|
+
sources: values.map((r) => canvas.sourceKey(id, r.input)), // an output's value for a wire from one (src/model/ports.js)
|
|
455
|
+
names: values.map((r) => r.input.name),
|
|
456
|
+
payload: { system: textBody(pane.system), prompt: textBody(pane.prompt), label },
|
|
457
|
+
});
|
|
458
|
+
if (signal?.aborted || prep?.superseded) return { superseded: true };
|
|
459
|
+
const said = fork ? fork.base.userText : pane.prompt?.trim() ? prep.prompt : (prep.message ?? "");
|
|
460
|
+
if (!said.trim()) {
|
|
461
|
+
finish("skipped");
|
|
462
|
+
return skip("no message: wire an input named `message`, or write a prompt");
|
|
463
|
+
}
|
|
464
|
+
// Composer mode (#545): answers of MCP tools the person ran by hand, attached to this message (used up by this run).
|
|
465
|
+
const attached = fork ? [] : cleanAttach(pane.attach);
|
|
466
|
+
const userText = attached.length ? groundedMessage(said, attached) : said;
|
|
467
|
+
|
|
468
|
+
// Memory: a state pane wired as `memory` (its value when this run starts).
|
|
469
|
+
const memory = roles.find((r) => r.role === "memory");
|
|
470
|
+
const memoryKey = memory ? canvas.homeOf(memory.input.source).key : undefined;
|
|
471
|
+
let remembered = [];
|
|
472
|
+
if (memoryKey) {
|
|
473
|
+
try {
|
|
474
|
+
remembered = memoryTurns((await runtime.clone([memoryKey]))[0]);
|
|
475
|
+
} catch {
|
|
476
|
+
remembered = []; // not run yet, or not data
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
// A fork goes on from the conversation as the source began it.
|
|
480
|
+
const history = fork ? fork.base.history.map((m) => ({ ...m })) : [...remembered.slice(-2 * MEMORY_TURNS), { role: "user", text: userText }];
|
|
481
|
+
// A named agent the person bound to this pane (src/agent-library/): its instructions come first and its caps and tool list can only tighten the pane's own.
|
|
482
|
+
const named = canvas === canvas.root ? canvas.root.agentLibrary?.resolve?.(canvas.root.id, id) ?? null : null;
|
|
483
|
+
const shaped = shapeRun(named, { system: prep.system, maxSteps: Number(pane.maxSteps) || 0, maxCostUsd: Number(pane.maxCostUsd) || 0, maxDurationMs: Number(pane.maxDurationMs) || 0 });
|
|
484
|
+
const system = fork ? fork.base.system : shaped.system;
|
|
485
|
+
const base = fork ? { ...fork.base } : { history: history.map((m) => ({ ...m })), system, userText };
|
|
486
|
+
live.value = { ...live.value, base };
|
|
487
|
+
|
|
488
|
+
// Tools.
|
|
489
|
+
const ask = new Set(Array.isArray(pane.ask) ? pane.ask : []);
|
|
490
|
+
const tools = [];
|
|
491
|
+
for (const { input, role } of roles) {
|
|
492
|
+
if (role !== "tool") continue;
|
|
493
|
+
const content = canvas.panes.get(input.source);
|
|
494
|
+
tools.push({
|
|
495
|
+
name: input.name,
|
|
496
|
+
kind: "subgraph",
|
|
497
|
+
// The wire's own description (a documented port, src/model/ports.js) wins.
|
|
498
|
+
description: input.description || content.description || `Runs the subgraph "${content.name || input.name}" with these inputs and returns its value.`,
|
|
499
|
+
schema: subgraphSchema(content),
|
|
500
|
+
ask: ask.has(input.name) || graphFetches(graphPanes(content)),
|
|
501
|
+
call: (args, ctx) => callSubgraph(canvas, id, input.source, args, ctx),
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
for (const f of prep.functions ?? []) {
|
|
505
|
+
const input = values.find((r) => r.input.name === f.name)?.input;
|
|
506
|
+
const home = input ? canvas.homeOf(input.source) : undefined;
|
|
507
|
+
const code = home && canvas.attached.has(home.node) && home.node === input.source ? canvas.panes.get(input.source)?.code : undefined;
|
|
508
|
+
const decl = functionTool({ ...f, code, description: f.description || input?.description });
|
|
509
|
+
tools.push({
|
|
510
|
+
name: f.name,
|
|
511
|
+
kind: "function",
|
|
512
|
+
description: decl.description,
|
|
513
|
+
schema: decl.schema,
|
|
514
|
+
ask: ask.has(f.name) || usesFetch(code) || usesFetch(f.source),
|
|
515
|
+
async call(args) {
|
|
516
|
+
const out = await runtime.agent({ id, runId, op: "call", sources: [home.key], payload: { args, positional: decl.positional } });
|
|
517
|
+
if (out?.error !== undefined) throw Object.assign(new Error(out.error), typeof out.code === "string" ? { code: out.code } : {}); // a typed failure (a WASM tool's fuel-exhausted)
|
|
518
|
+
return out?.value;
|
|
519
|
+
},
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
if (pane.canAsk === true) {
|
|
523
|
+
// The model's own question to a person (src/agent/park.js): their answer is the tool's result. Not a call that needs approving.
|
|
524
|
+
tools.push({
|
|
525
|
+
name: "ask_person",
|
|
526
|
+
kind: "question",
|
|
527
|
+
description: "Ask the person using mallory a question that only they can answer; their answer comes back as the result. Use it sparingly, for something you can't find out or decide yourself.",
|
|
528
|
+
schema: { type: "object", properties: { question: { type: "string", minLength: 1, maxLength: 2000, description: "The question, in words a person can answer." } }, required: ["question"], additionalProperties: false },
|
|
529
|
+
ask: false,
|
|
530
|
+
async call(args, ctx) {
|
|
531
|
+
const given = takePre("question");
|
|
532
|
+
const fromAnswer = (a) => {
|
|
533
|
+
if (a?.choice === "deny" || a?.choice === undefined) throw new Error(a?.reason ?? "The person declined to answer.");
|
|
534
|
+
const text = a.text ?? a.args?.answer;
|
|
535
|
+
if (typeof text !== "string") throw new Error("The person declined to answer.");
|
|
536
|
+
return { answer: text };
|
|
537
|
+
};
|
|
538
|
+
if (given) return fromAnswer(given);
|
|
539
|
+
const asked = await askPerson(canvas, id, live, { tool: { name: "ask_person", kind: "question", server: AGENT_SERVER, gateTool: "ask_person" }, call: { args }, signal: ctx?.signal, canPark });
|
|
540
|
+
if (asked?.park) throw new Parked({ kind: "question", question: args.question });
|
|
541
|
+
return fromAnswer(asked);
|
|
542
|
+
},
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
tools.push(...malloryTools(canvas, id, Array.isArray(pane.malloryTools) ? pane.malloryTools : []));
|
|
546
|
+
tools.push(...(await mcpTools(canvas, pane, ask, signal))); // MCP server panes' tools (#529)
|
|
547
|
+
if (signal?.aborted) return { superseded: true };
|
|
548
|
+
const gated = new Map(tools.map((t) => [t.name, t]));
|
|
549
|
+
|
|
550
|
+
// The model.
|
|
551
|
+
// A model call in flight stops when the run is superseded or stopped: the
|
|
552
|
+
// Worker cancels the response body (which cancels the request) or aborts
|
|
553
|
+
// the on-device prompt.
|
|
554
|
+
const stoppable = (call) => {
|
|
555
|
+
if (!signal) return call;
|
|
556
|
+
const stop = () => void runtime.agent({ id, runId, op: "cancel" }).catch(() => {});
|
|
557
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
558
|
+
return call.finally(() => signal.removeEventListener("abort", stop));
|
|
559
|
+
};
|
|
560
|
+
const kind = pane.provider ?? "chrome";
|
|
561
|
+
// Run limits (docs/design/agent-guards.md). A cost cap that can't be enforced refuses the run before it asks the model anything.
|
|
562
|
+
const num = (v) => (Number(v) > 0 ? Number(v) : 0);
|
|
563
|
+
const watchdog = Object.fromEntries(Object.entries(DEFAULT_WATCHDOG).map(([k, d]) => [k, Number.isFinite(Number(pane.watchdog?.[k])) && pane.watchdog?.[k] !== null && pane.watchdog?.[k] !== "" ? Math.max(0, Math.floor(Number(pane.watchdog[k]))) : d])); // absent: on
|
|
564
|
+
// An unattended run's caps are the lowest of the pane's, the grant's and what the ledger has left (already worked out by the authority).
|
|
565
|
+
const limits = { maxCostUsd: unat ? num(unat.auth.caps.maxCostUsd) : num(pane.maxCostUsd), maxDurationMs: unat ? num(unat.auth.caps.maxDurationMs) : num(pane.maxDurationMs), price: cleanPrice(pane.price), watchdog, ...(Number(pane.parallelReads) >= 1 ? { parallel: Math.floor(Number(pane.parallelReads)) } : {}), ...(Number(pane.compactChars) > 0 ? { compactChars: Math.floor(Number(pane.compactChars)) } : {}), ...(unat ? { authority: () => unat.auth.check() } : {}) };
|
|
566
|
+
// Delegation caps (src/delegation/caps.js): an agent another agent called as a tool gets the smaller of its own caps and its parent's, one level less depth, and only the
|
|
567
|
+
// tools its parent has. The allowance it hands to agents below it is kept for callSubgraph.
|
|
568
|
+
const delegated = narrowFor(canvas.delegation, { maxSteps: num(shaped.maxSteps), budget: pane.budget ?? {}, maxCostUsd: tighter(limits.maxCostUsd, shaped.maxCostUsd), maxDurationMs: tighter(limits.maxDurationMs, shaped.maxDurationMs) }, tools.filter(isCapability).map((t) => t.name), Date.now(), delegationSettings());
|
|
569
|
+
if (!delegated.ok) throw new AgentStop("maxSteps", delegated.message);
|
|
570
|
+
Object.assign(limits, { maxCostUsd: delegated.own.maxCostUsd, maxDurationMs: delegated.own.maxDurationMs });
|
|
571
|
+
for (let i = tools.length - 1; i >= 0; i--) if (isCapability(tools[i]) && (!delegated.tools.includes(tools[i].name) || (shaped.keepTools && !shaped.keepTools.includes(tools[i].name)))) tools.splice(i, 1);
|
|
572
|
+
const capSteps = delegated.own.maxSteps || pane.maxSteps;
|
|
573
|
+
const capBudget = { ...(pane.budget ?? {}), ...(delegated.own.budget.calls ? { calls: delegated.own.budget.calls } : {}), ...(delegated.own.budget.inputTokens ? { inputTokens: delegated.own.budget.inputTokens } : {}) };
|
|
574
|
+
(canvas.allowances ??= new Map()).set(id, delegated.allowance);
|
|
575
|
+
if (limits.maxCostUsd && !canPrice(kind, limits.price, pane.routing)) {
|
|
576
|
+
throw new AgentStop("cost", `The agent didn't start: the model's price is unknown (provider ${kind}), so the ${usd(limits.maxCostUsd)} cost cap can't be enforced. Set a price for this pane (US dollars per million tokens), or remove the cap.`);
|
|
577
|
+
}
|
|
578
|
+
// A router (#539) with a companion model in its chain reaches it the way provider "local" does.
|
|
579
|
+
const wantsLocal = kind === "local" || (kind === "router" && Array.isArray(pane.routing?.chain) && pane.routing.chain.some((m) => m?.provider === "local"));
|
|
580
|
+
const makeProvider = (start) => createProvider(kind, {
|
|
581
|
+
model: pane.model,
|
|
582
|
+
baseUrl: pane.baseUrl,
|
|
583
|
+
cloud: pane.cloud,
|
|
584
|
+
keyName: pane.keyName,
|
|
585
|
+
recorded: pane.recorded,
|
|
586
|
+
router: pane.routing,
|
|
587
|
+
scope: `${canvas.root.id}|${id}`, // a router's cache: this pane's, in this page's memory
|
|
588
|
+
start, // the recorded replies the replayed turns stand for
|
|
589
|
+
// `stream.onChunk`: the reply as it arrives, for the trace (runtime.agent's onProgress):
|
|
590
|
+
// the response body streams into the sandbox and the Worker sends its text back.
|
|
591
|
+
transport: {
|
|
592
|
+
http: (request, stream) => stoppable(runtime.agent({ id, runId, op: "http", payload: { ...request, ...(stream ? { stream: true } : {}) }, ...(stream ? { onProgress: stream.onChunk } : {}) })),
|
|
593
|
+
chrome: (op, payload = {}, stream) => stoppable(runtime.agent({ id, runId, op: "chrome", payload: { op, ...payload, ...(stream ? { stream: true } : {}) }, ...(stream ? { onProgress: stream.onChunk } : {}) })),
|
|
594
|
+
// A companion local model (#538): over the companion socket, as this pane (the attachment's gates and the permission bar).
|
|
595
|
+
...(wantsLocal ? { local: localTransport({ access: runtime.companion, pane: canvas.runawayKey(id), conversation: `${id}:${runId}`, signal }) } : {}),
|
|
596
|
+
},
|
|
597
|
+
});
|
|
598
|
+
let provider = makeProvider(fork?.turns.length);
|
|
599
|
+
const prelude = [];
|
|
600
|
+
if (fork && cannotReplayInto(provider.kind)) throw new Error(cannotReplayInto(provider.kind));
|
|
601
|
+
if (provider.kind === "local") {
|
|
602
|
+
// Only the models the person listed in their companion's config: an id it doesn't list is an error of the run.
|
|
603
|
+
let reach;
|
|
604
|
+
try {
|
|
605
|
+
reach = await provider.availability();
|
|
606
|
+
} catch (error) {
|
|
607
|
+
await provider.end?.();
|
|
608
|
+
throw error;
|
|
609
|
+
}
|
|
610
|
+
if (signal?.aborted) return (await provider.end?.(), { superseded: true });
|
|
611
|
+
if (!reach.ok) {
|
|
612
|
+
await provider.end?.();
|
|
613
|
+
finish("skipped");
|
|
614
|
+
return skip(`needs a companion local model: ${reach.why}`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
if (provider.kind === "chrome") {
|
|
618
|
+
const availability = await provider.availability();
|
|
619
|
+
if (signal?.aborted) return { superseded: true };
|
|
620
|
+
if (availability === "unavailable") {
|
|
621
|
+
finish("skipped");
|
|
622
|
+
return skip("needs Chrome's built-in AI (the Prompt API), which isn't available here: pick provider \"recorded\" or \"anthropic\"");
|
|
623
|
+
}
|
|
624
|
+
// Chrome can take tools and silently ignore them: find out first, rather than take made-up text for an answer.
|
|
625
|
+
if (tools.length) {
|
|
626
|
+
const show = (steps) => live.value.runId === runId && (live.value = { ...live.value, steps });
|
|
627
|
+
show([{ type: "check", status: "running", text: "Does Chrome's on-device model do tool use here?" }]);
|
|
628
|
+
const check = await stoppable(chromeToolUse(runtime, provider, signal));
|
|
629
|
+
if (signal?.aborted) return { superseded: true };
|
|
630
|
+
prelude.push(toolUseStep(check));
|
|
631
|
+
show(prelude.map((s) => ({ ...s })));
|
|
632
|
+
if (!check.supported) throw new Error(`${TOOL_USE_OFF} (${check.detail})`);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// The trace: each step at once; a streaming reply's text at most every STREAM_MS.
|
|
637
|
+
let streamTimer = null;
|
|
638
|
+
let latestSteps = null;
|
|
639
|
+
const publish = () => {
|
|
640
|
+
clearTimeout(streamTimer);
|
|
641
|
+
streamTimer = null;
|
|
642
|
+
if (latestSteps && live.value.runId === runId) live.value = { ...live.value, steps: latestSteps.steps.map((s) => ({ ...s })), usage: { ...latestSteps.usage } };
|
|
643
|
+
latestSteps = null;
|
|
644
|
+
};
|
|
645
|
+
const policy = restartPolicy(pane);
|
|
646
|
+
let attemptHistory = history;
|
|
647
|
+
let attemptFork = fork;
|
|
648
|
+
let attemptLimits = resumed ? { ...limits, elapsedMs: resumed.record.elapsedMs, carry: resumed.record.usage } : limits;
|
|
649
|
+
// Steps before this attempt's own: a resumed run's earlier attempts, then the note that it was parked and went on.
|
|
650
|
+
let attemptPrelude = resumed
|
|
651
|
+
? [...prelude, ...resumed.record.steps.slice(0, attemptStart(resumed.record.steps)), { type: "resume", text: `went on after being parked from ${new Date(resumed.record.parkedAt).toISOString()}: the person ${resumed.answer.choice === "deny" ? "declined" : "answered"} (${resumed.record.request.kind})` }]
|
|
652
|
+
: prelude;
|
|
653
|
+
let outcome;
|
|
654
|
+
const safety = personsSafety(); // the sanitizer and leak detector for this run (src/safety/): one stage, so a tainted result is remembered for the run's later calls
|
|
655
|
+
try {
|
|
656
|
+
for (;;) {
|
|
657
|
+
try {
|
|
658
|
+
outcome = await runLoop({
|
|
659
|
+
|
|
660
|
+
provider,
|
|
661
|
+
system,
|
|
662
|
+
history: attemptHistory,
|
|
663
|
+
tools,
|
|
664
|
+
maxSteps: capSteps,
|
|
665
|
+
budget: capBudget,
|
|
666
|
+
limits: attemptLimits,
|
|
667
|
+
safety,
|
|
668
|
+
outputSchema: pane.outputSchema && typeof pane.outputSchema === "object" ? pane.outputSchema : null,
|
|
669
|
+
approve: async (request) => {
|
|
670
|
+
const given = takePre("approval", request.tool.name);
|
|
671
|
+
if (given) return given.choice;
|
|
672
|
+
const answer = await askPerson(canvas, id, live, { ...request, canPark });
|
|
673
|
+
if (answer?.park) throw new Parked({ kind: "approval", tool: request.tool.name, toolKind: request.tool.kind, args: request.call.args });
|
|
674
|
+
return answer;
|
|
675
|
+
},
|
|
676
|
+
// The person's say over the final answer (src/agent/loop.js approveOutput): the same card and scripted answers as a tool call, as the tool "answer".
|
|
677
|
+
...(pane.approveAnswer === true ? { approveOutput: async ({ text, problem, signal: stop }) => {
|
|
678
|
+
const given = takePre("answer");
|
|
679
|
+
if (given) return { choice: given.choice, ...(given.text !== undefined ? { text: given.text } : {}) };
|
|
680
|
+
const answer = await askPerson(canvas, id, live, { tool: ANSWER, call: { args: { text, ...(problem ? { problem } : {}) } }, signal: stop, canPark });
|
|
681
|
+
if (answer?.park) throw new Parked({ kind: "answer", text });
|
|
682
|
+
if (!answer || typeof answer !== "object") return answer;
|
|
683
|
+
const { args, ...rest } = answer;
|
|
684
|
+
return { ...rest, ...(typeof args?.text === "string" ? { text: args.text } : {}) };
|
|
685
|
+
} } : {}),
|
|
686
|
+
// The person's gate policy for this canvas (src/gate/): refuses, holds for the inbox, redacts, audits every call.
|
|
687
|
+
// An MCP server's tool is gated as that server's (its pane's name) and by its own name, not the namespaced one the model sees.
|
|
688
|
+
gate: ({ tool, args, signal: stop }) => beginCall({ canvasId: canvas.root.id, server: tool.server ?? AGENT_SERVER, tool: tool.gateTool ?? tool.name, destructive: tool.destructive === true, args, signal: stop, interactive: canvas.root.interactive === true, script: canvas.root.approvalScript ?? null, names: [tool.name], origin: { canvas, paneId: id }, ...callSeams(canvas, { paneId: id, paneName: pane.name, safety, verdict: true }) }),
|
|
689
|
+
onRefused: ({ name, args, reason }) => noteRefused({ canvasId: canvas.root.id, server: gated.get(name)?.server ?? AGENT_SERVER, tool: gated.get(name)?.gateTool ?? name, args, reason }),
|
|
690
|
+
signal,
|
|
691
|
+
prelude: attemptPrelude,
|
|
692
|
+
...(attemptFork ? { fork: { turns: attemptFork.turns } } : {}),
|
|
693
|
+
onStep: (steps, usage, partial) => {
|
|
694
|
+
latestSteps = { steps, usage };
|
|
695
|
+
if (!partial) publish();
|
|
696
|
+
else streamTimer ??= setTimeout(publish, STREAM_MS);
|
|
697
|
+
},
|
|
698
|
+
});
|
|
699
|
+
break;
|
|
700
|
+
} catch (error) {
|
|
701
|
+
// A failure a fresh start could fix is started again after a wait, within the restart policy and the run's own caps (src/agent/restart.js).
|
|
702
|
+
const plan = error?.partial ? planRestart({ error, restarts, policy, elapsedMs: error.partial.elapsedMs, capMs: limits.maxDurationMs, random: canvas.root.restartRandom }) : { restart: false };
|
|
703
|
+
if (!plan.restart || signal?.aborted) {
|
|
704
|
+
if (restarts && error && typeof error === "object" && !(error instanceof Parked) && error.name !== "AbortError") {
|
|
705
|
+
error.runAttempts = restarts + 1; // (error.attempts is the error policy's own count of tries, src/model/errors.js)
|
|
706
|
+
if (typeof error.message === "string") error.message += ` (after ${restarts + 1} attempts)`;
|
|
707
|
+
}
|
|
708
|
+
throw error;
|
|
709
|
+
}
|
|
710
|
+
restarts++;
|
|
711
|
+
const prior = error.partial;
|
|
712
|
+
const ended = prior.steps.map((s) => (s.status === "running" ? { ...s, status: "error", error: "ended when the attempt failed" } : s));
|
|
713
|
+
attemptPrelude = [...ended, { type: "restart", text: plan.text, attempt: restarts + 1, ...(error instanceof AgentStop ? { kind: error.haltKind } : {}) }];
|
|
714
|
+
attemptLimits = { ...limits, elapsedMs: prior.elapsedMs + plan.delay, carry: { inputTokens: prior.usage.inputTokens, outputTokens: prior.usage.outputTokens, cost: prior.usage.cost ?? 0, unpriced: prior.usage.unpriced ?? 0 } };
|
|
715
|
+
attemptHistory = base.history.map((m) => ({ ...m })); // a fresh start: the conversation as the run began it
|
|
716
|
+
attemptFork = null;
|
|
717
|
+
if (resumed) resumed.used = true;
|
|
718
|
+
await provider.end?.();
|
|
719
|
+
provider = makeProvider(0);
|
|
720
|
+
latestSteps = { steps: attemptPrelude, usage: prior.usage };
|
|
721
|
+
publish();
|
|
722
|
+
await pause(plan.delay, signal);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
if (restarts) outcome.usage.restarts = restarts;
|
|
726
|
+
} finally {
|
|
727
|
+
clearTimeout(streamTimer);
|
|
728
|
+
await provider.end?.();
|
|
729
|
+
}
|
|
730
|
+
if (signal?.aborted) return { superseded: true };
|
|
731
|
+
|
|
732
|
+
// Remember the turn, and keep the replies when asked to record them.
|
|
733
|
+
if (memoryKey) {
|
|
734
|
+
// A fork's turn replaces the source's when that is the memory's last, rather than adding to it.
|
|
735
|
+
const last = remembered.slice(-2);
|
|
736
|
+
const replaces = fork && !fork.resume && last.length === 2 && last[0].text === userText && last[1].text === fork.base.answer;
|
|
737
|
+
const next = [...(replaces ? remembered.slice(0, -2) : remembered), { role: "user", text: userText }, { role: "assistant", text: outcome.text }].slice(-2 * MEMORY_TURNS);
|
|
738
|
+
await runtime.setState(memoryKey, next).catch(() => {});
|
|
739
|
+
}
|
|
740
|
+
if (pane.record && provider.kind !== "recorded") canvas.update(id, { recorded: outcome.replies, record: false });
|
|
741
|
+
|
|
742
|
+
const steps = outcome.steps.map(({ status, partial, reply, output, callId, ...s }) => s); // what a fork replays stays in the live trace
|
|
743
|
+
const value = { text: outcome.text, ...(outcome.data !== undefined ? { data: outcome.data } : {}), steps, usage: outcome.usage, provider: provider.kind, model: provider.model, ...(attached.length ? { grounding: groundingSummary(attached) } : {}) };
|
|
744
|
+
// The attached answers went with this message: they are used up (a change that reruns nothing).
|
|
745
|
+
if (attached.length && canvas.panes.get(id)?.attach?.length) canvas.update(id, { attach: [] });
|
|
746
|
+
if (resumed && !reparked) await store.delete(storeCanvas, storePane); // the parked run is over
|
|
747
|
+
if (unat) Object.assign(unat, { outcome: "done", cost: outcome.usage.cost, unpriced: outcome.usage.unpriced ?? 0 });
|
|
748
|
+
finish("done", { base: { ...base, answer: outcome.text, ...(outcome.data !== undefined ? { data: outcome.data } : {}) } });
|
|
749
|
+
const result = await runtime.set({ id, runId, value, view: "auto" });
|
|
750
|
+
// The run log (src/model/history.js) keeps the trace with the run, and (src/model/runlog.js) where a fork came from.
|
|
751
|
+
return { ...result, agent: { steps: steps.map(traceLine), usage: outcome.usage }, ...(forkOf ? { fork: forkOf } : {}), ...(restarts ? { attempts: restarts + 1 } : {}) };
|
|
752
|
+
} catch (error) {
|
|
753
|
+
if (error?.name === "AbortError" || signal?.aborted) {
|
|
754
|
+
finish("superseded");
|
|
755
|
+
return { superseded: true };
|
|
756
|
+
}
|
|
757
|
+
// The run needs a person and nobody is answering now: keep it (src/agent/park.js) and show the question.
|
|
758
|
+
if (error instanceof Parked && error.partial) {
|
|
759
|
+
const kept = await parkRun(canvas, id, pane, live, runId, error, canPark, restarts);
|
|
760
|
+
if (kept) {
|
|
761
|
+
reparked = true;
|
|
762
|
+
if (unat) Object.assign(unat, { outcome: "parked", cost: error.partial.usage?.cost, unpriced: error.partial.usage?.unpriced ?? 0 });
|
|
763
|
+
return skip("parked: waiting for a person's answer");
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
if (resumed && !reparked) {
|
|
767
|
+
const [c, p] = parkKey(canvas, id);
|
|
768
|
+
await (await parkStoreOf(canvas)).delete(c, p).catch(() => {});
|
|
769
|
+
}
|
|
770
|
+
// A run stopped on a limit keeps its trace and usage in the run log (src/model/history.js reads `error.agent`).
|
|
771
|
+
if (error instanceof AgentStop && error.partial) error.agent = { steps: error.partial.steps.filter((x) => x.type !== "model" || x.status !== "running").map(({ status, partial, reply, output, callId, ...x }) => traceLine(x)), usage: { ...error.partial.usage } };
|
|
772
|
+
finish(error instanceof AgentStop ? "stopped" : "error", { error: error?.message ?? String(error) });
|
|
773
|
+
throw error;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Keep a run that needs a person: its trace so far, what it had spent, the question. Returns false when it can't be kept (the pane
|
|
779
|
+
* doesn't allow parking, its trace can't be stored), and the caller then ends the run as an error.
|
|
780
|
+
*/
|
|
781
|
+
async function parkRun(canvas, id, pane, live, runId, parked, canPark, restarts = 0) {
|
|
782
|
+
if (!canPark) return false;
|
|
783
|
+
let steps;
|
|
784
|
+
try {
|
|
785
|
+
steps = JSON.parse(JSON.stringify(parked.partial.steps));
|
|
786
|
+
} catch {
|
|
787
|
+
return false;
|
|
788
|
+
}
|
|
789
|
+
// The last step a replay can end on: a model reply that finished, or a tool call that has its result. The request is what comes after it.
|
|
790
|
+
let at = -1;
|
|
791
|
+
steps.forEach((s, i) => {
|
|
792
|
+
if ((s.type === "model" && s.status === "done" && s.reply) || (s.type === "tool" && s.output)) at = i;
|
|
793
|
+
});
|
|
794
|
+
if (at < 0 || forkProblem(steps, at)) return false;
|
|
795
|
+
const [storeCanvas, storePane] = parkKey(canvas, id);
|
|
796
|
+
const record = parkRecord({
|
|
797
|
+
canvasId: storeCanvas,
|
|
798
|
+
paneId: storePane,
|
|
799
|
+
now: Date.now(),
|
|
800
|
+
parkMs: Number(pane.parkMs),
|
|
801
|
+
request: parked.request,
|
|
802
|
+
base: live.value.base,
|
|
803
|
+
steps,
|
|
804
|
+
at,
|
|
805
|
+
usage: parked.partial.usage,
|
|
806
|
+
elapsedMs: parked.partial.elapsedMs,
|
|
807
|
+
fingerprint: fingerprintOf(pane),
|
|
808
|
+
provider: pane.provider ?? "chrome",
|
|
809
|
+
runId,
|
|
810
|
+
restarts,
|
|
811
|
+
});
|
|
812
|
+
if (parkProblem(record)) return false;
|
|
813
|
+
await (await parkStoreOf(canvas)).set(storeCanvas, storePane, record);
|
|
814
|
+
live.value = { ...live.value, steps: steps.map(({ reply, output, ...s }) => s) };
|
|
815
|
+
showParked(canvas, id, live, runId, record);
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* The tools of the MCP server panes an agent pane names in `mcpServers` (#529): each as `<server>__<tool>`
|
|
821
|
+
* (namespaced, so two servers' tools never clash), with the tool's input schema, gated as that server's tool
|
|
822
|
+
* (`server`, `gateTool`), and called through its pane's connection (src/mcp/hub.js), connecting first when
|
|
823
|
+
* it hasn't yet. A name no MCP server pane has is an error of the run.
|
|
824
|
+
*/
|
|
825
|
+
export async function mcpTools(canvas, pane, ask = new Set(), signal) {
|
|
826
|
+
const names = Array.isArray(pane.mcpServers) ? pane.mcpServers.filter((n) => typeof n === "string" && n) : [];
|
|
827
|
+
if (!names.length) return [];
|
|
828
|
+
const { hubOf, findServer } = await import("../mcp/hub.js");
|
|
829
|
+
const { gateServerOf, namespacedTool } = await import("../mcp/settings.js");
|
|
830
|
+
const out = [];
|
|
831
|
+
for (const name of new Set(names)) {
|
|
832
|
+
const found = findServer(canvas, name);
|
|
833
|
+
if (!found) throw new Error(`mcpServers: there is no MCP server pane named "${name}" on this canvas`);
|
|
834
|
+
const hub = hubOf(found.canvas);
|
|
835
|
+
const snapshot = await hub.snapshot(found.id, { signal });
|
|
836
|
+
const server = gateServerOf(found.canvas.panes.get(found.id), found.id);
|
|
837
|
+
for (const t of snapshot.tools) {
|
|
838
|
+
const tool = namespacedTool(name, t.name);
|
|
839
|
+
out.push({
|
|
840
|
+
name: tool,
|
|
841
|
+
kind: "mcp",
|
|
842
|
+
description: `${t.description || t.title || t.name} (tool ${t.name} of the MCP server ${name})`.slice(0, 1024),
|
|
843
|
+
schema: t.inputSchema,
|
|
844
|
+
destructive: t.destructive === true,
|
|
845
|
+
readOnly: t.readOnly === true,
|
|
846
|
+
server,
|
|
847
|
+
gateTool: t.name,
|
|
848
|
+
ask: ask.has(tool),
|
|
849
|
+
call: (args, ctx) => hub.rawCall(found.id, t.name, args, { signal: ctx?.signal }),
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
return out;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/** One step of the trace as a line for the run log. */
|
|
857
|
+
export function traceLine(s) {
|
|
858
|
+
if (s.type === "model") return `model${s.tokens ? ` (${s.tokens.input} in, ${s.tokens.output} out)` : ""}: ${s.calls?.length ? `calls ${s.calls.join(", ")}` : brief(s.text, 120)}`;
|
|
859
|
+
if (s.type === "tool") return `${s.name}(${brief(s.args, 80)})${s.approval ? ` [${s.scripted ? "scripted " : ""}${s.approval}]` : ""} → ${s.error !== undefined ? `error${s.code ? ` (${s.code})` : ""}: ${brief(s.error, 120)}` : brief(s.result, 120)}`;
|
|
860
|
+
return `${s.type}: ${brief(s.text, 120)}`;
|
|
861
|
+
}
|