@parcha/agentrun-serve 0.1.0-beta.32 → 0.1.0-beta.34
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 +270 -0
- package/README.md +343 -246
- package/dist/adapters.d.ts +0 -7
- package/dist/adapters.js +11 -22
- package/dist/agent-rows.d.ts +98 -0
- package/dist/agent-rows.js +1 -0
- package/dist/agents-store.d.ts +6 -2
- package/dist/agents-store.js +60 -25
- package/dist/agents.d.ts +9 -125
- package/dist/agents.js +15 -305
- package/dist/answer-json.d.ts +23 -0
- package/dist/answer-json.js +58 -0
- package/dist/api-only.d.ts +14 -0
- package/dist/api-only.js +33 -0
- package/dist/archil-routes.d.ts +1 -1
- package/dist/bash-read-only.d.ts +22 -0
- package/dist/bash-read-only.js +701 -0
- package/dist/box-egress-vm.d.ts +0 -8
- package/dist/box-egress-vm.js +0 -10
- package/dist/box-egress.d.ts +0 -4
- package/dist/box-egress.js +1 -16
- package/dist/box-paths.d.ts +25 -2
- package/dist/box-paths.js +79 -11
- package/dist/box-relay.d.ts +0 -11
- package/dist/box-relay.js +0 -20
- package/dist/box-settings.d.ts +26 -0
- package/dist/box-settings.js +63 -0
- package/dist/boxes.d.ts +21 -1
- package/dist/boxes.js +27 -20
- package/dist/browser-commands.d.ts +5 -2
- package/dist/browser-commands.js +4 -4
- package/dist/browser-computer.d.ts +5 -0
- package/dist/browser-computer.js +21 -0
- package/dist/browser-cost.d.ts +9 -6
- package/dist/browser-cost.js +94 -51
- package/dist/browser-live.d.ts +7 -20
- package/dist/browser-live.js +15 -93
- package/dist/browser-person.d.ts +18 -53
- package/dist/browser-person.js +94 -279
- package/dist/budget.d.ts +0 -4
- package/dist/budget.js +0 -7
- package/dist/cap.d.ts +8 -12
- package/dist/cap.js +12 -27
- package/dist/cli.js +61 -20
- package/dist/closed-pipes.d.ts +2 -0
- package/dist/closed-pipes.js +13 -0
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +2 -0
- package/dist/computer-keys.js +5 -2
- package/dist/computer-setting.d.ts +20 -4
- package/dist/computer-setting.js +25 -5
- package/dist/computers.d.ts +31 -3
- package/dist/computers.js +70 -11
- package/dist/confine.d.ts +120 -0
- package/dist/confine.js +436 -0
- package/dist/console/assets/index-RPHGlXmM.js +540 -0
- package/dist/console/assets/index-opTN5Naq.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/daytona-api.d.ts +0 -11
- package/dist/daytona-api.js +1 -82
- package/dist/decision-rows.d.ts +1 -1
- package/dist/decision-rows.js +1 -1
- package/dist/docker-daemon.d.ts +31 -0
- package/dist/docker-daemon.js +56 -0
- package/dist/docker-host-addresses.d.ts +37 -0
- package/dist/docker-host-addresses.js +110 -0
- package/dist/effort-guidance.js +4 -3
- package/dist/environment.d.ts +0 -3
- package/dist/environment.js +3 -5
- package/dist/errors.d.ts +0 -2
- package/dist/errors.js +6 -9
- package/dist/filed-answer.d.ts +32 -0
- package/dist/filed-answer.js +160 -0
- package/dist/files.d.ts +1 -11
- package/dist/files.js +2 -21
- package/dist/github-connection.d.ts +2 -2
- package/dist/github-connection.js +1 -1
- package/dist/graph-view.d.ts +3 -5
- package/dist/graph-view.js +4 -14
- package/dist/handed-values.d.ts +9 -0
- package/dist/handed-values.js +26 -0
- package/dist/harness-install.d.ts +22 -5
- package/dist/harness-install.js +98 -20
- package/dist/harness-opencode/adapter.d.ts +7 -0
- package/dist/harness-opencode/adapter.js +23 -6
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/verify.d.ts +17 -0
- package/dist/harness-opencode/verify.js +30 -10
- package/dist/harness-table.js +6 -1
- package/dist/harness.d.ts +4 -3
- package/dist/harness.js +16 -1
- package/dist/heard.js +1 -1
- package/dist/held-fd.d.ts +5 -0
- package/dist/held-fd.js +14 -0
- package/dist/host-calls.d.ts +20 -0
- package/dist/host-calls.js +12 -0
- package/dist/host-tools.d.ts +4 -21
- package/dist/host-tools.js +4 -61
- package/dist/host.d.ts +2 -4
- package/dist/host.js +2 -7
- package/dist/import-summary.d.ts +1 -5
- package/dist/import-summary.js +0 -21
- package/dist/import.d.ts +6 -6
- package/dist/import.js +62 -24
- package/dist/key-refusal.d.ts +5 -1
- package/dist/key-refusal.js +19 -4
- package/dist/learn/check.d.ts +6 -2
- package/dist/learn/check.js +83 -29
- package/dist/learn/folder.d.ts +5 -1
- package/dist/learn/folder.js +10 -3
- package/dist/learn/grade.d.ts +14 -0
- package/dist/learn/grade.js +68 -12
- package/dist/learn/index.d.ts +4 -4
- package/dist/learn/index.js +4 -4
- package/dist/learn/reflect.d.ts +31 -2
- package/dist/learn/reflect.js +79 -4
- package/dist/learn/relevance.d.ts +24 -0
- package/dist/learn/relevance.js +91 -0
- package/dist/learn/secrets.d.ts +8 -1
- package/dist/learn/secrets.js +95 -15
- package/dist/learn/skills.d.ts +112 -14
- package/dist/learn/skills.js +556 -52
- package/dist/learned-workflow.d.ts +37 -5
- package/dist/learned-workflow.js +106 -12
- package/dist/learning-routes.d.ts +16 -49
- package/dist/learning-routes.js +46 -36
- package/dist/learning-run.d.ts +6 -250
- package/dist/learning-run.js +11 -665
- package/dist/learning-words.d.ts +12 -5
- package/dist/learning-words.js +18 -9
- package/dist/learning.d.ts +93 -77
- package/dist/learning.js +176 -304
- package/dist/live/stream.js +1 -1
- package/dist/live/translate.js +13 -3
- package/dist/local-models.d.ts +11 -5
- package/dist/local-models.js +13 -8
- package/dist/mcp-gateway.d.ts +11 -52
- package/dist/mcp-gateway.js +44 -148
- package/dist/mcp-oauth.d.ts +10 -14
- package/dist/mcp-oauth.js +14 -32
- package/dist/mcp-probe.d.ts +0 -7
- package/dist/mcp-probe.js +4 -10
- package/dist/mcp-servers-store.d.ts +6 -6
- package/dist/mcp-servers-store.js +13 -15
- package/dist/mcp-store.js +3 -4
- package/dist/mcp.js +4 -3
- package/dist/model.d.ts +6 -7
- package/dist/model.js +43 -27
- package/dist/monid.d.ts +0 -2
- package/dist/monid.js +3 -6
- package/dist/openapi.d.ts +8 -1
- package/dist/openapi.js +124 -50
- package/dist/page.d.ts +1 -3
- package/dist/page.js +9 -19
- package/dist/paid-calls.d.ts +21 -27
- package/dist/paid-calls.js +28 -62
- package/dist/pause.d.ts +0 -2
- package/dist/pause.js +1 -8
- package/dist/place.d.ts +0 -5
- package/dist/place.js +0 -10
- package/dist/print.d.ts +2 -1
- package/dist/print.js +4 -2
- package/dist/propose.js +83 -39
- package/dist/push-handler.d.ts +1 -1
- package/dist/reflect-range.d.ts +25 -0
- package/dist/reflect-range.js +30 -0
- package/dist/refusal-words.d.ts +5 -1
- package/dist/refusal-words.js +5 -1
- package/dist/rows.d.ts +1 -1
- package/dist/run-cut.d.ts +0 -6
- package/dist/run-cut.js +0 -6
- package/dist/run-db.d.ts +2 -13
- package/dist/run-db.js +2 -41
- package/dist/run-launch.d.ts +19 -2
- package/dist/run-launch.js +13 -5
- package/dist/run-learning-served.d.ts +46 -2
- package/dist/run-learning-served.js +26 -7
- package/dist/run-reads-over-store.d.ts +1 -1
- package/dist/run-reads-over-store.js +15 -6
- package/dist/run-secrets.d.ts +33 -0
- package/dist/run-secrets.js +53 -0
- package/dist/run-timeline-served.d.ts +5 -1
- package/dist/run-timeline-served.js +19 -5
- package/dist/run-view.d.ts +12 -17
- package/dist/run-view.js +29 -28
- package/dist/runnable.d.ts +18 -10
- package/dist/runnable.js +21 -10
- package/dist/runner/adapter-loop.d.ts +14 -3
- package/dist/runner/adapter-loop.js +464 -62
- package/dist/runner/adapter-run-spec.d.ts +29 -8
- package/dist/runner/adapter-run-spec.js +96 -37
- package/dist/runner/adapters/index.js +11 -1
- package/dist/runner/adapters/pi.d.ts +15 -1
- package/dist/runner/adapters/pi.js +19 -5
- package/dist/runner/beside.d.ts +30 -3
- package/dist/runner/beside.js +54 -12
- package/dist/runner/claim-secrets.d.ts +10 -1
- package/dist/runner/claim-secrets.js +49 -15
- package/dist/runner/cli-run-spec.d.ts +2 -0
- package/dist/runner/cli-run-spec.js +60 -17
- package/dist/runner/commands.js +1 -1
- package/dist/runner/computer-journal.d.ts +15 -2
- package/dist/runner/computer-journal.js +41 -5
- package/dist/runner/conformance/harness.js +118 -8
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/dispatch.d.ts +8 -1
- package/dist/runner/dispatch.js +81 -7
- package/dist/runner/end-of-run.d.ts +8 -2
- package/dist/runner/end-of-run.js +10 -4
- package/dist/runner/github-app.js +1 -1
- package/dist/runner/harness-loops.d.ts +9 -1
- package/dist/runner/harness-loops.js +15 -2
- package/dist/runner/journal-kinds.d.ts +30 -6
- package/dist/runner/journal-kinds.js +20 -5
- package/dist/runner/journal-reader.d.ts +1 -1
- package/dist/runner/journal-reader.js +2 -2
- package/dist/runner/learning-ask.d.ts +4 -0
- package/dist/runner/learning-ask.js +15 -1
- package/dist/runner/learning-end.d.ts +18 -3
- package/dist/runner/learning-end.js +113 -11
- package/dist/runner/learning-loop.d.ts +5 -0
- package/dist/runner/learning-loop.js +26 -6
- package/dist/runner/live-ticker.d.ts +1 -1
- package/dist/runner/live-ticker.js +28 -4
- package/dist/runner/loop-contract.d.ts +3 -2
- package/dist/runner/main.d.ts +64 -10
- package/dist/runner/main.js +165 -27
- package/dist/runner/mcp-claim.d.ts +1 -1
- package/dist/runner/mcp-claim.js +2 -3
- package/dist/runner/mcp-run.d.ts +2 -0
- package/dist/runner/mcp-run.js +15 -5
- package/dist/runner/memory-claim.d.ts +9 -0
- package/dist/runner/memory-claim.js +25 -0
- package/dist/runner/metrics.d.ts +33 -1
- package/dist/runner/metrics.js +85 -1
- package/dist/runner/model-route.d.ts +13 -0
- package/dist/runner/model-route.js +154 -11
- package/dist/runner/redact.d.ts +8 -2
- package/dist/runner/redact.js +11 -2
- package/dist/runner/reflect-hook.d.ts +12 -1
- package/dist/runner/reflect-hook.js +33 -3
- package/dist/runner/runner.d.ts +20 -0
- package/dist/runner/runner.js +56 -10
- package/dist/runner/store-port.d.ts +1 -1
- package/dist/runner/store-secrets.d.ts +3 -3
- package/dist/runner/store-secrets.js +8 -12
- package/dist/runner/text-tools.d.ts +44 -0
- package/dist/runner/text-tools.js +237 -0
- package/dist/runner/workflow-loop.d.ts +6 -0
- package/dist/runner/workflow-loop.js +6 -4
- package/dist/runner/workflow-spec.d.ts +18 -0
- package/dist/runner/workflow-spec.js +68 -26
- package/dist/runs-over-store.d.ts +8 -3
- package/dist/runs-over-store.js +76 -19
- package/dist/seal-key.d.ts +54 -15
- package/dist/seal-key.js +232 -82
- package/dist/sealed-settings-store.d.ts +19 -4
- package/dist/sealed-settings-store.js +9 -9
- package/dist/sealing.d.ts +4 -0
- package/dist/sealing.js +20 -0
- package/dist/secret-cut.d.ts +1 -1
- package/dist/secret-cut.js +1 -1
- package/dist/secret-name.d.ts +9 -0
- package/dist/secret-name.js +15 -0
- package/dist/secret-writes.d.ts +0 -1
- package/dist/secret-writes.js +0 -1
- package/dist/secrets.d.ts +2 -10
- package/dist/secrets.js +21 -17
- package/dist/server-fs.d.ts +4 -0
- package/dist/server-fs.js +8 -2
- package/dist/server-lock.d.ts +0 -24
- package/dist/server-lock.js +1 -80
- package/dist/server-secrets-store.d.ts +4 -4
- package/dist/server-secrets-store.js +10 -32
- package/dist/server-secrets.d.ts +4 -9
- package/dist/server-secrets.js +12 -33
- package/dist/server.d.ts +26 -44
- package/dist/server.js +229 -142
- package/dist/sign-ins-store.d.ts +34 -36
- package/dist/sign-ins-store.js +27 -38
- package/dist/sign-ins.d.ts +2 -119
- package/dist/sign-ins.js +5 -311
- package/dist/standard-webhooks.d.ts +1 -1
- package/dist/standard-webhooks.js +1 -1
- package/dist/stats.d.ts +3 -2
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.d.ts +8 -2
- package/dist/store/agent-body.js +16 -4
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +3 -3
- package/dist/store/open.d.ts +18 -5
- package/dist/store/open.js +23 -3
- package/dist/store/postgres/connection.d.ts +18 -2
- package/dist/store/postgres/connection.js +156 -32
- package/dist/store/postgres/migrate.d.ts +4 -0
- package/dist/store/postgres/migrate.js +27 -3
- package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
- package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
- package/dist/store/postgres/store.d.ts +9 -2
- package/dist/store/postgres/store.js +9 -0
- package/dist/store/schema.js +1 -1
- package/dist/store/seal.js +2 -2
- package/dist/store/sqlite/connection.js +49 -5
- package/dist/store/sqlite/run-patch.d.ts +3 -0
- package/dist/store/sqlite/run-patch.js +3 -0
- package/dist/store/sqlite/store.js +64 -20
- package/dist/store/store.d.ts +38 -6
- package/dist/store/store.js +12 -2
- package/dist/store-reads/cap.d.ts +1 -1
- package/dist/store-reads/cap.js +22 -4
- package/dist/store-reads/journal.d.ts +25 -6
- package/dist/store-reads/journal.js +173 -21
- package/dist/store-reads/learning.d.ts +26 -8
- package/dist/store-reads/learning.js +12 -4
- package/dist/store-reads/workflow.d.ts +1 -1
- package/dist/store-reads/workflow.js +1 -1
- package/dist/store-view.d.ts +5 -1
- package/dist/store-view.js +91 -23
- package/dist/template-eval.d.ts +60 -4
- package/dist/template-eval.js +120 -54
- package/dist/templates.d.ts +24 -10
- package/dist/templates.js +69 -38
- package/dist/timeline/group.d.ts +33 -0
- package/dist/timeline/group.js +77 -0
- package/dist/timeline/index.d.ts +7 -0
- package/dist/timeline/index.js +7 -0
- package/dist/timeline/labels.d.ts +79 -0
- package/dist/timeline/labels.js +150 -0
- package/dist/timeline/origin.d.ts +56 -0
- package/dist/timeline/origin.js +92 -0
- package/dist/timeline/render-text.d.ts +11 -0
- package/dist/timeline/render-text.js +62 -0
- package/dist/timeline/timeline.d.ts +274 -0
- package/dist/timeline/timeline.js +1308 -0
- package/dist/timeline/util.d.ts +17 -0
- package/dist/timeline/util.js +49 -0
- package/dist/tool-gate.d.ts +41 -216
- package/dist/tool-gate.js +79 -540
- package/dist/tool-keys-store.d.ts +11 -12
- package/dist/tool-keys-store.js +24 -31
- package/dist/tool-keys.d.ts +9 -104
- package/dist/tool-keys.js +15 -271
- package/dist/tool-plane.d.ts +14 -42
- package/dist/tool-plane.js +23 -81
- package/dist/tool-settings-store.d.ts +1 -2
- package/dist/tool-settings-store.js +5 -8
- package/dist/tools.d.ts +31 -19
- package/dist/tools.js +101 -108
- package/dist/trigger-adapter.d.ts +2 -2
- package/dist/trigger-schedule.js +2 -1
- package/dist/trigger-secrets-shown.js +5 -1
- package/dist/trigger-targets.d.ts +13 -1
- package/dist/trigger-targets.js +31 -1
- package/dist/triggers.d.ts +2 -2
- package/dist/triggers.js +3 -3
- package/dist/turn-end.d.ts +1 -1
- package/dist/turn-end.js +1 -1
- package/dist/turns.d.ts +0 -6
- package/dist/turns.js +0 -19
- package/dist/uploads.js +1 -1
- package/dist/usage.d.ts +0 -2
- package/dist/usage.js +0 -2
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +23 -14
- package/dist/webhooks.d.ts +102 -76
- package/dist/webhooks.js +266 -233
- package/dist/workflow-run.d.ts +114 -0
- package/dist/workflow-run.js +144 -0
- package/dist/workspace/beneath.d.ts +19 -0
- package/dist/workspace/beneath.js +106 -0
- package/dist/workspace/computer-deps.d.ts +52 -5
- package/dist/workspace/computer-deps.js +154 -19
- package/dist/workspace/computer-for-claim.d.ts +19 -14
- package/dist/workspace/computer-for-claim.js +77 -16
- package/dist/workspace/computer-hold.d.ts +6 -1
- package/dist/workspace/computer-hold.js +6 -1
- package/dist/workspace/computer-janitor.d.ts +47 -0
- package/dist/workspace/computer-janitor.js +182 -0
- package/dist/workspace/computer-providers.d.ts +6 -2
- package/dist/workspace/computer-providers.js +1 -1
- package/dist/workspace/grep-worker.d.ts +5 -0
- package/dist/workspace/grep-worker.js +9 -6
- package/dist/workspace/index.d.ts +4 -3
- package/dist/workspace/index.js +4 -4
- package/dist/workspace/local.d.ts +11 -2
- package/dist/workspace/local.js +161 -43
- package/dist/workspace/resolve-computer.d.ts +50 -10
- package/dist/workspace/resolve-computer.js +46 -11
- package/dist/workspace/run-tools.d.ts +13 -31
- package/dist/workspace/run-tools.js +10 -27
- package/dist/workspace-paths.d.ts +0 -17
- package/dist/workspace-paths.js +1 -41
- package/dist/workspace.d.ts +0 -17
- package/dist/workspace.js +3 -99
- package/launcher/agentrun-serve +6 -33
- package/package.json +14 -14
- package/templates/README.md +9 -3
- package/templates/inbound-lead/agent.md +1 -1
- package/templates/kyb/agent.md +1 -1
- package/templates/market-monitor/agent.md +2 -2
- package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
- package/dist/app.d.ts +0 -5
- package/dist/app.js +0 -514
- package/dist/bound-files.d.ts +0 -4
- package/dist/bound-files.js +0 -164
- package/dist/bounds.d.ts +0 -26
- package/dist/bounds.js +0 -137
- package/dist/coding-tools.d.ts +0 -47
- package/dist/coding-tools.js +0 -189
- package/dist/computer-adb.d.ts +0 -12
- package/dist/computer-adb.js +0 -14
- package/dist/console/assets/index-35-7aeIZ.js +0 -519
- package/dist/console/assets/index-Cejbov-Y.css +0 -1
- package/dist/content-filter.d.ts +0 -7
- package/dist/content-filter.js +0 -23
- package/dist/disk.d.ts +0 -33
- package/dist/disk.js +0 -85
- package/dist/door-line.d.ts +0 -23
- package/dist/door-line.js +0 -83
- package/dist/grade.d.ts +0 -63
- package/dist/grade.js +0 -150
- package/dist/harness-app.d.ts +0 -69
- package/dist/harness-app.js +0 -1162
- package/dist/mcp-servers.d.ts +0 -269
- package/dist/mcp-servers.js +0 -456
- package/dist/packs.d.ts +0 -71
- package/dist/packs.js +0 -180
- package/dist/request-start.d.ts +0 -27
- package/dist/request-start.js +0 -381
- package/dist/run-box.d.ts +0 -205
- package/dist/run-box.js +0 -661
- package/dist/run-holder.d.ts +0 -52
- package/dist/run-holder.js +0 -139
- package/dist/runs.d.ts +0 -1200
- package/dist/runs.js +0 -4103
- package/dist/sealed-settings.d.ts +0 -60
- package/dist/sealed-settings.js +0 -178
- package/dist/served-only.d.ts +0 -5
- package/dist/served-only.js +0 -12
- package/dist/sessions.d.ts +0 -6
- package/dist/sessions.js +0 -109
- package/dist/workspace/computer-serves.d.ts +0 -12
- package/dist/workspace/computer-serves.js +0 -15
package/dist/runs.js
DELETED
|
@@ -1,4103 +0,0 @@
|
|
|
1
|
-
// Runs: each one a child process (`pi-durable-disk run` on `<data>/runs/<id>` with serve's app), pinned to a revision in
|
|
2
|
-
// the agent store. An agentic run is read live through the door its process serves on loopback; a workflow run is
|
|
3
|
-
// working while its process lives. Once the process has exited the run is read from its store, read-only, and carried
|
|
4
|
-
// back to the agent store (`carryBack`), and it is finished. A run whose process went before the run ended is opened
|
|
5
|
-
// again on its directory, and resumes from its store.
|
|
6
|
-
import { spawn } from "node:child_process";
|
|
7
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
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";
|
|
11
|
-
import { join } from "node:path";
|
|
12
|
-
import { fileURLToPath } from "node:url";
|
|
13
|
-
import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
14
|
-
import { processAlive } from "@parcha/agentrun-kernel/host";
|
|
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";
|
|
19
|
-
import { HARNESS_LOG_EVENT, harnessModelKeys, thinkingFor } from "./adapters.js";
|
|
20
|
-
import { runLink } from "./console-links.js";
|
|
21
|
-
import { harnessOfBody } from "./harness.js";
|
|
22
|
-
import { builtinHarness, harnessOf } from "./harness-table.js";
|
|
23
|
-
import { hostMemory, memoryFull, neverFits, runMibOf, runsMemoryMib } from "./host.js";
|
|
24
|
-
import { storeBusy, storeError, whenFree } from "./agents.js";
|
|
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";
|
|
30
|
-
import { KEPT_AUTOSTOP_MINUTES, keepWhenIdle, wakeBoxes } from "./daytona-api.js";
|
|
31
|
-
import { servedOnly, servedOnlyIds } from "./served-only.js";
|
|
32
|
-
import { LEARNING_LABEL, shortOf } from "./learning.js";
|
|
33
|
-
import { Hearing } from "./heard.js";
|
|
34
|
-
import { labelled, LearningRuns, reflecting, reflects, withLearning } from "./learning-run.js";
|
|
35
|
-
import { settleBox, sweepBoxes } from "./box/sweep.js";
|
|
36
|
-
import { rowPaths } from "./workspace-paths.js";
|
|
37
|
-
import { ASK_TOOL, toolingOf, workflowTools } from "./tools.js";
|
|
38
|
-
import { withDecisions } from "./decision-rows.js";
|
|
39
|
-
import { DECISION_KEY_FD_ENV, decisionKeysFor, providersNamed } from "./decisions.js";
|
|
40
|
-
import { ApiError, invalid, unsupported } from "./errors.js";
|
|
41
|
-
import { DOCUMENTS_ENV } from "./pdf-pages.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";
|
|
43
|
-
import { DEFAULT_MODEL_ENV, EFFORT_ENV, GATEWAY_KEY_ENV, hostModel, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, thinkingOf, withoutFaux, workflowNodes } from "./model.js";
|
|
44
|
-
import { llmAnswers, pausedIn, readNodeLog, RUN_PAUSED } from "./pause.js";
|
|
45
|
-
import { BUDGET_PAUSE, budgetPausedIn, capStoppedIn, clearBudgetPause, raiseFinishes, writeRaisedCap } from "./budget.js";
|
|
46
|
-
import { durationMs } from "./print.js";
|
|
47
|
-
import { handsParallel, keptFromBefore, keptVendor, planeFor, recheckPlane, relaunchPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
|
|
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";
|
|
50
|
-
import { ChangeClock, RowLog } from "./rows.js";
|
|
51
|
-
import { TOOL_KEYS } from "./tool-keys.js";
|
|
52
|
-
import { isObject } from "./validate.js";
|
|
53
|
-
import { RequestBounds } from "./bounds.js";
|
|
54
|
-
import { firstMessage } from "./run-manifest.js";
|
|
55
|
-
import { REFLECT_REQUEST, Turns } from "./turns.js";
|
|
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";
|
|
58
|
-
import { MIN_SECRET } from "./learn/secrets.js";
|
|
59
|
-
import { cutStrings, keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf } from "./key-refusal.js";
|
|
60
|
-
import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
|
|
61
|
-
import { BOX_KEYS, VM_PROVIDER } from "./boxes.js";
|
|
62
|
-
import { remotePlace, storedPlace } from "./place.js";
|
|
63
|
-
import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, sweepRunBoxes } from "./run-box.js";
|
|
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";
|
|
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.
|
|
79
|
-
export const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
|
|
80
|
-
const TERMINAL = new Set(["completed", "failed", "cancelled"]);
|
|
81
|
-
const RELEASED = new Set(["sleeping", "paused", "done", "failed"]);
|
|
82
|
-
/** How long an agentic run's process may finish its turn after SIGTERM, unless the server says otherwise. */
|
|
83
|
-
const DRAIN = "30s";
|
|
84
|
-
/** The run process's stderr, in its folder: a file, so the process outlives a server that stops without stopping it. */
|
|
85
|
-
const PROCESS_LOG = "process.log";
|
|
86
|
-
/** How long a request waits for a run's door: its process coming up, or a settle in progress. */
|
|
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;
|
|
94
|
-
/** The reducer's live "Run started" and "Run finished" rows: a turn's edges, which no store entry makes on any harness,
|
|
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. */
|
|
96
|
-
const QUIET = /:run:(start|end)$/;
|
|
97
|
-
const RETRY_CODES = ["OPENING", "PARKING", "RELEASED"];
|
|
98
|
-
/** How often one server opens a run again whose process went before the run ended, before it fails the run. */
|
|
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 };
|
|
135
|
-
/** How often a run's end that the agent store refused is written again. */
|
|
136
|
-
const SETTLE_RETRY_MS = 30_000;
|
|
137
|
-
/** How a run ended in the store, as its status: the store's `stopped` is v2's `cancelled`, and an escalated workflow
|
|
138
|
-
* completed its work and waits for a person (its `review`), which is not a failure. */
|
|
139
|
-
const STATUS_OF = { completed: "completed", failed: "failed", escalated: "completed", stopped: "cancelled" };
|
|
140
|
-
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
141
|
-
// A run's process that exited and was never reaped (a zombie, under a PID 1 that does not reap) is not alive.
|
|
142
|
-
const alive = processAlive;
|
|
143
|
-
/** Waits between carry backs that found the store busy: each attempt itself waits 5 s for the store's lock. */
|
|
144
|
-
const CARRY_BACK_RETRIES_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
|
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
|
|
146
|
-
* store's exclusive lock until it exits. */
|
|
147
|
-
const EXIT_AFTER_RELEASE_MS = 30_000;
|
|
148
|
-
const warn = (runId, text) => void process.stderr.write(`agentrun-serve: run ${runId}: ${text}\n`);
|
|
149
|
-
/** How long serve's calls on a run's box (its destroy, the start's sweep) may take. */
|
|
150
|
-
const BOX_CALL_MS = 60_000;
|
|
151
|
-
const boxContext = (ms = BOX_CALL_MS) => withAbortSignal(AbortSignal.timeout(ms), BACKGROUND_CONTEXT);
|
|
152
|
-
/** How long a remote box's making and seed, or one pull of its work/, may take: a sandbox's start, then the copy. */
|
|
153
|
-
const REMOTE_SYNC_MS = 15 * 60_000;
|
|
154
|
-
/** How long a read of a run's files waits for the pull its turn's end began. */
|
|
155
|
-
const PULL_WAIT_MS = 120_000;
|
|
156
|
-
/** A run's end that waits for its remote box's last pull: its settle is tried again until the pull lands. */
|
|
157
|
-
class PullPending extends Error {
|
|
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
|
-
}
|
|
163
|
-
/** Run directory `dir`'s own door token, made now (mode 0600, never through a link) when it has none. */
|
|
164
|
-
function ensureRunDoorToken(dir) {
|
|
165
|
-
const held = runDoorToken(dir);
|
|
166
|
-
if (held)
|
|
167
|
-
return held;
|
|
168
|
-
const token = `ar_door_${randomBytes(24).toString("base64url")}`;
|
|
169
|
-
try {
|
|
170
|
-
writeFileSync(join(dir, RUN_DOOR_TOKEN), `${token}\n`, { mode: 0o600, flag: "wx" });
|
|
171
|
-
}
|
|
172
|
-
catch (error) {
|
|
173
|
-
// Made meanwhile: that one is the run's.
|
|
174
|
-
if (error.code !== "EEXIST")
|
|
175
|
-
throw error;
|
|
176
|
-
const made = runDoorToken(dir);
|
|
177
|
-
if (!made)
|
|
178
|
-
throw new Error(`the run's door token at ${RUN_DOOR_TOKEN} is not one`);
|
|
179
|
-
return made;
|
|
180
|
-
}
|
|
181
|
-
return token;
|
|
182
|
-
}
|
|
183
|
-
const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
184
|
-
const isLoopback = (host) => host === "localhost" || host === "[::1]" || host === "::1" || /^127\./.test(host);
|
|
185
|
-
/** How a workflow run's workflow ended, as its app wrote it in the run's final status: absent until it ended. */
|
|
186
|
-
function workflowEnding(record) {
|
|
187
|
-
const detail = isObject(record?.detail) ? record.detail : undefined;
|
|
188
|
-
if (!RELEASED.has(String(record?.status)) || !["complete", "escalated", "refused", "stopped"].includes(String(detail?.workflow)))
|
|
189
|
-
return undefined;
|
|
190
|
-
return { status: detail.workflow, ...(typeof detail.code === "string" ? { code: detail.code } : {}), ...(typeof detail.message === "string" ? { message: detail.message } : {}) };
|
|
191
|
-
}
|
|
192
|
-
/** `review` at the run's saved end `endedAt`, so review.at and ended_at are one time. */
|
|
193
|
-
const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
|
|
194
|
-
/** A failed run's error from its row and serve.json: its own, else the row's summary. */
|
|
195
|
-
const errorOfRow = (row, meta) => ({ code: meta?.error?.code ?? "run_failed", message: meta?.error?.message ?? row.summary ?? "The run failed.", retryable: false, ...(meta?.error?.details ? { details: meta.error.details } : {}) });
|
|
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
|
|
197
|
-
* reviews were kept) the row's summary; null for every other run. */
|
|
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). */
|
|
200
|
-
/** A value's sha256, of its JSON. */
|
|
201
|
-
const digestOf = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
|
|
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
|
-
};
|
|
211
|
-
/** Notes the messages the run's turns took and how each turn ended, from `entries` (its root's), `submissions` (pi's
|
|
212
|
-
* input submissions) and a reconnect's `snapshot` of them (the door's `inputs`, the run's whole state of them), and the
|
|
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
|
|
214
|
-
* them, its TURN_END and its settlement included, opens, closes or answers one of the run's messages. */
|
|
215
|
-
function noteTurns(run, entries, submissions = [], snapshot) {
|
|
216
|
-
for (const value of entries) {
|
|
217
|
-
if (!isObject(value) || typeof value.id !== "number")
|
|
218
|
-
continue;
|
|
219
|
-
run.lastEntry = Math.max(run.lastEntry ?? 0, value.id);
|
|
220
|
-
// A refusal for room's own start mark: what the cap counted as taken, and the least the request needed.
|
|
221
|
-
const data = value.kind === REQUEST_STARTED && isObject(value.data) && value.data[CAP_REFUSED_FIELD] === true ? value.data : undefined;
|
|
222
|
-
if (data)
|
|
223
|
-
run.capMark = value.id;
|
|
224
|
-
if (data)
|
|
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);
|
|
231
|
-
// The end-of-run turn's assistant messages, whole, by entry: what the turn answered, whose notes learning reads
|
|
232
|
-
// (learning-run.ts). The ledger skips them; this is their only reader here.
|
|
233
|
-
if (value.kind === "pi.assistant" && reflects(run.meta.reflect, value.id) && Array.isArray(value.model) && isObject(value.model[0])) {
|
|
234
|
-
const content = value.model[0].content;
|
|
235
|
-
(run.turnText ??= new Map()).set(value.id, typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => isObject(b) && b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim() : "");
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
const reflect = (id) => reflects(run.meta.reflect, id);
|
|
239
|
-
run.turns.note(entries, submissions, reflect);
|
|
240
|
-
(run.bounds ??= new RequestBounds()).note(entries, run.meta.max_cost_usd);
|
|
241
|
-
if (snapshot)
|
|
242
|
-
run.turns.snapshot(snapshot, reflect);
|
|
243
|
-
}
|
|
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));
|
|
258
|
-
};
|
|
259
|
-
// browserPending moves to run-view.ts (the run's served view), taking the ask as input; imported above.
|
|
260
|
-
/** Notes the tool calls that wait for approval in `entries` (the run's stored entries), and those whose answer its process
|
|
261
|
-
* acted on. */
|
|
262
|
-
function noteApprovals(run, entries) {
|
|
263
|
-
for (const value of entries) {
|
|
264
|
-
if (!isObject(value) || value.kind !== APPROVAL_ENTRY || !isObject(value.data) || typeof value.data.id !== "string")
|
|
265
|
-
continue;
|
|
266
|
-
const data = value.data;
|
|
267
|
-
run.approvals ??= new Map();
|
|
268
|
-
const known = run.approvals.get(data.id);
|
|
269
|
-
if (data.phase === "requested" && !known)
|
|
270
|
-
run.approvals.set(data.id, { id: data.id, tool: String(data.tool), call_id: String(data.call_id), args_json: "args" in data ? (JSON.stringify(data.args ?? {}) ?? "{}") : String(data.args_preview ?? ""), requested_at: String(data.requested_at), ...(typeof data.price === "number" || data.price === "not metered" ? { price: data.price } : {}) });
|
|
271
|
-
else if (data.phase === "resolved" && known)
|
|
272
|
-
known.resolved = true;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
// waitingApproval and shownArgs move to run-view.ts (the run's served view), imported above.
|
|
276
|
-
/** `entries` with the gate's resume messages (RESUME_PREFIX) redacted whole with `redact`, before the timeline cuts
|
|
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. */
|
|
279
|
-
function redactGateMessages(entries, redact) {
|
|
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) } };
|
|
284
|
-
const first = isObject(entry) && Array.isArray(entry.model) ? entry.model[0] : undefined;
|
|
285
|
-
if (!isObject(first) || first.role !== "user")
|
|
286
|
-
return entry;
|
|
287
|
-
const content = first.content;
|
|
288
|
-
const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((block) => (isObject(block) && block.type === "text" ? String(block.text ?? "") : "")).join("") : "";
|
|
289
|
-
if (!text.startsWith(RESUME_PREFIX))
|
|
290
|
-
return entry;
|
|
291
|
-
const redacted = typeof content === "string" ? redact(content) : content.map((block) => (isObject(block) && block.type === "text" && typeof block.text === "string" ? { ...block, text: redact(block.text) } : block));
|
|
292
|
-
return { ...entry, model: [{ ...first, content: redacted }, ...entry.model.slice(1)] };
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
// approvalOf and actingOn move to run-view.ts (the run's served view), imported above.
|
|
296
|
-
/** The row after each tool call that waited for approval, beside its result's row. Its arguments are redacted whole
|
|
297
|
-
* (`redact`, the Timeline's own: no held key), before any cut. */
|
|
298
|
-
function withApprovals(given, run, redact) {
|
|
299
|
-
if (!run.approvals?.size)
|
|
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);
|
|
304
|
-
const byCall = new Map([...run.approvals.values()].map((approval) => [approval.call_id, approval]));
|
|
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] : []; }));
|
|
326
|
-
return rows.flatMap((row) => {
|
|
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;
|
|
348
|
-
if (!approval)
|
|
349
|
-
return [row];
|
|
350
|
-
const args = shownArgs(approval, redact);
|
|
351
|
-
const said = run.meta.approvals?.[approval.id]?.decision;
|
|
352
|
-
const byMessage = run.meta.approvals?.[approval.id]?.by === "message";
|
|
353
|
-
const head = approval === waiting ? "Waiting for your approval" : byMessage ? "Declined by your message" : said === "withdrawn" ? "Withdrawn when the run was stopped" : said === "canceled" ? "Withdrawn when the run was cancelled" : "Asked your approval";
|
|
354
|
-
const summary = `${head}: ${approval.tool} ${clip(args, 400)}`;
|
|
355
|
-
// A message that would have declined the call, which a stop or a cancel overrode: its words were never sent, and
|
|
356
|
-
// the row says so (the record keeps them whole).
|
|
357
|
-
const dropped = run.meta.approvals?.[approval.id]?.superseded;
|
|
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;
|
|
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 }];
|
|
360
|
-
});
|
|
361
|
-
}
|
|
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.
|
|
400
|
-
/** How many tries a raised run's follow-up gets, and the waits between them, before the run fails with why. */
|
|
401
|
-
const CONTINUE_TRIES = 3;
|
|
402
|
-
const CONTINUE_RETRY_MS = [1_000, 3_000];
|
|
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)
|
|
412
|
-
return undefined;
|
|
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 };
|
|
418
|
-
};
|
|
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;
|
|
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
|
|
433
|
-
* last meaningful row is its answer when that row is one, a final answer's or a text row's. */
|
|
434
|
-
const importAnswerOf = (rows) => {
|
|
435
|
-
const last = meaningful(rows);
|
|
436
|
-
return last?.kind === "final_answer" || last?.kind === "text_block" ? last : undefined;
|
|
437
|
-
};
|
|
438
|
-
/** The cost reads a run's views show move to run-view.ts (over the run's rows), unchanged. */
|
|
439
|
-
/** What a run's meta kept of its cost so far at its end, when it is well formed. */
|
|
440
|
-
const soFarOfMeta = (meta) => {
|
|
441
|
-
const kept = meta?.cost_so_far;
|
|
442
|
-
return kept && typeof kept.so_far_usd === "number" && Number.isFinite(kept.so_far_usd) && Number.isInteger(kept.unpriced) && kept.unpriced > 0 ? { so_far_usd: kept.so_far_usd, unpriced: kept.unpriced } : undefined;
|
|
443
|
-
};
|
|
444
|
-
/** The whole text of the run's newest answer with text, paid for: an assistant message's, else its newest answer row's. */
|
|
445
|
-
const lastAnswer = (run) => run.turns.newestText ?? run.rows.findLast((r) => r.kind === "final_answer" && r.agent_label !== LEARNING_LABEL)?.text ?? null;
|
|
446
|
-
/** A row's store entry, from its id (`<conversation>:<entry>[:...]`). */
|
|
447
|
-
const entryOfRow = (id) => Number(id.split(":")[1]);
|
|
448
|
-
/** The answer of a run that completed: the whole text of the entry its turn's end names, "" when that turn showed no text,
|
|
449
|
-
* never an earlier turn's. Without such an end (a run still working, a workflow, a store an older server wrote): the
|
|
450
|
-
* newest answer it gave, whole (lastAnswer); an import's, its last row's when that row is its answer. */
|
|
451
|
-
function answerOfRun(run) {
|
|
452
|
-
const end = run.turns.end();
|
|
453
|
-
if (end?.status === "answered") {
|
|
454
|
-
if (end.answer === null)
|
|
455
|
-
return "";
|
|
456
|
-
// The entry's row when its text was not read here: a final answer's, or a text row's (a stop at the length limit).
|
|
457
|
-
return run.turns.text(end.answer) ?? run.rows.findLast((r) => (r.kind === "final_answer" || r.kind === "text_block") && entryOfRow(r.id) === end.answer)?.text ?? "";
|
|
458
|
-
}
|
|
459
|
-
const imported = run.imported ? importAnswerOf(run.rows) : undefined;
|
|
460
|
-
return lastAnswer(run) ?? imported?.text ?? imported?.summary ?? null;
|
|
461
|
-
}
|
|
462
|
-
// usersOf moves to run-view.ts (the run's served view), imported above.
|
|
463
|
-
const lastUserMessage = (rows) => rows.findLast(isMessageRow)?.id;
|
|
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).
|
|
466
|
-
/** A process by its pid and start ticks (Linux /proc; the pid alone elsewhere): a pid used again is another process. */
|
|
467
|
-
function processIdentity(pid) {
|
|
468
|
-
if (pid === undefined)
|
|
469
|
-
return undefined;
|
|
470
|
-
try {
|
|
471
|
-
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
472
|
-
return `${pid}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
|
|
473
|
-
}
|
|
474
|
-
catch {
|
|
475
|
-
return String(pid);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
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.
|
|
492
|
-
/** What a stop keeps of where the run stands: the person's last message, by its id, or the place before any. */
|
|
493
|
-
export const stopMark = (rows) => ({ stopped_at: lastUserMessage(rows) ?? `${ROOT_CONVERSATION_ID}:0` });
|
|
494
|
-
/** The rows a snapshot that no longer holds them leaves served: those committed entries made. A row any connection
|
|
495
|
-
* showed live is not one (`live` holds them for the run), so a live row that ended while the door was away goes. */
|
|
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()) {
|
|
500
|
-
for (const row of rows)
|
|
501
|
-
if (isLive(row.id))
|
|
502
|
-
live.add(row.id);
|
|
503
|
-
return (id) => !madeHere.has(id) && !live.has(id) && !isLive(id);
|
|
504
|
-
}
|
|
505
|
-
/** A wait's mark: the stop it stands at, while that stop holds, else its newest row (the question it waits on). */
|
|
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
|
-
};
|
|
514
|
-
/** Waits for `work`, or until `deadline` (ms since the epoch), whichever comes first. */
|
|
515
|
-
async function untilDeadline(work, deadline) {
|
|
516
|
-
let timer;
|
|
517
|
-
await Promise.race([work, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))))]);
|
|
518
|
-
clearTimeout(timer);
|
|
519
|
-
}
|
|
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. */
|
|
525
|
-
export function statusOf(run) {
|
|
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 };
|
|
542
|
-
}
|
|
543
|
-
/** The trigger a serve.json says started its run, as read back: `{id, firing_key}`, or null. */
|
|
544
|
-
function triggerOf(meta) {
|
|
545
|
-
const trigger = meta?.trigger;
|
|
546
|
-
return isObject(trigger) && typeof trigger.id === "string" && typeof trigger.firing_key === "string" ? { id: trigger.id, firing_key: trigger.firing_key } : null;
|
|
547
|
-
}
|
|
548
|
-
/** Why a message that may not answer a person's question is not sent. */
|
|
549
|
-
export const WAITS_ON_A_PERSON = "The run is waiting on a person.";
|
|
550
|
-
/** The server's own secrets, which a run's process never gets: the API token, by name or by value, the seal key
|
|
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]);
|
|
554
|
-
/** The secrets a run's process is handed over its pipe (secrets.ts): every one but the server's own and the decision
|
|
555
|
-
* keys, which go on their own descriptor. */
|
|
556
|
-
export const RUN_SECRETS = SECRET_NAMES.filter((name) => !SERVER_ONLY.has(name) && !DECISION_KEYS.includes(name));
|
|
557
|
-
/** The fields a run gets only when its revision names what they unlock: a `tool` key's. Any other kind's (a model key's)
|
|
558
|
-
* is the model's to need, as every model key is. */
|
|
559
|
-
const scopedOf = (rows) => rows.filter((row) => row.kind === "tool").flatMap((row) => row.fields);
|
|
560
|
-
/** The model keys: every key of pi-ai's providers (model.ts' PROVIDER_KEYS) and the gateway's. A run gets those its model
|
|
561
|
-
* needs and no other (secretsFor). A workflow's decision keys, OpenRouter's among them, go on its decision descriptor
|
|
562
|
-
* (decisions.ts), whatever its model. */
|
|
563
|
-
const MODEL_KEYS = [...new Set([...Object.values(PROVIDER_KEYS).flat(), GATEWAY_KEY_ENV])];
|
|
564
|
-
/** What a run whose revision was not read is handed: no tool key, and no model key. */
|
|
565
|
-
const NO_TOOL_KEYS = RUN_SECRETS.filter((name) => !scopedOf(TOOL_KEYS).includes(name) && !MODEL_KEYS.includes(name));
|
|
566
|
-
/** `revision`'s RunNeeds. */
|
|
567
|
-
export async function needsOf(revision) {
|
|
568
|
-
const workflow = revision.kind === "workflow" ? revision.body.workflow : undefined;
|
|
569
|
-
const nodes = workflow ? workflowNodes(workflow, (await import("@parcha/agentrun-dsl")).inspectWorkflow(workflow)) : undefined;
|
|
570
|
-
const bound = nodes && workflowTools(nodes);
|
|
571
|
-
return {
|
|
572
|
-
harness: harnessOfBody(revision.body),
|
|
573
|
-
...(revision.kind === "agentic" && revision.body.model ? { model: revision.body.model } : {}),
|
|
574
|
-
tools: bound ? [...bound.nodes, ...bound.calls] : [...(revision.body.tools ?? [])],
|
|
575
|
-
...(nodes ? { tiers: llmTiers(nodes, nodeTiers(nodes)) } : {}),
|
|
576
|
-
decisionProviders: nodes ? providersNamed(nodes) : [],
|
|
577
|
-
};
|
|
578
|
-
}
|
|
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
|
|
580
|
-
* `tool` row of `rows` (TOOL_KEYS) that unlocks none of the tools the run binds; and but each model key its model does
|
|
581
|
-
* not need, from the host's model settings and the keys in `env`: a pi run's, its models' providers' keys or the
|
|
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
|
|
584
|
-
* saved with no restart counts at the next. */
|
|
585
|
-
export function keysFor(needs, env, rows = TOOL_KEYS) {
|
|
586
|
-
const named = new Set(needs.tools);
|
|
587
|
-
const unlocked = new Set(rows.filter((row) => row.unlocks.some((name) => named.has(name))).flatMap((row) => row.fields));
|
|
588
|
-
const scoped = scopedOf(rows);
|
|
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));
|
|
591
|
-
return RUN_SECRETS.filter((name) => (!scoped.includes(name) || unlocked.has(name)) && (!MODEL_KEYS.includes(name) || model.has(name)));
|
|
592
|
-
}
|
|
593
|
-
/** The secrets a run of `revision` is handed with the keys `env` holds (needsOf, then keysFor). */
|
|
594
|
-
export async function secretsFor(revision, rows = TOOL_KEYS, env = process.env) {
|
|
595
|
-
return keysFor(await needsOf(revision), env, rows);
|
|
596
|
-
}
|
|
597
|
-
/** The decision providers a run of `revision` needs keys for (needsOf). Its web tools' need, Parallel's where one
|
|
598
|
-
* resolves to Parallel, is its tool plane's (tool-plane.ts' handsParallel), read at each launch. */
|
|
599
|
-
export async function decisionProvidersFor(revision) {
|
|
600
|
-
return (await needsOf(revision)).decisionProviders;
|
|
601
|
-
}
|
|
602
|
-
/** The module a run's process preloads (`--import`) to read its pipe before anything else; app.ts gets the same instance. */
|
|
603
|
-
const SECRETS_MODULE = new URL("./secrets.js", import.meta.url).href;
|
|
604
|
-
/** A run's process's environment: no secret in it (they go over its pipe), nor the token by value; the AGENT_MODEL
|
|
605
|
-
* variables and the rest pass, and the door token goes by file. A test hook's name passes never (withoutFaux): the run
|
|
606
|
-
* gets one only from startServe's options. */
|
|
607
|
-
export const childEnv = (env, token) => Object.fromEntries(Object.entries(withoutSecrets(withoutFaux(env))).filter(([, value]) => value !== token));
|
|
608
|
-
/** One line of the run process's log in words: pi-durable-disk writes JSON lines (`{at, event, message, ...}`). */
|
|
609
|
-
function inWords(line) {
|
|
610
|
-
let value;
|
|
611
|
-
try {
|
|
612
|
-
value = JSON.parse(line);
|
|
613
|
-
}
|
|
614
|
-
catch {
|
|
615
|
-
return line;
|
|
616
|
-
}
|
|
617
|
-
if (!isObject(value))
|
|
618
|
-
return line;
|
|
619
|
-
const text = (key) => (typeof value[key] === "string" ? value[key] : undefined);
|
|
620
|
-
return [text("event"), text("message") ?? text("error")].filter(Boolean).join(": ") || "the run's process left no message";
|
|
621
|
-
}
|
|
622
|
-
/** The line of the run process's log a failure's message is made of: its last, past any harness's own lines (a proxy's
|
|
623
|
-
* refusal just before a crash says nothing of why the process went). */
|
|
624
|
-
export function failureLine(log) {
|
|
625
|
-
const lines = log.trim().split("\n");
|
|
626
|
-
return ownLine(lines) ?? lines.at(-1) ?? "";
|
|
627
|
-
}
|
|
628
|
-
/** The last of `lines` that is not a harness's own line, if any. */
|
|
629
|
-
function ownLine(lines) {
|
|
630
|
-
return lines.findLast((line) => {
|
|
631
|
-
if (line.trim() === "")
|
|
632
|
-
return false;
|
|
633
|
-
try {
|
|
634
|
-
return JSON.parse(line)?.event !== HARNESS_LOG_EVENT;
|
|
635
|
-
}
|
|
636
|
-
catch {
|
|
637
|
-
return true;
|
|
638
|
-
}
|
|
639
|
-
});
|
|
640
|
-
}
|
|
641
|
-
/** How far back from its end a failure's message is looked for in the run's log, in steps of LOG_STEP. */
|
|
642
|
-
const LOG_STEP = 4096;
|
|
643
|
-
const LOG_REACH = 1 << 20;
|
|
644
|
-
/** The last line of the run process's log, in words, for a failure's message. */
|
|
645
|
-
export async function lastLogLine(run) {
|
|
646
|
-
const file = await openFile(join(run.dir, PROCESS_LOG)).catch(() => null);
|
|
647
|
-
if (!file)
|
|
648
|
-
return "";
|
|
649
|
-
try {
|
|
650
|
-
// Backward until a whole line is the process's own: harness lines after it may run past any one read, and a read
|
|
651
|
-
// that starts inside a line has only its tail, which is no line at all. Each step looks only at the lines it
|
|
652
|
-
// completes; what was read is joined once, and failureLine, the one rule, picks the line from it.
|
|
653
|
-
const { size } = await file.stat();
|
|
654
|
-
const chunks = [];
|
|
655
|
-
let start = size;
|
|
656
|
-
// The oldest line read so far, torn at the read's start unless that is the file's start.
|
|
657
|
-
let head = Buffer.alloc(0);
|
|
658
|
-
while (start > 0 && size - start < LOG_REACH) {
|
|
659
|
-
const from = Math.max(0, start - LOG_STEP);
|
|
660
|
-
const { buffer } = await file.read(Buffer.alloc(start - from), 0, start - from, from);
|
|
661
|
-
start = from;
|
|
662
|
-
chunks.unshift(buffer);
|
|
663
|
-
const newline = buffer.indexOf(0x0a);
|
|
664
|
-
const completed = start === 0 ? Buffer.concat([buffer, head]) : newline < 0 ? Buffer.alloc(0) : Buffer.concat([buffer.subarray(newline + 1), head]);
|
|
665
|
-
head = start === 0 ? Buffer.alloc(0) : newline < 0 ? Buffer.concat([buffer, head]) : buffer.subarray(0, newline);
|
|
666
|
-
if (ownLine(completed.toString("utf8").split("\n")) !== undefined)
|
|
667
|
-
break;
|
|
668
|
-
}
|
|
669
|
-
return clip(inWords(failureLine(Buffer.concat(chunks).subarray(head.length).toString("utf8"))), 300);
|
|
670
|
-
}
|
|
671
|
-
finally {
|
|
672
|
-
await file.close();
|
|
673
|
-
}
|
|
674
|
-
}
|
|
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. */
|
|
677
|
-
export const runsTestHooks = {};
|
|
678
|
-
export class Runs {
|
|
679
|
-
options;
|
|
680
|
-
runs = new Map();
|
|
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;
|
|
692
|
-
/** What decides the secrets each revision's runs are handed (needsOf), by revision id: read once, from the revision the
|
|
693
|
-
* run is pinned to, never from a request. The keys themselves are read at each launch (keysFor). */
|
|
694
|
-
needs = new Map();
|
|
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();
|
|
700
|
-
/** The hosts this server's next remote box asks for: the setting's, until the provider cannot keep a list here, then none. */
|
|
701
|
-
remoteAllow;
|
|
702
|
-
clock = new ChangeClock();
|
|
703
|
-
cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("@parcha/pi-durable-disk")));
|
|
704
|
-
app = fileURLToPath(new URL("./app.js", import.meta.url));
|
|
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;
|
|
710
|
-
/** Set once `close` is done: the store is closed, so nothing settles after it. */
|
|
711
|
-
closed = false;
|
|
712
|
-
/** Runs past the cap's check whose process is not started yet. */
|
|
713
|
-
starting = 0;
|
|
714
|
-
/** The memory the starts counted in `starting` reserve, in MiB. */
|
|
715
|
-
startingMib = 0;
|
|
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`). */
|
|
718
|
-
memory = hostMemory();
|
|
719
|
-
/** The start sweep of the boxes runs left: once, before any run opens a box (sweepOnce). */
|
|
720
|
-
swept;
|
|
721
|
-
/** The runs' learning (learning-run.ts): a step this file calls as a run starts, ends, settles, opens again and is
|
|
722
|
-
* recovered, handed what it moves of a run. */
|
|
723
|
-
learning;
|
|
724
|
-
/** When this server took the data root (one server a root): a run started since is its own, never one to recover. */
|
|
725
|
-
bootedAt = new Date().toISOString();
|
|
726
|
-
constructor(options) {
|
|
727
|
-
this.options = options;
|
|
728
|
-
this.learning = new LearningRuns(options, {
|
|
729
|
-
held: (id) => this.runs.get(id),
|
|
730
|
-
get: (id) => this.get(id),
|
|
731
|
-
live: (run) => this.live(run),
|
|
732
|
-
toLiveDoor: (run, path, body, turnOrigin) => this.toLiveDoor(run, path, body, turnOrigin),
|
|
733
|
-
toDoor: (run, path, body) => this.toDoor(run, path, body),
|
|
734
|
-
abortTurn: (run) => this.abortTurn(run),
|
|
735
|
-
terminate: (run) => this.terminate(run),
|
|
736
|
-
mark: (run) => this.mark(run),
|
|
737
|
-
show: (run) => this.show(run),
|
|
738
|
-
save: (run) => this.saveMeta(run),
|
|
739
|
-
costOf,
|
|
740
|
-
fauxEnv: () => this.fauxEnv(),
|
|
741
|
-
});
|
|
742
|
-
}
|
|
743
|
-
/** A test's seam (startServe's `beforeAbort`): awaited by a stop between its mark and its abort, so a test can hold a
|
|
744
|
-
* stop in flight there. */
|
|
745
|
-
beforeAbort;
|
|
746
|
-
/** A test's seam (startServe's `beforeReopenLaunch`): awaited by a reopen after the run reads open again and before its
|
|
747
|
-
* launch, so a test can hold a reopen there. */
|
|
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;
|
|
754
|
-
/** A test's seam (startServe's `onRunLoad`): told each run read in from its store, its timeline with it. */
|
|
755
|
-
onRunLoad;
|
|
756
|
-
/** A test's seam (startServe's `beforeSubmit`): awaited by a message before it goes to the run's door. */
|
|
757
|
-
beforeSubmit;
|
|
758
|
-
/** A test's seam (startServe's `beforeMetaSave`): awaited before a run's serve.json is written; one that throws fails
|
|
759
|
-
* the write, as a full disk would. */
|
|
760
|
-
beforeMetaSave;
|
|
761
|
-
/** A test's seam (startServe's `messageOrigin`): the origin a message sent through the messages route carries. */
|
|
762
|
-
messageOrigin;
|
|
763
|
-
get store() {
|
|
764
|
-
return this.options.agents.store;
|
|
765
|
-
}
|
|
766
|
-
// ---- reading --------------------------------------------------------------------------------------------------------
|
|
767
|
-
/** Run `id` when this process holds it, never read from disk. */
|
|
768
|
-
held(id) {
|
|
769
|
-
return this.runs.get(id);
|
|
770
|
-
}
|
|
771
|
-
/** Run `id`, read from the agent store the first time this process sees it. */
|
|
772
|
-
async get(id) {
|
|
773
|
-
const known = this.runs.get(id);
|
|
774
|
-
if (known)
|
|
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;
|
|
780
|
-
const row = await this.options.agents.request(() => this.store.readRun(id));
|
|
781
|
-
return row ? this.adopt(row) : null;
|
|
782
|
-
}
|
|
783
|
-
/** One Run per run id, however many requests ask for it at once. */
|
|
784
|
-
adopt(row) {
|
|
785
|
-
const known = this.runs.get(row.id);
|
|
786
|
-
if (known)
|
|
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));
|
|
792
|
-
let pending = this.adopting.get(row.id);
|
|
793
|
-
if (!pending) {
|
|
794
|
-
pending = this.load(row).finally(() => this.adopting.delete(row.id));
|
|
795
|
-
this.adopting.set(row.id, pending);
|
|
796
|
-
}
|
|
797
|
-
return pending;
|
|
798
|
-
}
|
|
799
|
-
async load(row) {
|
|
800
|
-
this.onRunLoad?.(row.id);
|
|
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));
|
|
806
|
-
const trigger = triggerOf(stored);
|
|
807
|
-
const meta = {
|
|
808
|
-
title: typeof stored?.title === "string" ? stored.title : "",
|
|
809
|
-
created_at: typeof stored?.created_at === "string" ? stored.created_at : row.startedAt,
|
|
810
|
-
...(isObject(stored?.input) ? { input: stored.input } : {}),
|
|
811
|
-
...(typeof stored?.effort === "string" ? { effort: stored.effort } : {}),
|
|
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 } : {}),
|
|
814
|
-
// Each raise of its cap, and the follow-up a stopped server never sent, which the next sends (resumeRaised).
|
|
815
|
-
...(Array.isArray(stored?.cap_raised) ? { cap_raised: stored.cap_raised } : {}),
|
|
816
|
-
...(isObject(stored?.cap_continue) ? { cap_continue: stored.cap_continue } : {}),
|
|
817
|
-
...(stored?.error ? { error: stored.error } : {}),
|
|
818
|
-
...(stored && "output" in stored ? { output: stored.output } : {}),
|
|
819
|
-
...(isObject(stored?.review) ? { review: stored.review } : {}),
|
|
820
|
-
...(typeof stored?.stopped_at === "string" ? { stopped_at: stored.stopped_at } : {}),
|
|
821
|
-
...(typeof stored?.stopped_after === "number" ? { stopped_after: stored.stopped_after } : {}),
|
|
822
|
-
...(isObject(stored?.launch_thinking) ? { launch_thinking: stored.launch_thinking } : {}),
|
|
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) } : {}),
|
|
826
|
-
...(stored?.place ? { place: storedPlace(stored.place) } : {}),
|
|
827
|
-
...(isObject(stored?.learning) ? { learning: stored.learning } : {}),
|
|
828
|
-
...(isObject(stored?.reflect) ? { reflect: stored.reflect } : {}),
|
|
829
|
-
...(isObject(stored?.approvals) ? { approvals: stored.approvals } : {}),
|
|
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) } : {}),
|
|
834
|
-
};
|
|
835
|
-
// A turn's origin a server before this one set is not known to be the turn running now: it goes.
|
|
836
|
-
await rm(join(dir, TURN_ORIGIN_FILE), { force: true }).catch(() => undefined);
|
|
837
|
-
// A seed copy a server went down during is taken back before anything holds the run: its relaunch, a settle, a
|
|
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.
|
|
840
|
-
if (stored)
|
|
841
|
-
await this.learning.onLoad(row, dir, meta, () => writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`));
|
|
842
|
-
const known = await this.options.agents.revision(row.agent, row.revision);
|
|
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);
|
|
849
|
-
this.runs.set(row.id, run);
|
|
850
|
-
run.launching = existsSync(join(dir, RUN_LAUNCHING));
|
|
851
|
-
run.notSetUp = row.state === "running" && !isObject(stored?.input);
|
|
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);
|
|
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.
|
|
856
|
-
if (row.state !== "running")
|
|
857
|
-
run.outcome = STATUS_OF[row.state];
|
|
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)
|
|
900
|
-
await this.storeWhenFree(run);
|
|
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);
|
|
904
|
-
run.endedAt = row.endedAt;
|
|
905
|
-
// An ended run the store kept no cost for has an unknown cost, never $0.
|
|
906
|
-
run.costUsd = row.costUsd ?? null;
|
|
907
|
-
// A workflow run's decisions' cost too: an unknown one keeps the run's unknown after a restart. Unread, it is unknown.
|
|
908
|
-
if (run.kind === "workflow")
|
|
909
|
-
await this.readDecisionCost(run).catch(() => void (run.decisionCost = null));
|
|
910
|
-
if (row.importedFrom)
|
|
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.
|
|
913
|
-
if (run.outcome === "failed")
|
|
914
|
-
run.error = run.meta.unshown ? { code: "run_failed", message: WITHHELD_SIGN_IN, retryable: false } : errorOfRow(row, meta);
|
|
915
|
-
run.settled = true;
|
|
916
|
-
}
|
|
917
|
-
else {
|
|
918
|
-
// A cancel a server took and could not carry back before it went: its mark is written first (cancel()), so it is
|
|
919
|
-
// the run's end, as it was from its 202 on, whatever the turn it cut reads.
|
|
920
|
-
if (run.kind === "agentic" && existsSync(join(dir, RUN_CANCELLED))) {
|
|
921
|
-
run.cancel = true;
|
|
922
|
-
run.finishing = "cancelled";
|
|
923
|
-
}
|
|
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) {
|
|
955
|
-
// A server that died between saving a stop and its abort reaching the run leaves the turn working.
|
|
956
|
-
run.finishStop = run.meta.stopped_at !== undefined || run.meta.stopped_after !== undefined;
|
|
957
|
-
this.adoptProcess(run, adopted);
|
|
958
|
-
// Its cancel's SIGTERM may never have gone: it is let go now, its turn aborted first.
|
|
959
|
-
if (run.cancel)
|
|
960
|
-
void this.abortTurn(run).then(() => this.terminate(run));
|
|
961
|
-
}
|
|
962
|
-
// One a server left in its end-of-run turn finishes with its job's outcome, and its turn, when its process lives,
|
|
963
|
-
// is asked again (learning-run.ts).
|
|
964
|
-
this.learning.onAdopt(run, lives);
|
|
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));
|
|
970
|
-
this.refresh(run);
|
|
971
|
-
return run;
|
|
972
|
-
}
|
|
973
|
-
blank(row, dir, meta, version, harness, tooling, revision) {
|
|
974
|
-
return {
|
|
975
|
-
id: row.id, agentId: row.agent, kind: row.kind, revision: row.revision, version, dir, meta, log: new RowLog(this.clock), rows: [], harness,
|
|
976
|
-
working: false, submitted: 0, users: new Set(), live: new Set(), cancel: false, relaunches: 0, settled: false, settles: 0, updatedAt: meta.created_at, turns: new Turns(),
|
|
977
|
-
...(tooling ? { tooling } : {}),
|
|
978
|
-
};
|
|
979
|
-
}
|
|
980
|
-
/** Writes the run's serve.json as it is when its turn comes; then tells learning what it now holds (the ledger's line
|
|
981
|
-
* once the run's learning ended). */
|
|
982
|
-
/** Writes the run's serve.json, after any write already under way: `meta`, a copy its caller publishes to run.meta
|
|
983
|
-
* only once this resolves (a raise, takeRaise), else run.meta, each as it stands when the write starts. */
|
|
984
|
-
saveMeta(run, meta) {
|
|
985
|
-
run.saving = (run.saving ?? Promise.resolve()).catch(() => undefined).then(async () => {
|
|
986
|
-
// A copy is built as its write starts, from run.meta as it stands then.
|
|
987
|
-
const written = meta ? meta() : run.meta;
|
|
988
|
-
const { learning } = written;
|
|
989
|
-
await this.beforeMetaSave?.(run.id, written);
|
|
990
|
-
await writeWhole(join(run.dir, RUN_META), `${JSON.stringify(written)}\n`);
|
|
991
|
-
await this.learning.onSaved(run, learning);
|
|
992
|
-
});
|
|
993
|
-
return run.saving;
|
|
994
|
-
}
|
|
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;
|
|
998
|
-
}
|
|
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);
|
|
1021
|
-
return url?.protocol === "http:" && isLoopback(url.hostname) ? url.origin : undefined;
|
|
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
|
-
}
|
|
1039
|
-
storeFile(run) {
|
|
1040
|
-
return join(run.dir, "store", "run.sqlite");
|
|
1041
|
-
}
|
|
1042
|
-
/** The run's rows from its store, opened read-only; only once its claim is released. An agentic run's rows are its
|
|
1043
|
-
* root conversation's; a workflow run's are its model nodes'. `atEnd`: a settle's read, which reads every
|
|
1044
|
-
* conversation (a workflow's nodes, a harness's session) once and counts the run's metrics from all of them. */
|
|
1045
|
-
async readStore(run, atEnd = false) {
|
|
1046
|
-
const file = this.storeFile(run);
|
|
1047
|
-
if (!(await stat(file).catch(() => null)))
|
|
1048
|
-
return;
|
|
1049
|
-
const read = [];
|
|
1050
|
-
const submissions = [];
|
|
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;
|
|
1056
|
-
const rows = run.kind === "workflow" || atEnd
|
|
1057
|
-
? db.prepare("SELECT conversation_id, record FROM entries ORDER BY id").iterate()
|
|
1058
|
-
: db.prepare("SELECT conversation_id, record FROM entries WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").iterate();
|
|
1059
|
-
for (const row of rows)
|
|
1060
|
-
read.push({ conversation: Number(row.conversation_id), entry: JSON.parse(String(row.record)) });
|
|
1061
|
-
// pi's settlements of the person's messages, the root's (turns.ts): its turns' ends.
|
|
1062
|
-
if (run.kind === "agentic") {
|
|
1063
|
-
const inputs = db.prepare("SELECT record FROM submissions WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").all();
|
|
1064
|
-
for (const row of inputs)
|
|
1065
|
-
submissions.push(JSON.parse(String(row.record)));
|
|
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);
|
|
1072
|
-
}
|
|
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;
|
|
1077
|
-
}
|
|
1078
|
-
const root = read.reduce((min, r) => Math.min(min, r.conversation), Infinity);
|
|
1079
|
-
const entries = read.flatMap((r) => (run.kind === "workflow" || r.conversation === root ? [r.entry] : []));
|
|
1080
|
-
if (run.kind === "workflow") {
|
|
1081
|
-
const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
|
|
1082
|
-
// Decisions it cannot read add no rows, and leave the served usage row's total unknown, as the run's cost read
|
|
1083
|
-
// does (readDecisionCost): never its model nodes' total alone.
|
|
1084
|
-
try {
|
|
1085
|
-
run.decisions = durableDecisions(file, { unlocked: true });
|
|
1086
|
-
}
|
|
1087
|
-
catch {
|
|
1088
|
-
run.decisions = null;
|
|
1089
|
-
}
|
|
1090
|
-
run.llmRead = llmAnswers(await readNodeLog(run.dir)).length;
|
|
1091
|
-
}
|
|
1092
|
-
// Its decision requests count with its model requests: each receipt's tokens, or unmetered without them.
|
|
1093
|
-
if (atEnd)
|
|
1094
|
-
run.metrics = runMetricsWithDecisions(read.map((r) => r.entry), run.kind === "workflow" ? (run.decisions ?? []) : []);
|
|
1095
|
-
run.working = false;
|
|
1096
|
-
noteTurns(run, entries, submissions);
|
|
1097
|
-
noteApprovals(run, entries);
|
|
1098
|
-
this.take(run, timelineOf(redactGateMessages(entries, this.redactor(run)), { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
|
|
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
|
-
}
|
|
1123
|
-
/** New rows in: into the log, then the run's status, then whatever the status asks for. */
|
|
1124
|
-
/** `keep`: rows that stay served though `rows` no longer holds them (the live path's committed rows). */
|
|
1125
|
-
take(run, rows, keep) {
|
|
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());
|
|
1127
|
-
// Counted by id: a snapshot of a compacted conversation shows fewer user messages than before, which is not more
|
|
1128
|
-
// messages waiting, so a count of rows would leave the run working forever.
|
|
1129
|
-
const arrived = run.rows.filter((r) => isMessageRow(r) && !run.users.has(r.id));
|
|
1130
|
-
for (const row of arrived)
|
|
1131
|
-
run.users.add(row.id);
|
|
1132
|
-
run.submitted = Math.max(0, run.submitted - arrived.length);
|
|
1133
|
-
run.keep = keep;
|
|
1134
|
-
this.show(run);
|
|
1135
|
-
this.refresh(run);
|
|
1136
|
-
}
|
|
1137
|
-
/** The approval rows as the run's answers say them now (a stop or a cancel withdraws a call, an answer settles one),
|
|
1138
|
-
* shown at once: an answer takes no new rows. */
|
|
1139
|
-
restate(run) {
|
|
1140
|
-
if (!run.approvals?.size)
|
|
1141
|
-
return;
|
|
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));
|
|
1144
|
-
this.show(run);
|
|
1145
|
-
}
|
|
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
|
|
1147
|
-
* only, never the run's own rows, which its cost and its answer are read from. */
|
|
1148
|
-
show(run) {
|
|
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'.
|
|
1150
|
-
// Their summary and text are redacted whole, then cut (decision-rows.ts): a provider's error can quote a held key.
|
|
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 });
|
|
1154
|
-
// An error row reads as the run's error does (errorWords): a refused key in plain words, no loopback address.
|
|
1155
|
-
const served = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : ended ? endedUsage(row) : row));
|
|
1156
|
-
// A run paused at its cap says so after the refusal, as the row its status reads.
|
|
1157
|
-
const said = pausedAt(run);
|
|
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))
|
|
1171
|
-
run.updatedAt = new Date().toISOString();
|
|
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
|
-
}
|
|
1196
|
-
/** A live process: the child this server started, or one an earlier server started that still serves the run. */
|
|
1197
|
-
live(run) {
|
|
1198
|
-
return Boolean(run.child || run.orphan);
|
|
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
|
-
}
|
|
1213
|
-
/** How an agentic run ends: over its cap, or as the turn of the person's newest message ended (turns.ts), once every
|
|
1214
|
-
* message the run took has had its turn. Undefined while one is open, or when the run stopped, waits, or its turn
|
|
1215
|
-
* ended interrupted (the run then waits for the person), or while its records name no message (a live process of an
|
|
1216
|
-
* older server: the run's next process writes its turn's end as it opens). Never from the order of its rows, or from
|
|
1217
|
-
* when its door said idle. A workflow run ends when its workflow does. */
|
|
1218
|
-
decide(run) {
|
|
1219
|
-
if (run.kind === "workflow")
|
|
1220
|
-
return undefined;
|
|
1221
|
-
// A cancel ends the run cancelled, by its settle (whatever the turn it cut wrote, a cost over the cap too): nothing
|
|
1222
|
-
// ends it otherwise meanwhile, so its first terminal status is its last. The cancel has aborted the turn already.
|
|
1223
|
-
if (run.cancel)
|
|
1224
|
-
return undefined;
|
|
1225
|
-
const cap = run.meta.max_cost_usd;
|
|
1226
|
-
const cost = costOf(run.rows);
|
|
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 } };
|
|
1231
|
-
if (run.submitted > 0)
|
|
1232
|
-
return undefined;
|
|
1233
|
-
if (run.turns.open > 0 || stopped(run))
|
|
1234
|
-
return undefined;
|
|
1235
|
-
// A tool call waits for a person's approval, or for its answer to be acted on: the run goes on after it.
|
|
1236
|
-
if (waitingApproval(run) || actingOn(run))
|
|
1237
|
-
return undefined;
|
|
1238
|
-
const end = run.turns.end();
|
|
1239
|
-
if (end?.status === "answered")
|
|
1240
|
-
return { outcome: "completed" };
|
|
1241
|
-
if (end?.status !== "failed")
|
|
1242
|
-
return undefined;
|
|
1243
|
-
const message = end.error ?? "The run failed.";
|
|
1244
|
-
// The cap's refusal for room pauses the run instead (pausedAt): a raise sends what was refused.
|
|
1245
|
-
if (roomRefusal(message) !== undefined)
|
|
1246
|
-
return undefined;
|
|
1247
|
-
// The cap's refusal in the run's process (cap.ts); a provider error with this exact prefix would read as one too.
|
|
1248
|
-
// Its code is `spend_cap_reached: `, or with a note after it (`spend_cap_reached (out of budget): `, cap.ts); the message is
|
|
1249
|
-
// the words after it.
|
|
1250
|
-
const capped = CAP_REFUSAL_PREFIX.exec(message);
|
|
1251
|
-
if (capped)
|
|
1252
|
-
return { outcome: "failed", error: { code: SPEND_CAP_REACHED, message: message.slice(capped[0].length), retryable: false } };
|
|
1253
|
-
// The provider's content filter stopped the answer (content-filter.ts): moderated, in words a person can act on.
|
|
1254
|
-
if (contentFiltered(message))
|
|
1255
|
-
return { outcome: "failed", error: { code: MODERATED, message: CONTENT_FILTER_WORDS, retryable: false } };
|
|
1256
|
-
return { outcome: "failed", error: { code: "run_failed", message: this.errorWords(run, message) ?? message, retryable: false } };
|
|
1257
|
-
}
|
|
1258
|
-
/** A run's error as a person reads it, in its error box and on its Timeline row alike: a refused key in plain words
|
|
1259
|
-
* (plainKey), else the harness's text with no loopback address (withoutLoopback: Codex names serve's own proxy). */
|
|
1260
|
-
errorWords(run, text) {
|
|
1261
|
-
return text ? this.shown(run, this.plainKey(run, text) ?? text) : text;
|
|
1262
|
-
}
|
|
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. */
|
|
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 };
|
|
1272
|
-
const plain = this.plainKey(run, row.text ?? undefined);
|
|
1273
|
-
if (plain) {
|
|
1274
|
-
const words = this.shown(run, plain);
|
|
1275
|
-
return { ...row, summary: words, text: words };
|
|
1276
|
-
}
|
|
1277
|
-
return { ...row, ...(row.summary ? { summary: this.shown(run, row.summary) } : {}), ...(row.text ? { text: this.shown(run, row.text) } : {}) };
|
|
1278
|
-
}
|
|
1279
|
-
/** What serve shows of a run's error text, for every run kind (run-view.ts shownOf): no held secret and no loopback. */
|
|
1280
|
-
shown(run, text) {
|
|
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);
|
|
1311
|
-
}
|
|
1312
|
-
/** A run's answer as serve serves it: no held secret, never cut (redactedAnswer). Loopback addresses stay: an answer is
|
|
1313
|
-
* the model's own words, and a local address there can be what the person asked about. */
|
|
1314
|
-
servedAnswer(run, text) {
|
|
1315
|
-
return text ? this.servedOnce(run, "answer", text, (values) => redactedAnswer(text, values)) : text;
|
|
1316
|
-
}
|
|
1317
|
-
/** A workflow run's output as serve serves it: each string in it as servedAnswer, its shape kept. */
|
|
1318
|
-
servedOutput(run, output) {
|
|
1319
|
-
return output === null ? null : this.servedOnce(run, "output", output, (values) => redactedOutput(output, values));
|
|
1320
|
-
}
|
|
1321
|
-
/** `redact(values)` over the values `run` holds, read once per input and held value set: a console polls a run's
|
|
1322
|
-
* view, and an answer a run was made to write can be large. The run keeps the one it served last, of each slot; a key
|
|
1323
|
-
* saved or deleted changes the values' digest, and the next view redacts again. */
|
|
1324
|
-
servedOnce(run, slot, input, redact) {
|
|
1325
|
-
const values = this.refusedValues(run);
|
|
1326
|
-
const keys = digestOf([...values].sort());
|
|
1327
|
-
const last = run.served?.[slot];
|
|
1328
|
-
if (last && last.keys === keys && last.input === input)
|
|
1329
|
-
return last.out;
|
|
1330
|
-
const out = redact(values);
|
|
1331
|
-
run.served = { ...run.served, [slot]: { keys, input, out } };
|
|
1332
|
-
return out;
|
|
1333
|
-
}
|
|
1334
|
-
/** The timeline's redaction of `run`'s error rows and of what a tool's result shows (its summary and preview), applied
|
|
1335
|
-
* before a row is cut (timelineOf's `redact`), so a cut never leaves the head of a key. Every such cut is within
|
|
1336
|
-
* redacted()'s SHOWN, so its window holds. */
|
|
1337
|
-
/** How a run's decision rows show a text (decision-rows.ts Shown): the run's redactor, and as many characters held back
|
|
1338
|
-
* from a text stored cut as a held value takes in its widest form. */
|
|
1339
|
-
decisionShown(run) {
|
|
1340
|
-
const values = this.refusedValues(run);
|
|
1341
|
-
return { redact: (text) => redacted(text, values), hold: 6 * values.reduce((most, value) => Math.max(most, value.length), 0) + 16 };
|
|
1342
|
-
}
|
|
1343
|
-
redactor(run) {
|
|
1344
|
-
return redactorOf(this.refusedValues(run));
|
|
1345
|
-
}
|
|
1346
|
-
/** The last line of the run process's log (lastLogLine) for a failure's message, with every value its errors never
|
|
1347
|
-
* show cut out: its process may have written a secret or its sign-in's pointer there. */
|
|
1348
|
-
async lastLine(run) {
|
|
1349
|
-
return this.redactor(run)(await lastLogLine(run));
|
|
1350
|
-
}
|
|
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. */
|
|
1353
|
-
refusedValues(run) {
|
|
1354
|
-
return refusedValuesOf(this.options.serverSecrets, run.handed);
|
|
1355
|
-
}
|
|
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
|
|
1357
|
-
* harness's route sends, by this server's settings and keys, and no secret's value. */
|
|
1358
|
-
plainKey(run, text) {
|
|
1359
|
-
// A workflow's nodes run on their own tiers' models, and its error row does not say which one failed: naming the
|
|
1360
|
-
// default tier's key could name the wrong one, so its error keeps the provider's own words.
|
|
1361
|
-
if (!text || run.kind === "workflow")
|
|
1362
|
-
return undefined;
|
|
1363
|
-
const env = withSecrets(process.env, "all", this.options.storedKeys);
|
|
1364
|
-
return keyRefusal(text, runKeyOf(env, run.harness ?? run.tooling?.harness, run.tooling?.model), this.refusedValues(run));
|
|
1365
|
-
}
|
|
1366
|
-
/** Records the run's status as a change when it moves, and lets go of a live run that answered, failed or is over its cap. */
|
|
1367
|
-
/** What a run paused at its cap has spent once its process is gone: its store's spend as the cap reads it (spentIn),
|
|
1368
|
-
* read once per pause (its refusal's row). None while its process lives, nor when the store says unknown or cannot
|
|
1369
|
-
* be read: the refusal's own figure stands then. */
|
|
1370
|
-
spentNow(run) {
|
|
1371
|
-
const mark = meaningful(run.rows)?.id;
|
|
1372
|
-
if (mark === undefined || !run.capRefusal || this.live(run) || pausedAt(run) === undefined)
|
|
1373
|
-
return undefined;
|
|
1374
|
-
// One read per pause, and a failed read again after a while, never kept until a restart.
|
|
1375
|
-
if (run.capSpent?.mark !== mark || (run.capSpent.usd === null && Date.now() - (run.capSpent.at ?? 0) > 30_000)) {
|
|
1376
|
-
let usd = null;
|
|
1377
|
-
try {
|
|
1378
|
-
usd = spentIn(this.storeFile(run));
|
|
1379
|
-
}
|
|
1380
|
-
catch (error) {
|
|
1381
|
-
warn(run.id, `its store's spend was not read (${error.message}); its refusal's figure stands`);
|
|
1382
|
-
}
|
|
1383
|
-
run.capSpent = { mark, usd, at: Date.now() };
|
|
1384
|
-
}
|
|
1385
|
-
return run.capSpent.usd ?? undefined;
|
|
1386
|
-
}
|
|
1387
|
-
/** The run's live process, by its pid and start ticks (processIdentity). */
|
|
1388
|
-
liveIdentity(run) {
|
|
1389
|
-
return processIdentity(run.child?.pid ?? run.orphan);
|
|
1390
|
-
}
|
|
1391
|
-
refresh(run) {
|
|
1392
|
-
this.mark(run);
|
|
1393
|
-
// A run whose cap was raised at its pause goes on once the process paused there is gone (resumeRaised): with no
|
|
1394
|
-
// process, or one another launch started (a server stopped between that launch and its message: the door takes the
|
|
1395
|
-
// message once, by its id). Never while one waits to be tried again.
|
|
1396
|
-
const next = continuationOf(run);
|
|
1397
|
-
const letting = next !== undefined && next.paused !== undefined && this.live(run) && this.liveIdentity(run) === next.paused;
|
|
1398
|
-
if (next && run.resuming === undefined && !this.closing && !run.cancel && !run.finishing && !run.outcome && !letting)
|
|
1399
|
-
void this.resumeRaised(run, next);
|
|
1400
|
-
if (!this.live(run) || run.finishing || run.outcome)
|
|
1401
|
-
return;
|
|
1402
|
-
const end = this.decide(run);
|
|
1403
|
-
// Paused at its cap, its process is let go: it waits without one, holding no place, until its cap is raised. Once
|
|
1404
|
-
// per pause (its refusal's row): SIGTERM drains and releases it, and the settle that follows leaves it waiting. A
|
|
1405
|
-
// raised one's paused process is let go too (a server started again finds it so).
|
|
1406
|
-
if (!end && (pausedAt(run) !== undefined || letting) && run.parked !== waitMark(run)) {
|
|
1407
|
-
run.parked = waitMark(run);
|
|
1408
|
-
this.terminate(run);
|
|
1409
|
-
}
|
|
1410
|
-
if (!end)
|
|
1411
|
-
return;
|
|
1412
|
-
if (end.error)
|
|
1413
|
-
run.error = end.error;
|
|
1414
|
-
// A run that learns is not let go yet: its end-of-run turn is asked first, unless learning skips it (learning-run.ts).
|
|
1415
|
-
if (this.learning.beforeFinish(run, end))
|
|
1416
|
-
return;
|
|
1417
|
-
this.finish(run, end.outcome, end.abort);
|
|
1418
|
-
}
|
|
1419
|
-
/** The test hooks startServe's options name, as a run's process and this server's own calls get them. */
|
|
1420
|
-
fauxEnv() {
|
|
1421
|
-
return { ...this.options.fauxEnv };
|
|
1422
|
-
}
|
|
1423
|
-
/** Let go of a live run with `outcome`: SIGTERM, after aborting its turn when it is still working. */
|
|
1424
|
-
finish(run, outcome, abortFirst = false) {
|
|
1425
|
-
run.finishing = outcome;
|
|
1426
|
-
run.endedAt = new Date().toISOString();
|
|
1427
|
-
this.mark(run);
|
|
1428
|
-
void (abortFirst ? this.abortTurn(run) : Promise.resolve()).then(() => this.terminate(run));
|
|
1429
|
-
}
|
|
1430
|
-
/** SIGTERM to the run's process: it drains, releases the run and exits. */
|
|
1431
|
-
terminate(run) {
|
|
1432
|
-
if (run.child)
|
|
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)
|
|
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;
|
|
1470
|
-
run.orphan = pid;
|
|
1471
|
-
run.orphanHolder = holder;
|
|
1472
|
-
this.reportedBack(run);
|
|
1473
|
-
if (follow)
|
|
1474
|
-
this.connect(run);
|
|
1475
|
-
let releasedAt;
|
|
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
|
-
};
|
|
1490
|
-
const timer = setInterval(() => {
|
|
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);
|
|
1518
|
-
return;
|
|
1519
|
-
}
|
|
1520
|
-
}
|
|
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));
|
|
1538
|
-
}, 500);
|
|
1539
|
-
timer.unref();
|
|
1540
|
-
}
|
|
1541
|
-
/** At start: every run the store says is running is read, supervised when its process lives, carried back when it
|
|
1542
|
-
* already ended, and opened again when its process went before it ended. */
|
|
1543
|
-
/** Every run's box let go that nothing owns, and every run cgroup no record names: once, before any run of this server
|
|
1544
|
-
* starts, opens again or relaunches, so a box or cgroup being made is never swept away. */
|
|
1545
|
-
sweepOnce() {
|
|
1546
|
-
const { box, runBoxes, remoteBoxes, vmBoxes } = this.options;
|
|
1547
|
-
if (!box && !runBoxes && !remoteBoxes && !vmBoxes)
|
|
1548
|
-
return Promise.resolve();
|
|
1549
|
-
this.swept ??= (async () => {
|
|
1550
|
-
const rows = await this.options.agents.request(() => this.store.listRuns());
|
|
1551
|
-
// The boxes of sandbox runs, by their label: one whose run has ended, or is archived, is destroyed. A failure only
|
|
1552
|
-
// warns: the next start sweeps again, and a box's lifetime bounds it.
|
|
1553
|
-
const ended = new Set(rows.filter((row) => row.state !== "running" || row.archivedAt).map((row) => row.id));
|
|
1554
|
-
if (runBoxes) {
|
|
1555
|
-
await sweepRunBoxes(runBoxes, (id) => ended.has(id), boxContext()).catch((error) => warn("-", `its start's sweep of run boxes failed (${error.message}); the next start sweeps again`));
|
|
1556
|
-
}
|
|
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
|
|
1558
|
-
// once that pull landed: one that fails keeps the box for the next start, its lifetime bounding it.
|
|
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);
|
|
1561
|
-
const pulledFirst = (boxes, daytona) => (id, boxId) => pullRemoteBox(boxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
|
|
1562
|
-
warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
|
|
1563
|
-
await this.keepBox(id, boxId, daytona);
|
|
1564
|
-
return false;
|
|
1565
|
-
});
|
|
1566
|
-
if (vmBoxes) {
|
|
1567
|
-
await sweepRunBoxes(vmBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(vmBoxes, false)).catch((error) => warn("-", `its start's sweep of Modal sandboxes failed (${error.message}); the next start sweeps again`));
|
|
1568
|
-
}
|
|
1569
|
-
if (remoteBoxes) {
|
|
1570
|
-
// A box kept at a run's end that Daytona stopped once idle is woken first, so this sweep pulls it like the rest.
|
|
1571
|
-
const api = this.options.remoteApi;
|
|
1572
|
-
if (api)
|
|
1573
|
-
await wakeBoxes(api, (id) => ended.has(id)).catch((error) => warn("-", `the stopped boxes of ended runs were not woken (${error.message}); the next start tries again`));
|
|
1574
|
-
await sweepRunBoxes(remoteBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(remoteBoxes, true)).catch((error) => warn("-", `its start's sweep of remote run boxes failed (${error.message}); the next start sweeps again`));
|
|
1575
|
-
}
|
|
1576
|
-
if (!box)
|
|
1577
|
-
return;
|
|
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) })));
|
|
1579
|
-
for (const [id, how] of Object.entries(settled))
|
|
1580
|
-
if (how === "quarantined")
|
|
1581
|
-
warn(id, "its box could not be emptied; it is quarantined, and tried again at each start");
|
|
1582
|
-
})().catch((error) => {
|
|
1583
|
-
// A sweep that failed is not kept: the next start, open or relaunch sweeps again, so one transient error never
|
|
1584
|
-
// holds every run back until the server restarts. Nothing of this server's runs has started a box before it.
|
|
1585
|
-
this.swept = undefined;
|
|
1586
|
-
throw error;
|
|
1587
|
-
});
|
|
1588
|
-
return this.swept;
|
|
1589
|
-
}
|
|
1590
|
-
/** A sandbox run's box (run-box.ts), destroyed by its label: at every settle, a cancel included, and at archive. A
|
|
1591
|
-
* remote box's work/ is pulled first, and its box goes only once that pull brought it back whole (or there is no box).
|
|
1592
|
-
* A copy that stopped for good (an archive the extractor cannot read, a limit it cannot pass) keeps the box, said in
|
|
1593
|
-
* the log, its lifetime bounding it, and the run ends. Any other failure at a run's end (`ending`) throws
|
|
1594
|
-
* PullPending, and the end is tried again; at an archive it only warns, the box kept for the run's end or the next
|
|
1595
|
-
* start's sweep. A destroy that fails only warns: the next start's sweep tries again, and the box's lifetime bounds it. */
|
|
1596
|
-
async dropBox(run, ending = false) {
|
|
1597
|
-
const place = run.meta.place;
|
|
1598
|
-
if (place?.mode !== "sandbox")
|
|
1599
|
-
return;
|
|
1600
|
-
// The relay's hold on the run's programs (box-relay-vm.ts) ends with the run, whatever becomes of its box: one kept
|
|
1601
|
-
// for a later pull, or one whose destroy failed, still lets them go, and their output with them.
|
|
1602
|
-
this.options.vmRelay?.drop(run.id);
|
|
1603
|
-
const remote = remotePlace(place);
|
|
1604
|
-
const boxes = remote ? this.remoteOf(place) : this.options.runBoxes;
|
|
1605
|
-
if (!boxes)
|
|
1606
|
-
return;
|
|
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.
|
|
1609
|
-
if (remote) {
|
|
1610
|
-
try {
|
|
1611
|
-
await this.pullBox(run, true);
|
|
1612
|
-
}
|
|
1613
|
-
catch (error) {
|
|
1614
|
-
if (error instanceof PullIncomplete && error.lasting) {
|
|
1615
|
-
await this.keepBox(run.id, error.box, place.box === "daytona");
|
|
1616
|
-
return warn(run.id, `its box is kept, not destroyed: ${error.message}; what came back is in its files, and the box stops after ${KEPT_AUTOSTOP_MINUTES} idle minutes, its files kept for the next start's pull`);
|
|
1617
|
-
}
|
|
1618
|
-
const why = `its box's last pull failed (${error.message})`;
|
|
1619
|
-
if (ending)
|
|
1620
|
-
throw new PullPending(why);
|
|
1621
|
-
return warn(run.id, `${why}; its box is kept for its end`);
|
|
1622
|
-
}
|
|
1623
|
-
}
|
|
1624
|
-
try {
|
|
1625
|
-
await destroyRunBoxes(boxes, run.id, boxContext());
|
|
1626
|
-
// The box's egress proxy directory (box-egress.ts), its socket the run's process left: nothing binds it now.
|
|
1627
|
-
await removeEgressDir(run.id, this.options.dockerPaths ? egressParentOf(this.options.agents.dir) : undefined).catch(() => undefined);
|
|
1628
|
-
}
|
|
1629
|
-
catch (error) {
|
|
1630
|
-
warn(run.id, `its box was not destroyed (${error.message}); the next start sweeps it`);
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
/** A remote box kept because its copy back is not whole: said in the log, and set to stop once idle, so it costs its
|
|
1634
|
-
* disk alone until the next start's pull (which wakes it) or its lifetime. */
|
|
1635
|
-
async keepBox(runId, boxId, daytona = true) {
|
|
1636
|
-
this.options.log?.("box_kept", { run: runId, box: boxId, reason: "pull_incomplete" });
|
|
1637
|
-
// A VM box keeps its lifetime alone: the provider has no idle stop to set.
|
|
1638
|
-
const api = daytona ? this.options.remoteApi : undefined;
|
|
1639
|
-
if (api)
|
|
1640
|
-
await keepWhenIdle(api, boxId).catch((error) => warn(runId, `its kept box was not kept from deletion or set to stop when idle (${error.message})`));
|
|
1641
|
-
}
|
|
1642
|
-
/** What wakes run `runId`'s remote box when Daytona stopped or paused it (a class that pauses when idle, while the run
|
|
1643
|
-
* waited for a person): how many it woke. */
|
|
1644
|
-
wakeOf(runId, place) {
|
|
1645
|
-
// Only Daytona stops or pauses a box: a VM box that ended is made again.
|
|
1646
|
-
const api = place?.mode === "sandbox" && place.box !== "daytona" ? undefined : this.options.remoteApi;
|
|
1647
|
-
return api && (() => wakeBoxes(api, (id) => id === runId));
|
|
1648
|
-
}
|
|
1649
|
-
/** Pulls run `run`'s remote box into its work/, after any pull already running: at a turn's end in the background (a
|
|
1650
|
-
* failure warns, and the next pull brings it), or awaited (`strict`: a failure throws). */
|
|
1651
|
-
pullBox(run, strict = false) {
|
|
1652
|
-
const place = run.meta.place;
|
|
1653
|
-
const boxes = place && remotePlace(place) ? this.remoteOf(place) : undefined;
|
|
1654
|
-
if (!boxes || !place)
|
|
1655
|
-
return Promise.resolve();
|
|
1656
|
-
// After any pull already running, and after the box's making and seed when one is under way.
|
|
1657
|
-
const pull = Promise.all([run.pulling, run.boxing?.catch(() => undefined)]).then(async () => {
|
|
1658
|
-
const pulled = await pullRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id, place));
|
|
1659
|
-
if (pulled)
|
|
1660
|
-
this.options.log?.("box_pulled", { run: run.id, changed: pulled.changed, files: pulled.files, bytes: pulled.bytes, removed: pulled.removed });
|
|
1661
|
-
});
|
|
1662
|
-
const settled = pull.catch((error) => {
|
|
1663
|
-
if (!strict)
|
|
1664
|
-
warn(run.id, `its box's work/ was not pulled at its turn's end (${error.message}); the next pull brings it`);
|
|
1665
|
-
});
|
|
1666
|
-
run.pulling = settled;
|
|
1667
|
-
void settled.finally(() => {
|
|
1668
|
-
if (run.pulling === settled)
|
|
1669
|
-
run.pulling = undefined;
|
|
1670
|
-
});
|
|
1671
|
-
return strict ? pull : settled;
|
|
1672
|
-
}
|
|
1673
|
-
/** Waits for the pull run `id`'s turn's end began, if any, up to PULL_WAIT_MS: its files then show what its box wrote. */
|
|
1674
|
-
async pulled(id) {
|
|
1675
|
-
const pulling = this.runs.get(id)?.pulling;
|
|
1676
|
-
if (!pulling)
|
|
1677
|
-
return;
|
|
1678
|
-
let timer;
|
|
1679
|
-
await Promise.race([pulling, new Promise((resolve) => (timer = setTimeout(resolve, PULL_WAIT_MS)))]);
|
|
1680
|
-
clearTimeout(timer);
|
|
1681
|
-
}
|
|
1682
|
-
/** Whether run `id` is one this server holds in a remote box and has not ended: the relay serves no other. */
|
|
1683
|
-
servesBox(id) {
|
|
1684
|
-
const run = this.runs.get(id);
|
|
1685
|
-
return Boolean(run && !run.outcome && run.meta.place && remotePlace(run.meta.place) && this.remoteOf(run.meta.place));
|
|
1686
|
-
}
|
|
1687
|
-
/** The server's provider of a remote place's boxes: the VM box's, or Daytona's. */
|
|
1688
|
-
remoteOf(place) {
|
|
1689
|
-
return place.mode === "sandbox" && place.box === VM_PROVIDER.id ? this.options.vmBoxes : this.options.remoteBoxes;
|
|
1690
|
-
}
|
|
1691
|
-
/** Run `id`'s remote box, found or made and seeded: what its process asks the relay for at its first tool call. */
|
|
1692
|
-
ensureBox(id) {
|
|
1693
|
-
const run = this.runs.get(id);
|
|
1694
|
-
const place = run?.meta.place;
|
|
1695
|
-
const boxes = place && this.remoteOf(place);
|
|
1696
|
-
if (!run || !place || !boxes || !this.servesBox(id))
|
|
1697
|
-
return Promise.reject(new Error(`no run ${id} of this server is in a remote box`));
|
|
1698
|
-
// The VM box has no network (its provider's host list cannot be read back), and takes the box limits.
|
|
1699
|
-
const vm = place.mode === "sandbox" && place.box === VM_PROVIDER.id;
|
|
1700
|
-
// After any pull of this run's box, so a seed never meets a pull.
|
|
1701
|
-
run.boxing ??= (run.pulling ?? Promise.resolve())
|
|
1702
|
-
.then(() => ensureRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), vm ? { allow: "none", ...(this.options.vmLimits ? { limits: this.options.vmLimits } : {}) } : {
|
|
1703
|
-
wake: this.wakeOf(run.id, place),
|
|
1704
|
-
allow: (this.remoteAllow ??= this.options.boxAllow ?? "none"),
|
|
1705
|
-
onNoList: (code, message) => {
|
|
1706
|
-
if (this.remoteAllow === "none")
|
|
1707
|
-
return;
|
|
1708
|
-
this.remoteAllow = "none";
|
|
1709
|
-
this.options.onNoBoxList?.(code, message);
|
|
1710
|
-
},
|
|
1711
|
-
}))
|
|
1712
|
-
.finally(() => void (run.boxing = undefined));
|
|
1713
|
-
return run.boxing;
|
|
1714
|
-
}
|
|
1715
|
-
/** The run's box let go (archive, or its process gone after an archive): reaped by the box's own count. */
|
|
1716
|
-
async teardown(run) {
|
|
1717
|
-
const box = this.options.box;
|
|
1718
|
-
if (!box || this.live(run))
|
|
1719
|
-
return;
|
|
1720
|
-
// Never in the way of the run's own end or an archive already saved: a box that could not be let go (its cgroup not
|
|
1721
|
-
// removed, its record not marked) is said, and its unmarked record is tried again by the next start's sweep.
|
|
1722
|
-
try {
|
|
1723
|
-
if ((await settleBox(box.host, box.quarantine, run.id, run.dir)) === "quarantined")
|
|
1724
|
-
warn(run.id, "its box could not be emptied; it is quarantined, and tried again at each start");
|
|
1725
|
-
}
|
|
1726
|
-
catch (error) {
|
|
1727
|
-
warn(run.id, `its box was not let go (${error.message}); the next start tries again`);
|
|
1728
|
-
}
|
|
1729
|
-
}
|
|
1730
|
-
/** After an archive (a run's, or an agent's, which archives its runs): the box of every run now archived is let go,
|
|
1731
|
-
* now when its process is gone, else when it exits. */
|
|
1732
|
-
async archived() {
|
|
1733
|
-
if (!this.options.box && !this.options.runBoxes && !this.options.remoteBoxes && !this.options.vmBoxes)
|
|
1734
|
-
return;
|
|
1735
|
-
for (const row of await this.options.agents.request(() => this.store.listRuns())) {
|
|
1736
|
-
if (!row.archivedAt)
|
|
1737
|
-
continue;
|
|
1738
|
-
// A run's box needs only the runs this server holds: one it has not read has ended, or was swept at its start.
|
|
1739
|
-
const run = this.options.box ? await this.get(row.id) : this.runs.get(row.id);
|
|
1740
|
-
if (!run)
|
|
1741
|
-
continue;
|
|
1742
|
-
// A run's box goes at its archive, its process live or not (an ended run's went at its end): an archived run takes
|
|
1743
|
-
// no message, and a call it still makes gets a fresh box, which its end or the next start's sweep destroys.
|
|
1744
|
-
if (!run.outcome)
|
|
1745
|
-
await this.dropBox(run);
|
|
1746
|
-
await this.teardown(run);
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
async recover() {
|
|
1750
|
-
// The learning a server left between steps, picked up once every running run is read (learning-run.ts).
|
|
1751
|
-
const recoverLearning = this.learning.recover();
|
|
1752
|
-
await this.sweepOnce();
|
|
1753
|
-
// Only what an earlier server left: a store slow to answer here must not hand back a run a create is setting up now.
|
|
1754
|
-
const rows = (await this.options.agents.request(() => this.store.listRuns())).filter((row) => row.startedAt < this.bootedAt);
|
|
1755
|
-
for (const row of rows) {
|
|
1756
|
-
if (row.state !== "running" || row.importedFrom)
|
|
1757
|
-
continue;
|
|
1758
|
-
const run = await this.adopt(row).catch((error) => (warn(row.id, `not recovered: ${error.message}; the next start tries again`), null));
|
|
1759
|
-
if (run && !this.live(run) && !run.outcome)
|
|
1760
|
-
await this.settle(run, null, false);
|
|
1761
|
-
}
|
|
1762
|
-
await recoverLearning(rows);
|
|
1763
|
-
}
|
|
1764
|
-
/** The run's status, state and whether its rows are all in, as one more change of its log when any of them moves. A wait
|
|
1765
|
-
* is told each time it is seen: webhooks.ts queues each wait once, whichever server sees it first. */
|
|
1766
|
-
mark(run) {
|
|
1767
|
-
const { status, state } = statusOf(run);
|
|
1768
|
-
// A turn's end, or a run first read waiting (a start that finds it so, whose last turn's pull may not have landed):
|
|
1769
|
-
// what its remote box changed is pulled into work/ now, and a read of the files waits for it.
|
|
1770
|
-
const waiting = status === "input_required";
|
|
1771
|
-
if (waiting && run.waited !== true)
|
|
1772
|
-
this.pullBox(run);
|
|
1773
|
-
run.waited = waiting;
|
|
1774
|
-
if (run.log.setState(`${status}/${state}/${run.settled}`))
|
|
1775
|
-
run.updatedAt = new Date().toISOString();
|
|
1776
|
-
// What it waits on: an ask_person question (waiting), else a stopped turn, for the person's next message.
|
|
1777
|
-
if (status === "input_required")
|
|
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" });
|
|
1779
|
-
}
|
|
1780
|
-
/** Tells webhooks.ts (`notify`) of a moment of the run under `marker`: a wait it reached (mark), or an end the agent store
|
|
1781
|
-
* has (settle, persistLater, reopen). What it already queued it queues no more. */
|
|
1782
|
-
notice(run, event, marker, pending) {
|
|
1783
|
-
if (!this.options.notify || !marker)
|
|
1784
|
-
return undefined;
|
|
1785
|
-
try {
|
|
1786
|
-
return this.options.notify(event, { run_id: run.id, agent_id: run.agentId, status: statusOf(run).status, title: run.meta.title, ...(pending ? { pending } : {}) }, marker);
|
|
1787
|
-
}
|
|
1788
|
-
catch (error) {
|
|
1789
|
-
warn(run.id, `its notice was not queued: ${error.message}`);
|
|
1790
|
-
return undefined;
|
|
1791
|
-
}
|
|
1792
|
-
}
|
|
1793
|
-
// ---- the door -------------------------------------------------------------------------------------------------------
|
|
1794
|
-
/** A call to run `run`'s door: with its own door token, or, for a process an older server started, the server-wide one. */
|
|
1795
|
-
headers(run, json = false) {
|
|
1796
|
-
run.doorToken ??= runDoorToken(run.dir);
|
|
1797
|
-
return { authorization: `Bearer ${run.doorToken ?? this.options.doorToken}`, ...(json ? { "content-type": "application/json" } : {}) };
|
|
1798
|
-
}
|
|
1799
|
-
/** Run `id`'s own door token, the one its calls to the box relay carry; none for a run it does not hold or that has none. */
|
|
1800
|
-
relayToken(id) {
|
|
1801
|
-
const run = this.runs.get(id);
|
|
1802
|
-
if (!run)
|
|
1803
|
-
return undefined;
|
|
1804
|
-
run.doorToken ??= runDoorToken(run.dir);
|
|
1805
|
-
return run.doorToken;
|
|
1806
|
-
}
|
|
1807
|
-
/** Follow the door's events into an agentic run's rows, again after each drop while the process lives. A workflow
|
|
1808
|
-
* run is only watched: the door's events are a root conversation's, and a workflow run has none. */
|
|
1809
|
-
connect(run) {
|
|
1810
|
-
if (run.feed)
|
|
1811
|
-
return;
|
|
1812
|
-
const abort = new AbortController();
|
|
1813
|
-
run.feed = abort;
|
|
1814
|
-
void (async () => {
|
|
1815
|
-
while (!abort.signal.aborted) {
|
|
1816
|
-
const door = this.doorOf(run);
|
|
1817
|
-
if (door)
|
|
1818
|
-
this.reportedBack(run);
|
|
1819
|
-
if (door && run.kind === "workflow") {
|
|
1820
|
-
if (!run.working && !run.outcome) {
|
|
1821
|
-
run.working = true;
|
|
1822
|
-
this.refresh(run);
|
|
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);
|
|
1829
|
-
}
|
|
1830
|
-
else if (door)
|
|
1831
|
-
await this.follow(run, door, abort.signal).catch(() => undefined);
|
|
1832
|
-
if (abort.signal.aborted || (!this.live(run) && !this.doorOf(run)))
|
|
1833
|
-
break;
|
|
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
|
-
});
|
|
1842
|
-
}
|
|
1843
|
-
if (run.feed === abort)
|
|
1844
|
-
run.feed = undefined;
|
|
1845
|
-
})();
|
|
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
|
-
}
|
|
1871
|
-
async follow(run, door, signal) {
|
|
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.
|
|
1873
|
-
const reducer = timelineReducer({ path: rowPaths(run.dir), redact: this.redactor(run), redactLive: (text) => redactedLive(text, this.refusedValues(run)) });
|
|
1874
|
-
// `inputs=1`: the snapshot carries pi's newest input submissions, the settlements its turns end on (turns.ts).
|
|
1875
|
-
const up = await fetch(new URL(`/events?inputs=1&skip=${encodeURIComponent(REFLECT_REQUEST)}`, door), { signal, headers: { ...this.headers(run), accept: "text/event-stream" } });
|
|
1876
|
-
if (!up.ok || !up.body)
|
|
1877
|
-
return;
|
|
1878
|
-
const decoder = new TextDecoder();
|
|
1879
|
-
let buffer = "";
|
|
1880
|
-
for await (const chunk of up.body) {
|
|
1881
|
-
buffer += decoder.decode(chunk, { stream: true });
|
|
1882
|
-
for (let end; (end = buffer.indexOf("\n\n")) >= 0;) {
|
|
1883
|
-
const frame = buffer.slice(0, end);
|
|
1884
|
-
buffer = buffer.slice(end + 2);
|
|
1885
|
-
let event = "message";
|
|
1886
|
-
const data = [];
|
|
1887
|
-
for (const line of frame.split("\n")) {
|
|
1888
|
-
if (line.startsWith("event:"))
|
|
1889
|
-
event = line.slice(6).trim();
|
|
1890
|
-
else if (line.startsWith("data:"))
|
|
1891
|
-
data.push(line.slice(5).replace(/^ /, ""));
|
|
1892
|
-
}
|
|
1893
|
-
let value;
|
|
1894
|
-
try {
|
|
1895
|
-
value = JSON.parse(data.join("\n"));
|
|
1896
|
-
}
|
|
1897
|
-
catch {
|
|
1898
|
-
continue;
|
|
1899
|
-
}
|
|
1900
|
-
if (event === "end")
|
|
1901
|
-
return;
|
|
1902
|
-
const events = event === "snapshot" ? [value] : event === "events" && Array.isArray(value) ? value : [];
|
|
1903
|
-
if (event === "snapshot")
|
|
1904
|
-
run.working = Boolean(value.run);
|
|
1905
|
-
for (const e of events)
|
|
1906
|
-
if (e.type === "run_start" || e.type === "run_end")
|
|
1907
|
-
run.working = e.type === "run_start";
|
|
1908
|
-
// The settlements of pi's turns: each a submission event in the commit of its turn's last entry, and the door's
|
|
1909
|
-
// snapshot of them on a (re)connect (pi-durable-disk's `inputs`), read as their whole state.
|
|
1910
|
-
const submissions = events.flatMap((e) => (e.type === "submission" && e.record !== undefined ? [e.record] : []));
|
|
1911
|
-
const inputs = events.find((e) => e.type === "snapshot" && Array.isArray(e.inputs))?.inputs;
|
|
1912
|
-
const entries = events.flatMap((e) => (Array.isArray(e.entries) ? e.entries : e.entry !== undefined ? [e.entry] : []));
|
|
1913
|
-
noteTurns(run, entries, submissions, inputs);
|
|
1914
|
-
noteApprovals(run, entries);
|
|
1915
|
-
const redact = this.redactor(run);
|
|
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;
|
|
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),
|
|
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))
|
|
1925
|
-
reducer.idle();
|
|
1926
|
-
// A snapshot rebuilds from the conversation's current view: after a compaction it holds fewer of the rows
|
|
1927
|
-
// already shown, which stay; only live rows go when they end.
|
|
1928
|
-
const rows = reducer.rows();
|
|
1929
|
-
this.take(run, rows, keepCommitted(run.live, rows, reducer.isLive, (run.madeHere ??= new Set())));
|
|
1930
|
-
if (event === "snapshot" && run.finishStop) {
|
|
1931
|
-
run.finishStop = false;
|
|
1932
|
-
if (run.working && stopped(run) && run.submitted === 0) {
|
|
1933
|
-
// The run reads stopped already, so a message sent now would go in behind the turn this abort ends, and be
|
|
1934
|
-
// withdrawn with it: it waits for the abort, as for a stop in flight.
|
|
1935
|
-
run.stopping = true;
|
|
1936
|
-
void this.abortTurn(run).catch(() => undefined).finally(() => (run.stopping = undefined));
|
|
1937
|
-
}
|
|
1938
|
-
}
|
|
1939
|
-
}
|
|
1940
|
-
}
|
|
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
|
-
}
|
|
1984
|
-
/** The door of a run that is not finished, starting or waking its process when it is not live. */
|
|
1985
|
-
async ensureLive(run, timeoutMs = this.options.readyTimeoutMs ?? READY_TIMEOUT_MS, refresh = false) {
|
|
1986
|
-
let deadline = Date.now() + timeoutMs;
|
|
1987
|
-
// A run brought up by a request (a message before the start's recovery reached it) waits for the sweep as well.
|
|
1988
|
-
await this.sweepOnce();
|
|
1989
|
-
await this.pinNeeds(run);
|
|
1990
|
-
// And for its files, which its start copies before it launches it: within the time left.
|
|
1991
|
-
const copying = run.preparing;
|
|
1992
|
-
if (copying) {
|
|
1993
|
-
await untilDeadline(copying, deadline);
|
|
1994
|
-
if (run.preparing === copying)
|
|
1995
|
-
throw new ApiError("unavailable", "the run's files are still being copied into its workspace", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1996
|
-
}
|
|
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.
|
|
2006
|
-
if (run.outcome || run.finishing || run.cancel)
|
|
2007
|
-
throw this.finished(run);
|
|
2008
|
-
const door = this.doorOf(run);
|
|
2009
|
-
if (door)
|
|
2010
|
-
return door;
|
|
2011
|
-
if (!this.live(run)) {
|
|
2012
|
-
// A process that just went is being settled: its run may be over, so nothing starts it again before that.
|
|
2013
|
-
if (run.settles > 0) {
|
|
2014
|
-
// Within the time left: a settle waiting on a busy store must not hold this caller past its deadline.
|
|
2015
|
-
await untilDeadline(run.settling, deadline);
|
|
2016
|
-
if (Date.now() > deadline)
|
|
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);
|
|
2025
|
-
continue;
|
|
2026
|
-
}
|
|
2027
|
-
if (launched)
|
|
2028
|
-
throw new ApiError("internal", `the run's process exited before it served: ${await this.lastLine(run)}`);
|
|
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);
|
|
2032
|
-
// A run already going is never refused a place, but one whose harness this host's memory never holds (after a
|
|
2033
|
-
// restart on a smaller one) is not started: said, never tried.
|
|
2034
|
-
const never = fresh ? undefined : neverFits(run.harness, this.memory);
|
|
2035
|
-
if (never)
|
|
2036
|
-
throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness: run.harness } });
|
|
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.
|
|
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
|
-
}
|
|
2051
|
-
await this.pinSignIn(run);
|
|
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)
|
|
2055
|
-
continue;
|
|
2056
|
-
this.launch(run);
|
|
2057
|
-
launched = true;
|
|
2058
|
-
}
|
|
2059
|
-
}
|
|
2060
|
-
if (Date.now() > deadline)
|
|
2061
|
-
throw this.notUp(run);
|
|
2062
|
-
}
|
|
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
|
-
}
|
|
2075
|
-
/** The refusal of a message to an imported run: it was run elsewhere, and is kept as history. */
|
|
2076
|
-
importedRefusal(run) {
|
|
2077
|
-
const source = run.imported?.source;
|
|
2078
|
-
return new ApiError("not_continuable", `This run was imported from ${source}: it is history, not run here, so it takes no message. Start a new run of the agent.`, {
|
|
2079
|
-
details: { reason: "imported", imported_from: source },
|
|
2080
|
-
next_action: { type: "request", method: "POST", path: `/agents/${run.agentId}/runs`, caller_supplies: ["input", "Idempotency-Key"] },
|
|
2081
|
-
});
|
|
2082
|
-
}
|
|
2083
|
-
finished(run) {
|
|
2084
|
-
const status = run.cancel ? "cancelled" : statusOf(run).status;
|
|
2085
|
-
const why = status === "completed" ? "This run is finished." : `This run ${status === "failed" ? "failed" : "was cancelled"}.`;
|
|
2086
|
-
return new ApiError("not_continuable", `${why} Start a new run of the agent.`, {
|
|
2087
|
-
next_action: { type: "request", method: "POST", path: `/agents/${run.agentId}/runs`, caller_supplies: ["input", "Idempotency-Key"] },
|
|
2088
|
-
});
|
|
2089
|
-
}
|
|
2090
|
-
/** Abort an agentic run's turn running now through the door, when there is one; never wakes the run. A workflow run
|
|
2091
|
-
* has no turn: the door's abort would give it a root conversation. */
|
|
2092
|
-
async abortTurn(run) {
|
|
2093
|
-
if (run.kind === "workflow")
|
|
2094
|
-
return;
|
|
2095
|
-
const door = this.doorOf(run);
|
|
2096
|
-
if (door)
|
|
2097
|
-
await fetch(new URL("/abort", door), { method: "POST", headers: this.headers(run, true), body: "{}", signal: AbortSignal.timeout(5_000) }).catch(() => undefined);
|
|
2098
|
-
}
|
|
2099
|
-
/** One request to the door of a run whose process lives, never waking it (toDoor wakes no run that is finishing): again
|
|
2100
|
-
* while it opens or parks. `turnOrigin`: who sent a turn this request sends (learning-run.ts's REFLECT_ORIGIN), kept in
|
|
2101
|
-
* the run's directory before it goes, where the tool gate reads it (tool-gate.ts NOTE_ONLY_TEXT); a person's message
|
|
2102
|
-
* removes it. */
|
|
2103
|
-
async toLiveDoor(run, path, body, turnOrigin) {
|
|
2104
|
-
if (turnOrigin)
|
|
2105
|
-
await (run.originWrite = writeWhole(join(run.dir, TURN_ORIGIN_FILE), `${JSON.stringify({ origin: turnOrigin })}\n`));
|
|
2106
|
-
for (const deadline = Date.now() + 30_000;; await sleep(200)) {
|
|
2107
|
-
if (!this.live(run) || run.cancel)
|
|
2108
|
-
throw new Error("the run's process is gone");
|
|
2109
|
-
const door = this.doorOf(run);
|
|
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;
|
|
2111
|
-
const data = res ? (await res.json().catch(() => null)) : null;
|
|
2112
|
-
if (res && res.status < 400)
|
|
2113
|
-
return data;
|
|
2114
|
-
if (res && !(res.status === 503 && RETRY_CODES.includes(String(data?.error))))
|
|
2115
|
-
throw new Error(`the run's door answered ${res.status}`);
|
|
2116
|
-
if (Date.now() > deadline)
|
|
2117
|
-
throw new Error("the run's door did not answer");
|
|
2118
|
-
}
|
|
2119
|
-
}
|
|
2120
|
-
async toDoor(run, path, body, readyMs, refresh = false) {
|
|
2121
|
-
const deadline = Date.now() + 30_000;
|
|
2122
|
-
for (;;) {
|
|
2123
|
-
const door = await this.ensureLive(run, readyMs, refresh);
|
|
2124
|
-
const res = await fetch(new URL(path, door), {
|
|
2125
|
-
method: body === undefined ? "GET" : "POST",
|
|
2126
|
-
headers: this.headers(run, body !== undefined),
|
|
2127
|
-
body: body === undefined ? undefined : JSON.stringify(body),
|
|
2128
|
-
signal: AbortSignal.timeout(15_000),
|
|
2129
|
-
}).catch(() => null);
|
|
2130
|
-
const data = res ? (await res.json().catch(() => null)) : null;
|
|
2131
|
-
if (res && !(res.status === 503 && RETRY_CODES.includes(String(data?.error))))
|
|
2132
|
-
return { status: res.status, body: data };
|
|
2133
|
-
if (Date.now() > deadline)
|
|
2134
|
-
throw new ApiError("unavailable", "the run's door did not answer", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
2135
|
-
await sleep(200);
|
|
2136
|
-
}
|
|
2137
|
-
}
|
|
2138
|
-
/** Reads what decides the secrets runs of `run`'s revision are handed (needsOf), once per revision: from `given` (a
|
|
2139
|
-
* start's, read from the store), else from the agent store, waiting out a busy one as a run's end does. */
|
|
2140
|
-
async pinNeeds(run, given) {
|
|
2141
|
-
if (this.needs.has(run.revision))
|
|
2142
|
-
return;
|
|
2143
|
-
const revision = given ?? (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
2144
|
-
this.needs.set(run.revision, await needsOf(revision));
|
|
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
|
-
}
|
|
2192
|
-
/** The saved sign-in the run's browser starts from (sign-ins.ts), resolved before each launch: made at the vendor when
|
|
2193
|
-
* its agent has none, and leased to this run to save unless another run of the agent holds the lease. One that cannot
|
|
2194
|
-
* be had (the vendor not answering, a seal key changed) leaves its browser signed out, said in its log. */
|
|
2195
|
-
async pinSignIn(run) {
|
|
2196
|
-
// Its browser as this launch will find it (launch: a vendor whose key is gone since is unavailable, and gets none).
|
|
2197
|
-
const browser = run.meta.tool_plane && recheckPlane(run.meta.tool_plane, withSecrets(process.env, "all", this.options.storedKeys)).browser;
|
|
2198
|
-
const signIns = this.options.signIns;
|
|
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) {
|
|
2204
|
-
// Never shown in its errors, from now on: a server started since its launch has handed it nothing yet.
|
|
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";
|
|
2261
|
-
}
|
|
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
|
|
2263
|
-
* (`clean`), else by the gone rule (sign-ins.ts). */
|
|
2264
|
-
async releaseSignIn(run, clean = true) {
|
|
2265
|
-
run.signIn = undefined;
|
|
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}`));
|
|
2267
|
-
}
|
|
2268
|
-
launch(run, followUp = run.followUpOpen === true) {
|
|
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)
|
|
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;
|
|
2292
|
-
// Taken by this launch only: a later launch (a relaunch after its process went) opens the run as any other.
|
|
2293
|
-
run.followUpOpen = undefined;
|
|
2294
|
-
// Its secrets go over fd 3, written whole and closed as it starts; it reads them first (secrets.ts). Each launch path
|
|
2295
|
-
// reads its revision's needs first (pinNeeds); one that did not hands no tool key. Which keys, from the keys this
|
|
2296
|
-
// server holds now (its launcher's and the saved ones, never its environment, which under the launcher holds none),
|
|
2297
|
-
// in this same turn as the handover, so a key saved with no restart counts at the next launch, and none can change
|
|
2298
|
-
// in between.
|
|
2299
|
-
const served = withSecrets(process.env, "all", this.options.storedKeys);
|
|
2300
|
-
const needs = this.needs.get(run.revision);
|
|
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;
|
|
2316
|
-
// And its saved sign-in, on the same pipe after them (pinSignIn): a pointer its browser opens, never in its environment.
|
|
2317
|
-
const secrets = Buffer.concat([handover(handed, this.options.storedKeys), ...(mcp ? [mcpHandover(mcp)] : []), ...(run.signIn ? [handoverSignIn(run.signIn)] : [])]);
|
|
2318
|
-
// What it was handed, for the check of what its end-of-run turn writes (learning-run.ts).
|
|
2319
|
-
this.learning.onLaunch(run, handed, mcpSecretValues(mcp ?? {}));
|
|
2320
|
-
// And for what its errors show (refusedValues): each value handed, kept past a key's rotation.
|
|
2321
|
-
run.handed ??= new Set();
|
|
2322
|
-
for (const name of handed) {
|
|
2323
|
-
const value = secret(name, this.options.storedKeys);
|
|
2324
|
-
if (value && value.length >= MIN_SECRET)
|
|
2325
|
-
run.handed.add(value);
|
|
2326
|
-
}
|
|
2327
|
-
for (const value of mcpSecretValues(mcp ?? {}))
|
|
2328
|
-
if (value.length >= MIN_SECRET)
|
|
2329
|
-
run.handed.add(value);
|
|
2330
|
-
if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
|
|
2331
|
-
run.handed.add(run.signIn.ref);
|
|
2332
|
-
const env = {
|
|
2333
|
-
...childEnv(process.env, this.options.token),
|
|
2334
|
-
// The run's box's network, as the server resolved it: never the setting itself, which the run's process ignores.
|
|
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 ?? "",
|
|
2342
|
-
[SECRETS_FD_ENV]: "3",
|
|
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),
|
|
2347
|
-
...this.fauxEnv(),
|
|
2348
|
-
...(run.meta.effort ? { [EFFORT_ENV]: run.meta.effort } : {}),
|
|
2349
|
-
...(this.options.documents ? { [DOCUMENTS_ENV]: this.options.documents } : {}),
|
|
2350
|
-
};
|
|
2351
|
-
// Kept for its metrics: the host's level may change before the run ends.
|
|
2352
|
-
run.meta.launch_thinking = { ...(env[EFFORT_ENV] ? { effort: env[EFFORT_ENV] } : {}), ...(env.AGENT_THINKING ? { host: env.AGENT_THINKING } : {}) };
|
|
2353
|
-
void this.saveMeta(run).catch((error) => warn(run.id, `what its process thinks at is not saved: ${error.message}`));
|
|
2354
|
-
delete env[CAP_ENV];
|
|
2355
|
-
delete env[CAP_MODE_ENV];
|
|
2356
|
-
if (run.meta.max_cost_usd !== undefined)
|
|
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;
|
|
2360
|
-
// A run on the host's default (its revision names no model) gets the model the server picks for its harness, never
|
|
2361
|
-
// the key that gave it: behind a gateway its process holds the gateway's key alone (keysFor) and could not tell. It is
|
|
2362
|
-
// the run's last choice (model.ts hostModel: the tier's variable, then AGENT_MODEL where the harness runs it, then a
|
|
2363
|
-
// key the run holds, then this), so a host's setting the harness can run still wins; and one it cannot (AGENT_MODEL
|
|
2364
|
-
// on Anthropic's model, for codex) no longer leaves the run with none. pi and codex choose through the gateway
|
|
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.
|
|
2367
|
-
delete env[DEFAULT_MODEL_ENV];
|
|
2368
|
-
const harness = run.harness;
|
|
2369
|
-
const defaultModel = run.tooling && !run.tooling.model && !builtinHarness(harness)?.facts?.ownModel ? hostModel(served, "default", harness) : undefined;
|
|
2370
|
-
if (defaultModel)
|
|
2371
|
-
env[DEFAULT_MODEL_ENV] = defaultModel;
|
|
2372
|
-
// Opened for a person's follow-up to a run whose turn had ended: nothing it resumes was cut (app.ts markResumed).
|
|
2373
|
-
delete env[FOLLOW_UP_OPEN_ENV];
|
|
2374
|
-
if (followUp)
|
|
2375
|
-
env[FOLLOW_UP_OPEN_ENV] = "1";
|
|
2376
|
-
// Its tools' providers (tool-plane.ts): resolved at its first launch from its pinned revision and this server's
|
|
2377
|
-
// settings, and kept in its serve.json, so a later change of the settings never changes a run's tools; at a later
|
|
2378
|
-
// launch only checked again (a Parallel key gone makes Parallel unavailable, never another provider). A new run's are
|
|
2379
|
-
// in the serve.json its start writes (start); resolving here is for a run made before that, whose browser stays
|
|
2380
|
-
// Browserbase (keptFromBefore), the vendor it had then, kept as its choice and checked again at each launch like the
|
|
2381
|
-
// rest; a vendor's missing-key refusal an earlier server saved reads as that vendor again (keptVendor), saved back. A
|
|
2382
|
-
// description with no secret
|
|
2383
|
-
// in it, read by the run's process, never by a request. A key saved through the settings API counts as the launcher's
|
|
2384
|
-
// does (secrets.ts), so a saved Parallel key makes Parallel available, and a deleted one unavailable at the next launch.
|
|
2385
|
-
// A capability set to ask or deny since resolves again (a harness's own search cannot wait for a person). Its first
|
|
2386
|
-
// launch, from its start, is told a deny as under ask; a later one is told it denied (relaunchPlane).
|
|
2387
|
-
const settings = this.options.toolSettings?.() ?? {};
|
|
2388
|
-
const capped = run.meta.max_cost_usd !== undefined;
|
|
2389
|
-
const first = run.firstLaunch === true;
|
|
2390
|
-
run.firstLaunch = undefined;
|
|
2391
|
-
const kept = run.meta.tool_plane ? keptVendor(run.meta.tool_plane) : run.tooling ? keptFromBefore(planeFor(served, run.tooling, settings, { capped })) : {};
|
|
2392
|
-
const plane = relaunchPlane(kept, served, run.tooling, settings, { capped, first });
|
|
2393
|
-
if (kept !== run.meta.tool_plane && Object.keys(kept).length) {
|
|
2394
|
-
run.meta.tool_plane = kept;
|
|
2395
|
-
void this.saveMeta(run).catch(() => undefined);
|
|
2396
|
-
}
|
|
2397
|
-
delete env[TOOL_PLANE_ENV];
|
|
2398
|
-
if (Object.keys(plane).length)
|
|
2399
|
-
env[TOOL_PLANE_ENV] = JSON.stringify(plane);
|
|
2400
|
-
// No one can approve here (accounts off): the run's gate refuses an ask instead of parking it (tool-gate.ts).
|
|
2401
|
-
delete env[NO_APPROVER_ENV];
|
|
2402
|
-
if (this.options.approvers === false)
|
|
2403
|
-
env[NO_APPROVER_ENV] = "1";
|
|
2404
|
-
// The decision keys are never in a run's environment, which its tools and its model's provider read (childEnv leaves
|
|
2405
|
-
// out every secret): a run's process gets those it needs once on an inherited pipe, by name: its decision
|
|
2406
|
-
// providers' (decisionProvidersFor), and Parallel's where one of its web tools resolves to Parallel (its plane,
|
|
2407
|
-
// handsParallel). A web tool reaches Parallel only where its own capability resolves there. A run that needs none
|
|
2408
|
-
// gets no pipe at all, and one whose revision was not read gets none.
|
|
2409
|
-
delete env[DECISION_KEY_FD_ENV];
|
|
2410
|
-
// Chosen from the secrets this server holds: out of its environment once its launcher hands them over (secrets.ts).
|
|
2411
|
-
const providers = needs?.decisionProviders;
|
|
2412
|
-
const decisionKeys = providers ? decisionKeysFor(served, { providers, parallelWeb: handsParallel(plane) }) : {};
|
|
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
|
-
}
|
|
2465
|
-
this.markLaunching(run);
|
|
2466
|
-
const log = openSync(join(run.dir, PROCESS_LOG), "a", 0o600);
|
|
2467
|
-
const stdio = ["ignore", "pipe", log, "pipe"];
|
|
2468
|
-
// The first descriptor after the others: macOS aborts the parent of a spawn with a pipe at 16 or above.
|
|
2469
|
-
const keyFd = stdio.length;
|
|
2470
|
-
if (handsKey) {
|
|
2471
|
-
stdio.push("pipe");
|
|
2472
|
-
env[DECISION_KEY_FD_ENV] = String(keyFd);
|
|
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");
|
|
2478
|
-
// A workflow run resumes from its journal when it opens again, so SIGTERM lets it go at once, undrained.
|
|
2479
|
-
const drain = run.kind === "workflow" ? "0s" : (this.options.drainTimeout ?? DRAIN);
|
|
2480
|
-
// Its own door token, which its door takes and its calls to the box relay carry: no other run's process holds it.
|
|
2481
|
-
run.doorToken = ensureRunDoorToken(run.dir);
|
|
2482
|
-
const doorTokenFile = join(run.dir, RUN_DOOR_TOKEN);
|
|
2483
|
-
const child = spawn(process.execPath, [
|
|
2484
|
-
// secrets.ts first, as a preload: the pipe is read and closed before pi-durable-disk's CLI loads or starts anything.
|
|
2485
|
-
"--no-warnings=ExperimentalWarning", "--import", SECRETS_MODULE, this.cli, "run", "--dir", run.dir, "--app", this.app,
|
|
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),
|
|
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);
|
|
2493
|
-
closeSync(log);
|
|
2494
|
-
const pipe = child.stdio[3];
|
|
2495
|
-
pipe?.on("error", () => { });
|
|
2496
|
-
pipe?.end(secrets);
|
|
2497
|
-
if (handsKey) {
|
|
2498
|
-
const keyPipe = child.stdio[keyFd];
|
|
2499
|
-
// A process that dies before it reads the key closes the pipe: that is its exit to settle, not an error here.
|
|
2500
|
-
keyPipe?.on("error", () => undefined);
|
|
2501
|
-
keyPipe?.end(JSON.stringify(decisionKeys));
|
|
2502
|
-
}
|
|
2503
|
-
run.child = child;
|
|
2504
|
-
run.door = undefined;
|
|
2505
|
-
child.once("exit", (code) => {
|
|
2506
|
-
if (run.child === child) {
|
|
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).
|
|
2515
|
-
this.reportedBack(run);
|
|
2516
|
-
void this.settle(run, code, true);
|
|
2517
|
-
});
|
|
2518
|
-
child.once("error", () => {
|
|
2519
|
-
if (run.child === child)
|
|
2520
|
-
run.child = undefined;
|
|
2521
|
-
this.reportedBack(run);
|
|
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
|
-
}
|
|
2573
|
-
this.connect(run);
|
|
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
|
-
}
|
|
2616
|
-
/** Writes the run's launch mark before its process is spawned: a spawn that takes the server down leaves it, and the
|
|
2617
|
-
* next start fails the run rather than launch it again and go down with it. The file exists once the call returns,
|
|
2618
|
-
* which a server's death does not undo; no fsync, which would hold the event loop on the disk at every launch. */
|
|
2619
|
-
markLaunching(run) {
|
|
2620
|
-
closeSync(openSync(join(run.dir, RUN_LAUNCHING), "w", 0o600));
|
|
2621
|
-
run.launching = true;
|
|
2622
|
-
}
|
|
2623
|
-
/** The run's newest launch came through with the server up: its process serves, or exited while it was watched. Its
|
|
2624
|
-
* callers are event handlers, so a mark that cannot be removed is logged, never thrown: a throw there stops the
|
|
2625
|
-
* server and every run on it. The mark left behind fails the run at the next start, which never launches it again. */
|
|
2626
|
-
reportedBack(run) {
|
|
2627
|
-
if (!run.launching)
|
|
2628
|
-
return;
|
|
2629
|
-
run.launching = false;
|
|
2630
|
-
try {
|
|
2631
|
-
rmSync(join(run.dir, RUN_LAUNCHING), { force: true });
|
|
2632
|
-
}
|
|
2633
|
-
catch (error) {
|
|
2634
|
-
this.options.log?.("launch_mark_kept", { run: run.id, code: error.code ?? "unknown" });
|
|
2635
|
-
}
|
|
2636
|
-
}
|
|
2637
|
-
/** Opens the run again on its directory after its process went before the run ended: it resumes from its store. An
|
|
2638
|
-
* agentic run whose first message never landed gets it again, under the same request id. */
|
|
2639
|
-
relaunch(run) {
|
|
2640
|
-
run.relaunches++;
|
|
2641
|
-
warn(run.id, `its process went before the run ended; opening it again (${run.relaunches} of ${MAX_RELAUNCHES})`);
|
|
2642
|
-
this.launch(run);
|
|
2643
|
-
const first = run.meta.input?.content;
|
|
2644
|
-
if (run.kind !== "agentic" || usersOf(run.rows) > 0 || typeof first !== "string")
|
|
2645
|
-
return;
|
|
2646
|
-
run.submitted = 1;
|
|
2647
|
-
this.refresh(run);
|
|
2648
|
-
// As it was first sent: the run never took it, so its work/inputs/ is as its start left it.
|
|
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}`));
|
|
2650
|
-
}
|
|
2651
|
-
/** After the run's process exited, or was found gone: its rows from its released store, then, when it is over, its
|
|
2652
|
-
* carry back. One at a time per run, and none once the run has its outcome. */
|
|
2653
|
-
settle(run, code, exited) {
|
|
2654
|
-
if (this.closed)
|
|
2655
|
-
return Promise.resolve();
|
|
2656
|
-
run.settles++;
|
|
2657
|
-
run.settling = (run.settling ?? Promise.resolve())
|
|
2658
|
-
.then(() => (run.outcome ? undefined : this.settleOnce(run, code, exited)))
|
|
2659
|
-
.catch((error) => {
|
|
2660
|
-
if (!(storeBusy(error) || error instanceof PullPending || error instanceof HolderUnknown) || this.closing)
|
|
2661
|
-
return warn(run.id, `not settled: ${error.message}; the next start tries again`);
|
|
2662
|
-
// A store still held past the run end's retries: settled again later, not left until the next start.
|
|
2663
|
-
const every = this.options.settleRetryMs ?? SETTLE_RETRY_MS;
|
|
2664
|
-
warn(run.id, `not settled: ${error.message}; trying again in ${every / 1000} s`);
|
|
2665
|
-
setTimeout(() => void this.settle(run, code, exited), every).unref();
|
|
2666
|
-
})
|
|
2667
|
-
.finally(() => void run.settles--);
|
|
2668
|
-
return run.settling;
|
|
2669
|
-
}
|
|
2670
|
-
/** `exited`: the process this server supervised exited. Exiting on an error before it released fails the run; going
|
|
2671
|
-
* any other way before the run ended (killed, or found gone at a start) opens it again. */
|
|
2672
|
-
async settleOnce(run, code, exited) {
|
|
2673
|
-
// A run whose files are still being copied has had no process yet: its start launches it, and only a cancel ends it
|
|
2674
|
-
// first (a recovery that lists it meanwhile must not fail it for its launch mark).
|
|
2675
|
-
if (run.preparing && !run.cancel)
|
|
2676
|
-
return;
|
|
2677
|
-
run.feed?.abort();
|
|
2678
|
-
run.feed = undefined;
|
|
2679
|
-
run.working = false;
|
|
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);
|
|
2682
|
-
const released = RELEASED.has(String(record?.status));
|
|
2683
|
-
run.letGo = released;
|
|
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;
|
|
2703
|
-
// Its sign-in's save lease stays with it (below), but no longer than a session it opened could outlive its process.
|
|
2704
|
-
if (gone)
|
|
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}`));
|
|
2706
|
-
// Its metrics are this settle's read, or none: never an earlier end's.
|
|
2707
|
-
run.metrics = undefined;
|
|
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)
|
|
2713
|
-
await this.storeWhenFree(run, true);
|
|
2714
|
-
// Its process gone: an archived run's box is let go now, whatever comes next (an outcome, a wait for the person, a
|
|
2715
|
-
// relaunch), since nothing else would until the next start or archive. This is every archived end that can let a box
|
|
2716
|
-
// go: a settle with the process not gone means another live holder of the run, whose box is its own. That holder is
|
|
2717
|
-
// one this server neither started nor adopted (adoptProcess watches only the holder it adopts), so its later exit
|
|
2718
|
-
// settles nothing here: its box stays held, fail-closed, until the next start's sweep or another archive lets it go.
|
|
2719
|
-
if (gone && (await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined))?.archivedAt)
|
|
2720
|
-
await this.teardown(run);
|
|
2721
|
-
let ended;
|
|
2722
|
-
// A workflow run carries back how its workflow ended, through workflowCarry; cancelled before that, it stopped.
|
|
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.
|
|
2727
|
-
if (run.cancel && !reflecting(run))
|
|
2728
|
-
ended = run.kind === "workflow" ? await this.workflowEnd(run, workflowEnding(record) ?? { status: "stopped" }) : { outcome: "cancelled" };
|
|
2729
|
-
else if (run.finishing)
|
|
2730
|
-
ended = { outcome: run.finishing };
|
|
2731
|
-
else if (run.notSetUp && gone) {
|
|
2732
|
-
run.error = { code: "run_failed", message: "The server went down while it set the run up, before it saved the run's input; the run never started, and a new one can.", retryable: false, details: { reason: SETUP_LOST } };
|
|
2733
|
-
ended = { outcome: "failed" };
|
|
2734
|
-
}
|
|
2735
|
-
else if (run.launching && gone) {
|
|
2736
|
-
run.error = { code: "run_failed", message: "The server went down while it started the run's process, which never came up; it is not started again, since starting it may be what took the server down.", retryable: false, details: { reason: LAUNCH_LOST } };
|
|
2737
|
-
ended = { outcome: "failed" };
|
|
2738
|
-
}
|
|
2739
|
-
else if (exited && !released && code !== null && code !== 0 && (run.resuming !== undefined || continuationOf(run) !== undefined)) {
|
|
2740
|
-
// A raised run's paused process held nothing (its turn had ended at the refusal): its exit without a release, at
|
|
2741
|
-
// its drain's end, say, loses nothing, and the raise's follow-up goes (resumeRaised), never a failed run.
|
|
2742
|
-
return this.refresh(run);
|
|
2743
|
-
}
|
|
2744
|
-
else if (exited && !released && code !== null && code !== 0) {
|
|
2745
|
-
run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await this.lastLine(run)}`, retryable: false };
|
|
2746
|
-
ended = { outcome: "failed" };
|
|
2747
|
-
}
|
|
2748
|
-
else if (!gone && door)
|
|
2749
|
-
ended = undefined;
|
|
2750
|
-
else if (run.kind === "workflow")
|
|
2751
|
-
ended = await this.workflowEnd(run, workflowEnding(record));
|
|
2752
|
-
else {
|
|
2753
|
-
const end = this.decide(run);
|
|
2754
|
-
if (end?.error)
|
|
2755
|
-
run.error = end.error;
|
|
2756
|
-
ended = end && { outcome: end.outcome };
|
|
2757
|
-
}
|
|
2758
|
-
if (!ended) {
|
|
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);
|
|
2770
|
-
// Its sign-in's save lease stays with it until it ends (carryBack), through a relaunch or a restart: a session it
|
|
2771
|
-
// opened before its process went may still be live at the vendor, and would write back over another run's. One
|
|
2772
|
-
// that let go cleanly to wait for its person released its sessions first, so its lease goes now.
|
|
2773
|
-
if (gone && released && !stalled)
|
|
2774
|
-
await this.releaseSignIn(run);
|
|
2775
|
-
// A raised run's follow-up, under way or still to go, opens the run's next process itself (resumeRaised): its
|
|
2776
|
-
// paused process going is no process lost, and no relaunch is counted for it.
|
|
2777
|
-
const continuing = run.resuming !== undefined || continuationOf(run) !== undefined || run.child !== undefined;
|
|
2778
|
-
if (!gone || !stalled || this.closing || continuing)
|
|
2779
|
-
return this.refresh(run);
|
|
2780
|
-
// Opened again without a place, as a run already going, unless its harness never fits this host (a restart on a
|
|
2781
|
-
// smaller one): that run fails with why.
|
|
2782
|
-
const never = neverFits(run.harness, this.memory);
|
|
2783
|
-
if (!never && run.relaunches < MAX_RELAUNCHES) {
|
|
2784
|
-
await this.pinNeeds(run);
|
|
2785
|
-
const refreshing = this.mcpFresh(run);
|
|
2786
|
-
if (refreshing)
|
|
2787
|
-
await refreshing;
|
|
2788
|
-
await this.pinSignIn(run);
|
|
2789
|
-
return this.relaunch(run);
|
|
2790
|
-
}
|
|
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 };
|
|
2792
|
-
ended = { outcome: "failed" };
|
|
2793
|
-
}
|
|
2794
|
-
await this.carryBack(run, ended.outcome, ended.state, ended.summary);
|
|
2795
|
-
}
|
|
2796
|
-
/** A workflow run's carry back, `workflowCarry` of @parcha/pi-durable-agent/workflow on its released store, and its
|
|
2797
|
-
* output when it completed; undefined while its workflow has not ended. */
|
|
2798
|
-
async workflowEnd(run, ending) {
|
|
2799
|
-
if (!ending)
|
|
2800
|
-
return undefined;
|
|
2801
|
-
const { readWorkflowRun, workflowCarry } = await import("@parcha/pi-durable-agent/workflow");
|
|
2802
|
-
// A run's end waits for a busy store as long as its carry back does, not a request's 2 s.
|
|
2803
|
-
const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
2804
|
-
const at = { runId: run.id, storePath: this.storeFile(run), revision };
|
|
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 });
|
|
2807
|
-
if (state === "completed")
|
|
2808
|
-
run.meta.output = (await readWorkflowRun(at, { unlocked: true })).output ?? null;
|
|
2809
|
-
else if (state === "escalated") {
|
|
2810
|
-
const { escalation, escalatedAt } = await readWorkflowRun(at, { unlocked: true });
|
|
2811
|
-
run.meta.review = { kind: escalation?.kind ?? null, node: escalation?.label ?? escalatedAt?.label ?? null, reason: escalation?.summary ?? summary };
|
|
2812
|
-
}
|
|
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
|
-
}
|
|
2818
|
-
await this.readDecisionCost(run);
|
|
2819
|
-
return { outcome: STATUS_OF[state], state, summary };
|
|
2820
|
-
}
|
|
2821
|
-
/** A workflow run's decisions' cost, from their receipts in its released store: a receipt whose cost is unknown leaves
|
|
2822
|
-
* the run's unknown, never $0. Read at its end and again when a restarted server adopts it as ended. */
|
|
2823
|
-
async readDecisionCost(run) {
|
|
2824
|
-
const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
|
|
2825
|
-
// Not its `llm` calls: each completes on the run's marked models, so its cost is a REQUEST_COST entry its usage row
|
|
2826
|
-
// already sums (request-start.ts).
|
|
2827
|
-
const paid = durableDecisions(this.storeFile(run), { unlocked: true }).map((row) => row.cost_usd);
|
|
2828
|
-
if (paid.length)
|
|
2829
|
-
run.decisionCost = paid.every((cost) => typeof cost === "number") ? paid.reduce((a, b) => a + b, 0) : null;
|
|
2830
|
-
if (paid.length)
|
|
2831
|
-
run.decisionsPriced = { known: paid.reduce((a, b) => a + (typeof b === "number" ? b : 0), 0), unpriced: paid.filter((cost) => typeof cost !== "number").length };
|
|
2832
|
-
}
|
|
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
|
|
2834
|
-
* another writer is tried again with backoff; past the last try the run stays unsettled, and the next start carries it back. */
|
|
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);
|
|
2841
|
-
// Ended, it saves to its agent's sign-in no more; but a process that went without letting its sessions go may have
|
|
2842
|
-
// left one live at the vendor, so its lease then ends by the gone rule. One never launched (letGo unset) has none.
|
|
2843
|
-
await this.releaseSignIn(run, run.letGo !== false);
|
|
2844
|
-
// Its process is gone: its box goes with its end, whatever the end (a follow-up after it gets a fresh box; work/ stays).
|
|
2845
|
-
// A remote box's last pull lands first: the end is not recorded until its files are in work/.
|
|
2846
|
-
await this.dropBox(run, true);
|
|
2847
|
-
// Its end-of-run turn closed, and what the turn wrote set aside before the run reads ended (learning-run.ts).
|
|
2848
|
-
await this.learning.beforeSettle(run, outcome);
|
|
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);
|
|
2851
|
-
// An unknown cost keeps what it cost so far beside it, for the list row read from the store.
|
|
2852
|
-
const soFar = cost === null && !run.imported ? soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) : undefined;
|
|
2853
|
-
if (soFar)
|
|
2854
|
-
run.meta.cost_so_far = soFar;
|
|
2855
|
-
else
|
|
2856
|
-
delete run.meta.cost_so_far;
|
|
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.
|
|
2862
|
-
if (run.error)
|
|
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))) } : {}) };
|
|
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
|
|
2865
|
-
// time. A server that settles the run after a kill chooses its own: nothing was sent before the store had an end.
|
|
2866
|
-
const endedAt = (run.endedAt ??= new Date().toISOString());
|
|
2867
|
-
const ending = { state: state ?? (outcome === "cancelled" ? "stopped" : outcome === "completed" ? "completed" : "failed"), ...(cost === null ? {} : { costUsd: cost }), ...(line ? { summary: line } : {}), endedAt };
|
|
2868
|
-
const counted = run.metrics;
|
|
2869
|
-
const end = (metrics) => {
|
|
2870
|
-
try {
|
|
2871
|
-
this.store.carryBack(run.id, metrics ? { ...ending, metrics } : ending);
|
|
2872
|
-
}
|
|
2873
|
-
catch (error) {
|
|
2874
|
-
if (!(error instanceof AgentHomeError && error.code === "exists"))
|
|
2875
|
-
throw error;
|
|
2876
|
-
}
|
|
2877
|
-
};
|
|
2878
|
-
const persist = async () => {
|
|
2879
|
-
await this.saveMeta(run);
|
|
2880
|
-
await whenFree(() => {
|
|
2881
|
-
const metrics = counted && this.storedMetrics(run, counted);
|
|
2882
|
-
try {
|
|
2883
|
-
end(metrics);
|
|
2884
|
-
}
|
|
2885
|
-
catch (error) {
|
|
2886
|
-
// Metrics the store refuses (a name past its limit) never hold up the run's end: it ends without them.
|
|
2887
|
-
if (!(metrics && error instanceof AgentHomeError && error.code === "invalid"))
|
|
2888
|
-
throw error;
|
|
2889
|
-
warn(run.id, `its metrics are not kept: ${error.message}`);
|
|
2890
|
-
end();
|
|
2891
|
-
}
|
|
2892
|
-
}, this.busyDelays(), this.onBusy(run.id, "the agent store"));
|
|
2893
|
-
};
|
|
2894
|
-
try {
|
|
2895
|
-
await persist();
|
|
2896
|
-
}
|
|
2897
|
-
catch (error) {
|
|
2898
|
-
// A store that refuses the write (a full disk, a store fenced by it) must not leave the run unended: it ends here
|
|
2899
|
-
// now, with its cost from its rows, and the write is tried again until it lands. A restart before then reads the
|
|
2900
|
-
// run as it was in the store. Its run.ended waits for the store (persistLater), so a receiver that reads the run
|
|
2901
|
-
// back on its notice reads it ended there too.
|
|
2902
|
-
warn(run.id, `its end could not be written to the agent store (${error.message}); trying again every ${(this.options.settleRetryMs ?? SETTLE_RETRY_MS) / 1000} s`);
|
|
2903
|
-
// An unknown cost stays unknown: never stored as 0.
|
|
2904
|
-
if (cost !== null)
|
|
2905
|
-
run.costUsd = cost;
|
|
2906
|
-
run.outcome = outcome;
|
|
2907
|
-
run.finishing = undefined;
|
|
2908
|
-
run.settled = true;
|
|
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);
|
|
2912
|
-
this.refresh(run);
|
|
2913
|
-
this.persistLater(run, persist);
|
|
2914
|
-
return;
|
|
2915
|
-
}
|
|
2916
|
-
const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
|
|
2917
|
-
// The store's time is the one it was given, unless an earlier end of the run's own landed first (a refused write that
|
|
2918
|
-
// went through after all): the row's then. A read that fails keeps the chosen time, never a new one.
|
|
2919
|
-
if (row?.endedAt)
|
|
2920
|
-
run.endedAt = row.endedAt;
|
|
2921
|
-
if (row?.costUsd !== undefined)
|
|
2922
|
-
run.costUsd = row.costUsd;
|
|
2923
|
-
this.options.log?.("run_ended", { run: run.id, agent: run.agentId, status: outcome, cost_usd: row?.costUsd ?? cost ?? "unknown" });
|
|
2924
|
-
run.outcome = outcome;
|
|
2925
|
-
run.finishing = undefined;
|
|
2926
|
-
run.settled = true;
|
|
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);
|
|
2932
|
-
this.refresh(run);
|
|
2933
|
-
this.notice(run, "run.ended", run.endedAt);
|
|
2934
|
-
// Only once the run has ended as it would without learning: a slow or failing check never holds the job.
|
|
2935
|
-
void this.learning.afterSettle(run);
|
|
2936
|
-
}
|
|
2937
|
-
/** The run's metrics as the store keeps them: what its entries say it used, the effort its newest process ran at (unknown
|
|
2938
|
-
* for one an older server started), and on a harness other than pi the model its revision names (its entries name the
|
|
2939
|
-
* harness). A busy store throws, for the write's retries; a revision that cannot be read otherwise adds nothing. */
|
|
2940
|
-
storedMetrics(run, counted) {
|
|
2941
|
-
let revision;
|
|
2942
|
-
try {
|
|
2943
|
-
revision = this.store.readRevision(run.revision);
|
|
2944
|
-
}
|
|
2945
|
-
catch (error) {
|
|
2946
|
-
if (storeBusy(error))
|
|
2947
|
-
throw error;
|
|
2948
|
-
return counted;
|
|
2949
|
-
}
|
|
2950
|
-
const body = revision.kind === "agentic" ? revision.body : undefined;
|
|
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.
|
|
2955
|
-
const launched = run.meta.launch_thinking;
|
|
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 } : {}) };
|
|
2959
|
-
}
|
|
2960
|
-
/** Tries `persist` again every settleRetryMs while the server lives, until it lands. */
|
|
2961
|
-
persistLater(run, persist) {
|
|
2962
|
-
const timer = setTimeout(() => {
|
|
2963
|
-
if (this.closing)
|
|
2964
|
-
return;
|
|
2965
|
-
persist().then(async () => {
|
|
2966
|
-
const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
|
|
2967
|
-
if (row?.endedAt)
|
|
2968
|
-
run.endedAt = row.endedAt;
|
|
2969
|
-
if (row?.costUsd !== undefined)
|
|
2970
|
-
run.costUsd = row.costUsd;
|
|
2971
|
-
// In the store at last: its run.ended goes now.
|
|
2972
|
-
this.notice(run, "run.ended", run.endedAt);
|
|
2973
|
-
await this.learning.afterSettle(run);
|
|
2974
|
-
}, () => this.persistLater(run, persist));
|
|
2975
|
-
}, this.options.settleRetryMs ?? SETTLE_RETRY_MS);
|
|
2976
|
-
timer.unref();
|
|
2977
|
-
}
|
|
2978
|
-
/** How long a run's end waits for a busy store, step by step. */
|
|
2979
|
-
busyDelays() {
|
|
2980
|
-
return this.options.carryBackRetry?.delaysMs ?? CARRY_BACK_RETRIES_MS;
|
|
2981
|
-
}
|
|
2982
|
-
/** Hears that `what` was busy for run `runId`, and says so when another try follows. */
|
|
2983
|
-
onBusy(runId, what) {
|
|
2984
|
-
return (attempt, delay) => {
|
|
2985
|
-
this.options.carryBackRetry?.onBusy?.(runId, attempt);
|
|
2986
|
-
if (delay !== undefined)
|
|
2987
|
-
warn(runId, `${what} is busy; trying again in ${delay} ms (${attempt + 1} of ${this.busyDelays().length})`);
|
|
2988
|
-
};
|
|
2989
|
-
}
|
|
2990
|
-
/** The run's store, read again while another connection holds it, within the same retries. */
|
|
2991
|
-
storeWhenFree(run, atEnd = false) {
|
|
2992
|
-
return whenFree(() => this.readStore(run, atEnd), this.busyDelays(), this.onBusy(run.id, "its store"));
|
|
2993
|
-
}
|
|
2994
|
-
// ---- acting ---------------------------------------------------------------------------------------------------------
|
|
2995
|
-
/** Start a run of `revision` (number `version`) of `entry`'s agent: `startRun` in the store, then its process, then an
|
|
2996
|
-
* agentic run's first message, `input.content`. */
|
|
2997
|
-
/** A place for one more live run of `harness`, taken for this start (counted in `starting` and `startingMib` from
|
|
2998
|
-
* here, so two starts at once cannot both take the last place), or 429 rate_limited; the function returned gives it
|
|
2999
|
-
* back once the run holds it as a live run, or did not start. A place is one under the cap on the count and the
|
|
3000
|
-
* memory a run of its harness reserves (host.ts): both must be free. A run that has ended (failed, completed,
|
|
3001
|
-
* cancelled) still holds its place until its process exits; a start that needs that place waits for it, up to that
|
|
3002
|
-
* process's drain and kill, never refused for a place already being given back. A harness whose one run is more than
|
|
3003
|
-
* the whole memory for runs is refused at once, never a 429 (capabilities say so too). From the read of what is held
|
|
3004
|
-
* to the reservation nothing awaits, so two starts at once never both take the last of it. */
|
|
3005
|
-
async takePlace(harness) {
|
|
3006
|
-
const { memory, options: { maxRuns: max } } = this;
|
|
3007
|
-
const need = runMibOf(harness);
|
|
3008
|
-
const never = neverFits(harness, memory);
|
|
3009
|
-
if (never)
|
|
3010
|
-
throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness } });
|
|
3011
|
-
for (const deadline = Date.now() + this.killAfterMs() + 1_000;; await sleep(50)) {
|
|
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));
|
|
3016
|
-
const counted = max === undefined || holding.length + this.starting < max;
|
|
3017
|
-
const held = holding.reduce((sum, run) => sum + runMibOf(run.harness), this.startingMib);
|
|
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).
|
|
3019
|
-
const fits = held === 0 || held + need <= runsMemoryMib(memory);
|
|
3020
|
-
if (counted && fits)
|
|
3021
|
-
break;
|
|
3022
|
-
const leaving = holding.some((run) => run.outcome || run.finishing || run.cancel);
|
|
3023
|
-
if (!leaving || Date.now() > deadline) {
|
|
3024
|
-
if (!counted)
|
|
3025
|
-
throw new ApiError("rate_limited", `This server runs at most ${max} runs at once (max_concurrent_runs); start this one when another ends.`, { retry_after_ms: 5_000, details: { max_concurrent_runs: max } }, { "retry-after": "5" });
|
|
3026
|
-
throw new ApiError("rate_limited", memoryFull(harness, memory, held), { retry_after_ms: 5_000, details: { max_concurrent_runs: max ?? null, harness, needs_mb: need, free_mb: Math.max(0, runsMemoryMib(memory) - held) } }, { "retry-after": "5" });
|
|
3027
|
-
}
|
|
3028
|
-
}
|
|
3029
|
-
this.starting++;
|
|
3030
|
-
this.startingMib += need;
|
|
3031
|
-
return () => {
|
|
3032
|
-
this.starting--;
|
|
3033
|
-
this.startingMib -= need;
|
|
3034
|
-
};
|
|
3035
|
-
}
|
|
3036
|
-
/** `inputs` copies the run's files into its work/ (uploads.ts), after the store made it and before its process starts. */
|
|
3037
|
-
async create(entry, revision, version, options) {
|
|
3038
|
-
await this.sweepOnce();
|
|
3039
|
-
const release = await this.takePlace(harnessOfBody(revision.body));
|
|
3040
|
-
try {
|
|
3041
|
-
// Read again: the place may have been waited for, and the agent archived meanwhile.
|
|
3042
|
-
const now = await this.options.agents.get(entry.agent.id);
|
|
3043
|
-
if (now?.agent.archivedAt)
|
|
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).
|
|
3046
|
-
return await this.start(entry, revision, version, options);
|
|
3047
|
-
}
|
|
3048
|
-
finally {
|
|
3049
|
-
release();
|
|
3050
|
-
}
|
|
3051
|
-
}
|
|
3052
|
-
/** Writes the serve.json of a run being set up. When it fails, the store has the run as running and no process will
|
|
3053
|
-
* run it: it ends failed here, never left for a later start to open with half its files. */
|
|
3054
|
-
async setUp(runId, dir, meta) {
|
|
3055
|
-
try {
|
|
3056
|
-
await writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`);
|
|
3057
|
-
}
|
|
3058
|
-
catch (error) {
|
|
3059
|
-
const summary = `The run could not be set up: ${error.message}`;
|
|
3060
|
-
await this.options.agents.request(() => this.store.carryBack(runId, { state: "failed", summary })).catch((undo) => warn(runId, `not ended after its setup failed: ${undo.message}`));
|
|
3061
|
-
throw error;
|
|
3062
|
-
}
|
|
3063
|
-
}
|
|
3064
|
-
async start(entry, revision, version, options) {
|
|
3065
|
-
// Its tools' providers, resolved before the run exists (tool-plane.ts) and kept in the serve.json its start writes first,
|
|
3066
|
-
// so a launch after a crash reads them back, never the settings of that moment, and keeping them is no write of its own.
|
|
3067
|
-
const tooling = await toolingOf(revision);
|
|
3068
|
-
const plane = tooling ? planeFor(withSecrets(process.env, "all", this.options.storedKeys), tooling, this.options.toolSettings?.() ?? {}, { capped: options.maxCostUsd !== undefined, run: true }) : {};
|
|
3069
|
-
// A run that learns: its seed read before it is made (learning-run.ts).
|
|
3070
|
-
const pin = await this.learning.onStart(entry.agent.id, revision);
|
|
3071
|
-
const started = await this.options.agents.request(() => this.store.startRun({ agent: entry.agent.id, revision: revision.id, ...(options.origin ? { origin: options.origin } : {}) })).catch((error) => storeError(error, "revision"));
|
|
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.
|
|
3073
|
-
if (started.existing)
|
|
3074
|
-
return (await this.get(started.runId));
|
|
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.
|
|
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);
|
|
3129
|
-
}
|
|
3130
|
-
const run = held;
|
|
3131
|
-
const meta = run.meta;
|
|
3132
|
-
// A seed that failed is a learning row from the start, and its learning's end is in the ledger.
|
|
3133
|
-
this.show(run);
|
|
3134
|
-
void this.learning.onSaved(run, meta.learning);
|
|
3135
|
-
this.options.log?.("run_started", { run: run.id, agent: run.agentId, kind: run.kind });
|
|
3136
|
-
if (revision.kind === "agentic")
|
|
3137
|
-
run.submitted = 1;
|
|
3138
|
-
this.refresh(run);
|
|
3139
|
-
if (options.inputs) {
|
|
3140
|
-
// Listed from here, so a request may reach it while it copies: `preparing` holds it until its files are in.
|
|
3141
|
-
const prepared = this.prepare(run, started.workspace, options.inputs).finally(() => void (run.preparing = undefined));
|
|
3142
|
-
// Never rejected: a request waiting on it reads how the start ended from the run; the start's own error is the create's.
|
|
3143
|
-
run.preparing = prepared.then(() => undefined, () => undefined);
|
|
3144
|
-
if (!(await prepared))
|
|
3145
|
-
return run;
|
|
3146
|
-
}
|
|
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.
|
|
3150
|
-
this.launch(run);
|
|
3151
|
-
if (revision.kind === "workflow")
|
|
3152
|
-
return run;
|
|
3153
|
-
// The first message names the files given to the run (run-manifest.ts), on every harness.
|
|
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) => {
|
|
3155
|
-
run.submitted = 0;
|
|
3156
|
-
// The run ended before its first message reached it (a process that crashed at its start): how it ended stands.
|
|
3157
|
-
if (run.outcome || run.finishing || run.cancel)
|
|
3158
|
-
return;
|
|
3159
|
-
run.error = { code: "run_failed", message: error.message, retryable: false };
|
|
3160
|
-
if (this.live(run))
|
|
3161
|
-
this.finish(run, "failed");
|
|
3162
|
-
else if (!run.cancel)
|
|
3163
|
-
void this.settle(run, 1, true);
|
|
3164
|
-
});
|
|
3165
|
-
return run;
|
|
3166
|
-
}
|
|
3167
|
-
/** Copies the run's files into its work/ under the launch mark: a server that goes down while it copies leaves the
|
|
3168
|
-
* mark, and the next start fails the run rather than run it on part of its files. Copied whole, the mark goes, and the
|
|
3169
|
-
* launch makes its own. False when the copy failed, and the run ended so (or was cancelled meanwhile). */
|
|
3170
|
-
async prepare(run, work, inputs) {
|
|
3171
|
-
try {
|
|
3172
|
-
// The mark itself may fail (a full disk): the run ends as when the copy does.
|
|
3173
|
-
this.markLaunching(run);
|
|
3174
|
-
await inputs(work);
|
|
3175
|
-
}
|
|
3176
|
-
catch (error) {
|
|
3177
|
-
run.submitted = 0;
|
|
3178
|
-
// Cancelled while it copied: it ends so.
|
|
3179
|
-
if (!(run.outcome || run.cancel)) {
|
|
3180
|
-
run.error = { code: "run_failed", message: `The run's files could not be copied into its workspace: ${error.message}`, retryable: false };
|
|
3181
|
-
await this.carryBack(run, "failed");
|
|
3182
|
-
}
|
|
3183
|
-
// The mark goes only once the store has the run's end: a server that goes down before then finds it, and fails the
|
|
3184
|
-
// run rather than launch it on part of its files.
|
|
3185
|
-
const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
|
|
3186
|
-
if (row && row.state !== "running")
|
|
3187
|
-
this.reportedBack(run);
|
|
3188
|
-
return false;
|
|
3189
|
-
}
|
|
3190
|
-
this.reportedBack(run);
|
|
3191
|
-
return true;
|
|
3192
|
-
}
|
|
3193
|
-
/** One message to the run's door. `origin`: who wrote it when the person did not (a raised cap's follow-up, an
|
|
3194
|
-
* approval's resume), carried to its user entry so the Timeline shows it as the server's (pi-durable-agent's
|
|
3195
|
-
* MessageOrigin); the model reads the same text either way. `answers: false`: the run's door refuses the message
|
|
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
|
|
3198
|
-
* turn that may end so; decided at the door's admission, past every wait here. */
|
|
3199
|
-
async submit(run, content, whenBusy, requestId, readyMs, origin, answers = true) {
|
|
3200
|
-
await this.beforeSubmit?.(run.id, content);
|
|
3201
|
-
const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy, ...(origin ? { origin } : {}), ...(answers ? {} : { answers: false, asks: [ASK_TOOL], parks: [APPROVAL_ENTRY] }) }, readyMs, true);
|
|
3202
|
-
if (answer.status === 409 && answer.body?.error === "WAITING")
|
|
3203
|
-
throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
|
|
3204
|
-
if (answer.status === 409 && answer.body?.error === "BUSY" && !answers)
|
|
3205
|
-
throw new ApiError("rate_limited", "The run is working: a message that may not answer it waits until it is idle.", { retry_after_ms: 5_000, details: { reason: "working" } });
|
|
3206
|
-
if (answer.status >= 400)
|
|
3207
|
-
throw new ApiError(answer.status === 409 ? "not_continuable" : "internal", String(answer.body?.message ?? answer.body?.error ?? "the run refused the message"));
|
|
3208
|
-
}
|
|
3209
|
-
/** Whether the run's harness takes a message mid-turn. */
|
|
3210
|
-
steers(run) {
|
|
3211
|
-
return run.kind !== "agentic" || (builtinHarness(run.harness)?.steer ?? false);
|
|
3212
|
-
}
|
|
3213
|
-
/** Whether the run's store already took a message under `requestId`: a trigger's firing sent it, and the server went
|
|
3214
|
-
* down before it wrote so. Read before sending it again, so a completed run is not opened again for a message it
|
|
3215
|
-
* already has. Only for a run with no live process: a live one holds its store, and takes the message through its
|
|
3216
|
-
* door, which takes one per id anyway. The store keeps the id as JSON text, as pi submits it, or as a harness's door
|
|
3217
|
-
* keeps its journal (doorKey), where a busy refusal is not a message taken (doorTook). A store held past the retries
|
|
3218
|
-
* throws as busy. */
|
|
3219
|
-
async tookMessage(run, requestId) {
|
|
3220
|
-
if (this.live(run))
|
|
3221
|
-
return false;
|
|
3222
|
-
const file = this.storeFile(run);
|
|
3223
|
-
if (!(await stat(file).catch(() => null)))
|
|
3224
|
-
return false;
|
|
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 () => {
|
|
3227
|
-
try {
|
|
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));
|
|
3244
|
-
}
|
|
3245
|
-
catch (error) {
|
|
3246
|
-
// A store that keeps no submissions has taken none.
|
|
3247
|
-
if (/no such table/.test(error.message))
|
|
3248
|
-
return false;
|
|
3249
|
-
throw error;
|
|
3250
|
-
}
|
|
3251
|
-
});
|
|
3252
|
-
}
|
|
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
|
|
3254
|
-
* its newest raise (a retry, which changes nothing). serve.json keeps it before any answer, and a raise it could not keep
|
|
3255
|
-
* is undone, so the run's next process opens under it (CAP_ENV), as does a server started again. A run paused at its
|
|
3256
|
-
* cap goes on: the raise names the pause it answers, and the pause gets one follow-up, "The cap was raised to $X;
|
|
3257
|
-
* continue the task." under an id fixed now, which refresh sends once the paused process is gone (resumeRaised), here
|
|
3258
|
-
* or after a restart; a second raise before it goes raises what it says. A run working keeps the cap its process was
|
|
3259
|
-
* opened with until its next process. Raises of one run are taken one at a time. */
|
|
3260
|
-
async raiseCap(run, cap) {
|
|
3261
|
-
const before = run.raising ?? Promise.resolve();
|
|
3262
|
-
const taking = before.catch(() => undefined).then(() => this.takeRaise(run, cap));
|
|
3263
|
-
run.raising = taking.catch(() => undefined);
|
|
3264
|
-
return taking;
|
|
3265
|
-
}
|
|
3266
|
-
async takeRaise(run, cap) {
|
|
3267
|
-
if (run.imported)
|
|
3268
|
-
throw this.importedRefusal(run);
|
|
3269
|
-
if (run.cancel || run.finishing || TERMINAL.has(statusOf(run).status))
|
|
3270
|
-
throw this.finished(run);
|
|
3271
|
-
const from = run.meta.max_cost_usd;
|
|
3272
|
-
if (from === undefined)
|
|
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);
|
|
3276
|
-
const last = run.meta.cap_raised?.at(-1);
|
|
3277
|
-
const pause = pauseOf(run);
|
|
3278
|
-
const next = continuationOf(run);
|
|
3279
|
-
// The same raise again (a retry): what the first one did stands.
|
|
3280
|
-
if (Math.abs(cap - from) <= CAP_TOLERANCE && last && Math.abs(last.to - cap) <= CAP_TOLERANCE) {
|
|
3281
|
-
// Resumed, as the first answer said, unless the run has since paused anew at another refusal: no raise of that one.
|
|
3282
|
-
const answered = last.pause !== undefined && run.meta.cap_continue?.pause === last.pause && (pause === undefined || pause === last.pause) ? run.meta.cap_continue : undefined;
|
|
3283
|
-
return answered ? { resumed: true, messageId: answered.message_id } : { resumed: false };
|
|
3284
|
-
}
|
|
3285
|
-
if (!(cap > from + CAP_TOLERANCE))
|
|
3286
|
-
throw invalid([{ field: "max_cost_usd", reason: "invalid", message: `A cap is only raised: name more than the run's ${money(from)}.` }]);
|
|
3287
|
-
// Built on a copy and written first: nothing reads the raise (its cap, the pause it answers, its follow-up) before
|
|
3288
|
-
// serve.json keeps it, so until then a message is still 409 budget_reached, the run reads its old cap and no
|
|
3289
|
-
// follow-up goes; a raise the write fails leaves the run as it was, and a retry raises it again.
|
|
3290
|
-
const raised = [...(run.meta.cap_raised ?? []), { from, to: cap, at: new Date().toISOString(), ...(pause ? { pause } : {}) }];
|
|
3291
|
-
let follow = run.meta.cap_continue;
|
|
3292
|
-
if (pause !== undefined && next === undefined) {
|
|
3293
|
-
// The pause's one follow-up, by an id fixed now, and the process being let go then, which it waits out.
|
|
3294
|
-
const paused = this.live(run) ? this.liveIdentity(run) : undefined;
|
|
3295
|
-
follow = { pause, message_id: `cap-${raised.length}-${randomBytes(4).toString("hex")}`, sent: false, tries: 0, ...(paused ? { paused } : {}) };
|
|
3296
|
-
}
|
|
3297
|
-
else if (next) {
|
|
3298
|
-
// A raise of a pause whose follow-up has not gone: that one follow-up goes, under this cap, with its tries anew.
|
|
3299
|
-
const { error: _, ...rest } = next;
|
|
3300
|
-
follow = { ...rest, tries: 0 };
|
|
3301
|
-
}
|
|
3302
|
-
await this.saveMeta(run, () => ({ ...run.meta, max_cost_usd: cap, cap_raised: raised, ...(follow ? { cap_continue: follow } : {}) }));
|
|
3303
|
-
run.meta.max_cost_usd = cap;
|
|
3304
|
-
run.meta.cap_raised = raised;
|
|
3305
|
-
if (next && follow) {
|
|
3306
|
-
// The same follow-up object resumeRaised may hold, renewed in place.
|
|
3307
|
-
next.tries = 0;
|
|
3308
|
-
delete next.error;
|
|
3309
|
-
}
|
|
3310
|
-
else if (follow)
|
|
3311
|
-
run.meta.cap_continue = follow;
|
|
3312
|
-
if (next && typeof run.resuming === "number")
|
|
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);
|
|
3317
|
-
this.refresh(run);
|
|
3318
|
-
const answered = pause !== undefined ? run.meta.cap_continue : undefined;
|
|
3319
|
-
if (!answered)
|
|
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.` } : {}) };
|
|
3321
|
-
return { resumed: true, messageId: answered.message_id };
|
|
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
|
-
}
|
|
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
|
|
3486
|
-
* follow-up to a run whose process has gone (message()), so the process it starts resumes nothing and opens under the
|
|
3487
|
-
* new cap, or to the process another launch started. Marked sent in serve.json. One that cannot be sent is tried
|
|
3488
|
-
* again (CONTINUE_RETRY_MS), and after CONTINUE_TRIES the run fails, saying why: never a pause stuck in silence. */
|
|
3489
|
-
async resumeRaised(run, next) {
|
|
3490
|
-
run.resuming = "sending";
|
|
3491
|
-
if (!this.live(run))
|
|
3492
|
-
run.followUpOpen = true;
|
|
3493
|
-
run.submitted++;
|
|
3494
|
-
this.refresh(run);
|
|
3495
|
-
const cap = run.meta.max_cost_usd ?? 0;
|
|
3496
|
-
try {
|
|
3497
|
-
// The server's line, shown as the server's (MessageOrigin), never as the person's: the model reads the same text.
|
|
3498
|
-
await this.submit(run, `The cap was raised to ${money(cap)}; continue the task.`, "followUp", next.message_id, undefined, { kind: "server", reason: "cap_raised" });
|
|
3499
|
-
// Marked sent once serve.json says so. Should that write fail, it went all the same (the door holds it), and its
|
|
3500
|
-
// run no longer stands at the pause, so nothing sends it again.
|
|
3501
|
-
await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, sent: true } })).then(() => void (next.sent = true), (error) => warn(run.id, `its raised cap's follow-up went, but is not marked sent: ${error.message}`));
|
|
3502
|
-
run.resuming = undefined;
|
|
3503
|
-
}
|
|
3504
|
-
catch (error) {
|
|
3505
|
-
run.submitted = Math.max(0, run.submitted - 1);
|
|
3506
|
-
// The try counts here whether or not serve.json can say so, so its tries stay bounded.
|
|
3507
|
-
const tried = { tries: next.tries + 1, error: error.message };
|
|
3508
|
-
await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, ...tried } })).catch(() => undefined);
|
|
3509
|
-
Object.assign(next, tried);
|
|
3510
|
-
if (next.tries >= CONTINUE_TRIES) {
|
|
3511
|
-
run.resuming = undefined;
|
|
3512
|
-
warn(run.id, `its raised cap's follow-up was not sent in ${next.tries} tries (${next.error}); the run fails`);
|
|
3513
|
-
return this.failRaised(run, cap, next.error);
|
|
3514
|
-
}
|
|
3515
|
-
const wait = CONTINUE_RETRY_MS[next.tries - 1] ?? CONTINUE_RETRY_MS.at(-1);
|
|
3516
|
-
warn(run.id, `its raised cap's follow-up was not sent (${next.error}); tried again in ${wait / 1000} s`);
|
|
3517
|
-
const at = Date.now() + wait;
|
|
3518
|
-
run.resuming = at;
|
|
3519
|
-
setTimeout(() => {
|
|
3520
|
-
if (run.resuming !== at)
|
|
3521
|
-
return;
|
|
3522
|
-
run.resuming = undefined;
|
|
3523
|
-
this.refresh(run);
|
|
3524
|
-
}, wait).unref();
|
|
3525
|
-
this.refresh(run);
|
|
3526
|
-
}
|
|
3527
|
-
finally {
|
|
3528
|
-
run.followUpOpen = undefined;
|
|
3529
|
-
}
|
|
3530
|
-
}
|
|
3531
|
-
/** Ends a raised run whose follow-up could not be sent: failed, in words a person can act on. */
|
|
3532
|
-
async failRaised(run, cap, why) {
|
|
3533
|
-
if (run.outcome || run.finishing || run.cancel)
|
|
3534
|
-
return;
|
|
3535
|
-
run.error = { code: "run_failed", message: `The run's cap was raised to ${money(cap)}, but the run could not be sent on (${why ?? "no answer"}). Start it again to go on.`, retryable: false };
|
|
3536
|
-
run.finishing = "failed";
|
|
3537
|
-
run.endedAt = new Date().toISOString();
|
|
3538
|
-
this.mark(run);
|
|
3539
|
-
if (this.live(run))
|
|
3540
|
-
this.terminate(run);
|
|
3541
|
-
else
|
|
3542
|
-
await this.settle(run, null, false);
|
|
3543
|
-
}
|
|
3544
|
-
/** One message to an agentic run, its mode chosen by the run's state (the contract's table). `requestId`: the message's
|
|
3545
|
-
* id in the run's store, which takes one message per id (a trigger's firing key); default a new one. */
|
|
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 } = {}) {
|
|
3548
|
-
if (run.imported)
|
|
3549
|
-
throw this.importedRefusal(run);
|
|
3550
|
-
// A cancelled run takes no message, whether or not its end is written yet.
|
|
3551
|
-
if (run.cancel)
|
|
3552
|
-
throw this.finished(run);
|
|
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;
|
|
3561
|
-
if (read) {
|
|
3562
|
-
await this.personsTurn(run);
|
|
3563
|
-
// Read again after that wait, with nothing awaited from here to the decline's own write: an answer, a stop or a
|
|
3564
|
-
// cancel that landed meanwhile stands (the first answer wins, and a stop's withdrawal is never replaced), and the
|
|
3565
|
-
// message is then a message, under the run's state now. It declines only the call it read, which the person saw:
|
|
3566
|
-
// another parked since waits for its own answer.
|
|
3567
|
-
const waiting = waitingApproval(run);
|
|
3568
|
-
if (waiting?.id === read.id && !run.cancel && !run.stopping)
|
|
3569
|
-
return this.declineBy(run, waiting, content);
|
|
3570
|
-
if (run.cancel)
|
|
3571
|
-
throw this.finished(run);
|
|
3572
|
-
}
|
|
3573
|
-
// Every wait first, then a last look for a stop in flight, again after any wait a stop came during: from that look
|
|
3574
|
-
// to the count below nothing awaits, so no stop can begin in between.
|
|
3575
|
-
do {
|
|
3576
|
-
// A stop in flight is answered first. Sent between its mark and its abort, a message would read the run stopped, go
|
|
3577
|
-
// to the turn the abort is cutting, and be dropped with it, its row never coming.
|
|
3578
|
-
if (run.stopping)
|
|
3579
|
-
await this.waitWhile(() => run.stopping === true, 50, "The run is being stopped");
|
|
3580
|
-
// A run that reads finished before its end is written (its process still closing, or its carry back waiting on the
|
|
3581
|
-
// store) is answered once the end is in: then it is completed and opens again, or it is failed or cancelled.
|
|
3582
|
-
if (run.finishing && !run.outcome)
|
|
3583
|
-
await this.waitWhile(() => Boolean(run.finishing && !run.outcome), 100, "The run's end is still being written");
|
|
3584
|
-
// A run another message is opening again is answered once that opening is done: reopen() clears the run's end
|
|
3585
|
-
// before it lays the run's notes again (learning-run.ts onReopen), and a message read meanwhile would launch the run
|
|
3586
|
-
// before they are back.
|
|
3587
|
-
if (run.reopening)
|
|
3588
|
-
await run.reopening.catch(() => undefined);
|
|
3589
|
-
// A raised run whose follow-up has not gone yet (its paused process still letting go, or the follow-up being sent)
|
|
3590
|
-
// takes a message once it has: after it, as the next turn, never into the process being let go.
|
|
3591
|
-
const following = () => continuationOf(run) !== undefined || run.resuming === "sending";
|
|
3592
|
-
if (following()) {
|
|
3593
|
-
await this.waitWhile(following, 100, "The run's raised cap's follow-up is still being sent");
|
|
3594
|
-
// Its follow-up's turn may have ended the run meanwhile (a quick answer): its end is written first, so the message
|
|
3595
|
-
// then opens it again, as one to any ended run does, never refused for an end still being written.
|
|
3596
|
-
await this.waitWhile(() => run.settles > 0 || Boolean(run.finishing && !run.outcome), 100, "The run's end is still being written");
|
|
3597
|
-
}
|
|
3598
|
-
if (run.kind === "agentic" && statusOf(run).status === "completed")
|
|
3599
|
-
await (run.reopening ??= this.reopen(run).finally(() => (run.reopening = undefined)));
|
|
3600
|
-
} while (run.stopping);
|
|
3601
|
-
const steers = this.steers(run);
|
|
3602
|
-
const { status, state } = statusOf(run);
|
|
3603
|
-
if (TERMINAL.has(status))
|
|
3604
|
-
throw this.finished(run);
|
|
3605
|
-
// Paused at its cap: a message would be refused for the same room, so the cap is raised first.
|
|
3606
|
-
const paused = pausedAt(run);
|
|
3607
|
-
if (paused !== undefined)
|
|
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 } });
|
|
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
|
|
3610
|
-
// the same run, which the contract calls follow_up, never a steer it does not do.
|
|
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;
|
|
3614
|
-
const mode = working ? (steers ? "steer" : "follow_up") : status === "input_required" && state === "waiting" ? "answer" : "follow_up";
|
|
3615
|
-
// A message that may not answer (a trigger's): one that would is refused here, past every wait, before it is sent.
|
|
3616
|
-
if (mode === "answer" && !answers)
|
|
3617
|
-
throw waitingRefusal();
|
|
3618
|
-
const messageId = requestId ?? `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
|
|
3619
|
-
// A follow-up to a run the person stopped, whose process has gone: its turn had ended, so the process this message
|
|
3620
|
-
// starts resumes nothing. With its process live the message starts none, and a relaunch after that process dies
|
|
3621
|
-
// under the message is a crash's, which keeps its row.
|
|
3622
|
-
if (status === "input_required" && state === "idle" && !this.live(run))
|
|
3623
|
-
run.followUpOpen = true;
|
|
3624
|
-
run.submitted++;
|
|
3625
|
-
this.refresh(run);
|
|
3626
|
-
try {
|
|
3627
|
-
// After every wait, and once the count above holds the run from ending (so no end-of-run turn is asked from here):
|
|
3628
|
-
// one asked while this message waited for the run's end wrote its origin then, after any earlier removal.
|
|
3629
|
-
await this.personsTurn(run);
|
|
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);
|
|
3635
|
-
}
|
|
3636
|
-
catch (error) {
|
|
3637
|
-
run.submitted = Math.max(0, run.submitted - 1);
|
|
3638
|
-
this.refresh(run);
|
|
3639
|
-
throw error;
|
|
3640
|
-
}
|
|
3641
|
-
finally {
|
|
3642
|
-
run.followUpOpen = undefined;
|
|
3643
|
-
}
|
|
3644
|
-
return { mode, messageId };
|
|
3645
|
-
}
|
|
3646
|
-
/** A person's turn is sent next: no turn from here on is the server's own end-of-run turn (tool-gate.ts NOTE_ONLY_TEXT),
|
|
3647
|
-
* so its origin goes, right before the turn is sent. */
|
|
3648
|
-
async personsTurn(run) {
|
|
3649
|
-
// A write of the origin still in flight lands first, then goes: none starts from here (learning-run.ts reflectTurn).
|
|
3650
|
-
await run.originWrite?.catch(() => undefined);
|
|
3651
|
-
await rm(join(run.dir, TURN_ORIGIN_FILE), { force: true }).catch((error) => warn(run.id, `its turn's origin is not removed: ${error.message}`));
|
|
3652
|
-
await runsTestHooks.personsTurn?.(run.dir);
|
|
3653
|
-
}
|
|
3654
|
-
/** Waits, up to a request's deadline, while `holds` (checked every `everyMs`): else 503 `unavailable`, saying `why`. */
|
|
3655
|
-
async waitWhile(holds, everyMs, why) {
|
|
3656
|
-
for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); holds(); await sleep(everyMs)) {
|
|
3657
|
-
if (Date.now() > deadline)
|
|
3658
|
-
throw new ApiError("unavailable", `${why}; try again.`, { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
3659
|
-
}
|
|
3660
|
-
}
|
|
3661
|
-
/** A completed agentic run that gets a follow-up opens again: the same run on its own store and session, under its
|
|
3662
|
-
* cap, taking a place under the server's. Launched here, with no wait after the place is taken, so no start takes
|
|
3663
|
-
* it meanwhile. An archived run, or a run of an archived agent, stays closed. */
|
|
3664
|
-
async reopen(run) {
|
|
3665
|
-
await this.sweepOnce();
|
|
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;
|
|
3671
|
-
const row = this.store.readRun(run.id);
|
|
3672
|
-
if (row?.archivedAt)
|
|
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);
|
|
3677
|
-
// Its end could not be written yet (persistLater tries again): it opens once the store has it.
|
|
3678
|
-
if (row?.state === "running")
|
|
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" });
|
|
3680
|
-
const release = await this.takePlace(run.harness);
|
|
3681
|
-
try {
|
|
3682
|
-
// Read again: the place may have been waited for, and the run (or its agent) archived meanwhile.
|
|
3683
|
-
const now = this.store.readRun(run.id);
|
|
3684
|
-
if (now?.archivedAt)
|
|
3685
|
-
throw new ApiError("not_continuable", "This run is archived: unarchive it to continue it.");
|
|
3686
|
-
if (now?.state === "running")
|
|
3687
|
-
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" });
|
|
3688
|
-
// Its end's run.ended in the outbox on disk before the run opens again, or not opened: once the row runs, no start finds
|
|
3689
|
-
// the end to queue it.
|
|
3690
|
-
if (now?.endedAt && this.notice(run, "run.ended", now.endedAt) === "unsaved")
|
|
3691
|
-
throw new ApiError("unavailable", "The run's end is still being announced to its webhook; try again.", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
3692
|
-
try {
|
|
3693
|
-
this.store.reopenRun(run.id);
|
|
3694
|
-
}
|
|
3695
|
-
catch (error) {
|
|
3696
|
-
storeError(error, "run");
|
|
3697
|
-
}
|
|
3698
|
-
run.outcome = undefined;
|
|
3699
|
-
// With its outcome cleared the run reads open. Messages wait for this reopen (message()), so its launch below is
|
|
3700
|
-
// the follow-up's; set here, with the outcome, whichever launch comes first carries the flag (launch() takes it).
|
|
3701
|
-
run.followUpOpen = true;
|
|
3702
|
-
run.settled = false;
|
|
3703
|
-
run.endedAt = undefined;
|
|
3704
|
-
run.error = undefined;
|
|
3705
|
-
delete run.meta.error;
|
|
3706
|
-
run.relaunches = 0;
|
|
3707
|
-
// A run that learns finds its agent's notes in its work again (learning-run.ts).
|
|
3708
|
-
await this.learning.onReopen(run);
|
|
3709
|
-
await this.pinSignIn(run);
|
|
3710
|
-
await this.beforeReopenLaunch?.(run.id);
|
|
3711
|
-
this.refresh(run);
|
|
3712
|
-
// Opened for the follow-up: the run had answered, so its open resumes nothing.
|
|
3713
|
-
this.launch(run, true);
|
|
3714
|
-
}
|
|
3715
|
-
finally {
|
|
3716
|
-
// Launched, it holds its place as a live run.
|
|
3717
|
-
release();
|
|
3718
|
-
}
|
|
3719
|
-
// An end-of-run turn its process went in is aborted before the follow-up is sent (learning-run.ts).
|
|
3720
|
-
await this.learning.afterReopen(run);
|
|
3721
|
-
}
|
|
3722
|
-
/** Waits, up to a request's deadline, until a live run's rows show every message sent to it, and any rows at all: its
|
|
3723
|
-
* record has caught up with its process. Its end, a cancel or its process going ends the wait. */
|
|
3724
|
-
async caughtUp(run) {
|
|
3725
|
-
for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); run.submitted > 0 || !run.rows.length; await run.log.changed(100)) {
|
|
3726
|
-
if (!this.live(run) || run.finishing || run.outcome || run.cancel || Date.now() > deadline)
|
|
3727
|
-
return;
|
|
3728
|
-
}
|
|
3729
|
-
}
|
|
3730
|
-
/** Abort the turn that is running; the run stays open, `input_required` and idle. A workflow run has no turn to stop. */
|
|
3731
|
-
async stop(run) {
|
|
3732
|
-
// The contract's stop has no refusal: an imported run answers as any ended one, stopped false, and nothing moves.
|
|
3733
|
-
if (run.imported)
|
|
3734
|
-
return false;
|
|
3735
|
-
// A message sent to the run shows in its rows only once its door's events bring it: until then the run reads queued
|
|
3736
|
-
// (state working), or holds a message not shown, however far its process is into the turn. The stop waits for its
|
|
3737
|
-
// rows first, so the mark it saves (the person's last message) covers the message the turn answers; then it stops
|
|
3738
|
-
// the turn as it stops any working run.
|
|
3739
|
-
if (run.kind !== "workflow")
|
|
3740
|
-
await this.caughtUp(run);
|
|
3741
|
-
// A tool call that waits for approval is withdrawn by the stop (never run, an answer after is 409); then a turn that
|
|
3742
|
-
// runs meanwhile is stopped as any working run's is, and with none the run is stopped as a stop leaves one.
|
|
3743
|
-
const open = run.kind === "agentic" && !run.cancel && !run.outcome && !run.finishing;
|
|
3744
|
-
const withdrawn = open && waitingApproval(run) ? await this.withdraw(run) : false;
|
|
3745
|
-
// An answer the run's process has not acted on yet is overridden too: a stop wins, so nothing runs and nothing resumes.
|
|
3746
|
-
const superseded = open ? await this.supersede(run, "withdrawn") : false;
|
|
3747
|
-
const { status, state } = statusOf(run);
|
|
3748
|
-
if (run.kind === "workflow" || !this.live(run) || !(status === "working" && state === "working") || run.submitted > 0)
|
|
3749
|
-
return withdrawn || superseded ? this.stopIdle(run) : false;
|
|
3750
|
-
run.stopping = true;
|
|
3751
|
-
try {
|
|
3752
|
-
return await this.stopTurn(run);
|
|
3753
|
-
}
|
|
3754
|
-
finally {
|
|
3755
|
-
run.stopping = undefined;
|
|
3756
|
-
}
|
|
3757
|
-
}
|
|
3758
|
-
/** message()'s decline of the tool call that waits for approval: a deny with the message as its note, which the
|
|
3759
|
-
* run's gate acts on as any deny, resuming the session with the refusal and the person's words in one message. */
|
|
3760
|
-
async declineBy(run, waiting, content) {
|
|
3761
|
-
// The person's message, whole: it is the reason the model reads. Nothing shows the note, so nothing cuts it.
|
|
3762
|
-
run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "deny", note: content, answered_at: new Date().toISOString(), args_shown: shownArgs(waiting, this.redactor(run)), by: "message" } };
|
|
3763
|
-
await this.saveMeta(run);
|
|
3764
|
-
this.restate(run);
|
|
3765
|
-
this.refresh(run);
|
|
3766
|
-
if (!run.outcome && !run.finishing && !run.cancel)
|
|
3767
|
-
void this.ensureLive(run, undefined, true).catch((error) => warn(run.id, `its declined approval waits for its process: ${error.message}`));
|
|
3768
|
-
return { mode: "answer", messageId: `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}` };
|
|
3769
|
-
}
|
|
3770
|
-
/** The answers given and not acted on yet (the run's process has not resolved them), overridden by a stop or a cancel:
|
|
3771
|
-
* `withdrawn` or `canceled`, each keeping the answer it superseded, so nothing runs and nothing resumes, and the
|
|
3772
|
-
* history shows what was given. The run's gate reads the answer again just before it acts (tool-gate.ts). */
|
|
3773
|
-
async supersede(run, decision) {
|
|
3774
|
-
const given = [...(run.approvals?.values() ?? [])].filter((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
|
|
3775
|
-
if (!given.length)
|
|
3776
|
-
return false;
|
|
3777
|
-
const now = new Date().toISOString();
|
|
3778
|
-
const overridden = given.map((a) => {
|
|
3779
|
-
const was = run.meta.approvals[a.id];
|
|
3780
|
-
return [a.id, { decision, answered_at: now, superseded: { decision: was.decision, answered_at: was.answered_at, ...(was.note !== undefined ? { note: was.note } : {}), ...(was.by ? { by: was.by } : {}) } }];
|
|
3781
|
-
});
|
|
3782
|
-
run.meta.approvals = { ...run.meta.approvals, ...Object.fromEntries(overridden) };
|
|
3783
|
-
await this.saveMeta(run);
|
|
3784
|
-
this.restate(run);
|
|
3785
|
-
return true;
|
|
3786
|
-
}
|
|
3787
|
-
/** Until every tool call of the run that waited for approval is resolved in its store (its process acted on its answer,
|
|
3788
|
-
* or cut it), or `ms` pass. */
|
|
3789
|
-
async untilResolved(run, ms) {
|
|
3790
|
-
for (const end = Date.now() + ms; [...(run.approvals?.values() ?? [])].some((approval) => !approval.resolved) && Date.now() < end;)
|
|
3791
|
-
await sleep(50);
|
|
3792
|
-
}
|
|
3793
|
-
/** stop()'s withdrawal of the tool call that waits for approval: never run, and an answer after is 409. */
|
|
3794
|
-
async withdraw(run) {
|
|
3795
|
-
const waiting = waitingApproval(run);
|
|
3796
|
-
run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "withdrawn", answered_at: new Date().toISOString() } };
|
|
3797
|
-
await this.saveMeta(run);
|
|
3798
|
-
this.restate(run);
|
|
3799
|
-
return true;
|
|
3800
|
-
}
|
|
3801
|
-
/** stop() of a run with no turn to abort (parked on an approval it withdrew): the stop's mark, as a stop saves it. */
|
|
3802
|
-
async stopIdle(run) {
|
|
3803
|
-
delete run.meta.stopped_at;
|
|
3804
|
-
delete run.meta.stopped_after;
|
|
3805
|
-
Object.assign(run.meta, stopMark(run.rows));
|
|
3806
|
-
await this.saveMeta(run);
|
|
3807
|
-
this.refresh(run);
|
|
3808
|
-
return true;
|
|
3809
|
-
}
|
|
3810
|
-
/** stop()'s mark and abort, once it took the stop. */
|
|
3811
|
-
async stopTurn(run) {
|
|
3812
|
-
// Set before the abort: the turn's end can arrive before the door answers, and must not read as an answer.
|
|
3813
|
-
const before = { stopped_at: run.meta.stopped_at, stopped_after: run.meta.stopped_after };
|
|
3814
|
-
delete run.meta.stopped_at;
|
|
3815
|
-
delete run.meta.stopped_after;
|
|
3816
|
-
Object.assign(run.meta, stopMark(run.rows));
|
|
3817
|
-
await this.saveMeta(run).catch((error) => warn(run.id, `its stop is not saved, so a restart will not keep it: ${error.message}`));
|
|
3818
|
-
await this.beforeAbort?.(run.id);
|
|
3819
|
-
const answer = await this.toDoor(run, "/abort", {}).catch(() => null);
|
|
3820
|
-
if (!answer || answer.status >= 400) {
|
|
3821
|
-
if (before.stopped_at === undefined)
|
|
3822
|
-
delete run.meta.stopped_at;
|
|
3823
|
-
else
|
|
3824
|
-
run.meta.stopped_at = before.stopped_at;
|
|
3825
|
-
if (before.stopped_after !== undefined)
|
|
3826
|
-
run.meta.stopped_after = before.stopped_after;
|
|
3827
|
-
await this.saveMeta(run).catch(() => undefined);
|
|
3828
|
-
this.refresh(run);
|
|
3829
|
-
return false;
|
|
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
|
-
}
|
|
3838
|
-
this.refresh(run);
|
|
3839
|
-
return true;
|
|
3840
|
-
}
|
|
3841
|
-
/** A person's answer to the tool call `id` that waits for approval (tool-gate.ts): kept in the run's serve.json before
|
|
3842
|
-
* it returns, the first answer winning (the same one again changes nothing; another is 409, `already_answered`). The
|
|
3843
|
-
* run's process reads it there, runs or refuses the call, and resumes; a run with no process gets one. */
|
|
3844
|
-
async approve(run, id, decision, note) {
|
|
3845
|
-
const given = run.meta.approvals?.[id];
|
|
3846
|
-
if (!given && !run.approvals?.has(id))
|
|
3847
|
-
throw new ApiError("not_found", `The run ${run.id} has no tool call ${id} waiting for approval.`);
|
|
3848
|
-
if (given) {
|
|
3849
|
-
if (given.decision === decision)
|
|
3850
|
-
return;
|
|
3851
|
-
throw new ApiError("not_continuable", `The tool call ${id} was already ${given.decision === "canceled" ? "canceled with its run" : given.decision === "withdrawn" ? "withdrawn when its run was stopped" : `answered: ${given.decision}`}.`, { details: { reason: "already_answered", decision: given.decision } });
|
|
3852
|
-
}
|
|
3853
|
-
run.meta.approvals = { ...run.meta.approvals, [id]: { decision, ...(note ? { note } : {}), answered_at: new Date().toISOString(), args_shown: shownArgs(run.approvals.get(id), this.redactor(run)) } };
|
|
3854
|
-
await this.saveMeta(run);
|
|
3855
|
-
this.restate(run);
|
|
3856
|
-
this.refresh(run);
|
|
3857
|
-
if (!run.outcome && !run.finishing && !run.cancel)
|
|
3858
|
-
void this.ensureLive(run, undefined, true).catch((error) => warn(run.id, `its answered approval waits for its process: ${error.message}`));
|
|
3859
|
-
}
|
|
3860
|
-
/** Record the cancel and signal the run. An agentic run reads `cancelled` from here on (the first end a run comes to is
|
|
3861
|
-
* its last: nothing its turn writes later moves it), and is carried back so once its process has exited; a workflow
|
|
3862
|
-
* run reads it once it is carried back, with how its workflow stopped. */
|
|
3863
|
-
async cancel(run) {
|
|
3864
|
-
// As stop: already terminal, and no cancel mark is written.
|
|
3865
|
-
if (run.imported)
|
|
3866
|
-
return false;
|
|
3867
|
-
// Finishing is already ending with its outcome (an answer, a failure, the cap): a run's first end is its last.
|
|
3868
|
-
if (run.outcome || run.finishing)
|
|
3869
|
-
return false;
|
|
3870
|
-
run.cancel = true;
|
|
3871
|
-
// A tool call that waits for approval is canceled with its run: an answer after this one is refused.
|
|
3872
|
-
const waiting = waitingApproval(run);
|
|
3873
|
-
if (waiting) {
|
|
3874
|
-
run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "canceled", answered_at: new Date().toISOString() } };
|
|
3875
|
-
await this.saveMeta(run).catch((error) => warn(run.id, `its canceled approval is not saved: ${error.message}`));
|
|
3876
|
-
this.restate(run);
|
|
3877
|
-
}
|
|
3878
|
-
// An answer its process has not acted on yet is overridden too: nothing runs and nothing resumes.
|
|
3879
|
-
const superseded = await this.supersede(run, "canceled").catch((error) => (warn(run.id, `its superseded approval is not saved: ${error.message}`), false));
|
|
3880
|
-
if (run.kind === "agentic") {
|
|
3881
|
-
run.finishing = "cancelled";
|
|
3882
|
-
run.endedAt = new Date().toISOString();
|
|
3883
|
-
this.mark(run);
|
|
3884
|
-
}
|
|
3885
|
-
// First, so no request leaves after the cancel landed, whether or not the process can be reached yet.
|
|
3886
|
-
await writeWhole(join(run.dir, RUN_CANCELLED), "").catch((error) => warn(run.id, `its cancel mark is not written: ${error.message}`));
|
|
3887
|
-
if (this.live(run)) {
|
|
3888
|
-
// The turn is aborted first, so the drain that SIGTERM starts does not wait for it.
|
|
3889
|
-
await this.abortTurn(run);
|
|
3890
|
-
// An approved call in flight runs outside any turn: its process's gate cuts it once it reads the cancel (tool-gate.ts),
|
|
3891
|
-
// which ending the process at once would forestall. A short wait for that, never a refusal.
|
|
3892
|
-
if (superseded) {
|
|
3893
|
-
run.meta.cancel_waits_for = [...(run.approvals?.values() ?? [])].filter((approval) => !approval.resolved).map((approval) => approval.id);
|
|
3894
|
-
await this.saveMeta(run).catch((error) => warn(run.id, `its cancel's wait is not saved: ${error.message}`));
|
|
3895
|
-
await this.untilResolved(run, 3_000);
|
|
3896
|
-
}
|
|
3897
|
-
this.terminate(run);
|
|
3898
|
-
}
|
|
3899
|
-
else
|
|
3900
|
-
await this.settle(run, null, false);
|
|
3901
|
-
return true;
|
|
3902
|
-
}
|
|
3903
|
-
/** Pause a workflow run (`paused` true) or resume it: the mark in its directory, which its process reads before each
|
|
3904
|
-
* node starts. A run that has ended is not continuable. */
|
|
3905
|
-
async pause(run, paused) {
|
|
3906
|
-
if (run.kind !== "workflow")
|
|
3907
|
-
throw unsupported("runs.pause", "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.");
|
|
3908
|
-
if (TERMINAL.has(statusOf(run).status) || run.cancel)
|
|
3909
|
-
throw this.finished(run);
|
|
3910
|
-
const mark = join(run.dir, RUN_PAUSED);
|
|
3911
|
-
if (paused)
|
|
3912
|
-
await writeWhole(mark, `${new Date().toISOString()}\n`);
|
|
3913
|
-
else
|
|
3914
|
-
await rm(mark, { force: true });
|
|
3915
|
-
this.mark(run);
|
|
3916
|
-
return { run_id: run.id, paused, status: statusOf(run).status };
|
|
3917
|
-
}
|
|
3918
|
-
/** How long a run's process gets after SIGTERM before SIGKILL: its drain and a second to exit. */
|
|
3919
|
-
killAfterMs() {
|
|
3920
|
-
return (durationMs(this.options.drainTimeout ?? DRAIN) ?? 30_000) + 1_000;
|
|
3921
|
-
}
|
|
3922
|
-
/** What close() will wait on: the runs whose processes are left to finish their turn (those this server started, and
|
|
3923
|
-
* those it adopted), and the longest it can wait on them: a kill bound for the started ones, and one more for the
|
|
3924
|
-
* adopted ones, which it stops after them. */
|
|
3925
|
-
stopping() {
|
|
3926
|
-
const all = [...this.runs.values()];
|
|
3927
|
-
const started = all.filter((run) => run.child).length;
|
|
3928
|
-
const adopted = all.filter((run) => !run.child && run.orphanHolder && holderLives(run.orphanHolder)).length;
|
|
3929
|
-
return { runs: started + adopted, boundMs: (started ? this.killAfterMs() : 0) + (adopted ? this.killAfterMs() : 0) };
|
|
3930
|
-
}
|
|
3931
|
-
async close() {
|
|
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;
|
|
3936
|
-
this.learning.close();
|
|
3937
|
-
const live = [...this.runs.values()].filter((run) => run.child);
|
|
3938
|
-
for (const run of live) {
|
|
3939
|
-
run.child.kill("SIGTERM");
|
|
3940
|
-
setTimeout(() => run.child?.exitCode === null && run.child.kill("SIGKILL"), this.killAfterMs()).unref();
|
|
3941
|
-
}
|
|
3942
|
-
await Promise.all(live.map((run) => new Promise((resolve) => (run.child ? run.child.once("exit", resolve) : resolve(undefined)))));
|
|
3943
|
-
// An adopted process is stopped the same way, and watched by its pid.
|
|
3944
|
-
const adopted = [...this.runs.values()].filter((run) => run.orphanHolder && holderLives(run.orphanHolder));
|
|
3945
|
-
for (const run of adopted)
|
|
3946
|
-
this.terminate(run);
|
|
3947
|
-
for (const deadline = Date.now() + this.killAfterMs(); adopted.some((run) => run.orphanHolder && holderLives(run.orphanHolder)) && Date.now() < deadline;)
|
|
3948
|
-
await sleep(100);
|
|
3949
|
-
await sleep(0);
|
|
3950
|
-
await Promise.all([...this.runs.values()].map((run) => run.settling));
|
|
3951
|
-
await this.learning.idle();
|
|
3952
|
-
for (const run of this.runs.values()) {
|
|
3953
|
-
run.feed?.abort();
|
|
3954
|
-
clearTimeout(run.stopPending);
|
|
3955
|
-
run.stopPending = undefined;
|
|
3956
|
-
}
|
|
3957
|
-
this.closed = true;
|
|
3958
|
-
}
|
|
3959
|
-
// ---- views ------------------------------------------------------------------------------------------------------------
|
|
3960
|
-
/** A run's cost from its rows, else what the store recorded when it carried the run back. */
|
|
3961
|
-
cost(run) {
|
|
3962
|
-
// An imported run's cost is its source's, for the whole session: its requests may not each have a price.
|
|
3963
|
-
const usd = run.imported ? (run.costUsd ?? null) : costView(run.rows, run.costUsd, run.decisionCost);
|
|
3964
|
-
// Unknown: what it cost so far and how many charges have no price (costsofar/1), from its rows, else what it said at
|
|
3965
|
-
// its end (a run carried back with no rows read since).
|
|
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;
|
|
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) {
|
|
3977
|
-
const stored = known ? (known.stored ?? undefined) : await this.options.agents.request(() => this.store.readRun(run.id));
|
|
3978
|
-
// After the read: the run may have moved on while it waited, and every field below is of this one moment.
|
|
3979
|
-
const { status, state } = statusOf(run);
|
|
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);
|
|
3983
|
-
// The whole text of the answer the run's turn ended on (answerOfRun), never the line the store keeps, which is cut;
|
|
3984
|
-
// the store's line only for a run whose rows are not read (an import's).
|
|
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);
|
|
3987
|
-
// When the turn of a message still open last wrote: a run working shows it is moving, or not.
|
|
3988
|
-
const progress = TERMINAL.has(status) || run.kind === "workflow" ? undefined : run.turns.progressAt();
|
|
3989
|
-
// A run its cap stopped keeps the answer it paid for.
|
|
3990
|
-
const kept = status === "failed" && run.error?.code === SPEND_CAP_REACHED ? lastAnswer(run) : null;
|
|
3991
|
-
const endedAt = TERMINAL.has(status) ? (row?.endedAt ?? run.endedAt ?? run.updatedAt) : null;
|
|
3992
|
-
return {
|
|
3993
|
-
run_id: run.id,
|
|
3994
|
-
agent_id: run.agentId,
|
|
3995
|
-
agent_version: run.version,
|
|
3996
|
-
console_url: runLink(origin, run.id),
|
|
3997
|
-
revision: run.revision,
|
|
3998
|
-
kind: run.kind,
|
|
3999
|
-
sha: null,
|
|
4000
|
-
status,
|
|
4001
|
-
state,
|
|
4002
|
-
title: run.meta.title,
|
|
4003
|
-
place: run.meta.place ?? { mode: "runner" },
|
|
4004
|
-
...(run.meta.effort ? { effort: run.meta.effort } : {}),
|
|
4005
|
-
created_at: run.meta.created_at,
|
|
4006
|
-
updated_at: run.updatedAt,
|
|
4007
|
-
ended_at: endedAt,
|
|
4008
|
-
// An answer is served with no held secret in it, whole (key-refusal.ts redactedAnswer); the stored one stays as written.
|
|
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,
|
|
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),
|
|
4020
|
-
archived_at: stored?.archivedAt ?? null,
|
|
4021
|
-
imported_from: run.imported ?? null,
|
|
4022
|
-
trigger: run.meta.trigger ?? null,
|
|
4023
|
-
// The notes it read once it settled: while it runs, or runs again for a follow-up, they are still being read.
|
|
4024
|
-
learning: this.learning.view(learning, TERMINAL.has(status) && run.settled),
|
|
4025
|
-
poll_after_ms: TERMINAL.has(status) && run.settled ? 0 : 1000,
|
|
4026
|
-
last_progress_at: progress === undefined ? null : new Date(progress).toISOString(),
|
|
4027
|
-
};
|
|
4028
|
-
}
|
|
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) };
|
|
4032
|
-
}
|
|
4033
|
-
/** A run's status for a list: an ended run's from its row, a running one's from the run itself. */
|
|
4034
|
-
async statusOfRow(row) {
|
|
4035
|
-
if (row.state !== "running")
|
|
4036
|
-
return STATUS_OF[row.state];
|
|
4037
|
-
const run = await this.get(row.id);
|
|
4038
|
-
return run ? statusOf(run).status : "queued";
|
|
4039
|
-
}
|
|
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,
|
|
4041
|
-
* not its store; `versions` numbers its agent's revisions. */
|
|
4042
|
-
async summaryOfRow(row, versions, origin) {
|
|
4043
|
-
const known = this.runs.get(row.id) ?? (row.state === "running" ? await this.get(row.id) : null);
|
|
4044
|
-
if (known)
|
|
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));
|
|
4053
|
-
return {
|
|
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,
|
|
4055
|
-
status: STATUS_OF[row.state], state: "idle", title: typeof meta?.title === "string" ? meta.title : "",
|
|
4056
|
-
...(typeof meta?.effort === "string" ? { effort: meta.effort } : {}),
|
|
4057
|
-
created_at: typeof meta?.created_at === "string" ? meta.created_at : row.startedAt, ended_at: row.endedAt ?? null,
|
|
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) ?? {}) : {}) },
|
|
4062
|
-
archived_at: row.archivedAt ?? null,
|
|
4063
|
-
// A run read from its row alone has ended: it waits on nothing.
|
|
4064
|
-
pending: null,
|
|
4065
|
-
imported_from: row.importedFrom ?? null,
|
|
4066
|
-
trigger: triggerOf(meta),
|
|
4067
|
-
// Its row says it ended: what serve.json holds of its learning is as it settled.
|
|
4068
|
-
learning: this.learning.short(isObject(meta?.learning) ? ((await this.learning.current(row.agent, meta.learning)) ?? null) : null, true),
|
|
4069
|
-
};
|
|
4070
|
-
}
|
|
4071
|
-
/** A key was saved on this server or deleted from it: each held run's learning row and decision rows shown again, cut
|
|
4072
|
-
* of the keys as they are now (learning-run.ts shown, decision-rows.ts), as its view and its lists already are from
|
|
4073
|
-
* the next read on. */
|
|
4074
|
-
keysChanged() {
|
|
4075
|
-
this.learning.keysChanged();
|
|
4076
|
-
// A run's learning row and its decision rows are shown again with the keys as they are now (show): a key saved after
|
|
4077
|
-
// a workflow ended is redacted from its decisions on the next read, learning or not.
|
|
4078
|
-
for (const run of this.runs.values())
|
|
4079
|
-
if (run.meta.learning || run.decisions)
|
|
4080
|
-
this.show(run);
|
|
4081
|
-
}
|
|
4082
|
-
/** A held run's learning, in short (learning-run.ts heldLearning). */
|
|
4083
|
-
heldLearning(runId) {
|
|
4084
|
-
return this.learning.heldLearning(runId);
|
|
4085
|
-
}
|
|
4086
|
-
/** The timeline from change `after`, held up to `waitMs` for a change when there is none. */
|
|
4087
|
-
async page(run, after, waitMs, limit) {
|
|
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);
|
|
4094
|
-
for (;;) {
|
|
4095
|
-
const page = run.log.page(after, limit);
|
|
4096
|
-
const { status, state } = statusOf(run);
|
|
4097
|
-
const final = TERMINAL.has(status) && run.settled;
|
|
4098
|
-
if (!page.unchanged || final || Date.now() >= deadline)
|
|
4099
|
-
return { ...page, status, state, final };
|
|
4100
|
-
await run.log.changed(deadline - Date.now());
|
|
4101
|
-
}
|
|
4102
|
-
}
|
|
4103
|
-
}
|