@parcha/agentrun-serve 0.1.0-beta.34 → 0.1.0-beta.36
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 +263 -0
- package/README.md +339 -179
- package/dist/adapters.d.ts +15 -2
- package/dist/adapters.js +34 -2
- package/dist/agent-rows.d.ts +3 -1
- package/dist/agents-store.d.ts +2 -0
- package/dist/agents-store.js +25 -5
- package/dist/api-only.d.ts +2 -1
- package/dist/api-only.js +3 -1
- package/dist/archil-routes.d.ts +40 -7
- package/dist/archil-routes.js +167 -54
- package/dist/archil-settings.d.ts +90 -8
- package/dist/archil-settings.js +150 -14
- package/dist/attach-images.d.ts +15 -0
- package/dist/attach-images.js +59 -0
- package/dist/background.d.ts +0 -6
- package/dist/background.js +0 -28
- package/dist/bash-read-only.d.ts +13 -0
- package/dist/bash-read-only.js +77 -0
- package/dist/box-image.d.ts +1 -97
- package/dist/box-image.js +4 -284
- package/dist/box-paths.d.ts +2 -7
- package/dist/box-paths.js +7 -13
- package/dist/box-settings.d.ts +0 -11
- package/dist/box-settings.js +4 -29
- package/dist/browser-commands.js +1 -1
- package/dist/browser-computer.d.ts +47 -3
- package/dist/browser-computer.js +286 -18
- package/dist/browser-cost.d.ts +2 -2
- package/dist/browser-cost.js +6 -4
- package/dist/browser-person.d.ts +19 -2
- package/dist/browser-person.js +55 -6
- package/dist/browser-wait-ended.d.ts +23 -0
- package/dist/browser-wait-ended.js +42 -0
- package/dist/cap.d.ts +19 -44
- package/dist/cap.js +31 -77
- package/dist/cli.js +36 -27
- package/dist/computer-keys.d.ts +20 -10
- package/dist/computer-keys.js +36 -57
- package/dist/computer-routes.d.ts +1 -4
- package/dist/computer-routes.js +3 -5
- package/dist/computer-setting.d.ts +8 -5
- package/dist/computer-setting.js +91 -26
- package/dist/computer-view.d.ts +11 -2
- package/dist/computer-view.js +2 -1
- package/dist/computers.d.ts +54 -8
- package/dist/computers.js +101 -22
- package/dist/console/assets/index-BI4Byidu.js +550 -0
- package/dist/console/assets/index-C19gUF2n.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-cap.d.ts +7 -29
- package/dist/decision-cap.js +3 -94
- package/dist/docker-daemon.d.ts +2 -2
- package/dist/docker-daemon.js +2 -2
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +8 -5
- package/dist/explain.js +3 -1
- package/dist/faux-computers.js +4 -0
- package/dist/files.d.ts +1 -9
- package/dist/files.js +1 -9
- package/dist/github-connection.js +25 -7
- package/dist/github-faux.d.ts +26 -0
- package/dist/github-faux.js +76 -0
- package/dist/github.d.ts +28 -4
- package/dist/github.js +46 -10
- package/dist/gpu-words.d.ts +14 -0
- package/dist/gpu-words.js +21 -0
- package/dist/graph-served.d.ts +5 -3
- package/dist/graph-served.js +14 -6
- package/dist/graph-view.d.ts +2 -0
- package/dist/graph-view.js +29 -2
- package/dist/handed-values.d.ts +1 -1
- package/dist/handed-values.js +1 -1
- package/dist/harness-install.d.ts +60 -3
- package/dist/harness-install.js +322 -34
- package/dist/harness-opencode/harness.js +0 -1
- package/dist/harness-opencode/host/policy.js +2 -2
- package/dist/harness.js +1 -1
- package/dist/host-tools.d.ts +8 -9
- package/dist/host-tools.js +7 -7
- package/dist/index.d.ts +2 -3
- package/dist/index.js +2 -2
- package/dist/key-refusal.d.ts +1 -1
- package/dist/key-refusal.js +2 -2
- package/dist/learn/check.d.ts +10 -2
- package/dist/learn/check.js +126 -8
- package/dist/learn/commit.d.ts +40 -6
- package/dist/learn/commit.js +164 -20
- package/dist/learn/folder.d.ts +11 -3
- package/dist/learn/folder.js +40 -16
- package/dist/learn/grade.d.ts +22 -2
- package/dist/learn/grade.js +127 -19
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/learning.sh +11 -13
- package/dist/learn/notes.d.ts +17 -3
- package/dist/learn/notes.js +19 -6
- package/dist/learn/reflect.d.ts +5 -2
- package/dist/learn/reflect.js +48 -32
- package/dist/learn/skills.d.ts +52 -5
- package/dist/learn/skills.js +104 -21
- package/dist/learned-nodes.d.ts +18 -0
- package/dist/learned-nodes.js +8 -0
- package/dist/learned-workflow.d.ts +27 -13
- package/dist/learned-workflow.js +110 -38
- package/dist/learning-cost.d.ts +79 -0
- package/dist/learning-cost.js +69 -0
- package/dist/learning-routes.d.ts +48 -2
- package/dist/learning-routes.js +99 -28
- package/dist/learning-run.d.ts +7 -5
- package/dist/learning-run.js +9 -6
- package/dist/learning-words.d.ts +3 -0
- package/dist/learning-words.js +6 -2
- package/dist/learning.d.ts +13 -28
- package/dist/learning.js +4 -18
- package/dist/llm.d.ts +4 -1
- package/dist/llm.js +4 -2
- package/dist/mcp-gateway.d.ts +6 -0
- package/dist/mcp-gateway.js +11 -1
- package/dist/mcp-probe.d.ts +8 -1
- package/dist/mcp-probe.js +62 -20
- package/dist/mcp-secret-writes.js +4 -0
- package/dist/mcp-servers-store.d.ts +12 -12
- package/dist/mcp-servers-store.js +8 -3
- package/dist/model.d.ts +8 -5
- package/dist/model.js +14 -6
- package/dist/openapi.d.ts +2 -0
- package/dist/openapi.js +236 -55
- package/dist/owner.d.ts +0 -1
- package/dist/owner.js +0 -2
- package/dist/pause.d.ts +2 -19
- package/dist/pause.js +5 -74
- package/dist/place-offers.d.ts +97 -0
- package/dist/place-offers.js +206 -0
- package/dist/place.d.ts +9 -13
- package/dist/place.js +22 -32
- package/dist/port-models.d.ts +12 -4
- package/dist/port-models.js +31 -9
- package/dist/print.d.ts +1 -8
- package/dist/print.js +1 -14
- package/dist/propose.d.ts +3 -0
- package/dist/propose.js +25 -19
- package/dist/run-cut.d.ts +5 -0
- package/dist/run-cut.js +19 -0
- package/dist/run-db.js +3 -3
- package/dist/run-launch.d.ts +18 -3
- package/dist/run-launch.js +11 -5
- package/dist/run-learning-served.d.ts +12 -1
- package/dist/run-manifest.d.ts +2 -2
- package/dist/run-manifest.js +2 -2
- package/dist/run-reads-over-store.d.ts +4 -2
- package/dist/run-reads-over-store.js +10 -8
- package/dist/run-secrets.js +3 -3
- package/dist/run-timeline-served.js +60 -38
- package/dist/run-view.d.ts +35 -16
- package/dist/run-view.js +64 -35
- package/dist/runnable.d.ts +6 -3
- package/dist/runnable.js +20 -4
- package/dist/runner/adapter-loop.d.ts +46 -5
- package/dist/runner/adapter-loop.js +381 -56
- package/dist/runner/adapter-run-spec.d.ts +46 -4
- package/dist/runner/adapter-run-spec.js +200 -45
- package/dist/runner/adapters/pi.d.ts +39 -3
- package/dist/runner/adapters/pi.js +124 -29
- package/dist/runner/beside.d.ts +8 -0
- package/dist/runner/beside.js +24 -2
- package/dist/runner/claim-secrets.d.ts +6 -0
- package/dist/runner/claim-secrets.js +15 -1
- package/dist/runner/cli-run-spec.d.ts +10 -0
- package/dist/runner/cli-run-spec.js +207 -64
- package/dist/runner/commands.d.ts +5 -1
- package/dist/runner/commands.js +3 -3
- package/dist/runner/conformance/harness.d.ts +1 -1
- package/dist/runner/conformance/harness.js +13 -10
- package/dist/runner/github-app.d.ts +7 -2
- package/dist/runner/github-app.js +46 -15
- package/dist/runner/harness-loops.d.ts +6 -1
- package/dist/runner/harness-loops.js +24 -1
- package/dist/runner/journal-kinds.d.ts +53 -7
- package/dist/runner/journal-kinds.js +29 -1
- package/dist/runner/learning-end.d.ts +15 -0
- package/dist/runner/learning-end.js +113 -20
- package/dist/runner/learning-factory.js +6 -2
- package/dist/runner/learning-loop.d.ts +75 -1
- package/dist/runner/learning-loop.js +215 -22
- package/dist/runner/learning-seed.d.ts +8 -0
- package/dist/runner/learning-seed.js +7 -1
- package/dist/runner/loop-contract.d.ts +12 -0
- package/dist/runner/loop-contract.js +6 -0
- package/dist/runner/loop.d.ts +5 -1
- package/dist/runner/loop.js +20 -0
- package/dist/runner/main.d.ts +9 -4
- package/dist/runner/main.js +38 -13
- package/dist/runner/mcp-claim.d.ts +7 -0
- package/dist/runner/mcp-claim.js +35 -2
- package/dist/runner/mcp-github.d.ts +15 -4
- package/dist/runner/mcp-github.js +55 -11
- package/dist/runner/mcp-run.d.ts +2 -0
- package/dist/runner/mcp-run.js +2 -0
- package/dist/runner/metrics.d.ts +18 -1
- package/dist/runner/metrics.js +81 -1
- package/dist/runner/model-route.d.ts +6 -0
- package/dist/runner/model-route.js +5 -2
- package/dist/runner/pr-checkout.d.ts +59 -0
- package/dist/runner/pr-checkout.js +176 -0
- package/dist/runner/reflect-hook.d.ts +1 -0
- package/dist/runner/reflect-hook.js +3 -3
- package/dist/runner/runner.js +136 -19
- package/dist/runner/spec-holds.d.ts +13 -3
- package/dist/runner/spec-holds.js +13 -10
- package/dist/runner/store-port.d.ts +4 -1
- package/dist/runner/store-secrets.js +17 -1
- package/dist/runner/subagent.d.ts +44 -0
- package/dist/runner/subagent.js +188 -0
- package/dist/runner/workflow-host.d.ts +25 -4
- package/dist/runner/workflow-host.js +26 -4
- package/dist/runner/workflow-loop.d.ts +9 -3
- package/dist/runner/workflow-loop.js +17 -10
- package/dist/runner/workflow-spec.d.ts +28 -13
- package/dist/runner/workflow-spec.js +247 -102
- package/dist/runs-over-store.d.ts +18 -7
- package/dist/runs-over-store.js +149 -31
- package/dist/seal-key.d.ts +0 -2
- package/dist/seal-key.js +0 -2
- package/dist/sealing.js +1 -2
- package/dist/secret-cut.d.ts +1 -1
- package/dist/secret-cut.js +1 -1
- package/dist/server-lock.js +4 -5
- package/dist/server.d.ts +49 -63
- package/dist/server.js +429 -230
- package/dist/stop-signals.d.ts +4 -2
- package/dist/stop-signals.js +5 -3
- package/dist/store/agent-body.d.ts +14 -3
- package/dist/store/agent-body.js +22 -8
- package/dist/store/deadline.d.ts +18 -0
- package/dist/store/deadline.js +49 -0
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/journal/storage.js +2 -1
- package/dist/store/postgres/connection.d.ts +4 -0
- package/dist/store/postgres/connection.js +64 -13
- package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
- package/dist/store/schema.d.ts +2 -1
- package/dist/store/schema.js +11 -8
- package/dist/store/seal.d.ts +13 -0
- package/dist/store/seal.js +19 -0
- package/dist/store/sqlite/connection.d.ts +5 -0
- package/dist/store/sqlite/connection.js +88 -82
- package/dist/store/sqlite/run-patch.d.ts +18 -2
- package/dist/store/sqlite/run-patch.js +31 -2
- package/dist/store/sqlite/store.js +65 -11
- package/dist/store/store.d.ts +62 -12
- package/dist/store/store.js +22 -1
- package/dist/store-reads/analytics.js +3 -2
- package/dist/store-reads/cap.d.ts +1 -3
- package/dist/store-reads/cap.js +8 -6
- package/dist/store-reads/decisions.d.ts +2 -2
- package/dist/store-reads/decisions.js +3 -6
- package/dist/store-reads/journal.js +83 -15
- package/dist/store-reads/learning.d.ts +73 -3
- package/dist/store-reads/learning.js +232 -9
- package/dist/store-reads/runs.d.ts +6 -4
- package/dist/store-reads/runs.js +17 -10
- package/dist/store-reads/stats.js +5 -1
- package/dist/store-view.d.ts +15 -1
- package/dist/store-view.js +88 -29
- package/dist/template-eval.js +2 -1
- package/dist/templates.d.ts +73 -4
- package/dist/templates.js +113 -23
- package/dist/timeline/timeline.d.ts +11 -1
- package/dist/timeline/timeline.js +19 -4
- package/dist/tool-blurbs.js +1 -0
- package/dist/tool-budget.d.ts +26 -0
- package/dist/tool-budget.js +56 -0
- package/dist/tool-gate.d.ts +13 -3
- package/dist/tool-gate.js +15 -7
- package/dist/tool-plane.d.ts +42 -29
- package/dist/tool-plane.js +64 -27
- package/dist/tools.d.ts +53 -39
- package/dist/tools.js +174 -79
- package/dist/trigger-signatures.d.ts +1 -0
- package/dist/trigger-signatures.js +3 -1
- package/dist/triggers.d.ts +3 -3
- package/dist/triggers.js +2 -2
- package/dist/turn-end.d.ts +0 -3
- package/dist/turn-end.js +0 -3
- package/dist/uploads.d.ts +28 -5
- package/dist/uploads.js +82 -9
- package/dist/usage-lines.d.ts +1 -1
- package/dist/usage.d.ts +1 -47
- package/dist/usage.js +3 -82
- package/dist/validate.d.ts +8 -0
- package/dist/validate.js +40 -3
- package/dist/webhooks.d.ts +2 -1
- package/dist/webhooks.js +5 -2
- package/dist/workflow/decision-recovery.d.ts +23 -0
- package/dist/workflow/decision-recovery.js +80 -0
- package/dist/workflow/decisions.d.ts +134 -0
- package/dist/workflow/decisions.js +46 -0
- package/dist/workflow/host-session.d.ts +5 -0
- package/dist/workflow/host-session.js +85 -0
- package/dist/workflow/host-tools.d.ts +3 -0
- package/dist/workflow/host-tools.js +3 -0
- package/dist/workflow/node-runner.d.ts +112 -0
- package/dist/workflow/node-runner.js +270 -0
- package/dist/workflow/node.d.ts +88 -0
- package/dist/workflow/node.js +99 -0
- package/dist/workflow/operator-error.d.ts +4 -0
- package/dist/workflow/operator-error.js +4 -0
- package/dist/workflow/pi-versions.d.ts +9 -0
- package/dist/workflow/pi-versions.js +8 -0
- package/dist/workflow/readers.d.ts +36 -0
- package/dist/workflow/readers.js +145 -0
- package/dist/workflow/record-file.d.ts +10 -0
- package/dist/workflow/record-file.js +56 -0
- package/dist/workflow/record-tool.d.ts +76 -0
- package/dist/workflow/record-tool.js +126 -0
- package/dist/workflow/record.d.ts +151 -0
- package/dist/workflow/record.js +401 -0
- package/dist/workflow/run-error.d.ts +16 -0
- package/dist/workflow/run-error.js +26 -0
- package/dist/workflow/runner.d.ts +6 -0
- package/dist/workflow/runner.js +240 -0
- package/dist/workflow/store.d.ts +23 -0
- package/dist/workflow/store.js +242 -0
- package/dist/workflow/task.d.ts +133 -0
- package/dist/workflow/task.js +411 -0
- package/dist/workflow/thinking.d.ts +3 -0
- package/dist/workflow/thinking.js +7 -0
- package/dist/workflow/tool-context.d.ts +21 -0
- package/dist/workflow/tool-context.js +13 -0
- package/dist/workflow/types.d.ts +126 -0
- package/dist/workflow/types.js +1 -0
- package/dist/workflow/wal.d.ts +11 -0
- package/dist/workflow/wal.js +106 -0
- package/dist/workflow-run.d.ts +1 -1
- package/dist/workspace/agent-computer.d.ts +137 -0
- package/dist/workspace/agent-computer.js +292 -0
- package/dist/workspace/archil-claim.d.ts +13 -2
- package/dist/workspace/archil-claim.js +22 -13
- package/dist/workspace/archil-disk.d.ts +10 -1
- package/dist/workspace/archil-disk.js +4 -0
- package/dist/workspace/archil-disks.d.ts +49 -0
- package/dist/workspace/archil-disks.js +185 -0
- package/dist/workspace/archil-exec.d.ts +12 -2
- package/dist/workspace/archil-exec.js +18 -3
- package/dist/workspace/archil-mount-credential.d.ts +20 -4
- package/dist/workspace/archil-mount-credential.js +13 -4
- package/dist/workspace/archil.d.ts +2 -2
- package/dist/workspace/archil.js +25 -5
- package/dist/workspace/attach.js +2 -0
- package/dist/workspace/computer-deps.d.ts +18 -11
- package/dist/workspace/computer-deps.js +64 -40
- package/dist/workspace/computer-for-claim.d.ts +47 -9
- package/dist/workspace/computer-for-claim.js +236 -24
- package/dist/workspace/computer-janitor.d.ts +3 -2
- package/dist/workspace/computer-janitor.js +43 -9
- package/dist/workspace/computer-ledger.d.ts +3 -8
- package/dist/workspace/computer-ledger.js +7 -3
- package/dist/workspace/computer-providers.d.ts +5 -3
- package/dist/workspace/computer-providers.js +11 -9
- package/dist/workspace/hands.d.ts +5 -2
- package/dist/workspace/hands.js +4 -3
- package/dist/workspace/index.d.ts +5 -4
- package/dist/workspace/index.js +2 -1
- package/dist/workspace/local.d.ts +3 -0
- package/dist/workspace/local.js +9 -0
- package/dist/workspace/paths.js +3 -2
- package/dist/workspace/pi-env.d.ts +4 -0
- package/dist/workspace/pi-env.js +3 -2
- package/dist/workspace/resolve-computer.d.ts +48 -12
- package/dist/workspace/resolve-computer.js +88 -19
- package/dist/workspace/run-disk.d.ts +34 -0
- package/dist/workspace/run-disk.js +91 -0
- package/dist/workspace/run-tools.d.ts +6 -4
- package/dist/workspace/run-tools.js +17 -9
- package/dist/workspace/server-run-workspace.d.ts +3 -2
- package/dist/workspace/server-run-workspace.js +17 -4
- package/dist/workspace/workspace.d.ts +5 -0
- package/dist/workspace.d.ts +0 -3
- package/dist/workspace.js +2 -15
- package/package.json +11 -16
- package/skills/agentrun-serve/SKILL.md +1 -1
- package/templates/README.md +11 -8
- package/templates/code-review/agent.md +27 -11
- package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
- package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
- package/templates/code-review/evals/injection/graders/ignores.md +1 -1
- package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
- package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
- package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
- package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
- package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
- package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
- package/templates/code-review/evals/never-flag/case.yaml +3 -0
- package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
- package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
- package/templates/code-review/evals/never-flag/prompt.md +30 -0
- package/templates/code-review/evals/null-name/graders/finds.md +1 -1
- package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
- package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
- package/templates/code-review/evals/re-review/prompt.md +1 -1
- package/templates/code-review/evals/re-review-open/case.yaml +3 -0
- package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
- package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
- package/templates/code-review/evals/re-review-open/prompt.md +27 -0
- package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
- package/templates/code-review/evals/two-defects/case.yaml +3 -0
- package/templates/code-review/evals/two-defects/graders/both.md +4 -0
- package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
- package/templates/code-review/evals/two-defects/prompt.md +25 -0
- package/templates/code-review/findings.schema.json +131 -27
- package/templates/code-review/rules/CODEREVIEW.md +76 -0
- package/templates/code-review/skills/review/DEEP.md +130 -0
- package/templates/code-review/skills/review/REVIEWER.md +116 -0
- package/templates/code-review/skills/review/SKILL.md +104 -154
- package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
- package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
- package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
- package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
- package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
- package/templates/release-notes/agent.md +11 -0
- package/dist/box/record.d.ts +0 -6
- package/dist/box/record.js +0 -41
- package/dist/box/sweep.d.ts +0 -53
- package/dist/box/sweep.js +0 -193
- package/dist/box-egress-vm.d.ts +0 -118
- package/dist/box-egress-vm.js +0 -354
- package/dist/box-egress.d.ts +0 -105
- package/dist/box-egress.js +0 -256
- package/dist/box-relay-vm.d.ts +0 -84
- package/dist/box-relay-vm.js +0 -437
- package/dist/box-relay.d.ts +0 -36
- package/dist/box-relay.js +0 -207
- package/dist/boxes.d.ts +0 -109
- package/dist/boxes.js +0 -249
- package/dist/budget.d.ts +0 -76
- package/dist/budget.js +0 -204
- package/dist/console/assets/index-RPHGlXmM.js +0 -540
- package/dist/console/assets/index-opTN5Naq.css +0 -1
- package/dist/daytona-api.d.ts +0 -10
- package/dist/daytona-api.js +0 -20
- package/dist/egress-proxy.d.ts +0 -45
- package/dist/egress-proxy.js +0 -416
- package/dist/egress-table.d.ts +0 -24
- package/dist/egress-table.js +0 -165
- package/templates/code-review/rules/REVIEW.md +0 -41
package/dist/server.js
CHANGED
|
@@ -31,12 +31,12 @@ import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./h
|
|
|
31
31
|
import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
|
|
32
32
|
import { IMPORT_ASKED } from "./import.js";
|
|
33
33
|
import { answerStoreCall } from "./import-proxy.js";
|
|
34
|
-
import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, seedOf } from "./learning.js";
|
|
35
|
-
import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
|
|
34
|
+
import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, seedOf } from "./learning.js";
|
|
35
|
+
import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
|
|
36
36
|
import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
|
|
37
37
|
import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
|
|
38
|
-
import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf } from "./place.js";
|
|
39
|
-
import {
|
|
38
|
+
import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
|
|
39
|
+
import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
|
|
40
40
|
import { dockerLimitsOf } from "./workspace/computer-deps.js";
|
|
41
41
|
import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
|
|
42
42
|
import { answerPage, byOwnerSession, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
|
|
@@ -44,9 +44,10 @@ import { hostFix, hostName, loopbackNames } from "./host-check.js";
|
|
|
44
44
|
import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile } from "./browser-live.js";
|
|
45
45
|
import { browserHandBack, handBackTarget } from "./browser-commands.js";
|
|
46
46
|
import { computerView } from "./computer-view.js";
|
|
47
|
+
import { screenWaitEnded } from "./browser-wait-ended.js";
|
|
47
48
|
import { durationMs, logLine } from "./print.js";
|
|
48
49
|
import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
|
|
49
|
-
import { momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
|
|
50
|
+
import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
|
|
50
51
|
import { HELD_WAITS } from "./runner/journal-kinds.js";
|
|
51
52
|
import { servedTimelineRows } from "./run-timeline-served.js";
|
|
52
53
|
import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
|
|
@@ -62,34 +63,33 @@ import { watchRun } from "./live/stream.js";
|
|
|
62
63
|
import { stats as statsOverStore } from "./store-reads/stats.js";
|
|
63
64
|
import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
|
|
64
65
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
65
|
-
import { openStore } from "./store/index.js";
|
|
66
|
+
import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
|
|
66
67
|
import { answerOf, logged } from "./agents.js";
|
|
67
68
|
import { FINAL_STATES } from "./store/store.js";
|
|
68
69
|
import { runModelRef } from "./model.js";
|
|
69
70
|
// The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
|
|
70
71
|
const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
|
|
71
72
|
import { runLines } from "./usage-lines.js";
|
|
72
|
-
import { boxesByDefault, boxesLog,
|
|
73
|
+
import { boxesByDefault, boxesLog, enabledBoxes, placeOffers, withNetworks } from "./place-offers.js";
|
|
74
|
+
import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
|
|
73
75
|
import { dockerDaemonCheck } from "./docker-daemon.js";
|
|
74
|
-
import { egressParentTooLong, FAUX_EGRESS_ENV, MAX_EGRESS_PARENT, sweepEgressDirs } from "./box-egress.js";
|
|
75
|
-
import { startEgressContainer } from "./box-egress-vm.js";
|
|
76
|
-
import { dockerComputerRefusal, dockerPathsOf, egressParentOf, FAUX_MOUNTINFO_ENV, remoteDockerOnce } from "./box-paths.js";
|
|
77
76
|
import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
|
|
78
|
-
import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
|
|
79
|
-
import { vmRelay } from "./box-relay-vm.js";
|
|
80
77
|
import { DOCUMENTS_ENV } from "./pdf-pages.js";
|
|
81
78
|
import { CAP_MODES } from "./cap.js";
|
|
82
79
|
import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
|
|
83
80
|
import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
|
|
84
81
|
import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
|
|
85
82
|
import { bootSealKey, withSealKey } from "./seal-key.js";
|
|
83
|
+
import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
|
|
84
|
+
import { DRAIN_TIMEOUT } from "./runner/beside.js";
|
|
86
85
|
import { analyticsFilter, analyticsView, statsView } from "./stats.js";
|
|
87
|
-
import { agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
|
|
86
|
+
import { agentCostOverStore, agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
|
|
87
|
+
import { costCsv, learningCostQuery } from "./learning-cost.js";
|
|
88
88
|
import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
|
|
89
89
|
import { toolKeysOverStore } from "./tool-keys-store.js";
|
|
90
90
|
import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
|
|
91
91
|
import { signInsOverStore } from "./sign-ins-store.js";
|
|
92
|
-
import { MCP_AUTH_TYPES } from "./mcp-probe.js";
|
|
92
|
+
import { MCP_AUTH_TYPES, mcpAuthOf } from "./mcp-probe.js";
|
|
93
93
|
import { mcpServersOverStore } from "./mcp-servers-store.js";
|
|
94
94
|
import { privateHostsRoute } from "./mcp-private-hosts.js";
|
|
95
95
|
import { metaToolOf } from "./mcp-meta.js";
|
|
@@ -100,6 +100,7 @@ import { templateApplied, templateTriggerSecret, templateWebhookSecrets, trigger
|
|
|
100
100
|
import { openServerSecretsOverStore } from "./server-secrets-store.js";
|
|
101
101
|
import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
|
|
102
102
|
import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
|
|
103
|
+
import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js";
|
|
103
104
|
import { GITHUB_API } from "./github.js";
|
|
104
105
|
import { HookCut, receivePush } from "./push-handler.js";
|
|
105
106
|
import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
|
|
@@ -107,25 +108,25 @@ import { webhook } from "./trigger-webhook.js";
|
|
|
107
108
|
import { SCHEME_NAMES } from "./trigger-signatures.js";
|
|
108
109
|
import { permissionFrom } from "./tool-gate.js";
|
|
109
110
|
import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
|
|
110
|
-
import { applyBodyOf, compiled,
|
|
111
|
+
import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageTiers, packageView, pickComputer, readPackages } from "./templates.js";
|
|
111
112
|
import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
|
|
112
|
-
import { agentTools, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
|
|
113
|
+
import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
|
|
113
114
|
import { toolSettingsOverStore } from "./tool-settings-store.js";
|
|
114
|
-
import { writeApprovers } from "./server-approvers.js";
|
|
115
|
+
import { readApprovers, writeApprovers } from "./server-approvers.js";
|
|
115
116
|
import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
|
|
116
117
|
import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
|
|
117
118
|
import { COMPUTER_ROUTES, computerHoldOf, computerRoute } from "./computer-routes.js";
|
|
118
119
|
import { PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
|
|
119
120
|
import { capabilityToolDefs, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
|
|
120
|
-
import { archilRoute, createArchilRoutes } from "./archil-routes.js";
|
|
121
|
+
import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
|
|
122
|
+
import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
|
|
121
123
|
import { computerOfPlace } from "./computer-setting.js";
|
|
122
|
-
import { computerCapabilities, createComputerRoutes, folderModeOf, settingsComputerRoute } from "./computers.js";
|
|
124
|
+
import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
|
|
123
125
|
import { FAUX_VIEW_PATH, fauxComputers } from "./faux-computers.js";
|
|
124
126
|
import { runComputerField } from "./run-computer.js";
|
|
125
127
|
import { writesHeld } from "./workspace.js";
|
|
126
|
-
import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
|
|
128
|
+
import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
|
|
127
129
|
import { keyReader } from "./key-meta.js";
|
|
128
|
-
// server-lock.ts is gone: the store's EXCLUSIVE connection is the one-server lock (StoreOwned refuses a second server).
|
|
129
130
|
export const CONTRACT = "agentrun.v2/0";
|
|
130
131
|
/** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
|
|
131
132
|
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] ?? ""));
|
|
@@ -140,12 +141,6 @@ const MAX_MESSAGE = 20_000;
|
|
|
140
141
|
const MAX_WAIT_MS = 25_000;
|
|
141
142
|
const PAGE_ROWS = 500;
|
|
142
143
|
const FILE_LIST_CAP = 2_000;
|
|
143
|
-
/** What a stopping server's record allows past its runs' kill bound, the cap a start waits under: the runs' carry backs,
|
|
144
|
-
* retried while the agent store is held (about 15.5 s), their boxes' cleanup (up to a minute), and the deliveries', the
|
|
145
|
-
* listener's and the stores' stop. A start stops waiting sooner once the stopping server's process is gone. */
|
|
146
|
-
const STOP_MARGIN_MS = 120_000;
|
|
147
|
-
/** A wait, as the stop's lines give it: whole seconds, rounded up, one at least. */
|
|
148
|
-
const seconds = (ms) => `${Math.max(1, Math.ceil(ms / 1000))} s`;
|
|
149
144
|
/** Where the stop's lines go (ServeOptions.notice). Best-effort: a notice that throws never stops a close or a start. */
|
|
150
145
|
const noticeOf = (options) => (line) => {
|
|
151
146
|
try {
|
|
@@ -161,7 +156,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
|
|
|
161
156
|
const LINK_REFUSED = "A link is on the way to this path, or is the file: this server follows none.";
|
|
162
157
|
/** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
|
|
163
158
|
* harness's, which scripts the harnesses with or without it. */
|
|
164
|
-
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], ["
|
|
159
|
+
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], ["fauxMountinfo", FAUX_MOUNTINFO_ENV]];
|
|
165
160
|
/** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
|
|
166
161
|
* takes the same (test/support.mjs startInProcessRunner). */
|
|
167
162
|
export function fauxEnvOf(options) {
|
|
@@ -188,8 +183,6 @@ async function tokenIn(file) {
|
|
|
188
183
|
return { token, made: true };
|
|
189
184
|
}
|
|
190
185
|
const digest = (text) => createHash("sha256").update(text).digest();
|
|
191
|
-
/** Why a trigger never messages a run: it has no spend cap, and every turn a trigger drives is capped. */
|
|
192
|
-
const NO_CAP = "The run has no spend cap: a trigger only messages a run with one, as every turn it drives is capped.";
|
|
193
186
|
const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
|
|
194
187
|
const SESSION_S = SESSION_MS / 1000;
|
|
195
188
|
export const ROUTES = [
|
|
@@ -207,6 +200,9 @@ export const ROUTES = [
|
|
|
207
200
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
|
|
208
201
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
|
|
209
202
|
{ method: "DELETE", pattern: /^\/agents\/([^/]+)\/sign-ins\/([^/]+)$/, name: "forgetSignIn" },
|
|
203
|
+
// The agent's Archil disk (archil-routes.ts): read, and removed for an archived agent.
|
|
204
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/archil$/, name: "getAgentArchil" },
|
|
205
|
+
{ method: "DELETE", pattern: /^\/agents\/([^/]+)\/archil$/, name: "deleteAgentArchil" },
|
|
210
206
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/runs$/, name: "createRun" },
|
|
211
207
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/runs$/, name: "listRuns" },
|
|
212
208
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/home\/files$/, name: "listHomeFiles" },
|
|
@@ -298,6 +294,7 @@ export const ROUTES = [
|
|
|
298
294
|
// Answered before routing (mcp.ts), with the token only: listed here for the document.
|
|
299
295
|
{ method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
|
|
300
296
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
|
|
297
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
|
|
301
298
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
|
|
302
299
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
|
|
303
300
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
|
|
@@ -305,6 +302,7 @@ export const ROUTES = [
|
|
|
305
302
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
|
|
306
303
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
|
|
307
304
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
|
|
305
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
|
|
308
306
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
|
|
309
307
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
|
|
310
308
|
];
|
|
@@ -312,9 +310,12 @@ export const ROUTES = [
|
|
|
312
310
|
* learning/); sign-ins/ only as the agent's `sign_ins`, never a pointer. */
|
|
313
311
|
/** A run's computer as GET /computer reads it with no viewer open: kind browser where its agent has the browser tool, its
|
|
314
312
|
* kept plane's (a run from before the plane names none, and is Browserbase's where it grants the tool) checked again as a
|
|
315
|
-
* launch would be; off, saying why, where it has none or its browser resolves unavailable here.
|
|
313
|
+
* launch would be; off, saying why, where it has none or its browser resolves unavailable here. Where the agent's
|
|
314
|
+
* computer is a browser, that browser, whose keys are the computer's (checked at the run's start), never the plane's.
|
|
316
315
|
* TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
|
|
317
316
|
function computerOf(kept, env, family = "computer") {
|
|
317
|
+
if (kept === ON_COMPUTER)
|
|
318
|
+
return { kind: "browser" };
|
|
318
319
|
const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
|
|
319
320
|
if (browser === undefined)
|
|
320
321
|
return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
|
|
@@ -323,18 +324,24 @@ function computerOf(kept, env, family = "computer") {
|
|
|
323
324
|
/** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
|
|
324
325
|
* (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
|
|
325
326
|
* a vendor, not a stored no-key sentinel; with no browser in the plane, the default vendor when the run's revision grants
|
|
326
|
-
* the browser tool, else none.
|
|
327
|
+
* the browser tool, else none. A revision that grants the tool to an agent whose computer is a browser is ON_COMPUTER:
|
|
328
|
+
* the tool's sessions are that computer's (tools.ts browserComputer), whatever the plane says. */
|
|
327
329
|
async function keptBrowserOf(store, runId) {
|
|
330
|
+
const runRow = await store.runs.get(runId);
|
|
331
|
+
const revision = runRow ? await store.agents.revision(runRow.revisionId) : undefined;
|
|
332
|
+
const body = revision?.body;
|
|
333
|
+
const granted = (body?.tools ?? []).includes("browser");
|
|
334
|
+
if (granted && body?.computer?.kind === "browser")
|
|
335
|
+
return ON_COMPUTER;
|
|
328
336
|
const row = await store.runs.launch(runId).catch(() => undefined);
|
|
329
337
|
const plane = row ? readLaunchBody(row.body)?.plane : undefined;
|
|
330
338
|
const kept = plane ? keptVendor(plane).browser : undefined;
|
|
331
339
|
if (kept !== undefined)
|
|
332
340
|
return kept;
|
|
333
|
-
const runRow = await store.runs.get(runId);
|
|
334
|
-
const revision = runRow ? await store.agents.revision(runRow.revisionId) : undefined;
|
|
335
|
-
const granted = (revision?.body?.tools ?? []).includes("browser");
|
|
336
341
|
return granted ? "browserbase" : undefined;
|
|
337
342
|
}
|
|
343
|
+
/** keptBrowserOf's answer for a run whose browser is its agent's browser computer. */
|
|
344
|
+
const ON_COMPUTER = Symbol("the agent's browser computer");
|
|
338
345
|
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);
|
|
339
346
|
/** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
|
|
340
347
|
export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
|
|
@@ -375,7 +382,7 @@ async function needsOf(env) {
|
|
|
375
382
|
/** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
|
|
376
383
|
* env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
|
|
377
384
|
* AGENTRUN_SERVE_LEARNING's when not given), its tool settings (`toolSettings`, what each web tool resolves to) and the
|
|
378
|
-
* box offers (`boxes`, what the
|
|
385
|
+
* box offers (`boxes`, what the server found at the start, place-offers.ts), with whether a revision that names no
|
|
379
386
|
* model runs (needsOf). The server makes it once at its start and then remakes only the parts a write changes
|
|
380
387
|
* (startHolding), so a key saved later can make a harness, a provider or the default model available with no restart.
|
|
381
388
|
* `gradeModel` is its `--grade-model`. */
|
|
@@ -390,8 +397,6 @@ export async function readingOf(base, maxRuns, stored, learning, toolSettings =
|
|
|
390
397
|
* `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
|
|
391
398
|
* server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
|
|
392
399
|
* `gradeModel`, its `--grade-model`. */
|
|
393
|
-
/** Why a Daytona box has no network although AGENTRUN_BOX_ALLOW names hosts: Daytona refused its domain list (`code`). */
|
|
394
|
-
const noListReason = (code) => `Daytona did not keep a sandbox's domain list (${code}), so this server's Daytona boxes have no network until it starts again: Daytona takes a domain list on its tier 3 and 4 only. To keep them closed without trying, set ${BOX_ALLOW_ENV}=none`;
|
|
395
400
|
export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
|
|
396
401
|
return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes, gradeModel);
|
|
397
402
|
}
|
|
@@ -416,7 +421,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
|
|
|
416
421
|
backend: "local",
|
|
417
422
|
contract: CONTRACT,
|
|
418
423
|
server: { name: "@parcha/agentrun-serve", version: VERSION, platform: process.platform },
|
|
419
|
-
runtimes:
|
|
424
|
+
/** What runs a run here (the contract's `runtimes`, informational): this server's runners, over its one store. */
|
|
425
|
+
runtimes: ["runner"],
|
|
420
426
|
/** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
|
|
421
427
|
// `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
|
|
422
428
|
harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
|
|
@@ -461,8 +467,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
|
|
|
461
467
|
efforts: [...EFFORTS],
|
|
462
468
|
thinking: [...THINKING_LEVELS],
|
|
463
469
|
/** The browser a run's `browser` tool drives: the vendor it resolves to under the server's settings when the tool is
|
|
464
|
-
* available here (tools[]),
|
|
465
|
-
browser: browser?.available ? (
|
|
470
|
+
* available here (tools[]), a browser provider's id (tool-plane.ts BROWSER_VENDOR_IDS), else none. */
|
|
471
|
+
browser: browser?.available ? ((resolved) => (BROWSER_VENDOR_IDS.includes(resolved ?? "") ? resolved : "browserbase"))(browser.resolves?.[DEFAULT_HARNESS]) : "none",
|
|
466
472
|
/** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): allow, ask or deny, which the tool
|
|
467
473
|
* gate holds every tool call to (tool-gate.ts); an ask is answered at POST /runs/{id}/approvals/{approval_id}. */
|
|
468
474
|
tool_permissions: true,
|
|
@@ -542,7 +548,7 @@ export async function startServe(options) {
|
|
|
542
548
|
// environment (an operator's export, a leftover) never loads, wherever the server reads its environment.
|
|
543
549
|
delete process.env[HARNESS_TABLE_ENV];
|
|
544
550
|
await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
|
|
545
|
-
// Canonical once, here: a
|
|
551
|
+
// Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
|
|
546
552
|
const data = await realpath(resolve(options.data));
|
|
547
553
|
if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
|
|
548
554
|
throw new Error("the token must be 32 characters or more, with no whitespace");
|
|
@@ -554,6 +560,9 @@ export async function startServe(options) {
|
|
|
554
560
|
dockerLimitsOf(process.env);
|
|
555
561
|
// The Docker host's addresses an operator names (workspace/computer-deps.ts): a bad entry stops the start, in words.
|
|
556
562
|
dockerHostAddressesOf(process.env);
|
|
563
|
+
// The Archil settings an operator sets (archil-settings.ts ARCHIL_SETTINGS_ENV): one of the region and S3 URL without the
|
|
564
|
+
// other, or a value the PUT would refuse, stops the start, in words naming each variable.
|
|
565
|
+
archilSettingsFromEnv(process.env);
|
|
557
566
|
const boxAllow = boxAllowOf(process.env);
|
|
558
567
|
const maxRuns = maxRunsOf(process.env, options.maxRuns);
|
|
559
568
|
const learning = learningOf(process.env, options.learning);
|
|
@@ -564,9 +573,9 @@ export async function startServe(options) {
|
|
|
564
573
|
const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
|
|
565
574
|
// The template packages, each checked whole (templates.ts readPackage): a broken one stops the start.
|
|
566
575
|
const templates = readPackages(options.templates);
|
|
567
|
-
// One server per data root
|
|
568
|
-
// data directory an earlier version wrote is refused there too
|
|
569
|
-
//
|
|
576
|
+
// One server per data root: the store's owner lock (StoreOwned), then the data root's own (server-lock.ts), both taken
|
|
577
|
+
// when startHolding opens the store; a data directory an earlier version wrote is refused there too
|
|
578
|
+
// (StoreFromEarlierVersion), in words, to start fresh. No oldHomes/oldLayout checks, no migration.
|
|
570
579
|
// What a start that fails stops: the webhook deliveries it began, which would write the next server's outbox, and the
|
|
571
580
|
// store handle it opened.
|
|
572
581
|
const stops = [];
|
|
@@ -579,25 +588,38 @@ export async function startServe(options) {
|
|
|
579
588
|
throw error;
|
|
580
589
|
}
|
|
581
590
|
}
|
|
591
|
+
/** How much longer than its drain timeout a start waits for the server it replaces (a redeploy, a restart that starts the
|
|
592
|
+
* new server before the old one has exited): the old one's close, after its runs' drain. */
|
|
593
|
+
const START_WAIT_MARGIN_MS = 30_000;
|
|
594
|
+
/** `take()`, tried again every 250 ms while `held(error)` says the server this one replaces still holds what it takes, up
|
|
595
|
+
* to `until` (epoch ms); `waiting` is told this wait's `until` once, as it begins. Past `until`, or on any other error,
|
|
596
|
+
* it throws. */
|
|
597
|
+
async function whileReplaced(take, held, until, waiting) {
|
|
598
|
+
let told = false;
|
|
599
|
+
for (;;) {
|
|
600
|
+
try {
|
|
601
|
+
return await take();
|
|
602
|
+
}
|
|
603
|
+
catch (error) {
|
|
604
|
+
if (!held(error) || Date.now() >= until)
|
|
605
|
+
throw error;
|
|
606
|
+
if (!told)
|
|
607
|
+
(told = true), waiting(until);
|
|
608
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
582
612
|
async function startHolding(options, data, checked, stops) {
|
|
583
613
|
const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates } = checked;
|
|
584
614
|
/** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
|
|
585
615
|
* on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
|
|
586
616
|
* read (the view never fails for it). */
|
|
587
617
|
const learningOfAgent = async (entry) => {
|
|
588
|
-
if (learning === "off" || entry.revision?.kind !== "agentic" || entry.revision.body.learning
|
|
618
|
+
if (learning === "off" || entry.revision?.kind !== "agentic" || !learnsOf(entry.revision.body.learning))
|
|
589
619
|
return undefined;
|
|
590
620
|
const pending = await pendingCount(data, entry.agent.id);
|
|
591
621
|
return pending === undefined ? undefined : { pending };
|
|
592
622
|
};
|
|
593
|
-
const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
|
|
594
|
-
const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
|
|
595
|
-
const token = options.token ?? stored.token;
|
|
596
|
-
// Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
|
|
597
|
-
// (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
|
|
598
|
-
// new file and token.
|
|
599
|
-
if (options.token !== undefined)
|
|
600
|
-
await rm(join(data, TOKEN_FILE), { force: true });
|
|
601
623
|
const log = options.log;
|
|
602
624
|
const quiet = process.env.AGENTRUN_LOG === "quiet";
|
|
603
625
|
const authFailed = (route, reason) => log?.(logLine("auth_failed", { route, reason }));
|
|
@@ -612,17 +634,49 @@ async function startHolding(options, data, checked, stops) {
|
|
|
612
634
|
let triggerSettings = new Map();
|
|
613
635
|
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) } : {}) };
|
|
614
636
|
// The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
|
|
615
|
-
//
|
|
616
|
-
// words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
|
|
637
|
+
// owner lock holds the store to this server (the data root's own lock follows), and it refuses a data directory an
|
|
638
|
+
// earlier version wrote, in words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
|
|
617
639
|
// server writes and reads rows, and a runner (its own process, sharing only this store) runs every run.
|
|
618
|
-
// On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts)
|
|
640
|
+
// On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts).
|
|
619
641
|
// A server deploying while the old one still holds the schema waits for it (said once), never exits at once.
|
|
620
|
-
|
|
642
|
+
// The server this one replaces may still be stopping (a redeploy, a restart that starts this one before the old one has
|
|
643
|
+
// exited): its close comes after its runs' drain, so this start waits for as long as its own drain timeout and a
|
|
644
|
+
// margin, saying so once, before it refuses. On Postgres the store's owner lock waits on its own (store/open.ts); on
|
|
645
|
+
// SQLite the store file's owner lock is waited for here, and the data root's lock below on either.
|
|
646
|
+
const replacedDrainMs = durationMs(options.drainTimeout ?? DRAIN_TIMEOUT) ?? 0;
|
|
647
|
+
const replacedUntil = Date.now() + replacedDrainMs + START_WAIT_MARGIN_MS;
|
|
648
|
+
const sayReplaced = noticeOf(options);
|
|
649
|
+
let replacedTold = false;
|
|
650
|
+
const waitingForReplaced = (until) => {
|
|
651
|
+
if (replacedTold)
|
|
652
|
+
return;
|
|
653
|
+
replacedTold = true;
|
|
654
|
+
sayReplaced(`another server holds this data root: waiting up to ${Math.max(1, Math.ceil((until - Date.now()) / 1000))} s for the previous server to stop`);
|
|
655
|
+
};
|
|
656
|
+
const onSqlite = storeTarget(data).kind === "sqlite";
|
|
657
|
+
const store = await whileReplaced(() => openStore({
|
|
621
658
|
dataDir: data, role: "server",
|
|
622
659
|
warn: (message) => void process.stderr.write(`agentrun-serve: ${message}\n`),
|
|
623
660
|
...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
|
|
624
|
-
});
|
|
661
|
+
}), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
|
|
625
662
|
stops.push(() => store.close());
|
|
663
|
+
// The data root's own lock, once the store is held (so a deploy on Postgres waits at the store's owner lock first): the
|
|
664
|
+
// store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
|
|
665
|
+
// uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
|
|
666
|
+
// Postgres) would share. The lock is SQLite's EXCLUSIVE lock (server-lock.ts): the kernel drops it when its process
|
|
667
|
+
// dies, so a crashed server never leaves it held.
|
|
668
|
+
// Its wait runs from when the store was held at the earliest, since a store on Postgres may have been waited for first.
|
|
669
|
+
const dataLock = await whileReplaced(() => takeServerLock(data), (error) => error instanceof ServerLockHeldError, Math.max(replacedUntil, Date.now() + START_WAIT_MARGIN_MS), waitingForReplaced);
|
|
670
|
+
stops.push(async () => dataLock.release());
|
|
671
|
+
// The token, once both locks are held: a start the locks refuse reads, makes and removes nothing in the data root.
|
|
672
|
+
const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
|
|
673
|
+
const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
|
|
674
|
+
const token = options.token ?? stored.token;
|
|
675
|
+
// Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
|
|
676
|
+
// (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
|
|
677
|
+
// new file and token.
|
|
678
|
+
if (options.token !== undefined)
|
|
679
|
+
await rm(join(data, TOKEN_FILE), { force: true });
|
|
626
680
|
// No start without a seal key (seal-key.ts), checked against the store before anything reads it: the one handed over,
|
|
627
681
|
// else the one in the data directory beside the store, made at the first start with only its path printed. A store whose
|
|
628
682
|
// secrets another key sealed is refused, in words, and no key is made over them. Every secret here is kept under it;
|
|
@@ -731,135 +785,38 @@ async function startHolding(options, data, checked, stops) {
|
|
|
731
785
|
else
|
|
732
786
|
await probe("key");
|
|
733
787
|
};
|
|
734
|
-
// The boxes
|
|
735
|
-
//
|
|
736
|
-
// Under --faux,
|
|
737
|
-
const
|
|
738
|
-
const
|
|
739
|
-
|
|
740
|
-
// is preparing until it is in, and unavailable if the pull fails. Its record tells the run's processes; with no Docker
|
|
741
|
-
// box here there is none, so no run waits on one an earlier start left.
|
|
742
|
-
let image;
|
|
743
|
-
// What a Docker box's programs reach, resolved once here (box-settings.ts boxNetworkOf): the setting's list, on a Docker
|
|
744
|
-
// daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
|
|
788
|
+
// The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
|
|
789
|
+
// them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
|
|
790
|
+
// run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
|
|
791
|
+
const fauxDocker = Boolean(options.faux) && options.fauxDocker === true;
|
|
792
|
+
const found = await placeOffers(env, { keyOf: keyReader(store, seal.key, env), fauxDocker });
|
|
793
|
+
const docker = found.some((offer) => offer.id === "docker" && offer.available);
|
|
745
794
|
// Under --faux, the mountinfo a test gives (fauxMountinfo, or FAUX_MOUNTINFO_ENV in the process's own environment, which
|
|
746
795
|
// `env` leaves out: a server under test in a container names its own /proc/self/mountinfo there); with none, a faux
|
|
747
796
|
// server is on a host.
|
|
748
797
|
const fauxMountinfo = options.faux ? (options.fauxMountinfo ?? process.env[FAUX_MOUNTINFO_ENV]) : undefined;
|
|
749
798
|
// Where Docker has this server's files (box-paths.ts): its own, on a host; its container's mount of the data directory,
|
|
750
799
|
// for a server in a container given Docker's socket; or none, and docker is unavailable, saying why. Under --faux, a
|
|
751
|
-
// host's unless the test gives a container's mountinfo.
|
|
752
|
-
|
|
753
|
-
// (box-egress-vm.ts), never a volume's subpath of its data.
|
|
754
|
-
const platform = options.faux && options.fauxPlatform ? options.fauxPlatform : process.platform;
|
|
755
|
-
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);
|
|
756
|
-
const boxPaths = "paths" in dockerPaths ? dockerPaths.paths : undefined;
|
|
757
|
-
const egressParent = boxPaths ? egressParentOf(data) : undefined;
|
|
800
|
+
// host's unless the test gives a container's mountinfo. Only on Linux: a container of a Docker's own is a Linux one.
|
|
801
|
+
const dockerPaths = fauxDocker || !docker || process.platform !== "linux" ? { here: true } : options.faux ? (fauxMountinfo ? await dockerPathsOf(env, data, { mountinfo: await readFile(fauxMountinfo, "utf8"), inContainer: true }) : { here: true }) : await dockerPathsOf(env, data);
|
|
758
802
|
if ("reason" in dockerPaths)
|
|
759
803
|
log?.(logLine("box_paths", { reason: dockerPaths.reason }));
|
|
760
|
-
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 } : {}) });
|
|
761
|
-
// The proxy directories runs that are gone left in /tmp, or, in a container, on the data directory's mount
|
|
762
|
-
// (box-egress.ts): a live run's, any server's, stays.
|
|
763
|
-
if (!fauxBox && boxes.provider("docker"))
|
|
764
|
-
await sweepEgressDirs(undefined, undefined, egressParent).catch(() => 0);
|
|
765
|
-
// On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
|
|
766
|
-
// (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.
|
|
767
|
-
let egress;
|
|
768
804
|
// A run's Docker computer mounts the run's folder, and the computer's daemon, by this server's paths: as they are on
|
|
769
805
|
// its Docker's own host, or as its named data volume's subpaths from a container of that Docker's (compose.yaml).
|
|
770
806
|
// Any other layout, or a daemon of another machine (DOCKER_HOST, or the current context's endpoint: box-paths.ts
|
|
771
807
|
// remoteDockerOnce), can't run one, and says so here (dockerComputerRefusal), where capabilities, the run's start
|
|
772
808
|
// (dockerAnswers) and a place's box check all read it: no run starts only to fail at its create.
|
|
773
|
-
const dockerElsewhere =
|
|
809
|
+
const dockerElsewhere = fauxDocker || !docker ? undefined : dockerComputerRefusal(dockerPaths, await remoteDockerOnce(env));
|
|
774
810
|
// From a container, a Docker computer keeps this server's allow-list only knowing the Docker host's own addresses: the
|
|
775
811
|
// union of the read through the socket and AGENTRUN_DOCKER_HOST_ADDRESSES (docker-host-addresses.ts), the same read the
|
|
776
812
|
// runner beside this server takes. Said at the start with what was found; with none, Docker isn't offered, in words.
|
|
777
|
-
const hostAddresses = dockerElsewhere === undefined &&
|
|
813
|
+
const hostAddresses = dockerElsewhere === undefined && "paths" in dockerPaths && boxAllow !== "none" ? unionOf(await hostAddressesOnce(env), dockerHostAddressesOf(env)) : undefined;
|
|
778
814
|
if (hostAddresses)
|
|
779
815
|
log?.(logLine("docker_host_addresses", { addresses: hostAddresses.addresses.join(",") || "none", ...(hostAddresses.why ? { read: hostAddresses.why } : {}) }));
|
|
780
816
|
const dockerRefused = dockerElsewhere ?? (hostAddresses && hostAddresses.addresses.length === 0 ? noHostAddresses(hostAddresses.why ?? "the read through Docker's socket found none") : undefined);
|
|
781
|
-
//
|
|
782
|
-
const
|
|
783
|
-
const dockerNetwork = (offer) => {
|
|
784
|
-
if (!offer.available)
|
|
785
|
-
return offer;
|
|
786
|
-
if (dockerRefused !== undefined)
|
|
787
|
-
return { id: offer.id, available: false, state: "unavailable", reason: dockerRefused };
|
|
788
|
-
if (boxNetwork.allow === "none")
|
|
789
|
-
return { ...offer, network: "none", network_reason: boxNetwork.reason };
|
|
790
|
-
const proxy = egress?.state();
|
|
791
|
-
return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist", ...hostShown };
|
|
792
|
-
};
|
|
793
|
-
// A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
|
|
794
|
-
// one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
|
|
795
|
-
let daytonaNoList;
|
|
796
|
-
const daytonaNetwork = (offer) => !offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : daytonaNoList ? { ...offer, network: "none", network_reason: noListReason(daytonaNoList) } : { ...offer, network: "allowlist" };
|
|
797
|
-
// The VM box has no network whatever AGENTRUN_BOX_ALLOW names: its provider takes a host list, but has no read of a
|
|
798
|
-
// box's list back, so the server cannot check one held (run-box.ts ensureRemoteBox makes it blocked). Said, with why.
|
|
799
|
-
const vmNetwork = (offer) => (!offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : { ...offer, network: "none", network_reason: VM_NO_LIST });
|
|
800
|
-
const offersNow = () => boxes.offers().map((offer) => (fauxBox && offer.id === "docker" ? dockerNetwork({ id: "docker", available: true, reason: "a faux box (tests)" }) : offer.id === "docker" ? dockerNetwork(image ? withImage(offer, image.state()) : offer) : offer.id === "daytona" ? daytonaNetwork(offer) : offer.id === VM_PROVIDER.id ? vmNetwork(offer) : offer));
|
|
801
|
-
const imageLog = (state, more = {}) => log?.(logLine("box_image", { image: image.image, state: state.state, ...more, ...("reason" in state ? { reason: state.reason } : {}) }));
|
|
802
|
-
let boxOffers = offersNow();
|
|
803
|
-
const boxImage = !fauxBox && boxes.provider("docker") ? boxImageOf(env) : undefined;
|
|
804
|
-
if (boxImage) {
|
|
805
|
-
image = await dockerImage(env, data, boxImage, {
|
|
806
|
-
warn: (message) => (log ? log(logLine("box_image", { image: boxImage, warning: message })) : void process.stderr.write(`agentrun-serve: ${message}\n`)),
|
|
807
|
-
onChange: (state, ms) => {
|
|
808
|
-
boxOffers = offersNow();
|
|
809
|
-
imageLog(state, { ms });
|
|
810
|
-
options.onBoxImage?.(state);
|
|
811
|
-
// The box's state is in caps alone, not in the offers: recomposed now, or, while the start's probe of the offers
|
|
812
|
-
// has not ended, by that probe, which reads the box offers when it does.
|
|
813
|
-
if (offers)
|
|
814
|
-
recompose();
|
|
815
|
-
},
|
|
816
|
-
});
|
|
817
|
-
stops.push(async () => void (await image?.close()));
|
|
818
|
-
options.onBoxImage?.(image.state());
|
|
819
|
-
}
|
|
820
|
-
else
|
|
821
|
-
await clearImage(data);
|
|
822
|
-
boxOffers = offersNow();
|
|
823
|
-
const runBoxes = fauxBox ?? boxes.provider("docker");
|
|
824
|
-
// Daytona's boxes are made, seeded, pulled and destroyed here, with the key this server holds; a run's process reaches
|
|
825
|
-
// its own through the relay below, which holds the key for it (box-relay.ts).
|
|
826
|
-
const remoteBoxes = boxes.provider("daytona");
|
|
827
|
-
// And the VM box's, the same way, with this server's SDK client: the relay's VM half makes a run's calls with it.
|
|
828
|
-
const vmBoxes = boxes.provider(VM_PROVIDER.id);
|
|
829
|
-
const vmClient = boxes.vmClient();
|
|
830
|
-
// What the provider says in an error is cut of every value this server holds (the VM token among them) before a run's
|
|
831
|
-
// process sees it.
|
|
832
|
-
const vmSecrets = () => [...serverSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
|
|
833
|
-
const vmRelayHalf = vmBoxes && vmClient ? vmRelay(vmClient, vmSecrets) : undefined;
|
|
834
|
-
// Daytona could not keep a run's box's domain list: said in the log and in capabilities, which recompose now.
|
|
835
|
-
// Daytona's own words go to the log, so a refusal for another cause is not taken silently for a tier that takes no list.
|
|
836
|
-
const onNoBoxList = (code, message) => {
|
|
837
|
-
daytonaNoList = code;
|
|
838
|
-
log?.(logLine("box_network", { box: "daytona", network: "none", refused: code, message }));
|
|
839
|
-
boxOffers = offersNow();
|
|
840
|
-
if (offers)
|
|
841
|
-
recompose();
|
|
842
|
-
};
|
|
843
|
-
if (boxNetwork.allow !== "none" && boxNetwork.vm) {
|
|
844
|
-
const allow = boxNetwork.allow;
|
|
845
|
-
const egressLog = (state) => log?.(logLine("box_egress", { runtime: boxNetwork.vm, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }));
|
|
846
|
-
egress = await startEgressContainer({
|
|
847
|
-
env, data, allow, uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0,
|
|
848
|
-
warn: (message) => (log ? log(logLine("box_egress", { runtime: boxNetwork.vm, warning: message })) : void process.stderr.write(`agentrun-serve: ${message}\n`)),
|
|
849
|
-
onChange: (state) => {
|
|
850
|
-
egressLog(state);
|
|
851
|
-
boxOffers = offersNow();
|
|
852
|
-
if (offers)
|
|
853
|
-
recompose();
|
|
854
|
-
},
|
|
855
|
-
});
|
|
856
|
-
stops.push(() => egress.close());
|
|
857
|
-
egressLog(egress.state());
|
|
858
|
-
boxOffers = offersNow();
|
|
859
|
-
}
|
|
817
|
+
// Each box with what it reaches (place-offers.ts withNetworks).
|
|
818
|
+
const boxOffers = withNetworks(found, boxAllow, { ...(dockerRefused !== undefined ? { refused: dockerRefused } : {}), ...(hostAddresses ? { hostAddresses: hostAddresses.addresses } : {}), faux: fauxDocker });
|
|
860
819
|
log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
|
|
861
|
-
if (image)
|
|
862
|
-
imageLog(image.state());
|
|
863
820
|
const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
|
|
864
821
|
const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
|
|
865
822
|
const sealKey = seal.key;
|
|
@@ -876,16 +833,18 @@ async function startHolding(options, data, checked, stops) {
|
|
|
876
833
|
const fauxOf = () => (faux ??= fauxComputers({ viewerBase: ownOriginOf() }));
|
|
877
834
|
/** Whether a computer on a provider that binds a folder of this machine (Docker) can be had here now: Settings →
|
|
878
835
|
* Computers' view and a run's start check (below) both ask it. Where AGENTRUN_BOXES lists Docker and it is no faux
|
|
879
|
-
*
|
|
836
|
+
* Docker, its daemon is asked (docker-daemon.ts: a short `docker version`, its answer kept a while and asked again, so a
|
|
880
837
|
* daemon that stops after the start is seen, and one that is gone says so in noDockerWords); once it answers, the
|
|
881
838
|
* box's start-time answer stands. A box the start did not make keeps its reason ("start Docker, then restart
|
|
882
839
|
* AgentRun"): the start's checks of Docker (Docker elsewhere, this server's paths, host addresses, its network) ran
|
|
883
840
|
* without it, so a daemon that answers later is not taken. Else the box's start-time answer (boxOffers), with its
|
|
884
|
-
* reason, which says how to fix it.
|
|
841
|
+
* reason, which says how to fix it. The provider whose computers run on this machine's container engine is the one
|
|
842
|
+
* whose descriptor declares `local`. */
|
|
885
843
|
const dockerDaemon = dockerDaemonCheck({ env });
|
|
886
844
|
const dockerAnswers = async (provider) => {
|
|
887
845
|
const box = boxAvailability(boxOffers).find((one) => one.id === provider);
|
|
888
|
-
|
|
846
|
+
const local = COMPUTER_PROVIDERS.find((one) => one.id === provider)?.local === true;
|
|
847
|
+
if (local && !fauxDocker && enabledBoxes(env).has(provider)) {
|
|
889
848
|
const daemon = await dockerDaemon();
|
|
890
849
|
if (!daemon.up || box?.available)
|
|
891
850
|
return daemon;
|
|
@@ -895,12 +854,16 @@ async function startHolding(options, data, checked, stops) {
|
|
|
895
854
|
return { up: false, absent: false, reason: box?.reason ?? `${provider} is not a box this server has` };
|
|
896
855
|
};
|
|
897
856
|
let computerRoutes;
|
|
857
|
+
// The programs a provider runs on this machine (the phone's adb), looked for on PATH once, at the start, as the boxes
|
|
858
|
+
// probe Docker: a provider whose program is missing is not ready, and its words say what to install.
|
|
859
|
+
const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
|
|
898
860
|
const computersOf = () => (computerRoutes ??= createComputerRoutes({
|
|
899
|
-
store, sealKey, tools: kindTools, mode: folderModeOf(store), env: process.env,
|
|
861
|
+
store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: process.env,
|
|
900
862
|
...(options.faux
|
|
901
863
|
// --faux's providers stand in for every vendor's, a local one's daemon included.
|
|
902
864
|
? { kinds: fauxOf().kinds, factories: fauxOf().factories, keyTable: fauxOf().keyTable }
|
|
903
865
|
: {
|
|
866
|
+
hostWhy,
|
|
904
867
|
kinds: { SETTING_KINDS, PROVIDERS: COMPUTER_PROVIDERS, servingRefusals },
|
|
905
868
|
// The one place serve builds a provider (workspace/computer-providers.ts), the claim's makers' own.
|
|
906
869
|
factories: computerProviderFactories(computerProviderMakers(), (id) => storeLedger(store.computerLedger, id)),
|
|
@@ -912,15 +875,42 @@ async function startHolding(options, data, checked, stops) {
|
|
|
912
875
|
* runner composes with: runner/main.ts gives it no faux, so the package's, under --faux too), in the folder mode of
|
|
913
876
|
* now, with keys read as the runner reads them (the secrets this process was started with, withSecrets "own", as
|
|
914
877
|
* runner/main.ts runEnv hands them; else the saved one). What runnable.ts checks for an agent with
|
|
915
|
-
* a computer setting, in place of the box check; whether Docker answers here is dockerAnswers'
|
|
878
|
+
* a computer setting, in place of the box check; whether Docker answers here is dockerAnswers', and whether a
|
|
879
|
+
* provider's program is on this machine is hostWhy's, read at the start. */
|
|
916
880
|
/** The server's folder mode now: 2 when the owner's Archil settings are saved (the run's folder on the disk), else 1. */
|
|
917
|
-
const modeNow = async () => ((await folderModeOf(store)()) === "disk" ? 2 : 1);
|
|
918
|
-
const computerReady = async (setting) => computerReadiness(setting, await modeNow(), claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow);
|
|
881
|
+
const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
|
|
882
|
+
const computerReady = async (setting) => computerReadiness(setting, await modeNow(), claimKinds({}), keyReader(store, sealKey, own(withSecrets(process.env, "own"))), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
|
|
919
883
|
/** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
|
|
920
884
|
* folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
|
|
921
885
|
* and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
|
|
922
886
|
const shellOf = async (setting) => runShellOf(setting, await modeNow(), claimKinds({}));
|
|
923
|
-
|
|
887
|
+
/** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
|
|
888
|
+
* has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
|
|
889
|
+
* with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
|
|
890
|
+
* is no shell), whose shell runs the shell tools; else none, and why. */
|
|
891
|
+
const shellHere = async () => {
|
|
892
|
+
if ((await shellOf({ kind: "none" })) === "local")
|
|
893
|
+
return { computer: { kind: "none" }, tools: [...shellTools("local")], words: "Archil's serverless exec" };
|
|
894
|
+
const fresh = newAgentPlace(boxOffers);
|
|
895
|
+
let why = "why" in fresh ? fresh.why : "it is not set up";
|
|
896
|
+
if ("place" in fresh && fresh.place.mode === "sandbox") {
|
|
897
|
+
const computer = { kind: "sandbox", provider: fresh.place.box };
|
|
898
|
+
const ready = await computerReady(computer);
|
|
899
|
+
if ("refused" in ready)
|
|
900
|
+
why = ready.refused;
|
|
901
|
+
else if ((await shellOf(computer)) === "computer")
|
|
902
|
+
return { computer, tools: [...shellTools("computer")], words: `the ${fresh.place.box} sandbox` };
|
|
903
|
+
}
|
|
904
|
+
return { none: `this server has no shell to give an agent now: Archil is off (Settings → Workspace), and the docker box is unavailable here (${why})` };
|
|
905
|
+
};
|
|
906
|
+
const archil = createArchilRoutes({ store, sealKey, env: process.env, ...(options.archilControl ? { control: options.archilControl } : {}) });
|
|
907
|
+
/** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
|
|
908
|
+
* settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
|
|
909
|
+
* list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
|
|
910
|
+
const shellOfRevision = async (revision) => {
|
|
911
|
+
const body = revision.body;
|
|
912
|
+
return shellOf(body.computer ?? computerOfPlace(resolvePlace(body.place, fallbackPlace(revision.kind, revision.kind === "agentic" ? (body.tools ?? []) : []))));
|
|
913
|
+
};
|
|
924
914
|
/** A run's computer on its read: its revision's computer setting, else the one its place says; absent for none. */
|
|
925
915
|
const runComputerOf = async (runId, view) => {
|
|
926
916
|
const run = await store.runs.get(runId);
|
|
@@ -972,6 +962,13 @@ async function startHolding(options, data, checked, stops) {
|
|
|
972
962
|
const swept = await uploads.sweep();
|
|
973
963
|
if (swept > 0)
|
|
974
964
|
log?.(logLine("uploads_swept", { removed: swept }));
|
|
965
|
+
// A run's hold of its files goes at its claim, once they are in its workspace; one that ended before any claim copied
|
|
966
|
+
// them (cancelled while queued) leaves its hold, which goes here, as does one whose run is gone.
|
|
967
|
+
for (const runId of await uploads.holders()) {
|
|
968
|
+
const row = await store.runs.get(runId);
|
|
969
|
+
if (!row || FINAL_STATES.includes(row.state))
|
|
970
|
+
await uploads.release(runId);
|
|
971
|
+
}
|
|
975
972
|
const documents = options.documents ?? process.env[DOCUMENTS_ENV];
|
|
976
973
|
if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
|
|
977
974
|
throw new Error(`the documents directory ${documents} is not a directory`);
|
|
@@ -1021,7 +1018,24 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1021
1018
|
told: (error) => told(error),
|
|
1022
1019
|
runnable,
|
|
1023
1020
|
readyFiles: (ids) => uploads.readyFiles(ids),
|
|
1021
|
+
files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
|
|
1024
1022
|
fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
|
|
1023
|
+
// The run's Archil disk for its launch record (run-launch.ts archilDisk): the body's, else its agent's when it has one.
|
|
1024
|
+
// A disk the body names is read at Archil once, before the run is made (archil-routes.ts checkLaunchDisk): one that is
|
|
1025
|
+
// not there or not in the key's region is a 422 here, and Mode 1 is too. An agent whose disk is being removed
|
|
1026
|
+
// (archil-routes.ts removeAgentDisk) starts no run on it: 409 until the removal is done.
|
|
1027
|
+
launchDiskOf: async (agentId, named) => {
|
|
1028
|
+
if (named !== undefined) {
|
|
1029
|
+
await archil.checkLaunchDisk(named);
|
|
1030
|
+
return { diskId: named, kind: "launch" };
|
|
1031
|
+
}
|
|
1032
|
+
if (!(await inArchilMode(store, process.env)))
|
|
1033
|
+
return undefined;
|
|
1034
|
+
const own = await agentDiskOf(store, agentId);
|
|
1035
|
+
if (own?.removing)
|
|
1036
|
+
throw new ApiError("agent_not_runnable", `The agent ${agentId}'s Archil disk ${own.diskId} is being removed (DELETE /v2/agents/${agentId}/archil): start the run once that is done, and it gets a new disk.`);
|
|
1037
|
+
return own ? { diskId: own.diskId, kind: "agent" } : undefined;
|
|
1038
|
+
},
|
|
1025
1039
|
workflowTitle,
|
|
1026
1040
|
serverSecrets,
|
|
1027
1041
|
toolSettings: () => settings.get(),
|
|
@@ -1078,9 +1092,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1078
1092
|
// (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
|
|
1079
1093
|
// timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
|
|
1080
1094
|
const runReadsDeps = {
|
|
1081
|
-
runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey }),
|
|
1095
|
+
runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: process.env }),
|
|
1082
1096
|
env,
|
|
1083
|
-
|
|
1097
|
+
runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1084
1098
|
withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1085
1099
|
cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
|
|
1086
1100
|
context: ctx,
|
|
@@ -1189,7 +1203,20 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1189
1203
|
// Connect GitHub: the server's one GitHub App, in the store's trigger_settings (adapter github, scope server), where the
|
|
1190
1204
|
// runner reads it per claim (runner/github-app.ts).
|
|
1191
1205
|
const github = new GitHubConnection(triggerSettings.get("github"));
|
|
1192
|
-
|
|
1206
|
+
// --faux-github (with --faux only): the fake App is connected afresh at each start, its API in this process.
|
|
1207
|
+
const was = options.faux && options.fauxGitHub ? github.view() : undefined;
|
|
1208
|
+
if (was && was.slug !== FAUX_GITHUB.slug)
|
|
1209
|
+
throw new Error(`--faux-github connects a fake GitHub App, and this data directory has the GitHub App ${was.slug} connected: use a scratch data directory.`);
|
|
1210
|
+
const fauxGitHub = options.faux && options.fauxGitHub ? await startFauxGitHub() : undefined;
|
|
1211
|
+
if (fauxGitHub) {
|
|
1212
|
+
stops.push(() => fauxGitHub.close());
|
|
1213
|
+
if (was)
|
|
1214
|
+
await github.remove();
|
|
1215
|
+
await github.save(fauxGitHub.app);
|
|
1216
|
+
await github.setInstallations([{ id: FAUX_GITHUB.installation, account: FAUX_GITHUB.account }]);
|
|
1217
|
+
await writeFile(join(data, FAUX_GITHUB_FILE), `${JSON.stringify({ webhook_secret: fauxGitHub.app.webhookSecret, installation: FAUX_GITHUB.installation, account: FAUX_GITHUB.account, repositories: FAUX_GITHUB.repositories })}\n`, { mode: 0o600 });
|
|
1218
|
+
}
|
|
1219
|
+
const githubConnect = new GitHubConnect(github, { ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}), api: fauxGitHub?.url ?? options.githubApi ?? GITHUB_API, say: (fields) => log?.(logLine("github", fields)) });
|
|
1193
1220
|
/** The connection a GitHub template or the console reads: the App's id, slug and installations, never a secret. */
|
|
1194
1221
|
const githubConnection = () => github.view();
|
|
1195
1222
|
/** What applying a template reads of the server (templates.ts TemplatesDeps). */
|
|
@@ -1351,16 +1378,24 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1351
1378
|
return value;
|
|
1352
1379
|
}
|
|
1353
1380
|
/** The tools a learned draft of agent `id` may name, as a run's merge reads them (learning-run.ts draftTools): its
|
|
1354
|
-
* current revision's, those the gate allows under the server's settings and the agent's own.
|
|
1355
|
-
|
|
1356
|
-
|
|
1381
|
+
* current revision's, those the gate allows under the server's settings and the agent's own. `entry`: the agent as the
|
|
1382
|
+
* caller already read it, so what it checks and what it copies are one revision's (a promotion). */
|
|
1383
|
+
async function learnedDraftToolsOf(id, entry) {
|
|
1384
|
+
const revision = (entry ?? (await needAgent(id))).revision;
|
|
1357
1385
|
if (revision?.kind !== "agentic")
|
|
1358
|
-
return { tools: [], gated: {} };
|
|
1359
|
-
const [{ learnedDraftTools }, {
|
|
1386
|
+
return { tools: [], gated: {}, deniedBy: {} };
|
|
1387
|
+
const [{ learnedDraftTools, mcpGrantsListed }, { permissionFrom }, { learnedAskFits }] = await Promise.all([import("./tools.js"), import("./tool-gate.js"), import("./learned-workflow.js")]);
|
|
1360
1388
|
const server = settings.get();
|
|
1361
1389
|
// The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
|
|
1362
1390
|
const body = revision.body;
|
|
1363
|
-
|
|
1391
|
+
// A server's wildcard grant read as the tools its server lists now (tools.ts mcpGrantsListed, LS-07).
|
|
1392
|
+
const rows = (body.tools ?? []).some((name) => /^mcp:[^/]+\/\*$/.test(name)) ? await store.mcp.servers().catch(() => []) : [];
|
|
1393
|
+
const listed = new Map(rows.map((row) => [row.name, (row.tools ?? []).flatMap((tool) => (typeof tool?.name === "string" ? [tool.name] : []))]));
|
|
1394
|
+
const gate = (name) => permissionFrom(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask");
|
|
1395
|
+
// `deniedBy`: where each deny was set (the agent's tool settings, the server's), which a refused draft's words name.
|
|
1396
|
+
const { tools, gated, deniedBy, asked } = learnedDraftTools(mcpGrantsListed(body.tools ?? [], (name) => listed.get(name) ?? []), (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
|
|
1397
|
+
// #2424's card rule (learnedAskFits): a restored draft whose ask-set MCP tools would not all show is refused.
|
|
1398
|
+
return { tools, gated, deniedBy, ask: { asked, fits: learnedAskFits } };
|
|
1364
1399
|
}
|
|
1365
1400
|
async function needAgent(id) {
|
|
1366
1401
|
const entry = ID.test(id) ? await agents.get(id) : null;
|
|
@@ -1374,7 +1409,21 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1374
1409
|
const agentExtra = async (entry) => {
|
|
1375
1410
|
const learning = await learningOfAgent(entry);
|
|
1376
1411
|
const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
|
|
1377
|
-
return {
|
|
1412
|
+
return {
|
|
1413
|
+
signIns: await signIns.view(entry.agent.id),
|
|
1414
|
+
...(learning ? { learning } : {}),
|
|
1415
|
+
runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
|
|
1416
|
+
// The agent's own computer (a persistent setting), as this server records it: the view's own_computer.
|
|
1417
|
+
ownComputer: agentComputerView(await agentComputerOf(store, entry.agent.id)),
|
|
1418
|
+
};
|
|
1419
|
+
};
|
|
1420
|
+
/** Deletes an agent's own computer once the agent has no use for it (archived, persistent turned off, another provider
|
|
1421
|
+
* or image: workspace/agent-computer.ts), after the write that made it so, in the background: a vendor's delete can
|
|
1422
|
+
* take minutes. Until the provider has deleted it, the agent's view shows it deleting, with why where a delete failed. */
|
|
1423
|
+
const reconcileComputer = (agentId) => {
|
|
1424
|
+
void reconcileAgentComputer(store, agentId, (provider, image) => computersOf().providerFor(provider, image))
|
|
1425
|
+
.then((done) => (done ? log?.(logLine("agent_computer", { agent: agentId, ...("deleted" in done ? { deleted: done.deleted } : { failed: done.failed }) })) : undefined))
|
|
1426
|
+
.catch((error) => log?.(logLine("agent_computer", { agent: agentId, failed: error instanceof Error ? error.message : String(error) })));
|
|
1378
1427
|
};
|
|
1379
1428
|
// A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
|
|
1380
1429
|
// routes read from the store + the run view now, not a live Run.
|
|
@@ -1389,9 +1438,6 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1389
1438
|
const v = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
|
|
1390
1439
|
return { status: v?.status ?? "queued", state: v?.state ?? "idle" };
|
|
1391
1440
|
};
|
|
1392
|
-
/** The run read routes (timeline, files, graph, browser, live viewer) over the store are E2c's run-reads-over-store.ts
|
|
1393
|
-
* (watchRun + run-workspace + store-view), not committed yet. TODO(E2c): replace each call with its function on that sha. */
|
|
1394
|
-
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"); };
|
|
1395
1441
|
const mismatch = () => new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
|
|
1396
1442
|
/** Replays the first answer to a create with the same key and body; another body is a mismatch. `work` gets the key's
|
|
1397
1443
|
* origin (its slot and the body, hashed) for a create the agent store records with the run it starts. */
|
|
@@ -1514,6 +1560,52 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1514
1560
|
const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
|
|
1515
1561
|
return { entry, warnings };
|
|
1516
1562
|
}
|
|
1563
|
+
/** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
|
|
1564
|
+
* (createAgentOf: the definition's checks, the workflow's validation and what this host refuses of it). Only an active
|
|
1565
|
+
* one, checked again as a restore checks it (learning-routes.ts promotable). Its revision is a workflow revision of the
|
|
1566
|
+
* learned workflow.json, its tools those its call nodes call (each one the source agent has and its gate allows), and
|
|
1567
|
+
* the source's policy as it is now: its own tool settings, its approvals and its default cap, never more. Named
|
|
1568
|
+
* `body.name`, else the workflow's own; its id is the workflow's name, with -2, -3 and on past an agent's id or name
|
|
1569
|
+
* already here. The learned workflow stays where it is, unchanged. */
|
|
1570
|
+
async function promoteOf(source, raw, body) {
|
|
1571
|
+
const extra = unknownFields(body, ["name"]);
|
|
1572
|
+
if (body.name !== undefined && (typeof body.name !== "string" || body.name.trim() === "" || body.name.length > 200))
|
|
1573
|
+
extra.push({ field: "name", reason: "wrong_type", message: "name is the new agent's name: text of 1 to 200 characters" });
|
|
1574
|
+
if (extra.length)
|
|
1575
|
+
throw invalid(extra);
|
|
1576
|
+
const id = source.agent.id;
|
|
1577
|
+
const learned = await promotable(data, id, raw, { refuse: await learningValues(id), draftTools: () => learnedDraftToolsOf(id, source) });
|
|
1578
|
+
// Its policy from the same read of the source as the tools checked above: one revision's, whatever is saved meanwhile.
|
|
1579
|
+
const policy = (source.revision?.body ?? {});
|
|
1580
|
+
const promoted = (agentId) => ({
|
|
1581
|
+
id: agentId,
|
|
1582
|
+
name: typeof body.name === "string" ? body.name.trim() : agentId,
|
|
1583
|
+
...(learned.description ? { description: learned.description } : {}),
|
|
1584
|
+
workflow: learned.workflow,
|
|
1585
|
+
tools: learned.calls,
|
|
1586
|
+
...(policy.toolSettings ? { tool_settings: policy.toolSettings } : {}),
|
|
1587
|
+
...(policy.approvals === "never" ? { approvals: "never" } : {}),
|
|
1588
|
+
...(policy.maxCostUsd !== undefined ? { max_cost_usd: policy.maxCostUsd } : {}),
|
|
1589
|
+
...(policy.capMode !== undefined ? { cap_mode: policy.capMode } : {}),
|
|
1590
|
+
});
|
|
1591
|
+
const note = `Made from the learned workflow ${learned.name} of agent ${id}.`;
|
|
1592
|
+
// Another promotion (or a create) may take the id between the read and the write: the next one is tried.
|
|
1593
|
+
for (let tries = 0;; tries++) {
|
|
1594
|
+
const all = [...(await agents.list()), ...(await agents.list({ archived: true }))];
|
|
1595
|
+
const taken = new Set(all.flatMap((entry) => [entry.agent.id, entry.agent.name]));
|
|
1596
|
+
let n = 1;
|
|
1597
|
+
while (taken.has(n === 1 ? learned.name : `${learned.name}-${n}`))
|
|
1598
|
+
n++;
|
|
1599
|
+
const agentId = n === 1 ? learned.name : `${learned.name}-${n}`;
|
|
1600
|
+
try {
|
|
1601
|
+
return await createAgentOf({ definition: promoted(agentId), note });
|
|
1602
|
+
}
|
|
1603
|
+
catch (error) {
|
|
1604
|
+
if (!(error instanceof ApiError && error.code === "agent_exists") || tries >= 4)
|
|
1605
|
+
throw error;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1517
1609
|
/** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
|
|
1518
1610
|
* servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
|
|
1519
1611
|
* agent made as POST /agents makes one, its MCP tools at the owner's own settings save those granted, set to allow (a
|
|
@@ -1533,6 +1625,13 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1533
1625
|
const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
|
|
1534
1626
|
throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`)].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 }))] });
|
|
1535
1627
|
}
|
|
1628
|
+
// The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
|
|
1629
|
+
// agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
|
|
1630
|
+
// whose entries is met (a shell alone, where there is none) refuses the apply: nothing is made.
|
|
1631
|
+
const pick = pickComputer(pkg, await shellHere());
|
|
1632
|
+
if (pick && "refused" in pick)
|
|
1633
|
+
throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: COMPUTER_FIX }] });
|
|
1634
|
+
const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
|
|
1536
1635
|
// An MCP server the package can do without is skipped, and said: its tools are not granted.
|
|
1537
1636
|
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.` }));
|
|
1538
1637
|
const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
|
|
@@ -1540,7 +1639,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1540
1639
|
const model = picked.model;
|
|
1541
1640
|
// Which model the agent got, where it is not the package's: a note, never a lack. The agent runs; only the package's
|
|
1542
1641
|
// choice was not an option here (not_set_up_here would read as a run refused until the host has something).
|
|
1543
|
-
|
|
1642
|
+
// The model of each tier its subagents run on (packageTiers): the package's where this server runs it.
|
|
1643
|
+
const tiers = await packageTiers(env, pkg.model, harness ?? DEFAULT_HARNESS, model);
|
|
1644
|
+
const modelWarnings = [...("warning" in picked && picked.warning ? [picked.warning] : []), ...(tiers.warning ? [tiers.warning] : [])].map((message) => ({ field: "model", reason: "not_an_option", message }));
|
|
1544
1645
|
const defaultTools = "place" in newAgentPlace(boxOffers) ? NEW_AGENT_TOOLS : [];
|
|
1545
1646
|
// A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
|
|
1546
1647
|
const server = settings.get();
|
|
@@ -1549,7 +1650,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1549
1650
|
// The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
|
|
1550
1651
|
// never), else ask. Deny and pins hold either way.
|
|
1551
1652
|
const chosenApprovals = approvals ?? pkg.approvals;
|
|
1552
|
-
const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), ...(chosenApprovals ? { approvals: chosenApprovals } : {}) }, templateDeps);
|
|
1653
|
+
const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
|
|
1553
1654
|
// Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
|
|
1554
1655
|
// from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
|
|
1555
1656
|
const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
|
|
@@ -1609,12 +1710,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1609
1710
|
const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
|
|
1610
1711
|
// Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
|
|
1611
1712
|
const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
|
|
1612
|
-
? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message:
|
|
1713
|
+
? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: githubTriggerUnconnected(pkg.name, trigger.source) } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
|
|
1613
1714
|
: []));
|
|
1614
1715
|
// Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
|
|
1615
1716
|
// (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
|
|
1616
1717
|
const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
|
|
1617
|
-
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, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
|
|
1718
|
+
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, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
|
|
1618
1719
|
return { applied, minted };
|
|
1619
1720
|
}
|
|
1620
1721
|
/** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
|
|
@@ -1663,11 +1764,39 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1663
1764
|
* tunnel's own port, say); else, with no Host, its own. Links made outside a request (the owner's, the webhooks') are
|
|
1664
1765
|
* at the public URL or the server's own address. */
|
|
1665
1766
|
const linkOrigin = (req) => (options.publicUrl ?? (req.headers.host ? ownOrigin(req) : url)).replace(/\/+$/, "");
|
|
1767
|
+
/** A run body's `mcp_auth` taken out of it, before anything else reads the body: the credentials a run's caller hands
|
|
1768
|
+
* its per_run MCP servers for this run alone (mcp-probe.ts mcpAuthOf). They never reach the run's saved body, its
|
|
1769
|
+
* timeline, an idempotency fingerprint (a retry with a fresh credential replays its first answer) or a log: only the
|
|
1770
|
+
* seal `sealer` makes, which seals them for the run's id into its launch row (store/seal.ts sealRunMcpAuth), bound to
|
|
1771
|
+
* each server's origin then. The request calls `sealer` only for new work, inside its idempotent work: there each
|
|
1772
|
+
* entry must name a saved per_run server, else 422, nothing written. A retry its key already answered replays that
|
|
1773
|
+
* answer even when the server has since changed or gone, since it does no new work. */
|
|
1774
|
+
function handedMcpAuth(body) {
|
|
1775
|
+
if (body.mcp_auth === undefined)
|
|
1776
|
+
return { body, sealer: async () => undefined };
|
|
1777
|
+
const { mcp_auth, ...rest } = body;
|
|
1778
|
+
const sealer = async () => {
|
|
1779
|
+
const issues = [];
|
|
1780
|
+
const handed = mcpAuthOf(mcp_auth, issues);
|
|
1781
|
+
const auth = {};
|
|
1782
|
+
for (const [server, headers] of Object.entries(handed ?? {})) {
|
|
1783
|
+
const row = await store.mcp.server(server);
|
|
1784
|
+
if (row?.auth !== "per_run")
|
|
1785
|
+
issues.push({ field: `mcp_auth.${server}`, reason: "not_an_option", message: row ? `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` : `No MCP server ${server} is saved here.` });
|
|
1786
|
+
else
|
|
1787
|
+
auth[server] = { headers, origin: new URL(row.url).origin };
|
|
1788
|
+
}
|
|
1789
|
+
if (issues.length)
|
|
1790
|
+
throw invalid(issues);
|
|
1791
|
+
return (runId) => sealRunMcpAuth(sealKey, runId, auth);
|
|
1792
|
+
};
|
|
1793
|
+
return { body: rest, sealer };
|
|
1794
|
+
}
|
|
1666
1795
|
async function createRun(req, agentId) {
|
|
1667
1796
|
const entry = await needAgent(agentId);
|
|
1668
1797
|
if (entry.agent.archivedAt)
|
|
1669
1798
|
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() } });
|
|
1670
|
-
const body = await bodyOf(req);
|
|
1799
|
+
const { body, sealer } = handedMcpAuth(await bodyOf(req));
|
|
1671
1800
|
return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
|
|
1672
1801
|
// A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
|
|
1673
1802
|
const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
|
|
@@ -1677,7 +1806,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1677
1806
|
const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
|
|
1678
1807
|
return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
|
|
1679
1808
|
}
|
|
1680
|
-
const
|
|
1809
|
+
const seal = await sealer();
|
|
1810
|
+
const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
|
|
1681
1811
|
// Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
|
|
1682
1812
|
return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
|
|
1683
1813
|
});
|
|
@@ -1688,7 +1818,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1688
1818
|
* Its first run makes the agent, a version's first run its revision; a later run of the version reuses both
|
|
1689
1819
|
* (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
|
|
1690
1820
|
async function createInlineRun(req) {
|
|
1691
|
-
const body = await bodyOf(req);
|
|
1821
|
+
const { body, sealer } = handedMcpAuth(await bodyOf(req));
|
|
1692
1822
|
const { external, definition, skills, note, revision: pinned, ...run } = body;
|
|
1693
1823
|
const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
|
|
1694
1824
|
const issues = [
|
|
@@ -1722,7 +1852,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1722
1852
|
const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
|
|
1723
1853
|
return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
|
|
1724
1854
|
}
|
|
1725
|
-
const
|
|
1855
|
+
const seal = await sealer();
|
|
1856
|
+
const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}) });
|
|
1726
1857
|
return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
|
|
1727
1858
|
});
|
|
1728
1859
|
}
|
|
@@ -1776,7 +1907,15 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1776
1907
|
}
|
|
1777
1908
|
/** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
|
|
1778
1909
|
function runBodyIssues(body) {
|
|
1779
|
-
const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id"]);
|
|
1910
|
+
const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "archil_disk"]);
|
|
1911
|
+
if (body.archil_disk !== undefined) {
|
|
1912
|
+
const disk = body.archil_disk;
|
|
1913
|
+
const extra = isObject(disk) ? Object.keys(disk).filter((key) => key !== "disk_id") : [];
|
|
1914
|
+
if (!isObject(disk) || typeof disk.disk_id !== "string" || !ARCHIL_DISK_ID.test(disk.disk_id))
|
|
1915
|
+
issues.push({ field: "archil_disk.disk_id", reason: "wrong_type", message: "archil_disk is { disk_id }: the disk id Archil returned when the disk was made (dsk- and 16 hex digits; Archil's API addresses disks by id, not owner/name), in this server's Archil region" });
|
|
1916
|
+
else if (extra.length)
|
|
1917
|
+
issues.push({ field: `archil_disk.${extra[0]}`, reason: "not_allowed", message: "archil_disk names a disk by its id alone: its region is this server's Archil key's, and no key is ever sent with a run", fix: `Remove ${extra.map((key) => `archil_disk.${key}`).join(" and ")}.` });
|
|
1918
|
+
}
|
|
1780
1919
|
if (!isObject(body.input))
|
|
1781
1920
|
issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
|
|
1782
1921
|
if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
|
|
@@ -1918,30 +2057,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1918
2057
|
// kept, as a settled run's journal no longer changes, keyed by its end, so a run opened again and ended again is read
|
|
1919
2058
|
// again. A run whose journal cannot be read leaves it all tokens.
|
|
1920
2059
|
const endedMeters = new Map();
|
|
1921
|
-
// 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
|
|
1922
|
-
// its decisions' receipts, which its root store alone does not hold), kept as its meters are; undefined when it saved
|
|
1923
|
-
// none (a run whose cost is known, or one ended before the figure was kept).
|
|
1924
|
-
const endedSoFar = new Map();
|
|
1925
|
-
const savedSoFarOf = (row) => {
|
|
1926
|
-
const key = `${row.id} ${row.endedAt}`;
|
|
1927
|
-
if (!endedSoFar.has(key)) {
|
|
1928
|
-
// 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
|
|
1929
|
-
// (runStorePath is gone). Undefined until the usage route reads it over the store.
|
|
1930
|
-
let usd;
|
|
1931
|
-
{
|
|
1932
|
-
usd = undefined;
|
|
1933
|
-
}
|
|
1934
|
-
endedSoFar.set(key, usd);
|
|
1935
|
-
}
|
|
1936
|
-
return endedSoFar.get(key);
|
|
1937
|
-
};
|
|
1938
2060
|
const metersOf = async (row) => {
|
|
1939
2061
|
const key = `${row.id} ${row.endedAt}`;
|
|
1940
2062
|
let meters = endedMeters.get(key);
|
|
1941
2063
|
if (!meters) {
|
|
1942
2064
|
// An ended run's meter figures over the one store: cap.ts meterFiguresFrom over A's journal, its paid tools' charges
|
|
1943
|
-
// folded back from the paid-tools session (store-reads/journal withPaidCosts)
|
|
1944
|
-
// run's own database — the same figures (the money-parity rule).
|
|
2065
|
+
// folded back from the paid-tools session (store-reads/journal withPaidCosts).
|
|
1945
2066
|
meters = await metersOverStore(store, row.id, ctx);
|
|
1946
2067
|
endedMeters.set(key, meters);
|
|
1947
2068
|
}
|
|
@@ -1996,7 +2117,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1996
2117
|
// A run whose cost is unknown still spent what is known of it (so_far: each meter's known dollars): that is in the
|
|
1997
2118
|
// total and its lines, and the run is counted unpriced, so a total is never below a line of its own and reads as
|
|
1998
2119
|
// the lower bound unpriced_runs says it is.
|
|
1999
|
-
const soFar = usd !== null || !read ? 0 :
|
|
2120
|
+
const soFar = usd !== null || !read ? 0 : read.known.tokens + read.known.browser + read.known.others;
|
|
2000
2121
|
const meters = group === "meter" && usd !== 0 ? read : undefined;
|
|
2001
2122
|
if (meters && meters.browser.usd !== 0)
|
|
2002
2123
|
browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
|
|
@@ -2324,6 +2445,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2324
2445
|
authFailed(`/v2${path}`, "approve_without_session");
|
|
2325
2446
|
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).");
|
|
2326
2447
|
}
|
|
2448
|
+
// Making a learned workflow an agent of its own gives it runs of its own, outside any agentic run's turn: the owner's
|
|
2449
|
+
// click alone, the same session as an approval.
|
|
2450
|
+
if (found.name === "promoteLearnedWorkflow" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
2451
|
+
authFailed(`/v2${path}`, "promote_without_session");
|
|
2452
|
+
throw new ApiError("forbidden", owner ? "Making a learned workflow an agent takes the owner's password sign-in in the console, never a token." : "Making a learned workflow an agent takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
2453
|
+
}
|
|
2327
2454
|
// A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
|
|
2328
2455
|
// approving a note is (never a token a run, an MCP client or a script may hold).
|
|
2329
2456
|
if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
@@ -2391,7 +2518,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2391
2518
|
case "getAgent": {
|
|
2392
2519
|
const entry = await needAgent(id);
|
|
2393
2520
|
// The tools its current revision grants, as capabilities list them, each with its provider for this agent.
|
|
2394
|
-
|
|
2521
|
+
// A tool of bash's family the agent's computer gives no shell for reads unavailable (runShellOf).
|
|
2522
|
+
const revision = entry.revision;
|
|
2523
|
+
const tools = revision ? agentTools(env, settings.get(), await toolingOf(revision), caps.tools.map((tool) => tool.name), await shellOfRevision(revision)) : [];
|
|
2395
2524
|
return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
|
|
2396
2525
|
}
|
|
2397
2526
|
case "updateDefinition": {
|
|
@@ -2415,6 +2544,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2415
2544
|
let warnings = [];
|
|
2416
2545
|
const check = async (revision) => void (warnings = await saveable(revision));
|
|
2417
2546
|
const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
|
|
2547
|
+
reconcileComputer(id);
|
|
2418
2548
|
return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
|
|
2419
2549
|
}
|
|
2420
2550
|
case "listRevisions": {
|
|
@@ -2438,6 +2568,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2438
2568
|
if (!(await agents.revision(id, revision)))
|
|
2439
2569
|
throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
|
|
2440
2570
|
const moved = await agents.setCurrent(entry, revision);
|
|
2571
|
+
reconcileComputer(id);
|
|
2441
2572
|
return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
|
|
2442
2573
|
}
|
|
2443
2574
|
case "archiveAgent":
|
|
@@ -2450,9 +2581,22 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2450
2581
|
// which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
|
|
2451
2582
|
// the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
|
|
2452
2583
|
const triggersOff = found.name === "archiveAgent" ? await triggers.agentArchived(id) : await triggers.agentUnarchived(id);
|
|
2584
|
+
// An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
|
|
2585
|
+
if (found.name === "archiveAgent")
|
|
2586
|
+
reconcileComputer(id);
|
|
2453
2587
|
const entry = await needAgent(id);
|
|
2454
2588
|
return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), triggers_off: triggersOff }, { etag: etagOf(entry) });
|
|
2455
2589
|
}
|
|
2590
|
+
case "getAgentArchil":
|
|
2591
|
+
case "deleteAgentArchil": {
|
|
2592
|
+
// The agent's Archil disk (archil-routes.ts): its rules are the handler's; the dispatch reads the agent (archived, or
|
|
2593
|
+
// managed by its source) and how to count the live runs on a disk.
|
|
2594
|
+
const entry = await needAgent(id);
|
|
2595
|
+
const controller = new AbortController();
|
|
2596
|
+
req.once("close", () => controller.abort());
|
|
2597
|
+
const agent = { id, archived: entry.agent.archivedAt != null, external: entry.agent.externalRef !== null, liveOn: (diskId) => liveRunsOnDisk(store.runs, id, diskId) };
|
|
2598
|
+
return send(res, 200, await archilRoute(archil, found.name, { agent, signal: controller.signal }), { "cache-control": "no-store" });
|
|
2599
|
+
}
|
|
2456
2600
|
case "forgetSignIn": {
|
|
2457
2601
|
await needAgent(id);
|
|
2458
2602
|
let key;
|
|
@@ -2495,8 +2639,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2495
2639
|
const run = await needRun(id);
|
|
2496
2640
|
if (run.kind === "workflow")
|
|
2497
2641
|
throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here: its workflow runs to its end, or a cancel ends it.");
|
|
2498
|
-
const body = await bodyOf(req);
|
|
2642
|
+
const { body, sealer } = handedMcpAuth(await bodyOf(req));
|
|
2499
2643
|
const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
|
|
2644
|
+
const seal = await sealer();
|
|
2500
2645
|
const extra = unknownFields(body, ["content"]);
|
|
2501
2646
|
if (extra.length)
|
|
2502
2647
|
throw invalid(extra);
|
|
@@ -2505,7 +2650,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2505
2650
|
throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
|
|
2506
2651
|
if (content.length > MAX_MESSAGE)
|
|
2507
2652
|
throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
|
|
2508
|
-
|
|
2653
|
+
// Its mcp_auth replaces the run's handed credentials in the steer's own write, so the turn it starts uses them.
|
|
2654
|
+
const { mode, messageId } = await message(store, run, content, seal ? { launchSealed: seal(run.id) } : {});
|
|
2509
2655
|
// The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
|
|
2510
2656
|
const { status, state } = await runStatusState(run.id);
|
|
2511
2657
|
return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
|
|
@@ -2513,7 +2659,11 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2513
2659
|
return send(res, answer.status, answer.body, answer.headers);
|
|
2514
2660
|
}
|
|
2515
2661
|
case "raiseRunCap": {
|
|
2516
|
-
|
|
2662
|
+
// The run is read once its body is in, right before the raise row is written: the pause the answer names
|
|
2663
|
+
// (raiseFollowUpId) is the one the run stands at when its runner takes that row, never one an earlier raise ended
|
|
2664
|
+
// while this body was on its way.
|
|
2665
|
+
if (!ID.test(id) || !(await store.runs.get(id)))
|
|
2666
|
+
throw new ApiError("not_found", `no run ${id}`);
|
|
2517
2667
|
const body = await bodyOf(req);
|
|
2518
2668
|
const extra = unknownFields(body, ["max_cost_usd"]);
|
|
2519
2669
|
if (extra.length)
|
|
@@ -2521,6 +2671,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2521
2671
|
const cap = body.max_cost_usd;
|
|
2522
2672
|
if (!(typeof cap === "number" && Number.isFinite(cap) && cap > 0))
|
|
2523
2673
|
throw invalid([{ field: "max_cost_usd", reason: cap === undefined ? "missing" : "wrong_type", message: "max_cost_usd is a number above 0" }]);
|
|
2674
|
+
const run = await needRun(id);
|
|
2524
2675
|
const now = run.maxCostUsd;
|
|
2525
2676
|
if (now === undefined)
|
|
2526
2677
|
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." }]);
|
|
@@ -2580,6 +2731,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2580
2731
|
},
|
|
2581
2732
|
computer: () => computerOf(kept, env, family),
|
|
2582
2733
|
hold: () => hold,
|
|
2734
|
+
// A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
|
|
2735
|
+
// row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
|
|
2736
|
+
// For an ended run, nothing, and its row goes.
|
|
2737
|
+
ended: () => screenWaitEnded(store.settings, run.id, run.terminal),
|
|
2583
2738
|
});
|
|
2584
2739
|
if (family === "browser")
|
|
2585
2740
|
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" });
|
|
@@ -2893,6 +3048,20 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2893
3048
|
const { counts, impact, notes } = await agentLearningOverStore(store, id);
|
|
2894
3049
|
return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, notes));
|
|
2895
3050
|
}
|
|
3051
|
+
case "getLearningCost": {
|
|
3052
|
+
await needAgent(id);
|
|
3053
|
+
// The agent's cost per run over the one store (agentCostOverStore): each ended run's figures and path, aggregates only.
|
|
3054
|
+
const { limit, csv } = learningCostQuery(url);
|
|
3055
|
+
const read = await agentCostOverStore(store, id, limit);
|
|
3056
|
+
// Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
|
|
3057
|
+
const shown = await learningShown(id);
|
|
3058
|
+
const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })) };
|
|
3059
|
+
if (csv) {
|
|
3060
|
+
res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-disposition": `attachment; filename="${id}-cost-per-run.csv"` });
|
|
3061
|
+
return void res.end(costCsv(cost.runs));
|
|
3062
|
+
}
|
|
3063
|
+
return send(res, 200, { agent: id, ...cost });
|
|
3064
|
+
}
|
|
2896
3065
|
case "listLearningNotes":
|
|
2897
3066
|
case "listLearningLog":
|
|
2898
3067
|
await needAgent(id);
|
|
@@ -2920,6 +3089,16 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2920
3089
|
const located = written.status === 201 && shown.name(written.file) === written.file;
|
|
2921
3090
|
return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
|
|
2922
3091
|
}
|
|
3092
|
+
case "promoteLearnedWorkflow": {
|
|
3093
|
+
// The source read once the body is in, as it is then: what promoteOf checks and what it copies are that one read.
|
|
3094
|
+
const body = await bodyOf(req);
|
|
3095
|
+
const source = await needAgent(id);
|
|
3096
|
+
const answer = await idempotent(req, `/agents/${id}/learning/workflows/${second}/promote`, body, async () => {
|
|
3097
|
+
const { entry, warnings } = await promoteOf(source, second, body);
|
|
3098
|
+
return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
|
|
3099
|
+
});
|
|
3100
|
+
return send(res, answer.status, answer.body, answer.headers);
|
|
3101
|
+
}
|
|
2923
3102
|
case "getRunLearning": {
|
|
2924
3103
|
const run = await needRun(id);
|
|
2925
3104
|
// The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
|
|
@@ -2968,8 +3147,19 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2968
3147
|
// Its minted secret to the owner's session alone (trigger-secrets-shown.ts); the token gets secret_set and the words.
|
|
2969
3148
|
return send(res, answer.status, secret && !replayed ? triggerMade(first, secret, mayHoldSecrets(req), new Date().toISOString()) : answer.body, answer.headers);
|
|
2970
3149
|
}
|
|
2971
|
-
case "listTemplates":
|
|
2972
|
-
|
|
3150
|
+
case "listTemplates": {
|
|
3151
|
+
// Each package's computer list read against this server now: what an apply here would pick (pickComputer).
|
|
3152
|
+
const here = templates.some((one) => one.computer) ? await shellHere() : undefined;
|
|
3153
|
+
const pickView = (pkg) => {
|
|
3154
|
+
const pick = here && pickComputer(pkg, here);
|
|
3155
|
+
if (!pick)
|
|
3156
|
+
return null;
|
|
3157
|
+
if ("refused" in pick)
|
|
3158
|
+
return { entry: null, computer: null, shell: null, dropped: [], note: pick.refused };
|
|
3159
|
+
return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
|
|
3160
|
+
};
|
|
3161
|
+
return send(res, 200, { templates: templates.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
|
|
3162
|
+
}
|
|
2973
3163
|
case "applyTemplate": {
|
|
2974
3164
|
const pkg = templates.find((t) => t.name === id);
|
|
2975
3165
|
if (!pkg)
|
|
@@ -3227,6 +3417,16 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3227
3417
|
return null;
|
|
3228
3418
|
return { ...endOf(row), notice: { run_id: id, agent_id: row.agentId, status: String(summary.status), title: typeof summary.title === "string" ? summary.title : "" } };
|
|
3229
3419
|
};
|
|
3420
|
+
/** The run-end read's look at a run: its end from its row alone when it has none, or one told already; else its
|
|
3421
|
+
* endNotice. The run's view redacts the run's words (its title, its output) on every build, and the newest runs are
|
|
3422
|
+
* read every RUN_ENDS_POLL_MS, so only an end still to tell builds one. */
|
|
3423
|
+
const endToTell = async (id) => {
|
|
3424
|
+
const row = await store.runs.get(id);
|
|
3425
|
+
if (!row)
|
|
3426
|
+
return null;
|
|
3427
|
+
const end = endOf(row);
|
|
3428
|
+
return !end.endedAt || toldEnds.get(id) === end.endedAt ? end : endNotice(id);
|
|
3429
|
+
};
|
|
3230
3430
|
const toldEnds = new Map();
|
|
3231
3431
|
/** 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
|
|
3232
3432
|
* is not read again, and a new wait comes with a new claim, so a new epoch. */
|
|
@@ -3282,7 +3482,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3282
3482
|
for (const id of new Set([...openRuns, ...newest.map((row) => row.id)])) {
|
|
3283
3483
|
if (open.has(id) || closing)
|
|
3284
3484
|
continue;
|
|
3285
|
-
const now = await
|
|
3485
|
+
const now = await endToTell(id).catch(() => undefined);
|
|
3286
3486
|
// Unread (a busy store): read again at the next turn, never lost.
|
|
3287
3487
|
if (now === undefined) {
|
|
3288
3488
|
open.add(id);
|
|
@@ -3290,7 +3490,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3290
3490
|
}
|
|
3291
3491
|
readWaits.delete(id);
|
|
3292
3492
|
heldReadAt.delete(id);
|
|
3293
|
-
if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
|
|
3493
|
+
if (!now?.endedAt || !("notice" in now) || toldEnds.get(id) === now.endedAt)
|
|
3294
3494
|
continue;
|
|
3295
3495
|
if ((await webhooks.emit("run.ended", now.notice, now.endedAt)) !== "unsaved")
|
|
3296
3496
|
toldEnds.set(id, now.endedAt);
|
|
@@ -3339,10 +3539,6 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3339
3539
|
await Promise.all([...workers.values()].map((w) => w.exit));
|
|
3340
3540
|
await importing;
|
|
3341
3541
|
await installStopped;
|
|
3342
|
-
// Before the store closes: the image's last record lands first (box-image.ts), never after the next server's start.
|
|
3343
|
-
await image?.close();
|
|
3344
|
-
// The box network proxy goes with the server that owns it (box-egress-vm.ts); its volume stays for the next start.
|
|
3345
|
-
await egress?.close();
|
|
3346
3542
|
// The ends' follower stops before the webhooks it feeds and the store it reads.
|
|
3347
3543
|
clearTimeout(endsTimer);
|
|
3348
3544
|
await endsRead;
|
|
@@ -3352,8 +3548,11 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3352
3548
|
await new Promise((done) => (server.close(done), server.closeAllConnections()));
|
|
3353
3549
|
await mcpStopped;
|
|
3354
3550
|
await githubStopped;
|
|
3551
|
+
// --faux-github's fake GitHub API, once nothing asks it anything.
|
|
3552
|
+
await fauxGitHub?.close();
|
|
3355
3553
|
// The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
|
|
3356
3554
|
await store.close();
|
|
3555
|
+
dataLock.release();
|
|
3357
3556
|
seal.release();
|
|
3358
3557
|
}
|
|
3359
3558
|
return {
|