@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +418 -0
- package/README.md +325 -124
- package/dist/adapters.d.ts +4 -1
- package/dist/adapters.js +4 -2
- package/dist/agent-rows.d.ts +0 -2
- package/dist/agents-store.d.ts +5 -5
- package/dist/agents-store.js +14 -14
- package/dist/bash-read-only.js +2 -1
- package/dist/cap-short.d.ts +12 -0
- package/dist/cap-short.js +60 -0
- package/dist/cap.d.ts +3 -10
- package/dist/cap.js +2 -5
- package/dist/catalog.d.ts +0 -5
- package/dist/catalog.js +1 -5
- package/dist/chatgpt-plan.d.ts +163 -0
- package/dist/chatgpt-plan.js +549 -0
- package/dist/cli.js +26 -6
- package/dist/composio-preset.d.ts +8 -0
- package/dist/composio-preset.js +8 -7
- package/dist/composio-triggers.d.ts +113 -0
- package/dist/composio-triggers.js +411 -0
- package/dist/computer-calls.js +2 -2
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +7 -3
- package/dist/computer-live.d.ts +7 -2
- package/dist/computer-live.js +9 -5
- package/dist/computer-routes.d.ts +2 -2
- package/dist/computer-routes.js +2 -2
- package/dist/computer-setting.d.ts +3 -3
- package/dist/computer-setting.js +5 -5
- package/dist/computer-view.d.ts +15 -0
- package/dist/computer-view.js +16 -2
- package/dist/computer-viewer.js +14 -1
- package/dist/computers.d.ts +5 -2
- package/dist/computers.js +9 -5
- package/dist/console/assets/index-BNhZs-jp.css +1 -0
- package/dist/console/assets/index-BQv5aOGB.js +700 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.js +3 -3
- package/dist/decision-cap.d.ts +2 -5
- package/dist/decision-cap.js +3 -6
- package/dist/decision-rows.js +11 -11
- package/dist/email/account.d.ts +84 -0
- package/dist/email/account.js +159 -0
- package/dist/email/answer.d.ts +10 -0
- package/dist/email/answer.js +182 -0
- package/dist/email/email-faux.d.ts +95 -0
- package/dist/email/email-faux.js +849 -0
- package/dist/email/labels.d.ts +1 -0
- package/dist/email/labels.js +84 -0
- package/dist/email/mail.d.ts +186 -0
- package/dist/email/mail.js +380 -0
- package/dist/email/names.d.ts +20 -0
- package/dist/email/names.js +40 -0
- package/dist/email/routes.d.ts +9 -0
- package/dist/email/routes.js +50 -0
- package/dist/email/tools.d.ts +20 -0
- package/dist/email/tools.js +517 -0
- package/dist/environment.d.ts +17 -2
- package/dist/environment.js +36 -8
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +12 -0
- package/dist/eval-mailbox.d.ts +103 -0
- package/dist/eval-mailbox.js +236 -0
- package/dist/graph-view.d.ts +9 -2
- package/dist/graph-view.js +6 -2
- package/dist/harness-install.d.ts +28 -2
- package/dist/harness-install.js +147 -59
- package/dist/harness-opencode/adapter.js +2 -26
- package/dist/harness-opencode/facts.js +5 -2
- package/dist/harness-opencode/host/policy.d.ts +2 -0
- package/dist/harness-opencode/host/policy.js +10 -5
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/versions.d.ts +6 -0
- package/dist/harness-opencode/versions.js +6 -0
- package/dist/harness-table.js +8 -5
- package/dist/harness.d.ts +12 -0
- package/dist/harness.js +15 -3
- package/dist/hosted-search.d.ts +3 -1
- package/dist/hosted-search.js +51 -11
- package/dist/import-sources.d.ts +1 -1
- package/dist/import-sources.js +3 -3
- package/dist/import.d.ts +21 -0
- package/dist/import.js +186 -1
- package/dist/key-check.d.ts +0 -2
- package/dist/key-check.js +3 -4
- package/dist/key-refusal.d.ts +8 -2
- package/dist/key-refusal.js +16 -13
- package/dist/learn/check.d.ts +18 -3
- package/dist/learn/check.js +328 -3
- package/dist/learn/compile.d.ts +9 -2
- package/dist/learn/compile.js +52 -16
- package/dist/learn/grade.d.ts +4 -0
- package/dist/learn/grade.js +4 -1
- package/dist/learn/promote.d.ts +106 -51
- package/dist/learn/promote.js +82 -189
- package/dist/learn/refit.d.ts +21 -12
- package/dist/learn/refit.js +51 -23
- package/dist/learn/replay-calls.js +1 -1
- package/dist/learn/skills.d.ts +2 -7
- package/dist/learn/skills.js +28 -14
- package/dist/learned-nodes.d.ts +15 -7
- package/dist/learned-nodes.js +29 -5
- package/dist/learned-workflow.d.ts +41 -31
- package/dist/learned-workflow.js +122 -63
- package/dist/learning-batch.js +3 -3
- package/dist/learning-cost.d.ts +26 -8
- package/dist/learning-cost.js +17 -7
- package/dist/learning-routes.d.ts +2 -4
- package/dist/learning-routes.js +20 -3
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +4 -1
- package/dist/learning.d.ts +5 -5
- package/dist/link-check.d.ts +27 -0
- package/dist/link-check.js +164 -0
- package/dist/local-models.d.ts +33 -2
- package/dist/local-models.js +43 -5
- package/dist/mcp-pin-first.js +6 -0
- package/dist/mcp-secret-writes.js +3 -0
- package/dist/mcp-servers-store.d.ts +25 -16
- package/dist/mcp-servers-store.js +23 -3
- package/dist/model-form.d.ts +11 -0
- package/dist/model-form.js +17 -1
- package/dist/model.d.ts +26 -6
- package/dist/model.js +126 -18
- package/dist/monid.d.ts +26 -31
- package/dist/monid.js +84 -79
- package/dist/native/binding.d.ts +13 -0
- package/dist/native/binding.js +57 -0
- package/dist/native/cli.d.ts +2 -0
- package/dist/native/cli.js +48 -0
- package/dist/native/connection.d.ts +8 -0
- package/dist/native/connection.js +94 -0
- package/dist/native/context.d.ts +6 -0
- package/dist/native/context.js +22 -0
- package/dist/native/discovery.d.ts +27 -0
- package/dist/native/discovery.js +404 -0
- package/dist/native/environment.d.ts +4 -0
- package/dist/native/environment.js +18 -0
- package/dist/native/history.d.ts +20 -0
- package/dist/native/history.js +147 -0
- package/dist/native/instructions.d.ts +21 -0
- package/dist/native/instructions.js +173 -0
- package/dist/native/remote-worker-bridge.d.ts +3 -0
- package/dist/native/remote-worker-bridge.js +278 -0
- package/dist/native/remote.d.ts +187 -0
- package/dist/native/remote.js +492 -0
- package/dist/native/runtime.d.ts +17 -0
- package/dist/native/runtime.js +316 -0
- package/dist/native/runtimes.d.ts +66 -0
- package/dist/native/runtimes.js +41 -0
- package/dist/native/schema.d.ts +46 -0
- package/dist/native/schema.js +41 -0
- package/dist/native/types.d.ts +87 -0
- package/dist/native/types.js +1 -0
- package/dist/observation/http.d.ts +4 -0
- package/dist/observation/http.js +140 -0
- package/dist/observation/observer.d.ts +301 -0
- package/dist/observation/observer.js +919 -0
- package/dist/observation/schema.d.ts +52 -0
- package/dist/observation/schema.js +154 -0
- package/dist/openapi.d.ts +1 -0
- package/dist/openapi.js +394 -85
- package/dist/paid-calls.d.ts +8 -3
- package/dist/paid-calls.js +6 -2
- package/dist/place-offers.d.ts +4 -8
- package/dist/place-offers.js +4 -9
- package/dist/port-models.d.ts +7 -2
- package/dist/port-models.js +5 -2
- package/dist/print.d.ts +4 -2
- package/dist/print.js +4 -3
- package/dist/propose.d.ts +1 -2
- package/dist/propose.js +10 -1
- package/dist/provider.d.ts +5 -1
- package/dist/provider.js +8 -0
- package/dist/push-handler.d.ts +3 -2
- package/dist/push-handler.js +20 -6
- package/dist/refusal-words.d.ts +11 -0
- package/dist/refusal-words.js +13 -2
- package/dist/run-launch.d.ts +10 -1
- package/dist/run-launch.js +11 -4
- package/dist/run-learning-served.d.ts +75 -2
- package/dist/run-manifest.d.ts +3 -0
- package/dist/run-manifest.js +13 -1
- package/dist/run-reads-over-store.d.ts +3 -3
- package/dist/run-reads-over-store.js +13 -10
- package/dist/run-timeline-served.d.ts +3 -2
- package/dist/run-timeline-served.js +8 -9
- package/dist/run-view.d.ts +42 -35
- package/dist/run-view.js +79 -44
- package/dist/runnable.d.ts +13 -5
- package/dist/runnable.js +69 -60
- package/dist/runner/adapter-loop.d.ts +42 -11
- package/dist/runner/adapter-loop.js +651 -247
- package/dist/runner/adapter-run-spec.d.ts +37 -12
- package/dist/runner/adapter-run-spec.js +139 -106
- package/dist/runner/adapters/pi.d.ts +24 -0
- package/dist/runner/adapters/pi.js +59 -9
- package/dist/runner/beside.d.ts +3 -1
- package/dist/runner/beside.js +24 -8
- package/dist/runner/claim-secrets.d.ts +3 -1
- package/dist/runner/claim-secrets.js +28 -4
- package/dist/runner/cli-run-spec.d.ts +30 -0
- package/dist/runner/cli-run-spec.js +94 -50
- package/dist/runner/computer-channel.d.ts +5 -2
- package/dist/runner/computer-channel.js +3 -2
- package/dist/runner/computer-journal.d.ts +6 -0
- package/dist/runner/computer-journal.js +8 -10
- package/dist/runner/conformance/harness.js +6 -3
- package/dist/runner/end-of-run.d.ts +2 -0
- package/dist/runner/end-of-run.js +3 -1
- package/dist/runner/feedback-round.d.ts +40 -13
- package/dist/runner/feedback-round.js +64 -16
- package/dist/runner/harness-loops.js +17 -0
- package/dist/runner/journal-kinds.d.ts +37 -13
- package/dist/runner/journal-kinds.js +9 -5
- package/dist/runner/learning-dispatch.d.ts +3 -2
- package/dist/runner/learning-dispatch.js +6 -6
- package/dist/runner/learning-end.d.ts +4 -0
- package/dist/runner/learning-end.js +64 -36
- package/dist/runner/learning-factory.d.ts +3 -0
- package/dist/runner/learning-factory.js +8 -2
- package/dist/runner/learning-loop.d.ts +2 -0
- package/dist/runner/learning-loop.js +19 -4
- package/dist/runner/loop.d.ts +18 -0
- package/dist/runner/loop.js +34 -0
- package/dist/runner/main.d.ts +6 -1
- package/dist/runner/main.js +26 -4
- package/dist/runner/mcp-run.d.ts +4 -1
- package/dist/runner/mcp-run.js +11 -5
- package/dist/runner/meta-tools.d.ts +10 -3
- package/dist/runner/meta-tools.js +112 -36
- package/dist/runner/metrics.d.ts +80 -21
- package/dist/runner/metrics.js +114 -39
- package/dist/runner/model-route.d.ts +12 -3
- package/dist/runner/model-route.js +139 -18
- package/dist/runner/monid-run.d.ts +8 -6
- package/dist/runner/monid-run.js +117 -43
- package/dist/runner/native-loop.d.ts +11 -0
- package/dist/runner/native-loop.js +438 -0
- package/dist/runner/promotion.d.ts +74 -8
- package/dist/runner/promotion.js +365 -124
- package/dist/runner/redact.js +3 -0
- package/dist/runner/reflect-hook.js +9 -0
- package/dist/runner/runner.d.ts +7 -1
- package/dist/runner/runner.js +8 -4
- package/dist/runner/sdk-loop.d.ts +7 -0
- package/dist/runner/sdk-loop.js +470 -0
- package/dist/runner/spec-holds.d.ts +16 -2
- package/dist/runner/spec-holds.js +42 -14
- package/dist/runner/store-secrets.js +17 -2
- package/dist/runner/workflow-first.d.ts +30 -20
- package/dist/runner/workflow-first.js +22 -32
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-loop.js +18 -12
- package/dist/runner/workflow-spec.d.ts +4 -1
- package/dist/runner/workflow-spec.js +56 -45
- package/dist/runs-over-store.d.ts +30 -2
- package/dist/runs-over-store.js +46 -14
- package/dist/sdk/runs.d.ts +115 -0
- package/dist/sdk/runs.js +422 -0
- package/dist/sdk/schema.d.ts +175 -0
- package/dist/sdk/schema.js +138 -0
- package/dist/sdk/workflows.d.ts +22 -0
- package/dist/sdk/workflows.js +39 -0
- package/dist/secrets.d.ts +2 -0
- package/dist/secrets.js +19 -1
- package/dist/server.d.ts +48 -32
- package/dist/server.js +554 -130
- package/dist/skill-route.d.ts +3 -0
- package/dist/skill-route.js +16 -0
- package/dist/skills/agentrun-serve/SKILL.md +368 -0
- package/dist/stats.d.ts +10 -10
- package/dist/store/agent-body.d.ts +12 -8
- package/dist/store/agent-body.js +9 -4
- package/dist/store/index.d.ts +1 -1
- package/dist/store/native-command-owner.d.ts +10 -0
- package/dist/store/native-command-owner.js +47 -0
- package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
- package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
- package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
- package/dist/store/postgres/store.js +3 -0
- package/dist/store/schema.d.ts +7 -0
- package/dist/store/schema.js +20 -1
- package/dist/store/sqlite/run-patch.d.ts +8 -1
- package/dist/store/sqlite/run-patch.js +14 -3
- package/dist/store/sqlite/store.js +133 -18
- package/dist/store/store.d.ts +52 -7
- package/dist/store-reads/analytics.d.ts +7 -7
- package/dist/store-reads/analytics.js +23 -5
- package/dist/store-reads/cap.js +8 -6
- package/dist/store-reads/journal.d.ts +5 -0
- package/dist/store-reads/journal.js +85 -41
- package/dist/store-reads/learning.d.ts +85 -5
- package/dist/store-reads/learning.js +45 -17
- package/dist/store-reads/runs.d.ts +5 -0
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.js +75 -21
- package/dist/template-eval.d.ts +73 -11
- package/dist/template-eval.js +535 -75
- package/dist/templates.d.ts +70 -20
- package/dist/templates.js +191 -34
- package/dist/text-urls.d.ts +38 -0
- package/dist/text-urls.js +170 -0
- package/dist/timeline/index.d.ts +3 -2
- package/dist/timeline/index.js +3 -2
- package/dist/timeline/labels.d.ts +5 -2
- package/dist/timeline/labels.js +29 -6
- package/dist/timeline/origin.d.ts +1 -1
- package/dist/timeline/origin.js +2 -2
- package/dist/timeline/render-text.js +1 -1
- package/dist/timeline/timeline.d.ts +66 -4
- package/dist/timeline/timeline.js +160 -30
- package/dist/timeline/util.d.ts +5 -0
- package/dist/timeline/util.js +44 -8
- package/dist/timeline/web-calls.d.ts +17 -0
- package/dist/timeline/web-calls.js +106 -0
- package/dist/tool-gate.d.ts +42 -42
- package/dist/tool-gate.js +97 -91
- package/dist/tool-list.d.ts +4 -1
- package/dist/tool-list.js +8 -1
- package/dist/tool-names.d.ts +18 -13
- package/dist/tool-names.js +19 -17
- package/dist/tool-plane.d.ts +17 -13
- package/dist/tool-plane.js +12 -5
- package/dist/tools.d.ts +44 -16
- package/dist/tools.js +28 -28
- package/dist/trigger-adapter.d.ts +85 -5
- package/dist/trigger-adapter.js +6 -0
- package/dist/trigger-adapters.js +3 -1
- package/dist/trigger-composio.d.ts +10 -0
- package/dist/trigger-composio.js +122 -0
- package/dist/trigger-email.d.ts +4 -0
- package/dist/trigger-email.js +228 -0
- package/dist/trigger-signatures.d.ts +6 -10
- package/dist/trigger-signatures.js +16 -16
- package/dist/trigger-targets.d.ts +1 -1
- package/dist/trigger-targets.js +4 -3
- package/dist/trigger-webhook.js +6 -4
- package/dist/triggers.d.ts +94 -9
- package/dist/triggers.js +263 -62
- package/dist/uploads.d.ts +9 -0
- package/dist/uploads.js +27 -0
- package/dist/validate.js +1 -7
- package/dist/web-fake.d.ts +56 -0
- package/dist/web-fake.js +102 -0
- package/dist/web-fetch-direct.d.ts +3 -0
- package/dist/web-fetch-direct.js +4 -1
- package/dist/web-fetch.d.ts +5 -1
- package/dist/web-fetch.js +8 -31
- package/dist/web-search.d.ts +51 -2
- package/dist/web-search.js +116 -18
- package/dist/webhooks.d.ts +2 -1
- package/dist/webhooks.js +5 -1
- package/dist/workflow/node-runner.js +10 -2
- package/dist/workspace/archil-claim.d.ts +3 -0
- package/dist/workspace/archil-claim.js +9 -2
- package/dist/workspace/computer-deps.d.ts +22 -9
- package/dist/workspace/computer-deps.js +78 -37
- package/dist/workspace/computer-for-claim.d.ts +54 -4
- package/dist/workspace/computer-for-claim.js +179 -39
- package/dist/workspace/computer-janitor.d.ts +10 -3
- package/dist/workspace/computer-janitor.js +96 -29
- package/dist/workspace/computer-kept.d.ts +82 -0
- package/dist/workspace/computer-kept.js +147 -0
- package/dist/workspace/computer-mcp.js +4 -3
- package/dist/workspace/computer-ports.d.ts +23 -3
- package/dist/workspace/computer-ports.js +115 -5
- package/dist/workspace/index.d.ts +1 -2
- package/dist/workspace/index.js +1 -2
- package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
- package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
- package/dist/workspace/resolve-computer.d.ts +15 -3
- package/dist/workspace/resolve-computer.js +10 -7
- package/dist/workspace/revision-skills.d.ts +6 -2
- package/dist/workspace/revision-skills.js +12 -5
- package/dist/workspace/run-end-computers.d.ts +30 -0
- package/dist/workspace/run-end-computers.js +137 -0
- package/dist/workspace/run-tools.d.ts +28 -29
- package/dist/workspace/run-tools.js +29 -30
- package/dist/wrap-up.d.ts +19 -5
- package/dist/wrap-up.js +31 -4
- package/package.json +13 -9
- package/skills/agentrun-serve/SKILL.md +248 -10
- package/templates/README.md +117 -23
- package/templates/TOOLS.md +168 -0
- package/templates/code-review/agent.md +18 -4
- package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
- package/templates/code-review/evals/other-repo/case.yaml +1 -1
- package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
- package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
- package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
- package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
- package/templates/code-review/skills/review/DEEP.md +2 -2
- package/templates/code-review/skills/review/REVIEWER.md +2 -2
- package/templates/code-review/skills/review/SKILL.md +7 -3
- package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
- package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
- package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
- package/templates/release-notes/evals/other-repo/case.yaml +1 -1
- package/dist/console/assets/index-CjqQirbo.css +0 -1
- package/dist/console/assets/index-b6-XY5A9.js +0 -576
- package/dist/host-calls.d.ts +0 -20
- package/dist/host-calls.js +0 -12
- package/dist/runner/adapters/pi-computer.d.ts +0 -9
- package/dist/runner/adapters/pi-computer.js +0 -51
- package/dist/workspace/computer-script.d.ts +0 -53
- package/dist/workspace/computer-script.js +0 -172
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
|
|
2
2
|
import { createModels } from "@earendil-works/pi-ai/models";
|
|
3
|
-
import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
4
|
-
import {
|
|
3
|
+
import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID, ToolTask } from "@earendil-works/pi-durable";
|
|
4
|
+
import { modelPortFor, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
|
|
5
5
|
import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
|
|
6
6
|
import { turnEndedOnAsk } from "../store-reads/journal.js";
|
|
7
|
-
import { CAP_WRAPUP, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
|
|
7
|
+
import { CAP_WRAPUP, COMPUTER_NOTE, endsTurn, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
|
|
8
8
|
import { raiseFollowUpId } from "../run-view.js";
|
|
9
9
|
import { durableWait } from "../workflow/pi-versions.js";
|
|
10
10
|
/** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
|
|
11
|
-
* takeover's note, its computer's hold, the learning seed it laid): read past when a claim asks
|
|
12
|
-
* on its end (a fresh reopen). */
|
|
13
|
-
const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
|
|
11
|
+
* takeover's note, its computer's hold, the learning seed it laid, the computer it made): read past when a claim asks
|
|
12
|
+
* whether the run's root ends on its end (a fresh reopen). */
|
|
13
|
+
const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, KINDS.computerMade, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
|
|
14
14
|
/** A learned workflow's handback is the server's message to the agent, never the person's. */
|
|
15
15
|
const HANDED_BACK_ORIGIN = { kind: "server", reason: "handed_back" };
|
|
16
16
|
/** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
|
|
@@ -29,8 +29,8 @@ const outputRetried = (entries) => {
|
|
|
29
29
|
import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
|
|
30
30
|
import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
|
|
31
31
|
import { ADAPTER_API } from "../turn-end.js";
|
|
32
|
-
import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
|
|
33
|
-
import { approvalOf, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
|
|
32
|
+
import { answerText, REFLECT_NOTE_ONLY, REFLECT_PREFIX, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
|
|
33
|
+
import { approvalOf, BOOKING_WRITE_MS, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, PARK_SIBLINGS_MS, readAgain, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
|
|
34
34
|
import { outputMiss, outputRetryWords } from "../answer-json.js";
|
|
35
35
|
import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
|
|
36
36
|
import { isComputerCommand, journalHold } from "./computer-journal.js";
|
|
@@ -41,19 +41,18 @@ import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
|
|
|
41
41
|
import { channelCallOf, runChannelCall } from "./computer-channel.js";
|
|
42
42
|
import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
|
|
43
43
|
import { journalSessions } from "./sessions.js";
|
|
44
|
-
import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal,
|
|
44
|
+
import { DECISION_SESSION, FIT_TOLERANCE, freeModel, freeRequestsIn, freeWrapUpDue, freeWrapUpWords, noteFor, overCapOf, paidRefusal, requestFigures, runCap, SERVER_NOTE_LABEL, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
45
45
|
import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
|
|
46
46
|
import { bookedIn } from "../paid-calls.js";
|
|
47
|
-
import { withHostCalls } from "../host-calls.js";
|
|
48
47
|
import { sideEffect } from "./side-effects.js";
|
|
49
48
|
import { McpClaimRefused } from "./mcp-claim.js";
|
|
50
|
-
import { CODEMODE, defersCatalog,
|
|
49
|
+
import { CODEMODE, defersCatalog, isCatalogWire, TOOLS_CALL, TOOLS_SEARCH } from "@parcha/agentrun-kernel";
|
|
51
50
|
import { metaTools } from "./meta-tools.js";
|
|
52
51
|
import { builtinHarness } from "../harness-table.js";
|
|
53
52
|
import { Fenced } from "../store/index.js";
|
|
54
53
|
import { answerAsServed } from "../answer-json.js";
|
|
55
|
-
import { reserveFor,
|
|
56
|
-
import { LEARNED_CLIP, LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
|
|
54
|
+
import { reserveFor, stepAndAnswerFor, wrappingUp, wrapUpText } from "../wrap-up.js";
|
|
55
|
+
import { LEARNED_CARD_FIELDS, LEARNED_CLIP, LEARNED_WORKFLOW_TOOL, learnedApprovedTools } from "../learned-workflow.js";
|
|
57
56
|
import { feedbackAsk, feedbackOf, pendingFeedbackOf } from "./feedback-round.js";
|
|
58
57
|
import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
|
|
59
58
|
/** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
|
|
@@ -61,6 +60,14 @@ import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLO
|
|
|
61
60
|
export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
|
|
62
61
|
/** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
|
|
63
62
|
export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
|
|
63
|
+
/** An asked call's card: the gate's own fields (`shown`) first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES)
|
|
64
|
+
* still names them whatever the input's size, then the call's input, which the model wrote, without any field of
|
|
65
|
+
* theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's. */
|
|
66
|
+
function cardOf(tool, shown, args) {
|
|
67
|
+
if (!shown && tool !== LEARNED_WORKFLOW_TOOL)
|
|
68
|
+
return args;
|
|
69
|
+
return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
|
|
70
|
+
}
|
|
64
71
|
/** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
|
|
65
72
|
const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
|
|
66
73
|
/** What a CLI's request held at a cut turn (TurnCut) is refused with: the turn ended at the person's question. */
|
|
@@ -145,10 +152,17 @@ export function pendingPauseOf(entries) {
|
|
|
145
152
|
}
|
|
146
153
|
/** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
|
|
147
154
|
const DELIVER_NOW_MS = 5_000;
|
|
148
|
-
/** How long the
|
|
149
|
-
* may take it. A request that leaves before its admission gives it back as it goes
|
|
150
|
-
* only the backstop for a path that never does. A proxy's token count and admission
|
|
155
|
+
/** How long a server note (the replaced computer's, a wrap-up), once a request took it, waits for that request's
|
|
156
|
+
* admission before a later request may take it. A request that leaves before its admission gives it back as it goes
|
|
157
|
+
* (ModelPort.noteReturned): this is only the backstop for a path that never does. A proxy's token count and admission
|
|
158
|
+
* take well under it. Once admitted, the request holds the note until it ends, however long it streams. */
|
|
151
159
|
const WRAP_UP_OFFER_MS = 30_000;
|
|
160
|
+
/** A note the model was told (it begins with SERVER_NOTE_LABEL) as the server's row for it says it: the words after the
|
|
161
|
+
* label, their first letter a capital, since the row is the server's already ("AgentRun: …", timeline.ts CAP_WRAPUP). */
|
|
162
|
+
const rowWords = (told) => {
|
|
163
|
+
const words = told.startsWith(SERVER_NOTE_LABEL) ? told.slice(SERVER_NOTE_LABEL.length) : told;
|
|
164
|
+
return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
|
|
165
|
+
};
|
|
152
166
|
/** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
|
|
153
167
|
const cutWhole = (text, max) => {
|
|
154
168
|
const cut = text.slice(0, max);
|
|
@@ -169,21 +183,6 @@ const cliErrorAnswer = (harness, error, at) => ({
|
|
|
169
183
|
timestamp: at,
|
|
170
184
|
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
171
185
|
});
|
|
172
|
-
/** The session's recent requests as its newest KINDS.capRecent record kept them: each that reads as one (a model, and each
|
|
173
|
-
* figure a finite number of 0 or more); none without a record. One that does not read is left out: a request is then
|
|
174
|
-
* priced from another or uncached, never under its worst. */
|
|
175
|
-
export function recentIn(records) {
|
|
176
|
-
const kept = records.findLast((record) => record.kind === KINDS.capRecent)?.data;
|
|
177
|
-
if (!Array.isArray(kept))
|
|
178
|
-
return [];
|
|
179
|
-
const figure = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
180
|
-
return kept.flatMap((data) => {
|
|
181
|
-
const one = (data ?? {});
|
|
182
|
-
if (typeof one !== "object" || typeof one.model !== "string" || !figure(one.cachedTokens) || !figure(one.inputTokens) || !figure(one.boundTokens) || !figure(one.endedAt))
|
|
183
|
-
return [];
|
|
184
|
-
return [{ model: one.model, cachedTokens: one.cachedTokens, inputTokens: one.inputTokens, boundTokens: one.boundTokens, endedAt: one.endedAt, ...(typeof one.counted === "boolean" ? { counted: one.counted } : {}) }];
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
186
|
/** The turns a session's records booked (its runner.turn records), in order. */
|
|
188
187
|
export function turnsOf(records) {
|
|
189
188
|
return records.filter((record) => record.kind === RUNNER_RECORDS.turn).map((record) => record.data.turn).filter((turn) => typeof turn === "number");
|
|
@@ -221,12 +220,15 @@ export function bookingOfAnswer(records, given) {
|
|
|
221
220
|
turns.push(turn.turn);
|
|
222
221
|
if (side.has(turn.turn))
|
|
223
222
|
continue;
|
|
224
|
-
//
|
|
225
|
-
|
|
223
|
+
// By the kernel's one rule (turnCostOf): an answer with no price of its own is unknown, never the hold it was booked at
|
|
224
|
+
// for the cap; one billed to a person's plan is $0 to the run.
|
|
225
|
+
const figure = turn.usd === undefined && turn.bookedUsd === undefined ? undefined : turnCostOf(turn).usd;
|
|
226
226
|
usd = usd !== null && typeof figure === "number" && Number.isFinite(figure) ? (usd ?? 0) + figure : null;
|
|
227
227
|
}
|
|
228
228
|
return { turns, usd };
|
|
229
229
|
}
|
|
230
|
+
/** How often a park's wait for the calls beside it (siblingsSettled) reads whether they ended. */
|
|
231
|
+
const SIBLINGS_POLL_MS = 50;
|
|
230
232
|
/** A host check's refusal as the cap's rule reads it (AdapterRunSpec.cap.park). */
|
|
231
233
|
const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forGood ?? true, ...(refusal.figures ? { figures: refusal.figures } : {}) });
|
|
232
234
|
/** The record on `root` of the run's Harness: what the journal holds already read once, and every call a crash or a
|
|
@@ -258,6 +260,12 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
|
|
|
258
260
|
const sent = new Set();
|
|
259
261
|
// A call of a tool that only nests calls (its start marked `nests`): never ended interrupted, as it runs again whole.
|
|
260
262
|
const nesting = new Set();
|
|
263
|
+
// The call of the harness's own each call runs inside (nestedIn), named on the call's start.
|
|
264
|
+
const parents = new Map();
|
|
265
|
+
const parentOf = (callId) => {
|
|
266
|
+
const parent = parents.get(callId);
|
|
267
|
+
return parent === undefined ? {} : { parent };
|
|
268
|
+
};
|
|
261
269
|
// The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
|
|
262
270
|
const sending = new Set();
|
|
263
271
|
let personWritten = false;
|
|
@@ -419,8 +427,10 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
|
|
|
419
427
|
}
|
|
420
428
|
return;
|
|
421
429
|
}
|
|
422
|
-
await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(nests ? { nests } : {}), ...(cwd ? { cwd } : {}) });
|
|
430
|
+
await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(nests ? { nests } : {}), ...parentOf(callId), ...(cwd ? { cwd } : {}) });
|
|
423
431
|
started.set(callId, false);
|
|
432
|
+
if (nests)
|
|
433
|
+
nesting.add(callId);
|
|
424
434
|
});
|
|
425
435
|
},
|
|
426
436
|
async park(callId, tool, input, replaySafe) {
|
|
@@ -428,7 +438,7 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
|
|
|
428
438
|
await inTurn(async () => {
|
|
429
439
|
if (started.has(callId))
|
|
430
440
|
return;
|
|
431
|
-
await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(cwd ? { cwd } : {}) });
|
|
441
|
+
await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...parentOf(callId), ...(cwd ? { cwd } : {}) });
|
|
432
442
|
started.set(callId, false);
|
|
433
443
|
parked.add(callId);
|
|
434
444
|
});
|
|
@@ -439,7 +449,7 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
|
|
|
439
449
|
if (started.get(callId) === true)
|
|
440
450
|
return;
|
|
441
451
|
const at = now();
|
|
442
|
-
const start = { callId, tool, input, replaySafe, at };
|
|
452
|
+
const start = { callId, tool, input, replaySafe, ...parentOf(callId), at };
|
|
443
453
|
const end = { callId, status: "refused", output: words, at };
|
|
444
454
|
await harness.commit(async (tx) => {
|
|
445
455
|
if (!started.has(callId))
|
|
@@ -450,7 +460,9 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
|
|
|
450
460
|
ends.set(callId, { status: "refused", output: words });
|
|
451
461
|
});
|
|
452
462
|
},
|
|
463
|
+
nestedIn: (callId, parent) => void parents.set(callId, parent),
|
|
453
464
|
unsentParked: () => [...parked].filter((callId) => !sent.has(callId) && started.get(callId) === false),
|
|
465
|
+
openNests: () => [...nesting].filter((callId) => started.get(callId) === false),
|
|
454
466
|
noteEnd(callId, status, output) {
|
|
455
467
|
started.set(callId, true);
|
|
456
468
|
ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
|
|
@@ -545,6 +557,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
545
557
|
void stopping.then(() => stopAbort.abort(new Error("the run was stopped")));
|
|
546
558
|
let parked = () => { };
|
|
547
559
|
const parking = new Promise((resolve) => (parked = resolve));
|
|
560
|
+
/** The claim is parking: it waits for the calls already running beside the parked one (siblingsSettled), and no call
|
|
561
|
+
* starts meanwhile, nor is an answer taken (it waits for the next claim, as once the journal is sealed). */
|
|
562
|
+
let parkPending = false;
|
|
563
|
+
/** The calls this claim parked the run on (their ask landed with the run parked): what siblingsSettled waits beside. */
|
|
564
|
+
const parkedCalls = new Set();
|
|
548
565
|
let finished;
|
|
549
566
|
let gate;
|
|
550
567
|
let harness;
|
|
@@ -591,9 +608,18 @@ function adapterLoop(specOf, options, deps) {
|
|
|
591
608
|
};
|
|
592
609
|
/** The current pass's spec's release, until it is called (closeSession). */
|
|
593
610
|
let releaseNow;
|
|
594
|
-
/**
|
|
595
|
-
|
|
611
|
+
/** The current pass ended in a park that keeps its computer (keepAtPark), for this cause, until its release reads it. */
|
|
612
|
+
let parkedNow;
|
|
613
|
+
/** From the end-of-run step's start (or a claim that found its turn open: lookingBackOpen, from its session's open)
|
|
614
|
+
* until the claim ends: a steer is left for the end, writes and edits under work/.learning/ are refused
|
|
615
|
+
* (REFLECT_NOTE_ONLY), and every request is learning's, never the job's: the cap's wrap-up note is never told to it,
|
|
616
|
+
* and a refusal of one never parks the run (learningRefused). Held between the step's asks too: a turn a takeover
|
|
617
|
+
* resumed may send its next request while the step still reads an earlier answer. */
|
|
596
618
|
let reflecting = false;
|
|
619
|
+
/** A cap refusal of a request of the end-of-run turn, until that turn's ask reads it: the run has answered, so it parks
|
|
620
|
+
* nothing; the ask fails in the refusal's words, and the learning is dropped as the cap's short room drops it
|
|
621
|
+
* (reflect-hook.ts CAP_REFUSAL: no_budget). An answered run never parks on learning spend. */
|
|
622
|
+
let learningRefused;
|
|
597
623
|
/** While the run's end waits for a person to hand its desktop or phone back (#2134): a steer is left for the end, as
|
|
598
624
|
* in the end-of-run turn, so no turn starts that the end, written after the hand-back, would cut. */
|
|
599
625
|
let handingBack = false;
|
|
@@ -668,6 +694,15 @@ function adapterLoop(specOf, options, deps) {
|
|
|
668
694
|
};
|
|
669
695
|
/** The claim's CLI record (record: "loop"), for the end-of-run turn's answer; undefined for an adapter keeping its own. */
|
|
670
696
|
let cliRecord;
|
|
697
|
+
/** The writes of the harness's own calls (SessionIO.ownCalls) not yet settled: the run's end waits for them, so it never
|
|
698
|
+
* closes interrupted an exec whose own end is on its way. */
|
|
699
|
+
const ownWrites = new Set();
|
|
700
|
+
const ownWrite = (write) => {
|
|
701
|
+
ownWrites.add(write);
|
|
702
|
+
const settled = () => void ownWrites.delete(write);
|
|
703
|
+
write.then(settled, settled);
|
|
704
|
+
return write;
|
|
705
|
+
};
|
|
671
706
|
/** A CLI's turn cut at its question to the person (TurnCut): armed by the call's end, asked for by the next request. */
|
|
672
707
|
const askCut = turnCut();
|
|
673
708
|
/** Whether this loop sent the run its output retry (sendOutputRetry): never a second, even when its turn gave no answer. */
|
|
@@ -677,6 +712,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
677
712
|
* fenced and lost, and its request read back at its hold. */
|
|
678
713
|
let unbooked = 0;
|
|
679
714
|
let bookedAll = [];
|
|
715
|
+
/** Of those, the ones whose booking has begun (the request answered or ended, its runner.turn on its way to the
|
|
716
|
+
* store), and who waits for none: a booking under way is waited for past CLOSE_MS (bookingsSettled), so a busy store
|
|
717
|
+
* never lets the end, or an answer's cost, go ahead of it. */
|
|
718
|
+
let bookingsWriting = 0;
|
|
719
|
+
let writtenAll = [];
|
|
680
720
|
/** The raises this claim has: the state the ones before left (the kernel cap's takeRaises, in arrival order), the rows
|
|
681
721
|
* to take in the raise entry's commit, whether any resumes a paused run, and the budget it answered. */
|
|
682
722
|
const raising = { takes: [], resumes: false, resuming: false };
|
|
@@ -691,13 +731,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
691
731
|
/** The pass's MCP (spec.mcp), until the pass ends; and whether a command row came since its credentials were last made
|
|
692
732
|
* fresh (a parked token may have expired meanwhile). */
|
|
693
733
|
let mcp;
|
|
694
|
-
/** The calls of this run a person
|
|
695
|
-
*
|
|
696
|
-
const
|
|
697
|
-
/** Each answered call's ask as journaled (the card the person saw), set by answerOf as it reads or writes the answer. */
|
|
698
|
-
const askedArgs = new Map();
|
|
699
|
-
/** An MCP tool of the run as the claim's pass wrapped it, by its catalog name (set once its tools are wrapped). */
|
|
700
|
-
let mcpHosted = () => undefined;
|
|
734
|
+
/** The calls of this run a person was asked about (their ask in the journal, on this claim or read on a resume), set as
|
|
735
|
+
* the ask is read: one of them the gate lets through was let through by a person's answer. */
|
|
736
|
+
const askedCalls = new Set();
|
|
701
737
|
let mcpStale = false;
|
|
702
738
|
/** Marks the raise's follow-up the server's (MESSAGE_ORIGIN, timeline/origin.ts) before it is sent: its own commit, the
|
|
703
739
|
* input's user entry left as pi writes it (its submission, which a re-claim answers from, unchanged), so the Timeline
|
|
@@ -1213,43 +1249,30 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1213
1249
|
const besideNow = async () => (specNow?.runCap?.beside ? await specNow.runCap.beside() : 0);
|
|
1214
1250
|
const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush(), claim }), { beside: besideNow });
|
|
1215
1251
|
let capBuilt;
|
|
1216
|
-
/** The session's recent requests, as the cap's `expected` pricing reads them (the kernel's recentAfter and
|
|
1217
|
-
* warmFrom): the harness's own requests that answered under CACHE_WARM_MS ago, each one's input as its usage
|
|
1218
|
-
* reported it (read from or written to the cache, and the rest), its input bound and when it ended. Kept on the
|
|
1219
|
-
* session (KINDS.capRecent), so a new claim after an approval, a deny or a park starts from them (seeded below,
|
|
1220
|
-
* once the session's records are read), and its first request is warm or cold by when they ended, as within a
|
|
1221
|
-
* claim. None before one has: a cache miss. */
|
|
1222
|
-
let recent = [];
|
|
1223
1252
|
/** What the run keeps back beside a request of its own session while it streams (RunCapOptions.keepBackUsd), set
|
|
1224
1253
|
* once the wrap-up's reserve is known (below): a tool call it makes mid-stream finds room for the steps after it. */
|
|
1225
1254
|
let keepBackOf;
|
|
1226
|
-
/**
|
|
1227
|
-
|
|
1255
|
+
/** The run's requests counted toward the free limit (free.ts freeRequestsIn) as of its last admission, in every
|
|
1256
|
+
* session: read from its records at the claim (below), then taken from each admission the cap judges, the count it
|
|
1257
|
+
* was judged with (runBooking's freeRequestsMade) and itself when it counts. Never a read of the run's records
|
|
1258
|
+
* between a request's admission and its leaving: that wait let a cancel close the session before the request was
|
|
1259
|
+
* booked, its cost left unknown. */
|
|
1260
|
+
let freeMade = 0;
|
|
1228
1261
|
const theCap = () => {
|
|
1229
1262
|
if (!specNow?.runCap)
|
|
1230
1263
|
throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
|
|
1231
1264
|
// The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
|
|
1232
|
-
// Its recent requests are the session's own (requestEnded), unless the spec names them (a test's warm cache).
|
|
1233
1265
|
const { beside: _beside, ...config } = specNow.runCap;
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
return;
|
|
1245
|
-
const cachedTokens = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
1246
|
-
if (!(usage.input >= 0 && cachedTokens >= 0 && usage.input + cachedTokens > 0))
|
|
1247
|
-
return;
|
|
1248
|
-
// A smaller request than the last (a CLI's own while a tool runs, a compaction's, a child's that the proxy cannot
|
|
1249
|
-
// tell from the root's) is kept beside the others, never in their place: each request is priced from the one
|
|
1250
|
-
// whose bound fits it best (warmFrom), so none resets the conversation's history.
|
|
1251
|
-
recent = recentAfter(recent, { model: asked.model, cachedTokens, inputTokens: usage.input, boundTokens: asked.bound, counted: asked.counted, endedAt: (specNow?.runCap?.now ?? Date.now)() });
|
|
1252
|
-
await keep.append([{ kind: KINDS.capRecent, data: recent }]).catch(() => undefined);
|
|
1266
|
+
// runCap tells `judged` only the verdict a request goes by: a refusal that waits is asked again, told then, so a
|
|
1267
|
+
// request admitted after waiting sets freeMade from the count it was admitted at.
|
|
1268
|
+
const judged = (request, answer) => {
|
|
1269
|
+
config.judged?.(request, answer);
|
|
1270
|
+
if (request.freeRequestsMade !== undefined)
|
|
1271
|
+
freeMade = request.freeRequestsMade + (answer && !("refuse" in answer) && answer.freeRequest === true ? 1 : 0);
|
|
1272
|
+
};
|
|
1273
|
+
// A step waiting for room leaves once the run has a pause (pendingPause, below): nothing more is sent until a
|
|
1274
|
+
// raise, and it is refused in the pause's words (beforeRequest). It leaves at the run's stop too, unsent.
|
|
1275
|
+
return (capBuilt ??= runCap({ sessions, keepBackUsd: (request, asked) => keepBackOf?.(request, asked), parked: () => pendingPause !== undefined, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), ...config, judged, capUsd: capNow }));
|
|
1253
1276
|
};
|
|
1254
1277
|
const flushed = { flush: () => deps.flush() };
|
|
1255
1278
|
const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
|
|
@@ -1377,6 +1400,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1377
1400
|
// outside any) and its decisions (ledger.decisions). Its last refusal is kept: a turn it ended ends the run in its
|
|
1378
1401
|
// words.
|
|
1379
1402
|
const paid = ledger.paid;
|
|
1403
|
+
// A host tool call's paid requests name the session the call runs in (RunTools.admit `under`): a request of it still
|
|
1404
|
+
// in flight may be the one that asked for the call (Claude Code books its cost after its calls; Codex starts a call
|
|
1405
|
+
// with its response open), so the call is judged beside it and never waits on it. pi's request has answered by then.
|
|
1406
|
+
const paidUnder = { admit: (request) => paid.admit({ ...request, under: spec.session.key }), settle: (id, usd, options) => paid.settle(id, usd, options) };
|
|
1380
1407
|
let refused;
|
|
1381
1408
|
/** The pause a refusal for room journaled before pi heard of it (pauseAtCap), the run parked with it. */
|
|
1382
1409
|
let pausedAtRefusal = false;
|
|
@@ -1436,9 +1463,6 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1436
1463
|
return { ...pending, refuse: text, figures };
|
|
1437
1464
|
};
|
|
1438
1465
|
const beforeRequest = async (request) => {
|
|
1439
|
-
// Kept until it ends, so its answer can be one of the session's recent requests (requestEnded): on its model as the cap
|
|
1440
|
-
// prices it (RunCap.asked), which a CLI's request names as its provider does, so the next request finds it.
|
|
1441
|
-
askedFor.set(request.turn, { model: specNow?.runCap ? theCap().asked(request).model.id : request.model, ...(request.inputTokensMax === undefined ? {} : { bound: request.inputTokensMax }), counted: request.inputTokensCounted === true, own: request.host === undefined && !request.side && !request.unanswered });
|
|
1442
1466
|
// A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
|
|
1443
1467
|
// whatever else would pause it (a paid call's refusal, pendingPause). One a paid call stopped for good
|
|
1444
1468
|
// (paid-calls.ts stopRun) ends in that call's words, which say why, past its cap too.
|
|
@@ -1449,8 +1473,14 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1449
1473
|
if (pendingPause === undefined)
|
|
1450
1474
|
await keepPending(null);
|
|
1451
1475
|
}
|
|
1452
|
-
|
|
1453
|
-
|
|
1476
|
+
let answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
|
|
1477
|
+
// A request that waited for room while the run parked (the cap let it leave the line): refused in the pause's
|
|
1478
|
+
// words, as any request after the pause is.
|
|
1479
|
+
if (!over && answer && "refuse" in answer && pendingPause !== undefined)
|
|
1480
|
+
answer = pendingPause;
|
|
1481
|
+
if (answer && "refuse" in answer && reflecting)
|
|
1482
|
+
learningRefused ??= answer;
|
|
1483
|
+
else if (answer && "refuse" in answer) {
|
|
1454
1484
|
refused = answer;
|
|
1455
1485
|
await pauseAt(answer);
|
|
1456
1486
|
}
|
|
@@ -1511,13 +1541,19 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1511
1541
|
// run's cap now, what it spent and holds, and its own priced answers. Once per cap, as main's process told it
|
|
1512
1542
|
// (cap.ts wrapUpSentIn): a CAP_WRAPUP entry names the cap it was told under, read at each claim, so a raise's new
|
|
1513
1543
|
// cap is told again when it too comes near; written as the server's row only once a request carrying the note is
|
|
1514
|
-
//
|
|
1544
|
+
// answered.
|
|
1515
1545
|
const wrapUpHarness = harness;
|
|
1516
1546
|
const wrapUpRoot = root ?? (await harness.root(context));
|
|
1517
1547
|
const toldCaps = (await entriesOf(gate.journal, wrapUpRoot.id, context))
|
|
1518
1548
|
.filter((entry) => entry.kind === CAP_WRAPUP)
|
|
1519
1549
|
.map((entry) => entry.data?.capUsd)
|
|
1520
1550
|
.filter((capUsd) => typeof capUsd === "number");
|
|
1551
|
+
// The free limits it was told under (a CAP_WRAPUP row naming `freeLimit`), read at each claim, so a restart never tells
|
|
1552
|
+
// one twice.
|
|
1553
|
+
const toldFreeLimits = new Set((await entriesOf(gate.journal, wrapUpRoot.id, context))
|
|
1554
|
+
.filter((entry) => entry.kind === CAP_WRAPUP)
|
|
1555
|
+
.map((entry) => entry.data?.freeLimit)
|
|
1556
|
+
.filter((limit) => typeof limit === "number"));
|
|
1521
1557
|
const toldAt = (capUsd) => capUsd !== undefined && toldCaps.some((told) => Math.abs(told - capUsd) <= 1e-9);
|
|
1522
1558
|
// What the run spent on its sessions other than this claim's model session, its decisions' and its paid calls' (an
|
|
1523
1559
|
// earlier session's, a grade's), summed as overCap sums them; null while any is unknown. Read at the claim and again
|
|
@@ -1540,11 +1576,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1540
1576
|
};
|
|
1541
1577
|
// The typical cost is of the harness's own main-model answers at what they cost: never a request the host sent beside
|
|
1542
1578
|
// them (`host`), nor the harness's own side call on a smaller model (`side`, a title request), nor one a crash cut
|
|
1543
|
-
// (booked at its hold
|
|
1579
|
+
// (booked at its hold, the worst case), one never sent, given back, owed or stopped.
|
|
1544
1580
|
const claimRecords = await writer.read();
|
|
1545
|
-
// The recent requests an earlier claim or pass kept (KINDS.capRecent): this claim's first request is priced from
|
|
1546
|
-
// them, warm or cold by when they ended, never as if the session had no history.
|
|
1547
|
-
recent = recentIn(claimRecords);
|
|
1548
1581
|
const claimHosts = sessionSpendOf(claimRecords).hosts;
|
|
1549
1582
|
/** The turns of requests that are no main-model request of the harness's own: read from the records, then each
|
|
1550
1583
|
* admitted side call's (its ticket's turn), so a live answer's cost is judged the same as a restart's. */
|
|
@@ -1554,6 +1587,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1554
1587
|
if (record.kind === RUNNER_RECORDS.request && data.side === true && typeof data.turn === "number")
|
|
1555
1588
|
notOwn.add(data.turn);
|
|
1556
1589
|
}
|
|
1590
|
+
// The free requests the run made before this claim, in every session (freeMade: each admission's from here on).
|
|
1591
|
+
let madeBefore = 0;
|
|
1592
|
+
for (const key of await sessions.keys())
|
|
1593
|
+
madeBefore += freeRequestsIn(await sessions.read(key));
|
|
1594
|
+
freeMade = madeBefore;
|
|
1557
1595
|
const capNote = {
|
|
1558
1596
|
costs: claimRecords.flatMap((record) => {
|
|
1559
1597
|
if (record.kind !== RUNNER_RECORDS.turn)
|
|
@@ -1564,16 +1602,16 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1564
1602
|
}),
|
|
1565
1603
|
restUsd: await restOf(),
|
|
1566
1604
|
};
|
|
1567
|
-
/** A main-model request as the run's cap prices it at admission (RunCap.asked: its model
|
|
1568
|
-
*
|
|
1569
|
-
*
|
|
1605
|
+
/** A main-model request as the run's cap prices it at admission (RunCap.asked: its model, its whole input uncached),
|
|
1606
|
+
* for the wrap-up's note and what the run keeps back to answer. A request the note takes is measured as its client
|
|
1607
|
+
* sent it (NoteRequest), by the input count its admission reads (a provider's or a local count, else its bytes). */
|
|
1570
1608
|
const pricedOf = (model, asked) => theCap().asked({ ...asked, model });
|
|
1571
1609
|
/** A main-model request's figures as the run's cap prices them (kernel cap requestFigures), for what it keeps back. */
|
|
1572
1610
|
const figuresOf = (model, asked) => {
|
|
1573
1611
|
const config = specNow?.runCap;
|
|
1574
1612
|
if (!config?.modelOf(model))
|
|
1575
1613
|
return undefined;
|
|
1576
|
-
return requestFigures(pricedOf(model, asked)
|
|
1614
|
+
return requestFigures(pricedOf(model, asked));
|
|
1577
1615
|
};
|
|
1578
1616
|
/** What the run keeps back to answer (wrap-up.ts reserveFor), its typical step the run's own priced answers'. */
|
|
1579
1617
|
const reserveOf = (figures) => reserveFor(figures, (step0Usd) => typicalCost(capNote.costs, step0Usd));
|
|
@@ -1587,10 +1625,71 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1587
1625
|
const config = specNow?.runCap;
|
|
1588
1626
|
if (!config || spec.record !== "loop" || request.key !== spec.session.key || request.host !== undefined || request.side || request.unanswered || request.paid)
|
|
1589
1627
|
return undefined;
|
|
1590
|
-
return reserveOf(requestFigures(asked
|
|
1628
|
+
return reserveOf(requestFigures(asked));
|
|
1591
1629
|
};
|
|
1592
1630
|
let bookingNow;
|
|
1631
|
+
// The replaced computer's note (spec.computerNote), until a request carrying it is answered. It goes before the
|
|
1632
|
+
// wrap-up: one note per request, so the wrap-up waits a request.
|
|
1633
|
+
let computerWords = spec.computerNote;
|
|
1634
|
+
// The server's note a request carries (the replaced computer's, else the cap's wrap-up; `cap` says the wrap-up's
|
|
1635
|
+
// figures), one request at a time: from its take until that request's admission ends, then, admitted carrying it
|
|
1636
|
+
// (`turn`), until that request ends. Told once that request is answered (afterRequest); given back for the next
|
|
1637
|
+
// request by a refusal, a dropped note, or an end with no answer (an error status, a 429, a lost or cut stream).
|
|
1638
|
+
// A request that took it and left before its admission (a note its policy could not place, an error) gives it back
|
|
1639
|
+
// as it goes (noteReturned). WRAP_UP_OFFER_MS is only the backstop for a take that
|
|
1640
|
+
// never reaches its admission and is never given back: past it, a later request may take the note. An admitted
|
|
1641
|
+
// request always ends (the proxy books each one once), so no backstop is needed from there.
|
|
1642
|
+
let carried;
|
|
1643
|
+
const takeNote = (model, asked) => {
|
|
1644
|
+
if (carried && (carried.turn !== undefined || Date.now() - carried.at < WRAP_UP_OFFER_MS))
|
|
1645
|
+
return undefined;
|
|
1646
|
+
const note = computerWords !== undefined && !reflecting ? { words: computerWords } : wrapUpNote(model, asked);
|
|
1647
|
+
carried = note ? { ...note, at: Date.now() } : undefined;
|
|
1648
|
+
return note?.words;
|
|
1649
|
+
};
|
|
1650
|
+
/** Told: the note is the run's told at once (no request takes it again), and its row, once, the server's, is
|
|
1651
|
+
* what is returned to write: after the request is booked, so a finished request's hold never waits on the row. */
|
|
1652
|
+
const tell = (told) => {
|
|
1653
|
+
let kind = CAP_WRAPUP;
|
|
1654
|
+
let data;
|
|
1655
|
+
let what;
|
|
1656
|
+
if (told.freeLimit !== undefined) {
|
|
1657
|
+
if (toldFreeLimits.has(told.freeLimit))
|
|
1658
|
+
return undefined;
|
|
1659
|
+
toldFreeLimits.add(told.freeLimit);
|
|
1660
|
+
data = { words: rowWords(told.words), freeLimit: told.freeLimit };
|
|
1661
|
+
what = "the free-limit wrap-up's row";
|
|
1662
|
+
}
|
|
1663
|
+
else if (told.cap === undefined) {
|
|
1664
|
+
computerWords = undefined;
|
|
1665
|
+
kind = COMPUTER_NOTE;
|
|
1666
|
+
data = { words: rowWords(told.words) };
|
|
1667
|
+
what = "the replaced computer's note row";
|
|
1668
|
+
}
|
|
1669
|
+
else {
|
|
1670
|
+
const { leftUsd, capUsd } = told.cap;
|
|
1671
|
+
if (toldAt(capUsd))
|
|
1672
|
+
return undefined;
|
|
1673
|
+
toldCaps.push(capUsd);
|
|
1674
|
+
data = { words: rowWords(told.words), leftUsd, capUsd };
|
|
1675
|
+
what = "the wrap-up's row";
|
|
1676
|
+
}
|
|
1677
|
+
return async () => {
|
|
1678
|
+
try {
|
|
1679
|
+
await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind, data: data }), context);
|
|
1680
|
+
await deps.flush();
|
|
1681
|
+
}
|
|
1682
|
+
catch (error) {
|
|
1683
|
+
console.warn(`[runner] ${what} was not written (the note was answered): ${said(error)}`);
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
};
|
|
1687
|
+
/** The wrap-up due for a request about to be sent: the cap's, with what is left and the cap it is told under, else
|
|
1688
|
+
* the free limit's. */
|
|
1593
1689
|
const wrapUpNote = (model, asked) => {
|
|
1690
|
+
// The end-of-run turn comes after the run's answer: "finish now with your answer" is the job's note, never its.
|
|
1691
|
+
if (reflecting)
|
|
1692
|
+
return undefined;
|
|
1594
1693
|
const config = specNow?.runCap;
|
|
1595
1694
|
const capModel = config?.modelOf(model);
|
|
1596
1695
|
const sessionSpent = bookingNow?.spentUsd();
|
|
@@ -1600,20 +1699,25 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1600
1699
|
// The model session's requests in flight, at what is held for each (as the cap reads a flight); unknown gives none.
|
|
1601
1700
|
const inFlight = bookingNow?.heldUsd();
|
|
1602
1701
|
const capUsd = capNow();
|
|
1603
|
-
|
|
1604
|
-
// offered it too (its admission tells it, or a refusal or a dropped note gives it back: below). A request that
|
|
1605
|
-
// took it and left before its admission (its client gone while the proxy counted its tokens, a body the proxy
|
|
1606
|
-
// refused) gives it back as it goes (noteReturned), so the next request takes it at once. WRAP_UP_OFFER_MS is
|
|
1607
|
-
// only the backstop for a path that never gives it back: past it, a later request is offered it.
|
|
1608
|
-
if (capNote.offered && Date.now() - capNote.offered.at < WRAP_UP_OFFER_MS)
|
|
1609
|
-
return undefined;
|
|
1610
|
-
if (!config || !capModel || capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
|
|
1702
|
+
if (!config || !capModel)
|
|
1611
1703
|
return undefined;
|
|
1704
|
+
// The free-model limit's wrap-up (free.ts): the same note and offer, one per run and limit, on a request of a free
|
|
1705
|
+
// model. The dollar cap's note, when it is due on this request, goes first: one note per request, and it is told
|
|
1706
|
+
// once, so the free one waits for the next request (or never comes, the run having answered).
|
|
1707
|
+
const freeNote = () => {
|
|
1708
|
+
const limit = config.freeRequests;
|
|
1709
|
+
if (limit === undefined || toldFreeLimits.has(limit) || !freeModel(capModel))
|
|
1710
|
+
return undefined;
|
|
1711
|
+
const due = freeWrapUpDue(limit, freeMade);
|
|
1712
|
+
return due ? { words: freeWrapUpWords(due.left), freeLimit: limit } : undefined;
|
|
1713
|
+
};
|
|
1714
|
+
if (capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
|
|
1715
|
+
return freeNote();
|
|
1612
1716
|
const spentUsd = sessionSpent + decided + paidSpent + rest;
|
|
1613
|
-
// The tools' gate counts a request in flight at its hold
|
|
1614
|
-
//
|
|
1615
|
-
const heldUsd = inFlight +
|
|
1616
|
-
const due = noteFor(pricedOf(model, asked), { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false
|
|
1717
|
+
// The tools' gate counts a request in flight at its hold (sessionSpendOf), so the note counts it the same: it never
|
|
1718
|
+
// comes later than the gate's first refusal.
|
|
1719
|
+
const heldUsd = inFlight + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
|
|
1720
|
+
const due = noteFor(pricedOf(model, asked), { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false });
|
|
1617
1721
|
// The two wrap-ups read as one story: the note tells the model what is left; once what the run keeps back to
|
|
1618
1722
|
// answer (wrap-up.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
|
|
1619
1723
|
// its own has not made it due before: told on the request whose tool call would be refused now, no later than the
|
|
@@ -1623,8 +1727,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1623
1727
|
const atLine = wrappingUp(capUsd, spentUsd + heldUsd, reserveOf(figuresOf(model, asked)));
|
|
1624
1728
|
const leftUsd = capUsd - spentUsd - heldUsd;
|
|
1625
1729
|
const note = due ?? (atLine ? { words: wrapUpWords(leftUsd, capNote.costs.length === 0), leftUsd } : undefined);
|
|
1626
|
-
|
|
1627
|
-
return note?.words;
|
|
1730
|
+
return note ? { words: note.words, cap: { leftUsd: note.leftUsd, capUsd } } : freeNote();
|
|
1628
1731
|
};
|
|
1629
1732
|
// The rule before a side effect for every paid model request, on the path every adapter's requests take: the
|
|
1630
1733
|
// booking writes the request's record, then awaits request_start before the request leaves, so the flush here
|
|
@@ -1633,11 +1736,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1633
1736
|
key: spec.session.key,
|
|
1634
1737
|
label: spec.session.label,
|
|
1635
1738
|
beforeRequest,
|
|
1636
|
-
note:
|
|
1739
|
+
note: takeNote,
|
|
1637
1740
|
// A request that took it and left before its admission gives it back: the next request may take it at once.
|
|
1638
1741
|
noteReturned: (note) => {
|
|
1639
|
-
if (
|
|
1640
|
-
|
|
1742
|
+
if (carried?.turn === undefined && carried?.words === note)
|
|
1743
|
+
carried = undefined;
|
|
1641
1744
|
},
|
|
1642
1745
|
onEvent: async (event) => {
|
|
1643
1746
|
// The run's own priced answers, the typical cost the wrap-up is worked out by (a request the host sent beside
|
|
@@ -1646,8 +1749,6 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1646
1749
|
// at their hold or cut, comes before `capNote.live` and is never one.)
|
|
1647
1750
|
if (capNote.live && event.type === "request_end" && event.host === undefined && !notOwn.has(event.turn) && typeof event.usage.usd === "number" && event.usage.usd > 0 && !event.usage.cut && !event.usage.givenBack)
|
|
1648
1751
|
capNote.costs.push(event.usage.usd);
|
|
1649
|
-
if (event.type === "request_end")
|
|
1650
|
-
await requestEnded(event.turn, event.usage, event.ended, writer);
|
|
1651
1752
|
if (event.type === "request_start") {
|
|
1652
1753
|
// A new request means the model's last message is over: what it said so far is on the record before the request,
|
|
1653
1754
|
// so an answer shows while the turn goes on (a CLI that answers, then makes another request).
|
|
@@ -1670,9 +1771,15 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1670
1771
|
const on = harness;
|
|
1671
1772
|
const conversation = root ?? (await on.root(context));
|
|
1672
1773
|
const unsent = event.ended.end === "nothing" && event.ended.label === "never_left";
|
|
1774
|
+
// One on a free model (`free`: booked a known $0) is no cost unknown: its mark says so, and the usage row counts
|
|
1775
|
+
// it at $0, never cut.
|
|
1776
|
+
// One cut with no answer and booked at its hold (bookCut's CUT_AT_HOLD) is that figure, the most it can have
|
|
1777
|
+
// cost: its mark says so, and the usage row counts it there, never as a cost no one knows.
|
|
1778
|
+
const atMost = typeof event.usage.atMostUsd === "number" && Number.isFinite(event.usage.atMostUsd) ? { atMostUsd: event.usage.atMostUsd } : {};
|
|
1779
|
+
const data = unsent ? { unsent: true } : event.usage.free ? { free: true } : atMost;
|
|
1673
1780
|
// Not written when the journal sealed under it (the run's end landed first): a settled run reads its unanswered
|
|
1674
1781
|
// mark cut all the same.
|
|
1675
|
-
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data:
|
|
1782
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data: data }), context).catch(() => undefined);
|
|
1676
1783
|
}
|
|
1677
1784
|
},
|
|
1678
1785
|
});
|
|
@@ -1693,13 +1800,14 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1693
1800
|
// spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
|
|
1694
1801
|
// hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
|
|
1695
1802
|
// flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
|
|
1803
|
+
// Its answer is the words a call reads once the run wraps up (wrap-up.ts wrapUpText), undefined while it does not.
|
|
1696
1804
|
const wrapUp = async () => {
|
|
1697
1805
|
// A run whose spec gives no cap (no runCap) has none to wrap up at, as overCap reads it.
|
|
1698
1806
|
if (!spec.runCap)
|
|
1699
|
-
return
|
|
1807
|
+
return undefined;
|
|
1700
1808
|
const capUsd = capNow();
|
|
1701
1809
|
if (capUsd === undefined)
|
|
1702
|
-
return
|
|
1810
|
+
return undefined;
|
|
1703
1811
|
// What was spent beside the run on its behalf counts as taken, as its sessions' spend does.
|
|
1704
1812
|
let taken = await besideNow();
|
|
1705
1813
|
for (const key of await sessions.keys()) {
|
|
@@ -1709,7 +1817,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1709
1817
|
}
|
|
1710
1818
|
// What the run keeps back to answer, priced on the main model's last request admitted on this claim (its next one
|
|
1711
1819
|
// is priced at least as high): none yet, no wrap-up, as no tool call comes before a request.
|
|
1712
|
-
|
|
1820
|
+
if (!wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures)))
|
|
1821
|
+
return undefined;
|
|
1822
|
+
// A cap below what the model needs for one more step and an answer is named in the words, by the same rule.
|
|
1823
|
+
return wrapUpText(capUsd, capNote.lastModel, stepAndAnswerFor(capNote.lastFigures, (step0Usd) => typicalCost(capNote.costs, step0Usd)), capNote.lastEffort);
|
|
1713
1824
|
};
|
|
1714
1825
|
const gateOf = preIntentGate(spec, hooks, wrapUp);
|
|
1715
1826
|
// A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
|
|
@@ -1753,18 +1864,21 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1753
1864
|
// By the name the gate before the intent asks it by: an MCP tool by its catalog name.
|
|
1754
1865
|
const name = mcp?.catalogOf(tool.name) ?? tool.name;
|
|
1755
1866
|
const asked = spec.gate.askedAs?.(name) ?? name;
|
|
1756
|
-
const
|
|
1757
|
-
if (
|
|
1867
|
+
const given = await spec.gate({ callId: toolContext.callId, tool: name, args: (args ?? {}) }, { replayed: true });
|
|
1868
|
+
if (given === "deny")
|
|
1758
1869
|
return { text: setToDenyText(asked, undefined, "server", "unknown"), isError: true };
|
|
1759
|
-
if (typeof
|
|
1760
|
-
return { text:
|
|
1870
|
+
if (typeof given === "object" && "deny" in given)
|
|
1871
|
+
return { text: given.deny, isError: true };
|
|
1872
|
+
// An ask with its card's own fields is an ask, its card as the gate shows it.
|
|
1873
|
+
const shown = typeof given === "object" ? given.ask : undefined;
|
|
1874
|
+
const now = shown ? "ask" : given;
|
|
1761
1875
|
// Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
|
|
1762
1876
|
// replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
|
|
1763
1877
|
// the claim lets it go; a deny says the earlier attempt may have taken effect. Asked and not answered yet, with
|
|
1764
1878
|
// the setting at allow now: the setting answers the ask (allowedBySetting).
|
|
1765
1879
|
const bySetting = now === "allow" && (await askStands(toolContext.callId));
|
|
1766
1880
|
if (now === "ask" || bySetting) {
|
|
1767
|
-
const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
|
|
1881
|
+
const call = { callId: toolContext.callId, tool: name, args: cardOf(name, shown, (args ?? {})) };
|
|
1768
1882
|
const price = mcp?.priceOf(name) ?? null;
|
|
1769
1883
|
const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
|
|
1770
1884
|
if (answer === "park")
|
|
@@ -1788,11 +1902,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1788
1902
|
flush: () => deps.flush(),
|
|
1789
1903
|
// Its paid requests booked under this call, on the run's one ledger (paid-calls.ts bookedIn, Ledger.paid); one
|
|
1790
1904
|
// refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
|
|
1791
|
-
// The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
|
|
1792
|
-
// loop wrapped it, and whether a person approved this call.
|
|
1793
1905
|
// The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
|
|
1794
1906
|
// row's computer_calls, before its result is written.
|
|
1795
|
-
route: () => bookedIn({ call: toolContext.callId, paid, pause: ledger.pause }, () =>
|
|
1907
|
+
route: () => bookedIn({ call: toolContext.callId, paid: paidUnder, pause: ledger.pause }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped))),
|
|
1796
1908
|
beforeResult: async (answer) => {
|
|
1797
1909
|
const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
|
|
1798
1910
|
try {
|
|
@@ -1825,11 +1937,20 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1825
1937
|
}
|
|
1826
1938
|
},
|
|
1827
1939
|
});
|
|
1828
|
-
const
|
|
1940
|
+
const facts = builtinHarness(spec.adapter.id)?.facts;
|
|
1829
1941
|
// tools_search, tools_call and codemode over the session's tools (meta-tools.ts), on every harness (codemode on
|
|
1830
1942
|
// each but one that runs scripts of its own): what they call is called nested, each call asked about and recorded
|
|
1831
1943
|
// as its own tool's. A search finds a tool whose setting is not deny; an MCP tool's setting is its catalog name's.
|
|
1832
1944
|
const settingOf = spec.gate?.permission;
|
|
1945
|
+
// A meta tool whose setting is deny is not offered at all, rather than offered and refused.
|
|
1946
|
+
const allowed = async (name) => !settingOf || (await settingOf(name).catch(() => "deny")) !== "deny";
|
|
1947
|
+
const hostCodemode = facts?.ownCodemode !== true && (await allowed(CODEMODE));
|
|
1948
|
+
// A tool the spec binds for a script's nested calls alone (deferred: a desktop's computer_op, and its step tools
|
|
1949
|
+
// under its surface "code") is listed wherever the host offers no codemode to call it: on a harness that runs
|
|
1950
|
+
// scripts in its own code mode, which reaches only the tools it is handed (Codex's exec), and on a run whose
|
|
1951
|
+
// codemode is set to deny, so the computer is never out of the model's reach.
|
|
1952
|
+
const listedFor = ({ deferred: _, ...tool }) => tool;
|
|
1953
|
+
const own = [...spec.session.tools, ...(mcp?.tools ?? [])].map((tool) => (!hostCodemode && tool.deferred ? listedFor(tool) : tool)).map(hosted);
|
|
1833
1954
|
// The harness's own tools beside them (pi's subagent, its browser's): found and called by name as the host's are,
|
|
1834
1955
|
// run by the harness as its own nested calls. Never called here: a nested call reaches them through the harness.
|
|
1835
1956
|
const native = (spec.adapter.ownTools ?? []).filter((one) => !own.some((tool) => tool.name === one.name)).map((one) => ({
|
|
@@ -1843,9 +1964,6 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1843
1964
|
// model finds them with tools_search and runs them with tools_call (still the tool's own call at the gate). Claude
|
|
1844
1965
|
// Code defers them itself (its ToolSearch, on under the same test), so it is offered neither. Under the threshold
|
|
1845
1966
|
// every tool is listed and there is no search or call. codemode is offered as it always was.
|
|
1846
|
-
const facts = builtinHarness(spec.adapter.id)?.facts;
|
|
1847
|
-
// A meta tool whose setting is deny is not offered at all, rather than offered and refused.
|
|
1848
|
-
const allowed = async (name) => !settingOf || (await settingOf(name).catch(() => "deny")) !== "deny";
|
|
1849
1967
|
// Deferred only when the model can both find and run what it hid: with either helper denied every tool stays listed,
|
|
1850
1968
|
// so denying a helper never takes an otherwise allowed tool out of reach.
|
|
1851
1969
|
// The one verdict for every harness: one with a tool search of its own (Claude Code's) follows it too, handed it as
|
|
@@ -1855,20 +1973,17 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1855
1973
|
const metas = metaTools({
|
|
1856
1974
|
tools: () => [...own, ...native],
|
|
1857
1975
|
granted: async (name) => !settingOf || (await settingOf(mcp?.catalogOf(name) ?? name).catch(() => "deny")) !== "deny",
|
|
1858
|
-
codemode:
|
|
1976
|
+
codemode: hostCodemode,
|
|
1859
1977
|
discovery: { search: offered, call: offered },
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
const wire = mcp?.tools.find((one) => mcp?.catalogOf(one.name) === catalog);
|
|
1865
|
-
const host = wire && tools.find((one) => one.name === wire.name);
|
|
1866
|
-
return host && ((args, ctx) => host.call(args, ctx));
|
|
1867
|
-
};
|
|
1978
|
+
...(facts?.hostName ? { hostName: facts.hostName } : {}),
|
|
1979
|
+
...(spec.scriptComputer ? { computer: spec.scriptComputer } : {}),
|
|
1980
|
+
});
|
|
1981
|
+
const tools = [...own.map((one) => (offered && isCatalogWire(one.name) ? { ...one, deferred: true } : one)), ...metas.map(hosted)];
|
|
1868
1982
|
// The session's model port, counting what it admitted and has not booked yet (a stop's booking comes once the
|
|
1869
1983
|
// session's proxy sees its upstream end, which can be after pi went idle).
|
|
1870
1984
|
const port = booking.models;
|
|
1871
1985
|
unbooked = 0;
|
|
1986
|
+
bookingsWriting = 0;
|
|
1872
1987
|
const counted = {
|
|
1873
1988
|
beforeRequest: async (request) => {
|
|
1874
1989
|
// The CLI's next request of its main model after its question to the person: never admitted, it asks for the
|
|
@@ -1880,19 +1995,35 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1880
1995
|
mcpStale = false;
|
|
1881
1996
|
await mcp.fresh();
|
|
1882
1997
|
}
|
|
1883
|
-
// The
|
|
1884
|
-
//
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1998
|
+
// The note this request carries, the one it took (takeNote: one at a time). Admitted with it, the request holds it
|
|
1999
|
+
// until it ends (afterRequest tells it or gives it back); a refusal (the throw) or a dropped note gives it back
|
|
2000
|
+
// now, for a later request.
|
|
2001
|
+
const taken = request.noted === true && carried?.turn === undefined ? carried : undefined;
|
|
2002
|
+
let ticket;
|
|
2003
|
+
try {
|
|
2004
|
+
ticket = await port.beforeRequest(request);
|
|
2005
|
+
}
|
|
2006
|
+
catch (error) {
|
|
2007
|
+
if (taken && carried === taken)
|
|
2008
|
+
carried = undefined;
|
|
2009
|
+
throw error;
|
|
2010
|
+
}
|
|
2011
|
+
if (taken && carried === taken) {
|
|
2012
|
+
if (ticket && !ticket.noteDropped)
|
|
2013
|
+
taken.turn = ticket.turn;
|
|
2014
|
+
else
|
|
2015
|
+
carried = undefined;
|
|
2016
|
+
}
|
|
1889
2017
|
unbooked += 1;
|
|
1890
2018
|
// The harness's own side call (a title request on its smaller model): never a typical cost of its main requests.
|
|
1891
2019
|
if (ticket && request.side)
|
|
1892
2020
|
notOwn.add(ticket.turn);
|
|
1893
2021
|
// The main model's request as the cap prices it: what the run keeps back to answer is priced on it (wrapUp).
|
|
1894
|
-
if (!request.side && request.host === undefined)
|
|
1895
|
-
|
|
2022
|
+
if (!request.side && request.host === undefined) {
|
|
2023
|
+
const figures = figuresOf(request.model, request);
|
|
2024
|
+
if (figures)
|
|
2025
|
+
Object.assign(capNote, { lastFigures: figures, lastModel: request.model, lastEffort: request.effort });
|
|
2026
|
+
}
|
|
1896
2027
|
// What follows is the wrap-up's own bookkeeping, after the request was admitted and its hold booked: it never fails
|
|
1897
2028
|
// the request (a throw here would leave it admitted and never sent, read as cut at its worst case).
|
|
1898
2029
|
try {
|
|
@@ -1902,28 +2033,31 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1902
2033
|
capNote.restUsd = null;
|
|
1903
2034
|
console.warn(`[runner] the run's other sessions' spend was not read; no wrap-up until it is: ${said(error)}`);
|
|
1904
2035
|
}
|
|
1905
|
-
// Told once a request carrying it is admitted with it (never one that went without the note's bytes): the server's
|
|
1906
|
-
// row, once per cap, made durable before the request leaves, so a machine lost after it never tells that cap twice.
|
|
1907
|
-
if (offer && ticket && !ticket.noteDropped && !toldAt(offer.capUsd)) {
|
|
1908
|
-
const { words, leftUsd, capUsd } = offer;
|
|
1909
|
-
toldCaps.push(capUsd);
|
|
1910
|
-
try {
|
|
1911
|
-
await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind: CAP_WRAPUP, data: { words, leftUsd, capUsd } }), context);
|
|
1912
|
-
await deps.flush();
|
|
1913
|
-
}
|
|
1914
|
-
catch (error) {
|
|
1915
|
-
console.warn(`[runner] the wrap-up's row was not written (the note went with the request): ${said(error)}`);
|
|
1916
|
-
}
|
|
1917
|
-
}
|
|
1918
2036
|
return ticket;
|
|
1919
2037
|
},
|
|
1920
|
-
afterRequest: async (
|
|
2038
|
+
afterRequest: async (usage, ticket, ended) => {
|
|
2039
|
+
// The note this request carried: told once the model answered it, else given back. Settled before anything here
|
|
2040
|
+
// waits: the proxy calls this as its client has the end, so a client's retry finds the note told or on offer.
|
|
2041
|
+
const held = carried?.turn !== undefined && carried.turn === ticket?.turn ? carried : undefined;
|
|
2042
|
+
if (held)
|
|
2043
|
+
carried = undefined;
|
|
2044
|
+
// An answer the model gave, not the provider's error inside one (a stream ended in an error event, a translated
|
|
2045
|
+
// route's failure in words included: the client drops it and asks again).
|
|
2046
|
+
const row = held && ended?.end === "answered" && ended.label !== "error" ? tell(held) : undefined;
|
|
2047
|
+
// Its booking has begun: waited for past CLOSE_MS, as long as its write takes (bookingsSettled).
|
|
2048
|
+
bookingsWriting += 1;
|
|
1921
2049
|
try {
|
|
1922
2050
|
await hooks.beforeBooking?.();
|
|
1923
|
-
await port.afterRequest(
|
|
2051
|
+
await port.afterRequest(usage, ticket, ended);
|
|
1924
2052
|
}
|
|
1925
2053
|
finally {
|
|
2054
|
+
bookingsWriting = Math.max(0, bookingsWriting - 1);
|
|
2055
|
+
if (row)
|
|
2056
|
+
await row();
|
|
1926
2057
|
unbooked = Math.max(0, unbooked - 1);
|
|
2058
|
+
if (bookingsWriting === 0)
|
|
2059
|
+
for (const wake of writtenAll.splice(0))
|
|
2060
|
+
wake();
|
|
1927
2061
|
if (unbooked === 0)
|
|
1928
2062
|
for (const wake of bookedAll.splice(0))
|
|
1929
2063
|
wake();
|
|
@@ -2003,7 +2137,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2003
2137
|
await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
|
|
2004
2138
|
// A harness's own tool (Claude Code's WebSearch, which its provider runs) the gate held and a person now lets
|
|
2005
2139
|
// run: the host runs nothing of this call, so the start it parked ends here; the harness's next call runs it.
|
|
2006
|
-
else if (answer === "allow" &&
|
|
2140
|
+
else if (answer === "allow" && askedCalls.has(call.callId) && !tools.some((one) => one.name === call.tool))
|
|
2007
2141
|
await record.end(call.callId, "done", OWN_TOOL_RELEASED);
|
|
2008
2142
|
return answer;
|
|
2009
2143
|
}
|
|
@@ -2020,7 +2154,27 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2020
2154
|
askCut.disarm();
|
|
2021
2155
|
theRecord.onEvent(event);
|
|
2022
2156
|
};
|
|
2023
|
-
|
|
2157
|
+
// A call of the CLI's own that its host tool calls run inside (Codex's code-mode `exec`): on its record as a call, and
|
|
2158
|
+
// each call it makes named under it, so its rows read as a codemode script's do on every other harness. Its start is
|
|
2159
|
+
// marked `nests`, so a crash leaves it open: its harness ends it (ownCalls.ended) from its CLI's own answer to it after
|
|
2160
|
+
// the resume, which comes after the rows of the calls it made, never as an interrupted end ahead of them. One no answer
|
|
2161
|
+
// of its CLI ends (a stop while it waits, a crash no resume follows) the run's end closes, interrupted (openNests).
|
|
2162
|
+
const ownCalls = record
|
|
2163
|
+
? {
|
|
2164
|
+
opened: (callId, name, input) => ownWrite(record.start(callId, name, input, false, true).catch(unlessSealed)),
|
|
2165
|
+
nestedIn: (callId, parent) => record.nestedIn(callId, parent),
|
|
2166
|
+
ended: (callId, output, failed) => ownWrite(record.end(callId, failed ? "failed" : "done", output).catch(unlessSealed)),
|
|
2167
|
+
}
|
|
2168
|
+
: undefined;
|
|
2169
|
+
const io = { writer, models: counted, signal: deps.signal, onEvent: record ? onEvent(record) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, ...(ownCalls ? { ownCalls } : {}), bookedCost, keepCalls, ...(record ? {} : { nestedEnded }) };
|
|
2170
|
+
// The end-of-run turn an earlier claim asked and never saw end (its runner lost mid look-back or mid compile): the
|
|
2171
|
+
// root's newest input still in flight is that turn's (end-of-run.ts REFLECT_PREFIX), which pi picks up again as its
|
|
2172
|
+
// session opens. The job's turn ended before it, answered: this pass runs no job turn (no recovery as the job's, no
|
|
2173
|
+
// wrap-up note, no park on its spend), and the end-of-run step's ask, under the same request id, waits on it (a
|
|
2174
|
+
// CLI's look-back has no submission until it ends: its record's lookingBack, below). Read before the session
|
|
2175
|
+
// opens, so its first request is already learning's.
|
|
2176
|
+
const lookingBackOpen = (await harness.inspect(context)).submissions.filter((one) => one.type === "input" && Number(one.conversationId) === Number(ROOT_CONVERSATION_ID)).at(-1)?.requestId?.startsWith(REFLECT_PREFIX) === true;
|
|
2177
|
+
reflecting = lookingBackOpen;
|
|
2024
2178
|
// The MCP tools are host tools like any other (mcp.tools, wrapped above): every harness gets them on its own channel
|
|
2025
2179
|
// for host tools, each call through the gate before its intent.
|
|
2026
2180
|
session = await spec.adapter.open({ ...spec.session, tools, deferCatalog: deferred }, io);
|
|
@@ -2040,6 +2194,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2040
2194
|
await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
|
|
2041
2195
|
}, context) };
|
|
2042
2196
|
}
|
|
2197
|
+
// The run's own computer, made by this claim: its kind recorded once per claim, before any request of the claim
|
|
2198
|
+
// (each request's flush makes it durable first), so a later claim knows the run had one (computer-journal.ts
|
|
2199
|
+
// hadComputer) however this one ends.
|
|
2200
|
+
if (restarts === 0 && spec.computer?.own) {
|
|
2201
|
+
const [rootOf, kind] = [root, spec.computer.kind];
|
|
2202
|
+
await harness.commit((tx) => tx.appendEntry(rootOf.id, { kind: KINDS.computerMade, data: { computer: kind } }), context);
|
|
2203
|
+
}
|
|
2043
2204
|
if (spec.computer?.hold && spec.computer.kind !== "sandbox") {
|
|
2044
2205
|
const [journalOf, rootOf] = [harness, root];
|
|
2045
2206
|
computerNow = journalHold(claim.runId, { kind: spec.computer.kind, hold: spec.computer.hold }, (entries) => journalOf.commit(async (tx) => {
|
|
@@ -2173,7 +2334,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2173
2334
|
await takeRaises();
|
|
2174
2335
|
if (paused) {
|
|
2175
2336
|
if (!resumes || raising.capUsd === undefined || !spec.cap?.followUpOf)
|
|
2176
|
-
return await parkAtCap(harness, root, gate, paused);
|
|
2337
|
+
return await parkAtCap(harness, root, gate, paused, "cap");
|
|
2177
2338
|
// The server's words, shown as its row ("AgentRun: …"), never as the person's; under the id a raise's answer named.
|
|
2178
2339
|
const followUp = spec.cap.followUpOf(raising.capUsd).text;
|
|
2179
2340
|
const followUpId = raiseFollowUpId(raising.state?.lastRaise?.pause ?? "follow-up");
|
|
@@ -2241,10 +2402,40 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2241
2402
|
* (its own entries are its record): its call goes on a record of its own for this step, the same entries. A claim
|
|
2242
2403
|
* that finds the entry or the call's end takes it as it is. Undefined: the run is its agent's (the tool is not the
|
|
2243
2404
|
* run's, or the gate denies it before anything is written); "park": the call waits for a person's approval. */
|
|
2405
|
+
/** The session's tools as calls nested in the workflow served first (`outer`), with no harness to nest them: each
|
|
2406
|
+
* asked at the gate as its own tool under `<outer>/<key>` (a deny, its argument pins; an ask passes when the card
|
|
2407
|
+
* a person approved for `outer` named the tool, and any other is refused, since a workflow served first never parks
|
|
2408
|
+
* part way), then run as this loop wraps the tool (its record, its flush and booking, the stop's abort). The call
|
|
2409
|
+
* is never run again, so a value is its first run's as it is. */
|
|
2410
|
+
const servedNested = (outer) => ({
|
|
2411
|
+
async call(name, args, key, own) {
|
|
2412
|
+
const tool = tools.find((one) => one.name === name);
|
|
2413
|
+
if (!tool)
|
|
2414
|
+
return { text: `${name} is no tool of this run.`, isError: true, refused: true, fresh: true };
|
|
2415
|
+
const callId = `${outer}/${key}`;
|
|
2416
|
+
const catalog = mcp?.catalogOf(name) ?? name;
|
|
2417
|
+
const asked = spec.gate?.askedAs?.(catalog) ?? catalog;
|
|
2418
|
+
const given = (await spec.gate?.({ callId, tool: catalog, args })) ?? "allow";
|
|
2419
|
+
if (given === "deny")
|
|
2420
|
+
return { text: setToDenyText(asked, undefined, "server", "no"), isError: true, refused: true, fresh: true };
|
|
2421
|
+
if (typeof given === "object" && "deny" in given)
|
|
2422
|
+
return { text: given.deny, isError: true, refused: true, fresh: true };
|
|
2423
|
+
if (given !== "allow" && !learnedApprovedTools(await approvedCardOver(callId, spec.gate?.askedAs?.(LEARNED_WORKFLOW_TOOL) ?? LEARNED_WORKFLOW_TOOL)).has(catalog)) {
|
|
2424
|
+
return { text: `This ${asked} call needs a person's approval, which a learned workflow run first cannot wait for; it was not run.`, isError: true, refused: true, fresh: true };
|
|
2425
|
+
}
|
|
2426
|
+
const got = await tool.call(args, { callId, signal: own ? AbortSignal.any([stopAbort.signal, own]) : stopAbort.signal });
|
|
2427
|
+
return { text: got.text, ...(got.isError ? { isError: true } : {}), ...(got.images?.length ? { images: got.images } : {}), ...(got.structured !== undefined ? { structured: got.structured } : {}), fresh: true };
|
|
2428
|
+
},
|
|
2429
|
+
memo: async (_key, value) => (typeof value === "function" ? value() : value),
|
|
2430
|
+
});
|
|
2244
2431
|
const serveFirst = async (first) => {
|
|
2245
|
-
|
|
2246
|
-
|
|
2432
|
+
// The session's learned_workflow as this loop wraps a tool, but nesting nothing of the harness's: a call a crash
|
|
2433
|
+
// cut is ended interrupted and handed back, never run again (its record's start is not marked `nests`).
|
|
2434
|
+
const bare = spec.session.tools.find((tool) => tool.name === LEARNED_WORKFLOW_TOOL);
|
|
2435
|
+
if (!bare || !tools.some((tool) => tool.name === LEARNED_WORKFLOW_TOOL))
|
|
2247
2436
|
return undefined;
|
|
2437
|
+
const { nests: _nests, ...plain } = bare;
|
|
2438
|
+
const learned = hosted(plain);
|
|
2248
2439
|
const [on, theRoot, theGate] = [harness, root, gate];
|
|
2249
2440
|
const args = { name: first.name, input: first.input };
|
|
2250
2441
|
const call = { callId: WORKFLOW_FIRST_CALL, tool: LEARNED_WORKFLOW_TOOL, args };
|
|
@@ -2274,7 +2465,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2274
2465
|
if (!ended) {
|
|
2275
2466
|
// A deny before anything is written leaves the run its agent's, as if the workflow were not there.
|
|
2276
2467
|
const before = await spec.gate?.({ callId: call.callId, tool: call.tool, args });
|
|
2277
|
-
if (before === "deny" || typeof before === "object")
|
|
2468
|
+
if (before === "deny" || (typeof before === "object" && "deny" in before))
|
|
2278
2469
|
return undefined;
|
|
2279
2470
|
if (spec.inputOrigin)
|
|
2280
2471
|
await rec.input(spec.input, spec.inputOrigin);
|
|
@@ -2301,7 +2492,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2301
2492
|
// A CLI's record takes the call's start and end inside the wrapper; pi's step record here.
|
|
2302
2493
|
if (!record)
|
|
2303
2494
|
await rec.start(WORKFLOW_FIRST_CALL, LEARNED_WORKFLOW_TOOL, args, false);
|
|
2304
|
-
const got = await learned.call(args, { callId: WORKFLOW_FIRST_CALL, signal: stopAbort.signal });
|
|
2495
|
+
const got = await learned.call(args, { callId: WORKFLOW_FIRST_CALL, signal: stopAbort.signal, nested: servedNested(WORKFLOW_FIRST_CALL) });
|
|
2305
2496
|
answer = { text: got.text, isError: got.isError === true };
|
|
2306
2497
|
if (!record)
|
|
2307
2498
|
await rec.end(WORKFLOW_FIRST_CALL, stopAbort.signal.aborted ? "interrupted" : answer.isError ? "failed" : "done", answer.text);
|
|
@@ -2311,7 +2502,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2311
2502
|
return undefined;
|
|
2312
2503
|
answer = taken(answer);
|
|
2313
2504
|
const outcome = answer.isError ? "handed_back" : "answered";
|
|
2314
|
-
const data = { workflow: first.name, digest: first.digest, revision: first.revision, call: WORKFLOW_FIRST_CALL, outcome };
|
|
2505
|
+
const data = { workflow: first.name, digest: first.digest, ...(first.promotion !== undefined ? { promotion: first.promotion } : {}), revision: first.revision, call: WORKFLOW_FIRST_CALL, outcome };
|
|
2315
2506
|
await on.commit(async (tx) => {
|
|
2316
2507
|
if (outcome === "answered")
|
|
2317
2508
|
await tx.appendEntry(theRoot.id, { kind: KINDS.message, data: { role: "model", text: answer.text, at: now() } });
|
|
@@ -2350,6 +2541,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2350
2541
|
const cutBy = stopReason;
|
|
2351
2542
|
if (step === "park" && cutBy?.kind !== "command") {
|
|
2352
2543
|
await releaseHost(harness);
|
|
2544
|
+
await keepAtPark(harness, "workflow");
|
|
2353
2545
|
gate.seal(new Parked());
|
|
2354
2546
|
return { state: "parked" };
|
|
2355
2547
|
}
|
|
@@ -2376,7 +2568,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2376
2568
|
}
|
|
2377
2569
|
}
|
|
2378
2570
|
const placed = served !== undefined || followedUp || (session.state !== "idle" && !firstUnplaced);
|
|
2379
|
-
|
|
2571
|
+
// The end-of-run turn found open (lookingBackOpen), with no turn of this claim's sent before it: never recovered as
|
|
2572
|
+
// the job's; the run goes to its end-of-run step, on the job's end the claim that asked it kept (jobEndKept).
|
|
2573
|
+
const lookingBack = lookingBackOpen && !followedUp && served === undefined;
|
|
2574
|
+
if (served || followedUp || firstUnplaced || lookingBack) {
|
|
2380
2575
|
// The workflow answered, or handed back and its handback is the turn; the follow-up is the turn this claim runs,
|
|
2381
2576
|
// or there is none.
|
|
2382
2577
|
}
|
|
@@ -2395,8 +2590,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2395
2590
|
// The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
|
|
2396
2591
|
// its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold. None
|
|
2397
2592
|
// when the workflow answered: the run ends on its answer.
|
|
2398
|
-
// A feedback round (feedbackNow) asks no turn either: the run goes to its end-of-run turn.
|
|
2399
|
-
|
|
2593
|
+
// A feedback round (feedbackNow) asks no turn either: the run goes to its end-of-run turn. Nor does a claim that found
|
|
2594
|
+
// that turn open (lookingBack).
|
|
2595
|
+
const alone = served?.outcome === "answered" || (served?.outcome === "handed_back" && spec.workflowFirst?.replay === true) || feedbackNow !== undefined || lookingBack;
|
|
2400
2596
|
let turn = alone ? new Promise(() => { }) : placed ? session.turnEnd() : idleTurnOf(harness, root);
|
|
2401
2597
|
// Set on every way out of the loop below but parkOn's, which returns before it is read.
|
|
2402
2598
|
let data;
|
|
@@ -2405,15 +2601,26 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2405
2601
|
let parkOn;
|
|
2406
2602
|
/** The ask_person call the run waits on in its claim, while it does. */
|
|
2407
2603
|
let waitingOn;
|
|
2408
|
-
if (alone)
|
|
2604
|
+
if (alone && lookingBack)
|
|
2605
|
+
({ end: data, failedWith } = await jobEndKept(root));
|
|
2606
|
+
else if (alone)
|
|
2409
2607
|
data = { state: "ended" };
|
|
2410
2608
|
else
|
|
2411
2609
|
for (;;) {
|
|
2412
|
-
|
|
2610
|
+
let end = await Promise.race([turn.then((ended) => (ended === "lapsed" ? "lapsed" : "answered")), parking.then(() => "parked"), stopping.then(() => "stop"), harness.closed.then(() => "closed"), askCut.asked.then(() => "cut")]);
|
|
2413
2611
|
// Parked on a call held at the gate (a CLI's at its tool bridge): the answer that made the call may still be
|
|
2414
|
-
// streaming, and its booking lands before the claim goes (parkClaim).
|
|
2415
|
-
|
|
2416
|
-
|
|
2612
|
+
// streaming, and its booking lands before the claim goes (parkClaim). pi's calls already running beside it end
|
|
2613
|
+
// first (siblingsSettled), so their results are on the journal for the resume. A person's stop or cancel while
|
|
2614
|
+
// they do ends the run in its words, as it would have before the park.
|
|
2615
|
+
if (end === "parked" && spec.record === "loop")
|
|
2616
|
+
return await parkClaim(harness, gate, "approval");
|
|
2617
|
+
if (end === "parked") {
|
|
2618
|
+
parkPending = true;
|
|
2619
|
+
await siblingsSettled(harness, spec);
|
|
2620
|
+
if (stopReason?.kind !== "command")
|
|
2621
|
+
return await parkClaim(harness, gate, "approval");
|
|
2622
|
+
end = "stop";
|
|
2623
|
+
}
|
|
2417
2624
|
if (end === "closed" && fault && !stopReason && !deps.signal.aborted) {
|
|
2418
2625
|
await closeSession();
|
|
2419
2626
|
continue passes;
|
|
@@ -2491,9 +2698,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2491
2698
|
const park = spec.cap?.park(refusalOf(refused), raisedCapUsd ?? spec.cap.capUsd);
|
|
2492
2699
|
// Its pause and the run parked landed before pi heard of the refusal.
|
|
2493
2700
|
if (park?.outcome === "parked" && pausedAtRefusal)
|
|
2494
|
-
return await parkClaim(harness, gate);
|
|
2701
|
+
return await parkClaim(harness, gate, "refusal");
|
|
2495
2702
|
if (park?.outcome === "parked")
|
|
2496
|
-
return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
|
|
2703
|
+
return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words }, "refusal");
|
|
2497
2704
|
data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
|
|
2498
2705
|
}
|
|
2499
2706
|
else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
|
|
@@ -2627,20 +2834,16 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2627
2834
|
return await writeEnd(harness, root, gate, stopEnd(failingStop.cancel), [failingStop.commandId], await cutRows(claim, spec, "stopped"));
|
|
2628
2835
|
// The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
|
|
2629
2836
|
// writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
|
|
2630
|
-
|
|
2837
|
+
// The run's status is how its job's own turn ended (`data`), whatever the step spends after it: learning spend that
|
|
2838
|
+
// takes the run past its cap is the learning's (askEndOfRun reads overCap after each of its turns), never the run's.
|
|
2839
|
+
// That end is kept before the step's first ask, so a claim that finds its turn open ends the run on it (jobEndKept).
|
|
2840
|
+
if (!lookingBack)
|
|
2841
|
+
await keepJobEnd(harness, root, spec, data, failedWith);
|
|
2842
|
+
const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed", overCap);
|
|
2631
2843
|
if (step.kind === "stopped")
|
|
2632
2844
|
return await writeEnd(harness, root, gate, stopEnd(stopReason?.kind === "command" ? stopReason.cancel : undefined), [step.commandId], await cutRows(claim, spec, "stopped-looking"));
|
|
2633
2845
|
if (step.kind === "interrupted")
|
|
2634
2846
|
return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
|
|
2635
|
-
// The end-of-run turn is one more paid answer: one that passed the cap ends the run in the cap's words (overCap,
|
|
2636
|
-
// read again once its booking settled), as a job's answer that passed it does, never completed. An end already
|
|
2637
|
-
// failed keeps its own words.
|
|
2638
|
-
if (data.state !== "failed") {
|
|
2639
|
-
await bookingsSettled();
|
|
2640
|
-
const overAtEnd = await overCap();
|
|
2641
|
-
if (overAtEnd)
|
|
2642
|
-
data = { state: "failed", summary: overAtEnd };
|
|
2643
|
-
}
|
|
2644
2847
|
return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
|
|
2645
2848
|
}
|
|
2646
2849
|
}
|
|
@@ -2668,6 +2871,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2668
2871
|
heldNow = undefined;
|
|
2669
2872
|
channelNow = undefined;
|
|
2670
2873
|
handingBack = false;
|
|
2874
|
+
reflecting = false;
|
|
2875
|
+
learningRefused = undefined;
|
|
2671
2876
|
deps.live?.(() => undefined);
|
|
2672
2877
|
// A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
|
|
2673
2878
|
// A restart within the claim is no release. What it writes after a lost claim is refused by the fence, as any write.
|
|
@@ -2676,7 +2881,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2676
2881
|
}
|
|
2677
2882
|
}
|
|
2678
2883
|
/** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
|
|
2679
|
-
* `wrapUp`:
|
|
2884
|
+
* `wrapUp`: once the run has taken its share of the cap, the words every call the model makes is refused in (wrapUpText).
|
|
2680
2885
|
* `beforeAsk`: what goes on the record of a call the gate asks about, before its ask is written or read (a CLI's call
|
|
2681
2886
|
* through its tool bridge: its start, marked parked, so its row shows while it waits and reads before its approval). */
|
|
2682
2887
|
function preIntentGate(spec, hooks, wrapUp, beforeAsk) {
|
|
@@ -2690,14 +2895,24 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2690
2895
|
await hooks.beforeIntent(kernelCall);
|
|
2691
2896
|
// The cap's wrap-up, the same way: once the run has taken its share of the cap, every call the model makes is refused
|
|
2692
2897
|
// in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
|
|
2693
|
-
|
|
2694
|
-
|
|
2898
|
+
const wrapUpDeny = call.nested !== true ? await wrapUp() : undefined;
|
|
2899
|
+
if (wrapUpDeny !== undefined)
|
|
2900
|
+
return { deny: wrapUpDeny };
|
|
2695
2901
|
// A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
|
|
2696
2902
|
const replayed = call.replayed === true;
|
|
2697
|
-
const
|
|
2903
|
+
const given = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
|
|
2904
|
+
// An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape).
|
|
2905
|
+
const shown = typeof given === "object" && "ask" in given ? given.ask : undefined;
|
|
2906
|
+
let decision = shown ? "ask" : given;
|
|
2907
|
+
// A call nested in a learned_workflow call a person approved, of an MCP tool that call's card named: its ask is
|
|
2908
|
+
// answered by that approval, as the card they saw named it (never one built again now). Any other asks for itself.
|
|
2909
|
+
if (call.nested === true && decision === "ask" && learnedApprovedTools(await approvedCardOver(call.callId, spec.gate?.askedAs?.(LEARNED_WORKFLOW_TOOL) ?? LEARNED_WORKFLOW_TOOL)).has(tool))
|
|
2910
|
+
decision = "allow";
|
|
2698
2911
|
// Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
|
|
2699
2912
|
// an MCP call by its catalog name (tool) either way, never pi's wire name, and so are its call and its price.
|
|
2700
|
-
|
|
2913
|
+
// A script's computer op is asked about by the tool it is held to (RunGate.askedAs with its arguments: bash for its
|
|
2914
|
+
// shell, write or read for its files).
|
|
2915
|
+
const asked = spec.gate?.askedAs?.(tool, call.args) ?? tool;
|
|
2701
2916
|
// A call a person was asked about and has not answered, refused now because its tool is set to deny (a bare "deny",
|
|
2702
2917
|
// or the gate's own words for it): the deny answers the ask first (deniedBySetting), a deny of theirs standing. The
|
|
2703
2918
|
// model reads the gate's words (main's, from refusal-words.ts) either way.
|
|
@@ -2716,37 +2931,46 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2716
2931
|
// A call a person was asked about and has not answered, its setting at allow now: the setting answers the ask
|
|
2717
2932
|
// (allowedBySetting), and the call runs without asking the person again.
|
|
2718
2933
|
const bySetting = decision === "allow" && !!spec.gate && (await askStands(call.callId));
|
|
2934
|
+
// While pi's park waits for the calls already running beside it (siblingsSettled), no new one starts: it is held as the
|
|
2935
|
+
// parked call is, its intent never stored, and asked again on the resume. A call a running tool makes is that tool's,
|
|
2936
|
+
// let through.
|
|
2937
|
+
if (decision === "allow" && !bySetting && parkPending && call.nested !== true)
|
|
2938
|
+
return { park: true };
|
|
2719
2939
|
if (decision === "allow" && !bySetting)
|
|
2720
2940
|
return "allow";
|
|
2721
2941
|
// The card shows the call's input, and beside it what the gate says the call would do that the person approves too
|
|
2722
|
-
// (a learned workflow's MCP
|
|
2723
|
-
const
|
|
2724
|
-
// Shown first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES) still names them whatever the input's size.
|
|
2725
|
-
// The gate's own fields win over any of the same name in the call's input, which the model wrote.
|
|
2726
|
-
const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
|
|
2942
|
+
// (a learned workflow's MCP actions set to ask: the gate's `ask`).
|
|
2943
|
+
const args = cardOf(tool, shown, call.args);
|
|
2727
2944
|
// The call on the record before its ask (beforeAsk), with the input its model gave it.
|
|
2728
2945
|
await beforeAsk?.(call);
|
|
2729
2946
|
// Its price on the card: a catalog tool's (an MCP tool's, a monid endpoint's pinned price), else none.
|
|
2730
2947
|
const price = mcp?.priceOf(tool) ?? null;
|
|
2731
|
-
// Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the
|
|
2732
|
-
// learned workflow's MCP
|
|
2733
|
-
const
|
|
2734
|
-
const destructive = [asked, ...covered].some((name) => mcp?.effectOf(name) === "destructive");
|
|
2948
|
+
// Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the card's `mcp_calls`, a
|
|
2949
|
+
// learned workflow's MCP actions set to ask): that allow takes the second confirm too.
|
|
2950
|
+
const destructive = [asked, ...learnedApprovedTools(shown)].some((name) => mcp?.effectOf(name) === "destructive");
|
|
2735
2951
|
const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked, destructive);
|
|
2736
2952
|
if (answer === "park")
|
|
2737
2953
|
return { park: true };
|
|
2738
|
-
// A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
|
|
2739
|
-
// approved with it (host-calls.ts), as far as the card they approved named it: its ask as journaled, the card they
|
|
2740
|
-
// saw, never one built again now.
|
|
2741
|
-
if (answer.approved) {
|
|
2742
|
-
const seen = askedArgs.get(call.callId);
|
|
2743
|
-
approvedCalls.set(call.callId, seen && typeof seen === "object" && !Array.isArray(seen) ? seen : {});
|
|
2744
|
-
}
|
|
2745
2954
|
if (answer.approved)
|
|
2746
2955
|
return "allow";
|
|
2747
2956
|
return { deny: replayed ? refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown") : deniedText(asked, answer.note) };
|
|
2748
2957
|
};
|
|
2749
2958
|
}
|
|
2959
|
+
/** The card a person approved for the learned_workflow call that `callId` (`<outer>/<key>`, its key never holding a
|
|
2960
|
+
* "/") is nested in: the ask journaled under that call's own id, answered with an allow. Keyed to that one call, so a
|
|
2961
|
+
* card approved for any other call (an earlier call of the same workflow among them) never passes it. None when its
|
|
2962
|
+
* outer call was not asked as learned_workflow, or its ask was denied or not answered. */
|
|
2963
|
+
async function approvedCardOver(callId, learnedAs) {
|
|
2964
|
+
const at = callId.lastIndexOf("/");
|
|
2965
|
+
if (at <= 0)
|
|
2966
|
+
return undefined;
|
|
2967
|
+
const outer = callId.slice(0, at);
|
|
2968
|
+
const conversation = await harness.root(context);
|
|
2969
|
+
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
2970
|
+
const ask = findData(entries, KINDS.ask, (data) => data.callId === outer);
|
|
2971
|
+
const answer = ask && findData(entries, KINDS.answer, (data) => data.callId === outer);
|
|
2972
|
+
return ask?.tool === learnedAs && answer?.approved === true ? ask.args : undefined;
|
|
2973
|
+
}
|
|
2750
2974
|
/** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
|
|
2751
2975
|
* park (the ask entry with the run parked, in one commit). The ask is main's approval card: the call's input, when it
|
|
2752
2976
|
* was asked and its `price`; asked again on a resume, it is the same request. */
|
|
@@ -2754,9 +2978,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2754
2978
|
const conversation = await harness.root(context);
|
|
2755
2979
|
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
2756
2980
|
const first = findData(entries, KINDS.ask, (data) => data.callId === call.callId);
|
|
2757
|
-
// The card the person answers is the ask as first journaled: kept for the caller, which scopes an approval to it.
|
|
2758
2981
|
if (first)
|
|
2759
|
-
|
|
2982
|
+
askedCalls.add(call.callId);
|
|
2760
2983
|
const known = findData(entries, KINDS.answer, (data) => data.callId === call.callId);
|
|
2761
2984
|
if (known)
|
|
2762
2985
|
return known;
|
|
@@ -2768,8 +2991,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2768
2991
|
const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
|
|
2769
2992
|
if (first === undefined) {
|
|
2770
2993
|
// Asked and parked; or held as the parked call is, when another call of the round parked the run first.
|
|
2771
|
-
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
|
|
2994
|
+
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } })) {
|
|
2995
|
+
parkedCalls.add(call.callId);
|
|
2772
2996
|
parked();
|
|
2997
|
+
}
|
|
2773
2998
|
return "park";
|
|
2774
2999
|
}
|
|
2775
3000
|
for (;;) {
|
|
@@ -2788,8 +3013,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2788
3013
|
// no waiting call and was refused): the call is asked again and the run parks on it, so it never waits here
|
|
2789
3014
|
// holding the claim while it reads running.
|
|
2790
3015
|
if (delivered || refusals > 0) {
|
|
2791
|
-
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
|
|
3016
|
+
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } })) {
|
|
3017
|
+
parkedCalls.add(call.callId);
|
|
2792
3018
|
parked();
|
|
3019
|
+
}
|
|
2793
3020
|
return "park";
|
|
2794
3021
|
}
|
|
2795
3022
|
await new Promise((resolve) => (wakeInbox = resolve));
|
|
@@ -2829,10 +3056,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2829
3056
|
inbox.splice(inbox.indexOf(row), 1);
|
|
2830
3057
|
if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
|
|
2831
3058
|
return "park";
|
|
2832
|
-
//
|
|
2833
|
-
|
|
2834
|
-
if (first)
|
|
2835
|
-
askedArgs.set(call.callId, first.args);
|
|
3059
|
+
// A call whose ask stands (askStands): a person was asked about it.
|
|
3060
|
+
askedCalls.add(call.callId);
|
|
2836
3061
|
return data;
|
|
2837
3062
|
}
|
|
2838
3063
|
/** The answer to an ask a person was shown and has not answered, once its tool's setting reads deny: the deny answers it
|
|
@@ -2893,7 +3118,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2893
3118
|
return false;
|
|
2894
3119
|
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
2895
3120
|
const [theGate, theHarness] = [gate, harness];
|
|
2896
|
-
if (!theGate || !theHarness || theGate.sealed)
|
|
3121
|
+
if (!theGate || !theHarness || theGate.sealed || parkPending)
|
|
2897
3122
|
return "later";
|
|
2898
3123
|
try {
|
|
2899
3124
|
const conversation = await theHarness.root(context);
|
|
@@ -2956,7 +3181,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2956
3181
|
parkedAt.catch(() => undefined);
|
|
2957
3182
|
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.personAsked, data: { callId } }), context);
|
|
2958
3183
|
await parkedAt;
|
|
2959
|
-
return parkClaim(on, theGate);
|
|
3184
|
+
return parkClaim(on, theGate, "answer");
|
|
2960
3185
|
}
|
|
2961
3186
|
/** A CLI's turn cut at its question to the person (TurnCut): its request after the question held, the turn is stopped
|
|
2962
3187
|
* (interrupt), the held request refused once the stop is under way, and the turn the session still reads open settled,
|
|
@@ -2998,6 +3223,24 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2998
3223
|
return { status: "completed" };
|
|
2999
3224
|
return turnOfRequest(on, conversation, last.requestId);
|
|
3000
3225
|
}
|
|
3226
|
+
/** How the job's own turn ended (`data`, and a CLI's error answer `failedWith`), as this claim decided it, kept on the
|
|
3227
|
+
* root before the end-of-run step asks its first turn (KINDS.jobEnd), for a run with a step to ask (stepOf). Its
|
|
3228
|
+
* summary is cut of every secret the runner holds, as every summary is when served. */
|
|
3229
|
+
async function keepJobEnd(on, conversation, spec, data, failedWith) {
|
|
3230
|
+
if (!stepOf(spec))
|
|
3231
|
+
return;
|
|
3232
|
+
const end = data.summary !== undefined && deps.redact ? { ...data, summary: deps.redact(data.summary) } : data;
|
|
3233
|
+
const kept = { end, ...(failedWith !== undefined ? { failedWith } : {}) };
|
|
3234
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.jobEnd, data: kept }), context);
|
|
3235
|
+
}
|
|
3236
|
+
/** The job's end for a claim that found the end-of-run turn open (lookingBackOpen): the newest keepJobEnd kept (a
|
|
3237
|
+
* follow-up's round keeps its own), never worked out again. */
|
|
3238
|
+
async function jobEndKept(conversation) {
|
|
3239
|
+
const kept = (await entriesOf(gate.journal, conversation.id, context)).filter((entry) => entry.kind === KINDS.jobEnd).at(-1);
|
|
3240
|
+
if (!kept)
|
|
3241
|
+
throw new Error("the end-of-run turn is open, but the job's end was never kept before it");
|
|
3242
|
+
return kept.data;
|
|
3243
|
+
}
|
|
3001
3244
|
/** How the turn of the root's submission `requestId` ended (a steer of the idle session, which no session tracks). */
|
|
3002
3245
|
async function turnOfRequest(on, conversation, requestId) {
|
|
3003
3246
|
const found = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
@@ -3119,18 +3362,34 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3119
3362
|
mcp?.release();
|
|
3120
3363
|
mcp = undefined;
|
|
3121
3364
|
// The pass's resources go once nothing more is written through them (AdapterRunSpec.release), once each.
|
|
3365
|
+
// A park's keeps the run's computer (keepAtPark).
|
|
3122
3366
|
const release = releaseNow;
|
|
3367
|
+
const parked = parkedNow;
|
|
3123
3368
|
releaseNow = undefined;
|
|
3124
|
-
|
|
3369
|
+
parkedNow = undefined;
|
|
3370
|
+
await release?.(parked ? { parked } : {}).catch((error) => console.warn(`[runner] its run's release failed: ${said(error)}`));
|
|
3371
|
+
}
|
|
3372
|
+
/** What a round's first ask kept, read before the hook can skip or close its resumed turn: the CLI's record, or pi's
|
|
3373
|
+
* durable root entry. A different round's snapshot never prices this one. */
|
|
3374
|
+
async function keptOf(claim) {
|
|
3375
|
+
const record = cliRecord;
|
|
3376
|
+
const entries = !record && gate && root ? await entriesOf(gate.journal, root.id, context) : [];
|
|
3377
|
+
return (round) => {
|
|
3378
|
+
const requestId = reflectRequestId(claim.runId, false, round);
|
|
3379
|
+
if (record)
|
|
3380
|
+
return record.keptOf(requestId);
|
|
3381
|
+
const first = entries.find((entry) => entry.kind === KINDS.endOfRunKept && entry.data?.requestId === requestId);
|
|
3382
|
+
const kept = first?.data?.kept;
|
|
3383
|
+
return kept && typeof kept === "object" && !Array.isArray(kept) ? kept : undefined;
|
|
3384
|
+
};
|
|
3125
3385
|
}
|
|
3126
|
-
/** What round `round`'s end-of-run turn kept as it was first asked (EndOfRunTurn's keptOf), on the CLI's record. */
|
|
3127
|
-
const keptOf = (claim) => (round) => cliRecord?.keptOf(reflectRequestId(claim.runId, false, round));
|
|
3128
3386
|
/** The run's end-of-run step: its spec's (AdapterRunSpec.endOfRun) when it has one, else the loop's deps'. */
|
|
3129
3387
|
const stepOf = (spec) => spec.endOfRun ?? deps.endOfRun;
|
|
3130
3388
|
/** The end-of-run step (stepOf: the spec's, else LoopDeps.endOfRun), asked once: the rows to stage with the end; `stopped` when a person's stop
|
|
3131
3389
|
* came during it; `interrupted` when the claim was lost or the runner is closing (no end is written, and the next claim
|
|
3132
|
-
* asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it.
|
|
3133
|
-
|
|
3390
|
+
* asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it. `over`:
|
|
3391
|
+
* the claim's overCap, read after each turn the step asks (askEndOfRun). */
|
|
3392
|
+
async function endOfRunStep(claim, spec, outcome, over) {
|
|
3134
3393
|
const cut = () => {
|
|
3135
3394
|
if (stopReason?.kind === "command")
|
|
3136
3395
|
return { kind: "stopped", commandId: stopReason.commandId };
|
|
@@ -3143,8 +3402,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3143
3402
|
return { kind: "rows", also: [] };
|
|
3144
3403
|
if (!spec.agentId)
|
|
3145
3404
|
throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
|
|
3405
|
+
// Every request from here is learning's, between the step's asks too, until the claim ends (reflecting).
|
|
3406
|
+
reflecting = true;
|
|
3146
3407
|
try {
|
|
3147
|
-
const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: keptOf(claim) });
|
|
3408
|
+
const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
|
|
3148
3409
|
return cut() ?? { kind: "rows", also: rows?.also ?? [] };
|
|
3149
3410
|
}
|
|
3150
3411
|
catch (error) {
|
|
@@ -3162,7 +3423,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3162
3423
|
let timer;
|
|
3163
3424
|
const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), CUT_STEP_MS)));
|
|
3164
3425
|
try {
|
|
3165
|
-
const
|
|
3426
|
+
const pending = async () => step({ runId: claim.runId, agentId: spec.agentId, claim, outcome: "failed", cut, signal: deps.signal, ask: refuse, keptOf: await keptOf(claim) });
|
|
3427
|
+
const rows = await Promise.race([pending(), late]);
|
|
3166
3428
|
if (rows === "late") {
|
|
3167
3429
|
console.warn(`[runner] ${claim.runId}: its end-of-run step gave no answer within ${CUT_STEP_MS / 1000} s; the end is written without it`);
|
|
3168
3430
|
return [];
|
|
@@ -3194,8 +3456,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3194
3456
|
/** The end-of-run turn: one more turn through the run's session, its request id one per round of the run (a repeat is
|
|
3195
3457
|
* answered from its submission, so a later claim never asks the model again; a follow-up's end is the next `round`,
|
|
3196
3458
|
* asked anew), its writes under work/.learning/ refused while it runs. `again`: its re-ask, a request of its own (one
|
|
3197
|
-
* per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why.
|
|
3198
|
-
|
|
3459
|
+
* per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. `over`:
|
|
3460
|
+
* the claim's overCap, read once the turn's booking settled. */
|
|
3461
|
+
async function askEndOfRun(claim, over, prompt, deadlineMs, again = false, round = 1, keep, step) {
|
|
3199
3462
|
if (!session || !harness || !gate || !root)
|
|
3200
3463
|
throw new Error("the run's session is not open");
|
|
3201
3464
|
const on = harness;
|
|
@@ -3212,11 +3475,12 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3212
3475
|
const seen = servedNow && specNow ? { job: specNow.input, served: { workflow: servedNow.workflow, answer: cut(servedNow.answer) } } : undefined;
|
|
3213
3476
|
prompt = `${feedbackAsk({ ...feedbackNow, text: cut(feedbackNow.text) }, seen)}\n\n${prompt}`;
|
|
3214
3477
|
}
|
|
3215
|
-
reflecting = true;
|
|
3216
3478
|
let timer;
|
|
3217
3479
|
try {
|
|
3218
|
-
// A
|
|
3219
|
-
|
|
3480
|
+
// A turn already answered (an earlier claim's) is read from its submission; a CLI's record answers one it already
|
|
3481
|
+
// wrote from it too, as pi does: its CLI is never asked twice.
|
|
3482
|
+
const prior = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
3483
|
+
const known = theRecord ? prior : undefined;
|
|
3220
3484
|
// How this claim's turn ended; a turn answered before reads as its submission says.
|
|
3221
3485
|
let turnStatus = "completed";
|
|
3222
3486
|
// What the turn's first ask kept (`keep`), an earlier claim's when it asked first: every answer carries it.
|
|
@@ -3240,6 +3504,20 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3240
3504
|
turnStatus = end.status;
|
|
3241
3505
|
await theRecord?.answered(requestId, prompt, end.status);
|
|
3242
3506
|
}
|
|
3507
|
+
// A turn the cap refused a request of (this claim's, or the one a takeover found open: lookingBackOpen) fails in the
|
|
3508
|
+
// refusal's words: the learning is dropped for the cap's room (reflect-hook.ts CAP_REFUSAL), the run never parked.
|
|
3509
|
+
const capped = prior?.status === "done" ? undefined : learningRefused;
|
|
3510
|
+
if (capped) {
|
|
3511
|
+
learningRefused = undefined;
|
|
3512
|
+
return withKept({ failed: { code: "refused", message: capped.refuse } });
|
|
3513
|
+
}
|
|
3514
|
+
// The run's booked spend once this turn's settled (its cut requests at their worst case, an earlier claim's too): past
|
|
3515
|
+
// the cap, the turn fails in the cap's words (overCap), and the learning is dropped as a refusal drops it
|
|
3516
|
+
// (reflect-hook.ts CAP_REFUSAL: no_budget), its spend still booked. The run keeps the end its job's turn gave it.
|
|
3517
|
+
await bookingsSettled();
|
|
3518
|
+
const passed = await over();
|
|
3519
|
+
if (passed)
|
|
3520
|
+
return withKept({ failed: { code: "refused", message: passed } });
|
|
3243
3521
|
const record = await on.commit((tx) => tx.submissionByRequest(conversation.id, requestId), context);
|
|
3244
3522
|
if (turnStatus !== "completed" || record?.status !== "done")
|
|
3245
3523
|
return withKept({ failed: { code: "unanswered", message: "the end-of-run turn gave no answer" } });
|
|
@@ -3248,49 +3526,152 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3248
3526
|
}
|
|
3249
3527
|
finally {
|
|
3250
3528
|
clearTimeout(timer);
|
|
3251
|
-
reflecting = false;
|
|
3252
3529
|
}
|
|
3253
3530
|
}
|
|
3254
3531
|
/** The end's patch from the run's spec (AdapterRunSpec.endPatch), bounded (END_PATCH_MS): late or failing, the end says
|
|
3255
3532
|
* its cost and metrics are unknown (END_PATCH_UNKNOWN). */
|
|
3256
3533
|
async function endPatchOf(data) {
|
|
3257
|
-
|
|
3534
|
+
const spec = specNow;
|
|
3535
|
+
if (!spec?.endPatch && !spec?.endCost)
|
|
3258
3536
|
return {};
|
|
3259
3537
|
let timer;
|
|
3260
|
-
const boundMs =
|
|
3538
|
+
const boundMs = spec.endPatchMs ?? END_PATCH_MS;
|
|
3261
3539
|
const late = new Promise((resolve) => (timer = setTimeout(() => resolve("late"), boundMs)));
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3540
|
+
// The cost, read apart (AdapterRunSpec.endCost): a patch whose metrics run late or fail never takes it with them. A
|
|
3541
|
+
// read that fails is read again within the same bound (END_COST_TRIES): the stored cost is every reader's answer
|
|
3542
|
+
// (the list, the view, usage), so a null there is kept only when the booking could not be read at all.
|
|
3543
|
+
const endCost = spec.endCost;
|
|
3544
|
+
const cost = endCost
|
|
3545
|
+
? readAgain(endCost, late, (error, tries, last) => console.warn(last ? `[runner] its end's cost failed ${tries} times, last: ${said(error)}; the end is written with its cost unknown` : `[runner] its end's cost failed: ${said(error)}; read again`)).then((answer) => {
|
|
3546
|
+
if (answer === "late")
|
|
3547
|
+
console.warn(`[runner] its end's cost gave no answer within ${boundMs / 1000} s; the end is written with its cost unknown`);
|
|
3548
|
+
return answer === "late" || answer === "failed" ? { costUsd: null, costUpperBound: false } : answer;
|
|
3549
|
+
})
|
|
3550
|
+
: undefined;
|
|
3551
|
+
const patched = async () => {
|
|
3552
|
+
if (!spec.endPatch)
|
|
3553
|
+
return {};
|
|
3554
|
+
try {
|
|
3555
|
+
const patch = await Promise.race([spec.endPatch(data), late]);
|
|
3556
|
+
if (patch === "late") {
|
|
3557
|
+
console.warn(`[runner] its end's patch gave no answer within ${boundMs / 1000} s; the end is written with its ${cost ? "metrics" : "cost and metrics"} unknown`);
|
|
3558
|
+
return END_PATCH_UNKNOWN;
|
|
3559
|
+
}
|
|
3560
|
+
return patch ?? {};
|
|
3561
|
+
}
|
|
3562
|
+
catch (error) {
|
|
3563
|
+
console.warn(`[runner] its end's patch failed: ${said(error)}; the end is written with its ${cost ? "metrics" : "cost and metrics"} unknown`);
|
|
3266
3564
|
return END_PATCH_UNKNOWN;
|
|
3267
3565
|
}
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
return END_PATCH_UNKNOWN;
|
|
3566
|
+
};
|
|
3567
|
+
try {
|
|
3568
|
+
const [patch, read] = await Promise.all([patched(), cost]);
|
|
3569
|
+
return read ? { ...patch, ...read } : patch;
|
|
3273
3570
|
}
|
|
3274
3571
|
finally {
|
|
3275
3572
|
clearTimeout(timer);
|
|
3276
3573
|
}
|
|
3277
3574
|
}
|
|
3278
3575
|
/** The run parked at its cap: its pending budget as an agentrun.budget entry, in one commit with the run parked in the
|
|
3279
|
-
* cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it.
|
|
3280
|
-
|
|
3576
|
+
* cap's words (as the ask park's entry and state), and the loop ends parked: a raise row wakes it. `cause`: parked again
|
|
3577
|
+
* at the cap on a resume, or at a refusal the turn ended on. */
|
|
3578
|
+
async function parkAtCap(on, conversation, theGate, data, cause) {
|
|
3281
3579
|
await pauseAtCap(on, conversation, theGate, data);
|
|
3282
|
-
return parkClaim(on, theGate);
|
|
3580
|
+
return parkClaim(on, theGate, cause);
|
|
3581
|
+
}
|
|
3582
|
+
/** Waits, at most the spec's parkSiblingsMs (PARK_SIBLINGS_MS), until no call pi started beside a parked one is still
|
|
3583
|
+
* running: a model call of the same answer (its assistant entry) past its stored intent. Each one's result is then on the
|
|
3584
|
+
* journal before the park seals it, and the resume hands it to the model with the parked call's answer, never as a call
|
|
3585
|
+
* cut short. Not waited on: a call held before its intent (the parked one, any held with it), the parked call itself
|
|
3586
|
+
* when it was asked after its intent (a replay-safe rerun), and every call it is nested in (a script or a workflow node
|
|
3587
|
+
* waiting on it), nor any call of another answer. A stop, a lost claim or a closed Harness ends the wait at once. Past
|
|
3588
|
+
* the bound the seal cuts what still runs, as before, and the model reads it interrupted. pi's alone: a CLI's park
|
|
3589
|
+
* (spec.record "loop") lets its claim go at once, and its resume settles a call that ended (resumeUnstartedCalls). */
|
|
3590
|
+
async function siblingsSettled(on, spec) {
|
|
3591
|
+
const until = Date.now() + (spec.parkSiblingsMs ?? PARK_SIBLINGS_MS);
|
|
3592
|
+
let over = false;
|
|
3593
|
+
let end = () => { };
|
|
3594
|
+
const ended = new Promise((resolve) => (end = resolve)).then(() => {
|
|
3595
|
+
over = true;
|
|
3596
|
+
});
|
|
3597
|
+
// Its own listener on the claim's signal, taken off on every way out (settled, past the bound, sealed): a loop leaves
|
|
3598
|
+
// nothing on the signal it was lent. The stop and the Harness's close are promises, which hold nothing on it.
|
|
3599
|
+
const onAbort = () => end();
|
|
3600
|
+
if (deps.signal.aborted)
|
|
3601
|
+
end();
|
|
3602
|
+
else
|
|
3603
|
+
deps.signal.addEventListener("abort", onAbort, { once: true });
|
|
3604
|
+
void stopping.then(() => end());
|
|
3605
|
+
void on.closed.then(() => end(), () => end());
|
|
3606
|
+
try {
|
|
3607
|
+
while (!over && !gate?.sealed && Date.now() < until) {
|
|
3608
|
+
let tasks;
|
|
3609
|
+
try {
|
|
3610
|
+
({ tasks } = await on.inspect(context));
|
|
3611
|
+
}
|
|
3612
|
+
catch {
|
|
3613
|
+
return;
|
|
3614
|
+
}
|
|
3615
|
+
if (siblingsRunning(tasks).length === 0)
|
|
3616
|
+
return;
|
|
3617
|
+
let timer;
|
|
3618
|
+
await Promise.race([ended, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, Math.min(SIBLINGS_POLL_MS, until - Date.now())))))]);
|
|
3619
|
+
clearTimeout(timer);
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
finally {
|
|
3623
|
+
deps.signal.removeEventListener("abort", onAbort);
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
/** siblingsSettled's read of the Harness's live tasks: the model calls past their intent that share an answer with a
|
|
3627
|
+
* call this claim parked on, less that call and every call it is nested in. */
|
|
3628
|
+
function siblingsRunning(tasks) {
|
|
3629
|
+
const calls = tasks.map((task) => task.record).filter((record) => record.kind === ToolTask.definition.name);
|
|
3630
|
+
const byId = new Map(calls.map((record) => [String(record.id), record]));
|
|
3631
|
+
const inputOf = (record) => (record.input ?? {});
|
|
3632
|
+
const answers = new Set();
|
|
3633
|
+
const holding = new Set();
|
|
3634
|
+
for (const record of calls) {
|
|
3635
|
+
const input = inputOf(record);
|
|
3636
|
+
if (!parkedCalls.has((input.kind === "nested" ? input.call?.id : input.callId) ?? ""))
|
|
3637
|
+
continue;
|
|
3638
|
+
// The parked call and each call it is nested in, up to the model's call that holds it, whose answer it shares.
|
|
3639
|
+
for (let at = record; at; at = byId.get(String(inputOf(at).parent ?? at.owner ?? ""))) {
|
|
3640
|
+
holding.add(String(at.id));
|
|
3641
|
+
const own = inputOf(at);
|
|
3642
|
+
if (own.kind !== "nested" && own.assistant !== undefined)
|
|
3643
|
+
answers.add(own.assistant);
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
return calls
|
|
3647
|
+
.filter((record) => {
|
|
3648
|
+
const input = inputOf(record);
|
|
3649
|
+
const phase = record.state.checkpoint?.phase;
|
|
3650
|
+
return input.kind !== "nested" && input.assistant !== undefined && answers.has(input.assistant) && !holding.has(String(record.id)) && phase === "execute";
|
|
3651
|
+
})
|
|
3652
|
+
.map((record) => String(record.id));
|
|
3283
3653
|
}
|
|
3284
3654
|
/** A park's release of the claim, as the end's: the tool host let go first (a browser's release, booked under the live
|
|
3285
3655
|
* claim), then every paid request the session admitted booked (bookingsSettled), then the journal sealed. A CLI turn
|
|
3286
3656
|
* the park cuts (its call held at the tool bridge) may still be streaming its answer: closed under it, its booking
|
|
3287
3657
|
* would be lost and the next claim would book the turn cut, at an unknown price. Past the bound, it is that cut. */
|
|
3288
|
-
async function parkClaim(on, theGate) {
|
|
3658
|
+
async function parkClaim(on, theGate, cause) {
|
|
3289
3659
|
await releaseHost(on);
|
|
3290
3660
|
await bookingsSettled();
|
|
3661
|
+
await keepAtPark(on, cause);
|
|
3291
3662
|
theGate.seal(new Parked());
|
|
3292
3663
|
return { state: "parked" };
|
|
3293
3664
|
}
|
|
3665
|
+
/** At a park for `cause`, before its seal: a pass whose spec keeps its computer (AdapterRunSpec.keptWords) has it kept
|
|
3666
|
+
* for the resume at its release (closeSession), once the run's timeline says so, for the person deciding; its owner's
|
|
3667
|
+
* live view is closed saying the cause. A write that fails (the fence's refusal: a lost claim, whose run a later claim
|
|
3668
|
+
* may hold already) keeps nothing: the computer goes as at the run's end. */
|
|
3669
|
+
async function keepAtPark(on, cause) {
|
|
3670
|
+
const summary = specNow?.keptWords;
|
|
3671
|
+
if (!summary)
|
|
3672
|
+
return;
|
|
3673
|
+
parkedNow = await on.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: HOST_PHASE, data: { summary, at: Date.now() } }), context).then(() => cause, () => undefined);
|
|
3674
|
+
}
|
|
3294
3675
|
/** The run's pause at its cap: its agentrun.budget entry, in one commit with the run parked in the cap's words. */
|
|
3295
3676
|
async function pauseAtCap(on, conversation, theGate, data) {
|
|
3296
3677
|
const parkedAt = theGate.expect(writesEntry(KINDS.budget), { run: { state: "parked", summary: data.words } });
|
|
@@ -3306,8 +3687,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3306
3687
|
await parkedAt;
|
|
3307
3688
|
}
|
|
3308
3689
|
/** Waits, at most CLOSE_MS, until every paid request the session admitted is booked: a person's stop is booked at what
|
|
3309
|
-
* streamed once the session's proxy sees its upstream end.
|
|
3310
|
-
*
|
|
3690
|
+
* streamed once the session's proxy sees its upstream end. Then, for a booking whose write has begun, as long as that
|
|
3691
|
+
* write takes (bookingWriteMs). Past the bounds the end is written anyway, and a request left unbooked reads at its
|
|
3692
|
+
* hold and bound, the worst it can have cost, and the run's cost unknown: never a known figure that leaves it out. */
|
|
3311
3693
|
async function bookingsSettled() {
|
|
3312
3694
|
if (unbooked === 0)
|
|
3313
3695
|
return;
|
|
@@ -3315,6 +3697,15 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3315
3697
|
let timer;
|
|
3316
3698
|
await Promise.race([new Promise((resolve) => bookedAll.push(resolve)), new Promise((resolve) => (timer = setTimeout(resolve, CLOSE_MS)))]);
|
|
3317
3699
|
clearTimeout(timer);
|
|
3700
|
+
// A booking whose write has begun (its request answered) is waited for as long as its write takes, bounded
|
|
3701
|
+
// (BOOKING_WRITE_MS): written after the end, it would be fenced and lost, and the run's cost read unknown for good.
|
|
3702
|
+
if (bookingsWriting === 0)
|
|
3703
|
+
return;
|
|
3704
|
+
const boundMs = specNow?.bookingWriteMs ?? BOOKING_WRITE_MS;
|
|
3705
|
+
const written = await Promise.race([new Promise((resolve) => writtenAll.push(() => resolve(true))), new Promise((resolve) => (timer = setTimeout(() => resolve(false), boundMs)))]);
|
|
3706
|
+
clearTimeout(timer);
|
|
3707
|
+
if (!written)
|
|
3708
|
+
console.warn(`[runner] ${bookingsWriting} paid request booking(s) still being written after ${boundMs / 1000} s; going on without them: each reads at its hold, and the run's cost unknown`);
|
|
3318
3709
|
}
|
|
3319
3710
|
/** The run's timeline says it went on after its runner was lost (RUN_RESUMED, `after: runner_lost`): one root entry,
|
|
3320
3711
|
* no run patch. A journal sealed meanwhile (the claim lost again, a shutdown) refuses it, and the loop goes on as it
|
|
@@ -3351,6 +3742,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3351
3742
|
// their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
|
|
3352
3743
|
await releaseHost(on);
|
|
3353
3744
|
await bookingsSettled();
|
|
3745
|
+
// The pull request's checkout goes before the end is committed: a run that reads final never still holds its code.
|
|
3746
|
+
await specNow?.endCheckout?.();
|
|
3354
3747
|
const patch = await endPatchOf(base);
|
|
3355
3748
|
// A person's stop that came while the end waited (its host's release, its bookings, its patch's reads, up to
|
|
3356
3749
|
// END_PATCH_MS on a busy store) is this end's, as a stop during any earlier await of the end path is: the run ends
|
|
@@ -3360,7 +3753,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3360
3753
|
const lateStop = late?.kind === "command" && !take.includes(late.commandId) ? late : undefined;
|
|
3361
3754
|
if (lateStop)
|
|
3362
3755
|
take = [...take, lateStop.commandId];
|
|
3363
|
-
const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
|
|
3756
|
+
const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
|
|
3364
3757
|
const run = {
|
|
3365
3758
|
state: data.state,
|
|
3366
3759
|
// An end's summary is its own: with none, a wait's summary the row still says (a question's, a hand-over's: HELD_WAITS
|
|
@@ -3368,7 +3761,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3368
3761
|
...(data.summary ? { summary: data.summary } : {}),
|
|
3369
3762
|
...(!data.summary ? { summary: null } : {}),
|
|
3370
3763
|
...(data.outcome !== undefined ? { outcome: data.outcome } : {}),
|
|
3371
|
-
...(data.costUsd !== undefined ? { costUsd: data.costUsd } : {}),
|
|
3764
|
+
...(data.costUsd !== undefined ? { costUsd: data.costUsd, costUpperBound: data.costUpperBound === true } : {}),
|
|
3372
3765
|
...(data.metrics !== undefined ? { metrics: data.metrics } : {}),
|
|
3373
3766
|
};
|
|
3374
3767
|
// A person's stop or cancel withdraws every call still waiting for its answer, in the end's own commit: the approval
|
|
@@ -3383,6 +3776,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3383
3776
|
const ends = cliRecord ?? (await openCliRecord(on, theGate.journal, context, now, undefined, true));
|
|
3384
3777
|
const recordEnds = ends.unsentParked();
|
|
3385
3778
|
const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
|
|
3779
|
+
// A call that only nests calls (a harness's own: Codex's `exec`) still open when the run ends: nothing will end it now
|
|
3780
|
+
// (a stop while its call waited, a crash whose next drive never resumed its CLI's thread), so it ends with the run,
|
|
3781
|
+
// interrupted, after the rows of its calls (their withdrawals above it in this commit). Its own end on its way is
|
|
3782
|
+
// written first. Marked `withRun`: a park or a stop failed nothing, so its row reads interrupted, never failed.
|
|
3783
|
+
while (ownWrites.size > 0)
|
|
3784
|
+
await Promise.allSettled([...ownWrites]);
|
|
3785
|
+
const cutOpen = ends.openNests();
|
|
3386
3786
|
const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
|
|
3387
3787
|
// A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
|
|
3388
3788
|
ended.catch(() => undefined);
|
|
@@ -3392,6 +3792,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3392
3792
|
await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
|
|
3393
3793
|
for (const callId of recordEnds)
|
|
3394
3794
|
await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
|
|
3795
|
+
for (const callId of cutOpen)
|
|
3796
|
+
await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "interrupted", withRun: true, at: now() } });
|
|
3395
3797
|
// A turn the run ends while it is open (a stop or cancel cut it, or the run failed in it) ends with the run.
|
|
3396
3798
|
if (cliRecord?.openTurn())
|
|
3397
3799
|
await tx.appendEntry(conversation.id, { kind: KINDS.turnEnd, data: { status: data.state === "failed" ? "failed" : data.state === "stopped" ? "interrupted" : "completed" } });
|
|
@@ -3408,6 +3810,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
3408
3810
|
await ended;
|
|
3409
3811
|
for (const callId of recordEnds)
|
|
3410
3812
|
ends.noteEnd(callId, "refused", notRun);
|
|
3813
|
+
for (const callId of cutOpen)
|
|
3814
|
+
ends.noteEnd(callId, "interrupted");
|
|
3411
3815
|
return data.state === "failed" ? { state: "failed", error: { code: "run-failed", message: data.summary ?? "the run failed" } } : { state: data.state };
|
|
3412
3816
|
}
|
|
3413
3817
|
return {
|