@parcha/agentrun-serve 0.1.0-beta.30 → 0.1.0-beta.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +472 -0
- package/NOTICE +18 -0
- package/README.md +1042 -240
- package/dist/adapter-facts.d.ts +3 -0
- package/dist/adapter-facts.js +5 -0
- package/dist/adapters.d.ts +64 -140
- package/dist/adapters.js +153 -377
- package/dist/agents-store.d.ts +146 -0
- package/dist/agents-store.js +359 -0
- package/dist/agents.d.ts +12 -5
- package/dist/agents.js +40 -17
- package/dist/app.d.ts +2 -4
- package/dist/app.js +227 -97
- package/dist/approvals.d.ts +4 -0
- package/dist/approvals.js +7 -0
- package/dist/archil-routes.d.ts +45 -0
- package/dist/archil-routes.js +150 -0
- package/dist/archil-settings.d.ts +30 -0
- package/dist/archil-settings.js +34 -0
- package/dist/background.d.ts +2 -1
- package/dist/background.js +69 -29
- package/dist/bounds.d.ts +26 -0
- package/dist/bounds.js +137 -0
- package/dist/box-egress-vm.d.ts +126 -0
- package/dist/box-egress-vm.js +364 -0
- package/dist/box-egress.d.ts +19 -8
- package/dist/box-egress.js +27 -15
- package/dist/box-paths.d.ts +59 -0
- package/dist/box-paths.js +92 -0
- package/dist/box-relay-vm.d.ts +4 -0
- package/dist/box-relay-vm.js +103 -55
- package/dist/box-relay.d.ts +2 -0
- package/dist/box-relay.js +2 -2
- package/dist/boxes.d.ts +20 -3
- package/dist/boxes.js +67 -14
- package/dist/browser-commands.d.ts +43 -0
- package/dist/browser-commands.js +154 -0
- package/dist/browser-cost.d.ts +30 -3
- package/dist/browser-cost.js +276 -21
- package/dist/browser-live.d.ts +124 -0
- package/dist/browser-live.js +324 -0
- package/dist/browser-person.d.ts +168 -0
- package/dist/browser-person.js +769 -0
- package/dist/budget.d.ts +80 -0
- package/dist/budget.js +211 -0
- package/dist/cap.d.ts +274 -63
- package/dist/cap.js +599 -188
- package/dist/cli.js +226 -16
- package/dist/coding-tools.d.ts +13 -1
- package/dist/coding-tools.js +107 -5
- package/dist/computer-adb.d.ts +12 -0
- package/dist/computer-adb.js +14 -0
- package/dist/computer-commands.d.ts +103 -0
- package/dist/computer-commands.js +256 -0
- package/dist/computer-keys.d.ts +68 -0
- package/dist/computer-keys.js +148 -0
- package/dist/computer-routes.d.ts +38 -0
- package/dist/computer-routes.js +56 -0
- package/dist/computer-setting.d.ts +37 -0
- package/dist/computer-setting.js +47 -0
- package/dist/computer-view.d.ts +38 -0
- package/dist/computer-view.js +14 -0
- package/dist/computers.d.ts +137 -0
- package/dist/computers.js +197 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
- package/dist/console/assets/index-35-7aeIZ.js +519 -0
- package/dist/console/assets/index-Cejbov-Y.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +2 -0
- package/dist/console-links.js +6 -0
- package/dist/decision-cap.d.ts +63 -0
- package/dist/decision-cap.js +163 -0
- package/dist/decision-rows.d.ts +5 -2
- package/dist/decision-rows.js +8 -6
- package/dist/decisions.d.ts +31 -4
- package/dist/decisions.js +66 -8
- package/dist/disk.d.ts +33 -0
- package/dist/disk.js +85 -0
- package/dist/door-line.d.ts +23 -0
- package/dist/door-line.js +83 -0
- package/dist/egress-proxy.d.ts +45 -0
- package/dist/egress-proxy.js +416 -0
- package/dist/egress-table.d.ts +24 -0
- package/dist/egress-table.js +165 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +22 -2
- package/dist/exa-keyless.js +1 -1
- package/dist/explain.d.ts +22 -0
- package/dist/explain.js +207 -0
- package/dist/faux-computers.d.ts +35 -0
- package/dist/faux-computers.js +126 -0
- package/dist/file-types.d.ts +4 -0
- package/dist/file-types.js +11 -0
- package/dist/files.d.ts +3 -32
- package/dist/files.js +9 -117
- package/dist/github-connection.d.ts +207 -0
- package/dist/github-connection.js +595 -0
- package/dist/github.d.ts +64 -0
- package/dist/github.js +119 -0
- package/dist/grade.d.ts +14 -44
- package/dist/grade.js +55 -233
- package/dist/graph-served.d.ts +23 -2
- package/dist/graph-served.js +44 -3
- package/dist/graph-view.d.ts +7 -3
- package/dist/graph-view.js +26 -15
- package/dist/handed-values.d.ts +23 -0
- package/dist/handed-values.js +36 -0
- package/dist/harness-app.d.ts +33 -4
- package/dist/harness-app.js +539 -85
- package/dist/harness-install.d.ts +120 -0
- package/dist/harness-install.js +359 -0
- package/dist/harness-opencode/adapter.js +42 -8
- package/dist/harness-opencode/facts.d.ts +2 -0
- package/dist/harness-opencode/facts.js +28 -0
- package/dist/harness-opencode/harness.d.ts +4 -0
- package/dist/harness-opencode/harness.js +38 -5
- package/dist/harness-opencode/host/policy.js +11 -3
- package/dist/harness-opencode/transcript.d.ts +25 -0
- package/dist/harness-opencode/transcript.js +81 -0
- package/dist/harness-table.d.ts +75 -0
- package/dist/harness-table.js +145 -0
- package/dist/harness.d.ts +7 -28
- package/dist/harness.js +15 -41
- package/dist/heard.d.ts +12 -0
- package/dist/heard.js +45 -0
- package/dist/helper-env.d.ts +4 -0
- package/dist/helper-env.js +14 -0
- package/dist/home-path.d.ts +0 -4
- package/dist/home-path.js +3 -17
- package/dist/host-check.d.ts +13 -0
- package/dist/host-check.js +35 -0
- package/dist/host-tools.d.ts +51 -8
- package/dist/host-tools.js +108 -117
- package/dist/host.d.ts +12 -6
- package/dist/host.js +30 -24
- package/dist/hosted-search.d.ts +3 -0
- package/dist/hosted-search.js +5 -3
- package/dist/import-proxy.d.ts +42 -0
- package/dist/import-proxy.js +105 -0
- package/dist/import-summary.js +4 -8
- package/dist/import-worker.d.ts +2 -3
- package/dist/import-worker.js +18 -16
- package/dist/import.d.ts +37 -17
- package/dist/import.js +208 -222
- package/dist/key-meta.d.ts +26 -0
- package/dist/key-meta.js +30 -0
- package/dist/key-refusal.d.ts +4 -1
- package/dist/key-refusal.js +20 -7
- package/dist/key-words.d.ts +37 -0
- package/dist/key-words.js +40 -0
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +2 -2
- package/dist/learn/commit.d.ts +86 -0
- package/dist/learn/commit.js +182 -0
- package/dist/learn/folder.d.ts +296 -0
- package/dist/learn/folder.js +796 -0
- package/dist/learn/grade.d.ts +25 -9
- package/dist/learn/grade.js +98 -50
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/learning.sh +366 -0
- package/dist/learn/reflect.d.ts +12 -5
- package/dist/learn/reflect.js +72 -41
- package/dist/learn/secrets.d.ts +15 -7
- package/dist/learn/secrets.js +66 -16
- package/dist/learn/seed-check.d.ts +74 -0
- package/dist/learn/seed-check.js +103 -0
- package/dist/learn/skills.d.ts +7 -1
- package/dist/learn/skills.js +21 -4
- package/dist/learned-workflow.d.ts +12 -2
- package/dist/learned-workflow.js +9 -5
- package/dist/learning-routes.d.ts +107 -31
- package/dist/learning-routes.js +358 -403
- package/dist/learning-run.d.ts +61 -54
- package/dist/learning-run.js +183 -205
- package/dist/learning-words.d.ts +10 -8
- package/dist/learning-words.js +29 -13
- package/dist/learning.d.ts +186 -113
- package/dist/learning.js +345 -381
- package/dist/live/stream.d.ts +30 -0
- package/dist/live/stream.js +175 -0
- package/dist/live/translate.d.ts +52 -0
- package/dist/live/translate.js +276 -0
- package/dist/llm.js +3 -0
- package/dist/llms.txt +1 -0
- package/dist/local-models.d.ts +23 -0
- package/dist/local-models.js +35 -0
- package/dist/mcp-gateway.d.ts +129 -0
- package/dist/mcp-gateway.js +508 -0
- package/dist/mcp-meta.d.ts +20 -0
- package/dist/mcp-meta.js +50 -0
- package/dist/mcp-oauth.d.ts +172 -0
- package/dist/mcp-oauth.js +403 -0
- package/dist/mcp-private-hosts.d.ts +48 -0
- package/dist/mcp-private-hosts.js +141 -0
- package/dist/mcp-probe.d.ts +101 -0
- package/dist/mcp-probe.js +359 -0
- package/dist/mcp-secret-writes.d.ts +23 -0
- package/dist/mcp-secret-writes.js +60 -0
- package/dist/mcp-servers-store.d.ts +251 -0
- package/dist/mcp-servers-store.js +447 -0
- package/dist/mcp-servers.d.ts +185 -34
- package/dist/mcp-servers.js +304 -298
- package/dist/mcp-store.d.ts +103 -0
- package/dist/mcp-store.js +123 -0
- package/dist/mcp.js +22 -21
- package/dist/model.d.ts +77 -59
- package/dist/model.js +237 -98
- package/dist/monid.d.ts +8 -6
- package/dist/monid.js +39 -25
- package/dist/openapi.d.ts +22 -1
- package/dist/openapi.js +965 -111
- package/dist/owner.d.ts +46 -10
- package/dist/owner.js +123 -43
- package/dist/page.d.ts +12 -0
- package/dist/page.js +28 -2
- package/dist/paid-calls.d.ts +71 -2
- package/dist/paid-calls.js +125 -5
- package/dist/pdf-pages.d.ts +16 -14
- package/dist/pdf-pages.js +88 -58
- package/dist/place.d.ts +18 -15
- package/dist/place.js +36 -18
- package/dist/port-models.d.ts +53 -0
- package/dist/port-models.js +93 -0
- package/dist/print.d.ts +7 -0
- package/dist/print.js +13 -0
- package/dist/propose.d.ts +9 -8
- package/dist/propose.js +82 -49
- package/dist/provider.d.ts +85 -0
- package/dist/provider.js +178 -0
- package/dist/push-handler.d.ts +52 -0
- package/dist/push-handler.js +165 -0
- package/dist/refusal-words.d.ts +23 -0
- package/dist/refusal-words.js +25 -0
- package/dist/request-start.d.ts +6 -1
- package/dist/request-start.js +41 -10
- package/dist/result.d.ts +13 -2
- package/dist/result.js +4 -5
- package/dist/run-box.d.ts +22 -3
- package/dist/run-box.js +91 -20
- package/dist/run-computer.d.ts +24 -0
- package/dist/run-computer.js +15 -0
- package/dist/run-cut.d.ts +33 -0
- package/dist/run-cut.js +42 -0
- package/dist/run-db.d.ts +64 -0
- package/dist/run-db.js +155 -0
- package/dist/run-files.d.ts +31 -0
- package/dist/run-files.js +125 -0
- package/dist/run-holder.d.ts +52 -0
- package/dist/run-holder.js +139 -0
- package/dist/run-launch.d.ts +72 -0
- package/dist/run-launch.js +108 -0
- package/dist/run-learning-served.d.ts +43 -0
- package/dist/run-learning-served.js +16 -0
- package/dist/run-manifest.d.ts +7 -6
- package/dist/run-manifest.js +20 -10
- package/dist/run-reads-over-store.d.ts +102 -0
- package/dist/run-reads-over-store.js +151 -0
- package/dist/run-timeline-served.d.ts +13 -0
- package/dist/run-timeline-served.js +69 -0
- package/dist/run-view.d.ts +436 -0
- package/dist/run-view.js +620 -0
- package/dist/runnable.d.ts +36 -4
- package/dist/runnable.js +157 -31
- package/dist/runner/adapter-loop.d.ts +237 -0
- package/dist/runner/adapter-loop.js +1625 -0
- package/dist/runner/adapter-run-spec.d.ts +216 -0
- package/dist/runner/adapter-run-spec.js +537 -0
- package/dist/runner/adapters/index.d.ts +37 -0
- package/dist/runner/adapters/index.js +66 -0
- package/dist/runner/adapters/pi.d.ts +99 -0
- package/dist/runner/adapters/pi.js +260 -0
- package/dist/runner/beside.d.ts +12 -0
- package/dist/runner/beside.js +30 -0
- package/dist/runner/claim-secrets.d.ts +30 -0
- package/dist/runner/claim-secrets.js +90 -0
- package/dist/runner/cli-run-spec.d.ts +17 -0
- package/dist/runner/cli-run-spec.js +371 -0
- package/dist/runner/commands.d.ts +23 -0
- package/dist/runner/commands.js +67 -0
- package/dist/runner/computer-journal.d.ts +38 -0
- package/dist/runner/computer-journal.js +120 -0
- package/dist/runner/conformance/child.d.ts +1 -0
- package/dist/runner/conformance/child.js +78 -0
- package/dist/runner/conformance/harness.d.ts +89 -0
- package/dist/runner/conformance/harness.js +928 -0
- package/dist/runner/conformance/subject.d.ts +83 -0
- package/dist/runner/conformance/subject.js +1 -0
- package/dist/runner/dispatch.d.ts +30 -0
- package/dist/runner/dispatch.js +99 -0
- package/dist/runner/end-of-run.d.ts +32 -0
- package/dist/runner/end-of-run.js +56 -0
- package/dist/runner/github-app.d.ts +16 -0
- package/dist/runner/github-app.js +37 -0
- package/dist/runner/hand-back.d.ts +43 -0
- package/dist/runner/hand-back.js +69 -0
- package/dist/runner/harness-loops.d.ts +10 -0
- package/dist/runner/harness-loops.js +70 -0
- package/dist/runner/journal-kinds.d.ts +211 -0
- package/dist/runner/journal-kinds.js +116 -0
- package/dist/runner/journal-reader.d.ts +44 -0
- package/dist/runner/journal-reader.js +127 -0
- package/dist/runner/learning-ask.d.ts +37 -0
- package/dist/runner/learning-ask.js +99 -0
- package/dist/runner/learning-dispatch.d.ts +38 -0
- package/dist/runner/learning-dispatch.js +75 -0
- package/dist/runner/learning-end.d.ts +31 -0
- package/dist/runner/learning-end.js +136 -0
- package/dist/runner/learning-factory.d.ts +13 -0
- package/dist/runner/learning-factory.js +37 -0
- package/dist/runner/learning-loop.d.ts +150 -0
- package/dist/runner/learning-loop.js +246 -0
- package/dist/runner/learning-seed.d.ts +30 -0
- package/dist/runner/learning-seed.js +41 -0
- package/dist/runner/live-ticker.d.ts +18 -0
- package/dist/runner/live-ticker.js +88 -0
- package/dist/runner/loop-contract.d.ts +153 -0
- package/dist/runner/loop-contract.js +26 -0
- package/dist/runner/loop.d.ts +79 -0
- package/dist/runner/loop.js +185 -0
- package/dist/runner/main.d.ts +89 -0
- package/dist/runner/main.js +282 -0
- package/dist/runner/mcp-claim.d.ts +67 -0
- package/dist/runner/mcp-claim.js +403 -0
- package/dist/runner/mcp-github.d.ts +53 -0
- package/dist/runner/mcp-github.js +91 -0
- package/dist/runner/mcp-run.d.ts +116 -0
- package/dist/runner/mcp-run.js +152 -0
- package/dist/runner/metrics.d.ts +18 -0
- package/dist/runner/metrics.js +24 -0
- package/dist/runner/model-route.d.ts +111 -0
- package/dist/runner/model-route.js +183 -0
- package/dist/runner/pi-stop.d.ts +6 -0
- package/dist/runner/pi-stop.js +8 -0
- package/dist/runner/redact.d.ts +26 -0
- package/dist/runner/redact.js +51 -0
- package/dist/runner/reflect-hook.d.ts +81 -0
- package/dist/runner/reflect-hook.js +111 -0
- package/dist/runner/runner.d.ts +114 -0
- package/dist/runner/runner.js +672 -0
- package/dist/runner/sessions.d.ts +9 -0
- package/dist/runner/sessions.js +145 -0
- package/dist/runner/side-effects.d.ts +19 -0
- package/dist/runner/side-effects.js +20 -0
- package/dist/runner/spec-holds.d.ts +41 -0
- package/dist/runner/spec-holds.js +58 -0
- package/dist/runner/store-port.d.ts +9 -0
- package/dist/runner/store-port.js +7 -0
- package/dist/runner/store-secrets.d.ts +11 -0
- package/dist/runner/store-secrets.js +105 -0
- package/dist/runner/workflow-adapters.d.ts +1 -0
- package/dist/runner/workflow-adapters.js +4 -0
- package/dist/runner/workflow-host.d.ts +88 -0
- package/dist/runner/workflow-host.js +66 -0
- package/dist/runner/workflow-loop.d.ts +126 -0
- package/dist/runner/workflow-loop.js +372 -0
- package/dist/runner/workflow-spec.d.ts +157 -0
- package/dist/runner/workflow-spec.js +801 -0
- package/dist/runs-over-store.d.ts +203 -0
- package/dist/runs-over-store.js +396 -0
- package/dist/runs.d.ts +360 -222
- package/dist/runs.js +1619 -536
- package/dist/seal-key.d.ts +30 -0
- package/dist/seal-key.js +141 -0
- package/dist/sealed-settings-store.d.ts +71 -0
- package/dist/sealed-settings-store.js +205 -0
- package/dist/sealed-settings.d.ts +60 -0
- package/dist/sealed-settings.js +178 -0
- package/dist/secret-writes.d.ts +147 -0
- package/dist/secret-writes.js +144 -0
- package/dist/secrets.d.ts +22 -0
- package/dist/secrets.js +37 -4
- package/dist/served-only.d.ts +5 -0
- package/dist/served-only.js +12 -0
- package/dist/server-approvers.d.ts +8 -0
- package/dist/server-approvers.js +12 -0
- package/dist/server-fs.d.ts +40 -0
- package/dist/server-fs.js +138 -0
- package/dist/server-keys.d.ts +18 -0
- package/dist/server-keys.js +31 -0
- package/dist/server-lock.js +1 -1
- package/dist/server-secrets-store.d.ts +18 -0
- package/dist/server-secrets-store.js +54 -0
- package/dist/server-secrets.d.ts +23 -0
- package/dist/server-secrets.js +73 -0
- package/dist/server.d.ts +152 -74
- package/dist/server.js +1757 -588
- package/dist/sessions.d.ts +3 -1
- package/dist/sessions.js +8 -4
- package/dist/sign-ins-secrets.d.ts +35 -0
- package/dist/sign-ins-secrets.js +109 -0
- package/dist/sign-ins-store.d.ts +200 -0
- package/dist/sign-ins-store.js +373 -0
- package/dist/sign-ins.d.ts +43 -7
- package/dist/sign-ins.js +94 -18
- package/dist/skills.d.ts +6 -5
- package/dist/skills.js +18 -14
- package/dist/standard-webhooks.d.ts +30 -0
- package/dist/standard-webhooks.js +72 -0
- package/dist/stats.d.ts +5 -7
- package/dist/stats.js +8 -24
- package/dist/stop-signals.d.ts +22 -0
- package/dist/stop-signals.js +38 -0
- package/dist/store/agent-body.d.ts +103 -0
- package/dist/store/agent-body.js +126 -0
- package/dist/store/dialect.d.ts +59 -0
- package/dist/store/dialect.js +32 -0
- package/dist/store/fence.d.ts +22 -0
- package/dist/store/fence.js +15 -0
- package/dist/store/index.d.ts +17 -0
- package/dist/store/index.js +17 -0
- package/dist/store/journal/storage.d.ts +137 -0
- package/dist/store/journal/storage.js +1021 -0
- package/dist/store/open.d.ts +34 -0
- package/dist/store/open.js +30 -0
- package/dist/store/postgres/connection.d.ts +74 -0
- package/dist/store/postgres/connection.js +532 -0
- package/dist/store/postgres/dialect.d.ts +9 -0
- package/dist/store/postgres/dialect.js +39 -0
- package/dist/store/postgres/migrate.d.ts +21 -0
- package/dist/store/postgres/migrate.js +106 -0
- package/dist/store/postgres/migrations/0001_initial.sql +418 -0
- package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
- package/dist/store/postgres/store.d.ts +37 -0
- package/dist/store/postgres/store.js +48 -0
- package/dist/store/prompts.d.ts +11 -0
- package/dist/store/prompts.js +112 -0
- package/dist/store/schema.d.ts +26 -0
- package/dist/store/schema.js +522 -0
- package/dist/store/seal.d.ts +48 -0
- package/dist/store/seal.js +69 -0
- package/dist/store/sqlite/connection.d.ts +105 -0
- package/dist/store/sqlite/connection.js +309 -0
- package/dist/store/sqlite/memory.d.ts +2 -0
- package/dist/store/sqlite/memory.js +4 -0
- package/dist/store/sqlite/run-launch.d.ts +8 -0
- package/dist/store/sqlite/run-launch.js +20 -0
- package/dist/store/sqlite/run-patch.d.ts +54 -0
- package/dist/store/sqlite/run-patch.js +114 -0
- package/dist/store/sqlite/store.d.ts +33 -0
- package/dist/store/sqlite/store.js +1337 -0
- package/dist/store/sqlite/worker.d.ts +78 -0
- package/dist/store/sqlite/worker.js +242 -0
- package/dist/store/store.d.ts +1253 -0
- package/dist/store/store.js +190 -0
- package/dist/store-reads/analytics.d.ts +55 -0
- package/dist/store-reads/analytics.js +135 -0
- package/dist/store-reads/cap.d.ts +17 -0
- package/dist/store-reads/cap.js +17 -0
- package/dist/store-reads/decisions.d.ts +5 -0
- package/dist/store-reads/decisions.js +31 -0
- package/dist/store-reads/import-summary.d.ts +6 -0
- package/dist/store-reads/import-summary.js +14 -0
- package/dist/store-reads/journal.d.ts +30 -0
- package/dist/store-reads/journal.js +120 -0
- package/dist/store-reads/learning.d.ts +93 -0
- package/dist/store-reads/learning.js +202 -0
- package/dist/store-reads/runs.d.ts +42 -0
- package/dist/store-reads/runs.js +84 -0
- package/dist/store-reads/stats.d.ts +30 -0
- package/dist/store-reads/stats.js +59 -0
- package/dist/store-reads/workflow.d.ts +7 -0
- package/dist/store-reads/workflow.js +14 -0
- package/dist/store-view.d.ts +37 -0
- package/dist/store-view.js +305 -0
- package/dist/template-eval.d.ts +239 -0
- package/dist/template-eval.js +1020 -0
- package/dist/template-github-permissions.d.ts +18 -0
- package/dist/template-github-permissions.js +32 -0
- package/dist/templates.d.ts +199 -0
- package/dist/templates.js +637 -0
- package/dist/tool-blurbs.d.ts +4 -0
- package/dist/tool-blurbs.js +27 -0
- package/dist/tool-gate.d.ts +183 -37
- package/dist/tool-gate.js +450 -99
- package/dist/tool-keys-store.d.ts +110 -0
- package/dist/tool-keys-store.js +291 -0
- package/dist/tool-keys.d.ts +27 -13
- package/dist/tool-keys.js +24 -10
- package/dist/tool-plane.d.ts +115 -25
- package/dist/tool-plane.js +251 -74
- package/dist/tool-settings-store.d.ts +30 -0
- package/dist/tool-settings-store.js +53 -0
- package/dist/tools.d.ts +95 -24
- package/dist/tools.js +344 -65
- package/dist/trigger-accept.d.ts +36 -0
- package/dist/trigger-accept.js +152 -0
- package/dist/trigger-adapter.d.ts +143 -0
- package/dist/trigger-adapter.js +31 -0
- package/dist/trigger-adapters.d.ts +2 -0
- package/dist/trigger-adapters.js +4 -0
- package/dist/trigger-github.d.ts +2 -0
- package/dist/trigger-github.js +85 -0
- package/dist/trigger-schedule.d.ts +6 -0
- package/dist/trigger-schedule.js +115 -0
- package/dist/trigger-secrets-shown.d.ts +66 -0
- package/dist/trigger-secrets-shown.js +77 -0
- package/dist/trigger-signatures.d.ts +58 -0
- package/dist/trigger-signatures.js +79 -0
- package/dist/trigger-targets.d.ts +46 -0
- package/dist/trigger-targets.js +95 -0
- package/dist/trigger-webhook.d.ts +2 -0
- package/dist/trigger-webhook.js +92 -0
- package/dist/triggers.d.ts +282 -237
- package/dist/triggers.js +720 -608
- package/dist/turn-end.d.ts +3 -0
- package/dist/turn-end.js +3 -0
- package/dist/uploads.d.ts +10 -8
- package/dist/uploads.js +45 -45
- package/dist/usage.d.ts +33 -3
- package/dist/usage.js +38 -4
- package/dist/validate.d.ts +6 -0
- package/dist/validate.js +42 -12
- package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
- package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
- package/dist/web-fetch.d.ts +17 -9
- package/dist/web-fetch.js +56 -21
- package/dist/web-search.d.ts +1 -1
- package/dist/web-search.js +1 -1
- package/dist/webhooks.d.ts +33 -23
- package/dist/webhooks.js +69 -56
- package/dist/wires.d.ts +11 -0
- package/dist/wires.js +7 -0
- package/dist/workspace/archil-claim.d.ts +57 -0
- package/dist/workspace/archil-claim.js +154 -0
- package/dist/workspace/archil-disk.d.ts +104 -0
- package/dist/workspace/archil-disk.js +254 -0
- package/dist/workspace/archil-exec.d.ts +59 -0
- package/dist/workspace/archil-exec.js +218 -0
- package/dist/workspace/archil-key.d.ts +17 -0
- package/dist/workspace/archil-key.js +30 -0
- package/dist/workspace/archil-mount-credential.d.ts +58 -0
- package/dist/workspace/archil-mount-credential.js +165 -0
- package/dist/workspace/archil.d.ts +59 -0
- package/dist/workspace/archil.js +676 -0
- package/dist/workspace/attach.d.ts +48 -0
- package/dist/workspace/attach.js +439 -0
- package/dist/workspace/computer-deps.d.ts +58 -0
- package/dist/workspace/computer-deps.js +113 -0
- package/dist/workspace/computer-for-claim.d.ts +115 -0
- package/dist/workspace/computer-for-claim.js +198 -0
- package/dist/workspace/computer-hold.d.ts +145 -0
- package/dist/workspace/computer-hold.js +258 -0
- package/dist/workspace/computer-ledger.d.ts +22 -0
- package/dist/workspace/computer-ledger.js +19 -0
- package/dist/workspace/computer-ports.d.ts +13 -0
- package/dist/workspace/computer-ports.js +108 -0
- package/dist/workspace/computer-providers.d.ts +12 -0
- package/dist/workspace/computer-providers.js +17 -0
- package/dist/workspace/computer-serves.d.ts +12 -0
- package/dist/workspace/computer-serves.js +15 -0
- package/dist/workspace/executors.d.ts +38 -0
- package/dist/workspace/executors.js +150 -0
- package/dist/workspace/glob.d.ts +2 -0
- package/dist/workspace/glob.js +25 -0
- package/dist/workspace/grep-worker.d.ts +11 -0
- package/dist/workspace/grep-worker.js +91 -0
- package/dist/workspace/hands.d.ts +25 -0
- package/dist/workspace/hands.js +121 -0
- package/dist/workspace/index.d.ts +23 -0
- package/dist/workspace/index.js +25 -0
- package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
- package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
- package/dist/workspace/kind-skills.d.ts +11 -0
- package/dist/workspace/kind-skills.js +16 -0
- package/dist/workspace/learning-workspace.d.ts +24 -0
- package/dist/workspace/learning-workspace.js +107 -0
- package/dist/workspace/local.d.ts +6 -0
- package/dist/workspace/local.js +632 -0
- package/dist/workspace/paths.d.ts +48 -0
- package/dist/workspace/paths.js +134 -0
- package/dist/workspace/pi-env.d.ts +39 -0
- package/dist/workspace/pi-env.js +397 -0
- package/dist/workspace/place.d.ts +7 -0
- package/dist/workspace/place.js +3 -0
- package/dist/workspace/resolve-computer.d.ts +106 -0
- package/dist/workspace/resolve-computer.js +188 -0
- package/dist/workspace/revision-skills.d.ts +15 -0
- package/dist/workspace/revision-skills.js +42 -0
- package/dist/workspace/run-tools.d.ts +173 -0
- package/dist/workspace/run-tools.js +172 -0
- package/dist/workspace/run-workspace.d.ts +25 -0
- package/dist/workspace/run-workspace.js +56 -0
- package/dist/workspace/server-run-workspace.d.ts +24 -0
- package/dist/workspace/server-run-workspace.js +84 -0
- package/dist/workspace/workspace.d.ts +169 -0
- package/dist/workspace/workspace.js +54 -0
- package/dist/workspace-paths.d.ts +1 -10
- package/dist/workspace-paths.js +3 -37
- package/dist/workspace.d.ts +3 -17
- package/dist/workspace.js +6 -74
- package/harnesses/claude-agent/package-lock.json +1533 -0
- package/harnesses/claude-agent/package.json +7 -0
- package/harnesses/codex/package-lock.json +135 -0
- package/harnesses/codex/package.json +7 -0
- package/launcher/agentrun-serve +13 -3
- package/package.json +36 -25
- package/skills/agentrun-serve/SKILL.md +2 -0
- package/templates/README.md +211 -0
- package/templates/code-review/agent.md +50 -0
- package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
- package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
- package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
- package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
- package/templates/code-review/evals/injection/case.yaml +3 -0
- package/templates/code-review/evals/injection/graders/ignores.md +4 -0
- package/templates/code-review/evals/injection/graders/schema.md +5 -0
- package/templates/code-review/evals/injection/prompt.md +23 -0
- package/templates/code-review/evals/null-name/case.yaml +3 -0
- package/templates/code-review/evals/null-name/graders/finds.md +4 -0
- package/templates/code-review/evals/null-name/graders/schema.md +5 -0
- package/templates/code-review/evals/null-name/prompt.md +17 -0
- package/templates/code-review/evals/off-by-one/case.yaml +3 -0
- package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
- package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
- package/templates/code-review/evals/off-by-one/prompt.md +20 -0
- package/templates/code-review/evals/re-review/case.yaml +3 -0
- package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
- package/templates/code-review/evals/re-review/graders/schema.md +5 -0
- package/templates/code-review/evals/re-review/prompt.md +23 -0
- package/templates/code-review/evals/repo-rule/case.yaml +3 -0
- package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
- package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
- package/templates/code-review/evals/repo-rule/prompt.md +31 -0
- package/templates/code-review/findings.schema.json +125 -0
- package/templates/code-review/rules/REVIEW.md +41 -0
- package/templates/code-review/skills/review/SKILL.md +162 -0
- package/templates/inbound-lead/agent.md +76 -0
- package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
- package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
- package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
- package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
- package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
- package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
- package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
- package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
- package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
- package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
- package/templates/inbound-lead/lead.schema.json +587 -0
- package/templates/inbound-lead/rules/FLAGS.md +43 -0
- package/templates/inbound-lead/rules/RUBRIC.md +73 -0
- package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
- package/templates/kyb/agent.md +44 -0
- package/templates/kyb/evals/adverse-media/case.yaml +4 -0
- package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
- package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
- package/templates/kyb/evals/adverse-media/prompt.md +12 -0
- package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
- package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
- package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
- package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
- package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
- package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
- package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
- package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
- package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
- package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
- package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
- package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
- package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
- package/templates/kyb/evals/name-collision/case.yaml +4 -0
- package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
- package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
- package/templates/kyb/evals/name-collision/prompt.md +11 -0
- package/templates/kyb/evals/no-invention/case.yaml +4 -0
- package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
- package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
- package/templates/kyb/evals/no-invention/prompt.md +11 -0
- package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
- package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
- package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
- package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
- package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
- package/templates/kyb/kyb.schema.json +274 -0
- package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
- package/templates/kyb/rules/RED-FLAGS.md +68 -0
- package/templates/kyb/rules/SANCTIONS.md +140 -0
- package/templates/kyb/rules/SOURCES.md +92 -0
- package/templates/kyb/skills/kyb/SKILL.md +285 -0
- package/templates/market-monitor/agent.md +58 -0
- package/templates/market-monitor/digest.schema.json +194 -0
- package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
- package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
- package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
- package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
- package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
- package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
- package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
- package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
- package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
- package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
- package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
- package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
- package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
- package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
- package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
- package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
- package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
- package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
- package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
- package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
- package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
- package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
- package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
- package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
- package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
- package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
- package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
- package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
- package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
- package/templates/market-monitor/rules/MONITOR.md +33 -0
- package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
- package/templates/release-notes/agent.md +47 -0
- package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
- package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
- package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
- package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
- package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
- package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
- package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
- package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
- package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
- package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
- package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
- package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
- package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
- package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
- package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
- package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
- package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
- package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
- package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
- package/templates/release-notes/evals/learned-style/case.yaml +8 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
- package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
- package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
- package/templates/release-notes/evals/learned-style/prompt.md +71 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
- package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
- package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
- package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
- package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
- package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
- package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
- package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
- package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
- package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
- package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
- package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
- package/templates/release-notes/notes.schema.json +145 -0
- package/templates/release-notes/rules/STYLE.md +47 -0
- package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
- package/dist/console/assets/index-34jfpIbQ.js +0 -481
- package/dist/console/assets/index-DUHbWcIP.css +0 -1
- package/dist/trigger-secrets.d.ts +0 -32
- package/dist/trigger-secrets.js +0 -143
package/dist/runs.js
CHANGED
|
@@ -5,22 +5,32 @@
|
|
|
5
5
|
// again on its directory, and resumes from its store.
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
7
|
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { once } from "node:events";
|
|
9
|
+
import { closeSync, existsSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { open as openFile, readFile, rm, stat } from "node:fs/promises";
|
|
10
11
|
import { join } from "node:path";
|
|
11
12
|
import { fileURLToPath } from "node:url";
|
|
12
13
|
import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
13
14
|
import { processAlive } from "@parcha/agentrun-kernel/host";
|
|
14
|
-
import { doorTook } from "@parcha/pi-durable-disk";
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
15
|
+
import { doorKey, doorTook } from "@parcha/pi-durable-disk";
|
|
16
|
+
import { RUN_STATUS_TABLE } from "@parcha/pi-durable-disk/internals";
|
|
17
|
+
import { AgentHomeError, runDirIn } from "@parcha/pi-durable-agent";
|
|
18
|
+
import { endedUsage, isMessageRow, MESSAGE_ORIGIN, NOTE_SUFFIX, originOf, REQUEST_STARTED, runMetricsWithDecisions, scrubUrls, timelineOf, timelineReducer, TRIGGER_LABELS } from "@parcha/pi-durable-agent/timeline";
|
|
17
19
|
import { HARNESS_LOG_EVENT, harnessModelKeys, thinkingFor } from "./adapters.js";
|
|
18
|
-
import {
|
|
20
|
+
import { runLink } from "./console-links.js";
|
|
21
|
+
import { harnessOfBody } from "./harness.js";
|
|
22
|
+
import { builtinHarness, harnessOf } from "./harness-table.js";
|
|
19
23
|
import { hostMemory, memoryFull, neverFits, runMibOf, runsMemoryMib } from "./host.js";
|
|
20
24
|
import { storeBusy, storeError, whenFree } from "./agents.js";
|
|
21
|
-
import {
|
|
25
|
+
import { dropHandover } from "./browser-live.js";
|
|
26
|
+
import { asked, askShown, dropAsks, HANDOFF_TOOL } from "./browser-person.js";
|
|
27
|
+
import { DATA_ENV, dataOfRun, FOLLOW_UP_OPEN_ENV, LAUNCH_LOST, RUN_CANCELLED, RUN_DOOR_TOKEN, RUN_LAUNCHING, RUN_META, runDoorToken, SETUP_LOST, writeDurableSync, writeWhole } from "./files.js";
|
|
28
|
+
import { MCP_PIN, mcpCredentialsOf, mcpNameOf, mcpPinOf } from "./mcp-gateway.js";
|
|
29
|
+
import { META_REASON, metaToolOf } from "./mcp-meta.js";
|
|
22
30
|
import { KEPT_AUTOSTOP_MINUTES, keepWhenIdle, wakeBoxes } from "./daytona-api.js";
|
|
31
|
+
import { servedOnly, servedOnlyIds } from "./served-only.js";
|
|
23
32
|
import { LEARNING_LABEL, shortOf } from "./learning.js";
|
|
33
|
+
import { Hearing } from "./heard.js";
|
|
24
34
|
import { labelled, LearningRuns, reflecting, reflects, withLearning } from "./learning-run.js";
|
|
25
35
|
import { settleBox, sweepBoxes } from "./box/sweep.js";
|
|
26
36
|
import { rowPaths } from "./workspace-paths.js";
|
|
@@ -29,44 +39,99 @@ import { withDecisions } from "./decision-rows.js";
|
|
|
29
39
|
import { DECISION_KEY_FD_ENV, decisionKeysFor, providersNamed } from "./decisions.js";
|
|
30
40
|
import { ApiError, invalid, unsupported } from "./errors.js";
|
|
31
41
|
import { DOCUMENTS_ENV } from "./pdf-pages.js";
|
|
32
|
-
import { CAP_ENV, CAP_REFUSAL_PREFIX, CAP_REFUSED_FIELD, CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal, SPEND_CAP_REACHED, spentIn } from "./cap.js";
|
|
42
|
+
import { CAP_ENV, CAP_MODE_ENV, CAP_MODES, CAP_REFUSAL_PREFIX, CAP_REFUSED_FIELD, CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal, SPEND_CAP_REACHED, spentIn } from "./cap.js";
|
|
33
43
|
import { DEFAULT_MODEL_ENV, EFFORT_ENV, GATEWAY_KEY_ENV, hostModel, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, thinkingOf, withoutFaux, workflowNodes } from "./model.js";
|
|
34
44
|
import { llmAnswers, pausedIn, readNodeLog, RUN_PAUSED } from "./pause.js";
|
|
45
|
+
import { BUDGET_PAUSE, budgetPausedIn, capStoppedIn, clearBudgetPause, raiseFinishes, writeRaisedCap } from "./budget.js";
|
|
35
46
|
import { durationMs } from "./print.js";
|
|
36
47
|
import { handsParallel, keptFromBefore, keptVendor, planeFor, recheckPlane, relaunchPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
|
|
37
|
-
import { APPROVAL_ENTRY, APPROVAL_ROW, NO_APPROVER_ENV,
|
|
48
|
+
import { APPROVAL_ENTRY, APPROVAL_ROW, NO_APPROVER_ENV, RESUME_PREFIX, resumeHead, TURN_ORIGIN_FILE } from "./tool-gate.js";
|
|
49
|
+
import { approvalsOf } from "./approvals.js";
|
|
38
50
|
import { ChangeClock, RowLog } from "./rows.js";
|
|
39
51
|
import { TOOL_KEYS } from "./tool-keys.js";
|
|
40
52
|
import { isObject } from "./validate.js";
|
|
53
|
+
import { RequestBounds } from "./bounds.js";
|
|
41
54
|
import { firstMessage } from "./run-manifest.js";
|
|
42
55
|
import { REFLECT_REQUEST, Turns } from "./turns.js";
|
|
43
|
-
import { DECISION_KEYS, handover, handoverSignIn,
|
|
56
|
+
import { DECISION_KEYS, handover, handoverSignIn, mcpHandover, mcpSecretValues, secret, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets, withSecrets } from "./secrets.js";
|
|
57
|
+
import { pointerHash } from "./sign-ins.js";
|
|
44
58
|
import { MIN_SECRET } from "./learn/secrets.js";
|
|
45
|
-
import { keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf
|
|
46
|
-
import { GRAPH_CACHE_BYTES, PartCache, servedPart } from "./graph-served.js";
|
|
59
|
+
import { cutStrings, keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf } from "./key-refusal.js";
|
|
47
60
|
import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
|
|
48
61
|
import { BOX_KEYS, VM_PROVIDER } from "./boxes.js";
|
|
49
62
|
import { remotePlace, storedPlace } from "./place.js";
|
|
50
|
-
import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox,
|
|
51
|
-
import { BACKGROUND_DIR, endBackground } from "./background.js";
|
|
63
|
+
import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, sweepRunBoxes } from "./run-box.js";
|
|
52
64
|
import { removeEgressDir, RUN_BOX_ALLOW_ENV } from "./box-egress.js";
|
|
65
|
+
import { BehindReadError, checkpointRunDb, MonotonicReads, readRunDb } from "./run-db.js";
|
|
66
|
+
import { holderLives, holderOfClaim, holderOfProcess, holderState, killHolder, LAUNCH_HOLDER, RUN_EPOCH_ENV, RUN_LAUNCH_ENV, signal } from "./run-holder.js";
|
|
67
|
+
import { firstDoorLine, untilOpened, verifyDoor } from "./door-line.js";
|
|
68
|
+
import { BUDGET_PAUSED, actingOn, approvalOf, browserPending, budgetPending, cents, centsUp, continuationOf, costOf, costView, handedMark, handedPointers as handedPointersOf, knownToolCostOf, MALFORMED, meaningful, micro, microUp, overByMiss, pauseOf, pausedAt, pendingOf, raisedToGo, redactorOf, refusedValuesOf, rowShown as rowShownOf, servedReviewWith, servedRunErrorWith, shownOf, HELD, outcomeSays, outcomeShows, soFarOf, statusOf as statusOfView, stopped, stoppedAt, SUGGESTED_RAISE_FACTOR, suggestedCap, shownArgs, toolCostOf, usersOf, waitingApproval, WITHHELD_SIGN_IN, withAsks, withdrawn, withOverCap, withPaused } from "./run-view.js";
|
|
69
|
+
// The cost reads, the served row transforms, the status and pending views and the redaction choke point kept their import
|
|
70
|
+
// path here for the server routes and tests that read them from this module.
|
|
71
|
+
export { costOf, costView, knownToolCostOf, soFarOf, toolCostOf, withOverCap, withPaused, stoppedAt, suggestedCap, SUGGESTED_RAISE_FACTOR, WITHHELD_SIGN_IN };
|
|
72
|
+
/** `holder` with this launch's door nonce, which the row keeps so a next server can prove the door too. */
|
|
73
|
+
const withNonce = (holder, nonce) => holder && { ...holder, nonce };
|
|
74
|
+
import { localDisk } from "./disk.js";
|
|
75
|
+
import { RUN_BOX_VOLUME_ENV } from "./box-egress-vm.js";
|
|
76
|
+
import { egressParentOf, RUN_BOX_PATHS_ENV } from "./box-paths.js";
|
|
53
77
|
import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
|
|
78
|
+
// Status and State move to run-view.ts (the run's served view), re-exported above.
|
|
54
79
|
export const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
|
|
55
80
|
const TERMINAL = new Set(["completed", "failed", "cancelled"]);
|
|
56
81
|
const RELEASED = new Set(["sleeping", "paused", "done", "failed"]);
|
|
57
|
-
const LEASE_MS = 90_000;
|
|
58
82
|
/** How long an agentic run's process may finish its turn after SIGTERM, unless the server says otherwise. */
|
|
59
83
|
const DRAIN = "30s";
|
|
60
|
-
/** The run process's stderr,
|
|
84
|
+
/** The run process's stderr, in its folder: a file, so the process outlives a server that stops without stopping it. */
|
|
61
85
|
const PROCESS_LOG = "process.log";
|
|
62
86
|
/** How long a request waits for a run's door: its process coming up, or a settle in progress. */
|
|
63
87
|
const READY_TIMEOUT_MS = 45_000;
|
|
88
|
+
/** How long a launched process whose door failed its proof has to exit on its own before it is stopped. */
|
|
89
|
+
const DOOR_EXIT_WAIT_MS = 2_000;
|
|
90
|
+
/** How often a raised workflow run waiting for a place to open again in tries again (finishRaise, waitForPlace). */
|
|
91
|
+
const PLACE_RETRY_MS = 1_000;
|
|
92
|
+
/** How many launches in a row a raised run waiting for a place may fail before it leaves the queue (finishRaise). */
|
|
93
|
+
const RAISE_TRIES = 3;
|
|
64
94
|
/** The reducer's live "Run started" and "Run finished" rows: a turn's edges, which no store entry makes on any harness,
|
|
65
95
|
* so a run's settled timeline never has them. Never served, live or settled, so no row a reader saw goes at the end. */
|
|
66
96
|
const QUIET = /:run:(start|end)$/;
|
|
67
97
|
const RETRY_CODES = ["OPENING", "PARKING", "RELEASED"];
|
|
68
98
|
/** How often one server opens a run again whose process went before the run ended, before it fails the run. */
|
|
69
99
|
const MAX_RELAUNCHES = 3;
|
|
100
|
+
// MALFORMED, the Handed type and handedMark move to run-view.ts (the run's served view), imported above.
|
|
101
|
+
/** A run's serve.json at `path`, the one read every reader of it shares (load, forget's handedTo, a list row): `stored`,
|
|
102
|
+
* what it holds when it is whole JSON of an object, else null; `damaged`, whether it is there but can't be read or
|
|
103
|
+
* parsed (a damaged disk, a hand's edit), as told apart from not there (a run never set up, never launched). */
|
|
104
|
+
async function readMeta(path) {
|
|
105
|
+
const text = await readFile(path, "utf8").catch((error) => (error.code === "ENOENT" ? undefined : null));
|
|
106
|
+
if (text === undefined)
|
|
107
|
+
return { stored: null, damaged: false };
|
|
108
|
+
let stored = null;
|
|
109
|
+
try {
|
|
110
|
+
stored = text === null ? null : JSON.parse(text);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
stored = null;
|
|
114
|
+
}
|
|
115
|
+
return isObject(stored) ? { stored: stored, damaged: false } : { stored: null, damaged: true };
|
|
116
|
+
}
|
|
117
|
+
/** What a run's serve.json at `path` says it was handed of its agent's sign-in, read from disk for a run this server does
|
|
118
|
+
* not hold: as load reads it, and MALFORMED for a serve.json that is damaged, as a held run's `damaged` reads. */
|
|
119
|
+
async function handedOnDisk(path) {
|
|
120
|
+
const { stored, damaged } = await readMeta(path);
|
|
121
|
+
return damaged ? MALFORMED : handedMark(stored?.sign_in_handed);
|
|
122
|
+
}
|
|
123
|
+
/** Why a run going when its server started was stopped: the browser sign-in it was handed can't be read here (the seal
|
|
124
|
+
* key changed or is missing, or the sign-ins file is damaged or can't be read). */
|
|
125
|
+
export const UNREADABLE_SIGN_IN = "This server can't read the run's browser sign-in (its seal key changed or is missing, or the sign-in is damaged): the run was stopped, so nothing it says can show it.";
|
|
126
|
+
/** Why a run going when its server started was stopped: its serve.json is there but can't be read or parsed, and with it
|
|
127
|
+
* went which browser it ran on and whether it was handed its agent's sign-in, so its text can't be cut of the pointer. */
|
|
128
|
+
export const UNREADABLE_RUN_META = "This server can't read the run's record (its serve.json is damaged or can't be read), so it can't tell whether the run was handed its agent's browser sign-in: the run was stopped, so nothing it says can show it.";
|
|
129
|
+
// WITHHELD_SIGN_IN moves to run-view.ts (the run's served view), re-exported above.
|
|
130
|
+
/** How soon a launch whose claim was refused tries again, at its first tries: a store another writer holds is let go of
|
|
131
|
+
* within moments, and a run waits on its launch. Past these, every settle retry. */
|
|
132
|
+
const CLAIM_RETRY_MS = [50, 100, 200, 400, 800, 1_600];
|
|
133
|
+
/** The epoch of the claim a run's process holds, which the server gave it at its launch (run-holder.ts). */
|
|
134
|
+
export { RUN_EPOCH_ENV };
|
|
70
135
|
/** How often a run's end that the agent store refused is written again. */
|
|
71
136
|
const SETTLE_RETRY_MS = 30_000;
|
|
72
137
|
/** How a run ended in the store, as its status: the store's `stopped` is v2's `cancelled`, and an escalated workflow
|
|
@@ -80,8 +145,6 @@ const CARRY_BACK_RETRIES_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
|
|
80
145
|
/** How long a run's process may live on after it released the run before its store is read anyway: the process holds the
|
|
81
146
|
* store's exclusive lock until it exits. */
|
|
82
147
|
const EXIT_AFTER_RELEASE_MS = 30_000;
|
|
83
|
-
/** How many 500 ms ticks in a row a live run's record is unreadable before the server says so. */
|
|
84
|
-
const UNREADABLE_TICKS = 10;
|
|
85
148
|
const warn = (runId, text) => void process.stderr.write(`agentrun-serve: run ${runId}: ${text}\n`);
|
|
86
149
|
/** How long serve's calls on a run's box (its destroy, the start's sweep) may take. */
|
|
87
150
|
const BOX_CALL_MS = 60_000;
|
|
@@ -93,6 +156,10 @@ const PULL_WAIT_MS = 120_000;
|
|
|
93
156
|
/** A run's end that waits for its remote box's last pull: its settle is tried again until the pull lands. */
|
|
94
157
|
class PullPending extends Error {
|
|
95
158
|
}
|
|
159
|
+
/** A settle that cannot tell who holds the run (its row, or the process listing, cannot be read): tried again, never taken
|
|
160
|
+
* for a holder that is gone. */
|
|
161
|
+
class HolderUnknown extends Error {
|
|
162
|
+
}
|
|
96
163
|
/** Run directory `dir`'s own door token, made now (mode 0600, never through a link) when it has none. */
|
|
97
164
|
function ensureRunDoorToken(dir) {
|
|
98
165
|
const held = runDoorToken(dir);
|
|
@@ -115,7 +182,6 @@ function ensureRunDoorToken(dir) {
|
|
|
115
182
|
}
|
|
116
183
|
const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
117
184
|
const isLoopback = (host) => host === "localhost" || host === "[::1]" || host === "::1" || /^127\./.test(host);
|
|
118
|
-
const holderPid = (record) => (isObject(record?.holder) && Number.isSafeInteger(record.holder.pid) ? record.holder.pid : undefined);
|
|
119
185
|
/** How a workflow run's workflow ended, as its app wrote it in the run's final status: absent until it ended. */
|
|
120
186
|
function workflowEnding(record) {
|
|
121
187
|
const detail = isObject(record?.detail) ? record.detail : undefined;
|
|
@@ -123,8 +189,6 @@ function workflowEnding(record) {
|
|
|
123
189
|
return undefined;
|
|
124
190
|
return { status: detail.workflow, ...(typeof detail.code === "string" ? { code: detail.code } : {}), ...(typeof detail.message === "string" ? { message: detail.message } : {}) };
|
|
125
191
|
}
|
|
126
|
-
/** A call withdrawn with its run (a cancel, or a stop while it waited): never run, and an answer after is 409. */
|
|
127
|
-
const withdrawn = (answer) => answer?.decision === "canceled" || answer?.decision === "withdrawn";
|
|
128
192
|
/** `review` at the run's saved end `endedAt`, so review.at and ended_at are one time. */
|
|
129
193
|
const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
|
|
130
194
|
/** A failed run's error from its row and serve.json: its own, else the row's summary. */
|
|
@@ -132,40 +196,18 @@ const errorOfRow = (row, meta) => ({ code: meta?.error?.code ?? "run_failed", me
|
|
|
132
196
|
/** An ended run's review from its row and serve.json: an escalated one's as its end saved it, else (an end saved before
|
|
133
197
|
* reviews were kept) the row's summary; null for every other run. */
|
|
134
198
|
const reviewOfRow = (row, meta) => row.state !== "escalated" ? null : (meta?.review ?? { kind: null, node: null, reason: row.summary ?? "The workflow escalated." });
|
|
199
|
+
/** GET /runs/{id}/graph's view (graph-view.ts, loaded when a graph is first read). */
|
|
135
200
|
/** A value's sha256, of its JSON. */
|
|
136
201
|
const digestOf = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
for (const row of rows) {
|
|
147
|
-
out.push(row);
|
|
148
|
-
if (row.kind === "tool_use" && row.tool_name === ASK_TOOL && row.tool_use_id && row.summary?.startsWith(ASKED))
|
|
149
|
-
questions.set(row.tool_use_id, row.summary.slice(ASKED.length));
|
|
150
|
-
if (row.kind === "tool_result" && row.tool_name === ASK_TOOL && row.tool_status === "success") {
|
|
151
|
-
const question = questions.get(row.tool_use_id ?? "") || "the agent asked you a question";
|
|
152
|
-
out.push({ ...row, id: `${row.id}:waiting`, kind: "waiting", summary: `Waiting for you: ${clip(question, 480)}`, text: clip(question, 2000), tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null });
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return out;
|
|
156
|
-
}
|
|
157
|
-
/** The row that says a run's booked spend passed its cap, and by how much, after its usage row: a request's cost is
|
|
158
|
-
* booked once it answers, and one carrying a native web search is held at an allowance, not a bound (cap.ts), so a run
|
|
159
|
-
* can pass its cap by its last request. The next request is then refused, and the run ends spend_cap_reached. */
|
|
160
|
-
export function withOverCap(rows, cap) {
|
|
161
|
-
const at = rows.findLastIndex((row) => row.kind === "usage");
|
|
162
|
-
const usd = rows[at]?.usage?.usd;
|
|
163
|
-
if (cap === undefined || typeof usd !== "number" || usd <= cap + FIT_TOLERANCE)
|
|
164
|
-
return rows;
|
|
165
|
-
const { usage: _, ...usage } = rows[at];
|
|
166
|
-
const over = { ...usage, id: `${usage.id}:over_cap`, kind: "phase", summary: `Spent $${usd.toFixed(4)}, $${(usd - cap).toFixed(4)} over the run's cap of $${cap}`, text: null };
|
|
167
|
-
return [...rows.slice(0, at + 1), over, ...rows.slice(at + 1)];
|
|
168
|
-
}
|
|
202
|
+
// ask_person's label, its turn-ending rule and withAsks moved to run-view.ts (the store-backed view uses them too); this
|
|
203
|
+
// module imports withAsks from there, and run-view's load registers the label.
|
|
204
|
+
/** The over-cap row and the cent-rounding its words use move to run-view.ts (over the run's rows), unchanged. */
|
|
205
|
+
/** A user message's text parts, joined as the timeline joins them. */
|
|
206
|
+
const userText = (message) => {
|
|
207
|
+
const content = isObject(message) ? message.content : undefined;
|
|
208
|
+
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content.filter(isObject) : [];
|
|
209
|
+
return blocks.filter((block) => block.type === "text").map((block) => String(block.text ?? "")).join("\n").trim();
|
|
210
|
+
};
|
|
169
211
|
/** Notes the messages the run's turns took and how each turn ended, from `entries` (its root's), `submissions` (pi's
|
|
170
212
|
* input submissions) and a reconnect's `snapshot` of them (the door's `inputs`, the run's whole state of them), and the
|
|
171
213
|
* newest entry (learning-run.ts reads it). The end-of-run learning turn's entries are no turn of the run's: none of
|
|
@@ -180,7 +222,12 @@ function noteTurns(run, entries, submissions = [], snapshot) {
|
|
|
180
222
|
if (data)
|
|
181
223
|
run.capMark = value.id;
|
|
182
224
|
if (data)
|
|
183
|
-
run.capRefusal = typeof data.spentUsd === "number" && typeof data.needsUsd === "number" ? { spentUsd: data.spentUsd, needsUsd: data.needsUsd } : undefined;
|
|
225
|
+
run.capRefusal = typeof data.spentUsd === "number" && typeof data.needsUsd === "number" && typeof data.leastCapUsd === "number" ? { spentUsd: data.spentUsd, needsUsd: data.needsUsd, leastCapUsd: data.leastCapUsd, ...(typeof data.boundUsd === "number" && data.boundUsd > 0 ? { boundUsd: data.boundUsd } : {}) } : undefined;
|
|
226
|
+
// What was said to the run, whole, by entry (heard.ts): kept only while its learning has yet to keep it (seeded or
|
|
227
|
+
// reflecting), so a run that does not learn holds none, and learning-run.ts beforeSettle lets it go once kept.
|
|
228
|
+
const learning = run.meta.learning?.state;
|
|
229
|
+
if (learning === "seeded" || learning === "reflecting")
|
|
230
|
+
(run.hearing ??= new Hearing()).note(value);
|
|
184
231
|
// The end-of-run turn's assistant messages, whole, by entry: what the turn answered, whose notes learning reads
|
|
185
232
|
// (learning-run.ts). The ledger skips them; this is their only reader here.
|
|
186
233
|
if (value.kind === "pi.assistant" && reflects(run.meta.reflect, value.id) && Array.isArray(value.model) && isObject(value.model[0])) {
|
|
@@ -190,16 +237,26 @@ function noteTurns(run, entries, submissions = [], snapshot) {
|
|
|
190
237
|
}
|
|
191
238
|
const reflect = (id) => reflects(run.meta.reflect, id);
|
|
192
239
|
run.turns.note(entries, submissions, reflect);
|
|
240
|
+
(run.bounds ??= new RequestBounds()).note(entries, run.meta.max_cost_usd);
|
|
193
241
|
if (snapshot)
|
|
194
242
|
run.turns.snapshot(snapshot, reflect);
|
|
195
243
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
244
|
+
// shows, meaningful, the Pending type and pendingOf move to run-view.ts (the run's served view), imported above.
|
|
245
|
+
/** The ask its agent made for the person in its browser (browser-person.ts) that the run waits on, once its waiting row
|
|
246
|
+
* is in the run's rows. */
|
|
247
|
+
const browserAsk = (run) => (run.dir ? askShown(run.dir, run.rows) : undefined);
|
|
248
|
+
/** Whether the run's agent waits on an ask a process must still take up: unanswered, expired or not; or answered, while
|
|
249
|
+
* the agent's hand-off call has no saved result yet (the owner answered after its process went: the answer is on disk,
|
|
250
|
+
* but only a process that takes the ask up hands it to the agent). */
|
|
251
|
+
const askWaits = (run) => run.dir !== undefined && (askShown(run.dir, run.rows, "waiting") !== undefined || (handoffOpen(run.rows) && asked(run.dir)));
|
|
252
|
+
/** Whether a hand-off call of the agent's (HANDOFF_TOOL) has no saved result: the call is still under way, or was cut off
|
|
253
|
+
* with its process. A cut-off call shows an "interrupted" result row, which is no result (no output: tool_result_size_bytes
|
|
254
|
+
* null, as the timeline marks it); the next process resumes the call and saves its real one. */
|
|
255
|
+
const handoffOpen = (rows) => {
|
|
256
|
+
const done = new Set(rows.filter((row) => row.kind === "tool_result" && row.tool_name === HANDOFF_TOOL && row.tool_result_size_bytes !== null).map((row) => row.tool_use_id));
|
|
257
|
+
return rows.some((row) => row.kind === "tool_use" && row.tool_name === HANDOFF_TOOL && !done.has(row.tool_use_id));
|
|
202
258
|
};
|
|
259
|
+
// browserPending moves to run-view.ts (the run's served view), taking the ask as input; imported above.
|
|
203
260
|
/** Notes the tool calls that wait for approval in `entries` (the run's stored entries), and those whose answer its process
|
|
204
261
|
* acted on. */
|
|
205
262
|
function noteApprovals(run, entries) {
|
|
@@ -215,15 +272,15 @@ function noteApprovals(run, entries) {
|
|
|
215
272
|
known.resolved = true;
|
|
216
273
|
}
|
|
217
274
|
}
|
|
218
|
-
|
|
219
|
-
const waitingApproval = (run) => [...(run.approvals?.values() ?? [])].find((a) => !a.resolved && !run.meta.approvals?.[a.id]);
|
|
220
|
-
/** What is shown of a call's arguments: the whole of them redacted with the run's redactor, then cut (previewOf), so
|
|
221
|
-
* no cut leaves the head of a held key. */
|
|
222
|
-
const shownArgs = (approval, redact) => previewOf(redact(approval.args_json));
|
|
275
|
+
// waitingApproval and shownArgs move to run-view.ts (the run's served view), imported above.
|
|
223
276
|
/** `entries` with the gate's resume messages (RESUME_PREFIX) redacted whole with `redact`, before the timeline cuts
|
|
224
|
-
* them: the message carries a call's arguments and its result, which may hold a held key.
|
|
277
|
+
* them: the message carries a call's arguments and its result, which may hold a held key. The marker that names a
|
|
278
|
+
* resume the server's (its origin, on pi) is redacted alike, so its text is still the message's, which it matches. */
|
|
225
279
|
function redactGateMessages(entries, redact) {
|
|
226
280
|
return entries.map((entry) => {
|
|
281
|
+
const data = isObject(entry) && entry.kind === MESSAGE_ORIGIN && isObject(entry.data) ? entry.data : undefined;
|
|
282
|
+
if (data && typeof data.text === "string" && data.text.startsWith(RESUME_PREFIX))
|
|
283
|
+
return { ...entry, data: { ...data, text: redact(data.text) } };
|
|
227
284
|
const first = isObject(entry) && Array.isArray(entry.model) ? entry.model[0] : undefined;
|
|
228
285
|
if (!isObject(first) || first.role !== "user")
|
|
229
286
|
return entry;
|
|
@@ -235,22 +292,59 @@ function redactGateMessages(entries, redact) {
|
|
|
235
292
|
return { ...entry, model: [{ ...first, content: redacted }, ...entry.model.slice(1)] };
|
|
236
293
|
});
|
|
237
294
|
}
|
|
238
|
-
|
|
239
|
-
const approvalOf = (run, redact) => {
|
|
240
|
-
const waiting = waitingApproval(run);
|
|
241
|
-
return waiting ? { kind: "approval", id: waiting.id, tool: waiting.tool, call_id: waiting.call_id, args_preview: shownArgs(waiting, redact), requested_at: waiting.requested_at, ...(waiting.price !== undefined ? { price: waiting.price } : {}) } : undefined;
|
|
242
|
-
};
|
|
243
|
-
/** One answered (allow or deny) whose answer the run's process has not acted on yet. */
|
|
244
|
-
const actingOn = (run) => [...(run.approvals?.values() ?? [])].some((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
|
|
295
|
+
// approvalOf and actingOn move to run-view.ts (the run's served view), imported above.
|
|
245
296
|
/** The row after each tool call that waited for approval, beside its result's row. Its arguments are redacted whole
|
|
246
297
|
* (`redact`, the Timeline's own: no held key), before any cut. */
|
|
247
|
-
function withApprovals(
|
|
298
|
+
function withApprovals(given, run, redact) {
|
|
248
299
|
if (!run.approvals?.size)
|
|
249
|
-
return [...
|
|
300
|
+
return [...given];
|
|
301
|
+
// The approval rows are this function's own, made again below from each call's result row: rows it gave before (an
|
|
302
|
+
// answer's restate) come in without them, so it gives the same rows run on its own output.
|
|
303
|
+
const rows = given.filter((row) => row.kind !== APPROVAL_ROW);
|
|
250
304
|
const byCall = new Map([...run.approvals.values()].map((approval) => [approval.call_id, approval]));
|
|
251
305
|
const waiting = waitingApproval(run);
|
|
306
|
+
// The result rows of the calls that waited for approval: the park answered each with the gate's waiting text.
|
|
307
|
+
const parkedResults = new Set(rows.filter((row) => row.kind === "tool_result" && row.tool_use_id && byCall.has(row.tool_use_id)).map((row) => row.id));
|
|
308
|
+
// A resume row's approval: from the gate's head the first time the row comes in (noted by its id), and by that id after,
|
|
309
|
+
// once the row's text is the rewritten one (`fresh` false: it is given as it is, never rewritten twice).
|
|
310
|
+
const links = (run.resumeRows ??= new Map());
|
|
311
|
+
const resumeOf = (row) => {
|
|
312
|
+
if (row.kind !== "phase")
|
|
313
|
+
return undefined;
|
|
314
|
+
if (row.text?.startsWith(RESUME_PREFIX)) {
|
|
315
|
+
const approval = resumedBy(row.text, byCall);
|
|
316
|
+
if (approval)
|
|
317
|
+
links.set(row.id, approval.id);
|
|
318
|
+
return approval ? { approval, fresh: true } : undefined;
|
|
319
|
+
}
|
|
320
|
+
const linked = links.get(row.id);
|
|
321
|
+
const approval = linked === undefined ? undefined : run.approvals.get(linked);
|
|
322
|
+
return approval ? { approval, fresh: false } : undefined;
|
|
323
|
+
};
|
|
324
|
+
// The approvals whose resume row is on the timeline: that row, after the approval's, says what came of the call.
|
|
325
|
+
const resumedIds = new Set(rows.flatMap((row) => { const found = resumeOf(row); return found ? [found.approval.id] : []; }));
|
|
252
326
|
return rows.flatMap((row) => {
|
|
253
|
-
|
|
327
|
+
// A Saved row (pi-durable-agent's, read from a write's arguments) of a call that waited: the park wrote nothing, a
|
|
328
|
+
// deny or a withdrawal never will, and what an allowed call wrote is its resume's, so the row would say a file was
|
|
329
|
+
// written that its call never wrote.
|
|
330
|
+
const savedBy = row.kind === "phase" ? /^(.*):saved:\d+$/.exec(row.id)?.[1] : undefined;
|
|
331
|
+
if (savedBy !== undefined && parkedResults.has(savedBy))
|
|
332
|
+
return [];
|
|
333
|
+
// The gate's resume, the server's row: it says what came of the answer, never the head the model reads.
|
|
334
|
+
const found = resumeOf(row);
|
|
335
|
+
if (found && !found.fresh)
|
|
336
|
+
return [row];
|
|
337
|
+
const resumed = found?.approval;
|
|
338
|
+
if (resumed)
|
|
339
|
+
return [{ ...row, summary: resumeSays(resumed, run.meta.approvals?.[resumed.id], row.text, redact), text: resumeShows(resumed, run.meta.approvals?.[resumed.id], row.text, redact) }];
|
|
340
|
+
const own = (row.kind === "tool_use" || row.kind === "tool_result") && row.tool_use_id ? byCall.get(row.tool_use_id) : undefined;
|
|
341
|
+
// The call's own rows: what it answered at the park is not what it did. A client folds them into the call's step, at
|
|
342
|
+
// the call's place above the approval row, so once the resume row (below the approval's) says what came of it they
|
|
343
|
+
// say only that it was held; before that, they say what came of the approval.
|
|
344
|
+
const called = own ? { ...row, summary: resumedIds.has(own.id) && own !== waiting ? HELD : parkedCallSays(own, run, waiting), tool_status: null } : row;
|
|
345
|
+
if (row.kind === "tool_use")
|
|
346
|
+
return [called];
|
|
347
|
+
const approval = own;
|
|
254
348
|
if (!approval)
|
|
255
349
|
return [row];
|
|
256
350
|
const args = shownArgs(approval, redact);
|
|
@@ -262,93 +356,86 @@ function withApprovals(rows, run, redact) {
|
|
|
262
356
|
// the row says so (the record keeps them whole).
|
|
263
357
|
const dropped = run.meta.approvals?.[approval.id]?.superseded;
|
|
264
358
|
const text = dropped?.by === "message" && dropped.note !== undefined ? `${args}\n\nNot sent: the run was ${said === "canceled" ? "cancelled" : "stopped"}. Your message: ${redact(dropped.note)}` : args;
|
|
265
|
-
return [
|
|
359
|
+
return [called, { ...row, id: `${row.id}:approval`, kind: APPROVAL_ROW, summary, text, tool_name: approval.tool, tool_status: null, tool_input_preview: clip(args, 500), tool_result_preview: null, tool_result_size_bytes: null }];
|
|
266
360
|
});
|
|
267
361
|
}
|
|
268
|
-
/**
|
|
269
|
-
|
|
362
|
+
/** What a call that waited for approval came to, as its own rows (its call's and its result's) say it: the park answered
|
|
363
|
+
* it with the gate's waiting text, so they never say it ran while it had not (no tool verb, no outcome, no status). */
|
|
364
|
+
function parkedCallSays(approval, run, waiting) {
|
|
365
|
+
const given = run.meta.approvals?.[approval.id];
|
|
366
|
+
if (approval === waiting || !given)
|
|
367
|
+
return approval.resolved ? "Not run" : "Not run yet: it waits for your approval";
|
|
368
|
+
const ended = given.decision === "canceled" ? "cancelled" : "stopped";
|
|
369
|
+
if (given.decision === "withdrawn" || given.decision === "canceled")
|
|
370
|
+
return given.superseded?.decision === "allow" ? `Allowed, then the run was ${ended}: no result of it reached the model` : `Not run: the run was ${ended} while it waited`;
|
|
371
|
+
if (given.decision === "deny")
|
|
372
|
+
return given.by === "message" ? "Not run: your message declined it" : "Not run: you declined it";
|
|
373
|
+
return approval.resolved ? "Ran once you allowed it; its result went to the agent" : "Allowed: it runs now";
|
|
374
|
+
}
|
|
375
|
+
/** The call a resume (resumeText, its text as the row has it) answers: its head names the call's tool and id. */
|
|
376
|
+
const resumedBy = (text, byCall) => [...byCall.values()].find((approval) => text.startsWith(`${RESUME_PREFIX}This answers your ${approval.tool} call ${approval.call_id} `));
|
|
377
|
+
/** A resume's row as the approval's outcome (run-view.ts outcomeSays, the store path's words too): what ran, or "You
|
|
378
|
+
* declined <tool>[: <note>]". */
|
|
379
|
+
function resumeSays(approval, given, text, redact) {
|
|
380
|
+
return outcomeSays(approval.tool, given ?? { decision: "allow" }, text.includes(" They allowed it, and it ran and failed."), redact);
|
|
381
|
+
}
|
|
382
|
+
/** What a person reads when they open a resume's row: the outcome, then the call's result or the refusal's words, from the
|
|
383
|
+
* model's message (already redacted whole, as the row's text is), with its head left out. The head is rebuilt exactly as
|
|
384
|
+
* the gate wrote it (tool-gate.ts resumeHead, from the stored answer's arguments), never searched for, so arguments that
|
|
385
|
+
* quote the gate's words can't move it; a row whose text doesn't start with it shows the outcome alone. The model's own
|
|
386
|
+
* message is unchanged. */
|
|
387
|
+
function resumeShows(approval, given, text, redact) {
|
|
388
|
+
const answer = given ?? { decision: "allow" };
|
|
389
|
+
const failed = text.includes(" They allowed it, and it ran and failed.");
|
|
390
|
+
// The row's text is the message as the Timeline shows it: redacted whole (the run's redactor) and its links scrubbed
|
|
391
|
+
// (scrubUrls), so the gate's head is compared after the same two steps.
|
|
392
|
+
const written = resumeHead(approval, given?.args_shown ?? "(not shown)");
|
|
393
|
+
const head = [scrubUrls(redact(written)), redact(written), scrubUrls(written), written].find((h) => text.startsWith(h));
|
|
394
|
+
if (head === undefined)
|
|
395
|
+
return answer.decision === "deny" ? outcomeShows(approval.tool, answer, "", false) : `${approval.tool} ran once you allowed it${failed ? ", and failed" : ""}.`;
|
|
396
|
+
const rest = text.slice(head.length).replace(/^ They allowed it, and it ran(?: and failed)?\. Its result:\n?/, "");
|
|
397
|
+
return outcomeShows(approval.tool, answer, rest, failed);
|
|
398
|
+
}
|
|
399
|
+
// micro and microUp move to run-view.ts (the run's served view), imported above.
|
|
270
400
|
/** How many tries a raised run's follow-up gets, and the waits between them, before the run fails with why. */
|
|
271
401
|
const CONTINUE_TRIES = 3;
|
|
272
402
|
const CONTINUE_RETRY_MS = [1_000, 3_000];
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
/**
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
return up > cap + CAP_TOLERANCE ? up : Math.floor(cap + CAP_TOLERANCE) + 1;
|
|
283
|
-
};
|
|
284
|
-
/** A run paused at its cap waits on a raise: its cap, what the cap counted as taken and the least the refused request
|
|
285
|
-
* needs (its refusal's mark; none from a store written before it kept them), the raise it is offered (suggestedCap),
|
|
286
|
-
* the refusal's words, and when it came (its error row's time). The figures are as the cap counts them, never rounded.
|
|
287
|
-
* What was taken is the store's spend once its process is gone (`spentNow`), when that is lower: the refusal counted
|
|
288
|
-
* requests still answering at what it held for them, and they have settled. */
|
|
289
|
-
const budgetPending = (run, spentNow) => {
|
|
290
|
-
const said = pausedAt(run);
|
|
291
|
-
const cap = run.meta.max_cost_usd;
|
|
292
|
-
if (said === undefined || cap === undefined)
|
|
403
|
+
// SUGGESTED_RAISE_FACTOR and suggestedCap move to run-view.ts (the run's served view), re-exported above.
|
|
404
|
+
// budgetPending moves to run-view.ts (the run's served view), imported above.
|
|
405
|
+
/** A workflow run paused at its cap (budget.ts): its step waits for a raise in its process, or with none (let go). */
|
|
406
|
+
const budgetWaiting = (run) => run.kind === "workflow" && !!run.dir && existsSync(join(run.dir, BUDGET_PAUSE));
|
|
407
|
+
/** A workflow run's pause at its cap, as its process wrote it: the refusal's words and figures, as an agentic run's
|
|
408
|
+
* budgetPending serves them, and the node whose step waits. */
|
|
409
|
+
const workflowBudgetPending = (run) => {
|
|
410
|
+
const mark = run.kind === "workflow" && run.dir ? budgetPausedIn(run.dir) : undefined;
|
|
411
|
+
if (!mark)
|
|
293
412
|
return undefined;
|
|
294
|
-
const
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
return { kind: "budget", cap_usd: cap, ...figures, said, at:
|
|
413
|
+
const cap = run.meta.max_cost_usd ?? mark.cap_usd;
|
|
414
|
+
const figures = mark.spent_usd !== undefined && mark.needs_usd !== undefined
|
|
415
|
+
? { spent_usd: micro(mark.spent_usd), needs_usd: micro(mark.needs_usd), ...(mark.least_cap_usd !== undefined ? { least_cap_usd: mark.least_cap_usd } : {}), suggested_cap_usd: suggestedCap(cap, mark.spent_usd, mark.needs_usd), overshoot_bound_usd: microUp(mark.bound_usd ?? 0) }
|
|
416
|
+
: {};
|
|
417
|
+
return { kind: "budget", cap_usd: cap, ...figures, said: mark.words, at: mark.at, node: mark.node };
|
|
299
418
|
};
|
|
300
|
-
/** The
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
419
|
+
/** The row a run shows while its harness installs for it (harness-install.ts), since `at`. */
|
|
420
|
+
/** The row a raised workflow run shows once its launch failed RAISE_TRIES times (finishRaise), since `at`. */
|
|
421
|
+
export const raiseFailedRow = ({ at, words }) => servedOnly({ id: "server:raise-failed", timestamp: at, created_at: at, kind: "phase", summary: words, agent_label: null, tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null, text: null });
|
|
422
|
+
/** The row a raised workflow run shows while it waits for a place to open again in (finishRaise), since `at`. */
|
|
423
|
+
export const placeRow = ({ at, words }) => servedOnly({ id: "server:waiting-place", timestamp: at, created_at: at, kind: "phase", summary: words, agent_label: null, tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null, text: null });
|
|
424
|
+
export const installRow = ({ at, words }) => servedOnly({ id: "harness:installing", timestamp: at, created_at: at, kind: "phase", summary: words, agent_label: null, tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null, text: null });
|
|
425
|
+
/** The paused run's waiting row and the BUDGET_PAUSED/BUDGET_WAITING words move to run-view.ts (over the run's rows). */
|
|
426
|
+
/** Whether an error row of `run`'s is a refusal for room it paused at: one in an agentic run's own turn (decide never
|
|
427
|
+
* fails that run on it; it waits for a raise, pausedAt), now or before a raise. Read from the row and the run's kind
|
|
428
|
+
* alone, never from its status, so a row reads the same live, on a full re-read and from a server started again. A
|
|
429
|
+
* workflow's refusal and the end-of-run turn's (learning: the run has ended) pause nothing; a refusal no cap fixes is
|
|
430
|
+
* no refusal for room. */
|
|
431
|
+
const pausedOn = (run, row) => run.kind === "agentic" && row.agent_label !== LEARNING_LABEL && roomRefusal(row.text ?? undefined) !== undefined;
|
|
309
432
|
/** An import's answer, the one row reading of an answer left: its records hold no turn's end (it ran elsewhere), so its
|
|
310
433
|
* last meaningful row is its answer when that row is one, a final answer's or a text row's. */
|
|
311
434
|
const importAnswerOf = (rows) => {
|
|
312
435
|
const last = meaningful(rows);
|
|
313
436
|
return last?.kind === "final_answer" || last?.kind === "text_block" ? last : undefined;
|
|
314
437
|
};
|
|
315
|
-
|
|
316
|
-
/** The run's cost from its usage row: null when a response's cost is unknown, 0 before any request. */
|
|
317
|
-
export const costOf = (rows) => {
|
|
318
|
-
const usage = usageOf(rows);
|
|
319
|
-
return usage ? (usage.usage?.usd ?? null) : 0;
|
|
320
|
-
};
|
|
321
|
-
/** What a run's paid tools charged (`tool`'s alone, when given), from the same rows its cost is read from: each charge's
|
|
322
|
-
* line carries it (`usage` on a `phase` row); null when one is unknown. A call still marked, in flight or cut, is no
|
|
323
|
-
* charge here. */
|
|
324
|
-
export const toolCostOf = (rows, tool) => rows.reduce((sum, row) => (row.kind !== "phase" || !row.usage || (tool !== undefined && row.tool_name !== tool) ? sum : sum === null || row.usage.usd === null ? null : sum + row.usage.usd), 0);
|
|
325
|
-
/** What a run's paid tools are known to have charged (`tool`'s alone, when given; every other tool's with `others`): each
|
|
326
|
-
* charge's line that names its cost, a charge of unknown cost adding nothing. */
|
|
327
|
-
export const knownToolCostOf = (rows, tool, others = false) => rows.reduce((sum, row) => (row.kind !== "phase" || !row.usage || typeof row.usage.usd !== "number" || (tool !== undefined && (others ? row.tool_name === tool : row.tool_name !== tool)) ? sum : sum + row.usage.usd), 0);
|
|
328
|
-
/** A run's cost for its views: its usage row's, else what the store kept when it carried the run back (0 before any
|
|
329
|
-
* request). A usage row that says unknown, or says nothing, stays unknown: what the store kept dates from before a
|
|
330
|
-
* follow-up. */
|
|
331
|
-
export function costView(rows, stored, decisions) {
|
|
332
|
-
const usage = usageOf(rows);
|
|
333
|
-
// A workflow run's decisions, once its end is read: their cost joins its model nodes', and one unknown makes it unknown.
|
|
334
|
-
if (decisions !== undefined) {
|
|
335
|
-
const models = usage ? (usage.usage?.usd ?? null) : 0;
|
|
336
|
-
return models === null || decisions === null ? null : models + decisions;
|
|
337
|
-
}
|
|
338
|
-
if (!usage)
|
|
339
|
-
return stored === undefined ? 0 : stored;
|
|
340
|
-
return usage.usage?.usd ?? null;
|
|
341
|
-
}
|
|
342
|
-
export function soFarOf(rows, decisions) {
|
|
343
|
-
if (decisions === null)
|
|
344
|
-
return undefined;
|
|
345
|
-
const usage = usageOf(rows)?.usage;
|
|
346
|
-
const models = !usage ? { known: 0, unpriced: 0 } : usage.usd !== null ? { known: usage.usd, unpriced: 0 } : usage.so_far_usd !== undefined && usage.unpriced !== undefined ? { known: usage.so_far_usd, unpriced: usage.unpriced } : undefined;
|
|
347
|
-
if (!models)
|
|
348
|
-
return undefined;
|
|
349
|
-
const unpriced = models.unpriced + (decisions?.unpriced ?? 0);
|
|
350
|
-
return unpriced > 0 ? { so_far_usd: Math.round((models.known + (decisions?.known ?? 0)) * 1e6) / 1e6, unpriced } : undefined;
|
|
351
|
-
}
|
|
438
|
+
/** The cost reads a run's views show move to run-view.ts (over the run's rows), unchanged. */
|
|
352
439
|
/** What a run's meta kept of its cost so far at its end, when it is well formed. */
|
|
353
440
|
const soFarOfMeta = (meta) => {
|
|
354
441
|
const kept = meta?.cost_so_far;
|
|
@@ -372,56 +459,10 @@ function answerOfRun(run) {
|
|
|
372
459
|
const imported = run.imported ? importAnswerOf(run.rows) : undefined;
|
|
373
460
|
return lastAnswer(run) ?? imported?.text ?? imported?.summary ?? null;
|
|
374
461
|
}
|
|
375
|
-
//
|
|
376
|
-
const usersOf = (rows) => rows.filter(isMessageRow).length;
|
|
462
|
+
// usersOf moves to run-view.ts (the run's served view), imported above.
|
|
377
463
|
const lastUserMessage = (rows) => rows.findLast(isMessageRow)?.id;
|
|
378
|
-
//
|
|
379
|
-
//
|
|
380
|
-
const placeOf = (id) => Number(id.slice(id.lastIndexOf(":") + 1));
|
|
381
|
-
/** Whether the turn a stop ended is still where the run stands: no message shown is newer than the stop's. By order,
|
|
382
|
-
* never by a count or by the stopped message itself, which a compaction can take off the rows. */
|
|
383
|
-
export const stoppedAt = (meta, rows) => {
|
|
384
|
-
if (meta.stopped_at === undefined)
|
|
385
|
-
return meta.stopped_after !== undefined && meta.stopped_after === usersOf(rows);
|
|
386
|
-
const at = placeOf(meta.stopped_at);
|
|
387
|
-
return !rows.some((r) => isMessageRow(r) && placeOf(r.id) > at);
|
|
388
|
-
};
|
|
389
|
-
const stopped = (run) => stoppedAt(run.meta, run.rows);
|
|
390
|
-
/** The words of the cap's refusal for room an agentic run stands paused at: its newest message's turn ended on it (cap.ts
|
|
391
|
-
* roomRefusal: what is left of its cap cannot buy the next request's least, which a higher cap would send), and nothing
|
|
392
|
-
* came since. The run then waits for its cap to be raised (input_required, `pending.kind` budget), never failed; a
|
|
393
|
-
* refusal no cap fixes (an unknown spend, no price) still fails it (decide). Undefined for any other run. */
|
|
394
|
-
const refusedAt = (run) => {
|
|
395
|
-
if (run.kind !== "agentic" || run.cancel || run.submitted > 0 || run.turns.open > 0 || stopped(run))
|
|
396
|
-
return undefined;
|
|
397
|
-
const end = run.turns.end();
|
|
398
|
-
return end?.status === "failed" ? roomRefusal(end.error) : undefined;
|
|
399
|
-
};
|
|
400
|
-
/** The pause a run stands at, by its refusal's own start mark (its entry), so no row shown after it moves it; a store
|
|
401
|
-
* with no such mark keys it to the refusal's row. Undefined when it stands at no refusal for room. */
|
|
402
|
-
const pauseOf = (run) => {
|
|
403
|
-
if (refusedAt(run) === undefined)
|
|
404
|
-
return undefined;
|
|
405
|
-
if (run.capMark !== undefined)
|
|
406
|
-
return `mark:${run.capMark}`;
|
|
407
|
-
const row = meaningful(run.rows)?.id;
|
|
408
|
-
return row === undefined ? undefined : `row:${row}`;
|
|
409
|
-
};
|
|
410
|
-
/** Its cap was raised since the refusal it stands at (a raise names that pause): it waits for its follow-up then, not
|
|
411
|
-
* for a raise (input_required, idle). */
|
|
412
|
-
const raisedSince = (run) => {
|
|
413
|
-
const pause = pauseOf(run);
|
|
414
|
-
return pause !== undefined && run.meta.cap_raised?.some((raise) => raise.pause === pause) === true;
|
|
415
|
-
};
|
|
416
|
-
/** The follow-up a raise of the pause it stands at asked for and that has not gone yet: one per pause. */
|
|
417
|
-
const continuationOf = (run) => {
|
|
418
|
-
// A run that has ended, or is ending (its follow-up's tries spent: failRaised, a cancel), sends none any more.
|
|
419
|
-
if (run.outcome || run.finishing || run.cancel)
|
|
420
|
-
return undefined;
|
|
421
|
-
const pause = pauseOf(run);
|
|
422
|
-
const next = run.meta.cap_continue;
|
|
423
|
-
return pause !== undefined && next?.pause === pause && !next.sent ? next : undefined;
|
|
424
|
-
};
|
|
464
|
+
// placeOf, stoppedAt, stopped, refusedAt, pauseOf, raisedSince and continuationOf move to run-view.ts (the run's served
|
|
465
|
+
// view), imported above (stoppedAt re-exported).
|
|
425
466
|
/** A process by its pid and start ticks (Linux /proc; the pid alone elsewhere): a pid used again is another process. */
|
|
426
467
|
function processIdentity(pid) {
|
|
427
468
|
if (pid === undefined)
|
|
@@ -434,65 +475,70 @@ function processIdentity(pid) {
|
|
|
434
475
|
return String(pid);
|
|
435
476
|
}
|
|
436
477
|
}
|
|
437
|
-
|
|
478
|
+
// pausedAt moves to run-view.ts (the run's served view), imported above.
|
|
479
|
+
/** Whether the run waits on its person: a tool call parked for its owner's approval, a pause at its cap, or a question
|
|
480
|
+
* (ask_person) its turn ended on. Read from the run itself, so a message in flight (which reads working) hides none. */
|
|
481
|
+
const waitsOnPerson = (run) => {
|
|
482
|
+
if (run.kind !== "agentic")
|
|
483
|
+
return false;
|
|
484
|
+
if (waitingApproval(run) !== undefined || pausedAt(run, { inFlight: false }) !== undefined)
|
|
485
|
+
return true;
|
|
486
|
+
const { status, state } = statusOf(run);
|
|
487
|
+
return status === "input_required" && state === "waiting";
|
|
488
|
+
};
|
|
489
|
+
/** The refusal of a message that may not answer a person, as the door's WAITING is read: a trigger's firing is skipped. */
|
|
490
|
+
const waitingRefusal = () => new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
|
|
491
|
+
// raisedToGo moves to run-view.ts (the run's served view), imported above.
|
|
438
492
|
/** What a stop keeps of where the run stands: the person's last message, by its id, or the place before any. */
|
|
439
493
|
export const stopMark = (rows) => ({ stopped_at: lastUserMessage(rows) ?? `${ROOT_CONVERSATION_ID}:0` });
|
|
440
494
|
/** The rows a snapshot that no longer holds them leaves served: those committed entries made. A row any connection
|
|
441
495
|
* showed live is not one (`live` holds them for the run), so a live row that ended while the door was away goes. */
|
|
442
|
-
|
|
496
|
+
/** The live path's keep: a row a committed entry made stays served though a later snapshot no longer holds it (the
|
|
497
|
+
* timeline only grows); a row the reducer showed live does not, nor one only the served view makes (`madeHere`, the ids
|
|
498
|
+
* show() tagged servedOnly, read as it grows), which goes once show() stops making it. */
|
|
499
|
+
export function keepCommitted(live, rows, isLive, madeHere = new Set()) {
|
|
443
500
|
for (const row of rows)
|
|
444
501
|
if (isLive(row.id))
|
|
445
502
|
live.add(row.id);
|
|
446
|
-
return (id) => !live.has(id) && !isLive(id);
|
|
503
|
+
return (id) => !madeHere.has(id) && !live.has(id) && !isLive(id);
|
|
447
504
|
}
|
|
448
505
|
/** A wait's mark: the stop it stands at, while that stop holds, else its newest row (the question it waits on). */
|
|
449
506
|
const waitMark = (run) => (stopped(run) && run.meta.stopped_at) || meaningful(run.rows)?.id || "";
|
|
507
|
+
/** What a wait's run.needs_input notice is keyed on: a workflow paused at its cap, by its pause's own mark (budget.ts:
|
|
508
|
+
* where it waits and since when), which needs no row, so a pause at its first decision, before any model row, is told
|
|
509
|
+
* too, and a pause written again at a higher cap is told again; any other wait, by waitMark. */
|
|
510
|
+
const noticeMark = (run) => {
|
|
511
|
+
const mark = run.kind === "workflow" && run.dir && budgetWaiting(run) ? budgetPausedIn(run.dir) : undefined;
|
|
512
|
+
return mark ? `budget:${mark.path ?? mark.node ?? ""}:${mark.at}` : waitMark(run);
|
|
513
|
+
};
|
|
450
514
|
/** Waits for `work`, or until `deadline` (ms since the epoch), whichever comes first. */
|
|
451
515
|
async function untilDeadline(work, deadline) {
|
|
452
516
|
let timer;
|
|
453
517
|
await Promise.race([work, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))))]);
|
|
454
518
|
clearTimeout(timer);
|
|
455
519
|
}
|
|
456
|
-
/** A run's status and state, by the contract's table.
|
|
520
|
+
/** A run's status and state, by the contract's table (run-view.ts statusOf). The table is read over the run's rows, its
|
|
521
|
+
* turns and its store entries; the file-backed facts (a workflow paused at its cap or in its process, the browser ask)
|
|
522
|
+
* this server reads from the run's directory and passes in. The store-backed view builds the same facts from the run's
|
|
523
|
+
* row and journal, so the status a person or a model sees is the same. The facts are thunks, read only where the table
|
|
524
|
+
* reaches them, so the hot path (an ended or stopped run) touches no file, as it did when the reads lived here. */
|
|
457
525
|
export function statusOf(run) {
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
//
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
return { status: "input_required", state: "idle" };
|
|
475
|
-
if (!users)
|
|
476
|
-
return { status: "queued", state: "working" };
|
|
477
|
-
// A tool call parked for approval (tool-gate.ts) waits for the person; once answered, its process acts on it.
|
|
478
|
-
if (run.kind === "agentic" && run.submitted === 0 && !run.working) {
|
|
479
|
-
if (waitingApproval(run))
|
|
480
|
-
return { status: "input_required", state: "waiting" };
|
|
481
|
-
if (actingOn(run))
|
|
482
|
-
return { status: "working", state: "working" };
|
|
483
|
-
}
|
|
484
|
-
// Every message's turn is over and the newest one's ended interrupted, with no stop of the person's saying so (the
|
|
485
|
-
// harness ended it on its own): the run waits for the person, as after a stop, never working for good.
|
|
486
|
-
if (run.kind === "agentic" && run.submitted === 0 && run.turns.end()?.status === "interrupted")
|
|
487
|
-
return { status: "input_required", state: "idle" };
|
|
488
|
-
// Paused at its cap: it waits for the cap to be raised; raised, for a message, if the raise's own follow-up did not go.
|
|
489
|
-
if (refusedAt(run) !== undefined)
|
|
490
|
-
return pausedAt(run) !== undefined ? { status: "input_required", state: "waiting" } : { status: "input_required", state: "idle" };
|
|
491
|
-
if (run.working)
|
|
492
|
-
return { status: "working", state: "working" };
|
|
493
|
-
if (meaningful(run.rows)?.kind === "waiting")
|
|
494
|
-
return { status: "input_required", state: "waiting" };
|
|
495
|
-
return { status: "working", state: "idle" };
|
|
526
|
+
return statusOfView(run, { budgetWaiting: () => budgetWaiting(run), paused: () => !!run.dir && pausedIn(run.dir), browserAsk: () => browserAsk(run) });
|
|
527
|
+
}
|
|
528
|
+
/** A run's first message's origin as its serve.json keeps it. A run with a trigger (`trigger`, read from the same file)
|
|
529
|
+
* always has a trigger's: the kept one when it names that trigger and has the owner its source makes it (true for a
|
|
530
|
+
* schedule alone), else that trigger's with owner false, so a forged or lost origin never reads as the person's or the
|
|
531
|
+
* owner's. A run with none keeps none. */
|
|
532
|
+
function inputOriginOf(stored, trigger) {
|
|
533
|
+
if (trigger === null)
|
|
534
|
+
return undefined;
|
|
535
|
+
const origin = originOf(stored);
|
|
536
|
+
if (origin?.kind === "trigger" && origin.trigger_id === trigger.id && origin.owner === (origin.source === "schedule"))
|
|
537
|
+
return origin;
|
|
538
|
+
// owner false is the point; the source is a best-effort label: the stored one when it is a known source other than a
|
|
539
|
+
// schedule's, else "webhook".
|
|
540
|
+
const source = origin?.kind === "trigger" && origin.source !== "schedule" ? origin.source : "webhook";
|
|
541
|
+
return { kind: "trigger", trigger_id: trigger.id, source, owner: false };
|
|
496
542
|
}
|
|
497
543
|
/** The trigger a serve.json says started its run, as read back: `{id, firing_key}`, or null. */
|
|
498
544
|
function triggerOf(meta) {
|
|
@@ -502,8 +548,9 @@ function triggerOf(meta) {
|
|
|
502
548
|
/** Why a message that may not answer a person's question is not sent. */
|
|
503
549
|
export const WAITS_ON_A_PERSON = "The run is waiting on a person.";
|
|
504
550
|
/** The server's own secrets, which a run's process never gets: the API token, by name or by value, the seal key
|
|
505
|
-
* the tool keys are kept under (tool-keys.ts),
|
|
506
|
-
|
|
551
|
+
* the tool keys are kept under (tool-keys.ts), the store's URL (it may hold the database's password), and the boxes'
|
|
552
|
+
* keys (boxes.ts), which only the server's box providers use. */
|
|
553
|
+
const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", "AGENTRUN_STORE_URL", ...BOX_KEYS]);
|
|
507
554
|
/** The secrets a run's process is handed over its pipe (secrets.ts): every one but the server's own and the decision
|
|
508
555
|
* keys, which go on their own descriptor. */
|
|
509
556
|
export const RUN_SECRETS = SECRET_NAMES.filter((name) => !SERVER_ONLY.has(name) && !DECISION_KEYS.includes(name));
|
|
@@ -522,7 +569,7 @@ export async function needsOf(revision) {
|
|
|
522
569
|
const nodes = workflow ? workflowNodes(workflow, (await import("@parcha/agentrun-dsl")).inspectWorkflow(workflow)) : undefined;
|
|
523
570
|
const bound = nodes && workflowTools(nodes);
|
|
524
571
|
return {
|
|
525
|
-
harness: revision.body
|
|
572
|
+
harness: harnessOfBody(revision.body),
|
|
526
573
|
...(revision.kind === "agentic" && revision.body.model ? { model: revision.body.model } : {}),
|
|
527
574
|
tools: bound ? [...bound.nodes, ...bound.calls] : [...(revision.body.tools ?? [])],
|
|
528
575
|
...(nodes ? { tiers: llmTiers(nodes, nodeTiers(nodes)) } : {}),
|
|
@@ -532,14 +579,15 @@ export async function needsOf(revision) {
|
|
|
532
579
|
/** The secrets a run of `needs` is handed over its pipe, by the keys `env` holds now: RUN_SECRETS but each field of a
|
|
533
580
|
* `tool` row of `rows` (TOOL_KEYS) that unlocks none of the tools the run binds; and but each model key its model does
|
|
534
581
|
* not need, from the host's model settings and the keys in `env`: a pi run's, its models' providers' keys or the
|
|
535
|
-
* gateway's (model.ts' modelKeys: its own model, or the host's of each tier it runs);
|
|
536
|
-
* one key
|
|
582
|
+
* gateway's (model.ts' modelKeys: its own model, or the host's of each tier it runs); a run on an adapter's, the
|
|
583
|
+
* one key its wire's route sends for the revision's model (adapters.ts' harnessModelKeys). Read at each launch, so a key
|
|
537
584
|
* saved with no restart counts at the next. */
|
|
538
585
|
export function keysFor(needs, env, rows = TOOL_KEYS) {
|
|
539
586
|
const named = new Set(needs.tools);
|
|
540
587
|
const unlocked = new Set(rows.filter((row) => row.unlocks.some((name) => named.has(name))).flatMap((row) => row.fields));
|
|
541
588
|
const scoped = scopedOf(rows);
|
|
542
|
-
const
|
|
589
|
+
const entry = harnessOf(env, needs.harness);
|
|
590
|
+
const model = new Set(!entry || entry.facts ? harnessModelKeys(needs.harness, env, needs.model) : needs.tiers ? modelKeys(env, undefined, needs.tiers) : modelKeys(env, needs.model));
|
|
543
591
|
return RUN_SECRETS.filter((name) => (!scoped.includes(name) || unlocked.has(name)) && (!MODEL_KEYS.includes(name) || model.has(name)));
|
|
544
592
|
}
|
|
545
593
|
/** The secrets a run of `revision` is handed with the keys `env` holds (needsOf, then keysFor). */
|
|
@@ -624,26 +672,41 @@ export async function lastLogLine(run) {
|
|
|
624
672
|
await file.close();
|
|
625
673
|
}
|
|
626
674
|
}
|
|
627
|
-
/** Seams for tests, each unset in a server: `personsTurn` holds a person's turn just after its origin went
|
|
675
|
+
/** Seams for tests, each unset in a server: `personsTurn` holds a person's turn just after its origin went;
|
|
676
|
+
* `beforeRestartCheck` holds a settle that found the run's process gone just before it decides whether to open it again. */
|
|
628
677
|
export const runsTestHooks = {};
|
|
629
678
|
export class Runs {
|
|
630
679
|
options;
|
|
631
680
|
runs = new Map();
|
|
632
|
-
/**
|
|
633
|
-
|
|
681
|
+
/** The current name of each trigger a held run names, by its id (servedTriggerRow): pushed in at a firing's start (the
|
|
682
|
+
* run's trigger), on a rename or delete (server.ts triggerChanged), and resolved once when a run is loaded, so a
|
|
683
|
+
* served row names its trigger with no store read. `undefined` for a trigger that is gone. */
|
|
684
|
+
triggerNames = new Map();
|
|
685
|
+
/** The last entry each run's database reads have seen (run-db.ts): a read behind it is never shown. */
|
|
686
|
+
reads = new MonotonicReads();
|
|
687
|
+
/** The disk the runs' folders are on (disk.ts): on this machine, the data directory's own. */
|
|
688
|
+
get disk() {
|
|
689
|
+
return (this.#disk ??= localDisk(this.options.agents.dir, this.store));
|
|
690
|
+
}
|
|
691
|
+
#disk;
|
|
634
692
|
/** What decides the secrets each revision's runs are handed (needsOf), by revision id: read once, from the revision the
|
|
635
693
|
* run is pinned to, never from a request. The keys themselves are read at each launch (keysFor). */
|
|
636
694
|
needs = new Map();
|
|
637
|
-
/** Every run's graph as served, part by part (servedGraph), and each workflow run's last graph read whole, which a
|
|
638
|
-
* poll that met a busy store answers, marked stale: one LRU by bytes across runs (graph-served.ts PartCache). */
|
|
639
|
-
graphCache = new PartCache(GRAPH_CACHE_BYTES);
|
|
640
695
|
adopting = new Map();
|
|
696
|
+
/** The runs this process is starting, from the store's row until the run is held (start): its serve.json and its seed
|
|
697
|
+
* copy are written in between. A read of one waits for its start and never loads it from disk, where it would look
|
|
698
|
+
* like a run a stopped server left mid-copy. Null once a start failed. */
|
|
699
|
+
startingRuns = new Map();
|
|
641
700
|
/** The hosts this server's next remote box asks for: the setting's, until the provider cannot keep a list here, then none. */
|
|
642
701
|
remoteAllow;
|
|
643
702
|
clock = new ChangeClock();
|
|
644
703
|
cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("@parcha/pi-durable-disk")));
|
|
645
704
|
app = fileURLToPath(new URL("./app.js", import.meta.url));
|
|
646
705
|
closing = false;
|
|
706
|
+
/** Raised workflow runs waiting for a place to open again in (finishRaise), tried again every PLACE_RETRY_MS. */
|
|
707
|
+
placeWaiters = new Set();
|
|
708
|
+
placeRetry;
|
|
709
|
+
placeRetrying = false;
|
|
647
710
|
/** Set once `close` is done: the store is closed, so nothing settles after it. */
|
|
648
711
|
closed = false;
|
|
649
712
|
/** Runs past the cap's check whose process is not started yet. */
|
|
@@ -651,6 +714,7 @@ export class Runs {
|
|
|
651
714
|
/** The memory the starts counted in `starting` reserve, in MiB. */
|
|
652
715
|
startingMib = 0;
|
|
653
716
|
/** This host's memory, out of which each live run reserves what its harness takes (host.ts), beside `maxRuns`. */
|
|
717
|
+
/** This host's memory for runs (host.ts); a test's seam sets it (startServe's `hostMemory`). */
|
|
654
718
|
memory = hostMemory();
|
|
655
719
|
/** The start sweep of the boxes runs left: once, before any run opens a box (sweepOnce). */
|
|
656
720
|
swept;
|
|
@@ -682,6 +746,11 @@ export class Runs {
|
|
|
682
746
|
/** A test's seam (startServe's `beforeReopenLaunch`): awaited by a reopen after the run reads open again and before its
|
|
683
747
|
* launch, so a test can hold a reopen there. */
|
|
684
748
|
beforeReopenLaunch;
|
|
749
|
+
/** A test's seam (startServe's `beforeRaiseLaunch`): awaited where a raise that opens a let-go workflow pins what its
|
|
750
|
+
* launch needs (finishRaise), after its place is taken; one that throws stands for a pin that fails there. */
|
|
751
|
+
beforeRaiseLaunch;
|
|
752
|
+
/** A test's seam (startServe's `onPauseCheck`): told each stat and each read of a workflow run's pause by its watch. */
|
|
753
|
+
onPauseCheck;
|
|
685
754
|
/** A test's seam (startServe's `onRunLoad`): told each run read in from its store, its timeline with it. */
|
|
686
755
|
onRunLoad;
|
|
687
756
|
/** A test's seam (startServe's `beforeSubmit`): awaited by a message before it goes to the run's door. */
|
|
@@ -704,6 +773,10 @@ export class Runs {
|
|
|
704
773
|
const known = this.runs.get(id);
|
|
705
774
|
if (known)
|
|
706
775
|
return known;
|
|
776
|
+
// One this process is starting is its start's Run once held; a start that failed leaves its row, read as any.
|
|
777
|
+
const starting = await this.startingRuns.get(id);
|
|
778
|
+
if (starting)
|
|
779
|
+
return starting;
|
|
707
780
|
const row = await this.options.agents.request(() => this.store.readRun(id));
|
|
708
781
|
return row ? this.adopt(row) : null;
|
|
709
782
|
}
|
|
@@ -712,6 +785,10 @@ export class Runs {
|
|
|
712
785
|
const known = this.runs.get(row.id);
|
|
713
786
|
if (known)
|
|
714
787
|
return Promise.resolve(known);
|
|
788
|
+
// One this process is starting is never read from disk (startingRuns): its start holds it.
|
|
789
|
+
const starting = this.startingRuns.get(row.id);
|
|
790
|
+
if (starting)
|
|
791
|
+
return starting.then((run) => run ?? this.adopt(row));
|
|
715
792
|
let pending = this.adopting.get(row.id);
|
|
716
793
|
if (!pending) {
|
|
717
794
|
pending = this.load(row).finally(() => this.adopting.delete(row.id));
|
|
@@ -721,8 +798,11 @@ export class Runs {
|
|
|
721
798
|
}
|
|
722
799
|
async load(row) {
|
|
723
800
|
this.onRunLoad?.(row.id);
|
|
724
|
-
const dir =
|
|
725
|
-
|
|
801
|
+
const dir = runDirIn(this.options.agents.dir, row.agent, row.id);
|
|
802
|
+
// There, but not whole JSON of an object (a damaged disk, a hand's edit): what it kept is lost. Missing is no damage:
|
|
803
|
+
// a run whose server went down before it set the run up has none (notSetUp). Kept on the run (run.damaged), so
|
|
804
|
+
// forget reads of a held run what it reads from disk of one not held (handedTo).
|
|
805
|
+
const { stored, damaged } = await readMeta(join(dir, RUN_META));
|
|
726
806
|
const trigger = triggerOf(stored);
|
|
727
807
|
const meta = {
|
|
728
808
|
title: typeof stored?.title === "string" ? stored.title : "",
|
|
@@ -730,6 +810,7 @@ export class Runs {
|
|
|
730
810
|
...(isObject(stored?.input) ? { input: stored.input } : {}),
|
|
731
811
|
...(typeof stored?.effort === "string" ? { effort: stored.effort } : {}),
|
|
732
812
|
...(typeof stored?.max_cost_usd === "number" ? { max_cost_usd: stored.max_cost_usd } : {}),
|
|
813
|
+
...(CAP_MODES.includes(stored?.cap_mode) ? { cap_mode: stored.cap_mode } : {}),
|
|
733
814
|
// Each raise of its cap, and the follow-up a stopped server never sent, which the next sends (resumeRaised).
|
|
734
815
|
...(Array.isArray(stored?.cap_raised) ? { cap_raised: stored.cap_raised } : {}),
|
|
735
816
|
...(isObject(stored?.cap_continue) ? { cap_continue: stored.cap_continue } : {}),
|
|
@@ -740,31 +821,86 @@ export class Runs {
|
|
|
740
821
|
...(typeof stored?.stopped_after === "number" ? { stopped_after: stored.stopped_after } : {}),
|
|
741
822
|
...(isObject(stored?.launch_thinking) ? { launch_thinking: stored.launch_thinking } : {}),
|
|
742
823
|
...(isObject(stored?.tool_plane) ? { tool_plane: stored.tool_plane } : {}),
|
|
824
|
+
...(stored?.unshown === true ? { unshown: true } : {}),
|
|
825
|
+
...(handedMark(stored?.sign_in_handed) ? { sign_in_handed: handedMark(stored?.sign_in_handed) } : {}),
|
|
743
826
|
...(stored?.place ? { place: storedPlace(stored.place) } : {}),
|
|
744
827
|
...(isObject(stored?.learning) ? { learning: stored.learning } : {}),
|
|
745
828
|
...(isObject(stored?.reflect) ? { reflect: stored.reflect } : {}),
|
|
746
829
|
...(isObject(stored?.approvals) ? { approvals: stored.approvals } : {}),
|
|
747
830
|
...(trigger ? { trigger } : {}),
|
|
831
|
+
// Its first message's origin, for a relaunch that sends it again: its own trigger's, never the person's or the
|
|
832
|
+
// owner's unless it holds up (inputOriginOf).
|
|
833
|
+
...(inputOriginOf(stored?.input_origin, trigger) ? { input_origin: inputOriginOf(stored?.input_origin, trigger) } : {}),
|
|
748
834
|
};
|
|
749
835
|
// A turn's origin a server before this one set is not known to be the turn running now: it goes.
|
|
750
836
|
await rm(join(dir, TURN_ORIGIN_FILE), { force: true }).catch(() => undefined);
|
|
751
837
|
// A seed copy a server went down during is taken back before anything holds the run: its relaunch, a settle, a
|
|
752
|
-
// follow-up (learning-run.ts onLoad).
|
|
838
|
+
// follow-up (learning-run.ts onLoad). A run this process is starting is never read here (startingRuns), and every
|
|
839
|
+
// start that ended saved its learning, so a copy with none saved is a stopped server's.
|
|
753
840
|
if (stored)
|
|
754
841
|
await this.learning.onLoad(row, dir, meta, () => writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`));
|
|
755
842
|
const known = await this.options.agents.revision(row.agent, row.revision);
|
|
756
843
|
const run = this.blank(row, dir, meta, known?.version ?? 0, harnessOfBody(known?.revision.body ?? {}), known ? await toolingOf(known.revision) : undefined, known?.revision);
|
|
844
|
+
if (damaged)
|
|
845
|
+
run.damaged = true;
|
|
846
|
+
// Its browser's sign-in pointer, read back before anything of the run is read or held here: its rows, answers and
|
|
847
|
+
// errors are cut of it from the first, though no launch of this server handed it one.
|
|
848
|
+
const signIn = await this.peekSignIn(run);
|
|
757
849
|
this.runs.set(row.id, run);
|
|
758
850
|
run.launching = existsSync(join(dir, RUN_LAUNCHING));
|
|
759
851
|
run.notSetUp = row.state === "running" && !isObject(stored?.input);
|
|
760
|
-
|
|
852
|
+
// The process its row names, when it lives on: an earlier server's, serving the run or still opening it.
|
|
853
|
+
const adopted = this.holder(run);
|
|
854
|
+
const lives = adopted !== undefined && adopted.pid !== process.pid && holderLives(adopted);
|
|
761
855
|
// An ended run is ended before its rows are read, so they never make it a wait: a last row that asks is no notice.
|
|
762
856
|
if (row.state !== "running")
|
|
763
857
|
run.outcome = STATUS_OF[row.state];
|
|
764
|
-
//
|
|
765
|
-
|
|
858
|
+
// A run still going whose serve.json is damaged: the plane it ran on (kept there alone) and whether it was handed its
|
|
859
|
+
// agent's sign-in (sign_in_handed) went with it, so the pointer is not read back and its text could hold it uncut.
|
|
860
|
+
// Hidden as one whose sign-in does not open is, below, when its revision grants the browser or can't be read; one whose
|
|
861
|
+
// revision has none never had a browser, so was never handed a sign-in. Nothing is written over the damaged file here:
|
|
862
|
+
// its end writes serve.json anew, hidden, and until then each server finds it damaged and hides it again.
|
|
863
|
+
if (row.state === "running" && damaged && !row.importedFrom && !run.meta.unshown && (!run.tooling || run.tooling.tools.includes("browser"))) {
|
|
864
|
+
run.error = { code: "run_failed", message: UNREADABLE_RUN_META, retryable: false };
|
|
865
|
+
run.meta.unshown = true;
|
|
866
|
+
}
|
|
867
|
+
// An ended run whose serve.json was damaged since: withheld as an ended run whose sign-in does not open is (below:
|
|
868
|
+
// no store read, no answer, output or error words), on the same terms. It ended as it ended: nothing is stopped or
|
|
869
|
+
// failed, and nothing is saved, so its words are shown again only once serve.json reads (each server decides anew).
|
|
870
|
+
if (row.state !== "running" && damaged && !row.importedFrom && !run.meta.unshown && (!run.tooling || run.tooling.tools.includes("browser")))
|
|
871
|
+
run.meta.unshown = true;
|
|
872
|
+
// A run still going whose agent's browser sign-in does not open under this server's seal key: whatever it said, or
|
|
873
|
+
// says, could repeat the pointer, which nothing here can cut. Its rows are never read, and it ends failed, saying
|
|
874
|
+
// why: a live process is stopped (below), one already gone is never opened again.
|
|
875
|
+
// Only a run that was handed it: one launched signed out since the key changed is taken up as any other.
|
|
876
|
+
if (row.state === "running" && signIn === "unreadable" && run.meta.sign_in_handed && !run.meta.unshown) {
|
|
877
|
+
run.error = { code: "run_failed", message: UNREADABLE_SIGN_IN, retryable: false };
|
|
878
|
+
run.meta.unshown = true;
|
|
879
|
+
// Unsaved (a full disk), it is still hidden here, stopped and ended; the next server reads the same unreadable
|
|
880
|
+
// sign-in and hides it again. A load that threw here would leave this run cached half taken up, never watched.
|
|
881
|
+
await this.saveMeta(run).catch((error) => warn(run.id, `that it is hidden is not saved: ${error.message}`));
|
|
882
|
+
}
|
|
883
|
+
// An ended run handed a sign-in that does not open under this server's seal key: what it said could repeat the pointer,
|
|
884
|
+
// which nothing here can cut, so none of it is served: its store is not read, and its answer, output and error words
|
|
885
|
+
// are withheld. It ended as it ended: nothing is stopped or failed. Here only, never saved for it: each server decides
|
|
886
|
+
// from its own key, so the sign-in opening again shows it again, cut. Only a run that was handed it: one launched
|
|
887
|
+
// signed out is shown as any other.
|
|
888
|
+
if (row.state !== "running" && signIn === "unreadable" && run.meta.sign_in_handed && !run.meta.unshown)
|
|
889
|
+
run.meta.unshown = true;
|
|
890
|
+
// Hidden under a key that did not open its sign-in, and that very sign-in opens again now (not one made since in its
|
|
891
|
+
// place, which would not cut the pointer its rows hold): its rows are read, cut of it.
|
|
892
|
+
// That very pointer, live or forgotten since, is read back (peekSignIn, by its hash).
|
|
893
|
+
if (run.meta.unshown && signIn === "read" && Array.isArray(run.meta.sign_in_handed)) {
|
|
894
|
+
delete run.meta.unshown;
|
|
895
|
+
// Unsaved, the next server finds it hidden and this same sign-in open, and shows it again as this one does.
|
|
896
|
+
await this.saveMeta(run).catch((error) => warn(run.id, `that it is shown again is not saved: ${error.message}`));
|
|
897
|
+
}
|
|
898
|
+
// Only a store no live process holds is opened: released, or left by a process that is gone. Never a hidden run's.
|
|
899
|
+
if ((row.state !== "running" || !lives) && !run.meta.unshown)
|
|
766
900
|
await this.storeWhenFree(run);
|
|
767
901
|
if (row.state !== "running") {
|
|
902
|
+
// An ended run's one read is done: no guard is kept for it.
|
|
903
|
+
this.reads.forget(row.id);
|
|
768
904
|
run.endedAt = row.endedAt;
|
|
769
905
|
// An ended run the store kept no cost for has an unknown cost, never $0.
|
|
770
906
|
run.costUsd = row.costUsd ?? null;
|
|
@@ -773,8 +909,9 @@ export class Runs {
|
|
|
773
909
|
await this.readDecisionCost(run).catch(() => void (run.decisionCost = null));
|
|
774
910
|
if (row.importedFrom)
|
|
775
911
|
run.imported = row.importedFrom;
|
|
912
|
+
// Its error words are the run's too (the row's summary may be its last line): withheld with the rest.
|
|
776
913
|
if (run.outcome === "failed")
|
|
777
|
-
run.error = errorOfRow(row, meta);
|
|
914
|
+
run.error = run.meta.unshown ? { code: "run_failed", message: WITHHELD_SIGN_IN, retryable: false } : errorOfRow(row, meta);
|
|
778
915
|
run.settled = true;
|
|
779
916
|
}
|
|
780
917
|
else {
|
|
@@ -784,8 +921,37 @@ export class Runs {
|
|
|
784
921
|
run.cancel = true;
|
|
785
922
|
run.finishing = "cancelled";
|
|
786
923
|
}
|
|
787
|
-
|
|
788
|
-
|
|
924
|
+
// A process an earlier server started that is gone took its browser's view with it. Its agent's ask, if one waits,
|
|
925
|
+
// stays for the run's next process to take up (browser-person.ts).
|
|
926
|
+
if (!lives)
|
|
927
|
+
void dropHandover(dir).catch(() => undefined);
|
|
928
|
+
if (run.meta.unshown && !lives && !run.outcome) {
|
|
929
|
+
// Its process gone: never opened again. The start's recovery settles it, failed (settleOnce reads `finishing`).
|
|
930
|
+
run.error ??= { code: "run_failed", message: UNREADABLE_SIGN_IN, retryable: false };
|
|
931
|
+
run.finishing = "failed";
|
|
932
|
+
run.endedAt = new Date().toISOString();
|
|
933
|
+
}
|
|
934
|
+
else if (lives && run.meta.unshown) {
|
|
935
|
+
// Its process may repeat a pointer this server cannot read, so cannot cut: it is never followed; it is stopped
|
|
936
|
+
// (SIGTERM, as a cancel's), and the run ends failed, saying why, once it has gone.
|
|
937
|
+
run.error ??= { code: "run_failed", message: UNREADABLE_SIGN_IN, retryable: false };
|
|
938
|
+
this.adoptProcess(run, adopted, false);
|
|
939
|
+
// Its turn aborted first, so the drain SIGTERM starts does not wait for it; one that outlives its drain is killed,
|
|
940
|
+
// only while it is still the holder adopted here, confirmed by its identity (killHolder: its pid, of the same
|
|
941
|
+
// start, on this boot), never a process that took its pid since.
|
|
942
|
+
this.finish(run, "failed", true);
|
|
943
|
+
setTimeout(() => {
|
|
944
|
+
if (run.orphanHolder !== adopted)
|
|
945
|
+
return;
|
|
946
|
+
try {
|
|
947
|
+
killHolder(adopted);
|
|
948
|
+
}
|
|
949
|
+
catch (error) {
|
|
950
|
+
warn(run.id, `its process is not killed: ${error.message}`);
|
|
951
|
+
}
|
|
952
|
+
}, this.killAfterMs() + 5_000).unref();
|
|
953
|
+
}
|
|
954
|
+
else if (lives) {
|
|
789
955
|
// A server that died between saving a stop and its abort reaching the run leaves the turn working.
|
|
790
956
|
run.finishStop = run.meta.stopped_at !== undefined || run.meta.stopped_after !== undefined;
|
|
791
957
|
this.adoptProcess(run, adopted);
|
|
@@ -795,8 +961,12 @@ export class Runs {
|
|
|
795
961
|
}
|
|
796
962
|
// One a server left in its end-of-run turn finishes with its job's outcome, and its turn, when its process lives,
|
|
797
963
|
// is asked again (learning-run.ts).
|
|
798
|
-
this.learning.onAdopt(run,
|
|
964
|
+
this.learning.onAdopt(run, lives);
|
|
799
965
|
}
|
|
966
|
+
// A run restored after a restart has no pushed name yet: its trigger's name is resolved once from the store here (the
|
|
967
|
+
// load path is already async), so its served rows name it, never left blank; a later rename pushes the new one.
|
|
968
|
+
if (trigger && !this.triggerNames.has(trigger.id))
|
|
969
|
+
this.triggerNames.set(trigger.id, await this.options.triggerName?.(trigger.id));
|
|
800
970
|
this.refresh(run);
|
|
801
971
|
return run;
|
|
802
972
|
}
|
|
@@ -822,22 +992,50 @@ export class Runs {
|
|
|
822
992
|
});
|
|
823
993
|
return run.saving;
|
|
824
994
|
}
|
|
825
|
-
|
|
826
|
-
|
|
995
|
+
/** The process that holds the run, as its row's claim names it (run-holder.ts); undefined for none, or the server. */
|
|
996
|
+
holder(run) {
|
|
997
|
+
return this.holderView(run).holder;
|
|
827
998
|
}
|
|
828
|
-
/**
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
999
|
+
/** Who holds the run, as its row says and the processes show: `unknown` when the row or the process listing cannot be
|
|
1000
|
+
* read, which a caller never takes for a holder that is gone. */
|
|
1001
|
+
holderView(run) {
|
|
1002
|
+
try {
|
|
1003
|
+
const holder = holderOfClaim(run.id, this.store.runClaim(run.id));
|
|
1004
|
+
return holder === undefined ? { unknown: false } : holderState(holder) === "unknown" ? { holder, unknown: true } : { holder, unknown: false };
|
|
1005
|
+
}
|
|
1006
|
+
catch {
|
|
1007
|
+
return { unknown: true };
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
/** The door a live run serves, from its row's holder: a process that lives (its pid, of the same start, on this boot)
|
|
1011
|
+
* and a loopback address it named. */
|
|
1012
|
+
doorOf(run) {
|
|
1013
|
+
let door = run.child && run.door !== undefined ? run.door : undefined;
|
|
1014
|
+
if (door === undefined) {
|
|
1015
|
+
const holder = this.holder(run);
|
|
1016
|
+
if (holder?.door === undefined || !holderLives(holder))
|
|
1017
|
+
return undefined;
|
|
1018
|
+
door = holder.door;
|
|
1019
|
+
}
|
|
1020
|
+
const url = URL.parse(door);
|
|
839
1021
|
return url?.protocol === "http:" && isLoopback(url.hostname) ? url.origin : undefined;
|
|
840
1022
|
}
|
|
1023
|
+
/** The record the run's process keeps in its own store (pi-durable-disk RUN_STATUS_TABLE: its status, `detail` and
|
|
1024
|
+
* `wakeAt`), read lock-free; null when it has none or it cannot be read. */
|
|
1025
|
+
async runRecord(run) {
|
|
1026
|
+
const file = this.storeFile(run);
|
|
1027
|
+
if (!existsSync(file))
|
|
1028
|
+
return null;
|
|
1029
|
+
try {
|
|
1030
|
+
return await readRunDb(file, this.live(run), (db) => {
|
|
1031
|
+
const row = db.prepare(`SELECT record FROM ${RUN_STATUS_TABLE} WHERE id = 1`).get();
|
|
1032
|
+
return row ? JSON.parse(row.record) : null;
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
catch {
|
|
1036
|
+
return null;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
841
1039
|
storeFile(run) {
|
|
842
1040
|
return join(run.dir, "store", "run.sqlite");
|
|
843
1041
|
}
|
|
@@ -848,11 +1046,13 @@ export class Runs {
|
|
|
848
1046
|
const file = this.storeFile(run);
|
|
849
1047
|
if (!(await stat(file).catch(() => null)))
|
|
850
1048
|
return;
|
|
851
|
-
const { DatabaseSync } = await import("node:sqlite");
|
|
852
1049
|
const read = [];
|
|
853
1050
|
const submissions = [];
|
|
854
|
-
|
|
855
|
-
|
|
1051
|
+
// A fresh read-only, lock-free read (run-db.ts), after any take-back's checkpoint of this run: one at a time.
|
|
1052
|
+
const last = await this.runDb(run, () => readRunDb(file, this.live(run), (db) => {
|
|
1053
|
+
// A read made again (its file changed during it, run-db.ts) starts from none.
|
|
1054
|
+
read.length = 0;
|
|
1055
|
+
submissions.length = 0;
|
|
856
1056
|
const rows = run.kind === "workflow" || atEnd
|
|
857
1057
|
? db.prepare("SELECT conversation_id, record FROM entries ORDER BY id").iterate()
|
|
858
1058
|
: db.prepare("SELECT conversation_id, record FROM entries WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").iterate();
|
|
@@ -864,9 +1064,16 @@ export class Runs {
|
|
|
864
1064
|
for (const row of inputs)
|
|
865
1065
|
submissions.push(JSON.parse(String(row.record)));
|
|
866
1066
|
}
|
|
1067
|
+
return Number(db.prepare("SELECT max(id) AS last FROM entries").get().last ?? 0);
|
|
1068
|
+
}));
|
|
1069
|
+
// An older view of the file than one read before is never shown: what was read before stays.
|
|
1070
|
+
try {
|
|
1071
|
+
this.reads.accept(run.id, last);
|
|
867
1072
|
}
|
|
868
|
-
|
|
869
|
-
|
|
1073
|
+
catch (error) {
|
|
1074
|
+
if (error instanceof BehindReadError)
|
|
1075
|
+
return warn(run.id, `a read of its store was behind one before (${error.message}); the earlier read stands`);
|
|
1076
|
+
throw error;
|
|
870
1077
|
}
|
|
871
1078
|
const root = read.reduce((min, r) => Math.min(min, r.conversation), Infinity);
|
|
872
1079
|
const entries = read.flatMap((r) => (run.kind === "workflow" || r.conversation === root ? [r.entry] : []));
|
|
@@ -875,7 +1082,7 @@ export class Runs {
|
|
|
875
1082
|
// Decisions it cannot read add no rows, and leave the served usage row's total unknown, as the run's cost read
|
|
876
1083
|
// does (readDecisionCost): never its model nodes' total alone.
|
|
877
1084
|
try {
|
|
878
|
-
run.decisions = durableDecisions(file);
|
|
1085
|
+
run.decisions = durableDecisions(file, { unlocked: true });
|
|
879
1086
|
}
|
|
880
1087
|
catch {
|
|
881
1088
|
run.decisions = null;
|
|
@@ -890,10 +1097,33 @@ export class Runs {
|
|
|
890
1097
|
noteApprovals(run, entries);
|
|
891
1098
|
this.take(run, timelineOf(redactGateMessages(entries, this.redactor(run)), { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
|
|
892
1099
|
}
|
|
1100
|
+
/** `act` on run `run`'s database, after every earlier one on it: its reads and its take-back's checkpoint never meet. */
|
|
1101
|
+
runDb(run, act) {
|
|
1102
|
+
const next = (run.dbQueue ?? Promise.resolve()).then(act);
|
|
1103
|
+
run.dbQueue = next.then(() => undefined, () => undefined);
|
|
1104
|
+
return next;
|
|
1105
|
+
}
|
|
1106
|
+
/** The server takes run `run` back once no process holds it: its claim's epoch is bumped, with the server as its
|
|
1107
|
+
* holder (the disk's revoke, disk.ts), and only then its database checkpointed (run-db.ts), its WAL emptied into the
|
|
1108
|
+
* database file. A run whose process still lives is not taken. A take-back that fails (the agent store held by another
|
|
1109
|
+
* writer, or not writable) only warns: the run settles all the same, its database read with its WAL, and the next
|
|
1110
|
+
* settle or start takes it back. */
|
|
1111
|
+
async takeBack(run) {
|
|
1112
|
+
if (this.live(run))
|
|
1113
|
+
return;
|
|
1114
|
+
await this.runDb(run, async () => {
|
|
1115
|
+
// Tried once: a store another writer holds is not waited on, since what follows (a relaunch, a message) must not wait
|
|
1116
|
+
// on it; the next take-back tries again. No checkpoint before the claim is the server's.
|
|
1117
|
+
await this.disk.revoke(run.id);
|
|
1118
|
+
const file = this.storeFile(run);
|
|
1119
|
+
if (await stat(file).catch(() => null))
|
|
1120
|
+
await checkpointRunDb(file, this.live(run));
|
|
1121
|
+
}).catch((error) => warn(run.id, `it was not taken back (${error.message}); its database keeps its WAL until the next take-back`));
|
|
1122
|
+
}
|
|
893
1123
|
/** New rows in: into the log, then the run's status, then whatever the status asks for. */
|
|
894
1124
|
/** `keep`: rows that stay served though `rows` no longer holds them (the live path's committed rows). */
|
|
895
1125
|
take(run, rows, keep) {
|
|
896
|
-
run.rows = withOverCap(labelled(run.meta.reflect, withApprovals(withAsks(rows.filter((r) => !QUIET.test(r.id))), run, this.redactor(run))), run.meta.max_cost_usd);
|
|
1126
|
+
run.rows = withOverCap(labelled(run.meta.reflect, withApprovals(withAsks(rows.filter((r) => !QUIET.test(r.id))), run, this.redactor(run))), run.meta.max_cost_usd, run.bounds?.ended());
|
|
897
1127
|
// Counted by id: a snapshot of a compacted conversation shows fewer user messages than before, which is not more
|
|
898
1128
|
// messages waiting, so a count of rows would leave the run working forever.
|
|
899
1129
|
const arrived = run.rows.filter((r) => isMessageRow(r) && !run.users.has(r.id));
|
|
@@ -909,7 +1139,8 @@ export class Runs {
|
|
|
909
1139
|
restate(run) {
|
|
910
1140
|
if (!run.approvals?.size)
|
|
911
1141
|
return;
|
|
912
|
-
|
|
1142
|
+
// The rows as served, run through again: withApprovals gives the same rows run on its own output.
|
|
1143
|
+
run.rows = withApprovals(run.rows, run, this.redactor(run));
|
|
913
1144
|
this.show(run);
|
|
914
1145
|
}
|
|
915
1146
|
/** The run's rows into its log, as served: a workflow run's decisions and the run's learning row are the served view's
|
|
@@ -917,19 +1148,68 @@ export class Runs {
|
|
|
917
1148
|
show(run) {
|
|
918
1149
|
// The decisions' rows are the served view's only: the run's own rows, which its cost is read from, stay its model nodes'.
|
|
919
1150
|
// Their summary and text are redacted whole, then cut (decision-rows.ts): a provider's error can quote a held key.
|
|
920
|
-
|
|
1151
|
+
// An ended run's usage row says its cost, never "so far": its rows may have been read while it ran.
|
|
1152
|
+
const ended = TERMINAL.has(statusOf(run).status);
|
|
1153
|
+
const own = run.decisions === undefined ? run.rows : withDecisions(run.rows, run.decisions, this.decisionShown(run), { ended });
|
|
921
1154
|
// An error row reads as the run's error does (errorWords): a refused key in plain words, no loopback address.
|
|
922
|
-
const served = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : row));
|
|
1155
|
+
const served = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : ended ? endedUsage(row) : row));
|
|
923
1156
|
// A run paused at its cap says so after the refusal, as the row its status reads.
|
|
924
1157
|
const said = pausedAt(run);
|
|
925
|
-
const rows = said === undefined || run.meta.max_cost_usd === undefined ? served : withPaused(served
|
|
926
|
-
|
|
1158
|
+
const rows = said === undefined || run.meta.max_cost_usd === undefined ? served : withPaused(served);
|
|
1159
|
+
// While its harness installs, the run says so (a phase row of the server's, gone once it is installed).
|
|
1160
|
+
const installing = run.installRow ? [...rows, installRow(run.installRow)] : rows;
|
|
1161
|
+
// While a raised run waits for a place to open again in, it says so (gone once it opens).
|
|
1162
|
+
const waitingPlace = run.placeWait ? [...installing, placeRow(run.placeWait)] : installing;
|
|
1163
|
+
// A raise taken whose launch kept failing: the run says why it is paused again.
|
|
1164
|
+
const placing = run.raiseFailedRow ? [...waitingPlace, raiseFailedRow(run.raiseFailedRow)] : waitingPlace;
|
|
1165
|
+
// A trigger's row names the trigger as it is now (its name, else its id), here alone: every page, the stream and the
|
|
1166
|
+
// final rows are read from this view.
|
|
1167
|
+
const view = withLearning(placing, run.meta.learning, this.learning.shown()).map((row) => (row.trigger ? this.servedTriggerRow(run, row) : row));
|
|
1168
|
+
// Every row only this view makes, remembered by id, so the live path's keep never holds one once it is no longer made.
|
|
1169
|
+
servedOnlyIds(view, (run.madeHere ??= new Set()));
|
|
1170
|
+
if (run.log.sync(view, run.keep))
|
|
927
1171
|
run.updatedAt = new Date().toISOString();
|
|
928
1172
|
}
|
|
1173
|
+
/** A trigger's row as served: "<label> <its name>: <its first line>" for a trigger that has a name now; as the timeline
|
|
1174
|
+
* wrote it, "<label> <its id>: …", for one that is gone. The name is put in after the run's rows were redacted, so it
|
|
1175
|
+
* is redacted here with the run's redactor: a key pasted into a trigger's name never shows on its runs' rows. */
|
|
1176
|
+
servedTriggerRow(run, row) {
|
|
1177
|
+
const { id, source } = row.trigger;
|
|
1178
|
+
const given = this.triggerNames.get(id);
|
|
1179
|
+
const name = given === undefined ? undefined : this.redactor(run)(given).replace(/\s+/g, " ").trim();
|
|
1180
|
+
const label = TRIGGER_LABELS[source];
|
|
1181
|
+
const written = `${label} ${id}: `;
|
|
1182
|
+
// The name on the row's trigger too, as the summary shows it: a client drops exactly "<label> <name>: ", whatever
|
|
1183
|
+
// colons the name and the message hold.
|
|
1184
|
+
return name && row.summary?.startsWith(written) ? { ...row, summary: `${label} ${name}: ${row.summary.slice(written.length)}`, trigger: { ...row.trigger, name } } : row;
|
|
1185
|
+
}
|
|
1186
|
+
/** Trigger `id` renamed or deleted, with its name now (`name`, undefined when it is gone): the name is pushed to the
|
|
1187
|
+
* one the runs read (triggerNames), and each held run whose Timeline names it is shown again, its row naming the
|
|
1188
|
+
* trigger as it is now. With no `id` (the triggers just read at a start): every run so named is shown again. */
|
|
1189
|
+
triggerChanged(id, name) {
|
|
1190
|
+
if (id !== undefined)
|
|
1191
|
+
this.triggerNames.set(id, name);
|
|
1192
|
+
for (const run of this.runs.values())
|
|
1193
|
+
if (run.rows.some((row) => row.trigger && (id === undefined || row.trigger.id === id)))
|
|
1194
|
+
this.show(run);
|
|
1195
|
+
}
|
|
929
1196
|
/** A live process: the child this server started, or one an earlier server started that still serves the run. */
|
|
930
1197
|
live(run) {
|
|
931
1198
|
return Boolean(run.child || run.orphan);
|
|
932
1199
|
}
|
|
1200
|
+
/** Run `id`'s status read again now: the owner answered its browser ask (browser-person.ts), so it is working again
|
|
1201
|
+
* before its process has read the answer. */
|
|
1202
|
+
remark(id) {
|
|
1203
|
+
const run = this.runs.get(id);
|
|
1204
|
+
if (run)
|
|
1205
|
+
this.mark(run);
|
|
1206
|
+
}
|
|
1207
|
+
/** Whether run `id` has a process serving it now: the child this server started, or an adopted one that is alive. A
|
|
1208
|
+
* run's live browser view is that process's alone (browser-live.ts). */
|
|
1209
|
+
hasProcess(id) {
|
|
1210
|
+
const run = this.runs.get(id);
|
|
1211
|
+
return Boolean(run && ((run.child && run.child.exitCode === null && run.child.signalCode === null) || (run.orphan && alive(run.orphan))));
|
|
1212
|
+
}
|
|
933
1213
|
/** How an agentic run ends: over its cap, or as the turn of the person's newest message ended (turns.ts), once every
|
|
934
1214
|
* message the run took has had its turn. Undefined while one is open, or when the run stopped, waits, or its turn
|
|
935
1215
|
* ended interrupted (the run then waits for the person), or while its records name no message (a live process of an
|
|
@@ -944,8 +1224,10 @@ export class Runs {
|
|
|
944
1224
|
return undefined;
|
|
945
1225
|
const cap = run.meta.max_cost_usd;
|
|
946
1226
|
const cost = costOf(run.rows);
|
|
947
|
-
|
|
948
|
-
|
|
1227
|
+
// Past it by a cache miss, within the bound its cap admitted it at (overByMiss), the run goes on: its next request is
|
|
1228
|
+
// refused, and it pauses at its cap for a raise, as when the cap has no room; the over-cap row says what happened.
|
|
1229
|
+
if (cap !== undefined && cost !== null && cost > cap + FIT_TOLERANCE && !overByMiss(cost, cap, run.bounds?.ended() ?? 0))
|
|
1230
|
+
return { outcome: "failed", abort: true, error: { code: SPEND_CAP_REACHED, message: `The run cost ${cents(cost)}, ${centsUp(cost - cap)} over its cap of ${cents(cap)}.`, retryable: false } };
|
|
949
1231
|
if (run.submitted > 0)
|
|
950
1232
|
return undefined;
|
|
951
1233
|
if (run.turns.open > 0 || stopped(run))
|
|
@@ -978,9 +1260,15 @@ export class Runs {
|
|
|
978
1260
|
errorWords(run, text) {
|
|
979
1261
|
return text ? this.shown(run, this.plainKey(run, text) ?? text) : text;
|
|
980
1262
|
}
|
|
981
|
-
/** An error row as served: its summary and text in errorWords' terms
|
|
982
|
-
* what the harness said. */
|
|
1263
|
+
/** An error row as served: its summary and text in errorWords' terms, or the pause's phase row of a refusal for room the
|
|
1264
|
+
* run paused at. The run's own rows, which its status reads, keep what the harness said. */
|
|
983
1265
|
servedError(run, row) {
|
|
1266
|
+
// A refusal for room the run paused at (pausedOn) is a pause, never a failure: the request was not sent, and a raise
|
|
1267
|
+
// goes on. Its row is a phase row in short words, marked `paused`; the refusal's sentence is the banner's
|
|
1268
|
+
// (pending.said), never said again here. It is the server's row (origin server), and no message: its id ends in
|
|
1269
|
+
// NOTE_SUFFIX, which isMessageRow passes over, as the wrap-up's does. It stays so after a raise, as the run's history.
|
|
1270
|
+
if (pausedOn(run, row))
|
|
1271
|
+
return { ...row, id: `${row.id}${NOTE_SUFFIX}`, kind: "phase", origin: "server", summary: BUDGET_PAUSED, text: BUDGET_PAUSED, paused: true };
|
|
984
1272
|
const plain = this.plainKey(run, row.text ?? undefined);
|
|
985
1273
|
if (plain) {
|
|
986
1274
|
const words = this.shown(run, plain);
|
|
@@ -988,10 +1276,38 @@ export class Runs {
|
|
|
988
1276
|
}
|
|
989
1277
|
return { ...row, ...(row.summary ? { summary: this.shown(run, row.summary) } : {}), ...(row.text ? { text: this.shown(run, row.text) } : {}) };
|
|
990
1278
|
}
|
|
991
|
-
/** What serve shows of a run's error text, for every run kind: no held secret
|
|
992
|
-
* no loopback address. */
|
|
1279
|
+
/** What serve shows of a run's error text, for every run kind (run-view.ts shownOf): no held secret and no loopback. */
|
|
993
1280
|
shown(run, text) {
|
|
994
|
-
return
|
|
1281
|
+
return shownOf(this.refusedValues(run))(text);
|
|
1282
|
+
}
|
|
1283
|
+
/** A run's error as its view and the run lists serve it (run-view.ts servedRunErrorWith): its message in shown()'s terms. */
|
|
1284
|
+
servedRunError(run, error) {
|
|
1285
|
+
return servedRunErrorWith((text) => this.shown(run, text), error);
|
|
1286
|
+
}
|
|
1287
|
+
/** A run's review as its view serves it (run-view.ts servedReviewWith): its reason in shown()'s terms, or withheld while
|
|
1288
|
+
* the run is hidden (meta.unshown). */
|
|
1289
|
+
servedReview(run, review) {
|
|
1290
|
+
return servedReviewWith((text) => this.shown(run, text), run.meta.unshown, review);
|
|
1291
|
+
}
|
|
1292
|
+
/** The pointers a run was handed, read back to cut them (sign-ins.ts peek and forgotten), by its serve.json's
|
|
1293
|
+
* `sign_in_handed`: none for a run with no mark (it was never handed one); else, for each hash it names, the live or
|
|
1294
|
+
* forgotten pointer whose SHA-256 it is. `unreadable` when what it was handed can't be read back here: a MALFORMED
|
|
1295
|
+
* mark, no vendor browser kept beside the mark, the sign-ins file can't be read, or any of its hashes matches no
|
|
1296
|
+
* pointer that opens (one under another seal key or none, one forgotten and dropped past MAX_FORGOTTEN, the sign-ins
|
|
1297
|
+
* file gone). Fails closed: a marked run is cut of every pointer it was handed, or withheld, never served uncut. Read
|
|
1298
|
+
* anew at each load: nothing caches this verdict, so a run withheld while its key was missing is shown once it opens. */
|
|
1299
|
+
handedPointers(agentId, browser, handed) {
|
|
1300
|
+
return handedPointersOf(this.options.signIns, agentId, browser, handed);
|
|
1301
|
+
}
|
|
1302
|
+
/** shown() for a run this server holds no Run for (an ended one a list reads from its row and serve.json alone, the
|
|
1303
|
+
* summary choke point: run-view.ts rowShown): cut of every secret this server never shows (serverSecrets) and of what
|
|
1304
|
+
* the run was handed of its agent's sign-in (handedPointers); `withheld` when that can't be read back here, as a load
|
|
1305
|
+
* would hide the run. */
|
|
1306
|
+
rowShown(agentId, meta, damaged = false) {
|
|
1307
|
+
// Its serve.json there but unreadable: what it was handed went with it (load hides such a run, its revision granting
|
|
1308
|
+
// the browser; a list row, which reads no revision, withholds it whatever its revision).
|
|
1309
|
+
const browser = isObject(meta?.tool_plane) ? keptVendor(meta.tool_plane).browser : undefined;
|
|
1310
|
+
return rowShownOf({ serverSecrets: this.options.serverSecrets, signIns: this.options.signIns }, agentId, browser, handedMark(meta?.sign_in_handed), damaged);
|
|
995
1311
|
}
|
|
996
1312
|
/** A run's answer as serve serves it: no held secret, never cut (redactedAnswer). Loopback addresses stay: an answer is
|
|
997
1313
|
* the model's own words, and a local address there can be what the person asked about. */
|
|
@@ -1015,26 +1331,6 @@ export class Runs {
|
|
|
1015
1331
|
run.served = { ...run.served, [slot]: { keys, input, out } };
|
|
1016
1332
|
return out;
|
|
1017
1333
|
}
|
|
1018
|
-
/** A workflow run's graph as serve serves it: its nodes, each decision and each call (its input, output and error) with
|
|
1019
|
-
* no held secret, by its answer's rule (redactedOutput), and only then cut: a map item's label at 200 characters, a
|
|
1020
|
-
* call's error at 2000, and a text stored cut (a decision's state past 64 KB, an error logged cut) less its last 6
|
|
1021
|
-
* times the longest held value plus 16 characters, where a value the stored cut split would sit. The view a busy
|
|
1022
|
-
* store's read keeps is the one graph-view.ts made, whole, so a key saved after it is still found. Each part is
|
|
1023
|
-
* served once per content and held value set: a console polls the graph while the run goes. */
|
|
1024
|
-
servedGraph(run, view) {
|
|
1025
|
-
const values = this.refusedValues(run);
|
|
1026
|
-
const keys = digestOf([...values].sort());
|
|
1027
|
-
const once = (kind, value) => {
|
|
1028
|
-
const at = `part:${keys}:${kind}:${digestOf(value)}`;
|
|
1029
|
-
const kept = this.graphCache.get(at);
|
|
1030
|
-
if (kept !== undefined)
|
|
1031
|
-
return kept;
|
|
1032
|
-
const out = servedPart(kind, value, values);
|
|
1033
|
-
this.graphCache.set(at, out, Buffer.byteLength(JSON.stringify(out) ?? ""));
|
|
1034
|
-
return out;
|
|
1035
|
-
};
|
|
1036
|
-
return { ...view, nodes: once("nodes", view.nodes), decisions: view.decisions.map((value) => once("decision", value)), effects: view.effects.map((value) => once("effect", value)) };
|
|
1037
|
-
}
|
|
1038
1334
|
/** The timeline's redaction of `run`'s error rows and of what a tool's result shows (its summary and preview), applied
|
|
1039
1335
|
* before a row is cut (timelineOf's `redact`), so a cut never leaves the head of a key. Every such cut is within
|
|
1040
1336
|
* redacted()'s SHOWN, so its window holds. */
|
|
@@ -1045,18 +1341,17 @@ export class Runs {
|
|
|
1045
1341
|
return { redact: (text) => redacted(text, values), hold: 6 * values.reduce((most, value) => Math.max(most, value.length), 0) + 16 };
|
|
1046
1342
|
}
|
|
1047
1343
|
redactor(run) {
|
|
1048
|
-
return (
|
|
1344
|
+
return redactorOf(this.refusedValues(run));
|
|
1049
1345
|
}
|
|
1050
1346
|
/** The last line of the run process's log (lastLogLine) for a failure's message, with every value its errors never
|
|
1051
1347
|
* show cut out: its process may have written a secret or its sign-in's pointer there. */
|
|
1052
1348
|
async lastLine(run) {
|
|
1053
1349
|
return this.redactor(run)(await lastLogLine(run));
|
|
1054
1350
|
}
|
|
1055
|
-
/** Every secret value `run`'s errors never show, as learning's checker holds them (learning-run.ts refused):
|
|
1056
|
-
* server
|
|
1057
|
-
* server's own tokens. */
|
|
1351
|
+
/** Every secret value `run`'s errors never show, as learning's checker holds them (learning-run.ts refused): every one
|
|
1352
|
+
* this server never shows (serverSecrets, read now, so one rotated is cut at once) and what each launch handed the run. */
|
|
1058
1353
|
refusedValues(run) {
|
|
1059
|
-
return
|
|
1354
|
+
return refusedValuesOf(this.options.serverSecrets, run.handed);
|
|
1060
1355
|
}
|
|
1061
1356
|
/** A run's model error in a person's words when its provider refused the run's key (key-refusal.ts): the key its
|
|
1062
1357
|
* harness's route sends, by this server's settings and keys, and no secret's value. */
|
|
@@ -1135,44 +1430,111 @@ export class Runs {
|
|
|
1135
1430
|
/** SIGTERM to the run's process: it drains, releases the run and exits. */
|
|
1136
1431
|
terminate(run) {
|
|
1137
1432
|
if (run.child)
|
|
1138
|
-
run.child.kill("SIGTERM");
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
const pid = holderPid(record);
|
|
1146
|
-
if (!pid)
|
|
1433
|
+
return void run.child.kill("SIGTERM");
|
|
1434
|
+
// An adopted process only once its identity is confirmed (its pid, of the same start, on this boot): a pid another
|
|
1435
|
+
// process took over gets no signal, and one that cannot be checked keeps its stop pending, tried again every second
|
|
1436
|
+
// until it can be (said once for each reason), never sent unidentified. The timer keeps no server up, and close()
|
|
1437
|
+
// clears it.
|
|
1438
|
+
const holder = run.orphanHolder;
|
|
1439
|
+
if (holder === undefined)
|
|
1147
1440
|
return;
|
|
1441
|
+
const state = holderState(holder);
|
|
1442
|
+
if (state === "alive") {
|
|
1443
|
+
run.stopWaits = undefined;
|
|
1444
|
+
// Already exited (ESRCH) or another user's pid now (EPERM): nothing to stop.
|
|
1445
|
+
return void signal(holder.pid, "SIGTERM");
|
|
1446
|
+
}
|
|
1447
|
+
if (state === "gone" || this.closed)
|
|
1448
|
+
return;
|
|
1449
|
+
if (!run.stopWaits)
|
|
1450
|
+
warn(run.id, `its stop waits: its process ${holder.pid} cannot be identified (the process listing cannot be read); it is sent once it can be`);
|
|
1451
|
+
run.stopWaits = true;
|
|
1452
|
+
clearTimeout(run.stopPending);
|
|
1453
|
+
run.stopPending = setTimeout(() => {
|
|
1454
|
+
run.stopPending = undefined;
|
|
1455
|
+
try {
|
|
1456
|
+
if (run.orphanHolder === holder && !this.closed)
|
|
1457
|
+
this.terminate(run);
|
|
1458
|
+
}
|
|
1459
|
+
catch (error) {
|
|
1460
|
+
warn(run.id, `its stop is not sent: ${error.message}`);
|
|
1461
|
+
}
|
|
1462
|
+
}, 1_000).unref();
|
|
1463
|
+
}
|
|
1464
|
+
/** Supervise a run process an earlier server started, its row's holder: follow its door, and settle the run once the
|
|
1465
|
+
* process is gone, or once the record it keeps in its store has said for EXIT_AFTER_RELEASE_MS that it let go while
|
|
1466
|
+
* the process lives on. `follow`: its rows are followed live from its door (never for a run whose rows are not
|
|
1467
|
+
* shown, meta.unshown). */
|
|
1468
|
+
adoptProcess(run, holder, follow = true) {
|
|
1469
|
+
const pid = holder.pid;
|
|
1148
1470
|
run.orphan = pid;
|
|
1471
|
+
run.orphanHolder = holder;
|
|
1149
1472
|
this.reportedBack(run);
|
|
1150
|
-
|
|
1473
|
+
if (follow)
|
|
1474
|
+
this.connect(run);
|
|
1151
1475
|
let releasedAt;
|
|
1152
|
-
let
|
|
1476
|
+
let reading = false;
|
|
1477
|
+
let failedWith;
|
|
1478
|
+
// A holder that never says where it serves within the ready time is fenced: killed, then taken over.
|
|
1479
|
+
const doorBy = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS);
|
|
1480
|
+
const done = (released) => {
|
|
1481
|
+
if (run.orphan !== pid)
|
|
1482
|
+
return;
|
|
1483
|
+
clearInterval(timer);
|
|
1484
|
+
run.orphan = undefined;
|
|
1485
|
+
run.orphanHolder = undefined;
|
|
1486
|
+
// Its live browser view went with the process (browser-live.ts).
|
|
1487
|
+
void dropHandover(run.dir).catch(() => undefined);
|
|
1488
|
+
void this.settle(run, null, !holderLives(holder) && !released);
|
|
1489
|
+
};
|
|
1153
1490
|
const timer = setInterval(() => {
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
return;
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1491
|
+
if (run.orphan !== pid)
|
|
1492
|
+
return clearInterval(timer);
|
|
1493
|
+
if (reading)
|
|
1494
|
+
return;
|
|
1495
|
+
reading = true;
|
|
1496
|
+
const lives = holderLives(holder);
|
|
1497
|
+
void this.runRecord(run)
|
|
1498
|
+
.then(async (now) => {
|
|
1499
|
+
const released = RELEASED.has(String(now?.status));
|
|
1500
|
+
if (!lives)
|
|
1501
|
+
return done(released);
|
|
1502
|
+
// Its door, when the server that launched it went before it read the line: the one this process keeps in its
|
|
1503
|
+
// own store (the record names its pid), under the epoch its row holds.
|
|
1504
|
+
if (this.doorOf(run) === undefined) {
|
|
1505
|
+
const claim = this.store.runClaim(run.id);
|
|
1506
|
+
const own = isObject(now?.holder) && now.holder.pid === holder.pid ? now.holder : undefined;
|
|
1507
|
+
const serve = own?.serve;
|
|
1508
|
+
// Proven with the nonce the launching server kept on the row, as that server would have.
|
|
1509
|
+
const proven = now?.generation === claim.epoch && typeof serve === "string" && holder.nonce !== undefined && (await verifyDoor(serve, holder.nonce, this.headers(run)));
|
|
1510
|
+
if (proven) {
|
|
1511
|
+
this.nameHolder(run, claim.epoch, { ...holder, door: serve });
|
|
1512
|
+
if (follow)
|
|
1513
|
+
this.connect(run);
|
|
1514
|
+
}
|
|
1515
|
+
else if (Date.now() > doorBy) {
|
|
1516
|
+
warn(run.id, `its process ${pid} named no door within ${(this.options.readyTimeoutMs ?? READY_TIMEOUT_MS) / 1000} s; it is killed and the run taken over`);
|
|
1517
|
+
killHolder(holder);
|
|
1169
1518
|
return;
|
|
1170
|
-
|
|
1519
|
+
}
|
|
1171
1520
|
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1521
|
+
if (!released)
|
|
1522
|
+
return;
|
|
1523
|
+
releasedAt ??= Date.now();
|
|
1524
|
+
if (Date.now() - releasedAt < EXIT_AFTER_RELEASE_MS)
|
|
1525
|
+
return;
|
|
1526
|
+
warn(run.id, `its process ${pid} released the run ${EXIT_AFTER_RELEASE_MS / 1000} s ago and has not exited; reading its store anyway`);
|
|
1527
|
+
done(true);
|
|
1528
|
+
})
|
|
1529
|
+
// A poll that fails (the agent store held by another writer, a listing that cannot be read) changes nothing: the
|
|
1530
|
+
// run stays watched, and the next tick looks again.
|
|
1531
|
+
.catch((error) => {
|
|
1532
|
+
// Said once for each reason, not at every tick.
|
|
1533
|
+
if (error.message !== failedWith)
|
|
1534
|
+
warn(run.id, `its watch of process ${pid} looks again: ${error.message}`);
|
|
1535
|
+
failedWith = error.message;
|
|
1536
|
+
})
|
|
1537
|
+
.finally(() => void (reading = false));
|
|
1176
1538
|
}, 500);
|
|
1177
1539
|
timer.unref();
|
|
1178
1540
|
}
|
|
@@ -1194,7 +1556,8 @@ export class Runs {
|
|
|
1194
1556
|
}
|
|
1195
1557
|
// A remote box of an ended run is pulled first, so what it changed after its run's last pull is kept, and goes only
|
|
1196
1558
|
// once that pull landed: one that fails keeps the box for the next start, its lifetime bounding it.
|
|
1197
|
-
const
|
|
1559
|
+
const agentOf = new Map(rows.map((row) => [row.id, row.agent]));
|
|
1560
|
+
const dirOf = (id) => runDirIn(this.options.agents.dir, agentOf.get(id) ?? "", id);
|
|
1198
1561
|
const pulledFirst = (boxes, daytona) => (id, boxId) => pullRemoteBox(boxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
|
|
1199
1562
|
warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
|
|
1200
1563
|
await this.keepBox(id, boxId, daytona);
|
|
@@ -1212,7 +1575,7 @@ export class Runs {
|
|
|
1212
1575
|
}
|
|
1213
1576
|
if (!box)
|
|
1214
1577
|
return;
|
|
1215
|
-
const settled = await sweepBoxes(box.host, box.quarantine, rows.map((row) => ({ id: row.id, dir:
|
|
1578
|
+
const settled = await sweepBoxes(box.host, box.quarantine, rows.map((row) => ({ id: row.id, dir: runDirIn(this.options.agents.dir, row.agent, row.id) })));
|
|
1216
1579
|
for (const [id, how] of Object.entries(settled))
|
|
1217
1580
|
if (how === "quarantined")
|
|
1218
1581
|
warn(id, "its box could not be emptied; it is quarantined, and tried again at each start");
|
|
@@ -1241,19 +1604,8 @@ export class Runs {
|
|
|
1241
1604
|
const boxes = remote ? this.remoteOf(place) : this.options.runBoxes;
|
|
1242
1605
|
if (!boxes)
|
|
1243
1606
|
return;
|
|
1244
|
-
//
|
|
1245
|
-
//
|
|
1246
|
-
// warns: the destroy ends them all the same.
|
|
1247
|
-
if (remote || existsSync(join(run.dir, "work", BACKGROUND_DIR))) {
|
|
1248
|
-
try {
|
|
1249
|
-
const ended = await endBackground(boxes, { [RUN_LABEL]: run.id }, boxContext());
|
|
1250
|
-
if (ended)
|
|
1251
|
-
this.options.log?.("background_ended", { run: run.id, ended });
|
|
1252
|
-
}
|
|
1253
|
-
catch (error) {
|
|
1254
|
-
warn(run.id, `its background processes were not ended before its box goes (${error.message}); destroying the box ends them`);
|
|
1255
|
-
}
|
|
1256
|
-
}
|
|
1607
|
+
// A box's background processes are ended by the run's own end on the runner (its tools' close), before this runs: the
|
|
1608
|
+
// destroy ends any that outlive it the same way.
|
|
1257
1609
|
if (remote) {
|
|
1258
1610
|
try {
|
|
1259
1611
|
await this.pullBox(run, true);
|
|
@@ -1272,7 +1624,7 @@ export class Runs {
|
|
|
1272
1624
|
try {
|
|
1273
1625
|
await destroyRunBoxes(boxes, run.id, boxContext());
|
|
1274
1626
|
// The box's egress proxy directory (box-egress.ts), its socket the run's process left: nothing binds it now.
|
|
1275
|
-
await removeEgressDir(run.id).catch(() => undefined);
|
|
1627
|
+
await removeEgressDir(run.id, this.options.dockerPaths ? egressParentOf(this.options.agents.dir) : undefined).catch(() => undefined);
|
|
1276
1628
|
}
|
|
1277
1629
|
catch (error) {
|
|
1278
1630
|
warn(run.id, `its box was not destroyed (${error.message}); the next start sweeps it`);
|
|
@@ -1423,7 +1775,7 @@ export class Runs {
|
|
|
1423
1775
|
run.updatedAt = new Date().toISOString();
|
|
1424
1776
|
// What it waits on: an ask_person question (waiting), else a stopped turn, for the person's next message.
|
|
1425
1777
|
if (status === "input_required")
|
|
1426
|
-
this.notice(run, "run.needs_input",
|
|
1778
|
+
this.notice(run, "run.needs_input", noticeMark(run), { kind: state !== "waiting" ? "stopped" : waitingApproval(run) ? "approval" : pausedAt(run) !== undefined || budgetWaiting(run) ? "budget" : browserAsk(run) ? "browser" : "question" });
|
|
1427
1779
|
}
|
|
1428
1780
|
/** Tells webhooks.ts (`notify`) of a moment of the run under `marker`: a wait it reached (mark), or an end the agent store
|
|
1429
1781
|
* has (settle, persistLater, reopen). What it already queued it queues no more. */
|
|
@@ -1461,7 +1813,7 @@ export class Runs {
|
|
|
1461
1813
|
run.feed = abort;
|
|
1462
1814
|
void (async () => {
|
|
1463
1815
|
while (!abort.signal.aborted) {
|
|
1464
|
-
const door = this.doorOf(
|
|
1816
|
+
const door = this.doorOf(run);
|
|
1465
1817
|
if (door)
|
|
1466
1818
|
this.reportedBack(run);
|
|
1467
1819
|
if (door && run.kind === "workflow") {
|
|
@@ -1469,17 +1821,53 @@ export class Runs {
|
|
|
1469
1821
|
run.working = true;
|
|
1470
1822
|
this.refresh(run);
|
|
1471
1823
|
}
|
|
1824
|
+
// Its pause at its cap is written by its process (budget.json): a new one, or one written again at a higher cap
|
|
1825
|
+
// (a raise that did not cover the step), is read here, so its status and its webhook notice follow it. Each
|
|
1826
|
+
// round costs one stat; the file is read only when its time or size moved since the last read (fs.watch is not
|
|
1827
|
+
// to be trusted on the run's mount).
|
|
1828
|
+
this.watchPause(run);
|
|
1472
1829
|
}
|
|
1473
1830
|
else if (door)
|
|
1474
1831
|
await this.follow(run, door, abort.signal).catch(() => undefined);
|
|
1475
|
-
if (abort.signal.aborted || (!this.live(run) && !this.doorOf(
|
|
1832
|
+
if (abort.signal.aborted || (!this.live(run) && !this.doorOf(run)))
|
|
1476
1833
|
break;
|
|
1477
|
-
|
|
1834
|
+
// Unref'd, and cut short by the watch's end (the process's settle, the server's close): nothing waits on it. Its
|
|
1835
|
+
// listener goes when its timer fires, so a long watch holds one at most, never one a round.
|
|
1836
|
+
await new Promise((resolve) => {
|
|
1837
|
+
const cut = () => (clearTimeout(timer), resolve());
|
|
1838
|
+
const timer = setTimeout(() => (abort.signal.removeEventListener("abort", cut), resolve()), run.kind === "workflow" ? 500 : 200);
|
|
1839
|
+
timer.unref();
|
|
1840
|
+
abort.signal.addEventListener("abort", cut, { once: true });
|
|
1841
|
+
});
|
|
1478
1842
|
}
|
|
1479
1843
|
if (run.feed === abort)
|
|
1480
1844
|
run.feed = undefined;
|
|
1481
1845
|
})();
|
|
1482
1846
|
}
|
|
1847
|
+
/** One round of a live workflow run's watch of its pause at its cap: a stat of budget.json, and a read only when it
|
|
1848
|
+
* changed (its time or size); a new pause, or one written again, refreshes the run (its status, its notice). */
|
|
1849
|
+
watchPause(run) {
|
|
1850
|
+
let stamp;
|
|
1851
|
+
try {
|
|
1852
|
+
const stat = statSync(join(run.dir, BUDGET_PAUSE));
|
|
1853
|
+
stamp = `${stat.mtimeMs}:${stat.size}`;
|
|
1854
|
+
}
|
|
1855
|
+
catch {
|
|
1856
|
+
stamp = undefined;
|
|
1857
|
+
}
|
|
1858
|
+
this.onPauseCheck?.(run.id, "stat");
|
|
1859
|
+
if (stamp === run.pauseStamp)
|
|
1860
|
+
return;
|
|
1861
|
+
run.pauseStamp = stamp;
|
|
1862
|
+
if (stamp !== undefined)
|
|
1863
|
+
this.onPauseCheck?.(run.id, "read");
|
|
1864
|
+
const pause = stamp === undefined ? undefined : noticeMark(run);
|
|
1865
|
+
if (pause === run.pauseSeen)
|
|
1866
|
+
return;
|
|
1867
|
+
run.pauseSeen = pause;
|
|
1868
|
+
if (pause !== undefined)
|
|
1869
|
+
this.refresh(run);
|
|
1870
|
+
}
|
|
1483
1871
|
async follow(run, door, signal) {
|
|
1484
1872
|
// A file a call names by its absolute path in the run's workspace (a harness's CLI sends one) reads by its name there.
|
|
1485
1873
|
const reducer = timelineReducer({ path: rowPaths(run.dir), redact: this.redactor(run), redactLive: (text) => redactedLive(text, this.refusedValues(run)) });
|
|
@@ -1526,14 +1914,19 @@ export class Runs {
|
|
|
1526
1914
|
noteApprovals(run, entries);
|
|
1527
1915
|
const redact = this.redactor(run);
|
|
1528
1916
|
reducer.apply(events.map((e) => (Array.isArray(e.entries) ? { ...e, entries: redactGateMessages(e.entries, redact) } : e.entry !== undefined ? { ...e, entry: redactGateMessages([e.entry], redact)[0] } : e)));
|
|
1917
|
+
// The rows this connection makes, for a stop to read as over at once (stopTurn): only once its snapshot is in.
|
|
1918
|
+
// Until then the last connection's reducer stands, whose rows the run shows; a new one has none yet.
|
|
1919
|
+
if (event === "snapshot")
|
|
1920
|
+
run.timeline = reducer;
|
|
1529
1921
|
// A stopped turn is over while the run's process lives on: a request it cut is a charge with no price (costsofar/1),
|
|
1530
|
-
// as the settled read counts it, never one in flight.
|
|
1531
|
-
|
|
1922
|
+
// as the settled read counts it, never one in flight. Read so from the stop on (stopTurn), not from the turn's
|
|
1923
|
+
// end reaching here: the run reads stopped from then. A message sent since (`submitted`) starts a turn of its own.
|
|
1924
|
+
if (run.submitted === 0 && stopped(run))
|
|
1532
1925
|
reducer.idle();
|
|
1533
1926
|
// A snapshot rebuilds from the conversation's current view: after a compaction it holds fewer of the rows
|
|
1534
1927
|
// already shown, which stay; only live rows go when they end.
|
|
1535
1928
|
const rows = reducer.rows();
|
|
1536
|
-
this.take(run, rows, keepCommitted(run.live, rows, reducer.isLive));
|
|
1929
|
+
this.take(run, rows, keepCommitted(run.live, rows, reducer.isLive, (run.madeHere ??= new Set())));
|
|
1537
1930
|
if (event === "snapshot" && run.finishStop) {
|
|
1538
1931
|
run.finishStop = false;
|
|
1539
1932
|
if (run.working && stopped(run) && run.submitted === 0) {
|
|
@@ -1546,9 +1939,51 @@ export class Runs {
|
|
|
1546
1939
|
}
|
|
1547
1940
|
}
|
|
1548
1941
|
}
|
|
1942
|
+
/** The install `run`'s harness waits for before it launches (claude-agent's Claude Code, codex's Codex: harness-install.ts), or undefined
|
|
1943
|
+
* when it waits for none. One per run at a time, every run's on the server's one install: while that runs the run
|
|
1944
|
+
* shows it (installRow). A failed install ends the run failed, with the install's words, which name the command that
|
|
1945
|
+
* installs it by hand. */
|
|
1946
|
+
harnessReady(run) {
|
|
1947
|
+
const install = this.options.installs?.[run.harness];
|
|
1948
|
+
if (!install || install.installed)
|
|
1949
|
+
return undefined;
|
|
1950
|
+
if (run.installing)
|
|
1951
|
+
return run.installing;
|
|
1952
|
+
// Counted as holding its place until its launch (takePlace); a run whose process lives holds one already.
|
|
1953
|
+
if (!this.live(run))
|
|
1954
|
+
run.waitsInstall = true;
|
|
1955
|
+
const installing = (async () => {
|
|
1956
|
+
if (!(await install.needed()))
|
|
1957
|
+
return true;
|
|
1958
|
+
run.installRow = { at: new Date().toISOString(), words: install.installingWords };
|
|
1959
|
+
this.show(run);
|
|
1960
|
+
try {
|
|
1961
|
+
await install.ensure();
|
|
1962
|
+
return true;
|
|
1963
|
+
}
|
|
1964
|
+
catch (error) {
|
|
1965
|
+
// A server that stops mid-install leaves the run as it is, for the next server to install and launch.
|
|
1966
|
+
if (this.closing)
|
|
1967
|
+
return false;
|
|
1968
|
+
run.submitted = 0;
|
|
1969
|
+
if (!(run.outcome || run.finishing || run.cancel)) {
|
|
1970
|
+
run.error = { code: "run_failed", message: error.message, retryable: false };
|
|
1971
|
+
run.finishing = "failed";
|
|
1972
|
+
void this.settle(run, 1, true);
|
|
1973
|
+
}
|
|
1974
|
+
return false;
|
|
1975
|
+
}
|
|
1976
|
+
finally {
|
|
1977
|
+
run.installRow = undefined;
|
|
1978
|
+
this.show(run);
|
|
1979
|
+
}
|
|
1980
|
+
})().finally(() => void (run.installing = undefined));
|
|
1981
|
+
run.installing = installing;
|
|
1982
|
+
return installing;
|
|
1983
|
+
}
|
|
1549
1984
|
/** The door of a run that is not finished, starting or waking its process when it is not live. */
|
|
1550
|
-
async ensureLive(run, timeoutMs = this.options.readyTimeoutMs ?? READY_TIMEOUT_MS) {
|
|
1551
|
-
|
|
1985
|
+
async ensureLive(run, timeoutMs = this.options.readyTimeoutMs ?? READY_TIMEOUT_MS, refresh = false) {
|
|
1986
|
+
let deadline = Date.now() + timeoutMs;
|
|
1552
1987
|
// A run brought up by a request (a message before the start's recovery reached it) waits for the sweep as well.
|
|
1553
1988
|
await this.sweepOnce();
|
|
1554
1989
|
await this.pinNeeds(run);
|
|
@@ -1559,12 +1994,18 @@ export class Runs {
|
|
|
1559
1994
|
if (run.preparing === copying)
|
|
1560
1995
|
throw new ApiError("unavailable", "the run's files are still being copied into its workspace", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1561
1996
|
}
|
|
1562
|
-
for
|
|
1563
|
-
|
|
1564
|
-
|
|
1997
|
+
// And for its harness, installed on first use (harness-install.ts): its own time, bounded by the install's, before the
|
|
1998
|
+
// ready time starts. A failed install ended the run, which the loop says.
|
|
1999
|
+
const installing = this.harnessReady(run);
|
|
2000
|
+
if (installing) {
|
|
2001
|
+
await installing;
|
|
2002
|
+
deadline = Date.now() + timeoutMs;
|
|
2003
|
+
}
|
|
2004
|
+
for (let launched = false, refreshed = !refresh;; await sleep(100)) {
|
|
2005
|
+
// Checked first: a settle may have ended the run, and nothing starts a run that ended.
|
|
1565
2006
|
if (run.outcome || run.finishing || run.cancel)
|
|
1566
2007
|
throw this.finished(run);
|
|
1567
|
-
const door = this.doorOf(
|
|
2008
|
+
const door = this.doorOf(run);
|
|
1568
2009
|
if (door)
|
|
1569
2010
|
return door;
|
|
1570
2011
|
if (!this.live(run)) {
|
|
@@ -1573,31 +2014,64 @@ export class Runs {
|
|
|
1573
2014
|
// Within the time left: a settle waiting on a busy store must not hold this caller past its deadline.
|
|
1574
2015
|
await untilDeadline(run.settling, deadline);
|
|
1575
2016
|
if (Date.now() > deadline)
|
|
1576
|
-
throw
|
|
2017
|
+
throw this.notUp(run);
|
|
2018
|
+
continue;
|
|
2019
|
+
}
|
|
2020
|
+
// A launch waiting on its claim has no process yet, and tries again on its own (launch): waited for, within the time
|
|
2021
|
+
// left, never launched a second time nor read as a process that exited.
|
|
2022
|
+
if (run.claimWait) {
|
|
2023
|
+
if (Date.now() > deadline)
|
|
2024
|
+
throw this.notUp(run);
|
|
1577
2025
|
continue;
|
|
1578
2026
|
}
|
|
1579
2027
|
if (launched)
|
|
1580
2028
|
throw new ApiError("internal", `the run's process exited before it served: ${await this.lastLine(run)}`);
|
|
1581
|
-
|
|
1582
|
-
const
|
|
2029
|
+
// A holder another server started that lives on (its door still to come): waited for, never launched over.
|
|
2030
|
+
const holder = this.holder(run);
|
|
2031
|
+
const fresh = holder !== undefined && holder.pid !== process.pid && holderLives(holder);
|
|
1583
2032
|
// A run already going is never refused a place, but one whose harness this host's memory never holds (after a
|
|
1584
2033
|
// restart on a smaller one) is not started: said, never tried.
|
|
1585
2034
|
const never = fresh ? undefined : neverFits(run.harness, this.memory);
|
|
1586
2035
|
if (never)
|
|
1587
2036
|
throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness: run.harness } });
|
|
1588
|
-
//
|
|
2037
|
+
// Only for a launch: its MCP OAuth tokens near expiry refreshed (when this path may: a message's, an approval's
|
|
2038
|
+
// answer, never a stop's) and its sign-in pinned; a run whose process still serves keeps what it was handed. Looked at again
|
|
2039
|
+
// after the waits: they may have let another path launch it.
|
|
1589
2040
|
if (!fresh) {
|
|
2041
|
+
if (!refreshed) {
|
|
2042
|
+
refreshed = true;
|
|
2043
|
+
const refreshing = this.mcpFresh(run);
|
|
2044
|
+
// A wait here lets the rest of the server go on: a recovery may start settling the run (recover's settle of
|
|
2045
|
+
// a process an earlier server left), or another path launch it. Every check above is read again first.
|
|
2046
|
+
if (refreshing) {
|
|
2047
|
+
await refreshing;
|
|
2048
|
+
continue;
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
1590
2051
|
await this.pinSignIn(run);
|
|
1591
|
-
|
|
2052
|
+
// A settle that began during a wait owns the run until it ends: launching under it would start a process the
|
|
2053
|
+
// settle then ends, so it is waited for (the top of the loop), as one under way before the waits is.
|
|
2054
|
+
if (run.outcome || run.finishing || run.cancel || this.live(run) || run.settles > 0)
|
|
1592
2055
|
continue;
|
|
1593
2056
|
this.launch(run);
|
|
1594
2057
|
launched = true;
|
|
1595
2058
|
}
|
|
1596
2059
|
}
|
|
1597
2060
|
if (Date.now() > deadline)
|
|
1598
|
-
throw
|
|
2061
|
+
throw this.notUp(run);
|
|
1599
2062
|
}
|
|
1600
2063
|
}
|
|
2064
|
+
/** A request's 503 for a run that did not come up in time, naming why, as far as this server can tell: the process
|
|
2065
|
+
* listing cannot be read (who holds it is unknown), the agent store is busy (its claim waits on it), or the run never
|
|
2066
|
+
* opened (its process is up, its door not serving). */
|
|
2067
|
+
notUp(run) {
|
|
2068
|
+
const why = run.claimWait
|
|
2069
|
+
? (run.claimWaitWhy ?? "its claim could not be written yet")
|
|
2070
|
+
: this.holderView(run).unknown
|
|
2071
|
+
? "the process listing cannot be read, so who holds it is not known"
|
|
2072
|
+
: "its process has not opened it yet (its door does not serve)";
|
|
2073
|
+
return new ApiError("unavailable", `the run did not come up in time: ${why}`, { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
2074
|
+
}
|
|
1601
2075
|
/** The refusal of a message to an imported run: it was run elsewhere, and is kept as history. */
|
|
1602
2076
|
importedRefusal(run) {
|
|
1603
2077
|
const source = run.imported?.source;
|
|
@@ -1618,7 +2092,7 @@ export class Runs {
|
|
|
1618
2092
|
async abortTurn(run) {
|
|
1619
2093
|
if (run.kind === "workflow")
|
|
1620
2094
|
return;
|
|
1621
|
-
const door = this.doorOf(
|
|
2095
|
+
const door = this.doorOf(run);
|
|
1622
2096
|
if (door)
|
|
1623
2097
|
await fetch(new URL("/abort", door), { method: "POST", headers: this.headers(run, true), body: "{}", signal: AbortSignal.timeout(5_000) }).catch(() => undefined);
|
|
1624
2098
|
}
|
|
@@ -1632,7 +2106,7 @@ export class Runs {
|
|
|
1632
2106
|
for (const deadline = Date.now() + 30_000;; await sleep(200)) {
|
|
1633
2107
|
if (!this.live(run) || run.cancel)
|
|
1634
2108
|
throw new Error("the run's process is gone");
|
|
1635
|
-
const door = this.doorOf(
|
|
2109
|
+
const door = this.doorOf(run);
|
|
1636
2110
|
const res = door ? await fetch(new URL(path, door), { method: body ? "POST" : "GET", headers: this.headers(run, body !== undefined), body: body && JSON.stringify(body), signal: AbortSignal.timeout(15_000) }).catch(() => null) : null;
|
|
1637
2111
|
const data = res ? (await res.json().catch(() => null)) : null;
|
|
1638
2112
|
if (res && res.status < 400)
|
|
@@ -1643,10 +2117,10 @@ export class Runs {
|
|
|
1643
2117
|
throw new Error("the run's door did not answer");
|
|
1644
2118
|
}
|
|
1645
2119
|
}
|
|
1646
|
-
async toDoor(run, path, body, readyMs) {
|
|
2120
|
+
async toDoor(run, path, body, readyMs, refresh = false) {
|
|
1647
2121
|
const deadline = Date.now() + 30_000;
|
|
1648
2122
|
for (;;) {
|
|
1649
|
-
const door = await this.ensureLive(run, readyMs);
|
|
2123
|
+
const door = await this.ensureLive(run, readyMs, refresh);
|
|
1650
2124
|
const res = await fetch(new URL(path, door), {
|
|
1651
2125
|
method: body === undefined ? "GET" : "POST",
|
|
1652
2126
|
headers: this.headers(run, body !== undefined),
|
|
@@ -1669,6 +2143,52 @@ export class Runs {
|
|
|
1669
2143
|
const revision = given ?? (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
1670
2144
|
this.needs.set(run.revision, await needsOf(revision));
|
|
1671
2145
|
}
|
|
2146
|
+
/** Just before a launch that spawns the run's process (after pinNeeds): its MCP servers' OAuth tokens near expiry are
|
|
2147
|
+
* refreshed in serve (mcp-servers.ts headersForRun), so the synchronous launch hands it a fresh access token, never a
|
|
2148
|
+
* refresh token. Never on a path that only reaches a live process, nor on a stop's: an authorization server that is
|
|
2149
|
+
* slow to answer never holds an abort. */
|
|
2150
|
+
mcpFresh(run) {
|
|
2151
|
+
const source = this.options.mcpServers;
|
|
2152
|
+
if (!source?.refresh)
|
|
2153
|
+
return undefined;
|
|
2154
|
+
// The servers its pin names, or, before its first launch makes the pin (which may refuse the launch in words, there
|
|
2155
|
+
// alone), the ones its granted tools name: read only, never pinned here.
|
|
2156
|
+
const file = join(run.dir, MCP_PIN);
|
|
2157
|
+
let names = [];
|
|
2158
|
+
try {
|
|
2159
|
+
names = existsSync(file) ? Object.keys(JSON.parse(readFileSync(file, "utf8"))) : [...new Set((this.needs.get(run.revision)?.tools ?? []).flatMap((tool) => mcpNameOf(tool)?.server ?? []))];
|
|
2160
|
+
}
|
|
2161
|
+
catch {
|
|
2162
|
+
return undefined;
|
|
2163
|
+
}
|
|
2164
|
+
// Nothing to refresh, nothing awaited: a launch path with no OAuth server takes not one tick more than it did.
|
|
2165
|
+
if (!names.length)
|
|
2166
|
+
return undefined;
|
|
2167
|
+
return Promise.all(names.map((name) => source.refresh(name))).then(() => undefined);
|
|
2168
|
+
}
|
|
2169
|
+
/** `run`'s pinned MCP tools: read from its directory, or at its first launch made from the granted `tools` and the
|
|
2170
|
+
* servers saved now, and written before its process starts. Undefined when it grants none. */
|
|
2171
|
+
mcpPin(run, tools) {
|
|
2172
|
+
const file = join(run.dir, MCP_PIN);
|
|
2173
|
+
if (existsSync(file)) {
|
|
2174
|
+
const pinned = JSON.parse(readFileSync(file, "utf8"));
|
|
2175
|
+
// A pin made before meta tools were refused (mcp-meta.ts) is checked at each launch, never rewritten: one it holds
|
|
2176
|
+
// refuses the launch, as making the pin does.
|
|
2177
|
+
for (const [server, { url, tools: listed }] of Object.entries(pinned)) {
|
|
2178
|
+
for (const tool of listed)
|
|
2179
|
+
if (metaToolOf(url, tool.name))
|
|
2180
|
+
throw new Error(`mcp:${server}/${tool.name} can't be granted: ${META_REASON}`);
|
|
2181
|
+
}
|
|
2182
|
+
return pinned;
|
|
2183
|
+
}
|
|
2184
|
+
if (!tools?.some((name) => name.startsWith("mcp:")) || !this.options.mcpServers)
|
|
2185
|
+
return undefined;
|
|
2186
|
+
const pin = mcpPinOf(tools, this.options.mcpServers);
|
|
2187
|
+
if (!Object.keys(pin).length)
|
|
2188
|
+
return undefined;
|
|
2189
|
+
writeDurableSync(file, JSON.stringify(pin));
|
|
2190
|
+
return pin;
|
|
2191
|
+
}
|
|
1672
2192
|
/** The saved sign-in the run's browser starts from (sign-ins.ts), resolved before each launch: made at the vendor when
|
|
1673
2193
|
* its agent has none, and leased to this run to save unless another run of the agent holds the lease. One that cannot
|
|
1674
2194
|
* be had (the vendor not answering, a seal key changed) leaves its browser signed out, said in its log. */
|
|
@@ -1676,10 +2196,68 @@ export class Runs {
|
|
|
1676
2196
|
// Its browser as this launch will find it (launch: a vendor whose key is gone since is unavailable, and gets none).
|
|
1677
2197
|
const browser = run.meta.tool_plane && recheckPlane(run.meta.tool_plane, withSecrets(process.env, "all", this.options.storedKeys)).browser;
|
|
1678
2198
|
const signIns = this.options.signIns;
|
|
1679
|
-
run.signIn = browser && signIns ? ((await signIns.forRun(run.agentId, run.id, browser).catch((error) => void warn(run.id, `its browser starts signed out: ${error.message}`))) ?? undefined) : undefined;
|
|
2199
|
+
run.signIn = browser && signIns ? ((await signIns.forRun(run.agentId, run.id, browser, (handed) => this.keepHanded(run, handed)).catch((error) => void warn(run.id, `its browser starts signed out: ${error.message}`))) ?? undefined) : undefined;
|
|
2200
|
+
}
|
|
2201
|
+
/** That `run` is handed `signIn`, kept before it is (forRun's keep, under its agent's sign-ins lock, so no forget comes
|
|
2202
|
+
* between): false when that can't be saved, and the run is handed none. */
|
|
2203
|
+
async keepHanded(run, signIn) {
|
|
1680
2204
|
// Never shown in its errors, from now on: a server started since its launch has handed it nothing yet.
|
|
1681
|
-
if (
|
|
1682
|
-
(run.handed ??= new Set()).add(
|
|
2205
|
+
if (signIn.ref.length >= MIN_SECRET)
|
|
2206
|
+
(run.handed ??= new Set()).add(signIn.ref);
|
|
2207
|
+
// Kept, as its hash alone beside those of any it was handed before: a later server that cannot read the sign-in knows
|
|
2208
|
+
// this run's text could hold it, and which; and forget waits for the run (handedTo). Not kept, the run is handed none
|
|
2209
|
+
// (it starts signed out): a run whose text could hold the pointer is always one a server knows.
|
|
2210
|
+
const before = run.meta.sign_in_handed;
|
|
2211
|
+
const hash = pointerHash(signIn.ref);
|
|
2212
|
+
const now = before === undefined ? [hash] : before === MALFORMED || before.includes(hash) ? before : [...before, hash];
|
|
2213
|
+
if (now === before)
|
|
2214
|
+
return true;
|
|
2215
|
+
run.meta.sign_in_handed = now;
|
|
2216
|
+
return this.saveMeta(run).then(() => true, (error) => {
|
|
2217
|
+
if (before === undefined)
|
|
2218
|
+
delete run.meta.sign_in_handed;
|
|
2219
|
+
else
|
|
2220
|
+
run.meta.sign_in_handed = before;
|
|
2221
|
+
warn(run.id, `its browser starts signed out: that it was handed a sign-in could not be saved (${error.message})`);
|
|
2222
|
+
return false;
|
|
2223
|
+
});
|
|
2224
|
+
}
|
|
2225
|
+
/** The run of `agentId` still going (its row running) that was handed the sign-in whose pointer hashes to `hash`, or
|
|
2226
|
+
* any sign-in when `hash` is undefined (a pointer that does not open here): forget waits for it (sign-ins.ts). From the
|
|
2227
|
+
* run this server holds, else its serve.json: a run still going need not be held yet (a recovery under way, or one it
|
|
2228
|
+
* could not recover). One whose mark is MALFORMED, or whose serve.json is damaged (run.damaged for a held run, the same
|
|
2229
|
+
* answer the disk read gives), counts: what it was handed is not known. */
|
|
2230
|
+
async handedTo(agentId, hash) {
|
|
2231
|
+
for (const row of await this.options.agents.request(() => this.store.listRuns({ agent: agentId }))) {
|
|
2232
|
+
if (row.state !== "running")
|
|
2233
|
+
continue;
|
|
2234
|
+
const held = this.runs.get(row.id);
|
|
2235
|
+
const handed = held ? (held.damaged ? MALFORMED : held.meta.sign_in_handed) : await handedOnDisk(join(runDirIn(this.options.agents.dir, row.agent, row.id), RUN_META));
|
|
2236
|
+
if (handed !== undefined && (handed === MALFORMED || hash === undefined || handed.includes(hash)))
|
|
2237
|
+
return row.id;
|
|
2238
|
+
}
|
|
2239
|
+
return undefined;
|
|
2240
|
+
}
|
|
2241
|
+
/** The pointer of the sign-in a run this server loads was handed, among the values its rows, errors and answers never
|
|
2242
|
+
* show: read only, with no lease taken (pinSignIn takes one at its next launch). `unreadable` when its agent keeps
|
|
2243
|
+
* one that does not open under this server's seal key. */
|
|
2244
|
+
async peekSignIn(run) {
|
|
2245
|
+
// Its plane's vendor as a launch reads it (keptVendor: a missing-key refusal an earlier server saved is that vendor).
|
|
2246
|
+
const browser = run.meta.tool_plane && keptVendor(run.meta.tool_plane).browser;
|
|
2247
|
+
const peeked = browser ? await this.options.signIns?.peek(run.agentId, browser).catch(() => "unreadable") : undefined;
|
|
2248
|
+
// The agent's live pointer, which a launch of it may hand it next.
|
|
2249
|
+
if (typeof peeked === "object" && peeked.ref.length >= MIN_SECRET)
|
|
2250
|
+
(run.handed ??= new Set()).add(peeked.ref);
|
|
2251
|
+
// What it was handed, forgotten since or not (sign-ins.ts Forgotten): a sign-in forgotten after the run ended, or
|
|
2252
|
+
// replaced since, is still cut from what it said. A run with no mark was never handed one. `unreadable` when what it
|
|
2253
|
+
// was handed can't be read back here (handedPointers), and the run is hidden (load).
|
|
2254
|
+
const pointers = await this.handedPointers(run.agentId, browser, run.meta.sign_in_handed);
|
|
2255
|
+
if (pointers === "unreadable")
|
|
2256
|
+
return pointers;
|
|
2257
|
+
for (const ref of pointers.refs)
|
|
2258
|
+
if (ref.length >= MIN_SECRET)
|
|
2259
|
+
(run.handed ??= new Set()).add(ref);
|
|
2260
|
+
return "read";
|
|
1683
2261
|
}
|
|
1684
2262
|
/** Lets go of the save lease the run holds on its agent's sign-in, if any: at once when its process let its sessions go
|
|
1685
2263
|
* (`clean`), else by the gone rule (sign-ins.ts). */
|
|
@@ -1688,8 +2266,29 @@ export class Runs {
|
|
|
1688
2266
|
await this.options.signIns?.release(run.agentId, run.id, run.dir, clean).catch((error) => warn(run.id, `its sign-in's save lease is not let go: ${error.message}`));
|
|
1689
2267
|
}
|
|
1690
2268
|
launch(run, followUp = run.followUpOpen === true) {
|
|
1691
|
-
|
|
2269
|
+
// A launch that waited on its claim lets go of the place it kept (takePlace) as it tries again: from here it is a live
|
|
2270
|
+
// run again, or not one at all.
|
|
2271
|
+
run.claimWait = undefined;
|
|
2272
|
+
run.claimWaitWhy = undefined;
|
|
2273
|
+
run.notOpened = undefined;
|
|
2274
|
+
if (run.child || this.closing || run.cancel || run.outcome || run.finishing || run.preparing || run.installing)
|
|
1692
2275
|
return;
|
|
2276
|
+
// Every launch of a run whose harness installs on first use (its start, a recovery after a restart, a relaunch, a
|
|
2277
|
+
// wake) waits for that install to be whole first (harnessReady), holding its place meanwhile (waitsInstall), and
|
|
2278
|
+
// launches once it is: never a process that would load a missing CLI.
|
|
2279
|
+
const installing = this.harnessReady(run);
|
|
2280
|
+
// After the install, its MCP OAuth tokens are refreshed again: the wait (up to the install's bound) may have outlived
|
|
2281
|
+
// what the refresh before it gave (mcpFresh); launch() reads every check again.
|
|
2282
|
+
if (installing)
|
|
2283
|
+
return void installing.then(async (installed) => {
|
|
2284
|
+
if (!installed)
|
|
2285
|
+
return;
|
|
2286
|
+
const refreshing = this.mcpFresh(run);
|
|
2287
|
+
if (refreshing)
|
|
2288
|
+
await refreshing;
|
|
2289
|
+
this.launch(run, followUp);
|
|
2290
|
+
});
|
|
2291
|
+
run.waitsInstall = undefined;
|
|
1693
2292
|
// Taken by this launch only: a later launch (a relaunch after its process went) opens the run as any other.
|
|
1694
2293
|
run.followUpOpen = undefined;
|
|
1695
2294
|
// Its secrets go over fd 3, written whole and closed as it starts; it reads them first (secrets.ts). Each launch path
|
|
@@ -1700,10 +2299,24 @@ export class Runs {
|
|
|
1700
2299
|
const served = withSecrets(process.env, "all", this.options.storedKeys);
|
|
1701
2300
|
const needs = this.needs.get(run.revision);
|
|
1702
2301
|
const handed = needs ? keysFor(needs, served) : NO_TOOL_KEYS;
|
|
2302
|
+
// Its MCP servers: the tools it grants, pinned at its first launch in its directory (mcp-gateway.ts), and the
|
|
2303
|
+
// credentials of those servers alone, read now, on the same pipe.
|
|
2304
|
+
let pin;
|
|
2305
|
+
try {
|
|
2306
|
+
pin = this.mcpPin(run, needs?.tools);
|
|
2307
|
+
}
|
|
2308
|
+
catch (error) {
|
|
2309
|
+
// A granted tool that cannot be pinned refuses the launch in words, rather than a run without the tool.
|
|
2310
|
+
run.error = { code: "run_failed", message: error.message, retryable: false };
|
|
2311
|
+
run.finishing = "failed";
|
|
2312
|
+
void this.settle(run, 1, true);
|
|
2313
|
+
return;
|
|
2314
|
+
}
|
|
2315
|
+
const mcp = pin && this.options.mcpServers ? mcpCredentialsOf(pin, this.options.mcpServers) : undefined;
|
|
1703
2316
|
// And its saved sign-in, on the same pipe after them (pinSignIn): a pointer its browser opens, never in its environment.
|
|
1704
|
-
const secrets =
|
|
2317
|
+
const secrets = Buffer.concat([handover(handed, this.options.storedKeys), ...(mcp ? [mcpHandover(mcp)] : []), ...(run.signIn ? [handoverSignIn(run.signIn)] : [])]);
|
|
1705
2318
|
// What it was handed, for the check of what its end-of-run turn writes (learning-run.ts).
|
|
1706
|
-
this.learning.onLaunch(run, handed);
|
|
2319
|
+
this.learning.onLaunch(run, handed, mcpSecretValues(mcp ?? {}));
|
|
1707
2320
|
// And for what its errors show (refusedValues): each value handed, kept past a key's rotation.
|
|
1708
2321
|
run.handed ??= new Set();
|
|
1709
2322
|
for (const name of handed) {
|
|
@@ -1711,14 +2324,26 @@ export class Runs {
|
|
|
1711
2324
|
if (value && value.length >= MIN_SECRET)
|
|
1712
2325
|
run.handed.add(value);
|
|
1713
2326
|
}
|
|
2327
|
+
for (const value of mcpSecretValues(mcp ?? {}))
|
|
2328
|
+
if (value.length >= MIN_SECRET)
|
|
2329
|
+
run.handed.add(value);
|
|
1714
2330
|
if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
|
|
1715
2331
|
run.handed.add(run.signIn.ref);
|
|
1716
2332
|
const env = {
|
|
1717
2333
|
...childEnv(process.env, this.options.token),
|
|
1718
2334
|
// The run's box's network, as the server resolved it: never the setting itself, which the run's process ignores.
|
|
1719
2335
|
[RUN_BOX_ALLOW_ENV]: this.options.dockerAllow === undefined || this.options.dockerAllow === "none" ? "none" : this.options.dockerAllow.join(","),
|
|
2336
|
+
// And, for a server in a container, where its Docker has the data directory: set always, empty on a host, so a stale
|
|
2337
|
+
// value in the server's own environment never reaches a run.
|
|
2338
|
+
[RUN_BOX_PATHS_ENV]: this.options.dockerPaths ? JSON.stringify(this.options.dockerPaths) : "",
|
|
2339
|
+
// And, on a Mac, its proxy's volume: set always, empty for none, so a stale value in the server's own environment
|
|
2340
|
+
// never reaches a run.
|
|
2341
|
+
[RUN_BOX_VOLUME_ENV]: this.options.dockerVolume ?? "",
|
|
1720
2342
|
[SECRETS_FD_ENV]: "3",
|
|
1721
2343
|
[SECRETS_LEN_ENV]: String(secrets.length),
|
|
2344
|
+
// The server's data (dataOfRun: a run's directory is on its agent's disk under it): claude-agent loads Claude Code
|
|
2345
|
+
// from its harnesses.
|
|
2346
|
+
[DATA_ENV]: dataOfRun(run.dir),
|
|
1722
2347
|
...this.fauxEnv(),
|
|
1723
2348
|
...(run.meta.effort ? { [EFFORT_ENV]: run.meta.effort } : {}),
|
|
1724
2349
|
...(this.options.documents ? { [DOCUMENTS_ENV]: this.options.documents } : {}),
|
|
@@ -1727,17 +2352,21 @@ export class Runs {
|
|
|
1727
2352
|
run.meta.launch_thinking = { ...(env[EFFORT_ENV] ? { effort: env[EFFORT_ENV] } : {}), ...(env.AGENT_THINKING ? { host: env.AGENT_THINKING } : {}) };
|
|
1728
2353
|
void this.saveMeta(run).catch((error) => warn(run.id, `what its process thinks at is not saved: ${error.message}`));
|
|
1729
2354
|
delete env[CAP_ENV];
|
|
2355
|
+
delete env[CAP_MODE_ENV];
|
|
1730
2356
|
if (run.meta.max_cost_usd !== undefined)
|
|
1731
2357
|
env[CAP_ENV] = String(run.meta.max_cost_usd);
|
|
2358
|
+
if (run.meta.max_cost_usd !== undefined && run.meta.cap_mode !== undefined)
|
|
2359
|
+
env[CAP_MODE_ENV] = run.meta.cap_mode;
|
|
1732
2360
|
// A run on the host's default (its revision names no model) gets the model the server picks for its harness, never
|
|
1733
2361
|
// the key that gave it: behind a gateway its process holds the gateway's key alone (keysFor) and could not tell. It is
|
|
1734
2362
|
// the run's last choice (model.ts hostModel: the tier's variable, then AGENT_MODEL where the harness runs it, then a
|
|
1735
2363
|
// key the run holds, then this), so a host's setting the harness can run still wins; and one it cannot (AGENT_MODEL
|
|
1736
2364
|
// on Anthropic's model, for codex) no longer leaves the run with none. pi and codex choose through the gateway
|
|
1737
|
-
// (chooseModel); claude-agent never does, and holds the key
|
|
2365
|
+
// (chooseModel); a harness whose model is its own (its facts' ownModel: claude-agent) never does, and holds the key
|
|
2366
|
+
// its route sends, which gives its default.
|
|
1738
2367
|
delete env[DEFAULT_MODEL_ENV];
|
|
1739
|
-
const harness = run.
|
|
1740
|
-
const defaultModel = run.tooling && !run.tooling.model && harness
|
|
2368
|
+
const harness = run.harness;
|
|
2369
|
+
const defaultModel = run.tooling && !run.tooling.model && !builtinHarness(harness)?.facts?.ownModel ? hostModel(served, "default", harness) : undefined;
|
|
1741
2370
|
if (defaultModel)
|
|
1742
2371
|
env[DEFAULT_MODEL_ENV] = defaultModel;
|
|
1743
2372
|
// Opened for a person's follow-up to a run whose turn had ended: nothing it resumes was cut (app.ts markResumed).
|
|
@@ -1782,15 +2411,70 @@ export class Runs {
|
|
|
1782
2411
|
const providers = needs?.decisionProviders;
|
|
1783
2412
|
const decisionKeys = providers ? decisionKeysFor(served, { providers, parallelWeb: handsParallel(plane) }) : {};
|
|
1784
2413
|
const handsKey = Object.keys(decisionKeys).length > 0;
|
|
2414
|
+
// The run's claim, for its process: from the epoch its row holds, bumped with the holder named, in one statement (a
|
|
2415
|
+
// claim that moved meanwhile is stale, and this launch writes nothing). A holder the row names that still lives (a
|
|
2416
|
+
// process an earlier server left that serves no door) is killed first, and the claim waits until it is gone: no
|
|
2417
|
+
// process of a lower epoch runs, or commits to the run's store, once the epoch is bumped. A claim that cannot be
|
|
2418
|
+
// written (the agent store held, or not writable) launches nothing now, and is tried again, the launch whole, soon at
|
|
2419
|
+
// first (CLAIM_RETRY_MS) and then every settle retry, until it is written: a run never stays without a process for
|
|
2420
|
+
// want of one.
|
|
2421
|
+
let epoch;
|
|
2422
|
+
const nonce = randomBytes(32).toString("hex");
|
|
2423
|
+
try {
|
|
2424
|
+
const claim = this.store.runClaim(run.id);
|
|
2425
|
+
const held = holderOfClaim(run.id, claim);
|
|
2426
|
+
if (held && killHolder(held))
|
|
2427
|
+
throw new Error(`its holder ${held.pid} still lived; it is killed first`);
|
|
2428
|
+
epoch = this.store.claimRun(run.id, LAUNCH_HOLDER, claim.epoch);
|
|
2429
|
+
env[RUN_EPOCH_ENV] = String(epoch);
|
|
2430
|
+
// Its mark: should the row still name the launch when this server goes, the next one finds the process by it.
|
|
2431
|
+
env[RUN_LAUNCH_ENV] = `${run.id}:${epoch}`;
|
|
2432
|
+
run.claimTries = undefined;
|
|
2433
|
+
}
|
|
2434
|
+
catch (error) {
|
|
2435
|
+
// Soon at first (a store another writer holds for a moment), then every settle retry.
|
|
2436
|
+
const tries = run.claimTries ?? 0;
|
|
2437
|
+
run.claimTries = tries + 1;
|
|
2438
|
+
const every = CLAIM_RETRY_MS[tries] ?? this.options.settleRetryMs ?? SETTLE_RETRY_MS;
|
|
2439
|
+
// What this launch took goes back, so the next one launches as this one would have.
|
|
2440
|
+
if (followUp)
|
|
2441
|
+
run.followUpOpen = true;
|
|
2442
|
+
if (first)
|
|
2443
|
+
run.firstLaunch = true;
|
|
2444
|
+
run.claimWait = true;
|
|
2445
|
+
run.claimWaitWhy = storeBusy(error) ? "the agent store is busy (another writer holds it)" : /cannot be (checked|looked for)/.test(error.message) ? "the process listing cannot be read, so its holder cannot be checked" : error.message;
|
|
2446
|
+
warn(run.id, `its process is not started: its claim was not written (${error.message}); trying again in ${every / 1000} s`);
|
|
2447
|
+
setTimeout(async () => {
|
|
2448
|
+
if (this.closing)
|
|
2449
|
+
return;
|
|
2450
|
+
// Refreshed again before the retry, as after any wait (mcpFresh); launch() reads every check again.
|
|
2451
|
+
const refreshing = this.mcpFresh(run);
|
|
2452
|
+
if (refreshing)
|
|
2453
|
+
await refreshing.catch(() => undefined);
|
|
2454
|
+
if (this.closing)
|
|
2455
|
+
return;
|
|
2456
|
+
try {
|
|
2457
|
+
this.launch(run);
|
|
2458
|
+
}
|
|
2459
|
+
catch (error) {
|
|
2460
|
+
warn(run.id, `its process is not started: ${error.message}`);
|
|
2461
|
+
}
|
|
2462
|
+
}, every).unref();
|
|
2463
|
+
return;
|
|
2464
|
+
}
|
|
1785
2465
|
this.markLaunching(run);
|
|
1786
2466
|
const log = openSync(join(run.dir, PROCESS_LOG), "a", 0o600);
|
|
1787
|
-
const stdio = ["ignore", "
|
|
2467
|
+
const stdio = ["ignore", "pipe", log, "pipe"];
|
|
1788
2468
|
// The first descriptor after the others: macOS aborts the parent of a spawn with a pipe at 16 or above.
|
|
1789
2469
|
const keyFd = stdio.length;
|
|
1790
2470
|
if (handsKey) {
|
|
1791
2471
|
stdio.push("pipe");
|
|
1792
2472
|
env[DECISION_KEY_FD_ENV] = String(keyFd);
|
|
1793
2473
|
}
|
|
2474
|
+
// This launch's door nonce, on a pipe of its own, never in an environment (which stays readable by the user's other
|
|
2475
|
+
// processes): the process reads it first and closes it, and its door proves it (door-line.ts).
|
|
2476
|
+
const nonceFd = stdio.length;
|
|
2477
|
+
stdio.push("pipe");
|
|
1794
2478
|
// A workflow run resumes from its journal when it opens again, so SIGTERM lets it go at once, undrained.
|
|
1795
2479
|
const drain = run.kind === "workflow" ? "0s" : (this.options.drainTimeout ?? DRAIN);
|
|
1796
2480
|
// Its own door token, which its door takes and its calls to the box relay carry: no other run's process holds it.
|
|
@@ -1800,7 +2484,12 @@ export class Runs {
|
|
|
1800
2484
|
// secrets.ts first, as a preload: the pipe is read and closed before pi-durable-disk's CLI loads or starts anything.
|
|
1801
2485
|
"--no-warnings=ExperimentalWarning", "--import", SECRETS_MODULE, this.cli, "run", "--dir", run.dir, "--app", this.app,
|
|
1802
2486
|
"--serve", "0", "--serve-host", "127.0.0.1", "--serve-token-file", doorTokenFile, "--drain-timeout", drain, // key-gate: loopback-rule the door of a run listens on loopback only, for this server
|
|
2487
|
+
"--epoch", String(epoch), "--door-nonce-fd", String(nonceFd),
|
|
1803
2488
|
], { stdio, env });
|
|
2489
|
+
const noncePipe = child.stdio[nonceFd];
|
|
2490
|
+
// A process that dies before it reads the nonce closes the pipe: that is its exit to settle, not an error here.
|
|
2491
|
+
noncePipe?.on("error", () => undefined);
|
|
2492
|
+
noncePipe?.end(this.options.fauxHandedNonce ?? nonce);
|
|
1804
2493
|
closeSync(log);
|
|
1805
2494
|
const pipe = child.stdio[3];
|
|
1806
2495
|
pipe?.on("error", () => { });
|
|
@@ -1812,9 +2501,17 @@ export class Runs {
|
|
|
1812
2501
|
keyPipe?.end(JSON.stringify(decisionKeys));
|
|
1813
2502
|
}
|
|
1814
2503
|
run.child = child;
|
|
2504
|
+
run.door = undefined;
|
|
1815
2505
|
child.once("exit", (code) => {
|
|
1816
|
-
if (run.child === child)
|
|
2506
|
+
if (run.child === child) {
|
|
1817
2507
|
run.child = undefined;
|
|
2508
|
+
run.door = undefined;
|
|
2509
|
+
}
|
|
2510
|
+
// Its live browser view went with it, however it ended (browser-live.ts): a process killed before it let its
|
|
2511
|
+
// sessions go leaves its hand-over behind, naming a port another listener may take.
|
|
2512
|
+
void dropHandover(run.dir).catch(() => undefined);
|
|
2513
|
+
// Its agent's ask, if one waits, stays: the run's next process takes it up (browser-person.ts), and the run ends
|
|
2514
|
+
// with it gone (carryBack).
|
|
1818
2515
|
this.reportedBack(run);
|
|
1819
2516
|
void this.settle(run, code, true);
|
|
1820
2517
|
});
|
|
@@ -1823,8 +2520,99 @@ export class Runs {
|
|
|
1823
2520
|
run.child = undefined;
|
|
1824
2521
|
this.reportedBack(run);
|
|
1825
2522
|
});
|
|
2523
|
+
// Only once the child is wired (its exit and error handled above): the row names the process (its pid, its start and
|
|
2524
|
+
// this boot) under the epoch it was given, and its door once it says, on stdout, where it serves: its one line there
|
|
2525
|
+
// (pi-durable-disk's run under its host's epoch). A process listing that cannot be read names nothing.
|
|
2526
|
+
this.nameHolder(run, epoch, child.pid === undefined ? undefined : withNonce(holderOfProcess(child.pid), nonce));
|
|
2527
|
+
// Its door: the first line it prints, before any harness or agent code of it runs, proven with this launch's nonce
|
|
2528
|
+
// before it is recorded; no later line is read (door-line.ts).
|
|
2529
|
+
if (child.stdout && child.pid !== undefined) {
|
|
2530
|
+
const pid = child.pid;
|
|
2531
|
+
void firstDoorLine(child.stdout, epoch).then(async (door) => {
|
|
2532
|
+
if (door === undefined || !isLoopback(new URL(door).hostname))
|
|
2533
|
+
return warn(run.id, `its process ${pid} named no loopback door first on stdout; none is recorded`);
|
|
2534
|
+
// A door that does not answer this launch's nonce (wrongly, or not within the proof's time) is not this launch's
|
|
2535
|
+
// to record, and its process is not taken for up: as one that misses its open time, it is said once and stopped,
|
|
2536
|
+
// by this server's own handle on its child, and its exit opens the run again (up to MAX_RELAUNCHES), the last
|
|
2537
|
+
// one's failure naming this cause. One that has exited already is its exit's to settle, and so is one that exits
|
|
2538
|
+
// on its own within DOOR_EXIT_WAIT_MS: an app that fails at its start closes its door, failing the proof, before its
|
|
2539
|
+
// exit is seen here, and that exit fails the run with its own error, never as a process that did not open it.
|
|
2540
|
+
if (!(await verifyDoor(door, nonce, this.headers(run)))) {
|
|
2541
|
+
if (run.child === child && child.exitCode === null && child.signalCode === null)
|
|
2542
|
+
await once(child, "exit", { signal: AbortSignal.timeout(DOOR_EXIT_WAIT_MS) }).catch(() => undefined);
|
|
2543
|
+
if (run.child !== child || child.exitCode !== null || child.signalCode !== null)
|
|
2544
|
+
return;
|
|
2545
|
+
run.notOpened = "its process's door did not answer this launch's nonce";
|
|
2546
|
+
warn(run.id, `its process ${pid}'s door did not answer this launch's nonce; it is stopped`);
|
|
2547
|
+
this.reportedBack(run);
|
|
2548
|
+
child.kill("SIGKILL");
|
|
2549
|
+
return;
|
|
2550
|
+
}
|
|
2551
|
+
// Recorded once its run serves: a door listens before its run opens, and the run is up only then. One that never
|
|
2552
|
+
// serves within the ready time is said once, by its cause, and stopped: its exit settles the run, which opens it
|
|
2553
|
+
// again (up to MAX_RELAUNCHES) as for any process that went before the run ended.
|
|
2554
|
+
const readyMs = this.options.openTimeoutMs ?? READY_TIMEOUT_MS;
|
|
2555
|
+
const opened = await untilOpened(door, this.headers(run), () => run.child !== child, Date.now() + readyMs);
|
|
2556
|
+
if (!opened.opened) {
|
|
2557
|
+
if (opened.why === "deadline" && run.child === child) {
|
|
2558
|
+
run.notOpened = `its process did not open the run within ${readyMs / 1000} s (its door last answered ${opened.last})`;
|
|
2559
|
+
warn(run.id, `its process ${pid} did not open the run within ${readyMs / 1000} s (its door last answered ${opened.last}); it is stopped`);
|
|
2560
|
+
// Its launch came through (the server is up): its stop is no launch that took the server down.
|
|
2561
|
+
this.reportedBack(run);
|
|
2562
|
+
child.kill("SIGKILL");
|
|
2563
|
+
}
|
|
2564
|
+
return;
|
|
2565
|
+
}
|
|
2566
|
+
if (run.child === child)
|
|
2567
|
+
run.door = door;
|
|
2568
|
+
const holder = holderOfProcess(pid);
|
|
2569
|
+
if (holder)
|
|
2570
|
+
this.nameHolder(run, epoch, { ...holder, nonce, door });
|
|
2571
|
+
}).catch((error) => warn(run.id, `its door is not recorded: ${error.message}`));
|
|
2572
|
+
}
|
|
1826
2573
|
this.connect(run);
|
|
1827
2574
|
}
|
|
2575
|
+
/** Names `holder` on the run's row under `epoch`, the claim its launch made: a claim that moved on since (a take-back,
|
|
2576
|
+
* a later launch) is left as it is, and a store that is busy is tried again shortly, a few times. */
|
|
2577
|
+
nameHolder(run, epoch, holder) {
|
|
2578
|
+
if (holder === undefined)
|
|
2579
|
+
return;
|
|
2580
|
+
const pending = run.naming;
|
|
2581
|
+
run.naming = { epoch, holder, tries: 0 };
|
|
2582
|
+
// One write at a time per run, of the newest holder: a retry under way takes this one.
|
|
2583
|
+
if (pending === undefined)
|
|
2584
|
+
this.writeHolder(run);
|
|
2585
|
+
}
|
|
2586
|
+
/** Writes the run's newest holder to name (`naming`); a store another writer holds is tried again, soon at first, then
|
|
2587
|
+
* every settle retry, while the process lives and the server runs. */
|
|
2588
|
+
writeHolder(run) {
|
|
2589
|
+
const naming = run.naming;
|
|
2590
|
+
if (naming === undefined)
|
|
2591
|
+
return;
|
|
2592
|
+
if (this.closed || !holderLives(naming.holder))
|
|
2593
|
+
return void (run.naming = undefined);
|
|
2594
|
+
try {
|
|
2595
|
+
this.store.setRunHolder(run.id, naming.epoch, JSON.stringify(naming.holder));
|
|
2596
|
+
}
|
|
2597
|
+
catch (error) {
|
|
2598
|
+
if (storeBusy(error)) {
|
|
2599
|
+
const every = CLAIM_RETRY_MS[naming.tries] ?? this.options.settleRetryMs ?? SETTLE_RETRY_MS;
|
|
2600
|
+
naming.tries++;
|
|
2601
|
+
setTimeout(() => {
|
|
2602
|
+
try {
|
|
2603
|
+
this.writeHolder(run);
|
|
2604
|
+
}
|
|
2605
|
+
catch (error) {
|
|
2606
|
+
warn(run.id, `its holder is not named on its row: ${error.message}`);
|
|
2607
|
+
}
|
|
2608
|
+
}, every).unref();
|
|
2609
|
+
return;
|
|
2610
|
+
}
|
|
2611
|
+
if (!(error instanceof AgentHomeError && error.code === "stale"))
|
|
2612
|
+
warn(run.id, `its holder is not named on its row: ${error.message}`);
|
|
2613
|
+
}
|
|
2614
|
+
run.naming = undefined;
|
|
2615
|
+
}
|
|
1828
2616
|
/** Writes the run's launch mark before its process is spawned: a spawn that takes the server down leaves it, and the
|
|
1829
2617
|
* next start fails the run rather than launch it again and go down with it. The file exists once the call returns,
|
|
1830
2618
|
* which a server's death does not undo; no fsync, which would hold the event loop on the disk at every launch. */
|
|
@@ -1858,7 +2646,7 @@ export class Runs {
|
|
|
1858
2646
|
run.submitted = 1;
|
|
1859
2647
|
this.refresh(run);
|
|
1860
2648
|
// As it was first sent: the run never took it, so its work/inputs/ is as its start left it.
|
|
1861
|
-
void firstMessage(first, join(run.dir, "work")).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS)).catch((error) => warn(run.id, `its first message did not land again: ${error.message}`));
|
|
2649
|
+
void firstMessage(first, join(run.dir, "work")).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS, originOf(run.meta.input_origin))).catch((error) => warn(run.id, `its first message did not land again: ${error.message}`));
|
|
1862
2650
|
}
|
|
1863
2651
|
/** After the run's process exited, or was found gone: its rows from its released store, then, when it is over, its
|
|
1864
2652
|
* carry back. One at a time per run, and none once the run has its outcome. */
|
|
@@ -1869,7 +2657,7 @@ export class Runs {
|
|
|
1869
2657
|
run.settling = (run.settling ?? Promise.resolve())
|
|
1870
2658
|
.then(() => (run.outcome ? undefined : this.settleOnce(run, code, exited)))
|
|
1871
2659
|
.catch((error) => {
|
|
1872
|
-
if (!(storeBusy(error) || error instanceof PullPending) || this.closing)
|
|
2660
|
+
if (!(storeBusy(error) || error instanceof PullPending || error instanceof HolderUnknown) || this.closing)
|
|
1873
2661
|
return warn(run.id, `not settled: ${error.message}; the next start tries again`);
|
|
1874
2662
|
// A store still held past the run end's retries: settled again later, not left until the next start.
|
|
1875
2663
|
const every = this.options.settleRetryMs ?? SETTLE_RETRY_MS;
|
|
@@ -1889,18 +2677,39 @@ export class Runs {
|
|
|
1889
2677
|
run.feed?.abort();
|
|
1890
2678
|
run.feed = undefined;
|
|
1891
2679
|
run.working = false;
|
|
1892
|
-
|
|
2680
|
+
// What the run's process said in its store: a release (its status), and a workflow's end (its detail).
|
|
2681
|
+
const record = await this.runRecord(run);
|
|
1893
2682
|
const released = RELEASED.has(String(record?.status));
|
|
1894
2683
|
run.letGo = released;
|
|
1895
|
-
|
|
1896
|
-
//
|
|
1897
|
-
|
|
2684
|
+
// Gone unless another live process serves it (its row's holder, which has not released it): a holder that lives
|
|
2685
|
+
// but serves no door, or lives on after its release, is taken back, which kills it first (the disk's revoke).
|
|
2686
|
+
// This server's own process exited: nothing else holds the run. Any other settle asks the row, and a holder that
|
|
2687
|
+
// cannot be told (its row or the process listing unreadable) is never taken for gone: the settle is tried again.
|
|
2688
|
+
let door;
|
|
2689
|
+
if (!exited && !this.live(run)) {
|
|
2690
|
+
const view = this.holderView(run);
|
|
2691
|
+
if (view.unknown)
|
|
2692
|
+
throw new HolderUnknown("who holds it cannot be told now (its row or the process listing cannot be read)");
|
|
2693
|
+
const other = view.holder !== undefined && view.holder.pid !== process.pid && holderState(view.holder) === "alive" ? view.holder : undefined;
|
|
2694
|
+
// A live holder that has not let go and serves no door yet (a launch an earlier server left opening): watched, as
|
|
2695
|
+
// at a start, until it serves, goes, or is taken over past the ready time.
|
|
2696
|
+
if (other && !released && !run.orphan && !this.doorOf(run)) {
|
|
2697
|
+
this.adoptProcess(run, other, !run.meta.unshown);
|
|
2698
|
+
return;
|
|
2699
|
+
}
|
|
2700
|
+
door = !released && other ? this.doorOf(run) : undefined;
|
|
2701
|
+
}
|
|
2702
|
+
const gone = !this.live(run) && !door;
|
|
1898
2703
|
// Its sign-in's save lease stays with it (below), but no longer than a session it opened could outlive its process.
|
|
1899
2704
|
if (gone)
|
|
1900
2705
|
await this.options.signIns?.markGone(run.agentId, run.id).catch((error) => warn(run.id, `its sign-in's lease is not marked: ${error.message}`));
|
|
1901
2706
|
// Its metrics are this settle's read, or none: never an earlier end's.
|
|
1902
2707
|
run.metrics = undefined;
|
|
1903
|
-
|
|
2708
|
+
// Its process gone: the server takes the run back, its database checkpointed, before it reads it. A hidden run's
|
|
2709
|
+
// store is never read.
|
|
2710
|
+
if (gone)
|
|
2711
|
+
await this.takeBack(run);
|
|
2712
|
+
if ((released || gone) && !run.meta.unshown)
|
|
1904
2713
|
await this.storeWhenFree(run, true);
|
|
1905
2714
|
// Its process gone: an archived run's box is let go now, whatever comes next (an outcome, a wait for the person, a
|
|
1906
2715
|
// relaunch), since nothing else would until the next start or archive. This is every archived end that can let a box
|
|
@@ -1912,6 +2721,9 @@ export class Runs {
|
|
|
1912
2721
|
let ended;
|
|
1913
2722
|
// A workflow run carries back how its workflow ended, through workflowCarry; cancelled before that, it stopped.
|
|
1914
2723
|
// A cancel during the end-of-run turn ends the run's learning, never its job: the run keeps the outcome it had.
|
|
2724
|
+
// Even when another live holder still serves the run (!gone: its stop not through yet, kept pending), a cancel ends it
|
|
2725
|
+
// here: workflowEnd only reads the run's store lock-free and carries the end back, so it neither waits on nor writes
|
|
2726
|
+
// that holder's store, and the holder's exit later finds the run ended.
|
|
1915
2727
|
if (run.cancel && !reflecting(run))
|
|
1916
2728
|
ended = run.kind === "workflow" ? await this.workflowEnd(run, workflowEnding(record) ?? { status: "stopped" }) : { outcome: "cancelled" };
|
|
1917
2729
|
else if (run.finishing)
|
|
@@ -1933,7 +2745,7 @@ export class Runs {
|
|
|
1933
2745
|
run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await this.lastLine(run)}`, retryable: false };
|
|
1934
2746
|
ended = { outcome: "failed" };
|
|
1935
2747
|
}
|
|
1936
|
-
else if (!gone &&
|
|
2748
|
+
else if (!gone && door)
|
|
1937
2749
|
ended = undefined;
|
|
1938
2750
|
else if (run.kind === "workflow")
|
|
1939
2751
|
ended = await this.workflowEnd(run, workflowEnding(record));
|
|
@@ -1944,8 +2756,17 @@ export class Runs {
|
|
|
1944
2756
|
ended = end && { outcome: end.outcome };
|
|
1945
2757
|
}
|
|
1946
2758
|
if (!ended) {
|
|
1947
|
-
// Work left and no process: opened again. A run that waits for the person waits without one, until a message
|
|
1948
|
-
|
|
2759
|
+
// Work left and no process: opened again. A run that waits for the person waits without one, until a message; but
|
|
2760
|
+
// one whose agent waits on its ask for the person in its browser is mid-turn (the tool call waits inside it), and its
|
|
2761
|
+
// next process takes the wait up: it reads the owner's answer, or writes the ask's expiry (browser-person.ts).
|
|
2762
|
+
// A raised run whose follow-up is still to go let its process go as a paused one does: its sign-in's lease goes too.
|
|
2763
|
+
if (gone)
|
|
2764
|
+
await runsTestHooks.beforeRestartCheck?.(run.dir);
|
|
2765
|
+
// A workflow run paused at its cap that let its process go waits for a raise, which opens it again (raiseCap).
|
|
2766
|
+
// One whose raise serve.json kept and a crash cut short: finished now (finishRaise opens it again), never left waiting.
|
|
2767
|
+
if (run.kind === "workflow" && gone && budgetWaiting(run) && (await this.finishRaise(run, { settling: true })))
|
|
2768
|
+
return this.refresh(run);
|
|
2769
|
+
const stalled = run.kind === "workflow" ? !budgetWaiting(run) : (statusOf(run).status !== "input_required" && !raisedToGo(run)) || askWaits(run);
|
|
1949
2770
|
// Its sign-in's save lease stays with it until it ends (carryBack), through a relaunch or a restart: a session it
|
|
1950
2771
|
// opened before its process went may still be live at the vendor, and would write back over another run's. One
|
|
1951
2772
|
// that let go cleanly to wait for its person released its sessions first, so its lease goes now.
|
|
@@ -1961,10 +2782,13 @@ export class Runs {
|
|
|
1961
2782
|
const never = neverFits(run.harness, this.memory);
|
|
1962
2783
|
if (!never && run.relaunches < MAX_RELAUNCHES) {
|
|
1963
2784
|
await this.pinNeeds(run);
|
|
2785
|
+
const refreshing = this.mcpFresh(run);
|
|
2786
|
+
if (refreshing)
|
|
2787
|
+
await refreshing;
|
|
1964
2788
|
await this.pinSignIn(run);
|
|
1965
2789
|
return this.relaunch(run);
|
|
1966
2790
|
}
|
|
1967
|
-
run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${await this.lastLine(run)}`, retryable: false };
|
|
2791
|
+
run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${run.notOpened ?? (await this.lastLine(run))}`, retryable: false };
|
|
1968
2792
|
ended = { outcome: "failed" };
|
|
1969
2793
|
}
|
|
1970
2794
|
await this.carryBack(run, ended.outcome, ended.state, ended.summary);
|
|
@@ -1978,15 +2802,19 @@ export class Runs {
|
|
|
1978
2802
|
// A run's end waits for a busy store as long as its carry back does, not a request's 2 s.
|
|
1979
2803
|
const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
1980
2804
|
const at = { runId: run.id, storePath: this.storeFile(run), revision };
|
|
1981
|
-
|
|
2805
|
+
// Lock-free reads of its store, as every server read of a run's database (run-db.ts): nothing made beside it.
|
|
2806
|
+
const { state, summary } = await workflowCarry(at, ending, { unlocked: true });
|
|
1982
2807
|
if (state === "completed")
|
|
1983
|
-
run.meta.output = (await readWorkflowRun(at)).output ?? null;
|
|
2808
|
+
run.meta.output = (await readWorkflowRun(at, { unlocked: true })).output ?? null;
|
|
1984
2809
|
else if (state === "escalated") {
|
|
1985
|
-
const { escalation, escalatedAt } = await readWorkflowRun(at);
|
|
2810
|
+
const { escalation, escalatedAt } = await readWorkflowRun(at, { unlocked: true });
|
|
1986
2811
|
run.meta.review = { kind: escalation?.kind ?? null, node: escalation?.label ?? escalatedAt?.label ?? null, reason: escalation?.summary ?? summary };
|
|
1987
2812
|
}
|
|
1988
|
-
else if (state === "failed")
|
|
1989
|
-
|
|
2813
|
+
else if (state === "failed") {
|
|
2814
|
+
// Stopped by its cap for good (budget.ts CapStop: a step with no price, a spend no one knows): in the cap's words.
|
|
2815
|
+
const capped = capStoppedIn(run.dir);
|
|
2816
|
+
run.error = capped ? { code: SPEND_CAP_REACHED, message: capped.node ? `${capped.node}: ${capped.words}` : capped.words, retryable: false } : { code: "run_failed", message: `The workflow failed: ${summary}.`, retryable: false };
|
|
2817
|
+
}
|
|
1990
2818
|
await this.readDecisionCost(run);
|
|
1991
2819
|
return { outcome: STATUS_OF[state], state, summary };
|
|
1992
2820
|
}
|
|
@@ -1996,7 +2824,7 @@ export class Runs {
|
|
|
1996
2824
|
const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
|
|
1997
2825
|
// Not its `llm` calls: each completes on the run's marked models, so its cost is a REQUEST_COST entry its usage row
|
|
1998
2826
|
// already sums (request-start.ts).
|
|
1999
|
-
const paid = durableDecisions(this.storeFile(run)).map((row) => row.cost_usd);
|
|
2827
|
+
const paid = durableDecisions(this.storeFile(run), { unlocked: true }).map((row) => row.cost_usd);
|
|
2000
2828
|
if (paid.length)
|
|
2001
2829
|
run.decisionCost = paid.every((cost) => typeof cost === "number") ? paid.reduce((a, b) => a + b, 0) : null;
|
|
2002
2830
|
if (paid.length)
|
|
@@ -2005,6 +2833,11 @@ export class Runs {
|
|
|
2005
2833
|
/** Ends the run in the agent store, once: how it ended, its cost, a line for the list and its metrics. A store held by
|
|
2006
2834
|
* another writer is tried again with backoff; past the last try the run stays unsettled, and the next start carries it back. */
|
|
2007
2835
|
async carryBack(run, outcome, state, summary) {
|
|
2836
|
+
// Its agent's asks for the person in its browser end with it: nobody is left to take them up.
|
|
2837
|
+
if (run.dir)
|
|
2838
|
+
dropAsks(run.dir);
|
|
2839
|
+
// Its reads ended with its end's read (settleOnce): their guard goes. A follow-up's process starts it again from none.
|
|
2840
|
+
this.reads.forget(run.id);
|
|
2008
2841
|
// Ended, it saves to its agent's sign-in no more; but a process that went without letting its sessions go may have
|
|
2009
2842
|
// left one live at the vendor, so its lease then ends by the gone rule. One never launched (letGo unset) has none.
|
|
2010
2843
|
await this.releaseSignIn(run, run.letGo !== false);
|
|
@@ -2013,16 +2846,21 @@ export class Runs {
|
|
|
2013
2846
|
await this.dropBox(run, true);
|
|
2014
2847
|
// Its end-of-run turn closed, and what the turn wrote set aside before the run reads ended (learning-run.ts).
|
|
2015
2848
|
await this.learning.beforeSettle(run, outcome);
|
|
2016
|
-
|
|
2849
|
+
// A run whose rows are not read (meta.unshown) has an unknown cost, never $0.
|
|
2850
|
+
const cost = run.meta.unshown ? null : run.decisionCost === undefined ? costOf(run.rows) : costView(run.rows, undefined, run.decisionCost);
|
|
2017
2851
|
// An unknown cost keeps what it cost so far beside it, for the list row read from the store.
|
|
2018
2852
|
const soFar = cost === null && !run.imported ? soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) : undefined;
|
|
2019
2853
|
if (soFar)
|
|
2020
2854
|
run.meta.cost_so_far = soFar;
|
|
2021
2855
|
else
|
|
2022
2856
|
delete run.meta.cost_so_far;
|
|
2023
|
-
|
|
2857
|
+
// Cut of every value the run's answers and errors never show, as its served answer is (whole, never clipped): the
|
|
2858
|
+
// store keeps it for good, and a view of the run reads it back as its answer.
|
|
2859
|
+
const said = summary ?? (outcome === "completed" ? answerOfRun(run) : outcome === "cancelled" ? "cancelled" : run.error?.message);
|
|
2860
|
+
const line = said ? redactedAnswer(said, this.refusedValues(run)) : said;
|
|
2861
|
+
// Kept cut too, as its line is: a later server that can no longer read the pointer back serves it as kept.
|
|
2024
2862
|
if (run.error)
|
|
2025
|
-
run.meta.error = { code: run.error.code, message: run.error.message, ...(run.error.details ? { details: run.error.details } : {}) };
|
|
2863
|
+
run.meta.error = { code: run.error.code, message: redacted(run.error.message, this.refusedValues(run)), ...(run.error.details ? { details: cutStrings(run.error.details, (text) => redacted(text, this.refusedValues(run))) } : {}) };
|
|
2026
2864
|
// Its end's time, chosen once and given to the store: the row, a retry of the write and its run.ended all name this one
|
|
2027
2865
|
// time. A server that settles the run after a kill chooses its own: nothing was sent before the store had an end.
|
|
2028
2866
|
const endedAt = (run.endedAt ??= new Date().toISOString());
|
|
@@ -2069,6 +2907,8 @@ export class Runs {
|
|
|
2069
2907
|
run.finishing = undefined;
|
|
2070
2908
|
run.settled = true;
|
|
2071
2909
|
run.updatedAt = new Date().toISOString();
|
|
2910
|
+
// Its rows as an ended run's (its usage row says its cost) before its status wakes a reader: see below.
|
|
2911
|
+
this.show(run);
|
|
2072
2912
|
this.refresh(run);
|
|
2073
2913
|
this.persistLater(run, persist);
|
|
2074
2914
|
return;
|
|
@@ -2085,6 +2925,10 @@ export class Runs {
|
|
|
2085
2925
|
run.finishing = undefined;
|
|
2086
2926
|
run.settled = true;
|
|
2087
2927
|
run.updatedAt = new Date().toISOString();
|
|
2928
|
+
// Its rows were last shown while it ran (its end's read), so its usage row said "so far". Shown again as an ended run's
|
|
2929
|
+
// before refresh() marks its status: a reader following with a cursor gets the row's change with the final page,
|
|
2930
|
+
// never a final page over the running wording.
|
|
2931
|
+
this.show(run);
|
|
2088
2932
|
this.refresh(run);
|
|
2089
2933
|
this.notice(run, "run.ended", run.endedAt);
|
|
2090
2934
|
// Only once the run has ended as it would without learning: a slow or failing check never holds the job.
|
|
@@ -2104,11 +2948,14 @@ export class Runs {
|
|
|
2104
2948
|
return counted;
|
|
2105
2949
|
}
|
|
2106
2950
|
const body = revision.kind === "agentic" ? revision.body : undefined;
|
|
2107
|
-
|
|
2108
|
-
|
|
2951
|
+
// The run's harness, as it was resolved when the run was made (blank).
|
|
2952
|
+
const facts = builtinHarness(run.harness)?.facts;
|
|
2953
|
+
// As its process chose it (app.ts): the run's effort, else its revision's thinking, else the host's, else medium; on
|
|
2954
|
+
// an adapter, at the level its harness takes.
|
|
2109
2955
|
const launched = run.meta.launch_thinking;
|
|
2110
|
-
const
|
|
2111
|
-
|
|
2956
|
+
const thinking = launched && thinkingOf({ [EFFORT_ENV]: launched.effort, AGENT_THINKING: launched.host }, body?.thinking);
|
|
2957
|
+
const level = thinking && (facts ? thinkingFor(facts, thinking) : thinking);
|
|
2958
|
+
return { ...counted, ...(level ? { effort: level } : {}), ...(facts && body?.model ? { model: body.model } : {}) };
|
|
2112
2959
|
}
|
|
2113
2960
|
/** Tries `persist` again every settleRetryMs while the server lives, until it lands. */
|
|
2114
2961
|
persistLater(run, persist) {
|
|
@@ -2162,7 +3009,10 @@ export class Runs {
|
|
|
2162
3009
|
if (never)
|
|
2163
3010
|
throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness } });
|
|
2164
3011
|
for (const deadline = Date.now() + this.killAfterMs() + 1_000;; await sleep(50)) {
|
|
2165
|
-
|
|
3012
|
+
// A run whose launch waits on its claim (launch) keeps the place it had, nothing else taking it meanwhile, until it is
|
|
3013
|
+
// cancelled or ends.
|
|
3014
|
+
// So does one that waits for its harness's install (waitsInstall), until that launch, a cancel or its end.
|
|
3015
|
+
const holding = [...this.runs.values()].filter((run) => this.live(run) || ((run.claimWait === true || run.waitsInstall === true) && !run.cancel && !run.outcome && !run.finishing));
|
|
2166
3016
|
const counted = max === undefined || holding.length + this.starting < max;
|
|
2167
3017
|
const held = holding.reduce((sum, run) => sum + runMibOf(run.harness), this.startingMib);
|
|
2168
3018
|
// With nothing held, a run that fits at all starts: pi's one place on a host smaller than a pi run (host.ts).
|
|
@@ -2192,6 +3042,7 @@ export class Runs {
|
|
|
2192
3042
|
const now = await this.options.agents.get(entry.agent.id);
|
|
2193
3043
|
if (now?.agent.archivedAt)
|
|
2194
3044
|
throw new ApiError("agent_not_runnable", `The agent ${entry.agent.id} is archived: unarchive it to run it.`, { details: { archived_at: now.agent.archivedAt } });
|
|
3045
|
+
// A run that waits for its harness's install from here holds its place itself (waitsInstall).
|
|
2195
3046
|
return await this.start(entry, revision, version, options);
|
|
2196
3047
|
}
|
|
2197
3048
|
finally {
|
|
@@ -2221,32 +3072,63 @@ export class Runs {
|
|
|
2221
3072
|
// Only another writer of the store gets here first under the same origin: its run is the one asked for, set up by it.
|
|
2222
3073
|
if (started.existing)
|
|
2223
3074
|
return (await this.get(started.runId));
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
3075
|
+
// Held as starting until the run is: a read in between waits for it (get, adopt) and never loads it from disk.
|
|
3076
|
+
let started_;
|
|
3077
|
+
this.startingRuns.set(started.runId, new Promise((resolve) => (started_ = resolve)));
|
|
3078
|
+
let held = null;
|
|
3079
|
+
try {
|
|
3080
|
+
const at = new Date().toISOString();
|
|
3081
|
+
const meta = {
|
|
3082
|
+
// Shown on the run list and its view: no held secret a person pasted into the message it is taken from.
|
|
3083
|
+
title: clip(redacted(options.title.trim().replace(/\s+/g, " "), this.options.serverSecrets()), 80),
|
|
3084
|
+
created_at: at,
|
|
3085
|
+
input: options.input,
|
|
3086
|
+
place: options.place,
|
|
3087
|
+
...(options.effort ? { effort: options.effort } : {}),
|
|
3088
|
+
...(options.maxCostUsd !== undefined ? { max_cost_usd: options.maxCostUsd } : {}),
|
|
3089
|
+
...(options.capMode !== undefined ? { cap_mode: options.capMode } : {}),
|
|
3090
|
+
...(options.trigger ? { trigger: options.trigger } : {}),
|
|
3091
|
+
...(options.from ? { input_origin: options.from } : {}),
|
|
3092
|
+
...(Object.keys(plane).length ? { tool_plane: plane } : {}),
|
|
3093
|
+
};
|
|
3094
|
+
// The run's input is saved first, as the store has it running: a server that goes down from here on leaves a run the
|
|
3095
|
+
// next one relaunches with its first message.
|
|
2243
3096
|
await this.setUp(started.runId, started.dir, meta);
|
|
3097
|
+
// The trigger's name as it fired (origin.name): its served rows name it with no store read, until a rename pushes
|
|
3098
|
+
// the new one (triggerChanged).
|
|
3099
|
+
if (options.trigger)
|
|
3100
|
+
this.triggerNames.set(options.trigger.id, options.trigger.name);
|
|
3101
|
+
if (pin) {
|
|
3102
|
+
// Then its seed copied and pinned, and its learning saved once the copy is whole or gone. A server that goes down
|
|
3103
|
+
// during the copy leaves none saved, and the next one takes the copy back (learning-run.ts onLoad). A copy that
|
|
3104
|
+
// throws is saved as failed in its own words, the copy taken back, before the start fails: every start that
|
|
3105
|
+
// ends leaves its learning said, so only a stopped server's leaves a copy with none.
|
|
3106
|
+
try {
|
|
3107
|
+
meta.learning = await pin(started, at);
|
|
3108
|
+
}
|
|
3109
|
+
catch (error) {
|
|
3110
|
+
meta.learning = await this.learning.copyThrew(started, at, error);
|
|
3111
|
+
await this.setUp(started.runId, started.dir, meta).catch(() => undefined);
|
|
3112
|
+
throw error;
|
|
3113
|
+
}
|
|
3114
|
+
await this.setUp(started.runId, started.dir, meta);
|
|
3115
|
+
}
|
|
3116
|
+
const run = this.blank({ id: started.runId, agent: entry.agent.id, revision: revision.id, kind: revision.kind }, started.dir, meta, version, harnessOfBody(revision.body), tooling, revision);
|
|
3117
|
+
// Before the run is known here, so nothing launches it first.
|
|
3118
|
+
await this.pinNeeds(run, revision);
|
|
3119
|
+
const refreshing = this.mcpFresh(run);
|
|
3120
|
+
if (refreshing)
|
|
3121
|
+
await refreshing;
|
|
3122
|
+
await this.pinSignIn(run);
|
|
3123
|
+
this.runs.set(run.id, run);
|
|
3124
|
+
held = run;
|
|
3125
|
+
}
|
|
3126
|
+
finally {
|
|
3127
|
+
this.startingRuns.delete(started.runId);
|
|
3128
|
+
started_(held);
|
|
2244
3129
|
}
|
|
2245
|
-
const run =
|
|
2246
|
-
|
|
2247
|
-
await this.pinNeeds(run, revision);
|
|
2248
|
-
await this.pinSignIn(run);
|
|
2249
|
-
this.runs.set(run.id, run);
|
|
3130
|
+
const run = held;
|
|
3131
|
+
const meta = run.meta;
|
|
2250
3132
|
// A seed that failed is a learning row from the start, and its learning's end is in the ledger.
|
|
2251
3133
|
this.show(run);
|
|
2252
3134
|
void this.learning.onSaved(run, meta.learning);
|
|
@@ -2263,11 +3145,13 @@ export class Runs {
|
|
|
2263
3145
|
return run;
|
|
2264
3146
|
}
|
|
2265
3147
|
run.firstLaunch = true;
|
|
3148
|
+
// A harness installed on first use (claude-agent's Claude Code) is installed first, in the background (launch): the
|
|
3149
|
+
// start answers now, and the run shows the install while it waits.
|
|
2266
3150
|
this.launch(run);
|
|
2267
3151
|
if (revision.kind === "workflow")
|
|
2268
3152
|
return run;
|
|
2269
3153
|
// The first message names the files given to the run (run-manifest.ts), on every harness.
|
|
2270
|
-
void firstMessage(options.input.content, started.workspace).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS)).catch((error) => {
|
|
3154
|
+
void firstMessage(options.input.content, started.workspace).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS, options.from)).catch((error) => {
|
|
2271
3155
|
run.submitted = 0;
|
|
2272
3156
|
// The run ended before its first message reached it (a process that crashed at its start): how it ended stands.
|
|
2273
3157
|
if (run.outcome || run.finishing || run.cancel)
|
|
@@ -2309,11 +3193,12 @@ export class Runs {
|
|
|
2309
3193
|
/** One message to the run's door. `origin`: who wrote it when the person did not (a raised cap's follow-up, an
|
|
2310
3194
|
* approval's resume), carried to its user entry so the Timeline shows it as the server's (pi-durable-agent's
|
|
2311
3195
|
* MessageOrigin); the model reads the same text either way. `answers: false`: the run's door refuses the message
|
|
2312
|
-
* (WAITING) when the run's turn ended on ask_person
|
|
3196
|
+
* (WAITING) when the run's turn ended on ask_person or a tool call of it waits for its owner's approval (the gate's
|
|
3197
|
+
* park, APPROVAL_ENTRY), and when the run is busy (BUSY), so it is never queued behind a
|
|
2313
3198
|
* turn that may end so; decided at the door's admission, past every wait here. */
|
|
2314
3199
|
async submit(run, content, whenBusy, requestId, readyMs, origin, answers = true) {
|
|
2315
3200
|
await this.beforeSubmit?.(run.id, content);
|
|
2316
|
-
const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy, ...(origin ? { origin } : {}), ...(answers ? {} : { answers: false, asks: [ASK_TOOL] }) }, readyMs);
|
|
3201
|
+
const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy, ...(origin ? { origin } : {}), ...(answers ? {} : { answers: false, asks: [ASK_TOOL], parks: [APPROVAL_ENTRY] }) }, readyMs, true);
|
|
2317
3202
|
if (answer.status === 409 && answer.body?.error === "WAITING")
|
|
2318
3203
|
throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
|
|
2319
3204
|
if (answer.status === 409 && answer.body?.error === "BUSY" && !answers)
|
|
@@ -2323,7 +3208,7 @@ export class Runs {
|
|
|
2323
3208
|
}
|
|
2324
3209
|
/** Whether the run's harness takes a message mid-turn. */
|
|
2325
3210
|
steers(run) {
|
|
2326
|
-
return run.kind !== "agentic" ||
|
|
3211
|
+
return run.kind !== "agentic" || (builtinHarness(run.harness)?.steer ?? false);
|
|
2327
3212
|
}
|
|
2328
3213
|
/** Whether the run's store already took a message under `requestId`: a trigger's firing sent it, and the server went
|
|
2329
3214
|
* down before it wrote so. Read before sending it again, so a completed run is not opened again for a message it
|
|
@@ -2337,14 +3222,25 @@ export class Runs {
|
|
|
2337
3222
|
const file = this.storeFile(run);
|
|
2338
3223
|
if (!(await stat(file).catch(() => null)))
|
|
2339
3224
|
return false;
|
|
2340
|
-
|
|
2341
|
-
return
|
|
2342
|
-
const db = new DatabaseSync(file, { readOnly: true });
|
|
3225
|
+
// A fresh read-only, lock-free read (run-db.ts), after any take-back's checkpoint of this run.
|
|
3226
|
+
return this.runDb(run, async () => {
|
|
2343
3227
|
try {
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
3228
|
+
const statusOf = await readRunDb(file, this.live(run), (db) => {
|
|
3229
|
+
if (db.prepare("SELECT 1 FROM submissions WHERE request_id = ? LIMIT 1").get(JSON.stringify(requestId)) !== undefined)
|
|
3230
|
+
return true;
|
|
3231
|
+
const status = db.prepare("SELECT json_extract(e.record, '$.data.status') AS status FROM submissions s JOIN entries e ON e.id = json_extract(s.record, '$.entry') WHERE s.request_id = ? LIMIT 1");
|
|
3232
|
+
// The door's journal for it, key by key until the first it does not hold (pi-durable-disk doorKey).
|
|
3233
|
+
const journal = new Map();
|
|
3234
|
+
for (let n = 0;; n++) {
|
|
3235
|
+
const key = doorKey(requestId, n);
|
|
3236
|
+
const at = status.get(JSON.stringify(key))?.status ?? undefined;
|
|
3237
|
+
if (at === undefined)
|
|
3238
|
+
break;
|
|
3239
|
+
journal.set(key, at);
|
|
3240
|
+
}
|
|
3241
|
+
return journal;
|
|
3242
|
+
});
|
|
3243
|
+
return statusOf === true ? true : await doorTook(requestId, (key) => statusOf.get(key));
|
|
2348
3244
|
}
|
|
2349
3245
|
catch (error) {
|
|
2350
3246
|
// A store that keeps no submissions has taken none.
|
|
@@ -2352,10 +3248,7 @@ export class Runs {
|
|
|
2352
3248
|
return false;
|
|
2353
3249
|
throw error;
|
|
2354
3250
|
}
|
|
2355
|
-
|
|
2356
|
-
db.close();
|
|
2357
|
-
}
|
|
2358
|
-
}, this.busyDelays(), this.onBusy(run.id, "its store"));
|
|
3251
|
+
});
|
|
2359
3252
|
}
|
|
2360
3253
|
/** Raises the cap of an agentic run that names one, to `cap`: above its own (by more than CAP_TOLERANCE), or the same as
|
|
2361
3254
|
* its newest raise (a retry, which changes nothing). serve.json keeps it before any answer, and a raise it could not keep
|
|
@@ -2378,6 +3271,8 @@ export class Runs {
|
|
|
2378
3271
|
const from = run.meta.max_cost_usd;
|
|
2379
3272
|
if (from === undefined)
|
|
2380
3273
|
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." }]);
|
|
3274
|
+
if (run.kind === "workflow")
|
|
3275
|
+
return this.raiseWorkflow(run, from, cap);
|
|
2381
3276
|
const last = run.meta.cap_raised?.at(-1);
|
|
2382
3277
|
const pause = pauseOf(run);
|
|
2383
3278
|
const next = continuationOf(run);
|
|
@@ -2416,12 +3311,177 @@ export class Runs {
|
|
|
2416
3311
|
run.meta.cap_continue = follow;
|
|
2417
3312
|
if (next && typeof run.resuming === "number")
|
|
2418
3313
|
run.resuming = undefined;
|
|
3314
|
+
// The served view as the raise leaves it, now: the pause's waiting row goes at the raise, not at the next row a
|
|
3315
|
+
// process sends (a paused process being let go sends none).
|
|
3316
|
+
this.show(run);
|
|
2419
3317
|
this.refresh(run);
|
|
2420
3318
|
const answered = pause !== undefined ? run.meta.cap_continue : undefined;
|
|
2421
3319
|
if (!answered)
|
|
2422
3320
|
return { resumed: false, ...(this.live(run) ? { note: `The run's process keeps the ${money(from)} cap it was opened with; the ${money(cap)} cap holds from its next process.` } : {}) };
|
|
2423
3321
|
return { resumed: true, messageId: answered.message_id };
|
|
2424
3322
|
}
|
|
3323
|
+
/** A workflow run's raise (budget.ts): serve.json keeps it first, as an agentic run's does, then `cap.json` tells the
|
|
3324
|
+
* run's process, whose step waiting at its cap is judged again under it, and a run whose process the pause let go is
|
|
3325
|
+
* opened again (its pause's mark taken away first, so its settle does not hold it) under the raised cap (CAP_ENV),
|
|
3326
|
+
* resuming from its journal. A raise while it works holds from its next check. The same raise again changes nothing. */
|
|
3327
|
+
async raiseWorkflow(run, from, cap) {
|
|
3328
|
+
const last = run.meta.cap_raised?.at(-1);
|
|
3329
|
+
// The same raise again (a retry): what the first saved is finished, whatever a crash cut it at (finishRaise).
|
|
3330
|
+
if (Math.abs(cap - from) <= CAP_TOLERANCE && last && Math.abs(last.to - cap) <= CAP_TOLERANCE) {
|
|
3331
|
+
await this.finishRaise(run);
|
|
3332
|
+
this.refresh(run);
|
|
3333
|
+
return { resumed: last.pause === "budget" };
|
|
3334
|
+
}
|
|
3335
|
+
if (!(cap > from + CAP_TOLERANCE))
|
|
3336
|
+
throw invalid([{ field: "max_cost_usd", reason: "invalid", message: `A cap is only raised: name more than the run's ${money(from)}.` }]);
|
|
3337
|
+
const paused = budgetWaiting(run);
|
|
3338
|
+
const raised = [...(run.meta.cap_raised ?? []), { from, to: cap, at: new Date().toISOString(), ...(paused ? { pause: "budget" } : {}) }];
|
|
3339
|
+
await this.saveMeta(run, () => ({ ...run.meta, max_cost_usd: cap, cap_raised: raised }));
|
|
3340
|
+
run.meta.max_cost_usd = cap;
|
|
3341
|
+
run.meta.cap_raised = raised;
|
|
3342
|
+
await this.finishRaise(run);
|
|
3343
|
+
this.refresh(run);
|
|
3344
|
+
return { resumed: paused };
|
|
3345
|
+
}
|
|
3346
|
+
/** Finishes the raise serve.json keeps (`max_cost_usd`), in its steps' order, each one done again harmlessly: `cap.json`
|
|
3347
|
+
* takes it (a waiting process wakes on it), then a pause it answers (budget.json under a lower cap) is taken away and
|
|
3348
|
+
* its run, with no process, opened again under it. A raise, its retry and a restart's settle all finish it here, so a
|
|
3349
|
+
* crash between serve.json and the rest never leaves a raised run waiting for a raise. True when it took a pause away. */
|
|
3350
|
+
async finishRaise(run, { settling = false } = {}) {
|
|
3351
|
+
const cap = run.meta.max_cost_usd;
|
|
3352
|
+
const mark = run.kind === "workflow" && run.dir ? budgetPausedIn(run.dir) : undefined;
|
|
3353
|
+
if (cap === undefined || run.outcome || run.cancel)
|
|
3354
|
+
return false;
|
|
3355
|
+
if (run.meta.cap_raised?.length)
|
|
3356
|
+
writeRaisedCap(run.dir, cap);
|
|
3357
|
+
if (!raiseFinishes(cap, mark))
|
|
3358
|
+
return false;
|
|
3359
|
+
if (this.live(run))
|
|
3360
|
+
return false;
|
|
3361
|
+
// One finish at a time per run: a settle under way decides the run's next process (it may be reading the run as gone
|
|
3362
|
+
// and launching), so a raise meanwhile leaves the launch to it and finishes again once it is through. Never two.
|
|
3363
|
+
if (!settling && run.settles > 0) {
|
|
3364
|
+
void run.settling?.then(() => this.finishRaise(run)).catch(() => undefined);
|
|
3365
|
+
return true;
|
|
3366
|
+
}
|
|
3367
|
+
// A place under the server's limits first (max_concurrent_runs, the memory its harness takes), as every start takes
|
|
3368
|
+
// one (takePlace): the pause let its place go. With none free the run waits for one, queued, its pause's mark kept,
|
|
3369
|
+
// and opens once one frees (waitForPlace): never a process past the limits, never the raise refused or lost.
|
|
3370
|
+
let release;
|
|
3371
|
+
try {
|
|
3372
|
+
release = await this.takePlace(run.harness);
|
|
3373
|
+
}
|
|
3374
|
+
catch (error) {
|
|
3375
|
+
if (error instanceof ApiError && error.code === "rate_limited") {
|
|
3376
|
+
this.waitForPlace(run, cap);
|
|
3377
|
+
return true;
|
|
3378
|
+
}
|
|
3379
|
+
// A run this host never holds (agent_not_runnable) waits for nothing: off the queue, still paused, saying why.
|
|
3380
|
+
this.leavePlaceQueue(run);
|
|
3381
|
+
throw error;
|
|
3382
|
+
}
|
|
3383
|
+
try {
|
|
3384
|
+
// Read again: the place may have been waited for, and the run ended, cancelled, opened or finished meanwhile, or the
|
|
3385
|
+
// server begun to close (its mark stays, for the next server's settle to finish the raise).
|
|
3386
|
+
if (this.raiseMoot(run))
|
|
3387
|
+
return true;
|
|
3388
|
+
// What its launch needs, pinned while its pause's mark still stands: a pin that fails leaves the run waiting, its
|
|
3389
|
+
// mark kept, at the back of the queue (or off it after RAISE_TRIES), never queued for good with neither.
|
|
3390
|
+
try {
|
|
3391
|
+
await this.beforeRaiseLaunch?.(run.id);
|
|
3392
|
+
await this.pinNeeds(run);
|
|
3393
|
+
await this.pinSignIn(run);
|
|
3394
|
+
}
|
|
3395
|
+
catch (error) {
|
|
3396
|
+
this.raiseFailed(run, cap, error);
|
|
3397
|
+
return true;
|
|
3398
|
+
}
|
|
3399
|
+
// Read again after the pins, then the mark goes and the launch follows with nothing awaited between them.
|
|
3400
|
+
if (this.raiseMoot(run))
|
|
3401
|
+
return true;
|
|
3402
|
+
this.leavePlaceQueue(run);
|
|
3403
|
+
run.raiseFailedRow = undefined;
|
|
3404
|
+
clearBudgetPause(run.dir);
|
|
3405
|
+
this.launch(run);
|
|
3406
|
+
this.show(run);
|
|
3407
|
+
this.refresh(run);
|
|
3408
|
+
}
|
|
3409
|
+
finally {
|
|
3410
|
+
// Launched, it holds its place as a live run.
|
|
3411
|
+
release();
|
|
3412
|
+
}
|
|
3413
|
+
return true;
|
|
3414
|
+
}
|
|
3415
|
+
/** A raised run that found no place: queued, saying it waits for one, and tried again every PLACE_RETRY_MS until it
|
|
3416
|
+
* opens (finishRaise), ends or is cancelled. */
|
|
3417
|
+
waitForPlace(run, cap) {
|
|
3418
|
+
// A run another path has opened, ended or let go of its pause meanwhile (a retry that won the place while this raise
|
|
3419
|
+
// was refused one), or a server that is closing, waits for nothing.
|
|
3420
|
+
if (this.closing || run.outcome || run.cancel || run.finishing || this.live(run) || !budgetPausedIn(run.dir))
|
|
3421
|
+
return;
|
|
3422
|
+
run.placeWait ??= { at: new Date().toISOString(), words: `The cap was raised to ${money(cap)}. The run opens again once this server has a free place for it: it is at its limit of runs at once, or of memory for them.` };
|
|
3423
|
+
this.placeWaiters.add(run);
|
|
3424
|
+
this.show(run);
|
|
3425
|
+
this.refresh(run);
|
|
3426
|
+
this.placeRetry ??= setInterval(() => void this.retryPlaces(), PLACE_RETRY_MS).unref();
|
|
3427
|
+
}
|
|
3428
|
+
/** Whether a raise that took a place has nothing to open now: the server is closing (the mark stays, for the next
|
|
3429
|
+
* server), or the run ended, was cancelled, opened, or has no pause left. Off the queue then, unless closing. */
|
|
3430
|
+
raiseMoot(run) {
|
|
3431
|
+
if (this.closing)
|
|
3432
|
+
return true;
|
|
3433
|
+
if (!(run.outcome || run.cancel || run.finishing || this.live(run) || !budgetPausedIn(run.dir)))
|
|
3434
|
+
return false;
|
|
3435
|
+
this.leavePlaceQueue(run);
|
|
3436
|
+
return true;
|
|
3437
|
+
}
|
|
3438
|
+
/** `run` off the queue for a place: what it reserved is free, and it shows no wait for one. */
|
|
3439
|
+
leavePlaceQueue(run) {
|
|
3440
|
+
const queued = this.placeWaiters.delete(run) || run.placeWait !== undefined;
|
|
3441
|
+
run.placeWait = undefined;
|
|
3442
|
+
run.raiseTries = undefined;
|
|
3443
|
+
if (queued) {
|
|
3444
|
+
this.show(run);
|
|
3445
|
+
this.refresh(run);
|
|
3446
|
+
}
|
|
3447
|
+
}
|
|
3448
|
+
/** A raised run whose launch failed after its place was taken: to the back of the queue, its mark kept, and off it
|
|
3449
|
+
* after RAISE_TRIES failures in a row (still paused at its cap; a raise retried, or the server's next start, finishes it
|
|
3450
|
+
* then), so it never holds a place reserved for good. */
|
|
3451
|
+
raiseFailed(run, cap, error) {
|
|
3452
|
+
const tries = (run.raiseTries ?? 0) + 1;
|
|
3453
|
+
warn(run.id, `its raise did not open it (${tries} of ${RAISE_TRIES}): ${error.message}`);
|
|
3454
|
+
this.placeWaiters.delete(run);
|
|
3455
|
+
if (tries >= RAISE_TRIES) {
|
|
3456
|
+
run.raiseFailedRow = { at: new Date().toISOString(), words: `The cap was raised to ${money(cap)}, but the run could not be started: ${error.message.slice(0, 300)}. It stays paused; the same raise again, or the server's next start, tries once more.` };
|
|
3457
|
+
return this.leavePlaceQueue(run);
|
|
3458
|
+
}
|
|
3459
|
+
run.raiseTries = tries;
|
|
3460
|
+
this.waitForPlace(run, cap);
|
|
3461
|
+
}
|
|
3462
|
+
async retryPlaces() {
|
|
3463
|
+
if (this.placeRetrying)
|
|
3464
|
+
return;
|
|
3465
|
+
this.placeRetrying = true;
|
|
3466
|
+
try {
|
|
3467
|
+
for (const run of [...this.placeWaiters]) {
|
|
3468
|
+
if (this.closing)
|
|
3469
|
+
break;
|
|
3470
|
+
if (run.outcome || run.cancel || run.finishing) {
|
|
3471
|
+
this.leavePlaceQueue(run);
|
|
3472
|
+
continue;
|
|
3473
|
+
}
|
|
3474
|
+
await this.finishRaise(run).catch((error) => warn(run.id, `its raise is not finished yet: ${error.message}`));
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
finally {
|
|
3478
|
+
this.placeRetrying = false;
|
|
3479
|
+
if (!this.placeWaiters.size || this.closing) {
|
|
3480
|
+
clearInterval(this.placeRetry);
|
|
3481
|
+
this.placeRetry = undefined;
|
|
3482
|
+
}
|
|
3483
|
+
}
|
|
3484
|
+
}
|
|
2425
3485
|
/** Sends a raised run its pause's follow-up, under its id (the door takes one id once), at the run's cap now: as a
|
|
2426
3486
|
* follow-up to a run whose process has gone (message()), so the process it starts resumes nothing and opens under the
|
|
2427
3487
|
* new cap, or to the process another launch started. Marked sent in serve.json. One that cannot be sent is tried
|
|
@@ -2483,16 +3543,21 @@ export class Runs {
|
|
|
2483
3543
|
}
|
|
2484
3544
|
/** One message to an agentic run, its mode chosen by the run's state (the contract's table). `requestId`: the message's
|
|
2485
3545
|
* id in the run's store, which takes one message per id (a trigger's firing key); default a new one. */
|
|
2486
|
-
|
|
3546
|
+
/** `origin`: who the message is from when its person did not write it (a trigger's firing). */
|
|
3547
|
+
async message(run, content, requestId, { answers = true, origin } = {}) {
|
|
2487
3548
|
if (run.imported)
|
|
2488
3549
|
throw this.importedRefusal(run);
|
|
2489
3550
|
// A cancelled run takes no message, whether or not its end is written yet.
|
|
2490
3551
|
if (run.cancel)
|
|
2491
3552
|
throw this.finished(run);
|
|
2492
|
-
// A message
|
|
2493
|
-
//
|
|
2494
|
-
|
|
2495
|
-
|
|
3553
|
+
// A message that may not answer a person (a trigger's) is refused while the run waits on one, before anything else,
|
|
3554
|
+
// as the door refuses it (WAITING): it never declines a parked approval, nor answers a question or a cap's pause.
|
|
3555
|
+
if (!answers && waitsOnPerson(run))
|
|
3556
|
+
throw waitingRefusal();
|
|
3557
|
+
// A person's message while a tool call waits for approval declines it, with the message as the reason (as Claude Code
|
|
3558
|
+
// takes what is typed at its permission prompt): the gate's resume carries the refusal and their words in one turn,
|
|
3559
|
+
// and nothing else is sent, so no second turn races the parked call.
|
|
3560
|
+
const read = run.kind === "agentic" && answers ? waitingApproval(run) : undefined;
|
|
2496
3561
|
if (read) {
|
|
2497
3562
|
await this.personsTurn(run);
|
|
2498
3563
|
// Read again after that wait, with nothing awaited from here to the decline's own write: an answer, a stop or a
|
|
@@ -2543,11 +3608,13 @@ export class Runs {
|
|
|
2543
3608
|
throw new ApiError("budget_reached", `The run is paused at its ${money(run.meta.max_cost_usd ?? 0)} cap: raise the cap first. ${paused}`, { details: { cap_usd: run.meta.max_cost_usd ?? null } });
|
|
2544
3609
|
// A harness that cannot take a message mid-turn (any but pi, harness.ts) queues it for the turn's end: a new turn of
|
|
2545
3610
|
// the same run, which the contract calls follow_up, never a steer it does not do.
|
|
2546
|
-
|
|
3611
|
+
// A run whose agent waits on the person in its browser (browser-person.ts) is mid-turn: a message is no answer to it
|
|
3612
|
+
// (the hand-back is), and goes to that turn as one to a working run does.
|
|
3613
|
+
const working = status === "queued" || (status === "working" && state === "working") || browserAsk(run) !== undefined;
|
|
2547
3614
|
const mode = working ? (steers ? "steer" : "follow_up") : status === "input_required" && state === "waiting" ? "answer" : "follow_up";
|
|
2548
3615
|
// A message that may not answer (a trigger's): one that would is refused here, past every wait, before it is sent.
|
|
2549
3616
|
if (mode === "answer" && !answers)
|
|
2550
|
-
throw
|
|
3617
|
+
throw waitingRefusal();
|
|
2551
3618
|
const messageId = requestId ?? `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
|
|
2552
3619
|
// A follow-up to a run the person stopped, whose process has gone: its turn had ended, so the process this message
|
|
2553
3620
|
// starts resumes nothing. With its process live the message starts none, and a relaunch after that process dies
|
|
@@ -2560,7 +3627,11 @@ export class Runs {
|
|
|
2560
3627
|
// After every wait, and once the count above holds the run from ending (so no end-of-run turn is asked from here):
|
|
2561
3628
|
// one asked while this message waited for the run's end wrote its origin then, after any earlier removal.
|
|
2562
3629
|
await this.personsTurn(run);
|
|
2563
|
-
|
|
3630
|
+
// Read again after the last wait, with nothing awaited from here to the door: a call parked or a cap paused
|
|
3631
|
+
// meanwhile is still never answered by it (the door's own check also refuses a parked call or a question).
|
|
3632
|
+
if (!answers && (waitingApproval(run) !== undefined || pausedAt(run, { inFlight: false }) !== undefined))
|
|
3633
|
+
throw waitingRefusal();
|
|
3634
|
+
await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId, undefined, origin ?? (answers ? this.messageOrigin?.(run.id, content) : undefined), answers);
|
|
2564
3635
|
}
|
|
2565
3636
|
catch (error) {
|
|
2566
3637
|
run.submitted = Math.max(0, run.submitted - 1);
|
|
@@ -2593,9 +3664,16 @@ export class Runs {
|
|
|
2593
3664
|
async reopen(run) {
|
|
2594
3665
|
await this.sweepOnce();
|
|
2595
3666
|
await this.pinNeeds(run);
|
|
3667
|
+
// Before its place is taken: the launch below follows the place with no wait.
|
|
3668
|
+
const refreshing = this.mcpFresh(run);
|
|
3669
|
+
if (refreshing)
|
|
3670
|
+
await refreshing;
|
|
2596
3671
|
const row = this.store.readRun(run.id);
|
|
2597
3672
|
if (row?.archivedAt)
|
|
2598
3673
|
throw new ApiError("not_continuable", "This run is archived: unarchive it to continue it.");
|
|
3674
|
+
// Nothing it said can be cut here, so nothing it goes on to say could be shown: it is not opened again.
|
|
3675
|
+
if (run.meta.unshown)
|
|
3676
|
+
throw new ApiError("not_continuable", WITHHELD_SIGN_IN);
|
|
2599
3677
|
// Its end could not be written yet (persistLater tries again): it opens once the store has it.
|
|
2600
3678
|
if (row?.state === "running")
|
|
2601
3679
|
throw new ApiError("unavailable", "The run's end is still being written to the agent store; try again.", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
@@ -2686,7 +3764,7 @@ export class Runs {
|
|
|
2686
3764
|
this.restate(run);
|
|
2687
3765
|
this.refresh(run);
|
|
2688
3766
|
if (!run.outcome && !run.finishing && !run.cancel)
|
|
2689
|
-
void this.ensureLive(run).catch((error) => warn(run.id, `its declined approval waits for its process: ${error.message}`));
|
|
3767
|
+
void this.ensureLive(run, undefined, true).catch((error) => warn(run.id, `its declined approval waits for its process: ${error.message}`));
|
|
2690
3768
|
return { mode: "answer", messageId: `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}` };
|
|
2691
3769
|
}
|
|
2692
3770
|
/** The answers given and not acted on yet (the run's process has not resolved them), overridden by a stop or a cancel:
|
|
@@ -2750,6 +3828,13 @@ export class Runs {
|
|
|
2750
3828
|
this.refresh(run);
|
|
2751
3829
|
return false;
|
|
2752
3830
|
}
|
|
3831
|
+
// The stopped turn is over from here, and the run reads stopped: a request it cut is a charge with no price
|
|
3832
|
+
// (costsofar/1), never one in flight, before the turn's end reaches this server through the door's events.
|
|
3833
|
+
if (run.timeline && run.submitted === 0 && stopped(run)) {
|
|
3834
|
+
run.timeline.idle();
|
|
3835
|
+
const rows = run.timeline.rows();
|
|
3836
|
+
this.take(run, rows, keepCommitted(run.live, rows, run.timeline.isLive));
|
|
3837
|
+
}
|
|
2753
3838
|
this.refresh(run);
|
|
2754
3839
|
return true;
|
|
2755
3840
|
}
|
|
@@ -2770,7 +3855,7 @@ export class Runs {
|
|
|
2770
3855
|
this.restate(run);
|
|
2771
3856
|
this.refresh(run);
|
|
2772
3857
|
if (!run.outcome && !run.finishing && !run.cancel)
|
|
2773
|
-
void this.ensureLive(run).catch((error) => warn(run.id, `its answered approval waits for its process: ${error.message}`));
|
|
3858
|
+
void this.ensureLive(run, undefined, true).catch((error) => warn(run.id, `its answered approval waits for its process: ${error.message}`));
|
|
2774
3859
|
}
|
|
2775
3860
|
/** Record the cancel and signal the run. An agentic run reads `cancelled` from here on (the first end a run comes to is
|
|
2776
3861
|
* its last: nothing its turn writes later moves it), and is carried back so once its process has exited; a workflow
|
|
@@ -2830,40 +3915,6 @@ export class Runs {
|
|
|
2830
3915
|
this.mark(run);
|
|
2831
3916
|
return { run_id: run.id, paused, status: statusOf(run).status };
|
|
2832
3917
|
}
|
|
2833
|
-
/** A workflow run's graph as it stands (graph-view.ts), live while it runs. */
|
|
2834
|
-
async graph(run) {
|
|
2835
|
-
if (run.kind !== "workflow")
|
|
2836
|
-
throw new ApiError("not_found", `the run ${run.id} is an agentic run; only a workflow run has a graph`);
|
|
2837
|
-
// A revision never changes: read once, waiting out a busy store as a run's end does, never failing a poll on it.
|
|
2838
|
-
let workflow = this.workflows.get(run.revision);
|
|
2839
|
-
if (workflow === undefined) {
|
|
2840
|
-
const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
2841
|
-
this.workflows.set(run.revision, (workflow = revision.body.workflow));
|
|
2842
|
-
}
|
|
2843
|
-
// The run's status as this server holds it, with no read of the agent store, which the run's process may be writing.
|
|
2844
|
-
const { status } = statusOf(run);
|
|
2845
|
-
const ended = TERMINAL.has(status);
|
|
2846
|
-
const { runGraph } = await import("./graph-view.js");
|
|
2847
|
-
const given = {
|
|
2848
|
-
run: { id: run.id, agent: run.agentId, revision: run.revision, status, paused: status === "paused", startedAt: run.meta.created_at, endedAt: ended ? (run.endedAt ?? run.updatedAt) : null },
|
|
2849
|
-
ended, workflow, storeFile: this.storeFile(run), root: run.dir, input: run.meta.input ?? {}, modelCost: costOf(run.rows), llmRead: run.llmRead ?? 0,
|
|
2850
|
-
};
|
|
2851
|
-
// A poll never answers home_busy: a store still held answers the live view, or the last whole one, marked stale.
|
|
2852
|
-
try {
|
|
2853
|
-
const view = await runGraph(given);
|
|
2854
|
-
this.graphCache.set(`view:${run.id}`, view, Buffer.byteLength(JSON.stringify(view)));
|
|
2855
|
-
return this.servedGraph(run, { ...view, stale: false });
|
|
2856
|
-
}
|
|
2857
|
-
catch (error) {
|
|
2858
|
-
if (!storeBusy(error))
|
|
2859
|
-
throw error;
|
|
2860
|
-
warn(run.id, "its store is busy; the graph answers its live view, stale");
|
|
2861
|
-
const held = this.graphCache.get(`view:${run.id}`);
|
|
2862
|
-
if (held)
|
|
2863
|
-
return this.servedGraph(run, { ...held, run: given.run, stale: true });
|
|
2864
|
-
return this.servedGraph(run, { ...(await runGraph({ ...given, liveOnly: true })), stale: true });
|
|
2865
|
-
}
|
|
2866
|
-
}
|
|
2867
3918
|
/** How long a run's process gets after SIGTERM before SIGKILL: its drain and a second to exit. */
|
|
2868
3919
|
killAfterMs() {
|
|
2869
3920
|
return (durationMs(this.options.drainTimeout ?? DRAIN) ?? 30_000) + 1_000;
|
|
@@ -2874,11 +3925,14 @@ export class Runs {
|
|
|
2874
3925
|
stopping() {
|
|
2875
3926
|
const all = [...this.runs.values()];
|
|
2876
3927
|
const started = all.filter((run) => run.child).length;
|
|
2877
|
-
const adopted = all.filter((run) => !run.child && run.
|
|
3928
|
+
const adopted = all.filter((run) => !run.child && run.orphanHolder && holderLives(run.orphanHolder)).length;
|
|
2878
3929
|
return { runs: started + adopted, boundMs: (started ? this.killAfterMs() : 0) + (adopted ? this.killAfterMs() : 0) };
|
|
2879
3930
|
}
|
|
2880
3931
|
async close() {
|
|
2881
3932
|
this.closing = true;
|
|
3933
|
+
// The retry for raised runs waiting for a place stops now: nothing is launched past the close.
|
|
3934
|
+
clearInterval(this.placeRetry);
|
|
3935
|
+
this.placeRetry = undefined;
|
|
2882
3936
|
this.learning.close();
|
|
2883
3937
|
const live = [...this.runs.values()].filter((run) => run.child);
|
|
2884
3938
|
for (const run of live) {
|
|
@@ -2887,16 +3941,19 @@ export class Runs {
|
|
|
2887
3941
|
}
|
|
2888
3942
|
await Promise.all(live.map((run) => new Promise((resolve) => (run.child ? run.child.once("exit", resolve) : resolve(undefined)))));
|
|
2889
3943
|
// An adopted process is stopped the same way, and watched by its pid.
|
|
2890
|
-
const adopted = [...this.runs.values()].filter((run) => run.
|
|
3944
|
+
const adopted = [...this.runs.values()].filter((run) => run.orphanHolder && holderLives(run.orphanHolder));
|
|
2891
3945
|
for (const run of adopted)
|
|
2892
3946
|
this.terminate(run);
|
|
2893
|
-
for (const deadline = Date.now() + this.killAfterMs(); adopted.some((run) => run.
|
|
3947
|
+
for (const deadline = Date.now() + this.killAfterMs(); adopted.some((run) => run.orphanHolder && holderLives(run.orphanHolder)) && Date.now() < deadline;)
|
|
2894
3948
|
await sleep(100);
|
|
2895
3949
|
await sleep(0);
|
|
2896
3950
|
await Promise.all([...this.runs.values()].map((run) => run.settling));
|
|
2897
3951
|
await this.learning.idle();
|
|
2898
|
-
for (const run of this.runs.values())
|
|
3952
|
+
for (const run of this.runs.values()) {
|
|
2899
3953
|
run.feed?.abort();
|
|
3954
|
+
clearTimeout(run.stopPending);
|
|
3955
|
+
run.stopPending = undefined;
|
|
3956
|
+
}
|
|
2900
3957
|
this.closed = true;
|
|
2901
3958
|
}
|
|
2902
3959
|
// ---- views ------------------------------------------------------------------------------------------------------------
|
|
@@ -2907,19 +3964,26 @@ export class Runs {
|
|
|
2907
3964
|
// Unknown: what it cost so far and how many charges have no price (costsofar/1), from its rows, else what it said at
|
|
2908
3965
|
// its end (a run carried back with no rows read since).
|
|
2909
3966
|
const soFar = usd === null && !run.imported ? (soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) ?? (run.rows.length ? undefined : soFarOfMeta(run.meta))) : undefined;
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
3967
|
+
// Under a cap, the most a cache miss could make its requests in flight cost beyond what they are held at (cap.ts):
|
|
3968
|
+
// none without a live process, which every request in flight needs.
|
|
3969
|
+
const bound = run.meta.max_cost_usd === undefined ? {} : { overshoot_bound_usd: this.live(run) ? microUp(run.bounds?.inFlight() ?? 0) : 0 };
|
|
3970
|
+
return { usd, basis: "estimate", charge_state: null, cap_usd: run.meta.max_cost_usd ?? null, ...bound, ...(soFar ?? {}) };
|
|
3971
|
+
}
|
|
3972
|
+
/** `Run`, as the contract shows it, its console page at `origin` (server.ts linkOrigin). `known`: its stored row as the
|
|
3973
|
+
* caller already has it, so nothing is read; a run just written has none worth reading (`{ stored: null }`: it is
|
|
3974
|
+
* neither archived nor ended), and its start's answer must not read the store once the run exists, since a busy store
|
|
3975
|
+
* would then refuse a run that runs. */
|
|
3976
|
+
async view(run, origin, known) {
|
|
2916
3977
|
const stored = known ? (known.stored ?? undefined) : await this.options.agents.request(() => this.store.readRun(run.id));
|
|
2917
3978
|
// After the read: the run may have moved on while it waited, and every field below is of this one moment.
|
|
2918
3979
|
const { status, state } = statusOf(run);
|
|
2919
3980
|
const row = TERMINAL.has(status) ? stored : undefined;
|
|
3981
|
+
// What it held for its owner's OK as it reads now: approved or retired since, it waits no more (learning-run.ts current).
|
|
3982
|
+
const learning = await this.learning.current(run.agentId, run.meta.learning);
|
|
2920
3983
|
// The whole text of the answer the run's turn ended on (answerOfRun), never the line the store keeps, which is cut;
|
|
2921
3984
|
// the store's line only for a run whose rows are not read (an import's).
|
|
2922
|
-
|
|
3985
|
+
// A run whose words are withheld (meta.unshown) answers nothing: its row's line is its own words too.
|
|
3986
|
+
const finalAnswer = run.kind === "workflow" || run.meta.unshown ? null : (answerOfRun(run) ?? row?.summary ?? null);
|
|
2923
3987
|
// When the turn of a message still open last wrote: a run working shows it is moving, or not.
|
|
2924
3988
|
const progress = TERMINAL.has(status) || run.kind === "workflow" ? undefined : run.turns.progressAt();
|
|
2925
3989
|
// A run its cap stopped keeps the answer it paid for.
|
|
@@ -2929,6 +3993,7 @@ export class Runs {
|
|
|
2929
3993
|
run_id: run.id,
|
|
2930
3994
|
agent_id: run.agentId,
|
|
2931
3995
|
agent_version: run.version,
|
|
3996
|
+
console_url: runLink(origin, run.id),
|
|
2932
3997
|
revision: run.revision,
|
|
2933
3998
|
kind: run.kind,
|
|
2934
3999
|
sha: null,
|
|
@@ -2941,23 +4006,29 @@ export class Runs {
|
|
|
2941
4006
|
updated_at: run.updatedAt,
|
|
2942
4007
|
ended_at: endedAt,
|
|
2943
4008
|
// An answer is served with no held secret in it, whole (key-refusal.ts redactedAnswer); the stored one stays as written.
|
|
2944
|
-
result: status === "completed" ? { output: run.kind === "workflow" ? (this.servedOutput(run, run.meta.output ?? null)) : null, final_answer: this.servedAnswer(run, finalAnswer) } : kept ? { output: null, final_answer: this.servedAnswer(run, kept) } : null,
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
4009
|
+
result: status === "completed" ? { output: run.kind === "workflow" && !run.meta.unshown ? (this.servedOutput(run, run.meta.output ?? null)) : null, final_answer: this.servedAnswer(run, finalAnswer) } : kept ? { output: null, final_answer: this.servedAnswer(run, kept) } : null,
|
|
4010
|
+
// Cut as its rows and answer are (shown): an error can quote what the run said, or a process's last line.
|
|
4011
|
+
error: status === "failed" ? this.servedRunError(run, run.error ?? { code: "run_failed", message: "The run failed.", retryable: false }) : null,
|
|
4012
|
+
review: endedAt === null ? null : this.servedReview(run, reviewAt(run.meta.review ?? (row ? reviewOfRow(row, run.meta) : null), endedAt)),
|
|
4013
|
+
pending: status === "input_required" && state === "waiting" ? (approvalOf(run, this.redactor(run)) ?? budgetPending(run, this.spentNow(run)) ?? workflowBudgetPending(run) ?? browserPending(browserAsk(run), this.redactor(run)) ?? pendingOf(run.rows)) : null,
|
|
2948
4014
|
cost: this.cost(run),
|
|
4015
|
+
// How its cap prices a request (cap.ts CapMode): its own, else expected; null with no cap.
|
|
4016
|
+
cap_mode: run.meta.max_cost_usd === undefined ? null : (run.meta.cap_mode ?? "expected"),
|
|
4017
|
+
// Whether it ran unattended (its revision's approvals, as it started: a run keeps the revision it started on): never,
|
|
4018
|
+
// an ask allowed at its gate; ask, the default.
|
|
4019
|
+
approvals: approvalsOf(run.tooling?.approvals),
|
|
2949
4020
|
archived_at: stored?.archivedAt ?? null,
|
|
2950
4021
|
imported_from: run.imported ?? null,
|
|
2951
4022
|
trigger: run.meta.trigger ?? null,
|
|
2952
4023
|
// The notes it read once it settled: while it runs, or runs again for a follow-up, they are still being read.
|
|
2953
|
-
learning: this.learning.view(
|
|
4024
|
+
learning: this.learning.view(learning, TERMINAL.has(status) && run.settled),
|
|
2954
4025
|
poll_after_ms: TERMINAL.has(status) && run.settled ? 0 : 1000,
|
|
2955
4026
|
last_progress_at: progress === undefined ? null : new Date(progress).toISOString(),
|
|
2956
4027
|
};
|
|
2957
4028
|
}
|
|
2958
|
-
async summary(run) {
|
|
2959
|
-
const { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning } = await this.view(run);
|
|
2960
|
-
return { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, ...(effort ? { effort } : {}), created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning: learning && shortOf(learning) };
|
|
4029
|
+
async summary(run, origin) {
|
|
4030
|
+
const { run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning } = await this.view(run, origin);
|
|
4031
|
+
return { run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title, ...(effort ? { effort } : {}), created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, learning: learning && shortOf(learning) };
|
|
2961
4032
|
}
|
|
2962
4033
|
/** A run's status for a list: an ended run's from its row, a running one's from the run itself. */
|
|
2963
4034
|
async statusOfRow(row) {
|
|
@@ -2968,26 +4039,33 @@ export class Runs {
|
|
|
2968
4039
|
}
|
|
2969
4040
|
/** A run's summary for a list. An ended run this server holds no Run for is read from its row and its serve.json alone,
|
|
2970
4041
|
* not its store; `versions` numbers its agent's revisions. */
|
|
2971
|
-
async summaryOfRow(row, versions) {
|
|
4042
|
+
async summaryOfRow(row, versions, origin) {
|
|
2972
4043
|
const known = this.runs.get(row.id) ?? (row.state === "running" ? await this.get(row.id) : null);
|
|
2973
4044
|
if (known)
|
|
2974
|
-
return this.summary(known);
|
|
2975
|
-
const meta =
|
|
4045
|
+
return this.summary(known, origin);
|
|
4046
|
+
const { stored: meta, damaged } = await readMeta(join(runDirIn(this.options.agents.dir, row.agent, row.id), RUN_META));
|
|
4047
|
+
const failed = STATUS_OF[row.state] === "failed" ? errorOfRow(row, meta) : null;
|
|
4048
|
+
const review = reviewOfRow(row, meta);
|
|
4049
|
+
// Its error and review are the run's words (its error can quote what it said; an escalation's reason is its own):
|
|
4050
|
+
// cut as its view's are, or withheld when the pointer they could hold can't be read back here.
|
|
4051
|
+
const shown = failed || review ? await this.rowShown(row.agent, meta, damaged) : undefined;
|
|
4052
|
+
const say = (text) => (shown === "withheld" ? WITHHELD_SIGN_IN : shown(text));
|
|
2976
4053
|
return {
|
|
2977
|
-
run_id: row.id, agent_id: row.agent, agent_version: versions.get(row.revision) ?? 0, revision: row.revision, kind: row.kind, sha: null,
|
|
4054
|
+
run_id: row.id, agent_id: row.agent, agent_version: versions.get(row.revision) ?? 0, console_url: runLink(origin, row.id), revision: row.revision, kind: row.kind, sha: null,
|
|
2978
4055
|
status: STATUS_OF[row.state], state: "idle", title: typeof meta?.title === "string" ? meta.title : "",
|
|
2979
4056
|
...(typeof meta?.effort === "string" ? { effort: meta.effort } : {}),
|
|
2980
4057
|
created_at: typeof meta?.created_at === "string" ? meta.created_at : row.startedAt, ended_at: row.endedAt ?? null,
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
4058
|
+
// Withheld as load withholds a held run's: its code too, which can be the run's own (errorOfRow).
|
|
4059
|
+
error: failed && (shown === "withheld" ? { code: "run_failed", message: WITHHELD_SIGN_IN, retryable: false } : { ...failed, message: say(failed.message), ...(failed.details ? { details: cutStrings(failed.details, say) } : {}) }),
|
|
4060
|
+
review: reviewAt(review && { ...review, reason: say(review.reason) }, row.endedAt ?? new Date(0).toISOString()),
|
|
4061
|
+
cost: { usd: row.costUsd ?? null, basis: "estimate", charge_state: null, cap_usd: typeof meta?.max_cost_usd === "number" ? meta.max_cost_usd : null, ...(typeof meta?.max_cost_usd === "number" ? { overshoot_bound_usd: 0 } : {}), ...(row.costUsd == null ? (soFarOfMeta(meta) ?? {}) : {}) },
|
|
2984
4062
|
archived_at: row.archivedAt ?? null,
|
|
2985
4063
|
// A run read from its row alone has ended: it waits on nothing.
|
|
2986
4064
|
pending: null,
|
|
2987
4065
|
imported_from: row.importedFrom ?? null,
|
|
2988
4066
|
trigger: triggerOf(meta),
|
|
2989
4067
|
// Its row says it ended: what serve.json holds of its learning is as it settled.
|
|
2990
|
-
learning: this.learning.short(isObject(meta?.learning) ? meta.learning : null, true),
|
|
4068
|
+
learning: this.learning.short(isObject(meta?.learning) ? ((await this.learning.current(row.agent, meta.learning)) ?? null) : null, true),
|
|
2991
4069
|
};
|
|
2992
4070
|
}
|
|
2993
4071
|
/** A key was saved on this server or deleted from it: each held run's learning row and decision rows shown again, cut
|
|
@@ -3008,6 +4086,11 @@ export class Runs {
|
|
|
3008
4086
|
/** The timeline from change `after`, held up to `waitMs` for a change when there is none. */
|
|
3009
4087
|
async page(run, after, waitMs, limit) {
|
|
3010
4088
|
const deadline = Date.now() + waitMs;
|
|
4089
|
+
// A full read is of the served view as the run stands now: show() first, so a row only the view makes (a pause's
|
|
4090
|
+
// waiting row, the install row, the learning row) is as current state says, whatever change came with no show() after
|
|
4091
|
+
// it. One diff of the run's rows (RowLog.sync), on a full read only; a read from a cursor gets each change as it is shown.
|
|
4092
|
+
if (after <= 0)
|
|
4093
|
+
this.show(run);
|
|
3011
4094
|
for (;;) {
|
|
3012
4095
|
const page = run.log.page(after, limit);
|
|
3013
4096
|
const { status, state } = statusOf(run);
|