@parcha/agentrun-serve 0.1.0-beta.31 → 0.1.0-beta.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +422 -0
- package/NOTICE +18 -0
- package/README.md +887 -241
- package/dist/adapter-facts.d.ts +3 -0
- package/dist/adapter-facts.js +5 -0
- package/dist/adapters.d.ts +64 -140
- package/dist/adapters.js +153 -377
- package/dist/agents-store.d.ts +146 -0
- package/dist/agents-store.js +359 -0
- package/dist/agents.d.ts +5 -3
- package/dist/agents.js +37 -17
- package/dist/app.d.ts +2 -4
- package/dist/app.js +207 -92
- package/dist/approvals.d.ts +4 -0
- package/dist/approvals.js +7 -0
- package/dist/archil-routes.d.ts +45 -0
- package/dist/archil-routes.js +150 -0
- package/dist/archil-settings.d.ts +30 -0
- package/dist/archil-settings.js +34 -0
- package/dist/background.js +28 -9
- package/dist/bounds.d.ts +26 -0
- package/dist/bounds.js +137 -0
- package/dist/box-egress-vm.d.ts +2 -1
- package/dist/box-egress-vm.js +20 -6
- package/dist/box-egress.d.ts +16 -6
- package/dist/box-egress.js +27 -15
- package/dist/box-paths.d.ts +59 -0
- package/dist/box-paths.js +92 -0
- package/dist/box-relay-vm.js +28 -1
- package/dist/box-relay.d.ts +2 -0
- package/dist/box-relay.js +2 -2
- package/dist/boxes.d.ts +13 -1
- package/dist/boxes.js +37 -3
- package/dist/browser-commands.d.ts +43 -0
- package/dist/browser-commands.js +154 -0
- package/dist/browser-cost.d.ts +30 -3
- package/dist/browser-cost.js +276 -21
- package/dist/browser-live.d.ts +124 -0
- package/dist/browser-live.js +324 -0
- package/dist/browser-person.d.ts +168 -0
- package/dist/browser-person.js +769 -0
- package/dist/budget.d.ts +80 -0
- package/dist/budget.js +211 -0
- package/dist/cap.d.ts +272 -62
- package/dist/cap.js +599 -189
- package/dist/cli.js +201 -17
- package/dist/coding-tools.d.ts +13 -1
- package/dist/coding-tools.js +107 -5
- package/dist/computer-adb.d.ts +12 -0
- package/dist/computer-adb.js +14 -0
- package/dist/computer-commands.d.ts +103 -0
- package/dist/computer-commands.js +256 -0
- package/dist/computer-keys.d.ts +68 -0
- package/dist/computer-keys.js +148 -0
- package/dist/computer-routes.d.ts +38 -0
- package/dist/computer-routes.js +56 -0
- package/dist/computer-setting.d.ts +37 -0
- package/dist/computer-setting.js +47 -0
- package/dist/computer-view.d.ts +38 -0
- package/dist/computer-view.js +14 -0
- package/dist/computers.d.ts +137 -0
- package/dist/computers.js +197 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
- package/dist/console/assets/index-35-7aeIZ.js +519 -0
- package/dist/console/assets/index-Cejbov-Y.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +2 -0
- package/dist/console-links.js +6 -0
- package/dist/decision-cap.d.ts +63 -0
- package/dist/decision-cap.js +163 -0
- package/dist/decision-rows.d.ts +5 -2
- package/dist/decision-rows.js +8 -6
- package/dist/decisions.d.ts +28 -1
- package/dist/decisions.js +63 -6
- package/dist/disk.d.ts +33 -0
- package/dist/disk.js +85 -0
- package/dist/door-line.d.ts +23 -0
- package/dist/door-line.js +83 -0
- package/dist/egress-proxy.d.ts +45 -0
- package/dist/egress-proxy.js +416 -0
- package/dist/egress-table.d.ts +24 -0
- package/dist/egress-table.js +165 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +22 -2
- package/dist/exa-keyless.js +1 -1
- package/dist/explain.d.ts +22 -0
- package/dist/explain.js +207 -0
- package/dist/faux-computers.d.ts +35 -0
- package/dist/faux-computers.js +126 -0
- package/dist/file-types.d.ts +4 -0
- package/dist/file-types.js +11 -0
- package/dist/files.d.ts +3 -35
- package/dist/files.js +9 -120
- package/dist/github-connection.d.ts +207 -0
- package/dist/github-connection.js +595 -0
- package/dist/github.d.ts +64 -0
- package/dist/github.js +119 -0
- package/dist/grade.d.ts +9 -42
- package/dist/grade.js +42 -228
- package/dist/graph-served.d.ts +23 -2
- package/dist/graph-served.js +44 -3
- package/dist/graph-view.d.ts +7 -3
- package/dist/graph-view.js +26 -15
- package/dist/handed-values.d.ts +23 -0
- package/dist/handed-values.js +36 -0
- package/dist/harness-app.d.ts +33 -4
- package/dist/harness-app.js +530 -85
- package/dist/harness-install.d.ts +120 -0
- package/dist/harness-install.js +359 -0
- package/dist/harness-opencode/adapter.js +42 -8
- package/dist/harness-opencode/facts.d.ts +2 -0
- package/dist/harness-opencode/facts.js +28 -0
- package/dist/harness-opencode/harness.d.ts +4 -0
- package/dist/harness-opencode/harness.js +38 -5
- package/dist/harness-opencode/host/policy.js +11 -3
- package/dist/harness-opencode/transcript.d.ts +25 -0
- package/dist/harness-opencode/transcript.js +81 -0
- package/dist/harness-table.d.ts +75 -0
- package/dist/harness-table.js +145 -0
- package/dist/harness.d.ts +7 -28
- package/dist/harness.js +15 -41
- package/dist/heard.d.ts +12 -0
- package/dist/heard.js +45 -0
- package/dist/helper-env.d.ts +4 -0
- package/dist/helper-env.js +14 -0
- package/dist/home-path.d.ts +0 -4
- package/dist/home-path.js +3 -17
- package/dist/host-check.d.ts +4 -3
- package/dist/host-check.js +5 -4
- package/dist/host-tools.d.ts +51 -8
- package/dist/host-tools.js +108 -117
- package/dist/host.d.ts +12 -6
- package/dist/host.js +30 -24
- package/dist/hosted-search.d.ts +3 -0
- package/dist/hosted-search.js +5 -3
- package/dist/import-proxy.d.ts +42 -0
- package/dist/import-proxy.js +105 -0
- package/dist/import-summary.js +4 -8
- package/dist/import-worker.d.ts +2 -3
- package/dist/import-worker.js +18 -16
- package/dist/import.d.ts +37 -17
- package/dist/import.js +208 -222
- package/dist/key-meta.d.ts +26 -0
- package/dist/key-meta.js +30 -0
- package/dist/key-refusal.d.ts +4 -1
- package/dist/key-refusal.js +20 -7
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +2 -2
- package/dist/learn/commit.d.ts +86 -0
- package/dist/learn/commit.js +182 -0
- package/dist/learn/folder.d.ts +296 -0
- package/dist/learn/folder.js +796 -0
- package/dist/learn/grade.d.ts +22 -9
- package/dist/learn/grade.js +95 -49
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/learning.sh +366 -0
- package/dist/learn/reflect.d.ts +12 -5
- package/dist/learn/reflect.js +70 -41
- package/dist/learn/secrets.d.ts +15 -7
- package/dist/learn/secrets.js +66 -16
- package/dist/learn/seed-check.d.ts +74 -0
- package/dist/learn/seed-check.js +103 -0
- package/dist/learn/skills.d.ts +5 -1
- package/dist/learn/skills.js +5 -4
- package/dist/learned-workflow.d.ts +12 -2
- package/dist/learned-workflow.js +9 -5
- package/dist/learning-routes.d.ts +88 -41
- package/dist/learning-routes.js +340 -539
- package/dist/learning-run.d.ts +60 -53
- package/dist/learning-run.js +181 -224
- package/dist/learning-words.d.ts +3 -5
- package/dist/learning-words.js +3 -5
- package/dist/learning.d.ts +177 -112
- package/dist/learning.js +289 -380
- package/dist/live/stream.d.ts +30 -0
- package/dist/live/stream.js +175 -0
- package/dist/live/translate.d.ts +52 -0
- package/dist/live/translate.js +276 -0
- package/dist/llm.js +3 -0
- package/dist/llms.txt +1 -0
- package/dist/local-models.d.ts +23 -0
- package/dist/local-models.js +35 -0
- package/dist/mcp-gateway.d.ts +46 -13
- package/dist/mcp-gateway.js +145 -45
- package/dist/mcp-meta.d.ts +3 -0
- package/dist/mcp-meta.js +14 -2
- package/dist/mcp-oauth.d.ts +172 -0
- package/dist/mcp-oauth.js +403 -0
- package/dist/mcp-private-hosts.d.ts +48 -0
- package/dist/mcp-private-hosts.js +141 -0
- package/dist/mcp-probe.d.ts +101 -0
- package/dist/mcp-probe.js +359 -0
- package/dist/mcp-secret-writes.d.ts +23 -0
- package/dist/mcp-secret-writes.js +60 -0
- package/dist/mcp-servers-store.d.ts +251 -0
- package/dist/mcp-servers-store.js +447 -0
- package/dist/mcp-servers.d.ts +180 -50
- package/dist/mcp-servers.js +284 -321
- package/dist/mcp-store.d.ts +103 -0
- package/dist/mcp-store.js +123 -0
- package/dist/mcp.js +22 -21
- package/dist/model.d.ts +77 -59
- package/dist/model.js +237 -98
- package/dist/monid.d.ts +8 -6
- package/dist/monid.js +39 -25
- package/dist/openapi.d.ts +22 -1
- package/dist/openapi.js +919 -108
- package/dist/owner.d.ts +46 -10
- package/dist/owner.js +123 -43
- package/dist/page.d.ts +10 -0
- package/dist/page.js +27 -4
- package/dist/paid-calls.d.ts +71 -2
- package/dist/paid-calls.js +125 -5
- package/dist/pdf-pages.d.ts +16 -14
- package/dist/pdf-pages.js +88 -58
- package/dist/place.d.ts +15 -13
- package/dist/place.js +25 -15
- package/dist/port-models.d.ts +53 -0
- package/dist/port-models.js +93 -0
- package/dist/propose.d.ts +9 -8
- package/dist/propose.js +82 -49
- package/dist/provider.d.ts +85 -0
- package/dist/provider.js +178 -0
- package/dist/push-handler.d.ts +52 -0
- package/dist/push-handler.js +165 -0
- package/dist/refusal-words.d.ts +23 -0
- package/dist/refusal-words.js +25 -0
- package/dist/request-start.d.ts +6 -1
- package/dist/request-start.js +41 -10
- package/dist/result.d.ts +13 -2
- package/dist/result.js +4 -5
- package/dist/run-box.d.ts +22 -3
- package/dist/run-box.js +78 -17
- package/dist/run-computer.d.ts +24 -0
- package/dist/run-computer.js +15 -0
- package/dist/run-cut.d.ts +33 -0
- package/dist/run-cut.js +42 -0
- package/dist/run-db.d.ts +64 -0
- package/dist/run-db.js +155 -0
- package/dist/run-files.d.ts +31 -0
- package/dist/run-files.js +125 -0
- package/dist/run-holder.d.ts +52 -0
- package/dist/run-holder.js +139 -0
- package/dist/run-launch.d.ts +72 -0
- package/dist/run-launch.js +108 -0
- package/dist/run-learning-served.d.ts +43 -0
- package/dist/run-learning-served.js +16 -0
- package/dist/run-manifest.d.ts +7 -6
- package/dist/run-manifest.js +20 -10
- package/dist/run-reads-over-store.d.ts +102 -0
- package/dist/run-reads-over-store.js +151 -0
- package/dist/run-timeline-served.d.ts +13 -0
- package/dist/run-timeline-served.js +69 -0
- package/dist/run-view.d.ts +436 -0
- package/dist/run-view.js +620 -0
- package/dist/runnable.d.ts +30 -5
- package/dist/runnable.js +149 -72
- package/dist/runner/adapter-loop.d.ts +237 -0
- package/dist/runner/adapter-loop.js +1625 -0
- package/dist/runner/adapter-run-spec.d.ts +216 -0
- package/dist/runner/adapter-run-spec.js +537 -0
- package/dist/runner/adapters/index.d.ts +37 -0
- package/dist/runner/adapters/index.js +66 -0
- package/dist/runner/adapters/pi.d.ts +99 -0
- package/dist/runner/adapters/pi.js +260 -0
- package/dist/runner/beside.d.ts +12 -0
- package/dist/runner/beside.js +30 -0
- package/dist/runner/claim-secrets.d.ts +30 -0
- package/dist/runner/claim-secrets.js +90 -0
- package/dist/runner/cli-run-spec.d.ts +17 -0
- package/dist/runner/cli-run-spec.js +371 -0
- package/dist/runner/commands.d.ts +23 -0
- package/dist/runner/commands.js +67 -0
- package/dist/runner/computer-journal.d.ts +38 -0
- package/dist/runner/computer-journal.js +120 -0
- package/dist/runner/conformance/child.d.ts +1 -0
- package/dist/runner/conformance/child.js +78 -0
- package/dist/runner/conformance/harness.d.ts +89 -0
- package/dist/runner/conformance/harness.js +928 -0
- package/dist/runner/conformance/subject.d.ts +83 -0
- package/dist/runner/conformance/subject.js +1 -0
- package/dist/runner/dispatch.d.ts +30 -0
- package/dist/runner/dispatch.js +99 -0
- package/dist/runner/end-of-run.d.ts +32 -0
- package/dist/runner/end-of-run.js +56 -0
- package/dist/runner/github-app.d.ts +16 -0
- package/dist/runner/github-app.js +37 -0
- package/dist/runner/hand-back.d.ts +43 -0
- package/dist/runner/hand-back.js +69 -0
- package/dist/runner/harness-loops.d.ts +10 -0
- package/dist/runner/harness-loops.js +70 -0
- package/dist/runner/journal-kinds.d.ts +211 -0
- package/dist/runner/journal-kinds.js +116 -0
- package/dist/runner/journal-reader.d.ts +44 -0
- package/dist/runner/journal-reader.js +127 -0
- package/dist/runner/learning-ask.d.ts +37 -0
- package/dist/runner/learning-ask.js +99 -0
- package/dist/runner/learning-dispatch.d.ts +38 -0
- package/dist/runner/learning-dispatch.js +75 -0
- package/dist/runner/learning-end.d.ts +31 -0
- package/dist/runner/learning-end.js +136 -0
- package/dist/runner/learning-factory.d.ts +13 -0
- package/dist/runner/learning-factory.js +37 -0
- package/dist/runner/learning-loop.d.ts +150 -0
- package/dist/runner/learning-loop.js +246 -0
- package/dist/runner/learning-seed.d.ts +30 -0
- package/dist/runner/learning-seed.js +41 -0
- package/dist/runner/live-ticker.d.ts +18 -0
- package/dist/runner/live-ticker.js +88 -0
- package/dist/runner/loop-contract.d.ts +153 -0
- package/dist/runner/loop-contract.js +26 -0
- package/dist/runner/loop.d.ts +79 -0
- package/dist/runner/loop.js +185 -0
- package/dist/runner/main.d.ts +89 -0
- package/dist/runner/main.js +282 -0
- package/dist/runner/mcp-claim.d.ts +67 -0
- package/dist/runner/mcp-claim.js +403 -0
- package/dist/runner/mcp-github.d.ts +53 -0
- package/dist/runner/mcp-github.js +91 -0
- package/dist/runner/mcp-run.d.ts +116 -0
- package/dist/runner/mcp-run.js +152 -0
- package/dist/runner/metrics.d.ts +18 -0
- package/dist/runner/metrics.js +24 -0
- package/dist/runner/model-route.d.ts +111 -0
- package/dist/runner/model-route.js +183 -0
- package/dist/runner/pi-stop.d.ts +6 -0
- package/dist/runner/pi-stop.js +8 -0
- package/dist/runner/redact.d.ts +26 -0
- package/dist/runner/redact.js +51 -0
- package/dist/runner/reflect-hook.d.ts +81 -0
- package/dist/runner/reflect-hook.js +111 -0
- package/dist/runner/runner.d.ts +114 -0
- package/dist/runner/runner.js +672 -0
- package/dist/runner/sessions.d.ts +9 -0
- package/dist/runner/sessions.js +145 -0
- package/dist/runner/side-effects.d.ts +19 -0
- package/dist/runner/side-effects.js +20 -0
- package/dist/runner/spec-holds.d.ts +41 -0
- package/dist/runner/spec-holds.js +58 -0
- package/dist/runner/store-port.d.ts +9 -0
- package/dist/runner/store-port.js +7 -0
- package/dist/runner/store-secrets.d.ts +11 -0
- package/dist/runner/store-secrets.js +105 -0
- package/dist/runner/workflow-adapters.d.ts +1 -0
- package/dist/runner/workflow-adapters.js +4 -0
- package/dist/runner/workflow-host.d.ts +88 -0
- package/dist/runner/workflow-host.js +66 -0
- package/dist/runner/workflow-loop.d.ts +126 -0
- package/dist/runner/workflow-loop.js +372 -0
- package/dist/runner/workflow-spec.d.ts +157 -0
- package/dist/runner/workflow-spec.js +801 -0
- package/dist/runs-over-store.d.ts +203 -0
- package/dist/runs-over-store.js +396 -0
- package/dist/runs.d.ts +351 -220
- package/dist/runs.js +1570 -540
- package/dist/seal-key.d.ts +30 -0
- package/dist/seal-key.js +141 -0
- package/dist/sealed-settings-store.d.ts +71 -0
- package/dist/sealed-settings-store.js +205 -0
- package/dist/sealed-settings.d.ts +60 -0
- package/dist/sealed-settings.js +178 -0
- package/dist/secret-writes.d.ts +147 -0
- package/dist/secret-writes.js +144 -0
- package/dist/secrets.d.ts +7 -0
- package/dist/secrets.js +17 -2
- package/dist/served-only.d.ts +5 -0
- package/dist/served-only.js +12 -0
- package/dist/server-approvers.d.ts +8 -0
- package/dist/server-approvers.js +12 -0
- package/dist/server-fs.d.ts +40 -0
- package/dist/server-fs.js +138 -0
- package/dist/server-keys.d.ts +18 -0
- package/dist/server-keys.js +31 -0
- package/dist/server-lock.js +1 -1
- package/dist/server-secrets-store.d.ts +18 -0
- package/dist/server-secrets-store.js +54 -0
- package/dist/server-secrets.d.ts +23 -0
- package/dist/server-secrets.js +73 -0
- package/dist/server.d.ts +142 -73
- package/dist/server.js +1683 -596
- package/dist/sessions.d.ts +3 -1
- package/dist/sessions.js +8 -4
- package/dist/sign-ins-secrets.d.ts +35 -0
- package/dist/sign-ins-secrets.js +109 -0
- package/dist/sign-ins-store.d.ts +200 -0
- package/dist/sign-ins-store.js +373 -0
- package/dist/sign-ins.d.ts +43 -7
- package/dist/sign-ins.js +94 -18
- package/dist/skills.d.ts +6 -5
- package/dist/skills.js +18 -14
- package/dist/standard-webhooks.d.ts +30 -0
- package/dist/standard-webhooks.js +72 -0
- package/dist/stats.d.ts +5 -7
- package/dist/stats.js +8 -24
- package/dist/stop-signals.d.ts +22 -0
- package/dist/stop-signals.js +38 -0
- package/dist/store/agent-body.d.ts +103 -0
- package/dist/store/agent-body.js +126 -0
- package/dist/store/dialect.d.ts +59 -0
- package/dist/store/dialect.js +32 -0
- package/dist/store/fence.d.ts +22 -0
- package/dist/store/fence.js +15 -0
- package/dist/store/index.d.ts +17 -0
- package/dist/store/index.js +17 -0
- package/dist/store/journal/storage.d.ts +137 -0
- package/dist/store/journal/storage.js +1021 -0
- package/dist/store/open.d.ts +34 -0
- package/dist/store/open.js +30 -0
- package/dist/store/postgres/connection.d.ts +74 -0
- package/dist/store/postgres/connection.js +532 -0
- package/dist/store/postgres/dialect.d.ts +9 -0
- package/dist/store/postgres/dialect.js +39 -0
- package/dist/store/postgres/migrate.d.ts +21 -0
- package/dist/store/postgres/migrate.js +106 -0
- package/dist/store/postgres/migrations/0001_initial.sql +418 -0
- package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
- package/dist/store/postgres/store.d.ts +37 -0
- package/dist/store/postgres/store.js +48 -0
- package/dist/store/prompts.d.ts +11 -0
- package/dist/store/prompts.js +112 -0
- package/dist/store/schema.d.ts +26 -0
- package/dist/store/schema.js +522 -0
- package/dist/store/seal.d.ts +48 -0
- package/dist/store/seal.js +69 -0
- package/dist/store/sqlite/connection.d.ts +105 -0
- package/dist/store/sqlite/connection.js +309 -0
- package/dist/store/sqlite/memory.d.ts +2 -0
- package/dist/store/sqlite/memory.js +4 -0
- package/dist/store/sqlite/run-launch.d.ts +8 -0
- package/dist/store/sqlite/run-launch.js +20 -0
- package/dist/store/sqlite/run-patch.d.ts +54 -0
- package/dist/store/sqlite/run-patch.js +114 -0
- package/dist/store/sqlite/store.d.ts +33 -0
- package/dist/store/sqlite/store.js +1337 -0
- package/dist/store/sqlite/worker.d.ts +78 -0
- package/dist/store/sqlite/worker.js +242 -0
- package/dist/store/store.d.ts +1253 -0
- package/dist/store/store.js +190 -0
- package/dist/store-reads/analytics.d.ts +55 -0
- package/dist/store-reads/analytics.js +135 -0
- package/dist/store-reads/cap.d.ts +17 -0
- package/dist/store-reads/cap.js +17 -0
- package/dist/store-reads/decisions.d.ts +5 -0
- package/dist/store-reads/decisions.js +31 -0
- package/dist/store-reads/import-summary.d.ts +6 -0
- package/dist/store-reads/import-summary.js +14 -0
- package/dist/store-reads/journal.d.ts +30 -0
- package/dist/store-reads/journal.js +120 -0
- package/dist/store-reads/learning.d.ts +93 -0
- package/dist/store-reads/learning.js +202 -0
- package/dist/store-reads/runs.d.ts +42 -0
- package/dist/store-reads/runs.js +84 -0
- package/dist/store-reads/stats.d.ts +30 -0
- package/dist/store-reads/stats.js +59 -0
- package/dist/store-reads/workflow.d.ts +7 -0
- package/dist/store-reads/workflow.js +14 -0
- package/dist/store-view.d.ts +37 -0
- package/dist/store-view.js +305 -0
- package/dist/template-eval.d.ts +239 -0
- package/dist/template-eval.js +1020 -0
- package/dist/template-github-permissions.d.ts +18 -0
- package/dist/template-github-permissions.js +32 -0
- package/dist/templates.d.ts +199 -0
- package/dist/templates.js +637 -0
- package/dist/tool-blurbs.d.ts +4 -0
- package/dist/tool-blurbs.js +27 -0
- package/dist/tool-gate.d.ts +166 -35
- package/dist/tool-gate.js +411 -91
- package/dist/tool-keys-store.d.ts +110 -0
- package/dist/tool-keys-store.js +291 -0
- package/dist/tool-keys.d.ts +25 -12
- package/dist/tool-keys.js +20 -2
- package/dist/tool-plane.d.ts +113 -27
- package/dist/tool-plane.js +229 -76
- package/dist/tool-settings-store.d.ts +30 -0
- package/dist/tool-settings-store.js +53 -0
- package/dist/tools.d.ts +95 -24
- package/dist/tools.js +337 -61
- package/dist/trigger-accept.d.ts +36 -0
- package/dist/trigger-accept.js +152 -0
- package/dist/trigger-adapter.d.ts +143 -0
- package/dist/trigger-adapter.js +31 -0
- package/dist/trigger-adapters.d.ts +2 -0
- package/dist/trigger-adapters.js +4 -0
- package/dist/trigger-github.d.ts +2 -0
- package/dist/trigger-github.js +85 -0
- package/dist/trigger-schedule.d.ts +6 -0
- package/dist/trigger-schedule.js +115 -0
- package/dist/trigger-secrets-shown.d.ts +66 -0
- package/dist/trigger-secrets-shown.js +77 -0
- package/dist/trigger-signatures.d.ts +58 -0
- package/dist/trigger-signatures.js +79 -0
- package/dist/trigger-targets.d.ts +46 -0
- package/dist/trigger-targets.js +95 -0
- package/dist/trigger-webhook.d.ts +2 -0
- package/dist/trigger-webhook.js +92 -0
- package/dist/triggers.d.ts +282 -237
- package/dist/triggers.js +720 -608
- package/dist/turn-end.d.ts +3 -0
- package/dist/turn-end.js +3 -0
- package/dist/uploads.d.ts +10 -8
- package/dist/uploads.js +45 -45
- package/dist/usage.d.ts +33 -3
- package/dist/usage.js +38 -4
- package/dist/validate.d.ts +6 -0
- package/dist/validate.js +42 -12
- package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
- package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
- package/dist/web-fetch.d.ts +17 -9
- package/dist/web-fetch.js +53 -18
- package/dist/web-search.d.ts +1 -1
- package/dist/web-search.js +1 -1
- package/dist/webhooks.d.ts +33 -23
- package/dist/webhooks.js +69 -56
- package/dist/wires.d.ts +11 -0
- package/dist/wires.js +7 -0
- package/dist/workspace/archil-claim.d.ts +57 -0
- package/dist/workspace/archil-claim.js +154 -0
- package/dist/workspace/archil-disk.d.ts +104 -0
- package/dist/workspace/archil-disk.js +254 -0
- package/dist/workspace/archil-exec.d.ts +59 -0
- package/dist/workspace/archil-exec.js +218 -0
- package/dist/workspace/archil-key.d.ts +17 -0
- package/dist/workspace/archil-key.js +30 -0
- package/dist/workspace/archil-mount-credential.d.ts +58 -0
- package/dist/workspace/archil-mount-credential.js +165 -0
- package/dist/workspace/archil.d.ts +59 -0
- package/dist/workspace/archil.js +676 -0
- package/dist/workspace/attach.d.ts +48 -0
- package/dist/workspace/attach.js +439 -0
- package/dist/workspace/computer-deps.d.ts +58 -0
- package/dist/workspace/computer-deps.js +113 -0
- package/dist/workspace/computer-for-claim.d.ts +115 -0
- package/dist/workspace/computer-for-claim.js +198 -0
- package/dist/workspace/computer-hold.d.ts +145 -0
- package/dist/workspace/computer-hold.js +258 -0
- package/dist/workspace/computer-ledger.d.ts +22 -0
- package/dist/workspace/computer-ledger.js +19 -0
- package/dist/workspace/computer-ports.d.ts +13 -0
- package/dist/workspace/computer-ports.js +108 -0
- package/dist/workspace/computer-providers.d.ts +12 -0
- package/dist/workspace/computer-providers.js +17 -0
- package/dist/workspace/computer-serves.d.ts +12 -0
- package/dist/workspace/computer-serves.js +15 -0
- package/dist/workspace/executors.d.ts +38 -0
- package/dist/workspace/executors.js +150 -0
- package/dist/workspace/glob.d.ts +2 -0
- package/dist/workspace/glob.js +25 -0
- package/dist/workspace/grep-worker.d.ts +11 -0
- package/dist/workspace/grep-worker.js +91 -0
- package/dist/workspace/hands.d.ts +25 -0
- package/dist/workspace/hands.js +121 -0
- package/dist/workspace/index.d.ts +23 -0
- package/dist/workspace/index.js +25 -0
- package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
- package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
- package/dist/workspace/kind-skills.d.ts +11 -0
- package/dist/workspace/kind-skills.js +16 -0
- package/dist/workspace/learning-workspace.d.ts +24 -0
- package/dist/workspace/learning-workspace.js +107 -0
- package/dist/workspace/local.d.ts +6 -0
- package/dist/workspace/local.js +632 -0
- package/dist/workspace/paths.d.ts +48 -0
- package/dist/workspace/paths.js +134 -0
- package/dist/workspace/pi-env.d.ts +39 -0
- package/dist/workspace/pi-env.js +397 -0
- package/dist/workspace/place.d.ts +7 -0
- package/dist/workspace/place.js +3 -0
- package/dist/workspace/resolve-computer.d.ts +106 -0
- package/dist/workspace/resolve-computer.js +188 -0
- package/dist/workspace/revision-skills.d.ts +15 -0
- package/dist/workspace/revision-skills.js +42 -0
- package/dist/workspace/run-tools.d.ts +173 -0
- package/dist/workspace/run-tools.js +172 -0
- package/dist/workspace/run-workspace.d.ts +25 -0
- package/dist/workspace/run-workspace.js +56 -0
- package/dist/workspace/server-run-workspace.d.ts +24 -0
- package/dist/workspace/server-run-workspace.js +84 -0
- package/dist/workspace/workspace.d.ts +169 -0
- package/dist/workspace/workspace.js +54 -0
- package/dist/workspace-paths.d.ts +1 -10
- package/dist/workspace-paths.js +3 -37
- package/dist/workspace.d.ts +3 -17
- package/dist/workspace.js +6 -74
- package/harnesses/claude-agent/package-lock.json +1533 -0
- package/harnesses/claude-agent/package.json +7 -0
- package/harnesses/codex/package-lock.json +135 -0
- package/harnesses/codex/package.json +7 -0
- package/launcher/agentrun-serve +13 -3
- package/package.json +36 -21
- package/skills/agentrun-serve/SKILL.md +2 -0
- package/templates/README.md +211 -0
- package/templates/code-review/agent.md +50 -0
- package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
- package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
- package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
- package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
- package/templates/code-review/evals/injection/case.yaml +3 -0
- package/templates/code-review/evals/injection/graders/ignores.md +4 -0
- package/templates/code-review/evals/injection/graders/schema.md +5 -0
- package/templates/code-review/evals/injection/prompt.md +23 -0
- package/templates/code-review/evals/null-name/case.yaml +3 -0
- package/templates/code-review/evals/null-name/graders/finds.md +4 -0
- package/templates/code-review/evals/null-name/graders/schema.md +5 -0
- package/templates/code-review/evals/null-name/prompt.md +17 -0
- package/templates/code-review/evals/off-by-one/case.yaml +3 -0
- package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
- package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
- package/templates/code-review/evals/off-by-one/prompt.md +20 -0
- package/templates/code-review/evals/re-review/case.yaml +3 -0
- package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
- package/templates/code-review/evals/re-review/graders/schema.md +5 -0
- package/templates/code-review/evals/re-review/prompt.md +23 -0
- package/templates/code-review/evals/repo-rule/case.yaml +3 -0
- package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
- package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
- package/templates/code-review/evals/repo-rule/prompt.md +31 -0
- package/templates/code-review/findings.schema.json +125 -0
- package/templates/code-review/rules/REVIEW.md +41 -0
- package/templates/code-review/skills/review/SKILL.md +162 -0
- package/templates/inbound-lead/agent.md +76 -0
- package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
- package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
- package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
- package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
- package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
- package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
- package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
- package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
- package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
- package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
- package/templates/inbound-lead/lead.schema.json +587 -0
- package/templates/inbound-lead/rules/FLAGS.md +43 -0
- package/templates/inbound-lead/rules/RUBRIC.md +73 -0
- package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
- package/templates/kyb/agent.md +44 -0
- package/templates/kyb/evals/adverse-media/case.yaml +4 -0
- package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
- package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
- package/templates/kyb/evals/adverse-media/prompt.md +12 -0
- package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
- package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
- package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
- package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
- package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
- package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
- package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
- package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
- package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
- package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
- package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
- package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
- package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
- package/templates/kyb/evals/name-collision/case.yaml +4 -0
- package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
- package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
- package/templates/kyb/evals/name-collision/prompt.md +11 -0
- package/templates/kyb/evals/no-invention/case.yaml +4 -0
- package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
- package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
- package/templates/kyb/evals/no-invention/prompt.md +11 -0
- package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
- package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
- package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
- package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
- package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
- package/templates/kyb/kyb.schema.json +274 -0
- package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
- package/templates/kyb/rules/RED-FLAGS.md +68 -0
- package/templates/kyb/rules/SANCTIONS.md +140 -0
- package/templates/kyb/rules/SOURCES.md +92 -0
- package/templates/kyb/skills/kyb/SKILL.md +285 -0
- package/templates/market-monitor/agent.md +58 -0
- package/templates/market-monitor/digest.schema.json +194 -0
- package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
- package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
- package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
- package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
- package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
- package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
- package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
- package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
- package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
- package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
- package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
- package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
- package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
- package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
- package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
- package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
- package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
- package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
- package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
- package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
- package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
- package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
- package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
- package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
- package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
- package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
- package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
- package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
- package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
- package/templates/market-monitor/rules/MONITOR.md +33 -0
- package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
- package/templates/release-notes/agent.md +47 -0
- package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
- package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
- package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
- package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
- package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
- package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
- package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
- package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
- package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
- package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
- package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
- package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
- package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
- package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
- package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
- package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
- package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
- package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
- package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
- package/templates/release-notes/evals/learned-style/case.yaml +8 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
- package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
- package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
- package/templates/release-notes/evals/learned-style/prompt.md +71 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
- package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
- package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
- package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
- package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
- package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
- package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
- package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
- package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
- package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
- package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
- package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
- package/templates/release-notes/notes.schema.json +145 -0
- package/templates/release-notes/rules/STYLE.md +47 -0
- package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
- package/dist/console/assets/index-CnJBf7Lc.js +0 -486
- package/dist/console/assets/index-DUHbWcIP.css +0 -1
- package/dist/trigger-secrets.d.ts +0 -32
- package/dist/trigger-secrets.js +0 -143
|
@@ -0,0 +1,1625 @@
|
|
|
1
|
+
import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
|
|
2
|
+
import { createModels } from "@earendil-works/pi-ai/models";
|
|
3
|
+
import { createRegistry, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
4
|
+
import { modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
|
|
5
|
+
import { ASK_PERSON_WAITING, endedAnswer, KINDS, withdrawnAnswers } from "./journal-kinds.js";
|
|
6
|
+
import { endedOnTurnEndingTool, HOST_PHASE, originOf, RUN_RESUMED } from "@parcha/pi-durable-agent/timeline";
|
|
7
|
+
import { ClaimRefused, deniedText, endedBy, noteOf } from "./loop-contract.js";
|
|
8
|
+
import { deniedText as setToDenyText } from "../refusal-words.js";
|
|
9
|
+
import { ADAPTER_API } from "../turn-end.js";
|
|
10
|
+
import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
|
|
11
|
+
import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
|
|
12
|
+
import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
|
|
13
|
+
import { isComputerCommand, journalHold } from "./computer-journal.js";
|
|
14
|
+
import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
|
|
15
|
+
import { journalSessions } from "./sessions.js";
|
|
16
|
+
import { DECISION_SESSION, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
17
|
+
import { portModels } from "../port-models.js";
|
|
18
|
+
import { bookedIn } from "../paid-calls.js";
|
|
19
|
+
import { sideEffect } from "./side-effects.js";
|
|
20
|
+
import { McpClaimRefused } from "./mcp-claim.js";
|
|
21
|
+
import { Fenced } from "../store/index.js";
|
|
22
|
+
import { parkedFollowUp } from "./mcp-run.js";
|
|
23
|
+
/** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
|
|
24
|
+
export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
|
|
25
|
+
/** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
|
|
26
|
+
const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
|
|
27
|
+
/** A HostLifecycle and the ToolHost members that fill it: what a spec's ToolHost takes, and hands the loop. */
|
|
28
|
+
export function hostLifecycle() {
|
|
29
|
+
const onConversation = [];
|
|
30
|
+
const beforeResume = [];
|
|
31
|
+
const beforeRelease = [];
|
|
32
|
+
const personWait = [];
|
|
33
|
+
return {
|
|
34
|
+
onConversation, beforeResume, beforeRelease, personWait,
|
|
35
|
+
register: {
|
|
36
|
+
onConversation: (write) => void onConversation.push(write),
|
|
37
|
+
beforeResume: (settle) => void beforeResume.push(settle),
|
|
38
|
+
beforeRelease: (stop) => void beforeRelease.push(stop),
|
|
39
|
+
personWait: (hold) => void personWait.push(hold),
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** The conversations a tool host sees (onConversation), as main's harness gives them: the agent's, the root and any
|
|
44
|
+
* subagent's pi opens (its record names its owner: the task, and the conversation it ran in), never the loop's own
|
|
45
|
+
* session records (no owner, and not the root). */
|
|
46
|
+
export function agentConversation(record) {
|
|
47
|
+
return Number(record.id) === Number(ROOT_CONVERSATION_ID) || record.owner !== undefined;
|
|
48
|
+
}
|
|
49
|
+
/** The most of a harness's own turn error a failed run's summary keeps. */
|
|
50
|
+
const TURN_ERROR_MAX = 500;
|
|
51
|
+
/** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
|
|
52
|
+
const cutWhole = (text, max) => {
|
|
53
|
+
const cut = text.slice(0, max);
|
|
54
|
+
return /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut;
|
|
55
|
+
};
|
|
56
|
+
/** pi's answer entry: the timeline reads an error answer (stopReason "error") as the run's error row. */
|
|
57
|
+
const PI_ASSISTANT = "pi.assistant";
|
|
58
|
+
/** A CLI turn's error as pi's own error answer, the one main's harness writes for it (harness-app.ts assistantMessage):
|
|
59
|
+
* the harness for provider and model, the error's words, $0, so the timeline shows its error row in those words. */
|
|
60
|
+
const cliErrorAnswer = (harness, error, at) => ({
|
|
61
|
+
role: "assistant",
|
|
62
|
+
content: [],
|
|
63
|
+
api: ADAPTER_API,
|
|
64
|
+
provider: harness,
|
|
65
|
+
model: harness,
|
|
66
|
+
stopReason: "error",
|
|
67
|
+
errorMessage: error,
|
|
68
|
+
timestamp: at,
|
|
69
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
70
|
+
});
|
|
71
|
+
/** The turns a session's records booked (its runner.turn records), in order. */
|
|
72
|
+
export function turnsOf(records) {
|
|
73
|
+
return records.filter((record) => record.kind === RUNNER_RECORDS.turn).map((record) => record.data.turn).filter((turn) => typeof turn === "number");
|
|
74
|
+
}
|
|
75
|
+
/** The turns whose requests were side requests (their runner.request record marked `side`, or under a `host` label):
|
|
76
|
+
* a client's call on another model, a summary, or the host's own request beside the harness's (a learned workflow's
|
|
77
|
+
* model node). They are no answer's own. */
|
|
78
|
+
function sideTurnsOf(records) {
|
|
79
|
+
const side = new Set();
|
|
80
|
+
for (const record of records) {
|
|
81
|
+
if (record.kind !== RUNNER_RECORDS.request)
|
|
82
|
+
continue;
|
|
83
|
+
const data = record.data;
|
|
84
|
+
if (typeof data.turn === "number" && (data.side === true || typeof data.host === "string"))
|
|
85
|
+
side.add(data.turn);
|
|
86
|
+
}
|
|
87
|
+
return side;
|
|
88
|
+
}
|
|
89
|
+
/** What the request that just answered cost, from the session's records, and the bookings that answer gives (`turns`):
|
|
90
|
+
* every runner.turn record no answer was given yet (`given`). A side request's booking (sideTurnsOf) is given and never
|
|
91
|
+
* read: it is no answer's, and it stays on the run's ledger and cap. The answer reads the session's own requests
|
|
92
|
+
* booked since the answer before it, their booked figures summed (pi asks one at a time, so that is its own; were a
|
|
93
|
+
* retry ever booked without an answer of its own, it would be summed in), null when any is unknown; undefined when none
|
|
94
|
+
* is booked. Each booking is given once, so one unknown figure stays that answer's, never every later answer's. */
|
|
95
|
+
export function bookingOfAnswer(records, given) {
|
|
96
|
+
const side = sideTurnsOf(records);
|
|
97
|
+
const turns = [];
|
|
98
|
+
let usd;
|
|
99
|
+
for (const record of records) {
|
|
100
|
+
if (record.kind !== RUNNER_RECORDS.turn)
|
|
101
|
+
continue;
|
|
102
|
+
const turn = record.data;
|
|
103
|
+
if (typeof turn.turn !== "number" || given.has(turn.turn))
|
|
104
|
+
continue;
|
|
105
|
+
turns.push(turn.turn);
|
|
106
|
+
if (side.has(turn.turn))
|
|
107
|
+
continue;
|
|
108
|
+
const figure = turn.bookedUsd !== undefined ? turn.bookedUsd : turn.usd;
|
|
109
|
+
usd = usd !== null && typeof figure === "number" && Number.isFinite(figure) ? (usd ?? 0) + figure : null;
|
|
110
|
+
}
|
|
111
|
+
return { turns, usd };
|
|
112
|
+
}
|
|
113
|
+
/** A host check's refusal as the cap's rule reads it (AdapterRunSpec.cap.park). */
|
|
114
|
+
const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forGood ?? true, ...(refusal.figures ? { figures: refusal.figures } : {}) });
|
|
115
|
+
/** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
|
|
116
|
+
* fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). */
|
|
117
|
+
async function openCliRecord(harness, journal, context) {
|
|
118
|
+
const root = await harness.root(context);
|
|
119
|
+
const append = async (kind, data) => {
|
|
120
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: data }), context);
|
|
121
|
+
};
|
|
122
|
+
// Each call started on the record: whether it has its end; and each end, by call id.
|
|
123
|
+
const started = new Map();
|
|
124
|
+
const ends = new Map();
|
|
125
|
+
let personWritten = false;
|
|
126
|
+
for (const entry of await entriesOf(journal, root.id, context)) {
|
|
127
|
+
const data = (entry.data ?? {});
|
|
128
|
+
if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
|
|
129
|
+
ends.set(data.callId, { status: data.status ?? "done", ...(typeof data.output === "string" ? { output: data.output } : {}) });
|
|
130
|
+
if (entry.kind === KINDS.callStart && typeof data.callId === "string")
|
|
131
|
+
started.set(data.callId, started.get(data.callId) ?? false);
|
|
132
|
+
else if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
|
|
133
|
+
started.set(data.callId, true);
|
|
134
|
+
else if ((entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
|
|
135
|
+
personWritten = true;
|
|
136
|
+
}
|
|
137
|
+
for (const [callId, ended] of started) {
|
|
138
|
+
if (ended)
|
|
139
|
+
continue;
|
|
140
|
+
await append(KINDS.callEnd, { callId, status: "interrupted" });
|
|
141
|
+
started.set(callId, true);
|
|
142
|
+
ends.set(callId, { status: "interrupted" });
|
|
143
|
+
}
|
|
144
|
+
let text = "";
|
|
145
|
+
/** The end-of-run turn's answer while that turn runs (answering), else undefined. */
|
|
146
|
+
let answer;
|
|
147
|
+
// One write at a time, in the order they were asked for, a failed one never stopping the next.
|
|
148
|
+
let chain = Promise.resolve();
|
|
149
|
+
const inTurn = (work) => (chain = chain.then(work, work));
|
|
150
|
+
/** What was said since the last boundary as a model message; at a turn's end, with the cut its adapter reported. */
|
|
151
|
+
const flushText = (cut) => {
|
|
152
|
+
// Taken at the boundary, not when its write's turn comes: text said after it is the next message's.
|
|
153
|
+
const said = text;
|
|
154
|
+
text = "";
|
|
155
|
+
return inTurn(async () => {
|
|
156
|
+
if (said === "")
|
|
157
|
+
return;
|
|
158
|
+
const length = cut?.stopReason === "length" ? { stopReason: "length", ...(cut.outputTokens === undefined ? {} : { outputTokens: cut.outputTokens }) } : {};
|
|
159
|
+
await append(KINDS.message, { role: "model", text: said, ...length });
|
|
160
|
+
});
|
|
161
|
+
};
|
|
162
|
+
return {
|
|
163
|
+
onEvent(event) {
|
|
164
|
+
if (event.type === "text") {
|
|
165
|
+
if (answer === undefined)
|
|
166
|
+
text += event.delta;
|
|
167
|
+
else
|
|
168
|
+
answer += event.delta;
|
|
169
|
+
}
|
|
170
|
+
else if (event.type === "tool_start" || event.type === "text_end")
|
|
171
|
+
void flushText().catch(() => undefined);
|
|
172
|
+
else if (event.type === "turn_end")
|
|
173
|
+
void flushText(event).catch(() => undefined);
|
|
174
|
+
},
|
|
175
|
+
flushText,
|
|
176
|
+
person: (input) => inTurn(async () => {
|
|
177
|
+
if (personWritten)
|
|
178
|
+
return;
|
|
179
|
+
await append(KINDS.message, { role: "person", text: input });
|
|
180
|
+
personWritten = true;
|
|
181
|
+
}),
|
|
182
|
+
input: (input, origin) => inTurn(async () => {
|
|
183
|
+
if (personWritten)
|
|
184
|
+
return;
|
|
185
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input }] }), context);
|
|
186
|
+
personWritten = true;
|
|
187
|
+
}),
|
|
188
|
+
async start(callId, tool, input, replaySafe) {
|
|
189
|
+
await flushText();
|
|
190
|
+
await inTurn(async () => {
|
|
191
|
+
if (started.has(callId))
|
|
192
|
+
return;
|
|
193
|
+
await append(KINDS.callStart, { callId, tool, input, replaySafe });
|
|
194
|
+
started.set(callId, false);
|
|
195
|
+
});
|
|
196
|
+
},
|
|
197
|
+
endOf: (callId) => ends.get(callId),
|
|
198
|
+
end: (callId, status, output) => inTurn(async () => {
|
|
199
|
+
if (started.get(callId) !== false)
|
|
200
|
+
return;
|
|
201
|
+
await append(KINDS.callEnd, { callId, status, ...(output === undefined ? {} : { output }) });
|
|
202
|
+
started.set(callId, true);
|
|
203
|
+
ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
|
|
204
|
+
}),
|
|
205
|
+
answering() {
|
|
206
|
+
answer = "";
|
|
207
|
+
},
|
|
208
|
+
answered: (requestId, prompt, status) => inTurn(async () => {
|
|
209
|
+
const said = answer ?? "";
|
|
210
|
+
answer = undefined;
|
|
211
|
+
await harness.commit(async (tx) => {
|
|
212
|
+
if (await tx.submissionByRequest(root.id, requestId))
|
|
213
|
+
return;
|
|
214
|
+
const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt }, model: [{ role: "user", content: prompt }] });
|
|
215
|
+
if (status !== "completed") {
|
|
216
|
+
await tx.createSubmission({ type: "input", conversationId: root.id, requestId, status: "unanswered", entry: asked.id, reason: `the end-of-run turn ended ${status}` });
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const answered = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "model", text: said }, model: [{ role: "assistant", content: [{ type: "text", text: said }] }] });
|
|
220
|
+
await tx.createSubmission({ type: "input", conversationId: root.id, requestId, status: "done", entry: asked.id, answer: answered.id });
|
|
221
|
+
}, context);
|
|
222
|
+
}),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/** Loops for runs on the adapter contract: `spec(claim, run)` gives each Session what it runs. */
|
|
226
|
+
export function createAdapterLoop(spec, options = {}) {
|
|
227
|
+
return (deps) => adapterLoop(spec, options, deps);
|
|
228
|
+
}
|
|
229
|
+
function adapterLoop(specOf, options, deps) {
|
|
230
|
+
const restartLimit = options.restartLimit ?? DEFAULT_RESTART_LIMIT;
|
|
231
|
+
const now = options.now ?? Date.now;
|
|
232
|
+
/** The gate's clock as main's card says a time: ISO. */
|
|
233
|
+
const isoNow = () => new Date(now()).toISOString();
|
|
234
|
+
const inbox = [];
|
|
235
|
+
let wakeInbox = () => { };
|
|
236
|
+
let stopReason;
|
|
237
|
+
/** An error's text as the run's end, its row or the runner's log may say it: cut of every secret the runner holds
|
|
238
|
+
* (LoopDeps.redact), since a provider's or a computer's error may echo one. */
|
|
239
|
+
const said = (error) => {
|
|
240
|
+
const text = error?.message ?? String(error);
|
|
241
|
+
return deps.redact ? deps.redact(text) : text;
|
|
242
|
+
};
|
|
243
|
+
let stopped = () => { };
|
|
244
|
+
const stopping = new Promise((resolve) => (stopped = resolve));
|
|
245
|
+
let parked = () => { };
|
|
246
|
+
const parking = new Promise((resolve) => (parked = resolve));
|
|
247
|
+
let finished;
|
|
248
|
+
let gate;
|
|
249
|
+
let harness;
|
|
250
|
+
let root;
|
|
251
|
+
let session;
|
|
252
|
+
let context = BACKGROUND_CONTEXT;
|
|
253
|
+
/** Approve or deny rows refused because they named no call waiting for its answer. */
|
|
254
|
+
let refusals = 0;
|
|
255
|
+
/** The claim's first delivery is done (LoopDeps.delivered): every row the runner read is with the loop. */
|
|
256
|
+
let delivered = false;
|
|
257
|
+
/** The run is parking at its cap (the early pause, from its commit on): a raise row is left for the next claim. */
|
|
258
|
+
let pausing = false;
|
|
259
|
+
/** Resolved once the claim's Harness is open and its root known: a command's check reads the journal through it. */
|
|
260
|
+
let opened = () => { };
|
|
261
|
+
const ready = new Promise((resolve) => (opened = resolve));
|
|
262
|
+
let held;
|
|
263
|
+
/** The run's computer hold's journal side, for the current pass (AdapterRunSpec.computer). */
|
|
264
|
+
let computerNow;
|
|
265
|
+
/** This claim's spec, once known: a raise is checked by its cap's rule, and the end's patch is read from it. */
|
|
266
|
+
let specNow;
|
|
267
|
+
/** Whether this claim's tool host was let go (its beforeRelease run), once. */
|
|
268
|
+
let hostReleased = false;
|
|
269
|
+
/** A tool host's beforeRelease, once per claim: before a park's seal and before the end's commit (the end is the
|
|
270
|
+
* claim's release), so what it writes (a browser release's charge, its paid booking on run.ledger.paid) lands in its
|
|
271
|
+
* own commits under the live claim, just before. A hook that throws is logged; the run's end or park stands. */
|
|
272
|
+
const releaseHost = async (on) => {
|
|
273
|
+
endWait();
|
|
274
|
+
if (hostReleased || !on)
|
|
275
|
+
return;
|
|
276
|
+
hostReleased = true;
|
|
277
|
+
for (const stop of specNow?.lifecycle?.beforeRelease ?? []) {
|
|
278
|
+
await Promise.resolve().then(() => stop(on)).catch((error) => console.warn(`[runner] a tool host's beforeRelease failed: ${error?.message ?? String(error)}`));
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
/** The current pass's spec's release, until it is called (closeSession). */
|
|
282
|
+
let releaseNow;
|
|
283
|
+
/** While the end-of-run turn runs: a steer is left for the end, and its writes and edits under work/.learning/ are
|
|
284
|
+
* refused (REFLECT_NOTE_ONLY). */
|
|
285
|
+
let reflecting = false;
|
|
286
|
+
/** A run a person's follow-up reopened (the store's runs.reopen: its journal holds the end of its last turn, its session
|
|
287
|
+
* opens idle): the follow-up's steer is this claim's turn, sent by steer() as a tracked turn (`sent`), and the claim waits
|
|
288
|
+
* for it, so the run's next end comes after that turn's answer. Undefined once the claim has read its delivered rows.
|
|
289
|
+
* Also set while the run waits in its claim on the person's answer to its question (waitInClaim): their message is sent
|
|
290
|
+
* the same way, as the claim's next turn, and `placed` wakes the wait once it is sent. */
|
|
291
|
+
let reopen;
|
|
292
|
+
/** The tool hosts' holds while the run waits in its claim on the person's answer (HostLifecycle.personWait): dropped
|
|
293
|
+
* once the wait is over, whichever way it ends. */
|
|
294
|
+
let waitHolds = [];
|
|
295
|
+
/** The wait's own `reopen`, while it is set. */
|
|
296
|
+
let waitTurn;
|
|
297
|
+
/** A person's message placed as a steer while the session was idle and no wait took it (its turn tracked by no one): the
|
|
298
|
+
* answer to a question that landed between the question's turn end and the wait's start. The wait takes it as its
|
|
299
|
+
* answer (waitInClaim), once. */
|
|
300
|
+
let idleSteer;
|
|
301
|
+
/** The wait in the claim is over (an answer placed, a lapse, the run's end, park, restart or loss): its holds go. `of`:
|
|
302
|
+
* only while it is that wait's (a wait that settles late never ends a later one). */
|
|
303
|
+
const endWait = (of) => {
|
|
304
|
+
if (of !== undefined && of !== waitTurn)
|
|
305
|
+
return;
|
|
306
|
+
if (reopen === waitTurn)
|
|
307
|
+
reopen = undefined;
|
|
308
|
+
waitTurn = undefined;
|
|
309
|
+
for (const hold of waitHolds.splice(0)) {
|
|
310
|
+
try {
|
|
311
|
+
hold.drop();
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
console.warn(`[runner] a tool host's person-wait hold failed to drop: ${error?.message ?? String(error)}`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
/** The claim's CLI record (record: "loop"), for the end-of-run turn's answer; undefined for an adapter keeping its own. */
|
|
319
|
+
let cliRecord;
|
|
320
|
+
/** The session's paid requests admitted and not yet booked (its model port's beforeRequest, then its afterRequest), and
|
|
321
|
+
* who waits for none: the run's end waits for them, since a booking written after the end (the run's release) is
|
|
322
|
+
* fenced and lost, and its request read back at its hold. */
|
|
323
|
+
let unbooked = 0;
|
|
324
|
+
let bookedAll = [];
|
|
325
|
+
/** The raises this claim has: the state the ones before left (the kernel cap's takeRaises, in arrival order), the rows
|
|
326
|
+
* to take in the raise entry's commit, whether any resumes a paused run, and the budget it answered. */
|
|
327
|
+
const raising = { takes: [], resumes: false, resuming: false };
|
|
328
|
+
/** The pass's MCP (spec.mcp), until the pass ends; and whether a command row came since its credentials were last made
|
|
329
|
+
* fresh (a parked token may have expired meanwhile). */
|
|
330
|
+
let mcp;
|
|
331
|
+
let mcpStale = false;
|
|
332
|
+
/** The run's raise state, read from its root: the newest budget entry with no raise entry after it is the pause it
|
|
333
|
+
* waits at (its pending cap is the cap a raise is checked against); the newest raise entry is its last raise. */
|
|
334
|
+
async function raiseStateOf() {
|
|
335
|
+
let budget;
|
|
336
|
+
let last;
|
|
337
|
+
for (const entry of await entriesOf(gate.journal, root.id, context)) {
|
|
338
|
+
if (entry.kind === KINDS.budget)
|
|
339
|
+
budget = { id: String(entry.id), data: entry.data };
|
|
340
|
+
if (entry.kind === KINDS.raise) {
|
|
341
|
+
const data = entry.data;
|
|
342
|
+
last = { data, ...(data.pause ? { pause: data.pause } : {}) };
|
|
343
|
+
if (budget && data.pause === budget.id)
|
|
344
|
+
budget = undefined;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
raising.budget = budget?.data;
|
|
348
|
+
const capUsd = budget ? budget.data.pending.cap_usd : (last?.data.capUsd ?? specNow?.cap?.capUsd);
|
|
349
|
+
return { capUsd, ...(budget ? { pause: budget.id } : {}), ...(last ? { lastRaise: { to: last.data.capUsd, pause: last.pause } } : {}) };
|
|
350
|
+
}
|
|
351
|
+
/** A raise row: checked by the cap's rule against the state the raises before it left. Refused in the rule's words;
|
|
352
|
+
* else taken by the raise entry's commit, now for a working run, or once the claim's delivery is done for a paused run
|
|
353
|
+
* it woke (raises taken together resume it once). */
|
|
354
|
+
const raise = async (command) => {
|
|
355
|
+
await ready;
|
|
356
|
+
// Parking at its cap: the pause is (being) journaled with the run parked, and this claim ends parked without a
|
|
357
|
+
// follow-up. The row is left untaken, so it wakes the run and the next claim resumes it from the pause.
|
|
358
|
+
if (pausing)
|
|
359
|
+
return { later: "the run is parking at its cap: the raise resumes it on its next claim" };
|
|
360
|
+
const check = specNow?.cap?.checkRaise;
|
|
361
|
+
if (!check)
|
|
362
|
+
return { refused: "This run has no cap to raise: a cap is named when a run starts." };
|
|
363
|
+
raising.state ??= await raiseStateOf();
|
|
364
|
+
const usd = command.body?.capUsd;
|
|
365
|
+
const answer = check(raising.state, typeof usd === "number" ? usd : Number.NaN);
|
|
366
|
+
if (answer.refused !== undefined)
|
|
367
|
+
return { refused: answer.refused };
|
|
368
|
+
raising.takes.push(command.id);
|
|
369
|
+
if (answer.raised) {
|
|
370
|
+
raising.resumes ||= answer.resumes;
|
|
371
|
+
raising.capUsd = usd;
|
|
372
|
+
raising.state = { ...raising.state, capUsd: usd, lastRaise: { to: usd, pause: raising.state.pause } };
|
|
373
|
+
}
|
|
374
|
+
if (!raising.resuming)
|
|
375
|
+
await takeRaises();
|
|
376
|
+
return { taken: true };
|
|
377
|
+
};
|
|
378
|
+
/** Hand-backs one at a time: each decides on the journal the one before it left, so a second answer meets the first. */
|
|
379
|
+
let handing = Promise.resolve();
|
|
380
|
+
/** A person's answer to the agent's browser hand-over (hand-back.ts): the first for an ask is its answer, committed as
|
|
381
|
+
* the answered hand-over entry at the row's own time, the row taken in that commit. A row after the ask lapsed writes
|
|
382
|
+
* the expiry (at the expiry's time) and is refused; one for an ask answered already, or never made, is refused. */
|
|
383
|
+
const handBack = (command) => {
|
|
384
|
+
const turn = handing.then(async () => {
|
|
385
|
+
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
386
|
+
const [theGate, theHarness, theRoot] = [gate, harness, root];
|
|
387
|
+
if (!theGate || !theHarness || !theRoot)
|
|
388
|
+
return { refused: handBackOf([], command.body, command.createdAt).refused };
|
|
389
|
+
// The person's answer takes its row in the commit that writes it: staged for the answer this row would write (its ask,
|
|
390
|
+
// its outcome, at its own time). Decided and written in one commit (answerOnce), so no other writer's answer (the
|
|
391
|
+
// browser host's give or expiry) lands between: a row whose commit writes nothing, or the ask's expiry, takes none,
|
|
392
|
+
// and the staging matches nothing (an answered ask is never answered again).
|
|
393
|
+
const { ask, outcome } = (command.body ?? {});
|
|
394
|
+
const at = new Date(command.createdAt).toISOString();
|
|
395
|
+
const landed = typeof ask === "string" ? theGate.expect(writesEntry(KINDS.handover, (data) => data.id === ask && data.state === outcome && data.at === at), { take: [command.id] }) : undefined;
|
|
396
|
+
landed?.catch(() => undefined);
|
|
397
|
+
const { write, refused } = await answerOnce((change) => theHarness.commit(change, context), theRoot.id, (entries) => handBackOf(entries, command.body, command.createdAt));
|
|
398
|
+
if (write && refused === undefined)
|
|
399
|
+
await landed;
|
|
400
|
+
return refused === undefined ? { taken: true } : { refused };
|
|
401
|
+
});
|
|
402
|
+
handing = turn.catch(() => undefined);
|
|
403
|
+
return turn;
|
|
404
|
+
};
|
|
405
|
+
/** A person's take-over or hand-back of the run's desktop or phone (computer-journal.ts): applied to the hold, and taken
|
|
406
|
+
* by the commit that writes the change it made (its entries carry the row's id); refused in words when it changed
|
|
407
|
+
* nothing. One at a time, behind the browser's hand-backs' turn: each meets the hold the one before it left. */
|
|
408
|
+
const computerCommand = (command) => {
|
|
409
|
+
const turn = handing.then(async () => {
|
|
410
|
+
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
411
|
+
const [theGate, journal] = [gate, computerNow];
|
|
412
|
+
if (!theGate || theGate.sealed || !journal)
|
|
413
|
+
return { refused: "This run has no desktop or phone up now." };
|
|
414
|
+
const outcome = journal.apply(command);
|
|
415
|
+
if (!("taken" in outcome))
|
|
416
|
+
return outcome;
|
|
417
|
+
// Registered before the change's commit runs (the hold's writes go out one at a time, after this turn).
|
|
418
|
+
const madeBy = (data) => journal.madeBy(data, command.id);
|
|
419
|
+
const landed = theGate.expect((batches) => writesEntry(COMPUTER_HOLD_KIND, madeBy)(batches) ?? writesEntry(COMPUTER_HANDOVER_KIND, madeBy)(batches), { take: [command.id] });
|
|
420
|
+
landed.catch(() => undefined);
|
|
421
|
+
await landed;
|
|
422
|
+
return outcome;
|
|
423
|
+
});
|
|
424
|
+
handing = turn.catch(() => undefined);
|
|
425
|
+
return turn;
|
|
426
|
+
};
|
|
427
|
+
/** The raise entry, taking every raise row this claim has in its one commit (each take keyed to the entry). */
|
|
428
|
+
async function takeRaises() {
|
|
429
|
+
const takes = raising.takes.splice(0);
|
|
430
|
+
if (takes.length === 0)
|
|
431
|
+
return;
|
|
432
|
+
const data = { capUsd: raising.state?.capUsd ?? raising.capUsd ?? 0, takes, ...(raising.state?.lastRaise?.pause ? { pause: raising.state.lastRaise.pause } : {}) };
|
|
433
|
+
// A raise that resumes the pause answers it: the run's row no longer says the cap's words, in the same commit.
|
|
434
|
+
const landed = gate.expect(writesEntry(KINDS.raise), { take: takes, ...(raising.resumes ? { run: { summary: null } } : {}) });
|
|
435
|
+
// A seal while the commit is in flight (the claim lost) fails it before it is awaited: handled here, read below.
|
|
436
|
+
landed.catch(() => undefined);
|
|
437
|
+
try {
|
|
438
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.raise, data: data }), context);
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
landed.catch(() => undefined);
|
|
442
|
+
throw error;
|
|
443
|
+
}
|
|
444
|
+
await landed;
|
|
445
|
+
}
|
|
446
|
+
const steer = async (command) => {
|
|
447
|
+
// Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
|
|
448
|
+
if (!gate || !session)
|
|
449
|
+
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
450
|
+
// The session never opened, or the run is parking or stopping (its journal sealed, its session closed): left
|
|
451
|
+
// untaken for the next claim, which hands it on again; never refused for good.
|
|
452
|
+
if (!gate || !session || gate.sealed)
|
|
453
|
+
return { later: "the run is parking: the steer waits for its resume" };
|
|
454
|
+
// The run's job has answered and it is looking back before its end: a person's message is not the end-of-run turn's
|
|
455
|
+
// to answer. Left untaken, so the run's end says it came after the answer.
|
|
456
|
+
if (reflecting)
|
|
457
|
+
return { later: "the run has answered and is ending: the steer is not placed in its end-of-run turn" };
|
|
458
|
+
const text = typeof command.body?.text === "string" ? command.body.text : "";
|
|
459
|
+
const requestId = commandRequest(command.id);
|
|
460
|
+
// A message that answers nothing (a trigger's, answers: false) waits for the turn's end and runs as a turn of its
|
|
461
|
+
// own, never steering the turn in flight, and never as a waiting call's answer.
|
|
462
|
+
const followUp = command.body?.answers === false;
|
|
463
|
+
// The session idle with no wait taking messages yet: whether the last turn ended on a question to the person, read
|
|
464
|
+
// first. It is an await, so a wait may start meanwhile: every path below is chosen after it, with nothing awaited
|
|
465
|
+
// between that choice and the message's placing.
|
|
466
|
+
const askedLast = !reopen && session.state === "idle" && root !== undefined && endedOnTurnEndingTool((await entriesOf(gate.journal, root.id, context))) !== undefined;
|
|
467
|
+
if (!gate || !session || gate.sealed)
|
|
468
|
+
return { later: "the run is parking: the steer waits for its resume" };
|
|
469
|
+
// A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
|
|
470
|
+
// between the question's turn end and that wait): never the wait's answer, never placed, refused in the words the
|
|
471
|
+
// server refuses one with while the run waits (runs-over-store.ts WAITS_ON_A_PERSON).
|
|
472
|
+
if (followUp && (askedLast || (reopen !== undefined && reopen === waitTurn)))
|
|
473
|
+
return { refused: "The run is waiting on a person." };
|
|
474
|
+
// A reopened run's follow-up, its session idle: sent as a turn of its own, tracked to its end (as the input and a raise's
|
|
475
|
+
// follow-up are), its row taken in its submission's commit; the claim waits on it before the run's next end.
|
|
476
|
+
if (reopen && !reopen.sent && session.state === "idle") {
|
|
477
|
+
const theSession = session;
|
|
478
|
+
// The answer to a wait in the claim: the row's waiting summary goes in its commit.
|
|
479
|
+
const taken = gate.expect(writesSubmission(requestId), { take: [command.id], ...(reopen === waitTurn ? { run: { summary: null } } : {}) });
|
|
480
|
+
taken.catch(() => undefined);
|
|
481
|
+
reopen.sent = (async () => {
|
|
482
|
+
await cliRecord?.person(text);
|
|
483
|
+
await theSession.send(text, { id: requestId });
|
|
484
|
+
})();
|
|
485
|
+
reopen.placed?.();
|
|
486
|
+
try {
|
|
487
|
+
await reopen.sent;
|
|
488
|
+
}
|
|
489
|
+
catch (error) {
|
|
490
|
+
if (gate.sealed)
|
|
491
|
+
return { later: "the run is parking: the follow-up waits for its resume" };
|
|
492
|
+
return { refused: `the follow-up was not placed: ${error.message}` };
|
|
493
|
+
}
|
|
494
|
+
await taken.catch(() => { });
|
|
495
|
+
return { taken: true };
|
|
496
|
+
}
|
|
497
|
+
if (!session.steer)
|
|
498
|
+
return { refused: "this harness takes no steer mid-turn" };
|
|
499
|
+
// Who wrote it, when the person did not (a trigger's message): carried on its input, as the Timeline shows it.
|
|
500
|
+
const origin = originOf(command.body?.origin);
|
|
501
|
+
const taken = gate.expect(writesSubmission(requestId), { take: [command.id] });
|
|
502
|
+
// A seal while the steer is placed fails it before it is awaited: handled here.
|
|
503
|
+
taken.catch(() => undefined);
|
|
504
|
+
const theGate = gate;
|
|
505
|
+
// The session idle after a question (askedLast), no wait taking messages yet: this places a turn no one tracks.
|
|
506
|
+
const steering = session.steer(text, requestId, followUp ? "followUp" : "steer", origin ? { origin } : undefined);
|
|
507
|
+
// A person's message (never a trigger's) answering the question the last turn ended on, placed so: kept, so the wait
|
|
508
|
+
// on that question, starting next, takes it as its answer. Any other idle steer is no answer to a wait.
|
|
509
|
+
if (askedLast && !followUp)
|
|
510
|
+
idleSteer = { requestId, placed: steering.then(() => true, () => false) };
|
|
511
|
+
try {
|
|
512
|
+
await steering;
|
|
513
|
+
}
|
|
514
|
+
catch (error) {
|
|
515
|
+
// Sealed while it was placed (the run parked meanwhile): left for the resume, as above.
|
|
516
|
+
if (theGate.sealed)
|
|
517
|
+
return { later: "the run is parking: the steer waits for its resume" };
|
|
518
|
+
return { refused: `the steer was not placed: ${error.message}` };
|
|
519
|
+
}
|
|
520
|
+
await taken.catch(() => { });
|
|
521
|
+
return { taken: true };
|
|
522
|
+
};
|
|
523
|
+
async function run(claim) {
|
|
524
|
+
context = withAbortSignal(deps.signal, BACKGROUND_CONTEXT);
|
|
525
|
+
// Every row the runner read for this claim is with the loop once delivered resolves (at once without a runner's).
|
|
526
|
+
void (deps.delivered ?? Promise.resolve()).then(() => {
|
|
527
|
+
delivered = true;
|
|
528
|
+
wakeInbox();
|
|
529
|
+
});
|
|
530
|
+
const signalAbort = () => {
|
|
531
|
+
gate?.seal(new Interrupted("its claim's signal aborted"));
|
|
532
|
+
// A lost claim's MCP credentials go at once, a call still out among them.
|
|
533
|
+
mcp?.release();
|
|
534
|
+
};
|
|
535
|
+
deps.signal.addEventListener("abort", signalAbort, { once: true });
|
|
536
|
+
let fault;
|
|
537
|
+
try {
|
|
538
|
+
passes: for (let restarts = 0;; restarts += 1) {
|
|
539
|
+
fault = undefined;
|
|
540
|
+
gate = new Gate(deps.journal(claim));
|
|
541
|
+
if (deps.signal.aborted)
|
|
542
|
+
gate.seal(new Interrupted("its claim's signal aborted"));
|
|
543
|
+
const registry = createRegistry();
|
|
544
|
+
let models = createModels();
|
|
545
|
+
// The spec's phases said before the run's root exists (AdapterRun.phase), written in the root's creating commit.
|
|
546
|
+
const phasesBeforeRoot = [];
|
|
547
|
+
let rootMade = false;
|
|
548
|
+
harness = await Harness.open(gate.journal, {
|
|
549
|
+
models: () => models, registry, settings: { restartLimit }, onReport: () => { },
|
|
550
|
+
// A tool host's onConversation, in each agent conversation's creating commit (the spec's, once it is known: the
|
|
551
|
+
// root is created when the session opens, after the spec).
|
|
552
|
+
conversationCreated: async (tx, record) => {
|
|
553
|
+
if (!agentConversation(record))
|
|
554
|
+
return;
|
|
555
|
+
if (Number(record.id) === Number(ROOT_CONVERSATION_ID)) {
|
|
556
|
+
rootMade = true;
|
|
557
|
+
for (const data of phasesBeforeRoot.splice(0))
|
|
558
|
+
await tx.appendEntry(record.id, { kind: HOST_PHASE, data });
|
|
559
|
+
}
|
|
560
|
+
for (const write of specNow?.lifecycle?.onConversation ?? [])
|
|
561
|
+
await write(tx, Number(record.id));
|
|
562
|
+
},
|
|
563
|
+
}, context);
|
|
564
|
+
// The run's one cap, on its own sessions, built once its spec gives the cap's config (spec.runCap); its handles are
|
|
565
|
+
// made here, before the spec, so the spec's tool host binds them at its bind (a browser release's charge comes
|
|
566
|
+
// outside any call). Each session is opened at its first step: a run that makes none writes nothing for it. A
|
|
567
|
+
// handle not opened on this claim reads what the run's records held when the claim began.
|
|
568
|
+
const sessions = journalSessions(harness, context, { flush: () => deps.flush() });
|
|
569
|
+
let capBuilt;
|
|
570
|
+
const theCap = () => {
|
|
571
|
+
if (!specNow?.runCap)
|
|
572
|
+
throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
|
|
573
|
+
return (capBuilt ??= runCap({ sessions, ...specNow.runCap }));
|
|
574
|
+
};
|
|
575
|
+
const flushed = { flush: () => deps.flush() };
|
|
576
|
+
const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
|
|
577
|
+
const earlierPaid = sessionSpendOf(await sessions.read(TOOL_SESSION)).spentUsd;
|
|
578
|
+
let decisionsReady;
|
|
579
|
+
let decisionsOpen;
|
|
580
|
+
const decisionsOf = () => (decisionsOpen ??= sessions.open(DECISION_SESSION).then((w) => theCap().decisions(w, flushed)).then((d) => (decisionsReady = d)));
|
|
581
|
+
let paidReady;
|
|
582
|
+
let paidOpen;
|
|
583
|
+
const paidOf = () => (paidOpen ??= sessions.open(TOOL_SESSION).then((w) => theCap().tools(w, flushed)).then((p) => (paidReady = p)));
|
|
584
|
+
/** The pause of a paid call the cap refused (ledger.pause), set once the claim's booking is: below. */
|
|
585
|
+
let pauseFor;
|
|
586
|
+
const ledger = {
|
|
587
|
+
decisions: {
|
|
588
|
+
admit: async (request) => (await decisionsOf()).admit(request),
|
|
589
|
+
settle: async (id, settled) => (await decisionsOf()).settle(id, settled),
|
|
590
|
+
spentUsd: () => (decisionsReady ? decisionsReady.spentUsd() : earlierDecisions),
|
|
591
|
+
heldUsd: () => decisionsReady?.heldUsd() ?? 0,
|
|
592
|
+
},
|
|
593
|
+
paid: {
|
|
594
|
+
admit: async (request) => (await paidOf()).admit(request),
|
|
595
|
+
settle: async (id, usd, options) => (await paidOf()).settle(id, usd, options),
|
|
596
|
+
spentUsd: () => (paidReady ? paidReady.spentUsd() : earlierPaid),
|
|
597
|
+
heldUsd: () => paidReady?.heldUsd() ?? 0,
|
|
598
|
+
},
|
|
599
|
+
// Lazy, as main's process takes them (portModels(() => sessionPort?.(...))): a spec takes them at its build, and
|
|
600
|
+
// each request reads the session's port then, there once the session is open.
|
|
601
|
+
models: (label) => portModels(() => session?.port?.(label)),
|
|
602
|
+
pause: async (refusal) => {
|
|
603
|
+
await pauseFor?.(refusal);
|
|
604
|
+
},
|
|
605
|
+
};
|
|
606
|
+
// A phase of the host's: queued until the root exists (written in its creating commit, above), else written at once.
|
|
607
|
+
const phasing = harness;
|
|
608
|
+
const phase = (summary) => {
|
|
609
|
+
const data = { summary, at: Date.now() };
|
|
610
|
+
void (async () => {
|
|
611
|
+
if (!rootMade && !(await phasing.conversation(ROOT_CONVERSATION_ID, context)) && !rootMade) {
|
|
612
|
+
phasesBeforeRoot.push(data);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
await phasing.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data }), context);
|
|
616
|
+
})().catch((error) => console.warn(`[runner] a phase row was not written: ${said(error)}`));
|
|
617
|
+
};
|
|
618
|
+
const passGate = gate;
|
|
619
|
+
const rowSummaryOn = (kind, test, summary) => {
|
|
620
|
+
if (passGate.sealed)
|
|
621
|
+
return;
|
|
622
|
+
passGate.expect(writesEntry(kind, test), { run: { summary } }).catch(() => undefined);
|
|
623
|
+
};
|
|
624
|
+
const runOf = { harness, registry, setModels: (given) => (models = given), ledger, ...(deps.redact ? { redact: deps.redact } : {}), signal: deps.signal, phase, rowSummaryOn };
|
|
625
|
+
// The spec, its MCP claim step among it (mcpForClaim, before the session opens). A refusal there ends the run in its
|
|
626
|
+
// words with nothing sent; a claim lost during its refresh ends the loop with nothing more written. A claim the spec
|
|
627
|
+
// refuses (ClaimRefused: a handed sign-in that won't read back) ends the run in its words too.
|
|
628
|
+
let spec;
|
|
629
|
+
try {
|
|
630
|
+
spec = await specOf(claim, runOf);
|
|
631
|
+
}
|
|
632
|
+
catch (error) {
|
|
633
|
+
if (error instanceof Fenced)
|
|
634
|
+
return await interrupted("its claim was lost while its MCP credentials were made fresh");
|
|
635
|
+
if (error instanceof McpClaimRefused)
|
|
636
|
+
return await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: error.message }, []);
|
|
637
|
+
if (error instanceof ClaimRefused)
|
|
638
|
+
return await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: error.message }, []);
|
|
639
|
+
throw error;
|
|
640
|
+
}
|
|
641
|
+
mcp = spec.mcp;
|
|
642
|
+
specNow = spec;
|
|
643
|
+
releaseNow = spec.release;
|
|
644
|
+
// A mark of the run's commits through its own Harness, under its fence.
|
|
645
|
+
const opened_ = harness;
|
|
646
|
+
spec.harnessReady?.((change, ctx) => opened_.commit(change, ctx));
|
|
647
|
+
// A tool host's beforeResume: the Harness is open and nothing in it has resumed (pi schedules a task only once a
|
|
648
|
+
// submit, a wait or the session's open asks for progress, all below).
|
|
649
|
+
for (const settle of spec.lifecycle?.beforeResume ?? [])
|
|
650
|
+
await settle(harness);
|
|
651
|
+
const hooks = spec.hooks ?? quiet;
|
|
652
|
+
const writer = await sessions.open(spec.session.key);
|
|
653
|
+
// Every paid request of the run is asked of its one cap (theCap: one rule, one admission queue, the run's totals
|
|
654
|
+
// over every session of it): its model requests here, its paid tool calls (ledger.paid, under each call below and
|
|
655
|
+
// outside any) and its decisions (ledger.decisions). Its last refusal is kept: a turn it ended ends the run in its
|
|
656
|
+
// words.
|
|
657
|
+
const paid = ledger.paid;
|
|
658
|
+
let refused;
|
|
659
|
+
/** The pause a refusal for room journaled before pi heard of it (pauseAtCap), the run parked with it. */
|
|
660
|
+
let pausedAtRefusal = false;
|
|
661
|
+
/** A paid call's refusal that pauses the run (ledger.pause): the run's next request is refused in its words. */
|
|
662
|
+
let pendingPause;
|
|
663
|
+
const beforeRequest = async (request) => {
|
|
664
|
+
const answer = pendingPause ?? (await theCap().before(request));
|
|
665
|
+
if (answer && "refuse" in answer) {
|
|
666
|
+
refused = answer;
|
|
667
|
+
await pauseAt(answer);
|
|
668
|
+
}
|
|
669
|
+
return answer;
|
|
670
|
+
};
|
|
671
|
+
pauseFor = async (refusal) => {
|
|
672
|
+
pendingPause = refusal;
|
|
673
|
+
await pauseAt(refusal);
|
|
674
|
+
};
|
|
675
|
+
async function pauseAt(answer) {
|
|
676
|
+
{
|
|
677
|
+
// A refusal a raise could fix (the cap's rule, parkOf) journals its pause, the run parked, before the refusal
|
|
678
|
+
// reaches pi: pi stores the refused turn only after it, so a claim lost in between leaves the pause, and the next
|
|
679
|
+
// claim resumes the run parked (an unanswered pause), never ends it as a failed turn. One that cannot land (the
|
|
680
|
+
// journal sealed) is left to the turn's end, as before.
|
|
681
|
+
const park = spec.cap?.park(refusalOf(answer));
|
|
682
|
+
if (park?.outcome === "parked" && !pausedAtRefusal && harness && gate && !gate.sealed) {
|
|
683
|
+
const on = gate;
|
|
684
|
+
// From here a raise row waits for the next claim (raise): one taken now would answer no pause this claim
|
|
685
|
+
// resumes, and the run would be left parked with nothing to wake it.
|
|
686
|
+
pausing = true;
|
|
687
|
+
try {
|
|
688
|
+
await pauseAtCap(harness, root ?? (await harness.root(context)), on, { pending: park.pending, words: park.words });
|
|
689
|
+
pausedAtRefusal = true;
|
|
690
|
+
}
|
|
691
|
+
catch {
|
|
692
|
+
// Not landed: the turn's end parks the run, or the claim's next holder does.
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
// The rule before a side effect for every paid model request, on the path every adapter's requests take: the
|
|
698
|
+
// booking writes the request's record, then awaits request_start before the request leaves, so the flush here
|
|
699
|
+
// makes that record and everything before it durable first (each send, a retry's included).
|
|
700
|
+
const booking = await modelPortFor(writer, {
|
|
701
|
+
key: spec.session.key,
|
|
702
|
+
label: spec.session.label,
|
|
703
|
+
beforeRequest,
|
|
704
|
+
onEvent: async (event) => {
|
|
705
|
+
if (event.type === "request_start")
|
|
706
|
+
await deps.flush();
|
|
707
|
+
},
|
|
708
|
+
});
|
|
709
|
+
// A paid request an earlier claim admitted and never saw answered (its runner lost while the request was out): the
|
|
710
|
+
// provider may have billed it, so it is booked once, as cut, at its hold and bound, and told as any answered request
|
|
711
|
+
// is, before this claim sends anything (the harness runner's bookCut, main's cut booking).
|
|
712
|
+
await booking.bookCut();
|
|
713
|
+
const gateOf = preIntentGate(spec, hooks);
|
|
714
|
+
// A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
|
|
715
|
+
const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context) : undefined;
|
|
716
|
+
cliRecord = record;
|
|
717
|
+
const tools = [...spec.session.tools, ...(mcp?.tools ?? [])].map((tool) => ({
|
|
718
|
+
...tool,
|
|
719
|
+
// The rule before a side effect, on the host-tool path every adapter's calls take: after the call's intent, a
|
|
720
|
+
// flush unless the tool is replay-safe, the call, then the beforeResult point. A throw there is the kernel's own
|
|
721
|
+
// fault: the journal is sealed before the harness's result commit, so the Session fails with the call before
|
|
722
|
+
// its result, and the loop restarts it. A CLI's call reaches here only once the gate allowed it (its tool
|
|
723
|
+
// bridge asks first), so its record's start is written here, before the flush and the call, and its end after.
|
|
724
|
+
call: async (args, toolContext) => {
|
|
725
|
+
// A call its CLI issues again under an id the record already ended (after the CLI's own resume) is answered
|
|
726
|
+
// from that end, never run again.
|
|
727
|
+
const ended = record?.endOf(toolContext.callId);
|
|
728
|
+
if (ended)
|
|
729
|
+
return endedAnswer(tool.name, ended);
|
|
730
|
+
if (record)
|
|
731
|
+
await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe");
|
|
732
|
+
try {
|
|
733
|
+
const answer = await sideEffect({
|
|
734
|
+
replaySafe: tool.replay === "safe",
|
|
735
|
+
flush: () => deps.flush(),
|
|
736
|
+
// Its paid requests booked under this call, on the run's one ledger (paid-calls.ts bookedIn, Ledger.paid); one
|
|
737
|
+
// refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
|
|
738
|
+
route: () => bookedIn({ call: toolContext.callId, record: async () => { }, paid, pause: ledger.pause }, () => tool.call(args, toolContext)),
|
|
739
|
+
beforeResult: async (answer) => {
|
|
740
|
+
const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
|
|
741
|
+
try {
|
|
742
|
+
await hooks.beforeResult(call, answer.text);
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
fault = new KernelFault(call, error);
|
|
746
|
+
gate.seal(fault);
|
|
747
|
+
throw fault;
|
|
748
|
+
}
|
|
749
|
+
},
|
|
750
|
+
});
|
|
751
|
+
if (record)
|
|
752
|
+
await record.end(toolContext.callId, answer.isError ? "failed" : "done", answer.text);
|
|
753
|
+
return answer;
|
|
754
|
+
}
|
|
755
|
+
catch (error) {
|
|
756
|
+
// A call its stop or its signal cut off ends interrupted; a fault leaves its end to the next open (the
|
|
757
|
+
// journal is sealed now), which ends it interrupted.
|
|
758
|
+
if (record && !(error instanceof KernelFault) && !gate.sealed)
|
|
759
|
+
await record.end(toolContext.callId, "interrupted").catch(() => undefined);
|
|
760
|
+
throw error;
|
|
761
|
+
}
|
|
762
|
+
},
|
|
763
|
+
}));
|
|
764
|
+
// The session's model port, counting what it admitted and has not booked yet (a stop's booking comes once the
|
|
765
|
+
// session's proxy sees its upstream end, which can be after pi went idle).
|
|
766
|
+
const port = booking.models;
|
|
767
|
+
unbooked = 0;
|
|
768
|
+
const counted = {
|
|
769
|
+
beforeRequest: async (request) => {
|
|
770
|
+
// A command row since the MCP credentials were made fresh: made fresh again before this request.
|
|
771
|
+
if (mcpStale && mcp) {
|
|
772
|
+
mcpStale = false;
|
|
773
|
+
await mcp.fresh();
|
|
774
|
+
}
|
|
775
|
+
const ticket = await port.beforeRequest(request);
|
|
776
|
+
unbooked += 1;
|
|
777
|
+
return ticket;
|
|
778
|
+
},
|
|
779
|
+
afterRequest: async (...args) => {
|
|
780
|
+
try {
|
|
781
|
+
await hooks.beforeBooking?.();
|
|
782
|
+
await port.afterRequest(...args);
|
|
783
|
+
}
|
|
784
|
+
finally {
|
|
785
|
+
unbooked = Math.max(0, unbooked - 1);
|
|
786
|
+
if (unbooked === 0)
|
|
787
|
+
for (const wake of bookedAll.splice(0))
|
|
788
|
+
wake();
|
|
789
|
+
}
|
|
790
|
+
},
|
|
791
|
+
...(port.responded ? { responded: port.responded.bind(port) } : {}),
|
|
792
|
+
...(port.note ? { note: port.note.bind(port) } : {}),
|
|
793
|
+
};
|
|
794
|
+
// What the request that just answered cost, once the session's requests are booked (bookingOfAnswer): its own
|
|
795
|
+
// booking's figure, null when unknown; a side request's is given and never read. A refused request's record is its $0.
|
|
796
|
+
// The bookings already given to an answer: every one the session holds when it opens (an earlier claim's), then each
|
|
797
|
+
// this claim gives.
|
|
798
|
+
const given = new Set(turnsOf(await writer.read().catch(() => [])));
|
|
799
|
+
const bookedCost = async () => {
|
|
800
|
+
await bookingsSettled();
|
|
801
|
+
const booking = bookingOfAnswer(await writer.read().catch(() => []), given);
|
|
802
|
+
for (const turn of booking.turns)
|
|
803
|
+
given.add(turn);
|
|
804
|
+
return booking.usd;
|
|
805
|
+
};
|
|
806
|
+
const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: gateOf, bookedCost };
|
|
807
|
+
// The MCP tools: pi's own (host tools, through the gate above); for a harness with its own MCP client, the session's
|
|
808
|
+
// MCP its adapter mounts on its proxy, each call asking the gate first (an ask parks the run, nothing sent).
|
|
809
|
+
const mcpNames = new Set(mcp?.tools.map((tool) => tool.name));
|
|
810
|
+
const ownClient = mcp !== undefined && spec.adapter.capabilities().mcpClient !== undefined;
|
|
811
|
+
const sessionMcp = ownClient
|
|
812
|
+
? mcp.session(new Map(tools.filter((tool) => mcpNames.has(tool.name)).map((tool) => [tool.name, tool])), async (call) => {
|
|
813
|
+
const answer = await gateOf(call, context);
|
|
814
|
+
return answer === "allow" ? undefined : "deny" in answer ? { refused: answer.deny } : { parked: true };
|
|
815
|
+
})
|
|
816
|
+
: undefined;
|
|
817
|
+
session = await spec.adapter.open({ ...spec.session, tools: ownClient ? tools.filter((tool) => !mcpNames.has(tool.name)) : tools, ...(sessionMcp ? { mcp: sessionMcp } : {}) }, io);
|
|
818
|
+
root = await harness.root(context);
|
|
819
|
+
// The run's desktop or phone: its hold's changes go to the run's journal, through this pass's Harness (under its
|
|
820
|
+
// fence), and the computer shows up, the agent driving.
|
|
821
|
+
computerNow?.detach();
|
|
822
|
+
computerNow = undefined;
|
|
823
|
+
if (spec.computer) {
|
|
824
|
+
const [journalOf, rootOf] = [harness, root];
|
|
825
|
+
computerNow = journalHold(claim.runId, spec.computer, (entries) => journalOf.commit(async (tx) => {
|
|
826
|
+
for (const entry of entries)
|
|
827
|
+
await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
|
|
828
|
+
}, context), now);
|
|
829
|
+
await computerNow.up();
|
|
830
|
+
}
|
|
831
|
+
// A run brought back from a park: the raises its claim has are taken together, once its delivery is done. So is a
|
|
832
|
+
// run whose journal still holds an unanswered budget pause, whatever its row said at the claim: a resumed claim lost
|
|
833
|
+
// before its raise entry landed leaves the run running, its pause unanswered and its raises untaken.
|
|
834
|
+
if (restarts === 0 && (claim.from === "parked" || (spec.cap?.checkRaise !== undefined && (await raiseStateOf()).pause !== undefined))) {
|
|
835
|
+
raising.resuming = true;
|
|
836
|
+
raising.state ??= await raiseStateOf();
|
|
837
|
+
}
|
|
838
|
+
// Taken over from a runner whose lease ran out mid-run: said on the run's timeline once, at this claim's first pass.
|
|
839
|
+
if (restarts === 0 && claim.lost)
|
|
840
|
+
await noteTakenOver(harness, root, claim.lost.runner);
|
|
841
|
+
// Reopened by a person's follow-up (runs.reopen): its journal holds an end and its session opens idle. Set before the
|
|
842
|
+
// session is ready, so the follow-up's steer, handed over once it is, is sent as this claim's turn.
|
|
843
|
+
if (restarts === 0 && session.state === "idle" && (await entriesOf(gate.journal, root.id, context)).some((entry) => entry.kind === KINDS.end))
|
|
844
|
+
reopen = {};
|
|
845
|
+
opened();
|
|
846
|
+
await reportHeld(harness, root.id);
|
|
847
|
+
if (restarts > restartLimit + 1) {
|
|
848
|
+
return await writeEnd(harness, root, gate, { state: "failed", summary: `the kernel faulted on every restart (${restarts} restarts)` }, [], await cutRows(claim, spec, "faulted"));
|
|
849
|
+
}
|
|
850
|
+
let followedUp = false;
|
|
851
|
+
if (raising.resuming) {
|
|
852
|
+
// Every row that woke it has reached its command() first (deps.delivered), so raises sent together are taken
|
|
853
|
+
// together: one raise entry, and the run resumes once, at the latest cap, with one follow-up in the server's
|
|
854
|
+
// words (the kernel cap's takeRaises and followUpOf). Parked at its cap with no raise that resumes it, it parks
|
|
855
|
+
// again on the same budget; its next refusal (a raise short of the need) parks it anew through the cap's rule.
|
|
856
|
+
await deps.delivered;
|
|
857
|
+
raising.resuming = false;
|
|
858
|
+
const paused = raising.budget;
|
|
859
|
+
const resumes = raising.resumes;
|
|
860
|
+
await takeRaises();
|
|
861
|
+
if (paused) {
|
|
862
|
+
if (!resumes || raising.capUsd === undefined || !spec.cap?.followUpOf)
|
|
863
|
+
return await parkAtCap(harness, root, gate, paused);
|
|
864
|
+
await session.send(spec.cap.followUpOf(raising.capUsd).text, { id: `agentrun:raise:${raising.state?.lastRaise?.pause ?? "follow-up"}` });
|
|
865
|
+
followedUp = true;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
if (!followedUp && spec.cap?.followUpOf) {
|
|
869
|
+
// A raise that resumed its pause, whose follow-up this claim did not send: a runner lost after the raise entry's
|
|
870
|
+
// commit, before the follow-up's submission or with its turn still open. Sent under its own id, so pi answers
|
|
871
|
+
// one already placed from its submission and never places it twice; and the turn this claim runs, whose end is
|
|
872
|
+
// the run's, is the follow-up's, never the first input's.
|
|
873
|
+
const state = await raiseStateOf();
|
|
874
|
+
if (state.pause === undefined && state.lastRaise?.pause !== undefined) {
|
|
875
|
+
await session.send(spec.cap.followUpOf(state.lastRaise.to).text, { id: `agentrun:raise:${state.lastRaise.pause}` });
|
|
876
|
+
followedUp = true;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
if (!followedUp && ownClient) {
|
|
880
|
+
// MCP calls a harness with its own client parked through the door: each answered once (an allow runs it, a deny
|
|
881
|
+
// is told), then the session goes on with main's resume message for them, written on the record before it is
|
|
882
|
+
// sent (as the person's input is). A call still waiting parks the run again.
|
|
883
|
+
const wrapped = new Map(tools.map((tool) => [tool.name, tool]));
|
|
884
|
+
const follow = await parkedFollowUp(mcp, {
|
|
885
|
+
entries: await entriesOf(gate.journal, root.id, context),
|
|
886
|
+
answer: (call, price) => answerOf(call, price),
|
|
887
|
+
deniedNow: async (call) => {
|
|
888
|
+
// The gate is Promise-capable on purpose (run-cap's and the approvals' gates may look things up), so await it.
|
|
889
|
+
const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
|
|
890
|
+
return now === "deny" ? setToDenyText(call.tool) : typeof now === "object" ? now.deny : undefined;
|
|
891
|
+
},
|
|
892
|
+
run: (call) => wrapped.get(mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool).name).call(call.args, { callId: call.callId, signal: deps.signal }),
|
|
893
|
+
});
|
|
894
|
+
if (follow === "park") {
|
|
895
|
+
gate.seal(new Parked());
|
|
896
|
+
return { state: "parked" };
|
|
897
|
+
}
|
|
898
|
+
if (follow) {
|
|
899
|
+
const theRoot = root;
|
|
900
|
+
await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" } } }), context);
|
|
901
|
+
await session.send(follow.text, { id: `agentrun:approval:${follow.callIds[0]}` });
|
|
902
|
+
followedUp = true;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
if (reopen) {
|
|
906
|
+
// Every row the runner read for this claim has reached its command() (deps.delivered): the follow-up's steer, sent
|
|
907
|
+
// by steer() as a turn, is the turn this claim runs. With none (a claim after that turn's answer), it ends again.
|
|
908
|
+
await deps.delivered;
|
|
909
|
+
// A steer handed over waits on the session's readiness (resolved above) before it sends: one turn of the event loop
|
|
910
|
+
// lets it get there.
|
|
911
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
912
|
+
const sent = reopen.sent;
|
|
913
|
+
reopen = undefined;
|
|
914
|
+
if (sent) {
|
|
915
|
+
await sent.catch(() => undefined);
|
|
916
|
+
followedUp = true;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
// A claim that starts a turn (the input, a recovery, a follow-up) waits for that turn's end: state is the session as
|
|
920
|
+
// open found it, and a CLI adapter reads idle once its turn is sent, so state read after a send says nothing.
|
|
921
|
+
const placed = followedUp || session.state !== "idle";
|
|
922
|
+
if (followedUp) {
|
|
923
|
+
// The follow-up is the turn this claim runs.
|
|
924
|
+
}
|
|
925
|
+
else if (session.state === "new") {
|
|
926
|
+
// A trigger's first input is its origin's (the launch's), never written as the person's.
|
|
927
|
+
if (spec.inputOrigin)
|
|
928
|
+
await record?.input(spec.input, spec.inputOrigin);
|
|
929
|
+
else
|
|
930
|
+
await record?.person(spec.input);
|
|
931
|
+
await session.send(spec.input, spec.inputOrigin ? { origin: spec.inputOrigin } : undefined);
|
|
932
|
+
}
|
|
933
|
+
else if (session.state === "open_turn")
|
|
934
|
+
await session.recover();
|
|
935
|
+
// The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
|
|
936
|
+
// its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold.
|
|
937
|
+
let turn = placed ? session.turnEnd() : idleTurnOf(harness, root);
|
|
938
|
+
// Set on every way out of the loop below but parkOn's, which returns before it is read.
|
|
939
|
+
let data;
|
|
940
|
+
let failedWith;
|
|
941
|
+
/** The ask_person call the run parks on, its turn ended on it and no wait in the claim holding (parkOnAsk). */
|
|
942
|
+
let parkOn;
|
|
943
|
+
/** The ask_person call the run waits on in its claim, while it does. */
|
|
944
|
+
let waitingOn;
|
|
945
|
+
for (;;) {
|
|
946
|
+
const end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed")]);
|
|
947
|
+
if (end === "parked") {
|
|
948
|
+
// Let the tool host go first (a browser's release, booked under the live claim), then seal.
|
|
949
|
+
await releaseHost(harness);
|
|
950
|
+
gate.seal(new Parked());
|
|
951
|
+
return { state: "parked" };
|
|
952
|
+
}
|
|
953
|
+
if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
|
|
954
|
+
await closeSession();
|
|
955
|
+
continue passes;
|
|
956
|
+
}
|
|
957
|
+
if (end === "closed" || (stopReason && stopReason.kind !== "command"))
|
|
958
|
+
return await interrupted(stopReason?.kind ?? "the Session closed");
|
|
959
|
+
if (end === "stop" && stopReason?.kind === "command") {
|
|
960
|
+
// Bounded, the interrupt included: a tool call that ignores its abort keeps the turn from settling, and the claim
|
|
961
|
+
// is renewed meanwhile. Past the bound the run is failed in words, the stop row taken in that end's commit.
|
|
962
|
+
const settleMs = spec.stopSettleMs ?? STOP_SETTLE_MS;
|
|
963
|
+
const settling = (async () => {
|
|
964
|
+
await session.interrupt().catch(() => { });
|
|
965
|
+
await harness.waitForIdle(context).catch(() => { });
|
|
966
|
+
return true;
|
|
967
|
+
})();
|
|
968
|
+
let timer;
|
|
969
|
+
const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
|
|
970
|
+
clearTimeout(timer);
|
|
971
|
+
// A cancel ends the same way, in its own words (main's "cancelled"); the bound is the same.
|
|
972
|
+
const words = endedBy(stopReason.cancel);
|
|
973
|
+
const cut = await cutRows(claim, spec, "stopped");
|
|
974
|
+
if (!settled)
|
|
975
|
+
return await writeEnd(harness, root, gate, { state: "failed", summary: `${words}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
|
|
976
|
+
return await writeEnd(harness, root, gate, { state: "stopped", summary: words }, [stopReason.commandId], cut);
|
|
977
|
+
}
|
|
978
|
+
// The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
|
|
979
|
+
// it kept went): the run parks on its question, as it does with nothing open.
|
|
980
|
+
if (end === "lapsed") {
|
|
981
|
+
parkOn = waitingOn;
|
|
982
|
+
break;
|
|
983
|
+
}
|
|
984
|
+
const outcome = (await turn);
|
|
985
|
+
// What the model said last, on the record before the run's end.
|
|
986
|
+
await record?.flushText();
|
|
987
|
+
await harness.waitForIdle(context);
|
|
988
|
+
const settledEntries = await entriesOf(gate.journal, root.id, context);
|
|
989
|
+
const cutOff = restartLimited(settledEntries);
|
|
990
|
+
if (cutOff)
|
|
991
|
+
data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
|
|
992
|
+
else if (outcome.status !== "completed" && refused) {
|
|
993
|
+
// A turn the host's check refused: what that does to the run is the cap's rule (parkOf), as on main. A refusal a
|
|
994
|
+
// raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
|
|
995
|
+
// check's own words, never as a run with no answer.
|
|
996
|
+
const park = spec.cap?.park(refusalOf(refused));
|
|
997
|
+
if (park?.outcome === "parked" && pausedAtRefusal) {
|
|
998
|
+
// Its pause and the run parked landed before pi heard of the refusal.
|
|
999
|
+
await releaseHost(harness);
|
|
1000
|
+
gate.seal(new Parked());
|
|
1001
|
+
return { state: "parked" };
|
|
1002
|
+
}
|
|
1003
|
+
if (park?.outcome === "parked")
|
|
1004
|
+
return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
|
|
1005
|
+
data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
|
|
1006
|
+
}
|
|
1007
|
+
else if (outcome.status !== "completed") {
|
|
1008
|
+
// A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
|
|
1009
|
+
// the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
|
|
1010
|
+
// the loop's own words.
|
|
1011
|
+
const said = outcome.error?.trim();
|
|
1012
|
+
data = { state: "failed", summary: said ? cutWhole(said, TURN_ERROR_MAX) : `the run gave no answer (${outcome.status})` };
|
|
1013
|
+
// A CLI's turn (record "loop"; pi journals its own): its error is also main's error row, pi's error answer in the
|
|
1014
|
+
// end's commit, cut of every secret the runner holds, so the timeline shows it as an error row with no key in it.
|
|
1015
|
+
if (said && spec.record === "loop")
|
|
1016
|
+
failedWith = deps.redact ? deps.redact(said) : said;
|
|
1017
|
+
}
|
|
1018
|
+
else if (endedOnTurnEndingTool(settledEntries) !== undefined) {
|
|
1019
|
+
// The turn ended on a tool that waits on the person (ask_person ended its turn). With something a tool host keeps
|
|
1020
|
+
// open for them meanwhile (the browser's session, its live view and its page), the run waits for their answer in
|
|
1021
|
+
// its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
|
|
1022
|
+
// its next turn, on the same session. With nothing open, it parks (parkOnAsk).
|
|
1023
|
+
const callId = endedOnTurnEndingTool(settledEntries);
|
|
1024
|
+
const waited = await waitInClaim(harness, callId);
|
|
1025
|
+
if (waited) {
|
|
1026
|
+
turn = waited.next;
|
|
1027
|
+
waitingOn = callId;
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
parkOn = callId;
|
|
1031
|
+
}
|
|
1032
|
+
else {
|
|
1033
|
+
// An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
|
|
1034
|
+
// the direct loop's rule: the words are loop-contract's cutAtLimit).
|
|
1035
|
+
const cut = cutLast(settledEntries);
|
|
1036
|
+
data = cut ? { state: "failed", summary: cut } : { state: "ended" };
|
|
1037
|
+
}
|
|
1038
|
+
break;
|
|
1039
|
+
}
|
|
1040
|
+
if (parkOn !== undefined)
|
|
1041
|
+
return await parkOnAsk(harness, root, gate, parkOn);
|
|
1042
|
+
// The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
|
|
1043
|
+
// writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
|
|
1044
|
+
const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
|
|
1045
|
+
if (step.kind === "stopped")
|
|
1046
|
+
return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason?.kind === "command" ? stopReason.cancel : undefined) }, [step.commandId], await cutRows(claim, spec, "stopped-looking"));
|
|
1047
|
+
if (step.kind === "interrupted")
|
|
1048
|
+
return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
|
|
1049
|
+
return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
catch (error) {
|
|
1053
|
+
if (gate?.sealed || deps.signal.aborted)
|
|
1054
|
+
return await interrupted("its claim's signal aborted");
|
|
1055
|
+
// A failure with no end written yet. While the journal still takes a commit, the run's end is written with why (the
|
|
1056
|
+
// run patch in that commit), so the journal and the live view read it failed too. A parked run brought back is never
|
|
1057
|
+
// failed by its resume: thrown, it stays parked and is tried again after a backoff, as is any failure whose end could
|
|
1058
|
+
// not be written (pi's Harness could not open): the runner stores that one failed with why. Returning "failed" with
|
|
1059
|
+
// no end would leave it running, released and claimed again at once.
|
|
1060
|
+
if (claim.from !== "parked" && harness && root && gate && !gate.sealed) {
|
|
1061
|
+
// Why, cut of every secret the runner holds (said): it is stored in the end and the row.
|
|
1062
|
+
const ended = await writeEnd(harness, root, gate, { state: "failed", summary: said(error) }, [], specNow ? await cutRows(claim, specNow, "faulted") : []).catch(() => undefined);
|
|
1063
|
+
if (ended)
|
|
1064
|
+
return ended;
|
|
1065
|
+
}
|
|
1066
|
+
throw error;
|
|
1067
|
+
}
|
|
1068
|
+
finally {
|
|
1069
|
+
deps.signal.removeEventListener("abort", signalAbort);
|
|
1070
|
+
held?.detach();
|
|
1071
|
+
computerNow?.detach();
|
|
1072
|
+
computerNow = undefined;
|
|
1073
|
+
deps.live?.(() => undefined);
|
|
1074
|
+
// A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
|
|
1075
|
+
// A restart within the claim is no release. What it writes after a lost claim is refused by the fence, as any write.
|
|
1076
|
+
await releaseHost(harness);
|
|
1077
|
+
await closeSession();
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
/** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park). */
|
|
1081
|
+
function preIntentGate(spec, hooks) {
|
|
1082
|
+
return async (call, _hookContext) => {
|
|
1083
|
+
// An MCP tool is asked about by its catalog name (`mcp:<server>/<tool>`), as its settings and its card name it.
|
|
1084
|
+
const tool = mcp?.catalogOf(call.tool) ?? call.tool;
|
|
1085
|
+
const kernelCall = { callId: call.callId, tool: tool, args: call.args };
|
|
1086
|
+
// The end-of-run turn's notes are kept only from its answer: a write there is refused before its intent.
|
|
1087
|
+
if (reflecting && WRITES.has(call.tool) && underLearning(spec.workRoot, call.args))
|
|
1088
|
+
return { deny: REFLECT_NOTE_ONLY };
|
|
1089
|
+
await hooks.beforeIntent(kernelCall);
|
|
1090
|
+
const decision = (await spec.gate?.(kernelCall)) ?? "allow";
|
|
1091
|
+
if (typeof decision === "object")
|
|
1092
|
+
return { deny: decision.deny };
|
|
1093
|
+
// Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
|
|
1094
|
+
// an MCP call by its catalog name (tool) either way, never pi's wire name, and so are its call and its price.
|
|
1095
|
+
const asked = spec.gate?.askedAs?.(tool) ?? tool;
|
|
1096
|
+
// Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
|
|
1097
|
+
if (decision === "deny")
|
|
1098
|
+
return { deny: setToDenyText(asked) };
|
|
1099
|
+
if (decision === "allow")
|
|
1100
|
+
return "allow";
|
|
1101
|
+
const answer = await answerOf({ ...call, tool }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
|
|
1102
|
+
if (answer === "park")
|
|
1103
|
+
return { park: true };
|
|
1104
|
+
return answer.approved ? "allow" : { deny: deniedText(asked, answer.note) };
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
/** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
|
|
1108
|
+
* park (the ask entry with the run parked, in one commit). The ask is main's approval card: the call's input, when it
|
|
1109
|
+
* was asked and its `price`; asked again on a resume, it is the same request. */
|
|
1110
|
+
async function answerOf(call, price, asked = call.tool) {
|
|
1111
|
+
const conversation = await harness.root(context);
|
|
1112
|
+
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
1113
|
+
const known = findData(entries, KINDS.answer, (data) => data.callId === call.callId);
|
|
1114
|
+
if (known)
|
|
1115
|
+
return known;
|
|
1116
|
+
const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
|
|
1117
|
+
// The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
|
|
1118
|
+
// run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
|
|
1119
|
+
const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price };
|
|
1120
|
+
// Commits the root's entry of `kind`, staging `staged` with it. False when the journal is sealed first (another call
|
|
1121
|
+
// of the round parked the run): nothing landed, and the expectation's failure is no one's to wait on.
|
|
1122
|
+
const entryLands = async (kind, data, staged) => {
|
|
1123
|
+
const landed = gate.expect(writesEntry(kind, (entry) => entry.callId === data.callId), staged);
|
|
1124
|
+
// A seal while the commit is in flight fails it before it is awaited: handled here, read by the await below.
|
|
1125
|
+
landed.catch(() => undefined);
|
|
1126
|
+
try {
|
|
1127
|
+
await harness.commit((tx) => tx.appendEntry(conversation.id, { kind, data: data }), context);
|
|
1128
|
+
await landed;
|
|
1129
|
+
return true;
|
|
1130
|
+
}
|
|
1131
|
+
catch (error) {
|
|
1132
|
+
if (gate.sealed)
|
|
1133
|
+
return false;
|
|
1134
|
+
throw error;
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
if (first === undefined) {
|
|
1138
|
+
// Asked and parked; or held as the parked call is, when another call of the round parked the run first.
|
|
1139
|
+
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
|
|
1140
|
+
parked();
|
|
1141
|
+
return "park";
|
|
1142
|
+
}
|
|
1143
|
+
for (;;) {
|
|
1144
|
+
const row = inbox.find((command) => (command.kind === "approve" || command.kind === "deny") && approvalOf(command) === call.callId);
|
|
1145
|
+
if (row) {
|
|
1146
|
+
inbox.splice(inbox.indexOf(row), 1);
|
|
1147
|
+
const approved = row.kind === "approve";
|
|
1148
|
+
const data = { callId: call.callId, approved, decision: approved ? "allow" : "deny", answeredAt: isoNow(), ...noteOf(row), ...(row.body?.by === "message" && !approved ? { by: "message" } : {}) };
|
|
1149
|
+
if (!(await entryLands(KINDS.answer, data, { take: [row.id] })))
|
|
1150
|
+
return "park";
|
|
1151
|
+
return data;
|
|
1152
|
+
}
|
|
1153
|
+
if (stopReason)
|
|
1154
|
+
return "park";
|
|
1155
|
+
// No answer for this call came with the claim's first delivery (a steer woke the run, or the row that woke it named
|
|
1156
|
+
// no waiting call and was refused): the call is asked again and the run parks on it, so it never waits here
|
|
1157
|
+
// holding the claim while it reads running.
|
|
1158
|
+
if (delivered || refusals > 0) {
|
|
1159
|
+
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
|
|
1160
|
+
parked();
|
|
1161
|
+
return "park";
|
|
1162
|
+
}
|
|
1163
|
+
await new Promise((resolve) => (wakeInbox = resolve));
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
/** Whether a call of this run waits for the answer `approval` names: asked, and not answered yet. */
|
|
1167
|
+
async function waitsFor(approval) {
|
|
1168
|
+
if (approval === undefined)
|
|
1169
|
+
return false;
|
|
1170
|
+
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
1171
|
+
if (!gate || !harness)
|
|
1172
|
+
return false;
|
|
1173
|
+
const conversation = await harness.root(context);
|
|
1174
|
+
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
1175
|
+
const asked = findData(entries, KINDS.ask, (data) => data.callId === approval) !== undefined;
|
|
1176
|
+
return asked && findData(entries, KINDS.answer, (data) => data.callId === approval) === undefined;
|
|
1177
|
+
}
|
|
1178
|
+
async function reportHeld(session, conversationId) {
|
|
1179
|
+
held?.detach();
|
|
1180
|
+
held = undefined;
|
|
1181
|
+
if (!deps.live)
|
|
1182
|
+
return;
|
|
1183
|
+
const report = heldReporter(deps.live);
|
|
1184
|
+
const observation = (await session.observeDoc(LiveDoc, conversationId, {
|
|
1185
|
+
advance: (call) => {
|
|
1186
|
+
try {
|
|
1187
|
+
if (call.kind === "value")
|
|
1188
|
+
report(call.retired ? undefined : call.value);
|
|
1189
|
+
}
|
|
1190
|
+
catch {
|
|
1191
|
+
deps.live?.(() => undefined);
|
|
1192
|
+
}
|
|
1193
|
+
},
|
|
1194
|
+
end: () => undefined,
|
|
1195
|
+
}, context));
|
|
1196
|
+
if (!observation)
|
|
1197
|
+
return;
|
|
1198
|
+
held = observation;
|
|
1199
|
+
report(observation.value);
|
|
1200
|
+
}
|
|
1201
|
+
/** An interrupted end (a lost claim, a shutdown, the Session closed): the journal sealed first, so nothing written after
|
|
1202
|
+
* reaches the store, then the adapter's interrupt() (where a CLI adapter stops its process), bounded; the session's
|
|
1203
|
+
* close() follows in run()'s finally. */
|
|
1204
|
+
async function interrupted(reason) {
|
|
1205
|
+
gate?.seal(new Interrupted(reason));
|
|
1206
|
+
if (session) {
|
|
1207
|
+
let timer;
|
|
1208
|
+
await Promise.race([session.interrupt().catch(() => { }), new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
|
|
1209
|
+
clearTimeout(timer);
|
|
1210
|
+
}
|
|
1211
|
+
return { state: "interrupted" };
|
|
1212
|
+
}
|
|
1213
|
+
/** The run parks on its question to the person (ask_person ended its turn), nothing open for them meanwhile: a
|
|
1214
|
+
* KINDS.personAsked entry naming that call carries the run patch to "parked" (as the cap park commits its pause on a
|
|
1215
|
+
* budget entry), so the runner leaves it for the person's message and never claims it again with nothing to answer; the
|
|
1216
|
+
* reader passes the entry over, and input_required with its question is the view's to read (the same
|
|
1217
|
+
* endedOnTurnEndingTool rule, over the ask_person call pi wrote). First write wins, so a second claim finding it does
|
|
1218
|
+
* not write it again. Then the cap park's move: the claim released, nothing more booked. The person's reply arrives as
|
|
1219
|
+
* the run's next user message and resumes it on the next claim, as on main: the ask_person tool result stays what pi
|
|
1220
|
+
* wrote, so nothing is re-asked or re-billed. The summary is plain words, never the question. */
|
|
1221
|
+
async function parkOnAsk(on, conversation, theGate, callId) {
|
|
1222
|
+
const parkedAt = theGate.expect(writesEntry(KINDS.personAsked, (entry) => entry.callId === callId), { run: { state: "parked", summary: ASK_PERSON_WAITING } });
|
|
1223
|
+
parkedAt.catch(() => undefined);
|
|
1224
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId } }), context);
|
|
1225
|
+
await parkedAt;
|
|
1226
|
+
await releaseHost(on);
|
|
1227
|
+
theGate.seal(new Parked());
|
|
1228
|
+
return { state: "parked" };
|
|
1229
|
+
}
|
|
1230
|
+
/** The row's waiting summary of a wait in the claim, gone: its answer came by a way whose commit did not clear it. */
|
|
1231
|
+
async function notWaiting(on, theGate, conversation, callId) {
|
|
1232
|
+
const cleared = theGate.expect(writesEntry(KINDS.personAsked, (data) => data.callId === callId && data.answered === true), { run: { summary: null } });
|
|
1233
|
+
cleared.catch(() => undefined);
|
|
1234
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId, inClaim: true, answered: true } }), context);
|
|
1235
|
+
await cleared;
|
|
1236
|
+
}
|
|
1237
|
+
/** How the claim's turn ended when its session opened idle: a person's message the run took as a turn of its own (a
|
|
1238
|
+
* wait's answer, a reopened run's follow-up, a parked question's answer: request ids commandRequest makes) that an
|
|
1239
|
+
* earlier claim placed, whose turn this claim resumed, ends as that submission ended, never read as completed when it
|
|
1240
|
+
* failed; with none such newest, completed, as before. */
|
|
1241
|
+
async function idleTurnOf(on, conversation) {
|
|
1242
|
+
const page = await gate.journal.scanSubmissions({ conversationId: conversation.id, order: "descending" }, 10, undefined, context);
|
|
1243
|
+
const last = page.items.find((submission) => submission.type === "input");
|
|
1244
|
+
if (!last?.requestId?.startsWith(COMMAND_REQUEST_PREFIX))
|
|
1245
|
+
return { status: "completed" };
|
|
1246
|
+
return turnOfRequest(on, conversation, last.requestId);
|
|
1247
|
+
}
|
|
1248
|
+
/** How the turn of the root's submission `requestId` ended (a steer of the idle session, which no session tracks). */
|
|
1249
|
+
async function turnOfRequest(on, conversation, requestId) {
|
|
1250
|
+
const found = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
1251
|
+
if (!found) {
|
|
1252
|
+
await on.waitForIdle(context);
|
|
1253
|
+
return { status: "completed" };
|
|
1254
|
+
}
|
|
1255
|
+
const submission = await on.submission(found.id, context);
|
|
1256
|
+
const record = submission ? await submission.wait(context) : undefined;
|
|
1257
|
+
return { status: !record || record.status === "done" ? "completed" : "failed" };
|
|
1258
|
+
}
|
|
1259
|
+
/** The run waits in its claim on the person's answer to its question (ask_person `callId` ended its turn) when a tool
|
|
1260
|
+
* host keeps something open for them meanwhile (HostLifecycle.personWait: the browser's session, whose live view the
|
|
1261
|
+
* person may watch or take over, and whose page the agent goes on from), as the browser's hand-over waits in the claim.
|
|
1262
|
+
* Each host's hold holds the person's time under the run's cap. The run reads input_required, waiting on the question,
|
|
1263
|
+
* from its journal as a parked one does; its claim, its session and its viewer stay. The person's message is sent as the
|
|
1264
|
+
* claim's next turn (steer, through `reopen`), the holds dropped as it is placed: the turn's end is what this gives. It
|
|
1265
|
+
* gives "lapsed" when a hold can no longer stand before the answer is placed (the cap refused more of the person's time,
|
|
1266
|
+
* or the session went), and the run parks on its question. Undefined when no host holds anything: the run parks. */
|
|
1267
|
+
async function waitInClaim(on, callId) {
|
|
1268
|
+
const holders = specNow?.lifecycle?.personWait ?? [];
|
|
1269
|
+
if (!holders.length || !session || !gate || gate.sealed || !root)
|
|
1270
|
+
return undefined;
|
|
1271
|
+
await options.beforePersonWait?.();
|
|
1272
|
+
// Set before anything else: an answer sent from here is the claim's next turn, never a steer into no turn.
|
|
1273
|
+
const [theSession, theGate, conversation] = [session, gate, root];
|
|
1274
|
+
const mine = {};
|
|
1275
|
+
let placing = new Promise((resolve) => (mine.placed = resolve));
|
|
1276
|
+
reopen = mine;
|
|
1277
|
+
waitTurn = mine;
|
|
1278
|
+
// The wait as the journal has it: an earlier claim's (its start, so its bound never restarts), or none.
|
|
1279
|
+
const entries = await entriesOf(theGate.journal, conversation.id, context);
|
|
1280
|
+
const marked = findData(entries, KINDS.personAsked, (data) => data.callId === callId && data.inClaim === true && typeof data.at === "number");
|
|
1281
|
+
const answeredMark = findData(entries, KINDS.personAsked, (data) => data.callId === callId && data.answered === true);
|
|
1282
|
+
const showing = marked !== undefined && answeredMark === undefined;
|
|
1283
|
+
// The answer already came, between the question's turn end and here, placed as a steer of the idle session (steer):
|
|
1284
|
+
// its turn is the next, at once; the row's waiting summary goes.
|
|
1285
|
+
const early = idleSteer;
|
|
1286
|
+
idleSteer = undefined;
|
|
1287
|
+
if (early && (await early.placed)) {
|
|
1288
|
+
endWait(mine);
|
|
1289
|
+
if (showing)
|
|
1290
|
+
await notWaiting(on, theGate, conversation, callId);
|
|
1291
|
+
return { next: turnOfRequest(on, conversation, early.requestId) };
|
|
1292
|
+
}
|
|
1293
|
+
const since = marked ? marked.at : now();
|
|
1294
|
+
for (const holder of holders) {
|
|
1295
|
+
const hold = await Promise.resolve().then(() => holder(on, callId, since)).catch((error) => {
|
|
1296
|
+
console.warn(`[runner] a tool host's person-wait failed: ${said(error)}`);
|
|
1297
|
+
return undefined;
|
|
1298
|
+
});
|
|
1299
|
+
if (hold)
|
|
1300
|
+
waitHolds.push(hold);
|
|
1301
|
+
}
|
|
1302
|
+
// Nothing held, and no answer placed meanwhile: the run parks.
|
|
1303
|
+
if (!waitHolds.length && !mine.sent) {
|
|
1304
|
+
endWait(mine);
|
|
1305
|
+
return undefined;
|
|
1306
|
+
}
|
|
1307
|
+
// The wait's start, once, in the journal, with the row's waiting summary (the server tells run.needs_input by it).
|
|
1308
|
+
if (!marked && !mine.sent) {
|
|
1309
|
+
const shown = theGate.expect(writesEntry(KINDS.personAsked, (data) => data.callId === callId && data.inClaim === true), { run: { summary: ASK_PERSON_WAITING } });
|
|
1310
|
+
shown.catch(() => undefined);
|
|
1311
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId, inClaim: true, at: since } }), context);
|
|
1312
|
+
await shown;
|
|
1313
|
+
}
|
|
1314
|
+
const next = new Promise((resolve, reject) => {
|
|
1315
|
+
let done = false;
|
|
1316
|
+
let lapsed = false;
|
|
1317
|
+
const finish = (value) => {
|
|
1318
|
+
if (done)
|
|
1319
|
+
return;
|
|
1320
|
+
done = true;
|
|
1321
|
+
endWait(mine);
|
|
1322
|
+
resolve(value);
|
|
1323
|
+
};
|
|
1324
|
+
// A hold that lapses ends the wait, unless the person's answer is being placed: then the answer's turn stands.
|
|
1325
|
+
for (const hold of waitHolds)
|
|
1326
|
+
void hold.lapsed.then(() => {
|
|
1327
|
+
lapsed = true;
|
|
1328
|
+
if (!mine.sent)
|
|
1329
|
+
finish("lapsed");
|
|
1330
|
+
}, () => undefined);
|
|
1331
|
+
void (async () => {
|
|
1332
|
+
for (;;) {
|
|
1333
|
+
await placing;
|
|
1334
|
+
try {
|
|
1335
|
+
await mine.sent;
|
|
1336
|
+
return finish(theSession.turnEnd());
|
|
1337
|
+
}
|
|
1338
|
+
catch {
|
|
1339
|
+
// Not placed (the steer was refused): the next message may be.
|
|
1340
|
+
mine.sent = undefined;
|
|
1341
|
+
placing = new Promise((resolve) => (mine.placed = resolve));
|
|
1342
|
+
if (lapsed)
|
|
1343
|
+
return finish("lapsed");
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
})().catch(reject);
|
|
1347
|
+
});
|
|
1348
|
+
return { next };
|
|
1349
|
+
}
|
|
1350
|
+
/** The session and its Harness closed behind the journal's seal: nothing they write after reaches the store. */
|
|
1351
|
+
async function closeSession() {
|
|
1352
|
+
gate?.seal(new Interrupted("the Session is closing"));
|
|
1353
|
+
endWait();
|
|
1354
|
+
const closing = Promise.all([session?.close().catch(() => { }), harness?.close(BACKGROUND_CONTEXT).catch(() => { })]);
|
|
1355
|
+
let timer;
|
|
1356
|
+
await Promise.race([closing, new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
|
|
1357
|
+
clearTimeout(timer);
|
|
1358
|
+
session = undefined;
|
|
1359
|
+
// The pass's MCP credentials go with it.
|
|
1360
|
+
mcp?.release();
|
|
1361
|
+
mcp = undefined;
|
|
1362
|
+
// The pass's resources go once nothing more is written through them (AdapterRunSpec.release), once each.
|
|
1363
|
+
const release = releaseNow;
|
|
1364
|
+
releaseNow = undefined;
|
|
1365
|
+
await release?.().catch((error) => console.warn(`[runner] its run's release failed: ${said(error)}`));
|
|
1366
|
+
}
|
|
1367
|
+
/** The run's end-of-run step: its spec's (AdapterRunSpec.endOfRun) when it has one, else the loop's deps'. */
|
|
1368
|
+
const stepOf = (spec) => spec.endOfRun ?? deps.endOfRun;
|
|
1369
|
+
/** The end-of-run step (stepOf: the spec's, else LoopDeps.endOfRun), asked once: the rows to stage with the end; `stopped` when a person's stop
|
|
1370
|
+
* came during it; `interrupted` when the claim was lost or the runner is closing (no end is written, and the next claim
|
|
1371
|
+
* asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it. */
|
|
1372
|
+
async function endOfRunStep(claim, spec, outcome) {
|
|
1373
|
+
const cut = () => {
|
|
1374
|
+
if (stopReason?.kind === "command")
|
|
1375
|
+
return { kind: "stopped", commandId: stopReason.commandId };
|
|
1376
|
+
if (stopReason || deps.signal.aborted)
|
|
1377
|
+
return { kind: "interrupted" };
|
|
1378
|
+
return undefined;
|
|
1379
|
+
};
|
|
1380
|
+
const step = stepOf(spec);
|
|
1381
|
+
if (!step)
|
|
1382
|
+
return { kind: "rows", also: [] };
|
|
1383
|
+
if (!spec.agentId)
|
|
1384
|
+
throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
|
|
1385
|
+
try {
|
|
1386
|
+
const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, prompt, opts.deadlineMs, opts.again === true) });
|
|
1387
|
+
return cut() ?? { kind: "rows", also: rows?.also ?? [] };
|
|
1388
|
+
}
|
|
1389
|
+
catch (error) {
|
|
1390
|
+
return cut() ?? (console.warn(`[runner] ${claim.runId}: its end-of-run step failed: ${said(error)}`), { kind: "rows", also: [] });
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
/** What a run cut before it could look back keeps beside its end (LoopDeps.endOfRun with `cut`, never asking): a
|
|
1394
|
+
* person's stop, before or during the end-of-run turn, or a fault. Bounded (CUT_STEP_MS): a step that reads a stalled
|
|
1395
|
+
* store, or throws, keeps nothing, and the end is never held up by it. */
|
|
1396
|
+
async function cutRows(claim, spec, cut) {
|
|
1397
|
+
const step = stepOf(spec);
|
|
1398
|
+
if (!step || !spec.agentId)
|
|
1399
|
+
return [];
|
|
1400
|
+
const refuse = () => Promise.reject(new Error("a cut run's end-of-run step asks nothing"));
|
|
1401
|
+
let timer;
|
|
1402
|
+
const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
|
|
1403
|
+
try {
|
|
1404
|
+
const rows = await Promise.race([step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse }), late]);
|
|
1405
|
+
if (rows === "late") {
|
|
1406
|
+
console.warn(`[runner] ${claim.runId}: its end-of-run step gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
|
|
1407
|
+
return [];
|
|
1408
|
+
}
|
|
1409
|
+
return rows?.also ?? [];
|
|
1410
|
+
}
|
|
1411
|
+
catch (error) {
|
|
1412
|
+
console.warn(`[runner] ${claim.runId}: its end-of-run step failed: ${said(error)}`);
|
|
1413
|
+
return [];
|
|
1414
|
+
}
|
|
1415
|
+
finally {
|
|
1416
|
+
clearTimeout(timer);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
/** The end-of-run turn: one more turn through the run's session, its request id one per run (a repeat is answered from
|
|
1420
|
+
* its submission, so a later claim never asks the model again), its writes under work/.learning/ refused while it runs.
|
|
1421
|
+
* `again`: its re-ask, a request of its own (one per run too). Aborted at `deadlineMs`. A stop or a lost claim cuts it:
|
|
1422
|
+
* it throws, and the step sees why. */
|
|
1423
|
+
async function askEndOfRun(claim, prompt, deadlineMs, again = false) {
|
|
1424
|
+
if (!session || !harness || !gate || !root)
|
|
1425
|
+
throw new Error("the run's session is not open");
|
|
1426
|
+
const on = harness;
|
|
1427
|
+
const conversation = root;
|
|
1428
|
+
const theSession = session;
|
|
1429
|
+
const requestId = reflectRequestId(claim.runId, again);
|
|
1430
|
+
const theRecord = cliRecord;
|
|
1431
|
+
reflecting = true;
|
|
1432
|
+
let timer;
|
|
1433
|
+
try {
|
|
1434
|
+
// A CLI's record answers a turn it already wrote from its submission, as pi does: its CLI is never asked twice.
|
|
1435
|
+
const known = theRecord ? await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context) : undefined;
|
|
1436
|
+
// How this claim's turn ended; a turn answered before reads as its submission says.
|
|
1437
|
+
let turnStatus = "completed";
|
|
1438
|
+
if (!known) {
|
|
1439
|
+
theRecord?.answering();
|
|
1440
|
+
await theSession.send(prompt, { id: requestId });
|
|
1441
|
+
const turn = theSession.turnEnd();
|
|
1442
|
+
const timeout = new Promise((resolve) => (timer = setTimeout(() => resolve("timeout"), deadlineMs)));
|
|
1443
|
+
const end = await Promise.race([turn, timeout, stopping.then(() => "stop"), on.closed.then(() => "closed")]);
|
|
1444
|
+
if (end === "stop" || end === "closed")
|
|
1445
|
+
throw new Interrupted(stopReason?.kind ?? "the Session closed");
|
|
1446
|
+
if (end === "timeout") {
|
|
1447
|
+
await theSession.interrupt().catch(() => { });
|
|
1448
|
+
await on.waitForIdle(context).catch(() => { });
|
|
1449
|
+
await theRecord?.answered(requestId, prompt, "timed out");
|
|
1450
|
+
return { timedOut: true };
|
|
1451
|
+
}
|
|
1452
|
+
// The CLI's turn, as the submission pi's adapter writes: what the step reads next, one reader for both.
|
|
1453
|
+
turnStatus = end.status;
|
|
1454
|
+
await theRecord?.answered(requestId, prompt, end.status);
|
|
1455
|
+
}
|
|
1456
|
+
const record = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
1457
|
+
if (turnStatus !== "completed" || record?.status !== "done")
|
|
1458
|
+
return { failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } };
|
|
1459
|
+
const answer = (await entriesOf(gate.journal, conversation.id, context)).find((entry) => entry.id === record.answer);
|
|
1460
|
+
return { ended: true, answer: answerText(answer) };
|
|
1461
|
+
}
|
|
1462
|
+
finally {
|
|
1463
|
+
clearTimeout(timer);
|
|
1464
|
+
reflecting = false;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
/** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded like the cut step: late or failing, none. */
|
|
1468
|
+
async function endPatchOf(data) {
|
|
1469
|
+
if (!specNow?.endPatch)
|
|
1470
|
+
return {};
|
|
1471
|
+
let timer;
|
|
1472
|
+
const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
|
|
1473
|
+
try {
|
|
1474
|
+
const patch = await Promise.race([specNow.endPatch(data), late]);
|
|
1475
|
+
if (patch === "late") {
|
|
1476
|
+
console.warn(`[runner] its end's patch gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
|
|
1477
|
+
return {};
|
|
1478
|
+
}
|
|
1479
|
+
return patch ?? {};
|
|
1480
|
+
}
|
|
1481
|
+
catch (error) {
|
|
1482
|
+
console.warn(`[runner] its end's patch failed: ${said(error)}`);
|
|
1483
|
+
return {};
|
|
1484
|
+
}
|
|
1485
|
+
finally {
|
|
1486
|
+
clearTimeout(timer);
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
/** The run parked at its cap: its pending budget as an agentrun.budget entry, in one commit with the run parked in the
|
|
1490
|
+
* cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it. */
|
|
1491
|
+
async function parkAtCap(on, conversation, theGate, data) {
|
|
1492
|
+
await pauseAtCap(on, conversation, theGate, data);
|
|
1493
|
+
await releaseHost(on);
|
|
1494
|
+
theGate.seal(new Parked());
|
|
1495
|
+
return { state: "parked" };
|
|
1496
|
+
}
|
|
1497
|
+
/** The run's pause at its cap: its agentrun.budget entry, in one commit with the run parked in the cap's words. */
|
|
1498
|
+
async function pauseAtCap(on, conversation, theGate, data) {
|
|
1499
|
+
const parkedAt = theGate.expect(writesEntry(KINDS.budget), { run: { state: "parked", summary: data.words } });
|
|
1500
|
+
// A seal while the commit is in flight fails it before it is awaited: handled here, read below.
|
|
1501
|
+
parkedAt.catch(() => undefined);
|
|
1502
|
+
try {
|
|
1503
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.budget, data: data }), context);
|
|
1504
|
+
}
|
|
1505
|
+
catch (error) {
|
|
1506
|
+
parkedAt.catch(() => undefined);
|
|
1507
|
+
throw error;
|
|
1508
|
+
}
|
|
1509
|
+
await parkedAt;
|
|
1510
|
+
}
|
|
1511
|
+
/** Waits, at most CLOSE_MS, until every paid request the session admitted is booked: a person's stop is booked at what
|
|
1512
|
+
* streamed once the session's proxy sees its upstream end. Past the bound the end is written anyway, and a request left
|
|
1513
|
+
* unbooked reads at its hold and bound, the worst it can have cost. */
|
|
1514
|
+
async function bookingsSettled() {
|
|
1515
|
+
if (unbooked === 0)
|
|
1516
|
+
return;
|
|
1517
|
+
specNow?.hooks?.awaitingBookings?.();
|
|
1518
|
+
let timer;
|
|
1519
|
+
await Promise.race([new Promise((resolve) => bookedAll.push(resolve)), new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
|
|
1520
|
+
clearTimeout(timer);
|
|
1521
|
+
}
|
|
1522
|
+
/** The run's timeline says it went on after its runner was lost (RUN_RESUMED, `after: runner_lost`): one root entry,
|
|
1523
|
+
* no run patch. A journal sealed meanwhile (the claim lost again, a shutdown) refuses it, and the loop goes on as it
|
|
1524
|
+
* would: the next claim says it. */
|
|
1525
|
+
async function noteTakenOver(on, conversation, runner) {
|
|
1526
|
+
try {
|
|
1527
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: RUN_RESUMED, data: { after: "runner_lost", runner, at: Date.now() } }), context);
|
|
1528
|
+
}
|
|
1529
|
+
catch (error) {
|
|
1530
|
+
if (!gate?.sealed)
|
|
1531
|
+
throw error;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
/** The end commit: an `agentrun.end` entry carrying the run row's final patch (the spec's end patch in it), the rows
|
|
1535
|
+
* staged with it (the end-of-run step's), and the rows it takes. */
|
|
1536
|
+
/** `failedWith`: a CLI turn's own error (record "loop"), cut of every secret the runner holds: written in the end's
|
|
1537
|
+
* commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn. */
|
|
1538
|
+
async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith) {
|
|
1539
|
+
// The end is the run's release: nothing of this claim lands after it, so the tool host is let go first (its writes in
|
|
1540
|
+
// their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
|
|
1541
|
+
await releaseHost(on);
|
|
1542
|
+
await bookingsSettled();
|
|
1543
|
+
const patch = await endPatchOf(base);
|
|
1544
|
+
const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}) };
|
|
1545
|
+
const run = {
|
|
1546
|
+
state: data.state,
|
|
1547
|
+
// An end's summary is its own: with none, a wait's summary the row still says (a question's, a hand-over's: HELD_WAITS
|
|
1548
|
+
// and the park's) goes, so an ended run never reads as waiting on its person.
|
|
1549
|
+
...(data.summary ? { summary: data.summary } : {}),
|
|
1550
|
+
...(!data.summary ? { summary: null } : {}),
|
|
1551
|
+
...(data.outcome !== undefined ? { outcome: data.outcome } : {}),
|
|
1552
|
+
...(data.costUsd !== undefined ? { costUsd: data.costUsd } : {}),
|
|
1553
|
+
...(data.metrics !== undefined ? { metrics: data.metrics } : {}),
|
|
1554
|
+
};
|
|
1555
|
+
// A person's stop or cancel withdraws every call still waiting for its answer, in the end's own commit: the approval
|
|
1556
|
+
// card reads answered (withdrawn), never waiting for good on a final run.
|
|
1557
|
+
const byPerson = data.state === "stopped" || stopReason?.kind === "command";
|
|
1558
|
+
const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow()) : [];
|
|
1559
|
+
const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
|
|
1560
|
+
// A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
|
|
1561
|
+
ended.catch(() => undefined);
|
|
1562
|
+
try {
|
|
1563
|
+
await on.commit(async (tx) => {
|
|
1564
|
+
for (const answer of withdrawn)
|
|
1565
|
+
await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
|
|
1566
|
+
if (failedWith !== undefined)
|
|
1567
|
+
await tx.appendEntry(conversation.id, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", failedWith, now())] });
|
|
1568
|
+
return tx.appendEntry(conversation.id, { kind: KINDS.end, data: data });
|
|
1569
|
+
}, context);
|
|
1570
|
+
}
|
|
1571
|
+
catch (error) {
|
|
1572
|
+
// The end was not written: its expectation fails when the journal is sealed, and nothing waits on it.
|
|
1573
|
+
ended.catch(() => undefined);
|
|
1574
|
+
throw error;
|
|
1575
|
+
}
|
|
1576
|
+
await ended;
|
|
1577
|
+
return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
|
|
1578
|
+
}
|
|
1579
|
+
return {
|
|
1580
|
+
start(claim) {
|
|
1581
|
+
finished = run(claim);
|
|
1582
|
+
return finished;
|
|
1583
|
+
},
|
|
1584
|
+
async command(command) {
|
|
1585
|
+
// A command row resumes a loop that may have sat past a token's life: its MCP credentials are made fresh again
|
|
1586
|
+
// before its next model request.
|
|
1587
|
+
if (command.kind === "steer" || command.kind === "approve" || command.kind === "deny" || command.kind === "raise")
|
|
1588
|
+
mcpStale = true;
|
|
1589
|
+
if (command.kind === "steer")
|
|
1590
|
+
return steer(command);
|
|
1591
|
+
if (command.kind === "approve" || command.kind === "deny") {
|
|
1592
|
+
// An answer names its approval: the asked call's id. One that names no call waiting for its answer (an old
|
|
1593
|
+
// approval, another run's) is refused, never applied to the call that waits now.
|
|
1594
|
+
const approval = approvalOf(command);
|
|
1595
|
+
if (!(await waitsFor(approval))) {
|
|
1596
|
+
refusals += 1;
|
|
1597
|
+
wakeInbox();
|
|
1598
|
+
return { refused: `no call of this run waits for approval ${JSON.stringify(approval ?? "")}` };
|
|
1599
|
+
}
|
|
1600
|
+
inbox.push(command);
|
|
1601
|
+
wakeInbox();
|
|
1602
|
+
return { taken: true };
|
|
1603
|
+
}
|
|
1604
|
+
if (command.kind === "raise")
|
|
1605
|
+
return raise(command);
|
|
1606
|
+
if (command.kind === HAND_BACK)
|
|
1607
|
+
return handBack(command);
|
|
1608
|
+
if (isComputerCommand(command))
|
|
1609
|
+
return computerCommand(command);
|
|
1610
|
+
// A pause is a workflow run's: an agentic run's turn is stopped instead, in main's words (runs.ts pause).
|
|
1611
|
+
if (command.kind === "pause" || command.kind === "resume")
|
|
1612
|
+
return { refused: AGENTIC_PAUSE_REFUSED };
|
|
1613
|
+
return { refused: `an adapter loop takes no ${command.kind} command` };
|
|
1614
|
+
},
|
|
1615
|
+
async stop(reason) {
|
|
1616
|
+
stopReason ??= reason;
|
|
1617
|
+
if (reason.kind !== "command")
|
|
1618
|
+
gate?.seal(new Interrupted(reason.kind));
|
|
1619
|
+
stopped();
|
|
1620
|
+
wakeInbox();
|
|
1621
|
+
await finished?.catch(() => undefined);
|
|
1622
|
+
},
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
export { Parked };
|