@parcha/agentrun-serve 0.1.0-beta.36 → 0.1.0-beta.37
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 +170 -0
- package/README.md +158 -52
- package/dist/attach-conformance-cli.d.ts +1 -0
- package/dist/attach-conformance-cli.js +18 -0
- package/dist/attach-conformance.d.ts +25 -0
- package/dist/attach-conformance.js +343 -0
- package/dist/browser-cost.d.ts +1 -1
- package/dist/browser-live.d.ts +20 -8
- package/dist/browser-live.js +50 -27
- package/dist/cap.d.ts +0 -17
- package/dist/cap.js +0 -91
- package/dist/catalog.d.ts +1 -12
- package/dist/catalog.js +3 -33
- package/dist/cli.js +13 -4
- package/dist/composio-preset.d.ts +36 -0
- package/dist/composio-preset.js +179 -0
- package/dist/computer-attach.d.ts +125 -0
- package/dist/computer-attach.js +330 -0
- package/dist/computer-calls.d.ts +48 -0
- package/dist/computer-calls.js +126 -0
- package/dist/computer-channel.d.ts +57 -0
- package/dist/computer-channel.js +115 -0
- package/dist/computer-commands.d.ts +1 -1
- package/dist/computer-held-routes.d.ts +35 -0
- package/dist/computer-held-routes.js +106 -0
- package/dist/computer-held.d.ts +48 -0
- package/dist/computer-held.js +87 -0
- package/dist/computer-keys.d.ts +21 -1
- package/dist/computer-keys.js +53 -11
- package/dist/computer-live.d.ts +160 -0
- package/dist/computer-live.js +643 -0
- package/dist/computer-view.d.ts +13 -0
- package/dist/computer-view.js +50 -3
- package/dist/computer-viewer.d.ts +6 -0
- package/dist/computer-viewer.js +297 -0
- package/dist/computers.d.ts +33 -7
- package/dist/computers.js +50 -8
- package/dist/console/assets/index-Cn6JX1uH.js +563 -0
- package/dist/console/assets/index-DRN62V5v.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/faux-computers.d.ts +9 -20
- package/dist/faux-computers.js +53 -25
- package/dist/github-connection.d.ts +10 -2
- package/dist/github-connection.js +65 -2
- package/dist/github-faux.js +1 -1
- package/dist/graph-view.d.ts +1 -1
- package/dist/harness.d.ts +1 -0
- package/dist/harness.js +35 -1
- package/dist/host-tools.d.ts +1 -1
- package/dist/hosted-search.d.ts +5 -4
- package/dist/hosted-search.js +2 -7
- package/dist/import-sources.d.ts +10 -0
- package/dist/import-sources.js +44 -2
- package/dist/import.d.ts +3 -3
- package/dist/import.js +37 -6
- package/dist/learn/check.d.ts +4 -1
- package/dist/learn/check.js +1 -1
- package/dist/learn/commit.d.ts +4 -2
- package/dist/learn/commit.js +5 -5
- package/dist/learn/folder.d.ts +6 -0
- package/dist/learn/folder.js +4 -1
- package/dist/learn/general.d.ts +66 -0
- package/dist/learn/general.js +73 -0
- package/dist/learn/grade.d.ts +4 -0
- package/dist/learn/grade.js +22 -1
- package/dist/learn/reflect.d.ts +10 -1
- package/dist/learn/reflect.js +14 -4
- package/dist/learn/skills.d.ts +33 -5
- package/dist/learn/skills.js +53 -7
- package/dist/learned-workflow.d.ts +24 -0
- package/dist/learned-workflow.js +66 -3
- package/dist/learning-batch.d.ts +283 -0
- package/dist/learning-batch.js +574 -0
- package/dist/learning-evals.d.ts +33 -0
- package/dist/learning-evals.js +98 -0
- package/dist/learning-routes.d.ts +25 -2
- package/dist/learning-routes.js +39 -6
- package/dist/learning-words.d.ts +6 -0
- package/dist/learning-words.js +6 -0
- package/dist/learning.d.ts +28 -15
- package/dist/learning.js +84 -44
- package/dist/live/stream.js +6 -3
- package/dist/live/translate.d.ts +4 -3
- package/dist/live/translate.js +8 -4
- package/dist/live-reach.d.ts +37 -0
- package/dist/live-reach.js +62 -0
- package/dist/mcp-gateway.d.ts +9 -0
- package/dist/mcp-gateway.js +60 -11
- package/dist/mcp-oauth.d.ts +57 -7
- package/dist/mcp-oauth.js +133 -18
- package/dist/mcp-private-hosts.d.ts +4 -4
- package/dist/mcp-private-hosts.js +20 -12
- package/dist/mcp-probe.d.ts +19 -2
- package/dist/mcp-probe.js +44 -9
- package/dist/mcp-secret-writes.js +4 -0
- package/dist/mcp-servers-store.d.ts +38 -15
- package/dist/mcp-servers-store.js +112 -20
- package/dist/mcp-store.d.ts +10 -4
- package/dist/mcp-store.js +17 -6
- package/dist/model-form.d.ts +26 -0
- package/dist/model-form.js +80 -0
- package/dist/model.js +23 -10
- package/dist/openapi.js +386 -21
- package/dist/page.d.ts +18 -0
- package/dist/page.js +48 -20
- package/dist/paid-calls.d.ts +1 -1
- package/dist/place-offers.d.ts +2 -3
- package/dist/place-offers.js +3 -7
- package/dist/place.js +1 -2
- package/dist/print.d.ts +15 -1
- package/dist/print.js +14 -3
- package/dist/propose.d.ts +3 -0
- package/dist/propose.js +13 -5
- package/dist/provider.js +3 -2
- package/dist/reflect-range.d.ts +8 -1
- package/dist/reflect-range.js +1 -1
- package/dist/run-launch.d.ts +14 -2
- package/dist/run-launch.js +9 -4
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-reads-over-store.d.ts +1 -1
- package/dist/run-repo.d.ts +20 -0
- package/dist/run-repo.js +63 -0
- package/dist/run-timeline-served.d.ts +1 -1
- package/dist/run-view.d.ts +3 -3
- package/dist/run-view.js +14 -7
- package/dist/runner/adapter-loop.d.ts +23 -7
- package/dist/runner/adapter-loop.js +648 -62
- package/dist/runner/adapter-run-spec.d.ts +11 -3
- package/dist/runner/adapter-run-spec.js +77 -22
- package/dist/runner/adapters/pi-computer.d.ts +7 -0
- package/dist/runner/adapters/pi-computer.js +43 -0
- package/dist/runner/adapters/pi.d.ts +9 -4
- package/dist/runner/adapters/pi.js +76 -14
- package/dist/runner/beside.d.ts +7 -3
- package/dist/runner/beside.js +21 -11
- package/dist/runner/claim-secrets.d.ts +4 -0
- package/dist/runner/claim-secrets.js +6 -1
- package/dist/runner/cli-run-spec.d.ts +20 -3
- package/dist/runner/cli-run-spec.js +113 -43
- package/dist/runner/commands.d.ts +3 -1
- package/dist/runner/commands.js +28 -3
- package/dist/runner/computer-channel.d.ts +34 -0
- package/dist/runner/computer-channel.js +61 -0
- package/dist/runner/conformance/harness.js +80 -14
- package/dist/runner/conformance/subject.d.ts +1 -1
- package/dist/runner/dispatch.js +3 -0
- package/dist/runner/end-of-run.d.ts +22 -12
- package/dist/runner/end-of-run.js +38 -16
- package/dist/runner/github-app.d.ts +2 -1
- package/dist/runner/github-app.js +4 -2
- package/dist/runner/harness-loops.js +15 -1
- package/dist/runner/held-run.d.ts +65 -0
- package/dist/runner/held-run.js +158 -0
- package/dist/runner/journal-kinds.d.ts +20 -1
- package/dist/runner/journal-kinds.js +14 -0
- package/dist/runner/journal-reader.d.ts +5 -4
- package/dist/runner/journal-reader.js +12 -10
- package/dist/runner/learning-ask.d.ts +7 -1
- package/dist/runner/learning-ask.js +21 -6
- package/dist/runner/learning-dispatch.d.ts +22 -0
- package/dist/runner/learning-dispatch.js +77 -10
- package/dist/runner/learning-end.d.ts +22 -1
- package/dist/runner/learning-end.js +92 -12
- package/dist/runner/learning-factory.d.ts +1 -1
- package/dist/runner/learning-factory.js +11 -5
- package/dist/runner/learning-loop.d.ts +67 -7
- package/dist/runner/learning-loop.js +173 -21
- package/dist/runner/learning-seed.d.ts +7 -0
- package/dist/runner/learning-seed.js +13 -0
- package/dist/runner/live-ticker.js +1 -0
- package/dist/runner/loop-contract.d.ts +8 -1
- package/dist/runner/loop.d.ts +5 -1
- package/dist/runner/loop.js +2 -1
- package/dist/runner/main.d.ts +13 -1
- package/dist/runner/main.js +27 -5
- package/dist/runner/mcp-claim.d.ts +10 -7
- package/dist/runner/mcp-claim.js +113 -24
- package/dist/runner/mcp-github.js +1 -1
- package/dist/runner/mcp-run.d.ts +5 -5
- package/dist/runner/mcp-run.js +15 -3
- package/dist/runner/metrics.d.ts +11 -2
- package/dist/runner/metrics.js +12 -2
- package/dist/runner/pr-checkout.d.ts +1 -0
- package/dist/runner/pr-checkout.js +1 -1
- package/dist/runner/reflect-hook.d.ts +18 -0
- package/dist/runner/reflect-hook.js +20 -8
- package/dist/runner/runner.d.ts +26 -0
- package/dist/runner/runner.js +184 -15
- package/dist/runner/scratch-sweep.d.ts +13 -0
- package/dist/runner/scratch-sweep.js +62 -0
- package/dist/runner/sessions.d.ts +1 -1
- package/dist/runner/store-port.d.ts +4 -2
- package/dist/runner/store-secrets.js +4 -3
- package/dist/runner/subagent.js +3 -1
- package/dist/runner/workflow-host.d.ts +6 -1
- package/dist/runner/workflow-host.js +1 -1
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-spec.d.ts +14 -2
- package/dist/runner/workflow-spec.js +56 -20
- package/dist/runs-over-store.d.ts +6 -1
- package/dist/runs-over-store.js +38 -9
- package/dist/seal-key.js +3 -3
- package/dist/sealed-settings-store.d.ts +5 -2
- package/dist/sealed-settings-store.js +10 -4
- package/dist/secret-writes.d.ts +5 -4
- package/dist/secret-writes.js +5 -4
- package/dist/server-secrets-store.d.ts +4 -3
- package/dist/server-secrets-store.js +15 -9
- package/dist/server-secrets.js +3 -2
- package/dist/server.d.ts +43 -14
- package/dist/server.js +472 -126
- package/dist/settings-wake.d.ts +21 -0
- package/dist/settings-wake.js +59 -0
- package/dist/standard-webhooks.d.ts +4 -1
- package/dist/standard-webhooks.js +8 -4
- package/dist/store/command-wake.d.ts +12 -0
- package/dist/store/command-wake.js +37 -0
- package/dist/store/dialect.d.ts +6 -0
- package/dist/store/dialect.js +5 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/journal/storage.d.ts +3 -2
- package/dist/store/journal/storage.js +13 -5
- package/dist/store/postgres/dialect.js +4 -0
- package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
- package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
- package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
- package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
- package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
- package/dist/store/schema.d.ts +1 -1
- package/dist/store/schema.js +77 -8
- package/dist/store/sqlite/run-patch.d.ts +7 -5
- package/dist/store/sqlite/run-patch.js +28 -13
- package/dist/store/sqlite/store.js +272 -54
- package/dist/store/store.d.ts +268 -9
- package/dist/store/store.js +12 -1
- package/dist/store-reads/cap.d.ts +1 -1
- package/dist/store-reads/cap.js +8 -1
- package/dist/store-reads/decisions.d.ts +2 -2
- package/dist/store-reads/decisions.js +1 -1
- package/dist/store-reads/import-summary.d.ts +1 -1
- package/dist/store-reads/journal.d.ts +5 -4
- package/dist/store-reads/journal.js +73 -15
- package/dist/store-reads/learning.d.ts +20 -4
- package/dist/store-reads/learning.js +74 -18
- package/dist/store-reads/runs.d.ts +1 -1
- package/dist/store-reads/workflow.d.ts +1 -1
- package/dist/store-view.d.ts +5 -0
- package/dist/store-view.js +26 -11
- package/dist/template-eval.js +6 -4
- package/dist/template-github-permissions.d.ts +22 -8
- package/dist/template-github-permissions.js +35 -15
- package/dist/timeline/timeline.d.ts +27 -0
- package/dist/timeline/timeline.js +10 -9
- package/dist/timeline/util.d.ts +4 -0
- package/dist/timeline/util.js +14 -0
- package/dist/tool-budget.d.ts +19 -7
- package/dist/tool-budget.js +14 -8
- package/dist/tool-gate.d.ts +16 -9
- package/dist/tool-gate.js +53 -42
- package/dist/tool-plane.d.ts +16 -12
- package/dist/tool-plane.js +9 -4
- package/dist/tools.d.ts +13 -4
- package/dist/tools.js +13 -4
- package/dist/trigger-adapter.d.ts +4 -0
- package/dist/trigger-secrets-shown.d.ts +2 -2
- package/dist/trigger-secrets-shown.js +1 -1
- package/dist/trigger-signatures.d.ts +25 -6
- package/dist/trigger-signatures.js +41 -7
- package/dist/trigger-targets.d.ts +2 -0
- package/dist/trigger-targets.js +1 -0
- package/dist/trigger-webhook.js +5 -2
- package/dist/triggers.d.ts +7 -3
- package/dist/triggers.js +35 -5
- package/dist/turns.js +16 -1
- package/dist/validate.js +11 -1
- package/dist/web-fetch.d.ts +1 -1
- package/dist/web-search.d.ts +10 -5
- package/dist/web-search.js +7 -6
- package/dist/webhooks.d.ts +145 -102
- package/dist/webhooks.js +559 -322
- package/dist/workflow/decisions.d.ts +1 -1
- package/dist/workflow/node-runner.d.ts +2 -1
- package/dist/workflow/node.d.ts +2 -1
- package/dist/workflow/node.js +3 -1
- package/dist/workflow/pi-versions.d.ts +23 -0
- package/dist/workflow/pi-versions.js +57 -0
- package/dist/workflow/record-tool.d.ts +2 -1
- package/dist/workflow/store.d.ts +1 -1
- package/dist/workflow/task.js +3 -2
- package/dist/workflow-run.d.ts +1 -1
- package/dist/workspace/attached-computers.d.ts +41 -0
- package/dist/workspace/attached-computers.js +114 -0
- package/dist/workspace/computer-deps.d.ts +16 -9
- package/dist/workspace/computer-deps.js +19 -7
- package/dist/workspace/computer-for-claim.d.ts +17 -8
- package/dist/workspace/computer-for-claim.js +62 -21
- package/dist/workspace/computer-hold.d.ts +11 -27
- package/dist/workspace/computer-hold.js +36 -56
- package/dist/workspace/computer-ledger.d.ts +3 -1
- package/dist/workspace/computer-ledger.js +4 -0
- package/dist/workspace/computer-mcp.d.ts +25 -0
- package/dist/workspace/computer-mcp.js +41 -0
- package/dist/workspace/computer-ports.d.ts +4 -13
- package/dist/workspace/computer-ports.js +4 -107
- package/dist/workspace/computer-script.d.ts +37 -0
- package/dist/workspace/computer-script.js +138 -0
- package/dist/workspace/executors.d.ts +1 -1
- package/dist/workspace/index.d.ts +4 -2
- package/dist/workspace/index.js +3 -1
- package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
- package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
- package/dist/workspace/resolve-computer.d.ts +3 -0
- package/dist/workspace/resolve-computer.js +8 -2
- package/dist/workspace/run-tools.d.ts +32 -15
- package/dist/workspace/run-tools.js +23 -30
- package/package.json +19 -16
- package/templates/market-monitor/agent.md +1 -1
- package/dist/console/assets/index-BI4Byidu.js +0 -550
- package/dist/console/assets/index-C19gUF2n.css +0 -1
- package/dist/run-db.d.ts +0 -53
- package/dist/run-db.js +0 -116
- package/dist/workflow/readers.d.ts +0 -36
- package/dist/workflow/readers.js +0 -145
- package/dist/workflow/wal.d.ts +0 -11
- package/dist/workflow/wal.js +0 -106
|
@@ -3,12 +3,13 @@ import { createModels } from "@earendil-works/pi-ai/models";
|
|
|
3
3
|
import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
4
4
|
import { answeredUnpriced, modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
|
|
5
5
|
import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
|
|
6
|
-
import { endedOnTurnEndingTool, HOST_PHASE, MESSAGE_ORIGIN, originOf, RUN_RESUMED } from "../timeline/index.js";
|
|
6
|
+
import { CAP_WRAPUP, endedOnTurnEndingTool, HOST_PHASE, MESSAGE_ORIGIN, originOf, REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
|
|
7
7
|
import { raiseFollowUpId } from "../run-view.js";
|
|
8
|
+
import { durableWait } from "../workflow/pi-versions.js";
|
|
8
9
|
/** The root entries a claim writes before its turn, whatever the run's turns are (its session's key, a phase row, a
|
|
9
10
|
* takeover's note, its computer's hold, the learning seed it laid): read past when a claim asks whether the run's root ends
|
|
10
11
|
* on its end (a fresh reopen). */
|
|
11
|
-
const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold"]);
|
|
12
|
+
const CLAIM_BOOKKEEPING = new Set([KINDS.sessionKey, HOST_PHASE, RUN_RESUMED, KINDS.learningLaid, "computer.hold", HELD_KIND, CALL_KIND, COMPUTER_CALLS, REQUEST_STARTED, REQUEST_ENDED]);
|
|
12
13
|
/** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
|
|
13
14
|
const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
|
|
14
15
|
import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
|
|
@@ -18,9 +19,14 @@ import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES
|
|
|
18
19
|
import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
|
|
19
20
|
import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
|
|
20
21
|
import { isComputerCommand, journalHold } from "./computer-journal.js";
|
|
22
|
+
import { isHeldCommand, journalHeld } from "./held-run.js";
|
|
23
|
+
import { HELD_KIND, heldWords } from "../computer-held.js";
|
|
24
|
+
import { CALL_KIND, CALL_MS, COMPUTER_CALL } from "../computer-channel.js";
|
|
25
|
+
import { COMPUTER_CALLS, recordingCalls } from "../computer-calls.js";
|
|
26
|
+
import { channelCallOf, runChannelCall } from "./computer-channel.js";
|
|
21
27
|
import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
|
|
22
28
|
import { journalSessions } from "./sessions.js";
|
|
23
|
-
import { DECISION_SESSION, FIT_TOLERANCE, overCapOf, paidRefusal, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
29
|
+
import { DECISION_SESSION, FIT_TOLERANCE, noteFor, overCapOf, paidRefusal, previousAfter, requestFigures, runCap, typicalCost, wrapUpWords, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
24
30
|
import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
|
|
25
31
|
import { bookedIn } from "../paid-calls.js";
|
|
26
32
|
import { withHostCalls } from "../host-calls.js";
|
|
@@ -28,7 +34,10 @@ import { sideEffect } from "./side-effects.js";
|
|
|
28
34
|
import { McpClaimRefused } from "./mcp-claim.js";
|
|
29
35
|
import { Fenced } from "../store/index.js";
|
|
30
36
|
import { parkedFollowUp } from "./mcp-run.js";
|
|
31
|
-
import { budgetOf, TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
|
|
37
|
+
import { budgetOf, reserveFor, TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
|
|
38
|
+
/** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
|
|
39
|
+
* and the harness's next call runs it. */
|
|
40
|
+
export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool runs it on its next call.";
|
|
32
41
|
/** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
|
|
33
42
|
export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
|
|
34
43
|
/** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
|
|
@@ -87,6 +96,10 @@ export function pendingPauseOf(entries) {
|
|
|
87
96
|
}
|
|
88
97
|
/** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
|
|
89
98
|
const DELIVER_NOW_MS = 5_000;
|
|
99
|
+
/** How long the cap's wrap-up note, once a request took it, waits for that request's admission before a later request
|
|
100
|
+
* may take it. A request that leaves before its admission gives it back as it goes (ModelPort.noteReturned): this is
|
|
101
|
+
* only the backstop for a path that never does. A proxy's token count and admission take well under it. */
|
|
102
|
+
const WRAP_UP_OFFER_MS = 30_000;
|
|
90
103
|
/** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
|
|
91
104
|
const cutWhole = (text, max) => {
|
|
92
105
|
const cut = text.slice(0, max);
|
|
@@ -161,6 +174,15 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
161
174
|
const append = async (kind, data) => {
|
|
162
175
|
await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
|
|
163
176
|
};
|
|
177
|
+
/** A message that starts a turn: its entry and the turn's start (KINDS.turnStart), one commit, so the turn is open from
|
|
178
|
+
* the commit that holds its message. `entry` is the whole message entry when it is the host's input (with its origin). */
|
|
179
|
+
const startsTurn = async (message) => {
|
|
180
|
+
await harness.commit(async (tx) => {
|
|
181
|
+
await tx.appendEntry(root.id, ("entry" in message ? message.entry : { kind: message.kind, data: { ...message.data, at: now() } }));
|
|
182
|
+
await tx.appendEntry(root.id, { kind: KINDS.turnStart, data: { at: now() } });
|
|
183
|
+
}, context);
|
|
184
|
+
turnsOpen += 1;
|
|
185
|
+
};
|
|
164
186
|
// Each call started on the record: whether it has its end; and each end, by call id.
|
|
165
187
|
const started = new Map();
|
|
166
188
|
const ends = new Map();
|
|
@@ -171,6 +193,8 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
171
193
|
// The command rows a message was about to be sent for (their intent marks): one sent again is a retry.
|
|
172
194
|
const sending = new Set();
|
|
173
195
|
let personWritten = false;
|
|
196
|
+
// The turns the record opened (KINDS.turnStart) and has not ended (KINDS.turnEnd): what the journal says on open, then kept.
|
|
197
|
+
let turnsOpen = 0;
|
|
174
198
|
// The request ids of the follow-ups written (followUp): each is written once.
|
|
175
199
|
const followUps = new Set();
|
|
176
200
|
// Each end-of-run turn's prompt the record wrote as it asked the turn, by its request id: a turn asked again (a later
|
|
@@ -194,6 +218,10 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
194
218
|
started.set(data.callId, true);
|
|
195
219
|
else if ((entry.kind === KINDS.message && data.role === "person") || entry.kind === KINDS.input)
|
|
196
220
|
personWritten = true;
|
|
221
|
+
if (entry.kind === KINDS.turnStart)
|
|
222
|
+
turnsOpen += 1;
|
|
223
|
+
else if (entry.kind === KINDS.turnEnd && turnsOpen > 0)
|
|
224
|
+
turnsOpen -= 1;
|
|
197
225
|
if ((entry.kind === KINDS.message || entry.kind === KINDS.input) && typeof data.requestId === "string")
|
|
198
226
|
followUps.add(data.requestId);
|
|
199
227
|
}
|
|
@@ -205,19 +233,27 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
205
233
|
ends.set(callId, { status: "interrupted" });
|
|
206
234
|
}
|
|
207
235
|
let text = "";
|
|
236
|
+
/** A model message was written at a request's start (flushSaid) and no other flush has come since. */
|
|
237
|
+
let flushedAtRequest = false;
|
|
208
238
|
/** The end-of-run turn's answer while that turn runs (answering), else undefined. */
|
|
209
239
|
let answer;
|
|
210
240
|
// One write at a time, in the order they were asked for, a failed one never stopping the next.
|
|
211
241
|
let chain = Promise.resolve();
|
|
212
242
|
const inTurn = (work) => (chain = chain.then(work, work));
|
|
213
243
|
/** What was said since the last boundary as a model message; at a turn's end, with the cut its adapter reported. */
|
|
214
|
-
const flushText = (cut) => {
|
|
244
|
+
const flushText = (cut, atRequest = false) => {
|
|
215
245
|
// Taken at the boundary, not when its write's turn comes: text said after it is the next message's.
|
|
216
246
|
const said = text;
|
|
217
247
|
text = "";
|
|
218
248
|
return inTurn(async () => {
|
|
219
249
|
if (said === "")
|
|
220
250
|
return;
|
|
251
|
+
// Whitespace after a message flushed at the request before it joined that message's row, as the turn's text up to its
|
|
252
|
+
// call always has: it is no message of its own.
|
|
253
|
+
const joined = flushedAtRequest && said.trim() === "";
|
|
254
|
+
flushedAtRequest = atRequest;
|
|
255
|
+
if (joined)
|
|
256
|
+
return;
|
|
221
257
|
const length = cut?.stopReason === "length" ? { stopReason: "length", ...(cut.outputTokens === undefined ? {} : { outputTokens: cut.outputTokens }) } : {};
|
|
222
258
|
await append(KINDS.message, { role: "model", text: said, ...length });
|
|
223
259
|
});
|
|
@@ -236,34 +272,49 @@ async function openCliRecord(harness, journal, context, now, cwd) {
|
|
|
236
272
|
void flushText(event).catch(() => undefined);
|
|
237
273
|
},
|
|
238
274
|
flushText,
|
|
239
|
-
|
|
275
|
+
flushSaid: () => (answer === undefined && text.trim() !== "" ? flushText(undefined, true) : Promise.resolve()),
|
|
276
|
+
person: (input, opens = true) => inTurn(async () => {
|
|
240
277
|
if (personWritten)
|
|
241
278
|
return;
|
|
242
|
-
|
|
279
|
+
if (opens)
|
|
280
|
+
await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
|
|
281
|
+
else
|
|
282
|
+
await append(KINDS.message, { role: "person", text: input });
|
|
243
283
|
personWritten = true;
|
|
244
284
|
}),
|
|
245
|
-
input: (input, origin) => inTurn(async () => {
|
|
285
|
+
input: (input, origin, opens = true) => inTurn(async () => {
|
|
246
286
|
if (personWritten)
|
|
247
287
|
return;
|
|
248
|
-
|
|
288
|
+
const entry = { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] };
|
|
289
|
+
if (opens)
|
|
290
|
+
await startsTurn({ entry });
|
|
291
|
+
else
|
|
292
|
+
await harness.commit((tx) => tx.appendEntry(root.id, entry), context);
|
|
249
293
|
personWritten = true;
|
|
250
294
|
}),
|
|
251
295
|
followUp: (input, requestId, origin) => inTurn(async () => {
|
|
252
296
|
if (followUps.has(requestId))
|
|
253
297
|
return;
|
|
254
298
|
if (origin)
|
|
255
|
-
await
|
|
299
|
+
await startsTurn({ entry: { kind: KINDS.input, data: { origin, requestId }, model: [{ role: "user", content: input, timestamp: now() }] } });
|
|
256
300
|
else
|
|
257
|
-
await
|
|
301
|
+
await startsTurn({ kind: KINDS.message, data: { role: "person", text: input, requestId } });
|
|
258
302
|
followUps.add(requestId);
|
|
259
303
|
personWritten = true;
|
|
260
304
|
}),
|
|
261
305
|
message: (input, origin) => inTurn(async () => {
|
|
262
306
|
if (origin)
|
|
263
|
-
await
|
|
307
|
+
await startsTurn({ entry: { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] } });
|
|
264
308
|
else
|
|
265
|
-
await
|
|
309
|
+
await startsTurn({ kind: KINDS.message, data: { role: "person", text: input } });
|
|
310
|
+
}),
|
|
311
|
+
turnEnded: (status, error) => inTurn(async () => {
|
|
312
|
+
if (turnsOpen === 0)
|
|
313
|
+
return;
|
|
314
|
+
await harness.commit((tx) => tx.appendEntry(root.id, { kind: KINDS.turnEnd, data: { status, ...(error === undefined ? {} : { error }) } }), context);
|
|
315
|
+
turnsOpen -= 1;
|
|
266
316
|
}),
|
|
317
|
+
openTurn: () => turnsOpen > 0,
|
|
267
318
|
async sending(commandId) {
|
|
268
319
|
let again = false;
|
|
269
320
|
await inTurn(async () => {
|
|
@@ -385,6 +436,16 @@ function adapterLoop(specOf, options, deps) {
|
|
|
385
436
|
};
|
|
386
437
|
let stopped = () => { };
|
|
387
438
|
const stopping = new Promise((resolve) => (stopped = resolve));
|
|
439
|
+
/** A cancel, a lost claim or a shutdown that came after a person's stop, and the cut it gives the held computer that
|
|
440
|
+
* stop kept (writeEnd). */
|
|
441
|
+
let laterStop;
|
|
442
|
+
/** Whether the run's first stop kept its computer (keeps), as the runner was told when it chose to go on handing the
|
|
443
|
+
* run's rows on: a stop that came before the hold was up (the computer still coming up) did not, so its end lets the
|
|
444
|
+
* computer go, never waiting for a release no row can bring. */
|
|
445
|
+
let keptAtStop = false;
|
|
446
|
+
const keeps = (reason) => reason.kind === "command" && !reason.cancel && heldNow !== undefined && heldNow.state() !== "released" && !gate?.sealed;
|
|
447
|
+
let cutHeld = () => { };
|
|
448
|
+
const heldCut = new Promise((resolve) => (cutHeld = resolve));
|
|
388
449
|
/** Aborted by any stop of the run (AdapterRun.stopped, with the claim's signal): a host tool call in flight (a CLI's door
|
|
389
450
|
* call among them, whose own request signal its CLI may never abort) is cut with it, as pi's own abort cuts pi's calls.
|
|
390
451
|
* stop() aborts it first, with the stop's Interrupted, so the reason a cut call reads is the stop's. */
|
|
@@ -402,6 +463,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
402
463
|
let refusals = 0;
|
|
403
464
|
/** The claim's first delivery is done (LoopDeps.delivered): every row the runner read is with the loop. */
|
|
404
465
|
let delivered = false;
|
|
466
|
+
/** The calls this run's journal had asked about and not answered when the claim first read it (askStands). */
|
|
467
|
+
let standing;
|
|
405
468
|
/** The run is parking at its cap (the early pause, from its commit on): a raise row is left for the next claim. */
|
|
406
469
|
let pausing = false;
|
|
407
470
|
/** Resolved once the claim's Harness is open and its root known: a command's check reads the journal through it. */
|
|
@@ -410,6 +473,14 @@ function adapterLoop(specOf, options, deps) {
|
|
|
410
473
|
let held;
|
|
411
474
|
/** The run's computer hold's journal side, for the current pass (AdapterRunSpec.computer). */
|
|
412
475
|
let computerNow;
|
|
476
|
+
/** The run's computer held for its owner, for the current pass (AdapterRunSpec.held). */
|
|
477
|
+
let heldNow;
|
|
478
|
+
/** The current pass's computer for the computer call channel (AdapterRunSpec.computer), and how a call's entry is
|
|
479
|
+
* committed on the run's root through the pass's Harness. */
|
|
480
|
+
let channelNow;
|
|
481
|
+
/** Channel calls done on the computer whose record (and row's take) is still to be written: each answers whether it
|
|
482
|
+
* wrote (settleCalls). */
|
|
483
|
+
const unsettledCalls = new Set();
|
|
413
484
|
/** This claim's spec, once known: a raise is checked by its cap's rule, and the end's patch is read from it. */
|
|
414
485
|
let specNow;
|
|
415
486
|
/** Whether this claim's tool host was let go (its beforeRelease run), once. */
|
|
@@ -444,6 +515,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
444
515
|
* person's message is placed as that first input. The claim waits on it, never sending the input they stopped, however
|
|
445
516
|
* late the runner hands the message over. */
|
|
446
517
|
let firstInputPlaced;
|
|
518
|
+
/** Resolved once a pass of this claim has sent what its session starts on (the run's input, a follow-up, a recovery),
|
|
519
|
+
* or found nothing to send: a message handed over while the session is still new waits for it, so it lands after the
|
|
520
|
+
* run's input, never as the session's first prompt (a message sent as soon as the run's 202 came back). */
|
|
521
|
+
let inputSent = () => { };
|
|
522
|
+
const startSent = new Promise((resolve) => (inputSent = resolve));
|
|
447
523
|
/** The tool hosts' holds while the run waits in its claim on the person's answer (HostLifecycle.personWait): dropped
|
|
448
524
|
* once the wait is over, whichever way it ends. */
|
|
449
525
|
let waitHolds = [];
|
|
@@ -636,6 +712,89 @@ function adapterLoop(specOf, options, deps) {
|
|
|
636
712
|
handing = turn.catch(() => undefined);
|
|
637
713
|
return turn;
|
|
638
714
|
};
|
|
715
|
+
/** The owner's start or release of a held computer (runner/held-run.ts): taken by the commit that writes what came of it
|
|
716
|
+
* (its entry carries the row's id); refused in words when it changed nothing. One at a time, in the take-over's turn. */
|
|
717
|
+
const heldCommand = (command) => {
|
|
718
|
+
const turn = handing.then(async () => {
|
|
719
|
+
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
720
|
+
const [theGate, theHeld] = [gate, heldNow];
|
|
721
|
+
if (!theGate || theGate.sealed)
|
|
722
|
+
return { later: "the run is parking or ending: the row waits for its next claim" };
|
|
723
|
+
if (!theHeld)
|
|
724
|
+
return { refused: "This run does not hold its computer: start it with hold: true." };
|
|
725
|
+
const decided = theHeld.decide(command);
|
|
726
|
+
if ("refused" in decided)
|
|
727
|
+
return decided;
|
|
728
|
+
const madeBy = (data) => theHeld.madeBy(data, command.id);
|
|
729
|
+
const landed = theGate.expect(writesEntry(HELD_KIND, madeBy), { take: [command.id] });
|
|
730
|
+
landed.catch(() => undefined);
|
|
731
|
+
await decided.write();
|
|
732
|
+
await landed;
|
|
733
|
+
return { taken: true };
|
|
734
|
+
});
|
|
735
|
+
handing = turn.catch(() => undefined);
|
|
736
|
+
return turn;
|
|
737
|
+
};
|
|
738
|
+
/**
|
|
739
|
+
* A call through the computer call channel (runner/computer-channel.ts): run on the pass's computer, behind the
|
|
740
|
+
* person's hold, and taken with its answer by the commit that writes its computer.call entry. It runs off the take-over's
|
|
741
|
+
* turn and off the runner's delivery, which goes on to the next row at once: a call may wait for a person's hand-back,
|
|
742
|
+
* and the hand-back is a later row. So `taken` here means its take rides on that entry's commit once the call is done
|
|
743
|
+
* (settleCalls): a fault's restart meanwhile writes it through the claim's next pass, and a claim that ends first leaves
|
|
744
|
+
* the row untaken for the run's end, or its next claim, to settle. Refused in words when the run has no
|
|
745
|
+
* computer that takes calls, is parking or ending, or held its computer and let it go.
|
|
746
|
+
*/
|
|
747
|
+
const channelCommand = async (command) => {
|
|
748
|
+
await Promise.race([ready, (finished ?? new Promise(() => { })).then(() => undefined, () => undefined)]);
|
|
749
|
+
const [theGate, pass, theHeld] = [gate, channelNow, heldNow];
|
|
750
|
+
if (!theGate || theGate.sealed)
|
|
751
|
+
return { refused: "The run's computer is not up now: the run is starting, parking or ending." };
|
|
752
|
+
if (!pass)
|
|
753
|
+
return { refused: specNow?.computer ? "The run's computer is not up now: the run is starting, parking or ending." : "This run has no computer that takes protocol calls: none, or a browser." };
|
|
754
|
+
const refusal = theHeld?.refusesCall();
|
|
755
|
+
if (refusal)
|
|
756
|
+
return { refused: refusal };
|
|
757
|
+
const call = channelCallOf(command);
|
|
758
|
+
if ("refused" in call)
|
|
759
|
+
return call;
|
|
760
|
+
void (async () => {
|
|
761
|
+
// The hold's idle count stands still while the call runs, and starts again when the last one ends.
|
|
762
|
+
theHeld?.callStarted();
|
|
763
|
+
let done;
|
|
764
|
+
try {
|
|
765
|
+
done = await runChannelCall(pass.computer, call, AbortSignal.any([deps.signal, AbortSignal.timeout(CALL_MS)]), now);
|
|
766
|
+
}
|
|
767
|
+
finally {
|
|
768
|
+
theHeld?.callEnded(now());
|
|
769
|
+
}
|
|
770
|
+
unsettledCalls.add(async () => {
|
|
771
|
+
// Written through the pass open now: the one the call ran in, or, when a fault closed that one meanwhile, the
|
|
772
|
+
// claim's next. None open (between passes): it waits for the next pass to open.
|
|
773
|
+
const [liveGate, livePass] = [gate, channelNow];
|
|
774
|
+
if (!liveGate || liveGate.sealed || !livePass)
|
|
775
|
+
return false;
|
|
776
|
+
const landed = liveGate.expect(writesEntry(CALL_KIND, (data) => data.by === command.id), { take: [command.id], answer: { command: command.id, value: done.answer } });
|
|
777
|
+
landed.catch(() => undefined);
|
|
778
|
+
await livePass.commit([{ kind: CALL_KIND, data: { by: command.id, at: done.at, ...done.record } }]);
|
|
779
|
+
await landed;
|
|
780
|
+
return true;
|
|
781
|
+
});
|
|
782
|
+
settleCalls();
|
|
783
|
+
})().catch(() => undefined);
|
|
784
|
+
return { taken: true };
|
|
785
|
+
};
|
|
786
|
+
/** Writes each finished channel call whose record is not written yet, through the pass open now. One the pass's seal
|
|
787
|
+
* failed stays for the next pass; one the claim ends with stays untaken, and the run's end (or its next claim) settles
|
|
788
|
+
* its row. */
|
|
789
|
+
function settleCalls() {
|
|
790
|
+
for (const settle of [...unsettledCalls]) {
|
|
791
|
+
unsettledCalls.delete(settle);
|
|
792
|
+
settle().then((written) => {
|
|
793
|
+
if (!written)
|
|
794
|
+
unsettledCalls.add(settle);
|
|
795
|
+
}, () => unsettledCalls.add(settle));
|
|
796
|
+
}
|
|
797
|
+
}
|
|
639
798
|
/** The raise entry, taking every raise row this claim has in its one commit (each take keyed to the entry). */
|
|
640
799
|
async function takeRaises() {
|
|
641
800
|
const takes = raising.takes.splice(0);
|
|
@@ -660,12 +819,21 @@ function adapterLoop(specOf, options, deps) {
|
|
|
660
819
|
}
|
|
661
820
|
const steer = async (command) => {
|
|
662
821
|
// Handed over before the session is open: placed once it is, its outcome the real one (never taken and then dropped).
|
|
663
|
-
|
|
664
|
-
|
|
822
|
+
// Awaited even with a session there: until the claim is ready it has not said whether this message reopens the run.
|
|
823
|
+
const over = () => (finished ?? new Promise(() => { })).then(() => undefined, () => undefined);
|
|
824
|
+
await Promise.race([ready, over()]);
|
|
665
825
|
// The session never opened, or the run is parking or stopping (its journal sealed, its session closed): left
|
|
666
826
|
// untaken for the next claim, which hands it on again; never refused for good.
|
|
667
827
|
if (!gate || !session || gate.sealed)
|
|
668
828
|
return { later: "the run is parking: the steer waits for its resume" };
|
|
829
|
+
// The session is still new and this is no reopen's message: the claim has yet to send the run's input. Placed now,
|
|
830
|
+
// the message would be the session's first prompt and the input would follow it; it waits for the input instead, then
|
|
831
|
+
// goes into that turn as any message does.
|
|
832
|
+
if (!reopen && session.state === "new") {
|
|
833
|
+
await Promise.race([startSent, over()]);
|
|
834
|
+
if (!gate || !session || gate.sealed)
|
|
835
|
+
return { later: "the run is parking: the steer waits for its resume" };
|
|
836
|
+
}
|
|
669
837
|
// The run's job has answered and it is looking back before its end: a person's message is not the end-of-run turn's
|
|
670
838
|
// to answer. Left untaken, the run's end opens a completed run again with it as a new turn (store run-patch.ts
|
|
671
839
|
// refuseLeftovers).
|
|
@@ -681,7 +849,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
681
849
|
// The session idle with no wait taking messages yet: whether the last turn ended on a question to the person, read
|
|
682
850
|
// first. It is an await, so a wait may start meanwhile: every path below is chosen after it, with nothing awaited
|
|
683
851
|
// between that choice and the message's placing.
|
|
684
|
-
const
|
|
852
|
+
const reopenedBefore = reopen;
|
|
853
|
+
const endedOnAsk = session.state === "idle" && root !== undefined && endedOnTurnEndingTool((await entriesOf(gate.journal, root.id, context))) !== undefined;
|
|
854
|
+
const askedLast = !reopenedBefore && endedOnAsk;
|
|
685
855
|
if (!gate || !session || gate.sealed)
|
|
686
856
|
return { later: "the run is parking: the steer waits for its resume" };
|
|
687
857
|
// A message that may not answer a person (a trigger's), delivered once the run waits on its person (in its claim, or
|
|
@@ -706,19 +876,21 @@ function adapterLoop(specOf, options, deps) {
|
|
|
706
876
|
// The row is taken only once the session holds the prompt: pi's in its submission's commit; a CLI's (whose harness
|
|
707
877
|
// writes no submission) in the record's follow-up entry, written right after the send, as sendAfterTurn takes its
|
|
708
878
|
// row. A runner lost between the send and that entry leaves the row untaken, so the next claim sends it again: a
|
|
709
|
-
// follow-up may be sent twice after a crash, never lost. The answer to
|
|
710
|
-
//
|
|
879
|
+
// follow-up may be sent twice after a crash, never lost. The answer to an ask: the row's waiting summary goes in
|
|
880
|
+
// that commit too, for a wait in the claim and for a question a reopened run parked on (its journal holds its earlier
|
|
881
|
+
// end, so its claim reads as reopened). Left until the end commit, the answer's turn reads running, held and "Waiting
|
|
882
|
+
// for your reply", and the server tells that ask again.
|
|
711
883
|
const placedBy = theRecord ? writesEntry(by ? KINDS.input : KINDS.message, (data) => data.requestId === requestId) : writesSubmission(sendId);
|
|
712
|
-
const taken = gate.expect(placedBy, { take: [command.id], ...(reopen === waitTurn ? { run: { summary: null } } : {}) });
|
|
884
|
+
const taken = gate.expect(placedBy, { take: [command.id], ...(reopen === waitTurn || endedOnAsk ? { run: { summary: null } } : {}) });
|
|
713
885
|
taken.catch(() => undefined);
|
|
714
886
|
reopen.sent = (async () => {
|
|
715
887
|
await theSession.send(content, { id: sendId, ...(by ? { origin: by } : {}) });
|
|
716
888
|
// A CLI's record: the original input as its writer's (the launch's origin, else the person's), then the message.
|
|
717
889
|
if (first) {
|
|
718
890
|
if (first.inputOrigin)
|
|
719
|
-
await theRecord?.input(first.input, first.inputOrigin);
|
|
891
|
+
await theRecord?.input(first.input, first.inputOrigin, false);
|
|
720
892
|
else
|
|
721
|
-
await theRecord?.person(first.input);
|
|
893
|
+
await theRecord?.person(first.input, false);
|
|
722
894
|
}
|
|
723
895
|
await theRecord?.followUp(text, requestId, by);
|
|
724
896
|
})();
|
|
@@ -856,13 +1028,38 @@ function adapterLoop(specOf, options, deps) {
|
|
|
856
1028
|
// made here, before the spec, so the spec's tool host binds them at its bind (a browser release's charge comes
|
|
857
1029
|
// outside any call). Each session is opened at its first step: a run that makes none writes nothing for it. A
|
|
858
1030
|
// handle not opened on this claim reads what the run's records held when the claim began.
|
|
859
|
-
|
|
1031
|
+
// What was spent beside them on the run's behalf (its spec's runCap.beside) is read with them at each admission
|
|
1032
|
+
// (runBooking), the spec's once it is known.
|
|
1033
|
+
const besideNow = async () => (specNow?.runCap?.beside ? await specNow.runCap.beside() : 0);
|
|
1034
|
+
const sessions = Object.assign(journalSessions(harness, context, { flush: () => deps.flush() }), { beside: besideNow });
|
|
860
1035
|
let capBuilt;
|
|
1036
|
+
/** The session's previous request, as the cap's `expected` pricing reads it (the kernel's Previous): the last of the
|
|
1037
|
+
* harness's own requests on this claim that answered, its input as its usage reported it (read from or written to
|
|
1038
|
+
* the cache, and the rest) and its input bound, and when it ended. None before one has: priced as a cache miss. */
|
|
1039
|
+
let previous;
|
|
1040
|
+
/** Each of this claim's requests as the cap was asked about it, by its turn, until it ends. */
|
|
1041
|
+
const askedFor = new Map();
|
|
861
1042
|
const theCap = () => {
|
|
862
1043
|
if (!specNow?.runCap)
|
|
863
1044
|
throw new Error("the run's spec gives no cap (AdapterRunSpec.runCap)");
|
|
864
1045
|
// The cap each admission reads is the run's now (capNow): a raise taken on this claim or an earlier one.
|
|
865
|
-
|
|
1046
|
+
// Its previous request is the session's own (requestEnded), unless the spec names one (a test's warm cache).
|
|
1047
|
+
const { beside: _beside, ...config } = specNow.runCap;
|
|
1048
|
+
return (capBuilt ??= runCap({ sessions, previousOf: (model) => (previous?.model === model ? previous : undefined), ...config, capUsd: capNow }));
|
|
1049
|
+
};
|
|
1050
|
+
/** A request of this claim ended (`request_end`): one of the harness's own (no host label, no side call) that
|
|
1051
|
+
* answered with its input reported is the session's previous request from now. */
|
|
1052
|
+
const requestEnded = (turn, usage, how) => {
|
|
1053
|
+
const asked = askedFor.get(turn);
|
|
1054
|
+
askedFor.delete(turn);
|
|
1055
|
+
if (!asked?.own || asked.bound === undefined || usage.cut || (how !== undefined && how.end !== "answered"))
|
|
1056
|
+
return;
|
|
1057
|
+
const cachedTokens = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
1058
|
+
if (!(usage.input >= 0 && cachedTokens >= 0 && usage.input + cachedTokens > 0))
|
|
1059
|
+
return;
|
|
1060
|
+
// A smaller request than the previous on the same model is a compaction or another conversation's (a child of the
|
|
1061
|
+
// run, whose requests the proxy cannot tell from the root's): history resets (previousAfter), never sticks.
|
|
1062
|
+
previous = previousAfter(previous, { model: asked.model, cachedTokens, inputTokens: usage.input, boundTokens: asked.bound, counted: asked.counted, endedAt: (specNow?.runCap?.now ?? Date.now)() });
|
|
866
1063
|
};
|
|
867
1064
|
const flushed = { flush: () => deps.flush() };
|
|
868
1065
|
const earlierDecisions = sessionSpendOf(await sessions.read(DECISION_SESSION)).spentUsd;
|
|
@@ -1006,7 +1203,11 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1006
1203
|
const cap = capNow();
|
|
1007
1204
|
if (cap === undefined)
|
|
1008
1205
|
return undefined;
|
|
1009
|
-
|
|
1206
|
+
// What was spent beside the run on its behalf counts as its other sessions' spend does.
|
|
1207
|
+
const beside = await besideNow();
|
|
1208
|
+
if (beside === null)
|
|
1209
|
+
return undefined;
|
|
1210
|
+
let others = beside;
|
|
1010
1211
|
for (const key of await sessions.keys()) {
|
|
1011
1212
|
if (key === spec.session.key)
|
|
1012
1213
|
continue;
|
|
@@ -1029,7 +1230,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1029
1230
|
const cap = capNow();
|
|
1030
1231
|
if (!step || cap === undefined)
|
|
1031
1232
|
return pending;
|
|
1032
|
-
|
|
1233
|
+
const beside = await besideNow();
|
|
1234
|
+
if (beside === null)
|
|
1235
|
+
return pending;
|
|
1236
|
+
let spent = beside;
|
|
1033
1237
|
for (const key of await sessions.keys()) {
|
|
1034
1238
|
const spend = sessionSpendOf(await sessions.read(key)).spentUsd;
|
|
1035
1239
|
if (spend === null)
|
|
@@ -1042,6 +1246,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1042
1246
|
return { ...pending, refuse: text, figures };
|
|
1043
1247
|
};
|
|
1044
1248
|
const beforeRequest = async (request) => {
|
|
1249
|
+
// Kept until it ends, so its answer can be the session's previous request (requestEnded).
|
|
1250
|
+
askedFor.set(request.turn, { model: request.model, ...(request.inputTokensMax === undefined ? {} : { bound: request.inputTokensMax }), counted: request.inputTokensCounted === true, own: request.host === undefined && !request.side && !request.unanswered });
|
|
1045
1251
|
// A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
|
|
1046
1252
|
// whatever else would pause it (a paid call's refusal, pendingPause).
|
|
1047
1253
|
const over = await overCap();
|
|
@@ -1108,6 +1314,108 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1108
1314
|
}
|
|
1109
1315
|
}
|
|
1110
1316
|
}
|
|
1317
|
+
// The cap's wrap-up note (#2080): near its cap the run's next main-model request is told once, inside its own body
|
|
1318
|
+
// (the session's model proxy places it: ModelPort.note), to finish now, by the kernel cap's rule (noteFor) over the
|
|
1319
|
+
// run's cap now, what it spent and holds, and its own priced answers. Once per cap, as main's process told it
|
|
1320
|
+
// (cap.ts wrapUpSentIn): a CAP_WRAPUP entry names the cap it was told under, read at each claim, so a raise's new
|
|
1321
|
+
// cap is told again when it too comes near; written as the server's row only once a request carrying the note is
|
|
1322
|
+
// admitted with it.
|
|
1323
|
+
const wrapUpHarness = harness;
|
|
1324
|
+
const wrapUpRoot = root ?? (await harness.root(context));
|
|
1325
|
+
const toldCaps = (await entriesOf(gate.journal, wrapUpRoot.id, context))
|
|
1326
|
+
.filter((entry) => entry.kind === CAP_WRAPUP)
|
|
1327
|
+
.map((entry) => entry.data?.capUsd)
|
|
1328
|
+
.filter((capUsd) => typeof capUsd === "number");
|
|
1329
|
+
const toldAt = (capUsd) => capUsd !== undefined && toldCaps.some((told) => Math.abs(told - capUsd) <= 1e-9);
|
|
1330
|
+
// What the run spent on its sessions other than this claim's model session, its decisions' and its paid calls' (an
|
|
1331
|
+
// earlier session's, a grade's), summed as overCap sums them; null while any is unknown. Read at the claim and again
|
|
1332
|
+
// after each request is admitted (the note is placed before its own request's admission, so it reads the last).
|
|
1333
|
+
const restOf = async () => {
|
|
1334
|
+
// And what was spent beside the run on its behalf (its learning runs' grades).
|
|
1335
|
+
const beside = await besideNow();
|
|
1336
|
+
if (beside === null)
|
|
1337
|
+
return null;
|
|
1338
|
+
let rest = beside;
|
|
1339
|
+
for (const key of await sessions.keys()) {
|
|
1340
|
+
if (key === spec.session.key || key === DECISION_SESSION || key === TOOL_SESSION)
|
|
1341
|
+
continue;
|
|
1342
|
+
const spent = sessionSpendOf(await sessions.read(key)).spentUsd;
|
|
1343
|
+
if (spent === null)
|
|
1344
|
+
return null;
|
|
1345
|
+
rest += spent;
|
|
1346
|
+
}
|
|
1347
|
+
return rest;
|
|
1348
|
+
};
|
|
1349
|
+
// The typical cost is of the harness's own main-model answers at what they cost: never a request the host sent beside
|
|
1350
|
+
// them (`host`), nor the harness's own side call on a smaller model (`side`, a title request), nor one a crash cut
|
|
1351
|
+
// (booked at its hold and bound, the worst case), one never sent, given back, owed or stopped.
|
|
1352
|
+
const claimRecords = await writer.read();
|
|
1353
|
+
const claimHosts = sessionSpendOf(claimRecords).hosts;
|
|
1354
|
+
/** The turns of requests that are no main-model request of the harness's own: read from the records, then each
|
|
1355
|
+
* admitted side call's (its ticket's turn), so a live answer's cost is judged the same as a restart's. */
|
|
1356
|
+
const notOwn = new Set(claimHosts.keys());
|
|
1357
|
+
for (const record of claimRecords) {
|
|
1358
|
+
const data = (record.data ?? {});
|
|
1359
|
+
if (record.kind === RUNNER_RECORDS.request && data.side === true && typeof data.turn === "number")
|
|
1360
|
+
notOwn.add(data.turn);
|
|
1361
|
+
}
|
|
1362
|
+
const capNote = {
|
|
1363
|
+
costs: claimRecords.flatMap((record) => {
|
|
1364
|
+
if (record.kind !== RUNNER_RECORDS.turn)
|
|
1365
|
+
return [];
|
|
1366
|
+
const data = (record.data ?? {});
|
|
1367
|
+
const own = typeof data.usd === "number" && data.usd > 0 && !data.cut && !data.unsent && !data.givenBack && !data.stopped && data.rule !== "owed";
|
|
1368
|
+
return own && (data.turn === undefined || !notOwn.has(data.turn)) ? [data.usd] : [];
|
|
1369
|
+
}),
|
|
1370
|
+
restUsd: await restOf(),
|
|
1371
|
+
};
|
|
1372
|
+
/** A main-model request's figures as the run's cap prices them (kernel cap requestFigures), for what it keeps back. */
|
|
1373
|
+
const figuresOf = (model, asked) => {
|
|
1374
|
+
const config = specNow?.runCap;
|
|
1375
|
+
const capModel = config?.modelOf(model);
|
|
1376
|
+
if (!config || !capModel)
|
|
1377
|
+
return undefined;
|
|
1378
|
+
return requestFigures({ kind: "model", id: "reserve", model: capModel, inputTokens: asked?.inputTokensMax, ...(asked?.outputTokensAsked === undefined ? {} : { outputAsked: asked.outputTokensAsked }), ...(asked?.outputTokensLeast === undefined ? {} : { outputTokensLeast: asked.outputTokensLeast }) }, config.mode ?? "expected", Date.now());
|
|
1379
|
+
};
|
|
1380
|
+
/** What the run keeps back to answer (tool-budget.ts reserveFor), its typical step the run's own priced answers'. */
|
|
1381
|
+
const reserveOf = (figures) => reserveFor(figures, (step0Usd) => typicalCost(capNote.costs, step0Usd));
|
|
1382
|
+
let bookingNow;
|
|
1383
|
+
const wrapUpNote = (model, asked) => {
|
|
1384
|
+
const config = specNow?.runCap;
|
|
1385
|
+
const capModel = config?.modelOf(model);
|
|
1386
|
+
const sessionSpent = bookingNow?.spentUsd();
|
|
1387
|
+
const decided = ledger.decisions.spentUsd();
|
|
1388
|
+
const paidSpent = ledger.paid.spentUsd();
|
|
1389
|
+
const rest = capNote.restUsd;
|
|
1390
|
+
// The model session's requests in flight, at what is held for each (as the cap reads a flight); unknown gives none.
|
|
1391
|
+
const inFlight = bookingNow?.heldUsd();
|
|
1392
|
+
const capUsd = capNow();
|
|
1393
|
+
// One request at a time carries it: while one offered it waits for its admission, an overlapping request is not
|
|
1394
|
+
// offered it too (its admission tells it, or a refusal or a dropped note gives it back: below). A request that
|
|
1395
|
+
// took it and left before its admission (its client gone while the proxy counted its tokens, a body the proxy
|
|
1396
|
+
// refused) gives it back as it goes (noteReturned), so the next request takes it at once. WRAP_UP_OFFER_MS is
|
|
1397
|
+
// only the backstop for a path that never gives it back: past it, a later request is offered it.
|
|
1398
|
+
if (capNote.offered && Date.now() - capNote.offered.at < WRAP_UP_OFFER_MS)
|
|
1399
|
+
return undefined;
|
|
1400
|
+
if (!config || !capModel || capUsd === undefined || toldAt(capUsd) || sessionSpent == null || decided === null || paidSpent === null || rest === null || inFlight == null)
|
|
1401
|
+
return undefined;
|
|
1402
|
+
const spentUsd = sessionSpent + decided + paidSpent + rest;
|
|
1403
|
+
// The tools' gate counts a request in flight at its hold and its bound (sessionSpendOf: a cache miss adds the bound),
|
|
1404
|
+
// so the note counts it the same: it never comes later than the gate's first refusal.
|
|
1405
|
+
const heldUsd = inFlight + (bookingNow?.boundUsd() ?? 0) + ledger.decisions.heldUsd() + ledger.paid.heldUsd();
|
|
1406
|
+
const due = noteFor({ kind: "model", id: "wrap-up", model: capModel, inputTokens: asked?.inputTokensMax, ...(asked?.outputTokensAsked === undefined ? {} : { outputAsked: asked.outputTokensAsked }), ...(asked?.outputTokensLeast === undefined ? {} : { outputTokensLeast: asked.outputTokensLeast }) }, { capUsd, spentUsd, heldUsd, costs: capNote.costs, told: false, mode: config.mode ?? "expected", now: Date.now() });
|
|
1407
|
+
// The two wrap-ups read as one story: the note tells the model what is left; once what the run keeps back to
|
|
1408
|
+
// answer (tool-budget.ts reserveFor) no longer fits, its tools stop. So the note comes due on that same rule too, if
|
|
1409
|
+
// its own has not made it due before: told on the request whose tool call would be refused now, no later than the
|
|
1410
|
+
// first refusal. The rule's figure here is the run's spend and holds as they stand at this take, and this request's
|
|
1411
|
+
// own reserve. (The gate's reader, wrapUp, reads the records at each call and is async; a reading kept from an
|
|
1412
|
+
// admission would count that request's own hold as taken after it answered.)
|
|
1413
|
+
const atLine = wrappingUp(capUsd, spentUsd + heldUsd, reserveOf(figuresOf(model, asked)));
|
|
1414
|
+
const leftUsd = capUsd - spentUsd - heldUsd;
|
|
1415
|
+
const note = due ?? (atLine ? { words: wrapUpWords(leftUsd, capNote.costs.length === 0), leftUsd } : undefined);
|
|
1416
|
+
capNote.offered = note ? { ...note, capUsd, at: Date.now() } : undefined;
|
|
1417
|
+
return note?.words;
|
|
1418
|
+
};
|
|
1111
1419
|
// The rule before a side effect for every paid model request, on the path every adapter's requests take: the
|
|
1112
1420
|
// booking writes the request's record, then awaits request_start before the request leaves, so the flush here
|
|
1113
1421
|
// makes that record and everything before it durable first (each send, a retry's included).
|
|
@@ -1115,15 +1423,56 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1115
1423
|
key: spec.session.key,
|
|
1116
1424
|
label: spec.session.label,
|
|
1117
1425
|
beforeRequest,
|
|
1426
|
+
note: wrapUpNote,
|
|
1427
|
+
// A request that took it and left before its admission gives it back: the next request may take it at once.
|
|
1428
|
+
noteReturned: (note) => {
|
|
1429
|
+
if (capNote.offered?.words === note)
|
|
1430
|
+
capNote.offered = undefined;
|
|
1431
|
+
},
|
|
1118
1432
|
onEvent: async (event) => {
|
|
1119
|
-
|
|
1433
|
+
// The run's own priced answers, the typical cost the wrap-up is worked out by (a request the host sent beside
|
|
1434
|
+
// the harness's own is not one of them).
|
|
1435
|
+
// (A price from the host's table, `estimated`, is a cost; what bookCut tells of an earlier claim's requests, owed
|
|
1436
|
+
// at their hold or cut, comes before `capNote.live` and is never one.)
|
|
1437
|
+
if (capNote.live && event.type === "request_end" && event.host === undefined && !notOwn.has(event.turn) && typeof event.usage.usd === "number" && event.usage.usd > 0 && !event.usage.cut && !event.usage.givenBack)
|
|
1438
|
+
capNote.costs.push(event.usage.usd);
|
|
1439
|
+
if (event.type === "request_end")
|
|
1440
|
+
requestEnded(event.turn, event.usage, event.ended);
|
|
1441
|
+
if (event.type === "request_start") {
|
|
1442
|
+
// A new request means the model's last message is over: what it said so far is on the record before the request,
|
|
1443
|
+
// so an answer shows while the turn goes on (a CLI that answers, then makes another request).
|
|
1444
|
+
await cliRecord?.flushSaid().catch(() => undefined);
|
|
1445
|
+
// A pi run's answers are its own entries, so a request that leaves is marked on the root before it does: one
|
|
1446
|
+
// with no answer by the time the run settles (a stop or cancel cut it mid-answer) was cut, and a cut request's
|
|
1447
|
+
// cost is unknown, never the $0 an unmarked one reads (timeline REQUEST_STARTED). The other harnesses' requests
|
|
1448
|
+
// are read from the booking (spec.record "loop"), and a host's own side request (event.host: a learned node's, a
|
|
1449
|
+
// web search's) is marked and costed by its own path, never as one of the run's answers.
|
|
1450
|
+
if (spec.record !== "loop" && event.host === undefined && event.label === spec.session.label && harness && gate && !gate.sealed) {
|
|
1451
|
+
const on = harness;
|
|
1452
|
+
const conversation = root ?? (await on.root(context));
|
|
1453
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_STARTED, data: {} }), context);
|
|
1454
|
+
}
|
|
1120
1455
|
await deps.flush();
|
|
1456
|
+
}
|
|
1457
|
+
// Its end, when the request did not answer at a price: the stream ended with no answer or none priced (a stop cut
|
|
1458
|
+
// it), which reads cut and unknown once the run's answer entries are counted; or it never left (a stop landed as it was marked), which withdraws the mark (`unsent`), at no cost.
|
|
1459
|
+
if (event.type === "request_end" && event.ended && (event.ended.end !== "answered" || event.ended.usd === null) && spec.record !== "loop" && event.host === undefined && event.label === spec.session.label && harness && gate && !gate.sealed) {
|
|
1460
|
+
const on = harness;
|
|
1461
|
+
const conversation = root ?? (await on.root(context));
|
|
1462
|
+
const unsent = event.ended.end === "nothing" && event.ended.label === "never_left";
|
|
1463
|
+
// Not written when the journal sealed under it (the run's end landed first): a settled run reads its unanswered
|
|
1464
|
+
// mark cut all the same.
|
|
1465
|
+
await on.commit((tx) => tx.appendEntry(conversation.id, { kind: REQUEST_ENDED, data: (unsent ? { unsent: true } : {}) }), context).catch(() => undefined);
|
|
1466
|
+
}
|
|
1121
1467
|
},
|
|
1122
1468
|
});
|
|
1469
|
+
bookingNow = booking;
|
|
1123
1470
|
// A paid request an earlier claim admitted and never saw answered (its runner lost while the request was out): the
|
|
1124
1471
|
// provider may have billed it, so it is booked once, as cut, at its hold and bound, and told as any answered request
|
|
1125
1472
|
// is, before this claim sends anything (the harness runner's bookCut, main's cut booking).
|
|
1126
1473
|
await booking.bookCut();
|
|
1474
|
+
// This claim's own answers count toward the typical cost from here (bookCut's owed and cut bookings came before).
|
|
1475
|
+
capNote.live = true;
|
|
1127
1476
|
// A paid tool call an earlier claim admitted and never saw settled is booked the same way, cut, at its hold, its
|
|
1128
1477
|
// charge unknown: it may have run and been charged before the claim was lost. Its session opens only for a paid call
|
|
1129
1478
|
// of this claim, and a replay the gate refuses makes none, so it is opened here for the cut alone, never read as free.
|
|
@@ -1141,13 +1490,16 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1141
1490
|
const capUsd = capNow();
|
|
1142
1491
|
if (capUsd === undefined)
|
|
1143
1492
|
return false;
|
|
1144
|
-
|
|
1493
|
+
// What was spent beside the run on its behalf counts as taken, as its sessions' spend does.
|
|
1494
|
+
let taken = await besideNow();
|
|
1145
1495
|
for (const key of await sessions.keys()) {
|
|
1146
1496
|
const read = sessionSpendOf(await sessions.read(key));
|
|
1147
1497
|
const reserved = [...read.openHolds].reduce((sum, turn) => sum + (read.held.get(turn) ?? 0), 0);
|
|
1148
1498
|
taken = taken === null || read.spentUsd === null ? null : taken + read.spentUsd + reserved;
|
|
1149
1499
|
}
|
|
1150
|
-
|
|
1500
|
+
// What the run keeps back to answer, priced on the main model's last request admitted on this claim (its next one
|
|
1501
|
+
// is priced at least as high): none yet, no wrap-up, as no tool call comes before a request.
|
|
1502
|
+
return wrappingUp(capUsd, taken, reserveOf(capNote.lastFigures));
|
|
1151
1503
|
};
|
|
1152
1504
|
const gateOf = preIntentGate(spec, hooks, wrapUp);
|
|
1153
1505
|
// A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
|
|
@@ -1155,6 +1507,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1155
1507
|
cliRecord = record;
|
|
1156
1508
|
// Each tool the session runs on the host, the host's own and any its adapter adds (SessionIO.hostTool: a CLI's
|
|
1157
1509
|
// read_skill_file), the same way: a CLI's call on its record, so the run's Timeline shows it and its result.
|
|
1510
|
+
/** A tool call's computer calls (computer-calls.ts), kept on the run's root beside the call, by its id. */
|
|
1511
|
+
const keepCalls = async (call, calls, dropped) => {
|
|
1512
|
+
const [journalOf, rootOf] = [harness, root];
|
|
1513
|
+
if (!journalOf || !rootOf || gate?.sealed)
|
|
1514
|
+
return;
|
|
1515
|
+
await journalOf.commit((tx) => tx.appendEntry(rootOf.id, { kind: COMPUTER_CALLS, data: { call, calls, ...(dropped > 0 ? { dropped } : {}) } }), context);
|
|
1516
|
+
};
|
|
1158
1517
|
const hosted = (tool) => ({
|
|
1159
1518
|
...tool,
|
|
1160
1519
|
// The rule before a side effect, on the host-tool path every adapter's calls take: after the call's intent, a
|
|
@@ -1183,10 +1542,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1183
1542
|
return { text: now.deny, isError: true };
|
|
1184
1543
|
// Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
|
|
1185
1544
|
// replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
|
|
1186
|
-
// the claim lets it go; a deny says the earlier attempt may have taken effect.
|
|
1187
|
-
|
|
1545
|
+
// the claim lets it go; a deny says the earlier attempt may have taken effect. Asked and not answered yet, with
|
|
1546
|
+
// the setting at allow now: the setting answers the ask (allowedBySetting).
|
|
1547
|
+
const bySetting = now === "allow" && (await askStands(toolContext.callId));
|
|
1548
|
+
if (now === "ask" || bySetting) {
|
|
1188
1549
|
const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
|
|
1189
|
-
const
|
|
1550
|
+
const price = mcp?.priceOf(name) ?? spec.approvalPrice?.({ ...call, tool: name }) ?? null;
|
|
1551
|
+
const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
|
|
1190
1552
|
if (answer === "park")
|
|
1191
1553
|
return await heldUntilAborted(toolContext.signal);
|
|
1192
1554
|
if (!answer.approved)
|
|
@@ -1207,7 +1569,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1207
1569
|
// refused for room pauses the run (Ledger.pause, the run's pause), as main's paidCall does.
|
|
1208
1570
|
// The calls it may make of the run's other tools (a learned workflow's MCP nodes: host-calls.ts), each as this
|
|
1209
1571
|
// loop wrapped it, and whether a person approved this call.
|
|
1210
|
-
|
|
1572
|
+
// The computer protocol calls it makes, kept beside it on the run's root (COMPUTER_CALLS) for its result
|
|
1573
|
+
// row's computer_calls, before its result is written.
|
|
1574
|
+
route: () => bookedIn({ call: toolContext.callId, record: async () => { }, paid, pause: ledger.pause }, () => withHostCalls({ mcp: mcpHosted, approved: approvedCalls.get(toolContext.callId) }, () => recordingCalls(() => tool.call(args, { ...toolContext, signal: toolContext.signal ? AbortSignal.any([toolContext.signal, stopAbort.signal]) : stopAbort.signal }), (calls, dropped) => keepCalls(toolContext.callId, calls, dropped)))),
|
|
1211
1575
|
beforeResult: async (answer) => {
|
|
1212
1576
|
const call = { callId: toolContext.callId, tool: tool.name, args: (args ?? {}) };
|
|
1213
1577
|
try {
|
|
@@ -1252,8 +1616,41 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1252
1616
|
mcpStale = false;
|
|
1253
1617
|
await mcp.fresh();
|
|
1254
1618
|
}
|
|
1619
|
+
// The wrap-up this request carries, taken off the offer now: its admission tells it; a refusal (the throw below)
|
|
1620
|
+
// or a dropped note leaves it untold, to be offered to a later request.
|
|
1621
|
+
const offer = request.noted ? capNote.offered : undefined;
|
|
1622
|
+
if (offer)
|
|
1623
|
+
capNote.offered = undefined;
|
|
1255
1624
|
const ticket = await port.beforeRequest(request);
|
|
1256
1625
|
unbooked += 1;
|
|
1626
|
+
// The harness's own side call (a title request on its smaller model): never a typical cost of its main requests.
|
|
1627
|
+
if (ticket && request.side)
|
|
1628
|
+
notOwn.add(ticket.turn);
|
|
1629
|
+
// The main model's request as the cap prices it: what the run keeps back to answer is priced on it (wrapUp).
|
|
1630
|
+
if (!request.side && request.host === undefined)
|
|
1631
|
+
capNote.lastFigures = figuresOf(request.model, request) ?? capNote.lastFigures;
|
|
1632
|
+
// What follows is the wrap-up's own bookkeeping, after the request was admitted and its hold booked: it never fails
|
|
1633
|
+
// the request (a throw here would leave it admitted and never sent, read as cut at its worst case).
|
|
1634
|
+
try {
|
|
1635
|
+
capNote.restUsd = await restOf();
|
|
1636
|
+
}
|
|
1637
|
+
catch (error) {
|
|
1638
|
+
capNote.restUsd = null;
|
|
1639
|
+
console.warn(`[runner] the run's other sessions' spend was not read; no wrap-up until it is: ${said(error)}`);
|
|
1640
|
+
}
|
|
1641
|
+
// Told once a request carrying it is admitted with it (never one that went without the note's bytes): the server's
|
|
1642
|
+
// row, once per cap, made durable before the request leaves, so a machine lost after it never tells that cap twice.
|
|
1643
|
+
if (offer && ticket && !ticket.noteDropped && !toldAt(offer.capUsd)) {
|
|
1644
|
+
const { words, leftUsd, capUsd } = offer;
|
|
1645
|
+
toldCaps.push(capUsd);
|
|
1646
|
+
try {
|
|
1647
|
+
await wrapUpHarness.commit((tx) => tx.appendEntry(wrapUpRoot.id, { kind: CAP_WRAPUP, data: { words, leftUsd, capUsd } }), context);
|
|
1648
|
+
await deps.flush();
|
|
1649
|
+
}
|
|
1650
|
+
catch (error) {
|
|
1651
|
+
console.warn(`[runner] the wrap-up's row was not written (the note went with the request): ${said(error)}`);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1257
1654
|
return ticket;
|
|
1258
1655
|
},
|
|
1259
1656
|
afterRequest: async (...args) => {
|
|
@@ -1270,6 +1667,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1270
1667
|
},
|
|
1271
1668
|
...(port.responded ? { responded: port.responded.bind(port) } : {}),
|
|
1272
1669
|
...(port.note ? { note: port.note.bind(port) } : {}),
|
|
1670
|
+
...(port.noteReturned ? { noteReturned: port.noteReturned.bind(port) } : {}),
|
|
1273
1671
|
};
|
|
1274
1672
|
// What the request that just answered cost, once the session's requests are booked (bookingOfAnswer): its own
|
|
1275
1673
|
// booking's figure, null when unknown; a side request's is given and never read. A refused request's record is its $0.
|
|
@@ -1303,10 +1701,17 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1303
1701
|
const answer = await askingGate(call, hookContext);
|
|
1304
1702
|
if (answer !== "allow" && "deny" in answer)
|
|
1305
1703
|
await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
|
|
1704
|
+
// A harness's own tool (Claude Code's WebSearch, which its provider runs) the gate held and a person now lets
|
|
1705
|
+
// run: the host runs nothing of this call, so the start it parked ends here; the harness's next call runs it.
|
|
1706
|
+
else if (answer === "allow" && approvedCalls.has(call.callId) && !tools.some((one) => one.name === call.tool))
|
|
1707
|
+
await record.end(call.callId, "done", OWN_TOOL_RELEASED);
|
|
1306
1708
|
return answer;
|
|
1307
1709
|
}
|
|
1308
1710
|
: gateOf;
|
|
1309
|
-
|
|
1711
|
+
// A tool no call of which reaches the gate before it runs (Codex's live search, inside its model requests): its
|
|
1712
|
+
// setting now, read again at each request, so a deny or ask set mid-run reaches the next one.
|
|
1713
|
+
const permission = spec.gate?.permission;
|
|
1714
|
+
const io = { writer, models: counted, signal: deps.signal, onEvent: record ? (event) => record.onEvent(event) : () => { }, gate: bridgeGate, ...(permission ? { permission } : {}), hostTool: hosted, bookedCost };
|
|
1310
1715
|
// The MCP tools: pi's own (host tools, through the gate above); for a harness with its own MCP client, the session's
|
|
1311
1716
|
// MCP its adapter mounts on its proxy, each call asking the gate first (an ask parks the run, nothing sent).
|
|
1312
1717
|
const mcpNames = new Set(mcp?.tools.map((tool) => tool.name));
|
|
@@ -1339,15 +1744,37 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1339
1744
|
// fence), and the computer shows up, the agent driving.
|
|
1340
1745
|
computerNow?.detach();
|
|
1341
1746
|
computerNow = undefined;
|
|
1747
|
+
channelNow = undefined;
|
|
1342
1748
|
if (spec.computer) {
|
|
1343
1749
|
const [journalOf, rootOf] = [harness, root];
|
|
1344
|
-
|
|
1750
|
+
channelNow = { computer: spec.computer, commit: (entries) => journalOf.commit(async (tx) => {
|
|
1751
|
+
for (const entry of entries)
|
|
1752
|
+
await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
|
|
1753
|
+
}, context) };
|
|
1754
|
+
}
|
|
1755
|
+
if (spec.computer?.hold && spec.computer.kind !== "sandbox") {
|
|
1756
|
+
const [journalOf, rootOf] = [harness, root];
|
|
1757
|
+
computerNow = journalHold(claim.runId, { kind: spec.computer.kind, hold: spec.computer.hold }, (entries) => journalOf.commit(async (tx) => {
|
|
1345
1758
|
for (const entry of entries)
|
|
1346
1759
|
await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
|
|
1347
1760
|
}, context), now);
|
|
1348
1761
|
// The run's journal so far: a take an earlier claim's computer left in force ends released here (computer-journal.ts).
|
|
1349
1762
|
await computerNow.up(await entriesOf(gate.journal, root.id, context));
|
|
1350
1763
|
}
|
|
1764
|
+
// The run's computer held for its owner: the hold starts waiting on the run's first pass. A later pass's computer
|
|
1765
|
+
// (a new claim's, or a restart's after a fault: closeSession let the last one go) is not the one an open hold held,
|
|
1766
|
+
// nor has what the owner set up on it: the run ends in those words.
|
|
1767
|
+
heldNow = undefined;
|
|
1768
|
+
if (spec.held) {
|
|
1769
|
+
const [journalOf, rootOf] = [harness, root];
|
|
1770
|
+
heldNow = journalHeld(spec.held, (entries) => journalOf.commit(async (tx) => {
|
|
1771
|
+
for (const entry of entries)
|
|
1772
|
+
await tx.appendEntry(rootOf.id, { kind: entry.kind, data: entry.data });
|
|
1773
|
+
}, context), now);
|
|
1774
|
+
if ((await heldNow.up(await entriesOf(gate.journal, root.id, context))) === "lost") {
|
|
1775
|
+
return await writeEnd(harness, root, gate, { state: "failed", summary: heldWords.lost }, []);
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1351
1778
|
// The cap a raise left the run at, before any request of this claim, through the one reader the run view and its
|
|
1352
1779
|
// budget card read too (capNowOf: the newest raise entry, else the launch's cap): a claim that takes over a raised
|
|
1353
1780
|
// run (a resume, another runner's, a restarted server's) holds it to the raise, never the launch's cap.
|
|
@@ -1402,10 +1829,29 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1402
1829
|
}
|
|
1403
1830
|
}
|
|
1404
1831
|
opened();
|
|
1832
|
+
// A channel call a fault's restart cut off from its pass: its record is written through this one.
|
|
1833
|
+
settleCalls();
|
|
1405
1834
|
await reportHeld(harness, root.id);
|
|
1406
1835
|
if (restarts > restartLimit + 1) {
|
|
1407
1836
|
return await writeEnd(harness, root, gate, { state: "failed", summary: `the kernel faulted on every restart (${restarts} restarts)` }, [], await cutRows(claim, spec, "faulted"));
|
|
1408
1837
|
}
|
|
1838
|
+
// A held computer waits for its owner's start before the agent's first input; the owner's calls set the task up
|
|
1839
|
+
// meanwhile. A release, or no call for the hold's minutes, ends the run before its agent ever ran. A stop ends it
|
|
1840
|
+
// stopped, and a lost claim leaves it for the next claim.
|
|
1841
|
+
if (heldNow?.state() === "waiting") {
|
|
1842
|
+
const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
|
|
1843
|
+
const waited = await heldNow.untilStarted(Promise.race([stopping, aborted, harness.closed]));
|
|
1844
|
+
// Set by stop() during the wait: read past the narrowing TypeScript did before it.
|
|
1845
|
+
const cut = stopReason;
|
|
1846
|
+
if (cut?.kind === "command")
|
|
1847
|
+
return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
|
|
1848
|
+
if (cut || deps.signal.aborted || waited === "cut")
|
|
1849
|
+
return await interrupted(cut?.kind ?? "its claim's signal aborted");
|
|
1850
|
+
if (heldNow.state() === "released") {
|
|
1851
|
+
const why = heldNow.lapse() === "timeout" ? heldWords.timeout(spec.held.minutes) : "The owner released the computer before the agent started";
|
|
1852
|
+
return await writeEnd(harness, root, gate, { state: "stopped", outcome: "cancelled", summary: why }, []);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1409
1855
|
let followedUp = false;
|
|
1410
1856
|
if (raising.resuming) {
|
|
1411
1857
|
// Every row that woke it has reached its command() first (deps.delivered), so raises sent together are taken
|
|
@@ -1456,7 +1902,13 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1456
1902
|
const wrapped = new Map(tools.map((tool) => [tool.name, tool]));
|
|
1457
1903
|
const follow = await parkedFollowUp(mcp, {
|
|
1458
1904
|
entries: await entriesOf(gate.journal, root.id, context),
|
|
1459
|
-
|
|
1905
|
+
// As the gate before an intent does: a call still waiting on its person whose tool now reads allow is answered by
|
|
1906
|
+
// the setting (allowedBySetting); any other waits for the person's answer.
|
|
1907
|
+
answer: async (call, price) => {
|
|
1908
|
+
const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
|
|
1909
|
+
const bySetting = now === "allow" && (await askStands(call.callId));
|
|
1910
|
+
return bySetting ? allowedBySetting(call, price, call.tool) : answerOf(call, price);
|
|
1911
|
+
},
|
|
1460
1912
|
deniedNow: async (call) => {
|
|
1461
1913
|
// The gate is Promise-capable on purpose (run-cap's and the approvals' gates may look things up), so await it.
|
|
1462
1914
|
const now = await spec.gate?.({ callId: call.callId, tool: call.tool, args: call.args });
|
|
@@ -1520,6 +1972,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1520
1972
|
}
|
|
1521
1973
|
else if (session.state === "open_turn")
|
|
1522
1974
|
await session.recover();
|
|
1975
|
+
// A message handed over while the session was new is placed from here on, after what was just sent.
|
|
1976
|
+
inputSent();
|
|
1523
1977
|
// The turn this claim waits on: the first, then each the person's answer starts while the run waits in its claim on
|
|
1524
1978
|
// its question (waitInClaim: ask_person with the browser open); "lapsed" when such a wait can no longer hold.
|
|
1525
1979
|
let turn = placed ? session.turnEnd() : idleTurnOf(harness, root);
|
|
@@ -1572,6 +2026,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1572
2026
|
const outcome = (await turn);
|
|
1573
2027
|
// What the model said last, on the record before the run's end.
|
|
1574
2028
|
await record?.flushText();
|
|
2029
|
+
// The turn's end on the record, after its last text: a CLI run reads working until here.
|
|
2030
|
+
await record?.turnEnded(outcome.status, outcome.error === undefined ? undefined : deps.redact ? deps.redact(outcome.error) : outcome.error);
|
|
1575
2031
|
await harness.waitForIdle(context);
|
|
1576
2032
|
const settledEntries = await entriesOf(gate.journal, root.id, context);
|
|
1577
2033
|
const cutOff = restartLimited(settledEntries);
|
|
@@ -1579,6 +2035,20 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1579
2035
|
// answer booked: main's end of a run over its cap, before any pause (a question to the person, a cap refusal).
|
|
1580
2036
|
await bookingsSettled();
|
|
1581
2037
|
const over = cutOff ? undefined : await overCap();
|
|
2038
|
+
// A failed CLI turn: a message the person sent while it ran may not have reached the loop yet (the runner's next
|
|
2039
|
+
// poll), and the run's status is its last turn's end, so it is handed on now (bounded), as a finished turn's is.
|
|
2040
|
+
if (!cutOff && !over && !refused && outcome.status === "failed" && spec.record === "loop" && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow && !stopReason) {
|
|
2041
|
+
let bound;
|
|
2042
|
+
await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
|
|
2043
|
+
clearTimeout(bound);
|
|
2044
|
+
// A stop or cancel among the delivered rows: the run ends stopped in its words, never failed. Read past the
|
|
2045
|
+
// narrowing TypeScript did before the delivery.
|
|
2046
|
+
const cutBy = stopReason;
|
|
2047
|
+
if (cutBy?.kind === "command")
|
|
2048
|
+
return await writeEnd(harness, root, gate, stopEnd(cutBy.cancel), [cutBy.commandId], await cutRows(claim, spec, "stopped"));
|
|
2049
|
+
if (cutBy || deps.signal.aborted)
|
|
2050
|
+
return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
|
|
2051
|
+
}
|
|
1582
2052
|
if (cutOff)
|
|
1583
2053
|
data = { state: "failed", summary: `a tool call faulted on every restart: ${cutOff}` };
|
|
1584
2054
|
else if (over)
|
|
@@ -1598,6 +2068,22 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1598
2068
|
return await parkAtCap(harness, root, gate, { pending: park.pending, words: park.words });
|
|
1599
2069
|
data = { state: "failed", summary: park?.outcome === "failed" ? park.error : refused.refuse };
|
|
1600
2070
|
}
|
|
2071
|
+
else if (outcome.status === "failed" && spec.record === "loop" && afterTurn.length > 0 && !stopReason && !deps.signal.aborted) {
|
|
2072
|
+
// A CLI turn that failed with a message queued behind it: the run's status is its last turn's end, so the
|
|
2073
|
+
// queued message's turn runs, and the failure stays in the timeline as the error row a chat keeps before a good
|
|
2074
|
+
// answer (the same row the run's end would have written).
|
|
2075
|
+
const said = outcome.error?.trim() ?? "";
|
|
2076
|
+
const rootId = root.id;
|
|
2077
|
+
await harness.commit((tx) => tx.appendEntry(rootId, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", said ? cutWhole(deps.redact ? deps.redact(said) : said, TURN_ERROR_MAX) : "the turn gave no answer (failed)", now())] }), context);
|
|
2078
|
+
turn = sendAfterTurn(gate, afterTurn.shift());
|
|
2079
|
+
continue;
|
|
2080
|
+
}
|
|
2081
|
+
else if (outcome.status === "interrupted" && spec.record === "loop" && !outcome.error?.trim()) {
|
|
2082
|
+
// A CLI turn its harness ended on its own, with no stop or cancel from a person and no error of its own: the
|
|
2083
|
+
// turn is over, the run is not. It waits for the person as after a stop (a message reopens it), never failed
|
|
2084
|
+
// with no answer (the status reader's contract: an interrupted newest turn is input_required, turns.ts).
|
|
2085
|
+
data = { state: "stopped", outcome: "stopped", summary: "the turn was interrupted" };
|
|
2086
|
+
}
|
|
1601
2087
|
else if (outcome.status !== "completed") {
|
|
1602
2088
|
// A turn that ended on its harness's own error (a CLI's: a codex run whose MCP door could not be reached) fails
|
|
1603
2089
|
// the run in those words, bounded; serve redacts a run's summary as it serves it, as every summary. With none,
|
|
@@ -1684,6 +2170,24 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1684
2170
|
if (cut || deps.signal.aborted)
|
|
1685
2171
|
return await interrupted(cut?.kind ?? "its claim's signal aborted");
|
|
1686
2172
|
}
|
|
2173
|
+
// A held computer stays the owner's after the agent's end, for their checks: the run's end, and its computer's
|
|
2174
|
+
// release after it, wait for the owner's release or the hold's lapse. A person's stop keeps waiting (writeEnd), the
|
|
2175
|
+
// run then ending stopped; a cancel ends it at once, and a lost claim leaves it for the next claim.
|
|
2176
|
+
if (heldNow) {
|
|
2177
|
+
const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
|
|
2178
|
+
handingBack = true;
|
|
2179
|
+
const waited = await heldNow.heldAtEnd(Promise.race([stopping, aborted, harness.closed]));
|
|
2180
|
+
const cut = stopReason;
|
|
2181
|
+
if (cut?.kind === "command")
|
|
2182
|
+
return await writeEnd(harness, root, gate, stopEnd(cut.cancel), [cut.commandId], await cutRows(claim, spec, "stopped"));
|
|
2183
|
+
if (cut || deps.signal.aborted || waited === "cut")
|
|
2184
|
+
return await interrupted(cut?.kind ?? "its claim's signal aborted");
|
|
2185
|
+
}
|
|
2186
|
+
// A stop or cancel the runner handed on as the turn was failing (it hands rows on as they are written) is taken by
|
|
2187
|
+
// this end, which is the stop's own: with the turn's failure the end, its row would be handed on and never taken.
|
|
2188
|
+
const failingStop = data.state === "failed" ? stopReason : undefined;
|
|
2189
|
+
if (failingStop?.kind === "command")
|
|
2190
|
+
return await writeEnd(harness, root, gate, stopEnd(failingStop.cancel), [failingStop.commandId], await cutRows(claim, spec, "stopped"));
|
|
1687
2191
|
// The end-of-run step, once, before the end: its rows ride in the end commit. A stop or a lost claim during it
|
|
1688
2192
|
// writes no end of the job's (a person's stop ends the run stopped; a lost claim leaves it for the next claim).
|
|
1689
2193
|
const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed");
|
|
@@ -1724,6 +2228,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1724
2228
|
held?.detach();
|
|
1725
2229
|
computerNow?.detach();
|
|
1726
2230
|
computerNow = undefined;
|
|
2231
|
+
heldNow = undefined;
|
|
2232
|
+
channelNow = undefined;
|
|
1727
2233
|
handingBack = false;
|
|
1728
2234
|
deps.live?.(() => undefined);
|
|
1729
2235
|
// A tool host's beforeRelease, when no end or park let it go first (a shutdown, a lost claim): the Harness still open.
|
|
@@ -1766,7 +2272,10 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1766
2272
|
// Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
|
|
1767
2273
|
if (decision === "deny")
|
|
1768
2274
|
return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
|
|
1769
|
-
|
|
2275
|
+
// A call a person was asked about and has not answered, its setting at allow now: the setting answers the ask
|
|
2276
|
+
// (allowedBySetting), and the call runs without asking the person again.
|
|
2277
|
+
const bySetting = decision === "allow" && !!spec.gate && (await askStands(call.callId));
|
|
2278
|
+
if (decision === "allow" && !bySetting)
|
|
1770
2279
|
return "allow";
|
|
1771
2280
|
// The card shows the call's input, and beside it what the gate says the call would do that the person approves too
|
|
1772
2281
|
// (a learned workflow's MCP calls set to ask: askedFor).
|
|
@@ -1776,7 +2285,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1776
2285
|
const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
|
|
1777
2286
|
// The call on the record before its ask (beforeAsk), with the input its model gave it.
|
|
1778
2287
|
await beforeAsk?.(call);
|
|
1779
|
-
const
|
|
2288
|
+
const price = mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null;
|
|
2289
|
+
const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked);
|
|
1780
2290
|
if (answer === "park")
|
|
1781
2291
|
return { park: true };
|
|
1782
2292
|
// A call a person approved: what it runs inside its own call (a learned workflow's MCP nodes set to ask) runs as
|
|
@@ -1807,23 +2317,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1807
2317
|
// The ask names the call as the person is asked about it (`asked`: its settings key), so every reader of the ask (the
|
|
1808
2318
|
// run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
|
|
1809
2319
|
const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price };
|
|
1810
|
-
|
|
1811
|
-
// of the round parked the run): nothing landed, and the expectation's failure is no one's to wait on.
|
|
1812
|
-
const entryLands = async (kind, data, staged) => {
|
|
1813
|
-
const landed = gate.expect(writesEntry(kind, (entry) => entry.callId === data.callId), staged);
|
|
1814
|
-
// A seal while the commit is in flight fails it before it is awaited: handled here, read by the await below.
|
|
1815
|
-
landed.catch(() => undefined);
|
|
1816
|
-
try {
|
|
1817
|
-
await harness.commit((tx) => tx.appendEntry(conversation.id, { kind, data: data }), context);
|
|
1818
|
-
await landed;
|
|
1819
|
-
return true;
|
|
1820
|
-
}
|
|
1821
|
-
catch (error) {
|
|
1822
|
-
if (gate.sealed)
|
|
1823
|
-
return false;
|
|
1824
|
-
throw error;
|
|
1825
|
-
}
|
|
1826
|
-
};
|
|
2320
|
+
const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
|
|
1827
2321
|
if (first === undefined) {
|
|
1828
2322
|
// Asked and parked; or held as the parked call is, when another call of the round parked the run first.
|
|
1829
2323
|
if (await entryLands(KINDS.ask, ask, { run: { state: "parked" } }))
|
|
@@ -1853,6 +2347,67 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1853
2347
|
await new Promise((resolve) => (wakeInbox = resolve));
|
|
1854
2348
|
}
|
|
1855
2349
|
}
|
|
2350
|
+
/** Commits the root's entry of `kind`, staging `staged` with it. False when the journal is sealed first (another call
|
|
2351
|
+
* of the round parked the run): nothing landed, and the expectation's failure is no one's to wait on. */
|
|
2352
|
+
async function landEntry(conversation, kind, data, staged) {
|
|
2353
|
+
const landed = gate.expect(writesEntry(kind, (entry) => entry.callId === data.callId), staged);
|
|
2354
|
+
// A seal while the commit is in flight fails it before it is awaited: handled here, read by the await below.
|
|
2355
|
+
landed.catch(() => undefined);
|
|
2356
|
+
try {
|
|
2357
|
+
await harness.commit((tx) => tx.appendEntry(conversation.id, { kind, data: data }), context);
|
|
2358
|
+
await landed;
|
|
2359
|
+
return true;
|
|
2360
|
+
}
|
|
2361
|
+
catch (error) {
|
|
2362
|
+
if (gate.sealed)
|
|
2363
|
+
return false;
|
|
2364
|
+
throw error;
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
/** The answer to an ask a person was shown and has not answered, once its tool's setting reads allow: the setting
|
|
2368
|
+
* answers it. The ask closes with an allow row of its own (by "setting": "Allowed by the tool's setting"), the call
|
|
2369
|
+
* runs, and the person is never asked again. A person's answer already in the inbox for the call stands over it when it
|
|
2370
|
+
* is a deny; an allow of theirs is taken with the setting's answer, so no row is left untaken. */
|
|
2371
|
+
async function allowedBySetting(call, price, asked) {
|
|
2372
|
+
// Decided only once the claim's stored commands are with the loop (deps.delivered): pi's recovery starts tool tasks while
|
|
2373
|
+
// the session opens, before command() can put a person's stored deny into the inbox, and the setting must not win over it.
|
|
2374
|
+
await (deps.delivered ?? Promise.resolve());
|
|
2375
|
+
const row = inbox.find((command) => (command.kind === "approve" || command.kind === "deny") && approvalOf(command) === call.callId);
|
|
2376
|
+
if (row?.kind === "deny")
|
|
2377
|
+
return answerOf(call, price, asked);
|
|
2378
|
+
const conversation = await harness.root(context);
|
|
2379
|
+
const data = { callId: call.callId, approved: true, decision: "allow", answeredAt: isoNow(), by: "setting" };
|
|
2380
|
+
if (row)
|
|
2381
|
+
inbox.splice(inbox.indexOf(row), 1);
|
|
2382
|
+
if (!(await landEntry(conversation, KINDS.answer, data, { take: row ? [row.id] : [] })))
|
|
2383
|
+
return "park";
|
|
2384
|
+
// The call's ask, as journaled: kept for the caller, which scopes an approval to it.
|
|
2385
|
+
const first = findData(await entriesOf(gate.journal, conversation.id, context), KINDS.ask, (ask) => ask.callId === call.callId);
|
|
2386
|
+
if (first)
|
|
2387
|
+
askedArgs.set(call.callId, first.args);
|
|
2388
|
+
return data;
|
|
2389
|
+
}
|
|
2390
|
+
/** Whether a person was asked about this call and has not answered yet (an ask in the journal, no answer): its card is
|
|
2391
|
+
* theirs, so the call waits for that answer (answerOf) even when its tool's setting reads allow by now, and runs on
|
|
2392
|
+
* their allow, its rows reading so. Let through on the setting alone, it ran with its ask unanswered, which the run's
|
|
2393
|
+
* end reads withdrawn: its rows said "Not run: the run ended while it waited" of a call that ran. A deny set since still
|
|
2394
|
+
* refuses it first. Read from the journal once a claim: an ask written later in the claim parks it, and an answer
|
|
2395
|
+
* written later is read by answerOf itself. */
|
|
2396
|
+
async function askStands(callId) {
|
|
2397
|
+
standing ??= (async () => {
|
|
2398
|
+
const conversation = await harness.root(context);
|
|
2399
|
+
const entries = await entriesOf(gate.journal, conversation.id, context);
|
|
2400
|
+
const answered = new Set(entries.filter((entry) => entry.kind === KINDS.answer).map((entry) => entry.data.callId));
|
|
2401
|
+
return new Set(entries.filter((entry) => entry.kind === KINDS.ask).map((entry) => entry.data.callId).filter((id) => !answered.has(id)));
|
|
2402
|
+
})();
|
|
2403
|
+
// A read that failed (a seal while it ran) is read again by the next call, never kept.
|
|
2404
|
+
const read = standing;
|
|
2405
|
+
return (await read.catch((error) => {
|
|
2406
|
+
if (standing === read)
|
|
2407
|
+
standing = undefined;
|
|
2408
|
+
throw error;
|
|
2409
|
+
})).has(callId);
|
|
2410
|
+
}
|
|
1856
2411
|
/** A call parked from inside its run (a rerun asked again): held unrun until its signal aborts (the pass ends on the
|
|
1857
2412
|
* park), then thrown, so nothing of it is answered in this pass. */
|
|
1858
2413
|
function heldUntilAborted(signal) {
|
|
@@ -1964,7 +2519,8 @@ function adapterLoop(specOf, options, deps) {
|
|
|
1964
2519
|
return { status: "completed" };
|
|
1965
2520
|
}
|
|
1966
2521
|
const submission = await on.submission(found.id, context);
|
|
1967
|
-
|
|
2522
|
+
// Never on the claim's signal (durableWait): an abort while it registers is this wait's rejection, never one unhandled.
|
|
2523
|
+
const record = submission ? await durableWait((at) => submission.wait(at), context) : undefined;
|
|
1968
2524
|
return { status: !record || record.status === "done" ? "completed" : "failed" };
|
|
1969
2525
|
}
|
|
1970
2526
|
/** The run waits in its claim on the person's answer to its question (ask_person `callId` ended its turn) when a tool
|
|
@@ -2097,7 +2653,7 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2097
2653
|
if (!spec.agentId)
|
|
2098
2654
|
throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
|
|
2099
2655
|
try {
|
|
2100
|
-
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) });
|
|
2656
|
+
const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1) });
|
|
2101
2657
|
return cut() ?? { kind: "rows", also: rows?.also ?? [] };
|
|
2102
2658
|
}
|
|
2103
2659
|
catch (error) {
|
|
@@ -2130,17 +2686,17 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2130
2686
|
clearTimeout(timer);
|
|
2131
2687
|
}
|
|
2132
2688
|
}
|
|
2133
|
-
/** The end-of-run turn: one more turn through the run's session, its request id one per run (a repeat is
|
|
2134
|
-
* its submission, so a later claim never asks the model again
|
|
2135
|
-
* `again`: its re-ask, a request of its own (one
|
|
2136
|
-
* it throws, and the step sees why. */
|
|
2137
|
-
async function askEndOfRun(claim, prompt, deadlineMs, again = false) {
|
|
2689
|
+
/** The end-of-run turn: one more turn through the run's session, its request id one per round of the run (a repeat is
|
|
2690
|
+
* answered from its submission, so a later claim never asks the model again; a follow-up's end is the next `round`,
|
|
2691
|
+
* asked anew), its writes under work/.learning/ refused while it runs. `again`: its re-ask, a request of its own (one
|
|
2692
|
+
* per round too). Aborted at `deadlineMs`. A stop or a lost claim cuts it: it throws, and the step sees why. */
|
|
2693
|
+
async function askEndOfRun(claim, prompt, deadlineMs, again = false, round = 1) {
|
|
2138
2694
|
if (!session || !harness || !gate || !root)
|
|
2139
2695
|
throw new Error("the run's session is not open");
|
|
2140
2696
|
const on = harness;
|
|
2141
2697
|
const conversation = root;
|
|
2142
2698
|
const theSession = session;
|
|
2143
|
-
const requestId = reflectRequestId(claim.runId, again);
|
|
2699
|
+
const requestId = reflectRequestId(claim.runId, again, round);
|
|
2144
2700
|
const theRecord = cliRecord;
|
|
2145
2701
|
reflecting = true;
|
|
2146
2702
|
let timer;
|
|
@@ -2250,6 +2806,20 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2250
2806
|
/** `failedWith`: a CLI turn's own error (record "loop"), cut of every secret the runner holds: written in the end's
|
|
2251
2807
|
* commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn. */
|
|
2252
2808
|
async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith) {
|
|
2809
|
+
// A person's stop of a run that holds its computer ends its agent, not the hold (computer-held.ts): the end, and the
|
|
2810
|
+
// computer's release after it, wait for the owner's release or the hold's lapse, the owner's calls still answered.
|
|
2811
|
+
// A cancel, a lost claim or a shutdown meanwhile ends the wait; a cancel's end is then the run's, taking both rows.
|
|
2812
|
+
const stop = stopReason;
|
|
2813
|
+
if (stop?.kind === "command" && keptAtStop && take.includes(stop.commandId) && heldNow && heldNow.state() !== "released" && !theGate.sealed) {
|
|
2814
|
+
const aborted = new Promise((resolve) => (deps.signal.aborted ? resolve() : deps.signal.addEventListener("abort", () => resolve(), { once: true })));
|
|
2815
|
+
handingBack = true;
|
|
2816
|
+
await heldNow.heldAtEnd(Promise.race([heldCut, aborted, on.closed]), heldWords.stopped(heldNow.minutes));
|
|
2817
|
+
const later = laterStop;
|
|
2818
|
+
if (later?.kind === "command" && later.cancel) {
|
|
2819
|
+
base = { ...base, ...stopEnd(true) };
|
|
2820
|
+
take = [...take, later.commandId];
|
|
2821
|
+
}
|
|
2822
|
+
}
|
|
2253
2823
|
// The end is the run's release: nothing of this claim lands after it, so the tool host is let go first (its writes in
|
|
2254
2824
|
// their own commits, the end's patch reading the cost they book), and its requests' bookings come first.
|
|
2255
2825
|
await releaseHost(on);
|
|
@@ -2284,6 +2854,9 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2284
2854
|
await tx.appendEntry(conversation.id, { kind: KINDS.answer, data: answer });
|
|
2285
2855
|
for (const callId of recordEnds)
|
|
2286
2856
|
await tx.appendEntry(conversation.id, { kind: KINDS.callEnd, data: { callId, status: "refused", output: notRun, at: now() } });
|
|
2857
|
+
// A turn the run ends while it is open (a stop or cancel cut it, or the run failed in it) ends with the run.
|
|
2858
|
+
if (cliRecord?.openTurn())
|
|
2859
|
+
await tx.appendEntry(conversation.id, { kind: KINDS.turnEnd, data: { status: data.state === "failed" ? "failed" : data.state === "stopped" ? "interrupted" : "completed" } });
|
|
2287
2860
|
if (failedWith !== undefined)
|
|
2288
2861
|
await tx.appendEntry(conversation.id, { kind: PI_ASSISTANT, model: [cliErrorAnswer(specNow?.adapter.id ?? "cli", failedWith, now())] });
|
|
2289
2862
|
return tx.appendEntry(conversation.id, { kind: KINDS.end, data: data });
|
|
@@ -2333,12 +2906,25 @@ function adapterLoop(specOf, options, deps) {
|
|
|
2333
2906
|
return handBack(command);
|
|
2334
2907
|
if (isComputerCommand(command))
|
|
2335
2908
|
return computerCommand(command);
|
|
2909
|
+
if (isHeldCommand(command))
|
|
2910
|
+
return heldCommand(command);
|
|
2911
|
+
if (command.kind === COMPUTER_CALL)
|
|
2912
|
+
return channelCommand(command);
|
|
2336
2913
|
// A pause is a workflow run's: an agentic run's turn is stopped instead, in main's words (runs.ts pause).
|
|
2337
2914
|
if (command.kind === "pause" || command.kind === "resume")
|
|
2338
2915
|
return { refused: AGENTIC_PAUSE_REFUSED };
|
|
2339
2916
|
return { refused: `an adapter loop takes no ${command.kind} command` };
|
|
2340
2917
|
},
|
|
2918
|
+
keepsComputer: keeps,
|
|
2341
2919
|
async stop(reason) {
|
|
2920
|
+
// The runner asked keepsComputer right before this call: the first stop's answer is the one its end keeps to.
|
|
2921
|
+
if (stopReason === undefined)
|
|
2922
|
+
keptAtStop = keeps(reason);
|
|
2923
|
+
// A cancel, a lost claim or a shutdown after a stop that kept the run's computer: the hold ends with it (writeEnd).
|
|
2924
|
+
if (stopReason && stopReason !== reason && (reason.kind !== "command" || reason.cancel)) {
|
|
2925
|
+
laterStop ??= reason;
|
|
2926
|
+
cutHeld();
|
|
2927
|
+
}
|
|
2342
2928
|
stopReason ??= reason;
|
|
2343
2929
|
if (reason.kind !== "command")
|
|
2344
2930
|
gate?.seal(new Interrupted(reason.kind));
|