@parcha/agentrun-serve 0.1.0-beta.30 → 0.1.0-beta.32
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/CHANGELOG.md +472 -0
- package/NOTICE +18 -0
- package/README.md +1042 -240
- package/dist/adapter-facts.d.ts +3 -0
- package/dist/adapter-facts.js +5 -0
- package/dist/adapters.d.ts +64 -140
- package/dist/adapters.js +153 -377
- package/dist/agents-store.d.ts +146 -0
- package/dist/agents-store.js +359 -0
- package/dist/agents.d.ts +12 -5
- package/dist/agents.js +40 -17
- package/dist/app.d.ts +2 -4
- package/dist/app.js +227 -97
- package/dist/approvals.d.ts +4 -0
- package/dist/approvals.js +7 -0
- package/dist/archil-routes.d.ts +45 -0
- package/dist/archil-routes.js +150 -0
- package/dist/archil-settings.d.ts +30 -0
- package/dist/archil-settings.js +34 -0
- package/dist/background.d.ts +2 -1
- package/dist/background.js +69 -29
- package/dist/bounds.d.ts +26 -0
- package/dist/bounds.js +137 -0
- package/dist/box-egress-vm.d.ts +126 -0
- package/dist/box-egress-vm.js +364 -0
- package/dist/box-egress.d.ts +19 -8
- package/dist/box-egress.js +27 -15
- package/dist/box-paths.d.ts +59 -0
- package/dist/box-paths.js +92 -0
- package/dist/box-relay-vm.d.ts +4 -0
- package/dist/box-relay-vm.js +103 -55
- package/dist/box-relay.d.ts +2 -0
- package/dist/box-relay.js +2 -2
- package/dist/boxes.d.ts +20 -3
- package/dist/boxes.js +67 -14
- package/dist/browser-commands.d.ts +43 -0
- package/dist/browser-commands.js +154 -0
- package/dist/browser-cost.d.ts +30 -3
- package/dist/browser-cost.js +276 -21
- package/dist/browser-live.d.ts +124 -0
- package/dist/browser-live.js +324 -0
- package/dist/browser-person.d.ts +168 -0
- package/dist/browser-person.js +769 -0
- package/dist/budget.d.ts +80 -0
- package/dist/budget.js +211 -0
- package/dist/cap.d.ts +274 -63
- package/dist/cap.js +599 -188
- package/dist/cli.js +226 -16
- package/dist/coding-tools.d.ts +13 -1
- package/dist/coding-tools.js +107 -5
- package/dist/computer-adb.d.ts +12 -0
- package/dist/computer-adb.js +14 -0
- package/dist/computer-commands.d.ts +103 -0
- package/dist/computer-commands.js +256 -0
- package/dist/computer-keys.d.ts +68 -0
- package/dist/computer-keys.js +148 -0
- package/dist/computer-routes.d.ts +38 -0
- package/dist/computer-routes.js +56 -0
- package/dist/computer-setting.d.ts +37 -0
- package/dist/computer-setting.js +47 -0
- package/dist/computer-view.d.ts +38 -0
- package/dist/computer-view.js +14 -0
- package/dist/computers.d.ts +137 -0
- package/dist/computers.js +197 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
- package/dist/console/assets/index-35-7aeIZ.js +519 -0
- package/dist/console/assets/index-Cejbov-Y.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +2 -0
- package/dist/console-links.js +6 -0
- package/dist/decision-cap.d.ts +63 -0
- package/dist/decision-cap.js +163 -0
- package/dist/decision-rows.d.ts +5 -2
- package/dist/decision-rows.js +8 -6
- package/dist/decisions.d.ts +31 -4
- package/dist/decisions.js +66 -8
- package/dist/disk.d.ts +33 -0
- package/dist/disk.js +85 -0
- package/dist/door-line.d.ts +23 -0
- package/dist/door-line.js +83 -0
- package/dist/egress-proxy.d.ts +45 -0
- package/dist/egress-proxy.js +416 -0
- package/dist/egress-table.d.ts +24 -0
- package/dist/egress-table.js +165 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +22 -2
- package/dist/exa-keyless.js +1 -1
- package/dist/explain.d.ts +22 -0
- package/dist/explain.js +207 -0
- package/dist/faux-computers.d.ts +35 -0
- package/dist/faux-computers.js +126 -0
- package/dist/file-types.d.ts +4 -0
- package/dist/file-types.js +11 -0
- package/dist/files.d.ts +3 -32
- package/dist/files.js +9 -117
- package/dist/github-connection.d.ts +207 -0
- package/dist/github-connection.js +595 -0
- package/dist/github.d.ts +64 -0
- package/dist/github.js +119 -0
- package/dist/grade.d.ts +14 -44
- package/dist/grade.js +55 -233
- package/dist/graph-served.d.ts +23 -2
- package/dist/graph-served.js +44 -3
- package/dist/graph-view.d.ts +7 -3
- package/dist/graph-view.js +26 -15
- package/dist/handed-values.d.ts +23 -0
- package/dist/handed-values.js +36 -0
- package/dist/harness-app.d.ts +33 -4
- package/dist/harness-app.js +539 -85
- package/dist/harness-install.d.ts +120 -0
- package/dist/harness-install.js +359 -0
- package/dist/harness-opencode/adapter.js +42 -8
- package/dist/harness-opencode/facts.d.ts +2 -0
- package/dist/harness-opencode/facts.js +28 -0
- package/dist/harness-opencode/harness.d.ts +4 -0
- package/dist/harness-opencode/harness.js +38 -5
- package/dist/harness-opencode/host/policy.js +11 -3
- package/dist/harness-opencode/transcript.d.ts +25 -0
- package/dist/harness-opencode/transcript.js +81 -0
- package/dist/harness-table.d.ts +75 -0
- package/dist/harness-table.js +145 -0
- package/dist/harness.d.ts +7 -28
- package/dist/harness.js +15 -41
- package/dist/heard.d.ts +12 -0
- package/dist/heard.js +45 -0
- package/dist/helper-env.d.ts +4 -0
- package/dist/helper-env.js +14 -0
- package/dist/home-path.d.ts +0 -4
- package/dist/home-path.js +3 -17
- package/dist/host-check.d.ts +13 -0
- package/dist/host-check.js +35 -0
- package/dist/host-tools.d.ts +51 -8
- package/dist/host-tools.js +108 -117
- package/dist/host.d.ts +12 -6
- package/dist/host.js +30 -24
- package/dist/hosted-search.d.ts +3 -0
- package/dist/hosted-search.js +5 -3
- package/dist/import-proxy.d.ts +42 -0
- package/dist/import-proxy.js +105 -0
- package/dist/import-summary.js +4 -8
- package/dist/import-worker.d.ts +2 -3
- package/dist/import-worker.js +18 -16
- package/dist/import.d.ts +37 -17
- package/dist/import.js +208 -222
- package/dist/key-meta.d.ts +26 -0
- package/dist/key-meta.js +30 -0
- package/dist/key-refusal.d.ts +4 -1
- package/dist/key-refusal.js +20 -7
- package/dist/key-words.d.ts +37 -0
- package/dist/key-words.js +40 -0
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +2 -2
- package/dist/learn/commit.d.ts +86 -0
- package/dist/learn/commit.js +182 -0
- package/dist/learn/folder.d.ts +296 -0
- package/dist/learn/folder.js +796 -0
- package/dist/learn/grade.d.ts +25 -9
- package/dist/learn/grade.js +98 -50
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/learning.sh +366 -0
- package/dist/learn/reflect.d.ts +12 -5
- package/dist/learn/reflect.js +72 -41
- package/dist/learn/secrets.d.ts +15 -7
- package/dist/learn/secrets.js +66 -16
- package/dist/learn/seed-check.d.ts +74 -0
- package/dist/learn/seed-check.js +103 -0
- package/dist/learn/skills.d.ts +7 -1
- package/dist/learn/skills.js +21 -4
- package/dist/learned-workflow.d.ts +12 -2
- package/dist/learned-workflow.js +9 -5
- package/dist/learning-routes.d.ts +107 -31
- package/dist/learning-routes.js +358 -403
- package/dist/learning-run.d.ts +61 -54
- package/dist/learning-run.js +183 -205
- package/dist/learning-words.d.ts +10 -8
- package/dist/learning-words.js +29 -13
- package/dist/learning.d.ts +186 -113
- package/dist/learning.js +345 -381
- package/dist/live/stream.d.ts +30 -0
- package/dist/live/stream.js +175 -0
- package/dist/live/translate.d.ts +52 -0
- package/dist/live/translate.js +276 -0
- package/dist/llm.js +3 -0
- package/dist/llms.txt +1 -0
- package/dist/local-models.d.ts +23 -0
- package/dist/local-models.js +35 -0
- package/dist/mcp-gateway.d.ts +129 -0
- package/dist/mcp-gateway.js +508 -0
- package/dist/mcp-meta.d.ts +20 -0
- package/dist/mcp-meta.js +50 -0
- package/dist/mcp-oauth.d.ts +172 -0
- package/dist/mcp-oauth.js +403 -0
- package/dist/mcp-private-hosts.d.ts +48 -0
- package/dist/mcp-private-hosts.js +141 -0
- package/dist/mcp-probe.d.ts +101 -0
- package/dist/mcp-probe.js +359 -0
- package/dist/mcp-secret-writes.d.ts +23 -0
- package/dist/mcp-secret-writes.js +60 -0
- package/dist/mcp-servers-store.d.ts +251 -0
- package/dist/mcp-servers-store.js +447 -0
- package/dist/mcp-servers.d.ts +185 -34
- package/dist/mcp-servers.js +304 -298
- package/dist/mcp-store.d.ts +103 -0
- package/dist/mcp-store.js +123 -0
- package/dist/mcp.js +22 -21
- package/dist/model.d.ts +77 -59
- package/dist/model.js +237 -98
- package/dist/monid.d.ts +8 -6
- package/dist/monid.js +39 -25
- package/dist/openapi.d.ts +22 -1
- package/dist/openapi.js +965 -111
- package/dist/owner.d.ts +46 -10
- package/dist/owner.js +123 -43
- package/dist/page.d.ts +12 -0
- package/dist/page.js +28 -2
- package/dist/paid-calls.d.ts +71 -2
- package/dist/paid-calls.js +125 -5
- package/dist/pdf-pages.d.ts +16 -14
- package/dist/pdf-pages.js +88 -58
- package/dist/place.d.ts +18 -15
- package/dist/place.js +36 -18
- package/dist/port-models.d.ts +53 -0
- package/dist/port-models.js +93 -0
- package/dist/print.d.ts +7 -0
- package/dist/print.js +13 -0
- package/dist/propose.d.ts +9 -8
- package/dist/propose.js +82 -49
- package/dist/provider.d.ts +85 -0
- package/dist/provider.js +178 -0
- package/dist/push-handler.d.ts +52 -0
- package/dist/push-handler.js +165 -0
- package/dist/refusal-words.d.ts +23 -0
- package/dist/refusal-words.js +25 -0
- package/dist/request-start.d.ts +6 -1
- package/dist/request-start.js +41 -10
- package/dist/result.d.ts +13 -2
- package/dist/result.js +4 -5
- package/dist/run-box.d.ts +22 -3
- package/dist/run-box.js +91 -20
- package/dist/run-computer.d.ts +24 -0
- package/dist/run-computer.js +15 -0
- package/dist/run-cut.d.ts +33 -0
- package/dist/run-cut.js +42 -0
- package/dist/run-db.d.ts +64 -0
- package/dist/run-db.js +155 -0
- package/dist/run-files.d.ts +31 -0
- package/dist/run-files.js +125 -0
- package/dist/run-holder.d.ts +52 -0
- package/dist/run-holder.js +139 -0
- package/dist/run-launch.d.ts +72 -0
- package/dist/run-launch.js +108 -0
- package/dist/run-learning-served.d.ts +43 -0
- package/dist/run-learning-served.js +16 -0
- package/dist/run-manifest.d.ts +7 -6
- package/dist/run-manifest.js +20 -10
- package/dist/run-reads-over-store.d.ts +102 -0
- package/dist/run-reads-over-store.js +151 -0
- package/dist/run-timeline-served.d.ts +13 -0
- package/dist/run-timeline-served.js +69 -0
- package/dist/run-view.d.ts +436 -0
- package/dist/run-view.js +620 -0
- package/dist/runnable.d.ts +36 -4
- package/dist/runnable.js +157 -31
- package/dist/runner/adapter-loop.d.ts +237 -0
- package/dist/runner/adapter-loop.js +1625 -0
- package/dist/runner/adapter-run-spec.d.ts +216 -0
- package/dist/runner/adapter-run-spec.js +537 -0
- package/dist/runner/adapters/index.d.ts +37 -0
- package/dist/runner/adapters/index.js +66 -0
- package/dist/runner/adapters/pi.d.ts +99 -0
- package/dist/runner/adapters/pi.js +260 -0
- package/dist/runner/beside.d.ts +12 -0
- package/dist/runner/beside.js +30 -0
- package/dist/runner/claim-secrets.d.ts +30 -0
- package/dist/runner/claim-secrets.js +90 -0
- package/dist/runner/cli-run-spec.d.ts +17 -0
- package/dist/runner/cli-run-spec.js +371 -0
- package/dist/runner/commands.d.ts +23 -0
- package/dist/runner/commands.js +67 -0
- package/dist/runner/computer-journal.d.ts +38 -0
- package/dist/runner/computer-journal.js +120 -0
- package/dist/runner/conformance/child.d.ts +1 -0
- package/dist/runner/conformance/child.js +78 -0
- package/dist/runner/conformance/harness.d.ts +89 -0
- package/dist/runner/conformance/harness.js +928 -0
- package/dist/runner/conformance/subject.d.ts +83 -0
- package/dist/runner/conformance/subject.js +1 -0
- package/dist/runner/dispatch.d.ts +30 -0
- package/dist/runner/dispatch.js +99 -0
- package/dist/runner/end-of-run.d.ts +32 -0
- package/dist/runner/end-of-run.js +56 -0
- package/dist/runner/github-app.d.ts +16 -0
- package/dist/runner/github-app.js +37 -0
- package/dist/runner/hand-back.d.ts +43 -0
- package/dist/runner/hand-back.js +69 -0
- package/dist/runner/harness-loops.d.ts +10 -0
- package/dist/runner/harness-loops.js +70 -0
- package/dist/runner/journal-kinds.d.ts +211 -0
- package/dist/runner/journal-kinds.js +116 -0
- package/dist/runner/journal-reader.d.ts +44 -0
- package/dist/runner/journal-reader.js +127 -0
- package/dist/runner/learning-ask.d.ts +37 -0
- package/dist/runner/learning-ask.js +99 -0
- package/dist/runner/learning-dispatch.d.ts +38 -0
- package/dist/runner/learning-dispatch.js +75 -0
- package/dist/runner/learning-end.d.ts +31 -0
- package/dist/runner/learning-end.js +136 -0
- package/dist/runner/learning-factory.d.ts +13 -0
- package/dist/runner/learning-factory.js +37 -0
- package/dist/runner/learning-loop.d.ts +150 -0
- package/dist/runner/learning-loop.js +246 -0
- package/dist/runner/learning-seed.d.ts +30 -0
- package/dist/runner/learning-seed.js +41 -0
- package/dist/runner/live-ticker.d.ts +18 -0
- package/dist/runner/live-ticker.js +88 -0
- package/dist/runner/loop-contract.d.ts +153 -0
- package/dist/runner/loop-contract.js +26 -0
- package/dist/runner/loop.d.ts +79 -0
- package/dist/runner/loop.js +185 -0
- package/dist/runner/main.d.ts +89 -0
- package/dist/runner/main.js +282 -0
- package/dist/runner/mcp-claim.d.ts +67 -0
- package/dist/runner/mcp-claim.js +403 -0
- package/dist/runner/mcp-github.d.ts +53 -0
- package/dist/runner/mcp-github.js +91 -0
- package/dist/runner/mcp-run.d.ts +116 -0
- package/dist/runner/mcp-run.js +152 -0
- package/dist/runner/metrics.d.ts +18 -0
- package/dist/runner/metrics.js +24 -0
- package/dist/runner/model-route.d.ts +111 -0
- package/dist/runner/model-route.js +183 -0
- package/dist/runner/pi-stop.d.ts +6 -0
- package/dist/runner/pi-stop.js +8 -0
- package/dist/runner/redact.d.ts +26 -0
- package/dist/runner/redact.js +51 -0
- package/dist/runner/reflect-hook.d.ts +81 -0
- package/dist/runner/reflect-hook.js +111 -0
- package/dist/runner/runner.d.ts +114 -0
- package/dist/runner/runner.js +672 -0
- package/dist/runner/sessions.d.ts +9 -0
- package/dist/runner/sessions.js +145 -0
- package/dist/runner/side-effects.d.ts +19 -0
- package/dist/runner/side-effects.js +20 -0
- package/dist/runner/spec-holds.d.ts +41 -0
- package/dist/runner/spec-holds.js +58 -0
- package/dist/runner/store-port.d.ts +9 -0
- package/dist/runner/store-port.js +7 -0
- package/dist/runner/store-secrets.d.ts +11 -0
- package/dist/runner/store-secrets.js +105 -0
- package/dist/runner/workflow-adapters.d.ts +1 -0
- package/dist/runner/workflow-adapters.js +4 -0
- package/dist/runner/workflow-host.d.ts +88 -0
- package/dist/runner/workflow-host.js +66 -0
- package/dist/runner/workflow-loop.d.ts +126 -0
- package/dist/runner/workflow-loop.js +372 -0
- package/dist/runner/workflow-spec.d.ts +157 -0
- package/dist/runner/workflow-spec.js +801 -0
- package/dist/runs-over-store.d.ts +203 -0
- package/dist/runs-over-store.js +396 -0
- package/dist/runs.d.ts +360 -222
- package/dist/runs.js +1619 -536
- package/dist/seal-key.d.ts +30 -0
- package/dist/seal-key.js +141 -0
- package/dist/sealed-settings-store.d.ts +71 -0
- package/dist/sealed-settings-store.js +205 -0
- package/dist/sealed-settings.d.ts +60 -0
- package/dist/sealed-settings.js +178 -0
- package/dist/secret-writes.d.ts +147 -0
- package/dist/secret-writes.js +144 -0
- package/dist/secrets.d.ts +22 -0
- package/dist/secrets.js +37 -4
- package/dist/served-only.d.ts +5 -0
- package/dist/served-only.js +12 -0
- package/dist/server-approvers.d.ts +8 -0
- package/dist/server-approvers.js +12 -0
- package/dist/server-fs.d.ts +40 -0
- package/dist/server-fs.js +138 -0
- package/dist/server-keys.d.ts +18 -0
- package/dist/server-keys.js +31 -0
- package/dist/server-lock.js +1 -1
- package/dist/server-secrets-store.d.ts +18 -0
- package/dist/server-secrets-store.js +54 -0
- package/dist/server-secrets.d.ts +23 -0
- package/dist/server-secrets.js +73 -0
- package/dist/server.d.ts +152 -74
- package/dist/server.js +1757 -588
- package/dist/sessions.d.ts +3 -1
- package/dist/sessions.js +8 -4
- package/dist/sign-ins-secrets.d.ts +35 -0
- package/dist/sign-ins-secrets.js +109 -0
- package/dist/sign-ins-store.d.ts +200 -0
- package/dist/sign-ins-store.js +373 -0
- package/dist/sign-ins.d.ts +43 -7
- package/dist/sign-ins.js +94 -18
- package/dist/skills.d.ts +6 -5
- package/dist/skills.js +18 -14
- package/dist/standard-webhooks.d.ts +30 -0
- package/dist/standard-webhooks.js +72 -0
- package/dist/stats.d.ts +5 -7
- package/dist/stats.js +8 -24
- package/dist/stop-signals.d.ts +22 -0
- package/dist/stop-signals.js +38 -0
- package/dist/store/agent-body.d.ts +103 -0
- package/dist/store/agent-body.js +126 -0
- package/dist/store/dialect.d.ts +59 -0
- package/dist/store/dialect.js +32 -0
- package/dist/store/fence.d.ts +22 -0
- package/dist/store/fence.js +15 -0
- package/dist/store/index.d.ts +17 -0
- package/dist/store/index.js +17 -0
- package/dist/store/journal/storage.d.ts +137 -0
- package/dist/store/journal/storage.js +1021 -0
- package/dist/store/open.d.ts +34 -0
- package/dist/store/open.js +30 -0
- package/dist/store/postgres/connection.d.ts +74 -0
- package/dist/store/postgres/connection.js +532 -0
- package/dist/store/postgres/dialect.d.ts +9 -0
- package/dist/store/postgres/dialect.js +39 -0
- package/dist/store/postgres/migrate.d.ts +21 -0
- package/dist/store/postgres/migrate.js +106 -0
- package/dist/store/postgres/migrations/0001_initial.sql +418 -0
- package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
- package/dist/store/postgres/store.d.ts +37 -0
- package/dist/store/postgres/store.js +48 -0
- package/dist/store/prompts.d.ts +11 -0
- package/dist/store/prompts.js +112 -0
- package/dist/store/schema.d.ts +26 -0
- package/dist/store/schema.js +522 -0
- package/dist/store/seal.d.ts +48 -0
- package/dist/store/seal.js +69 -0
- package/dist/store/sqlite/connection.d.ts +105 -0
- package/dist/store/sqlite/connection.js +309 -0
- package/dist/store/sqlite/memory.d.ts +2 -0
- package/dist/store/sqlite/memory.js +4 -0
- package/dist/store/sqlite/run-launch.d.ts +8 -0
- package/dist/store/sqlite/run-launch.js +20 -0
- package/dist/store/sqlite/run-patch.d.ts +54 -0
- package/dist/store/sqlite/run-patch.js +114 -0
- package/dist/store/sqlite/store.d.ts +33 -0
- package/dist/store/sqlite/store.js +1337 -0
- package/dist/store/sqlite/worker.d.ts +78 -0
- package/dist/store/sqlite/worker.js +242 -0
- package/dist/store/store.d.ts +1253 -0
- package/dist/store/store.js +190 -0
- package/dist/store-reads/analytics.d.ts +55 -0
- package/dist/store-reads/analytics.js +135 -0
- package/dist/store-reads/cap.d.ts +17 -0
- package/dist/store-reads/cap.js +17 -0
- package/dist/store-reads/decisions.d.ts +5 -0
- package/dist/store-reads/decisions.js +31 -0
- package/dist/store-reads/import-summary.d.ts +6 -0
- package/dist/store-reads/import-summary.js +14 -0
- package/dist/store-reads/journal.d.ts +30 -0
- package/dist/store-reads/journal.js +120 -0
- package/dist/store-reads/learning.d.ts +93 -0
- package/dist/store-reads/learning.js +202 -0
- package/dist/store-reads/runs.d.ts +42 -0
- package/dist/store-reads/runs.js +84 -0
- package/dist/store-reads/stats.d.ts +30 -0
- package/dist/store-reads/stats.js +59 -0
- package/dist/store-reads/workflow.d.ts +7 -0
- package/dist/store-reads/workflow.js +14 -0
- package/dist/store-view.d.ts +37 -0
- package/dist/store-view.js +305 -0
- package/dist/template-eval.d.ts +239 -0
- package/dist/template-eval.js +1020 -0
- package/dist/template-github-permissions.d.ts +18 -0
- package/dist/template-github-permissions.js +32 -0
- package/dist/templates.d.ts +199 -0
- package/dist/templates.js +637 -0
- package/dist/tool-blurbs.d.ts +4 -0
- package/dist/tool-blurbs.js +27 -0
- package/dist/tool-gate.d.ts +183 -37
- package/dist/tool-gate.js +450 -99
- package/dist/tool-keys-store.d.ts +110 -0
- package/dist/tool-keys-store.js +291 -0
- package/dist/tool-keys.d.ts +27 -13
- package/dist/tool-keys.js +24 -10
- package/dist/tool-plane.d.ts +115 -25
- package/dist/tool-plane.js +251 -74
- package/dist/tool-settings-store.d.ts +30 -0
- package/dist/tool-settings-store.js +53 -0
- package/dist/tools.d.ts +95 -24
- package/dist/tools.js +344 -65
- package/dist/trigger-accept.d.ts +36 -0
- package/dist/trigger-accept.js +152 -0
- package/dist/trigger-adapter.d.ts +143 -0
- package/dist/trigger-adapter.js +31 -0
- package/dist/trigger-adapters.d.ts +2 -0
- package/dist/trigger-adapters.js +4 -0
- package/dist/trigger-github.d.ts +2 -0
- package/dist/trigger-github.js +85 -0
- package/dist/trigger-schedule.d.ts +6 -0
- package/dist/trigger-schedule.js +115 -0
- package/dist/trigger-secrets-shown.d.ts +66 -0
- package/dist/trigger-secrets-shown.js +77 -0
- package/dist/trigger-signatures.d.ts +58 -0
- package/dist/trigger-signatures.js +79 -0
- package/dist/trigger-targets.d.ts +46 -0
- package/dist/trigger-targets.js +95 -0
- package/dist/trigger-webhook.d.ts +2 -0
- package/dist/trigger-webhook.js +92 -0
- package/dist/triggers.d.ts +282 -237
- package/dist/triggers.js +720 -608
- package/dist/turn-end.d.ts +3 -0
- package/dist/turn-end.js +3 -0
- package/dist/uploads.d.ts +10 -8
- package/dist/uploads.js +45 -45
- package/dist/usage.d.ts +33 -3
- package/dist/usage.js +38 -4
- package/dist/validate.d.ts +6 -0
- package/dist/validate.js +42 -12
- package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
- package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
- package/dist/web-fetch.d.ts +17 -9
- package/dist/web-fetch.js +56 -21
- package/dist/web-search.d.ts +1 -1
- package/dist/web-search.js +1 -1
- package/dist/webhooks.d.ts +33 -23
- package/dist/webhooks.js +69 -56
- package/dist/wires.d.ts +11 -0
- package/dist/wires.js +7 -0
- package/dist/workspace/archil-claim.d.ts +57 -0
- package/dist/workspace/archil-claim.js +154 -0
- package/dist/workspace/archil-disk.d.ts +104 -0
- package/dist/workspace/archil-disk.js +254 -0
- package/dist/workspace/archil-exec.d.ts +59 -0
- package/dist/workspace/archil-exec.js +218 -0
- package/dist/workspace/archil-key.d.ts +17 -0
- package/dist/workspace/archil-key.js +30 -0
- package/dist/workspace/archil-mount-credential.d.ts +58 -0
- package/dist/workspace/archil-mount-credential.js +165 -0
- package/dist/workspace/archil.d.ts +59 -0
- package/dist/workspace/archil.js +676 -0
- package/dist/workspace/attach.d.ts +48 -0
- package/dist/workspace/attach.js +439 -0
- package/dist/workspace/computer-deps.d.ts +58 -0
- package/dist/workspace/computer-deps.js +113 -0
- package/dist/workspace/computer-for-claim.d.ts +115 -0
- package/dist/workspace/computer-for-claim.js +198 -0
- package/dist/workspace/computer-hold.d.ts +145 -0
- package/dist/workspace/computer-hold.js +258 -0
- package/dist/workspace/computer-ledger.d.ts +22 -0
- package/dist/workspace/computer-ledger.js +19 -0
- package/dist/workspace/computer-ports.d.ts +13 -0
- package/dist/workspace/computer-ports.js +108 -0
- package/dist/workspace/computer-providers.d.ts +12 -0
- package/dist/workspace/computer-providers.js +17 -0
- package/dist/workspace/computer-serves.d.ts +12 -0
- package/dist/workspace/computer-serves.js +15 -0
- package/dist/workspace/executors.d.ts +38 -0
- package/dist/workspace/executors.js +150 -0
- package/dist/workspace/glob.d.ts +2 -0
- package/dist/workspace/glob.js +25 -0
- package/dist/workspace/grep-worker.d.ts +11 -0
- package/dist/workspace/grep-worker.js +91 -0
- package/dist/workspace/hands.d.ts +25 -0
- package/dist/workspace/hands.js +121 -0
- package/dist/workspace/index.d.ts +23 -0
- package/dist/workspace/index.js +25 -0
- package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
- package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
- package/dist/workspace/kind-skills.d.ts +11 -0
- package/dist/workspace/kind-skills.js +16 -0
- package/dist/workspace/learning-workspace.d.ts +24 -0
- package/dist/workspace/learning-workspace.js +107 -0
- package/dist/workspace/local.d.ts +6 -0
- package/dist/workspace/local.js +632 -0
- package/dist/workspace/paths.d.ts +48 -0
- package/dist/workspace/paths.js +134 -0
- package/dist/workspace/pi-env.d.ts +39 -0
- package/dist/workspace/pi-env.js +397 -0
- package/dist/workspace/place.d.ts +7 -0
- package/dist/workspace/place.js +3 -0
- package/dist/workspace/resolve-computer.d.ts +106 -0
- package/dist/workspace/resolve-computer.js +188 -0
- package/dist/workspace/revision-skills.d.ts +15 -0
- package/dist/workspace/revision-skills.js +42 -0
- package/dist/workspace/run-tools.d.ts +173 -0
- package/dist/workspace/run-tools.js +172 -0
- package/dist/workspace/run-workspace.d.ts +25 -0
- package/dist/workspace/run-workspace.js +56 -0
- package/dist/workspace/server-run-workspace.d.ts +24 -0
- package/dist/workspace/server-run-workspace.js +84 -0
- package/dist/workspace/workspace.d.ts +169 -0
- package/dist/workspace/workspace.js +54 -0
- package/dist/workspace-paths.d.ts +1 -10
- package/dist/workspace-paths.js +3 -37
- package/dist/workspace.d.ts +3 -17
- package/dist/workspace.js +6 -74
- package/harnesses/claude-agent/package-lock.json +1533 -0
- package/harnesses/claude-agent/package.json +7 -0
- package/harnesses/codex/package-lock.json +135 -0
- package/harnesses/codex/package.json +7 -0
- package/launcher/agentrun-serve +13 -3
- package/package.json +36 -25
- package/skills/agentrun-serve/SKILL.md +2 -0
- package/templates/README.md +211 -0
- package/templates/code-review/agent.md +50 -0
- package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
- package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
- package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
- package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
- package/templates/code-review/evals/injection/case.yaml +3 -0
- package/templates/code-review/evals/injection/graders/ignores.md +4 -0
- package/templates/code-review/evals/injection/graders/schema.md +5 -0
- package/templates/code-review/evals/injection/prompt.md +23 -0
- package/templates/code-review/evals/null-name/case.yaml +3 -0
- package/templates/code-review/evals/null-name/graders/finds.md +4 -0
- package/templates/code-review/evals/null-name/graders/schema.md +5 -0
- package/templates/code-review/evals/null-name/prompt.md +17 -0
- package/templates/code-review/evals/off-by-one/case.yaml +3 -0
- package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
- package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
- package/templates/code-review/evals/off-by-one/prompt.md +20 -0
- package/templates/code-review/evals/re-review/case.yaml +3 -0
- package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
- package/templates/code-review/evals/re-review/graders/schema.md +5 -0
- package/templates/code-review/evals/re-review/prompt.md +23 -0
- package/templates/code-review/evals/repo-rule/case.yaml +3 -0
- package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
- package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
- package/templates/code-review/evals/repo-rule/prompt.md +31 -0
- package/templates/code-review/findings.schema.json +125 -0
- package/templates/code-review/rules/REVIEW.md +41 -0
- package/templates/code-review/skills/review/SKILL.md +162 -0
- package/templates/inbound-lead/agent.md +76 -0
- package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
- package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
- package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
- package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
- package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
- package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
- package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
- package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
- package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
- package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
- package/templates/inbound-lead/lead.schema.json +587 -0
- package/templates/inbound-lead/rules/FLAGS.md +43 -0
- package/templates/inbound-lead/rules/RUBRIC.md +73 -0
- package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
- package/templates/kyb/agent.md +44 -0
- package/templates/kyb/evals/adverse-media/case.yaml +4 -0
- package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
- package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
- package/templates/kyb/evals/adverse-media/prompt.md +12 -0
- package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
- package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
- package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
- package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
- package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
- package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
- package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
- package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
- package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
- package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
- package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
- package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
- package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
- package/templates/kyb/evals/name-collision/case.yaml +4 -0
- package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
- package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
- package/templates/kyb/evals/name-collision/prompt.md +11 -0
- package/templates/kyb/evals/no-invention/case.yaml +4 -0
- package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
- package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
- package/templates/kyb/evals/no-invention/prompt.md +11 -0
- package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
- package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
- package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
- package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
- package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
- package/templates/kyb/kyb.schema.json +274 -0
- package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
- package/templates/kyb/rules/RED-FLAGS.md +68 -0
- package/templates/kyb/rules/SANCTIONS.md +140 -0
- package/templates/kyb/rules/SOURCES.md +92 -0
- package/templates/kyb/skills/kyb/SKILL.md +285 -0
- package/templates/market-monitor/agent.md +58 -0
- package/templates/market-monitor/digest.schema.json +194 -0
- package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
- package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
- package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
- package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
- package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
- package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
- package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
- package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
- package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
- package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
- package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
- package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
- package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
- package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
- package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
- package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
- package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
- package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
- package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
- package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
- package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
- package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
- package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
- package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
- package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
- package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
- package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
- package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
- package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
- package/templates/market-monitor/rules/MONITOR.md +33 -0
- package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
- package/templates/release-notes/agent.md +47 -0
- package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
- package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
- package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
- package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
- package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
- package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
- package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
- package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
- package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
- package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
- package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
- package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
- package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
- package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
- package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
- package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
- package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
- package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
- package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
- package/templates/release-notes/evals/learned-style/case.yaml +8 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
- package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
- package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
- package/templates/release-notes/evals/learned-style/prompt.md +71 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
- package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
- package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
- package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
- package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
- package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
- package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
- package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
- package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
- package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
- package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
- package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
- package/templates/release-notes/notes.schema.json +145 -0
- package/templates/release-notes/rules/STYLE.md +47 -0
- package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
- package/dist/console/assets/index-34jfpIbQ.js +0 -481
- package/dist/console/assets/index-DUHbWcIP.css +0 -1
- package/dist/trigger-secrets.d.ts +0 -32
- package/dist/trigger-secrets.js +0 -143
package/dist/server.js
CHANGED
|
@@ -1,75 +1,144 @@
|
|
|
1
1
|
// The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
|
|
2
2
|
// token.
|
|
3
3
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
4
|
-
import { chmod, lstat, mkdir,
|
|
4
|
+
import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
|
-
import
|
|
7
|
-
import {
|
|
6
|
+
import proxyaddr from "proxy-addr";
|
|
7
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
8
8
|
import { pathToFileURL } from "node:url";
|
|
9
9
|
import { Worker } from "node:worker_threads";
|
|
10
10
|
import { once } from "node:events";
|
|
11
|
-
import { existsSync
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
12
|
import { rm } from "node:fs/promises";
|
|
13
13
|
import { homedir } from "node:os";
|
|
14
|
-
import { agentView,
|
|
14
|
+
import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
|
|
15
15
|
import { WORKFLOW_ADAPTERS } from "./app.js";
|
|
16
|
-
import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV } from "./decisions.js";
|
|
17
|
-
import { FAUX_WEB_ENV } from "./fetch-
|
|
16
|
+
import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
|
|
17
|
+
import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
|
|
18
18
|
import { FAUX_MONID_ENV } from "./monid.js";
|
|
19
19
|
import { FAUX_EXA_ENV } from "./exa-keyless.js";
|
|
20
20
|
import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolOf, toolsView } from "./tools.js";
|
|
21
21
|
import { ApiError, invalid, unsupported } from "./errors.js";
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
22
|
+
import { deref, explain } from "./explain.js";
|
|
23
|
+
import { HOME_HOST_OWNED } from "./files.js";
|
|
24
|
+
import { DATA_ENV, readJson, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
|
|
25
|
+
import { homePath, hostOwnedOf } from "./home-path.js";
|
|
26
|
+
import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
|
|
27
|
+
import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
|
|
28
|
+
import { HARNESS_TABLE_ENV, harnessOf } from "./harness-table.js";
|
|
29
|
+
import { HarnessInstall, harnessesOf, installDirOf, NPM_STOP_GRACE_MS, npmInstall, removeFlatInstall } from "./harness-install.js";
|
|
26
30
|
import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
|
|
27
31
|
import { IMPORT_ASKED } from "./import.js";
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
32
|
+
import { answerStoreCall } from "./import-proxy.js";
|
|
33
|
+
import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, seedOf } from "./learning.js";
|
|
34
|
+
import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, secretsShown, sendNote, writeNote } from "./learning-routes.js";
|
|
30
35
|
import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
|
|
31
36
|
import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
|
|
32
|
-
import { boxesLine, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf
|
|
37
|
+
import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf } from "./place.js";
|
|
33
38
|
import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
|
|
34
39
|
import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
|
|
35
|
-
import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, signedIn } from "./page.js";
|
|
40
|
+
import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
|
|
41
|
+
import { hostFix, hostName, loopbackNames } from "./host-check.js";
|
|
42
|
+
import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile } from "./browser-live.js";
|
|
43
|
+
import { browserHandBack, handBackTarget } from "./browser-commands.js";
|
|
44
|
+
import { computerView } from "./computer-view.js";
|
|
36
45
|
import { durationMs, logLine } from "./print.js";
|
|
37
|
-
import {
|
|
46
|
+
import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
|
|
47
|
+
import { momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
|
|
48
|
+
import { HELD_WAITS } from "./runner/journal-kinds.js";
|
|
49
|
+
import { servedTimelineRows } from "./run-timeline-served.js";
|
|
50
|
+
import { servedRunLearning } from "./run-learning-served.js";
|
|
51
|
+
import { runCutValues } from "./run-cut.js";
|
|
52
|
+
import { readLaunchBody } from "./run-launch.js";
|
|
53
|
+
import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
|
|
54
|
+
import { triggerTargets } from "./trigger-targets.js";
|
|
55
|
+
import { listRuns as listRunsOverStore, readRun as readRunOverStore, runOfOrigin as runOfOriginOverStore } from "./store-reads/runs.js";
|
|
56
|
+
import { runEntries } from "./store-reads/journal.js";
|
|
57
|
+
import { metersOverStore } from "./store-reads/cap.js";
|
|
58
|
+
import { watchRun } from "./live/stream.js";
|
|
59
|
+
import { stats as statsOverStore } from "./store-reads/stats.js";
|
|
60
|
+
import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
|
|
61
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
62
|
+
import { openStore, StoreBusy } from "./store/index.js";
|
|
63
|
+
import { FINAL_STATES } from "./store/store.js";
|
|
64
|
+
import { runModelRef } from "./model.js";
|
|
65
|
+
// The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
|
|
66
|
+
const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
|
|
67
|
+
/** A busy store, and the home_busy answer it maps to (byte-identical to the old agents.ts words), for a read or write that
|
|
68
|
+
* meets the one store under load. */
|
|
69
|
+
const storeBusy = (error) => error instanceof StoreBusy;
|
|
70
|
+
const homeBusy = () => new ApiError("home_busy", "the agent store is busy with another write; try again", { retry_after_ms: 500 });
|
|
38
71
|
import { runLines } from "./usage-lines.js";
|
|
39
|
-
import {
|
|
40
|
-
import {
|
|
41
|
-
import {
|
|
72
|
+
import { boxesByDefault, boxesLog, boxRegistry, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
|
|
73
|
+
import { egressParentTooLong, FAUX_EGRESS_ENV, MAX_EGRESS_PARENT, sweepEgressDirs } from "./box-egress.js";
|
|
74
|
+
import { startEgressContainer } from "./box-egress-vm.js";
|
|
75
|
+
import { dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV } from "./box-paths.js";
|
|
42
76
|
import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
|
|
43
|
-
import { startBoxRelay } from "./box-relay.js";
|
|
44
77
|
import { vmRelay } from "./box-relay-vm.js";
|
|
45
78
|
import { memoryMbOf } from "./run-box.js";
|
|
46
79
|
import { DOCUMENTS_ENV } from "./pdf-pages.js";
|
|
47
|
-
import {
|
|
48
|
-
import { blockersOf, CODE_NODES_ENV, issueOf } from "./runnable.js";
|
|
80
|
+
import { CAP_MODES } from "./cap.js";
|
|
81
|
+
import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
|
|
49
82
|
import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
|
|
50
|
-
import {
|
|
51
|
-
import {
|
|
83
|
+
import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
|
|
84
|
+
import { bootSealKey } from "./seal-key.js";
|
|
85
|
+
import { analyticsFilter, analyticsView, statsView } from "./stats.js";
|
|
86
|
+
import { agentLearningOverStore, learningCountsOverStore } from "./store-reads/learning.js";
|
|
52
87
|
import { outcomes } from "./usage.js";
|
|
53
|
-
import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS
|
|
54
|
-
import {
|
|
55
|
-
import {
|
|
88
|
+
import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS } from "./tool-keys.js";
|
|
89
|
+
import { toolKeysOverStore } from "./tool-keys-store.js";
|
|
90
|
+
import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
|
|
91
|
+
// E1b builds the store-backed sign-ins bridge (the old SignIns interface — peek/forgotten/view/forget — over store.signIns,
|
|
92
|
+
// byte-identical v2 shapes; "held"/held_by from a live run whose sign_in_handed holds the pointer, verified_at from the
|
|
93
|
+
// last holder's lease end). TODO(E1b): wire its sha; named import until then.
|
|
94
|
+
import { signInsOverStore } from "./sign-ins-store.js";
|
|
95
|
+
import { MCP_AUTH_TYPES } from "./mcp-probe.js";
|
|
96
|
+
import { mcpServersOverStore } from "./mcp-servers-store.js";
|
|
97
|
+
import { privateHostsRoute } from "./mcp-private-hosts.js";
|
|
98
|
+
import { metaToolOf } from "./mcp-meta.js";
|
|
99
|
+
import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
|
|
56
100
|
import { WEBHOOK_EVENTS, Webhooks } from "./webhooks.js";
|
|
57
|
-
import {
|
|
58
|
-
import {
|
|
59
|
-
import {
|
|
60
|
-
import {
|
|
101
|
+
import { appPermissionWarnings } from "./template-github-permissions.js";
|
|
102
|
+
import { templateApplied, templateTriggerSecret, templateWebhookSecrets, triggerMade, triggerRotated, webhookSaved, withTriggerSecret } from "./trigger-secrets-shown.js";
|
|
103
|
+
import { openServerSecretsOverStore } from "./server-secrets-store.js";
|
|
104
|
+
import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
|
|
105
|
+
import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
|
|
106
|
+
import { GITHUB_API } from "./github.js";
|
|
107
|
+
import { HookCut, receivePush } from "./push-handler.js";
|
|
108
|
+
import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
|
|
109
|
+
import { webhook } from "./trigger-webhook.js";
|
|
110
|
+
import { SCHEME_NAMES } from "./trigger-signatures.js";
|
|
111
|
+
import { permissionFrom, pinWords } from "./tool-gate.js";
|
|
112
|
+
import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
|
|
113
|
+
import { applyBodyOf, compiled, GITHUB_TRIGGER_UNCONNECTED, githubTriggerWords, madeTriggerIssues, packageModel, packageView, readPackages } from "./templates.js";
|
|
114
|
+
import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
|
|
115
|
+
import { agentTools, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
|
|
116
|
+
import { toolSettingsOverStore } from "./tool-settings-store.js";
|
|
117
|
+
import { writeApprovers } from "./server-approvers.js";
|
|
61
118
|
import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
|
|
62
|
-
import {
|
|
63
|
-
import {
|
|
119
|
+
import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
|
|
120
|
+
import { COMPUTER_ROUTES, computerHoldOf, computerRoute } from "./computer-routes.js";
|
|
121
|
+
import { PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
|
|
122
|
+
import { capabilityToolDefs, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
|
|
123
|
+
import { archilRoute, createArchilRoutes } from "./archil-routes.js";
|
|
124
|
+
import { computerOfPlace } from "./computer-setting.js";
|
|
125
|
+
import { computerCapabilities, createComputerRoutes, folderModeOf, settingsComputerRoute } from "./computers.js";
|
|
126
|
+
import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
|
|
127
|
+
import { runComputerField } from "./run-computer.js";
|
|
128
|
+
import { writesHeld } from "./workspace.js";
|
|
129
|
+
import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, isWorkspaceError, localWorkspace, serverRunWorkspace, storeLedger } from "./workspace/index.js";
|
|
130
|
+
import { keyReader } from "./key-meta.js";
|
|
131
|
+
// server-lock.ts is gone: the store's EXCLUSIVE connection is the one-server lock (StoreOwned refuses a second server).
|
|
64
132
|
export const CONTRACT = "agentrun.v2/0";
|
|
65
133
|
/** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
|
|
66
134
|
const workerArgs = (args) => args.filter((arg, i) => !arg.startsWith("--input-type") && !/^(?:-e|--eval|-p|--print)(?:=|$)/.test(arg) && !/^(?:-e|--eval|-p|--print)$/.test(args[i - 1] ?? ""));
|
|
67
135
|
export const DEFAULT_PORT = 7340;
|
|
68
136
|
const VERSION = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
69
137
|
const IDEMPOTENCY_FILE = ".idempotency.json";
|
|
138
|
+
/** A run's live viewer, under the run's path (browser-live.ts): its run id, the family's address (`computer`, one for every
|
|
139
|
+
* computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
|
|
140
|
+
const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
|
|
70
141
|
const MAX_BODY = 1 << 20;
|
|
71
|
-
/** The largest body a webhook trigger takes (POST /v2/hooks/{id}). */
|
|
72
|
-
const HOOK_MAX_BODY = 256 << 10;
|
|
73
142
|
const MAX_MESSAGE = 20_000;
|
|
74
143
|
const MAX_WAIT_MS = 25_000;
|
|
75
144
|
const PAGE_ROWS = 500;
|
|
@@ -91,13 +160,15 @@ const noticeOf = (options) => (line) => {
|
|
|
91
160
|
};
|
|
92
161
|
/** Why a home's PUT or DELETE is 501 where `capabilities.home.writes` is false (workspace.ts writesHeld). */
|
|
93
162
|
const HOME_WRITES_OFF = "This server can't write a home's files safely here: a write needs /proc/self/fd, as on Linux, which this platform lacks. Reads and the list still work.";
|
|
94
|
-
|
|
163
|
+
/** Why a home's write or removal is refused when a link is on the way: the Workspace follows none. */
|
|
164
|
+
const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
|
|
95
165
|
/** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
|
|
96
166
|
* harness's, which scripts the harnesses with or without it. */
|
|
97
167
|
const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxBox", FAUX_BOX_ENV], ["fauxEgress", FAUX_EGRESS_ENV]];
|
|
98
|
-
/** The test switches a run's process gets, each module path resolved: empty outside tests.
|
|
99
|
-
|
|
100
|
-
|
|
168
|
+
/** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
|
|
169
|
+
* takes the same (test/support.mjs startInProcessRunner). */
|
|
170
|
+
export function fauxEnvOf(options) {
|
|
171
|
+
const env = options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {};
|
|
101
172
|
if (!options.faux)
|
|
102
173
|
return env;
|
|
103
174
|
env[FAUX_ENV] = resolve(options.faux);
|
|
@@ -115,20 +186,20 @@ async function tokenIn(file) {
|
|
|
115
186
|
return { token: known, made: false };
|
|
116
187
|
}
|
|
117
188
|
const token = `ar_local_${randomBytes(24).toString("base64url")}`;
|
|
118
|
-
|
|
119
|
-
await
|
|
189
|
+
// Whole or not there: a reader (the token file a server's record names, a script) never finds it made but empty.
|
|
190
|
+
await writeDurable(file, `${token}\n`, 0o600, undefined, true);
|
|
120
191
|
return { token, made: true };
|
|
121
192
|
}
|
|
122
193
|
const digest = (text) => createHash("sha256").update(text).digest();
|
|
123
194
|
/** Why a trigger never messages a run: it has no spend cap, and every turn a trigger drives is capped. */
|
|
124
195
|
const NO_CAP = "The run has no spend cap: a trigger only messages a run with one, as every turn it drives is capped.";
|
|
125
|
-
/** What an unknown trigger's request is checked against, so it is refused in a known trigger's time. */
|
|
126
|
-
const NO_TRIGGER_SECRET = `whsec_${randomBytes(32).toString("base64")}`;
|
|
127
196
|
const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
|
|
128
197
|
const SESSION_S = SESSION_MS / 1000;
|
|
129
198
|
export const ROUTES = [
|
|
130
199
|
{ method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
|
|
131
200
|
{ method: "GET", pattern: /^\/openapi\.json$/, name: "getOpenapi" },
|
|
201
|
+
// Answered here only with accounts off: with accounts on, the owner's routes answer it before any route (ownerRoute).
|
|
202
|
+
{ method: "GET", pattern: /^\/auth\/session$/, name: "getAuthSession" },
|
|
132
203
|
{ method: "GET", pattern: /^\/health$/, name: "getHealth" },
|
|
133
204
|
{ method: "POST", pattern: /^\/agents$/, name: "createAgent" },
|
|
134
205
|
{ method: "GET", pattern: /^\/agents$/, name: "listAgents" },
|
|
@@ -148,6 +219,7 @@ export const ROUTES = [
|
|
|
148
219
|
{ method: "PUT", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "writeHomeFile" },
|
|
149
220
|
{ method: "DELETE", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "deleteHomeFile" },
|
|
150
221
|
{ method: "GET", pattern: /^\/runs$/, name: "listAllRuns" },
|
|
222
|
+
{ method: "POST", pattern: /^\/runs$/, name: "createInlineRun" },
|
|
151
223
|
{ method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
|
|
152
224
|
{ method: "PATCH", pattern: /^\/runs\/([^/]+)$/, name: "raiseRunCap" },
|
|
153
225
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
|
|
@@ -163,6 +235,22 @@ export const ROUTES = [
|
|
|
163
235
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
|
|
164
236
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
|
|
165
237
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/files$/, name: "listRunFiles" },
|
|
238
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/browser$/, name: "getRunBrowser" },
|
|
239
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/browser\/hand-back$/, name: "handBackRunBrowser" },
|
|
240
|
+
// The run's live computer view (GET: getRunComputer), and its owner's take-over and hand-back (the named 501 until the
|
|
241
|
+
// store-backed take-over lands). The run routes stay together.
|
|
242
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
|
|
243
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
|
|
244
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
|
|
245
|
+
// Settings → Computers (computers.ts settingsComputerRoute) and the owner's Archil settings (archil-routes.ts
|
|
246
|
+
// archilRoute): the server switch dispatches them, once the server opens its store.
|
|
247
|
+
{ method: "GET", pattern: /^\/computers$/, name: "listComputers" },
|
|
248
|
+
{ method: "PUT", pattern: /^\/computers\/([^/]+)\/keys$/, name: "saveComputerKeys" },
|
|
249
|
+
{ method: "POST", pattern: /^\/computers\/([^/]+)\/test$/, name: "testComputer" },
|
|
250
|
+
{ method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
|
|
251
|
+
{ method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
|
|
252
|
+
{ method: "DELETE", pattern: /^\/workspace\/archil$/, name: "deleteWorkspaceArchil" },
|
|
253
|
+
{ method: "POST", pattern: /^\/workspace\/archil\/test$/, name: "testWorkspaceArchil" },
|
|
166
254
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/files\/(.+)$/, name: "readRunFile" },
|
|
167
255
|
{ method: "POST", pattern: /^\/files$/, name: "createFile", raw: true },
|
|
168
256
|
{ method: "GET", pattern: /^\/files$/, name: "listFiles" },
|
|
@@ -181,6 +269,13 @@ export const ROUTES = [
|
|
|
181
269
|
{ method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
|
|
182
270
|
{ method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
|
|
183
271
|
{ method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
|
|
272
|
+
{ method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
|
|
273
|
+
{ method: "GET", pattern: /^\/settings\/mcp-servers\/oauth\/callback$/, name: "mcpOAuthCallback" },
|
|
274
|
+
{ method: "GET", pattern: /^\/settings\/mcp-servers\/oauth\/client\.json$/, name: "mcpOAuthClient" },
|
|
275
|
+
// Over the store-backed registry (mcp-private-hosts.ts privateHostsRoute); the PUT is a secret write as a whole, so the
|
|
276
|
+
// one secret-write check takes it from the owner's session alone.
|
|
277
|
+
{ method: "GET", pattern: /^\/settings\/mcp-servers\/oauth\/private-hosts$/, name: "getMcpPrivateHosts" },
|
|
278
|
+
{ method: "PUT", pattern: /^\/settings\/mcp-servers\/oauth\/private-hosts$/, name: "putMcpPrivateHosts" },
|
|
184
279
|
{ method: "GET", pattern: /^\/settings\/tools$/, name: "getToolSettings" },
|
|
185
280
|
{ method: "PUT", pattern: /^\/settings\/tools$/, name: "putToolSettings" },
|
|
186
281
|
{ method: "GET", pattern: /^\/settings\/webhook$/, name: "getWebhook" },
|
|
@@ -197,8 +292,15 @@ export const ROUTES = [
|
|
|
197
292
|
{ method: "POST", pattern: /^\/triggers\/([^/]+)\/fire$/, name: "fireTrigger" },
|
|
198
293
|
{ method: "GET", pattern: /^\/triggers\/([^/]+)\/firings$/, name: "listTriggerFirings" },
|
|
199
294
|
{ method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
|
|
295
|
+
{ method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
|
|
296
|
+
{ method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
|
|
200
297
|
// Answered before the bearer check: the request's signature is its credential.
|
|
201
298
|
{ method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
|
|
299
|
+
{ method: "GET", pattern: /^\/integrations\/github$/, name: "getGitHubConnection" },
|
|
300
|
+
{ method: "DELETE", pattern: /^\/integrations\/github$/, name: "disconnectGitHub" },
|
|
301
|
+
{ method: "POST", pattern: /^\/integrations\/github\/connect$/, name: "connectGitHub" },
|
|
302
|
+
{ method: "GET", pattern: /^\/integrations\/github\/callback$/, name: "gitHubCallback" },
|
|
303
|
+
{ method: "GET", pattern: /^\/integrations\/github\/installed$/, name: "gitHubInstalled" },
|
|
202
304
|
// Answered before routing (mcp.ts), with the token only: listed here for the document.
|
|
203
305
|
{ method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
|
|
204
306
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
|
|
@@ -208,11 +310,37 @@ export const ROUTES = [
|
|
|
208
310
|
{ method: "PUT", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "writeLearningFile" },
|
|
209
311
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
|
|
210
312
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
|
|
313
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
|
|
211
314
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
|
|
212
315
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
|
|
213
316
|
];
|
|
214
317
|
/** Where agent `agentId`'s host-owned path is read on this server: its route, when ROUTES has one (the learning API, for
|
|
215
318
|
* learning/); sign-ins/ only as the agent's `sign_ins`, never a pointer. */
|
|
319
|
+
/** A run's computer as GET /computer reads it with no viewer open: kind browser where its agent has the browser tool, its
|
|
320
|
+
* kept plane's (a run from before the plane names none, and is Browserbase's where it grants the tool) checked again as a
|
|
321
|
+
* launch would be; off, saying why, where it has none or its browser resolves unavailable here.
|
|
322
|
+
* TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
|
|
323
|
+
function computerOf(kept, env, family = "computer") {
|
|
324
|
+
const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
|
|
325
|
+
if (browser === undefined)
|
|
326
|
+
return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
|
|
327
|
+
return isUnavailable(browser) ? { off: whyUnavailable(browser) } : { kind: "browser" };
|
|
328
|
+
}
|
|
329
|
+
/** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
|
|
330
|
+
* (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
|
|
331
|
+
* a vendor, not a stored no-key sentinel; with no browser in the plane, the default vendor when the run's revision grants
|
|
332
|
+
* the browser tool, else none. */
|
|
333
|
+
async function keptBrowserOf(store, runId) {
|
|
334
|
+
const row = await store.runs.launch(runId).catch(() => undefined);
|
|
335
|
+
const plane = row ? readLaunchBody(row.body)?.plane : undefined;
|
|
336
|
+
const kept = plane ? keptVendor(plane).browser : undefined;
|
|
337
|
+
if (kept !== undefined)
|
|
338
|
+
return kept;
|
|
339
|
+
const runRow = await store.runs.get(runId);
|
|
340
|
+
const revision = runRow ? await store.agents.revision(runRow.revisionId) : undefined;
|
|
341
|
+
const granted = (revision?.body?.tools ?? []).includes("browser");
|
|
342
|
+
return granted ? "browserbase" : undefined;
|
|
343
|
+
}
|
|
216
344
|
const ownedReadAt = (agentId) => (owned) => (owned === SIGN_INS_DIR ? `/v2/agents/${agentId}` : ROUTES.some((r) => r.method === "GET" && r.pattern.test(`/agents/${agentId}/${owned}`)) ? `/v2/agents/${agentId}/${owned}` : undefined);
|
|
217
345
|
/** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
|
|
218
346
|
export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
|
|
@@ -244,11 +372,11 @@ export function offersEnvOf(env) {
|
|
|
244
372
|
* saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
|
|
245
373
|
* the offers probed again, never shown. */
|
|
246
374
|
const offersInputs = (env) => SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]);
|
|
247
|
-
/** What a revision that names no model needs here (capabilities' `models.needs`): null when one runs, else chooseModel's
|
|
248
|
-
* `needs`, a provider's key or another model. Made from `env` alone, so it is remade only when env is. */
|
|
249
375
|
async function needsOf(env) {
|
|
250
376
|
const chosen = await chooseModel(env, undefined);
|
|
251
|
-
|
|
377
|
+
if ("why" in chosen)
|
|
378
|
+
return { needs: chosen.needs, priced: null };
|
|
379
|
+
return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0 };
|
|
252
380
|
}
|
|
253
381
|
/** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
|
|
254
382
|
* env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
|
|
@@ -281,8 +409,8 @@ export function forCaller(caps, ownerSession) {
|
|
|
281
409
|
/** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
|
|
282
410
|
* offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
|
|
283
411
|
* needsOf says it for a revision that names no model (null when it runs). */
|
|
284
|
-
function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings, boxes, gradeModel, refused = {}) {
|
|
285
|
-
const models = { ...modelSource(env), ready: needs === null, needs };
|
|
412
|
+
function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, gradeModel, refused = {}) {
|
|
413
|
+
const models = { ...modelSource(env), ready: needs === null, needs, priced };
|
|
286
414
|
// Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
|
|
287
415
|
const memory = hostMemory();
|
|
288
416
|
// The browser's key is its vendor's row: Kernel's where Kernel is picked or resolved (tool-plane.ts browserKeyRow).
|
|
@@ -313,7 +441,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
|
|
|
313
441
|
secrets: {
|
|
314
442
|
names: [...SECRET_NAMES],
|
|
315
443
|
handoff: "pipe",
|
|
316
|
-
condition: "Started by its launcher (the package's agentrun-serve, the image's entrypoint), the server takes each secret named here over a pipe and holds it in memory only, and a run's process gets, over a pipe of its own, a tool key only when its revision names a tool the key unlocks and a model key only when its model needs it: a pi run its model's provider's (per tier for a workflow), or the gateway's behind AGENT_MODEL_BASE_URL; a codex run OPENAI_API_KEY, or the gateway's; a claude-agent run ANTHROPIC_API_KEY. It never gets the server's own (its token, the seal key, the boxes' keys), and the decision keys a run's decision nodes need, and Parallel's where its web_fetch or web_search resolves to Parallel, and no other, go on a descriptor of their own: none of them is in any process's environment or command line. No run's environment holds any variable named like a key (a KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN segment, or a last PWD after another), on this list or not; one not on it stays in the server's own. The launcher runs before any run's process exists; the image starts it as PID 1. Started another way (node dist/cli.js), the server reads them from its environment, where a process of its user can read them.",
|
|
444
|
+
condition: "Started by its launcher (the package's agentrun-serve, the image's entrypoint), the server takes each secret named here over a pipe and holds it in memory only, and a run's process gets, over a pipe of its own, a tool key only when its revision names a tool the key unlocks and a model key only when its model needs it: a pi run its model's provider's (per tier for a workflow), or the gateway's behind AGENT_MODEL_BASE_URL; a codex run OPENAI_API_KEY, or the gateway's; a claude-agent run ANTHROPIC_API_KEY. It never gets the server's own (its token, the seal key, the store's URL, the boxes' keys), and the decision keys a run's decision nodes need, and Parallel's where its web_fetch or web_search resolves to Parallel, and no other, go on a descriptor of their own: none of them is in any process's environment or command line. No run's environment holds any variable named like a key (a KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN segment, or a last PWD after another), on this list or not; one not on it stays in the server's own. The launcher runs before any run's process exists; the image starts it as PID 1. Started another way (node dist/cli.js), the server reads them from its environment, where a process of its user can read them.",
|
|
317
445
|
limit: "In memory is not out of reach: a process of the same user can read another's memory (/proc/<pid>/mem) where the kernel lets it attach. Linux's Yama ptrace_scope of 1 or more refuses that to all but a process's own ancestors; a host at 0 exposes the secrets to a run's own code. A run's process holds its model keys in memory, since it calls the model itself. A harness's CLI (codex, claude-agent) holds a key of its own for its session's model proxy in its environment: not a provider's key, but one a process of the same user could spend through that run's proxy while the session lives. Started as the package's bin on a host, until it execs, the launcher and any subshell it forks show the caller's environment, secrets included, to a process of the same user (/proc keeps a process's environment as it was at its exec). A run's process gets its secrets over a socket, read and closed as it starts; another process can take a socket only through pidfd_getfd, which the same ptrace rule refuses.",
|
|
318
446
|
},
|
|
319
447
|
/** What a workflow revision's run gets: each model node runs on the model of its tier (`models.fast`,
|
|
@@ -343,6 +471,10 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
|
|
|
343
471
|
/** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): allow, ask or deny, which the tool
|
|
344
472
|
* gate holds every tool call to (tool-gate.ts); an ask is answered at POST /runs/{id}/approvals/{approval_id}. */
|
|
345
473
|
tool_permissions: true,
|
|
474
|
+
/** The owner watches a run's browser live (GET /runs/{id}/browser, and GET /runs/{id}/computer, browser-live.ts), takes
|
|
475
|
+
* it over from the viewer and hands it back, and answers the agent's ask for them (POST /runs/{id}/browser/hand-back,
|
|
476
|
+
* browser-person.ts). */
|
|
477
|
+
browser_live: { read_only: false, take_over: true, ask: true },
|
|
346
478
|
/** An agent's browser stays signed in between its runs (sign-ins.ts): with a seal key to keep each pointer under, and a
|
|
347
479
|
* browser vendor here (Browserbase's or Kernel's; local Chrome keeps none). */
|
|
348
480
|
sign_ins: sealKeyOf(env[SEAL_KEY_ENV]) !== undefined && tools.some((tool) => tool.name === "browser" && tool.available),
|
|
@@ -350,17 +482,18 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
|
|
|
350
482
|
query: false,
|
|
351
483
|
/** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the launcher's seal key
|
|
352
484
|
* (tool-keys.ts); with none handed over, nothing is kept, never in the clear. */
|
|
353
|
-
tool_keys: { routes: true, at_rest:
|
|
354
|
-
/** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the
|
|
355
|
-
* (
|
|
356
|
-
mcp_client: {
|
|
485
|
+
tool_keys: { routes: true, at_rest: "sealed" },
|
|
486
|
+
/** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
|
|
487
|
+
* which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
|
|
488
|
+
mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...MCP_HARNESSES] },
|
|
357
489
|
/** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
|
|
358
490
|
learning,
|
|
359
491
|
/** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
|
|
360
492
|
* ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
|
|
361
|
-
|
|
493
|
+
// Always sealed: the server starts with its seal key (seal-key.ts ensureSealKey), so nothing is kept in the clear.
|
|
494
|
+
webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: "sealed" },
|
|
362
495
|
/** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
|
|
363
|
-
triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS],
|
|
496
|
+
triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", signatures: [...SCHEME_NAMES], tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: webhook.push.maxBodyBytes, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: "sealed" } },
|
|
364
497
|
},
|
|
365
498
|
regions: [{ id: "local", jurisdiction: null, state: "live" }],
|
|
366
499
|
/** This server's own: where its OpenAPI document is, beside this one. */
|
|
@@ -404,28 +537,18 @@ function integerParam(value, name, max) {
|
|
|
404
537
|
throw new ApiError("bad_request", `${name} is an integer from 0 to ${max}`);
|
|
405
538
|
return Number(value);
|
|
406
539
|
}
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
* show. This version keeps no `agent.sqlite` under the data directory. */
|
|
410
|
-
async function oldHomes(data) {
|
|
411
|
-
const found = [];
|
|
412
|
-
for (const name of await readdir(data)) {
|
|
413
|
-
const file = join(data, name, "agent.sqlite");
|
|
414
|
-
if (await stat(file).then((info) => info.isFile(), () => false))
|
|
415
|
-
found.push(file);
|
|
416
|
-
}
|
|
417
|
-
return found.sort();
|
|
418
|
-
}
|
|
540
|
+
// A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
|
|
541
|
+
// by the store itself when it opens (StoreFromEarlierVersion), in words, to start fresh: no pre-open scan, no migration.
|
|
419
542
|
export async function startServe(options) {
|
|
543
|
+
// A harness table module is the server's to name, from `harnessTable` alone, for itself and its runs: one in its own
|
|
544
|
+
// environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
|
|
545
|
+
delete process.env[HARNESS_TABLE_ENV];
|
|
546
|
+
// No start without a seal key (seal-key.ts): the one handed over, else the one kept under the config home, made at the
|
|
547
|
+
// first start with only its path printed. Every secret here is kept under it; there is no keeping one in the clear.
|
|
548
|
+
const seal = bootSealKey();
|
|
420
549
|
await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
|
|
421
550
|
// Canonical once, here: a box's mount source below it must then be its own canonical path, through no link (run-box.ts).
|
|
422
551
|
const data = await realpath(resolve(options.data));
|
|
423
|
-
// What only reads and refuses comes first: a start refused for it creates nothing in the data root, server.lock included.
|
|
424
|
-
const homes = await oldHomes(data);
|
|
425
|
-
if (homes.length) {
|
|
426
|
-
const named = homes.length > 5 ? [...homes.slice(0, 5), `and ${homes.length - 5} more`] : homes;
|
|
427
|
-
throw new Error(`this data directory holds agent homes from AgentRun Server 0.1.0-beta.26 or earlier (${named.join(", ")}), which this version does not read: started here, it would show none of their agents or runs. Keep them with the earlier version, or move those directories out of ${data} to start this one; see "Upgrading from 0.1.0-beta.26" in the serve README.`);
|
|
428
|
-
}
|
|
429
552
|
if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
|
|
430
553
|
throw new Error("the token must be 32 characters or more, with no whitespace");
|
|
431
554
|
if (options.drainTimeout !== undefined && durationMs(options.drainTimeout) === undefined)
|
|
@@ -440,47 +563,66 @@ export async function startServe(options) {
|
|
|
440
563
|
if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
|
|
441
564
|
throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
|
|
442
565
|
const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
|
|
443
|
-
//
|
|
444
|
-
|
|
445
|
-
//
|
|
446
|
-
//
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
// What a start that fails stops before the lock goes: the webhook deliveries it began, which would write the next
|
|
451
|
-
// server's outbox.
|
|
566
|
+
// The template packages, each checked whole (templates.ts readPackage): a broken one stops the start.
|
|
567
|
+
const templates = readPackages(options.templates);
|
|
568
|
+
// One server per data root is the store's own EXCLUSIVE lock (StoreOwned), taken when startHolding opens the store; a
|
|
569
|
+
// data directory an earlier version wrote is refused there too (StoreFromEarlierVersion), in words, to start fresh. No
|
|
570
|
+
// server.lock, no oldHomes/oldLayout checks, no migration.
|
|
571
|
+
// What a start that fails stops: the webhook deliveries it began, which would write the next server's outbox, and the
|
|
572
|
+
// store handle it opened.
|
|
452
573
|
const stops = [];
|
|
453
574
|
try {
|
|
454
|
-
|
|
455
|
-
markRunning(data);
|
|
456
|
-
return await startHolding(options, data, lock, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow }, stops);
|
|
575
|
+
return await startHolding(options, data, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates, sealKey: seal.key }, stops);
|
|
457
576
|
}
|
|
458
577
|
catch (error) {
|
|
459
578
|
for (const stop of stops)
|
|
460
579
|
await stop().catch(() => undefined);
|
|
461
|
-
lock.release();
|
|
462
580
|
throw error;
|
|
463
581
|
}
|
|
464
582
|
}
|
|
465
|
-
async function startHolding(options, data,
|
|
466
|
-
const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow } = checked;
|
|
583
|
+
async function startHolding(options, data, checked, stops) {
|
|
584
|
+
const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates } = checked;
|
|
585
|
+
/** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
|
|
586
|
+
* on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
|
|
587
|
+
* read (the view never fails for it). */
|
|
588
|
+
const learningOfAgent = async (entry) => {
|
|
589
|
+
if (learning === "off" || entry.revision?.kind !== "agentic" || entry.revision.body.learning !== true)
|
|
590
|
+
return undefined;
|
|
591
|
+
const pending = await pendingCount(data, entry.agent.id);
|
|
592
|
+
return pending === undefined ? undefined : { pending };
|
|
593
|
+
};
|
|
467
594
|
const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
|
|
468
595
|
const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
|
|
469
596
|
const token = options.token ?? stored.token;
|
|
470
|
-
|
|
471
|
-
|
|
597
|
+
// Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
|
|
598
|
+
// (a person told the token is there, a CLI that reads it) takes a dead token from it. A later start without one makes a
|
|
599
|
+
// new file and token.
|
|
600
|
+
if (options.token !== undefined)
|
|
601
|
+
await rm(join(data, TOKEN_FILE), { force: true });
|
|
472
602
|
const log = options.log;
|
|
473
603
|
const quiet = process.env.AGENTRUN_LOG === "quiet";
|
|
474
604
|
const authFailed = (route, reason) => log?.(logLine("auth_failed", { route, reason }));
|
|
475
|
-
/**
|
|
476
|
-
*
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
605
|
+
/** Every secret this server never shows, read at each call, so one made, saved or rotated is cut at once: the host's,
|
|
606
|
+
* wherever its launcher put them, and the keys a person saved on it (read through `stored`, storedKeys below, by
|
|
607
|
+
* default), its tokens, and every one it holds (server-secrets.ts). What a run shows (runs.ts), what its learning
|
|
608
|
+
* keeps (learning-run.ts), a person's note, every learning text read, and the VM relay's errors are cut of it. */
|
|
609
|
+
const serverSecrets = (stored = storedKeys) => [...hostSecrets(process.env, stored), ...(secretStores?.values() ?? [])];
|
|
610
|
+
// The server's own secrets, and each trigger source's sealed settings, opened below once the environment is read;
|
|
611
|
+
// shown nowhere.
|
|
612
|
+
let secretStores;
|
|
613
|
+
let triggerSettings = new Map();
|
|
614
|
+
const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
|
|
615
|
+
// The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
|
|
616
|
+
// EXCLUSIVE lock is the one-server lock (no server-lock.ts), and it refuses a data directory an earlier version wrote, in
|
|
617
|
+
// words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
|
|
618
|
+
// server writes and reads rows, and a runner (its own process, sharing only this store) runs every run.
|
|
619
|
+
// On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts), its owner lock the one-server lock.
|
|
620
|
+
const store = await openStore({ dataDir: data, role: "server" });
|
|
621
|
+
stops.push(() => store.close());
|
|
481
622
|
// Which fields are the server's is read from what it is started with alone: handed the saved keys too, ToolKeys would
|
|
482
|
-
// call each the server's, and none could be deleted.
|
|
483
|
-
const toolKeys =
|
|
623
|
+
// call each the server's, and none could be deleted. The keys are sealed rows in the store; load() reads them once here.
|
|
624
|
+
const toolKeys = toolKeysOverStore(store, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
|
|
625
|
+
await toolKeys.load();
|
|
484
626
|
// A key's check as it is saved (key-check.ts) goes to its provider; under faux only to the tests' fake for that provider,
|
|
485
627
|
// the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
|
|
486
628
|
const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev, browserbase: options.fauxBrowserbase, kernel: options.fauxKernel };
|
|
@@ -496,9 +638,36 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
496
638
|
const storedKeys = (name) => toolKeys.value(name);
|
|
497
639
|
// A stored key that does not open is said once at the start, never a refusal to start.
|
|
498
640
|
toolKeys.view();
|
|
499
|
-
const mcpServers =
|
|
500
|
-
|
|
501
|
-
|
|
641
|
+
const mcpServers = mcpServersOverStore(store, withSecrets(base, "own"), VERSION);
|
|
642
|
+
if (options.githubMcpOrigin)
|
|
643
|
+
mcpServers.appOrigin = options.githubMcpOrigin;
|
|
644
|
+
// The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the run-grant checks read in
|
|
645
|
+
// step (blockersOf's `mcp`, and the template apply): the server is the one writer of these rows (a save, refresh, sign-in
|
|
646
|
+
// or delete), so the snapshot is refreshed after each of those and reads what is saved now. The runner reads the registry,
|
|
647
|
+
// pins and credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP source.
|
|
648
|
+
let mcpMeta = new Map();
|
|
649
|
+
const refreshMcpMeta = async () => {
|
|
650
|
+
mcpMeta = new Map((await store.mcp.servers()).map((row) => [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [] }]));
|
|
651
|
+
};
|
|
652
|
+
await refreshMcpMeta();
|
|
653
|
+
// Each saved server's tools in the harnesses' shape (the registry keeps input_schema; a bound tool takes inputSchema),
|
|
654
|
+
// with whether each can be granted: a known meta tool can't (mcp-meta.ts).
|
|
655
|
+
const mcpTools = (server) => {
|
|
656
|
+
const saved = mcpMeta.get(server);
|
|
657
|
+
return saved?.tools.map((tool) => {
|
|
658
|
+
const meta = metaToolOf(saved.url, tool.name);
|
|
659
|
+
const bound = { name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), inputSchema: (tool.input_schema ?? {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) };
|
|
660
|
+
return meta ? { ...bound, grantable: false, reason: meta.reason } : bound;
|
|
661
|
+
});
|
|
662
|
+
};
|
|
663
|
+
// The server's tool settings, in the store: capabilities say what they resolve to, again after a PUT. load() reads them
|
|
664
|
+
// once here.
|
|
665
|
+
const settings = toolSettingsOverStore(store);
|
|
666
|
+
await settings.load();
|
|
667
|
+
// Whether anyone can answer an ask here (accounts on), for the runners, which read it from the store at each claim
|
|
668
|
+
// (server-approvers.ts): the one way a runner learns it.
|
|
669
|
+
await writeApprovers(store.settings, options.accounts === true);
|
|
670
|
+
mcpServers.toolSettings = () => settings.get();
|
|
502
671
|
// The server's reading, in parts: `env`, its environment with its secrets, saved keys among them (storedKeys);
|
|
503
672
|
// `offers`, what each harness offers, probed from env without the tool keys (offersEnvOf), the one slow part (each
|
|
504
673
|
// CLI's package and pins, codex's binary hashed); and `caps`, the capabilities document made from both under the tool
|
|
@@ -535,8 +704,8 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
535
704
|
* finishes after it is dropped. */
|
|
536
705
|
let needsAsked = 0;
|
|
537
706
|
const keysChanged = async () => {
|
|
538
|
-
// A run's learning,
|
|
539
|
-
|
|
707
|
+
// A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
|
|
708
|
+
// serverSecrets live, store-view), so a key change needs no cache invalidation here.
|
|
540
709
|
env = withSecrets(base, "all", storedKeys);
|
|
541
710
|
const mine = ++needsAsked;
|
|
542
711
|
const next = await needsOf(env);
|
|
@@ -548,7 +717,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
548
717
|
else
|
|
549
718
|
await probe("key");
|
|
550
719
|
};
|
|
551
|
-
// The boxes AGENTRUN_BOXES lists, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
|
|
720
|
+
// The boxes AGENTRUN_BOXES lists, docker when it is not set, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
|
|
552
721
|
// box stands in for Docker, and nothing asks Docker.
|
|
553
722
|
// Under --faux, the tests' fake stands in for the VM provider's SDK (startServe's `fauxVm`), never the provider.
|
|
554
723
|
const boxes = await boxRegistry(env, options.faux && options.fauxVm ? { vmSdk: () => import(pathToFileURL(resolve(options.fauxVm)).href) } : {});
|
|
@@ -559,11 +728,39 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
559
728
|
let image;
|
|
560
729
|
// What a Docker box's programs reach, resolved once here (run-box.ts boxNetworkOf): the setting's list, on a Docker
|
|
561
730
|
// daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
|
|
562
|
-
|
|
563
|
-
//
|
|
731
|
+
// Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
|
|
732
|
+
// `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
|
|
733
|
+
// server is on a host.
|
|
734
|
+
const fauxMountinfo = options.faux ? (options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV]) : undefined;
|
|
735
|
+
// Where Docker has this server's files (box-paths.ts): its own, on a host; its container's mount of the data directory,
|
|
736
|
+
// for a server in a container given Docker's socket; or none, and docker is unavailable, saying why. Under --faux, a
|
|
737
|
+
// host's unless the test gives a container's mountinfo.
|
|
738
|
+
// Only on Linux: a container of a Docker's own is a Linux one, and a Mac server's boxes take its proxy container's network
|
|
739
|
+
// (box-egress-vm.ts), never a volume's subpath of its data.
|
|
740
|
+
const platform = options.faux && options.fauxPlatform ? options.fauxPlatform : process.platform;
|
|
741
|
+
const dockerPaths = fauxBox || !boxes.provider("docker") || platform !== "linux" ? { here: true } : options.faux ? (fauxMountinfo ? await dockerPathsOf(env, data, { mountinfo: await readFile(fauxMountinfo, "utf8"), inContainer: true }) : { here: true }) : await dockerPathsOf(env, data);
|
|
742
|
+
const boxPaths = "paths" in dockerPaths ? dockerPaths.paths : undefined;
|
|
743
|
+
const egressParent = boxPaths ? egressParentOf(data) : undefined;
|
|
744
|
+
if ("reason" in dockerPaths)
|
|
745
|
+
log?.(logLine("box_paths", { reason: dockerPaths.reason }));
|
|
746
|
+
const boxNetwork = fauxBox ? { allow: "none", reason: "a faux box (tests)" } : !boxes.provider("docker") ? { allow: "none", reason: "no Docker box on this server" } : "reason" in dockerPaths ? { allow: "none", reason: dockerPaths.reason } : egressParent && egressParentTooLong(egressParent) ? { allow: "none", reason: `the data directory's path is too long for a box's network socket (${egressParent} is over ${MAX_EGRESS_PARENT} bytes): give the server a shorter --data` } : await boxNetworkOf(env, { ...(boxPaths ? { mapped: true } : {}), ...(options.faux && options.fauxPlatform ? { platform: options.fauxPlatform } : {}) });
|
|
747
|
+
// The proxy directories runs that are gone left in /tmp, or, in a container, on the data directory's mount
|
|
748
|
+
// (box-egress.ts): a live run's, any server's, stays.
|
|
564
749
|
if (!fauxBox && boxes.provider("docker"))
|
|
565
|
-
await sweepEgressDirs().catch(() => 0);
|
|
566
|
-
|
|
750
|
+
await sweepEgressDirs(undefined, undefined, egressParent).catch(() => 0);
|
|
751
|
+
// On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
|
|
752
|
+
// (box-egress-vm.ts): a box's network is the list once it is ready, and none, saying why, until then or when it can't start.
|
|
753
|
+
let egress;
|
|
754
|
+
const dockerNetwork = (offer) => {
|
|
755
|
+
if (!offer.available)
|
|
756
|
+
return offer;
|
|
757
|
+
if ("reason" in dockerPaths)
|
|
758
|
+
return { id: offer.id, available: false, state: "unavailable", reason: dockerPaths.reason };
|
|
759
|
+
if (boxNetwork.allow === "none")
|
|
760
|
+
return { ...offer, network: "none", network_reason: boxNetwork.reason };
|
|
761
|
+
const proxy = egress?.state();
|
|
762
|
+
return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist" };
|
|
763
|
+
};
|
|
567
764
|
// A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
|
|
568
765
|
// one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
|
|
569
766
|
let daytonaNoList;
|
|
@@ -581,6 +778,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
581
778
|
onChange: (state, ms) => {
|
|
582
779
|
boxOffers = offersNow();
|
|
583
780
|
imageLog(state, { ms });
|
|
781
|
+
options.onBoxImage?.(state);
|
|
584
782
|
// The box's state is in caps alone, not in the offers: recomposed now, or, while the start's probe of the offers
|
|
585
783
|
// has not ended, by that probe, which reads the box offers when it does.
|
|
586
784
|
if (offers)
|
|
@@ -588,6 +786,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
588
786
|
},
|
|
589
787
|
});
|
|
590
788
|
stops.push(async () => void (await image?.close()));
|
|
789
|
+
options.onBoxImage?.(image.state());
|
|
591
790
|
}
|
|
592
791
|
else
|
|
593
792
|
await clearImage(data);
|
|
@@ -601,7 +800,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
601
800
|
const vmClient = boxes.vmClient();
|
|
602
801
|
// What the provider says in an error is cut of every value this server holds (the VM token among them) before a run's
|
|
603
802
|
// process sees it.
|
|
604
|
-
const vmSecrets = () => [...
|
|
803
|
+
const vmSecrets = () => [...serverSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
|
|
605
804
|
const vmRelayHalf = vmBoxes && vmClient ? vmRelay(vmClient, vmSecrets) : undefined;
|
|
606
805
|
const vmLimits = (() => {
|
|
607
806
|
const limits = boxLimitsOf(env);
|
|
@@ -616,16 +815,107 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
616
815
|
if (offers)
|
|
617
816
|
recompose();
|
|
618
817
|
};
|
|
818
|
+
if (boxNetwork.allow !== "none" && boxNetwork.vm) {
|
|
819
|
+
const allow = boxNetwork.allow;
|
|
820
|
+
const egressLog = (state) => log?.(logLine("box_egress", { runtime: boxNetwork.vm, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }));
|
|
821
|
+
egress = await startEgressContainer({
|
|
822
|
+
env, data, allow, uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0,
|
|
823
|
+
warn: (message) => (log ? log(logLine("box_egress", { runtime: boxNetwork.vm, warning: message })) : void process.stderr.write(`agentrun-serve: ${message}\n`)),
|
|
824
|
+
onChange: (state) => {
|
|
825
|
+
egressLog(state);
|
|
826
|
+
boxOffers = offersNow();
|
|
827
|
+
if (offers)
|
|
828
|
+
recompose();
|
|
829
|
+
},
|
|
830
|
+
});
|
|
831
|
+
stops.push(() => egress.close());
|
|
832
|
+
egressLog(egress.state());
|
|
833
|
+
boxOffers = offersNow();
|
|
834
|
+
}
|
|
619
835
|
log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
|
|
620
836
|
if (image)
|
|
621
837
|
imageLog(image.state());
|
|
622
|
-
const
|
|
623
|
-
const
|
|
624
|
-
|
|
625
|
-
//
|
|
626
|
-
//
|
|
627
|
-
|
|
838
|
+
const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
|
|
839
|
+
const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
|
|
840
|
+
const sealKey = sealKeyOf(withSecrets(base, "own")[SEAL_KEY_ENV]);
|
|
841
|
+
// Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
|
|
842
|
+
// at the first request, when the server's own address is known (--faux's desktop view is a page on it). The real kind
|
|
843
|
+
// registry and each provider's create() are the computer package's (kinds.ts, providers.ts providerFor); under --faux,
|
|
844
|
+
// faux-computers.ts's three providers stand in. The folder mode is read at each call (folderModeOf), so turning Archil
|
|
845
|
+
// on or off needs no rebuild; a key named in the server's environment wins over a saved one.
|
|
846
|
+
const browserToolNames = (await import("@parcha/pi-browser")).BROWSER_TOOLS.map((tool) => tool.name);
|
|
847
|
+
const localTools = new Set(hostToolDefs({ maxExecS: 600, shell: "local" }).map((def) => def.name));
|
|
848
|
+
const kindTools = (kind) => kind === "none" ? [] : kind === "sandbox" ? hostToolDefs({ maxExecS: 600, shell: "computer" }).map((def) => def.name).filter((name) => !localTools.has(name))
|
|
849
|
+
: kind === "browser" ? browserToolNames : capabilityToolDefs(kind).map((def) => def.name);
|
|
850
|
+
let faux;
|
|
851
|
+
const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
|
|
852
|
+
let computerRoutes;
|
|
853
|
+
const computersOf = () => (computerRoutes ??= createComputerRoutes({
|
|
854
|
+
store, sealKey: checked.sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
|
|
855
|
+
...(options.faux
|
|
856
|
+
? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
|
|
857
|
+
: {
|
|
858
|
+
kinds: { SETTING_KINDS, PROVIDERS: COMPUTER_PROVIDERS, servingRefusals },
|
|
859
|
+
// The one place serve builds a provider (workspace/computer-providers.ts), the claim's makers' own.
|
|
860
|
+
factories: computerProviderFactories(computerProviderMakers(), (id) => storeLedger(store.computerLedger, id)),
|
|
861
|
+
}),
|
|
862
|
+
}));
|
|
863
|
+
/** Whether an agent's computer setting can be had here now, by the answers the runner's claim gives (resolve-computer.ts
|
|
864
|
+
* computerReadiness): over the registry the claim reads (workspace/computer-deps.ts claimKinds, asked with what the
|
|
865
|
+
* runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
|
|
866
|
+
* now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
|
|
867
|
+
* runner/main.ts runEnv hands them; else the saved one). What runnable.ts checks for an agent with
|
|
868
|
+
* a computer setting, in place of the box check. Whether Docker answers here is the boxes' own start-time probe
|
|
869
|
+
* (boxOffers, in memory: no new probe), with its reason, which says how to fix it. */
|
|
870
|
+
const dockerAnswers = (provider) => {
|
|
871
|
+
const box = boxAvailability(boxOffers).find((one) => one.id === provider);
|
|
872
|
+
return box?.available ? true : box?.reason ?? `${provider} is not a box this server has`;
|
|
873
|
+
};
|
|
874
|
+
const computerReady = async (setting) => computerReadiness(setting, (await folderModeOf(store)()) === "disk" ? 2 : 1, claimKinds({}), keyReader(store, checked.sealKey, withSecrets(process.env, "own")), dockerAnswers);
|
|
875
|
+
const archil = createArchilRoutes({ store, sealKey: checked.sealKey, env: process.env });
|
|
876
|
+
/** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
|
|
877
|
+
const runComputerOf = async (runId, view) => {
|
|
878
|
+
const run = await store.runs.get(runId);
|
|
879
|
+
const body = run ? (await store.agents.revision(run.revisionId))?.body : undefined;
|
|
880
|
+
const setting = body?.computer ?? (body?.place ? computerOfPlace(body.place) : undefined);
|
|
881
|
+
if (!setting)
|
|
882
|
+
return {};
|
|
883
|
+
const error = view.error;
|
|
884
|
+
const field = runComputerField(setting, { id: runId, status: String(view.status), ...(error && typeof error.code === "string" ? { error: { code: error.code, message: String(error.message ?? "") } } : {}) });
|
|
885
|
+
return field ? { computer: field } : {};
|
|
886
|
+
};
|
|
887
|
+
// The agents accessor the routes call, over the one store (module A): the agents-store functions, with the run-row reads
|
|
888
|
+
// the server makes (store-reads) under `.store`. `.request` is a thin pass-through — the store runs its own transactions,
|
|
889
|
+
// so a call needs no outer serialization. The old Agents class and its per-agent home store are gone.
|
|
890
|
+
const ctx = BACKGROUND_CONTEXT;
|
|
891
|
+
const agents = {
|
|
892
|
+
get: (id) => getAgent(store, id),
|
|
893
|
+
list: (options = {}) => listAgents(store, options),
|
|
894
|
+
create: (body, check, fresh) => createAgent(store, body, { ...(check ? { check } : {}), ...(fresh ? { fresh } : {}) }),
|
|
895
|
+
commit: (entry, body, options = {}) => commitAgent(store, entry, body, options),
|
|
896
|
+
revisions: (id) => agentRevisions(store, id),
|
|
897
|
+
revision: (agentId, revisionId) => agentRevision(store, agentId, revisionId),
|
|
898
|
+
setCurrent: (entry, revisionId) => setCurrentRevision(store, entry, revisionId),
|
|
899
|
+
setArchived: (kind, id, archived) => (kind === "agent" ? setAgentArchived(store, id, archived) : archiveRun(store, id, archived)),
|
|
900
|
+
request: (fn) => Promise.resolve(fn()),
|
|
901
|
+
dir: data,
|
|
902
|
+
store: {
|
|
903
|
+
listRuns: (filter = {}) => listRunsOverStore(store, filter, ctx),
|
|
904
|
+
readRun: (id) => readRunOverStore(store, id, ctx),
|
|
905
|
+
runOfOrigin: (key) => runOfOriginOverStore(store, key),
|
|
906
|
+
readRevision: (id) => store.agents.revision(id),
|
|
907
|
+
},
|
|
908
|
+
close: () => store.close(),
|
|
909
|
+
};
|
|
910
|
+
({ secrets: secretStores, settings: triggerSettings } = await openServerSecretsOverStore(store, data, env, adapters, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`))));
|
|
911
|
+
secretStores.add("server", () => [token]);
|
|
912
|
+
// Each agent's saved sign-ins, over the one store (module A, sign-ins-store): the vendor's calls on the server's keys
|
|
913
|
+
// (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
|
|
914
|
+
// (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
|
|
915
|
+
const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
|
|
628
916
|
const webhooks = new Webhooks(data, env, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
|
|
917
|
+
// The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
|
|
918
|
+
secretStores.add("webhook", () => webhooks.signingSecrets());
|
|
629
919
|
stops.push(() => webhooks.close());
|
|
630
920
|
const uploads = new Uploads(join(data, UPLOADS_DIR));
|
|
631
921
|
// Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
|
|
@@ -636,24 +926,126 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
636
926
|
const documents = options.documents ?? process.env[DOCUMENTS_ENV];
|
|
637
927
|
if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
|
|
638
928
|
throw new Error(`the documents directory ${documents} is not a directory`);
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
929
|
+
// The CLI harnesses, each installed on first use into the data's harnesses directory (harness-install.ts): one install
|
|
930
|
+
// of each at a time, which every run on that harness, and the save of an agent on it, waits for or starts; once one is
|
|
931
|
+
// in, the offers are probed again, so capabilities no longer say it installs on first use. Each is its table entry's
|
|
932
|
+
// `installs` (a test's stand-in has none).
|
|
933
|
+
// Claude Code as an earlier build installed it, at the top of the harnesses directory itself (read-only): removed once,
|
|
934
|
+
// before the first install, which then goes in beside nothing. Any other layout is left as it is.
|
|
935
|
+
let flat;
|
|
936
|
+
const flatRemoved = () => (flat ??= removeFlatInstall(harnessesOf(data)).then((removed) => void (removed && log?.(logLine("harness_install_removed", { dir: harnessesOf(data), said: `removed the earlier Claude Code install at ${harnessesOf(data)}: it installs again under harnesses/claude-agent` }))), (error) => ((flat = undefined), Promise.reject(error))));
|
|
937
|
+
const installed = HARNESSES.flatMap((id) => {
|
|
938
|
+
const harness = harnessOf(base, id);
|
|
939
|
+
return harness?.installs && harness.pins ? [{ entry: harness.installs, pins: harness.pins }] : [];
|
|
940
|
+
});
|
|
941
|
+
const installs = Object.fromEntries(installed.map(({ entry, pins }) => {
|
|
942
|
+
const lock = options.harnessLocks?.[entry.id];
|
|
943
|
+
// npm past its SIGTERM's grace (it waits on a tarball once it writes): killed, and the line says so.
|
|
944
|
+
const onKilled = () => log?.(logLine("harness_install_killed", { harness: entry.id, said: `npm did not stop within ${NPM_STOP_GRACE_MS / 1000} s of SIGTERM; killed` }));
|
|
945
|
+
return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, async (entry, dir, pins, signal) => (await flatRemoved(), npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) })), (ms) => {
|
|
946
|
+
log?.(logLine("harness_installed", { harness: entry.id, ms, dir: installDirOf(data, entry.id) }));
|
|
947
|
+
void probe(`${entry.id}_installed`).catch(() => undefined);
|
|
948
|
+
})];
|
|
949
|
+
}));
|
|
950
|
+
// A capped start prices each OpenRouter Decisions model a workflow pins (runnable.ts) from OpenRouter's public catalog,
|
|
951
|
+
// read once for this server (and again after a read that failed), through the faux one under --faux.
|
|
952
|
+
let pricing;
|
|
953
|
+
const decisionPrice = async (model) => {
|
|
954
|
+
const making = (pricing ??= (async () => {
|
|
955
|
+
const [{ openrouterProvider }, faux] = await Promise.all([import("@parcha/agentrun-decisions"), fauxFetch(fauxEnvOf(options), FAUX_OPENROUTER_ENV)]);
|
|
956
|
+
return openrouterProvider(faux ? { fetch: faux } : {});
|
|
957
|
+
})());
|
|
958
|
+
// One that could not be made is made again next time: a rejection is never kept.
|
|
959
|
+
const provider = await making.catch((error) => { if (pricing === making)
|
|
960
|
+
pricing = undefined; throw error; });
|
|
961
|
+
return provider.priceOf(model);
|
|
962
|
+
};
|
|
963
|
+
// The run write half (runs-over-store): the server INSERTs a queued run and its launch (startRun), and writes command
|
|
964
|
+
// rows (message/stop/cancel/raise/approve/archive) a run's runner reads and applies. No per-run process, no HTTP door,
|
|
965
|
+
// no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
|
|
966
|
+
// needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
|
|
967
|
+
// reads launch.model alone).
|
|
968
|
+
const modelOf = (_entry, revision) => runModelRef(env, revision);
|
|
969
|
+
const startDeps = {
|
|
970
|
+
runBodyIssues,
|
|
971
|
+
pinnedOf,
|
|
972
|
+
inputIssuesOf,
|
|
973
|
+
explainRun,
|
|
974
|
+
// told and fallbackPlace are const arrows declared later in startHolding; wrap them so startDeps captures the binding
|
|
975
|
+
// (called at request time, after they are assigned) rather than reading them before their declaration.
|
|
976
|
+
told: (error) => told(error),
|
|
977
|
+
runnable,
|
|
978
|
+
readyFiles: (ids) => uploads.readyFiles(ids),
|
|
979
|
+
fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
|
|
980
|
+
workflowTitle,
|
|
981
|
+
serverSecrets,
|
|
982
|
+
toolSettings: () => settings.get(),
|
|
983
|
+
planeEnv: () => env,
|
|
984
|
+
approvers: options.accounts === true,
|
|
985
|
+
...(documents ? { documents: resolve(documents) } : {}),
|
|
986
|
+
...(boxAllow !== undefined ? { boxAllow } : {}),
|
|
987
|
+
modelOf,
|
|
988
|
+
// The run's learning start, decided at start as the old file-backed start decided it (learning-run.ts onStart/seedFor):
|
|
989
|
+
// the server's learning switch, the budget its # Learned section fits, the agent's seed read now from its learning folder
|
|
990
|
+
// (git), and the host's secrets as they are shown now to cut the notes a run is given. runs-over-store.learningStartFor
|
|
991
|
+
// pins the result (given/seed/section/seedNotes) in the launch for the runner; a seed that cannot be read starts the run
|
|
992
|
+
// with nothing learned (a fault never refuses it). INERT until the runner installs learning-1's learningEndOfRun as its
|
|
993
|
+
// endOfRun (cutover-learning-end 283008bb05, E2r3's one-line spec-builder hookup); land this in that same round.
|
|
994
|
+
learning,
|
|
995
|
+
learningBudget,
|
|
996
|
+
seedFor: async (agentId) => {
|
|
997
|
+
// The switch runs no git in this process (learning.ts seedOf: the folder's own script and file API, which checks git
|
|
998
|
+
// itself); a git or folder fault surfaces here as a seedOf error, so the run starts with nothing learned, never refused.
|
|
999
|
+
return seedOf(data, agentId).then((seed) => ({ seed }), (error) => {
|
|
1000
|
+
process.stderr.write(`agentrun-serve: the agent ${agentId}'s learning folder could not be read, so its run starts with nothing learned: ${error.message}\n`);
|
|
1001
|
+
return { failed: error.message };
|
|
1002
|
+
});
|
|
1003
|
+
},
|
|
1004
|
+
shown: () => secretsShown(serverSecrets()),
|
|
1005
|
+
};
|
|
1006
|
+
// A run's served view and its live moment, from the store (store-view): `origin` is where this request reaches the
|
|
1007
|
+
// console, the secrets are cut live, and the sign-ins give the handed-pointer cut. Trigger and background reads (no
|
|
1008
|
+
// request) use the server's public address, else its own.
|
|
1009
|
+
// The run's key read from this server's environment with the keys a person saved, as its Timeline reads it (keyEnv below).
|
|
1010
|
+
const viewDepsFor = (origin) => ({ origin, serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) });
|
|
1011
|
+
const ownOriginOf = () => options.publicUrl ?? url;
|
|
1012
|
+
// The run read routes (a run's files, its browser state, its workflow graph) over the one store (run-reads-over-store):
|
|
1013
|
+
// a run's files through the server's read-only Workspace of its folder (serverRunWorkspace, no runner claim), its view
|
|
1014
|
+
// and withheld verdict from store-view. The live browser viewer reads the runner's published handover from the store
|
|
1015
|
+
// (liveViewerLink, the one the runner's browser tool wrote under its claim), when this server has the seal key its token
|
|
1016
|
+
// is sealed under; with no seal key no live view is ever served, so the live branch is left off. The timeline route keeps
|
|
1017
|
+
// its own stub (store-reads journal + SSE) until E2c's timeline lands.
|
|
1018
|
+
const runReadsDeps = {
|
|
1019
|
+
runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey }),
|
|
1020
|
+
env,
|
|
1021
|
+
runView: (_store, runId) => viewOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1022
|
+
withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1023
|
+
cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
|
|
1024
|
+
context: ctx,
|
|
1025
|
+
...(sealKey ? { liveViewer: (runId) => liveViewerLink(store, sealKey, runId) } : {}),
|
|
1026
|
+
};
|
|
1027
|
+
// The run timeline reader over the store (run-reads-over-store runTimelines): one change-numbered RowLog per run, synced
|
|
1028
|
+
// from its journal (store-reads) on each read, its view (viewOverStore) for status/state/cost and whether it is final.
|
|
1029
|
+
// The route frames the SSE around its `page`, which long-polls the journal, byte-identical to the old live run's page.
|
|
1030
|
+
const timelines = runTimelines({
|
|
1031
|
+
context: ctx,
|
|
1032
|
+
// The run's rows as served (run-timeline-served.ts), by its one cut (run-cut.ts, read for each page: a secret rotated
|
|
1033
|
+
// or saved since is cut at once), the set its view's words, title and error are cut of: each secret this server never
|
|
1034
|
+
// shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
|
|
1035
|
+
// error's words. A run whose hand can't be read back here is withheld: none of its rows. A run's Timeline is read
|
|
1036
|
+
// from its journal, which keeps what the run said whole.
|
|
1037
|
+
timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => withSecrets(process.env, "all", storedKeys) }, forStore, runId, context),
|
|
1038
|
+
runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
|
|
1039
|
+
});
|
|
1040
|
+
const triggerDeps = {
|
|
1041
|
+
start: startDeps,
|
|
1042
|
+
getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
|
|
1043
|
+
needAgent,
|
|
1044
|
+
momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1045
|
+
runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
|
|
1046
|
+
};
|
|
1047
|
+
const targets = triggerTargets(store, triggerDeps);
|
|
644
1048
|
const expected = digest(`Bearer ${token}`);
|
|
645
|
-
if (options.beforeAbort)
|
|
646
|
-
runs.beforeAbort = options.beforeAbort;
|
|
647
|
-
if (options.beforeReopenLaunch)
|
|
648
|
-
runs.beforeReopenLaunch = options.beforeReopenLaunch;
|
|
649
|
-
if (options.beforeSubmit)
|
|
650
|
-
runs.beforeSubmit = options.beforeSubmit;
|
|
651
|
-
if (options.beforeMetaSave)
|
|
652
|
-
runs.beforeMetaSave = options.beforeMetaSave;
|
|
653
|
-
if (options.onRunLoad)
|
|
654
|
-
runs.onRunLoad = options.onRunLoad;
|
|
655
|
-
if (options.messageOrigin)
|
|
656
|
-
runs.messageOrigin = options.messageOrigin;
|
|
657
1049
|
const keptFile = join(data, IDEMPOTENCY_FILE);
|
|
658
1050
|
const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
|
|
659
1051
|
const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
|
|
@@ -667,7 +1059,31 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
667
1059
|
await rename(`${keptFile}.partial`, keptFile);
|
|
668
1060
|
}));
|
|
669
1061
|
const host = options.host ?? "127.0.0.1";
|
|
670
|
-
|
|
1062
|
+
// Open setup (no code) only where no one else reaches the port: a loopback listener. Bound to any other address
|
|
1063
|
+
// (0.0.0.0 in the image, a LAN address), the first visit takes the printed code even with no public address.
|
|
1064
|
+
const openSetup = options.openSetup === true && isLoopback(host);
|
|
1065
|
+
const owner = options.accounts ? new Owner(data, openSetup, (line) => void process.stdout.write(`${line}\n`), options.signInAddresses) : undefined;
|
|
1066
|
+
// Who a sign-in comes from, for its limit: the socket's peer, or, from a trusted proxy only, the client it forwards for.
|
|
1067
|
+
const trusted = (() => {
|
|
1068
|
+
if (!options.trustedProxies?.length)
|
|
1069
|
+
return undefined;
|
|
1070
|
+
try {
|
|
1071
|
+
return proxyaddr.compile([...options.trustedProxies]);
|
|
1072
|
+
}
|
|
1073
|
+
catch (error) {
|
|
1074
|
+
throw new Error(`trustedProxies: ${error.message}`);
|
|
1075
|
+
}
|
|
1076
|
+
})();
|
|
1077
|
+
const clientOf = (req) => (trusted ? proxyaddr(req, trusted) : req.socket.remoteAddress) ?? "unknown";
|
|
1078
|
+
/** Whether `req` may be shown a secret this server mints (trigger-secrets-shown.ts): the caller that may write one. */
|
|
1079
|
+
const mayHoldSecrets = (req) => writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) });
|
|
1080
|
+
/** A trigger's view with its minted secret's metadata, never the secret (trigger-secrets-shown.ts). */
|
|
1081
|
+
const withSecretOf = (view) => withTriggerSecret(view, adapters, (adapterId, scope, field) => {
|
|
1082
|
+
const settings = triggerSettings.get(adapterId);
|
|
1083
|
+
return settings?.get(scope, field) !== undefined ? "set" : settings?.unopenedAt(scope, field) ? "unopened" : "unset";
|
|
1084
|
+
});
|
|
1085
|
+
// The owner's open live views (browser-live.ts): each closes once no session that let it in holds.
|
|
1086
|
+
const viewers = new OpenViewers();
|
|
671
1087
|
// A saved key is read by name from here, past the checks that refuse a start and before any run (a recovered one too)
|
|
672
1088
|
// is launched: each launch hands over what is saved then. One server in a process reads them: the last started.
|
|
673
1089
|
await probe("start");
|
|
@@ -683,112 +1099,64 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
683
1099
|
};
|
|
684
1100
|
// Decided once, by the probe the confinement walks by: capabilities.home.writes says what PUT and DELETE do.
|
|
685
1101
|
const homeWrites = caps.home.writes;
|
|
686
|
-
//
|
|
687
|
-
//
|
|
688
|
-
//
|
|
689
|
-
//
|
|
690
|
-
void runs
|
|
691
|
-
.recover()
|
|
692
|
-
.catch((error) => void process.stderr.write(`agentrun-serve: recovery: ${error.message}\n`))
|
|
693
|
-
.then(async () => {
|
|
694
|
-
const rows = (await agents.request(() => agents.store.listRuns())).filter((row) => !row.importedFrom);
|
|
695
|
-
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
696
|
-
// An end's notice from its row and its serve.json alone, as the run list reads an ended run (summaryOfRow): never
|
|
697
|
-
// its own store, whose read can fail, so a busy store loses no end. The same body a live end's notice has.
|
|
698
|
-
await webhooks.catchUp(rows, async (id) => {
|
|
699
|
-
const row = byId.get(id);
|
|
700
|
-
if (!row)
|
|
701
|
-
return null;
|
|
702
|
-
const meta = await readJson(join(agents.dir, "runs", id, RUN_META));
|
|
703
|
-
return { run_id: id, agent_id: row.agent, status: await runs.statusOfRow(row), title: isObject(meta) && typeof meta.title === "string" ? meta.title : "" };
|
|
704
|
-
});
|
|
705
|
-
})
|
|
706
|
-
.catch((error) => void process.stderr.write(`agentrun-serve: the webhook's catch-up: ${error.message}\n`));
|
|
1102
|
+
// No server-side run recovery: a runner (its own process) claims every run an earlier runner left and resumes it from the
|
|
1103
|
+
// journal under the claim epoch — the server starts no run process and adopts none.
|
|
1104
|
+
// TODO(switch): rebuild the webhook catch-up over the store's run rows (listRuns + the run view's status) so an end a
|
|
1105
|
+
// stopped server never delivered is queued at the next start; deferred (webhooks stay until route-1's triggers8 merges).
|
|
707
1106
|
// Schedules: each firing starts its run as POST /agents/{id}/runs does, capped, under the firing's key (triggers.ts).
|
|
708
1107
|
// Firings an earlier server left due are driven again now, beside the recovery above.
|
|
709
|
-
|
|
1108
|
+
// Connect GitHub: the server's one GitHub App, in the store's trigger_settings (adapter github, scope server), where the
|
|
1109
|
+
// runner reads it per claim (runner/github-app.ts).
|
|
1110
|
+
const github = new GitHubConnection(triggerSettings.get("github"));
|
|
1111
|
+
const githubConnect = new GitHubConnect(github, { ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}), api: options.githubApi ?? GITHUB_API, say: (fields) => log?.(logLine("github", fields)) });
|
|
1112
|
+
/** The connection a GitHub template or the console reads: the App's id, slug and installations, never a secret. */
|
|
1113
|
+
const githubConnection = () => github.view();
|
|
1114
|
+
/** What applying a template reads of the server (templates.ts TemplatesDeps). */
|
|
1115
|
+
const templateDeps = { githubConnection };
|
|
1116
|
+
// A github_app MCP server's tools are listed with an installation token of the App, narrowed to one repository it covers
|
|
1117
|
+
// with metadata read (tokenForListing); a run's own is minted in the runner (runner/github-app.ts). Every token minted
|
|
1118
|
+
// is a server secret while it may be in use.
|
|
1119
|
+
mcpServers.appToken = (signal) => githubConnect.tokenForListing(signal);
|
|
1120
|
+
secretStores.add("github-tokens", () => githubConnect.liveTokens());
|
|
1121
|
+
const triggers = new Triggers({
|
|
1122
|
+
// The server's own store (the one it opened) holds the triggers a person writes and reads; a test may inject another
|
|
1123
|
+
// (startServe's `store`).
|
|
1124
|
+
store: options.store ?? store,
|
|
710
1125
|
clock: options.triggerClock,
|
|
1126
|
+
...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
|
|
1127
|
+
adapters,
|
|
1128
|
+
unavailable: (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : undefined),
|
|
711
1129
|
say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
if (run.kind === "workflow")
|
|
718
|
-
return [{ field: "target.run_id", reason: "not_allowed", message: "A workflow run takes no messages here." }];
|
|
719
|
-
return run.meta.max_cost_usd === undefined ? [{ field: "target.run_id", reason: "not_allowed", message: NO_CAP }] : [];
|
|
720
|
-
}
|
|
721
|
-
const entry = await agents.get(target.agent_id);
|
|
722
|
-
if (!entry)
|
|
723
|
-
return [{ field: "target.agent_id", reason: "not_found", message: `no agent ${target.agent_id}` }];
|
|
724
|
-
if (!entry.revision)
|
|
725
|
-
return [{ field: "target.agent_id", reason: "invalid", message: `the agent ${target.agent_id} has no current revision` }];
|
|
726
|
-
if (entry.revision.kind === "workflow")
|
|
727
|
-
return [{ field: "target.agent_id", reason: "not_allowed", message: "A trigger's runs are capped, and a workflow run's spend is not capped here: name an agent that is not a workflow." }];
|
|
728
|
-
const uncapped = target.max_cost_usd === undefined && entry.revision.body.maxCostUsd === undefined ? [{ field: "target.max_cost_usd", reason: "missing", message: `Every run a trigger starts is capped: give the target a max_cost_usd or set the agent's (the agent ${target.agent_id} has none).` }] : [];
|
|
729
|
-
return [...uncapped, ...(await inputIssuesOf(entry.revision, target.input)).map((issue) => ({ ...issue, field: `target.${issue.field}` }))];
|
|
730
|
-
},
|
|
731
|
-
async start(target, input, trigger) {
|
|
732
|
-
const entry = await needAgent(target.agent_id);
|
|
733
|
-
// The target's cap, else the agent's default as it stands now: a run a trigger starts is never uncapped.
|
|
734
|
-
const run = await startRunOf(entry, { input, ...(target.max_cost_usd !== undefined ? { max_cost_usd: target.max_cost_usd } : {}), ...(target.effort ? { effort: target.effort } : {}) }, { trigger, origin: { key: trigger.firing_key }, capped: true });
|
|
735
|
-
return { run_id: run.id };
|
|
736
|
-
},
|
|
737
|
-
async message(target, input, key) {
|
|
738
|
-
const run = await needRun(target.run_id);
|
|
739
|
-
if (run.kind === "workflow")
|
|
740
|
-
throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here.");
|
|
741
|
-
// A store held past its retries is a busy store: the firing stays due and is tried again, never failed.
|
|
742
|
-
if (await runs.tookMessage(run, key).catch((error) => { throw storeBusy(error) ? homeBusy() : error; }))
|
|
743
|
-
return;
|
|
744
|
-
// Never an uncapped turn, nor an answer to a person's question, an approval or a budget pause: a run that waits on
|
|
745
|
-
// its person is told nothing by a trigger.
|
|
746
|
-
if (run.meta.max_cost_usd === undefined)
|
|
747
|
-
throw new ApiError("not_continuable", NO_CAP);
|
|
748
|
-
const { status, state } = statusOf(run);
|
|
749
|
-
if (status === "input_required" && state === "waiting")
|
|
750
|
-
return { skipped: WAITS_ON_A_PERSON };
|
|
751
|
-
try {
|
|
752
|
-
await runs.message(run, String(input.content), key, { answers: false });
|
|
753
|
-
}
|
|
754
|
-
catch (error) {
|
|
755
|
-
if (error instanceof ApiError && error.message === WAITS_ON_A_PERSON)
|
|
756
|
-
return { skipped: WAITS_ON_A_PERSON };
|
|
757
|
-
throw error;
|
|
758
|
-
}
|
|
759
|
-
},
|
|
760
|
-
secrets: { mint: (id) => triggerSecrets.mint(id), remove: (id) => triggerSecrets.remove(id) },
|
|
1130
|
+
// The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
|
|
1131
|
+
// (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
|
|
1132
|
+
// queue a firing takes — how many of a trigger's messages wait for a busy run — is route-1's store.triggers.
|
|
1133
|
+
...targets,
|
|
1134
|
+
settings: (adapterId) => triggerSettings.get(adapterId),
|
|
761
1135
|
notify: (failed, key) => webhooks.emitTrigger(failed, key),
|
|
762
|
-
async runOf(key) {
|
|
763
|
-
const started = await agents.request(() => agents.store.runOfOrigin(key));
|
|
764
|
-
if (!started)
|
|
765
|
-
return null;
|
|
766
|
-
// Never set up as runs.ts load reads it (notSetUp: the store has it running and its serve.json holds no input), which
|
|
767
|
-
// this start's recovery fails as server_lost_at_setup; or failed so already.
|
|
768
|
-
const run = await runs.get(started.runId);
|
|
769
|
-
return { run_id: started.runId, setup_lost: run?.notSetUp === true || run?.error?.details?.reason === SETUP_LOST };
|
|
770
|
-
},
|
|
771
|
-
async statusOf(runId) {
|
|
772
|
-
const row = await agents.request(() => agents.store.readRun(runId));
|
|
773
|
-
return row ? runs.statusOfRow(row) : null;
|
|
774
|
-
},
|
|
775
1136
|
});
|
|
1137
|
+
// A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
|
|
1138
|
+
stops.push(() => githubConnect.close());
|
|
776
1139
|
stops.push(async () => triggers.close());
|
|
777
|
-
|
|
1140
|
+
// The firing loop runs against the server's own opened store: due firings start their runs through the run write half,
|
|
1141
|
+
// times missed while it was down are recorded, and the timer is armed for the next. (A test may inject its own store.)
|
|
1142
|
+
void triggers.start().catch((error) => void process.stderr.write(`agentrun-serve: the triggers' start: ${error.message}\n`));
|
|
1143
|
+
// The App's installations repaired from GitHub's own, once, as the server starts: events missed while it was down. It
|
|
1144
|
+
// never rejects, and close (or a start that fails) aborts it and waits for it before it closes.
|
|
1145
|
+
void githubConnect.reconcile((detail) => triggers.turnOff("github", detail), { force: true });
|
|
778
1146
|
// Setup's import of this machine's sessions: offered by a server on this machine only (no public address, listening
|
|
779
1147
|
// on loopback), counted once (a listing, no transcript kept), run once, each on a worker thread (import-worker.ts) so
|
|
780
1148
|
// a busy store's wait and the sessions' parsing never hold up a request.
|
|
781
|
-
const offersImport =
|
|
1149
|
+
const offersImport = openSetup && options.publicUrl === undefined;
|
|
782
1150
|
let closing = false;
|
|
783
1151
|
const workers = new Map();
|
|
784
1152
|
// Once the server closes, no worker starts: a setup still being answered then leaves its yes for the next start.
|
|
785
1153
|
const onWorker = (task) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
|
|
786
1154
|
const worker = new Worker(new URL("./import-worker.js", import.meta.url), {
|
|
787
|
-
// The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none),
|
|
788
|
-
//
|
|
789
|
-
//
|
|
790
|
-
//
|
|
791
|
-
workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = secret(name); return value === undefined ? [] : [[name, value]]; }))
|
|
1155
|
+
// The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), in the
|
|
1156
|
+
// worker's memory alone: what the import cuts out of everything it writes. The keys saved on the Tool keys page are
|
|
1157
|
+
// not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
|
|
1158
|
+
// secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
|
|
1159
|
+
workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = secret(name); return value === undefined ? [] : [[name, value]]; })) },
|
|
792
1160
|
// Started from a string (its launcher runs node --input-type=module -e), the server's flags are given again
|
|
793
1161
|
// without that string and its type: a worker started from a file with them is refused. Otherwise the worker
|
|
794
1162
|
// inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
|
|
@@ -797,7 +1165,14 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
797
1165
|
});
|
|
798
1166
|
workers.set(worker, { task, exit: once(worker, "exit").catch(() => undefined) });
|
|
799
1167
|
let answer;
|
|
800
|
-
worker
|
|
1168
|
+
// The import worker opens no store of its own: a message carrying `req` is one of its calls to this server's open
|
|
1169
|
+
// store, answered against it and posted back; anything else is its one final answer.
|
|
1170
|
+
worker.on("message", (message) => {
|
|
1171
|
+
if (typeof message === "object" && message !== null && "req" in message)
|
|
1172
|
+
void answerStoreCall(store, ctx, message).then((reply) => worker.postMessage(reply));
|
|
1173
|
+
else
|
|
1174
|
+
answer = message;
|
|
1175
|
+
});
|
|
801
1176
|
worker.once("error", failed);
|
|
802
1177
|
worker.once("exit", (code) => {
|
|
803
1178
|
workers.delete(worker);
|
|
@@ -873,33 +1248,11 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
873
1248
|
throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
|
|
874
1249
|
return Buffer.concat(chunks);
|
|
875
1250
|
}
|
|
876
|
-
/** POST /v2/hooks/{trigger_id}: a webhook trigger's firing, signed by the Standard Webhooks spec under its secret
|
|
877
|
-
* (trigger-secrets.ts), checked on the raw body before anything else. An unknown trigger, one that is off or not a
|
|
878
|
-
* webhook's, and a check that fails are one answer, so no trigger id can be found by asking; an unknown one is
|
|
879
|
-
* checked against a secret of no trigger's, so it takes the same time. A webhook-id already fired answers its firing. */
|
|
880
|
-
async function hook(req, res, path) {
|
|
881
|
-
const refuse = (reason) => {
|
|
882
|
-
authFailed(`/v2${path}`, reason);
|
|
883
|
-
return new ApiError("unauthenticated", "this route needs a request signed by the webhook trigger's secret");
|
|
884
|
-
};
|
|
885
|
-
// Headers that can never pass are refused before a byte of the body is read; they say nothing of the trigger.
|
|
886
|
-
const early = hookHeadersRefusal(req.headers, Date.now());
|
|
887
|
-
if (early)
|
|
888
|
-
throw refuse(early);
|
|
889
|
-
const body = await bytesOf(req, HOOK_MAX_BODY);
|
|
890
|
-
let id = "";
|
|
891
|
-
try {
|
|
892
|
-
id = decodeURIComponent(/^\/hooks\/([^/]+)$/.exec(path)[1]);
|
|
893
|
-
}
|
|
894
|
-
catch { }
|
|
895
|
-
const secret = ID.test(id) && triggers.hookable(id) ? triggerSecrets.value(id) : undefined;
|
|
896
|
-
const refusal = hookRefusal(secret ?? NO_TRIGGER_SECRET, req.headers, body, Date.now());
|
|
897
|
-
if (!secret || refusal)
|
|
898
|
-
throw refuse(secret ? refusal : "no_webhook_trigger");
|
|
899
|
-
const { created, firing } = triggers.receive(id, String(req.headers["webhook-id"]), body.toString("utf8"));
|
|
900
|
-
return send(res, created ? 202 : 200, firing, created ? {} : { "idempotent-replayed": "true" });
|
|
901
|
-
}
|
|
902
1251
|
async function bodyOf(req) {
|
|
1252
|
+
// Read once: the secret-write check reads a registered operation's body before its route does (secret-writes.ts).
|
|
1253
|
+
const read = bodies.get(req);
|
|
1254
|
+
if (read !== undefined)
|
|
1255
|
+
return read;
|
|
903
1256
|
const type = String(req.headers["content-type"] ?? "");
|
|
904
1257
|
if (!type.startsWith("application/json"))
|
|
905
1258
|
throw new ApiError("unsupported_media_type", "the body must be application/json");
|
|
@@ -913,23 +1266,62 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
913
1266
|
}
|
|
914
1267
|
if (!isObject(value))
|
|
915
1268
|
throw new ApiError("bad_request", "the body is not a JSON object");
|
|
1269
|
+
bodies.set(req, value);
|
|
916
1270
|
return value;
|
|
917
1271
|
}
|
|
1272
|
+
/** The tools a learned draft of agent `id` may name, as a run's merge reads them (learning-run.ts draftTools): its
|
|
1273
|
+
* current revision's, those the gate allows under the server's settings and the agent's own. */
|
|
1274
|
+
async function learnedDraftToolsOf(id) {
|
|
1275
|
+
const revision = (await needAgent(id)).revision;
|
|
1276
|
+
if (revision?.kind !== "agentic")
|
|
1277
|
+
return { tools: [], gated: {} };
|
|
1278
|
+
const [{ learnedDraftTools }, { permissionOf }] = await Promise.all([import("./tools.js"), import("./tool-gate.js")]);
|
|
1279
|
+
const server = settings.get();
|
|
1280
|
+
// The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
|
|
1281
|
+
const body = revision.body;
|
|
1282
|
+
return learnedDraftTools(body.tools ?? [], (name) => permissionOf(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask"));
|
|
1283
|
+
}
|
|
918
1284
|
async function needAgent(id) {
|
|
919
1285
|
const entry = ID.test(id) ? await agents.get(id) : null;
|
|
920
1286
|
if (!entry)
|
|
921
1287
|
throw new ApiError("not_found", `no agent ${id}`);
|
|
922
1288
|
return entry;
|
|
923
1289
|
}
|
|
1290
|
+
/** An agent view's extra fields (agents-store agentView): its saved sign-ins, its learning count, and its run counts.
|
|
1291
|
+
* The run counts read the store's runs (store-reads/runs.ts listRuns): `count` is every run the agent has, `live` those
|
|
1292
|
+
* still running (runReadState 'running': queued, running or parked), the same numbers the file-backed view showed. */
|
|
1293
|
+
const agentExtra = async (entry) => {
|
|
1294
|
+
const learning = await learningOfAgent(entry);
|
|
1295
|
+
const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
|
|
1296
|
+
return { signIns: await signIns.view(entry.agent.id), ...(learning ? { learning } : {}), runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length } };
|
|
1297
|
+
};
|
|
1298
|
+
// A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
|
|
1299
|
+
// routes read from the store + the run view now, not a live Run.
|
|
924
1300
|
async function needRun(id) {
|
|
925
|
-
const run = ID.test(id) ? await
|
|
1301
|
+
const run = ID.test(id) ? await momentOverStore(store, id, viewDepsFor(ownOriginOf())) : undefined;
|
|
926
1302
|
if (!run)
|
|
927
1303
|
throw new ApiError("not_found", `no run ${id}`);
|
|
928
1304
|
return run;
|
|
929
1305
|
}
|
|
1306
|
+
/** A run's v2 status and state now (the run view), for the answer an act reports once it has written its command row. */
|
|
1307
|
+
const runStatusState = async (runId) => {
|
|
1308
|
+
const v = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
|
|
1309
|
+
return { status: v?.status ?? "queued", state: v?.state ?? "idle" };
|
|
1310
|
+
};
|
|
1311
|
+
/** The run read routes (timeline, files, graph, browser, live viewer) over the store are E2c's run-reads-over-store.ts
|
|
1312
|
+
* (watchRun + run-workspace + store-view), not committed yet. TODO(E2c): replace each call with its function on that sha. */
|
|
1313
|
+
const runReadsTodo = () => { throw new ApiError("unsupported_here", "run reads over the store (timeline, files, graph, browser) are being wired (run-reads-over-store); not available on this build yet"); };
|
|
930
1314
|
const mismatch = () => new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
|
|
931
1315
|
/** Replays the first answer to a create with the same key and body; another body is a mismatch. `work` gets the key's
|
|
932
1316
|
* origin (its slot and the body, hashed) for a create the agent store records with the run it starts. */
|
|
1317
|
+
/** A kept answer, replayed to `req`: its console page (a run's or an agent's console_url) at the address this request
|
|
1318
|
+
* reached (linkOrigin), not the first request's. */
|
|
1319
|
+
const pageFor = (req, body) => {
|
|
1320
|
+
if (!isObject(body) || typeof body.console_url !== "string")
|
|
1321
|
+
return body;
|
|
1322
|
+
const at = body.console_url.indexOf("/#/");
|
|
1323
|
+
return at < 0 ? body : { ...body, console_url: `${linkOrigin(req)}${body.console_url.slice(at)}` };
|
|
1324
|
+
};
|
|
933
1325
|
async function idempotent(req, path, body, work) {
|
|
934
1326
|
const key = req.headers["idempotency-key"];
|
|
935
1327
|
if (key === undefined)
|
|
@@ -948,7 +1340,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
948
1340
|
throw mismatch();
|
|
949
1341
|
if (!known.answer)
|
|
950
1342
|
throw new ApiError("idempotency_in_progress", "the first request with this Idempotency-Key is still in flight", { retry_after_ms: 500 });
|
|
951
|
-
return { ...known.answer, headers: { ...known.answer.headers, "idempotent-replayed": "true" } };
|
|
1343
|
+
return { ...known.answer, body: pageFor(req, known.answer.body), headers: { ...known.answer.headers, "idempotent-replayed": "true" } };
|
|
952
1344
|
}
|
|
953
1345
|
idempotency.set(slot, { fingerprint, at: now });
|
|
954
1346
|
let answer;
|
|
@@ -968,60 +1360,242 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
968
1360
|
}
|
|
969
1361
|
// ---- runs -----------------------------------------------------------------------------------------------------------
|
|
970
1362
|
/** A workflow revision's shape as runnable.ts checks it: its workflow, tools, harness, place and tool settings. */
|
|
971
|
-
const workflowShape = ({ workflow, tools, harness, place, toolSettings }) => ({ kind: "workflow", workflow, tools: tools ?? [], ...(harness ? { harness } : {}), ...(place ? { place } : {}), ...(toolSettings ? { toolSettings } : {}) });
|
|
1363
|
+
const workflowShape = ({ workflow, tools, harness, place, toolSettings, approvals }) => ({ kind: "workflow", workflow, tools: tools ?? [], ...(harness ? { harness } : {}), ...(place ? { place } : {}), ...(toolSettings ? { toolSettings } : {}), ...(approvals === "never" ? { approvals } : {}) });
|
|
972
1364
|
const shapeOf = (revision) => (revision.kind === "agentic" ? { kind: "agentic", ...revision.body } : workflowShape(revision.body));
|
|
973
1365
|
/** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
|
|
974
1366
|
* starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
|
|
975
1367
|
* does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
|
|
976
1368
|
async function runnable(revision, place, { capped = false } = {}) {
|
|
977
|
-
const shape = { ...shapeOf(revision), place };
|
|
978
|
-
const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, offers });
|
|
1369
|
+
const shape = { ...shapeOf(revision), place, ...(revision.body.place ? {} : { unnamed: true }) };
|
|
1370
|
+
const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, offers, mcp: mcpTools, decisionPrice });
|
|
979
1371
|
if (!blockers.length)
|
|
980
1372
|
return;
|
|
981
1373
|
const message = blockers.map((b) => b.message).join(" ");
|
|
1374
|
+
// Each blocker as a 422 names its issue: its field, reason and message, and the fix when it has one.
|
|
1375
|
+
const fields = blockers.map(issueOf);
|
|
982
1376
|
const unbound = blockers.flatMap((b) => (b.tool ? [b.tool] : []));
|
|
1377
|
+
// A known MCP meta tool is no server or tool that is missing: it has a key of its own, with why it is not granted.
|
|
1378
|
+
const notGrantable = blockers.flatMap((b) => (b.notGrantable ? [b.notGrantable] : []));
|
|
983
1379
|
const missing = Object.fromEntries(blockers.flatMap((b) => (b.missing ? [[b.missing.tool, b.missing.vars]] : [])));
|
|
984
1380
|
const harness = blockers.find((b) => b.harness)?.harness;
|
|
985
1381
|
const box = blockers.find((b) => b.box)?.box;
|
|
986
|
-
const named = { ...(harness ? { harness } : {}), ...(box ? { box } : {}) };
|
|
1382
|
+
const named = { ...(harness ? { harness } : {}), ...(box ? { box } : {}), ...(notGrantable.length ? { not_grantable: notGrantable } : {}) };
|
|
987
1383
|
if (revision.kind === "agentic")
|
|
988
|
-
throw new ApiError("agent_not_runnable", message, { details: { unbound, missing, ...named } });
|
|
1384
|
+
throw new ApiError("agent_not_runnable", message, { fields, details: { unbound, missing, ...named } });
|
|
989
1385
|
const tier = blockers.find((b) => b.tier)?.tier;
|
|
990
1386
|
const decisions = Object.fromEntries(blockers.flatMap((b) => (b.decision ? [[b.decision.provider, { reason: b.reason, needs: b.decision.needs }]] : [])));
|
|
991
1387
|
const denied = blockers.flatMap((b) => (b.denied ? [b.denied] : []));
|
|
992
1388
|
const asks = blockers.flatMap((b) => (b.asks ? [b.asks] : []));
|
|
993
|
-
throw new ApiError("agent_not_runnable", message, { details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...(denied.length ? { denied } : {}), ...(asks.length ? { asks } : {}), ...named } });
|
|
1389
|
+
throw new ApiError("agent_not_runnable", message, { fields, details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...(denied.length ? { denied } : {}), ...(asks.length ? { asks } : {}), ...named } });
|
|
994
1390
|
}
|
|
995
|
-
/**
|
|
1391
|
+
/** Where a revision of `kind` naming `tools` and no place runs here: the place a new agent would be saved with. */
|
|
1392
|
+
const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, (tool) => toolOf(tool)?.runnerOnly === true);
|
|
1393
|
+
/** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. A
|
|
1394
|
+
* revision that names no place is checked where it would run (fallbackPlace). */
|
|
996
1395
|
async function saveable(revision) {
|
|
997
|
-
|
|
998
|
-
|
|
1396
|
+
// The store's NewRevision keeps the revision's fields under `body` (AgenticBody|WorkflowBody); build the flat shape the
|
|
1397
|
+
// host checks (runnable.ts RevisionShape) from it, as shapeOf does for a run's Revision.
|
|
1398
|
+
const body = revision.body;
|
|
1399
|
+
// An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
|
|
1400
|
+
const install = revision.kind === "agentic" ? installs[harnessOfBody(body)] : undefined;
|
|
1401
|
+
if (install) {
|
|
1402
|
+
void install.ensure().catch((error) => log?.(logLine("harness_install_failed", { harness: install.entry.id, message: error.message })));
|
|
1403
|
+
}
|
|
1404
|
+
const named = (revision.kind === "agentic" ? { kind: "agentic", ...body } : workflowShape(body));
|
|
1405
|
+
const shape = named.place ? named : { ...named, place: fallbackPlace(named.kind, named.tools ?? []), unnamed: true };
|
|
1406
|
+
const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, offers, mcp: mcpTools });
|
|
999
1407
|
// An agent's default cap caps each run started without one of its own, and a web tool resolves by the cap: what a cap
|
|
1000
1408
|
// alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
|
|
1001
1409
|
// from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
|
|
1002
|
-
if (
|
|
1410
|
+
if ((body.maxCostUsd ?? 0) > 0) {
|
|
1003
1411
|
const key = (b) => `${b.field}\n${b.message}`;
|
|
1004
|
-
const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, offers })).map(key));
|
|
1005
|
-
const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, offers });
|
|
1006
|
-
|
|
1412
|
+
const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, offers, mcp: mcpTools })).map(key));
|
|
1413
|
+
const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, offers, mcp: mcpTools, decisionPrice });
|
|
1414
|
+
// A model with no price (`unpriced`) is a setting this host fixes (AGENT_MODEL_PRICE): a warning, as it is; the
|
|
1415
|
+
// agent saves and updates, and only a run under the cap is refused (409). A tool's pick a cap rules out refuses it.
|
|
1416
|
+
const added = capped.filter((b) => !plain.has(key(b)));
|
|
1417
|
+
blockers.push(...added.filter((b) => b.unpriced));
|
|
1418
|
+
blockers.push(...added.filter((b) => !b.unpriced).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
|
|
1007
1419
|
}
|
|
1008
1420
|
const never = blockers.filter((b) => !b.host);
|
|
1009
1421
|
if (never.length)
|
|
1010
1422
|
throw invalid(never.map(issueOf));
|
|
1011
1423
|
return blockers.map(issueOf);
|
|
1012
1424
|
}
|
|
1425
|
+
/** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
|
|
1426
|
+
* that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
|
|
1427
|
+
* tool the box refuses (browser) keeps the runner. */
|
|
1428
|
+
async function createAgentOf(body) {
|
|
1429
|
+
let warnings = [];
|
|
1430
|
+
const definition = checkDefinitionBody(body);
|
|
1431
|
+
const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
|
|
1432
|
+
const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
|
|
1433
|
+
const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
|
|
1434
|
+
return { entry, warnings };
|
|
1435
|
+
}
|
|
1436
|
+
/** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
|
|
1437
|
+
* servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
|
|
1438
|
+
* agent made as POST /agents makes one, its MCP tools at the owner's own settings save those granted, set to allow (a
|
|
1439
|
+
* deny the owner set on this server stays, with a warning), its body held to POST /agents' limit (413), on the first harness of its list this server runs and the model packageModel
|
|
1440
|
+
* picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
|
|
1441
|
+
* before it are deleted and the agent is archived (an agent store keeps every agent), and the refusal is the answer, a 422's fields under `triggers.<i>`; a
|
|
1442
|
+
* github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
|
|
1443
|
+
* trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one. */
|
|
1444
|
+
async function applyTemplate(pkg, body) {
|
|
1445
|
+
const { parameters, grants, model: override, approvals } = applyBodyOf(pkg, body);
|
|
1446
|
+
const missing = pkg.secrets.filter((name) => !secret(name, storedKeys));
|
|
1447
|
+
const saved = pkg.mcp.filter((need) => mcpMeta.has(need.server));
|
|
1448
|
+
const unsaved = pkg.mcp.filter((need) => !saved.includes(need));
|
|
1449
|
+
const needed = unsaved.filter((need) => need.required);
|
|
1450
|
+
// A webhook trigger's secret is kept sealed, never in the clear: with no seal key, its create would be refused after
|
|
1451
|
+
// the agent is made, so the apply is refused first, naming each one.
|
|
1452
|
+
const unsealed = sealKeyOf(env[SEAL_KEY_ENV]) ? [] : pkg.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [i] : []));
|
|
1453
|
+
if (missing.length || needed.length || unsealed.length) {
|
|
1454
|
+
const fix = "Add it in Settings → Model keys or Settings → Tool keys, or set it where AgentRun starts, then apply the template again.";
|
|
1455
|
+
const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
|
|
1456
|
+
const sealing = `Start the server with its launcher, agentrun-serve, which makes and keeps a seal key, or set ${SEAL_KEY_ENV} (32 random bytes in base64) where AgentRun starts, then apply the template again.`;
|
|
1457
|
+
throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`), ...(unsealed.length ? ["a seal key for its webhook trigger's secret"] : [])].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server.`, fix: server })), ...unsealed.map((i) => ({ field: `triggers.${i}`, reason: NOT_SET_UP, message: `This server has no seal key (${SEAL_KEY_ENV}), so it cannot keep the webhook trigger's secret.`, fix: sealing }))] });
|
|
1458
|
+
}
|
|
1459
|
+
// An MCP server the package can do without is skipped, and said: its tools are not granted.
|
|
1460
|
+
const skipped = unsaved.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server, so the agent was made without its tools (${need.tools.join(", ")}). Save it in Settings → MCP servers and apply again to grant them.` }));
|
|
1461
|
+
const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
|
|
1462
|
+
const picked = override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
|
|
1463
|
+
const model = picked.model;
|
|
1464
|
+
// Which model the agent got, where it is not the package's: a note, never a lack. The agent runs; only the package's
|
|
1465
|
+
// choice was not an option here (not_set_up_here would read as a run refused until the host has something).
|
|
1466
|
+
const modelWarnings = "warning" in picked && picked.warning ? [{ field: "model", reason: "not_an_option", message: picked.warning }] : [];
|
|
1467
|
+
const defaultTools = "place" in newAgentPlace(boxOffers) ? NEW_AGENT_TOOLS : [];
|
|
1468
|
+
// A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
|
|
1469
|
+
const server = settings.get();
|
|
1470
|
+
const denied = grants.filter((tool) => { const set = permissionFrom(tool, server); return set.from === "server" && set.permission === "deny"; });
|
|
1471
|
+
const kept = denied.map((tool) => ({ field: `grants.${tool}`, reason: "not_allowed", message: `${tool} is denied on this server (Settings → Tools), so the agent was not allowed it: its runs are refused it until the owner changes that setting.` }));
|
|
1472
|
+
// The tools this server's own settings pin (or hold refused for a pin that does not read): a package's pin the agent
|
|
1473
|
+
// store can't keep yet is covered there, so its grant stands; any other such tool is made deny (compiled).
|
|
1474
|
+
// The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
|
|
1475
|
+
// never), else ask. Deny and pins hold either way.
|
|
1476
|
+
const chosenApprovals = approvals ?? pkg.approvals;
|
|
1477
|
+
const serverPinned = new Set(Object.entries(settings.get()).filter(([, one]) => one?.pin || one?.brokenPin).map(([name]) => name));
|
|
1478
|
+
const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), serverPinned, ...(chosenApprovals ? { approvals: chosenApprovals } : {}) }, templateDeps);
|
|
1479
|
+
// Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
|
|
1480
|
+
// from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
|
|
1481
|
+
const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
|
|
1482
|
+
if (refusedTriggers.length)
|
|
1483
|
+
throw invalid(refusedTriggers);
|
|
1484
|
+
// POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
|
|
1485
|
+
for (const one of [made.agent, ...made.triggers])
|
|
1486
|
+
if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
|
|
1487
|
+
throw new ApiError("payload_too_large", `the ${pkg.name} template, its parameters filled in, makes a body over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
|
|
1488
|
+
const { entry, warnings } = await createAgentOf(made.agent);
|
|
1489
|
+
const ids = [];
|
|
1490
|
+
// Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
|
|
1491
|
+
// /triggers hands back its own, so the owner can give it to the sender.
|
|
1492
|
+
const secrets = [];
|
|
1493
|
+
// A github trigger on a server GitHub is not connected to is skipped, never the apply: the agent stands, and the
|
|
1494
|
+
// answer says to connect GitHub and apply again (a warning under triggers.<i>).
|
|
1495
|
+
const unconnected = new Set();
|
|
1496
|
+
try {
|
|
1497
|
+
for (const [i, trigger] of made.triggers.entries()) {
|
|
1498
|
+
try {
|
|
1499
|
+
const { id: madeId, secret } = await triggers.create({ ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } });
|
|
1500
|
+
ids.push(madeId);
|
|
1501
|
+
if (secret)
|
|
1502
|
+
secrets.push({ trigger_id: madeId, secret });
|
|
1503
|
+
}
|
|
1504
|
+
catch (error) {
|
|
1505
|
+
if (error instanceof ApiError && error.code === "github_not_connected" && isObject(trigger.source) && trigger.source.kind === "github") {
|
|
1506
|
+
unconnected.add(i);
|
|
1507
|
+
continue;
|
|
1508
|
+
}
|
|
1509
|
+
if (error instanceof ApiError && error.code === "input_invalid" && error.extra.fields)
|
|
1510
|
+
throw told(new ApiError("input_invalid", error.message, { ...error.extra, fields: error.extra.fields.map((f) => ({ ...f, field: `triggers.${i}.${f.field}` })) }));
|
|
1511
|
+
throw error;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
catch (error) {
|
|
1516
|
+
for (const id of ids.reverse()) {
|
|
1517
|
+
try {
|
|
1518
|
+
await triggers.remove(id);
|
|
1519
|
+
}
|
|
1520
|
+
catch (undo) {
|
|
1521
|
+
log?.(logLine("template_undo_failed", { template: pkg.name, trigger: id, message: undo.message }));
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
// Archived through the trigger engine, as POST /agents/{id}/archive is: a trigger the undo could not remove is turned
|
|
1525
|
+
// off in that same store transaction with the reason agent_archived, never with none, and unarchive answers it.
|
|
1526
|
+
await triggers.agentArchived(entry.agent.id).catch((undo) => log?.(logLine("template_undo_failed", { template: pkg.name, agent: entry.agent.id, message: undo.message })));
|
|
1527
|
+
throw error;
|
|
1528
|
+
}
|
|
1529
|
+
// A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
|
|
1530
|
+
const unpinned = made.unpinned.map(({ tool, parameters: named }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: `${tool}'s arguments are fixed by ${named.map((one) => `the ${one} parameter`).join(" and ")}, which was not given, so the agent was made with ${tool} set to deny: it can't call it at all. Apply again with ${named.join(" and ")} set to let it.` }));
|
|
1531
|
+
// A pin this server's agent store does not keep yet (tool-plane.ts AGENT_LAYER_PINS): said, with the setting that holds
|
|
1532
|
+
// the send to its destination meanwhile, the server's.
|
|
1533
|
+
const unkept = made.unkept.map(({ tool, pin }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: serverPinned.has(tool) ? `${tool} is not pinned to ${pinWords(pin)} for this agent yet (this server's agent store keeps an agent's own pin from the store cutover on); this server's own pin of ${tool} holds its calls meanwhile.` : `${tool} is not pinned to ${pinWords(pin)} for this agent yet: this server's agent store keeps an agent's own pin from the store cutover on. Until then the agent was made with ${tool} set to deny, so nothing it reads can send it elsewhere. Pin it on this server, which holds every agent's calls of ${tool}, and apply again to let it.`, ...(serverPinned.has(tool) ? {} : { fix: `Add ${JSON.stringify({ [tool]: { pin } })} to this server's tool settings (Settings → Tools; PUT /v2/settings/tools replaces the whole map, so send it with the rest).` }) }));
|
|
1534
|
+
// A GitHub tool the package grants that Connect GitHub's App may not use (its manifest asks for less), where the github
|
|
1535
|
+
// MCP server runs on the App's tokens: said now, before a run's first call is refused (template-github-permissions.ts).
|
|
1536
|
+
const appShort = appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app");
|
|
1537
|
+
// A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
|
|
1538
|
+
const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
|
|
1539
|
+
// Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
|
|
1540
|
+
const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
|
|
1541
|
+
? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: GITHUB_TRIGGER_UNCONNECTED } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
|
|
1542
|
+
: []));
|
|
1543
|
+
// Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
|
|
1544
|
+
// (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
|
|
1545
|
+
const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
|
|
1546
|
+
const applied = { template: pkg.name, version: pkg.version, agent_id: entry.agent.id, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...unpinned, ...unkept, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
|
|
1547
|
+
return { applied, minted };
|
|
1548
|
+
}
|
|
1549
|
+
/** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
|
|
1550
|
+
* with the documented run bodies; a workflow run's its workflow's input schema, never the agentic example. Each value
|
|
1551
|
+
* suggested must pass this route's own checks of the body, the workflow's input check among them. */
|
|
1552
|
+
async function explainRun(issues, body, revision) {
|
|
1553
|
+
const dsl = revision?.kind === "workflow" ? await import("@parcha/agentrun-dsl") : undefined;
|
|
1554
|
+
const workflow = dsl && revision?.kind === "workflow" ? revision.body.workflow : undefined;
|
|
1555
|
+
const declared = workflow?.input?.schemaId === undefined ? undefined : workflow.schemas[workflow.input.schemaId];
|
|
1556
|
+
const input = !dsl ? DEFAULT_INPUT_SCHEMA : declared ? dsl.resolveSchemaForWorkflow(workflow, declared) : { type: "object" };
|
|
1557
|
+
const base = deref(openapi, { $ref: "#/components/schemas/RunCreate" }) ?? {};
|
|
1558
|
+
const schema = { ...base, properties: { ...base.properties, input } };
|
|
1559
|
+
const check = (sent) => {
|
|
1560
|
+
const value = isObject(sent) ? sent : {};
|
|
1561
|
+
const issues = runBodyIssues(value);
|
|
1562
|
+
if (!revision || !isObject(value.input))
|
|
1563
|
+
return issues;
|
|
1564
|
+
return [...issues, ...(dsl ? workflowInputIssues(dsl.validateWorkflow, revision, value.input) : inputIssues(value.input, DEFAULT_INPUT_SCHEMA))];
|
|
1565
|
+
};
|
|
1566
|
+
return explain(issues, openapi, schema, { examples: dsl ? [] : examplesOf("createRun"), body, check });
|
|
1567
|
+
}
|
|
1013
1568
|
/** A run's input: an agentic run's `{content: string}`, a workflow run's what its workflow's input schema takes. */
|
|
1014
1569
|
async function inputIssuesOf(revision, input) {
|
|
1015
1570
|
if (revision.kind === "agentic")
|
|
1016
1571
|
return inputIssues(input, DEFAULT_INPUT_SCHEMA);
|
|
1017
1572
|
const { validateWorkflow } = await import("@parcha/agentrun-dsl");
|
|
1573
|
+
return workflowInputIssues(validateWorkflow, revision, input);
|
|
1574
|
+
}
|
|
1575
|
+
/** A workflow run's input against its workflow's input schema, as the DSL checks it before the first node. */
|
|
1576
|
+
function workflowInputIssues(validateWorkflow, revision, input) {
|
|
1577
|
+
if (revision.kind !== "workflow")
|
|
1578
|
+
return [];
|
|
1018
1579
|
const checked = validateWorkflow(revision.body.workflow, { executeCode: false, input });
|
|
1019
|
-
|
|
1580
|
+
if (checked.ok)
|
|
1581
|
+
return [];
|
|
1582
|
+
return checked.issues.map((i) => {
|
|
1583
|
+
// An input problem has no path of its own; its message names the schema's path and why (the DSL's schemaProblems
|
|
1584
|
+
// reports schema paths, never the input's data), so it is said as it is, and the field carries that path (#1926).
|
|
1585
|
+
const said = !i.path && i.code === "INPUT_INVALID" && i.message ? i.message.replace(/^input:\s*/, "") : `${i.code}${i.path ? ` at ${i.path}` : ""}`;
|
|
1586
|
+
const at = i.path || /^(#\/\S*?):\s/.exec(said)?.[1];
|
|
1587
|
+
return { field: `input${at ? ` at ${at}` : ""}`, reason: "invalid", message: `the workflow does not take this input: ${said}` };
|
|
1588
|
+
});
|
|
1020
1589
|
}
|
|
1590
|
+
/** Where a person opens a page an answer to `req` names (a run's or an agent's console_url, console-links.ts): the
|
|
1591
|
+
* server's public URL when it has one; else the address the request reached it at, which passed the Host check (a
|
|
1592
|
+
* tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
|
|
1593
|
+
* at the public URL or the server's own address. */
|
|
1594
|
+
const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
|
|
1021
1595
|
async function createRun(req, agentId) {
|
|
1022
1596
|
const entry = await needAgent(agentId);
|
|
1023
1597
|
if (entry.agent.archivedAt)
|
|
1024
|
-
throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: entry.agent.archivedAt } });
|
|
1598
|
+
throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
|
|
1025
1599
|
const body = await bodyOf(req);
|
|
1026
1600
|
return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
|
|
1027
1601
|
// A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
|
|
@@ -1030,20 +1604,108 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1030
1604
|
if (first.existing?.fingerprint !== origin.fingerprint)
|
|
1031
1605
|
throw mismatch();
|
|
1032
1606
|
const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
|
|
1033
|
-
return { status: 202, body: await
|
|
1607
|
+
return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
|
|
1034
1608
|
}
|
|
1035
1609
|
const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}) });
|
|
1036
|
-
// Its view from the
|
|
1037
|
-
|
|
1038
|
-
return { status: 202, body: await runs.view(run, { stored: null }), headers: { location: `/v2/runs/${run.id}` } };
|
|
1610
|
+
// Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
|
|
1611
|
+
return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
|
|
1039
1612
|
});
|
|
1040
1613
|
}
|
|
1614
|
+
/** POST /runs: a run of an agent another system owns, given inline. The body is POST /agents/{agent_id}/runs' own, but
|
|
1615
|
+
* `revision` (the run's revision is its external version's), with the agent's reference in its source (`external`) and
|
|
1616
|
+
* the agent as POST /agents takes one (`definition`, `skills`, `note`), checked as that route checks it, in its words.
|
|
1617
|
+
* Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
|
|
1618
|
+
* (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
|
|
1619
|
+
async function createInlineRun(req) {
|
|
1620
|
+
const body = await bodyOf(req);
|
|
1621
|
+
const { external, definition, skills, note, revision: pinned, ...run } = body;
|
|
1622
|
+
const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
|
|
1623
|
+
const issues = [
|
|
1624
|
+
...externalIssues(external),
|
|
1625
|
+
...(pinned !== undefined ? [{ field: "revision", reason: "not_allowed", message: "An inline run pins no revision: it runs the revision of its external version.", fix: "Remove revision." }] : []),
|
|
1626
|
+
...runBodyIssues(run),
|
|
1627
|
+
...definitionBodyIssues(given),
|
|
1628
|
+
// The agent's id is this server's, one per external reference, and its version is the reference's.
|
|
1629
|
+
...["id", "version"].flatMap((key) => (isObject(definition) && definition[key] !== undefined ? [{ field: `definition.${key}`, reason: "not_allowed", message: `An inline agent's ${key} is its external reference's: the definition names none.`, fix: `Remove definition.${key}.` }] : [])),
|
|
1630
|
+
];
|
|
1631
|
+
if (issues.length)
|
|
1632
|
+
throw invalid(issues);
|
|
1633
|
+
const checked = checkDefinitionBody(given);
|
|
1634
|
+
const revision = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
|
|
1635
|
+
// Refused where POST /agents refuses the definition (one this host can never run); what this host still lacks for it
|
|
1636
|
+
// is the run's own refusal (prepareLaunch's runnable), as for a run of a stored agent.
|
|
1637
|
+
await saveable(revision);
|
|
1638
|
+
const ref = external;
|
|
1639
|
+
const inline = {
|
|
1640
|
+
external: { source: ref.source, kind: ref.kind, id: ref.id, version: String(ref.version) },
|
|
1641
|
+
name: checked.definition.name,
|
|
1642
|
+
description: typeof checked.definition.description === "string" ? checked.definition.description : null,
|
|
1643
|
+
revision,
|
|
1644
|
+
};
|
|
1645
|
+
return idempotent(req, "/runs", body, async (origin) => {
|
|
1646
|
+
// A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
|
|
1647
|
+
const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
|
|
1648
|
+
if (first) {
|
|
1649
|
+
if (first.existing?.fingerprint !== origin.fingerprint)
|
|
1650
|
+
throw mismatch();
|
|
1651
|
+
const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
|
|
1652
|
+
return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
|
|
1653
|
+
}
|
|
1654
|
+
const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}) });
|
|
1655
|
+
return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
/** An inline run's `external`, field by field: its source and kind (no colon, which the reference's key splits on), its
|
|
1659
|
+
* id in its source (text), and its version there (text or a whole number). */
|
|
1660
|
+
function externalIssues(external) {
|
|
1661
|
+
if (external === undefined)
|
|
1662
|
+
return [{ field: "external", reason: "missing", message: "external is the agent's reference in the system that owns it: {source, kind, id, version}" }];
|
|
1663
|
+
if (!isObject(external))
|
|
1664
|
+
return [{ field: "external", reason: "wrong_type", message: "external is an object: {source, kind, id, version}" }];
|
|
1665
|
+
const issues = unknownFields(external, ["source", "kind", "id", "version"]).map((issue) => ({ ...issue, field: `external.${issue.field}`, message: `external keeps no field ${issue.field}.` }));
|
|
1666
|
+
for (const key of ["source", "kind"]) {
|
|
1667
|
+
const value = external[key];
|
|
1668
|
+
if (value === undefined)
|
|
1669
|
+
issues.push({ field: `external.${key}`, reason: "missing", message: `external.${key} is required` });
|
|
1670
|
+
else if (typeof value !== "string")
|
|
1671
|
+
issues.push({ field: `external.${key}`, reason: "wrong_type", message: `external.${key} is text` });
|
|
1672
|
+
else if (!EXTERNAL_NAME.test(value))
|
|
1673
|
+
issues.push({ field: `external.${key}`, reason: "bad_format", message: `external.${key} does not match ${EXTERNAL_NAME.source}` });
|
|
1674
|
+
}
|
|
1675
|
+
if (external.id === undefined)
|
|
1676
|
+
issues.push({ field: "external.id", reason: "missing", message: "external.id is required" });
|
|
1677
|
+
else if (typeof external.id !== "string" || external.id.length < 1 || external.id.length > 255)
|
|
1678
|
+
issues.push({ field: "external.id", reason: "wrong_type", message: "external.id is the agent's id in its source: text of 1 to 255 characters" });
|
|
1679
|
+
const { version } = external;
|
|
1680
|
+
if (version === undefined)
|
|
1681
|
+
issues.push({ field: "external.version", reason: "missing", message: "external.version is required" });
|
|
1682
|
+
else if (!((typeof version === "string" && version.length >= 1 && version.length <= 128) || (Number.isSafeInteger(version) && version >= 0)))
|
|
1683
|
+
issues.push({ field: "external.version", reason: "wrong_type", message: "external.version is the agent's version in its source: text of 1 to 128 characters, or a whole number" });
|
|
1684
|
+
return issues;
|
|
1685
|
+
}
|
|
1041
1686
|
/** A run of `entry`'s agent from a create's body, checked as POST /agents/{id}/runs checks it: that route's, and a
|
|
1042
1687
|
* trigger's firing's, which names itself as the run's `trigger`. Under `origin`, a key that already started a run
|
|
1043
1688
|
* gets that run (the agent store's run_origins). */
|
|
1044
1689
|
/** `capped`: the run must have a cap (a trigger's), its own or else its agent's default. */
|
|
1045
|
-
|
|
1046
|
-
|
|
1690
|
+
/** `from`: who the run's first message is from when the person did not write it (a trigger's firing). */
|
|
1691
|
+
async function startRunOf(entry, body, options = {}) {
|
|
1692
|
+
// Every check the old start made, in the same order and words, now lives in the run write half (runs-over-store.startRun,
|
|
1693
|
+
// over StartDeps): the body's fields, the revision it pins, the input against its schema, the cap rules, the plane this
|
|
1694
|
+
// host resolves, whether the revision can run here — then an INSERT of a queued run and its launch in one transaction,
|
|
1695
|
+
// which a runner reads at its claim. No process, no door, no setup file.
|
|
1696
|
+
return startRun(store, startDeps, entry, body, options);
|
|
1697
|
+
}
|
|
1698
|
+
/** The revision a run of `entry` starts on: the one `body.revision` pins, else the agent's current; undefined when the
|
|
1699
|
+
* pin names none, or the agent has no revision. */
|
|
1700
|
+
async function pinnedOf(entry, body) {
|
|
1701
|
+
const found = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
|
|
1702
|
+
// A store RevisionRow is the same revision the run path reads as a pi Revision (its body is the revision body JSON); the
|
|
1703
|
+
// run write half (StartDeps) types it as Revision, so the row is handed across as one.
|
|
1704
|
+
return found ? { revision: found.revision, version: found.version } : undefined;
|
|
1705
|
+
}
|
|
1706
|
+
/** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
|
|
1707
|
+
function runBodyIssues(body) {
|
|
1708
|
+
const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id"]);
|
|
1047
1709
|
if (!isObject(body.input))
|
|
1048
1710
|
issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
|
|
1049
1711
|
if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
|
|
@@ -1052,35 +1714,11 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1052
1714
|
issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
|
|
1053
1715
|
if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0 && Number.isFinite(body.max_cost_usd)))
|
|
1054
1716
|
issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
|
|
1717
|
+
if (body.cap_mode !== undefined && !CAP_MODES.includes(body.cap_mode))
|
|
1718
|
+
issues.push({ field: "cap_mode", reason: "not_an_option", message: `cap_mode is one of ${CAP_MODES.join(", ")}` });
|
|
1055
1719
|
if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
|
|
1056
1720
|
issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
|
|
1057
|
-
|
|
1058
|
-
throw invalid(issues);
|
|
1059
|
-
if (body.quote_id !== undefined)
|
|
1060
|
-
throw unsupported("quotes", "This server has no billing, so it takes no quotes.");
|
|
1061
|
-
// Each a ready file, before anything starts: copied into the run's work/inputs/ once its directory is made.
|
|
1062
|
-
const files = Array.isArray(body.file_ids) ? await uploads.readyFiles(body.file_ids) : [];
|
|
1063
|
-
const pinned = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
|
|
1064
|
-
if (!pinned)
|
|
1065
|
-
throw invalid([{ field: "revision", reason: "not_an_option", message: typeof body.revision === "string" ? `${body.revision} is not a revision of the agent ${entry.agent.id}` : `the agent ${entry.agent.id} has no current revision` }]);
|
|
1066
|
-
const { revision, version } = pinned;
|
|
1067
|
-
if (revision.kind === "workflow" && body.max_cost_usd !== undefined)
|
|
1068
|
-
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here: its cost shows once it ends." }]);
|
|
1069
|
-
const input = body.input;
|
|
1070
|
-
const wrong = await inputIssuesOf(revision, input);
|
|
1071
|
-
if (wrong.length)
|
|
1072
|
-
throw invalid(wrong);
|
|
1073
|
-
// The run's own cap, else the agent's default (an agentic revision's): the caller chose its own.
|
|
1074
|
-
const cap = typeof body.max_cost_usd === "number" ? body.max_cost_usd : revision.kind === "agentic" ? revision.body.maxCostUsd : undefined;
|
|
1075
|
-
if (capped && cap === undefined)
|
|
1076
|
-
throw invalid([{ field: "max_cost_usd", reason: "missing", message: "Every run a trigger starts is capped: give the trigger's target a max_cost_usd or set the agent's." }]);
|
|
1077
|
-
const place = resolvePlace(revision.body.place);
|
|
1078
|
-
await runnable(revision, place, { capped: cap !== undefined });
|
|
1079
|
-
// The title shows on the run's page, the runs list and Mission Control: built from its input as shown, each held
|
|
1080
|
-
// value redacted before a long one is cut (a cut key could no longer be found), and the run gets its input as given.
|
|
1081
|
-
const shown = redactedOutput(input, learningSecrets());
|
|
1082
|
-
const title = revision.kind === "workflow" ? workflowTitle(entry.agent.name || entry.agent.id, isObject(shown) ? shown : {}) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
|
|
1083
|
-
return runs.create(entry, revision, version, { input, title, place, ...(typeof body.effort === "string" ? { effort: body.effort } : {}), ...(cap !== undefined ? { maxCostUsd: cap } : {}), ...(trigger ? { trigger } : {}), ...(origin ? { origin } : {}), ...(files.length ? { inputs: (work) => uploads.copyInto(work, files) } : {}) });
|
|
1721
|
+
return issues;
|
|
1084
1722
|
}
|
|
1085
1723
|
/** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
|
|
1086
1724
|
/** A list's `archived`: true lists only what is archived, false (the default) only what is not. */
|
|
@@ -1090,7 +1728,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1090
1728
|
throw new ApiError("bad_request", "archived is true or false");
|
|
1091
1729
|
return value === "true";
|
|
1092
1730
|
}
|
|
1093
|
-
async function runsPage(url, filter) {
|
|
1731
|
+
async function runsPage(url, filter, origin) {
|
|
1094
1732
|
const limit = limitOf(url.searchParams.get("limit"));
|
|
1095
1733
|
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
1096
1734
|
const status = url.searchParams.get("status");
|
|
@@ -1100,19 +1738,18 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1100
1738
|
if (value !== undefined && !ID.test(value))
|
|
1101
1739
|
throw new ApiError("bad_request", `${key} is an id`);
|
|
1102
1740
|
const archived = archivedParam(url);
|
|
1103
|
-
|
|
1741
|
+
const vd = viewDepsFor(origin);
|
|
1742
|
+
let rows = (await listRunsOverStore(store, filter, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
|
|
1104
1743
|
if (status !== null) {
|
|
1105
|
-
|
|
1744
|
+
// The v2 status is the run view's (store-view over the journal), per row.
|
|
1745
|
+
const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
|
|
1106
1746
|
rows = rows.filter((_, i) => statuses[i] === status);
|
|
1107
1747
|
}
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
for (const r of await agents.revisions(agent))
|
|
1111
|
-
versions.set(r.id, r.version);
|
|
1112
|
-
const page = await Promise.all(rows.slice(offset, offset + limit).map((row) => runs.summaryOfRow(row, versions)));
|
|
1748
|
+
// summaryOverStore reads each run's view (its version, status, cost and learning among them); no versions map is needed.
|
|
1749
|
+
const page = await Promise.all(rows.slice(offset, offset + limit).map((row) => summaryOverStore(store, row.id, vd)));
|
|
1113
1750
|
return { runs: page, next_cursor: nextCursor(offset + limit, rows.length) };
|
|
1114
1751
|
}
|
|
1115
|
-
async function timeline(req, res, url,
|
|
1752
|
+
async function timeline(req, res, url, runId) {
|
|
1116
1753
|
const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
|
|
1117
1754
|
const waitMs = integerParam(url.searchParams.get("wait_ms"), "wait_ms", MAX_WAIT_MS);
|
|
1118
1755
|
// This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's).
|
|
@@ -1120,12 +1757,11 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1120
1757
|
if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
|
|
1121
1758
|
throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
|
|
1122
1759
|
const limit = asked === null ? PAGE_ROWS : Number(asked);
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
};
|
|
1760
|
+
// The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
|
|
1761
|
+
// cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
|
|
1762
|
+
// journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
|
|
1127
1763
|
if (!String(req.headers.accept ?? "").includes("text/event-stream")) {
|
|
1128
|
-
const page = await
|
|
1764
|
+
const page = await timelines.page(store, runId, after, waitMs, limit);
|
|
1129
1765
|
return send(res, 200, { ...page, poll_after_ms: page.final || page.has_more ? 0 : 1000 });
|
|
1130
1766
|
}
|
|
1131
1767
|
const last = req.headers["last-event-id"];
|
|
@@ -1136,9 +1772,20 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1136
1772
|
const beat = setInterval(() => res.write(": keepalive\n\n"), 15_000);
|
|
1137
1773
|
let open = true;
|
|
1138
1774
|
res.once("close", () => void (open = false));
|
|
1775
|
+
// The live wake: watchRun (live/stream.ts) signals a new journal commit or the run's end, so the page is re-read at
|
|
1776
|
+
// once instead of only on a poll. A run with no watch (gone, or a store with no live) falls back to a 1s re-read; the
|
|
1777
|
+
// page it serves is byte-identical either way.
|
|
1778
|
+
const stream = await watchRun(store, runId).catch(() => undefined);
|
|
1779
|
+
let notify;
|
|
1780
|
+
stream?.start(() => notify?.());
|
|
1781
|
+
const nextChange = (ms) => new Promise((resolve) => {
|
|
1782
|
+
const t = setTimeout(() => ((notify = undefined), resolve()), ms);
|
|
1783
|
+
t.unref?.();
|
|
1784
|
+
notify = () => (clearTimeout(t), (notify = undefined), resolve());
|
|
1785
|
+
});
|
|
1139
1786
|
try {
|
|
1140
1787
|
for (let first = true; open; first = false) {
|
|
1141
|
-
const page = await
|
|
1788
|
+
const page = await timelines.page(store, runId, cursor, 0, limit);
|
|
1142
1789
|
if (!open)
|
|
1143
1790
|
break;
|
|
1144
1791
|
if (first || !page.unchanged || page.final)
|
|
@@ -1148,117 +1795,57 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1148
1795
|
res.write(`event: end\ndata: ${JSON.stringify({ reason: "terminal" })}\n\n`);
|
|
1149
1796
|
break;
|
|
1150
1797
|
}
|
|
1798
|
+
// Until the next commit, the run's end, or 15s (the keepalive cadence; a run with no watch re-reads every 1s).
|
|
1799
|
+
await Promise.race([nextChange(stream ? 15_000 : 1_000), ...(stream ? [stream.closed] : [])]);
|
|
1151
1800
|
}
|
|
1152
1801
|
}
|
|
1153
1802
|
finally {
|
|
1154
1803
|
clearInterval(beat);
|
|
1804
|
+
await stream?.stop().catch(() => { });
|
|
1155
1805
|
res.end();
|
|
1156
1806
|
}
|
|
1157
1807
|
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
* host-owned name at its top is the host's: named in `owned`, and nothing below it walked. */
|
|
1162
|
-
async function walk(base, home = false) {
|
|
1163
|
-
const out = [];
|
|
1164
|
-
const owned = [];
|
|
1165
|
-
let deep = false;
|
|
1166
|
-
if (!(await lstat(base).catch(() => null))?.isDirectory())
|
|
1167
|
-
return { files: out, deep, owned };
|
|
1168
|
-
// The directory unreadable as a whole lists nothing; what the walk could not read in it is left out.
|
|
1169
|
-
await walkWork(base, (path, st, readable) => {
|
|
1170
|
-
if (st.isFile())
|
|
1171
|
-
out.push({ ...fileView(path, st), ...(readable ? {} : { unreadable: true }) });
|
|
1172
|
-
else if (st.isDirectory() && path.split("/").length > WALK_DEPTH)
|
|
1173
|
-
deep = true;
|
|
1174
|
-
return out.length <= FILE_LIST_CAP;
|
|
1175
|
-
}, {
|
|
1176
|
-
skip: (name, path) => {
|
|
1177
|
-
if (name.startsWith("."))
|
|
1178
|
-
return true;
|
|
1179
|
-
if (!home || path !== name || !hostOwnedOf(name))
|
|
1180
|
-
return false;
|
|
1181
|
-
owned.push(name);
|
|
1182
|
-
return true;
|
|
1183
|
-
},
|
|
1184
|
-
}).catch((error) => {
|
|
1185
|
-
if (!(error instanceof WorkRefused))
|
|
1186
|
-
throw error;
|
|
1187
|
-
});
|
|
1188
|
-
return { files: out, deep, owned };
|
|
1189
|
-
}
|
|
1190
|
-
/** The file `rel` under `root`, raw; `unreadable` says why one this server cannot read is private. */
|
|
1191
|
-
async function sendFile(req, res, url, root, rel, unreadable) {
|
|
1192
|
-
if (!(await lstat(root).catch(() => null))?.isDirectory())
|
|
1193
|
-
throw new ApiError("not_found", "no such file");
|
|
1194
|
-
// Through no link, held from the open to the last byte (workspace.ts): a name swapped for one is refused, not followed.
|
|
1195
|
-
const opened = await openWorkFile(root, rel).catch((error) => {
|
|
1196
|
-
if (error instanceof WorkRefused && error.reason === "unreadable")
|
|
1197
|
-
throw new ApiError("system_file_forbidden", `This file was created private by ${unreadable}: this server cannot read it.`, { details: { reason: "unreadable" } });
|
|
1198
|
-
return null;
|
|
1199
|
-
});
|
|
1200
|
-
if (!opened)
|
|
1201
|
-
throw new ApiError("not_found", "no such file");
|
|
1202
|
-
const { handle, stats: st } = opened;
|
|
1203
|
-
const type = typeOf(rel) ?? "application/octet-stream";
|
|
1204
|
-
const download = url.searchParams.get("download") === "1" || !INLINE_TYPES.has(type);
|
|
1205
|
-
const name = rel.split("/").at(-1).replace(/[^\w.-]/g, "_");
|
|
1206
|
-
res.writeHead(200, {
|
|
1207
|
-
"content-type": type,
|
|
1208
|
-
"content-length": st.size,
|
|
1209
|
-
"x-content-type-options": "nosniff",
|
|
1210
|
-
"cache-control": "no-store",
|
|
1211
|
-
...(type.startsWith("text/html") ? { "content-security-policy": FILE_CSP } : {}),
|
|
1212
|
-
...(download ? { "content-disposition": `attachment; filename="${name}"` } : {}),
|
|
1213
|
-
});
|
|
1214
|
-
if (req.method === "HEAD" || st.size === 0) {
|
|
1215
|
-
await handle.close();
|
|
1216
|
-
return void res.end();
|
|
1217
|
-
}
|
|
1218
|
-
await pipeline(handle.createReadStream(), res).catch(() => undefined);
|
|
1219
|
-
await handle.close().catch(() => undefined);
|
|
1220
|
-
}
|
|
1808
|
+
// ---- files ----------------------------------------------------------------------------------------------------------
|
|
1809
|
+
// A run's Workspace (its files' list and reads) is the store-backed run reads' now (run-reads-over-store, E2c, over the
|
|
1810
|
+
// run's launch place with run-workspace.ts), not a local folder off the data directory. Removed with the file routes.
|
|
1221
1811
|
// ---- an agent's home --------------------------------------------------------------------------------------------------
|
|
1222
|
-
/**
|
|
1223
|
-
* `make
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1812
|
+
/** Agent `agentId`'s home as its Workspace (paths.ts agentHomeFolder): null while nothing was ever written to it. With
|
|
1813
|
+
* `make`, its folder and each above it under the data directory are made (0700) where absent, each one made synced
|
|
1814
|
+
* into its parent, so a write in it that is answered survives a crash of the machine. Never a link: a read finds no
|
|
1815
|
+
* home there, and a write is refused. */
|
|
1816
|
+
async function homeWorkspace(agentId, make) {
|
|
1817
|
+
const root = agentHomeFolder(data, agentId);
|
|
1818
|
+
if (make) {
|
|
1819
|
+
let dir = data;
|
|
1820
|
+
for (const part of relative(data, root).split(sep)) {
|
|
1821
|
+
dir = join(dir, part);
|
|
1822
|
+
if (await mkdir(dir, { mode: 0o700 }).then(() => true, (error) => (error.code === "EEXIST" ? false : Promise.reject(error))))
|
|
1823
|
+
await syncDir(dirname(dir));
|
|
1824
|
+
}
|
|
1235
1825
|
}
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
const owned = await ownedByIdentity(home, rel);
|
|
1242
|
-
if (owned)
|
|
1243
|
-
throw hostOwnedRefusal(owned, agentId, write, ownedReadAt(agentId));
|
|
1826
|
+
if ((await lstat(root).catch(() => null))?.isDirectory())
|
|
1827
|
+
return localWorkspace(root);
|
|
1828
|
+
if (make)
|
|
1829
|
+
throw new ApiError("system_file_forbidden", LINK_REFUSED, { details: { reason: "link" } });
|
|
1830
|
+
return null;
|
|
1244
1831
|
}
|
|
1245
|
-
/** A write to the home or a removal from it refused
|
|
1832
|
+
/** A write to the home or a removal from it the Workspace refused, as its answer. */
|
|
1246
1833
|
function homeRefusal(error) {
|
|
1247
|
-
if (!(error
|
|
1834
|
+
if (!isWorkspaceError(error))
|
|
1248
1835
|
throw error;
|
|
1249
|
-
if (error.
|
|
1250
|
-
throw new ApiError("system_file_forbidden",
|
|
1251
|
-
|
|
1836
|
+
if (error.code === "ESCAPE")
|
|
1837
|
+
throw new ApiError("system_file_forbidden", LINK_REFUSED, { details: { reason: "link" } });
|
|
1838
|
+
const denied = ["EACCES", "EPERM"].includes(error.cause?.code ?? "");
|
|
1839
|
+
if (denied)
|
|
1252
1840
|
throw new ApiError("system_file_forbidden", "This server may not enter a directory on the way to this path.", { details: { reason: "unreadable" } });
|
|
1253
|
-
if (error.
|
|
1841
|
+
if (error.code === "REFUSED" || error.code === "EXISTS" || error.code === "NOT_FOUND")
|
|
1254
1842
|
throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
|
|
1255
|
-
|
|
1256
|
-
throw new ApiError("unsupported_here", HOME_WRITES_OFF);
|
|
1257
|
-
throw new ApiError("not_found", "no such file");
|
|
1843
|
+
throw error;
|
|
1258
1844
|
}
|
|
1259
1845
|
// ---- usage ----------------------------------------------------------------------------------------------------------
|
|
1260
|
-
// Each ended run's meters,
|
|
1261
|
-
//
|
|
1846
|
+
// Each ended run's meters, over the one store (store-reads/cap metersOverStore, cap.ts meterFiguresFrom over A's journal):
|
|
1847
|
+
// kept, as a settled run's journal no longer changes, keyed by its end, so a run opened again and ended again is read
|
|
1848
|
+
// again. A run whose journal cannot be read leaves it all tokens.
|
|
1262
1849
|
const endedMeters = new Map();
|
|
1263
1850
|
// Each ended run's spend so far as it saved it at its end (serve.json's cost_so_far: every conversation's charges and
|
|
1264
1851
|
// its decisions' receipts, which its root store alone does not hold), kept as its meters are; undefined when it saved
|
|
@@ -1267,28 +1854,24 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1267
1854
|
const savedSoFarOf = (row) => {
|
|
1268
1855
|
const key = `${row.id} ${row.endedAt}`;
|
|
1269
1856
|
if (!endedSoFar.has(key)) {
|
|
1857
|
+
// TODO(E3/store-reads): a run's kept so-far cost comes from the store (its row/journal), not a per-run RUN_META file
|
|
1858
|
+
// (runStorePath is gone). Undefined until the usage route reads it over the store.
|
|
1270
1859
|
let usd;
|
|
1271
|
-
|
|
1272
|
-
const kept = JSON.parse(readFileSync(join(dirname(dirname(agents.store.runStorePath(row.id))), RUN_META), "utf8")).cost_so_far?.so_far_usd;
|
|
1273
|
-
usd = typeof kept === "number" && Number.isFinite(kept) ? kept : undefined;
|
|
1274
|
-
}
|
|
1275
|
-
catch {
|
|
1860
|
+
{
|
|
1276
1861
|
usd = undefined;
|
|
1277
1862
|
}
|
|
1278
1863
|
endedSoFar.set(key, usd);
|
|
1279
1864
|
}
|
|
1280
1865
|
return endedSoFar.get(key);
|
|
1281
1866
|
};
|
|
1282
|
-
const metersOf = (row) => {
|
|
1867
|
+
const metersOf = async (row) => {
|
|
1283
1868
|
const key = `${row.id} ${row.endedAt}`;
|
|
1284
1869
|
let meters = endedMeters.get(key);
|
|
1285
1870
|
if (!meters) {
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
meters = { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
|
|
1291
|
-
}
|
|
1871
|
+
// An ended run's meter figures over the one store: cap.ts meterFiguresFrom over A's journal, its paid tools' charges
|
|
1872
|
+
// folded back from the paid-tools session (store-reads/journal withPaidCosts), as meterFiguresIn read a file-backed
|
|
1873
|
+
// run's own database — the same figures (the money-parity rule).
|
|
1874
|
+
meters = await metersOverStore(store, row.id, ctx);
|
|
1292
1875
|
endedMeters.set(key, meters);
|
|
1293
1876
|
}
|
|
1294
1877
|
return meters;
|
|
@@ -1305,6 +1888,8 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1305
1888
|
if (!["meter", "agent", "key", "day", "region"].includes(group))
|
|
1306
1889
|
throw new ApiError("bad_request", "group_by is meter, agent, key, day or region");
|
|
1307
1890
|
const lines = new Map();
|
|
1891
|
+
// Tool calls run with no price (an MCP tool its owner set none for): outside every cost, counted on `tools`.
|
|
1892
|
+
let notMetered = 0;
|
|
1308
1893
|
const total = { usd: 0, unpriced: 0 };
|
|
1309
1894
|
// The browser_time line's seconds: its ended runs' (their stores keep each charge's), none once a live run is in it.
|
|
1310
1895
|
let browserSeconds = 0;
|
|
@@ -1325,23 +1910,32 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1325
1910
|
const at = Date.parse(row.startedAt);
|
|
1326
1911
|
if (!(at >= from && at < to))
|
|
1327
1912
|
continue;
|
|
1328
|
-
|
|
1329
|
-
|
|
1913
|
+
// A running run's cost is its booked-so-far spend (store-reads/runs listRuns reads it over the store with
|
|
1914
|
+
// spentOverStore); an ended run's is its stored cost. A null cost (a running run with none yet) counts unpriced.
|
|
1915
|
+
const usd = row.costUsd ?? null;
|
|
1330
1916
|
const key = group === "agent" ? row.agent : group === "day" ? row.startedAt.slice(0, 10) : group === "meter" ? "tokens" : "local";
|
|
1331
1917
|
// By meter, what a run's paid tools charged (monid's) is `tools`, its browser session time `browser_time`, the rest
|
|
1332
1918
|
// `tokens`, all from the same records: a live run's rows (a call still marked is no charge), else its store as it
|
|
1333
1919
|
// ended (a call a crash cut makes `tools` unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
|
|
1334
1920
|
// An ended run's are its store's figures (metersOf keeps them, never its timeline), read for its lines by meter and,
|
|
1335
|
-
// by any group, for what a run of unknown cost is known to have spent.
|
|
1336
|
-
|
|
1921
|
+
// by any group, for what a run of unknown cost is known to have spent. Read once per run (the store read is async): by
|
|
1922
|
+
// meter (its lines and its not-metered calls), and for any group of a run of unknown cost (its known so-far).
|
|
1923
|
+
const all = group === "meter" || usd === null ? await metersOf(row) : undefined;
|
|
1924
|
+
const read = (group === "meter" && usd !== 0) || usd === null ? all : undefined;
|
|
1337
1925
|
// A run whose cost is unknown still spent what is known of it (so_far: each meter's known dollars): that is in the
|
|
1338
1926
|
// total and its lines, and the run is counted unpriced, so a total is never below a line of its own and reads as
|
|
1339
1927
|
// the lower bound unpriced_runs says it is.
|
|
1340
|
-
const soFar = usd !== null || !read ? 0 :
|
|
1928
|
+
const soFar = usd !== null || !read ? 0 : (savedSoFarOf(row) ?? read.known.tokens + read.known.browser + read.known.others);
|
|
1341
1929
|
const meters = group === "meter" && usd !== 0 ? read : undefined;
|
|
1342
1930
|
if (meters && meters.browser.usd !== 0)
|
|
1343
1931
|
browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
|
|
1344
1932
|
// Its parts of the lines (usage-lines.ts): an unknown one counts the run unpriced there and adds what is known of it.
|
|
1933
|
+
// An unpriced MCP call is in none of them: counted apart as not metered on the tools line, which a $0 run shows only
|
|
1934
|
+
// when it made one.
|
|
1935
|
+
const unmetered = group !== "meter" ? 0 : (all?.notMetered ?? 0);
|
|
1936
|
+
notMetered += unmetered;
|
|
1937
|
+
if (unmetered && !lines.has("tools"))
|
|
1938
|
+
lines.set("tools", { usd: 0, unpriced: 0 });
|
|
1345
1939
|
for (const part of runLines({ usd, soFar, key, meters })) {
|
|
1346
1940
|
const line = lines.get(part.name) ?? lines.set(part.name, { usd: 0, unpriced: 0 }).get(part.name);
|
|
1347
1941
|
line.usd += part.usd;
|
|
@@ -1361,7 +1955,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1361
1955
|
const round = (v) => Math.round(v * 1e6) / 1e6;
|
|
1362
1956
|
return {
|
|
1363
1957
|
from: new Date(from).toISOString(), to: new Date(to).toISOString(), currency: "USD", basis: "estimate", group_by: group, total_usd: round(total.usd), unpriced_runs: total.unpriced,
|
|
1364
|
-
lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), ...(key === "browser_time" && group === "meter" && browserSeconds !== null ? { quantity: round(browserSeconds), unit: "second" } : {}), usd: round(line.usd), unpriced_runs: line.unpriced })),
|
|
1958
|
+
lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), ...(key === "browser_time" && group === "meter" && browserSeconds !== null ? { quantity: round(browserSeconds), unit: "second" } : {}), usd: round(line.usd), unpriced_runs: line.unpriced, ...(group === "meter" && key === "tools" && notMetered ? { not_metered_calls: notMetered } : {}) })),
|
|
1365
1959
|
account: null,
|
|
1366
1960
|
};
|
|
1367
1961
|
}
|
|
@@ -1391,8 +1985,9 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1391
1985
|
throw invalid(issues);
|
|
1392
1986
|
return { password: body.password, body };
|
|
1393
1987
|
}
|
|
1394
|
-
/** POST /v2/setup, POST /v2/auth/sign-in, POST /v2/auth/sign-out
|
|
1395
|
-
* credential: their own checks are the setup code (or the token), the password,
|
|
1988
|
+
/** POST /v2/setup, POST /v2/auth/sign-in, POST /v2/auth/sign-out, POST /v2/auth/sign-out-everywhere and GET
|
|
1989
|
+
* /v2/auth/session, answered before any credential: their own checks are the setup code (or the token), the password,
|
|
1990
|
+
* and the session. */
|
|
1396
1991
|
async function ownerRoute(req, res, path, me) {
|
|
1397
1992
|
const method = path === "/auth/session" || path === "/setup/import" ? "GET" : "POST";
|
|
1398
1993
|
if (req.method !== method)
|
|
@@ -1412,11 +2007,20 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1412
2007
|
// The owner's yes, on the box ticked, is kept with the owner: written durably before the password, so a setup that
|
|
1413
2008
|
// cannot keep it sets no owner and can be tried again, and taken back if the password is not written.
|
|
1414
2009
|
const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
|
|
1415
|
-
|
|
2010
|
+
// The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
|
|
2011
|
+
// code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
|
|
2012
|
+
const tokenAsCode = typeof body.code === "string" && body.code !== "" && timingSafeEqual(digest(`Bearer ${body.code}`), expected);
|
|
2013
|
+
const made = await me.setFirst(password, body.code, byToken || tokenAsCode, along);
|
|
1416
2014
|
if (made === "exists")
|
|
1417
2015
|
throw new ApiError("forbidden", "this server has its owner, or is being set up: sign in");
|
|
1418
|
-
if (made === "
|
|
1419
|
-
throw new ApiError("forbidden", "
|
|
2016
|
+
if (made === "missing")
|
|
2017
|
+
throw new ApiError("forbidden", "this server's setup takes the setup code in its log: send it as code");
|
|
2018
|
+
if (made === "wrong")
|
|
2019
|
+
throw new ApiError("forbidden", "that is not the setup code in the server's log");
|
|
2020
|
+
if (made === "new")
|
|
2021
|
+
throw new ApiError("forbidden", "that setup code expired, or five wrong tries voided it: a new one is in the server's log");
|
|
2022
|
+
// A new password ends every session from before (a reset in another process cleared the old one).
|
|
2023
|
+
viewers.recheck();
|
|
1420
2024
|
// The count is for the offer, now answered: it stops.
|
|
1421
2025
|
stopCount();
|
|
1422
2026
|
// Only on the box ticked: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
|
|
@@ -1447,34 +2051,122 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1447
2051
|
}
|
|
1448
2052
|
case "/auth/sign-in": {
|
|
1449
2053
|
fromPage(req);
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
authFailed("/v2/auth/sign-in", "sign_in_table_full");
|
|
1453
|
-
if (allowed !== "ok")
|
|
1454
|
-
throw new ApiError("rate_limited", "too many sign-ins; try again later", { retry_after_ms: 900_000 }, { "retry-after": "900" });
|
|
2054
|
+
// The body first: the limit's place is taken only for the password's check, so a body sent slowly holds nothing
|
|
2055
|
+
// of the limit (the request's own timeout bounds it, as on any route).
|
|
1455
2056
|
const { password } = await passwordIn(req, ["password"], false);
|
|
1456
2057
|
if (!me.hasPassword())
|
|
1457
2058
|
throw new ApiError("forbidden", "this server has no password yet: set it on the setup page");
|
|
1458
|
-
|
|
2059
|
+
// Never refused for good (owner.ts SignInLimit): a try past the limit is told how long to wait, a minute at most.
|
|
2060
|
+
const allowed = me.signIns.allow(clientOf(req));
|
|
2061
|
+
if (!allowed.ok) {
|
|
2062
|
+
const seconds = Math.ceil(allowed.retryAfterMs / 1000);
|
|
2063
|
+
throw new ApiError("rate_limited", `too many sign-ins ${allowed.by === "address" ? "from this address" : "on this server"}; try again in ${seconds} s`, { retry_after_ms: allowed.retryAfterMs }, { "retry-after": String(seconds) });
|
|
2064
|
+
}
|
|
2065
|
+
if (allowed.untracked)
|
|
2066
|
+
authFailed("/v2/auth/sign-in", "sign_in_table_full");
|
|
2067
|
+
// The try holds its place in the server's count while the password is checked: a wrong one is charged.
|
|
2068
|
+
let wrong = false;
|
|
2069
|
+
try {
|
|
2070
|
+
wrong = !(await me.check(password));
|
|
2071
|
+
}
|
|
2072
|
+
finally {
|
|
2073
|
+
allowed.done(wrong);
|
|
2074
|
+
}
|
|
2075
|
+
if (wrong) {
|
|
1459
2076
|
authFailed("/v2/auth/sign-in", "wrong_password");
|
|
1460
2077
|
throw new ApiError("unauthenticated", "that is not the password");
|
|
1461
2078
|
}
|
|
1462
2079
|
return send(res, 200, { signed_in: true }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
|
|
1463
2080
|
}
|
|
2081
|
+
// This browser: its session revoked on the server (a copy of its cookie is no session either) and its cookie
|
|
2082
|
+
// cleared; every other browser's session left as it is. A viewer watching with it is cut off.
|
|
1464
2083
|
case "/auth/sign-out": {
|
|
2084
|
+
fromPage(req);
|
|
2085
|
+
if (!signedIn(req, me))
|
|
2086
|
+
throw new ApiError("unauthenticated", "this browser is not signed in");
|
|
2087
|
+
for (const value of heldSessions(req))
|
|
2088
|
+
if (me.valid(value))
|
|
2089
|
+
me.revoke(value);
|
|
2090
|
+
viewers.recheck();
|
|
2091
|
+
return send(res, 200, { signed_out: true }, { "set-cookie": ownerCookie(req, "", 0) });
|
|
2092
|
+
}
|
|
2093
|
+
// Every browser and phone: the sessions' epoch moves on, so every cookie made before is none, this one's too.
|
|
2094
|
+
case "/auth/sign-out-everywhere": {
|
|
1465
2095
|
fromPage(req);
|
|
1466
2096
|
if (!signedIn(req, me))
|
|
1467
2097
|
throw new ApiError("unauthenticated", "this browser is not signed in");
|
|
1468
2098
|
me.signOutEverywhere();
|
|
2099
|
+
viewers.recheck();
|
|
1469
2100
|
return send(res, 200, { signed_out: true }, { "set-cookie": ownerCookie(req, "", 0) });
|
|
1470
2101
|
}
|
|
1471
|
-
case "/auth/session":
|
|
1472
|
-
|
|
2102
|
+
case "/auth/session": {
|
|
2103
|
+
// Before the owner's password is set: whether setup takes the printed code (a server at a public address, or on a non-loopback listener), so
|
|
2104
|
+
// the page asks for it when opened with no link. Never the code itself.
|
|
2105
|
+
const set = me.hasPassword();
|
|
2106
|
+
// secrets_writable: whether this browser may save a secret (secret-writes.ts mayWriteSecrets, the dispatch check's
|
|
2107
|
+
// own rule), so the console offers a paste only where it would be taken. Answered before the page marks the
|
|
2108
|
+
// request, so its facts are read here: accounts are on, and its session is its password's.
|
|
2109
|
+
const writable = secretsWritableFields({ accounts: true, passwordSession: signedIn(req, me), consoleSession: false, token: req.headers.authorization !== undefined && !signedIn(req, me), loopbackBound: isLoopback(host) });
|
|
2110
|
+
return send(res, 200, { accounts: true, password_set: set, signed_in: signedIn(req, me), ...writable, ...(set ? {} : { setup_code: !me.openSetup }) });
|
|
2111
|
+
}
|
|
1473
2112
|
}
|
|
1474
2113
|
throw new ApiError("not_found", `no route /v2${path}`);
|
|
1475
2114
|
}
|
|
1476
2115
|
// ---- routing --------------------------------------------------------------------------------------------------------
|
|
2116
|
+
/** A route's answer; a 422's field issues told from the operation's request body schema (explain.ts). */
|
|
1477
2117
|
async function route(req, res, url, path) {
|
|
2118
|
+
try {
|
|
2119
|
+
return await routeOf(req, res, url, path);
|
|
2120
|
+
}
|
|
2121
|
+
catch (error) {
|
|
2122
|
+
const name = ROUTES.find((r) => r.pattern.test(path) && r.method === req.method)?.name;
|
|
2123
|
+
if (!(error instanceof ApiError) || error.code !== "input_invalid" || !error.extra.fields?.length || !name || explained.has(error))
|
|
2124
|
+
throw error;
|
|
2125
|
+
const body = bodies.get(req);
|
|
2126
|
+
const fields = explain(error.extra.fields, openapi, bodySchemaOf(name), { examples: examplesOf(name), body, check: body && BODY_CHECKS[name]?.(body) });
|
|
2127
|
+
throw new ApiError(error.code, error.message === error.extra.fields[0].message ? fields[0].message : error.message, { ...error.extra, fields }, error.headers);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
/** The 422s already told where they were thrown, with the checks only that place has (a run's, its agent's input). */
|
|
2131
|
+
const explained = new WeakSet();
|
|
2132
|
+
const told = (error) => (explained.add(error), error);
|
|
2133
|
+
/** Each request's body as bodyOf read it, for the 422's suggestions to be checked against. */
|
|
2134
|
+
const bodies = new WeakMap();
|
|
2135
|
+
/** The check of a whole body a route makes before anything else, by operation, for the body sent: what a suggested
|
|
2136
|
+
* value must pass. PUT .../definition's contract body (the definition itself) has none here. */
|
|
2137
|
+
const definitionCheck = (creating) => (body) => definitionBodyIssues(isObject(body) ? body : {}, { creating });
|
|
2138
|
+
const BODY_CHECKS = {
|
|
2139
|
+
createAgent: () => definitionCheck(true),
|
|
2140
|
+
updateDefinition: (sent) => ("definition" in sent ? definitionCheck(false) : undefined),
|
|
2141
|
+
// POST /runs' agent, given inline, is POST /agents' body inside its own: checked as that one is.
|
|
2142
|
+
createInlineRun: () => (body) => {
|
|
2143
|
+
const { definition, skills, note } = isObject(body) ? body : {};
|
|
2144
|
+
return definitionBodyIssues({ definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) });
|
|
2145
|
+
},
|
|
2146
|
+
};
|
|
2147
|
+
/** An operation's documented request bodies (its JSON media type's examples), each its value. */
|
|
2148
|
+
function examplesOf(operationId) {
|
|
2149
|
+
for (const item of Object.values(openapi.paths)) {
|
|
2150
|
+
for (const op of Object.values(item)) {
|
|
2151
|
+
if (op.operationId !== operationId)
|
|
2152
|
+
continue;
|
|
2153
|
+
const media = op.requestBody?.content?.["application/json"] ?? {};
|
|
2154
|
+
return Object.values(media.examples ?? {}).map((example) => example.value);
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
return [];
|
|
2158
|
+
}
|
|
2159
|
+
/** An operation's JSON request body schema in the served document, if it has one. */
|
|
2160
|
+
function bodySchemaOf(operationId) {
|
|
2161
|
+
for (const item of Object.values(openapi.paths)) {
|
|
2162
|
+
for (const op of Object.values(item)) {
|
|
2163
|
+
if (op.operationId === operationId)
|
|
2164
|
+
return deref(openapi, op.requestBody?.content?.["application/json"]?.schema);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
return undefined;
|
|
2168
|
+
}
|
|
2169
|
+
async function routeOf(req, res, url, path) {
|
|
1478
2170
|
const matching = ROUTES.filter((r) => r.pattern.test(path));
|
|
1479
2171
|
// `/v2` twice: a path an answer gives (upload.url, a Location) appended to the /v2 base, where it starts at the root.
|
|
1480
2172
|
if (!matching.length)
|
|
@@ -1482,15 +2174,65 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1482
2174
|
const found = matching.find((r) => r.method === req.method || (req.method === "HEAD" && r.method === "GET"));
|
|
1483
2175
|
if (!found)
|
|
1484
2176
|
throw new ApiError("method_not_allowed", `${req.method} is not a method of ${path}`, {}, { allow: [...new Set(matching.map((r) => r.method))].join(", ") });
|
|
1485
|
-
if (found.name === "getCapabilities")
|
|
1486
|
-
|
|
2177
|
+
if (found.name === "getCapabilities") {
|
|
2178
|
+
// features.computers: the computer kinds this server offers now (computers.ts), read at each answer, since turning
|
|
2179
|
+
// Archil on or off, or saving a key, changes them.
|
|
2180
|
+
const answer = forCaller(caps, byOwnerSession(req));
|
|
2181
|
+
return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()) } });
|
|
2182
|
+
}
|
|
1487
2183
|
if (found.name === "getOpenapi")
|
|
1488
2184
|
return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
|
|
1489
|
-
//
|
|
1490
|
-
|
|
1491
|
-
|
|
2185
|
+
// With accounts off there is no owner, and the console still asks whether it may save a secret: secret-writes.ts'
|
|
2186
|
+
// verdict over the request the page just marked, never a signed-in user it doesn't have.
|
|
2187
|
+
if (found.name === "getAuthSession")
|
|
2188
|
+
return send(res, 200, { accounts: false, ...secretsWritableFields(secretWriterFacts(req, { accounts: false, loopbackBound: isLoopback(host) })) });
|
|
2189
|
+
// The one route with no token: a pushed trigger source's request, checked by its source before anything else is
|
|
2190
|
+
// read (push-handler.ts).
|
|
2191
|
+
if (found.name === "receiveHook") {
|
|
2192
|
+
// A body cut at its cap or its time is answered, then its socket closed: never read to its end.
|
|
2193
|
+
const answer = await receivePush({ adapters, hooked: (id) => triggers.hookSource(id), ...(options.hookBodyMs !== undefined ? { bodyMs: options.hookBodyMs } : {}), ignored: (id, eventId) => triggers.ignored(id, eventId), listening: (kind) => triggers.listening(kind), notice: async (adapterId, event, body) => (adapterId === "github" && event === "installation" ? githubConnect.installationEvent(body, (detail) => triggers.turnOff("github", detail)) : undefined), receive: (id, eventId, payload, attrs) => triggers.receive(id, eventId, payload, attrs), scoped: (kind, scope) => triggers.scoped(kind, scope), setting: (adapterId, scope, field) => triggerSettings.get(adapterId)?.get(scope, field), refused: authFailed, say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)) }, req, /^\/hooks\/([^/]+)$/.exec(path)[1]);
|
|
2194
|
+
return send(res, answer.status, answer.body, answer.headers ?? {});
|
|
2195
|
+
}
|
|
2196
|
+
// An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
|
|
2197
|
+
// it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
|
|
2198
|
+
if (found.name === "mcpOAuthCallback") {
|
|
2199
|
+
// Its state's start set a cookie in the browser that started it: no other browser finishes that sign-in.
|
|
2200
|
+
const state = url.searchParams.get("state");
|
|
2201
|
+
if (!startedHere(req.headers.cookie, req.socket.localPort, state))
|
|
2202
|
+
throw new ApiError("forbidden", "This sign-in was started in another browser, or its 10 minutes are over: start it again in Settings → MCP servers, in this browser.");
|
|
2203
|
+
const location = await mcpServers.oauthCallback(url.searchParams, stopping.signal);
|
|
2204
|
+
// A sign-in that finished kept the server's tools again: the grant-check snapshot reads them.
|
|
2205
|
+
await refreshMcpMeta();
|
|
2206
|
+
// Its sign-in is over: its cookie goes.
|
|
2207
|
+
return void res.writeHead(302, { location, "cache-control": "no-store", "set-cookie": signInCookie(req.socket.localPort, state, overHttps(req), 0) }).end();
|
|
2208
|
+
}
|
|
2209
|
+
if (found.name === "mcpOAuthClient")
|
|
2210
|
+
return send(res, 200, mcpServers.clientDocument(), { "cache-control": "public, max-age=3600" });
|
|
2211
|
+
// Connect GitHub's two steps back from GitHub: the owner's browser, which carries no token. The callback's state is
|
|
2212
|
+
// its check, with the cookie its start set in that browser; an installation is kept only as GitHub, asked with the
|
|
2213
|
+
// App's own JWT, says it is the App's.
|
|
2214
|
+
// Both answer the browser with where to go, never an error body: on to install the App, or to the console's GitHub
|
|
2215
|
+
// settings, connected or with why not.
|
|
2216
|
+
if (found.name === "gitHubCallback") {
|
|
2217
|
+
const state = url.searchParams.get("state") ?? "";
|
|
2218
|
+
// Another browser's (no cookie for this state) leaves the state as it is, for the browser that started it.
|
|
2219
|
+
if (!state || !gitHubStartedHere(req.headers.cookie, req.socket.localPort, state))
|
|
2220
|
+
return void res.writeHead(302, { location: githubConnect.failed("state_invalid", "the browser brought no cookie for this state"), "cache-control": "no-store" }).end();
|
|
2221
|
+
const { location, installState } = await githubConnect.callback(url.searchParams.get("code"), state, stopping.signal);
|
|
2222
|
+
// Its state's cookie goes; the install state's is set, for the installed redirect GitHub sends this browser to.
|
|
2223
|
+
const cookies = [stateCookie(req.socket.localPort, state, overHttps(req), 0), ...(installState ? [stateCookie(req.socket.localPort, installState, overHttps(req), undefined, INSTALLED_PATH)] : [])];
|
|
2224
|
+
return void res.writeHead(302, { location, "cache-control": "no-store", "set-cookie": cookies }).end();
|
|
2225
|
+
}
|
|
2226
|
+
if (found.name === "gitHubInstalled") {
|
|
2227
|
+
// Bound only by the install state the callback sent GitHub and the cookie it set in this browser.
|
|
2228
|
+
const state = url.searchParams.get("state");
|
|
2229
|
+
const bound = state && gitHubStartedHere(req.headers.cookie, req.socket.localPort, state) ? state : null;
|
|
2230
|
+
const location = await githubConnect.installed(url.searchParams.get("installation_id"), bound, stopping.signal);
|
|
2231
|
+
return void res.writeHead(302, { location, "cache-control": "no-store", ...(bound ? { "set-cookie": stateCookie(req.socket.localPort, bound, overHttps(req), 0, INSTALLED_PATH) } : {}) }).end();
|
|
2232
|
+
}
|
|
1492
2233
|
if (found.name === "getHealth") {
|
|
1493
|
-
|
|
2234
|
+
// The store this server opened (SQLite or Postgres), never a second open of the data directory's file.
|
|
2235
|
+
const health = await healthOf(store, data, minFreeBytes);
|
|
1494
2236
|
return send(res, health.status === "ok" ? 200 : 503, health);
|
|
1495
2237
|
}
|
|
1496
2238
|
// Approving a note the grader held for its owner's OK (a risky rule a run's user asked for) takes the owner's
|
|
@@ -1498,16 +2240,55 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1498
2240
|
// page cookie a token can mint (accounts off). The page's cookie stands in for the token only on its own origin
|
|
1499
2241
|
// with a JSON body (page.ts), so this is CSRF-checked as every page write is. With no credential at all it is 401,
|
|
1500
2242
|
// as every route is.
|
|
2243
|
+
// Restoring a retired one puts it back in every later run, as an approval does: the same owner's session alone.
|
|
2244
|
+
if (found.name === "restoreLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
2245
|
+
authFailed(`/v2${path}`, "restore_without_session");
|
|
2246
|
+
throw new ApiError("forbidden", owner ? "Restoring a retired note takes the owner's password sign-in in the console, never a token." : "Restoring a retired note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
2247
|
+
}
|
|
1501
2248
|
if (found.name === "approveLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
1502
2249
|
authFailed(`/v2${path}`, "approve_without_session");
|
|
1503
2250
|
throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
1504
2251
|
}
|
|
2252
|
+
// A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
|
|
2253
|
+
// approving a note is (never a token a run, an MCP client or a script may hold).
|
|
2254
|
+
if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
2255
|
+
const what = found.name.endsWith("Browser") ? "browser" : "computer";
|
|
2256
|
+
authFailed(`/v2${path}`, `${what}_without_session`);
|
|
2257
|
+
throw new ApiError("forbidden", owner ? `A run's live ${what} takes the owner's password sign-in in the console, never a token.` : `A run's live ${what} takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).`);
|
|
2258
|
+
}
|
|
2259
|
+
// A run's desktop or phone view drives it once taken over: the owner's signed-in page alone (computer-routes.ts decides).
|
|
2260
|
+
if (COMPUTER_ROUTES.has(found.name) && !byOwnerSession(req) && req.headers.authorization !== undefined)
|
|
2261
|
+
authFailed(`/v2${path}`, "computer_without_session");
|
|
1505
2262
|
// Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
|
|
1506
2263
|
// token, which the run's own process, an agent's MCP client or a script may hold.
|
|
1507
2264
|
if (found.name === "answerApproval" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
1508
2265
|
authFailed(`/v2${path}`, "approve_without_session");
|
|
1509
2266
|
throw new ApiError("forbidden", owner ? "Answering a tool call's approval takes the owner's password sign-in in the console, never a token." : "Answering a tool call's approval takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
1510
2267
|
}
|
|
2268
|
+
// Saving, replacing or removing a secret (secret-writes.ts): the one check. Who may is mayWriteSecrets' alone (the
|
|
2269
|
+
// owner's session); which writes are secret is each plane's registered predicate, read from the body, so a token's
|
|
2270
|
+
// non-secret edit on the same route still goes through. A body that does not read counts as the plane says of none.
|
|
2271
|
+
// What a stored predicate read to let the request through (SecretRequest.seen): the operation's write is refused if
|
|
2272
|
+
// that changed before it lands, so a write allowed against one stored credential never lands over another.
|
|
2273
|
+
let secretSeen;
|
|
2274
|
+
if (isSecretWriteOperation(found.name) && req.headers.authorization !== undefined && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
|
|
2275
|
+
const body = req.method === "DELETE" || req.method === "GET" ? undefined : await bodyOf(req).catch(() => undefined);
|
|
2276
|
+
// A segment that is not valid percent-encoding is taken as it came: the request goes on to the token's own check.
|
|
2277
|
+
const params = (found.pattern.exec(path) ?? []).slice(1).map((part) => {
|
|
2278
|
+
try {
|
|
2279
|
+
return part === undefined ? "" : decodeURIComponent(part);
|
|
2280
|
+
}
|
|
2281
|
+
catch {
|
|
2282
|
+
return part;
|
|
2283
|
+
}
|
|
2284
|
+
});
|
|
2285
|
+
const checked = { params, store };
|
|
2286
|
+
if (await writesSecretFor(found.name, body, checked)) {
|
|
2287
|
+
authFailed(`/v2${path}`, "secret_without_session");
|
|
2288
|
+
throw new ApiError("forbidden", SECRET_WRITE_REFUSAL);
|
|
2289
|
+
}
|
|
2290
|
+
secretSeen = checked.seen;
|
|
2291
|
+
}
|
|
1511
2292
|
if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
|
|
1512
2293
|
authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
|
|
1513
2294
|
throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
|
|
@@ -1520,14 +2301,8 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1520
2301
|
case "createAgent": {
|
|
1521
2302
|
const body = await bodyOf(req);
|
|
1522
2303
|
const answer = await idempotent(req, "/agents", body, async () => {
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
// one that names a tool the box refuses (browser) keeps the runner, as before.
|
|
1526
|
-
const definition = checkDefinitionBody(body);
|
|
1527
|
-
const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
|
|
1528
|
-
const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
|
|
1529
|
-
const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
|
|
1530
|
-
return { status: 201, body: { ...agentView(entry, await signIns.view(entry.agent.id)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
|
|
2304
|
+
const { entry, warnings } = await createAgentOf(body);
|
|
2305
|
+
return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
|
|
1531
2306
|
});
|
|
1532
2307
|
return send(res, answer.status, answer.body, answer.headers);
|
|
1533
2308
|
}
|
|
@@ -1535,14 +2310,14 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1535
2310
|
const limit = limitOf(url.searchParams.get("limit"));
|
|
1536
2311
|
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
1537
2312
|
const archived = archivedParam(url);
|
|
1538
|
-
const all =
|
|
1539
|
-
return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, await
|
|
2313
|
+
const all = await agents.list({ archived });
|
|
2314
|
+
return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, linkOrigin(req), await agentExtra(entry)))), next_cursor: nextCursor(offset + limit, all.length) });
|
|
1540
2315
|
}
|
|
1541
2316
|
case "getAgent": {
|
|
1542
2317
|
const entry = await needAgent(id);
|
|
1543
2318
|
// The tools its current revision grants, as capabilities list them, each with its provider for this agent.
|
|
1544
2319
|
const tools = entry.revision ? agentTools(env, settings.get(), await toolingOf(entry.revision), caps.tools.map((tool) => tool.name)) : [];
|
|
1545
|
-
return send(res, 200, { ...agentView(entry, await
|
|
2320
|
+
return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
|
|
1546
2321
|
}
|
|
1547
2322
|
case "updateDefinition": {
|
|
1548
2323
|
const entry = await needAgent(id);
|
|
@@ -1565,14 +2340,15 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1565
2340
|
let warnings = [];
|
|
1566
2341
|
const check = async (revision) => void (warnings = await saveable(revision));
|
|
1567
2342
|
const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
|
|
1568
|
-
return send(res, 200, { ...agentView(edited, await
|
|
2343
|
+
return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
|
|
1569
2344
|
}
|
|
1570
2345
|
case "listRevisions": {
|
|
1571
2346
|
const entry = await needAgent(id);
|
|
1572
2347
|
const limit = limitOf(url.searchParams.get("limit"));
|
|
1573
2348
|
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
1574
2349
|
const all = await agents.revisions(id);
|
|
1575
|
-
|
|
2350
|
+
// agentRevisions already carries each row's version and current flag; revisionView builds the v2 shape from it.
|
|
2351
|
+
const page = all.slice(offset, offset + limit).map((row) => revisionView(entry.agent, row));
|
|
1576
2352
|
return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
|
|
1577
2353
|
}
|
|
1578
2354
|
case "setCurrent": {
|
|
@@ -1587,16 +2363,20 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1587
2363
|
if (!(await agents.revision(id, revision)))
|
|
1588
2364
|
throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
|
|
1589
2365
|
const moved = await agents.setCurrent(entry, revision);
|
|
1590
|
-
return send(res, 200, agentView(moved, await
|
|
2366
|
+
return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
|
|
1591
2367
|
}
|
|
1592
2368
|
case "archiveAgent":
|
|
1593
2369
|
case "unarchiveAgent": {
|
|
1594
|
-
|
|
1595
|
-
await
|
|
1596
|
-
|
|
1597
|
-
|
|
2370
|
+
// An agent another system owns is that system's to keep or drop: archiving it here is refused, as an edit is.
|
|
2371
|
+
refuseExternal((await needAgent(id)).agent);
|
|
2372
|
+
// No run sweep on archive: a runner reads an archived agent's run rows directly, nothing to sweep.
|
|
2373
|
+
// The engine archives (or unarchives) the agent itself: archived, every trigger that runs as it turns off with
|
|
2374
|
+
// agent_archived in that same store transaction; unarchived, none turns on. Never archived first by another path,
|
|
2375
|
+
// which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
|
|
2376
|
+
// the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
|
|
2377
|
+
const triggersOff = found.name === "archiveAgent" ? await triggers.agentArchived(id) : await triggers.agentUnarchived(id);
|
|
1598
2378
|
const entry = await needAgent(id);
|
|
1599
|
-
return send(res, 200, agentView(entry, await
|
|
2379
|
+
return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), triggers_off: triggersOff }, { etag: etagOf(entry) });
|
|
1600
2380
|
}
|
|
1601
2381
|
case "forgetSignIn": {
|
|
1602
2382
|
await needAgent(id);
|
|
@@ -1613,18 +2393,29 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1613
2393
|
const answer = await createRun(req, id);
|
|
1614
2394
|
return send(res, answer.status, answer.body, answer.headers);
|
|
1615
2395
|
}
|
|
2396
|
+
case "createInlineRun": {
|
|
2397
|
+
const answer = await createInlineRun(req);
|
|
2398
|
+
return send(res, answer.status, answer.body, answer.headers);
|
|
2399
|
+
}
|
|
1616
2400
|
case "listRuns":
|
|
1617
2401
|
await needAgent(id);
|
|
1618
|
-
return send(res, 200, await runsPage(url, { agent: id }));
|
|
2402
|
+
return send(res, 200, await runsPage(url, { agent: id }, linkOrigin(req)));
|
|
1619
2403
|
case "listAllRuns": {
|
|
1620
2404
|
const agent = url.searchParams.get("agent") ?? undefined;
|
|
1621
2405
|
const revision = url.searchParams.get("revision") ?? undefined;
|
|
1622
|
-
return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }));
|
|
2406
|
+
return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }, linkOrigin(req)));
|
|
2407
|
+
}
|
|
2408
|
+
case "getRun": {
|
|
2409
|
+
const view = await viewOverStore(store, id, viewDepsFor(linkOrigin(req)));
|
|
2410
|
+
if (!view)
|
|
2411
|
+
throw new ApiError("not_found", `no run ${id}`);
|
|
2412
|
+
return send(res, 200, { ...view, ...(await runComputerOf(id, view)) });
|
|
1623
2413
|
}
|
|
1624
|
-
case "getRun":
|
|
1625
|
-
return send(res, 200, await runs.view(await needRun(id)));
|
|
1626
2414
|
case "getTimeline":
|
|
1627
|
-
|
|
2415
|
+
await needRun(id);
|
|
2416
|
+
// Awaited, not dropped: a throw from the timeline (a run gone mid-stream, a bad page) reaches the router's catch,
|
|
2417
|
+
// which answers; a floated rejection would hang the request with no answer.
|
|
2418
|
+
return await timeline(req, res, url, id);
|
|
1628
2419
|
case "sendMessage": {
|
|
1629
2420
|
const run = await needRun(id);
|
|
1630
2421
|
if (run.kind === "workflow")
|
|
@@ -1639,10 +2430,9 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1639
2430
|
throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
|
|
1640
2431
|
if (content.length > MAX_MESSAGE)
|
|
1641
2432
|
throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
|
|
1642
|
-
const { mode, messageId } = await
|
|
1643
|
-
// The run's state
|
|
1644
|
-
|
|
1645
|
-
const { status, state } = statusOf(run);
|
|
2433
|
+
const { mode, messageId } = await message(store, run, content);
|
|
2434
|
+
// The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
|
|
2435
|
+
const { status, state } = await runStatusState(run.id);
|
|
1646
2436
|
return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
|
|
1647
2437
|
});
|
|
1648
2438
|
return send(res, answer.status, answer.body, answer.headers);
|
|
@@ -1656,26 +2446,23 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1656
2446
|
const cap = body.max_cost_usd;
|
|
1657
2447
|
if (!(typeof cap === "number" && Number.isFinite(cap) && cap > 0))
|
|
1658
2448
|
throw invalid([{ field: "max_cost_usd", reason: cap === undefined ? "missing" : "wrong_type", message: "max_cost_usd is a number above 0" }]);
|
|
1659
|
-
|
|
1660
|
-
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here, so it has no cap to raise." }]);
|
|
1661
|
-
const now = run.meta.max_cost_usd;
|
|
2449
|
+
const now = run.maxCostUsd;
|
|
1662
2450
|
if (now === undefined)
|
|
1663
2451
|
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "This run has no cap to raise: a cap is named when a run starts." }]);
|
|
1664
|
-
const { resumed, messageId, note } = await
|
|
1665
|
-
const { status, state } =
|
|
2452
|
+
const { resumed, messageId, note } = await raiseCap(store, run, cap);
|
|
2453
|
+
const { status, state } = await runStatusState(run.id);
|
|
1666
2454
|
return send(res, 200, { run_id: run.id, max_cost_usd: cap, resumed, ...(messageId ? { message_id: messageId } : {}), ...(note ? { note } : {}), status, state });
|
|
1667
2455
|
}
|
|
1668
2456
|
case "stopRun": {
|
|
1669
2457
|
const run = await needRun(id);
|
|
1670
|
-
const stopped = await
|
|
1671
|
-
|
|
1672
|
-
const { status, state } = statusOf(run);
|
|
2458
|
+
const stopped = await stopRunOverStore(store, run.id);
|
|
2459
|
+
const { status, state } = await runStatusState(run.id);
|
|
1673
2460
|
return send(res, 200, { run_id: run.id, stopped, status, state });
|
|
1674
2461
|
}
|
|
1675
2462
|
case "cancelRun": {
|
|
1676
2463
|
const run = await needRun(id);
|
|
1677
|
-
const requested = await
|
|
1678
|
-
return send(res, 202, { run_id: run.id, cancel_requested: requested, already_terminal: !requested, status:
|
|
2464
|
+
const requested = await cancel(store, run);
|
|
2465
|
+
return send(res, 202, { run_id: run.id, cancel_requested: requested, already_terminal: !requested, status: (await runStatusState(run.id)).status });
|
|
1679
2466
|
}
|
|
1680
2467
|
case "answerApproval": {
|
|
1681
2468
|
// The owner's answer to a tool call that waits for approval (tool-gate.ts): the first answer wins.
|
|
@@ -1688,31 +2475,104 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1688
2475
|
issues.push({ field: "note", reason: "wrong_type", message: "note is a string of at most 2000 characters" });
|
|
1689
2476
|
if (issues.length)
|
|
1690
2477
|
throw invalid(issues);
|
|
1691
|
-
await
|
|
2478
|
+
await approve(store, run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined);
|
|
1692
2479
|
res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
1693
2480
|
return void res.end();
|
|
1694
2481
|
}
|
|
1695
2482
|
case "archiveRun":
|
|
1696
2483
|
case "unarchiveRun": {
|
|
1697
2484
|
const run = await needRun(id);
|
|
1698
|
-
await
|
|
1699
|
-
|
|
1700
|
-
await runs.archived();
|
|
1701
|
-
return send(res, 200, await runs.view(run));
|
|
2485
|
+
await archiveRun(store, run.id, found.name === "archiveRun");
|
|
2486
|
+
return send(res, 200, await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))));
|
|
1702
2487
|
}
|
|
1703
|
-
case "
|
|
2488
|
+
case "getRunBrowser":
|
|
2489
|
+
case "getRunComputer": {
|
|
2490
|
+
// One read for both families, over the one store: the computer family's answer, and the browser's own in its base
|
|
2491
|
+
// shape (its link under /browser/live, no kind or hold, off's why as `reason`).
|
|
2492
|
+
const run = await needRun(id);
|
|
2493
|
+
const family = found.name === "getRunBrowser" ? "browser" : "computer";
|
|
2494
|
+
// The run's open viewer, from the store's sealed viewer rows the runner publishes its hand-over into (browser-live.ts
|
|
2495
|
+
// liveViewerLink/computerViewerLink, under the seal key); who drives, from the cut's computerHoldOf over the store.
|
|
2496
|
+
const hold = await computerHoldOf(store, run.id);
|
|
2497
|
+
const kept = await keptBrowserOf(store, run.id);
|
|
2498
|
+
const view = await computerView({
|
|
2499
|
+
viewer: async () => {
|
|
2500
|
+
if (sealKey === undefined)
|
|
2501
|
+
return undefined;
|
|
2502
|
+
if (family === "browser") {
|
|
2503
|
+
const link = await liveViewerLink(store, sealKey, run.id);
|
|
2504
|
+
return link === undefined ? undefined : { kind: "browser", viewer: link.viewer };
|
|
2505
|
+
}
|
|
2506
|
+
return computerViewerLink(store, sealKey, run.id);
|
|
2507
|
+
},
|
|
2508
|
+
computer: () => computerOf(kept, env, family),
|
|
2509
|
+
hold: () => hold,
|
|
2510
|
+
});
|
|
2511
|
+
if (family === "browser")
|
|
2512
|
+
return send(res, 200, view.state === "live" ? { state: "live", viewer: view.viewer } : view.state === "none" ? { state: "none" } : { state: "off", reason: view.why }, { "cache-control": "no-store" });
|
|
2513
|
+
return send(res, 200, view, { "cache-control": "no-store" });
|
|
2514
|
+
}
|
|
2515
|
+
case "handBackRunBrowser": {
|
|
2516
|
+
// The owner's answer to the agent's ask for them in its browser (browser-commands.ts): the first answer wins, the same
|
|
2517
|
+
// one again is that answer, a different one is 409; an ask past its expiry has `expired`. A hand-over command row the
|
|
2518
|
+
// runner reads and applies.
|
|
2519
|
+
const run = await needRun(id);
|
|
2520
|
+
const body = await bodyOf(req);
|
|
2521
|
+
const issues = unknownFields(body, ["outcome"]);
|
|
2522
|
+
if (body.outcome !== "done" && body.outcome !== "cancelled")
|
|
2523
|
+
issues.push({ field: "outcome", reason: body.outcome === undefined ? "missing" : "not_an_option", message: "outcome is done or cancelled" });
|
|
2524
|
+
if (issues.length)
|
|
2525
|
+
throw invalid(issues);
|
|
2526
|
+
// The ask this answer targets, read over the run's hand-over entries and the hand-back commands before this write;
|
|
2527
|
+
// browserHandBack writes the answer (its not_found and handoff_answered words, with details.outcome, as the console
|
|
2528
|
+
// and tests read them), then lets the lowest-id command win, re-reading the journal for a live view's own give.
|
|
2529
|
+
const entries = (await runEntries(store, run.id, ctx));
|
|
2530
|
+
const target = handBackTarget(entries, await store.commands(run.id, 0));
|
|
2531
|
+
const answered = await browserHandBack(store, run.id, body.outcome, target, Date.now(), async () => (await runEntries(store, run.id, ctx)));
|
|
2532
|
+
return send(res, 200, { outcome: answered.outcome }, { "cache-control": "no-store" });
|
|
2533
|
+
}
|
|
2534
|
+
case "takeOverRunComputer":
|
|
2535
|
+
case "handBackRunComputer": {
|
|
2536
|
+
// The owner's take-over of a run's desktop or phone, and the hand-back for every kind (computer-routes.ts), over the
|
|
2537
|
+
// store: the hold is the run's journal, a take-over and a hand-back are command rows its runner applies; a browser's
|
|
2538
|
+
// hand-back is the browser's own answer row, as POST .../browser/hand-back writes it.
|
|
1704
2539
|
const run = await needRun(id);
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
2540
|
+
const answer = await computerRoute(found.name, run.id, {
|
|
2541
|
+
ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, accounts: owner !== undefined, body: await bodyOf(req),
|
|
2542
|
+
}, store, { context: ctx });
|
|
2543
|
+
return send(res, 200, answer, { "cache-control": "no-store" });
|
|
2544
|
+
}
|
|
2545
|
+
case "listComputers":
|
|
2546
|
+
case "saveComputerKeys":
|
|
2547
|
+
case "testComputer": {
|
|
2548
|
+
// Settings → Computers (computers.ts): the rules are the handler's; this sends its answer.
|
|
2549
|
+
const provider = found.name === "listComputers" ? undefined : id;
|
|
2550
|
+
const body = found.name === "saveComputerKeys" ? await bodyOf(req) : undefined;
|
|
2551
|
+
const controller = new AbortController();
|
|
2552
|
+
req.once("close", () => controller.abort());
|
|
2553
|
+
return send(res, 200, await settingsComputerRoute(computersOf(), found.name, { ...(provider !== undefined ? { provider } : {}), ...(body !== undefined ? { body } : {}), signal: controller.signal }), { "cache-control": "no-store" });
|
|
2554
|
+
}
|
|
2555
|
+
case "getWorkspaceArchil":
|
|
2556
|
+
case "putWorkspaceArchil":
|
|
2557
|
+
case "deleteWorkspaceArchil":
|
|
2558
|
+
case "testWorkspaceArchil": {
|
|
2559
|
+
// The owner's Archil settings, Mode 2 on and off (archil-routes.ts): the rules are the handler's.
|
|
2560
|
+
const body = found.name === "putWorkspaceArchil" ? await bodyOf(req) : undefined;
|
|
2561
|
+
const controller = new AbortController();
|
|
2562
|
+
req.once("close", () => controller.abort());
|
|
2563
|
+
return send(res, 200, await archilRoute(archil, found.name, { ...(body !== undefined ? { body } : {}), signal: controller.signal }), { "cache-control": "no-store" });
|
|
2564
|
+
}
|
|
2565
|
+
case "listRunFiles": {
|
|
2566
|
+
await needRun(id);
|
|
2567
|
+
// A run's files through the server's read-only Workspace of its folder (serverRunWorkspace); a run with no folder
|
|
2568
|
+
// lists none, a withheld run refuses (403), as the base did (filesShown). Same shape and cap the file route answered.
|
|
2569
|
+
return send(res, 200, await listRunFilesOverStore(store, id, runReadsDeps));
|
|
1710
2570
|
}
|
|
1711
2571
|
// An archived agent's home is read and written as any other's: as its definition is.
|
|
1712
2572
|
case "listHomeFiles": {
|
|
1713
2573
|
await needAgent(id);
|
|
1714
|
-
const home = await
|
|
1715
|
-
const { files, deep, owned } = home ? await
|
|
2574
|
+
const home = await homeWorkspace(id, false);
|
|
2575
|
+
const { files, deep, owned } = home ? await listFiles(home, FILE_LIST_CAP, { owned: (name) => hostOwnedOf(name) !== undefined }) : { files: [], deep: false, owned: [] };
|
|
1716
2576
|
// A host-owned path there is one entry by its name, and none of what is in it.
|
|
1717
2577
|
const listed = [...files, ...owned.map((path) => ({ path, host_owned: true }))].sort((a, b) => a.path.localeCompare(b.path));
|
|
1718
2578
|
return send(res, 200, { agent_id: id, files: listed.slice(0, FILE_LIST_CAP), complete: true, truncated: deep || listed.length > FILE_LIST_CAP });
|
|
@@ -1720,11 +2580,10 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1720
2580
|
case "readHomeFile": {
|
|
1721
2581
|
await needAgent(id);
|
|
1722
2582
|
const rel = homePath(second, id, false, ownedReadAt(id));
|
|
1723
|
-
const home = await
|
|
2583
|
+
const home = await homeWorkspace(id, false);
|
|
1724
2584
|
if (!home)
|
|
1725
2585
|
throw new ApiError("not_found", "no such file");
|
|
1726
|
-
|
|
1727
|
-
return sendFile(req, res, url, home, rel, "another user");
|
|
2586
|
+
return sendWorkspaceFile(req, res, url, home, rel, "another user");
|
|
1728
2587
|
}
|
|
1729
2588
|
case "writeHomeFile": {
|
|
1730
2589
|
await needAgent(id);
|
|
@@ -1732,25 +2591,30 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1732
2591
|
throw new ApiError("unsupported_here", HOME_WRITES_OFF);
|
|
1733
2592
|
const rel = homePath(second, id, true);
|
|
1734
2593
|
const bytes = await bytesOf(req);
|
|
1735
|
-
// Each write lands whole (
|
|
1736
|
-
const
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
return send(res, 200, fileView(rel, st));
|
|
2594
|
+
// Each write lands whole (the Workspace's write is atomic); of two at once, the last one wins.
|
|
2595
|
+
const home = await homeWorkspace(id, true);
|
|
2596
|
+
await home.write(rel, bytes).catch(homeRefusal);
|
|
2597
|
+
const written = await entryAt(home, rel);
|
|
2598
|
+
if (written?.kind !== "file")
|
|
2599
|
+
throw new ApiError("not_found", "no such file");
|
|
2600
|
+
return send(res, 200, viewOf(rel, written));
|
|
1743
2601
|
}
|
|
1744
2602
|
case "deleteHomeFile": {
|
|
1745
2603
|
await needAgent(id);
|
|
1746
2604
|
if (!homeWrites)
|
|
1747
2605
|
throw new ApiError("unsupported_here", HOME_WRITES_OFF);
|
|
1748
2606
|
const rel = homePath(second, id, true);
|
|
1749
|
-
const home = await
|
|
2607
|
+
const home = await homeWorkspace(id, false);
|
|
1750
2608
|
if (!home)
|
|
1751
2609
|
throw new ApiError("not_found", "no such file");
|
|
1752
|
-
|
|
1753
|
-
await
|
|
2610
|
+
// A file alone: a folder is refused by the listing; a link (never listed) by the Workspace's remove (ESCAPE).
|
|
2611
|
+
if ((await entryAt(home, rel))?.kind === "dir")
|
|
2612
|
+
throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
|
|
2613
|
+
await home.remove(rel).catch((error) => {
|
|
2614
|
+
if (isWorkspaceError(error, "NOT_FOUND"))
|
|
2615
|
+
throw new ApiError("not_found", "no such file");
|
|
2616
|
+
homeRefusal(error);
|
|
2617
|
+
});
|
|
1754
2618
|
res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
1755
2619
|
return void res.end();
|
|
1756
2620
|
}
|
|
@@ -1767,7 +2631,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1767
2631
|
const { issues, warnings } = await workflowIssues(body.workflow, body.tools);
|
|
1768
2632
|
// What a save refuses on this host (a model node's tool, a code node where none runs), and what it lacks yet.
|
|
1769
2633
|
if (!issues.length) {
|
|
1770
|
-
for (const blocker of await blockersOf(env, { kind: "workflow", workflow: body.workflow, ...(body.tools ? { tools: body.tools } : {}) }, settings.get(), { offers }).catch(() => [])) {
|
|
2634
|
+
for (const blocker of await blockersOf(env, { kind: "workflow", workflow: body.workflow, ...(body.tools ? { tools: body.tools } : {}) }, settings.get(), { offers, mcp: mcpTools }).catch(() => [])) {
|
|
1771
2635
|
if (blocker.host)
|
|
1772
2636
|
warnings.push(blocker.message);
|
|
1773
2637
|
else
|
|
@@ -1777,14 +2641,25 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1777
2641
|
return send(res, 200, { ok: issues.length === 0, issues, warnings });
|
|
1778
2642
|
}
|
|
1779
2643
|
case "getRunGraph":
|
|
1780
|
-
|
|
2644
|
+
await needRun(id);
|
|
2645
|
+
// The workflow run's graph from its journal over the store (run-reads-over-store): an agentic run has none (404),
|
|
2646
|
+
// a run whose output is withheld is refused (403), as the route refused it.
|
|
2647
|
+
return send(res, 200, await runGraphView(store, id, runReadsDeps));
|
|
1781
2648
|
case "pauseRun":
|
|
1782
|
-
case "resumeRun":
|
|
1783
|
-
|
|
1784
|
-
|
|
2649
|
+
case "resumeRun": {
|
|
2650
|
+
// A workflow run's pause or resume is a command its runner reads and applies (runs-over-store.pauseOrResume): an
|
|
2651
|
+
// agentic run has none (501, its turn is stopped instead), an ended or cancelling one takes none (409). The route
|
|
2652
|
+
// adds the run's status from its view.
|
|
1785
2653
|
const run = await needRun(id);
|
|
1786
|
-
await
|
|
1787
|
-
|
|
2654
|
+
const { paused } = await (found.name === "pauseRun" ? pauseRunOverStore : resumeRunOverStore)(store, run);
|
|
2655
|
+
const { status } = await runStatusState(run.id);
|
|
2656
|
+
return send(res, 200, { run_id: run.id, paused, status });
|
|
2657
|
+
}
|
|
2658
|
+
case "readRunFile": {
|
|
2659
|
+
await needRun(id);
|
|
2660
|
+
// One of a run's files through the server's read-only Workspace, streamed as the file route streams it; a withheld
|
|
2661
|
+
// run refuses (403, as filesShown did), the path check and 404 words are the reader's own.
|
|
2662
|
+
return readRunFileOverStore(store, id, second, req, res, url, runReadsDeps);
|
|
1788
2663
|
}
|
|
1789
2664
|
case "createFile": {
|
|
1790
2665
|
// A `path` in the query, or a body that is not JSON: the file sent in one call, its bytes the body. Else the
|
|
@@ -1826,15 +2701,19 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1826
2701
|
return send(res, 200, await usage(url));
|
|
1827
2702
|
case "getStats": {
|
|
1828
2703
|
const filter = analyticsFilter(url);
|
|
1829
|
-
//
|
|
1830
|
-
//
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
2704
|
+
// The store's counts and cost sums (store-reads/stats), the runs' metrics summed (store-reads/analytics), and the
|
|
2705
|
+
// runs over the store for the learning counts. No in-process pending set and no held Runs: the runner writes a
|
|
2706
|
+
// run's end to the store before it lets it go.
|
|
2707
|
+
const [s, a] = await Promise.all([statsOverStore(store), analyticsOverStore(store, { ...filter })]);
|
|
2708
|
+
// Each running row's status over the store (viewOverStore), for the active/needs_input/unknown buckets.
|
|
2709
|
+
const vd = viewDepsFor(ownOriginOf());
|
|
2710
|
+
const runningStatus = new Map();
|
|
2711
|
+
await Promise.all(s.running.map(async (id) => { const v = await viewOverStore(store, id, vd); if (v?.status)
|
|
2712
|
+
runningStatus.set(id, v.status); }));
|
|
2713
|
+
// How the runs that tried to learn fared, over the store (learning-1's learningCountsOverStore): the same figures the
|
|
2714
|
+
// ledger gave, run for run; no held run's learning from memory.
|
|
2715
|
+
const learning = await learningCountsOverStore(store, filter);
|
|
2716
|
+
return send(res, 200, { ...statsView(s, (id) => runningStatus.get(id)), analytics: analyticsView(a, filter), learning });
|
|
1838
2717
|
}
|
|
1839
2718
|
case "listToolKeys":
|
|
1840
2719
|
// The offers the server holds, not capabilities': a model key's row names the harnesses its key would run too.
|
|
@@ -1848,27 +2727,73 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1848
2727
|
// directory and its keys by now.
|
|
1849
2728
|
if (stopping.signal.aborted)
|
|
1850
2729
|
throw new ApiError("unavailable", "The server is shutting down: the key was not saved.");
|
|
1851
|
-
toolKeys.save(id, body, check);
|
|
2730
|
+
await toolKeys.save(id, body, check);
|
|
1852
2731
|
await keysChanged();
|
|
1853
2732
|
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1854
2733
|
}
|
|
1855
2734
|
case "deleteToolKey":
|
|
1856
|
-
toolKeys.remove(id);
|
|
2735
|
+
await toolKeys.remove(id);
|
|
1857
2736
|
await keysChanged();
|
|
1858
2737
|
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1859
2738
|
// Never through `idempotent`: its record keeps the body, and a body may hold a credential.
|
|
1860
2739
|
case "listMcpServers":
|
|
1861
|
-
return send(res, 200, mcpServers.list());
|
|
2740
|
+
return send(res, 200, await mcpServers.list());
|
|
1862
2741
|
case "getMcpServer":
|
|
1863
|
-
return send(res, 200, mcpServers.get(id));
|
|
2742
|
+
return send(res, 200, await mcpServers.get(id));
|
|
1864
2743
|
case "previewMcpServer":
|
|
1865
2744
|
return send(res, 200, await mcpServers.preview(await bodyOf(req), stopping.signal));
|
|
1866
|
-
case "saveMcpServer":
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
return send(res, 200,
|
|
2745
|
+
case "saveMcpServer": {
|
|
2746
|
+
const saved = await mcpServers.save(id, await bodyOf(req), stopping.signal, secretSeen);
|
|
2747
|
+
await refreshMcpMeta();
|
|
2748
|
+
return send(res, 200, saved);
|
|
2749
|
+
}
|
|
2750
|
+
case "refreshMcpServer": {
|
|
2751
|
+
const refreshed = await mcpServers.refresh(id, stopping.signal);
|
|
2752
|
+
await refreshMcpMeta();
|
|
2753
|
+
return send(res, 200, refreshed);
|
|
2754
|
+
}
|
|
2755
|
+
case "startMcpOAuth": {
|
|
2756
|
+
// The cookie is set on the address the request came to, and the authorization server sends the browser back
|
|
2757
|
+
// to the callback's: they must be the one origin, or the callback never sees the cookie. The redirect URI
|
|
2758
|
+
// stays that one address (a registered client names it), and a start from another answers where to go.
|
|
2759
|
+
const origin = mcpServers.callbackOrigin;
|
|
2760
|
+
if (ownOrigin(req) !== origin)
|
|
2761
|
+
throw new ApiError("wrong_origin", `This server's sign-in comes back to ${origin}, and finishes only in a browser that started it there: open the console at ${origin}${MCP_SETTINGS_PAGE} and sign in from it.`, { details: { open: `${origin}${MCP_SETTINGS_PAGE}` } });
|
|
2762
|
+
const started = await mcpServers.oauthStart(id, await bodyOf(req));
|
|
2763
|
+
const state = new URL(started.authorization_url).searchParams.get("state") ?? "";
|
|
2764
|
+
return send(res, 200, started, { "set-cookie": signInCookie(req.socket.localPort, state, overHttps(req)) });
|
|
2765
|
+
}
|
|
2766
|
+
case "connectGitHub": {
|
|
2767
|
+
const started = githubConnect.start(await bodyOf(req), ownOrigin(req));
|
|
2768
|
+
// The callback finishes only in this browser: the cookie it brings back names this state.
|
|
2769
|
+
return send(res, 200, started, { "set-cookie": stateCookie(req.socket.localPort, started.state, overHttps(req)) });
|
|
2770
|
+
}
|
|
2771
|
+
case "getGitHubConnection": {
|
|
2772
|
+
// Repaired from GitHub's own first, at most once a minute: a missed installation event is put right here.
|
|
2773
|
+
await githubConnect.reconcile((detail) => triggers.turnOff("github", detail));
|
|
2774
|
+
// Always a 200: not connected is an answer, never an error a browser logs as one.
|
|
2775
|
+
const view = githubConnection();
|
|
2776
|
+
return send(res, 200, view ? { connected: true, ...view } : { connected: false });
|
|
2777
|
+
}
|
|
2778
|
+
case "disconnectGitHub": {
|
|
2779
|
+
const view = githubConnection();
|
|
2780
|
+
if (!view)
|
|
2781
|
+
throw new ApiError("not_found", "No GitHub App is connected to this server.");
|
|
2782
|
+
const settingsUrl = github.settingsUrl();
|
|
2783
|
+
// Awaited: the App's rows go before the answer, so a Connect right after never races their removal.
|
|
2784
|
+
await github.remove();
|
|
2785
|
+
// Kept, and off: an agent keeps its triggers, which go on again once GitHub is connected again.
|
|
2786
|
+
const off = await triggers.turnOff("github", "GitHub was disconnected from this server: connect it again in Settings, then turn the trigger on.");
|
|
2787
|
+
log?.(logLine("github", { condition: "github_disconnected", app_id: view.app_id, triggers_off: off }));
|
|
2788
|
+
return send(res, 200, { disconnected: true, triggers_off: off, note: `Delete the App itself on GitHub: ${settingsUrl}` });
|
|
2789
|
+
}
|
|
2790
|
+
case "getMcpPrivateHosts":
|
|
2791
|
+
return send(res, 200, await privateHostsRoute(mcpServers, { method: "GET" }), { "cache-control": "no-store" });
|
|
2792
|
+
case "putMcpPrivateHosts":
|
|
2793
|
+
return send(res, 200, await privateHostsRoute(mcpServers, { method: "PUT", body: () => bodyOf(req) }), { "cache-control": "no-store" });
|
|
1870
2794
|
case "deleteMcpServer":
|
|
1871
|
-
mcpServers.remove(id);
|
|
2795
|
+
await mcpServers.remove(id, secretSeen);
|
|
2796
|
+
await refreshMcpMeta();
|
|
1872
2797
|
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1873
2798
|
case "getToolSettings":
|
|
1874
2799
|
return send(res, 200, withDefaults(settings.get()));
|
|
@@ -1879,7 +2804,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1879
2804
|
const issues = settingsIssues(body);
|
|
1880
2805
|
if (issues.length)
|
|
1881
2806
|
throw invalid(issues);
|
|
1882
|
-
settings.put(body);
|
|
2807
|
+
await settings.put(body);
|
|
1883
2808
|
// A setting changes what the web tools resolve to, never env or what a harness offers: capabilities again.
|
|
1884
2809
|
recompose();
|
|
1885
2810
|
return send(res, 200, withDefaults(settings.get()));
|
|
@@ -1888,41 +2813,56 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1888
2813
|
// they are now; a write as the definition's: an archived agent's too.
|
|
1889
2814
|
case "getAgentLearning": {
|
|
1890
2815
|
await needAgent(id);
|
|
1891
|
-
|
|
1892
|
-
//
|
|
1893
|
-
//
|
|
1894
|
-
const { counts, impact } = await
|
|
1895
|
-
return send(res, 200, await agentLearning(data, id, secretsShown(
|
|
2816
|
+
// The agent's learning view: its notes, skills, workflows and log from its learning folder; its run-fared counts, each
|
|
2817
|
+
// note's runs (given it and that read it) and its impact over the one store (agentLearningOverStore), from each run's
|
|
2818
|
+
// launch, journal and learning end.
|
|
2819
|
+
const { counts, impact, notes } = await agentLearningOverStore(store, id);
|
|
2820
|
+
return send(res, 200, await agentLearning(data, id, secretsShown(serverSecrets()), counts, impact, notes));
|
|
1896
2821
|
}
|
|
1897
2822
|
case "listLearningNotes":
|
|
1898
2823
|
case "listLearningLog":
|
|
1899
2824
|
await needAgent(id);
|
|
1900
|
-
|
|
2825
|
+
if (found.name === "listLearningNotes") {
|
|
2826
|
+
// The notes from the agent's learning folder, each with its runs over the one store (agentLearningOverStore's noteRuns).
|
|
2827
|
+
const { notes } = await agentLearningOverStore(store, id);
|
|
2828
|
+
return send(res, 200, await learningNotes(data, id, url.searchParams, secretsShown(serverSecrets()), notes));
|
|
2829
|
+
}
|
|
2830
|
+
return send(res, 200, await learningLog(data, id, url.searchParams, secretsShown(serverSecrets())));
|
|
1901
2831
|
case "readLearningFile":
|
|
1902
2832
|
await needAgent(id);
|
|
1903
|
-
return sendNote(res, 200, await readNote(data, id, second, secretsShown(
|
|
2833
|
+
return sendNote(res, 200, await readNote(data, id, second, secretsShown(serverSecrets())));
|
|
1904
2834
|
case "writeLearningFile":
|
|
1905
2835
|
case "retireLearningFile":
|
|
1906
|
-
case "approveLearningFile":
|
|
2836
|
+
case "approveLearningFile":
|
|
2837
|
+
case "restoreLearningFile": {
|
|
1907
2838
|
await needAgent(id);
|
|
1908
2839
|
const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
|
|
1909
2840
|
const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
|
|
1910
|
-
const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse:
|
|
2841
|
+
const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: serverSecrets(), approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile", draftTools: () => learnedDraftToolsOf(id) });
|
|
1911
2842
|
// A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
|
|
1912
|
-
const shown = secretsShown(
|
|
2843
|
+
const shown = secretsShown(serverSecrets());
|
|
1913
2844
|
const located = written.status === 201 && shown.name(written.file) === written.file;
|
|
1914
2845
|
return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
|
|
1915
2846
|
}
|
|
1916
|
-
case "getRunLearning":
|
|
1917
|
-
|
|
2847
|
+
case "getRunLearning": {
|
|
2848
|
+
const run = await needRun(id);
|
|
2849
|
+
// The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
|
|
2850
|
+
// from its launch, what it holds for the owner's OK as the store's run view reads it (no folder), byte-identical to main.
|
|
2851
|
+
// Cut by the run's one cut, and refused for a withheld run (run-learning-served.ts).
|
|
2852
|
+
return send(res, 200, await servedRunLearning({ serverSecrets, signIns }, store, run.id));
|
|
2853
|
+
}
|
|
1918
2854
|
case "getRunLearningDiff":
|
|
1919
|
-
|
|
2855
|
+
await needRun(id);
|
|
2856
|
+
// TODO(learning-1): the run's learning diff over the store — learning-1's diff read on untangle/cutover-switch-learn, not the run's
|
|
2857
|
+
// .learning/diffs files. Wire when its head lands.
|
|
2858
|
+
return runReadsTodo();
|
|
1920
2859
|
case "getWebhook":
|
|
1921
2860
|
return send(res, 200, webhooks.view());
|
|
1922
2861
|
case "saveWebhook": {
|
|
1923
2862
|
// Never through `idempotent`: its record would keep the answer, and the first one holds the secret.
|
|
2863
|
+
// Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets its metadata and the words.
|
|
1924
2864
|
const saved = webhooks.save(await bodyOf(req));
|
|
1925
|
-
return send(res, saved.created ? 201 : 200,
|
|
2865
|
+
return send(res, saved.created ? 201 : 200, webhookSaved(saved.view, saved.secret, mayHoldSecrets(req)));
|
|
1926
2866
|
}
|
|
1927
2867
|
case "deleteWebhook":
|
|
1928
2868
|
webhooks.remove();
|
|
@@ -1934,7 +2874,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1934
2874
|
case "redeliverWebhook":
|
|
1935
2875
|
return send(res, 200, await webhooks.redeliver(id));
|
|
1936
2876
|
case "listTriggers":
|
|
1937
|
-
return send(res, 200, triggers.list());
|
|
2877
|
+
return send(res, 200, { triggers: (await triggers.list()).triggers.map(withSecretOf) });
|
|
1938
2878
|
case "createTrigger": {
|
|
1939
2879
|
const body = await bodyOf(req);
|
|
1940
2880
|
// A webhook trigger's secret is in its first answer alone: the Idempotency-Key's record keeps the trigger and a
|
|
@@ -1947,16 +2887,39 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1947
2887
|
});
|
|
1948
2888
|
const replayed = answer.headers?.["idempotent-replayed"] === "true";
|
|
1949
2889
|
const { note: _, ...first } = answer.body;
|
|
1950
|
-
|
|
2890
|
+
// Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets secret_set and the words.
|
|
2891
|
+
return send(res, answer.status, secret && !replayed ? triggerMade(first, secret, mayHoldSecrets(req), new Date().toISOString()) : answer.body, answer.headers);
|
|
2892
|
+
}
|
|
2893
|
+
case "listTemplates":
|
|
2894
|
+
return send(res, 200, { templates: templates.map(packageView) });
|
|
2895
|
+
case "applyTemplate": {
|
|
2896
|
+
const pkg = templates.find((t) => t.name === id);
|
|
2897
|
+
if (!pkg)
|
|
2898
|
+
throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
|
|
2899
|
+
const body = await bodyOf(req);
|
|
2900
|
+
// The Idempotency-Key's record keeps the agent and triggers, so a retry under the key gets the same apply; it never
|
|
2901
|
+
// keeps a webhook trigger's secret (below).
|
|
2902
|
+
let minted = new Map();
|
|
2903
|
+
const answer = await idempotent(req, `/templates/${pkg.name}/apply`, body, async () => {
|
|
2904
|
+
const made = await applyTemplate(pkg, body);
|
|
2905
|
+
minted = made.minted;
|
|
2906
|
+
return { status: 201, body: made.applied, headers: { location: `/v2/agents/${made.applied.agent_id}` } };
|
|
2907
|
+
});
|
|
2908
|
+
// Each webhook trigger's secret, to the owner's session in this first answer alone (trigger-secrets-shown.ts
|
|
2909
|
+
// templateApplied): the record above never held it, so a replay under the key shows none.
|
|
2910
|
+
const replayed = answer.headers?.["idempotent-replayed"] === "true";
|
|
2911
|
+
const shown = replayed ? "replay" : mayHoldSecrets(req) ? "first" : "token";
|
|
2912
|
+
return send(res, answer.status, answer.status === 201 ? templateApplied(answer.body, minted, shown) : answer.body, answer.headers);
|
|
1951
2913
|
}
|
|
1952
2914
|
case "rotateTriggerSecret":
|
|
1953
|
-
|
|
2915
|
+
// A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
|
|
2916
|
+
return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
|
|
1954
2917
|
case "getTrigger":
|
|
1955
|
-
return send(res, 200, triggers.get(id));
|
|
2918
|
+
return send(res, 200, withSecretOf(await triggers.get(id)));
|
|
1956
2919
|
case "updateTrigger":
|
|
1957
2920
|
return send(res, 200, await triggers.update(id, await bodyOf(req)));
|
|
1958
2921
|
case "deleteTrigger":
|
|
1959
|
-
triggers.remove(id);
|
|
2922
|
+
await triggers.remove(id);
|
|
1960
2923
|
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1961
2924
|
case "fireTrigger": {
|
|
1962
2925
|
const key = req.headers["idempotency-key"];
|
|
@@ -1966,7 +2929,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1966
2929
|
return send(res, fired.created ? 202 : 200, fired.firing, fired.created ? {} : { "idempotent-replayed": "true" });
|
|
1967
2930
|
}
|
|
1968
2931
|
case "listTriggerFirings":
|
|
1969
|
-
return send(res, 200, triggers.firings(id));
|
|
2932
|
+
return send(res, 200, await triggers.firings(id));
|
|
1970
2933
|
}
|
|
1971
2934
|
throw new ApiError("not_found", `no route ${path}`);
|
|
1972
2935
|
}
|
|
@@ -1977,6 +2940,35 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1977
2940
|
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
|
|
1978
2941
|
res.end(text);
|
|
1979
2942
|
}
|
|
2943
|
+
/** A run's live viewer's page and files (browser-live.ts, /v2/runs/{id}/computer/live/*): the owner's signed-in page
|
|
2944
|
+
* alone, GET or HEAD, for a viewer the run's live process has handed over. The bytes are this server's own copy of pi-browser's viewer, never the run's port's:
|
|
2945
|
+
* only the viewer's WebSocket reaches the run. */
|
|
2946
|
+
async function liveRoute(req, res, runId, family, rest) {
|
|
2947
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
2948
|
+
throw new ApiError("method_not_allowed", `${req.method} is not a method of a run's live view`, {}, { allow: "GET, HEAD" });
|
|
2949
|
+
if (!byOwnerSession(req)) {
|
|
2950
|
+
authFailed(`/v2/runs/${runId}/${family}/live`, req.headers.authorization === undefined ? "no_credential" : `${family}_without_session`);
|
|
2951
|
+
throw req.headers.authorization === undefined ? new ApiError("unauthenticated", `a run's live ${family} view takes the owner's password sign-in in the console`) : new ApiError("forbidden", `a run's live ${family} view takes the owner's password sign-in in the console, never a token`);
|
|
2952
|
+
}
|
|
2953
|
+
await needRun(runId);
|
|
2954
|
+
// The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim; liveViewerFor picks
|
|
2955
|
+
// a named viewer's handover or the run's open one). None for a run no runner holds; with no seal key this server serves
|
|
2956
|
+
// no live view. A /computer/live path reaches a viewer of every kind (the link GET /computer gives, a browser's among
|
|
2957
|
+
// them), a /browser/live path a browser's alone (familyReaches).
|
|
2958
|
+
const handover = sealKey ? await liveViewerFor(store, sealKey, runId, rest) : undefined;
|
|
2959
|
+
if (handover === undefined || !familyReaches(family, handover))
|
|
2960
|
+
throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
|
|
2961
|
+
await serveViewerFile(req, res, rest);
|
|
2962
|
+
}
|
|
2963
|
+
/** The origin of the address people open (`publicUrl`, AGENTRUN_PUBLIC_URL), lowercased; none, undefined. */
|
|
2964
|
+
const publicOrigin = (() => {
|
|
2965
|
+
try {
|
|
2966
|
+
return options.publicUrl ? new URL(options.publicUrl).origin.toLowerCase() : undefined;
|
|
2967
|
+
}
|
|
2968
|
+
catch {
|
|
2969
|
+
return undefined;
|
|
2970
|
+
}
|
|
2971
|
+
})();
|
|
1980
2972
|
let names;
|
|
1981
2973
|
const server = createServer((req, res) => {
|
|
1982
2974
|
const requestId = `req_${randomBytes(8).toString("hex")}`;
|
|
@@ -1990,6 +2982,9 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1990
2982
|
const fail = (error) => {
|
|
1991
2983
|
if (res.headersSent)
|
|
1992
2984
|
return void res.end();
|
|
2985
|
+
// A request cut before its body was read (push-handler.ts readCapped): its socket goes once the answer is out.
|
|
2986
|
+
if (error instanceof HookCut)
|
|
2987
|
+
res.once("finish", () => req.socket.destroy());
|
|
1993
2988
|
// A store still busy past a request's wait is home_busy, whichever read or write met it.
|
|
1994
2989
|
const known = error instanceof ApiError ? error : storeBusy(error) ? homeBusy() : new ApiError("internal", error?.message ?? String(error));
|
|
1995
2990
|
if (!(error instanceof ApiError) && !storeBusy(error))
|
|
@@ -2003,9 +2998,13 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
2003
2998
|
catch {
|
|
2004
2999
|
return fail(new ApiError("bad_request", "the request target is not a URL"));
|
|
2005
3000
|
}
|
|
2006
|
-
// On loopback, a Host that is not
|
|
2007
|
-
|
|
2008
|
-
|
|
3001
|
+
// On loopback, a Host that is not one of its names (host-check.ts) is a page that rebound a name of its own to this
|
|
3002
|
+
// address. A browser is shown a page that says which names work; a script, the same in the error.
|
|
3003
|
+
if (names && !names.has(hostName(req.headers.host) ?? "")) {
|
|
3004
|
+
if (/\btext\/html\b/i.test(String(req.headers.accept ?? "")))
|
|
3005
|
+
return sendHostRefused(req, res);
|
|
3006
|
+
return fail(new ApiError("forbidden", `unexpected Host header: ${hostFix(req.socket.localPort ?? 0)}`));
|
|
3007
|
+
}
|
|
2009
3008
|
// Routed on the path as sent: a parsed URL folds `..` and `%2E%2E` segments away, and a file path must see them.
|
|
2010
3009
|
const raw = (req.url ?? "/").split("?")[0];
|
|
2011
3010
|
// Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
|
|
@@ -2015,12 +3014,74 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
2015
3014
|
return void mcp(req, res).catch(fail);
|
|
2016
3015
|
if (raw === "/llms.txt")
|
|
2017
3016
|
return void answerLlms(req, res).catch(fail);
|
|
2018
|
-
if (answerPage(req, res, raw, { token, dir: data, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}) }))
|
|
3017
|
+
if (answerPage(req, res, raw, { token, dir: data, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
|
|
3018
|
+
return;
|
|
3019
|
+
// Under --faux only: a faux desktop's live view, a page on this server's own address (faux-computers.ts viewPage), so
|
|
3020
|
+
// a run's take-over has a viewer to open in the console's real-browser flows. Gone after the computer's release.
|
|
3021
|
+
if (options.faux && raw.startsWith(`${FAUX_VIEW_PATH}/`)) {
|
|
3022
|
+
const page = fauxOf().viewPage(raw);
|
|
3023
|
+
if (page === undefined)
|
|
3024
|
+
return fail(new ApiError("not_found", `no faux desktop at ${raw}`));
|
|
3025
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(req.method === "HEAD" ? undefined : page);
|
|
2019
3026
|
return;
|
|
3027
|
+
}
|
|
2020
3028
|
if (!raw.startsWith("/v2/"))
|
|
2021
3029
|
return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
|
|
3030
|
+
// A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
|
|
3031
|
+
// decoded here, where a throw would leave the request listener.
|
|
3032
|
+
const viewing = LIVE_PATH.exec(raw);
|
|
3033
|
+
if (viewing)
|
|
3034
|
+
return ID.test(viewing[1]) ? void liveRoute(req, res, viewing[1], viewing[2], viewing[3]).catch(fail) : fail(new ApiError("not_found", "no run's live view at that address"));
|
|
2022
3035
|
route(req, res, url, raw.slice(3)).catch(fail);
|
|
2023
3036
|
});
|
|
3037
|
+
// A request's headers come within 10 s, whatever its route: nothing sends more than a few kilobytes of them. Its body
|
|
3038
|
+
// keeps Node's 5-minute request timeout, which an upload of a large file needs; the token-less hook route has its own
|
|
3039
|
+
// 30 s for its body (push-handler.ts HOOK_BODY_MS), so dribbling senders hold no socket for long.
|
|
3040
|
+
server.headersTimeout = 10_000;
|
|
3041
|
+
// The one upgrade this server takes: a run's live computer viewer's WebSocket (browser-live.ts). Every other is refused.
|
|
3042
|
+
server.on("upgrade", (req, socket, head) => {
|
|
3043
|
+
socket.on("error", () => socket.destroy());
|
|
3044
|
+
const raw = (req.url ?? "/").split("?")[0];
|
|
3045
|
+
const viewing = LIVE_PATH.exec(raw);
|
|
3046
|
+
const deny = (status) => void socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
3047
|
+
// On loopback, the Host check every route gets (host-check.ts), first: a page that rebound a name of its own to this
|
|
3048
|
+
// address sends its own name as Origin too, which the Origin check below would take, so its Host is what gives it
|
|
3049
|
+
// away. Its name alone, on any port, as the HTTP routes check it.
|
|
3050
|
+
if (names && !names.has(hostName(req.headers.host) ?? ""))
|
|
3051
|
+
return deny("403 Forbidden");
|
|
3052
|
+
if (!viewing || !ID.test(viewing[1]) || !/^\/v\/[A-Za-z0-9_-]{22}\/ws$/.test(viewing[3]))
|
|
3053
|
+
return deny("404 Not Found");
|
|
3054
|
+
// A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
|
|
3055
|
+
// (as this request reaches it, or its public address, which a TLS proxy that rewrites Host or drops
|
|
3056
|
+
// X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing.
|
|
3057
|
+
const sent = String(req.headers.origin ?? "").toLowerCase();
|
|
3058
|
+
if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
|
|
3059
|
+
return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
|
|
3060
|
+
if (!owner || !signedIn(req, owner))
|
|
3061
|
+
return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
|
|
3062
|
+
// Once the run's WebSocket is piped to this socket, a failure here only ends it: an HTTP line would land mid-stream.
|
|
3063
|
+
let piping = false;
|
|
3064
|
+
void (async () => {
|
|
3065
|
+
const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
|
|
3066
|
+
// The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
|
|
3067
|
+
// runner holds; with no seal key no live view is served. A /computer/live socket reaches a viewer of every kind, a
|
|
3068
|
+
// /browser/live socket a browser's alone (familyReaches), as the page does.
|
|
3069
|
+
const viewerHandover = run && sealKey ? await liveViewerById(store, sealKey, run.id, viewing[3].slice(3, -3)) : undefined;
|
|
3070
|
+
const handover = viewerHandover !== undefined && familyReaches(viewing[2], viewerHandover) ? viewerHandover : undefined;
|
|
3071
|
+
if (!handover)
|
|
3072
|
+
return deny("404 Not Found");
|
|
3073
|
+
// Gone during the lookup, or the server is closing and has ended its viewers, or is about to.
|
|
3074
|
+
if (socket.destroyed || closing)
|
|
3075
|
+
return void socket.destroy();
|
|
3076
|
+
// Checked again after the lookup, then for as long as the socket is open: the sessions that let it in, and no other.
|
|
3077
|
+
const held = heldSessions(req);
|
|
3078
|
+
const admitted = () => held.some((value) => owner.valid(value));
|
|
3079
|
+
if (!admitted())
|
|
3080
|
+
return deny("401 Unauthorized");
|
|
3081
|
+
viewers.watch(socket, admitted);
|
|
3082
|
+
proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; });
|
|
3083
|
+
})().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
|
|
3084
|
+
});
|
|
2024
3085
|
const first = options.port ?? DEFAULT_PORT;
|
|
2025
3086
|
const last = options.nextFreePort && first !== 0 ? Math.min(first + 99, 65_535) : first;
|
|
2026
3087
|
for (let port = first;; port++) {
|
|
@@ -2055,33 +3116,133 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
2055
3116
|
countSessions();
|
|
2056
3117
|
const address = server.address();
|
|
2057
3118
|
if (isLoopback(host))
|
|
2058
|
-
names =
|
|
3119
|
+
names = loopbackNames(host, options.allowHosts, options.publicUrl);
|
|
2059
3120
|
// An address of every interface is reached on this machine at its loopback one.
|
|
2060
3121
|
const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
|
|
2061
3122
|
const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
|
|
2062
3123
|
owner?.attach(options.publicUrl ?? url);
|
|
2063
3124
|
webhooks.attach(options.publicUrl ?? url);
|
|
3125
|
+
mcpServers.attach(options.publicUrl ?? url, url);
|
|
3126
|
+
// A run's end and its wait are the outbound webhook's run.ended and run.needs_input (webhooks.ts). The runners write them
|
|
3127
|
+
// to the store and this server runs no run, so it follows the store: each read takes the runs not final yet and the
|
|
3128
|
+
// newest runs (one that started and ended between two reads is among them). It tells each end it has not told once the
|
|
3129
|
+
// run reads final, and each wait of a run a runner left parked (or let go of) once it reads input_required. The markers
|
|
3130
|
+
// are main's (an end's time, a wait's last row), so each webhook-id is the one it always had, and the ledger tells each
|
|
3131
|
+
// once across restarts; a start first catches up the ends the ledger lacks, which no server was up to see. A store read
|
|
3132
|
+
// of the runs ended (or parked) since a mark would be the cleaner seam than this read of the open runs every 250 ms.
|
|
3133
|
+
const RUN_ENDS_POLL_MS = 250;
|
|
3134
|
+
const RUN_ENDS_NEWEST = 50;
|
|
3135
|
+
const final = (row) => FINAL_STATES.includes(row.state);
|
|
3136
|
+
const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}) });
|
|
3137
|
+
/** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
|
|
3138
|
+
const endNotice = async (id) => {
|
|
3139
|
+
const row = await store.runs.get(id);
|
|
3140
|
+
const summary = row && (await summaryOverStore(store, id, viewDepsFor(ownOriginOf())));
|
|
3141
|
+
if (!row || !summary)
|
|
3142
|
+
return null;
|
|
3143
|
+
return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
|
|
3144
|
+
};
|
|
3145
|
+
const toldEnds = new Map();
|
|
3146
|
+
/** Each waiting run's row as it was last read for its wait (its state, epoch and runner): a row that has not moved since
|
|
3147
|
+
* is not read again, and a new wait comes with a new claim, so a new epoch. */
|
|
3148
|
+
const readWaits = new Map();
|
|
3149
|
+
/** When each held wait (a run waiting on its person with its claim held) was last read again. */
|
|
3150
|
+
const heldReadAt = new Map();
|
|
3151
|
+
const HELD_WAIT_REREAD_MS = 1_000;
|
|
3152
|
+
const waitKinds = new Set(["question", "approval", "budget", "browser"]);
|
|
3153
|
+
/** The wait of a run its runner left parked (or let go of), told once as main told it: its marker the run's last row
|
|
3154
|
+
* that shows (not usage, a phase or learning's), its kind the pending card's (a stop's when it waits on no card). */
|
|
3155
|
+
const tellWait = async (row) => {
|
|
3156
|
+
const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
|
|
3157
|
+
if (readWaits.get(row.id) === seen)
|
|
3158
|
+
return;
|
|
3159
|
+
const view = await viewOverStore(store, row.id, viewDepsFor(ownOriginOf()));
|
|
3160
|
+
if (view?.status !== "input_required")
|
|
3161
|
+
return void readWaits.set(row.id, seen);
|
|
3162
|
+
const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
|
|
3163
|
+
const marker = rows.findLast((r) => r.kind !== "usage" && r.kind !== "phase" && r.agent_label !== LEARNING_LABEL)?.id;
|
|
3164
|
+
if (!marker)
|
|
3165
|
+
return void readWaits.set(row.id, seen);
|
|
3166
|
+
const card = view.pending?.kind;
|
|
3167
|
+
const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
|
|
3168
|
+
const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: { kind } };
|
|
3169
|
+
if (webhooks.emit("run.needs_input", notice, marker) !== "unsaved")
|
|
3170
|
+
readWaits.set(row.id, seen);
|
|
3171
|
+
};
|
|
3172
|
+
let openRuns = new Set();
|
|
3173
|
+
let endsTimer;
|
|
3174
|
+
let endsRead = Promise.resolve();
|
|
3175
|
+
const readEnds = async () => {
|
|
3176
|
+
const open = new Set();
|
|
3177
|
+
for (const state of ["queued", "running", "parked"]) {
|
|
3178
|
+
for (const row of await store.runs.list({ state })) {
|
|
3179
|
+
open.add(row.id);
|
|
3180
|
+
// A run waits on its person once its runner has let it go: parked, or running with no runner. Or held in its claim
|
|
3181
|
+
// waiting on its person (ask_person with its browser open, adapter-loop waitInClaim; or its browser hand-over,
|
|
3182
|
+
// tools.ts), which its row's summary says (HELD_WAITS); a new ask sets it anew, so each is read and told once.
|
|
3183
|
+
const waitsInClaim = row.state === "running" && row.runner !== null && row.summary !== null && HELD_WAITS.has(row.summary);
|
|
3184
|
+
// A held run's next ask in the same claim reads the same row as its last (state, epoch, runner, summary), and the
|
|
3185
|
+
// answer between may come and go within one read: so a held wait is read again now and then (HELD_WAIT_REREAD_MS),
|
|
3186
|
+
// and told once per ask all the same, since each ask's notice is keyed to its own last row (webhooks.ts emit).
|
|
3187
|
+
if (waitsInClaim && Date.now() - (heldReadAt.get(row.id) ?? 0) >= HELD_WAIT_REREAD_MS) {
|
|
3188
|
+
heldReadAt.set(row.id, Date.now());
|
|
3189
|
+
readWaits.delete(row.id);
|
|
3190
|
+
}
|
|
3191
|
+
if (!closing && (row.state === "parked" || (row.state === "running" && row.runner === null) || waitsInClaim))
|
|
3192
|
+
await tellWait(row).catch(() => undefined);
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
const newest = await store.runs.list({ limit: RUN_ENDS_NEWEST });
|
|
3196
|
+
for (const id of new Set([...openRuns, ...newest.map((row) => row.id)])) {
|
|
3197
|
+
if (open.has(id) || closing)
|
|
3198
|
+
continue;
|
|
3199
|
+
const now = await endNotice(id).catch(() => undefined);
|
|
3200
|
+
// Unread (a busy store): read again at the next turn, never lost.
|
|
3201
|
+
if (now === undefined) {
|
|
3202
|
+
open.add(id);
|
|
3203
|
+
continue;
|
|
3204
|
+
}
|
|
3205
|
+
readWaits.delete(id);
|
|
3206
|
+
heldReadAt.delete(id);
|
|
3207
|
+
if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
|
|
3208
|
+
continue;
|
|
3209
|
+
if (webhooks.emit("run.ended", now.notice, now.endedAt) !== "unsaved")
|
|
3210
|
+
toldEnds.set(id, now.endedAt);
|
|
3211
|
+
}
|
|
3212
|
+
openRuns = open;
|
|
3213
|
+
};
|
|
3214
|
+
const followEnds = () => {
|
|
3215
|
+
if (closing)
|
|
3216
|
+
return;
|
|
3217
|
+
endsRead = readEnds()
|
|
3218
|
+
.catch((error) => log?.(logLine("webhook", { condition: "run_ends_unread", error: error.message })))
|
|
3219
|
+
.finally(() => {
|
|
3220
|
+
if (!closing)
|
|
3221
|
+
(endsTimer = setTimeout(followEnds, RUN_ENDS_POLL_MS)).unref();
|
|
3222
|
+
});
|
|
3223
|
+
};
|
|
3224
|
+
void store.runs
|
|
3225
|
+
.list({})
|
|
3226
|
+
.then((rows) => webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), endNotice))
|
|
3227
|
+
.catch((error) => log?.(logLine("webhook", { condition: "catch_up_unread", error: error.message })))
|
|
3228
|
+
.finally(followEnds);
|
|
2064
3229
|
const setupUrl = owner && !owner.hasPassword() ? owner.setupLink() : undefined;
|
|
2065
3230
|
/** The server's stop: once (`close` keeps its promise). */
|
|
2066
3231
|
let stopped;
|
|
2067
3232
|
async function stop() {
|
|
2068
|
-
//
|
|
2069
|
-
//
|
|
2070
|
-
//
|
|
2071
|
-
|
|
2072
|
-
try {
|
|
2073
|
-
markStopping(data, Date.now() + boundMs + STOP_MARGIN_MS);
|
|
2074
|
-
}
|
|
2075
|
-
catch (error) {
|
|
2076
|
-
const fields = { reason: error.code ?? error.message };
|
|
2077
|
-
void (log ? log(logLine("stopping_mark_unwritten", fields)) : process.stderr.write(`agentrun-serve: ${logLine("stopping_mark_unwritten", fields)}\n`));
|
|
2078
|
-
}
|
|
2079
|
-
if (busy > 0)
|
|
2080
|
-
noticeOf(options)(`stopping: waiting up to ${seconds(boundMs)} for ${busy === 1 ? "1 run to finish its turn" : `${busy} runs to finish their turn`}`);
|
|
2081
|
-
// An import under way stops between two session files and is waited for: nothing writes the store after close. A
|
|
2082
|
-
// count writes nothing (it lists and reads), so it is ended at once: its listing of a big home checks for no stop.
|
|
3233
|
+
// The server writes rows and a runner (its own process) runs every run, so this stop drains no run process and writes
|
|
3234
|
+
// no "stopping" mark for a start to wait on: the store's EXCLUSIVE lock is this server's one-server lock, released as
|
|
3235
|
+
// the store closes, and the next server takes it. The deliveries, the import, the installs and the listener stop first;
|
|
3236
|
+
// the store closes last.
|
|
2083
3237
|
closing = true;
|
|
2084
3238
|
stopping.abort();
|
|
3239
|
+
// A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
|
|
3240
|
+
const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
|
|
3241
|
+
// Aborted now, so nothing it writes races the next server on the same refresh token; drained before the store closes.
|
|
3242
|
+
const mcpStopped = mcpServers.close();
|
|
3243
|
+
// A repair of the GitHub installations under way stops waiting on GitHub and writes nothing from here: before the
|
|
3244
|
+
// triggers close, so it never turns one off into a closed file.
|
|
3245
|
+
const githubStopped = githubConnect.close();
|
|
2085
3246
|
triggers.close();
|
|
2086
3247
|
for (const [worker, { task }] of workers) {
|
|
2087
3248
|
if (task === "plan")
|
|
@@ -2091,16 +3252,22 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
2091
3252
|
}
|
|
2092
3253
|
await Promise.all([...workers.values()].map((w) => w.exit));
|
|
2093
3254
|
await importing;
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
await relay?.close();
|
|
2097
|
-
// Before the lock goes: the image's last record lands first (box-image.ts), never after the next server's start.
|
|
3255
|
+
await installStopped;
|
|
3256
|
+
// Before the store closes: the image's last record lands first (box-image.ts), never after the next server's start.
|
|
2098
3257
|
await image?.close();
|
|
3258
|
+
// The box network proxy goes with the server that owns it (box-egress-vm.ts); its volume stays for the next start.
|
|
3259
|
+
await egress?.close();
|
|
3260
|
+
// The ends' follower stops before the webhooks it feeds and the store it reads.
|
|
3261
|
+
clearTimeout(endsTimer);
|
|
3262
|
+
await endsRead;
|
|
2099
3263
|
await webhooks.close();
|
|
3264
|
+
// An upgraded socket is no connection closeAllConnections ends, and server.close waits for it.
|
|
3265
|
+
viewers.close();
|
|
2100
3266
|
await new Promise((done) => (server.close(done), server.closeAllConnections()));
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
lock.
|
|
3267
|
+
await mcpStopped;
|
|
3268
|
+
await githubStopped;
|
|
3269
|
+
// The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
|
|
3270
|
+
await store.close();
|
|
2104
3271
|
}
|
|
2105
3272
|
return {
|
|
2106
3273
|
url,
|
|
@@ -2109,10 +3276,12 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
2109
3276
|
token,
|
|
2110
3277
|
tokenFile,
|
|
2111
3278
|
tokenMade: stored?.made ?? false,
|
|
2112
|
-
...(setupUrl ? { setupUrl } : {}),
|
|
2113
|
-
boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow),
|
|
3279
|
+
...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
|
|
3280
|
+
boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
|
|
2114
3281
|
// Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
|
|
2115
3282
|
// never writes this data root's record again (the next server's, by then).
|
|
2116
3283
|
close: () => (stopped ??= stop()),
|
|
3284
|
+
// No per-run process drains here: the runner owns a run's turn, so a stop waits on none.
|
|
3285
|
+
stopping: () => ({ runs: 0, boundMs: 0 }),
|
|
2117
3286
|
};
|
|
2118
3287
|
}
|