@parcha/agentrun-serve 0.1.0-beta.33 → 0.1.0-beta.35
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 +368 -0
- package/README.md +341 -208
- package/dist/adapters.d.ts +3 -4
- package/dist/adapters.js +18 -15
- package/dist/agent-rows.d.ts +99 -0
- package/dist/agent-rows.js +1 -0
- package/dist/agents-store.d.ts +6 -2
- package/dist/agents-store.js +75 -25
- package/dist/agents.d.ts +9 -125
- package/dist/agents.js +15 -305
- package/dist/answer-json.d.ts +23 -0
- package/dist/answer-json.js +58 -0
- package/dist/api-only.d.ts +1 -1
- package/dist/api-only.js +2 -2
- package/dist/archil-settings.d.ts +11 -1
- package/dist/archil-settings.js +10 -0
- package/dist/bash-read-only.d.ts +35 -0
- package/dist/bash-read-only.js +778 -0
- package/dist/box-settings.d.ts +3 -23
- package/dist/box-settings.js +7 -51
- package/dist/boxes.d.ts +17 -0
- package/dist/boxes.js +27 -20
- package/dist/browser-commands.d.ts +5 -2
- package/dist/browser-commands.js +4 -4
- package/dist/browser-computer.d.ts +5 -0
- package/dist/browser-computer.js +21 -0
- package/dist/browser-cost.d.ts +9 -6
- package/dist/browser-cost.js +95 -51
- package/dist/browser-live.d.ts +7 -20
- package/dist/browser-live.js +15 -93
- package/dist/browser-person.d.ts +18 -51
- package/dist/browser-person.js +94 -277
- package/dist/budget.d.ts +0 -5
- package/dist/budget.js +0 -5
- package/dist/cap.d.ts +14 -8
- package/dist/cap.js +19 -9
- package/dist/cli.js +71 -18
- package/dist/closed-pipes.d.ts +2 -0
- package/dist/closed-pipes.js +13 -0
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +2 -0
- package/dist/computer-keys.d.ts +20 -10
- package/dist/computer-keys.js +36 -54
- package/dist/computer-setting.d.ts +20 -3
- package/dist/computer-setting.js +58 -10
- package/dist/computers.d.ts +35 -2
- package/dist/computers.js +72 -11
- package/dist/confine.d.ts +120 -0
- package/dist/confine.js +436 -0
- package/dist/console/assets/index-B7NKTU8E.css +1 -0
- package/dist/console/assets/index-CXZMgJE7.js +550 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-cap.d.ts +7 -29
- package/dist/decision-cap.js +3 -94
- package/dist/decision-rows.d.ts +1 -1
- package/dist/decision-rows.js +1 -1
- package/dist/docker-daemon.d.ts +31 -0
- package/dist/docker-daemon.js +56 -0
- package/dist/effort-guidance.js +4 -3
- package/dist/environment.d.ts +0 -3
- package/dist/environment.js +3 -5
- package/dist/errors.d.ts +1 -2
- package/dist/errors.js +9 -9
- package/dist/explain.js +3 -1
- package/dist/filed-answer.d.ts +32 -0
- package/dist/filed-answer.js +160 -0
- package/dist/files.d.ts +1 -3
- package/dist/files.js +2 -4
- package/dist/github-connection.d.ts +1 -1
- package/dist/github-connection.js +25 -7
- package/dist/github-faux.d.ts +26 -0
- package/dist/github-faux.js +76 -0
- package/dist/github.d.ts +6 -2
- package/dist/github.js +5 -3
- package/dist/graph-served.d.ts +5 -3
- package/dist/graph-served.js +14 -6
- package/dist/graph-view.d.ts +3 -5
- package/dist/graph-view.js +9 -16
- package/dist/handed-values.d.ts +9 -0
- package/dist/handed-values.js +26 -0
- package/dist/harness-install.d.ts +1 -7
- package/dist/harness-install.js +1 -18
- package/dist/harness-opencode/adapter.d.ts +7 -0
- package/dist/harness-opencode/adapter.js +23 -6
- package/dist/harness-opencode/harness.js +0 -1
- package/dist/harness-opencode/host/policy.js +2 -2
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/verify.d.ts +17 -0
- package/dist/harness-opencode/verify.js +30 -10
- package/dist/harness-table.js +6 -1
- package/dist/heard.js +1 -1
- package/dist/held-fd.d.ts +5 -0
- package/dist/held-fd.js +14 -0
- package/dist/host-calls.d.ts +20 -0
- package/dist/host-calls.js +12 -0
- package/dist/host-tools.d.ts +4 -21
- package/dist/host-tools.js +4 -61
- package/dist/host.d.ts +2 -4
- package/dist/host.js +2 -7
- package/dist/import-summary.d.ts +1 -5
- package/dist/import-summary.js +0 -21
- package/dist/import.d.ts +6 -6
- package/dist/import.js +14 -15
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/key-refusal.d.ts +5 -1
- package/dist/key-refusal.js +19 -4
- package/dist/learn/check.d.ts +8 -2
- package/dist/learn/check.js +85 -31
- package/dist/learn/folder.d.ts +11 -4
- package/dist/learn/folder.js +17 -19
- package/dist/learn/grade.d.ts +18 -1
- package/dist/learn/grade.js +108 -14
- package/dist/learn/index.d.ts +5 -5
- package/dist/learn/index.js +5 -5
- package/dist/learn/learning.sh +1 -14
- package/dist/learn/notes.d.ts +14 -3
- package/dist/learn/notes.js +16 -6
- package/dist/learn/reflect.d.ts +31 -2
- package/dist/learn/reflect.js +83 -6
- package/dist/learn/relevance.d.ts +24 -0
- package/dist/learn/relevance.js +91 -0
- package/dist/learn/secrets.d.ts +7 -1
- package/dist/learn/secrets.js +86 -19
- package/dist/learn/skills.d.ts +159 -18
- package/dist/learn/skills.js +644 -64
- package/dist/learned-nodes.d.ts +14 -0
- package/dist/learned-nodes.js +8 -0
- package/dist/learned-workflow.d.ts +41 -6
- package/dist/learned-workflow.js +153 -18
- package/dist/learning-routes.d.ts +49 -4
- package/dist/learning-routes.js +113 -31
- package/dist/learning-run.d.ts +16 -31
- package/dist/learning-run.js +31 -38
- package/dist/learning-words.d.ts +12 -5
- package/dist/learning-words.js +18 -9
- package/dist/learning.d.ts +91 -97
- package/dist/learning.js +176 -320
- package/dist/live/stream.js +1 -1
- package/dist/live/translate.js +12 -2
- package/dist/llm.d.ts +4 -1
- package/dist/llm.js +4 -2
- package/dist/local-models.d.ts +11 -5
- package/dist/local-models.js +13 -8
- package/dist/mcp-gateway.d.ts +17 -49
- package/dist/mcp-gateway.js +55 -136
- package/dist/mcp-oauth.d.ts +10 -14
- package/dist/mcp-oauth.js +14 -32
- package/dist/mcp-probe.d.ts +0 -7
- package/dist/mcp-probe.js +4 -10
- package/dist/mcp-servers-store.d.ts +18 -18
- package/dist/mcp-servers-store.js +12 -14
- package/dist/mcp-store.js +3 -4
- package/dist/mcp.js +4 -3
- package/dist/model.d.ts +9 -7
- package/dist/model.js +51 -27
- package/dist/monid.d.ts +0 -2
- package/dist/monid.js +3 -6
- package/dist/openapi.d.ts +8 -1
- package/dist/openapi.js +156 -58
- package/dist/page.d.ts +1 -3
- package/dist/page.js +6 -18
- package/dist/paid-calls.d.ts +21 -27
- package/dist/paid-calls.js +26 -61
- package/dist/pause.d.ts +2 -19
- package/dist/pause.js +5 -74
- package/dist/port-models.d.ts +10 -3
- package/dist/port-models.js +26 -6
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +80 -45
- package/dist/push-handler.d.ts +1 -1
- package/dist/reflect-range.d.ts +25 -0
- package/dist/reflect-range.js +30 -0
- package/dist/refusal-words.d.ts +5 -1
- package/dist/refusal-words.js +5 -1
- package/dist/rows.d.ts +1 -1
- package/dist/run-cut.d.ts +0 -6
- package/dist/run-cut.js +0 -6
- package/dist/run-db.d.ts +2 -11
- package/dist/run-db.js +2 -37
- package/dist/run-launch.d.ts +21 -2
- package/dist/run-launch.js +14 -5
- package/dist/run-learning-served.d.ts +21 -4
- package/dist/run-learning-served.js +23 -13
- package/dist/run-reads-over-store.d.ts +5 -3
- package/dist/run-reads-over-store.js +25 -14
- package/dist/run-secrets.d.ts +1 -1
- package/dist/run-timeline-served.d.ts +5 -1
- package/dist/run-timeline-served.js +27 -6
- package/dist/run-view.d.ts +37 -22
- package/dist/run-view.js +85 -38
- package/dist/runnable.d.ts +21 -10
- package/dist/runnable.js +35 -12
- package/dist/runner/adapter-loop.d.ts +36 -5
- package/dist/runner/adapter-loop.js +663 -69
- package/dist/runner/adapter-run-spec.d.ts +42 -8
- package/dist/runner/adapter-run-spec.js +186 -52
- package/dist/runner/adapters/index.js +11 -1
- package/dist/runner/adapters/pi.d.ts +40 -2
- package/dist/runner/adapters/pi.js +110 -27
- package/dist/runner/beside.d.ts +38 -3
- package/dist/runner/beside.js +54 -5
- package/dist/runner/claim-secrets.d.ts +16 -1
- package/dist/runner/claim-secrets.js +62 -14
- package/dist/runner/cli-run-spec.d.ts +5 -0
- package/dist/runner/cli-run-spec.js +159 -41
- package/dist/runner/commands.js +1 -1
- package/dist/runner/computer-journal.d.ts +15 -2
- package/dist/runner/computer-journal.js +41 -5
- package/dist/runner/conformance/harness.d.ts +1 -0
- package/dist/runner/conformance/harness.js +123 -13
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/dispatch.d.ts +8 -1
- package/dist/runner/dispatch.js +81 -7
- package/dist/runner/end-of-run.d.ts +8 -2
- package/dist/runner/end-of-run.js +10 -4
- package/dist/runner/github-app.d.ts +7 -2
- package/dist/runner/github-app.js +47 -16
- package/dist/runner/harness-loops.d.ts +15 -2
- package/dist/runner/harness-loops.js +38 -2
- package/dist/runner/journal-kinds.d.ts +60 -6
- package/dist/runner/journal-kinds.js +43 -5
- package/dist/runner/journal-reader.d.ts +1 -1
- package/dist/runner/journal-reader.js +2 -2
- package/dist/runner/learning-ask.d.ts +4 -0
- package/dist/runner/learning-ask.js +15 -1
- package/dist/runner/learning-end.d.ts +18 -3
- package/dist/runner/learning-end.js +194 -20
- package/dist/runner/learning-loop.d.ts +7 -0
- package/dist/runner/learning-loop.js +36 -8
- package/dist/runner/learning-seed.d.ts +6 -0
- package/dist/runner/learning-seed.js +6 -0
- package/dist/runner/loop-contract.d.ts +4 -0
- package/dist/runner/main.d.ts +61 -9
- package/dist/runner/main.js +144 -20
- package/dist/runner/mcp-claim.d.ts +3 -0
- package/dist/runner/mcp-claim.js +7 -3
- package/dist/runner/mcp-github.d.ts +11 -2
- package/dist/runner/mcp-github.js +55 -4
- package/dist/runner/mcp-run.d.ts +2 -0
- package/dist/runner/mcp-run.js +16 -5
- package/dist/runner/memory-claim.d.ts +9 -0
- package/dist/runner/memory-claim.js +25 -0
- package/dist/runner/metrics.d.ts +46 -1
- package/dist/runner/metrics.js +156 -1
- package/dist/runner/model-route.d.ts +16 -0
- package/dist/runner/model-route.js +134 -10
- package/dist/runner/reflect-hook.d.ts +12 -1
- package/dist/runner/reflect-hook.js +33 -3
- package/dist/runner/runner.d.ts +20 -0
- package/dist/runner/runner.js +146 -18
- package/dist/runner/spec-holds.d.ts +7 -2
- package/dist/runner/spec-holds.js +4 -3
- package/dist/runner/store-port.d.ts +1 -1
- package/dist/runner/store-secrets.d.ts +3 -3
- package/dist/runner/store-secrets.js +8 -12
- package/dist/runner/text-tools.d.ts +44 -0
- package/dist/runner/text-tools.js +237 -0
- package/dist/runner/workflow-host.d.ts +7 -2
- package/dist/runner/workflow-host.js +3 -1
- package/dist/runner/workflow-loop.d.ts +10 -1
- package/dist/runner/workflow-loop.js +14 -6
- package/dist/runner/workflow-spec.d.ts +21 -0
- package/dist/runner/workflow-spec.js +217 -93
- package/dist/runs-over-store.d.ts +14 -3
- package/dist/runs-over-store.js +100 -23
- package/dist/seal-key.d.ts +0 -2
- package/dist/seal-key.js +5 -45
- package/dist/sealed-settings-store.d.ts +19 -4
- package/dist/sealed-settings-store.js +9 -9
- package/dist/sealing.d.ts +4 -0
- package/dist/sealing.js +20 -0
- package/dist/secret-cut.d.ts +1 -1
- package/dist/secret-cut.js +1 -1
- package/dist/secret-name.d.ts +9 -0
- package/dist/secret-name.js +15 -0
- package/dist/secret-writes.d.ts +0 -1
- package/dist/secret-writes.js +0 -1
- package/dist/server-fs.d.ts +4 -0
- package/dist/server-fs.js +8 -2
- package/dist/server-lock.d.ts +0 -24
- package/dist/server-lock.js +5 -85
- package/dist/server-secrets-store.d.ts +4 -4
- package/dist/server-secrets-store.js +9 -31
- package/dist/server-secrets.d.ts +4 -9
- package/dist/server-secrets.js +12 -36
- package/dist/server.d.ts +37 -56
- package/dist/server.js +322 -134
- package/dist/sign-ins-store.d.ts +34 -36
- package/dist/sign-ins-store.js +27 -38
- package/dist/sign-ins.d.ts +2 -119
- package/dist/sign-ins.js +5 -311
- package/dist/standard-webhooks.d.ts +1 -1
- package/dist/standard-webhooks.js +1 -1
- package/dist/stats.d.ts +3 -2
- package/dist/stats.js +1 -1
- package/dist/stop-signals.d.ts +4 -2
- package/dist/stop-signals.js +5 -3
- package/dist/store/agent-body.d.ts +12 -2
- package/dist/store/agent-body.js +22 -4
- package/dist/store/deadline.d.ts +18 -0
- package/dist/store/deadline.js +45 -0
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +2 -2
- package/dist/store/open.d.ts +6 -3
- package/dist/store/open.js +2 -2
- package/dist/store/postgres/connection.d.ts +22 -2
- package/dist/store/postgres/connection.js +211 -41
- package/dist/store/postgres/migrate.d.ts +4 -0
- package/dist/store/postgres/migrate.js +9 -2
- package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
- package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
- package/dist/store/postgres/store.d.ts +9 -2
- package/dist/store/postgres/store.js +9 -0
- package/dist/store/schema.js +1 -1
- package/dist/store/seal.js +2 -2
- package/dist/store/sqlite/connection.js +14 -5
- package/dist/store/sqlite/run-patch.d.ts +3 -0
- package/dist/store/sqlite/run-patch.js +3 -0
- package/dist/store/sqlite/store.js +41 -12
- package/dist/store/store.d.ts +35 -6
- package/dist/store/store.js +12 -2
- package/dist/store-reads/cap.d.ts +1 -1
- package/dist/store-reads/cap.js +22 -4
- package/dist/store-reads/journal.d.ts +9 -6
- package/dist/store-reads/journal.js +129 -18
- package/dist/store-reads/learning.d.ts +82 -8
- package/dist/store-reads/learning.js +184 -11
- package/dist/store-reads/workflow.d.ts +1 -1
- package/dist/store-reads/workflow.js +1 -1
- package/dist/store-view.d.ts +19 -1
- package/dist/store-view.js +95 -27
- package/dist/template-eval.d.ts +60 -4
- package/dist/template-eval.js +120 -54
- package/dist/templates.d.ts +33 -14
- package/dist/templates.js +82 -46
- package/dist/timeline/group.d.ts +33 -0
- package/dist/timeline/group.js +77 -0
- package/dist/timeline/index.d.ts +7 -0
- package/dist/timeline/index.js +7 -0
- package/dist/timeline/labels.d.ts +79 -0
- package/dist/timeline/labels.js +150 -0
- package/dist/timeline/origin.d.ts +56 -0
- package/dist/timeline/origin.js +92 -0
- package/dist/timeline/render-text.d.ts +11 -0
- package/dist/timeline/render-text.js +62 -0
- package/dist/timeline/timeline.d.ts +282 -0
- package/dist/timeline/timeline.js +1308 -0
- package/dist/timeline/util.d.ts +17 -0
- package/dist/timeline/util.js +49 -0
- package/dist/tool-budget.d.ts +18 -0
- package/dist/tool-budget.js +50 -0
- package/dist/tool-gate.d.ts +47 -218
- package/dist/tool-gate.js +87 -545
- package/dist/tool-keys-store.d.ts +11 -12
- package/dist/tool-keys-store.js +24 -31
- package/dist/tool-keys.d.ts +5 -101
- package/dist/tool-keys.js +8 -267
- package/dist/tool-plane.d.ts +23 -52
- package/dist/tool-plane.js +23 -81
- package/dist/tool-settings-store.d.ts +1 -2
- package/dist/tool-settings-store.js +5 -8
- package/dist/tools.d.ts +67 -25
- package/dist/tools.js +170 -119
- package/dist/trigger-adapter.d.ts +2 -2
- package/dist/trigger-targets.d.ts +13 -1
- package/dist/trigger-targets.js +31 -1
- package/dist/triggers.d.ts +2 -2
- package/dist/triggers.js +3 -3
- package/dist/turn-end.d.ts +1 -1
- package/dist/turn-end.js +1 -1
- package/dist/turns.d.ts +0 -6
- package/dist/turns.js +0 -19
- package/dist/uploads.d.ts +28 -5
- package/dist/uploads.js +83 -10
- package/dist/usage.d.ts +1 -49
- package/dist/usage.js +3 -84
- package/dist/validate.d.ts +4 -0
- package/dist/validate.js +33 -14
- package/dist/webhooks.d.ts +102 -76
- package/dist/webhooks.js +266 -233
- package/dist/workflow-run.d.ts +114 -0
- package/dist/workflow-run.js +144 -0
- package/dist/workspace/archil-claim.d.ts +2 -2
- package/dist/workspace/archil-claim.js +4 -3
- package/dist/workspace/archil-disk.d.ts +10 -1
- package/dist/workspace/archil-disk.js +4 -0
- package/dist/workspace/archil-exec.d.ts +12 -2
- package/dist/workspace/archil-exec.js +16 -0
- package/dist/workspace/archil.d.ts +2 -2
- package/dist/workspace/archil.js +25 -5
- package/dist/workspace/attach.js +2 -0
- package/dist/workspace/beneath.d.ts +19 -0
- package/dist/workspace/beneath.js +106 -0
- package/dist/workspace/computer-deps.d.ts +26 -9
- package/dist/workspace/computer-deps.js +144 -43
- package/dist/workspace/computer-for-claim.d.ts +17 -14
- package/dist/workspace/computer-for-claim.js +99 -26
- package/dist/workspace/computer-hold.d.ts +6 -1
- package/dist/workspace/computer-hold.js +6 -1
- package/dist/workspace/computer-janitor.d.ts +47 -0
- package/dist/workspace/computer-janitor.js +182 -0
- package/dist/workspace/computer-ledger.d.ts +1 -8
- package/dist/workspace/computer-ledger.js +0 -3
- package/dist/workspace/computer-providers.d.ts +5 -3
- package/dist/workspace/computer-providers.js +11 -9
- package/dist/workspace/grep-worker.d.ts +5 -0
- package/dist/workspace/grep-worker.js +9 -6
- package/dist/workspace/hands.d.ts +5 -2
- package/dist/workspace/hands.js +4 -3
- package/dist/workspace/index.d.ts +6 -5
- package/dist/workspace/index.js +4 -4
- package/dist/workspace/local.d.ts +14 -2
- package/dist/workspace/local.js +170 -43
- package/dist/workspace/paths.js +3 -2
- package/dist/workspace/pi-env.d.ts +4 -0
- package/dist/workspace/pi-env.js +3 -2
- package/dist/workspace/resolve-computer.d.ts +55 -10
- package/dist/workspace/resolve-computer.js +66 -14
- package/dist/workspace/run-tools.d.ts +15 -31
- package/dist/workspace/run-tools.js +19 -30
- package/dist/workspace/workspace.d.ts +5 -0
- package/dist/workspace-paths.d.ts +0 -17
- package/dist/workspace-paths.js +1 -41
- package/dist/workspace.d.ts +0 -17
- package/dist/workspace.js +4 -110
- package/package.json +14 -14
- package/skills/agentrun-serve/SKILL.md +1 -1
- package/templates/README.md +11 -5
- package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
- package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
- package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
- package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
- package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
- package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
- package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
- package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
- package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
- package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
- package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
- package/templates/market-monitor/agent.md +2 -2
- package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
- package/templates/release-notes/agent.md +11 -0
- package/dist/bound-files.d.ts +0 -4
- package/dist/bound-files.js +0 -164
- package/dist/coding-tools.d.ts +0 -47
- package/dist/coding-tools.js +0 -189
- package/dist/computer-adb.d.ts +0 -12
- package/dist/computer-adb.js +0 -14
- package/dist/console/assets/index-Dn0ngwG9.js +0 -535
- package/dist/console/assets/index-DvW6Aled.css +0 -1
- package/dist/grade.d.ts +0 -63
- package/dist/grade.js +0 -150
- package/dist/mcp-servers.d.ts +0 -269
- package/dist/mcp-servers.js +0 -456
- package/dist/packs.d.ts +0 -71
- package/dist/packs.js +0 -180
- package/dist/sealed-settings.d.ts +0 -60
- package/dist/sealed-settings.js +0 -171
- package/dist/sessions.d.ts +0 -6
- package/dist/sessions.js +0 -109
- package/dist/workspace/computer-serves.d.ts +0 -12
- package/dist/workspace/computer-serves.js +0 -15
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
|
|
2
2
|
import { createModels } from "@earendil-works/pi-ai/models";
|
|
3
|
-
import { createRegistry, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
4
|
-
import { modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
|
|
5
|
-
import { ASK_PERSON_WAITING, endedAnswer, KINDS, withdrawnAnswers } from "./journal-kinds.js";
|
|
6
|
-
import { endedOnTurnEndingTool, HOST_PHASE, originOf, RUN_RESUMED } from "
|
|
3
|
+
import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
4
|
+
import { answeredUnpriced, modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
|
|
5
|
+
import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
|
|
6
|
+
import { endedOnTurnEndingTool, HOST_PHASE, MESSAGE_ORIGIN, originOf, RUN_RESUMED } from "../timeline/index.js";
|
|
7
|
+
import { raiseFollowUpId } from "../run-view.js";
|
|
8
|
+
/** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
|
|
9
|
+
const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
|
|
7
10
|
import { ClaimRefused, deniedText, endedBy, noteOf } from "./loop-contract.js";
|
|
8
|
-
import { deniedText as setToDenyText } from "../refusal-words.js";
|
|
11
|
+
import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
|
|
9
12
|
import { ADAPTER_API } from "../turn-end.js";
|
|
10
13
|
import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
|
|
11
14
|
import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
|
|
@@ -13,13 +16,15 @@ import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
|
|
|
13
16
|
import { isComputerCommand, journalHold } from "./computer-journal.js";
|
|
14
17
|
import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
|
|
15
18
|
import { journalSessions } from "./sessions.js";
|
|
16
|
-
import { DECISION_SESSION, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
17
|
-
import { portModels } from "../port-models.js";
|
|
19
|
+
import { DECISION_SESSION, FIT_TOLERANCE, overCapOf, paidRefusal, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
20
|
+
import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
|
|
18
21
|
import { bookedIn } from "../paid-calls.js";
|
|
22
|
+
import { withHostCalls } from "../host-calls.js";
|
|
19
23
|
import { sideEffect } from "./side-effects.js";
|
|
20
24
|
import { McpClaimRefused } from "./mcp-claim.js";
|
|
21
25
|
import { Fenced } from "../store/index.js";
|
|
22
26
|
import { parkedFollowUp } from "./mcp-run.js";
|
|
27
|
+
import { TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
|
|
23
28
|
/** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
|
|
24
29
|
export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
|
|
25
30
|
/** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
|
|
@@ -46,8 +51,29 @@ export function hostLifecycle() {
|
|
|
46
51
|
export function agentConversation(record) {
|
|
47
52
|
return Number(record.id) === Number(ROOT_CONVERSATION_ID) || record.owner !== undefined;
|
|
48
53
|
}
|
|
54
|
+
/** On the run's root: the spec's onConversation writes for it are owed (a phase made the root while the spec was built,
|
|
55
|
+
* before the spec's lifecycle was known). Set in the root's creating commit, cleared in the commit that makes them, so a
|
|
56
|
+
* claim lost in between leaves them to the next claim. */
|
|
57
|
+
const RootWritesOwed = defineDoc({ kind: "agentrun.root-writes-owed", version: 1, scope: "conversation", history: "latest", fork: "initial", initial: () => ({ owed: false }), checkpointWhen: () => false });
|
|
49
58
|
/** The most of a harness's own turn error a failed run's summary keeps. */
|
|
50
59
|
const TURN_ERROR_MAX = 500;
|
|
60
|
+
/** A paid call's refusal an earlier claim kept (KINDS.pausePending) whose pause never landed: the newest one with no
|
|
61
|
+
* pause (KINDS.budget), no end and no park on a person's question (KINDS.personAsked: the turn ended on the ask with no
|
|
62
|
+
* next request, so the refusal is spent, and the person's answer is no retry of the call) after it. Undefined when there
|
|
63
|
+
* is none. */
|
|
64
|
+
export function pendingPauseOf(entries) {
|
|
65
|
+
for (let at = entries.length - 1; at >= 0; at--) {
|
|
66
|
+
const entry = entries[at];
|
|
67
|
+
if (entry.kind === KINDS.budget || entry.kind === KINDS.end || entry.kind === KINDS.personAsked)
|
|
68
|
+
return undefined;
|
|
69
|
+
// A kept refusal, or none: a drop kept as null (the call would since fit, or the turn ended on a question).
|
|
70
|
+
if (entry.kind === KINDS.pausePending)
|
|
71
|
+
return (entry.data ?? undefined);
|
|
72
|
+
}
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
/** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
|
|
76
|
+
const DELIVER_NOW_MS = 5_000;
|
|
51
77
|
/** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
|
|
52
78
|
const cutWhole = (text, max) => {
|
|
53
79
|
const cut = text.slice(0, max);
|
|
@@ -105,7 +131,8 @@ export function bookingOfAnswer(records, given) {
|
|
|
105
131
|
turns.push(turn.turn);
|
|
106
132
|
if (side.has(turn.turn))
|
|
107
133
|
continue;
|
|
108
|
-
|
|
134
|
+
// An answer with no price of its own is unknown, never the hold it was booked at for the cap (answeredUnpriced).
|
|
135
|
+
const figure = answeredUnpriced(turn) ? null : turn.bookedUsd !== undefined ? turn.bookedUsd : turn.usd;
|
|
109
136
|
usd = usd !== null && typeof figure === "number" && Number.isFinite(figure) ? (usd ?? 0) + figure : null;
|
|
110
137
|
}
|
|
111
138
|
return { turns, usd };
|
|
@@ -116,7 +143,7 @@ const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forG
|
|
|
116
143
|
* fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
|
|
117
144
|
* it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
|
|
118
145
|
* message's timestamp: the Timeline dates its rows by them. */
|
|
119
|
-
async function openCliRecord(harness, journal, context, now) {
|
|
146
|
+
async function openCliRecord(harness, journal, context, now, cwd) {
|
|
120
147
|
const root = await harness.root(context);
|
|
121
148
|
const append = async (kind, data) => {
|
|
122
149
|
await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
|
|
@@ -124,11 +151,28 @@ async function openCliRecord(harness, journal, context, now) {
|
|
|
124
151
|
// Each call started on the record: whether it has its end; and each end, by call id.
|
|
125
152
|
const started = new Map();
|
|
126
153
|
const ends = new Map();
|
|
154
|
+
// A call parked at its gate (its start marked parked) and its sent mark: one parked and never marked never left, so it
|
|
155
|
+
// is never ended interrupted; it waits for its answer, which ends it (run once, refused, or withdrawn).
|
|
156
|
+
const parked = new Set();
|
|
157
|
+
const sent = new Set();
|
|
158
|
+
// The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
|
|
159
|
+
const sending = new Set();
|
|
127
160
|
let personWritten = false;
|
|
161
|
+
// 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
|
|
162
|
+
// claim, after a crash in the turn) reuses it, never writes a second.
|
|
163
|
+
const askedAt = new Map();
|
|
128
164
|
for (const entry of await entriesOf(journal, root.id, context)) {
|
|
129
165
|
const data = (entry.data ?? {});
|
|
166
|
+
if (entry.kind === KINDS.messageSending && typeof data.commandId === "number")
|
|
167
|
+
sending.add(data.commandId);
|
|
168
|
+
if (entry.kind === KINDS.endOfRunTurn && data.role === "person" && typeof data.requestId === "string")
|
|
169
|
+
askedAt.set(data.requestId, entry.id);
|
|
130
170
|
if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
|
|
131
171
|
ends.set(data.callId, { status: data.status ?? "done", ...(typeof data.output === "string" ? { output: data.output } : {}) });
|
|
172
|
+
if (entry.kind === KINDS.callStart && typeof data.callId === "string" && data.parked === true)
|
|
173
|
+
parked.add(data.callId);
|
|
174
|
+
if (entry.kind === KINDS.callSent && typeof data.callId === "string")
|
|
175
|
+
sent.add(data.callId);
|
|
132
176
|
if (entry.kind === KINDS.callStart && typeof data.callId === "string")
|
|
133
177
|
started.set(data.callId, started.get(data.callId) ?? false);
|
|
134
178
|
else if (entry.kind === KINDS.callEnd && typeof data.callId === "string")
|
|
@@ -137,7 +181,7 @@ async function openCliRecord(harness, journal, context, now) {
|
|
|
137
181
|
personWritten = true;
|
|
138
182
|
}
|
|
139
183
|
for (const [callId, ended] of started) {
|
|
140
|
-
if (ended)
|
|
184
|
+
if (ended || (parked.has(callId) && !sent.has(callId)))
|
|
141
185
|
continue;
|
|
142
186
|
await append(KINDS.callEnd, { callId, status: "interrupted" });
|
|
143
187
|
started.set(callId, true);
|
|
@@ -187,15 +231,71 @@ async function openCliRecord(harness, journal, context, now) {
|
|
|
187
231
|
await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
|
|
188
232
|
personWritten = true;
|
|
189
233
|
}),
|
|
234
|
+
message: (input, origin) => inTurn(async () => {
|
|
235
|
+
if (origin)
|
|
236
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] }), context);
|
|
237
|
+
else
|
|
238
|
+
await append(KINDS.message, { role: "person", text: input });
|
|
239
|
+
}),
|
|
240
|
+
async sending(commandId) {
|
|
241
|
+
let again = false;
|
|
242
|
+
await inTurn(async () => {
|
|
243
|
+
again = sending.has(commandId);
|
|
244
|
+
if (again)
|
|
245
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind: HOST_PHASE, data: { summary: MESSAGE_SENT_AGAIN, at: now() } }), context);
|
|
246
|
+
else
|
|
247
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.messageSending, data: { commandId, at: now() } }), context);
|
|
248
|
+
sending.add(commandId);
|
|
249
|
+
});
|
|
250
|
+
return again;
|
|
251
|
+
},
|
|
190
252
|
async start(callId, tool, input, replaySafe) {
|
|
253
|
+
await flushText();
|
|
254
|
+
await inTurn(async () => {
|
|
255
|
+
if (started.has(callId)) {
|
|
256
|
+
// Parked at its gate and now sent: its mark first, in its own commit (the flush before the send makes it last).
|
|
257
|
+
if (parked.has(callId) && !sent.has(callId) && started.get(callId) === false) {
|
|
258
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.callSent, data: { callId } }), context);
|
|
259
|
+
sent.add(callId);
|
|
260
|
+
}
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(cwd ? { cwd } : {}) });
|
|
264
|
+
started.set(callId, false);
|
|
265
|
+
});
|
|
266
|
+
},
|
|
267
|
+
async park(callId, tool, input, replaySafe, bridge) {
|
|
191
268
|
await flushText();
|
|
192
269
|
await inTurn(async () => {
|
|
193
270
|
if (started.has(callId))
|
|
194
271
|
return;
|
|
195
|
-
await append(KINDS.callStart, { callId, tool, input, replaySafe });
|
|
272
|
+
await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(bridge ? { bridge } : {}), ...(cwd ? { cwd } : {}) });
|
|
196
273
|
started.set(callId, false);
|
|
274
|
+
parked.add(callId);
|
|
275
|
+
});
|
|
276
|
+
},
|
|
277
|
+
async refused(callId, tool, input, replaySafe, words) {
|
|
278
|
+
await flushText();
|
|
279
|
+
await inTurn(async () => {
|
|
280
|
+
if (started.get(callId) === true)
|
|
281
|
+
return;
|
|
282
|
+
const at = now();
|
|
283
|
+
const start = { callId, tool, input, replaySafe, at };
|
|
284
|
+
const end = { callId, status: "refused", output: words, at };
|
|
285
|
+
await harness.commit(async (tx) => {
|
|
286
|
+
if (!started.has(callId))
|
|
287
|
+
await tx.appendEntry(root.id, { kind: KINDS.callStart, data: start });
|
|
288
|
+
await tx.appendEntry(root.id, { kind: KINDS.callEnd, data: end });
|
|
289
|
+
}, context);
|
|
290
|
+
started.set(callId, true);
|
|
291
|
+
ends.set(callId, { status: "refused", output: words });
|
|
197
292
|
});
|
|
198
293
|
},
|
|
294
|
+
unsentParked: () => [...parked].filter((callId) => !sent.has(callId) && started.get(callId) === false),
|
|
295
|
+
noteEnd(callId, status, output) {
|
|
296
|
+
started.set(callId, true);
|
|
297
|
+
ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
|
|
298
|
+
},
|
|
199
299
|
endOf: (callId) => ends.get(callId),
|
|
200
300
|
end: (callId, status, output) => inTurn(async () => {
|
|
201
301
|
if (started.get(callId) !== false)
|
|
@@ -204,8 +304,18 @@ async function openCliRecord(harness, journal, context, now) {
|
|
|
204
304
|
started.set(callId, true);
|
|
205
305
|
ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
|
|
206
306
|
}),
|
|
207
|
-
answering() {
|
|
307
|
+
answering: (requestId, prompt) => {
|
|
208
308
|
answer = "";
|
|
309
|
+
return inTurn(async () => {
|
|
310
|
+
if (askedAt.has(requestId))
|
|
311
|
+
return;
|
|
312
|
+
await harness.commit(async (tx) => {
|
|
313
|
+
if (await tx.submissionByRequest(root.id, requestId))
|
|
314
|
+
return;
|
|
315
|
+
const asked = await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId }, model: [{ role: "user", content: prompt, timestamp: now() }] });
|
|
316
|
+
askedAt.set(requestId, asked.id);
|
|
317
|
+
}, context);
|
|
318
|
+
});
|
|
209
319
|
},
|
|
210
320
|
answered: (requestId, prompt, status) => inTurn(async () => {
|
|
211
321
|
const said = answer ?? "";
|
|
@@ -213,7 +323,9 @@ async function openCliRecord(harness, journal, context, now) {
|
|
|
213
323
|
await harness.commit(async (tx) => {
|
|
214
324
|
if (await tx.submissionByRequest(root.id, requestId))
|
|
215
325
|
return;
|
|
216
|
-
|
|
326
|
+
// The prompt answering wrote as the turn was asked, else written now.
|
|
327
|
+
const written = askedAt.get(requestId);
|
|
328
|
+
const asked = written !== undefined ? { id: written } : await tx.appendEntry(root.id, { kind: KINDS.endOfRunTurn, data: { role: "person", text: prompt, requestId }, model: [{ role: "user", content: prompt, timestamp: now() }] });
|
|
217
329
|
if (status !== "completed") {
|
|
218
330
|
await tx.createSubmission({ type: "input", conversationId: root.id, requestId, status: "unanswered", entry: asked.id, reason: `the end-of-run turn ended ${status}` });
|
|
219
331
|
return;
|
|
@@ -244,7 +356,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
244
356
|
};
|
|
245
357
|
let stopped = () => { };
|
|
246
358
|
const stopping = new Promise((resolve) => (stopped = resolve));
|
|
247
|
-
/** Aborted by any stop of the run (AdapterRun.stopped, with the claim's signal)
|
|
359
|
+
/** Aborted by any stop of the run (AdapterRun.stopped, with the claim's signal): a host tool call in flight (a CLI's door
|
|
360
|
+
* call among them, whose own request signal its CLI may never abort) is cut with it, as pi's own abort cuts pi's calls.
|
|
361
|
+
* stop() aborts it first, with the stop's Interrupted, so the reason a cut call reads is the stop's. */
|
|
248
362
|
const stopAbort = new AbortController();
|
|
249
363
|
void stopping.then(() => stopAbort.abort(new Error("the run was stopped")));
|
|
250
364
|
let parked = () => { };
|
|
@@ -288,6 +402,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
288
402
|
/** While the end-of-run turn runs: a steer is left for the end, and its writes and edits under work/.learning/ are
|
|
289
403
|
* refused (REFLECT_NOTE_ONLY). */
|
|
290
404
|
let reflecting = false;
|
|
405
|
+
/** 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
|
|
406
|
+
* in the end-of-run turn, so no turn starts that the end, written after the hand-back, would cut. */
|
|
407
|
+
let handingBack = false;
|
|
291
408
|
/** A run a person's follow-up reopened (the store's runs.reopen: its journal holds the end of its last turn, its session
|
|
292
409
|
* opens idle): the follow-up's steer is this claim's turn, sent by steer() as a tracked turn (`sent`), and the claim waits
|
|
293
410
|
* for it, so the run's next end comes after that turn's answer. Undefined once the claim has read its delivered rows.
|
|
@@ -303,6 +420,19 @@ function adapterLoop(specOf, options, deps) {
|
|
|
303
420
|
* answer to a question that landed between the question's turn end and the wait's start. The wait takes it as its
|
|
304
421
|
* answer (waitInClaim), once. */
|
|
305
422
|
let idleSteer;
|
|
423
|
+
/** The messages a harness with no mid-turn steer (a CLI's: claude-agent, codex, opencode) took while its turn ran, in the
|
|
424
|
+
* order they came: each is sent as a turn of its own once the turn in flight ends, its row taken once the session holds
|
|
425
|
+
* it (sendAfterTurn) (#2174: refused here, a message the API had accepted was lost). Kept across a pass's restart; a row still here
|
|
426
|
+
* when the claim ends is untaken, so the run's next claim takes it again, or the run's end refuses it in the end's words. */
|
|
427
|
+
const afterTurn = [];
|
|
428
|
+
/** The request ids of the messages placed as steers into a turn in flight (a harness that steers: pi), in order. pi
|
|
429
|
+
* answers one in the turn it steered, or, placed as that turn answered, in a run of its own right after it: the turn's
|
|
430
|
+
* end waits on each one's submission (turnOfRequest) before the run may end, so the run never reads completed with a
|
|
431
|
+
* message it took still unanswered, and its session is never closed under that answer. */
|
|
432
|
+
const steeredIn = [];
|
|
433
|
+
/** 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
|
|
434
|
+
* during the end-of-run turn does. */
|
|
435
|
+
let turnsOver = false;
|
|
306
436
|
/** The wait in the claim is over (an answer placed, a lapse, the run's end, park, restart or loss): its holds go. `of`:
|
|
307
437
|
* only while it is that wait's (a wait that settles late never ends a later one). */
|
|
308
438
|
const endWait = (of) => {
|
|
@@ -341,7 +471,28 @@ function adapterLoop(specOf, options, deps) {
|
|
|
341
471
|
/** The pass's MCP (spec.mcp), until the pass ends; and whether a command row came since its credentials were last made
|
|
342
472
|
* fresh (a parked token may have expired meanwhile). */
|
|
343
473
|
let mcp;
|
|
474
|
+
/** The calls of this run a person approved (an ask answered allow, on this claim or read from the journal on a resume),
|
|
475
|
+
* each with the arguments its approval card showed (its journaled ask's): an approval covers what that card named. */
|
|
476
|
+
const approvedCalls = new Map();
|
|
477
|
+
/** Each answered call's ask as journaled (the card the person saw), set by answerOf as it reads or writes the answer. */
|
|
478
|
+
const askedArgs = new Map();
|
|
479
|
+
/** An MCP tool of the run as the claim's pass wrapped it, by its catalog name (set once its tools are wrapped). */
|
|
480
|
+
let mcpHosted = () => undefined;
|
|
344
481
|
let mcpStale = false;
|
|
482
|
+
/** Marks the raise's follow-up the server's (MESSAGE_ORIGIN, timeline/origin.ts) before it is sent: its own commit, the
|
|
483
|
+
* input's user entry left as pi writes it (its submission, which a re-claim answers from, unchanged), so the Timeline
|
|
484
|
+
* shows the next user entry with exactly this text as "AgentRun: …". Once per follow-up: the marker names its request
|
|
485
|
+
* id, and a re-claim that finds one under it writes none (a second would stay open, and could take a person's later
|
|
486
|
+
* message of the same words for the server's). A CLI's run records its follow-up through its own record, which carries
|
|
487
|
+
* the origin itself. */
|
|
488
|
+
const markServerFollowUp = async (theHarness, theRoot, text, requestId) => {
|
|
489
|
+
if (cliRecord)
|
|
490
|
+
return;
|
|
491
|
+
const marked = (await entriesOf(gate.journal, theRoot.id, context)).some((entry) => entry.kind === MESSAGE_ORIGIN && entry.data?.requestId === requestId);
|
|
492
|
+
if (marked)
|
|
493
|
+
return;
|
|
494
|
+
await theHarness.commit((tx) => tx.appendEntry(theRoot.id, { kind: MESSAGE_ORIGIN, data: { origin: CAP_RAISED_ORIGIN, text, requestId } }), context);
|
|
495
|
+
};
|
|
345
496
|
/** The run's raise state, read from its root: the newest budget entry with no raise entry after it is the pause it
|
|
346
497
|
* waits at (its pending cap is the cap a raise is checked against); the newest raise entry is its last raise. */
|
|
347
498
|
async function raiseStateOf() {
|
|
@@ -388,33 +539,48 @@ function adapterLoop(specOf, options, deps) {
|
|
|
388
539
|
await takeRaises();
|
|
389
540
|
return { taken: true };
|
|
390
541
|
};
|
|
542
|
+
/** A hand-back that reaches a loop whose pass is over, or never opened, waits for the run's next claim. */
|
|
543
|
+
const HAND_BACK_LATER = "the run is parking or ending: the hand-back waits for its next claim";
|
|
391
544
|
/** Hand-backs one at a time: each decides on the journal the one before it left, so a second answer meets the first. */
|
|
392
545
|
let handing = Promise.resolve();
|
|
393
546
|
/** A person's answer to the agent's browser hand-over (hand-back.ts): the first for an ask is its answer, committed as
|
|
394
547
|
* the answered hand-over entry at the row's own time, the row taken in that commit. A row after the ask lapsed writes
|
|
395
|
-
* the expiry (at the expiry's time) and is refused; one for an ask answered already, or never made, is refused.
|
|
548
|
+
* the expiry (at the expiry's time) and is refused; one for an ask answered already, or never made, is refused. `later`
|
|
549
|
+
* when this claim can no longer say, as an approval's (waitsFor): its Harness never opened, or its pass is over. */
|
|
396
550
|
const handBack = (command) => {
|
|
397
551
|
const turn = handing.then(async () => {
|
|
398
552
|
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
399
553
|
const [theGate, theHarness, theRoot] = [gate, harness, root];
|
|
400
|
-
if (!theGate || !theHarness || !theRoot)
|
|
401
|
-
return {
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
if (write && refused === undefined)
|
|
412
|
-
await landed;
|
|
413
|
-
return refused === undefined ? { taken: true } : { refused };
|
|
554
|
+
if (!theGate || !theHarness || !theRoot || theGate.sealed)
|
|
555
|
+
return { later: HAND_BACK_LATER };
|
|
556
|
+
try {
|
|
557
|
+
return await handBackThrough(command, theGate, theHarness, theRoot);
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
// Sealed while it read or wrote: closeSession seals, then closes the Harness the answer went through.
|
|
561
|
+
if (theGate.sealed)
|
|
562
|
+
return { later: HAND_BACK_LATER };
|
|
563
|
+
throw error;
|
|
564
|
+
}
|
|
414
565
|
});
|
|
415
566
|
handing = turn.catch(() => undefined);
|
|
416
567
|
return turn;
|
|
417
568
|
};
|
|
569
|
+
/** A hand-back's answer, decided and written through the pass's open Harness. */
|
|
570
|
+
const handBackThrough = async (command, theGate, theHarness, theRoot) => {
|
|
571
|
+
// The person's answer takes its row in the commit that writes it: staged for the answer this row would write (its ask,
|
|
572
|
+
// its outcome, at its own time). Decided and written in one commit (answerOnce), so no other writer's answer (the
|
|
573
|
+
// browser host's give or expiry) lands between: a row whose commit writes nothing, or the ask's expiry, takes none,
|
|
574
|
+
// and the staging matches nothing (an answered ask is never answered again).
|
|
575
|
+
const { ask, outcome } = (command.body ?? {});
|
|
576
|
+
const at = new Date(command.createdAt).toISOString();
|
|
577
|
+
const landed = typeof ask === "string" ? theGate.expect(writesEntry(KINDS.handover, (data) => data.id === ask && data.state === outcome && data.at === at), { take: [command.id] }) : undefined;
|
|
578
|
+
landed?.catch(() => undefined);
|
|
579
|
+
const { write, refused } = await answerOnce((change) => theHarness.commit(change, context), theRoot.id, (entries) => handBackOf(entries, command.body, command.createdAt));
|
|
580
|
+
if (write && refused === undefined)
|
|
581
|
+
await landed;
|
|
582
|
+
return refused === undefined ? { taken: true } : { refused };
|
|
583
|
+
};
|
|
418
584
|
/** A person's take-over or hand-back of the run's desktop or phone (computer-journal.ts): applied to the hold, and taken
|
|
419
585
|
* by the commit that writes the change it made (its entries carry the row's id); refused in words when it changed
|
|
420
586
|
* nothing. One at a time, behind the browser's hand-backs' turn: each meets the hold the one before it left. */
|
|
@@ -471,6 +637,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
471
637
|
// to answer. Left untaken, so the run's end says it came after the answer.
|
|
472
638
|
if (reflecting)
|
|
473
639
|
return { later: "the run has answered and is ending: the steer is not placed in its end-of-run turn" };
|
|
640
|
+
if (handingBack)
|
|
641
|
+
return { later: "the run has answered and waits for its computer to be handed back before it ends: the steer is not placed" };
|
|
474
642
|
const text = typeof command.body?.text === "string" ? command.body.text : "";
|
|
475
643
|
const requestId = commandRequest(command.id);
|
|
476
644
|
// A message that answers nothing (a trigger's, answers: false) waits for the turn's end and runs as a turn of its
|
|
@@ -510,11 +678,25 @@ function adapterLoop(specOf, options, deps) {
|
|
|
510
678
|
await taken.catch(() => { });
|
|
511
679
|
return { taken: true };
|
|
512
680
|
}
|
|
513
|
-
if (!session.steer)
|
|
514
|
-
return { refused: "this harness takes no steer mid-turn" };
|
|
515
681
|
// Who wrote it, when the person did not (a trigger's message): carried on its input, as the Timeline shows it.
|
|
516
682
|
const origin = originOf(command.body?.origin);
|
|
517
|
-
|
|
683
|
+
if (!session.steer) {
|
|
684
|
+
// A harness that takes no message mid-turn: the API answered it `follow_up` (it waits for the turn's end), so it is
|
|
685
|
+
// the run's next turn, after any taken before it (afterTurn). Taken now as the dispatch takes a row it buffers: the
|
|
686
|
+
// store's take is the commit of its submission, once sent.
|
|
687
|
+
if (turnsOver)
|
|
688
|
+
return { later: "the run has answered and is ending: the message waits for the run's end" };
|
|
689
|
+
afterTurn.push({ commandId: command.id, text, requestId, ...(origin ? { origin } : {}) });
|
|
690
|
+
return { taken: true };
|
|
691
|
+
}
|
|
692
|
+
// The claim's last turn has ended and nothing more is sent (turnsOver): a steer placed now would start a turn the run's
|
|
693
|
+
// end then cuts, so it waits for the run's end, as a CLI's message does.
|
|
694
|
+
if (turnsOver && !askedLast)
|
|
695
|
+
return { later: "the run has answered and is ending: the message waits for the run's end" };
|
|
696
|
+
// A person's answer to the question the last turn ended on (a parked ask's, its run claimed again by it): the row's
|
|
697
|
+
// waiting summary goes in its commit, as an in-claim wait's answer clears it. Left until the end commit, the answer's
|
|
698
|
+
// turn reads running, held and "Waiting for your reply", and the server tells run.needs_input for that ask again.
|
|
699
|
+
const taken = gate.expect(writesSubmission(requestId), { take: [command.id], ...(askedLast ? { run: { summary: null } } : {}) });
|
|
518
700
|
// A seal while the steer is placed fails it before it is awaited: handled here.
|
|
519
701
|
taken.catch(() => undefined);
|
|
520
702
|
const theGate = gate;
|
|
@@ -533,9 +715,37 @@ function adapterLoop(specOf, options, deps) {
|
|
|
533
715
|
return { later: "the run is parking: the steer waits for its resume" };
|
|
534
716
|
return { refused: `the steer was not placed: ${error.message}` };
|
|
535
717
|
}
|
|
718
|
+
// Placed in the turn in flight: the turn's end waits for it to be answered (steeredIn), never ending the run first.
|
|
719
|
+
if (!askedLast)
|
|
720
|
+
steeredIn.push(requestId);
|
|
536
721
|
await taken.catch(() => { });
|
|
537
722
|
return { taken: true };
|
|
538
723
|
};
|
|
724
|
+
/** A message the turn in flight could not take (afterTurn), sent as a turn of its own. Its row is taken only once the
|
|
725
|
+
* session holds the prompt (send resolves once it is placed): in the commit that writes it on the run's record, right
|
|
726
|
+
* after the send (a CLI's session writes no submission to the run's journal), or, for an adapter keeping its own record,
|
|
727
|
+
* in its submission's commit. A runner lost before that leaves the row untaken, so the next claim sends it again: a
|
|
728
|
+
* message may be sent twice after a crash, never lost. Its turn's end is what this gives. */
|
|
729
|
+
const sendAfterTurn = async (theGate, next) => {
|
|
730
|
+
// Its intent mark, durable before the send (the flush): a runner lost between the send and the take leaves the mark,
|
|
731
|
+
// and the next claim's send of the same row says it is sent again (CliRecord.sending), never silently paid twice.
|
|
732
|
+
if (cliRecord) {
|
|
733
|
+
await cliRecord.sending(next.commandId);
|
|
734
|
+
await deps.flush();
|
|
735
|
+
}
|
|
736
|
+
const origin = next.origin === undefined ? undefined : JSON.stringify(next.origin);
|
|
737
|
+
const match = !cliRecord
|
|
738
|
+
? writesSubmission(next.requestId)
|
|
739
|
+
: origin !== undefined
|
|
740
|
+
? writesEntry(KINDS.input, (data) => JSON.stringify(data.origin) === origin)
|
|
741
|
+
: writesEntry(KINDS.message, (data) => data.role === "person" && data.text === next.text);
|
|
742
|
+
const taken = theGate.expect(match, { take: [next.commandId] });
|
|
743
|
+
taken.catch(() => undefined);
|
|
744
|
+
await session.send(next.text, { id: next.requestId, ...(next.origin ? { origin: next.origin } : {}) });
|
|
745
|
+
await specNow?.hooks?.afterMessageSent?.();
|
|
746
|
+
await cliRecord?.message(next.text, next.origin);
|
|
747
|
+
return session.turnEnd();
|
|
748
|
+
};
|
|
539
749
|
async function run(claim) {
|
|
540
750
|
context = withAbortSignal(deps.signal, BACKGROUND_CONTEXT);
|
|
541
751
|
// Every row the runner read for this claim is with the loop once delivered resolves (at once without a runner's).
|
|
@@ -561,6 +771,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
561
771
|
// The spec's phases said before the run's root exists (AdapterRun.phase), written in the root's creating commit.
|
|
562
772
|
const phasesBeforeRoot = [];
|
|
563
773
|
let rootMade = false;
|
|
774
|
+
// A root made by a phase while the spec was built (below), before the spec's own lifecycle was known: its
|
|
775
|
+
// onConversation writes for the root are owed (RootWritesOwed, on the root), made once the spec is (after specOf).
|
|
776
|
+
let specKnown = false;
|
|
777
|
+
/** The root a phase is making, awaited before the owed writes are read. */
|
|
778
|
+
let rootMaking;
|
|
564
779
|
harness = await Harness.open(gate.journal, {
|
|
565
780
|
models: () => models, registry, settings: { restartLimit }, onReport: () => { },
|
|
566
781
|
// A tool host's onConversation, in each agent conversation's creating commit (the spec's, once it is known: the
|
|
@@ -572,6 +787,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
572
787
|
rootMade = true;
|
|
573
788
|
for (const data of phasesBeforeRoot.splice(0))
|
|
574
789
|
await tx.appendEntry(record.id, { kind: HOST_PHASE, data });
|
|
790
|
+
if (!specKnown) {
|
|
791
|
+
(await tx.doc(RootWritesOwed, record.id)).owed = true;
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
575
794
|
}
|
|
576
795
|
for (const write of specNow?.lifecycle?.onConversation ?? [])
|
|
577
796
|
await write(tx, Number(record.id));
|
|
@@ -615,18 +834,32 @@ function adapterLoop(specOf, options, deps) {
|
|
|
615
834
|
},
|
|
616
835
|
// Lazy, as main's process takes them (portModels(() => sessionPort?.(...))): a spec takes them at its build, and
|
|
617
836
|
// each request reads the session's port then, there once the session is open.
|
|
618
|
-
models: (label) => portModels(() => session?.port?.(label)),
|
|
837
|
+
models: (label, tier) => portModels(() => session?.port?.(label, tier), undefined, tier === undefined ? PORT_PROVIDER : tierProvider(tier)),
|
|
619
838
|
pause: async (refusal) => {
|
|
620
839
|
await pauseFor?.(refusal);
|
|
621
840
|
},
|
|
841
|
+
flush: () => deps.flush(),
|
|
622
842
|
};
|
|
623
|
-
// A phase of the host's
|
|
843
|
+
// A phase of the host's, on the run's timeline while its step runs. Said before the root exists (the claim's computer
|
|
844
|
+
// waiting on its image build, inside specOf), it makes the root then, the row in its creating commit (above), so a
|
|
845
|
+
// person sees the row during the wait, and a failed step keeps it (run()'s catch writes the end on that root). The
|
|
846
|
+
// session opens onto that root later and sets its agent there (pi.ts configures it on every open). Else at once.
|
|
624
847
|
const phasing = harness;
|
|
625
848
|
const phase = (summary) => {
|
|
626
849
|
const data = { summary, at: Date.now() };
|
|
627
850
|
void (async () => {
|
|
628
851
|
if (!rootMade && !(await phasing.conversation(ROOT_CONVERSATION_ID, context)) && !rootMade) {
|
|
629
852
|
phasesBeforeRoot.push(data);
|
|
853
|
+
rootMaking = phasing.root(context);
|
|
854
|
+
await rootMaking;
|
|
855
|
+
// The root was made by another write meanwhile (its creating commit took none of these): written now.
|
|
856
|
+
const left = phasesBeforeRoot.splice(0);
|
|
857
|
+
if (left.length === 0)
|
|
858
|
+
return;
|
|
859
|
+
await phasing.commit(async (tx) => {
|
|
860
|
+
for (const one of left)
|
|
861
|
+
await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data: one });
|
|
862
|
+
}, context);
|
|
630
863
|
return;
|
|
631
864
|
}
|
|
632
865
|
await phasing.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data }), context);
|
|
@@ -654,14 +887,39 @@ function adapterLoop(specOf, options, deps) {
|
|
|
654
887
|
if (error instanceof ClaimRefused)
|
|
655
888
|
return await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: error.message }, []);
|
|
656
889
|
// A person's stop while the spec was built (it waited on a harness's install): the run ends stopped, in the stop's
|
|
657
|
-
// words, its row taken; the work it waited on goes on for the next run.
|
|
890
|
+
// words, its row taken; the work it waited on goes on for the next run. A stop wins over the build's own failure.
|
|
658
891
|
if (stopReason?.kind === "command")
|
|
659
892
|
return await writeEnd(harness, await harness.root(context), gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId]);
|
|
893
|
+
// A spec that failed after a phase made the run's root (its computer's image build failed): the end goes on that
|
|
894
|
+
// root with why (said: cut of every secret the runner holds), as run()'s catch writes it once the session's root
|
|
895
|
+
// is known, so the timeline keeps the phase row and reads the failure after it.
|
|
896
|
+
await rootMaking?.catch(() => undefined);
|
|
897
|
+
if (rootMade && claim.from !== "parked" && !gate.sealed && !deps.signal.aborted) {
|
|
898
|
+
const ended = await writeEnd(harness, await harness.root(context), gate, { state: "failed", summary: said(error) }, []).catch(() => undefined);
|
|
899
|
+
if (ended)
|
|
900
|
+
return ended;
|
|
901
|
+
}
|
|
660
902
|
throw error;
|
|
661
903
|
}
|
|
662
904
|
mcp = spec.mcp;
|
|
663
905
|
specNow = spec;
|
|
906
|
+
specKnown = true;
|
|
907
|
+
// The spec's resources are the pass's from here: a claim lost in any write below still lets them go (closeSession).
|
|
664
908
|
releaseNow = spec.release;
|
|
909
|
+
// A root a phase made while the spec was built (on this claim or an earlier one lost before this point) took none
|
|
910
|
+
// of the spec's onConversation writes: they are made now, in a commit of their own, before anything of the
|
|
911
|
+
// session's. A root still being made is waited for first (made from here on, its creating commit takes them itself).
|
|
912
|
+
await rootMaking?.catch(() => undefined);
|
|
913
|
+
if (await harness.conversation(ROOT_CONVERSATION_ID, context)) {
|
|
914
|
+
await harness.commit(async (tx) => {
|
|
915
|
+
const owed = await tx.doc(RootWritesOwed, ROOT_CONVERSATION_ID);
|
|
916
|
+
if (!owed.owed)
|
|
917
|
+
return;
|
|
918
|
+
owed.owed = false;
|
|
919
|
+
for (const write of spec.lifecycle?.onConversation ?? [])
|
|
920
|
+
await write(tx, Number(ROOT_CONVERSATION_ID));
|
|
921
|
+
}, context);
|
|
922
|
+
}
|
|
665
923
|
// A mark of the run's commits through its own Harness, under its fence.
|
|
666
924
|
const opened_ = harness;
|
|
667
925
|
spec.harnessReady?.((change, ctx) => opened_.commit(change, ctx));
|
|
@@ -681,18 +939,92 @@ function adapterLoop(specOf, options, deps) {
|
|
|
681
939
|
let pausedAtRefusal = false;
|
|
682
940
|
/** A paid call's refusal that pauses the run (ledger.pause): the run's next request is refused in its words. */
|
|
683
941
|
let pendingPause;
|
|
942
|
+
/** How the run ends once its booked spend passed its cap (the kernel's overCapEnd, main's run end): every session's
|
|
943
|
+
* booked spend summed, as the cap reads it; the bound, its model session's requests' since the cost last fit, so a
|
|
944
|
+
* cache miss within that bound pauses the run at its next request instead. Undefined while it fits, with no cap, or
|
|
945
|
+
* with a spend unknown. */
|
|
946
|
+
const overCap = async () => {
|
|
947
|
+
// A run whose spec gives no cap (no runCap, or no cap's rule) has none to pass.
|
|
948
|
+
if (!spec.cap || !spec.runCap)
|
|
949
|
+
return undefined;
|
|
950
|
+
const cap = capNow();
|
|
951
|
+
if (cap === undefined)
|
|
952
|
+
return undefined;
|
|
953
|
+
let others = 0;
|
|
954
|
+
for (const key of await sessions.keys()) {
|
|
955
|
+
if (key === spec.session.key)
|
|
956
|
+
continue;
|
|
957
|
+
const spent = sessionSpendOf(await sessions.read(key)).spentUsd;
|
|
958
|
+
if (spent === null)
|
|
959
|
+
return undefined;
|
|
960
|
+
others += spent;
|
|
961
|
+
}
|
|
962
|
+
// Its model session read as the cap reads it (the kernel's overCapOf: a request cut by a crash at its hold plus its
|
|
963
|
+
// bound, and that bound kept, so a possible cache miss pauses the run, never fails it).
|
|
964
|
+
return overCapOf(await sessions.read(spec.session.key), others, cap);
|
|
965
|
+
};
|
|
966
|
+
/** A paid call's pending pause as it lands, at the model's next request: said again with the run's spend as it is
|
|
967
|
+
* now (every session's booked spend; the turn's calls have all ended, so nothing else is held), so the budget card
|
|
968
|
+
* counts what parallel calls settled since the refusal. Undefined when the call would now fit (one of them settled
|
|
969
|
+
* for less than it held): no pause, and the request goes to the cap as any does. A refusal with no call named on
|
|
970
|
+
* it, or a spend unknown, lands as it was. */
|
|
971
|
+
const landing = async (pending) => {
|
|
972
|
+
const step = pending.figures?.step;
|
|
973
|
+
const cap = capNow();
|
|
974
|
+
if (!step || cap === undefined)
|
|
975
|
+
return pending;
|
|
976
|
+
let spent = 0;
|
|
977
|
+
for (const key of await sessions.keys()) {
|
|
978
|
+
const spend = sessionSpendOf(await sessions.read(key)).spentUsd;
|
|
979
|
+
if (spend === null)
|
|
980
|
+
return pending;
|
|
981
|
+
spent += spend;
|
|
982
|
+
}
|
|
983
|
+
if (spent + step.holdUsd <= cap + FIT_TOLERANCE)
|
|
984
|
+
return undefined;
|
|
985
|
+
const { text, figures } = paidRefusal(cap, spent, 0, step.name, step.holdUsd, step.basis);
|
|
986
|
+
return { ...pending, refuse: text, figures };
|
|
987
|
+
};
|
|
684
988
|
const beforeRequest = async (request) => {
|
|
685
|
-
|
|
989
|
+
// A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
|
|
990
|
+
// whatever else would pause it (a paid call's refusal, pendingPause).
|
|
991
|
+
const over = await overCap();
|
|
992
|
+
if (!over && pendingPause) {
|
|
993
|
+
pendingPause = await landing(pendingPause);
|
|
994
|
+
// Fits now: dropped for good, on the root too, so a later claim never revives the old refusal.
|
|
995
|
+
if (pendingPause === undefined)
|
|
996
|
+
await keepPending(null);
|
|
997
|
+
}
|
|
998
|
+
const answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
|
|
686
999
|
if (answer && "refuse" in answer) {
|
|
687
1000
|
refused = answer;
|
|
688
1001
|
await pauseAt(answer);
|
|
689
1002
|
}
|
|
690
1003
|
return answer;
|
|
691
1004
|
};
|
|
1005
|
+
// A paid call's refusal is the call's result first: its pause is journaled at the model's next request (beforeRequest,
|
|
1006
|
+
// pendingPause), once the harness has stored that result, so the run never reads waiting on a raise before its
|
|
1007
|
+
// Timeline says why. The refusal is kept on the root at once (KINDS.pausePending, no run patch, nothing a person
|
|
1008
|
+
// reads), so a claim lost in between restores it (pendingPauseOf) and the next claim's request parks the run.
|
|
692
1009
|
pauseFor = async (refusal) => {
|
|
693
1010
|
pendingPause = refusal;
|
|
694
|
-
await
|
|
1011
|
+
await keepPending(refusal);
|
|
695
1012
|
};
|
|
1013
|
+
/** The pending pause kept on the root (KINDS.pausePending): a refusal, or null once it is dropped for good (the call
|
|
1014
|
+
* would now fit, or the turn ended on a question), which pendingPauseOf reads as none. */
|
|
1015
|
+
async function keepPending(refusal) {
|
|
1016
|
+
if (!harness || !gate || gate.sealed)
|
|
1017
|
+
return;
|
|
1018
|
+
const on = harness;
|
|
1019
|
+
try {
|
|
1020
|
+
const conversation = root ?? (await on.root(context));
|
|
1021
|
+
await on.commit(async (tx) => void (await tx.appendEntry(conversation.id, { kind: KINDS.pausePending, data: refusal })), context);
|
|
1022
|
+
}
|
|
1023
|
+
catch {
|
|
1024
|
+
// Not kept (the journal sealed: the claim lost or the run parking): a refusal still parks this claim's own
|
|
1025
|
+
// request; a drop leaves the next claim to judge the old refusal again when it lands (landing).
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
696
1028
|
async function pauseAt(answer) {
|
|
697
1029
|
{
|
|
698
1030
|
// A refusal a raise could fix (the cap's rule, parkOf) journals its pause, the run parked, before the refusal
|
|
@@ -731,23 +1063,79 @@ function adapterLoop(specOf, options, deps) {
|
|
|
731
1063
|
// provider may have billed it, so it is booked once, as cut, at its hold and bound, and told as any answered request
|
|
732
1064
|
// is, before this claim sends anything (the harness runner's bookCut, main's cut booking).
|
|
733
1065
|
await booking.bookCut();
|
|
734
|
-
|
|
1066
|
+
// A paid tool call an earlier claim admitted and never saw settled is booked the same way, cut, at its hold, its
|
|
1067
|
+
// charge unknown: it may have run and been charged before the claim was lost. Its session opens only for a paid call
|
|
1068
|
+
// of this claim, and a replay the gate refuses makes none, so it is opened here for the cut alone, never read as free.
|
|
1069
|
+
const toolsAtOpen = sessionSpendOf(await sessions.read(TOOL_SESSION));
|
|
1070
|
+
if (spec.runCap && toolsAtOpen.turns.some((turn) => !toolsAtOpen.answered.has(turn)))
|
|
1071
|
+
await paidOf();
|
|
1072
|
+
// The cap's wrap-up (tool-budget.ts wrappingUp): what every session of the run has taken as the cap counts it, its
|
|
1073
|
+
// spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
|
|
1074
|
+
// hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
|
|
1075
|
+
// flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
|
|
1076
|
+
const wrapUp = async () => {
|
|
1077
|
+
// A run whose spec gives no cap (no runCap) has none to wrap up at, as overCap reads it.
|
|
1078
|
+
if (!spec.runCap)
|
|
1079
|
+
return false;
|
|
1080
|
+
const capUsd = capNow();
|
|
1081
|
+
if (capUsd === undefined)
|
|
1082
|
+
return false;
|
|
1083
|
+
let taken = 0;
|
|
1084
|
+
for (const key of await sessions.keys()) {
|
|
1085
|
+
const read = sessionSpendOf(await sessions.read(key));
|
|
1086
|
+
const reserved = [...read.openHolds].reduce((sum, turn) => sum + (read.held.get(turn) ?? 0), 0);
|
|
1087
|
+
taken = taken === null || read.spentUsd === null ? null : taken + read.spentUsd + reserved;
|
|
1088
|
+
}
|
|
1089
|
+
return wrappingUp(capUsd, taken);
|
|
1090
|
+
};
|
|
1091
|
+
const gateOf = preIntentGate(spec, hooks, wrapUp);
|
|
735
1092
|
// A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
|
|
736
|
-
const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now) : undefined;
|
|
1093
|
+
const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now, spec.cwd) : undefined;
|
|
737
1094
|
cliRecord = record;
|
|
738
|
-
|
|
1095
|
+
// Each tool the session runs on the host, the host's own and any its adapter adds (SessionIO.hostTool: a CLI's
|
|
1096
|
+
// read_skill_file), the same way: a CLI's call on its record, so the run's Timeline shows it and its result.
|
|
1097
|
+
const hosted = (tool) => ({
|
|
739
1098
|
...tool,
|
|
740
1099
|
// The rule before a side effect, on the host-tool path every adapter's calls take: after the call's intent, a
|
|
741
1100
|
// flush unless the tool is replay-safe, the call, then the beforeResult point. A throw there is the kernel's own
|
|
742
1101
|
// fault: the journal is sealed before the harness's result commit, so the Session fails with the call before
|
|
743
1102
|
// its result, and the loop restarts it. A CLI's call reaches here only once the gate allowed it (its tool
|
|
744
|
-
// bridge asks first
|
|
1103
|
+
// bridge asks first; one refused is on the record from the gate, bridgeGate), so its record's start is written
|
|
1104
|
+
// here, before the flush and the call, and its end after.
|
|
745
1105
|
call: async (args, toolContext) => {
|
|
746
1106
|
// A call its CLI issues again under an id the record already ended (after the CLI's own resume) is answered
|
|
747
1107
|
// from that end, never run again.
|
|
748
1108
|
const ended = record?.endOf(toolContext.callId);
|
|
749
1109
|
if (ended)
|
|
750
1110
|
return endedAnswer(tool.name, ended);
|
|
1111
|
+
// A call run again after an earlier attempt (the harness's rerun of a replay-safe call after a crash: its
|
|
1112
|
+
// attempt above 0) never passed the gate before its intent this time: the gate is asked again here, so a deny
|
|
1113
|
+
// set since the first attempt refuses the rerun, in words saying the earlier attempt may have taken effect.
|
|
1114
|
+
if ((toolContext.attempt ?? 0) > 0 && spec.gate) {
|
|
1115
|
+
// By the name the gate before the intent asks it by: an MCP tool by its catalog name.
|
|
1116
|
+
const name = mcp?.catalogOf(tool.name) ?? tool.name;
|
|
1117
|
+
const asked = spec.gate.askedAs?.(name) ?? name;
|
|
1118
|
+
const now = await spec.gate({ callId: toolContext.callId, tool: name, args: (args ?? {}) }, { replayed: true });
|
|
1119
|
+
if (now === "deny")
|
|
1120
|
+
return { text: setToDenyText(asked, undefined, "server", "unknown"), isError: true };
|
|
1121
|
+
if (typeof now === "object")
|
|
1122
|
+
return { text: now.deny, isError: true };
|
|
1123
|
+
// Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
|
|
1124
|
+
// replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
|
|
1125
|
+
// the claim lets it go; a deny says the earlier attempt may have taken effect.
|
|
1126
|
+
if (now === "ask") {
|
|
1127
|
+
const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
|
|
1128
|
+
const answer = await answerOf(call, mcp?.priceOf(name) ?? spec.approvalPrice?.({ ...call, tool: name }) ?? null, asked);
|
|
1129
|
+
if (answer === "park")
|
|
1130
|
+
return await heldUntilAborted(toolContext.signal);
|
|
1131
|
+
if (!answer.approved)
|
|
1132
|
+
return { text: refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown"), isError: true };
|
|
1133
|
+
}
|
|
1134
|
+
// pi let this call start before it was asked here: a stop while the gate or a person was asked wins over the
|
|
1135
|
+
// permission that came after it, and the call is never started.
|
|
1136
|
+
if (stopAbort.signal.aborted || toolContext.signal?.aborted)
|
|
1137
|
+
return { text: STOPPED_WHILE_WAITING, isError: true };
|
|
1138
|
+
}
|
|
751
1139
|
if (record)
|
|
752
1140
|
await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe");
|
|
753
1141
|
try {
|
|
@@ -756,7 +1144,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
756
1144
|
flush: () => deps.flush(),
|
|
757
1145
|
// Its paid requests booked under this call, on the run's one ledger (paid-calls.ts bookedIn, Ledger.paid); one
|
|
758
1146
|
// refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
|
|
759
|
-
|
|
1147
|
+
// The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
|
|
1148
|
+
// loop wrapped it, and whether a person approved this call.
|
|
1149
|
+
route: () => bookedIn({ call: toolContext.callId, record: async () => { }, paid, pause: ledger.pause }, () => withHostCalls({ mcp: mcpHosted, approved: approvedCalls.get(toolContext.callId) }, () => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }))),
|
|
760
1150
|
beforeResult: async (answer) => {
|
|
761
1151
|
const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
|
|
762
1152
|
try {
|
|
@@ -769,8 +1159,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
769
1159
|
}
|
|
770
1160
|
},
|
|
771
1161
|
});
|
|
1162
|
+
// A call a stop cut answers whatever its tool said of the abort: it ends interrupted, never as its outcome.
|
|
772
1163
|
if (record)
|
|
773
|
-
await record.end(toolContext.callId, answer.isError ? "failed" : "done", answer.text);
|
|
1164
|
+
await record.end(toolContext.callId, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
|
|
774
1165
|
return answer;
|
|
775
1166
|
}
|
|
776
1167
|
catch (error) {
|
|
@@ -781,7 +1172,14 @@ function adapterLoop(specOf, options, deps) {
|
|
|
781
1172
|
throw error;
|
|
782
1173
|
}
|
|
783
1174
|
},
|
|
784
|
-
})
|
|
1175
|
+
});
|
|
1176
|
+
const tools = [...spec.session.tools, ...(mcp?.tools ?? [])].map(hosted);
|
|
1177
|
+
// An MCP tool of the run by its catalog name, as wrapped above: what a learned workflow's MCP node calls.
|
|
1178
|
+
mcpHosted = (catalog) => {
|
|
1179
|
+
const wire = mcp?.tools.find((one) => mcp?.catalogOf(one.name) === catalog);
|
|
1180
|
+
const host = wire && tools.find((one) => one.name === wire.name);
|
|
1181
|
+
return host && ((args, ctx) => host.call(args, ctx));
|
|
1182
|
+
};
|
|
785
1183
|
// The session's model port, counting what it admitted and has not booked yet (a stop's booking comes once the
|
|
786
1184
|
// session's proxy sees its upstream end, which can be after pi went idle).
|
|
787
1185
|
const port = booking.models;
|
|
@@ -824,15 +1222,51 @@ function adapterLoop(specOf, options, deps) {
|
|
|
824
1222
|
given.add(turn);
|
|
825
1223
|
return booking.usd;
|
|
826
1224
|
};
|
|
827
|
-
|
|
1225
|
+
// The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
|
|
1226
|
+
// start and its end, refused in the gate's words, go on the record here, as pi writes a refused call and its error
|
|
1227
|
+
// 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
|
|
1228
|
+
// about goes on the record first, its start marked parked (once per call id), as an MCP call parked at its door does,
|
|
1229
|
+
// and marked the bridge's: the bridge hands the CLI nothing while it waits, so no waiting result shows, as on pi. Its
|
|
1230
|
+
// row shows while it waits, before its approval; the claim that runs it once allowed writes its sent mark on that
|
|
1231
|
+
// one start (start()), and a stop withdraws it never sent (unsentParked). A start refused because another call of the
|
|
1232
|
+
// round parked the run first (the journal sealed) leaves this call held as that one is.
|
|
1233
|
+
const replaySafe = (name) => tools.find((one) => one.name === name)?.replay === "safe";
|
|
1234
|
+
const askingGate = record
|
|
1235
|
+
? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), true).catch((error) => {
|
|
1236
|
+
if (!gate?.sealed)
|
|
1237
|
+
throw error;
|
|
1238
|
+
}))
|
|
1239
|
+
: gateOf;
|
|
1240
|
+
const bridgeGate = record
|
|
1241
|
+
? async (call, hookContext) => {
|
|
1242
|
+
const answer = await askingGate(call, hookContext);
|
|
1243
|
+
if (answer !== "allow" && "deny" in answer)
|
|
1244
|
+
await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
|
|
1245
|
+
return answer;
|
|
1246
|
+
}
|
|
1247
|
+
: gateOf;
|
|
1248
|
+
const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: bridgeGate, hostTool: hosted, bookedCost };
|
|
828
1249
|
// The MCP tools: pi's own (host tools, through the gate above); for a harness with its own MCP client, the session's
|
|
829
1250
|
// MCP its adapter mounts on its proxy, each call asking the gate first (an ask parks the run, nothing sent).
|
|
830
1251
|
const mcpNames = new Set(mcp?.tools.map((tool) => tool.name));
|
|
831
1252
|
const ownClient = mcp !== undefined && spec.adapter.capabilities().mcpClient !== undefined;
|
|
832
1253
|
const sessionMcp = ownClient
|
|
833
1254
|
? mcp.session(new Map(tools.filter((tool) => mcpNames.has(tool.name)).map((tool) => [tool.name, tool])), async (call) => {
|
|
1255
|
+
// A call through the door is on the run's record before its gate answers (once per call id; the gate's park
|
|
1256
|
+
// seals the journal): its row, and an approval read beside it, show while it waits. A refused one ends there;
|
|
1257
|
+
// a parked one runs, or is refused, on the claim that resumes it (parkedFollowUp); an allowed one runs now.
|
|
1258
|
+
const wire = mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool);
|
|
1259
|
+
if (record)
|
|
1260
|
+
await record.park(call.callId, wire?.name ?? call.tool, call.args ?? {}, wire?.replay === "safe");
|
|
834
1261
|
const answer = await gateOf(call, context);
|
|
835
|
-
|
|
1262
|
+
if (answer === "allow")
|
|
1263
|
+
return undefined;
|
|
1264
|
+
if ("deny" in answer) {
|
|
1265
|
+
if (record)
|
|
1266
|
+
await record.end(call.callId, "refused", answer.deny);
|
|
1267
|
+
return { refused: answer.deny };
|
|
1268
|
+
}
|
|
1269
|
+
return { parked: true };
|
|
836
1270
|
})
|
|
837
1271
|
: undefined;
|
|
838
1272
|
session = await spec.adapter.open({ ...spec.session, tools: ownClient ? tools.filter((tool) => !mcpNames.has(tool.name)) : tools, ...(sessionMcp ? { mcp: sessionMcp } : {}) }, io);
|
|
@@ -847,12 +1281,19 @@ function adapterLoop(specOf, options, deps) {
|
|
|
847
1281
|
for (const entry of entries)
|
|
848
1282
|
await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
|
|
849
1283
|
}, context), now);
|
|
850
|
-
|
|
1284
|
+
// The run's journal so far: a take an earlier claim's computer left in force ends released here (computer-journal.ts).
|
|
1285
|
+
await computerNow.up(await entriesOf(gate.journal, root.id, context));
|
|
851
1286
|
}
|
|
852
|
-
// The cap a raise left the run at,
|
|
853
|
-
//
|
|
1287
|
+
// The cap a raise left the run at, before any request of this claim, through the one reader the run view and its
|
|
1288
|
+
// budget card read too (capNowOf: the newest raise entry, else the launch's cap): a claim that takes over a raised
|
|
1289
|
+
// run (a resume, another runner's, a restarted server's) holds it to the raise, never the launch's cap.
|
|
854
1290
|
if (spec.cap)
|
|
855
|
-
raisedCapUsd = (await
|
|
1291
|
+
raisedCapUsd = capNowOf(spec.cap.capUsd, await entriesOf(gate.journal, root.id, context)) ?? raisedCapUsd;
|
|
1292
|
+
// A paid call an earlier claim refused for room whose pause never landed (the claim lost between the call's stored
|
|
1293
|
+
// result and the model's next request): its pending pause, restored, so that request is refused in its words and
|
|
1294
|
+
// the run parks for the raise the call needs.
|
|
1295
|
+
if (spec.cap && pendingPause === undefined)
|
|
1296
|
+
pendingPause = pendingPauseOf(await entriesOf(gate.journal, root.id, context)) ?? pendingPause;
|
|
856
1297
|
// A run brought back from a park: the raises its claim has are taken together, once its delivery is done. So is a
|
|
857
1298
|
// run whose journal still holds an unanswered budget pause, whatever its row said at the claim: a resumed claim lost
|
|
858
1299
|
// before its raise entry landed leaves the run running, its pause unanswered and its raises untaken.
|
|
@@ -863,6 +1304,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
863
1304
|
// Taken over from a runner whose lease ran out mid-run: said on the run's timeline once, at this claim's first pass.
|
|
864
1305
|
if (restarts === 0 && claim.lost)
|
|
865
1306
|
await noteTakenOver(harness, root, claim.lost.runner);
|
|
1307
|
+
// What this claim laid of the run's learning seed, once per claim: the newest is what the run was given.
|
|
1308
|
+
if (restarts === 0 && spec.learningLaid) {
|
|
1309
|
+
const [journalOf, rootOf, laid] = [harness, root, spec.learningLaid];
|
|
1310
|
+
await journalOf.commit((tx) => tx.appendEntry(rootOf.id, { kind: KINDS.learningLaid, data: { skills: [...laid.skills], workflows: [...laid.workflows] } }), context);
|
|
1311
|
+
}
|
|
866
1312
|
// Reopened by a person's follow-up (runs.reopen): its journal holds an end and its session opens idle. Set before the
|
|
867
1313
|
// session is ready, so the follow-up's steer, handed over once it is, is sent as this claim's turn.
|
|
868
1314
|
if (restarts === 0 && session.state === "idle" && (await entriesOf(gate.journal, root.id, context)).some((entry) => entry.kind === KINDS.end))
|
|
@@ -893,7 +1339,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
893
1339
|
if (paused) {
|
|
894
1340
|
if (!resumes || raising.capUsd === undefined || !spec.cap?.followUpOf)
|
|
895
1341
|
return await parkAtCap(harness, root, gate, paused);
|
|
896
|
-
|
|
1342
|
+
// The server's words, shown as its row ("AgentRun: …"), never as the person's; under the id a raise's answer named.
|
|
1343
|
+
const followUp = spec.cap.followUpOf(raising.capUsd).text;
|
|
1344
|
+
const followUpId = raiseFollowUpId(raising.state?.lastRaise?.pause ?? "follow-up");
|
|
1345
|
+
await markServerFollowUp(harness, root, followUp, followUpId);
|
|
1346
|
+
await session.send(followUp, { id: followUpId });
|
|
897
1347
|
followedUp = true;
|
|
898
1348
|
}
|
|
899
1349
|
}
|
|
@@ -904,7 +1354,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
904
1354
|
// the run's, is the follow-up's, never the first input's.
|
|
905
1355
|
const state = await raiseStateOf();
|
|
906
1356
|
if (state.pause === undefined && state.lastRaise?.pause !== undefined) {
|
|
907
|
-
|
|
1357
|
+
const followUp = spec.cap.followUpOf(state.lastRaise.to).text;
|
|
1358
|
+
const followUpId = raiseFollowUpId(state.lastRaise.pause);
|
|
1359
|
+
await markServerFollowUp(harness, root, followUp, followUpId);
|
|
1360
|
+
await session.send(followUp, { id: followUpId });
|
|
908
1361
|
followedUp = true;
|
|
909
1362
|
}
|
|
910
1363
|
}
|
|
@@ -922,8 +1375,14 @@ function adapterLoop(specOf, options, deps) {
|
|
|
922
1375
|
return now === "deny" ? setToDenyText(call.tool) : typeof now === "object" ? now.deny : undefined;
|
|
923
1376
|
},
|
|
924
1377
|
run: (call) => wrapped.get(mcp.tools.find((tool) => mcp.catalogOf(tool.name) === call.tool).name).call(call.args, { callId: call.callId, signal: deps.signal }),
|
|
1378
|
+
// A parked call refused ends on the run's record (its start was written at its park), in the refusal's words.
|
|
1379
|
+
refused: async (call, text) => cliRecord?.end(call.callId, "refused", text),
|
|
925
1380
|
});
|
|
926
1381
|
if (follow === "park") {
|
|
1382
|
+
// A person's stop (or cancel) waiting here is taken: the run ends stopped, its waiting calls withdrawn in the
|
|
1383
|
+
// end's commit. Released parked instead, its untaken stop would have it claimed again at once, and again.
|
|
1384
|
+
if (stopReason?.kind === "command")
|
|
1385
|
+
return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason.cancel) }, [stopReason.commandId], await cutRows(claim, spec, "stopped"));
|
|
927
1386
|
gate.seal(new Parked());
|
|
928
1387
|
return { state: "parked" };
|
|
929
1388
|
}
|
|
@@ -1019,8 +1478,14 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1019
1478
|
await harness.waitForIdle(context);
|
|
1020
1479
|
const settledEntries = await entriesOf(gate.journal, root.id, context);
|
|
1021
1480
|
const cutOff = restartLimited(settledEntries);
|
|
1481
|
+
// A turn whose booked spend passed the run's cap ends the run failed in the cap's words (overCap), its crossing
|
|
1482
|
+
// answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
|
|
1483
|
+
await bookingsSettled();
|
|
1484
|
+
const over = cutOff ? undefined : await overCap();
|
|
1022
1485
|
if (cutOff)
|
|
1023
1486
|
data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
|
|
1487
|
+
else if (over)
|
|
1488
|
+
data = { state: "failed", summary: over };
|
|
1024
1489
|
else if (outcome.status !== "completed" && refused) {
|
|
1025
1490
|
// 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
|
|
1026
1491
|
// raise could fix parks the run on a raise; one no raise could fix (or a check with no cap) fails it, in the
|
|
@@ -1053,6 +1518,12 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1053
1518
|
// its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
|
|
1054
1519
|
// its next turn, on the same session. With nothing open, it parks (parkOnAsk).
|
|
1055
1520
|
const callId = endedOnTurnEndingTool(settledEntries);
|
|
1521
|
+
// Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
|
|
1522
|
+
// person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
|
|
1523
|
+
if (pendingPause) {
|
|
1524
|
+
pendingPause = undefined;
|
|
1525
|
+
await keepPending(null);
|
|
1526
|
+
}
|
|
1056
1527
|
const waited = await waitInClaim(harness, callId);
|
|
1057
1528
|
if (waited) {
|
|
1058
1529
|
turn = waited.next;
|
|
@@ -1065,12 +1536,57 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1065
1536
|
// An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
|
|
1066
1537
|
// the direct loop's rule: the words are loop-contract's cutAtLimit).
|
|
1067
1538
|
const cut = cutLast(settledEntries);
|
|
1539
|
+
// The rows the runner has not handed on yet (its next poll may be half a second away): handed on now, so a
|
|
1540
|
+
// message sent while the turn worked is one of the run's turns below, never refused by its end. Bounded: a
|
|
1541
|
+
// command that waits on this loop cannot hold its end.
|
|
1542
|
+
if (!cut && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow) {
|
|
1543
|
+
let bound;
|
|
1544
|
+
await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
|
|
1545
|
+
clearTimeout(bound);
|
|
1546
|
+
// A stop or cancel among them: the run ends stopped in its words, its row taken, never completed. Its turn
|
|
1547
|
+
// has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
|
|
1548
|
+
const cutBy = stopReason;
|
|
1549
|
+
if (cutBy?.kind === "command")
|
|
1550
|
+
return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(cutBy.cancel) }, [cutBy.commandId], await cutRows(claim, spec, "stopped"));
|
|
1551
|
+
if (cutBy || deps.signal.aborted)
|
|
1552
|
+
return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
|
|
1553
|
+
}
|
|
1554
|
+
// A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
|
|
1555
|
+
const next = cut ? undefined : afterTurn.shift();
|
|
1556
|
+
if (next) {
|
|
1557
|
+
turn = sendAfterTurn(gate, next);
|
|
1558
|
+
continue;
|
|
1559
|
+
}
|
|
1560
|
+
// A message steered into the turn (steeredIn): its answer, in that turn or a run of its own after it, before
|
|
1561
|
+
// the run's end. One already answered settles at once.
|
|
1562
|
+
const steered = cut ? undefined : steeredIn.shift();
|
|
1563
|
+
if (steered !== undefined) {
|
|
1564
|
+
turn = turnOfRequest(harness, root, steered);
|
|
1565
|
+
continue;
|
|
1566
|
+
}
|
|
1068
1567
|
data = cut ? { state: "failed", summary: cut } : { state: "ended" };
|
|
1069
1568
|
}
|
|
1070
1569
|
break;
|
|
1071
1570
|
}
|
|
1571
|
+
// No turn is sent after this one: a message from here on waits for the run's end (steer).
|
|
1572
|
+
turnsOver = true;
|
|
1072
1573
|
if (parkOn !== undefined)
|
|
1073
1574
|
return await parkOnAsk(harness, root, gate, parkOn);
|
|
1575
|
+
// A person who holds the run's desktop or phone keeps it (#2134): the run's end, and its computer's release after
|
|
1576
|
+
// it, wait for the hand-back or the hold's idle bound, the Timeline saying why. A stop ends the run stopped at
|
|
1577
|
+
// once, and a lost claim or a closing runner leaves it for the next claim, as during the end-of-run step.
|
|
1578
|
+
if (computerNow) {
|
|
1579
|
+
const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
|
|
1580
|
+
// Until the run returns: a steer after the hand-back would start a turn its end then cuts, too.
|
|
1581
|
+
handingBack = true;
|
|
1582
|
+
await computerNow.heldAtEnd(Promise.race([stopping, aborted, harness.closed]));
|
|
1583
|
+
// Set by stop() during the wait: read past the narrowing TypeScript did before it.
|
|
1584
|
+
const cut = stopReason;
|
|
1585
|
+
if (cut?.kind === "command")
|
|
1586
|
+
return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(cut.cancel) }, [cut.commandId], await cutRows(claim, spec, "stopped"));
|
|
1587
|
+
if (cut || deps.signal.aborted)
|
|
1588
|
+
return await interrupted(cut?.kind ?? "its claim's signal aborted");
|
|
1589
|
+
}
|
|
1074
1590
|
// The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
|
|
1075
1591
|
// writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
|
|
1076
1592
|
const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
|
|
@@ -1078,6 +1594,15 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1078
1594
|
return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(stopReason?.kind === "command" ? stopReason.cancel : undefined) }, [step.commandId], await cutRows(claim, spec, "stopped-looking"));
|
|
1079
1595
|
if (step.kind === "interrupted")
|
|
1080
1596
|
return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
|
|
1597
|
+
// The end-of-run turn is one more paid answer: one that passed the cap ends the run in the cap's words (overCap,
|
|
1598
|
+
// read again once its booking settled), as a job's answer that passed it does, never completed. An end already
|
|
1599
|
+
// failed keeps its own words.
|
|
1600
|
+
if (data.state !== "failed") {
|
|
1601
|
+
await bookingsSettled();
|
|
1602
|
+
const overAtEnd = await overCap();
|
|
1603
|
+
if (overAtEnd)
|
|
1604
|
+
data = { state: "failed", summary: overAtEnd };
|
|
1605
|
+
}
|
|
1081
1606
|
return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
|
|
1082
1607
|
}
|
|
1083
1608
|
}
|
|
@@ -1102,6 +1627,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1102
1627
|
held?.detach();
|
|
1103
1628
|
computerNow?.detach();
|
|
1104
1629
|
computerNow = undefined;
|
|
1630
|
+
handingBack = false;
|
|
1105
1631
|
deps.live?.(() => undefined);
|
|
1106
1632
|
// A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
|
|
1107
1633
|
// A restart within the claim is no release. What it writes after a lost claim is refused by the fence, as any write.
|
|
@@ -1109,8 +1635,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1109
1635
|
await closeSession();
|
|
1110
1636
|
}
|
|
1111
1637
|
}
|
|
1112
|
-
/** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
|
|
1113
|
-
|
|
1638
|
+
/** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
|
|
1639
|
+
* `wrapUp`: whether the run has taken its share of the cap, so every call the model makes is refused in its fixed words.
|
|
1640
|
+
* `beforeAsk`: what goes on the record of a call the gate asks about, before its ask is written or read (a CLI's call
|
|
1641
|
+
* through its tool bridge: its start, marked parked, so its row shows while it waits and reads before its approval). */
|
|
1642
|
+
function preIntentGate(spec, hooks, wrapUp, beforeAsk) {
|
|
1114
1643
|
return async (call, _hookContext) => {
|
|
1115
1644
|
// An MCP tool is asked about by its catalog name (`mcp:<server>/<tool>`), as its settings and its card name it.
|
|
1116
1645
|
const tool = mcp?.catalogOf(call.tool) ?? call.tool;
|
|
@@ -1119,7 +1648,18 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1119
1648
|
if (reflecting && WRITES.has(call.tool) && underLearning(spec.workRoot, call.args))
|
|
1120
1649
|
return { deny: REFLECT_NOTE_ONLY };
|
|
1121
1650
|
await hooks.beforeIntent(kernelCall);
|
|
1122
|
-
|
|
1651
|
+
// The tool-call budget, before the gate's settings: a call past it is refused in its fixed words, never parked or
|
|
1652
|
+
// asked about.
|
|
1653
|
+
const budget = spec.gate?.toolCalls;
|
|
1654
|
+
if (budget !== undefined && call.callsBefore && (await call.callsBefore(budget)) >= budget)
|
|
1655
|
+
return { deny: TOOL_BUDGET_TEXT };
|
|
1656
|
+
// 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
|
|
1657
|
+
// in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
|
|
1658
|
+
if (call.nested !== true && (await wrapUp()))
|
|
1659
|
+
return { deny: WRAP_UP_TEXT };
|
|
1660
|
+
// A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
|
|
1661
|
+
const replayed = call.replayed === true;
|
|
1662
|
+
const decision = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
|
|
1123
1663
|
if (typeof decision === "object")
|
|
1124
1664
|
return { deny: decision.deny };
|
|
1125
1665
|
// Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
|
|
@@ -1127,13 +1667,30 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1127
1667
|
const asked = spec.gate?.askedAs?.(tool) ?? tool;
|
|
1128
1668
|
// Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
|
|
1129
1669
|
if (decision === "deny")
|
|
1130
|
-
return { deny: setToDenyText(asked) };
|
|
1670
|
+
return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
|
|
1131
1671
|
if (decision === "allow")
|
|
1132
1672
|
return "allow";
|
|
1133
|
-
|
|
1673
|
+
// The card shows the call's input, and beside it what the gate says the call would do that the person approves too
|
|
1674
|
+
// (a learned workflow's MCP calls set to ask: askedFor).
|
|
1675
|
+
const shown = await spec.gate?.askedFor?.(tool, call.args);
|
|
1676
|
+
// Shown first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES) still names them whatever the input's size.
|
|
1677
|
+
// The gate's own fields win over any of the same name in the call's input, which the model wrote.
|
|
1678
|
+
const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
|
|
1679
|
+
// The call on the record before its ask (beforeAsk), with the input its model gave it.
|
|
1680
|
+
await beforeAsk?.(call);
|
|
1681
|
+
const answer = await answerOf({ ...call, tool, args }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
|
|
1134
1682
|
if (answer === "park")
|
|
1135
1683
|
return { park: true };
|
|
1136
|
-
|
|
1684
|
+
// A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
|
|
1685
|
+
// approved with it (host-calls.ts), as far as the card they approved named it: its ask as journaled, the card they
|
|
1686
|
+
// saw, never one built again now.
|
|
1687
|
+
if (answer.approved) {
|
|
1688
|
+
const seen = askedArgs.get(call.callId);
|
|
1689
|
+
approvedCalls.set(call.callId, seen && typeof seen === "object" && !Array.isArray(seen) ? seen : {});
|
|
1690
|
+
}
|
|
1691
|
+
if (answer.approved)
|
|
1692
|
+
return "allow";
|
|
1693
|
+
return { deny: replayed ? refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown") : deniedText(asked, answer.note) };
|
|
1137
1694
|
};
|
|
1138
1695
|
}
|
|
1139
1696
|
/** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
|
|
@@ -1142,10 +1699,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1142
1699
|
async function answerOf(call, price, asked = call.tool) {
|
|
1143
1700
|
const conversation = await harness.root(context);
|
|
1144
1701
|
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
1702
|
+
const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
|
|
1703
|
+
// The card the person answers is the ask as first journaled: kept for the caller, which scopes an approval to it.
|
|
1704
|
+
if (first)
|
|
1705
|
+
askedArgs.set(call.callId, first.args);
|
|
1145
1706
|
const known = findData(entries, KINDS.answer, (data) => data.callId === call.callId);
|
|
1146
1707
|
if (known)
|
|
1147
1708
|
return known;
|
|
1148
|
-
const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
|
|
1149
1709
|
// The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
|
|
1150
1710
|
// run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
|
|
1151
1711
|
const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price };
|
|
@@ -1195,17 +1755,38 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1195
1755
|
await new Promise((resolve) => (wakeInbox = resolve));
|
|
1196
1756
|
}
|
|
1197
1757
|
}
|
|
1198
|
-
/**
|
|
1758
|
+
/** A call parked from inside its run (a rerun asked again): held unrun until its signal aborts (the pass ends on the
|
|
1759
|
+
* park), then thrown, so nothing of it is answered in this pass. */
|
|
1760
|
+
function heldUntilAborted(signal) {
|
|
1761
|
+
return new Promise((_, reject) => {
|
|
1762
|
+
if (signal.aborted)
|
|
1763
|
+
return reject(new Error("parked"));
|
|
1764
|
+
signal.addEventListener("abort", () => reject(new Error("parked")), { once: true });
|
|
1765
|
+
});
|
|
1766
|
+
}
|
|
1767
|
+
/** Whether a call of this run waits for the answer `approval` names: asked, and not answered yet. `later` when this
|
|
1768
|
+
* claim can no longer say: its Harness never opened, or its pass is parking, ending or stopping (the journal sealed,
|
|
1769
|
+
* closeSession closing the Harness behind the seal). The row is left untaken and the run's next claim checks it, as a
|
|
1770
|
+
* steer that comes as the run parks is (#2292: the read went through the closed Harness and threw). */
|
|
1199
1771
|
async function waitsFor(approval) {
|
|
1200
1772
|
if (approval === undefined)
|
|
1201
1773
|
return false;
|
|
1202
1774
|
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1775
|
+
const [theGate, theHarness] = [gate, harness];
|
|
1776
|
+
if (!theGate || !theHarness || theGate.sealed)
|
|
1777
|
+
return "later";
|
|
1778
|
+
try {
|
|
1779
|
+
const conversation = await theHarness.root(context);
|
|
1780
|
+
const entries = await entriesOf(theGate.journal, conversation.id, context);
|
|
1781
|
+
const asked = findData(entries, KINDS.ask, (data) => data.callId === approval) !== undefined;
|
|
1782
|
+
return asked && findData(entries, KINDS.answer, (data) => data.callId === approval) === undefined;
|
|
1783
|
+
}
|
|
1784
|
+
catch (error) {
|
|
1785
|
+
// Sealed while it read: closeSession seals, then closes the Harness the read went through.
|
|
1786
|
+
if (theGate.sealed)
|
|
1787
|
+
return "later";
|
|
1788
|
+
throw error;
|
|
1789
|
+
}
|
|
1209
1790
|
}
|
|
1210
1791
|
async function reportHeld(session, conversationId) {
|
|
1211
1792
|
held?.detach();
|
|
@@ -1468,7 +2049,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1468
2049
|
// How this claim's turn ended; a turn answered before reads as its submission says.
|
|
1469
2050
|
let turnStatus = "completed";
|
|
1470
2051
|
if (!known) {
|
|
1471
|
-
theRecord?.answering();
|
|
2052
|
+
await theRecord?.answering(requestId, prompt);
|
|
1472
2053
|
await theSession.send(prompt, { id: requestId });
|
|
1473
2054
|
const turn = theSession.turnEnd();
|
|
1474
2055
|
const timeout = new Promise((resolve) => (timer = setTimeout(() => resolve("timeout"), deadlineMs)));
|
|
@@ -1587,7 +2168,12 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1587
2168
|
// A person's stop or cancel withdraws every call still waiting for its answer, in the end's own commit: the approval
|
|
1588
2169
|
// card reads answered (withdrawn), never waiting for good on a final run.
|
|
1589
2170
|
const byPerson = data.state === "stopped" || stopReason?.kind === "command";
|
|
1590
|
-
|
|
2171
|
+
// A cancel's calls read cancelled with their run; a stop's, withdrawn.
|
|
2172
|
+
const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow(), stopReason?.kind === "command" && stopReason.cancel ? "canceled" : "withdrawn") : [];
|
|
2173
|
+
// A CLI's call on the record from its gate and never sent (parked, or its runner gone before its send): its record ends
|
|
2174
|
+
// with the run's, in the same commit, saying it was not run (never interrupted: it never left).
|
|
2175
|
+
const recordEnds = cliRecord?.unsentParked() ?? [];
|
|
2176
|
+
const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
|
|
1591
2177
|
const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
|
|
1592
2178
|
// A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
|
|
1593
2179
|
ended.catch(() => undefined);
|
|
@@ -1595,6 +2181,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1595
2181
|
await on.commit(async (tx) => {
|
|
1596
2182
|
for (const answer of withdrawn)
|
|
1597
2183
|
await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
|
|
2184
|
+
for (const callId of recordEnds)
|
|
2185
|
+
await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
|
|
1598
2186
|
if (failedWith !== undefined)
|
|
1599
2187
|
await tx.appendEntry(conversation.id, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", failedWith, now())] });
|
|
1600
2188
|
return tx.appendEntry(conversation.id, { kind: KINDS.end, data: data });
|
|
@@ -1606,6 +2194,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1606
2194
|
throw error;
|
|
1607
2195
|
}
|
|
1608
2196
|
await ended;
|
|
2197
|
+
for (const callId of recordEnds)
|
|
2198
|
+
cliRecord?.noteEnd(callId, "refused", notRun);
|
|
1609
2199
|
return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
|
|
1610
2200
|
}
|
|
1611
2201
|
return {
|
|
@@ -1624,7 +2214,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1624
2214
|
// An answer names its approval: the asked call's id. One that names no call waiting for its answer (an old
|
|
1625
2215
|
// approval, another run's) is refused, never applied to the call that waits now.
|
|
1626
2216
|
const approval = approvalOf(command);
|
|
1627
|
-
|
|
2217
|
+
const waits = await waitsFor(approval);
|
|
2218
|
+
if (waits === "later")
|
|
2219
|
+
return { later: "the run is parking or ending: the answer waits for its next claim" };
|
|
2220
|
+
if (!waits) {
|
|
1628
2221
|
refusals += 1;
|
|
1629
2222
|
wakeInbox();
|
|
1630
2223
|
return { refused: `no call of this run waits for approval ${JSON.stringify(approval ?? "")}` };
|
|
@@ -1649,6 +2242,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1649
2242
|
if (reason.kind !== "command")
|
|
1650
2243
|
gate?.seal(new Interrupted(reason.kind));
|
|
1651
2244
|
stopped();
|
|
2245
|
+
stopAbort.abort(new Interrupted(reason.kind));
|
|
1652
2246
|
wakeInbox();
|
|
1653
2247
|
await finished?.catch(() => undefined);
|
|
1654
2248
|
},
|