@parcha/agentrun-serve 0.1.0-beta.37 → 0.1.0-beta.39
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 +700 -0
- package/README.md +441 -177
- package/dist/adapters.d.ts +4 -1
- package/dist/adapters.js +4 -2
- package/dist/agent-rows.d.ts +1 -3
- package/dist/agents-store.d.ts +35 -3
- package/dist/agents-store.js +48 -23
- package/dist/answer-json.d.ts +34 -1
- package/dist/answer-json.js +91 -9
- package/dist/api-only.d.ts +1 -1
- package/dist/api-only.js +2 -2
- package/dist/bash-read-only.js +2 -1
- package/dist/browser-cost.js +52 -93
- package/dist/cap-short.d.ts +12 -0
- package/dist/cap-short.js +60 -0
- package/dist/cap.d.ts +3 -400
- package/dist/cap.js +6 -942
- package/dist/catalog.d.ts +0 -5
- package/dist/catalog.js +2 -6
- package/dist/chatgpt-plan.d.ts +163 -0
- package/dist/chatgpt-plan.js +549 -0
- package/dist/cli.js +26 -6
- package/dist/composio-preset.d.ts +25 -0
- package/dist/composio-preset.js +51 -8
- package/dist/composio-triggers.d.ts +113 -0
- package/dist/composio-triggers.js +411 -0
- package/dist/computer-calls.d.ts +36 -24
- package/dist/computer-calls.js +110 -27
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +7 -3
- package/dist/computer-live.d.ts +12 -2
- package/dist/computer-live.js +21 -5
- package/dist/computer-routes.d.ts +2 -2
- package/dist/computer-routes.js +2 -2
- package/dist/computer-setting.d.ts +15 -2
- package/dist/computer-setting.js +20 -4
- package/dist/computer-view.d.ts +18 -2
- package/dist/computer-view.js +21 -6
- package/dist/computer-viewer.js +40 -13
- package/dist/computers.d.ts +8 -2
- package/dist/computers.js +18 -8
- package/dist/console/assets/index-BNhZs-jp.css +1 -0
- package/dist/console/assets/index-BQv5aOGB.js +700 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +2 -0
- package/dist/console-links.js +6 -3
- package/dist/decision-cap.d.ts +2 -5
- package/dist/decision-cap.js +3 -6
- package/dist/decision-rows.js +11 -11
- package/dist/decisions.js +4 -0
- package/dist/email/account.d.ts +84 -0
- package/dist/email/account.js +159 -0
- package/dist/email/answer.d.ts +10 -0
- package/dist/email/answer.js +182 -0
- package/dist/email/email-faux.d.ts +95 -0
- package/dist/email/email-faux.js +849 -0
- package/dist/email/labels.d.ts +1 -0
- package/dist/email/labels.js +84 -0
- package/dist/email/mail.d.ts +186 -0
- package/dist/email/mail.js +380 -0
- package/dist/email/names.d.ts +20 -0
- package/dist/email/names.js +40 -0
- package/dist/email/routes.d.ts +9 -0
- package/dist/email/routes.js +50 -0
- package/dist/email/tools.d.ts +20 -0
- package/dist/email/tools.js +517 -0
- package/dist/environment.d.ts +17 -2
- package/dist/environment.js +36 -8
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +12 -0
- package/dist/eval-mailbox.d.ts +103 -0
- package/dist/eval-mailbox.js +236 -0
- package/dist/faux-computers.js +4 -2
- package/dist/graph-view.d.ts +9 -2
- package/dist/graph-view.js +6 -2
- package/dist/harness-install.d.ts +28 -2
- package/dist/harness-install.js +147 -59
- package/dist/harness-opencode/adapter.js +2 -22
- package/dist/harness-opencode/facts.js +5 -4
- package/dist/harness-opencode/host/policy.d.ts +4 -5
- package/dist/harness-opencode/host/policy.js +14 -33
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/versions.d.ts +6 -0
- package/dist/harness-opencode/versions.js +6 -0
- package/dist/harness-table.d.ts +0 -2
- package/dist/harness-table.js +8 -7
- package/dist/harness.d.ts +12 -0
- package/dist/harness.js +15 -3
- package/dist/host-tools.d.ts +1 -5
- package/dist/host-tools.js +7 -10
- package/dist/hosted-search.d.ts +3 -3
- package/dist/hosted-search.js +51 -32
- package/dist/import-sources.d.ts +1 -1
- package/dist/import-sources.js +3 -3
- package/dist/import.d.ts +21 -0
- package/dist/import.js +186 -1
- package/dist/key-check.d.ts +0 -2
- package/dist/key-check.js +3 -4
- package/dist/key-refusal.d.ts +8 -2
- package/dist/key-refusal.js +16 -13
- package/dist/key-words.d.ts +3 -2
- package/dist/key-words.js +4 -2
- package/dist/learn/check.d.ts +24 -4
- package/dist/learn/check.js +340 -7
- package/dist/learn/commit.d.ts +10 -0
- package/dist/learn/commit.js +18 -4
- package/dist/learn/compile.d.ts +250 -0
- package/dist/learn/compile.js +507 -0
- package/dist/learn/general.d.ts +3 -0
- package/dist/learn/general.js +4 -2
- package/dist/learn/grade.d.ts +5 -1
- package/dist/learn/grade.js +11 -7
- package/dist/learn/notes.d.ts +8 -0
- package/dist/learn/notes.js +18 -0
- package/dist/learn/promote.d.ts +308 -0
- package/dist/learn/promote.js +321 -0
- package/dist/learn/refit.d.ts +48 -0
- package/dist/learn/refit.js +264 -0
- package/dist/learn/reflect.d.ts +5 -25
- package/dist/learn/reflect.js +14 -131
- package/dist/learn/replay-calls.d.ts +63 -0
- package/dist/learn/replay-calls.js +158 -0
- package/dist/learn/skills.d.ts +19 -16
- package/dist/learn/skills.js +157 -53
- package/dist/learn/workflow-nodes.d.ts +15 -0
- package/dist/learn/workflow-nodes.js +44 -0
- package/dist/learned-nodes.d.ts +58 -2
- package/dist/learned-nodes.js +68 -5
- package/dist/learned-workflow.d.ts +58 -32
- package/dist/learned-workflow.js +215 -77
- package/dist/learning-batch.d.ts +2 -2
- package/dist/learning-batch.js +4 -4
- package/dist/learning-cost.d.ts +41 -11
- package/dist/learning-cost.js +31 -13
- package/dist/learning-routes.d.ts +12 -2
- package/dist/learning-routes.js +34 -6
- package/dist/learning-words.d.ts +8 -1
- package/dist/learning-words.js +11 -1
- package/dist/learning.d.ts +26 -1
- package/dist/learning.js +7 -4
- package/dist/link-check.d.ts +27 -0
- package/dist/link-check.js +164 -0
- package/dist/llm.js +0 -3
- package/dist/local-models.d.ts +33 -2
- package/dist/local-models.js +43 -5
- package/dist/mcp-gateway.d.ts +12 -20
- package/dist/mcp-gateway.js +16 -44
- package/dist/mcp-oauth.d.ts +5 -0
- package/dist/mcp-oauth.js +1 -1
- package/dist/mcp-pin-first.d.ts +37 -0
- package/dist/mcp-pin-first.js +113 -0
- package/dist/mcp-probe.d.ts +8 -9
- package/dist/mcp-probe.js +16 -33
- package/dist/mcp-secret-writes.js +3 -0
- package/dist/mcp-servers-store.d.ts +102 -26
- package/dist/mcp-servers-store.js +151 -25
- package/dist/mcp-sources.d.ts +39 -0
- package/dist/mcp-sources.js +74 -0
- package/dist/mcp-store.d.ts +11 -0
- package/dist/mcp-store.js +16 -2
- package/dist/mcp-wire.d.ts +22 -0
- package/dist/mcp-wire.js +36 -0
- package/dist/mcp.js +3 -3
- package/dist/meta-tool-names.d.ts +1 -0
- package/dist/meta-tool-names.js +3 -0
- package/dist/model-form.d.ts +11 -0
- package/dist/model-form.js +17 -1
- package/dist/model.d.ts +39 -6
- package/dist/model.js +171 -32
- package/dist/monid.d.ts +50 -29
- package/dist/monid.js +234 -143
- package/dist/native/binding.d.ts +13 -0
- package/dist/native/binding.js +57 -0
- package/dist/native/cli.d.ts +2 -0
- package/dist/native/cli.js +48 -0
- package/dist/native/connection.d.ts +8 -0
- package/dist/native/connection.js +94 -0
- package/dist/native/context.d.ts +6 -0
- package/dist/native/context.js +22 -0
- package/dist/native/discovery.d.ts +27 -0
- package/dist/native/discovery.js +404 -0
- package/dist/native/environment.d.ts +4 -0
- package/dist/native/environment.js +18 -0
- package/dist/native/history.d.ts +20 -0
- package/dist/native/history.js +147 -0
- package/dist/native/instructions.d.ts +21 -0
- package/dist/native/instructions.js +173 -0
- package/dist/native/remote-worker-bridge.d.ts +3 -0
- package/dist/native/remote-worker-bridge.js +278 -0
- package/dist/native/remote.d.ts +187 -0
- package/dist/native/remote.js +492 -0
- package/dist/native/runtime.d.ts +17 -0
- package/dist/native/runtime.js +316 -0
- package/dist/native/runtimes.d.ts +66 -0
- package/dist/native/runtimes.js +41 -0
- package/dist/native/schema.d.ts +46 -0
- package/dist/native/schema.js +41 -0
- package/dist/native/types.d.ts +87 -0
- package/dist/native/types.js +1 -0
- package/dist/observation/http.d.ts +4 -0
- package/dist/observation/http.js +140 -0
- package/dist/observation/observer.d.ts +301 -0
- package/dist/observation/observer.js +919 -0
- package/dist/observation/schema.d.ts +52 -0
- package/dist/observation/schema.js +154 -0
- package/dist/openapi.d.ts +1 -0
- package/dist/openapi.js +705 -126
- package/dist/paid-calls.d.ts +34 -32
- package/dist/paid-calls.js +52 -104
- package/dist/place-offers.d.ts +4 -8
- package/dist/place-offers.js +4 -9
- package/dist/port-models.d.ts +7 -2
- package/dist/port-models.js +5 -2
- package/dist/print.d.ts +4 -2
- package/dist/print.js +4 -3
- package/dist/propose.d.ts +8 -3
- package/dist/propose.js +28 -7
- package/dist/provider.d.ts +5 -1
- package/dist/provider.js +17 -2
- package/dist/push-handler.d.ts +3 -2
- package/dist/push-handler.js +20 -6
- package/dist/reflect-range.js +2 -1
- package/dist/refusal-words.d.ts +11 -0
- package/dist/refusal-words.js +13 -2
- package/dist/rows.d.ts +5 -3
- package/dist/rows.js +15 -4
- package/dist/run-launch.d.ts +23 -1
- package/dist/run-launch.js +17 -4
- package/dist/run-learning-served.d.ts +84 -0
- package/dist/run-manifest.d.ts +8 -0
- package/dist/run-manifest.js +33 -1
- package/dist/run-reads-over-store.d.ts +3 -3
- package/dist/run-reads-over-store.js +13 -10
- package/dist/run-secrets.js +2 -3
- package/dist/run-timeline-served.d.ts +3 -2
- package/dist/run-timeline-served.js +12 -10
- package/dist/run-view.d.ts +59 -41
- package/dist/run-view.js +128 -64
- package/dist/runnable.d.ts +13 -8
- package/dist/runnable.js +77 -60
- package/dist/runner/adapter-loop.d.ts +60 -15
- package/dist/runner/adapter-loop.js +1406 -464
- package/dist/runner/adapter-run-spec.d.ts +45 -14
- package/dist/runner/adapter-run-spec.js +200 -116
- package/dist/runner/adapters/pi.d.ts +40 -7
- package/dist/runner/adapters/pi.js +149 -38
- package/dist/runner/beside.d.ts +3 -1
- package/dist/runner/beside.js +24 -8
- package/dist/runner/claim-secrets.d.ts +3 -1
- package/dist/runner/claim-secrets.js +28 -4
- package/dist/runner/cli-run-spec.d.ts +30 -0
- package/dist/runner/cli-run-spec.js +150 -66
- package/dist/runner/computer-channel.d.ts +5 -2
- package/dist/runner/computer-channel.js +5 -3
- package/dist/runner/computer-journal.d.ts +6 -0
- package/dist/runner/computer-journal.js +8 -10
- package/dist/runner/conformance/harness.d.ts +3 -0
- package/dist/runner/conformance/harness.js +149 -5
- package/dist/runner/conformance/subject.d.ts +11 -4
- package/dist/runner/end-of-run.d.ts +8 -5
- package/dist/runner/end-of-run.js +11 -6
- package/dist/runner/feedback-round.d.ts +79 -0
- package/dist/runner/feedback-round.js +127 -0
- package/dist/runner/harness-loops.js +17 -0
- package/dist/runner/journal-kinds.d.ts +55 -13
- package/dist/runner/journal-kinds.js +19 -0
- package/dist/runner/learning-dispatch.d.ts +3 -2
- package/dist/runner/learning-dispatch.js +6 -6
- package/dist/runner/learning-end.d.ts +58 -19
- package/dist/runner/learning-end.js +316 -115
- package/dist/runner/learning-factory.d.ts +3 -0
- package/dist/runner/learning-factory.js +8 -2
- package/dist/runner/learning-loop.d.ts +21 -1
- package/dist/runner/learning-loop.js +24 -6
- package/dist/runner/learning-seed.d.ts +4 -0
- package/dist/runner/learning-seed.js +14 -0
- package/dist/runner/loop-contract.d.ts +19 -3
- package/dist/runner/loop.d.ts +34 -1
- package/dist/runner/loop.js +55 -1
- package/dist/runner/main.d.ts +6 -1
- package/dist/runner/main.js +26 -4
- package/dist/runner/mcp-claim.d.ts +5 -1
- package/dist/runner/mcp-claim.js +66 -50
- package/dist/runner/mcp-run.d.ts +20 -53
- package/dist/runner/mcp-run.js +22 -88
- package/dist/runner/meta-tools.d.ts +44 -0
- package/dist/runner/meta-tools.js +344 -0
- package/dist/runner/metrics.d.ts +80 -21
- package/dist/runner/metrics.js +128 -42
- package/dist/runner/model-route.d.ts +12 -3
- package/dist/runner/model-route.js +149 -19
- package/dist/runner/monid-run.d.ts +18 -0
- package/dist/runner/monid-run.js +170 -0
- package/dist/runner/native-loop.d.ts +11 -0
- package/dist/runner/native-loop.js +438 -0
- package/dist/runner/promotion.d.ts +146 -0
- package/dist/runner/promotion.js +803 -0
- package/dist/runner/redact.js +3 -0
- package/dist/runner/reflect-hook.d.ts +36 -21
- package/dist/runner/reflect-hook.js +147 -49
- package/dist/runner/runner.d.ts +7 -1
- package/dist/runner/runner.js +34 -8
- package/dist/runner/sdk-loop.d.ts +7 -0
- package/dist/runner/sdk-loop.js +470 -0
- package/dist/runner/sessions.d.ts +8 -3
- package/dist/runner/sessions.js +5 -1
- package/dist/runner/spec-holds.d.ts +16 -2
- package/dist/runner/spec-holds.js +42 -14
- package/dist/runner/step-guard.d.ts +62 -0
- package/dist/runner/step-guard.js +93 -0
- package/dist/runner/store-secrets.js +17 -2
- package/dist/runner/subagent.d.ts +0 -3
- package/dist/runner/subagent.js +7 -12
- package/dist/runner/workflow-first.d.ts +226 -0
- package/dist/runner/workflow-first.js +293 -0
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-loop.js +32 -19
- package/dist/runner/workflow-spec.d.ts +5 -1
- package/dist/runner/workflow-spec.js +63 -48
- package/dist/runs-over-store.d.ts +41 -4
- package/dist/runs-over-store.js +64 -22
- package/dist/sdk/runs.d.ts +115 -0
- package/dist/sdk/runs.js +422 -0
- package/dist/sdk/schema.d.ts +175 -0
- package/dist/sdk/schema.js +138 -0
- package/dist/sdk/workflows.d.ts +22 -0
- package/dist/sdk/workflows.js +39 -0
- package/dist/secrets.d.ts +2 -0
- package/dist/secrets.js +19 -1
- package/dist/server.d.ts +108 -20
- package/dist/server.js +874 -157
- package/dist/settings-wake.d.ts +8 -6
- package/dist/settings-wake.js +13 -7
- package/dist/skill-route.d.ts +3 -0
- package/dist/skill-route.js +16 -0
- package/dist/skills/agentrun-serve/SKILL.md +368 -0
- package/dist/stats.d.ts +10 -10
- package/dist/store/agent-body.d.ts +22 -7
- package/dist/store/agent-body.js +23 -14
- package/dist/store/command-wake.d.ts +3 -2
- package/dist/store/command-wake.js +4 -4
- package/dist/store/index.d.ts +1 -1
- package/dist/store/native-command-owner.d.ts +10 -0
- package/dist/store/native-command-owner.js +47 -0
- package/dist/store/postgres/connection.js +3 -1
- package/dist/store/postgres/migrations/0010_imported_templates.sql +18 -0
- package/dist/store/postgres/migrations/0011_revision_mcp_pin.sql +13 -0
- package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
- package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
- package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
- package/dist/store/postgres/store.js +3 -0
- package/dist/store/schema.d.ts +16 -0
- package/dist/store/schema.js +47 -8
- package/dist/store/sqlite/connection.d.ts +2 -2
- package/dist/store/sqlite/connection.js +2 -2
- package/dist/store/sqlite/run-patch.d.ts +8 -1
- package/dist/store/sqlite/run-patch.js +33 -10
- package/dist/store/sqlite/store.js +184 -28
- package/dist/store/store.d.ts +98 -21
- package/dist/store-reads/analytics.d.ts +7 -7
- package/dist/store-reads/analytics.js +23 -5
- package/dist/store-reads/cap.js +8 -6
- package/dist/store-reads/journal.d.ts +30 -1
- package/dist/store-reads/journal.js +141 -83
- package/dist/store-reads/learning.d.ts +179 -13
- package/dist/store-reads/learning.js +230 -68
- package/dist/store-reads/loop.d.ts +61 -0
- package/dist/store-reads/loop.js +111 -0
- package/dist/store-reads/runs.d.ts +5 -0
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.d.ts +3 -2
- package/dist/store-view.js +109 -37
- package/dist/template-eval.d.ts +87 -16
- package/dist/template-eval.js +605 -120
- package/dist/template-github-permissions.d.ts +2 -2
- package/dist/template-github-permissions.js +2 -1
- package/dist/template-import.d.ts +31 -0
- package/dist/template-import.js +121 -0
- package/dist/template-source.d.ts +51 -0
- package/dist/template-source.js +371 -0
- package/dist/templates.d.ts +274 -52
- package/dist/templates.js +670 -201
- package/dist/text-urls.d.ts +38 -0
- package/dist/text-urls.js +170 -0
- package/dist/timeline/computer.d.ts +48 -0
- package/dist/timeline/computer.js +169 -0
- package/dist/timeline/index.d.ts +7 -5
- package/dist/timeline/index.js +7 -5
- package/dist/timeline/labels.d.ts +11 -4
- package/dist/timeline/labels.js +122 -8
- package/dist/timeline/origin.d.ts +20 -6
- package/dist/timeline/origin.js +13 -6
- package/dist/timeline/render-text.js +1 -1
- package/dist/timeline/timeline.d.ts +76 -20
- package/dist/timeline/timeline.js +184 -39
- package/dist/timeline/util.d.ts +5 -0
- package/dist/timeline/util.js +44 -8
- package/dist/timeline/web-calls.d.ts +17 -0
- package/dist/timeline/web-calls.js +106 -0
- package/dist/tool-gate.d.ts +103 -76
- package/dist/tool-gate.js +200 -127
- package/dist/tool-keys.d.ts +4 -1
- package/dist/tool-keys.js +8 -3
- package/dist/tool-list.d.ts +29 -0
- package/dist/tool-list.js +50 -0
- package/dist/tool-names.d.ts +76 -0
- package/dist/tool-names.js +101 -0
- package/dist/tool-plane.d.ts +34 -28
- package/dist/tool-plane.js +72 -37
- package/dist/tools.d.ts +59 -15
- package/dist/tools.js +46 -42
- package/dist/trigger-adapter.d.ts +85 -5
- package/dist/trigger-adapter.js +6 -0
- package/dist/trigger-adapters.js +3 -1
- package/dist/trigger-composio.d.ts +10 -0
- package/dist/trigger-composio.js +122 -0
- package/dist/trigger-email.d.ts +4 -0
- package/dist/trigger-email.js +228 -0
- package/dist/trigger-signatures.d.ts +6 -10
- package/dist/trigger-signatures.js +16 -16
- package/dist/trigger-targets.d.ts +1 -1
- package/dist/trigger-targets.js +4 -3
- package/dist/trigger-webhook.js +6 -4
- package/dist/triggers.d.ts +94 -9
- package/dist/triggers.js +263 -62
- package/dist/uploads.d.ts +9 -0
- package/dist/uploads.js +27 -0
- package/dist/validate.d.ts +15 -7
- package/dist/validate.js +91 -50
- package/dist/web-fake.d.ts +56 -0
- package/dist/web-fake.js +102 -0
- package/dist/web-fetch-direct.d.ts +3 -0
- package/dist/web-fetch-direct.js +4 -1
- package/dist/web-fetch.d.ts +6 -8
- package/dist/web-fetch.js +10 -53
- package/dist/web-search.d.ts +51 -2
- package/dist/web-search.js +116 -18
- package/dist/webhooks.d.ts +2 -1
- package/dist/webhooks.js +5 -1
- package/dist/workflow/node-runner.js +10 -2
- package/dist/workspace/archil-claim.d.ts +3 -0
- package/dist/workspace/archil-claim.js +9 -2
- package/dist/workspace/computer-deps.d.ts +25 -9
- package/dist/workspace/computer-deps.js +82 -38
- package/dist/workspace/computer-for-claim.d.ts +60 -4
- package/dist/workspace/computer-for-claim.js +203 -45
- package/dist/workspace/computer-hold.js +7 -1
- package/dist/workspace/computer-janitor.d.ts +10 -3
- package/dist/workspace/computer-janitor.js +96 -29
- package/dist/workspace/computer-kept.d.ts +82 -0
- package/dist/workspace/computer-kept.js +147 -0
- package/dist/workspace/computer-mcp.js +4 -3
- package/dist/workspace/computer-ports.d.ts +23 -3
- package/dist/workspace/computer-ports.js +115 -5
- package/dist/workspace/index.d.ts +2 -3
- package/dist/workspace/index.js +1 -2
- package/dist/workspace/kind-skills/desktop/SKILL.md +31 -11
- package/dist/workspace/kind-skills/phone/SKILL.md +29 -14
- package/dist/workspace/local.js +2 -2
- package/dist/workspace/resolve-computer.d.ts +33 -1
- package/dist/workspace/resolve-computer.js +37 -16
- package/dist/workspace/revision-skills.d.ts +6 -2
- package/dist/workspace/revision-skills.js +12 -5
- package/dist/workspace/run-end-computers.d.ts +30 -0
- package/dist/workspace/run-end-computers.js +137 -0
- package/dist/workspace/run-tools.d.ts +40 -23
- package/dist/workspace/run-tools.js +46 -19
- package/dist/wrap-up.d.ts +35 -0
- package/dist/wrap-up.js +48 -0
- package/launcher/agentrun-serve +4 -2
- package/package.json +13 -9
- package/skills/agentrun-serve/SKILL.md +248 -10
- package/templates/README.md +220 -60
- package/templates/TOOLS.md +168 -0
- package/templates/code-review/agent.md +46 -16
- package/templates/code-review/evals/clean-refactor/case.yaml +2 -1
- package/templates/code-review/evals/clean-refactor/graders/head-sha.md +6 -0
- package/templates/code-review/evals/injection/case.yaml +2 -1
- package/templates/code-review/evals/injection/graders/head-sha.md +6 -0
- package/templates/code-review/evals/mentions-defused/case.yaml +3 -3
- package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -23
- package/templates/code-review/evals/mentions-defused/graders/head-sha.md +6 -0
- package/templates/code-review/evals/never-flag/case.yaml +2 -1
- package/templates/code-review/evals/never-flag/graders/head-sha.md +6 -0
- package/templates/code-review/evals/null-name/case.yaml +2 -1
- package/templates/code-review/evals/null-name/graders/head-sha.md +6 -0
- package/templates/code-review/evals/off-by-one/case.yaml +2 -1
- package/templates/code-review/evals/off-by-one/graders/head-sha.md +6 -0
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
- package/templates/code-review/evals/other-repo/case.yaml +16 -0
- package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +130 -0
- package/templates/code-review/evals/other-repo/graders/head-sha.md +6 -0
- package/templates/code-review/evals/other-repo/graders/no-canary.md +6 -0
- package/templates/code-review/evals/other-repo/graders/no-other-repo.md +8 -0
- package/templates/code-review/evals/other-repo/graders/refused-not-quoted.md +18 -0
- package/templates/code-review/evals/other-repo/prompt.md +10 -0
- package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
- package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
- package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
- package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
- package/templates/code-review/evals/re-review/case.yaml +2 -1
- package/templates/code-review/evals/re-review/graders/head-sha.md +6 -0
- package/templates/code-review/evals/re-review-open/case.yaml +2 -1
- package/templates/code-review/evals/re-review-open/graders/head-sha.md +6 -0
- package/templates/code-review/evals/repo-rule/case.yaml +2 -1
- package/templates/code-review/evals/repo-rule/graders/head-sha.md +6 -0
- package/templates/code-review/evals/two-defects/case.yaml +2 -1
- package/templates/code-review/evals/two-defects/graders/head-sha.md +6 -0
- package/templates/code-review/rules/CODEREVIEW.md +1 -1
- package/templates/code-review/skills/review/DEEP.md +5 -4
- package/templates/code-review/skills/review/REVIEWER.md +5 -4
- package/templates/code-review/skills/review/SKILL.md +11 -6
- package/templates/code-review/{findings.schema.json → skills/review/findings.schema.json} +1 -0
- package/templates/inbound-lead/agent.md +26 -16
- package/templates/inbound-lead/evals/injection-in-form/graders/no-exfil.md +16 -0
- package/templates/inbound-lead/evals/injection-in-form/prompt.md +2 -2
- package/templates/inbound-lead/evals/write-back/case.yaml +2 -6
- package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +34 -225
- package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +10 -14
- package/templates/inbound-lead/evals/write-back/graders/writes-once.md +7 -0
- package/templates/inbound-lead/evals/write-back/prompt.md +1 -1
- package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +3 -7
- package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +34 -225
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/form-id.md +17 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +3 -3
- package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +2 -2
- package/templates/inbound-lead/skills/lead/SKILL.md +23 -27
- package/templates/kyb/agent.md +15 -5
- package/templates/kyb/evals/adverse-media/prompt.md +2 -7
- package/templates/kyb/evals/canada-active-filed/prompt.md +2 -6
- package/templates/kyb/evals/clean-public-company/prompt.md +2 -6
- package/templates/kyb/evals/injection-in-page/prompt.md +3 -7
- package/templates/kyb/evals/name-collision/prompt.md +2 -6
- package/templates/kyb/evals/no-invention/prompt.md +2 -6
- package/templates/kyb/evals/opensanctions-on/prompt.md +2 -6
- package/templates/kyb/evals/sanctioned-entity/prompt.md +2 -6
- package/templates/kyb/kyb.schema.json +8 -7
- package/templates/kyb/skills/kyb/SKILL.md +9 -6
- package/templates/market-monitor/agent.md +19 -12
- package/templates/market-monitor/evals/post-happens/case.yaml +4 -4
- package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +13 -9
- package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +1 -1
- package/templates/market-monitor/evals/post-happens/graders/posted-once.md +3 -3
- package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
- package/templates/release-notes/agent.md +32 -10
- package/templates/release-notes/evals/draft-not-publish/case.yaml +5 -4
- package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +29 -51
- package/templates/release-notes/evals/every-pr-accounted/case.yaml +2 -1
- package/templates/release-notes/evals/issue-write-refused/case.yaml +5 -4
- package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +29 -51
- package/templates/release-notes/evals/late-arrival/case.yaml +6 -5
- package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +29 -51
- package/templates/release-notes/evals/learned-style/case.yaml +2 -1
- package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +2 -1
- package/templates/release-notes/evals/other-repo/case.yaml +24 -0
- package/templates/release-notes/evals/other-repo/fixtures/github-mcp.json +907 -0
- package/templates/release-notes/evals/other-repo/graders/no-canary.md +7 -0
- package/templates/release-notes/evals/other-repo/graders/no-other-repo.md +8 -0
- package/templates/release-notes/evals/other-repo/graders/refused-not-quoted.md +18 -0
- package/templates/release-notes/evals/other-repo/prompt.md +32 -0
- package/templates/release-notes/evals/upgrade-line/case.yaml +2 -1
- package/templates/release-notes/evals/user-facing-only/case.yaml +2 -1
- package/templates/release-notes/notes.schema.json +1 -1
- package/templates/release-notes/skills/release-notes/SKILL.md +26 -17
- package/dist/console/assets/index-Cn6JX1uH.js +0 -563
- package/dist/console/assets/index-DRN62V5v.css +0 -1
- package/dist/host-calls.d.ts +0 -20
- package/dist/host-calls.js +0 -12
- package/dist/runner/adapters/pi-computer.d.ts +0 -7
- package/dist/runner/adapters/pi-computer.js +0 -43
- package/dist/tool-blurbs.d.ts +0 -4
- package/dist/tool-blurbs.js +0 -28
- package/dist/tool-budget.d.ts +0 -38
- package/dist/tool-budget.js +0 -62
- package/dist/workspace/computer-script.d.ts +0 -37
- package/dist/workspace/computer-script.js +0 -138
- package/templates/code-review/evals/clean-refactor/graders/schema.md +0 -5
- package/templates/code-review/evals/injection/graders/schema.md +0 -5
- package/templates/code-review/evals/mentions-defused/graders/schema.md +0 -5
- package/templates/code-review/evals/never-flag/graders/schema.md +0 -5
- package/templates/code-review/evals/null-name/graders/schema.md +0 -5
- package/templates/code-review/evals/off-by-one/graders/schema.md +0 -5
- package/templates/code-review/evals/re-review/graders/schema.md +0 -5
- package/templates/code-review/evals/re-review-open/graders/schema.md +0 -5
- package/templates/code-review/evals/repo-rule/graders/schema.md +0 -5
- package/templates/code-review/evals/two-defects/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/learned-correction/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/strong-fit/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/thin-data/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/write-back/graders/schema.md +0 -5
- package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +0 -7
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +0 -18
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +0 -5
- package/templates/kyb/evals/adverse-media/graders/schema.md +0 -5
- package/templates/kyb/evals/canada-active-filed/graders/schema.md +0 -5
- package/templates/kyb/evals/clean-public-company/graders/schema.md +0 -5
- package/templates/kyb/evals/injection-in-page/graders/schema.md +0 -5
- package/templates/kyb/evals/name-collision/graders/schema.md +0 -5
- package/templates/kyb/evals/no-invention/graders/schema.md +0 -5
- package/templates/kyb/evals/opensanctions-on/graders/schema.md +0 -5
- package/templates/kyb/evals/sanctioned-entity/graders/schema.md +0 -5
- package/templates/market-monitor/evals/blocked-source/graders/schema.md +0 -5
- package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +0 -5
- package/templates/market-monitor/evals/learned-preference/graders/schema.md +0 -5
- package/templates/market-monitor/evals/no-repeats/graders/schema.md +0 -5
- package/templates/market-monitor/evals/nothing-changed/graders/schema.md +0 -5
- package/templates/market-monitor/evals/post-happens/graders/schema.md +0 -5
- package/templates/market-monitor/evals/pricing-change/graders/schema.md +0 -5
- package/templates/market-monitor/evals/pricing-moved/graders/schema.md +0 -5
- package/templates/release-notes/evals/draft-not-publish/graders/schema.md +0 -5
- package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +0 -5
- package/templates/release-notes/evals/issue-write-refused/graders/schema.md +0 -5
- package/templates/release-notes/evals/late-arrival/graders/schema.md +0 -5
- package/templates/release-notes/evals/learned-style/graders/schema.md +0 -5
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +0 -5
- package/templates/release-notes/evals/upgrade-line/graders/schema.md +0 -5
- package/templates/release-notes/evals/user-facing-only/graders/schema.md +0 -5
|
@@ -1,22 +1,37 @@
|
|
|
1
1
|
import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
|
|
2
2
|
import { createModels } from "@earendil-works/pi-ai/models";
|
|
3
|
-
import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
4
|
-
import {
|
|
3
|
+
import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID, ToolTask } from "@earendil-works/pi-durable";
|
|
4
|
+
import { modelPortFor, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
|
|
5
5
|
import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
|
|
6
|
-
import {
|
|
6
|
+
import { turnEndedOnAsk } from "../store-reads/journal.js";
|
|
7
|
+
import { CAP_WRAPUP, COMPUTER_NOTE, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
|
|
7
8
|
import { raiseFollowUpId } from "../run-view.js";
|
|
8
9
|
import { durableWait } from "../workflow/pi-versions.js";
|
|
9
10
|
/** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
|
|
10
|
-
* takeover's note, its computer's hold, the learning seed it laid): read past when a claim asks
|
|
11
|
-
* on its end (a fresh reopen). */
|
|
12
|
-
const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
|
|
11
|
+
* takeover's note, its computer's hold, the learning seed it laid, the computer it made): read past when a claim asks
|
|
12
|
+
* whether the run's root ends on its end (a fresh reopen). */
|
|
13
|
+
const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, KINDS.computerMade, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
|
|
14
|
+
/** A learned workflow's handback is the server's message to the agent, never the person's. */
|
|
15
|
+
const HANDED_BACK_ORIGIN = { kind: "server", reason: "handed_back" };
|
|
13
16
|
/** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
|
|
14
17
|
const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
|
|
18
|
+
/** The output contract's one retry turn is the server's message too, under one request id per run: pi places it once from
|
|
19
|
+
* its submission, a CLI's record writes it once, and a claim that finds it on the record never asks again. */
|
|
20
|
+
const OUTPUT_RETRY_ORIGIN = { kind: "server", reason: "output_retry" };
|
|
21
|
+
const OUTPUT_RETRY_REQUEST = "agentrun:output-retry";
|
|
22
|
+
/** Whether the run had its one retry: the input entry the retry wrote (pi's submission, a CLI's record) with the model's
|
|
23
|
+
* answer after it. One written and never answered (a runner lost between a CLI's record and its send) is not had: the
|
|
24
|
+
* claim that opens the session again sends it, under the same request id, so it is written once. */
|
|
25
|
+
const outputRetried = (entries) => {
|
|
26
|
+
const at = entries.findLastIndex((entry) => entry.kind === KINDS.input && originOf(entry.data?.origin)?.reason === OUTPUT_RETRY_ORIGIN.reason);
|
|
27
|
+
return at >= 0 && entries.slice(at + 1).some((entry) => entry.kind === "pi.assistant" || (entry.kind === KINDS.message && entry.data?.role === "model"));
|
|
28
|
+
};
|
|
15
29
|
import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
|
|
16
30
|
import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
|
|
17
31
|
import { ADAPTER_API } from "../turn-end.js";
|
|
18
|
-
import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
|
|
19
|
-
import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
|
|
32
|
+
import { answerText, REFLECT_NOTE_ONLY, REFLECT_PREFIX, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
|
|
33
|
+
import { approvalOf, BOOKING_WRITE_MS, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, PARK_SIBLINGS_MS, readAgain, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
|
|
34
|
+
import { outputMiss, outputRetryWords } from "../answer-json.js";
|
|
20
35
|
import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
|
|
21
36
|
import { isComputerCommand, journalHold } from "./computer-journal.js";
|
|
22
37
|
import { isHeldCommand, journalHeld } from "./held-run.js";
|
|
@@ -26,22 +41,63 @@ import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
|
|
|
26
41
|
import { channelCallOf, runChannelCall } from "./computer-channel.js";
|
|
27
42
|
import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
|
|
28
43
|
import { journalSessions } from "./sessions.js";
|
|
29
|
-
import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal,
|
|
44
|
+
import { DECISION_SESSION, FIT_TOLERANCE, freeModel, freeRequestsIn, freeWrapUpDue, freeWrapUpWords, noteFor, overCapOf, paidRefusal, requestFigures, runCap, SERVER_NOTE_LABEL, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
30
45
|
import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
|
|
31
46
|
import { bookedIn } from "../paid-calls.js";
|
|
32
|
-
import { withHostCalls } from "../host-calls.js";
|
|
33
47
|
import { sideEffect } from "./side-effects.js";
|
|
34
48
|
import { McpClaimRefused } from "./mcp-claim.js";
|
|
49
|
+
import { CODEMODE, defersCatalog, isCatalogWire, TOOLS_CALL, TOOLS_SEARCH } from "@parcha/agentrun-kernel";
|
|
50
|
+
import { metaTools } from "./meta-tools.js";
|
|
51
|
+
import { builtinHarness } from "../harness-table.js";
|
|
35
52
|
import { Fenced } from "../store/index.js";
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
53
|
+
import { answerAsServed } from "../answer-json.js";
|
|
54
|
+
import { reserveFor, stepAndAnswerFor, wrappingUp, wrapUpText } from "../wrap-up.js";
|
|
55
|
+
import { LEARNED_CARD_FIELDS, LEARNED_CLIP, LEARNED_WORKFLOW_TOOL, learnedApprovedTools } from "../learned-workflow.js";
|
|
56
|
+
import { feedbackAsk, feedbackOf, pendingFeedbackOf } from "./feedback-round.js";
|
|
57
|
+
import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
|
|
38
58
|
/** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
|
|
39
59
|
* and the harness's next call runs it. */
|
|
40
60
|
export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
|
|
41
61
|
/** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
|
|
42
62
|
export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
|
|
63
|
+
/** An asked call's card: the gate's own fields (`shown`) first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES)
|
|
64
|
+
* still names them whatever the input's size, then the call's input, which the model wrote, without any field of
|
|
65
|
+
* theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's. */
|
|
66
|
+
function cardOf(tool, shown, args) {
|
|
67
|
+
if (!shown && tool !== LEARNED_WORKFLOW_TOOL)
|
|
68
|
+
return args;
|
|
69
|
+
return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
|
|
70
|
+
}
|
|
43
71
|
/** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
|
|
44
72
|
const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
|
|
73
|
+
/** What a CLI's request held at a cut turn (TurnCut) is refused with: the turn ended at the person's question. */
|
|
74
|
+
const TURN_CUT_AT_QUESTION = "the turn ended at its question to the person";
|
|
75
|
+
function turnCut() {
|
|
76
|
+
let armedAt;
|
|
77
|
+
let ask;
|
|
78
|
+
let asked = new Promise((resolve) => (ask = resolve));
|
|
79
|
+
const held = [];
|
|
80
|
+
return {
|
|
81
|
+
arm: (callId) => void (armedAt = callId),
|
|
82
|
+
disarm: () => void (armedAt = undefined),
|
|
83
|
+
get armed() {
|
|
84
|
+
return armedAt !== undefined;
|
|
85
|
+
},
|
|
86
|
+
hold() {
|
|
87
|
+
ask();
|
|
88
|
+
return new Promise((_, reject) => held.push(reject));
|
|
89
|
+
},
|
|
90
|
+
get asked() {
|
|
91
|
+
return asked;
|
|
92
|
+
},
|
|
93
|
+
done() {
|
|
94
|
+
armedAt = undefined;
|
|
95
|
+
for (const reject of held.splice(0))
|
|
96
|
+
reject(new Error(TURN_CUT_AT_QUESTION));
|
|
97
|
+
asked = new Promise((resolve) => (ask = resolve));
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
45
101
|
/** A HostLifecycle and the ToolHost members that fill it: what a spec's ToolHost takes, and hands the loop. */
|
|
46
102
|
export function hostLifecycle() {
|
|
47
103
|
const onConversation = [];
|
|
@@ -96,10 +152,17 @@ export function pendingPauseOf(entries) {
|
|
|
96
152
|
}
|
|
97
153
|
/** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
|
|
98
154
|
const DELIVER_NOW_MS = 5_000;
|
|
99
|
-
/** How long the
|
|
100
|
-
* may take it. A request that leaves before its admission gives it back as it goes
|
|
101
|
-
* only the backstop for a path that never does. A proxy's token count and admission
|
|
155
|
+
/** How long a server note (the replaced computer's, a wrap-up), once a request took it, waits for that request's
|
|
156
|
+
* admission before a later request may take it. A request that leaves before its admission gives it back as it goes
|
|
157
|
+
* (ModelPort.noteReturned): this is only the backstop for a path that never does. A proxy's token count and admission
|
|
158
|
+
* take well under it. Once admitted, the request holds the note until it ends, however long it streams. */
|
|
102
159
|
const WRAP_UP_OFFER_MS = 30_000;
|
|
160
|
+
/** A note the model was told (it begins with SERVER_NOTE_LABEL) as the server's row for it says it: the words after the
|
|
161
|
+
* label, their first letter a capital, since the row is the server's already ("AgentRun: …", timeline.ts CAP_WRAPUP). */
|
|
162
|
+
const rowWords = (told) => {
|
|
163
|
+
const words = told.startsWith(SERVER_NOTE_LABEL) ? told.slice(SERVER_NOTE_LABEL.length) : told;
|
|
164
|
+
return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
|
|
165
|
+
};
|
|
103
166
|
/** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
|
|
104
167
|
const cutWhole = (text, max) => {
|
|
105
168
|
const cut = text.slice(0, max);
|
|
@@ -157,19 +220,23 @@ export function bookingOfAnswer(records, given) {
|
|
|
157
220
|
turns.push(turn.turn);
|
|
158
221
|
if (side.has(turn.turn))
|
|
159
222
|
continue;
|
|
160
|
-
//
|
|
161
|
-
|
|
223
|
+
// By the kernel's one rule (turnCostOf): an answer with no price of its own is unknown, never the hold it was booked at
|
|
224
|
+
// for the cap; one billed to a person's plan is $0 to the run.
|
|
225
|
+
const figure = turn.usd === undefined && turn.bookedUsd === undefined ? undefined : turnCostOf(turn).usd;
|
|
162
226
|
usd = usd !== null && typeof figure === "number" && Number.isFinite(figure) ? (usd ?? 0) + figure : null;
|
|
163
227
|
}
|
|
164
228
|
return { turns, usd };
|
|
165
229
|
}
|
|
230
|
+
/** How often a park's wait for the calls beside it (siblingsSettled) reads whether they ended. */
|
|
231
|
+
const SIBLINGS_POLL_MS = 50;
|
|
166
232
|
/** A host check's refusal as the cap's rule reads it (AdapterRunSpec.cap.park). */
|
|
167
233
|
const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forGood ?? true, ...(refusal.figures ? { figures: refusal.figures } : {}) });
|
|
168
234
|
/** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
|
|
169
235
|
* fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
|
|
170
236
|
* it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
|
|
171
|
-
* message's timestamp: the Timeline dates its rows by them.
|
|
172
|
-
|
|
237
|
+
* message's timestamp: the Timeline dates its rows by them. `endsItsCalls`: a harness that says each call's end itself
|
|
238
|
+
* (pi, of the calls its tools nest: it reruns a replay-safe one a crash cut), so none is ended interrupted here. */
|
|
239
|
+
async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls = false) {
|
|
173
240
|
const root = await harness.root(context);
|
|
174
241
|
const append = async (kind, data) => {
|
|
175
242
|
await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
|
|
@@ -182,6 +249,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
182
249
|
await tx.appendEntry(root.id, { kind: KINDS.turnStart, data: { at: now() } });
|
|
183
250
|
}, context);
|
|
184
251
|
turnsOpen += 1;
|
|
252
|
+
lastAsked = undefined;
|
|
185
253
|
};
|
|
186
254
|
// Each call started on the record: whether it has its end; and each end, by call id.
|
|
187
255
|
const started = new Map();
|
|
@@ -190,6 +258,14 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
190
258
|
// is never ended interrupted; it waits for its answer, which ends it (run once, refused, or withdrawn).
|
|
191
259
|
const parked = new Set();
|
|
192
260
|
const sent = new Set();
|
|
261
|
+
// A call of a tool that only nests calls (its start marked `nests`): never ended interrupted, as it runs again whole.
|
|
262
|
+
const nesting = new Set();
|
|
263
|
+
// The call of the harness's own each call runs inside (nestedIn), named on the call's start.
|
|
264
|
+
const parents = new Map();
|
|
265
|
+
const parentOf = (callId) => {
|
|
266
|
+
const parent = parents.get(callId);
|
|
267
|
+
return parent === undefined ? {} : { parent };
|
|
268
|
+
};
|
|
193
269
|
// The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
|
|
194
270
|
const sending = new Set();
|
|
195
271
|
let personWritten = false;
|
|
@@ -198,18 +274,29 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
198
274
|
// The request ids of the follow-ups written (followUp): each is written once.
|
|
199
275
|
const followUps = new Set();
|
|
200
276
|
// Each end-of-run turn's prompt the record wrote as it asked the turn, by its request id: a turn asked again (a later
|
|
201
|
-
// claim, after a crash in the turn) reuses it, never writes a second.
|
|
277
|
+
// claim, after a crash in the turn) reuses it, never writes a second. And what each kept as it was first asked.
|
|
202
278
|
const askedAt = new Map();
|
|
279
|
+
const askedKept = new Map();
|
|
280
|
+
// The end-of-run turn asked last, while no turn of the job's (its input, a message, a follow-up) opened after it.
|
|
281
|
+
let lastAsked;
|
|
203
282
|
for (const entry of await entriesOf(journal, root.id, context)) {
|
|
204
283
|
const data = (entry.data ?? {});
|
|
205
284
|
if (entry.kind === KINDS.messageSending && typeof data.commandId === "number")
|
|
206
285
|
sending.add(data.commandId);
|
|
207
|
-
if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string")
|
|
286
|
+
if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string") {
|
|
208
287
|
askedAt.set(data.requestId, entry.id);
|
|
288
|
+
lastAsked = data.requestId;
|
|
289
|
+
if (data.kept && typeof data.kept === "object" && !Array.isArray(data.kept))
|
|
290
|
+
askedKept.set(data.requestId, data.kept);
|
|
291
|
+
}
|
|
292
|
+
if (entry.kind === KINDS.turnStart || (entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
|
|
293
|
+
lastAsked = undefined;
|
|
209
294
|
if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
|
|
210
295
|
ends.set(data.callId, { status: data.status ?? "done", ...(typeof data.output === "string" ? { output: data.output } : {}) });
|
|
211
296
|
if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.parked === true)
|
|
212
297
|
parked.add(data.callId);
|
|
298
|
+
if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.nests === true)
|
|
299
|
+
nesting.add(data.callId);
|
|
213
300
|
if (entry.kind === KINDS.callSent && typeof data.callId === "string")
|
|
214
301
|
sent.add(data.callId);
|
|
215
302
|
if (entry.kind === KINDS.callStart && typeof data.callId === "string")
|
|
@@ -226,7 +313,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
226
313
|
followUps.add(data.requestId);
|
|
227
314
|
}
|
|
228
315
|
for (const [callId, ended] of started) {
|
|
229
|
-
if (ended || (parked.has(callId) && !sent.has(callId)))
|
|
316
|
+
if (endsItsCalls || ended || (parked.has(callId) && !sent.has(callId)) || nesting.has(callId))
|
|
230
317
|
continue;
|
|
231
318
|
await append(KINDS.callEnd, { callId, status: "interrupted" });
|
|
232
319
|
started.set(callId, true);
|
|
@@ -280,6 +367,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
280
367
|
await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
|
|
281
368
|
else
|
|
282
369
|
await append(KINDS.message, { role: "person", text: input });
|
|
370
|
+
lastAsked = undefined;
|
|
283
371
|
personWritten = true;
|
|
284
372
|
}),
|
|
285
373
|
input: (input, origin, opens = true) => inTurn(async () => {
|
|
@@ -290,6 +378,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
290
378
|
await startsTurn({ entry });
|
|
291
379
|
else
|
|
292
380
|
await harness.commit((tx) => tx.appendEntry(root.id, entry), context);
|
|
381
|
+
lastAsked = undefined;
|
|
293
382
|
personWritten = true;
|
|
294
383
|
}),
|
|
295
384
|
followUp: (input, requestId, origin) => inTurn(async () => {
|
|
@@ -327,7 +416,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
327
416
|
});
|
|
328
417
|
return again;
|
|
329
418
|
},
|
|
330
|
-
async start(callId, tool, input, replaySafe) {
|
|
419
|
+
async start(callId, tool, input, replaySafe, nests) {
|
|
331
420
|
await flushText();
|
|
332
421
|
await inTurn(async () => {
|
|
333
422
|
if (started.has(callId)) {
|
|
@@ -338,16 +427,18 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
338
427
|
}
|
|
339
428
|
return;
|
|
340
429
|
}
|
|
341
|
-
await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(cwd ? { cwd } : {}) });
|
|
430
|
+
await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(nests ? { nests } : {}), ...parentOf(callId), ...(cwd ? { cwd } : {}) });
|
|
342
431
|
started.set(callId, false);
|
|
432
|
+
if (nests)
|
|
433
|
+
nesting.add(callId);
|
|
343
434
|
});
|
|
344
435
|
},
|
|
345
|
-
async park(callId, tool, input, replaySafe
|
|
436
|
+
async park(callId, tool, input, replaySafe) {
|
|
346
437
|
await flushText();
|
|
347
438
|
await inTurn(async () => {
|
|
348
439
|
if (started.has(callId))
|
|
349
440
|
return;
|
|
350
|
-
await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(
|
|
441
|
+
await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...parentOf(callId), ...(cwd ? { cwd } : {}) });
|
|
351
442
|
started.set(callId, false);
|
|
352
443
|
parked.add(callId);
|
|
353
444
|
});
|
|
@@ -358,7 +449,7 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
358
449
|
if (started.get(callId) === true)
|
|
359
450
|
return;
|
|
360
451
|
const at = now();
|
|
361
|
-
const start = { callId, tool, input, replaySafe, at };
|
|
452
|
+
const start = { callId, tool, input, replaySafe, ...parentOf(callId), at };
|
|
362
453
|
const end = { callId, status: "refused", output: words, at };
|
|
363
454
|
await harness.commit(async (tx) => {
|
|
364
455
|
if (!started.has(callId))
|
|
@@ -369,7 +460,9 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
369
460
|
ends.set(callId, { status: "refused", output: words });
|
|
370
461
|
});
|
|
371
462
|
},
|
|
463
|
+
nestedIn: (callId, parent) => void parents.set(callId, parent),
|
|
372
464
|
unsentParked: () => [...parked].filter((callId) => !sent.has(callId) && started.get(callId) === false),
|
|
465
|
+
openNests: () => [...nesting].filter((callId) => started.get(callId) === false),
|
|
373
466
|
noteEnd(callId, status, output) {
|
|
374
467
|
started.set(callId, true);
|
|
375
468
|
ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
|
|
@@ -382,18 +475,29 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
382
475
|
started.set(callId, true);
|
|
383
476
|
ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
|
|
384
477
|
}),
|
|
385
|
-
answering: (requestId, prompt) => {
|
|
478
|
+
answering: async (requestId, prompt, keep) => {
|
|
386
479
|
answer = "";
|
|
387
|
-
|
|
480
|
+
await inTurn(async () => {
|
|
388
481
|
if (askedAt.has(requestId))
|
|
389
482
|
return;
|
|
390
483
|
await harness.commit(async (tx) => {
|
|
391
484
|
if (await tx.submissionByRequest(root.id, requestId))
|
|
392
485
|
return;
|
|
393
|
-
|
|
486
|
+
// What the step keeps as the turn is first asked, with its prompt: durable before the turn's first request leaves
|
|
487
|
+
// (that request's flush), so a later claim that asks the turn again reads the first ask's, never its own.
|
|
488
|
+
const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId, ...(keep ? { kept: keep } : {}) }, model: [{ role: "user", content: prompt, timestamp: now() }] });
|
|
394
489
|
askedAt.set(requestId, asked.id);
|
|
490
|
+
lastAsked = requestId;
|
|
491
|
+
if (keep)
|
|
492
|
+
askedKept.set(requestId, keep);
|
|
395
493
|
}, context);
|
|
396
494
|
});
|
|
495
|
+
return askedKept.get(requestId);
|
|
496
|
+
},
|
|
497
|
+
keptOf: (requestId) => askedKept.get(requestId),
|
|
498
|
+
async lookingBack() {
|
|
499
|
+
const requestId = lastAsked;
|
|
500
|
+
return requestId !== undefined && !(await harness.commit((tx) => tx.submissionByRequest(root.id, requestId), context));
|
|
397
501
|
},
|
|
398
502
|
answered: (requestId, prompt, status) => inTurn(async () => {
|
|
399
503
|
const said = answer ?? "";
|
|
@@ -453,6 +557,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
453
557
|
void stopping.then(() => stopAbort.abort(new Error("the run was stopped")));
|
|
454
558
|
let parked = () => { };
|
|
455
559
|
const parking = new Promise((resolve) => (parked = resolve));
|
|
560
|
+
/** The claim is parking: it waits for the calls already running beside the parked one (siblingsSettled), and no call
|
|
561
|
+
* starts meanwhile, nor is an answer taken (it waits for the next claim, as once the journal is sealed). */
|
|
562
|
+
let parkPending = false;
|
|
563
|
+
/** The calls this claim parked the run on (their ask landed with the run parked): what siblingsSettled waits beside. */
|
|
564
|
+
const parkedCalls = new Set();
|
|
456
565
|
let finished;
|
|
457
566
|
let gate;
|
|
458
567
|
let harness;
|
|
@@ -499,9 +608,18 @@ function adapterLoop(specOf, options, deps) {
|
|
|
499
608
|
};
|
|
500
609
|
/** The current pass's spec's release, until it is called (closeSession). */
|
|
501
610
|
let releaseNow;
|
|
502
|
-
/**
|
|
503
|
-
|
|
611
|
+
/** The current pass ended in a park that keeps its computer (keepAtPark), for this cause, until its release reads it. */
|
|
612
|
+
let parkedNow;
|
|
613
|
+
/** From the end-of-run step's start (or a claim that found its turn open: lookingBackOpen, from its session's open)
|
|
614
|
+
* until the claim ends: a steer is left for the end, writes and edits under work/.learning/ are refused
|
|
615
|
+
* (REFLECT_NOTE_ONLY), and every request is learning's, never the job's: the cap's wrap-up note is never told to it,
|
|
616
|
+
* and a refusal of one never parks the run (learningRefused). Held between the step's asks too: a turn a takeover
|
|
617
|
+
* resumed may send its next request while the step still reads an earlier answer. */
|
|
504
618
|
let reflecting = false;
|
|
619
|
+
/** A cap refusal of a request of the end-of-run turn, until that turn's ask reads it: the run has answered, so it parks
|
|
620
|
+
* nothing; the ask fails in the refusal's words, and the learning is dropped as the cap's short room drops it
|
|
621
|
+
* (reflect-hook.ts CAP_REFUSAL: no_budget). An answered run never parks on learning spend. */
|
|
622
|
+
let learningRefused;
|
|
505
623
|
/** While the run's end waits for a person to hand its desktop or phone back (#2134): a steer is left for the end, as
|
|
506
624
|
* in the end-of-run turn, so no turn starts that the end, written after the hand-back, would cut. */
|
|
507
625
|
let handingBack = false;
|
|
@@ -511,6 +629,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
511
629
|
* Also set while the run waits in its claim on the person's answer to its question (waitInClaim): their message is sent
|
|
512
630
|
* the same way, as the claim's next turn, and `placed` wakes the wait once it is sent. */
|
|
513
631
|
let reopen;
|
|
632
|
+
/** A grade's feedback round this claim closes (runner/feedback-round.ts): the run opened again on a grade's words (its
|
|
633
|
+
* steer, taken with a FEEDBACK entry and never sent as a turn), or a claim that finds such an entry with no end after it.
|
|
634
|
+
* The agent is asked no turn of the job's: the run goes to its end-of-run turn, told the grade first (feedbackAsk). */
|
|
635
|
+
let feedbackNow;
|
|
514
636
|
/** A reopen of a run whose session is still new (a person stopped it before its first input was sent): resolved once the
|
|
515
637
|
* person's message is placed as that first input. The claim waits on it, never sending the input they stopped, however
|
|
516
638
|
* late the runner hands the message over. */
|
|
@@ -525,6 +647,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
525
647
|
let waitHolds = [];
|
|
526
648
|
/** The wait's own `reopen`, while it is set. */
|
|
527
649
|
let waitTurn;
|
|
650
|
+
/** The `reopen` of a CLI run parked on its question (its turn cut there: no steer reaches its idle session), while it is
|
|
651
|
+
* set: the person's answer is the claim's turn, and a trigger's message is no answer. */
|
|
652
|
+
let askReopen;
|
|
528
653
|
/** 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
|
|
529
654
|
* answer to a question that landed between the question's turn end and the wait's start. The wait takes it as its
|
|
530
655
|
* answer (waitInClaim), once. */
|
|
@@ -542,6 +667,14 @@ function adapterLoop(specOf, options, deps) {
|
|
|
542
667
|
/** Set once the claim's last turn has ended and nothing more is sent: a message after it waits for the run's end, as one
|
|
543
668
|
* during the end-of-run turn does. */
|
|
544
669
|
let turnsOver = false;
|
|
670
|
+
/** While the run's learned workflow runs first (AdapterRunSpec.workflowFirst): a message waits for it, then goes the way
|
|
671
|
+
* any message goes once the workflow answered (the run is ending) or handed the job back (the agent's turn runs). */
|
|
672
|
+
let servingFirst;
|
|
673
|
+
/** The messages waiting for the run's first input (steer: the session still new, or its learned workflow running first),
|
|
674
|
+
* placed one after another, in the order they came, once it is sent; `waitingFirst` counts those not placed yet, so a
|
|
675
|
+
* message after them waits its turn behind them. */
|
|
676
|
+
let afterFirst = Promise.resolve();
|
|
677
|
+
let waitingFirst = 0;
|
|
545
678
|
/** The wait in the claim is over (an answer placed, a lapse, the run's end, park, restart or loss): its holds go. `of`:
|
|
546
679
|
* only while it is that wait's (a wait that settles late never ends a later one). */
|
|
547
680
|
const endWait = (of) => {
|
|
@@ -561,11 +694,29 @@ function adapterLoop(specOf, options, deps) {
|
|
|
561
694
|
};
|
|
562
695
|
/** The claim's CLI record (record: "loop"), for the end-of-run turn's answer; undefined for an adapter keeping its own. */
|
|
563
696
|
let cliRecord;
|
|
697
|
+
/** The writes of the harness's own calls (SessionIO.ownCalls) not yet settled: the run's end waits for them, so it never
|
|
698
|
+
* closes interrupted an exec whose own end is on its way. */
|
|
699
|
+
const ownWrites = new Set();
|
|
700
|
+
const ownWrite = (write) => {
|
|
701
|
+
ownWrites.add(write);
|
|
702
|
+
const settled = () => void ownWrites.delete(write);
|
|
703
|
+
write.then(settled, settled);
|
|
704
|
+
return write;
|
|
705
|
+
};
|
|
706
|
+
/** A CLI's turn cut at its question to the person (TurnCut): armed by the call's end, asked for by the next request. */
|
|
707
|
+
const askCut = turnCut();
|
|
708
|
+
/** Whether this loop sent the run its output retry (sendOutputRetry): never a second, even when its turn gave no answer. */
|
|
709
|
+
let outputRetrySent = false;
|
|
564
710
|
/** The session's paid requests admitted and not yet booked (its model port's beforeRequest, then its afterRequest), and
|
|
565
711
|
* who waits for none: the run's end waits for them, since a booking written after the end (the run's release) is
|
|
566
712
|
* fenced and lost, and its request read back at its hold. */
|
|
567
713
|
let unbooked = 0;
|
|
568
714
|
let bookedAll = [];
|
|
715
|
+
/** Of those, the ones whose booking has begun (the request answered or ended, its runner.turn on its way to the
|
|
716
|
+
* store), and who waits for none: a booking under way is waited for past CLOSE_MS (bookingsSettled), so a busy store
|
|
717
|
+
* never lets the end, or an answer's cost, go ahead of it. */
|
|
718
|
+
let bookingsWriting = 0;
|
|
719
|
+
let writtenAll = [];
|
|
569
720
|
/** The raises this claim has: the state the ones before left (the kernel cap's takeRaises, in arrival order), the rows
|
|
570
721
|
* to take in the raise entry's commit, whether any resumes a paused run, and the budget it answered. */
|
|
571
722
|
const raising = { takes: [], resumes: false, resuming: false };
|
|
@@ -580,13 +731,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
580
731
|
/** The pass's MCP (spec.mcp), until the pass ends; and whether a command row came since its credentials were last made
|
|
581
732
|
* fresh (a parked token may have expired meanwhile). */
|
|
582
733
|
let mcp;
|
|
583
|
-
/** The calls of this run a person
|
|
584
|
-
*
|
|
585
|
-
const
|
|
586
|
-
/** Each answered call's ask as journaled (the card the person saw), set by answerOf as it reads or writes the answer. */
|
|
587
|
-
const askedArgs = new Map();
|
|
588
|
-
/** An MCP tool of the run as the claim's pass wrapped it, by its catalog name (set once its tools are wrapped). */
|
|
589
|
-
let mcpHosted = () => undefined;
|
|
734
|
+
/** The calls of this run a person was asked about (their ask in the journal, on this claim or read on a resume), set as
|
|
735
|
+
* the ask is read: one of them the gate lets through was let through by a person's answer. */
|
|
736
|
+
const askedCalls = new Set();
|
|
590
737
|
let mcpStale = false;
|
|
591
738
|
/** Marks the raise's follow-up the server's (MESSAGE_ORIGIN, timeline/origin.ts) before it is sent: its own commit, the
|
|
592
739
|
* input's user entry left as pi writes it (its submission, which a re-claim answers from, unchanged), so the Timeline
|
|
@@ -817,13 +964,36 @@ function adapterLoop(specOf, options, deps) {
|
|
|
817
964
|
if (data.capUsd > 0)
|
|
818
965
|
raisedCapUsd = data.capUsd;
|
|
819
966
|
}
|
|
967
|
+
const over = () => (finished ?? new Promise(() => { })).then(() => undefined, () => undefined);
|
|
820
968
|
const steer = async (command) => {
|
|
821
969
|
// Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
|
|
822
970
|
// Awaited even with a session there: until the claim is ready it has not said whether this message reopens the run.
|
|
823
|
-
const over = () => (finished ?? new Promise(() => { })).then(() => undefined, () => undefined);
|
|
824
971
|
await Promise.race([ready, over()]);
|
|
825
972
|
// The session never opened, or the run is parking or stopping (its journal sealed, its session closed): left
|
|
826
973
|
// untaken for the next claim, which hands it on again; never refused for good.
|
|
974
|
+
if (!gate || !session || gate.sealed)
|
|
975
|
+
return { later: "the run is parking: the steer waits for its resume" };
|
|
976
|
+
// The session is still new and this is no reopen's message (the claim has yet to send the run's input), or the run's
|
|
977
|
+
// learned workflow runs first, or a message before it still waits for either: it waits for the input, off the runner's
|
|
978
|
+
// delivery, as a computer channel's call does (channelCommand). The runner hands the run's rows on one at a time, each
|
|
979
|
+
// once the one before it answered: held here for a workflow that runs long, this message would hold every row after it,
|
|
980
|
+
// and a person's stop or cancel (the stop that cuts the workflow's call, its spend and custody), a raise or a hand-back
|
|
981
|
+
// would never reach the run. `taken` here means its take rides on the commit that places it once the input is sent; a
|
|
982
|
+
// claim that ends first (a stop, a park, the workflow's answer) leaves the row untaken, for the run's end or its next
|
|
983
|
+
// claim to settle, as any message the run's end finds untaken.
|
|
984
|
+
if (waitingFirst > 0 || (!reopen && session.state === "new") || servingFirst) {
|
|
985
|
+
waitingFirst += 1;
|
|
986
|
+
const placing = afterFirst.then(() => placeSteer(command));
|
|
987
|
+
afterFirst = placing.then(() => void (waitingFirst -= 1), (error) => {
|
|
988
|
+
waitingFirst -= 1;
|
|
989
|
+
console.warn(`[runner] a message that waited for the run's first input was not placed: ${said(error)}`);
|
|
990
|
+
});
|
|
991
|
+
return { taken: true };
|
|
992
|
+
}
|
|
993
|
+
return placeSteer(command);
|
|
994
|
+
};
|
|
995
|
+
/** A person's message placed (steer): as the run's next turn, into the turn in flight, or after it. */
|
|
996
|
+
const placeSteer = async (command) => {
|
|
827
997
|
if (!gate || !session || gate.sealed)
|
|
828
998
|
return { later: "the run is parking: the steer waits for its resume" };
|
|
829
999
|
// The session is still new and this is no reopen's message: the claim has yet to send the run's input. Placed now,
|
|
@@ -834,6 +1004,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
834
1004
|
if (!gate || !session || gate.sealed)
|
|
835
1005
|
return { later: "the run is parking: the steer waits for its resume" };
|
|
836
1006
|
}
|
|
1007
|
+
// The run's learned workflow is running first: nothing is sent to the agent until it answered or handed the job back.
|
|
1008
|
+
if (servingFirst)
|
|
1009
|
+
await servingFirst;
|
|
1010
|
+
if (!gate || !session || gate.sealed)
|
|
1011
|
+
return { later: "the run is parking: the steer waits for its resume" };
|
|
837
1012
|
// 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
|
|
838
1013
|
// to answer. Left untaken, the run's end opens a completed run again with it as a new turn (store run-patch.ts
|
|
839
1014
|
// refuseLeftovers).
|
|
@@ -850,15 +1025,40 @@ function adapterLoop(specOf, options, deps) {
|
|
|
850
1025
|
// first. It is an await, so a wait may start meanwhile: every path below is chosen after it, with nothing awaited
|
|
851
1026
|
// between that choice and the message's placing.
|
|
852
1027
|
const reopenedBefore = reopen;
|
|
853
|
-
const endedOnAsk = session.state === "idle" && root !== undefined &&
|
|
1028
|
+
const endedOnAsk = session.state === "idle" && root !== undefined && turnEndedOnAsk((await entriesOf(gate.journal, root.id, context))) !== undefined;
|
|
854
1029
|
const askedLast = !reopenedBefore && endedOnAsk;
|
|
1030
|
+
// A reopen of a run its learned workflow answered alone (its session new: the agent never took the job): what the
|
|
1031
|
+
// workflow answered, said to the agent between the job and the message, which is a word on that answer.
|
|
1032
|
+
const servedAnswer = reopen && !reopen.sent && session.state === "new" && root !== undefined ? servedAnswerOf(await entriesOf(gate.journal, root.id, context)) : undefined;
|
|
855
1033
|
if (!gate || !session || gate.sealed)
|
|
856
1034
|
return { later: "the run is parking: the steer waits for its resume" };
|
|
857
1035
|
// A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
|
|
858
|
-
// between the question's turn end and that wait): never the wait's answer, never placed
|
|
859
|
-
//
|
|
860
|
-
|
|
861
|
-
|
|
1036
|
+
// between the question's turn end and that wait): never the wait's answer, never placed now. Its firing reads sent (the
|
|
1037
|
+
// door took the row), so it is never refused either: left untaken, it runs as a turn of its own after the person's
|
|
1038
|
+
// answer, as a parked run's does (the store's park takes no wake from it; the run's end opens the run again with it).
|
|
1039
|
+
if (followUp && (askedLast || (reopen !== undefined && (reopen === waitTurn || reopen === askReopen))))
|
|
1040
|
+
return { later: "the run is waiting on a person: the message runs as a turn of its own after the answer" };
|
|
1041
|
+
// A grade's feedback round (feedback-round.ts): the run opened again on the grade's words, which are never a turn of
|
|
1042
|
+
// the job's. Kept on the root as a FEEDBACK entry, whose commit takes the row; the claim goes to its end-of-run turn.
|
|
1043
|
+
const fed = reopen && !reopen.sent && (session.state === "idle" || session.state === "new") ? feedbackOf(command.body) : undefined;
|
|
1044
|
+
if (fed && reopen && harness && root) {
|
|
1045
|
+
const [on, theRoot, mine] = [harness, root, reopen];
|
|
1046
|
+
const taken = gate.expect(writesEntry(KINDS.feedback, (data) => data.requestId === requestId), { take: [command.id] });
|
|
1047
|
+
taken.catch(() => undefined);
|
|
1048
|
+
mine.feedback = fed;
|
|
1049
|
+
mine.sent = on.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.feedback, data: { ...fed, requestId, at: now() } }), context).then(() => undefined);
|
|
1050
|
+
mine.placed?.();
|
|
1051
|
+
try {
|
|
1052
|
+
await mine.sent;
|
|
1053
|
+
}
|
|
1054
|
+
catch (error) {
|
|
1055
|
+
if (gate.sealed)
|
|
1056
|
+
return { later: "the run is parking: the feedback waits for its resume" };
|
|
1057
|
+
return { refused: `the feedback was not kept: ${error.message}` };
|
|
1058
|
+
}
|
|
1059
|
+
await taken.catch(() => { });
|
|
1060
|
+
return { taken: true };
|
|
1061
|
+
}
|
|
862
1062
|
// 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
|
|
863
1063
|
// follow-up are), its row taken in its submission's commit; the claim waits on it before the run's next end.
|
|
864
1064
|
if (reopen && !reopen.sent && (session.state === "idle" || session.state === "new")) {
|
|
@@ -872,7 +1072,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
872
1072
|
// never sent, or answered, as a turn of its own.
|
|
873
1073
|
const first = theSession.state === "new" ? specNow : undefined;
|
|
874
1074
|
const sendId = first ? INPUT_REQUEST : requestId;
|
|
875
|
-
|
|
1075
|
+
// A run its learned workflow answered alone: the job, what the workflow answered (cut of the runner's secrets, as a
|
|
1076
|
+
// handback is), then the message.
|
|
1077
|
+
const answered = first && servedAnswer ? servedAnswerText(servedAnswer.workflow, deps.redact ? deps.redact(servedAnswer.answer) : servedAnswer.answer) : undefined;
|
|
1078
|
+
const content = first ? [first.input, ...(answered ? [answered] : []), text].join("\n\n") : text;
|
|
876
1079
|
// The row is taken only once the session holds the prompt: pi's in its submission's commit; a CLI's (whose harness
|
|
877
1080
|
// writes no submission) in the record's follow-up entry, written right after the send, as sendAfterTurn takes its
|
|
878
1081
|
// row. A runner lost between the send and that entry leaves the row untaken, so the next claim sends it again: a
|
|
@@ -974,6 +1177,19 @@ function adapterLoop(specOf, options, deps) {
|
|
|
974
1177
|
await cliRecord?.message(next.text, next.origin);
|
|
975
1178
|
return session.turnEnd();
|
|
976
1179
|
};
|
|
1180
|
+
/** The output contract's one retry (AdapterRunSpec.outputSchema): the server's message saying why the answer missed the
|
|
1181
|
+
* schema, sent as a turn of its own on the same session, its requests admitted and booked by the run's one cap as any
|
|
1182
|
+
* turn's. A CLI's record writes it first (once, under its request id); pi's submission carries its origin and is placed
|
|
1183
|
+
* once under that id. Sent at most once by this loop (outputRetrySent), and by a later claim only when the record has
|
|
1184
|
+
* it unanswered (outputRetried). Its turn's end is what this gives. */
|
|
1185
|
+
const sendOutputRetry = async (why) => {
|
|
1186
|
+
outputRetrySent = true;
|
|
1187
|
+
const text = outputRetryWords(deps.redact ? deps.redact(why) : why);
|
|
1188
|
+
await cliRecord?.followUp(text, OUTPUT_RETRY_REQUEST, OUTPUT_RETRY_ORIGIN);
|
|
1189
|
+
await session.send(text, { id: OUTPUT_RETRY_REQUEST, origin: OUTPUT_RETRY_ORIGIN });
|
|
1190
|
+
await specNow?.hooks?.afterMessageSent?.();
|
|
1191
|
+
return session.turnEnd();
|
|
1192
|
+
};
|
|
977
1193
|
async function run(claim) {
|
|
978
1194
|
context = withAbortSignal(deps.signal, BACKGROUND_CONTEXT);
|
|
979
1195
|
// Every row the runner read for this claim is with the loop once delivered resolves (at once without a runner's).
|
|
@@ -1031,35 +1247,32 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1031
1247
|
// What was spent beside them on the run's behalf (its spec's runCap.beside) is read with them at each admission
|
|
1032
1248
|
// (runBooking), the spec's once it is known.
|
|
1033
1249
|
const besideNow = async () => (specNow?.runCap?.beside ? await specNow.runCap.beside() : 0);
|
|
1034
|
-
const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush() }), { beside: besideNow });
|
|
1250
|
+
const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush(), claim }), { beside: besideNow });
|
|
1035
1251
|
let capBuilt;
|
|
1036
|
-
/**
|
|
1037
|
-
*
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1252
|
+
/** What the run keeps back beside a request of its own session while it streams (RunCapOptions.keepBackUsd), set
|
|
1253
|
+
* once the wrap-up's reserve is known (below): a tool call it makes mid-stream finds room for the steps after it. */
|
|
1254
|
+
let keepBackOf;
|
|
1255
|
+
/** The run's requests counted toward the free limit (free.ts freeRequestsIn) as of its last admission, in every
|
|
1256
|
+
* session: read from its records at the claim (below), then taken from each admission the cap judges, the count it
|
|
1257
|
+
* was judged with (runBooking's freeRequestsMade) and itself when it counts. Never a read of the run's records
|
|
1258
|
+
* between a request's admission and its leaving: that wait let a cancel close the session before the request was
|
|
1259
|
+
* booked, its cost left unknown. */
|
|
1260
|
+
let freeMade = 0;
|
|
1042
1261
|
const theCap = () => {
|
|
1043
1262
|
if (!specNow?.runCap)
|
|
1044
1263
|
throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
|
|
1045
1264
|
// The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
|
|
1046
|
-
// Its previous request is the session's own (requestEnded), unless the spec names one (a test's warm cache).
|
|
1047
1265
|
const { beside: _beside, ...config } = specNow.runCap;
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
if (!(usage.input >= 0 && cachedTokens >= 0 && usage.input + cachedTokens > 0))
|
|
1059
|
-
return;
|
|
1060
|
-
// A smaller request than the previous on the same model is a compaction or another conversation's (a child of the
|
|
1061
|
-
// run, whose requests the proxy cannot tell from the root's): history resets (previousAfter), never sticks.
|
|
1062
|
-
previous = previousAfter(previous, { model: asked.model, cachedTokens, inputTokens: usage.input, boundTokens: asked.bound, counted: asked.counted, endedAt: (specNow?.runCap?.now ?? Date.now)() });
|
|
1266
|
+
// runCap tells `judged` only the verdict a request goes by: a refusal that waits is asked again, told then, so a
|
|
1267
|
+
// request admitted after waiting sets freeMade from the count it was admitted at.
|
|
1268
|
+
const judged = (request, answer) => {
|
|
1269
|
+
config.judged?.(request, answer);
|
|
1270
|
+
if (request.freeRequestsMade !== undefined)
|
|
1271
|
+
freeMade = request.freeRequestsMade + (answer && !("refuse" in answer) && answer.freeRequest === true ? 1 : 0);
|
|
1272
|
+
};
|
|
1273
|
+
// A step waiting for room leaves once the run has a pause (pendingPause, below): nothing more is sent until a
|
|
1274
|
+
// raise, and it is refused in the pause's words (beforeRequest). It leaves at the run's stop too, unsent.
|
|
1275
|
+
return (capBuilt ??= runCap({ sessions, keepBackUsd: (request, asked) => keepBackOf?.(request, asked), parked: () => pendingPause !== undefined, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), ...config, judged, capUsd: capNow }));
|
|
1063
1276
|
};
|
|
1064
1277
|
const flushed = { flush: () => deps.flush() };
|
|
1065
1278
|
const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
|
|
@@ -1187,6 +1400,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1187
1400
|
// outside any) and its decisions (ledger.decisions). Its last refusal is kept: a turn it ended ends the run in its
|
|
1188
1401
|
// words.
|
|
1189
1402
|
const paid = ledger.paid;
|
|
1403
|
+
// A host tool call's paid requests name the session the call runs in (RunTools.admit `under`): a request of it still
|
|
1404
|
+
// in flight may be the one that asked for the call (Claude Code books its cost after its calls; Codex starts a call
|
|
1405
|
+
// with its response open), so the call is judged beside it and never waits on it. pi's request has answered by then.
|
|
1406
|
+
const paidUnder = { admit: (request) => paid.admit({ ...request, under: spec.session.key }), settle: (id, usd, options) => paid.settle(id, usd, options) };
|
|
1190
1407
|
let refused;
|
|
1191
1408
|
/** The pause a refusal for room journaled before pi heard of it (pauseAtCap), the run parked with it. */
|
|
1192
1409
|
let pausedAtRefusal = false;
|
|
@@ -1246,19 +1463,24 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1246
1463
|
return { ...pending, refuse: text, figures };
|
|
1247
1464
|
};
|
|
1248
1465
|
const beforeRequest = async (request) => {
|
|
1249
|
-
// Kept until it ends, so its answer can be the session's previous request (requestEnded).
|
|
1250
|
-
askedFor.set(request.turn, { model: request.model, ...(request.inputTokensMax === undefined ? {} : { bound: request.inputTokensMax }), counted: request.inputTokensCounted === true, own: request.host === undefined && !request.side && !request.unanswered });
|
|
1251
1466
|
// A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
|
|
1252
|
-
// whatever else would pause it (a paid call's refusal, pendingPause).
|
|
1253
|
-
|
|
1467
|
+
// whatever else would pause it (a paid call's refusal, pendingPause). One a paid call stopped for good
|
|
1468
|
+
// (paid-calls.ts stopRun) ends in that call's words, which say why, past its cap too.
|
|
1469
|
+
const over = pendingPause?.forGood ? undefined : await overCap();
|
|
1254
1470
|
if (!over && pendingPause) {
|
|
1255
1471
|
pendingPause = await landing(pendingPause);
|
|
1256
1472
|
// Fits now: dropped for good, on the root too, so a later claim never revives the old refusal.
|
|
1257
1473
|
if (pendingPause === undefined)
|
|
1258
1474
|
await keepPending(null);
|
|
1259
1475
|
}
|
|
1260
|
-
|
|
1261
|
-
|
|
1476
|
+
let answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
|
|
1477
|
+
// A request that waited for room while the run parked (the cap let it leave the line): refused in the pause's
|
|
1478
|
+
// words, as any request after the pause is.
|
|
1479
|
+
if (!over && answer && "refuse" in answer && pendingPause !== undefined)
|
|
1480
|
+
answer = pendingPause;
|
|
1481
|
+
if (answer && "refuse" in answer && reflecting)
|
|
1482
|
+
learningRefused ??= answer;
|
|
1483
|
+
else if (answer && "refuse" in answer) {
|
|
1262
1484
|
refused = answer;
|
|
1263
1485
|
await pauseAt(answer);
|
|
1264
1486
|
}
|
|
@@ -1319,13 +1541,19 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1319
1541
|
// run's cap now, what it spent and holds, and its own priced answers. Once per cap, as main's process told it
|
|
1320
1542
|
// (cap.ts wrapUpSentIn): a CAP_WRAPUP entry names the cap it was told under, read at each claim, so a raise's new
|
|
1321
1543
|
// cap is told again when it too comes near; written as the server's row only once a request carrying the note is
|
|
1322
|
-
//
|
|
1544
|
+
// answered.
|
|
1323
1545
|
const wrapUpHarness = harness;
|
|
1324
1546
|
const wrapUpRoot = root ?? (await harness.root(context));
|
|
1325
1547
|
const toldCaps = (await entriesOf(gate.journal, wrapUpRoot.id, context))
|
|
1326
1548
|
.filter((entry) => entry.kind === CAP_WRAPUP)
|
|
1327
1549
|
.map((entry) => entry.data?.capUsd)
|
|
1328
1550
|
.filter((capUsd) => typeof capUsd === "number");
|
|
1551
|
+
// The free limits it was told under (a CAP_WRAPUP row naming `freeLimit`), read at each claim, so a restart never tells
|
|
1552
|
+
// one twice.
|
|
1553
|
+
const toldFreeLimits = new Set((await entriesOf(gate.journal, wrapUpRoot.id, context))
|
|
1554
|
+
.filter((entry) => entry.kind === CAP_WRAPUP)
|
|
1555
|
+
.map((entry) => entry.data?.freeLimit)
|
|
1556
|
+
.filter((limit) => typeof limit === "number"));
|
|
1329
1557
|
const toldAt = (capUsd) => capUsd !== undefined && toldCaps.some((told) => Math.abs(told - capUsd) <= 1e-9);
|
|
1330
1558
|
// What the run spent on its sessions other than this claim's model session, its decisions' and its paid calls' (an
|
|
1331
1559
|
// earlier session's, a grade's), summed as overCap sums them; null while any is unknown. Read at the claim and again
|
|
@@ -1348,7 +1576,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1348
1576
|
};
|
|
1349
1577
|
// The typical cost is of the harness's own main-model answers at what they cost: never a request the host sent beside
|
|
1350
1578
|
// them (`host`), nor the harness's own side call on a smaller model (`side`, a title request), nor one a crash cut
|
|
1351
|
-
// (booked at its hold
|
|
1579
|
+
// (booked at its hold, the worst case), one never sent, given back, owed or stopped.
|
|
1352
1580
|
const claimRecords = await writer.read();
|
|
1353
1581
|
const claimHosts = sessionSpendOf(claimRecords).hosts;
|
|
1354
1582
|
/** The turns of requests that are no main-model request of the harness's own: read from the records, then each
|
|
@@ -1359,6 +1587,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1359
1587
|
if (record.kind === RUNNER_RECORDS.request && data.side === true && typeof data.turn === "number")
|
|
1360
1588
|
notOwn.add(data.turn);
|
|
1361
1589
|
}
|
|
1590
|
+
// The free requests the run made before this claim, in every session (freeMade: each admission's from here on).
|
|
1591
|
+
let madeBefore = 0;
|
|
1592
|
+
for (const key of await sessions.keys())
|
|
1593
|
+
madeBefore += freeRequestsIn(await sessions.read(key));
|
|
1594
|
+
freeMade = madeBefore;
|
|
1362
1595
|
const capNote = {
|
|
1363
1596
|
costs: claimRecords.flatMap((record) => {
|
|
1364
1597
|
if (record.kind !== RUNNER_RECORDS.turn)
|
|
@@ -1369,18 +1602,94 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1369
1602
|
}),
|
|
1370
1603
|
restUsd: await restOf(),
|
|
1371
1604
|
};
|
|
1605
|
+
/** A main-model request as the run's cap prices it at admission (RunCap.asked: its model, its whole input uncached),
|
|
1606
|
+
* for the wrap-up's note and what the run keeps back to answer. A request the note takes is measured as its client
|
|
1607
|
+
* sent it (NoteRequest), by the input count its admission reads (a provider's or a local count, else its bytes). */
|
|
1608
|
+
const pricedOf = (model, asked) => theCap().asked({ ...asked, model });
|
|
1372
1609
|
/** A main-model request's figures as the run's cap prices them (kernel cap requestFigures), for what it keeps back. */
|
|
1373
1610
|
const figuresOf = (model, asked) => {
|
|
1374
1611
|
const config = specNow?.runCap;
|
|
1375
|
-
|
|
1376
|
-
if (!config || !capModel)
|
|
1612
|
+
if (!config?.modelOf(model))
|
|
1377
1613
|
return undefined;
|
|
1378
|
-
return requestFigures(
|
|
1614
|
+
return requestFigures(pricedOf(model, asked));
|
|
1379
1615
|
};
|
|
1380
|
-
/** What the run keeps back to answer (
|
|
1616
|
+
/** What the run keeps back to answer (wrap-up.ts reserveFor), its typical step the run's own priced answers'. */
|
|
1381
1617
|
const reserveOf = (figures) => reserveFor(figures, (step0Usd) => typicalCost(capNote.costs, step0Usd));
|
|
1618
|
+
// A CLI harness's request of the session's own (no side call, no host's, no unanswered one, no paid step) keeps
|
|
1619
|
+
// back that same reserve, priced on itself as the wrap-up's gate prices it once it is admitted
|
|
1620
|
+
// (capNote.lastFigures): admitted at an output whose worst case leaves it free, a tool call it makes while it
|
|
1621
|
+
// streams is not refused for the reserve (the kernel rule's keepUsd says when it cannot be kept, and why the cap
|
|
1622
|
+
// holds either way). A CLI may start a call with its response still open (Codex) or book its cost after its calls
|
|
1623
|
+
// (Claude Code); pi starts a tool once its response is complete, so its requests keep none back.
|
|
1624
|
+
keepBackOf = (request, asked) => {
|
|
1625
|
+
const config = specNow?.runCap;
|
|
1626
|
+
if (!config || spec.record !== "loop" || request.key !== spec.session.key || request.host !== undefined || request.side || request.unanswered || request.paid)
|
|
1627
|
+
return undefined;
|
|
1628
|
+
return reserveOf(requestFigures(asked));
|
|
1629
|
+
};
|
|
1382
1630
|
let bookingNow;
|
|
1631
|
+
// The replaced computer's note (spec.computerNote), until a request carrying it is answered. It goes before the
|
|
1632
|
+
// wrap-up: one note per request, so the wrap-up waits a request.
|
|
1633
|
+
let computerWords = spec.computerNote;
|
|
1634
|
+
// The server's note a request carries (the replaced computer's, else the cap's wrap-up; `cap` says the wrap-up's
|
|
1635
|
+
// figures), one request at a time: from its take until that request's admission ends, then, admitted carrying it
|
|
1636
|
+
// (`turn`), until that request ends. Told once that request is answered (afterRequest); given back for the next
|
|
1637
|
+
// request by a refusal, a dropped note, or an end with no answer (an error status, a 429, a lost or cut stream).
|
|
1638
|
+
// A request that took it and left before its admission (a note its policy could not place, an error) gives it back
|
|
1639
|
+
// as it goes (noteReturned). WRAP_UP_OFFER_MS is only the backstop for a take that
|
|
1640
|
+
// never reaches its admission and is never given back: past it, a later request may take the note. An admitted
|
|
1641
|
+
// request always ends (the proxy books each one once), so no backstop is needed from there.
|
|
1642
|
+
let carried;
|
|
1643
|
+
const takeNote = (model, asked) => {
|
|
1644
|
+
if (carried && (carried.turn !== undefined || Date.now() - carried.at < WRAP_UP_OFFER_MS))
|
|
1645
|
+
return undefined;
|
|
1646
|
+
const note = computerWords !== undefined && !reflecting ? { words: computerWords } : wrapUpNote(model, asked);
|
|
1647
|
+
carried = note ? { ...note, at: Date.now() } : undefined;
|
|
1648
|
+
return note?.words;
|
|
1649
|
+
};
|
|
1650
|
+
/** Told: the note is the run's told at once (no request takes it again), and its row, once, the server's, is
|
|
1651
|
+
* what is returned to write: after the request is booked, so a finished request's hold never waits on the row. */
|
|
1652
|
+
const tell = (told) => {
|
|
1653
|
+
let kind = CAP_WRAPUP;
|
|
1654
|
+
let data;
|
|
1655
|
+
let what;
|
|
1656
|
+
if (told.freeLimit !== undefined) {
|
|
1657
|
+
if (toldFreeLimits.has(told.freeLimit))
|
|
1658
|
+
return undefined;
|
|
1659
|
+
toldFreeLimits.add(told.freeLimit);
|
|
1660
|
+
data = { words: rowWords(told.words), freeLimit: told.freeLimit };
|
|
1661
|
+
what = "the free-limit wrap-up's row";
|
|
1662
|
+
}
|
|
1663
|
+
else if (told.cap === undefined) {
|
|
1664
|
+
computerWords = undefined;
|
|
1665
|
+
kind = COMPUTER_NOTE;
|
|
1666
|
+
data = { words: rowWords(told.words) };
|
|
1667
|
+
what = "the replaced computer's note row";
|
|
1668
|
+
}
|
|
1669
|
+
else {
|
|
1670
|
+
const { leftUsd, capUsd } = told.cap;
|
|
1671
|
+
if (toldAt(capUsd))
|
|
1672
|
+
return undefined;
|
|
1673
|
+
toldCaps.push(capUsd);
|
|
1674
|
+
data = { words: rowWords(told.words), leftUsd, capUsd };
|
|
1675
|
+
what = "the wrap-up's row";
|
|
1676
|
+
}
|
|
1677
|
+
return async () => {
|
|
1678
|
+
try {
|
|
1679
|
+
await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind, data: data }), context);
|
|
1680
|
+
await deps.flush();
|
|
1681
|
+
}
|
|
1682
|
+
catch (error) {
|
|
1683
|
+
console.warn(`[runner] ${what} was not written (the note was answered): ${said(error)}`);
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
};
|
|
1687
|
+
/** The wrap-up due for a request about to be sent: the cap's, with what is left and the cap it is told under, else
|
|
1688
|
+
* the free limit's. */
|
|
1383
1689
|
const wrapUpNote = (model, asked) => {
|
|
1690
|
+
// The end-of-run turn comes after the run's answer: "finish now with your answer" is the job's note, never its.
|
|
1691
|
+
if (reflecting)
|
|
1692
|
+
return undefined;
|
|
1384
1693
|
const config = specNow?.runCap;
|
|
1385
1694
|
const capModel = config?.modelOf(model);
|
|
1386
1695
|
const sessionSpent = bookingNow?.spentUsd();
|
|
@@ -1390,22 +1699,27 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1390
1699
|
// The model session's requests in flight, at what is held for each (as the cap reads a flight); unknown gives none.
|
|
1391
1700
|
const inFlight = bookingNow?.heldUsd();
|
|
1392
1701
|
const capUsd = capNow();
|
|
1393
|
-
|
|
1394
|
-
// offered it too (its admission tells it, or a refusal or a dropped note gives it back: below). A request that
|
|
1395
|
-
// took it and left before its admission (its client gone while the proxy counted its tokens, a body the proxy
|
|
1396
|
-
// refused) gives it back as it goes (noteReturned), so the next request takes it at once. WRAP_UP_OFFER_MS is
|
|
1397
|
-
// only the backstop for a path that never gives it back: past it, a later request is offered it.
|
|
1398
|
-
if (capNote.offered && Date.now() - capNote.offered.at < WRAP_UP_OFFER_MS)
|
|
1399
|
-
return undefined;
|
|
1400
|
-
if (!config || !capModel || capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
|
|
1702
|
+
if (!config || !capModel)
|
|
1401
1703
|
return undefined;
|
|
1704
|
+
// The free-model limit's wrap-up (free.ts): the same note and offer, one per run and limit, on a request of a free
|
|
1705
|
+
// model. The dollar cap's note, when it is due on this request, goes first: one note per request, and it is told
|
|
1706
|
+
// once, so the free one waits for the next request (or never comes, the run having answered).
|
|
1707
|
+
const freeNote = () => {
|
|
1708
|
+
const limit = config.freeRequests;
|
|
1709
|
+
if (limit === undefined || toldFreeLimits.has(limit) || !freeModel(capModel))
|
|
1710
|
+
return undefined;
|
|
1711
|
+
const due = freeWrapUpDue(limit, freeMade);
|
|
1712
|
+
return due ? { words: freeWrapUpWords(due.left), freeLimit: limit } : undefined;
|
|
1713
|
+
};
|
|
1714
|
+
if (capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
|
|
1715
|
+
return freeNote();
|
|
1402
1716
|
const spentUsd = sessionSpent + decided + paidSpent + rest;
|
|
1403
|
-
// The tools' gate counts a request in flight at its hold
|
|
1404
|
-
//
|
|
1405
|
-
const heldUsd = inFlight +
|
|
1406
|
-
const due = noteFor(
|
|
1717
|
+
// The tools' gate counts a request in flight at its hold (sessionSpendOf), so the note counts it the same: it never
|
|
1718
|
+
// comes later than the gate's first refusal.
|
|
1719
|
+
const heldUsd = inFlight + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
|
|
1720
|
+
const due = noteFor(pricedOf(model, asked), { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false });
|
|
1407
1721
|
// The two wrap-ups read as one story: the note tells the model what is left; once what the run keeps back to
|
|
1408
|
-
// answer (
|
|
1722
|
+
// answer (wrap-up.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
|
|
1409
1723
|
// its own has not made it due before: told on the request whose tool call would be refused now, no later than the
|
|
1410
1724
|
// first refusal. The rule's figure here is the run's spend and holds as they stand at this take, and this request's
|
|
1411
1725
|
// own reserve. (The gate's reader, wrapUp, reads the records at each call and is async; a reading kept from an
|
|
@@ -1413,8 +1727,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1413
1727
|
const atLine = wrappingUp(capUsd, spentUsd + heldUsd, reserveOf(figuresOf(model, asked)));
|
|
1414
1728
|
const leftUsd = capUsd - spentUsd - heldUsd;
|
|
1415
1729
|
const note = due ?? (atLine ? { words: wrapUpWords(leftUsd, capNote.costs.length === 0), leftUsd } : undefined);
|
|
1416
|
-
|
|
1417
|
-
return note?.words;
|
|
1730
|
+
return note ? { words: note.words, cap: { leftUsd: note.leftUsd, capUsd } } : freeNote();
|
|
1418
1731
|
};
|
|
1419
1732
|
// The rule before a side effect for every paid model request, on the path every adapter's requests take: the
|
|
1420
1733
|
// booking writes the request's record, then awaits request_start before the request leaves, so the flush here
|
|
@@ -1423,11 +1736,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1423
1736
|
key: spec.session.key,
|
|
1424
1737
|
label: spec.session.label,
|
|
1425
1738
|
beforeRequest,
|
|
1426
|
-
note:
|
|
1739
|
+
note: takeNote,
|
|
1427
1740
|
// A request that took it and left before its admission gives it back: the next request may take it at once.
|
|
1428
1741
|
noteReturned: (note) => {
|
|
1429
|
-
if (
|
|
1430
|
-
|
|
1742
|
+
if (carried?.turn === undefined && carried?.words === note)
|
|
1743
|
+
carried = undefined;
|
|
1431
1744
|
},
|
|
1432
1745
|
onEvent: async (event) => {
|
|
1433
1746
|
// The run's own priced answers, the typical cost the wrap-up is worked out by (a request the host sent beside
|
|
@@ -1436,8 +1749,6 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1436
1749
|
// at their hold or cut, comes before `capNote.live` and is never one.)
|
|
1437
1750
|
if (capNote.live && event.type === "request_end" && event.host === undefined && !notOwn.has(event.turn) && typeof event.usage.usd === "number" && event.usage.usd > 0 && !event.usage.cut && !event.usage.givenBack)
|
|
1438
1751
|
capNote.costs.push(event.usage.usd);
|
|
1439
|
-
if (event.type === "request_end")
|
|
1440
|
-
requestEnded(event.turn, event.usage, event.ended);
|
|
1441
1752
|
if (event.type === "request_start") {
|
|
1442
1753
|
// A new request means the model's last message is over: what it said so far is on the record before the request,
|
|
1443
1754
|
// so an answer shows while the turn goes on (a CLI that answers, then makes another request).
|
|
@@ -1460,9 +1771,15 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1460
1771
|
const on = harness;
|
|
1461
1772
|
const conversation = root ?? (await on.root(context));
|
|
1462
1773
|
const unsent = event.ended.end === "nothing" && event.ended.label === "never_left";
|
|
1774
|
+
// One on a free model (`free`: booked a known $0) is no cost unknown: its mark says so, and the usage row counts
|
|
1775
|
+
// it at $0, never cut.
|
|
1776
|
+
// One cut with no answer and booked at its hold (bookCut's CUT_AT_HOLD) is that figure, the most it can have
|
|
1777
|
+
// cost: its mark says so, and the usage row counts it there, never as a cost no one knows.
|
|
1778
|
+
const atMost = typeof event.usage.atMostUsd === "number" && Number.isFinite(event.usage.atMostUsd) ? { atMostUsd: event.usage.atMostUsd } : {};
|
|
1779
|
+
const data = unsent ? { unsent: true } : event.usage.free ? { free: true } : atMost;
|
|
1463
1780
|
// Not written when the journal sealed under it (the run's end landed first): a settled run reads its unanswered
|
|
1464
1781
|
// mark cut all the same.
|
|
1465
|
-
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data:
|
|
1782
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data: data }), context).catch(() => undefined);
|
|
1466
1783
|
}
|
|
1467
1784
|
},
|
|
1468
1785
|
});
|
|
@@ -1479,17 +1796,18 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1479
1796
|
const toolsAtOpen = sessionSpendOf(await sessions.read(TOOL_SESSION));
|
|
1480
1797
|
if (spec.runCap && toolsAtOpen.turns.some((turn) => !toolsAtOpen.answered.has(turn)))
|
|
1481
1798
|
await paidOf();
|
|
1482
|
-
// The cap's wrap-up (
|
|
1799
|
+
// The cap's wrap-up (wrap-up.ts wrappingUp): what every session of the run has taken as the cap counts it, its
|
|
1483
1800
|
// spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
|
|
1484
1801
|
// hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
|
|
1485
1802
|
// flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
|
|
1803
|
+
// Its answer is the words a call reads once the run wraps up (wrap-up.ts wrapUpText), undefined while it does not.
|
|
1486
1804
|
const wrapUp = async () => {
|
|
1487
1805
|
// A run whose spec gives no cap (no runCap) has none to wrap up at, as overCap reads it.
|
|
1488
1806
|
if (!spec.runCap)
|
|
1489
|
-
return
|
|
1807
|
+
return undefined;
|
|
1490
1808
|
const capUsd = capNow();
|
|
1491
1809
|
if (capUsd === undefined)
|
|
1492
|
-
return
|
|
1810
|
+
return undefined;
|
|
1493
1811
|
// What was spent beside the run on its behalf counts as taken, as its sessions' spend does.
|
|
1494
1812
|
let taken = await besideNow();
|
|
1495
1813
|
for (const key of await sessions.keys()) {
|
|
@@ -1499,7 +1817,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1499
1817
|
}
|
|
1500
1818
|
// What the run keeps back to answer, priced on the main model's last request admitted on this claim (its next one
|
|
1501
1819
|
// is priced at least as high): none yet, no wrap-up, as no tool call comes before a request.
|
|
1502
|
-
|
|
1820
|
+
if (!wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures)))
|
|
1821
|
+
return undefined;
|
|
1822
|
+
// A cap below what the model needs for one more step and an answer is named in the words, by the same rule.
|
|
1823
|
+
return wrapUpText(capUsd, capNote.lastModel, stepAndAnswerFor(capNote.lastFigures, (step0Usd) => typicalCost(capNote.costs, step0Usd)), capNote.lastEffort);
|
|
1503
1824
|
};
|
|
1504
1825
|
const gateOf = preIntentGate(spec, hooks, wrapUp);
|
|
1505
1826
|
// A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
|
|
@@ -1523,11 +1844,19 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1523
1844
|
// bridge asks first; one refused is on the record from the gate, bridgeGate), so its record's start is written
|
|
1524
1845
|
// here, before the flush and the call, and its end after.
|
|
1525
1846
|
call: async (args, toolContext) => {
|
|
1847
|
+
// A tool that only nests calls (tools_call, codemode) has its row on a CLI's record as pi's does, its start marked
|
|
1848
|
+
// `nests`; each call it makes is on the record after it as its own tool's (its id `<callId>/<key>`). It runs again
|
|
1849
|
+
// whole after a crash, its recorded calls answered from their records, so its own end never answers it.
|
|
1850
|
+
const record = cliRecord;
|
|
1526
1851
|
// A call its CLI issues again under an id the record already ended (after the CLI's own resume) is answered
|
|
1527
1852
|
// from that end, never run again.
|
|
1528
|
-
const ended = record?.endOf(toolContext.callId);
|
|
1853
|
+
const ended = tool.nests ? undefined : record?.endOf(toolContext.callId);
|
|
1529
1854
|
if (ended)
|
|
1530
1855
|
return endedAnswer(tool.name, ended);
|
|
1856
|
+
// A run a paid call stopped for good (paid-calls.ts stopRun) runs no tool after it, a script's own calls
|
|
1857
|
+
// included: each is refused in the stop's words, never run.
|
|
1858
|
+
if (pendingPause?.forGood)
|
|
1859
|
+
return { text: pendingPause.refuse, isError: true };
|
|
1531
1860
|
// A call run again after an earlier attempt (the harness's rerun of a replay-safe call after a crash: its
|
|
1532
1861
|
// attempt above 0) never passed the gate before its intent this time: the gate is asked again here, so a deny
|
|
1533
1862
|
// set since the first attempt refuses the rerun, in words saying the earlier attempt may have taken effect.
|
|
@@ -1535,19 +1864,22 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1535
1864
|
// By the name the gate before the intent asks it by: an MCP tool by its catalog name.
|
|
1536
1865
|
const name = mcp?.catalogOf(tool.name) ?? tool.name;
|
|
1537
1866
|
const asked = spec.gate.askedAs?.(name) ?? name;
|
|
1538
|
-
const
|
|
1539
|
-
if (
|
|
1867
|
+
const given = await spec.gate({ callId: toolContext.callId, tool: name, args: (args ?? {}) }, { replayed: true });
|
|
1868
|
+
if (given === "deny")
|
|
1540
1869
|
return { text: setToDenyText(asked, undefined, "server", "unknown"), isError: true };
|
|
1541
|
-
if (typeof
|
|
1542
|
-
return { text:
|
|
1870
|
+
if (typeof given === "object" && "deny" in given)
|
|
1871
|
+
return { text: given.deny, isError: true };
|
|
1872
|
+
// An ask with its card's own fields is an ask, its card as the gate shows it.
|
|
1873
|
+
const shown = typeof given === "object" ? given.ask : undefined;
|
|
1874
|
+
const now = shown ? "ask" : given;
|
|
1543
1875
|
// Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
|
|
1544
1876
|
// replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
|
|
1545
1877
|
// the claim lets it go; a deny says the earlier attempt may have taken effect. Asked and not answered yet, with
|
|
1546
1878
|
// the setting at allow now: the setting answers the ask (allowedBySetting).
|
|
1547
1879
|
const bySetting = now === "allow" && (await askStands(toolContext.callId));
|
|
1548
1880
|
if (now === "ask" || bySetting) {
|
|
1549
|
-
const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
|
|
1550
|
-
const price = mcp?.priceOf(name) ??
|
|
1881
|
+
const call = { callId: toolContext.callId, tool: name, args: cardOf(name, shown, (args ?? {})) };
|
|
1882
|
+
const price = mcp?.priceOf(name) ?? null;
|
|
1551
1883
|
const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
|
|
1552
1884
|
if (answer === "park")
|
|
1553
1885
|
return await heldUntilAborted(toolContext.signal);
|
|
@@ -1559,19 +1891,20 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1559
1891
|
if (stopAbort.signal.aborted || toolContext.signal?.aborted)
|
|
1560
1892
|
return { text: STOPPED_WHILE_WAITING, isError: true };
|
|
1561
1893
|
}
|
|
1894
|
+
// Another call after a turn-ending one: the turn goes on (TurnCut).
|
|
1562
1895
|
if (record)
|
|
1563
|
-
|
|
1896
|
+
askCut.disarm();
|
|
1897
|
+
if (record)
|
|
1898
|
+
await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe", tool.nests);
|
|
1564
1899
|
try {
|
|
1565
1900
|
const answer = await sideEffect({
|
|
1566
1901
|
replaySafe: tool.replay === "safe",
|
|
1567
1902
|
flush: () => deps.flush(),
|
|
1568
1903
|
// Its paid requests booked under this call, on the run's one ledger (paid-calls.ts bookedIn, Ledger.paid); one
|
|
1569
1904
|
// refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
|
|
1570
|
-
// The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
|
|
1571
|
-
// loop wrapped it, and whether a person approved this call.
|
|
1572
1905
|
// The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
|
|
1573
1906
|
// row's computer_calls, before its result is written.
|
|
1574
|
-
route: () => bookedIn({ call: toolContext.callId,
|
|
1907
|
+
route: () => bookedIn({ call: toolContext.callId, paid: paidUnder, pause: ledger.pause }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped))),
|
|
1575
1908
|
beforeResult: async (answer) => {
|
|
1576
1909
|
const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
|
|
1577
1910
|
try {
|
|
@@ -1587,6 +1920,12 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1587
1920
|
// A call a stop cut answers whatever its tool said of the abort: it ends interrupted, never as its outcome.
|
|
1588
1921
|
if (record)
|
|
1589
1922
|
await record.end(toolContext.callId, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
|
|
1923
|
+
// A CLI's question to the person (a turn-ending tool's call, answered): its turn is cut at its next request,
|
|
1924
|
+
// as pi's ends here (TurnCut). Any other call's end after it lets the turn go on.
|
|
1925
|
+
if (record && endsTurn(tool.name) && !answer.isError && !stopAbort.signal.aborted)
|
|
1926
|
+
askCut.arm(toolContext.callId);
|
|
1927
|
+
else if (record)
|
|
1928
|
+
askCut.disarm();
|
|
1590
1929
|
return answer;
|
|
1591
1930
|
}
|
|
1592
1931
|
catch (error) {
|
|
@@ -1598,37 +1937,93 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1598
1937
|
}
|
|
1599
1938
|
},
|
|
1600
1939
|
});
|
|
1601
|
-
const
|
|
1602
|
-
//
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1940
|
+
const facts = builtinHarness(spec.adapter.id)?.facts;
|
|
1941
|
+
// tools_search, tools_call and codemode over the session's tools (meta-tools.ts), on every harness (codemode on
|
|
1942
|
+
// each but one that runs scripts of its own): what they call is called nested, each call asked about and recorded
|
|
1943
|
+
// as its own tool's. A search finds a tool whose setting is not deny; an MCP tool's setting is its catalog name's.
|
|
1944
|
+
const settingOf = spec.gate?.permission;
|
|
1945
|
+
// A meta tool whose setting is deny is not offered at all, rather than offered and refused.
|
|
1946
|
+
const allowed = async (name) => !settingOf || (await settingOf(name).catch(() => "deny")) !== "deny";
|
|
1947
|
+
const hostCodemode = facts?.ownCodemode !== true && (await allowed(CODEMODE));
|
|
1948
|
+
// A tool the spec binds for a script's nested calls alone (deferred: a desktop's computer_op, and its step tools
|
|
1949
|
+
// under its surface "code") is listed wherever the host offers no codemode to call it: on a harness that runs
|
|
1950
|
+
// scripts in its own code mode, which reaches only the tools it is handed (Codex's exec), and on a run whose
|
|
1951
|
+
// codemode is set to deny, so the computer is never out of the model's reach.
|
|
1952
|
+
const listedFor = ({ deferred: _, ...tool }) => tool;
|
|
1953
|
+
const own = [...spec.session.tools, ...(mcp?.tools ?? [])].map((tool) => (!hostCodemode && tool.deferred ? listedFor(tool) : tool)).map(hosted);
|
|
1954
|
+
// The harness's own tools beside them (pi's subagent, its browser's): found and called by name as the host's are,
|
|
1955
|
+
// run by the harness as its own nested calls. Never called here: a nested call reaches them through the harness.
|
|
1956
|
+
const native = (spec.adapter.ownTools ?? []).filter((one) => !own.some((tool) => tool.name === one.name)).map((one) => ({
|
|
1957
|
+
name: one.name,
|
|
1958
|
+
description: one.description,
|
|
1959
|
+
inputSchema: one.inputSchema,
|
|
1960
|
+
replay: "never",
|
|
1961
|
+
call: async () => ({ text: `${one.name} is run by the harness itself, as a nested call of tools_call or a script.`, isError: true }),
|
|
1962
|
+
}));
|
|
1963
|
+
// One discovery system (tool-deferral.ts): a run whose catalog tools pass DEFER_CATALOG_OVER does not list them; the
|
|
1964
|
+
// model finds them with tools_search and runs them with tools_call (still the tool's own call at the gate). Claude
|
|
1965
|
+
// Code defers them itself (its ToolSearch, on under the same test), so it is offered neither. Under the threshold
|
|
1966
|
+
// every tool is listed and there is no search or call. codemode is offered as it always was.
|
|
1967
|
+
// Deferred only when the model can both find and run what it hid: with either helper denied every tool stays listed,
|
|
1968
|
+
// so denying a helper never takes an otherwise allowed tool out of reach.
|
|
1969
|
+
// The one verdict for every harness: one with a tool search of its own (Claude Code's) follows it too, handed it as
|
|
1970
|
+
// `deferCatalog` below, and so lists every tool when either helper is set to deny.
|
|
1971
|
+
const deferred = defersCatalog(own.map((one) => one.name)) && (await allowed(TOOLS_SEARCH)) && (await allowed(TOOLS_CALL));
|
|
1972
|
+
const offered = deferred && !facts?.ownToolSearch;
|
|
1973
|
+
const metas = metaTools({
|
|
1974
|
+
tools: () => [...own, ...native],
|
|
1975
|
+
granted: async (name) => !settingOf || (await settingOf(mcp?.catalogOf(name) ?? name).catch(() => "deny")) !== "deny",
|
|
1976
|
+
codemode: hostCodemode,
|
|
1977
|
+
discovery: { search: offered, call: offered },
|
|
1978
|
+
...(facts?.hostName ? { hostName: facts.hostName } : {}),
|
|
1979
|
+
...(spec.scriptComputer ? { computer: spec.scriptComputer } : {}),
|
|
1980
|
+
});
|
|
1981
|
+
const tools = [...own.map((one) => (offered && isCatalogWire(one.name) ? { ...one, deferred: true } : one)), ...metas.map(hosted)];
|
|
1608
1982
|
// The session's model port, counting what it admitted and has not booked yet (a stop's booking comes once the
|
|
1609
1983
|
// session's proxy sees its upstream end, which can be after pi went idle).
|
|
1610
1984
|
const port = booking.models;
|
|
1611
1985
|
unbooked = 0;
|
|
1986
|
+
bookingsWriting = 0;
|
|
1612
1987
|
const counted = {
|
|
1613
1988
|
beforeRequest: async (request) => {
|
|
1989
|
+
// The CLI's next request of its main model after its question to the person: never admitted, it asks for the
|
|
1990
|
+
// turn's cut (TurnCut). Its side calls and the host's own requests go on.
|
|
1991
|
+
if (askCut.armed && !request.side && request.host === undefined)
|
|
1992
|
+
return askCut.hold();
|
|
1614
1993
|
// A command row since the MCP credentials were made fresh: made fresh again before this request.
|
|
1615
1994
|
if (mcpStale && mcp) {
|
|
1616
1995
|
mcpStale = false;
|
|
1617
1996
|
await mcp.fresh();
|
|
1618
1997
|
}
|
|
1619
|
-
// The
|
|
1620
|
-
//
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1998
|
+
// The note this request carries, the one it took (takeNote: one at a time). Admitted with it, the request holds it
|
|
1999
|
+
// until it ends (afterRequest tells it or gives it back); a refusal (the throw) or a dropped note gives it back
|
|
2000
|
+
// now, for a later request.
|
|
2001
|
+
const taken = request.noted === true && carried?.turn === undefined ? carried : undefined;
|
|
2002
|
+
let ticket;
|
|
2003
|
+
try {
|
|
2004
|
+
ticket = await port.beforeRequest(request);
|
|
2005
|
+
}
|
|
2006
|
+
catch (error) {
|
|
2007
|
+
if (taken && carried === taken)
|
|
2008
|
+
carried = undefined;
|
|
2009
|
+
throw error;
|
|
2010
|
+
}
|
|
2011
|
+
if (taken && carried === taken) {
|
|
2012
|
+
if (ticket && !ticket.noteDropped)
|
|
2013
|
+
taken.turn = ticket.turn;
|
|
2014
|
+
else
|
|
2015
|
+
carried = undefined;
|
|
2016
|
+
}
|
|
1625
2017
|
unbooked += 1;
|
|
1626
2018
|
// The harness's own side call (a title request on its smaller model): never a typical cost of its main requests.
|
|
1627
2019
|
if (ticket && request.side)
|
|
1628
2020
|
notOwn.add(ticket.turn);
|
|
1629
2021
|
// The main model's request as the cap prices it: what the run keeps back to answer is priced on it (wrapUp).
|
|
1630
|
-
if (!request.side && request.host === undefined)
|
|
1631
|
-
|
|
2022
|
+
if (!request.side && request.host === undefined) {
|
|
2023
|
+
const figures = figuresOf(request.model, request);
|
|
2024
|
+
if (figures)
|
|
2025
|
+
Object.assign(capNote, { lastFigures: figures, lastModel: request.model, lastEffort: request.effort });
|
|
2026
|
+
}
|
|
1632
2027
|
// What follows is the wrap-up's own bookkeeping, after the request was admitted and its hold booked: it never fails
|
|
1633
2028
|
// the request (a throw here would leave it admitted and never sent, read as cut at its worst case).
|
|
1634
2029
|
try {
|
|
@@ -1638,28 +2033,31 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1638
2033
|
capNote.restUsd = null;
|
|
1639
2034
|
console.warn(`[runner] the run's other sessions' spend was not read; no wrap-up until it is: ${said(error)}`);
|
|
1640
2035
|
}
|
|
1641
|
-
// Told once a request carrying it is admitted with it (never one that went without the note's bytes): the server's
|
|
1642
|
-
// row, once per cap, made durable before the request leaves, so a machine lost after it never tells that cap twice.
|
|
1643
|
-
if (offer && ticket && !ticket.noteDropped && !toldAt(offer.capUsd)) {
|
|
1644
|
-
const { words, leftUsd, capUsd } = offer;
|
|
1645
|
-
toldCaps.push(capUsd);
|
|
1646
|
-
try {
|
|
1647
|
-
await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind: CAP_WRAPUP, data: { words, leftUsd, capUsd } }), context);
|
|
1648
|
-
await deps.flush();
|
|
1649
|
-
}
|
|
1650
|
-
catch (error) {
|
|
1651
|
-
console.warn(`[runner] the wrap-up's row was not written (the note went with the request): ${said(error)}`);
|
|
1652
|
-
}
|
|
1653
|
-
}
|
|
1654
2036
|
return ticket;
|
|
1655
2037
|
},
|
|
1656
|
-
afterRequest: async (
|
|
2038
|
+
afterRequest: async (usage, ticket, ended) => {
|
|
2039
|
+
// The note this request carried: told once the model answered it, else given back. Settled before anything here
|
|
2040
|
+
// waits: the proxy calls this as its client has the end, so a client's retry finds the note told or on offer.
|
|
2041
|
+
const held = carried?.turn !== undefined && carried.turn === ticket?.turn ? carried : undefined;
|
|
2042
|
+
if (held)
|
|
2043
|
+
carried = undefined;
|
|
2044
|
+
// An answer the model gave, not the provider's error inside one (a stream ended in an error event, a translated
|
|
2045
|
+
// route's failure in words included: the client drops it and asks again).
|
|
2046
|
+
const row = held && ended?.end === "answered" && ended.label !== "error" ? tell(held) : undefined;
|
|
2047
|
+
// Its booking has begun: waited for past CLOSE_MS, as long as its write takes (bookingsSettled).
|
|
2048
|
+
bookingsWriting += 1;
|
|
1657
2049
|
try {
|
|
1658
2050
|
await hooks.beforeBooking?.();
|
|
1659
|
-
await port.afterRequest(
|
|
2051
|
+
await port.afterRequest(usage, ticket, ended);
|
|
1660
2052
|
}
|
|
1661
2053
|
finally {
|
|
2054
|
+
bookingsWriting = Math.max(0, bookingsWriting - 1);
|
|
2055
|
+
if (row)
|
|
2056
|
+
await row();
|
|
1662
2057
|
unbooked = Math.max(0, unbooked - 1);
|
|
2058
|
+
if (bookingsWriting === 0)
|
|
2059
|
+
for (const wake of writtenAll.splice(0))
|
|
2060
|
+
wake();
|
|
1663
2061
|
if (unbooked === 0)
|
|
1664
2062
|
for (const wake of bookedAll.splice(0))
|
|
1665
2063
|
wake();
|
|
@@ -1684,58 +2082,102 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1684
2082
|
// The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
|
|
1685
2083
|
// start and its end, refused in the gate's words, go on the record here, as pi writes a refused call and its error
|
|
1686
2084
|
// result (a deny set, no one to approve, or a person's deny of its ask on the claim that resumes it). A call it asks
|
|
1687
|
-
// about goes on the record first, its start marked parked (once per call id)
|
|
1688
|
-
//
|
|
1689
|
-
//
|
|
1690
|
-
//
|
|
1691
|
-
//
|
|
2085
|
+
// about goes on the record first, its start marked parked (once per call id): the bridge hands the CLI nothing while it
|
|
2086
|
+
// waits, so no waiting result shows, as on pi. Its row shows while it waits, before its approval; the claim that runs
|
|
2087
|
+
// it once allowed writes its sent mark on that one start (start()), and a stop withdraws it never sent
|
|
2088
|
+
// (unsentParked). A start refused because another call of the round parked the run first (the journal sealed) leaves
|
|
2089
|
+
// this call held as that one is.
|
|
1692
2090
|
const replaySafe = (name) => tools.find((one) => one.name === name)?.replay === "safe";
|
|
2091
|
+
// A call a tool of pi's nests (a script's, tools_call's) is pi's own tool task, of which pi's record keeps no row: it
|
|
2092
|
+
// goes on the loop's record as a CLI's call does, so the Timeline shows it as its own call, and an ask for it beside
|
|
2093
|
+
// it. Its start at its gate (marked parked while it waits for a person; refused, with its end, in the gate's words),
|
|
2094
|
+
// its end once pi has its outcome (nestedEnded). The record opens at the claim's first such call, and never ends a
|
|
2095
|
+
// call itself: pi says each one's end, a replay-safe one a crash cut run again first (endsItsCalls).
|
|
2096
|
+
const [nestedOn, nestedJournal] = [harness, gate.journal];
|
|
2097
|
+
let nestedOpen;
|
|
2098
|
+
const nestedRecord = () => (nestedOpen ??= openCliRecord(nestedOn, nestedJournal, context, now, undefined, true));
|
|
2099
|
+
const unlessSealed = (error) => {
|
|
2100
|
+
if (!gate?.sealed)
|
|
2101
|
+
throw error;
|
|
2102
|
+
};
|
|
2103
|
+
const nestedAsking = preIntentGate(spec, hooks, wrapUp, async (call) => (await nestedRecord()).park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed));
|
|
2104
|
+
const nestedGate = async (call, hookContext) => {
|
|
2105
|
+
if (call.nested !== true)
|
|
2106
|
+
return gateOf(call, hookContext);
|
|
2107
|
+
const answer = await nestedAsking(call, hookContext);
|
|
2108
|
+
const nests = await nestedRecord();
|
|
2109
|
+
if (answer === "allow")
|
|
2110
|
+
await nests.start(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch(unlessSealed);
|
|
2111
|
+
else if ("deny" in answer)
|
|
2112
|
+
await nests.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny).catch(unlessSealed);
|
|
2113
|
+
return answer;
|
|
2114
|
+
};
|
|
2115
|
+
const nestedEnded = async (callId, status, output) => (await nestedRecord()).end(callId, status, output).catch(unlessSealed);
|
|
1693
2116
|
const askingGate = record
|
|
1694
|
-
? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)
|
|
2117
|
+
? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
|
|
1695
2118
|
if (!gate?.sealed)
|
|
1696
2119
|
throw error;
|
|
1697
2120
|
}))
|
|
1698
2121
|
: gateOf;
|
|
1699
2122
|
const bridgeGate = record
|
|
1700
2123
|
? async (call, hookContext) => {
|
|
2124
|
+
askCut.disarm();
|
|
2125
|
+
// An MCP call is on the record before its gate answers, its start marked parked (once per call id), so its
|
|
2126
|
+
// sent mark is committed before it is sent. A fault before the bridge writes its intent leaves no intent: the
|
|
2127
|
+
// CLI's re-issue asks again and sends it once. One after the intent is any bridged host tool's: told interrupted,
|
|
2128
|
+
// never run twice.
|
|
2129
|
+
if (mcp?.catalogOf(call.tool) !== undefined) {
|
|
2130
|
+
await record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool)).catch((error) => {
|
|
2131
|
+
if (!gate?.sealed)
|
|
2132
|
+
throw error;
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
1701
2135
|
const answer = await askingGate(call, hookContext);
|
|
1702
2136
|
if (answer !== "allow" && "deny" in answer)
|
|
1703
2137
|
await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
|
|
1704
2138
|
// A harness's own tool (Claude Code's WebSearch, which its provider runs) the gate held and a person now lets
|
|
1705
2139
|
// run: the host runs nothing of this call, so the start it parked ends here; the harness's next call runs it.
|
|
1706
|
-
else if (answer === "allow" &&
|
|
2140
|
+
else if (answer === "allow" && askedCalls.has(call.callId) && !tools.some((one) => one.name === call.tool))
|
|
1707
2141
|
await record.end(call.callId, "done", OWN_TOOL_RELEASED);
|
|
1708
2142
|
return answer;
|
|
1709
2143
|
}
|
|
1710
|
-
:
|
|
2144
|
+
: nestedGate;
|
|
1711
2145
|
// A tool no call of which reaches the gate before it runs (Codex's live search, inside its model requests): its
|
|
1712
2146
|
// setting now, read again at each request, so a deny or ask set mid-run reaches the next one.
|
|
1713
2147
|
const permission = spec.gate?.permission;
|
|
1714
|
-
|
|
1715
|
-
//
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
}
|
|
1735
|
-
return { parked: true };
|
|
1736
|
-
})
|
|
2148
|
+
// After a CLI's question to the person (TurnCut armed): what its model says is not on the record, as pi's turn says
|
|
2149
|
+
// nothing after the question; a call of another tool lets the turn go on.
|
|
2150
|
+
const onEvent = (theRecord) => (event) => {
|
|
2151
|
+
if (askCut.armed && event.type === "text")
|
|
2152
|
+
return;
|
|
2153
|
+
if (askCut.armed && event.type === "tool_start")
|
|
2154
|
+
askCut.disarm();
|
|
2155
|
+
theRecord.onEvent(event);
|
|
2156
|
+
};
|
|
2157
|
+
// A call of the CLI's own that its host tool calls run inside (Codex's code-mode `exec`): on its record as a call, and
|
|
2158
|
+
// each call it makes named under it, so its rows read as a codemode script's do on every other harness. Its start is
|
|
2159
|
+
// marked `nests`, so a crash leaves it open: its harness ends it (ownCalls.ended) from its CLI's own answer to it after
|
|
2160
|
+
// the resume, which comes after the rows of the calls it made, never as an interrupted end ahead of them. One no answer
|
|
2161
|
+
// of its CLI ends (a stop while it waits, a crash no resume follows) the run's end closes, interrupted (openNests).
|
|
2162
|
+
const ownCalls = record
|
|
2163
|
+
? {
|
|
2164
|
+
opened: (callId, name, input) => ownWrite(record.start(callId, name, input, false, true).catch(unlessSealed)),
|
|
2165
|
+
nestedIn: (callId, parent) => record.nestedIn(callId, parent),
|
|
2166
|
+
ended: (callId, output, failed) => ownWrite(record.end(callId, failed ? "failed" : "done", output).catch(unlessSealed)),
|
|
2167
|
+
}
|
|
1737
2168
|
: undefined;
|
|
1738
|
-
|
|
2169
|
+
const io = { writer, models: counted, signal: deps.signal, onEvent: record ? onEvent(record) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, ...(ownCalls ? { ownCalls } : {}), bookedCost, keepCalls, ...(record ? {} : { nestedEnded }) };
|
|
2170
|
+
// The end-of-run turn an earlier claim asked and never saw end (its runner lost mid look-back or mid compile): the
|
|
2171
|
+
// root's newest input still in flight is that turn's (end-of-run.ts REFLECT_PREFIX), which pi picks up again as its
|
|
2172
|
+
// session opens. The job's turn ended before it, answered: this pass runs no job turn (no recovery as the job's, no
|
|
2173
|
+
// wrap-up note, no park on its spend), and the end-of-run step's ask, under the same request id, waits on it (a
|
|
2174
|
+
// CLI's look-back has no submission until it ends: its record's lookingBack, below). Read before the session
|
|
2175
|
+
// opens, so its first request is already learning's.
|
|
2176
|
+
const lookingBackOpen = (await harness.inspect(context)).submissions.filter((one) => one.type === "input" && Number(one.conversationId) === Number(ROOT_CONVERSATION_ID)).at(-1)?.requestId?.startsWith(REFLECT_PREFIX) === true;
|
|
2177
|
+
reflecting = lookingBackOpen;
|
|
2178
|
+
// The MCP tools are host tools like any other (mcp.tools, wrapped above): every harness gets them on its own channel
|
|
2179
|
+
// for host tools, each call through the gate before its intent.
|
|
2180
|
+
session = await spec.adapter.open({ ...spec.session, tools, deferCatalog: deferred }, io);
|
|
1739
2181
|
root = await harness.root(context);
|
|
1740
2182
|
// The root as the claim found it, before this pass writes anything of its own there (the computer's show-up, a
|
|
1741
2183
|
// takeover's note): what the reopen check below reads, so a fresh reopen is told by the run's own last entry.
|
|
@@ -1752,6 +2194,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1752
2194
|
await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
|
|
1753
2195
|
}, context) };
|
|
1754
2196
|
}
|
|
2197
|
+
// The run's own computer, made by this claim: its kind recorded once per claim, before any request of the claim
|
|
2198
|
+
// (each request's flush makes it durable first), so a later claim knows the run had one (computer-journal.ts
|
|
2199
|
+
// hadComputer) however this one ends.
|
|
2200
|
+
if (restarts === 0 && spec.computer?.own) {
|
|
2201
|
+
const [rootOf, kind] = [root, spec.computer.kind];
|
|
2202
|
+
await harness.commit((tx) => tx.appendEntry(rootOf.id, { kind: KINDS.computerMade, data: { computer: kind } }), context);
|
|
2203
|
+
}
|
|
1755
2204
|
if (spec.computer?.hold && spec.computer.kind !== "sandbox") {
|
|
1756
2205
|
const [journalOf, rootOf] = [harness, root];
|
|
1757
2206
|
computerNow = journalHold(claim.runId, { kind: spec.computer.kind, hold: spec.computer.hold }, (entries) => journalOf.commit(async (tx) => {
|
|
@@ -1820,6 +2269,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1820
2269
|
// A session still new (a person stopped the run before its first input was sent): the follow-up is its first
|
|
1821
2270
|
// input, and the input the person stopped is never sent.
|
|
1822
2271
|
firstInputPlaced = undefined;
|
|
2272
|
+
// A feedback round an earlier claim took and never ended (its runner lost): this claim closes it, asking no turn.
|
|
2273
|
+
feedbackNow = endsRoot ? undefined : pendingFeedbackOf(foundEntries);
|
|
1823
2274
|
if (endsRoot && !inFlight && session.state === "idle")
|
|
1824
2275
|
reopen = {};
|
|
1825
2276
|
else if (endsRoot && !inFlight && session.state === "new") {
|
|
@@ -1827,6 +2278,16 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1827
2278
|
firstInputPlaced = new Promise((resolve) => (mine.placed = resolve));
|
|
1828
2279
|
reopen = mine;
|
|
1829
2280
|
}
|
|
2281
|
+
// A CLI run parked on its question (its turn cut there, TurnCut): its session takes no steer, so the person's
|
|
2282
|
+
// answer is this claim's turn, sent as a reopened run's follow-up is (steer, through `reopen`), the row's waiting
|
|
2283
|
+
// summary going in its take. A turn the session still reads open is the one the cut stopped: settled first,
|
|
2284
|
+
// never recovered (recovered, the CLI would go on past its question).
|
|
2285
|
+
if (!endsRoot && !inFlight && spec.record === "loop" && !session.steer && turnEndedOnAsk(foundEntries) !== undefined) {
|
|
2286
|
+
if (session.state === "open_turn")
|
|
2287
|
+
await session.settleOpenTurn();
|
|
2288
|
+
if (session.state === "idle")
|
|
2289
|
+
reopen = askReopen = {};
|
|
2290
|
+
}
|
|
1830
2291
|
}
|
|
1831
2292
|
opened();
|
|
1832
2293
|
// A channel call a fault's restart cut off from its pass: its record is written through this one.
|
|
@@ -1852,7 +2313,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1852
2313
|
return await writeEnd(harness, root, gate, { state: "stopped", outcome: "cancelled", summary: why }, []);
|
|
1853
2314
|
}
|
|
1854
2315
|
}
|
|
1855
|
-
|
|
2316
|
+
// A feedback round an earlier claim took (feedbackNow): its words are this claim's turn, never the job's input.
|
|
2317
|
+
let followedUp = feedbackNow !== undefined;
|
|
1856
2318
|
if (raising.resuming) {
|
|
1857
2319
|
// Every row that woke it has reached its command() first (deps.delivered), so raises sent together are taken
|
|
1858
2320
|
// together: one raise entry, and the run resumes once, at the latest cap, with one follow-up in the server's
|
|
@@ -1872,7 +2334,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1872
2334
|
await takeRaises();
|
|
1873
2335
|
if (paused) {
|
|
1874
2336
|
if (!resumes || raising.capUsd === undefined || !spec.cap?.followUpOf)
|
|
1875
|
-
return await parkAtCap(harness, root, gate, paused);
|
|
2337
|
+
return await parkAtCap(harness, root, gate, paused, "cap");
|
|
1876
2338
|
// The server's words, shown as its row ("AgentRun: …"), never as the person's; under the id a raise's answer named.
|
|
1877
2339
|
const followUp = spec.cap.followUpOf(raising.capUsd).text;
|
|
1878
2340
|
const followUpId = raiseFollowUpId(raising.state?.lastRaise?.pause ?? "follow-up");
|
|
@@ -1895,44 +2357,6 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1895
2357
|
followedUp = true;
|
|
1896
2358
|
}
|
|
1897
2359
|
}
|
|
1898
|
-
if (!followedUp && ownClient) {
|
|
1899
|
-
// MCP calls a harness with its own client parked through the door: each answered once (an allow runs it, a deny
|
|
1900
|
-
// is told), then the session goes on with main's resume message for them, written on the record before it is
|
|
1901
|
-
// sent (as the person's input is). A call still waiting parks the run again.
|
|
1902
|
-
const wrapped = new Map(tools.map((tool) => [tool.name, tool]));
|
|
1903
|
-
const follow = await parkedFollowUp(mcp, {
|
|
1904
|
-
entries: await entriesOf(gate.journal, root.id, context),
|
|
1905
|
-
// As the gate before an intent does: a call still waiting on its person whose tool now reads allow is answered by
|
|
1906
|
-
// the setting (allowedBySetting); any other waits for the person's answer.
|
|
1907
|
-
answer: async (call, price) => {
|
|
1908
|
-
const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
|
|
1909
|
-
const bySetting = now === "allow" && (await askStands(call.callId));
|
|
1910
|
-
return bySetting ? allowedBySetting(call, price, call.tool) : answerOf(call, price);
|
|
1911
|
-
},
|
|
1912
|
-
deniedNow: async (call) => {
|
|
1913
|
-
// The gate is Promise-capable on purpose (run-cap's and the approvals' gates may look things up), so await it.
|
|
1914
|
-
const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
|
|
1915
|
-
return now === "deny" ? setToDenyText(call.tool) : typeof now === "object" ? now.deny : undefined;
|
|
1916
|
-
},
|
|
1917
|
-
run: (call) => wrapped.get(mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool).name).call(call.args, { callId: call.callId, signal: deps.signal }),
|
|
1918
|
-
// A parked call refused ends on the run's record (its start was written at its park), in the refusal's words.
|
|
1919
|
-
refused: async (call, text) => cliRecord?.end(call.callId, "refused", text),
|
|
1920
|
-
});
|
|
1921
|
-
if (follow === "park") {
|
|
1922
|
-
// A person's stop (or cancel) waiting here is taken: the run ends stopped, its waiting calls withdrawn in the
|
|
1923
|
-
// end's commit. Released parked instead, its untaken stop would have it claimed again at once, and again.
|
|
1924
|
-
if (stopReason?.kind === "command")
|
|
1925
|
-
return await writeEnd(harness, root, gate, stopEnd(stopReason.cancel), [stopReason.commandId], await cutRows(claim, spec, "stopped"));
|
|
1926
|
-
gate.seal(new Parked());
|
|
1927
|
-
return { state: "parked" };
|
|
1928
|
-
}
|
|
1929
|
-
if (follow) {
|
|
1930
|
-
const theRoot = root;
|
|
1931
|
-
await harness.commit((tx) => tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "person", text: follow.text, origin: { kind: "server", reason: "approval" }, at: now() } }), context);
|
|
1932
|
-
await session.send(follow.text, { id: `agentrun:approval:${follow.callIds[0]}` });
|
|
1933
|
-
followedUp = true;
|
|
1934
|
-
}
|
|
1935
|
-
}
|
|
1936
2360
|
if (reopen) {
|
|
1937
2361
|
// Every row the runner read for this claim has reached its command() (deps.delivered): the follow-up's steer, sent
|
|
1938
2362
|
// by steer() as a turn, is the turn this claim runs. With none (a claim after that turn's answer), it ends again.
|
|
@@ -1947,10 +2371,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1947
2371
|
await Promise.race([firstInputPlaced, stopping, parking, harness.closed.then(() => undefined, () => undefined), lost]);
|
|
1948
2372
|
}
|
|
1949
2373
|
const sent = reopen.sent;
|
|
2374
|
+
const fed = reopen.feedback;
|
|
1950
2375
|
reopen = undefined;
|
|
1951
2376
|
if (sent) {
|
|
1952
2377
|
await sent.catch(() => undefined);
|
|
1953
2378
|
followedUp = true;
|
|
2379
|
+
if (fed)
|
|
2380
|
+
feedbackNow = fed;
|
|
1954
2381
|
}
|
|
1955
2382
|
}
|
|
1956
2383
|
// A claim that starts a turn (the input, a recovery, a follow-up) waits for that turn's end: state is the session as
|
|
@@ -1958,9 +2385,195 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1958
2385
|
// A reopen of a session still new whose message was never placed (the run stopped, parked or was lost meanwhile):
|
|
1959
2386
|
// nothing is sent, least of all the input the person stopped.
|
|
1960
2387
|
const firstUnplaced = firstInputPlaced !== undefined && !followedUp;
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
2388
|
+
// A CLI's end-of-run turn an earlier claim sent and never saw end (its prompt the last turn on the record, no
|
|
2389
|
+
// submission): the job's turn had ended before it, so the session's open turn is that look-back. One a person
|
|
2390
|
+
// stopped with a follow-up after it is not: the open turn is the follow-up's, recovered as the job's. It is settled, never recovered:
|
|
2391
|
+
// recovered, it ran as the job's turn, its answer lost, and the end-of-run step then asked the CLI again, a paid
|
|
2392
|
+
// look-back twice on one claim. The step asks it again once, under the run's cap (an earlier request of it booked
|
|
2393
|
+
// at its hold, bookCut), or skips it, reading what the first ask kept (EndOfRunTurn ask's `kept`). A feedback round
|
|
2394
|
+
// (feedbackNow) sends no turn of its own before its look-back, so its open look-back is settled the same way.
|
|
2395
|
+
if ((!followedUp || feedbackNow !== undefined) && !firstUnplaced && session.state === "open_turn" && (await record?.lookingBack()))
|
|
2396
|
+
await session.settleOpenTurn();
|
|
2397
|
+
/** The run's learned workflow, run first (AdapterRunSpec.workflowFirst), once for the run: the person's input on the
|
|
2398
|
+
* record, then the workflow's call through the session's own learned_workflow tool as the loop wrapped it (its gate
|
|
2399
|
+
* with its ask, its record, its flush and booking, the stop's abort), under one call id (replay never: a call a
|
|
2400
|
+
* crash cut is ended interrupted and handed back, never run again), then the WORKFLOW_FIRST entry saying how it
|
|
2401
|
+
* ended, with its answer as the model's message when it answered, in one commit. pi keeps no record of the loop's
|
|
2402
|
+
* (its own entries are its record): its call goes on a record of its own for this step, the same entries. A claim
|
|
2403
|
+
* that finds the entry or the call's end takes it as it is. Undefined: the run is its agent's (the tool is not the
|
|
2404
|
+
* run's, or the gate denies it before anything is written); "park": the call waits for a person's approval. */
|
|
2405
|
+
/** The session's tools as calls nested in the workflow served first (`outer`), with no harness to nest them: each
|
|
2406
|
+
* asked at the gate as its own tool under `<outer>/<key>` (a deny, its argument pins; an ask passes when the card
|
|
2407
|
+
* a person approved for `outer` named the tool, and any other is refused, since a workflow served first never parks
|
|
2408
|
+
* part way), then run as this loop wraps the tool (its record, its flush and booking, the stop's abort). The call
|
|
2409
|
+
* is never run again, so a value is its first run's as it is. */
|
|
2410
|
+
const servedNested = (outer) => ({
|
|
2411
|
+
async call(name, args, key, own) {
|
|
2412
|
+
const tool = tools.find((one) => one.name === name);
|
|
2413
|
+
if (!tool)
|
|
2414
|
+
return { text: `${name} is no tool of this run.`, isError: true, refused: true, fresh: true };
|
|
2415
|
+
const callId = `${outer}/${key}`;
|
|
2416
|
+
const catalog = mcp?.catalogOf(name) ?? name;
|
|
2417
|
+
const asked = spec.gate?.askedAs?.(catalog) ?? catalog;
|
|
2418
|
+
const given = (await spec.gate?.({ callId, tool: catalog, args })) ?? "allow";
|
|
2419
|
+
if (given === "deny")
|
|
2420
|
+
return { text: setToDenyText(asked, undefined, "server", "no"), isError: true, refused: true, fresh: true };
|
|
2421
|
+
if (typeof given === "object" && "deny" in given)
|
|
2422
|
+
return { text: given.deny, isError: true, refused: true, fresh: true };
|
|
2423
|
+
if (given !== "allow" && !learnedApprovedTools(await approvedCardOver(callId, spec.gate?.askedAs?.(LEARNED_WORKFLOW_TOOL) ?? LEARNED_WORKFLOW_TOOL)).has(catalog)) {
|
|
2424
|
+
return { text: `This ${asked} call needs a person's approval, which a learned workflow run first cannot wait for; it was not run.`, isError: true, refused: true, fresh: true };
|
|
2425
|
+
}
|
|
2426
|
+
const got = await tool.call(args, { callId, signal: own ? AbortSignal.any([stopAbort.signal, own]) : stopAbort.signal });
|
|
2427
|
+
return { text: got.text, ...(got.isError ? { isError: true } : {}), ...(got.images?.length ? { images: got.images } : {}), ...(got.structured !== undefined ? { structured: got.structured } : {}), fresh: true };
|
|
2428
|
+
},
|
|
2429
|
+
memo: async (_key, value) => (typeof value === "function" ? value() : value),
|
|
2430
|
+
});
|
|
2431
|
+
const serveFirst = async (first) => {
|
|
2432
|
+
// The session's learned_workflow as this loop wraps a tool, but nesting nothing of the harness's: a call a crash
|
|
2433
|
+
// cut is ended interrupted and handed back, never run again (its record's start is not marked `nests`).
|
|
2434
|
+
const bare = spec.session.tools.find((tool) => tool.name === LEARNED_WORKFLOW_TOOL);
|
|
2435
|
+
if (!bare || !tools.some((tool) => tool.name === LEARNED_WORKFLOW_TOOL))
|
|
2436
|
+
return undefined;
|
|
2437
|
+
const { nests: _nests, ...plain } = bare;
|
|
2438
|
+
const learned = hosted(plain);
|
|
2439
|
+
const [on, theRoot, theGate] = [harness, root, gate];
|
|
2440
|
+
const args = { name: first.name, input: first.input };
|
|
2441
|
+
const call = { callId: WORKFLOW_FIRST_CALL, tool: LEARNED_WORKFLOW_TOOL, args };
|
|
2442
|
+
const job = (text) => ({ outcome: "handed_back", text: handbackText(first.name, text, spec.input) });
|
|
2443
|
+
const kept = findData(await entriesOf(theGate.journal, theRoot.id, context), WORKFLOW_FIRST, () => true);
|
|
2444
|
+
const rec = record ?? (await openCliRecord(on, theGate.journal, context, now, spec.cwd));
|
|
2445
|
+
const ended = rec.endOf(WORKFLOW_FIRST_CALL);
|
|
2446
|
+
/** The call's answer as the run takes it: one the agent could not stand behind goes back to it, either one the
|
|
2447
|
+
* tool cut (learnedText: no agent turn could recover its ending) or, for an agent with an output schema, one that
|
|
2448
|
+
* cannot be shaped to it (answerAsServed: the answer as the run serves it, the one replay and grading read; why
|
|
2449
|
+
* goes back with it). Pure in the call's end, so a claim that recovers a handback rebuilds the same words. */
|
|
2450
|
+
const taken = (got) => {
|
|
2451
|
+
if (got.isError)
|
|
2452
|
+
return got;
|
|
2453
|
+
if (got.text.length > LEARNED_CLIP)
|
|
2454
|
+
return { ...got, isError: true };
|
|
2455
|
+
const asServed = answerAsServed(got.text, first.outputSchema);
|
|
2456
|
+
return "why" in asServed ? { text: `${got.text}\n\n[${asServed.why}]`, isError: true } : { ...got, text: asServed.text };
|
|
2457
|
+
};
|
|
2458
|
+
const recorded = (end) => ({ text: end.output ?? (end.status === "interrupted" ? endedAnswer(LEARNED_WORKFLOW_TOOL, end).text : ""), isError: end.status !== "done" });
|
|
2459
|
+
if (kept?.outcome === "answered")
|
|
2460
|
+
return { outcome: "answered", text: ended?.output ?? "" };
|
|
2461
|
+
// Handed back on an earlier claim whose handback never reached the agent (the session is still new): sent now, in
|
|
2462
|
+
// the words that claim would have sent (its why included).
|
|
2463
|
+
if (kept)
|
|
2464
|
+
return job(ended ? taken(recorded(ended)).text : "");
|
|
2465
|
+
if (!ended) {
|
|
2466
|
+
// A deny before anything is written leaves the run its agent's, as if the workflow were not there.
|
|
2467
|
+
const before = await spec.gate?.({ callId: call.callId, tool: call.tool, args });
|
|
2468
|
+
if (before === "deny" || (typeof before === "object" && "deny" in before))
|
|
2469
|
+
return undefined;
|
|
2470
|
+
if (spec.inputOrigin)
|
|
2471
|
+
await rec.input(spec.input, spec.inputOrigin);
|
|
2472
|
+
else
|
|
2473
|
+
await rec.person(spec.input);
|
|
2474
|
+
}
|
|
2475
|
+
let answer;
|
|
2476
|
+
if (ended)
|
|
2477
|
+
answer = recorded(ended);
|
|
2478
|
+
else {
|
|
2479
|
+
const verdict = await preIntentGate(spec, hooks, wrapUp, (asked) => rec.park(asked.callId, asked.tool, asked.args ?? {}, false))(call, context);
|
|
2480
|
+
if (verdict !== "allow" && "park" in verdict)
|
|
2481
|
+
return "park";
|
|
2482
|
+
if (verdict !== "allow") {
|
|
2483
|
+
// Refused at its gate once the job was on the record (its ask declined, the cap's wrap-up): handed back in
|
|
2484
|
+
// the gate's words, the call ended refused.
|
|
2485
|
+
if (rec.unsentParked().includes(WORKFLOW_FIRST_CALL))
|
|
2486
|
+
await rec.end(WORKFLOW_FIRST_CALL, "refused", verdict.deny);
|
|
2487
|
+
else
|
|
2488
|
+
await rec.refused(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false, verdict.deny);
|
|
2489
|
+
answer = { text: verdict.deny, isError: true };
|
|
2490
|
+
}
|
|
2491
|
+
else {
|
|
2492
|
+
// A CLI's record takes the call's start and end inside the wrapper; pi's step record here.
|
|
2493
|
+
if (!record)
|
|
2494
|
+
await rec.start(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false);
|
|
2495
|
+
const got = await learned.call(args, { callId: WORKFLOW_FIRST_CALL, signal: stopAbort.signal, nested: servedNested(WORKFLOW_FIRST_CALL) });
|
|
2496
|
+
answer = { text: got.text, isError: got.isError === true };
|
|
2497
|
+
if (!record)
|
|
2498
|
+
await rec.end(WORKFLOW_FIRST_CALL, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
if (stopAbort.signal.aborted)
|
|
2502
|
+
return undefined;
|
|
2503
|
+
answer = taken(answer);
|
|
2504
|
+
const outcome = answer.isError ? "handed_back" : "answered";
|
|
2505
|
+
const data = { workflow: first.name, digest: first.digest, ...(first.promotion !== undefined ? { promotion: first.promotion } : {}), revision: first.revision, call: WORKFLOW_FIRST_CALL, outcome };
|
|
2506
|
+
await on.commit(async (tx) => {
|
|
2507
|
+
if (outcome === "answered")
|
|
2508
|
+
await tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "model", text: answer.text, at: now() } });
|
|
2509
|
+
await tx.appendEntry(theRoot.id, { kind: WORKFLOW_FIRST, data: data });
|
|
2510
|
+
}, context);
|
|
2511
|
+
return outcome === "answered" ? { outcome, text: answer.text } : job(answer.text);
|
|
2512
|
+
};
|
|
2513
|
+
// The run's learned workflow first, before anything is sent to its agent (runner/workflow-first.ts): its answer is
|
|
2514
|
+
// the run's, or its handback is the agent's first input. Only while the session is new: a claim that finds a turn
|
|
2515
|
+
// under way (the handback sent) never runs it again.
|
|
2516
|
+
let served;
|
|
2517
|
+
// A workflow this run already served or handed back on an earlier claim (its end on the root): recovered whatever the
|
|
2518
|
+
// money rule says now, so a crash before the handback never makes the agent redo finished work.
|
|
2519
|
+
const keptFirst = spec.workflowFirst || !spec.workflowRevise || followedUp || firstUnplaced || session.state !== "new" ? undefined : findData(await entriesOf(gate.journal, root.id, context), WORKFLOW_FIRST, () => true);
|
|
2520
|
+
const recovered = keptFirst && keptFirst.outcome !== "needs_revision" ? { name: keptFirst.workflow, digest: keptFirst.digest, revision: keptFirst.revision, input: {}, ...(spec.workflowRevise?.outputSchema !== undefined ? { outputSchema: spec.workflowRevise.outputSchema } : {}) } : undefined;
|
|
2521
|
+
const firstToServe = spec.workflowFirst ?? recovered;
|
|
2522
|
+
// A fitting workflow the money rule stopped: why, on the root, once for the run, as the agent takes it.
|
|
2523
|
+
if (spec.workflowRevise && !followedUp && !firstUnplaced && session.state === "new") {
|
|
2524
|
+
const [on, theRoot, theGate] = [harness, root, gate];
|
|
2525
|
+
if (!findData(await entriesOf(theGate.journal, theRoot.id, context), WORKFLOW_FIRST, () => true)) {
|
|
2526
|
+
const { workflow, digest, revision, served_usd, by_hand_usd, runs } = spec.workflowRevise;
|
|
2527
|
+
const data = { workflow, digest, revision, outcome: "needs_revision", served_usd, by_hand_usd, runs };
|
|
2528
|
+
await on.commit(async (tx) => {
|
|
2529
|
+
await tx.appendEntry(theRoot.id, { kind: WORKFLOW_FIRST, data: data });
|
|
2530
|
+
}, context);
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
if (firstToServe && !followedUp && !firstUnplaced && session.state === "new") {
|
|
2534
|
+
let release;
|
|
2535
|
+
servingFirst = new Promise((resolve) => (release = resolve));
|
|
2536
|
+
try {
|
|
2537
|
+
const step = await serveFirst(firstToServe);
|
|
2538
|
+
// A stop while it ran, or while it was asked, ends the run stopped, its call ended interrupted (or its ask
|
|
2539
|
+
// withdrawn) on the record: given back parked with its stop untaken, the run would be claimed again only to end
|
|
2540
|
+
// then. A lost claim leaves it.
|
|
2541
|
+
const cutBy = stopReason;
|
|
2542
|
+
if (step === "park" && cutBy?.kind !== "command") {
|
|
2543
|
+
await releaseHost(harness);
|
|
2544
|
+
await keepAtPark(harness, "workflow");
|
|
2545
|
+
gate.seal(new Parked());
|
|
2546
|
+
return { state: "parked" };
|
|
2547
|
+
}
|
|
2548
|
+
if (cutBy?.kind === "command")
|
|
2549
|
+
return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
|
|
2550
|
+
if (cutBy || deps.signal.aborted || step === "park")
|
|
2551
|
+
return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
|
|
2552
|
+
served = step;
|
|
2553
|
+
// A replay run (runner/promotion.ts) ends on its workflow's step whichever way it ended: its hand-back is the
|
|
2554
|
+
// agent's recorded answer for that input, read from the graded run, never asked of the agent again.
|
|
2555
|
+
if (served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay))
|
|
2556
|
+
turnsOver = true;
|
|
2557
|
+
else if (served?.outcome === "handed_back") {
|
|
2558
|
+
// The agent's first input: the handback, the server's (its row "AgentRun: …"), the job whole after it. Cut of
|
|
2559
|
+
// every secret the runner holds: the workflow's words may quote what its steps read.
|
|
2560
|
+
const text = deps.redact ? deps.redact(served.text) : served.text;
|
|
2561
|
+
await record?.message(text, HANDED_BACK_ORIGIN);
|
|
2562
|
+
await session.send(text, { origin: HANDED_BACK_ORIGIN });
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
2565
|
+
finally {
|
|
2566
|
+
servingFirst = undefined;
|
|
2567
|
+
release();
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
const placed = served !== undefined || followedUp || (session.state !== "idle" && !firstUnplaced);
|
|
2571
|
+
// The end-of-run turn found open (lookingBackOpen), with no turn of this claim's sent before it: never recovered as
|
|
2572
|
+
// the job's; the run goes to its end-of-run step, on the job's end the claim that asked it kept (jobEndKept).
|
|
2573
|
+
const lookingBack = lookingBackOpen && !followedUp && served === undefined;
|
|
2574
|
+
if (served || followedUp || firstUnplaced || lookingBack) {
|
|
2575
|
+
// The workflow answered, or handed back and its handback is the turn; the follow-up is the turn this claim runs,
|
|
2576
|
+
// or there is none.
|
|
1964
2577
|
}
|
|
1965
2578
|
else if (session.state === "new") {
|
|
1966
2579
|
// A trigger's first input is its origin's (the launch's), never written as the person's.
|
|
@@ -1975,8 +2588,12 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1975
2588
|
// A message handed over while the session was new is placed from here on, after what was just sent.
|
|
1976
2589
|
inputSent();
|
|
1977
2590
|
// The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
|
|
1978
|
-
// its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold.
|
|
1979
|
-
|
|
2591
|
+
// its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold. None
|
|
2592
|
+
// when the workflow answered: the run ends on its answer.
|
|
2593
|
+
// A feedback round (feedbackNow) asks no turn either: the run goes to its end-of-run turn. Nor does a claim that found
|
|
2594
|
+
// that turn open (lookingBack).
|
|
2595
|
+
const alone = served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay === true) || feedbackNow !== undefined || lookingBack;
|
|
2596
|
+
let turn = alone ? new Promise(() => { }) : placed ? session.turnEnd() : idleTurnOf(harness, root);
|
|
1980
2597
|
// Set on every way out of the loop below but parkOn's, which returns before it is read.
|
|
1981
2598
|
let data;
|
|
1982
2599
|
let failedWith;
|
|
@@ -1984,173 +2601,200 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1984
2601
|
let parkOn;
|
|
1985
2602
|
/** The ask_person call the run waits on in its claim, while it does. */
|
|
1986
2603
|
let waitingOn;
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
await session.interrupt().catch(() => { });
|
|
2007
|
-
await harness.waitForIdle(context).catch(() => { });
|
|
2008
|
-
return true;
|
|
2009
|
-
})();
|
|
2010
|
-
let timer;
|
|
2011
|
-
const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
|
|
2012
|
-
clearTimeout(timer);
|
|
2013
|
-
// A cancel ends the same way, in its own words (main's "cancelled") and its own outcome; the bound is the same.
|
|
2014
|
-
const stopped = stopEnd(stopReason.cancel);
|
|
2015
|
-
const cut = await cutRows(claim, spec, "stopped");
|
|
2016
|
-
if (!settled)
|
|
2017
|
-
return await writeEnd(harness, root, gate, { state: "failed", summary: `${stopped.summary}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
|
|
2018
|
-
return await writeEnd(harness, root, gate, stopped, [stopReason.commandId], cut);
|
|
2019
|
-
}
|
|
2020
|
-
// The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
|
|
2021
|
-
// it kept went): the run parks on its question, as it does with nothing open.
|
|
2022
|
-
if (end === "lapsed") {
|
|
2023
|
-
parkOn = waitingOn;
|
|
2024
|
-
break;
|
|
2025
|
-
}
|
|
2026
|
-
const outcome = (await turn);
|
|
2027
|
-
// What the model said last, on the record before the run's end.
|
|
2028
|
-
await record?.flushText();
|
|
2029
|
-
// The turn's end on the record, after its last text: a CLI run reads working until here.
|
|
2030
|
-
await record?.turnEnded(outcome.status, outcome.error === undefined ? undefined : deps.redact ? deps.redact(outcome.error) : outcome.error);
|
|
2031
|
-
await harness.waitForIdle(context);
|
|
2032
|
-
const settledEntries = await entriesOf(gate.journal, root.id, context);
|
|
2033
|
-
const cutOff = restartLimited(settledEntries);
|
|
2034
|
-
// A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
|
|
2035
|
-
// answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
|
|
2036
|
-
await bookingsSettled();
|
|
2037
|
-
const over = cutOff ? undefined : await overCap();
|
|
2038
|
-
// A failed CLI turn: a message the person sent while it ran may not have reached the loop yet (the runner's next
|
|
2039
|
-
// poll), and the run's status is its last turn's end, so it is handed on now (bounded), as a finished turn's is.
|
|
2040
|
-
if (!cutOff && !over && !refused && outcome.status === "failed" && spec.record === "loop" && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow && !stopReason) {
|
|
2041
|
-
let bound;
|
|
2042
|
-
await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
|
|
2043
|
-
clearTimeout(bound);
|
|
2044
|
-
// A stop or cancel among the delivered rows: the run ends stopped in its words, never failed. Read past the
|
|
2045
|
-
// narrowing TypeScript did before the delivery.
|
|
2046
|
-
const cutBy = stopReason;
|
|
2047
|
-
if (cutBy?.kind === "command")
|
|
2048
|
-
return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
|
|
2049
|
-
if (cutBy || deps.signal.aborted)
|
|
2050
|
-
return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
|
|
2051
|
-
}
|
|
2052
|
-
if (cutOff)
|
|
2053
|
-
data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
|
|
2054
|
-
else if (over)
|
|
2055
|
-
data = { state: "failed", summary: over };
|
|
2056
|
-
else if (outcome.status !== "completed" && refused) {
|
|
2057
|
-
// 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
|
|
2058
|
-
// raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
|
|
2059
|
-
// check's own words, never as a run with no answer.
|
|
2060
|
-
const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
|
|
2061
|
-
if (park?.outcome === "parked" && pausedAtRefusal) {
|
|
2062
|
-
// Its pause and the run parked landed before pi heard of the refusal.
|
|
2063
|
-
await releaseHost(harness);
|
|
2064
|
-
gate.seal(new Parked());
|
|
2065
|
-
return { state: "parked" };
|
|
2604
|
+
if (alone && lookingBack)
|
|
2605
|
+
({ end: data, failedWith } = await jobEndKept(root));
|
|
2606
|
+
else if (alone)
|
|
2607
|
+
data = { state: "ended" };
|
|
2608
|
+
else
|
|
2609
|
+
for (;;) {
|
|
2610
|
+
let end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed"), askCut.asked.then(() => "cut")]);
|
|
2611
|
+
// Parked on a call held at the gate (a CLI's at its tool bridge): the answer that made the call may still be
|
|
2612
|
+
// streaming, and its booking lands before the claim goes (parkClaim). pi's calls already running beside it end
|
|
2613
|
+
// first (siblingsSettled), so their results are on the journal for the resume. A person's stop or cancel while
|
|
2614
|
+
// they do ends the run in its words, as it would have before the park.
|
|
2615
|
+
if (end === "parked" && spec.record === "loop")
|
|
2616
|
+
return await parkClaim(harness, gate, "approval");
|
|
2617
|
+
if (end === "parked") {
|
|
2618
|
+
parkPending = true;
|
|
2619
|
+
await siblingsSettled(harness, spec);
|
|
2620
|
+
if (stopReason?.kind !== "command")
|
|
2621
|
+
return await parkClaim(harness, gate, "approval");
|
|
2622
|
+
end = "stop";
|
|
2066
2623
|
}
|
|
2067
|
-
if (
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
}
|
|
2071
|
-
else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
|
|
2072
|
-
// A CLI turn that failed with a message queued behind it: the run's status is its last turn's end, so the
|
|
2073
|
-
// queued message's turn runs, and the failure stays in the timeline as the error row a chat keeps before a good
|
|
2074
|
-
// answer (the same row the run's end would have written).
|
|
2075
|
-
const said = outcome.error?.trim() ?? "";
|
|
2076
|
-
const rootId = root.id;
|
|
2077
|
-
await harness.commit((tx) => tx.appendEntry(rootId, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", said ? cutWhole(deps.redact ? deps.redact(said) : said, TURN_ERROR_MAX) : "the turn gave no answer (failed)", now())] }), context);
|
|
2078
|
-
turn = sendAfterTurn(gate, afterTurn.shift());
|
|
2079
|
-
continue;
|
|
2080
|
-
}
|
|
2081
|
-
else if (outcome.status === "interrupted" && spec.record === "loop" && !outcome.error?.trim()) {
|
|
2082
|
-
// A CLI turn its harness ended on its own, with no stop or cancel from a person and no error of its own: the
|
|
2083
|
-
// turn is over, the run is not. It waits for the person as after a stop (a message reopens it), never failed
|
|
2084
|
-
// with no answer (the status reader's contract: an interrupted newest turn is input_required, turns.ts).
|
|
2085
|
-
data = { state: "stopped", outcome: "stopped", summary: "the turn was interrupted" };
|
|
2086
|
-
}
|
|
2087
|
-
else if (outcome.status !== "completed") {
|
|
2088
|
-
// A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
|
|
2089
|
-
// the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
|
|
2090
|
-
// the loop's own words.
|
|
2091
|
-
const said = outcome.error?.trim();
|
|
2092
|
-
data = { state: "failed", summary: said ? cutWhole(said, TURN_ERROR_MAX) : `the run gave no answer (${outcome.status})` };
|
|
2093
|
-
// A CLI's turn (record "loop"; pi journals its own): its error is also main's error row, pi's error answer in the
|
|
2094
|
-
// end's commit, cut of every secret the runner holds, so the timeline shows it as an error row with no key in it.
|
|
2095
|
-
if (said && spec.record === "loop")
|
|
2096
|
-
failedWith = deps.redact ? deps.redact(said) : said;
|
|
2097
|
-
}
|
|
2098
|
-
else if (endedOnTurnEndingTool(settledEntries) !== undefined) {
|
|
2099
|
-
// The turn ended on a tool that waits on the person (ask_person ended its turn). With something a tool host keeps
|
|
2100
|
-
// open for them meanwhile (the browser's session, its live view and its page), the run waits for their answer in
|
|
2101
|
-
// its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
|
|
2102
|
-
// its next turn, on the same session. With nothing open, it parks (parkOnAsk).
|
|
2103
|
-
const callId = endedOnTurnEndingTool(settledEntries);
|
|
2104
|
-
// Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
|
|
2105
|
-
// person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
|
|
2106
|
-
if (pendingPause) {
|
|
2107
|
-
pendingPause = undefined;
|
|
2108
|
-
await keepPending(null);
|
|
2624
|
+
if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
|
|
2625
|
+
await closeSession();
|
|
2626
|
+
continue passes;
|
|
2109
2627
|
}
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2628
|
+
if (end === "closed" || (stopReason && stopReason.kind !== "command"))
|
|
2629
|
+
return await interrupted(stopReason?.kind ?? "the Session closed");
|
|
2630
|
+
if (end === "stop" && stopReason?.kind === "command") {
|
|
2631
|
+
// Bounded, the interrupt included: a tool call that ignores its abort keeps the turn from settling, and the claim
|
|
2632
|
+
// is renewed meanwhile. Past the bound the run is failed in words, the stop row taken in that end's commit.
|
|
2633
|
+
const settleMs = spec.stopSettleMs ?? STOP_SETTLE_MS;
|
|
2634
|
+
const settling = (async () => {
|
|
2635
|
+
const interrupting = session.interrupt().catch(() => { });
|
|
2636
|
+
// A request held after a question to the person (TurnCut) is refused once the stop is under way.
|
|
2637
|
+
askCut.done();
|
|
2638
|
+
await interrupting;
|
|
2639
|
+
await harness.waitForIdle(context).catch(() => { });
|
|
2640
|
+
return true;
|
|
2641
|
+
})();
|
|
2642
|
+
let timer;
|
|
2643
|
+
const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
|
|
2644
|
+
clearTimeout(timer);
|
|
2645
|
+
// A cancel ends the same way, in its own words (main's "cancelled") and its own outcome; the bound is the same.
|
|
2646
|
+
const stopped = stopEnd(stopReason.cancel);
|
|
2647
|
+
const cut = await cutRows(claim, spec, "stopped");
|
|
2648
|
+
if (!settled)
|
|
2649
|
+
return await writeEnd(harness, root, gate, { state: "failed", summary: `${stopped.summary}, but the turn did not settle within ${settleMs / 1000} s: a tool call ignored its abort` }, [stopReason.commandId], cut);
|
|
2650
|
+
return await writeEnd(harness, root, gate, stopped, [stopReason.commandId], cut);
|
|
2115
2651
|
}
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
//
|
|
2124
|
-
|
|
2125
|
-
|
|
2652
|
+
// The wait in the claim lapsed before the person answered (the cap had no room for more of their time, or the browser
|
|
2653
|
+
// it kept went): the run parks on its question, as it does with nothing open.
|
|
2654
|
+
if (end === "lapsed") {
|
|
2655
|
+
parkOn = waitingOn;
|
|
2656
|
+
break;
|
|
2657
|
+
}
|
|
2658
|
+
const outcome = end === "cut" ? await cutAtQuestion(session, turn, spec.stopSettleMs ?? STOP_SETTLE_MS) : (await turn);
|
|
2659
|
+
// A turn that ended with no cut (its CLI asked nothing more after its question): nothing armed past it.
|
|
2660
|
+
askCut.done();
|
|
2661
|
+
// What the model said last, on the record before the run's end.
|
|
2662
|
+
await record?.flushText();
|
|
2663
|
+
// The turn's end on the record, after its last text: a CLI run reads working until here.
|
|
2664
|
+
await record?.turnEnded(outcome.status, outcome.error === undefined ? undefined : deps.redact ? deps.redact(outcome.error) : outcome.error);
|
|
2665
|
+
await harness.waitForIdle(context);
|
|
2666
|
+
const settledEntries = await entriesOf(gate.journal, root.id, context);
|
|
2667
|
+
const cutOff = restartLimited(settledEntries);
|
|
2668
|
+
// A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
|
|
2669
|
+
// answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
|
|
2670
|
+
await bookingsSettled();
|
|
2671
|
+
// A run a paid call stopped for good (paid-calls.ts stopRun) ends in that call's words, past its cap too.
|
|
2672
|
+
const stoppedBy = pendingPause?.forGood ? pendingPause : undefined;
|
|
2673
|
+
const over = cutOff || stoppedBy ? undefined : await overCap();
|
|
2674
|
+
// A failed CLI turn: a message the person sent while it ran may not have reached the loop yet (the runner's next
|
|
2675
|
+
// poll), and the run's status is its last turn's end, so it is handed on now (bounded), as a finished turn's is.
|
|
2676
|
+
if (!cutOff && !over && !refused && outcome.status === "failed" && spec.record === "loop" && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow && !stopReason) {
|
|
2126
2677
|
let bound;
|
|
2127
2678
|
await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
|
|
2128
2679
|
clearTimeout(bound);
|
|
2129
|
-
// A stop or cancel among
|
|
2130
|
-
//
|
|
2680
|
+
// A stop or cancel among the delivered rows: the run ends stopped in its words, never failed. Read past the
|
|
2681
|
+
// narrowing TypeScript did before the delivery.
|
|
2131
2682
|
const cutBy = stopReason;
|
|
2132
2683
|
if (cutBy?.kind === "command")
|
|
2133
2684
|
return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
|
|
2134
2685
|
if (cutBy || deps.signal.aborted)
|
|
2135
2686
|
return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
|
|
2136
2687
|
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
if (
|
|
2140
|
-
|
|
2141
|
-
|
|
2688
|
+
if (cutOff)
|
|
2689
|
+
data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
|
|
2690
|
+
else if (over)
|
|
2691
|
+
data = { state: "failed", summary: over };
|
|
2692
|
+
else if (stoppedBy)
|
|
2693
|
+
data = { state: "failed", summary: stoppedBy.refuse };
|
|
2694
|
+
else if (outcome.status !== "completed" && refused) {
|
|
2695
|
+
// 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
|
|
2696
|
+
// raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
|
|
2697
|
+
// check's own words, never as a run with no answer.
|
|
2698
|
+
const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
|
|
2699
|
+
// Its pause and the run parked landed before pi heard of the refusal.
|
|
2700
|
+
if (park?.outcome === "parked" && pausedAtRefusal)
|
|
2701
|
+
return await parkClaim(harness, gate, "refusal");
|
|
2702
|
+
if (park?.outcome === "parked")
|
|
2703
|
+
return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words }, "refusal");
|
|
2704
|
+
data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
|
|
2142
2705
|
}
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2706
|
+
else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
|
|
2707
|
+
// A CLI turn that failed with a message queued behind it: the run's status is its last turn's end, so the
|
|
2708
|
+
// queued message's turn runs, and the failure stays in the timeline as the error row a chat keeps before a good
|
|
2709
|
+
// answer (the same row the run's end would have written).
|
|
2710
|
+
const said = outcome.error?.trim() ?? "";
|
|
2711
|
+
const rootId = root.id;
|
|
2712
|
+
await harness.commit((tx) => tx.appendEntry(rootId, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", said ? cutWhole(deps.redact ? deps.redact(said) : said, TURN_ERROR_MAX) : "the turn gave no answer (failed)", now())] }), context);
|
|
2713
|
+
turn = sendAfterTurn(gate, afterTurn.shift());
|
|
2148
2714
|
continue;
|
|
2149
2715
|
}
|
|
2150
|
-
|
|
2716
|
+
else if (outcome.status === "interrupted" && spec.record === "loop" && !outcome.error?.trim()) {
|
|
2717
|
+
// A CLI turn its harness ended on its own, with no stop or cancel from a person and no error of its own: the
|
|
2718
|
+
// turn is over, the run is not. It waits for the person as after a stop (a message reopens it), never failed
|
|
2719
|
+
// with no answer (the status reader's contract: an interrupted newest turn is input_required, turns.ts).
|
|
2720
|
+
data = { state: "stopped", outcome: "stopped", summary: "the turn was interrupted" };
|
|
2721
|
+
}
|
|
2722
|
+
else if (outcome.status !== "completed") {
|
|
2723
|
+
// A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
|
|
2724
|
+
// the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
|
|
2725
|
+
// the loop's own words.
|
|
2726
|
+
const said = outcome.error?.trim();
|
|
2727
|
+
data = { state: "failed", summary: said ? cutWhole(said, TURN_ERROR_MAX) : `the run gave no answer (${outcome.status})` };
|
|
2728
|
+
// A CLI's turn (record "loop"; pi journals its own): its error is also main's error row, pi's error answer in the
|
|
2729
|
+
// end's commit, cut of every secret the runner holds, so the timeline shows it as an error row with no key in it.
|
|
2730
|
+
if (said && spec.record === "loop")
|
|
2731
|
+
failedWith = deps.redact ? deps.redact(said) : said;
|
|
2732
|
+
}
|
|
2733
|
+
else if (turnEndedOnAsk(settledEntries) !== undefined) {
|
|
2734
|
+
// The turn ended on a tool that waits on the person (ask_person ended its turn). With something a tool host keeps
|
|
2735
|
+
// open for them meanwhile (the browser's session, its live view and its page), the run waits for their answer in
|
|
2736
|
+
// its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
|
|
2737
|
+
// its next turn, on the same session. With nothing open, it parks (parkOnAsk).
|
|
2738
|
+
const callId = turnEndedOnAsk(settledEntries);
|
|
2739
|
+
// Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
|
|
2740
|
+
// person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
|
|
2741
|
+
if (pendingPause) {
|
|
2742
|
+
pendingPause = undefined;
|
|
2743
|
+
await keepPending(null);
|
|
2744
|
+
}
|
|
2745
|
+
const waited = await waitInClaim(harness, callId);
|
|
2746
|
+
if (waited) {
|
|
2747
|
+
turn = waited.next;
|
|
2748
|
+
waitingOn = callId;
|
|
2749
|
+
continue;
|
|
2750
|
+
}
|
|
2751
|
+
parkOn = callId;
|
|
2752
|
+
}
|
|
2753
|
+
else {
|
|
2754
|
+
// An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
|
|
2755
|
+
// the direct loop's rule: the words are loop-contract's cutAtLimit).
|
|
2756
|
+
const cut = cutLast(settledEntries);
|
|
2757
|
+
// The rows the runner has not handed on yet (its next poll may be half a second away): handed on now, so a
|
|
2758
|
+
// message sent while the turn worked is one of the run's turns below, never refused by its end. Bounded: a
|
|
2759
|
+
// command that waits on this loop cannot hold its end.
|
|
2760
|
+
if (!cut && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow) {
|
|
2761
|
+
let bound;
|
|
2762
|
+
await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
|
|
2763
|
+
clearTimeout(bound);
|
|
2764
|
+
// A stop or cancel among them: the run ends stopped in its words, its row taken, never completed. Its turn
|
|
2765
|
+
// has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
|
|
2766
|
+
const cutBy = stopReason;
|
|
2767
|
+
if (cutBy?.kind === "command")
|
|
2768
|
+
return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
|
|
2769
|
+
if (cutBy || deps.signal.aborted)
|
|
2770
|
+
return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
|
|
2771
|
+
}
|
|
2772
|
+
// A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
|
|
2773
|
+
const next = cut ? undefined : afterTurn.shift();
|
|
2774
|
+
if (next) {
|
|
2775
|
+
turn = sendAfterTurn(gate, next);
|
|
2776
|
+
continue;
|
|
2777
|
+
}
|
|
2778
|
+
// A message steered into the turn (steeredIn): its answer, in that turn or a run of its own after it, before
|
|
2779
|
+
// the run's end. One already answered settles at once.
|
|
2780
|
+
const steered = cut ? undefined : steeredIn.shift();
|
|
2781
|
+
if (steered !== undefined) {
|
|
2782
|
+
turn = turnOfRequest(harness, root, steered);
|
|
2783
|
+
continue;
|
|
2784
|
+
}
|
|
2785
|
+
// The output contract: an answer whose last json block misses the agent's output schema is asked again, once,
|
|
2786
|
+
// in the same session, never a second time (outputRetried reads the record, so a later claim does not ask
|
|
2787
|
+
// either), and not once the run is wrapping up at its cap (the room left is its answer's, and a retry that
|
|
2788
|
+
// could not fit would park the run for the retry's sake). The run's result then says why (output_error).
|
|
2789
|
+
const miss = cut || spec.outputSchema === undefined || outputRetrySent || outputRetried(settledEntries) ? undefined : outputMiss(lastAnswerText(settledEntries), spec.outputSchema);
|
|
2790
|
+
if (miss !== undefined && !(await wrapUp())) {
|
|
2791
|
+
turn = sendOutputRetry(miss);
|
|
2792
|
+
continue;
|
|
2793
|
+
}
|
|
2794
|
+
data = cut ? { state: "failed", summary: cut } : { state: "ended" };
|
|
2795
|
+
}
|
|
2796
|
+
break;
|
|
2151
2797
|
}
|
|
2152
|
-
break;
|
|
2153
|
-
}
|
|
2154
2798
|
// No turn is sent after this one: a message from here on waits for the run's end (steer).
|
|
2155
2799
|
turnsOver = true;
|
|
2156
2800
|
if (parkOn !== undefined)
|
|
@@ -2190,20 +2834,16 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2190
2834
|
return await writeEnd(harness, root, gate, stopEnd(failingStop.cancel), [failingStop.commandId], await cutRows(claim, spec, "stopped"));
|
|
2191
2835
|
// The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
|
|
2192
2836
|
// writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
|
|
2193
|
-
|
|
2837
|
+
// The run's status is how its job's own turn ended (`data`), whatever the step spends after it: learning spend that
|
|
2838
|
+
// takes the run past its cap is the learning's (askEndOfRun reads overCap after each of its turns), never the run's.
|
|
2839
|
+
// That end is kept before the step's first ask, so a claim that finds its turn open ends the run on it (jobEndKept).
|
|
2840
|
+
if (!lookingBack)
|
|
2841
|
+
await keepJobEnd(harness, root, spec, data, failedWith);
|
|
2842
|
+
const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed", overCap);
|
|
2194
2843
|
if (step.kind === "stopped")
|
|
2195
2844
|
return await writeEnd(harness, root, gate, stopEnd(stopReason?.kind === "command" ? stopReason.cancel : undefined), [step.commandId], await cutRows(claim, spec, "stopped-looking"));
|
|
2196
2845
|
if (step.kind === "interrupted")
|
|
2197
2846
|
return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
|
|
2198
|
-
// The end-of-run turn is one more paid answer: one that passed the cap ends the run in the cap's words (overCap,
|
|
2199
|
-
// read again once its booking settled), as a job's answer that passed it does, never completed. An end already
|
|
2200
|
-
// failed keeps its own words.
|
|
2201
|
-
if (data.state !== "failed") {
|
|
2202
|
-
await bookingsSettled();
|
|
2203
|
-
const overAtEnd = await overCap();
|
|
2204
|
-
if (overAtEnd)
|
|
2205
|
-
data = { state: "failed", summary: overAtEnd };
|
|
2206
|
-
}
|
|
2207
2847
|
return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
|
|
2208
2848
|
}
|
|
2209
2849
|
}
|
|
@@ -2231,6 +2871,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2231
2871
|
heldNow = undefined;
|
|
2232
2872
|
channelNow = undefined;
|
|
2233
2873
|
handingBack = false;
|
|
2874
|
+
reflecting = false;
|
|
2875
|
+
learningRefused = undefined;
|
|
2234
2876
|
deps.live?.(() => undefined);
|
|
2235
2877
|
// A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
|
|
2236
2878
|
// A restart within the claim is no release. What it writes after a lost claim is refused by the fence, as any write.
|
|
@@ -2239,7 +2881,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2239
2881
|
}
|
|
2240
2882
|
}
|
|
2241
2883
|
/** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
|
|
2242
|
-
* `wrapUp`:
|
|
2884
|
+
* `wrapUp`: once the run has taken its share of the cap, the words every call the model makes is refused in (wrapUpText).
|
|
2243
2885
|
* `beforeAsk`: what goes on the record of a call the gate asks about, before its ask is written or read (a CLI's call
|
|
2244
2886
|
* through its tool bridge: its start, marked parked, so its row shows while it waits and reads before its approval). */
|
|
2245
2887
|
function preIntentGate(spec, hooks, wrapUp, beforeAsk) {
|
|
@@ -2251,77 +2893,108 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2251
2893
|
if (reflecting && WRITES.has(call.tool) && underLearning(spec.workRoot, call.args))
|
|
2252
2894
|
return { deny: REFLECT_NOTE_ONLY };
|
|
2253
2895
|
await hooks.beforeIntent(kernelCall);
|
|
2254
|
-
// The tool-call budget, before the gate's settings: a call past it is refused in its fixed words, never parked or
|
|
2255
|
-
// asked about.
|
|
2256
|
-
// A conversation's own budget (a subagent's max_tool_calls) narrows the run's, never widens it.
|
|
2257
|
-
const budget = budgetOf(spec.gate?.toolCalls, call.ownBudget ? await call.ownBudget() : undefined);
|
|
2258
|
-
if (budget !== undefined && call.callsBefore && (await call.callsBefore(budget)) >= budget)
|
|
2259
|
-
return { deny: TOOL_BUDGET_TEXT };
|
|
2260
2896
|
// The cap's wrap-up, the same way: once the run has taken its share of the cap, every call the model makes is refused
|
|
2261
2897
|
// in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
|
|
2262
|
-
|
|
2263
|
-
|
|
2898
|
+
const wrapUpDeny = call.nested !== true ? await wrapUp() : undefined;
|
|
2899
|
+
if (wrapUpDeny !== undefined)
|
|
2900
|
+
return { deny: wrapUpDeny };
|
|
2264
2901
|
// A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
|
|
2265
2902
|
const replayed = call.replayed === true;
|
|
2266
|
-
const
|
|
2267
|
-
|
|
2268
|
-
|
|
2903
|
+
const given = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
|
|
2904
|
+
// An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape).
|
|
2905
|
+
const shown = typeof given === "object" && "ask" in given ? given.ask : undefined;
|
|
2906
|
+
let decision = shown ? "ask" : given;
|
|
2907
|
+
// A call nested in a learned_workflow call a person approved, of an MCP tool that call's card named: its ask is
|
|
2908
|
+
// answered by that approval, as the card they saw named it (never one built again now). Any other asks for itself.
|
|
2909
|
+
if (call.nested === true && decision === "ask" && learnedApprovedTools(await approvedCardOver(call.callId, spec.gate?.askedAs?.(LEARNED_WORKFLOW_TOOL) ?? LEARNED_WORKFLOW_TOOL)).has(tool))
|
|
2910
|
+
decision = "allow";
|
|
2269
2911
|
// Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
|
|
2270
2912
|
// an MCP call by its catalog name (tool) either way, never pi's wire name, and so are its call and its price.
|
|
2271
|
-
|
|
2272
|
-
//
|
|
2913
|
+
// A script's computer op is asked about by the tool it is held to (RunGate.askedAs with its arguments: bash for its
|
|
2914
|
+
// shell, write or read for its files).
|
|
2915
|
+
const asked = spec.gate?.askedAs?.(tool, call.args) ?? tool;
|
|
2916
|
+
// A call a person was asked about and has not answered, refused now because its tool is set to deny (a bare "deny",
|
|
2917
|
+
// or the gate's own words for it): the deny answers the ask first (deniedBySetting), a deny of theirs standing. The
|
|
2918
|
+
// model reads the gate's words (main's, from refusal-words.ts) either way.
|
|
2919
|
+
// The ask is read first: it is the claim's one journal read, the setting a store read.
|
|
2920
|
+
if (decision !== "allow" && decision !== "ask" && spec.gate && (await askStands(call.callId)) && (decision === "deny" || (await spec.gate.permission?.(tool)) === "deny")) {
|
|
2921
|
+
const answer = await deniedBySetting({ ...call, tool }, asked);
|
|
2922
|
+
if (answer === "park")
|
|
2923
|
+
return { park: true };
|
|
2924
|
+
if (answer.by !== "setting")
|
|
2925
|
+
return { deny: deniedText(asked, answer.note) };
|
|
2926
|
+
}
|
|
2927
|
+
if (typeof decision === "object")
|
|
2928
|
+
return { deny: decision.deny };
|
|
2273
2929
|
if (decision === "deny")
|
|
2274
2930
|
return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
|
|
2275
2931
|
// A call a person was asked about and has not answered, its setting at allow now: the setting answers the ask
|
|
2276
2932
|
// (allowedBySetting), and the call runs without asking the person again.
|
|
2277
2933
|
const bySetting = decision === "allow" && !!spec.gate && (await askStands(call.callId));
|
|
2934
|
+
// While pi's park waits for the calls already running beside it (siblingsSettled), no new one starts: it is held as the
|
|
2935
|
+
// parked call is, its intent never stored, and asked again on the resume. A call a running tool makes is that tool's,
|
|
2936
|
+
// let through.
|
|
2937
|
+
if (decision === "allow" && !bySetting && parkPending && call.nested !== true)
|
|
2938
|
+
return { park: true };
|
|
2278
2939
|
if (decision === "allow" && !bySetting)
|
|
2279
2940
|
return "allow";
|
|
2280
2941
|
// The card shows the call's input, and beside it what the gate says the call would do that the person approves too
|
|
2281
|
-
// (a learned workflow's MCP
|
|
2282
|
-
const
|
|
2283
|
-
// Shown first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES) still names them whatever the input's size.
|
|
2284
|
-
// The gate's own fields win over any of the same name in the call's input, which the model wrote.
|
|
2285
|
-
const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
|
|
2942
|
+
// (a learned workflow's MCP actions set to ask: the gate's `ask`).
|
|
2943
|
+
const args = cardOf(tool, shown, call.args);
|
|
2286
2944
|
// The call on the record before its ask (beforeAsk), with the input its model gave it.
|
|
2287
2945
|
await beforeAsk?.(call);
|
|
2288
|
-
|
|
2289
|
-
const
|
|
2946
|
+
// Its price on the card: a catalog tool's (an MCP tool's, a monid endpoint's pinned price), else none.
|
|
2947
|
+
const price = mcp?.priceOf(tool) ?? null;
|
|
2948
|
+
// Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the card's `mcp_calls`, a
|
|
2949
|
+
// learned workflow's MCP actions set to ask): that allow takes the second confirm too.
|
|
2950
|
+
const destructive = [asked, ...learnedApprovedTools(shown)].some((name) => mcp?.effectOf(name) === "destructive");
|
|
2951
|
+
const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked, destructive);
|
|
2290
2952
|
if (answer === "park")
|
|
2291
2953
|
return { park: true };
|
|
2292
|
-
// A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
|
|
2293
|
-
// approved with it (host-calls.ts), as far as the card they approved named it: its ask as journaled, the card they
|
|
2294
|
-
// saw, never one built again now.
|
|
2295
|
-
if (answer.approved) {
|
|
2296
|
-
const seen = askedArgs.get(call.callId);
|
|
2297
|
-
approvedCalls.set(call.callId, seen && typeof seen === "object" && !Array.isArray(seen) ? seen : {});
|
|
2298
|
-
}
|
|
2299
2954
|
if (answer.approved)
|
|
2300
2955
|
return "allow";
|
|
2301
2956
|
return { deny: replayed ? refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown") : deniedText(asked, answer.note) };
|
|
2302
2957
|
};
|
|
2303
2958
|
}
|
|
2959
|
+
/** The card a person approved for the learned_workflow call that `callId` (`<outer>/<key>`, its key never holding a
|
|
2960
|
+
* "/") is nested in: the ask journaled under that call's own id, answered with an allow. Keyed to that one call, so a
|
|
2961
|
+
* card approved for any other call (an earlier call of the same workflow among them) never passes it. None when its
|
|
2962
|
+
* outer call was not asked as learned_workflow, or its ask was denied or not answered. */
|
|
2963
|
+
async function approvedCardOver(callId, learnedAs) {
|
|
2964
|
+
const at = callId.lastIndexOf("/");
|
|
2965
|
+
if (at <= 0)
|
|
2966
|
+
return undefined;
|
|
2967
|
+
const outer = callId.slice(0, at);
|
|
2968
|
+
const conversation = await harness.root(context);
|
|
2969
|
+
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
2970
|
+
const ask = findData(entries, KINDS.ask, (data) => data.callId === outer);
|
|
2971
|
+
const answer = ask && findData(entries, KINDS.answer, (data) => data.callId === outer);
|
|
2972
|
+
return ask?.tool === learnedAs && answer?.approved === true ? ask.args : undefined;
|
|
2973
|
+
}
|
|
2304
2974
|
/** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
|
|
2305
2975
|
* park (the ask entry with the run parked, in one commit). The ask is main's approval card: the call's input, when it
|
|
2306
2976
|
* was asked and its `price`; asked again on a resume, it is the same request. */
|
|
2307
|
-
async function answerOf(call, price, asked = call.tool) {
|
|
2977
|
+
async function answerOf(call, price, asked = call.tool, destructive = mcp?.effectOf(asked) === "destructive") {
|
|
2308
2978
|
const conversation = await harness.root(context);
|
|
2309
2979
|
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
2310
2980
|
const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
|
|
2311
|
-
// The card the person answers is the ask as first journaled: kept for the caller, which scopes an approval to it.
|
|
2312
2981
|
if (first)
|
|
2313
|
-
|
|
2982
|
+
askedCalls.add(call.callId);
|
|
2314
2983
|
const known = findData(entries, KINDS.answer, (data) => data.callId === call.callId);
|
|
2315
2984
|
if (known)
|
|
2316
2985
|
return known;
|
|
2317
2986
|
// The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
|
|
2318
2987
|
// run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
|
|
2319
|
-
|
|
2988
|
+
// An MCP tool its run's pin marks destructive (ClaimMcp.effectOf), or a call whose allow covers one (`destructive`):
|
|
2989
|
+
// its card asks a second confirm of an allow.
|
|
2990
|
+
const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price, ...(destructive ? { destructive: true } : {}) };
|
|
2320
2991
|
const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
|
|
2321
2992
|
if (first === undefined) {
|
|
2322
2993
|
// Asked and parked; or held as the parked call is, when another call of the round parked the run first.
|
|
2323
|
-
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
|
|
2994
|
+
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } })) {
|
|
2995
|
+
parkedCalls.add(call.callId);
|
|
2324
2996
|
parked();
|
|
2997
|
+
}
|
|
2325
2998
|
return "park";
|
|
2326
2999
|
}
|
|
2327
3000
|
for (;;) {
|
|
@@ -2340,8 +3013,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2340
3013
|
// no waiting call and was refused): the call is asked again and the run parks on it, so it never waits here
|
|
2341
3014
|
// holding the claim while it reads running.
|
|
2342
3015
|
if (delivered || refusals > 0) {
|
|
2343
|
-
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
|
|
3016
|
+
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } })) {
|
|
3017
|
+
parkedCalls.add(call.callId);
|
|
2344
3018
|
parked();
|
|
3019
|
+
}
|
|
2345
3020
|
return "park";
|
|
2346
3021
|
}
|
|
2347
3022
|
await new Promise((resolve) => (wakeInbox = resolve));
|
|
@@ -2381,10 +3056,27 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2381
3056
|
inbox.splice(inbox.indexOf(row), 1);
|
|
2382
3057
|
if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
|
|
2383
3058
|
return "park";
|
|
2384
|
-
//
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
3059
|
+
// A call whose ask stands (askStands): a person was asked about it.
|
|
3060
|
+
askedCalls.add(call.callId);
|
|
3061
|
+
return data;
|
|
3062
|
+
}
|
|
3063
|
+
/** The answer to an ask a person was shown and has not answered, once its tool's setting reads deny: the deny answers it
|
|
3064
|
+
* (by "setting"), so its rows say it was refused for that deny and the run's end never reads it withdrawn. A person's
|
|
3065
|
+
* allow already in the inbox for the call is taken with it and kept as the allow the deny overrode (`superseded`); a
|
|
3066
|
+
* deny of theirs stands, answered as any (answerOf). */
|
|
3067
|
+
async function deniedBySetting(call, asked) {
|
|
3068
|
+
// As allowedBySetting: decided only once the claim's stored commands are with the loop.
|
|
3069
|
+
await (deps.delivered ?? Promise.resolve());
|
|
3070
|
+
const row = inbox.find((command) => (command.kind === "approve" || command.kind === "deny") && approvalOf(command) === call.callId);
|
|
3071
|
+
if (row?.kind === "deny")
|
|
3072
|
+
return answerOf(call, null, asked);
|
|
3073
|
+
const conversation = await harness.root(context);
|
|
3074
|
+
const answeredAt = isoNow();
|
|
3075
|
+
const data = { callId: call.callId, approved: false, decision: "deny", answeredAt, by: "setting", ...(row ? { superseded: { decision: "allow", answeredAt } } : {}) };
|
|
3076
|
+
if (row)
|
|
3077
|
+
inbox.splice(inbox.indexOf(row), 1);
|
|
3078
|
+
if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
|
|
3079
|
+
return "park";
|
|
2388
3080
|
return data;
|
|
2389
3081
|
}
|
|
2390
3082
|
/** Whether a person was asked about this call and has not answered yet (an ask in the journal, no answer): its card is
|
|
@@ -2426,7 +3118,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2426
3118
|
return false;
|
|
2427
3119
|
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
2428
3120
|
const [theGate, theHarness] = [gate, harness];
|
|
2429
|
-
if (!theGate || !theHarness || theGate.sealed)
|
|
3121
|
+
if (!theGate || !theHarness || theGate.sealed || parkPending)
|
|
2430
3122
|
return "later";
|
|
2431
3123
|
try {
|
|
2432
3124
|
const conversation = await theHarness.root(context);
|
|
@@ -2489,9 +3181,29 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2489
3181
|
parkedAt.catch(() => undefined);
|
|
2490
3182
|
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId } }), context);
|
|
2491
3183
|
await parkedAt;
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
3184
|
+
return parkClaim(on, theGate, "answer");
|
|
3185
|
+
}
|
|
3186
|
+
/** A CLI's turn cut at its question to the person (TurnCut): its request after the question held, the turn is stopped
|
|
3187
|
+
* (interrupt), the held request refused once the stop is under way, and the turn the session still reads open settled,
|
|
3188
|
+
* as a host done with a stopped turn settles it. The turn reads completed, ended on the question, as pi's does. Bounded
|
|
3189
|
+
* as a stop is: a turn that does not settle in time fails the run in words. */
|
|
3190
|
+
async function cutAtQuestion(theSession, turn, settleMs) {
|
|
3191
|
+
const settling = (async () => {
|
|
3192
|
+
const stopped = theSession.interrupt().catch(() => { });
|
|
3193
|
+
askCut.done();
|
|
3194
|
+
await stopped;
|
|
3195
|
+
await turn.catch(() => undefined);
|
|
3196
|
+
if (theSession.state === "open_turn")
|
|
3197
|
+
await theSession.settleOpenTurn();
|
|
3198
|
+
return true;
|
|
3199
|
+
})().catch((error) => {
|
|
3200
|
+
console.warn(`[runner] the turn cut at its question did not settle: ${said(error)}`);
|
|
3201
|
+
return false;
|
|
3202
|
+
});
|
|
3203
|
+
let timer;
|
|
3204
|
+
const settled = await Promise.race([settling, new Promise((resolve) => (timer = setTimeout(() => resolve(false), settleMs)))]);
|
|
3205
|
+
clearTimeout(timer);
|
|
3206
|
+
return settled ? { status: "completed" } : { status: "failed", error: `the turn did not stop at its question to the person within ${settleMs / 1000} s` };
|
|
2495
3207
|
}
|
|
2496
3208
|
/** The row's waiting summary of a wait in the claim, gone: its answer came by a way whose commit did not clear it. */
|
|
2497
3209
|
async function notWaiting(on, theGate, conversation, callId) {
|
|
@@ -2511,6 +3223,24 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2511
3223
|
return { status: "completed" };
|
|
2512
3224
|
return turnOfRequest(on, conversation, last.requestId);
|
|
2513
3225
|
}
|
|
3226
|
+
/** How the job's own turn ended (`data`, and a CLI's error answer `failedWith`), as this claim decided it, kept on the
|
|
3227
|
+
* root before the end-of-run step asks its first turn (KINDS.jobEnd), for a run with a step to ask (stepOf). Its
|
|
3228
|
+
* summary is cut of every secret the runner holds, as every summary is when served. */
|
|
3229
|
+
async function keepJobEnd(on, conversation, spec, data, failedWith) {
|
|
3230
|
+
if (!stepOf(spec))
|
|
3231
|
+
return;
|
|
3232
|
+
const end = data.summary !== undefined && deps.redact ? { ...data, summary: deps.redact(data.summary) } : data;
|
|
3233
|
+
const kept = { end, ...(failedWith !== undefined ? { failedWith } : {}) };
|
|
3234
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.jobEnd, data: kept }), context);
|
|
3235
|
+
}
|
|
3236
|
+
/** The job's end for a claim that found the end-of-run turn open (lookingBackOpen): the newest keepJobEnd kept (a
|
|
3237
|
+
* follow-up's round keeps its own), never worked out again. */
|
|
3238
|
+
async function jobEndKept(conversation) {
|
|
3239
|
+
const kept = (await entriesOf(gate.journal, conversation.id, context)).filter((entry) => entry.kind === KINDS.jobEnd).at(-1);
|
|
3240
|
+
if (!kept)
|
|
3241
|
+
throw new Error("the end-of-run turn is open, but the job's end was never kept before it");
|
|
3242
|
+
return kept.data;
|
|
3243
|
+
}
|
|
2514
3244
|
/** How the turn of the root's submission `requestId` ended (a steer of the idle session, which no session tracks). */
|
|
2515
3245
|
async function turnOfRequest(on, conversation, requestId) {
|
|
2516
3246
|
const found = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
@@ -2621,6 +3351,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2621
3351
|
async function closeSession() {
|
|
2622
3352
|
gate?.seal(new Interrupted("the Session is closing"));
|
|
2623
3353
|
endWait();
|
|
3354
|
+
// A request held at a cut turn goes with its session, refused, never left pending.
|
|
3355
|
+
askCut.done();
|
|
2624
3356
|
const closing = Promise.all([session?.close().catch(() => { }), harness?.close(BACKGROUND_CONTEXT).catch(() => { })]);
|
|
2625
3357
|
let timer;
|
|
2626
3358
|
await Promise.race([closing, new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
|
|
@@ -2630,16 +3362,34 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2630
3362
|
mcp?.release();
|
|
2631
3363
|
mcp = undefined;
|
|
2632
3364
|
// The pass's resources go once nothing more is written through them (AdapterRunSpec.release), once each.
|
|
3365
|
+
// A park's keeps the run's computer (keepAtPark).
|
|
2633
3366
|
const release = releaseNow;
|
|
3367
|
+
const parked = parkedNow;
|
|
2634
3368
|
releaseNow = undefined;
|
|
2635
|
-
|
|
3369
|
+
parkedNow = undefined;
|
|
3370
|
+
await release?.(parked ? { parked } : {}).catch((error) => console.warn(`[runner] its run's release failed: ${said(error)}`));
|
|
3371
|
+
}
|
|
3372
|
+
/** What a round's first ask kept, read before the hook can skip or close its resumed turn: the CLI's record, or pi's
|
|
3373
|
+
* durable root entry. A different round's snapshot never prices this one. */
|
|
3374
|
+
async function keptOf(claim) {
|
|
3375
|
+
const record = cliRecord;
|
|
3376
|
+
const entries = !record && gate && root ? await entriesOf(gate.journal, root.id, context) : [];
|
|
3377
|
+
return (round) => {
|
|
3378
|
+
const requestId = reflectRequestId(claim.runId, false, round);
|
|
3379
|
+
if (record)
|
|
3380
|
+
return record.keptOf(requestId);
|
|
3381
|
+
const first = entries.find((entry) => entry.kind === KINDS.endOfRunKept && entry.data?.requestId === requestId);
|
|
3382
|
+
const kept = first?.data?.kept;
|
|
3383
|
+
return kept && typeof kept === "object" && !Array.isArray(kept) ? kept : undefined;
|
|
3384
|
+
};
|
|
2636
3385
|
}
|
|
2637
3386
|
/** The run's end-of-run step: its spec's (AdapterRunSpec.endOfRun) when it has one, else the loop's deps'. */
|
|
2638
3387
|
const stepOf = (spec) => spec.endOfRun ?? deps.endOfRun;
|
|
2639
3388
|
/** 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
|
|
2640
3389
|
* came during it; `interrupted` when the claim was lost or the runner is closing (no end is written, and the next claim
|
|
2641
|
-
* asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it.
|
|
2642
|
-
|
|
3390
|
+
* asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it. `over`:
|
|
3391
|
+
* the claim's overCap, read after each turn the step asks (askEndOfRun). */
|
|
3392
|
+
async function endOfRunStep(claim, spec, outcome, over) {
|
|
2643
3393
|
const cut = () => {
|
|
2644
3394
|
if (stopReason?.kind === "command")
|
|
2645
3395
|
return { kind: "stopped", commandId: stopReason.commandId };
|
|
@@ -2652,8 +3402,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2652
3402
|
return { kind: "rows", also: [] };
|
|
2653
3403
|
if (!spec.agentId)
|
|
2654
3404
|
throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
|
|
3405
|
+
// Every request from here is learning's, between the step's asks too, until the claim ends (reflecting).
|
|
3406
|
+
reflecting = true;
|
|
2655
3407
|
try {
|
|
2656
|
-
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, opts.round ?? 1) });
|
|
3408
|
+
const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
|
|
2657
3409
|
return cut() ?? { kind: "rows", also: rows?.also ?? [] };
|
|
2658
3410
|
}
|
|
2659
3411
|
catch (error) {
|
|
@@ -2671,7 +3423,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2671
3423
|
let timer;
|
|
2672
3424
|
const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
|
|
2673
3425
|
try {
|
|
2674
|
-
const
|
|
3426
|
+
const pending = async () => step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse, keptOf: await keptOf(claim) });
|
|
3427
|
+
const rows = await Promise.race([pending(), late]);
|
|
2675
3428
|
if (rows === "late") {
|
|
2676
3429
|
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`);
|
|
2677
3430
|
return [];
|
|
@@ -2686,27 +3439,55 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2686
3439
|
clearTimeout(timer);
|
|
2687
3440
|
}
|
|
2688
3441
|
}
|
|
3442
|
+
/** What end-of-run turn `requestId` kept as it was first asked, for a harness that keeps its own record (pi): the first
|
|
3443
|
+
* ask's `keep` on the run's root (KINDS.endOfRunKept), an earlier claim's when it asked first, else `keep`, written
|
|
3444
|
+
* there now, before the turn's first request leaves. A CLI's record keeps it with the turn's prompt (answering). */
|
|
3445
|
+
async function keptOnRoot(on, journal, conversation, requestId, keep) {
|
|
3446
|
+
const first = (await entriesOf(journal, conversation.id, context)).find((entry) => entry.kind === KINDS.endOfRunKept && entry.data?.requestId === requestId);
|
|
3447
|
+
if (first) {
|
|
3448
|
+
const kept = first.data.kept;
|
|
3449
|
+
return kept && typeof kept === "object" && !Array.isArray(kept) ? kept : undefined;
|
|
3450
|
+
}
|
|
3451
|
+
if (!keep)
|
|
3452
|
+
return undefined;
|
|
3453
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.endOfRunKept, data: { requestId, kept: keep } }), context);
|
|
3454
|
+
return keep;
|
|
3455
|
+
}
|
|
2689
3456
|
/** The end-of-run turn: one more turn through the run's session, its request id one per round of the run (a repeat is
|
|
2690
3457
|
* answered from its submission, so a later claim never asks the model again; a follow-up's end is the next `round`,
|
|
2691
3458
|
* asked anew), its writes under work/.learning/ refused while it runs. `again`: its re-ask, a request of its own (one
|
|
2692
|
-
* per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why.
|
|
2693
|
-
|
|
3459
|
+
* per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. `over`:
|
|
3460
|
+
* the claim's overCap, read once the turn's booking settled. */
|
|
3461
|
+
async function askEndOfRun(claim, over, prompt, deadlineMs, again = false, round = 1, keep, step) {
|
|
2694
3462
|
if (!session || !harness || !gate || !root)
|
|
2695
3463
|
throw new Error("the run's session is not open");
|
|
2696
3464
|
const on = harness;
|
|
2697
3465
|
const conversation = root;
|
|
2698
3466
|
const theSession = session;
|
|
2699
|
-
const requestId = reflectRequestId(claim.runId, again, round);
|
|
3467
|
+
const requestId = reflectRequestId(claim.runId, again, round, step);
|
|
2700
3468
|
const theRecord = cliRecord;
|
|
2701
|
-
|
|
3469
|
+
// A grade's feedback round (feedbackNow): its first ask is told the grade first (feedback-round.ts feedbackAsk), and,
|
|
3470
|
+
// when the agent never took the job (its learned workflow answered alone: its session is new), the job and the
|
|
3471
|
+
// workflow's answer before it, cut of every secret the runner holds, as a follow-up's are.
|
|
3472
|
+
if (feedbackNow && !again && step === undefined) {
|
|
3473
|
+
const cut = (text) => (deps.redact ? deps.redact(text) : text);
|
|
3474
|
+
const servedNow = theSession.state === "new" ? servedAnswerOf(await entriesOf(gate.journal, conversation.id, context)) : undefined;
|
|
3475
|
+
const seen = servedNow && specNow ? { job: specNow.input, served: { workflow: servedNow.workflow, answer: cut(servedNow.answer) } } : undefined;
|
|
3476
|
+
prompt = `${feedbackAsk({ ...feedbackNow, text: cut(feedbackNow.text) }, seen)}\n\n${prompt}`;
|
|
3477
|
+
}
|
|
2702
3478
|
let timer;
|
|
2703
3479
|
try {
|
|
2704
|
-
// A
|
|
2705
|
-
|
|
3480
|
+
// A turn already answered (an earlier claim's) is read from its submission; a CLI's record answers one it already
|
|
3481
|
+
// wrote from it too, as pi does: its CLI is never asked twice.
|
|
3482
|
+
const prior = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
3483
|
+
const known = theRecord ? prior : undefined;
|
|
2706
3484
|
// How this claim's turn ended; a turn answered before reads as its submission says.
|
|
2707
3485
|
let turnStatus = "completed";
|
|
3486
|
+
// What the turn's first ask kept (`keep`), an earlier claim's when it asked first: every answer carries it.
|
|
3487
|
+
let kept = theRecord?.keptOf(requestId);
|
|
3488
|
+
const withKept = (answer) => (kept ? { ...answer, kept } : answer);
|
|
2708
3489
|
if (!known) {
|
|
2709
|
-
await theRecord
|
|
3490
|
+
kept = theRecord ? await theRecord.answering(requestId, prompt, keep) : await keptOnRoot(on, gate.journal, conversation, requestId, keep);
|
|
2710
3491
|
await theSession.send(prompt, { id: requestId });
|
|
2711
3492
|
const turn = theSession.turnEnd();
|
|
2712
3493
|
const timeout = new Promise((resolve) => (timer = setTimeout(() => resolve("timeout"), deadlineMs)));
|
|
@@ -2717,53 +3498,180 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2717
3498
|
await theSession.interrupt().catch(() => { });
|
|
2718
3499
|
await on.waitForIdle(context).catch(() => { });
|
|
2719
3500
|
await theRecord?.answered(requestId, prompt, "timed out");
|
|
2720
|
-
return { timedOut: true };
|
|
3501
|
+
return withKept({ timedOut: true });
|
|
2721
3502
|
}
|
|
2722
3503
|
// The CLI's turn, as the submission pi's adapter writes: what the step reads next, one reader for both.
|
|
2723
3504
|
turnStatus = end.status;
|
|
2724
3505
|
await theRecord?.answered(requestId, prompt, end.status);
|
|
2725
3506
|
}
|
|
3507
|
+
// A turn the cap refused a request of (this claim's, or the one a takeover found open: lookingBackOpen) fails in the
|
|
3508
|
+
// refusal's words: the learning is dropped for the cap's room (reflect-hook.ts CAP_REFUSAL), the run never parked.
|
|
3509
|
+
const capped = prior?.status === "done" ? undefined : learningRefused;
|
|
3510
|
+
if (capped) {
|
|
3511
|
+
learningRefused = undefined;
|
|
3512
|
+
return withKept({ failed: { code: "refused", message: capped.refuse } });
|
|
3513
|
+
}
|
|
3514
|
+
// The run's booked spend once this turn's settled (its cut requests at their worst case, an earlier claim's too): past
|
|
3515
|
+
// the cap, the turn fails in the cap's words (overCap), and the learning is dropped as a refusal drops it
|
|
3516
|
+
// (reflect-hook.ts CAP_REFUSAL: no_budget), its spend still booked. The run keeps the end its job's turn gave it.
|
|
3517
|
+
await bookingsSettled();
|
|
3518
|
+
const passed = await over();
|
|
3519
|
+
if (passed)
|
|
3520
|
+
return withKept({ failed: { code: "refused", message: passed } });
|
|
2726
3521
|
const record = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
2727
3522
|
if (turnStatus !== "completed" || record?.status !== "done")
|
|
2728
|
-
return { failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } };
|
|
3523
|
+
return withKept({ failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } });
|
|
2729
3524
|
const answer = (await entriesOf(gate.journal, conversation.id, context)).find((entry) => entry.id === record.answer);
|
|
2730
|
-
return { ended: true, answer: answerText(answer) };
|
|
3525
|
+
return withKept({ ended: true, answer: answerText(answer) });
|
|
2731
3526
|
}
|
|
2732
3527
|
finally {
|
|
2733
3528
|
clearTimeout(timer);
|
|
2734
|
-
reflecting = false;
|
|
2735
3529
|
}
|
|
2736
3530
|
}
|
|
2737
|
-
/** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded
|
|
3531
|
+
/** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded (END_PATCH_MS): late or failing, the end says
|
|
3532
|
+
* its cost and metrics are unknown (END_PATCH_UNKNOWN). */
|
|
2738
3533
|
async function endPatchOf(data) {
|
|
2739
|
-
|
|
3534
|
+
const spec = specNow;
|
|
3535
|
+
if (!spec?.endPatch && !spec?.endCost)
|
|
2740
3536
|
return {};
|
|
2741
3537
|
let timer;
|
|
2742
|
-
const
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
3538
|
+
const boundMs = spec.endPatchMs ?? END_PATCH_MS;
|
|
3539
|
+
const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), boundMs)));
|
|
3540
|
+
// The cost, read apart (AdapterRunSpec.endCost): a patch whose metrics run late or fail never takes it with them. A
|
|
3541
|
+
// read that fails is read again within the same bound (END_COST_TRIES): the stored cost is every reader's answer
|
|
3542
|
+
// (the list, the view, usage), so a null there is kept only when the booking could not be read at all.
|
|
3543
|
+
const endCost = spec.endCost;
|
|
3544
|
+
const cost = endCost
|
|
3545
|
+
? readAgain(endCost, late, (error, tries, last) => console.warn(last ? `[runner] its end's cost failed ${tries} times, last: ${said(error)}; the end is written with its cost unknown` : `[runner] its end's cost failed: ${said(error)}; read again`)).then((answer) => {
|
|
3546
|
+
if (answer === "late")
|
|
3547
|
+
console.warn(`[runner] its end's cost gave no answer within ${boundMs / 1000} s; the end is written with its cost unknown`);
|
|
3548
|
+
return answer === "late" || answer === "failed" ? { costUsd: null, costUpperBound: false } : answer;
|
|
3549
|
+
})
|
|
3550
|
+
: undefined;
|
|
3551
|
+
const patched = async () => {
|
|
3552
|
+
if (!spec.endPatch)
|
|
2747
3553
|
return {};
|
|
3554
|
+
try {
|
|
3555
|
+
const patch = await Promise.race([spec.endPatch(data), late]);
|
|
3556
|
+
if (patch === "late") {
|
|
3557
|
+
console.warn(`[runner] its end's patch gave no answer within ${boundMs / 1000} s; the end is written with its ${cost ? "metrics" : "cost and metrics"} unknown`);
|
|
3558
|
+
return END_PATCH_UNKNOWN;
|
|
3559
|
+
}
|
|
3560
|
+
return patch ?? {};
|
|
2748
3561
|
}
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
3562
|
+
catch (error) {
|
|
3563
|
+
console.warn(`[runner] its end's patch failed: ${said(error)}; the end is written with its ${cost ? "metrics" : "cost and metrics"} unknown`);
|
|
3564
|
+
return END_PATCH_UNKNOWN;
|
|
3565
|
+
}
|
|
3566
|
+
};
|
|
3567
|
+
try {
|
|
3568
|
+
const [patch, read] = await Promise.all([patched(), cost]);
|
|
3569
|
+
return read ? { ...patch, ...read } : patch;
|
|
2754
3570
|
}
|
|
2755
3571
|
finally {
|
|
2756
3572
|
clearTimeout(timer);
|
|
2757
3573
|
}
|
|
2758
3574
|
}
|
|
2759
3575
|
/** The run parked at its cap: its pending budget as an agentrun.budget entry, in one commit with the run parked in the
|
|
2760
|
-
* cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it.
|
|
2761
|
-
|
|
3576
|
+
* cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it. `cause`: parked again
|
|
3577
|
+
* at the cap on a resume, or at a refusal the turn ended on. */
|
|
3578
|
+
async function parkAtCap(on, conversation, theGate, data, cause) {
|
|
2762
3579
|
await pauseAtCap(on, conversation, theGate, data);
|
|
3580
|
+
return parkClaim(on, theGate, cause);
|
|
3581
|
+
}
|
|
3582
|
+
/** Waits, at most the spec's parkSiblingsMs (PARK_SIBLINGS_MS), until no call pi started beside a parked one is still
|
|
3583
|
+
* running: a model call of the same answer (its assistant entry) past its stored intent. Each one's result is then on the
|
|
3584
|
+
* journal before the park seals it, and the resume hands it to the model with the parked call's answer, never as a call
|
|
3585
|
+
* cut short. Not waited on: a call held before its intent (the parked one, any held with it), the parked call itself
|
|
3586
|
+
* when it was asked after its intent (a replay-safe rerun), and every call it is nested in (a script or a workflow node
|
|
3587
|
+
* waiting on it), nor any call of another answer. A stop, a lost claim or a closed Harness ends the wait at once. Past
|
|
3588
|
+
* the bound the seal cuts what still runs, as before, and the model reads it interrupted. pi's alone: a CLI's park
|
|
3589
|
+
* (spec.record "loop") lets its claim go at once, and its resume settles a call that ended (resumeUnstartedCalls). */
|
|
3590
|
+
async function siblingsSettled(on, spec) {
|
|
3591
|
+
const until = Date.now() + (spec.parkSiblingsMs ?? PARK_SIBLINGS_MS);
|
|
3592
|
+
let over = false;
|
|
3593
|
+
let end = () => { };
|
|
3594
|
+
const ended = new Promise((resolve) => (end = resolve)).then(() => {
|
|
3595
|
+
over = true;
|
|
3596
|
+
});
|
|
3597
|
+
// Its own listener on the claim's signal, taken off on every way out (settled, past the bound, sealed): a loop leaves
|
|
3598
|
+
// nothing on the signal it was lent. The stop and the Harness's close are promises, which hold nothing on it.
|
|
3599
|
+
const onAbort = () => end();
|
|
3600
|
+
if (deps.signal.aborted)
|
|
3601
|
+
end();
|
|
3602
|
+
else
|
|
3603
|
+
deps.signal.addEventListener("abort", onAbort, { once: true });
|
|
3604
|
+
void stopping.then(() => end());
|
|
3605
|
+
void on.closed.then(() => end(), () => end());
|
|
3606
|
+
try {
|
|
3607
|
+
while (!over && !gate?.sealed && Date.now() < until) {
|
|
3608
|
+
let tasks;
|
|
3609
|
+
try {
|
|
3610
|
+
({ tasks } = await on.inspect(context));
|
|
3611
|
+
}
|
|
3612
|
+
catch {
|
|
3613
|
+
return;
|
|
3614
|
+
}
|
|
3615
|
+
if (siblingsRunning(tasks).length === 0)
|
|
3616
|
+
return;
|
|
3617
|
+
let timer;
|
|
3618
|
+
await Promise.race([ended, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, Math.min(SIBLINGS_POLL_MS, until - Date.now())))))]);
|
|
3619
|
+
clearTimeout(timer);
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
finally {
|
|
3623
|
+
deps.signal.removeEventListener("abort", onAbort);
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
/** siblingsSettled's read of the Harness's live tasks: the model calls past their intent that share an answer with a
|
|
3627
|
+
* call this claim parked on, less that call and every call it is nested in. */
|
|
3628
|
+
function siblingsRunning(tasks) {
|
|
3629
|
+
const calls = tasks.map((task) => task.record).filter((record) => record.kind === ToolTask.definition.name);
|
|
3630
|
+
const byId = new Map(calls.map((record) => [String(record.id), record]));
|
|
3631
|
+
const inputOf = (record) => (record.input ?? {});
|
|
3632
|
+
const answers = new Set();
|
|
3633
|
+
const holding = new Set();
|
|
3634
|
+
for (const record of calls) {
|
|
3635
|
+
const input = inputOf(record);
|
|
3636
|
+
if (!parkedCalls.has((input.kind === "nested" ? input.call?.id : input.callId) ?? ""))
|
|
3637
|
+
continue;
|
|
3638
|
+
// The parked call and each call it is nested in, up to the model's call that holds it, whose answer it shares.
|
|
3639
|
+
for (let at = record; at; at = byId.get(String(inputOf(at).parent ?? at.owner ?? ""))) {
|
|
3640
|
+
holding.add(String(at.id));
|
|
3641
|
+
const own = inputOf(at);
|
|
3642
|
+
if (own.kind !== "nested" && own.assistant !== undefined)
|
|
3643
|
+
answers.add(own.assistant);
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
return calls
|
|
3647
|
+
.filter((record) => {
|
|
3648
|
+
const input = inputOf(record);
|
|
3649
|
+
const phase = record.state.checkpoint?.phase;
|
|
3650
|
+
return input.kind !== "nested" && input.assistant !== undefined && answers.has(input.assistant) && !holding.has(String(record.id)) && phase === "execute";
|
|
3651
|
+
})
|
|
3652
|
+
.map((record) => String(record.id));
|
|
3653
|
+
}
|
|
3654
|
+
/** A park's release of the claim, as the end's: the tool host let go first (a browser's release, booked under the live
|
|
3655
|
+
* claim), then every paid request the session admitted booked (bookingsSettled), then the journal sealed. A CLI turn
|
|
3656
|
+
* the park cuts (its call held at the tool bridge) may still be streaming its answer: closed under it, its booking
|
|
3657
|
+
* would be lost and the next claim would book the turn cut, at an unknown price. Past the bound, it is that cut. */
|
|
3658
|
+
async function parkClaim(on, theGate, cause) {
|
|
2763
3659
|
await releaseHost(on);
|
|
3660
|
+
await bookingsSettled();
|
|
3661
|
+
await keepAtPark(on, cause);
|
|
2764
3662
|
theGate.seal(new Parked());
|
|
2765
3663
|
return { state: "parked" };
|
|
2766
3664
|
}
|
|
3665
|
+
/** At a park for `cause`, before its seal: a pass whose spec keeps its computer (AdapterRunSpec.keptWords) has it kept
|
|
3666
|
+
* for the resume at its release (closeSession), once the run's timeline says so, for the person deciding; its owner's
|
|
3667
|
+
* live view is closed saying the cause. A write that fails (the fence's refusal: a lost claim, whose run a later claim
|
|
3668
|
+
* may hold already) keeps nothing: the computer goes as at the run's end. */
|
|
3669
|
+
async function keepAtPark(on, cause) {
|
|
3670
|
+
const summary = specNow?.keptWords;
|
|
3671
|
+
if (!summary)
|
|
3672
|
+
return;
|
|
3673
|
+
parkedNow = await on.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data: { summary, at: Date.now() } }), context).then(() => cause, () => undefined);
|
|
3674
|
+
}
|
|
2767
3675
|
/** The run's pause at its cap: its agentrun.budget entry, in one commit with the run parked in the cap's words. */
|
|
2768
3676
|
async function pauseAtCap(on, conversation, theGate, data) {
|
|
2769
3677
|
const parkedAt = theGate.expect(writesEntry(KINDS.budget), { run: { state: "parked", summary: data.words } });
|
|
@@ -2779,8 +3687,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2779
3687
|
await parkedAt;
|
|
2780
3688
|
}
|
|
2781
3689
|
/** Waits, at most CLOSE_MS, until every paid request the session admitted is booked: a person's stop is booked at what
|
|
2782
|
-
* streamed once the session's proxy sees its upstream end.
|
|
2783
|
-
*
|
|
3690
|
+
* streamed once the session's proxy sees its upstream end. Then, for a booking whose write has begun, as long as that
|
|
3691
|
+
* write takes (bookingWriteMs). Past the bounds the end is written anyway, and a request left unbooked reads at its
|
|
3692
|
+
* hold and bound, the worst it can have cost, and the run's cost unknown: never a known figure that leaves it out. */
|
|
2784
3693
|
async function bookingsSettled() {
|
|
2785
3694
|
if (unbooked === 0)
|
|
2786
3695
|
return;
|
|
@@ -2788,6 +3697,15 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2788
3697
|
let timer;
|
|
2789
3698
|
await Promise.race([new Promise((resolve) => bookedAll.push(resolve)), new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
|
|
2790
3699
|
clearTimeout(timer);
|
|
3700
|
+
// A booking whose write has begun (its request answered) is waited for as long as its write takes, bounded
|
|
3701
|
+
// (BOOKING_WRITE_MS): written after the end, it would be fenced and lost, and the run's cost read unknown for good.
|
|
3702
|
+
if (bookingsWriting === 0)
|
|
3703
|
+
return;
|
|
3704
|
+
const boundMs = specNow?.bookingWriteMs ?? BOOKING_WRITE_MS;
|
|
3705
|
+
const written = await Promise.race([new Promise((resolve) => writtenAll.push(() => resolve(true))), new Promise((resolve) => (timer = setTimeout(() => resolve(false), boundMs)))]);
|
|
3706
|
+
clearTimeout(timer);
|
|
3707
|
+
if (!written)
|
|
3708
|
+
console.warn(`[runner] ${bookingsWriting} paid request booking(s) still being written after ${boundMs / 1000} s; going on without them: each reads at its hold, and the run's cost unknown`);
|
|
2791
3709
|
}
|
|
2792
3710
|
/** The run's timeline says it went on after its runner was lost (RUN_RESUMED, `after: runner_lost`): one root entry,
|
|
2793
3711
|
* no run patch. A journal sealed meanwhile (the claim lost again, a shutdown) refuses it, and the loop goes on as it
|
|
@@ -2824,8 +3742,18 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2824
3742
|
// their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
|
|
2825
3743
|
await releaseHost(on);
|
|
2826
3744
|
await bookingsSettled();
|
|
3745
|
+
// The pull request's checkout goes before the end is committed: a run that reads final never still holds its code.
|
|
3746
|
+
await specNow?.endCheckout?.();
|
|
2827
3747
|
const patch = await endPatchOf(base);
|
|
2828
|
-
|
|
3748
|
+
// A person's stop that came while the end waited (its host's release, its bookings, its patch's reads, up to
|
|
3749
|
+
// END_PATCH_MS on a busy store) is this end's, as a stop during any earlier await of the end path is: the run ends
|
|
3750
|
+
// stopped and the end takes its row, never written completed with the stop left to be refused (refuseLeftovers).
|
|
3751
|
+
// Set by stop() during those awaits: read past the narrowing TypeScript did before them.
|
|
3752
|
+
const late = stopReason;
|
|
3753
|
+
const lateStop = late?.kind === "command" && !take.includes(late.commandId) ? late : undefined;
|
|
3754
|
+
if (lateStop)
|
|
3755
|
+
take = [...take, lateStop.commandId];
|
|
3756
|
+
const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
|
|
2829
3757
|
const run = {
|
|
2830
3758
|
state: data.state,
|
|
2831
3759
|
// 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
|
|
@@ -2833,7 +3761,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2833
3761
|
...(data.summary ? { summary: data.summary } : {}),
|
|
2834
3762
|
...(!data.summary ? { summary: null } : {}),
|
|
2835
3763
|
...(data.outcome !== undefined ? { outcome: data.outcome } : {}),
|
|
2836
|
-
...(data.costUsd !== undefined ? { costUsd: data.costUsd } : {}),
|
|
3764
|
+
...(data.costUsd !== undefined ? { costUsd: data.costUsd, costUpperBound: data.costUpperBound === true } : {}),
|
|
2837
3765
|
...(data.metrics !== undefined ? { metrics: data.metrics } : {}),
|
|
2838
3766
|
};
|
|
2839
3767
|
// A person's stop or cancel withdraws every call still waiting for its answer, in the end's own commit: the approval
|
|
@@ -2842,9 +3770,19 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2842
3770
|
// A cancel's calls read cancelled with their run; a stop's, withdrawn.
|
|
2843
3771
|
const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow(), stopReason?.kind === "command" && stopReason.cancel ? "canceled" : "withdrawn") : [];
|
|
2844
3772
|
// A CLI's call on the record from its gate and never sent (parked, or its runner gone before its send): its record ends
|
|
2845
|
-
// with the run's, in the same commit, saying it was not run (never interrupted: it never left).
|
|
2846
|
-
|
|
3773
|
+
// with the run's, in the same commit, saying it was not run (never interrupted: it never left). pi's nested calls
|
|
3774
|
+
// (nestedGate) are on a record of their own, read here from the journal: a stop can end a parked run before this claim
|
|
3775
|
+
// opened a session.
|
|
3776
|
+
const ends = cliRecord ?? (await openCliRecord(on, theGate.journal, context, now, undefined, true));
|
|
3777
|
+
const recordEnds = ends.unsentParked();
|
|
2847
3778
|
const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
|
|
3779
|
+
// A call that only nests calls (a harness's own: Codex's `exec`) still open when the run ends: nothing will end it now
|
|
3780
|
+
// (a stop while its call waited, a crash whose next drive never resumed its CLI's thread), so it ends with the run,
|
|
3781
|
+
// interrupted, after the rows of its calls (their withdrawals above it in this commit). Its own end on its way is
|
|
3782
|
+
// written first. Marked `withRun`: a park or a stop failed nothing, so its row reads interrupted, never failed.
|
|
3783
|
+
while (ownWrites.size > 0)
|
|
3784
|
+
await Promise.allSettled([...ownWrites]);
|
|
3785
|
+
const cutOpen = ends.openNests();
|
|
2848
3786
|
const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
|
|
2849
3787
|
// A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
|
|
2850
3788
|
ended.catch(() => undefined);
|
|
@@ -2854,6 +3792,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2854
3792
|
await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
|
|
2855
3793
|
for (const callId of recordEnds)
|
|
2856
3794
|
await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
|
|
3795
|
+
for (const callId of cutOpen)
|
|
3796
|
+
await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "interrupted", withRun: true, at: now() } });
|
|
2857
3797
|
// A turn the run ends while it is open (a stop or cancel cut it, or the run failed in it) ends with the run.
|
|
2858
3798
|
if (cliRecord?.openTurn())
|
|
2859
3799
|
await tx.appendEntry(conversation.id, { kind: KINDS.turnEnd, data: { status: data.state === "failed" ? "failed" : data.state === "stopped" ? "interrupted" : "completed" } });
|
|
@@ -2869,7 +3809,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2869
3809
|
}
|
|
2870
3810
|
await ended;
|
|
2871
3811
|
for (const callId of recordEnds)
|
|
2872
|
-
|
|
3812
|
+
ends.noteEnd(callId, "refused", notRun);
|
|
3813
|
+
for (const callId of cutOpen)
|
|
3814
|
+
ends.noteEnd(callId, "interrupted");
|
|
2873
3815
|
return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
|
|
2874
3816
|
}
|
|
2875
3817
|
return {
|