@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.40
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 +455 -0
- package/README.md +376 -125
- package/dist/adapters.d.ts +4 -1
- package/dist/adapters.js +4 -2
- package/dist/agent-rows.d.ts +0 -2
- package/dist/agents-store.d.ts +5 -5
- package/dist/agents-store.js +14 -14
- package/dist/bash-read-only.js +2 -1
- package/dist/cap-short.d.ts +12 -0
- package/dist/cap-short.js +60 -0
- package/dist/cap.d.ts +3 -10
- package/dist/cap.js +2 -5
- package/dist/catalog.d.ts +0 -5
- package/dist/catalog.js +1 -5
- package/dist/chatgpt-plan.d.ts +163 -0
- package/dist/chatgpt-plan.js +549 -0
- package/dist/cli.js +26 -6
- package/dist/composio-preset.d.ts +8 -0
- package/dist/composio-preset.js +8 -7
- package/dist/composio-triggers.d.ts +113 -0
- package/dist/composio-triggers.js +411 -0
- package/dist/computer-calls.js +2 -2
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +7 -3
- package/dist/computer-live.d.ts +7 -2
- package/dist/computer-live.js +9 -5
- package/dist/computer-routes.d.ts +2 -2
- package/dist/computer-routes.js +2 -2
- package/dist/computer-setting.d.ts +3 -3
- package/dist/computer-setting.js +5 -5
- package/dist/computer-view.d.ts +15 -0
- package/dist/computer-view.js +16 -2
- package/dist/computer-viewer.js +14 -1
- package/dist/computers.d.ts +5 -2
- package/dist/computers.js +9 -5
- package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
- package/dist/console/assets/index-Jbxjcmdp.js +705 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.js +3 -3
- package/dist/decision-cap.d.ts +2 -5
- package/dist/decision-cap.js +3 -6
- package/dist/decision-rows.js +11 -11
- package/dist/email/account.d.ts +83 -0
- package/dist/email/account.js +159 -0
- package/dist/email/answer.d.ts +15 -0
- package/dist/email/answer.js +217 -0
- package/dist/email/email-faux.d.ts +95 -0
- package/dist/email/email-faux.js +849 -0
- package/dist/email/labels.d.ts +1 -0
- package/dist/email/labels.js +84 -0
- package/dist/email/mail.d.ts +186 -0
- package/dist/email/mail.js +373 -0
- package/dist/email/names.d.ts +50 -0
- package/dist/email/names.js +74 -0
- package/dist/email/routes.d.ts +10 -0
- package/dist/email/routes.js +50 -0
- package/dist/email/tools.d.ts +27 -0
- package/dist/email/tools.js +562 -0
- package/dist/environment.d.ts +17 -2
- package/dist/environment.js +36 -8
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +12 -0
- package/dist/eval-mailbox.d.ts +103 -0
- package/dist/eval-mailbox.js +236 -0
- package/dist/graph-view.d.ts +9 -2
- package/dist/graph-view.js +6 -2
- package/dist/harness-install.d.ts +28 -2
- package/dist/harness-install.js +147 -59
- package/dist/harness-opencode/adapter.js +2 -26
- package/dist/harness-opencode/facts.js +5 -2
- package/dist/harness-opencode/host/policy.d.ts +2 -0
- package/dist/harness-opencode/host/policy.js +10 -5
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/versions.d.ts +6 -0
- package/dist/harness-opencode/versions.js +6 -0
- package/dist/harness-table.js +8 -5
- package/dist/harness.d.ts +12 -0
- package/dist/harness.js +15 -3
- package/dist/hosted-search.d.ts +3 -1
- package/dist/hosted-search.js +51 -11
- package/dist/import-sources.d.ts +1 -1
- package/dist/import-sources.js +3 -3
- package/dist/import.d.ts +21 -0
- package/dist/import.js +186 -1
- package/dist/key-check.d.ts +0 -2
- package/dist/key-check.js +3 -4
- package/dist/key-refusal.d.ts +8 -2
- package/dist/key-refusal.js +16 -13
- package/dist/learn/check.d.ts +18 -3
- package/dist/learn/check.js +328 -3
- package/dist/learn/compile.d.ts +12 -4
- package/dist/learn/compile.js +57 -20
- package/dist/learn/grade.d.ts +4 -0
- package/dist/learn/grade.js +4 -1
- package/dist/learn/promote.d.ts +130 -64
- package/dist/learn/promote.js +113 -202
- package/dist/learn/refit.d.ts +21 -12
- package/dist/learn/refit.js +51 -23
- package/dist/learn/replay-calls.js +1 -1
- package/dist/learn/skills.d.ts +2 -7
- package/dist/learn/skills.js +28 -14
- package/dist/learned-nodes.d.ts +15 -7
- package/dist/learned-nodes.js +29 -5
- package/dist/learned-workflow.d.ts +41 -31
- package/dist/learned-workflow.js +122 -63
- package/dist/learning-batch.js +3 -3
- package/dist/learning-cost.d.ts +35 -8
- package/dist/learning-cost.js +27 -9
- package/dist/learning-routes.d.ts +2 -4
- package/dist/learning-routes.js +20 -3
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +4 -1
- package/dist/learning.d.ts +5 -5
- package/dist/link-check.d.ts +27 -0
- package/dist/link-check.js +164 -0
- package/dist/local-models.d.ts +39 -2
- package/dist/local-models.js +49 -5
- package/dist/mcp-pin-first.js +6 -0
- package/dist/mcp-secret-writes.js +3 -0
- package/dist/mcp-servers-store.d.ts +25 -16
- package/dist/mcp-servers-store.js +23 -3
- package/dist/model-form.d.ts +11 -0
- package/dist/model-form.js +17 -1
- package/dist/model.d.ts +26 -6
- package/dist/model.js +126 -18
- package/dist/monid.d.ts +26 -31
- package/dist/monid.js +84 -79
- package/dist/native/binding.d.ts +13 -0
- package/dist/native/binding.js +57 -0
- package/dist/native/cli.d.ts +2 -0
- package/dist/native/cli.js +48 -0
- package/dist/native/connection.d.ts +8 -0
- package/dist/native/connection.js +94 -0
- package/dist/native/context.d.ts +6 -0
- package/dist/native/context.js +22 -0
- package/dist/native/discovery.d.ts +27 -0
- package/dist/native/discovery.js +404 -0
- package/dist/native/environment.d.ts +4 -0
- package/dist/native/environment.js +18 -0
- package/dist/native/history.d.ts +20 -0
- package/dist/native/history.js +147 -0
- package/dist/native/instructions.d.ts +21 -0
- package/dist/native/instructions.js +173 -0
- package/dist/native/remote-worker-bridge.d.ts +3 -0
- package/dist/native/remote-worker-bridge.js +278 -0
- package/dist/native/remote.d.ts +187 -0
- package/dist/native/remote.js +492 -0
- package/dist/native/runtime.d.ts +17 -0
- package/dist/native/runtime.js +316 -0
- package/dist/native/runtimes.d.ts +66 -0
- package/dist/native/runtimes.js +41 -0
- package/dist/native/schema.d.ts +46 -0
- package/dist/native/schema.js +41 -0
- package/dist/native/types.d.ts +87 -0
- package/dist/native/types.js +1 -0
- package/dist/observation/http.d.ts +4 -0
- package/dist/observation/http.js +140 -0
- package/dist/observation/observer.d.ts +301 -0
- package/dist/observation/observer.js +919 -0
- package/dist/observation/schema.d.ts +52 -0
- package/dist/observation/schema.js +154 -0
- package/dist/openapi.d.ts +2 -1
- package/dist/openapi.js +404 -93
- package/dist/paid-calls.d.ts +8 -3
- package/dist/paid-calls.js +6 -2
- package/dist/place-offers.d.ts +4 -8
- package/dist/place-offers.js +4 -9
- package/dist/port-models.d.ts +10 -2
- package/dist/port-models.js +6 -2
- package/dist/print.d.ts +4 -2
- package/dist/print.js +4 -3
- package/dist/propose.d.ts +1 -2
- package/dist/propose.js +10 -1
- package/dist/provider.d.ts +5 -1
- package/dist/provider.js +8 -0
- package/dist/push-handler.d.ts +3 -2
- package/dist/push-handler.js +20 -6
- package/dist/refusal-words.d.ts +14 -0
- package/dist/refusal-words.js +16 -2
- package/dist/run-launch.d.ts +12 -1
- package/dist/run-launch.js +13 -4
- package/dist/run-learning-served.d.ts +75 -2
- package/dist/run-manifest.d.ts +3 -0
- package/dist/run-manifest.js +13 -1
- package/dist/run-reads-over-store.d.ts +3 -3
- package/dist/run-reads-over-store.js +13 -10
- package/dist/run-timeline-served.d.ts +3 -2
- package/dist/run-timeline-served.js +8 -9
- package/dist/run-view.d.ts +44 -38
- package/dist/run-view.js +93 -56
- package/dist/runnable.d.ts +13 -5
- package/dist/runnable.js +69 -60
- package/dist/runner/adapter-loop.d.ts +48 -13
- package/dist/runner/adapter-loop.js +691 -254
- package/dist/runner/adapter-run-spec.d.ts +38 -12
- package/dist/runner/adapter-run-spec.js +175 -106
- package/dist/runner/adapters/pi.d.ts +24 -0
- package/dist/runner/adapters/pi.js +59 -9
- package/dist/runner/beside.d.ts +3 -1
- package/dist/runner/beside.js +24 -8
- package/dist/runner/claim-secrets.d.ts +3 -1
- package/dist/runner/claim-secrets.js +28 -4
- package/dist/runner/cli-run-spec.d.ts +30 -0
- package/dist/runner/cli-run-spec.js +95 -50
- package/dist/runner/computer-channel.d.ts +5 -2
- package/dist/runner/computer-channel.js +3 -2
- package/dist/runner/computer-journal.d.ts +6 -0
- package/dist/runner/computer-journal.js +8 -10
- package/dist/runner/conformance/harness.js +6 -3
- package/dist/runner/end-of-run.d.ts +2 -0
- package/dist/runner/end-of-run.js +3 -1
- package/dist/runner/feedback-round.d.ts +40 -13
- package/dist/runner/feedback-round.js +64 -16
- package/dist/runner/harness-loops.js +17 -0
- package/dist/runner/journal-kinds.d.ts +59 -13
- package/dist/runner/journal-kinds.js +48 -5
- package/dist/runner/learning-dispatch.d.ts +3 -2
- package/dist/runner/learning-dispatch.js +6 -6
- package/dist/runner/learning-end.d.ts +4 -0
- package/dist/runner/learning-end.js +64 -36
- package/dist/runner/learning-factory.d.ts +3 -0
- package/dist/runner/learning-factory.js +8 -2
- package/dist/runner/learning-loop.d.ts +2 -0
- package/dist/runner/learning-loop.js +19 -4
- package/dist/runner/loop.d.ts +18 -0
- package/dist/runner/loop.js +34 -0
- package/dist/runner/main.d.ts +6 -1
- package/dist/runner/main.js +26 -4
- package/dist/runner/mcp-run.d.ts +4 -1
- package/dist/runner/mcp-run.js +11 -5
- package/dist/runner/meta-tools.d.ts +10 -3
- package/dist/runner/meta-tools.js +112 -36
- package/dist/runner/metrics.d.ts +80 -21
- package/dist/runner/metrics.js +114 -39
- package/dist/runner/model-route.d.ts +14 -3
- package/dist/runner/model-route.js +155 -19
- package/dist/runner/monid-run.d.ts +8 -6
- package/dist/runner/monid-run.js +117 -43
- package/dist/runner/native-loop.d.ts +11 -0
- package/dist/runner/native-loop.js +438 -0
- package/dist/runner/promotion.d.ts +76 -10
- package/dist/runner/promotion.js +476 -154
- package/dist/runner/redact.js +3 -0
- package/dist/runner/reflect-hook.js +9 -0
- package/dist/runner/runner.d.ts +7 -1
- package/dist/runner/runner.js +8 -4
- package/dist/runner/sdk-loop.d.ts +7 -0
- package/dist/runner/sdk-loop.js +470 -0
- package/dist/runner/spec-holds.d.ts +16 -2
- package/dist/runner/spec-holds.js +42 -14
- package/dist/runner/store-secrets.js +17 -2
- package/dist/runner/workflow-first.d.ts +30 -20
- package/dist/runner/workflow-first.js +22 -32
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-loop.js +18 -12
- package/dist/runner/workflow-spec.d.ts +4 -1
- package/dist/runner/workflow-spec.js +56 -45
- package/dist/runs-over-store.d.ts +30 -2
- package/dist/runs-over-store.js +46 -14
- package/dist/sdk/runs.d.ts +115 -0
- package/dist/sdk/runs.js +422 -0
- package/dist/sdk/schema.d.ts +175 -0
- package/dist/sdk/schema.js +138 -0
- package/dist/sdk/workflows.d.ts +22 -0
- package/dist/sdk/workflows.js +39 -0
- package/dist/secrets.d.ts +2 -0
- package/dist/secrets.js +19 -1
- package/dist/server.d.ts +48 -32
- package/dist/server.js +568 -137
- package/dist/skill-route.d.ts +3 -0
- package/dist/skill-route.js +16 -0
- package/dist/skills/agentrun-serve/SKILL.md +368 -0
- package/dist/stats.d.ts +10 -10
- package/dist/store/agent-body.d.ts +12 -8
- package/dist/store/agent-body.js +9 -4
- package/dist/store/dialect.d.ts +3 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/native-command-owner.d.ts +10 -0
- package/dist/store/native-command-owner.js +47 -0
- package/dist/store/postgres/connection.d.ts +11 -5
- package/dist/store/postgres/connection.js +44 -17
- package/dist/store/postgres/dialect.js +5 -0
- package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
- package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
- package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
- package/dist/store/postgres/store.d.ts +7 -3
- package/dist/store/postgres/store.js +4 -0
- package/dist/store/schema.d.ts +7 -0
- package/dist/store/schema.js +20 -1
- package/dist/store/sqlite/connection.js +72 -8
- package/dist/store/sqlite/run-launch.d.ts +11 -0
- package/dist/store/sqlite/run-launch.js +8 -0
- package/dist/store/sqlite/run-patch.d.ts +8 -1
- package/dist/store/sqlite/run-patch.js +14 -3
- package/dist/store/sqlite/store.js +170 -34
- package/dist/store/sqlite/worker.d.ts +2 -0
- package/dist/store/sqlite/worker.js +13 -10
- package/dist/store/store.d.ts +67 -7
- package/dist/store-reads/analytics.d.ts +7 -7
- package/dist/store-reads/analytics.js +23 -5
- package/dist/store-reads/cap.js +8 -6
- package/dist/store-reads/journal.d.ts +5 -0
- package/dist/store-reads/journal.js +85 -41
- package/dist/store-reads/learning.d.ts +115 -18
- package/dist/store-reads/learning.js +170 -68
- package/dist/store-reads/runs.d.ts +5 -0
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.js +75 -21
- package/dist/template-eval.d.ts +73 -11
- package/dist/template-eval.js +535 -75
- package/dist/templates.d.ts +84 -21
- package/dist/templates.js +254 -47
- package/dist/text-urls.d.ts +38 -0
- package/dist/text-urls.js +170 -0
- package/dist/timeline/index.d.ts +3 -2
- package/dist/timeline/index.js +3 -2
- package/dist/timeline/labels.d.ts +5 -2
- package/dist/timeline/labels.js +29 -6
- package/dist/timeline/origin.d.ts +1 -1
- package/dist/timeline/origin.js +2 -2
- package/dist/timeline/render-text.js +1 -1
- package/dist/timeline/timeline.d.ts +66 -4
- package/dist/timeline/timeline.js +160 -30
- package/dist/timeline/util.d.ts +5 -0
- package/dist/timeline/util.js +44 -8
- package/dist/timeline/web-calls.d.ts +17 -0
- package/dist/timeline/web-calls.js +106 -0
- package/dist/tool-gate.d.ts +46 -44
- package/dist/tool-gate.js +101 -92
- package/dist/tool-list.d.ts +4 -1
- package/dist/tool-list.js +8 -1
- package/dist/tool-names.d.ts +18 -13
- package/dist/tool-names.js +19 -17
- package/dist/tool-plane.d.ts +17 -13
- package/dist/tool-plane.js +12 -5
- package/dist/tools.d.ts +57 -16
- package/dist/tools.js +33 -28
- package/dist/trigger-adapter.d.ts +56 -5
- package/dist/trigger-adapter.js +6 -0
- package/dist/trigger-adapters.js +3 -1
- package/dist/trigger-composio.d.ts +10 -0
- package/dist/trigger-composio.js +122 -0
- package/dist/trigger-email.d.ts +4 -0
- package/dist/trigger-email.js +181 -0
- package/dist/trigger-signatures.d.ts +6 -10
- package/dist/trigger-signatures.js +16 -16
- package/dist/trigger-targets.d.ts +1 -1
- package/dist/trigger-targets.js +4 -3
- package/dist/trigger-webhook.js +6 -4
- package/dist/triggers.d.ts +105 -8
- package/dist/triggers.js +286 -62
- package/dist/uploads.d.ts +9 -0
- package/dist/uploads.js +27 -0
- package/dist/validate.js +1 -7
- package/dist/web-fake.d.ts +56 -0
- package/dist/web-fake.js +102 -0
- package/dist/web-fetch-direct.d.ts +3 -0
- package/dist/web-fetch-direct.js +4 -1
- package/dist/web-fetch.d.ts +5 -1
- package/dist/web-fetch.js +8 -31
- package/dist/web-search.d.ts +51 -2
- package/dist/web-search.js +116 -18
- package/dist/webhooks.d.ts +2 -1
- package/dist/webhooks.js +5 -1
- package/dist/workflow/decision-recovery.js +5 -2
- package/dist/workflow/decisions.d.ts +7 -0
- package/dist/workflow/node-runner.js +10 -2
- package/dist/workspace/archil-claim.d.ts +3 -0
- package/dist/workspace/archil-claim.js +9 -2
- package/dist/workspace/computer-deps.d.ts +22 -9
- package/dist/workspace/computer-deps.js +78 -37
- package/dist/workspace/computer-for-claim.d.ts +54 -4
- package/dist/workspace/computer-for-claim.js +179 -39
- package/dist/workspace/computer-janitor.d.ts +10 -3
- package/dist/workspace/computer-janitor.js +96 -29
- package/dist/workspace/computer-kept.d.ts +82 -0
- package/dist/workspace/computer-kept.js +147 -0
- package/dist/workspace/computer-mcp.js +4 -3
- package/dist/workspace/computer-ports.d.ts +23 -3
- package/dist/workspace/computer-ports.js +115 -5
- package/dist/workspace/index.d.ts +1 -2
- package/dist/workspace/index.js +1 -2
- package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
- package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
- package/dist/workspace/resolve-computer.d.ts +15 -3
- package/dist/workspace/resolve-computer.js +10 -7
- package/dist/workspace/revision-skills.d.ts +6 -2
- package/dist/workspace/revision-skills.js +12 -5
- package/dist/workspace/run-end-computers.d.ts +30 -0
- package/dist/workspace/run-end-computers.js +137 -0
- package/dist/workspace/run-tools.d.ts +28 -29
- package/dist/workspace/run-tools.js +29 -30
- package/dist/wrap-up.d.ts +19 -5
- package/dist/wrap-up.js +31 -4
- package/package.json +13 -9
- package/skills/agentrun-serve/SKILL.md +248 -10
- package/templates/README.md +117 -23
- package/templates/TOOLS.md +168 -0
- package/templates/code-review/agent.md +18 -4
- package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
- package/templates/code-review/evals/other-repo/case.yaml +1 -1
- package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
- package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
- package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
- package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
- package/templates/code-review/skills/review/DEEP.md +2 -2
- package/templates/code-review/skills/review/REVIEWER.md +2 -2
- package/templates/code-review/skills/review/SKILL.md +7 -3
- package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
- package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
- package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
- package/templates/release-notes/evals/other-repo/case.yaml +1 -1
- package/dist/console/assets/index-CjqQirbo.css +0 -1
- package/dist/console/assets/index-b6-XY5A9.js +0 -576
- package/dist/host-calls.d.ts +0 -20
- package/dist/host-calls.js +0 -12
- package/dist/runner/adapters/pi-computer.d.ts +0 -9
- package/dist/runner/adapters/pi-computer.js +0 -51
- package/dist/workspace/computer-script.d.ts +0 -53
- package/dist/workspace/computer-script.js +0 -172
package/dist/runner/metrics.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// passes its decisions. `effort` is the level the run ran at and `model`, on a harness other than pi, the model its
|
|
9
9
|
// revision named — both as storedMetrics added them, resolved by the caller from the run's launch and harness.
|
|
10
10
|
import { runMetricsWithDecisions, timelineOf } from "../timeline/index.js";
|
|
11
|
-
import {
|
|
11
|
+
import { costOfParts, rebooked, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
|
|
12
12
|
import { DECISION_SESSION, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
|
|
13
13
|
import { KINDS, WORKFLOW_SESSION } from "./journal-kinds.js";
|
|
14
14
|
import { anthropicModelId } from "../provider.js";
|
|
@@ -55,10 +55,16 @@ export function bookedSpend(entries, which) {
|
|
|
55
55
|
models[name] = (models[name] ?? 0) + 1;
|
|
56
56
|
};
|
|
57
57
|
let known = 0;
|
|
58
|
+
let bounded = 0;
|
|
58
59
|
let unpriced = 0;
|
|
59
60
|
let requests = 0;
|
|
60
61
|
let unmetered = 0;
|
|
62
|
+
let free = 0;
|
|
63
|
+
let atMost = 0;
|
|
61
64
|
const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
65
|
+
// Each request is booked once, as the kernel's sessionSpendOf reads it: a second runner.turn of a turn already booked
|
|
66
|
+
// (two bookings of one session that each read it open, a cut written twice) counts no money and no request again.
|
|
67
|
+
const booked = new Set();
|
|
62
68
|
for (const e of entries) {
|
|
63
69
|
if (!chosen(e))
|
|
64
70
|
continue;
|
|
@@ -71,17 +77,25 @@ export function bookedSpend(entries, which) {
|
|
|
71
77
|
}
|
|
72
78
|
if (e.kind !== RUNNER_RECORDS.turn)
|
|
73
79
|
continue;
|
|
80
|
+
if (rebooked(booked, typeof e.data?.turn === "number" ? turnOf(e) : undefined))
|
|
81
|
+
continue;
|
|
74
82
|
const d = (e.data ?? {});
|
|
75
83
|
if (d.givenBack === true || d.unsent === true)
|
|
76
84
|
continue;
|
|
77
85
|
requests += 1;
|
|
78
86
|
count(e);
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
87
|
+
if (d.free === true)
|
|
88
|
+
free += 1;
|
|
89
|
+
// Its own cost by the kernel's one rule (turnCostOf): an answer with no price of its own is unknown, never the hold it
|
|
90
|
+
// was booked at for the cap; a request cut with no answer booked at its hold counts that figure, the most it can cost,
|
|
91
|
+
// kept apart from the requests' own figures.
|
|
92
|
+
const own = turnCostOf(d);
|
|
93
|
+
if (own.usd === null)
|
|
82
94
|
unpriced += 1;
|
|
95
|
+
else if (own.atMost)
|
|
96
|
+
(bounded += own.usd), (atMost += 1);
|
|
83
97
|
else
|
|
84
|
-
known += usd;
|
|
98
|
+
known += own.usd;
|
|
85
99
|
// The booking keeps a request's usage only when it reported some (runner.ts tokensOf): one with none is unmetered.
|
|
86
100
|
if (d.usage === undefined)
|
|
87
101
|
unmetered += 1;
|
|
@@ -89,13 +103,68 @@ export function bookedSpend(entries, which) {
|
|
|
89
103
|
if (typeof d.usage?.[key] === "number")
|
|
90
104
|
tokens[key] += d.usage[key];
|
|
91
105
|
}
|
|
92
|
-
return { usd: unpriced ? null : known, known, unpriced, requests, unmetered, models, tokens };
|
|
106
|
+
return { usd: unpriced ? null : known + bounded, known, bounded, unpriced, atMost, requests, unmetered, models, tokens, ...(requests > 0 && free === requests ? { free: true } : {}) };
|
|
107
|
+
}
|
|
108
|
+
/** A sum of charges with its float noise rounded off, nothing more (as the decisions row rounds, decision-rows.ts): a
|
|
109
|
+
* decision costs millionths of a dollar, so a sum rounded to the millionth would lose it. */
|
|
110
|
+
const floatNoiseOff = (usd) => Math.round(usd * 1e12) / 1e12;
|
|
111
|
+
export function costWordsOf(parts, extraUnpriced = 0) {
|
|
112
|
+
if (parts.some((part) => part === null))
|
|
113
|
+
return { usd: null };
|
|
114
|
+
const all = [...parts, { known: 0, bounded: 0, atMost: 0, unpriced: extraUnpriced }];
|
|
115
|
+
const cost = costOfParts(all);
|
|
116
|
+
const round = floatNoiseOff;
|
|
117
|
+
if (cost.usd === null)
|
|
118
|
+
return { usd: null, so_far_usd: round(cost.soFarUsd), unpriced: cost.unpriced };
|
|
119
|
+
if (!cost.atMost)
|
|
120
|
+
return { usd: round(cost.usd) };
|
|
121
|
+
// The exact part: the charges' own figures, never a hold (costOfParts' soFarUsd counts the holds once every charge is).
|
|
122
|
+
return { usd: round(cost.usd), so_far_usd: round(all.reduce((sum, part) => sum + part.known, 0)), unpriced: cost.atMost, upper_bound: true };
|
|
123
|
+
}
|
|
124
|
+
/** A usage row's cost (TimelineEvent.usage, or a cost block in the same words) as the kernel's parts, for a join
|
|
125
|
+
* (costWordsOf): an exact figure is `known`; a bound is its exact part (`so_far_usd`) known and the rest bounded over its
|
|
126
|
+
* `unpriced` holds, or, from a row that says no exact part, the whole bounded over one hold, never spend; an unknown cost
|
|
127
|
+
* is its known part and its unpriced count. Null: an unknown cost that says neither. No row (undefined): nothing spent. */
|
|
128
|
+
export function usageParts(usage) {
|
|
129
|
+
if (usage === undefined)
|
|
130
|
+
return { known: 0, bounded: 0, atMost: 0, unpriced: 0 };
|
|
131
|
+
const said = usage.so_far_usd !== undefined && usage.unpriced !== undefined;
|
|
132
|
+
if (usage.usd !== null && usage.upper_bound === true) {
|
|
133
|
+
return said ? { known: usage.so_far_usd, bounded: Math.max(0, usage.usd - usage.so_far_usd), atMost: usage.unpriced, unpriced: 0 } : { known: 0, bounded: usage.usd, atMost: 1, unpriced: 0 };
|
|
134
|
+
}
|
|
135
|
+
if (usage.usd !== null)
|
|
136
|
+
return { known: usage.usd, bounded: 0, atMost: 0, unpriced: 0 };
|
|
137
|
+
return said ? { known: usage.so_far_usd, bounded: 0, atMost: 0, unpriced: usage.unpriced } : null;
|
|
138
|
+
}
|
|
139
|
+
export function runCostOf(entries, { unbooked = false } = {}) {
|
|
140
|
+
const parts = [bookedSpend(entries, "model"), bookedSpend(entries, "paid"), bookedSpend(entries, "decisions")];
|
|
141
|
+
const cost = costOfParts([...parts, { known: 0, bounded: 0, atMost: 0, unpriced: unbooked && parts[0].requests === 0 ? 1 : 0 }]);
|
|
142
|
+
const round = floatNoiseOff;
|
|
143
|
+
// Its parts as one (CostParts, so its words are costWordsOf([cost])): `known` the requests' own figures alone, a hold
|
|
144
|
+
// never among them; while the cost is known, `bounded` and `atMost` its holds, else every hold counted in `unpriced`.
|
|
145
|
+
const known = round(parts.reduce((sum, part) => sum + part.known, 0));
|
|
146
|
+
const usd = cost.usd === null ? null : round(cost.usd);
|
|
147
|
+
return { usd, known, bounded: usd === null ? 0 : Math.max(0, round(usd - known)), unpriced: cost.unpriced, atMost: cost.atMost ?? 0, requests: parts.reduce((sum, part) => sum + part.requests, 0) };
|
|
93
148
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
*
|
|
97
|
-
|
|
98
|
-
|
|
149
|
+
export const endCostOf = (cost) => ({ costUsd: cost.usd, costUpperBound: cost.usd !== null && cost.atMost > 0 });
|
|
150
|
+
/** The run's model requests billed to a ChatGPT plan (runner.turn `billing` "plan", booked at no price, chatgpt-plan.ts):
|
|
151
|
+
* how many and their tokens (input, output and cache, as each booking reported them). Each is $0 to the run by the
|
|
152
|
+
* kernel's one rule (turnCostOf), however it ended: the plan pays for it, so no reader counts it unpriced. */
|
|
153
|
+
export function planSpend(entries) {
|
|
154
|
+
let requests = 0;
|
|
155
|
+
let tokens = 0;
|
|
156
|
+
for (const e of entries) {
|
|
157
|
+
if (e.kind !== RUNNER_RECORDS.turn)
|
|
158
|
+
continue;
|
|
159
|
+
const d = (e.data ?? {});
|
|
160
|
+
if (d.billing !== "plan" || d.givenBack === true || d.unsent === true)
|
|
161
|
+
continue;
|
|
162
|
+
requests += 1;
|
|
163
|
+
for (const key of ["input", "output", "cacheRead", "cacheWrite"])
|
|
164
|
+
if (typeof d.usage?.[key] === "number")
|
|
165
|
+
tokens += d.usage[key];
|
|
166
|
+
}
|
|
167
|
+
return { requests, tokens };
|
|
99
168
|
}
|
|
100
169
|
/** Whether a CLI harness's record (`entries`, its root's) shows the model at work: a model message, a tool call it made, or
|
|
101
170
|
* its end-of-run turn's answer. Each took a model request, so a run that shows one and booked none (its requests went
|
|
@@ -122,9 +191,9 @@ export function cliModelWorked(entries) {
|
|
|
122
191
|
export function costIsBooked(entries, cli) {
|
|
123
192
|
return cli || sessionConversations(entries).has(WORKFLOW_SESSION);
|
|
124
193
|
}
|
|
125
|
-
/** What the run has spent as its cap reads it (the kernel's sessionSpendOf over every session's records: a
|
|
126
|
-
* out at its hold and bound), for a run whose cost is its booking: the
|
|
127
|
-
* session's is unknown, never 0 for it. */
|
|
194
|
+
/** What the run has spent and holds as its cap reads it (the kernel's sessionSpendOf over every session's records: a
|
|
195
|
+
* request still out at its hold and bound), for a run whose cost is its booking: the figure a gate holds it to (the
|
|
196
|
+
* runs list says bookedListSpend). Null when one session's is unknown, never 0 for it. */
|
|
128
197
|
export function bookedCapSpend(entries) {
|
|
129
198
|
let spent = 0;
|
|
130
199
|
// Every conversation that holds booking records, keyed or not, as bookedSpend reads them.
|
|
@@ -138,45 +207,51 @@ export function bookedCapSpend(entries) {
|
|
|
138
207
|
}
|
|
139
208
|
return spent;
|
|
140
209
|
}
|
|
141
|
-
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const keyed = sessionConversations(entries);
|
|
147
|
-
const paidConv = keyed.get(TOOL_SESSION);
|
|
148
|
-
const decisionsConv = keyed.get(DECISION_SESSION);
|
|
149
|
-
const others = [paidConv, decisionsConv].reduce((sum, conversation) => {
|
|
150
|
-
if (conversation === undefined)
|
|
151
|
-
return sum;
|
|
152
|
-
const read = sessionSpendOf(recordsIn(entries, conversation)).spentUsd;
|
|
153
|
-
return sum + (read ?? 0);
|
|
154
|
-
}, 0);
|
|
210
|
+
/** What a run whose cost is its booking has spent, as the runs list says it while the run goes on: every booked request at
|
|
211
|
+
* what it was booked at, never the hold of a request still out (a hold is no spend: the request settles at what it cost,
|
|
212
|
+
* which the cap's own reading, bookedCapSpend, holds it to meanwhile). Null when a booked request's figure is unknown. */
|
|
213
|
+
export function bookedListSpend(entries) {
|
|
214
|
+
let spent = 0;
|
|
155
215
|
const booking = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn).map((e) => Number(e.conversationId)));
|
|
156
|
-
let running = others;
|
|
157
|
-
let bound = 0;
|
|
158
216
|
for (const conversation of booking) {
|
|
159
|
-
if (conversation === paidConv || conversation === decisionsConv)
|
|
160
|
-
continue;
|
|
161
217
|
const read = sessionSpendOf(recordsIn(entries, conversation));
|
|
162
218
|
for (const { turn, usd } of read.figures) {
|
|
163
|
-
|
|
164
|
-
|
|
219
|
+
if (!read.answered.has(turn))
|
|
220
|
+
continue;
|
|
221
|
+
if (usd === null)
|
|
222
|
+
return null;
|
|
223
|
+
spent += usd;
|
|
165
224
|
}
|
|
166
225
|
}
|
|
167
|
-
return
|
|
226
|
+
return spent;
|
|
168
227
|
}
|
|
169
228
|
/** The booking records of `conversation`, as the kernel's session readers take them. */
|
|
170
229
|
const recordsIn = (entries, conversation) => entries.filter((e) => Number(e.conversationId) === conversation && e.kind !== KINDS.sessionKey).map((e) => ({ kind: e.kind, data: (e.data ?? null) }));
|
|
230
|
+
/** `counted` with each tool `catalog` names (an MCP tool's hashed wire name: store-reads/journal.ts hashedMcpOf) counted
|
|
231
|
+
* under its catalog name, `mcp:<server>/<tool>`, as the run's timeline names its calls; the analytics' top tools read
|
|
232
|
+
* the name a run's metrics key a tool by. Every other tool keeps the name it was called by. */
|
|
233
|
+
function catalogKeyed(counted, catalog) {
|
|
234
|
+
if (!catalog?.size)
|
|
235
|
+
return counted;
|
|
236
|
+
const tools = {};
|
|
237
|
+
for (const [name, each] of Object.entries(counted.tools)) {
|
|
238
|
+
const key = catalog.get(name) ?? name;
|
|
239
|
+
const had = tools[key];
|
|
240
|
+
tools[key] = had ? { calls: had.calls + each.calls, errors: had.errors + each.errors } : each;
|
|
241
|
+
}
|
|
242
|
+
return { ...counted, tools };
|
|
243
|
+
}
|
|
171
244
|
/** The run's metrics and cost from its journal `entries`. `decisions`: a workflow run's receipts (none for pi).
|
|
172
|
-
* `effort`/`model`: the enrichment the old storedMetrics added. `
|
|
173
|
-
*
|
|
245
|
+
* `effort`/`model`: the enrichment the old storedMetrics added. `catalog`: the run's MCP tools called by a hashed wire
|
|
246
|
+
* name, each counted under its catalog name (catalogKeyed). `costUsd` is the usage row's cost: null when a response's
|
|
247
|
+
* cost is unknown, 0 before any request (costOf). */
|
|
174
248
|
export function runMetrics(entries, options = {}) {
|
|
175
|
-
const counted = runMetricsWithDecisions(entries, options.decisions ?? []);
|
|
249
|
+
const counted = catalogKeyed(runMetricsWithDecisions(entries, options.decisions ?? []), options.catalog);
|
|
176
250
|
// The run's cost from its usage row, as serve/src/runs.ts costOf reads it: the usage row's usd (null unknown, 0 before
|
|
177
251
|
// any request). The usage row is the one the settled timeline appends from the run's request-cost marks.
|
|
178
252
|
const usage = timelineOf(entries, { settled: true }).findLast((row) => row.kind === "usage");
|
|
179
|
-
|
|
253
|
+
// An exact reader: a cost that counts a hold (`upper_bound`) is the most the run can have cost, unknown here.
|
|
254
|
+
const costUsd = usage ? (usage.usage?.upper_bound === true ? null : (usage.usage?.usd ?? null)) : 0;
|
|
180
255
|
return {
|
|
181
256
|
metrics: { ...counted, ...(options.effort !== undefined ? { effort: options.effort } : {}), ...(options.model !== undefined ? { model: options.model } : {}) },
|
|
182
257
|
costUsd,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ThinkingLevelMap } from "../port-models.js";
|
|
1
2
|
import type { Wire } from "@parcha/agentrun-kernel";
|
|
2
3
|
import type { ToolsAs } from "../local-models.js";
|
|
3
4
|
import { type PinnedModel, type Tier } from "../model.js";
|
|
@@ -28,12 +29,17 @@ export type RouteUsage = {
|
|
|
28
29
|
* when its model speaks no wire of the caller's. The fields of the learning grader's route (learning-ask.ts GraderRoute),
|
|
29
30
|
* and `cost` beside them. */
|
|
30
31
|
export interface ModelRoute {
|
|
32
|
+
/** `plan`: a ChatGPT plan's route (provider.ts billing "plan"), billed to the plan: no price, its rules on the wire.
|
|
33
|
+
* Whether its answers state what they cost is the proxy's to read from `origin` (statesUsageCost): OpenRouter's, or
|
|
34
|
+
* this route's own translation of one (ROUTE_ORIGIN). */
|
|
31
35
|
readonly provider: {
|
|
32
36
|
readonly api: Wire;
|
|
33
37
|
readonly origin: string;
|
|
34
38
|
readonly credential: () => string | Promise<string>;
|
|
35
39
|
readonly headers?: Readonly<Record<string, string>>;
|
|
36
40
|
readonly auth?: "bearer" | "x-api-key";
|
|
41
|
+
readonly plan?: boolean;
|
|
42
|
+
readonly refused?: (credential: string) => Promise<void>;
|
|
37
43
|
};
|
|
38
44
|
readonly model: string;
|
|
39
45
|
/** The model as the run names it (`provider/model-id`, chooseModel's): what the `llm` tool's answer says it ran on,
|
|
@@ -41,13 +47,19 @@ export interface ModelRoute {
|
|
|
41
47
|
readonly named?: string;
|
|
42
48
|
/** The catalog's entry for the model, as pi-ai's model of it takes it: on every wire, what it takes as input (whether it
|
|
43
49
|
* takes images) and its input limits (an image's most size), which pi's session and its read size an image by; on a
|
|
44
|
-
* wire that carries its reasoning (Responses), also whether it reasons, its window
|
|
50
|
+
* wire that carries its reasoning (Responses), also whether it reasons, its window, its output ceiling, and the effort
|
|
51
|
+
* each thinking level asks for (`thinkingLevelMap`: a level mapped to null sends no effort, so pi's thinking off asks
|
|
52
|
+
* a model that takes no "none" for none, gpt-6.1-sol's case). On the route's own translation, a model that reasons
|
|
53
|
+
* asks its level by name (LEVELS_BY_NAME: `adaptiveThinking`), so the run's effort reaches it. */
|
|
45
54
|
readonly like?: {
|
|
46
55
|
readonly reasoning?: boolean;
|
|
47
56
|
readonly contextWindow?: number;
|
|
48
57
|
readonly maxTokens?: number;
|
|
49
58
|
readonly input?: readonly string[];
|
|
50
59
|
readonly inputLimits?: unknown;
|
|
60
|
+
readonly developerRole?: boolean;
|
|
61
|
+
readonly adaptiveThinking?: boolean;
|
|
62
|
+
readonly thinkingLevelMap?: ThinkingLevelMap;
|
|
51
63
|
};
|
|
52
64
|
/** A request's price from its usage (the proxy's booking reads it): pi-ai's calculateCost, tiers included. */
|
|
53
65
|
readonly price?: (model: string, usage: RouteUsage) => number | null;
|
|
@@ -61,8 +73,6 @@ export interface ModelRoute {
|
|
|
61
73
|
/** The model's most output tokens (its catalog ceiling): the cap's output bound, null when the catalog names none. */
|
|
62
74
|
readonly outputCeiling?: number | null;
|
|
63
75
|
}
|
|
64
|
-
/** The origin a route with its own fetch names: nothing is ever sent there, its fetch answers every request. */
|
|
65
|
-
export declare const ROUTE_ORIGIN = "https://model-route.invalid";
|
|
66
76
|
type PiModel = {
|
|
67
77
|
id: string;
|
|
68
78
|
provider: string;
|
|
@@ -74,6 +84,7 @@ type PiModel = {
|
|
|
74
84
|
contextWindow?: number;
|
|
75
85
|
input?: readonly string[];
|
|
76
86
|
inputLimits?: unknown;
|
|
87
|
+
thinkingLevelMap?: ThinkingLevelMap;
|
|
77
88
|
toolsAs?: ToolsAs;
|
|
78
89
|
};
|
|
79
90
|
type PiModels = {
|
|
@@ -15,12 +15,11 @@
|
|
|
15
15
|
// the tier, as its provider bills it), and its cost is that catalog entry, tiers included, for the cap's judgement.
|
|
16
16
|
import { randomUUID } from "node:crypto";
|
|
17
17
|
import { calculateCost } from "@earendil-works/pi-ai";
|
|
18
|
+
import { ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
|
|
18
19
|
import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
|
|
19
20
|
import { providerFor } from "../provider.js";
|
|
20
21
|
import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
|
|
21
22
|
import { callsOfText, toolsAsText } from "./text-tools.js";
|
|
22
|
-
/** The origin a route with its own fetch names: nothing is ever sent there, its fetch answers every request. */
|
|
23
|
-
export const ROUTE_ORIGIN = "https://model-route.invalid";
|
|
24
23
|
/** The wires a caller of routeOf speaks when it names none: Anthropic's Messages alone. */
|
|
25
24
|
const MESSAGES_ONLY = ["anthropic-messages"];
|
|
26
25
|
/** The route of `model` ("provider/model-id"; undefined for the host's model of `tier`; a claimed run's pin, sent as
|
|
@@ -48,7 +47,7 @@ export async function routeOf(model, env = process.env, tier = "default", wires
|
|
|
48
47
|
const sees = { ...(target.input ? { input: target.input } : {}), ...(target.inputLimits ? { inputLimits: target.inputLimits } : {}) };
|
|
49
48
|
// The settings serve registered for a gateway model, carried on either wire, so pi's session reads the same model whether
|
|
50
49
|
// it speaks Messages or Responses to the gateway.
|
|
51
|
-
const settings = { ...sees, ...(target.reasoning !== undefined ? { reasoning: target.reasoning } : {}), ...(target.contextWindow ? { contextWindow: target.contextWindow } : {}), ...(target.maxTokens ? { maxTokens: target.maxTokens } : {}) };
|
|
50
|
+
const settings = { ...sees, ...(target.reasoning !== undefined ? { reasoning: target.reasoning } : {}), ...(target.contextWindow ? { contextWindow: target.contextWindow } : {}), ...(target.maxTokens ? { maxTokens: target.maxTokens } : {}), ...(target.thinkingLevelMap ? { thinkingLevelMap: target.thinkingLevelMap } : {}) };
|
|
52
51
|
const route = { model: chosen.model.modelId, named: `${chosen.model.provider}/${chosen.model.modelId}`, price, cost: target.cost, ...(unpriced.has(chosen.model.modelId) ? { unpriced: true } : {}), outputCeiling: target.maxTokens ?? null, like: sees };
|
|
53
52
|
// An Anthropic model speaks Messages itself: the network, at its catalog origin, its key read by name per request.
|
|
54
53
|
if (chosen.model.provider === "anthropic") {
|
|
@@ -63,13 +62,50 @@ export async function routeOf(model, env = process.env, tier = "default", wires
|
|
|
63
62
|
// A model pi-ai speaks Responses to, for a caller that speaks it: that wire itself, where main sends it (provider.ts).
|
|
64
63
|
if (target.api === "openai-responses" && wires.includes("openai-responses")) {
|
|
65
64
|
const to = providerFor("openai-responses", env, chosen.model, "pi");
|
|
65
|
+
// A ChatGPT plan's model: billed to the plan, at no price here (unpriced, never $0), its instructions sent as a
|
|
66
|
+
// developer message (the plan takes no system one).
|
|
67
|
+
const onPlan = to.billing === "plan";
|
|
68
|
+
const plan = onPlan ? { price: () => null, unpriced: true } : {};
|
|
66
69
|
return {
|
|
67
|
-
...route, model: to.modelId,
|
|
68
|
-
provider: { api: "openai-responses", origin: to.origin, credential: to.credential, auth: to.auth },
|
|
69
|
-
like: settings,
|
|
70
|
+
...route, model: to.modelId, ...plan,
|
|
71
|
+
provider: { api: "openai-responses", origin: to.origin, credential: to.credential, auth: to.auth, ...(onPlan ? { plan: true } : {}), ...(to.refused ? { refused: to.refused } : {}) },
|
|
72
|
+
like: onPlan ? { ...settings, developerRole: true } : settings,
|
|
70
73
|
};
|
|
71
74
|
}
|
|
72
|
-
|
|
75
|
+
// The translation writes an answer's cost in its usage only where pi-ai read the provider's own (OpenRouter's): the
|
|
76
|
+
// proxy reads it on ROUTE_ORIGIN (statesUsageCost). A model that reasons is given to pi's session as one that asks its
|
|
77
|
+
// thinking level by name (LEVELS_BY_NAME), which the translation hands to pi-ai (levelOf): the run's effort reaches the
|
|
78
|
+
// model, mapped and clamped by its own catalog entry.
|
|
79
|
+
return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
|
|
80
|
+
}
|
|
81
|
+
/** OpenRouter's origin: every answer it gives states its cost in its usage (https://openrouter.ai/docs/use-cases/usage-accounting). */
|
|
82
|
+
const OPENROUTER_HOST = "openrouter.ai";
|
|
83
|
+
const onOpenRouter = (origin) => URL.canParse(origin) && new URL(origin).hostname === OPENROUTER_HOST;
|
|
84
|
+
/** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
|
|
85
|
+
const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
|
|
86
|
+
/** How much of an answer's text the error tap keeps: its end, where a stream's error event is. */
|
|
87
|
+
const TAP_WINDOW = 64 * 1024;
|
|
88
|
+
/** `upstream` (the network when absent) with the end of each answer's body kept (`kept()`), as it streams by: what the
|
|
89
|
+
* provider said when pi-ai reports a failure, read for the provider's own error event by its fields (streamErrorOf),
|
|
90
|
+
* which pi-ai's client drops (it keeps the words alone). The body reaches pi-ai as it came. */
|
|
91
|
+
function tapped(upstream) {
|
|
92
|
+
let kept = "";
|
|
93
|
+
const send = upstream ?? globalThis.fetch;
|
|
94
|
+
const fetcher = (async (input, init) => {
|
|
95
|
+
const response = await send(input, init);
|
|
96
|
+
kept = "";
|
|
97
|
+
if (!response.body)
|
|
98
|
+
return response;
|
|
99
|
+
const decoder = new TextDecoder();
|
|
100
|
+
const keep = new TransformStream({
|
|
101
|
+
transform(chunk, controller) {
|
|
102
|
+
kept = (kept + decoder.decode(chunk, { stream: true })).slice(-TAP_WINDOW);
|
|
103
|
+
controller.enqueue(chunk);
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
return new Response(response.body.pipeThrough(keep), { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
107
|
+
});
|
|
108
|
+
return { fetch: fetcher, kept: () => kept };
|
|
73
109
|
}
|
|
74
110
|
/** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
|
|
75
111
|
* pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
|
|
@@ -89,7 +125,11 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
89
125
|
// result of its history as text, and its calls read from its reply. A request with no tools goes as it is.
|
|
90
126
|
const asText = target.toolsAs === "text" && (built.tools?.length ?? 0) > 0;
|
|
91
127
|
const context = asText ? toolsAsText(built) : built;
|
|
92
|
-
|
|
128
|
+
// On OpenRouter, each answer's end is kept as it streams by, for a rate limit it ends in (limitedWords).
|
|
129
|
+
const tap = piOnOpenRouter(target) ? tapped(upstream) : undefined;
|
|
130
|
+
const sendWith = tap?.fetch ?? upstream;
|
|
131
|
+
const level = levelOf(body);
|
|
132
|
+
const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}) };
|
|
93
133
|
const events = models.streamSimple(target, context, streamOptions);
|
|
94
134
|
const encoder = new TextEncoder();
|
|
95
135
|
const stream = new ReadableStream({
|
|
@@ -98,7 +138,31 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
98
138
|
// A failed request's error event carries its words alone, one data line each: pi-ai's Messages client throws an
|
|
99
139
|
// error event's data as the request's error, so the caller reads the model's own error as main's in-process pi
|
|
100
140
|
// reports it ("500 {...}"), never this route's envelope around it.
|
|
101
|
-
const
|
|
141
|
+
const sendWords = (words) => controller.enqueue(encoder.encode(`event: error\n${words.split(/\r?\n/).map((line) => `data: ${line}`).join("\n")}\n\n`));
|
|
142
|
+
// What the provider said the answer cost (pi-ai reads OpenRouter's usage.cost: totalFromProvider), in the
|
|
143
|
+
// message's usage as `cost`, for the proxy to book (usageCostOf). Never pi-ai's own pricing of it.
|
|
144
|
+
const reportedOf = (used) => {
|
|
145
|
+
const cost = used?.cost;
|
|
146
|
+
return cost?.totalFromProvider === true && typeof cost.total === "number" && Number.isFinite(cost.total) && cost.total > 0 ? cost.total : undefined;
|
|
147
|
+
};
|
|
148
|
+
// The provider's own error inside its 200 stream (the tap's kept end, read by its fields: streamErrorOf) goes as
|
|
149
|
+
// Messages writes one (`rate_limit_error` for a rate limit, else `api_error`), after the usage the provider reported
|
|
150
|
+
// before it (`used`, its stated `cost` too) as the message's, so the proxy books it by its one rule for an error in a
|
|
151
|
+
// stream: those tokens at list (or that cost), else refused at nothing. Its top-level `message` is the same words,
|
|
152
|
+
// which pi-ai's Messages client reads as the request's error. A failure with no such event (a transport error, a
|
|
153
|
+
// status) goes as its words alone: the proxy books that as an answer cut short, at an unknown cost. Whatever the
|
|
154
|
+
// model wrote that this translation held is sent before either (sendHeld), so an error with no usage after the
|
|
155
|
+
// model began is never read as a refusal.
|
|
156
|
+
const sendError = (words, used, cost) => {
|
|
157
|
+
const failed = tap ? streamErrorOf(tap.kept()) : undefined;
|
|
158
|
+
if (failed === undefined)
|
|
159
|
+
return sendWords(words);
|
|
160
|
+
const tokens = used ? { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead ?? 0, cache_creation_input_tokens: used.cacheWrite ?? 0 } : undefined;
|
|
161
|
+
if ((tokens && tokens.input_tokens + tokens.output_tokens + tokens.cache_read_input_tokens + tokens.cache_creation_input_tokens > 0) || cost !== undefined) {
|
|
162
|
+
send({ type: "message_delta", delta: { stop_reason: null, stop_sequence: null }, usage: { ...(tokens ?? { input_tokens: 0, output_tokens: 0 }), ...(cost === undefined ? {} : { cost }) } });
|
|
163
|
+
}
|
|
164
|
+
send({ type: "error", message: words, error: { type: failed.rateLimit ? "rate_limit_error" : "api_error", message: words } });
|
|
165
|
+
};
|
|
102
166
|
send({ type: "message_start", message: { id: `msg_${Date.now().toString(36)}`, type: "message", role: "assistant", model: body.model ?? target.id, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } });
|
|
103
167
|
// Messages blocks are numbered as sent. A thinking block is sent too, so the model's reasoning reaches the run's
|
|
104
168
|
// record as a Timeline row; its text goes through the run's one redactor, so a held key the model quoted in its
|
|
@@ -107,13 +171,49 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
107
171
|
const blockOf = new Map();
|
|
108
172
|
const sentJson = new Set();
|
|
109
173
|
let blocks = 0;
|
|
110
|
-
// The thinking of the block being streamed, gathered so its whole text is redacted at once (its deltas are not sent)
|
|
174
|
+
// The thinking of the block being streamed, gathered so its whole text is redacted at once (its deltas are not sent),
|
|
175
|
+
// and that block's index while it is open.
|
|
111
176
|
let thinking = "";
|
|
177
|
+
let thinkingAt;
|
|
112
178
|
const open = (at) => {
|
|
113
179
|
const index = blocks++;
|
|
114
180
|
blockOf.set(at ?? -1, index);
|
|
115
181
|
return index;
|
|
116
182
|
};
|
|
183
|
+
// The thinking block held open, sent as it ends: its whole text through the run's one redactor, then its stop.
|
|
184
|
+
const endThinking = () => {
|
|
185
|
+
if (thinkingAt === undefined)
|
|
186
|
+
return;
|
|
187
|
+
send({ type: "content_block_delta", index: thinkingAt, delta: { type: "thinking_delta", thinking: redact(thinking) } });
|
|
188
|
+
send({ type: "content_block_stop", index: thinkingAt });
|
|
189
|
+
thinkingAt = undefined;
|
|
190
|
+
};
|
|
191
|
+
// What the model wrote that this translation held back when its request fails (a thinking block before its end; a
|
|
192
|
+
// text-tools reply, read whole at its end, here the failed reply's parts): sent before the error, as a provider
|
|
193
|
+
// that streams it would have sent it. The model ran, and the proxy must not read the error as one before anything
|
|
194
|
+
// was generated (a refusal at $0): what it wrote shows it did. A text-tools reply that began with no part pi-ai
|
|
195
|
+
// kept goes as an empty text block, which still shows the model began.
|
|
196
|
+
const sendHeld = (reply) => {
|
|
197
|
+
endThinking();
|
|
198
|
+
if (!reply?.began)
|
|
199
|
+
return;
|
|
200
|
+
const parts = reply.message.content ?? [];
|
|
201
|
+
const thought = parts.filter((each) => each.type === "thinking").map((each) => each.thinking ?? "").join("");
|
|
202
|
+
const text = parts.filter((each) => each.type === "text").map((each) => each.text ?? "").join("");
|
|
203
|
+
if (thought) {
|
|
204
|
+
const index = blocks++;
|
|
205
|
+
send({ type: "content_block_start", index, content_block: { type: "thinking", thinking: "", signature: "" } });
|
|
206
|
+
send({ type: "content_block_delta", index, delta: { type: "thinking_delta", thinking: redact(thought) } });
|
|
207
|
+
send({ type: "content_block_stop", index });
|
|
208
|
+
}
|
|
209
|
+
if (text || !thought) {
|
|
210
|
+
const index = blocks++;
|
|
211
|
+
send({ type: "content_block_start", index, content_block: { type: "text", text: "" } });
|
|
212
|
+
if (text)
|
|
213
|
+
send({ type: "content_block_delta", index, delta: { type: "text_delta", text } });
|
|
214
|
+
send({ type: "content_block_stop", index });
|
|
215
|
+
}
|
|
216
|
+
};
|
|
117
217
|
try {
|
|
118
218
|
for await (const event of asText ? [] : events) {
|
|
119
219
|
const at = event.contentIndex;
|
|
@@ -121,7 +221,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
121
221
|
send({ type: "content_block_start", index: open(at), content_block: { type: "text", text: "" } });
|
|
122
222
|
else if (event.type === "thinking_start") {
|
|
123
223
|
thinking = "";
|
|
124
|
-
|
|
224
|
+
thinkingAt = open(at);
|
|
225
|
+
send({ type: "content_block_start", index: thinkingAt, content_block: { type: "thinking", thinking: "", signature: "" } });
|
|
125
226
|
}
|
|
126
227
|
else if (event.type === "thinking_delta")
|
|
127
228
|
thinking += event.delta ?? "";
|
|
@@ -129,9 +230,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
129
230
|
// The whole thinking at its end, through the run's one redactor, in one delta: a held key the model quoted is
|
|
130
231
|
// cut before pi's session journals it even where it spans two deltas (a cut per delta could miss a key split
|
|
131
232
|
// across them).
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
send({ type: "content_block_stop", index });
|
|
233
|
+
thinkingAt = blockOf.get(at ?? -1);
|
|
234
|
+
endThinking();
|
|
135
235
|
}
|
|
136
236
|
else if (event.type === "text_delta")
|
|
137
237
|
send({ type: "content_block_delta", index: blockOf.get(at ?? -1), delta: { type: "text_delta", text: event.delta ?? "" } });
|
|
@@ -163,11 +263,13 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
163
263
|
else if (event.type === "done" || event.type === "error") {
|
|
164
264
|
const message = (event.type === "done" ? event.message : event.error) ?? {};
|
|
165
265
|
if (event.type === "error") {
|
|
166
|
-
|
|
266
|
+
sendHeld();
|
|
267
|
+
sendError(redact(message.errorMessage ?? event.reason ?? "the model's request failed"), message.usage, reportedOf(message.usage));
|
|
167
268
|
break;
|
|
168
269
|
}
|
|
169
270
|
const used = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
170
|
-
|
|
271
|
+
const cost = reportedOf(message.usage);
|
|
272
|
+
send({ type: "message_delta", delta: { stop_reason: stopReasonOf(event.reason ?? message.stopReason), stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite, ...(cost === undefined ? {} : { cost }) } });
|
|
171
273
|
send({ type: "message_stop" });
|
|
172
274
|
}
|
|
173
275
|
}
|
|
@@ -178,6 +280,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
178
280
|
// left of it once the tries so far and the re-ask's own input, uncached, are paid.
|
|
179
281
|
const tools = built.tools ?? [];
|
|
180
282
|
const used = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
283
|
+
// The provider's cost of every try, summed while each stated one; unknown once one did not.
|
|
284
|
+
let reported = 0;
|
|
181
285
|
const outputHeld = body.max_tokens ?? target.maxTokens;
|
|
182
286
|
let heldUsd = 0;
|
|
183
287
|
let spentUsd = 0;
|
|
@@ -185,12 +289,29 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
185
289
|
let nextTokens = 0;
|
|
186
290
|
for (let attempt = 1;; attempt++) {
|
|
187
291
|
let again = false;
|
|
292
|
+
// Whether this try's reply began: any of its content's events (pi-ai's `start` is the request's own).
|
|
293
|
+
let began = false;
|
|
188
294
|
for await (const event of replies) {
|
|
189
|
-
if (event.type !== "done" && event.type !== "error")
|
|
295
|
+
if (event.type !== "done" && event.type !== "error") {
|
|
296
|
+
if (event.type !== "start")
|
|
297
|
+
began = true;
|
|
190
298
|
continue;
|
|
299
|
+
}
|
|
191
300
|
const message = (event.type === "done" ? event.message : event.error) ?? {};
|
|
192
301
|
if (event.type === "error") {
|
|
193
|
-
|
|
302
|
+
const wrote = began || (message.content ?? []).length > 0;
|
|
303
|
+
sendHeld({ began: wrote, message });
|
|
304
|
+
// The tries so far were paid, and this one's usage too: their sum, with their stated cost while each
|
|
305
|
+
// try that reported tokens stated one. A try that wrote and then failed with no usage and no cost ran at
|
|
306
|
+
// a cost nobody said: the sum of the tries before it would undercount the request, so none is sent
|
|
307
|
+
// and the request's total is unknown (the cap's hold covers every try).
|
|
308
|
+
const given = message.usage;
|
|
309
|
+
const own = reportedOf(given);
|
|
310
|
+
const said = given !== undefined && given.input + given.output + (given.cacheRead ?? 0) + (given.cacheWrite ?? 0) > 0;
|
|
311
|
+
const unsaid = wrote && !said && own === undefined;
|
|
312
|
+
const tokens = unsaid ? undefined : { input: used.input + (given?.input ?? 0), output: used.output + (given?.output ?? 0), cacheRead: used.cacheRead + (given?.cacheRead ?? 0), cacheWrite: used.cacheWrite + (given?.cacheWrite ?? 0) };
|
|
313
|
+
const cost = unsaid || reported === undefined || (said && own === undefined) ? undefined : reported + (own ?? 0);
|
|
314
|
+
sendError(redact(message.errorMessage ?? event.reason ?? "the model's request failed"), tokens, cost !== undefined && cost > 0 ? cost : undefined);
|
|
194
315
|
break;
|
|
195
316
|
}
|
|
196
317
|
const given = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
@@ -199,6 +320,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
199
320
|
used.output += part.output;
|
|
200
321
|
used.cacheRead += part.cacheRead;
|
|
201
322
|
used.cacheWrite += part.cacheWrite;
|
|
323
|
+
const cost = reportedOf(message.usage);
|
|
324
|
+
reported = reported === undefined || cost === undefined ? undefined : reported + cost;
|
|
202
325
|
if (attempt === 1 && outputHeld !== undefined)
|
|
203
326
|
heldUsd = priceOn(target, { ...part, output: outputHeld });
|
|
204
327
|
spentUsd += priceOn(target, part);
|
|
@@ -236,7 +359,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
236
359
|
send({ type: "content_block_stop", index });
|
|
237
360
|
}
|
|
238
361
|
const reason = read.calls.length ? "tool_use" : stopReasonOf(event.reason === "toolUse" ? "stop" : event.reason ?? message.stopReason);
|
|
239
|
-
send({ type: "message_delta", delta: { stop_reason: reason, stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite } });
|
|
362
|
+
send({ type: "message_delta", delta: { stop_reason: reason, stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite, ...(reported === undefined ? {} : { cost: reported }) } });
|
|
240
363
|
send({ type: "message_stop" });
|
|
241
364
|
}
|
|
242
365
|
if (!again)
|
|
@@ -246,6 +369,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
246
369
|
}
|
|
247
370
|
}
|
|
248
371
|
catch (error) {
|
|
372
|
+
sendHeld();
|
|
249
373
|
sendError(redact(error?.message ?? String(error)));
|
|
250
374
|
}
|
|
251
375
|
controller.close();
|
|
@@ -256,6 +380,18 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
|
|
|
256
380
|
}
|
|
257
381
|
/** pi-ai's stop reason as Messages says it. */
|
|
258
382
|
const stopReasonOf = (reason) => (reason === "toolUse" ? "tool_use" : reason === "length" ? "max_tokens" : "end_turn");
|
|
383
|
+
/** pi-ai's thinking levels past off, each asked by its own name. */
|
|
384
|
+
const NAMED_LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
|
|
385
|
+
/** How the route's translation has pi's session register a model that reasons: on Messages, with adaptive thinking whose
|
|
386
|
+
* effort is the level's own name (a thinkingLevelMap of each level to itself), so a request carries the session's level
|
|
387
|
+
* as it is, `output_config.effort`, and no budget the translation would have to read a level back from. Off maps to
|
|
388
|
+
* nothing: a session at off sends thinking disabled, and no level reaches the model. */
|
|
389
|
+
const LEVELS_BY_NAME = { reasoning: true, adaptiveThinking: true, thinkingLevelMap: Object.fromEntries(NAMED_LEVELS.map((level) => [level, level])) };
|
|
390
|
+
/** The thinking level a Messages request from pi's session asks (LEVELS_BY_NAME), else undefined: none asked, or off. */
|
|
391
|
+
function levelOf(body) {
|
|
392
|
+
const effort = body.output_config?.effort;
|
|
393
|
+
return body.thinking?.type === "adaptive" && NAMED_LEVELS.includes(effort) ? effort : undefined;
|
|
394
|
+
}
|
|
259
395
|
const textOf = (content) => (typeof content === "string" ? content : (content ?? []).filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n"));
|
|
260
396
|
/** A Messages block as pi-ai's part: a text as text, a base64 image as an image; anything else none. */
|
|
261
397
|
const partOf = (block) => block.type === "text" ? [{ type: "text", text: block.text ?? "" }] : block.type === "image" && block.source?.data ? [{ type: "image", data: block.source.data, mimeType: block.source.media_type ?? "image/png" }] : [];
|
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { MonidPinBody } from "../store/index.js";
|
|
2
2
|
import type { Workspace } from "../workspace/index.js";
|
|
3
3
|
import type { ClaimMcp } from "./mcp-run.js";
|
|
4
4
|
/** The run's monid endpoints, as the loop's catalog seam reads them. */
|
|
5
5
|
export type ClaimMonid = Pick<ClaimMcp, "tools" | "catalogOf" | "priceOf">;
|
|
6
|
+
/** A template eval case's monid fake (template-eval.ts, `monid:` in its case.yaml): `unavailable`, monid unreachable. */
|
|
7
|
+
export type MonidFake = "unavailable";
|
|
6
8
|
/** One host tool per endpoint of `pin`, on the claim's environment `env` (its key, and the tests' fake under faux), an
|
|
7
|
-
* answer too long for the model filed in `work()`; undefined when the pin holds none. `runId` names the run in the log
|
|
8
|
-
|
|
9
|
+
* answer too long for the model filed in `work()`; undefined when the pin holds none. `runId` names the run in the log;
|
|
10
|
+
* `capped`, whether the run has a spend cap now (its launch's, read at each call). `fake`: a template eval case's monid
|
|
11
|
+
* fake (AdapterSpecDeps.evalFakes), `unavailable`: each call goes as it does with monid unreachable, its price read
|
|
12
|
+
* first and failing, so it is never sent, and nothing is held or booked. */
|
|
13
|
+
export declare function monidForClaim(pin: MonidPinBody | undefined, env: NodeJS.ProcessEnv, work: () => Workspace, runId?: string, capped?: () => boolean, fake?: MonidFake): ClaimMonid | undefined;
|
|
9
14
|
/** The claim's MCP with the run's monid endpoints beside it: the one catalog seam the loop reads (AdapterRunSpec.mcp).
|
|
10
15
|
* Its credentials' hooks are MCP's alone, and so is the closure of a pinned tool's arguments (argumentsOf: the gate's
|
|
11
16
|
* settings pins are on MCP tools; a monid endpoint's input is held to its pinned schema by the harness), and so is each
|
|
12
17
|
* tool's effect (effectOf: Allow reads and the destructive confirm read an MCP tool's annotations; an endpoint has none). */
|
|
13
18
|
export declare function withMonid(mcp: ClaimMcp | undefined, monid: ClaimMonid | undefined): ClaimMcp | undefined;
|
|
14
|
-
/** What a subagent may be given for the grant `grant` (subagent.ts sessionNames): for a provider's wildcard, every endpoint
|
|
15
|
-
* the revision's `pin` holds of that provider, by wire name; undefined for any other grant. */
|
|
16
|
-
export declare function monidSessionNames(grant: string, pin: MonidPin | undefined): string[] | undefined;
|