@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.45
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 +231 -0
- package/README.md +580 -320
- package/dist/acp-package.d.ts +28 -0
- package/dist/acp-package.js +23 -0
- package/dist/adapter-facts.d.ts +8 -1
- package/dist/adapter-facts.js +9 -1
- package/dist/adapters.d.ts +5 -0
- package/dist/adapters.js +36 -3
- package/dist/agent-delete.d.ts +50 -0
- package/dist/agent-delete.js +125 -0
- package/dist/agents-store.d.ts +9 -3
- package/dist/agents-store.js +22 -8
- package/dist/agents.d.ts +5 -1
- package/dist/agents.js +8 -4
- package/dist/api-only.d.ts +8 -3
- package/dist/api-only.js +10 -4
- package/dist/archil-routes.d.ts +5 -1
- package/dist/archil-routes.js +57 -2
- package/dist/browser-wait-ended.d.ts +2 -0
- package/dist/browser-wait-ended.js +2 -0
- package/dist/calendar/ics-faux.d.ts +3 -1
- package/dist/calendar/ics-faux.js +12 -2
- package/dist/calendar/tools.js +5 -2
- package/dist/chatgpt-plan.js +3 -1
- package/dist/claude-login.d.ts +135 -0
- package/dist/claude-login.js +244 -0
- package/dist/cli.js +92 -22
- package/dist/composio-preset.d.ts +4 -3
- package/dist/composio-preset.js +81 -11
- package/dist/composio-triggers.d.ts +34 -2
- package/dist/composio-triggers.js +261 -31
- package/dist/computer-attach.d.ts +40 -5
- package/dist/computer-attach.js +130 -15
- package/dist/computer-keys.d.ts +3 -0
- package/dist/computer-keys.js +7 -1
- package/dist/computer-live.js +3 -2
- package/dist/computer-lost.d.ts +11 -0
- package/dist/computer-lost.js +19 -0
- package/dist/computer-record.d.ts +10 -2
- package/dist/computer-record.js +50 -18
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +2 -2
- package/dist/computers.d.ts +21 -10
- package/dist/computers.js +39 -28
- package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
- package/dist/console/assets/index-DaFsZuzQ.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.d.ts +1 -1
- package/dist/dial-relay.d.ts +29 -0
- package/dist/dial-relay.js +94 -0
- package/dist/email/tools.js +10 -5
- package/dist/env-proxy.d.ts +2 -0
- package/dist/env-proxy.js +35 -0
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +10 -4
- package/dist/faux-computers.d.ts +8 -2
- package/dist/faux-computers.js +83 -6
- package/dist/harness-archive.d.ts +67 -0
- package/dist/harness-archive.js +177 -0
- package/dist/harness-goose.d.ts +34 -0
- package/dist/harness-goose.js +87 -0
- package/dist/harness-install.d.ts +21 -0
- package/dist/harness-install.js +24 -11
- package/dist/harness-opencode/adapter.js +1 -1
- package/dist/harness-table.d.ts +59 -3
- package/dist/harness-table.js +119 -14
- package/dist/harness.d.ts +17 -1
- package/dist/harness.js +22 -11
- package/dist/host.d.ts +12 -10
- package/dist/host.js +19 -16
- package/dist/import-worker.d.ts +3 -0
- package/dist/import-worker.js +7 -5
- package/dist/import.d.ts +22 -1
- package/dist/import.js +141 -28
- package/dist/key-check.js +3 -0
- package/dist/learn/audit.d.ts +6 -6
- package/dist/learn/audit.js +3 -7
- package/dist/learn/check.d.ts +26 -89
- package/dist/learn/check.js +58 -336
- package/dist/learn/commit.d.ts +63 -90
- package/dist/learn/commit.js +124 -316
- package/dist/learn/compile.d.ts +53 -50
- package/dist/learn/compile.js +88 -103
- package/dist/learn/corrections.d.ts +13 -0
- package/dist/learn/corrections.js +23 -0
- package/dist/learn/delete.d.ts +17 -0
- package/dist/learn/delete.js +42 -0
- package/dist/learn/folder.d.ts +35 -47
- package/dist/learn/folder.js +118 -134
- package/dist/learn/index.d.ts +3 -5
- package/dist/learn/index.js +6 -9
- package/dist/learn/learning.sh +45 -15
- package/dist/learn/promote.d.ts +20 -2
- package/dist/learn/promote.js +17 -4
- package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +34 -38
- package/dist/learn/{skills.js → workflow-draft.js} +65 -59
- package/dist/learn/workflow-nodes.d.ts +22 -1
- package/dist/learn/workflow-nodes.js +29 -10
- package/dist/learned-workflow.js +2 -2
- package/dist/learning-cost.d.ts +127 -13
- package/dist/learning-cost.js +142 -10
- package/dist/learning-routes.d.ts +99 -170
- package/dist/learning-routes.js +199 -420
- package/dist/learning-run.d.ts +19 -40
- package/dist/learning-run.js +23 -93
- package/dist/learning-setting.d.ts +4 -4
- package/dist/learning-setting.js +6 -6
- package/dist/learning-words.d.ts +28 -74
- package/dist/learning-words.js +64 -162
- package/dist/learning.d.ts +62 -393
- package/dist/learning.js +101 -651
- package/dist/listen-first.d.ts +30 -0
- package/dist/listen-first.js +115 -0
- package/dist/live-reach.d.ts +25 -2
- package/dist/live-reach.js +46 -4
- package/dist/llms.txt +2 -1
- package/dist/local-models.d.ts +3 -11
- package/dist/local-models.js +5 -6
- package/dist/mcp-servers-store.d.ts +16 -16
- package/dist/model-form.js +6 -5
- package/dist/model.d.ts +12 -4
- package/dist/model.js +41 -16
- package/dist/native/binding.js +1 -1
- package/dist/native/connection.js +1 -1
- package/dist/native/discovery.js +1 -1
- package/dist/native/instructions.d.ts +3 -0
- package/dist/native/instructions.js +5 -3
- package/dist/native/remote-worker-bridge.js +9 -43
- package/dist/native/remote.d.ts +8 -15
- package/dist/native/remote.js +3 -3
- package/dist/native/schema.js +1 -1
- package/dist/native/types.d.ts +2 -2
- package/dist/openapi.js +375 -347
- package/dist/owner.d.ts +8 -0
- package/dist/owner.js +11 -0
- package/dist/paid-calls.d.ts +14 -0
- package/dist/paid-calls.js +31 -1
- package/dist/particle-provider.d.ts +11 -0
- package/dist/particle-provider.js +135 -0
- package/dist/place.d.ts +8 -3
- package/dist/place.js +13 -9
- package/dist/port-models.d.ts +12 -4
- package/dist/port-models.js +28 -11
- package/dist/print.d.ts +27 -0
- package/dist/print.js +21 -0
- package/dist/provider.d.ts +7 -0
- package/dist/provider.js +30 -2
- package/dist/reflect-range.js +2 -3
- package/dist/run-launch.d.ts +14 -28
- package/dist/run-launch.js +9 -12
- package/dist/run-learning-served.d.ts +16 -90
- package/dist/run-listing.d.ts +34 -0
- package/dist/run-listing.js +128 -0
- package/dist/run-model-key.d.ts +64 -0
- package/dist/run-model-key.js +147 -0
- package/dist/run-timeline-served.js +5 -3
- package/dist/run-trace.d.ts +97 -0
- package/dist/run-trace.js +253 -0
- package/dist/run-view.d.ts +15 -0
- package/dist/run-view.js +9 -0
- package/dist/runnable.js +2 -1
- package/dist/runner/adapter-loop.d.ts +14 -6
- package/dist/runner/adapter-loop.js +25 -14
- package/dist/runner/adapter-run-spec.d.ts +22 -7
- package/dist/runner/adapter-run-spec.js +130 -77
- package/dist/runner/adapters/index.d.ts +4 -2
- package/dist/runner/adapters/index.js +35 -4
- package/dist/runner/adapters/pi.d.ts +4 -12
- package/dist/runner/adapters/pi.js +2 -2
- package/dist/runner/audit.d.ts +5 -1
- package/dist/runner/audit.js +31 -12
- package/dist/runner/beside.d.ts +7 -2
- package/dist/runner/beside.js +41 -9
- package/dist/runner/claim-secrets.d.ts +66 -1
- package/dist/runner/claim-secrets.js +136 -3
- package/dist/runner/cli-run-spec.d.ts +2 -1
- package/dist/runner/cli-run-spec.js +82 -59
- package/dist/runner/commands.d.ts +3 -6
- package/dist/runner/conformance/harness.d.ts +6 -0
- package/dist/runner/conformance/harness.js +16 -5
- package/dist/runner/dispatch.d.ts +2 -2
- package/dist/runner/end-of-run.d.ts +6 -14
- package/dist/runner/end-of-run.js +8 -33
- package/dist/runner/feedback-round.d.ts +5 -4
- package/dist/runner/feedback-round.js +14 -10
- package/dist/runner/github-app.js +3 -1
- package/dist/runner/harness-loops.d.ts +0 -8
- package/dist/runner/harness-loops.js +30 -56
- package/dist/runner/held.d.ts +170 -0
- package/dist/runner/held.js +57 -0
- package/dist/runner/journal-kinds.d.ts +7 -3
- package/dist/runner/journal-kinds.js +2 -3
- package/dist/runner/learned-first.d.ts +40 -0
- package/dist/runner/learned-first.js +32 -0
- package/dist/runner/learning-end.d.ts +77 -66
- package/dist/runner/learning-end.js +250 -299
- package/dist/runner/learning-seed.d.ts +15 -33
- package/dist/runner/learning-seed.js +24 -45
- package/dist/runner/loop-contract.d.ts +8 -3
- package/dist/runner/loop-contract.js +4 -0
- package/dist/runner/loop.js +6 -2
- package/dist/runner/main.d.ts +18 -9
- package/dist/runner/main.js +82 -22
- package/dist/runner/mcp-run.d.ts +11 -0
- package/dist/runner/mcp-run.js +67 -0
- package/dist/runner/memory-claim.d.ts +14 -6
- package/dist/runner/memory-claim.js +18 -9
- package/dist/runner/model-route.d.ts +7 -4
- package/dist/runner/model-route.js +22 -10
- package/dist/runner/native-loop.d.ts +0 -7
- package/dist/runner/native-loop.js +9 -101
- package/dist/runner/promotion.d.ts +13 -6
- package/dist/runner/promotion.js +63 -17
- package/dist/runner/reflect-hook.d.ts +64 -91
- package/dist/runner/reflect-hook.js +112 -206
- package/dist/runner/run-channel.d.ts +43 -0
- package/dist/runner/run-channel.js +467 -0
- package/dist/runner/run-child-host.d.ts +169 -0
- package/dist/runner/run-child-host.js +1222 -0
- package/dist/runner/run-child.d.ts +1 -0
- package/dist/runner/run-child.js +254 -0
- package/dist/runner/run-errors.d.ts +2 -0
- package/dist/runner/run-errors.js +20 -0
- package/dist/runner/runner.js +58 -9
- package/dist/runner/sdk-ask.d.ts +78 -0
- package/dist/runner/sdk-ask.js +158 -0
- package/dist/runner/sdk-loop.d.ts +2 -4
- package/dist/runner/sdk-loop.js +29 -49
- package/dist/runner/store-secrets.d.ts +5 -3
- package/dist/runner/store-secrets.js +14 -6
- package/dist/runner/workflow-first.d.ts +5 -0
- package/dist/runner/workflow-first.js +4 -0
- package/dist/runner/workflow-spec.js +17 -4
- package/dist/runs-over-store.d.ts +21 -32
- package/dist/runs-over-store.js +44 -41
- package/dist/sdk/runs.d.ts +6 -11
- package/dist/sdk/runs.js +20 -41
- package/dist/sdk/schema.js +3 -4
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/seal-key.d.ts +5 -0
- package/dist/seal-key.js +7 -0
- package/dist/secrets.d.ts +3 -0
- package/dist/secrets.js +16 -3
- package/dist/server.d.ts +119 -83
- package/dist/server.js +1121 -419
- package/dist/sign-ins-store.d.ts +8 -0
- package/dist/sign-ins-store.js +36 -1
- package/dist/skills.js +1 -1
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/journal/storage.js +3 -0
- package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
- package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
- package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
- package/dist/store/schema.d.ts +53 -4
- package/dist/store/schema.js +137 -6
- package/dist/store/seal.d.ts +20 -2
- package/dist/store/seal.js +24 -8
- package/dist/store/sqlite/connection.d.ts +2 -0
- package/dist/store/sqlite/connection.js +3 -1
- package/dist/store/sqlite/run-launch.d.ts +4 -1
- package/dist/store/sqlite/run-launch.js +12 -0
- package/dist/store/sqlite/run-patch.d.ts +0 -17
- package/dist/store/sqlite/run-patch.js +4 -33
- package/dist/store/sqlite/store.d.ts +3 -2
- package/dist/store/sqlite/store.js +360 -75
- package/dist/store/sqlite/worker.js +25 -0
- package/dist/store/store.d.ts +231 -39
- package/dist/store/store.js +25 -3
- package/dist/store-reads/analytics.js +11 -1
- package/dist/store-reads/learning.d.ts +131 -194
- package/dist/store-reads/learning.js +292 -301
- package/dist/store-reads/loop.d.ts +0 -1
- package/dist/store-reads/loop.js +1 -1
- package/dist/store-reads/stats.js +13 -3
- package/dist/store-view.d.ts +34 -2
- package/dist/store-view.js +108 -41
- package/dist/telemetry.d.ts +59 -0
- package/dist/telemetry.js +153 -0
- package/dist/template-eval.d.ts +3 -6
- package/dist/template-eval.js +22 -36
- package/dist/templates.d.ts +2 -1
- package/dist/templates.js +6 -3
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +5 -1
- package/dist/timeline/timeline.js +16 -0
- package/dist/tool-gate.d.ts +0 -7
- package/dist/tool-gate.js +1 -15
- package/dist/tool-keys-store.d.ts +1 -1
- package/dist/tool-keys.d.ts +6 -4
- package/dist/tool-keys.js +12 -6
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +13 -13
- package/dist/tools.js +29 -9
- package/dist/trigger-adapter.d.ts +3 -0
- package/dist/trigger-adapters.d.ts +4 -0
- package/dist/trigger-adapters.js +13 -0
- package/dist/trigger-composio.d.ts +58 -1
- package/dist/trigger-composio.js +160 -6
- package/dist/triggers.d.ts +64 -5
- package/dist/triggers.js +141 -17
- package/dist/validate.d.ts +11 -7
- package/dist/validate.js +9 -8
- package/dist/webhooks.d.ts +4 -1
- package/dist/webhooks.js +11 -4
- package/dist/workspace/agent-computer.d.ts +2 -0
- package/dist/workspace/agent-computer.js +2 -0
- package/dist/workspace/archil-claim.d.ts +7 -0
- package/dist/workspace/archil-claim.js +29 -0
- package/dist/workspace/archil.d.ts +9 -1
- package/dist/workspace/archil.js +165 -3
- package/dist/workspace/attach.d.ts +3 -1
- package/dist/workspace/attach.js +2 -0
- package/dist/workspace/attached-computers.d.ts +16 -5
- package/dist/workspace/attached-computers.js +25 -9
- package/dist/workspace/computer-deps.js +1 -1
- package/dist/workspace/computer-for-claim.d.ts +22 -8
- package/dist/workspace/computer-for-claim.js +339 -46
- package/dist/workspace/computer-hold.js +2 -1
- package/dist/workspace/computer-kept.d.ts +11 -1
- package/dist/workspace/computer-kept.js +24 -3
- package/dist/workspace/resolve-computer.d.ts +41 -21
- package/dist/workspace/resolve-computer.js +172 -64
- package/dist/workspace/revision-skills.d.ts +1 -2
- package/dist/workspace/revision-skills.js +3 -4
- package/dist/workspace/run-workspace.d.ts +1 -1
- package/dist/workspace/run-workspace.js +5 -0
- package/dist/workspace/synced-folder.d.ts +85 -0
- package/dist/workspace/synced-folder.js +230 -0
- package/dist/workspace/workspace.d.ts +4 -0
- package/launcher/agentrun-serve +1 -1
- package/package.json +10 -9
- package/templates/README.md +7 -7
- package/templates/inbound-lead/agent.md +3 -3
- package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
- package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
- package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
- package/templates/inbound-lead/lead.schema.json +6 -5
- package/templates/inbound-lead/rules/RUBRIC.md +4 -4
- package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
- package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
- package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
- package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
- package/templates/release-notes/evals/learned-style/case.yaml +4 -4
- package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
- package/templates/release-notes/evals/learned-style/prompt.md +1 -1
- package/dist/console/assets/index-BrcDSBD8.css +0 -1
- package/dist/console/assets/index-Bz6IWncl.js +0 -711
- package/dist/learn/grade.d.ts +0 -138
- package/dist/learn/grade.js +0 -682
- package/dist/learn/notes.d.ts +0 -81
- package/dist/learn/notes.js +0 -178
- package/dist/learn/reflect.d.ts +0 -77
- package/dist/learn/reflect.js +0 -228
- package/dist/learn/relevance.d.ts +0 -24
- package/dist/learn/relevance.js +0 -91
- package/dist/learn/seed-check.d.ts +0 -74
- package/dist/learn/seed-check.js +0 -103
- package/dist/learning-batch.d.ts +0 -291
- package/dist/learning-batch.js +0 -600
- package/dist/learning-evals.d.ts +0 -33
- package/dist/learning-evals.js +0 -98
- package/dist/native/context.d.ts +0 -6
- package/dist/native/context.js +0 -22
- package/dist/propose.d.ts +0 -52
- package/dist/propose.js +0 -224
- package/dist/runner/learning-ask.d.ts +0 -47
- package/dist/runner/learning-ask.js +0 -128
- package/dist/runner/learning-dispatch.d.ts +0 -45
- package/dist/runner/learning-dispatch.js +0 -99
- package/dist/runner/learning-factory.d.ts +0 -16
- package/dist/runner/learning-factory.js +0 -50
- package/dist/runner/learning-loop.d.ts +0 -273
- package/dist/runner/learning-loop.js +0 -521
- package/dist/usage.d.ts +0 -11
- package/dist/usage.js +0 -11
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// A run's own model key: a key its caller hands with the run (`model_key` on POST /runs, POST /agents/{id}/runs and
|
|
2
|
+
// POST /runs/{id}/messages), such as a LiteLLM virtual key minted for that run, which every model request the run makes
|
|
3
|
+
// carries in place of the server's own key. AgentRun never mints, lists or revokes it: the caller owns its life.
|
|
4
|
+
//
|
|
5
|
+
// Where it goes: the model gateway at AGENT_MODEL_BASE_URL, which every pi model and every workflow model node is sent to,
|
|
6
|
+
// and Anthropic's Messages endpoint when ANTHROPIC_BASE_URL names that same gateway origin (a CLI harness on Anthropic's
|
|
7
|
+
// wire). It is sealed with the run, bound to that origin when handed (store/seal.ts RunModelKey), so a gateway moved since
|
|
8
|
+
// never receives it; it fills the gateway's key variable (and ANTHROPIC_API_KEY on that origin) in the model routes' env
|
|
9
|
+
// alone, read at each request, never enumerable and never on the env a tool, a harness or a sandbox runs under.
|
|
10
|
+
//
|
|
11
|
+
// No setting: what the server holds decides. A run with a model_key spends on it alone, outside its turn too (its
|
|
12
|
+
// subagents, learned nodes, end-of-run compile turn), never on the server's key. A run without one spends on the server's
|
|
13
|
+
// key for its route, as before. A server that holds no key for a run's route (no AGENT_MODEL_API_KEY, nothing saved in
|
|
14
|
+
// Settings) is an operator saying "callers bring their own": a start or a message that would start a turn with no key
|
|
15
|
+
// to spend is 422 model_key_required, never a failure at the first model call. Spend after a run's turn ended (its key
|
|
16
|
+
// erased with that end, and revoked by its caller) or tied to no run, with no key to spend, is skipped or refused in words.
|
|
17
|
+
import { ApiError } from "./errors.js";
|
|
18
|
+
import { FAUX_ENV, GATEWAY_KEY_ENV, MODEL_PROVIDER, PROVIDER_KEYS } from "./model.js";
|
|
19
|
+
import { gatewayBase } from "./provider.js";
|
|
20
|
+
/** The longest model key a run takes: a header value, never a document. */
|
|
21
|
+
export const MAX_MODEL_KEY_CHARS = 4096;
|
|
22
|
+
/** The origin of the model gateway a run's model key goes to (AGENT_MODEL_BASE_URL's, by the one base rule), or undefined
|
|
23
|
+
* when the server names none or one a key may not go to. */
|
|
24
|
+
export function runModelOrigin(env) {
|
|
25
|
+
if (!env.AGENT_MODEL_BASE_URL)
|
|
26
|
+
return undefined;
|
|
27
|
+
try {
|
|
28
|
+
return new URL(gatewayBase("AGENT_MODEL_BASE_URL", env.AGENT_MODEL_BASE_URL)).origin;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Whether ANTHROPIC_BASE_URL names the gateway at `origin`: there a CLI harness on Anthropic's wire sends ANTHROPIC_API_KEY,
|
|
35
|
+
* which a run's key then fills. */
|
|
36
|
+
function anthropicOnGateway(env, origin) {
|
|
37
|
+
if (!env.ANTHROPIC_BASE_URL)
|
|
38
|
+
return false;
|
|
39
|
+
try {
|
|
40
|
+
return new URL(gatewayBase("ANTHROPIC_BASE_URL", env.ANTHROPIC_BASE_URL)).origin === origin;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** The variables a run's model key fills in a model route's env, for a gateway at `origin`: the gateway's key, and
|
|
47
|
+
* ANTHROPIC_API_KEY where ANTHROPIC_BASE_URL is that same gateway. */
|
|
48
|
+
export function runKeyNames(env, origin) {
|
|
49
|
+
return [GATEWAY_KEY_ENV, ...(anthropicOnGateway(env, origin) ? ["ANTHROPIC_API_KEY"] : [])];
|
|
50
|
+
}
|
|
51
|
+
/** Every model key a model route reads by name: each of pi-ai's providers' and the gateway's. */
|
|
52
|
+
const MODEL_KEY_NAMES = new Set([...Object.values(PROVIDER_KEYS).flat(), GATEWAY_KEY_ENV]);
|
|
53
|
+
/** A model key `body` hands, checked: text of 1 to MAX_MODEL_KEY_CHARS characters with no whitespace or control character
|
|
54
|
+
* (it goes in a header). Issues are pushed at `model_key`. */
|
|
55
|
+
export function modelKeyOf(value, issues) {
|
|
56
|
+
if (typeof value !== "string")
|
|
57
|
+
return void issues.push({ field: "model_key", reason: "wrong_type", message: "model_key is the run's model key as text, such as a LiteLLM virtual key minted for this run." });
|
|
58
|
+
if (!value.length || value.length > MAX_MODEL_KEY_CHARS || /[\s\x00-\x1f\x7f]/.test(value))
|
|
59
|
+
return void issues.push({ field: "model_key", reason: "invalid", message: `model_key is 1 to ${MAX_MODEL_KEY_CHARS} characters with no space or control character.` });
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
/** 422 model_key_required: a run start, or a message that would start a turn, with no model key to spend: none handed,
|
|
63
|
+
* none the run holds, and none the server holds for its route. */
|
|
64
|
+
export const modelKeyRequired = (message) => new ApiError("model_key_required", `This server holds no model key for this run's model (AGENT_MODEL_API_KEY is not set and none is saved in Settings → Model keys), so each run's caller brings its own: send model_key with ${message ? "a message that starts a turn" : "the run"}, a key for the model gateway at AGENT_MODEL_BASE_URL (such as a LiteLLM virtual key) minted for ${message ? "that turn" : "this run"}.`, { fields: [{ field: "model_key", reason: "missing", message: "model_key is required here: the server holds no model key for this run's model." }] });
|
|
65
|
+
/** The variables a run's model route reads its key from when that route goes to the model gateway (a workflow's model
|
|
66
|
+
* nodes, pi's and codex's models, a CLI harness on Anthropic's wire where ANTHROPIC_BASE_URL is the gateway's origin);
|
|
67
|
+
* undefined for a route that goes elsewhere (a provider's own, the ChatGPT plan, the faux model) or a native run. */
|
|
68
|
+
export function gatewayKeyNames(env, run) {
|
|
69
|
+
const origin = runModelOrigin(env);
|
|
70
|
+
if (!origin || run.native || env[FAUX_ENV])
|
|
71
|
+
return undefined;
|
|
72
|
+
if (run.kind === "workflow" || run.model?.provider === MODEL_PROVIDER)
|
|
73
|
+
return [GATEWAY_KEY_ENV];
|
|
74
|
+
if (run.model?.provider === "anthropic" && anthropicOnGateway(env, origin))
|
|
75
|
+
return ["ANTHROPIC_API_KEY"];
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
/** Whether a run of `run` with no key of its own has none to spend: its route goes to the gateway, and `env` (the
|
|
79
|
+
* server's, with the keys saved in Settings) holds no key it reads. */
|
|
80
|
+
export function serverKeyMissing(env, run) {
|
|
81
|
+
const names = gatewayKeyNames(env, run);
|
|
82
|
+
return names !== undefined && !names.some((name) => env[name]);
|
|
83
|
+
}
|
|
84
|
+
/** Words for model spend tied to no run's key (`what`, a noun phrase) on a server that holds no gateway key (`env`, its
|
|
85
|
+
* keys saved in Settings among them): skipped or refused, never sent with no key. Undefined where the server holds one. */
|
|
86
|
+
export function noServerKeyFor(env, what) {
|
|
87
|
+
return runModelOrigin(env) && !env[GATEWAY_KEY_ENV] ? noServerKeyWords(what) : undefined;
|
|
88
|
+
}
|
|
89
|
+
/** The words of noServerKeyFor for `what`. */
|
|
90
|
+
export const noServerKeyWords = (what) => `${what} is skipped: it is tied to no run's model key, and this server holds none of its own (AGENT_MODEL_API_KEY is not set and none is saved in Settings → Model keys).`;
|
|
91
|
+
/** Words for spend after the turn of a run that held its own model key (`what`): skipped, since that key is erased with
|
|
92
|
+
* the turn's end and revoked by its caller, and the server's key never pays for a run that brought its own. */
|
|
93
|
+
export const runKeyEndedFor = (what) => `${what} is skipped: this run spent on its own model key, which is erased when its turn ends; the server's key never pays for a run that brought its own.`;
|
|
94
|
+
/** Why a run's model key would never be used, so it is refused rather than kept unused; undefined where it applies: a
|
|
95
|
+
* workflow run (its model nodes go to the gateway), or an agentic run whose model goes to the gateway (pi's and codex's,
|
|
96
|
+
* MODEL_PROVIDER) or to Anthropic's endpoint on the gateway's origin (a CLI harness on Anthropic's wire). */
|
|
97
|
+
export function modelKeyMisfit(env, run) {
|
|
98
|
+
const origin = runModelOrigin(env);
|
|
99
|
+
if (!origin)
|
|
100
|
+
return "This server sends no model through a gateway (AGENT_MODEL_BASE_URL is not set), so a run's model key has nowhere to go.";
|
|
101
|
+
if (run.native)
|
|
102
|
+
return "A native run's model runs on its own machine, never through this server's gateway, so a model key would never be used.";
|
|
103
|
+
if (run.kind === "workflow")
|
|
104
|
+
return undefined;
|
|
105
|
+
if (run.model?.provider === MODEL_PROVIDER)
|
|
106
|
+
return undefined;
|
|
107
|
+
if (run.model?.provider === "anthropic" && anthropicOnGateway(env, origin))
|
|
108
|
+
return undefined;
|
|
109
|
+
const named = run.model ? `${run.model.provider}/${run.model.modelId}` : "its harness's own model";
|
|
110
|
+
return `This run's model (${named}) is not sent through the gateway at AGENT_MODEL_BASE_URL, so its model key would never be used.`;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* `env` for a run's model routes when the run holds its own key: every property of `env` but each model key (the runner's
|
|
114
|
+
* own and any saved one never go), with the run's key read at each request (`held.key()`) in each variable it fills
|
|
115
|
+
* (runKeyNames). Those are getters, never enumerable: a spread of the result, a spawn given it or a tool's env made from
|
|
116
|
+
* it carries none of them. No ChatGPT sign-in either (a symbol, not copied): every model call tied to the run carries
|
|
117
|
+
* the run's key.
|
|
118
|
+
*/
|
|
119
|
+
export function withRunModelKey(env, held) {
|
|
120
|
+
const out = {};
|
|
121
|
+
for (const name of Object.getOwnPropertyNames(env)) {
|
|
122
|
+
if (!MODEL_KEY_NAMES.has(name))
|
|
123
|
+
Object.defineProperty(out, name, Object.getOwnPropertyDescriptor(env, name));
|
|
124
|
+
}
|
|
125
|
+
for (const name of runKeyNames(env, held.origin))
|
|
126
|
+
Object.defineProperty(out, name, { get: () => held.key(), enumerable: false, configurable: false });
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* `env` (a claim's model env on the server's keys, withModelKeys) for a run that holds no key of its own yet: each
|
|
131
|
+
* variable a run's key fills (runKeyNames) reads the run's key once a message hands one, and the server's value until
|
|
132
|
+
* then, at each request; every other variable as it is. So a run that started on the server's key spends a message's
|
|
133
|
+
* key from the request after that message on. Getters, never enumerable, as withRunModelKey's.
|
|
134
|
+
*/
|
|
135
|
+
export function withRunModelKeyLater(env, held) {
|
|
136
|
+
const names = new Set(runKeyNames(env, held.origin));
|
|
137
|
+
const out = {};
|
|
138
|
+
for (const name of Object.getOwnPropertyNames(env)) {
|
|
139
|
+
if (!names.has(name))
|
|
140
|
+
Object.defineProperty(out, name, Object.getOwnPropertyDescriptor(env, name));
|
|
141
|
+
}
|
|
142
|
+
for (const name of names) {
|
|
143
|
+
const server = env[name];
|
|
144
|
+
Object.defineProperty(out, name, { get: () => held.key() ?? server, enumerable: false, configurable: false });
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
@@ -5,7 +5,7 @@ import { withLearning } from "./learning-run.js";
|
|
|
5
5
|
import { runLearningEnd } from "./store-reads/learning.js";
|
|
6
6
|
import { heldNumber, redacted } from "./key-refusal.js";
|
|
7
7
|
import { runCutValues, runErrorWordsOf, underCut } from "./run-cut.js";
|
|
8
|
-
import { answersOf, asksOf, shownOf, withApprovalRows, withAsks, withBudgetRows, withOverCap } from "./run-view.js";
|
|
8
|
+
import { answersOf, asksOf, shownOf, stopAsked, withApprovalRows, withAsks, withBudgetRows, withOverCap } from "./run-view.js";
|
|
9
9
|
import { launchOf } from "./handed-values.js";
|
|
10
10
|
import { capNowOf } from "./runner/journal-kinds.js";
|
|
11
11
|
import { journalRecords } from "./runner/journal-reader.js";
|
|
@@ -34,7 +34,6 @@ export async function servedTimelineRows(deps, store, runId, context, calls = fa
|
|
|
34
34
|
const run = await snapshot.runs.get(runId);
|
|
35
35
|
const ended = run ? FINAL_STATES.includes(run.state) : false;
|
|
36
36
|
const records = await journalRecords(snapshot.readJournal(runId), context);
|
|
37
|
-
const final = run?.state === "stopped" || run?.state === "failed" ? run.state : undefined;
|
|
38
37
|
// A question the agent asked (ask_person) and waits on: its waiting row after the call's result (run-view.ts withAsks), as
|
|
39
38
|
// the run's view carries it and main's served Timeline did, so the console's "The agent asks" box reads that question,
|
|
40
39
|
// never an earlier wait's words.
|
|
@@ -44,6 +43,9 @@ export async function servedTimelineRows(deps, store, runId, context, calls = fa
|
|
|
44
43
|
// Over is not final: an agentic run a person stopped is final in the store but reads running in its view (readRun: its
|
|
45
44
|
// turn is over, the run can go on), and its usage row says what it has cost so far there, so here too.
|
|
46
45
|
const view = await readRun(snapshot, runId, context);
|
|
46
|
+
// And every call still waiting once a stop is asked and not yet taken, as the run's view reads it (stopAsked).
|
|
47
|
+
const final = run?.state === "stopped" || run?.state === "failed" ? run.state
|
|
48
|
+
: stopAsked(view, run, await snapshot.commands(runId, 0)) ? "stopped" : undefined;
|
|
47
49
|
const options = { redact, settled: ended, ended: view ? view.state !== "running" : false, ...(calls ? { calls: { result: CALL_RESULT_CHARS, redact: (text) => redacted(text, values, CALL_RESULT_CHARS), held: (value) => heldNumber(value, values) } } : {}) };
|
|
48
50
|
const timeline = await wholeAnswers(snapshot, runId, context, await runTimeline(snapshot, runId, context, options), options, wholeAnswerFor(values));
|
|
49
51
|
// A run whose booked spend passed its cap says so, by how much, after its usage row (run-view.ts withOverCap, as main's
|
|
@@ -58,7 +60,7 @@ export async function servedTimelineRows(deps, store, runId, context, calls = fa
|
|
|
58
60
|
const receipts = await decisionsOverStore(snapshot, runId, context).catch(() => null);
|
|
59
61
|
const decisionShown = { redact: (text) => redacted(text, values), hold: 6 * values.reduce((most, value) => Math.max(most, value.length), 0) + 16 };
|
|
60
62
|
const own = receipts === null || receipts.length ? withDecisions(rows, receipts, decisionShown, { ended }) : rows;
|
|
61
|
-
// The run's learning end, once its learning
|
|
63
|
+
// The run's learning end, once its learning merged or dropped (runLearningEnd).
|
|
62
64
|
const end = await runLearningEnd(snapshot, runId);
|
|
63
65
|
// Each trigger the rows name, read once for this read: its name now, or none for one gone.
|
|
64
66
|
const names = new Map();
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
|
+
import { type ServedTimelineDeps } from "./run-timeline-served.js";
|
|
3
|
+
import { type ApprovalAnswer } from "./run-view.js";
|
|
4
|
+
import type { Store } from "./store/store.js";
|
|
5
|
+
import { type EntryLike, type TimelineEvent } from "./timeline/index.js";
|
|
6
|
+
/** The most spans one read serves: the run's first, in the order they started. `dropped` counts the rest. */
|
|
7
|
+
export declare const TRACE_SPANS_MAX = 2000;
|
|
8
|
+
/** `reasoning`: the thinking tokens among `output`, where the provider reports them. */
|
|
9
|
+
export type TraceTokens = {
|
|
10
|
+
input: number;
|
|
11
|
+
cache_read: number;
|
|
12
|
+
cache_write: number;
|
|
13
|
+
output: number;
|
|
14
|
+
reasoning?: number;
|
|
15
|
+
};
|
|
16
|
+
/** How a span ended. `waiting`: a tool call held for its owner's approval, which has not run. `running`: a tool call
|
|
17
|
+
* with no result yet. `refused`: a call refused before it ran (a deny). `interrupted`: a request or a call cut before
|
|
18
|
+
* its end, or a call whose approval was withdrawn with its run. A model request is a span once it answered, so it is
|
|
19
|
+
* never waiting or running. */
|
|
20
|
+
export type TraceStatus = "ok" | "failed" | "refused" | "interrupted" | "waiting" | "running";
|
|
21
|
+
export type TraceSpan = {
|
|
22
|
+
/** The span's id in this trace: stable across reads of the run. */
|
|
23
|
+
id: string;
|
|
24
|
+
kind: "model" | "tool";
|
|
25
|
+
/** The span this one ran under: a tool call's, the model request that called it, or the call it nested in; a subagent's
|
|
26
|
+
* model request's, the call that started the subagent. Null at the top. */
|
|
27
|
+
parent_id: string | null;
|
|
28
|
+
/** A model request's model, as its answer names it (a decision's, the model its provider answered with, else the
|
|
29
|
+
* provider); a tool call's tool. */
|
|
30
|
+
name: string;
|
|
31
|
+
/** The subagent the span ran in, as the Timeline labels it; a workflow decision's node. */
|
|
32
|
+
agent_label: string | null;
|
|
33
|
+
started_at: string;
|
|
34
|
+
/** Null while a tool call runs or waits, and for a span whose end the record does not keep (a request with no
|
|
35
|
+
* duration, a call cut with no result). */
|
|
36
|
+
ended_at: string | null;
|
|
37
|
+
status: TraceStatus;
|
|
38
|
+
/** A model request's stop reason, as pi names it (`stop`, `toolUse`, `length`, `error`, `aborted`). Null on a tool call. */
|
|
39
|
+
stop_reason: string | null;
|
|
40
|
+
/** A model request's tokens: `input` not read from cache, `cache_read`, `cache_write`, `output`. A decision's receipt
|
|
41
|
+
* keeps its input whole, so all of it is `input`. Null when the answer reported none (a cut request), and on a tool call. */
|
|
42
|
+
tokens: TraceTokens | null;
|
|
43
|
+
/** A model request's cost; a tool call's, the sum of the charges booked under it. Null when it is not known (a cut
|
|
44
|
+
* request, a charge of an unknown amount, a request whose run's cost is its booking's: `model_requests`), and on a
|
|
45
|
+
* call nothing was charged under (`charged`). */
|
|
46
|
+
usd: number | null;
|
|
47
|
+
/** Whether anything was charged under a tool call (a browser session's time, a paid tool's fee): `usd` is their sum.
|
|
48
|
+
* False on a model request. */
|
|
49
|
+
charged: boolean;
|
|
50
|
+
/** A workflow decision's request (a judge's, a route's, a verify's), which has a cost of its own whatever
|
|
51
|
+
* `model_requests` says of the run's other requests. False on every other span. */
|
|
52
|
+
decision: boolean;
|
|
53
|
+
/** A tool call whose tool has no price set: it ran outside the run's cost. */
|
|
54
|
+
not_metered: boolean;
|
|
55
|
+
/** The tool call's id, as its Timeline rows carry it. Null on a model request. */
|
|
56
|
+
tool_use_id: string | null;
|
|
57
|
+
input_preview: string | null;
|
|
58
|
+
result_preview: string | null;
|
|
59
|
+
result_size_bytes: number | null;
|
|
60
|
+
};
|
|
61
|
+
export type RunTrace = {
|
|
62
|
+
run_id: string;
|
|
63
|
+
/** What the run's record keeps of its model requests. `priced`: each is a span with its tokens and its cost.
|
|
64
|
+
* `tokens_only`: a workflow run. Each model node's request is a span with its tokens and no cost (the run's cost is
|
|
65
|
+
* its booking's); each decision is a span with its own cost. `not_recorded`: the harness's record keeps no request,
|
|
66
|
+
* so the spans are its tool calls alone. */
|
|
67
|
+
model_requests: "priced" | "tokens_only" | "not_recorded";
|
|
68
|
+
spans: TraceSpan[];
|
|
69
|
+
/** Spans left out past TRACE_SPANS_MAX. */
|
|
70
|
+
dropped: number;
|
|
71
|
+
};
|
|
72
|
+
/** What came of a call's approval, by the call's id: `decision` absent while it still waits; `answered_at`, when it was
|
|
73
|
+
* answered or withdrawn, where the journal says. */
|
|
74
|
+
export type TraceApprovals = ReadonlyMap<string, {
|
|
75
|
+
decision?: ApprovalAnswer["decision"];
|
|
76
|
+
answered_at?: string;
|
|
77
|
+
}>;
|
|
78
|
+
/** The approvals of a run's calls, from its journal's asks and answers (run-view.ts asksOf, answersOf), as its served
|
|
79
|
+
* Timeline reads them. `final`: the run's state where it is stopped or failed, whose end its journal may not hold. */
|
|
80
|
+
export declare function traceApprovals(entries: readonly {
|
|
81
|
+
kind?: string;
|
|
82
|
+
data?: unknown;
|
|
83
|
+
}[], final?: "stopped" | "failed"): TraceApprovals;
|
|
84
|
+
/** The spans of a run whose served Timeline rows are `rows` and whose journal entries are `entries` (as the store keeps
|
|
85
|
+
* them: runEntries). `redact`: the run's cut, for the one text taken from an entry (a model's name); every other word is
|
|
86
|
+
* a row's, cut already. `approvals`: what came of each call that asked for one (traceApprovals): how such a call ended
|
|
87
|
+
* is read from there, never from its rows, which the Timeline rewords while it waits. `decisions`: a workflow run's
|
|
88
|
+
* decision receipts (store-reads/decisions.ts), each a model request of its own: a judge's, a route's, a verify's. */
|
|
89
|
+
export declare function traceSpans(rows: readonly TimelineEvent[], entries: readonly EntryLike[], options?: {
|
|
90
|
+
redact?: (text: string) => string;
|
|
91
|
+
approvals?: TraceApprovals;
|
|
92
|
+
decisions?: readonly Record<string, unknown>[];
|
|
93
|
+
}): Pick<RunTrace, "model_requests" | "spans" | "dropped">;
|
|
94
|
+
/** Run `runId`'s trace as served: its spans over its served Timeline rows and its journal, the model's name through the
|
|
95
|
+
* run's cut. A run withheld (its sign-in can't be read back here) is refused (403), as its graph and its files are:
|
|
96
|
+
* none of its words is served, and an empty trace would read as a run that did nothing. */
|
|
97
|
+
export declare function servedRunTrace(deps: ServedTimelineDeps, store: Store, runId: string, context: Context): Promise<RunTrace>;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { ApiError } from "./errors.js";
|
|
2
|
+
import { redacted } from "./key-refusal.js";
|
|
3
|
+
import { runCutValues } from "./run-cut.js";
|
|
4
|
+
import { servedTimelineRows } from "./run-timeline-served.js";
|
|
5
|
+
import { answersOf, asksOf, WITHHELD_SIGN_IN } from "./run-view.js";
|
|
6
|
+
import { costIsBooked } from "./runner/metrics.js";
|
|
7
|
+
import { decisionsOverStore } from "./store-reads/decisions.js";
|
|
8
|
+
import { isCliRecord, piShaped, runEntries } from "./store-reads/journal.js";
|
|
9
|
+
import { answeredRequests } from "./timeline/index.js";
|
|
10
|
+
/** The most spans one read serves: the run's first, in the order they started. `dropped` counts the rest. */
|
|
11
|
+
export const TRACE_SPANS_MAX = 2_000;
|
|
12
|
+
const obj = (value) => (typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined);
|
|
13
|
+
const finite = (value) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
|
|
14
|
+
const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
15
|
+
/** A time as the rows write theirs; undefined for one no Date holds. */
|
|
16
|
+
const iso = (ms) => (Math.abs(ms) <= 8.64e15 ? new Date(ms).toISOString() : undefined);
|
|
17
|
+
const STOP_REASONS = new Set(["stop", "length", "toolUse", "error", "aborted", "deferred", "pending"]);
|
|
18
|
+
/** An answer's tokens, by the usage row's rule (timeline tokensOf): all four known, and some input unless it failed. */
|
|
19
|
+
function tokensOf(usage, failed) {
|
|
20
|
+
const u = obj(usage);
|
|
21
|
+
const [input, output] = [count(u?.input), count(u?.output)];
|
|
22
|
+
const cacheRead = u?.cacheRead === undefined ? 0 : count(u.cacheRead);
|
|
23
|
+
const cacheWrite = u?.cacheWrite === undefined ? 0 : count(u.cacheWrite);
|
|
24
|
+
if (input === undefined || output === undefined || cacheRead === undefined || cacheWrite === undefined)
|
|
25
|
+
return null;
|
|
26
|
+
if (!(failed || input + cacheRead + cacheWrite > 0))
|
|
27
|
+
return null;
|
|
28
|
+
const reasoning = count(u?.reasoning);
|
|
29
|
+
return { input, cache_read: cacheRead, cache_write: cacheWrite, output, ...(reasoning !== undefined && reasoning <= output ? { reasoning } : {}) };
|
|
30
|
+
}
|
|
31
|
+
const keyOf = (conv, id) => `${conv ?? 0}:${id}`;
|
|
32
|
+
/** The approvals of a run's calls, from its journal's asks and answers (run-view.ts asksOf, answersOf), as its served
|
|
33
|
+
* Timeline reads them. `final`: the run's state where it is stopped or failed, whose end its journal may not hold. */
|
|
34
|
+
export function traceApprovals(entries, final) {
|
|
35
|
+
const answers = answersOf(entries, final ? { final } : {});
|
|
36
|
+
return new Map([...asksOf(entries).values()].map((ask) => {
|
|
37
|
+
const answer = answers[ask.id];
|
|
38
|
+
return [ask.call_id, answer ? { decision: answer.decision, ...(answer.answered_at ? { answered_at: answer.answered_at } : {}) } : {}];
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
/** The spans of a run whose served Timeline rows are `rows` and whose journal entries are `entries` (as the store keeps
|
|
42
|
+
* them: runEntries). `redact`: the run's cut, for the one text taken from an entry (a model's name); every other word is
|
|
43
|
+
* a row's, cut already. `approvals`: what came of each call that asked for one (traceApprovals): how such a call ended
|
|
44
|
+
* is read from there, never from its rows, which the Timeline rewords while it waits. `decisions`: a workflow run's
|
|
45
|
+
* decision receipts (store-reads/decisions.ts), each a model request of its own: a judge's, a route's, a verify's. */
|
|
46
|
+
export function traceSpans(rows, entries, options = {}) {
|
|
47
|
+
const said = (text) => (options.redact ? options.redact(text) : text);
|
|
48
|
+
const cli = isCliRecord(entries);
|
|
49
|
+
const booked = costIsBooked(entries, cli);
|
|
50
|
+
// A CLI harness's messages are no requests (its booking counts those, with no time): none is a span.
|
|
51
|
+
const requests = cli ? [] : answeredRequests(piShaped(entries));
|
|
52
|
+
// Each call's rows are its own conversation's (two conversations may each make a call of one id), so a call is known
|
|
53
|
+
// by both. The conversations that made a call of an id, in the order they did: a call named from another conversation
|
|
54
|
+
// (a subagent's rows name the call that started it) is the first of them that is not the namer's own.
|
|
55
|
+
const uses = rows.filter((row) => row.kind === "tool_use" && row.tool_use_id);
|
|
56
|
+
const convsOf = new Map();
|
|
57
|
+
for (const row of uses) {
|
|
58
|
+
const convs = convsOf.get(row.tool_use_id) ?? [];
|
|
59
|
+
if (!convs.includes(row.conversation_id ?? 0))
|
|
60
|
+
convsOf.set(row.tool_use_id, [...convs, row.conversation_id ?? 0]);
|
|
61
|
+
}
|
|
62
|
+
/** The span id of call `callId` as conversation `conv`'s rows name it: its own call of that id where `own`, else another's. */
|
|
63
|
+
const toolId = (callId, conv, own) => {
|
|
64
|
+
const convs = convsOf.get(callId) ?? [];
|
|
65
|
+
const of = own && convs.includes(conv) ? conv : convs.find((other) => other !== conv);
|
|
66
|
+
return of === undefined ? null : `t:${keyOf(of, callId)}`;
|
|
67
|
+
};
|
|
68
|
+
// The call that started each subagent conversation, and the label each conversation's rows carry. Every row of a
|
|
69
|
+
// subagent's conversation names the call that started it, its first row too; a conversation whose first row names
|
|
70
|
+
// none was started by no call (a call nested in one of its own names that call on its own rows alone).
|
|
71
|
+
const startedBy = new Map();
|
|
72
|
+
const labels = new Map();
|
|
73
|
+
const first = new Set();
|
|
74
|
+
for (const row of rows) {
|
|
75
|
+
const conv = row.conversation_id ?? 0;
|
|
76
|
+
if (row.agent_label && !labels.has(conv))
|
|
77
|
+
labels.set(conv, row.agent_label);
|
|
78
|
+
if (first.has(conv))
|
|
79
|
+
continue;
|
|
80
|
+
first.add(conv);
|
|
81
|
+
const started = row.parent_tool_use_id === undefined ? null : toolId(row.parent_tool_use_id, conv, false);
|
|
82
|
+
if (started)
|
|
83
|
+
startedBy.set(conv, started);
|
|
84
|
+
}
|
|
85
|
+
const spans = [];
|
|
86
|
+
const modelEnds = new Map();
|
|
87
|
+
for (const entry of requests) {
|
|
88
|
+
const message = obj(entry.model?.[0]);
|
|
89
|
+
const at = finite(message?.timestamp);
|
|
90
|
+
const started = at === undefined ? undefined : iso(at);
|
|
91
|
+
if (!message || at === undefined || started === undefined || entry.id === undefined)
|
|
92
|
+
continue;
|
|
93
|
+
const conv = entry.conversationId ?? 0;
|
|
94
|
+
const took = count(message.durationMs);
|
|
95
|
+
const ended = took === undefined ? undefined : iso(at + took);
|
|
96
|
+
const failed = message.stopReason === "error";
|
|
97
|
+
const aborted = message.stopReason === "aborted";
|
|
98
|
+
const total = finite(obj(obj(message.usage)?.cost)?.total);
|
|
99
|
+
modelEnds.set(keyOf(conv, entry.id), ended === undefined ? undefined : at + took);
|
|
100
|
+
spans.push({
|
|
101
|
+
at, id: `m:${keyOf(conv, entry.id)}`, kind: "model", parent_id: startedBy.get(conv) ?? null,
|
|
102
|
+
name: said(typeof message.model === "string" && message.model ? message.model : "model"), agent_label: labels.get(conv) ?? null,
|
|
103
|
+
started_at: started, ended_at: ended ?? null, status: failed ? "failed" : aborted ? "interrupted" : "ok",
|
|
104
|
+
stop_reason: typeof message.stopReason === "string" && STOP_REASONS.has(message.stopReason) ? message.stopReason : null,
|
|
105
|
+
// A request cut before its end reported no final usage and no cost (the usage row counts it unknown).
|
|
106
|
+
tokens: aborted ? null : tokensOf(message.usage, failed),
|
|
107
|
+
usd: booked || aborted || total === undefined || total < 0 ? null : total, decision: false,
|
|
108
|
+
charged: false, not_metered: false, tool_use_id: null, input_preview: null, result_preview: null, result_size_bytes: null,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
// A workflow's decisions: each receipt is one request to its decision model, written when it answered (`at`), with
|
|
112
|
+
// how long it took, its tokens and its own cost. Its node is its label, as its Timeline row's is.
|
|
113
|
+
(options.decisions ?? []).forEach((receipt, place) => {
|
|
114
|
+
const ended = typeof receipt.at === "string" ? Date.parse(receipt.at) : Number.NaN;
|
|
115
|
+
if (!Number.isFinite(ended))
|
|
116
|
+
return;
|
|
117
|
+
const took = count(receipt.latency_ms);
|
|
118
|
+
const at = took === undefined ? ended : ended - took;
|
|
119
|
+
const usage = obj(receipt.usage);
|
|
120
|
+
const [input, output] = [count(usage?.input_tokens), count(usage?.output_tokens)];
|
|
121
|
+
const cost = finite(receipt.cost_usd);
|
|
122
|
+
const named = typeof receipt.model === "string" && receipt.model ? receipt.model : typeof receipt.provider === "string" && receipt.provider ? receipt.provider : "decision";
|
|
123
|
+
spans.push({
|
|
124
|
+
at, id: `d:${String(receipt.id ?? place)}:${String(obj(receipt.request)?.index ?? 0)}`, kind: "model", parent_id: null,
|
|
125
|
+
name: said(named), agent_label: typeof receipt.node === "string" && receipt.node ? said(receipt.node) : null,
|
|
126
|
+
started_at: iso(at) ?? String(receipt.at), ended_at: took === undefined ? null : iso(ended) ?? null,
|
|
127
|
+
status: receipt.status === "failed" || (receipt.status === undefined && typeof receipt.error === "string" && receipt.error !== "") ? "failed" : receipt.status === "cancelled" ? "interrupted" : "ok",
|
|
128
|
+
stop_reason: null,
|
|
129
|
+
// A receipt keeps its input whole, with no split by cache.
|
|
130
|
+
tokens: input !== undefined && output !== undefined ? { input, cache_read: 0, cache_write: 0, output } : null,
|
|
131
|
+
usd: cost !== undefined && cost >= 0 ? cost : null, decision: true,
|
|
132
|
+
charged: false, not_metered: false, tool_use_id: null, input_preview: null, result_preview: null, result_size_bytes: null,
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
// How long each tool ran, where its result says (pi's monotonic clock): a pi call's row is dated by its request's start,
|
|
136
|
+
// so the row alone would count the model's writing as the tool's time. In order, one for each result of a call's id.
|
|
137
|
+
const ran = new Map();
|
|
138
|
+
for (const entry of entries) {
|
|
139
|
+
const message = entry.kind === "pi.tool-result" ? obj(entry.model?.[0]) : undefined;
|
|
140
|
+
if (!message || typeof message.toolCallId !== "string")
|
|
141
|
+
continue;
|
|
142
|
+
const key = keyOf(entry.conversationId, message.toolCallId);
|
|
143
|
+
ran.set(key, [...(ran.get(key) ?? []), count(message.durationMs)]);
|
|
144
|
+
}
|
|
145
|
+
// Each call's result rows, in order (a conversation that made two calls of one id has two), and what was charged under
|
|
146
|
+
// each: a charge is the call's it follows, so the second call of an id has its own.
|
|
147
|
+
const results = new Map();
|
|
148
|
+
const charges = new Map();
|
|
149
|
+
const chargeOf = (key) => {
|
|
150
|
+
let charge = charges.get(key);
|
|
151
|
+
if (!charge)
|
|
152
|
+
charges.set(key, (charge = { known: 0, unknown: false, charged: false, notMetered: false }));
|
|
153
|
+
return charge;
|
|
154
|
+
};
|
|
155
|
+
const called = new Set(uses.map((row) => keyOf(row.conversation_id, row.tool_use_id)));
|
|
156
|
+
/** How many calls of each id its conversation has made so far, as the rows are read in order. */
|
|
157
|
+
const sofar = new Map();
|
|
158
|
+
const occurrence = (key) => `${key}#${Math.max(0, (sofar.get(key) ?? 1) - 1)}`;
|
|
159
|
+
for (const row of rows) {
|
|
160
|
+
if (!row.tool_use_id)
|
|
161
|
+
continue;
|
|
162
|
+
// A row is its own conversation's call's; a charge written with no conversation of its own is the call's by its id.
|
|
163
|
+
const own = keyOf(row.conversation_id, row.tool_use_id);
|
|
164
|
+
const key = called.has(own) ? own : keyOf(convsOf.get(row.tool_use_id)?.[0] ?? row.conversation_id, row.tool_use_id);
|
|
165
|
+
if (row.kind === "tool_use")
|
|
166
|
+
sofar.set(key, (sofar.get(key) ?? 0) + 1);
|
|
167
|
+
if (row.kind === "tool_result")
|
|
168
|
+
results.set(key, [...(results.get(key) ?? []), row]);
|
|
169
|
+
// A browser call's session time is folded into its own row; a paid tool's fee is a row of its own after the result.
|
|
170
|
+
else if ((row.kind === "tool_use" || row.kind === "phase") && row.usage) {
|
|
171
|
+
const charge = chargeOf(occurrence(key));
|
|
172
|
+
charge.charged = true;
|
|
173
|
+
if (row.usage.usd === null)
|
|
174
|
+
charge.unknown = true;
|
|
175
|
+
else
|
|
176
|
+
charge.known += row.usage.usd;
|
|
177
|
+
}
|
|
178
|
+
else if (row.kind === "phase" && row.tool_name && !row.path && (row.summary ?? "").startsWith("Not metered:"))
|
|
179
|
+
chargeOf(occurrence(key)).notMetered = true;
|
|
180
|
+
}
|
|
181
|
+
const made = new Map();
|
|
182
|
+
for (const use of uses) {
|
|
183
|
+
const conv = use.conversation_id ?? 0;
|
|
184
|
+
const key = keyOf(conv, use.tool_use_id);
|
|
185
|
+
// The nth call of an id in its conversation takes that conversation's nth result of it, and is a span of its own.
|
|
186
|
+
const nth = made.get(key) ?? 0;
|
|
187
|
+
made.set(key, nth + 1);
|
|
188
|
+
const result = results.get(key)?.[nth];
|
|
189
|
+
const shown = Date.parse(use.timestamp);
|
|
190
|
+
const approval = nth === 0 ? options.approvals?.get(use.tool_use_id) : undefined;
|
|
191
|
+
// A result the renderer wrote for a call that never got one (timeline interrupt): the call was cut, and neither that
|
|
192
|
+
// row's status nor its time is the call's. One the run's end closed (no status) was cut too, at its own time.
|
|
193
|
+
const cutShort = result !== undefined && result.id.includes(":interrupted:");
|
|
194
|
+
const answered = approval?.answered_at ? Date.parse(approval.answered_at) : Number.NaN;
|
|
195
|
+
// How it ended, and when, where the record says: a call that asked for approval by what came of that (it waits, it
|
|
196
|
+
// was withdrawn with its run and never ran, it was denied), any other by its result.
|
|
197
|
+
const [status, done] = approval && approval.decision === undefined ? ["waiting", undefined]
|
|
198
|
+
: approval && (approval.decision === "canceled" || approval.decision === "withdrawn") ? ["interrupted", answered]
|
|
199
|
+
: approval?.decision === "deny" ? ["refused", Number.isFinite(answered) ? answered : result ? Date.parse(result.timestamp) : undefined]
|
|
200
|
+
: !result ? ["running", undefined]
|
|
201
|
+
: cutShort ? ["interrupted", undefined]
|
|
202
|
+
: result.refused ? ["refused", Date.parse(result.timestamp)]
|
|
203
|
+
: result.tool_status === "failed" ? ["failed", Date.parse(result.timestamp)]
|
|
204
|
+
: result.tool_status === "success" ? ["ok", Date.parse(result.timestamp)]
|
|
205
|
+
: ["interrupted", Date.parse(result.timestamp)];
|
|
206
|
+
const over = done !== undefined && Number.isFinite(done);
|
|
207
|
+
const model = use.round === undefined ? undefined : keyOf(conv, use.round);
|
|
208
|
+
const asked = model !== undefined && modelEnds.has(model);
|
|
209
|
+
// How long it ran is its result's to say, for a call that ran to a result of its own.
|
|
210
|
+
const took = status === "ok" || status === "failed" ? ran.get(key)?.[nth] : undefined;
|
|
211
|
+
const after = asked ? modelEnds.get(model) : undefined;
|
|
212
|
+
// Where the result keeps how long the tool ran, it started that long before it ended; else when its request ended,
|
|
213
|
+
// where that is known; else when its row says. Never after its own end.
|
|
214
|
+
const from = over && took !== undefined ? done - took : after !== undefined ? Math.max(shown, after) : shown;
|
|
215
|
+
const at = over ? Math.min(from, done) : from;
|
|
216
|
+
const charge = charges.get(`${key}#${nth}`);
|
|
217
|
+
const parent = asked ? `m:${model}` : use.parent_tool_use_id !== undefined ? toolId(use.parent_tool_use_id, conv, true) : null;
|
|
218
|
+
spans.push({
|
|
219
|
+
at, id: nth === 0 ? `t:${key}` : `t:${key}#${nth + 1}`, kind: "tool", parent_id: parent, name: use.tool_name ?? "tool", agent_label: use.agent_label ?? null,
|
|
220
|
+
started_at: iso(at) ?? use.timestamp, ended_at: over ? iso(done) ?? null : null, status,
|
|
221
|
+
stop_reason: null, tokens: null,
|
|
222
|
+
usd: charge?.charged ? (charge.unknown ? null : Math.round(charge.known * 1e12) / 1e12) : null,
|
|
223
|
+
decision: false, charged: charge?.charged ?? false, not_metered: charge?.notMetered ?? false,
|
|
224
|
+
tool_use_id: use.tool_use_id, input_preview: use.tool_input_preview ?? null,
|
|
225
|
+
// A call that never ran has no result of its own: what its rows say of it is the Timeline's words, not its output.
|
|
226
|
+
result_preview: status === "waiting" || cutShort || (approval && status === "interrupted") ? null : result?.tool_result_preview ?? null,
|
|
227
|
+
result_size_bytes: status === "waiting" || cutShort || (approval && status === "interrupted") ? null : result?.tool_result_size_bytes ?? null,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
// In the order they started; a request before the calls it made at the same instant.
|
|
231
|
+
spans.sort((a, b) => a.at - b.at || (a.kind === b.kind ? 0 : a.kind === "model" ? -1 : 1) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
232
|
+
const kept = spans.slice(0, TRACE_SPANS_MAX).map(({ at: _at, ...span }) => span);
|
|
233
|
+
return { model_requests: cli ? "not_recorded" : booked ? "tokens_only" : "priced", spans: kept, dropped: spans.length - kept.length };
|
|
234
|
+
}
|
|
235
|
+
/** Run `runId`'s trace as served: its spans over its served Timeline rows and its journal, the model's name through the
|
|
236
|
+
* run's cut. A run withheld (its sign-in can't be read back here) is refused (403), as its graph and its files are:
|
|
237
|
+
* none of its words is served, and an empty trace would read as a run that did nothing. */
|
|
238
|
+
export async function servedRunTrace(deps, store, runId, context) {
|
|
239
|
+
if ((await runCutValues(deps, store, runId)) === "unreadable")
|
|
240
|
+
throw new ApiError("forbidden", WITHHELD_SIGN_IN);
|
|
241
|
+
const rows = await servedTimelineRows(deps, store, runId, context);
|
|
242
|
+
// The cut after the rows: it only grows, so it holds every value the rows were cut of.
|
|
243
|
+
const cut = await runCutValues(deps, store, runId);
|
|
244
|
+
if (cut === "unreadable")
|
|
245
|
+
throw new ApiError("forbidden", WITHHELD_SIGN_IN);
|
|
246
|
+
const run = await store.runs.get(runId);
|
|
247
|
+
const entries = await runEntries(store, runId, context);
|
|
248
|
+
const approvals = traceApprovals(entries, run?.state === "stopped" || run?.state === "failed" ? run.state : undefined);
|
|
249
|
+
// A workflow's decision receipts; a run that made none has none. Receipts that can't be read leave their spans out
|
|
250
|
+
// (the run's usage row says its cost is unknown then: decision-rows.ts withDecisions).
|
|
251
|
+
const decisions = await decisionsOverStore(store, runId, context).catch(() => []);
|
|
252
|
+
return { run_id: runId, ...traceSpans(rows, entries, { redact: (text) => redacted(text, cut.values), approvals, decisions }) };
|
|
253
|
+
}
|
package/dist/run-view.d.ts
CHANGED
|
@@ -96,6 +96,21 @@ type JournalEntry = {
|
|
|
96
96
|
* so the run waits on it no more (the file path's `resolved` once its process acted). The card's id and call id are both
|
|
97
97
|
* the call's id, and its arguments are kept as JSON (shown cut and redacted by the view), as the file path kept them. */
|
|
98
98
|
export declare function asksOf(entries: readonly JournalEntry[]): Map<string, Approval>;
|
|
99
|
+
/** Whether a person's stop of a run stands asked and not yet taken: an agentic run (readRun's kind) still reading running,
|
|
100
|
+
* with a stop command its runner has neither taken nor refused. The runner cuts the turn first and takes the stop row in
|
|
101
|
+
* the commit that ends the run stopped, so between the two the run is stopped all the same: its view says so (stopped
|
|
102
|
+
* pending) and every call still waiting reads withdrawn (answersOf `final`), as the stop's answer endpoint already says
|
|
103
|
+
* (runs-over-store endBefore: an answer after the stop is 409 withdrawn). */
|
|
104
|
+
export declare function stopAsked(view: {
|
|
105
|
+
kind?: string;
|
|
106
|
+
state?: string;
|
|
107
|
+
} | null | undefined, run: {
|
|
108
|
+
importedFrom: unknown;
|
|
109
|
+
} | null | undefined, commands: readonly {
|
|
110
|
+
kind: string;
|
|
111
|
+
takenAt: number | null;
|
|
112
|
+
refused: string | null;
|
|
113
|
+
}[]): boolean;
|
|
99
114
|
/** The answers a run got to its asks, from its journal's `agentrun.answer` entries, by the call's id (the key the moment
|
|
100
115
|
* and the pending views read as run.meta.approvals): a person's allow or deny with any note, or a withdrawal taken when
|
|
101
116
|
* the run was stopped or cancelled while the call waited. The first answer for a call stands, but for a stop's
|
package/dist/run-view.js
CHANGED
|
@@ -148,6 +148,15 @@ export function asksOf(entries) {
|
|
|
148
148
|
}
|
|
149
149
|
return map;
|
|
150
150
|
}
|
|
151
|
+
/** Whether a person's stop of a run stands asked and not yet taken: an agentic run (readRun's kind) still reading running,
|
|
152
|
+
* with a stop command its runner has neither taken nor refused. The runner cuts the turn first and takes the stop row in
|
|
153
|
+
* the commit that ends the run stopped, so between the two the run is stopped all the same: its view says so (stopped
|
|
154
|
+
* pending) and every call still waiting reads withdrawn (answersOf `final`), as the stop's answer endpoint already says
|
|
155
|
+
* (runs-over-store endBefore: an answer after the stop is 409 withdrawn). */
|
|
156
|
+
export function stopAsked(view, run, commands) {
|
|
157
|
+
return view?.state === "running" && view.kind === "agentic" && run?.importedFrom === null &&
|
|
158
|
+
commands.some((command) => command.kind === "stop" && command.takenAt === null && command.refused === null);
|
|
159
|
+
}
|
|
151
160
|
/** The answers a run got to its asks, from its journal's `agentrun.answer` entries, by the call's id (the key the moment
|
|
152
161
|
* and the pending views read as run.meta.approvals): a person's allow or deny with any note, or a withdrawal taken when
|
|
153
162
|
* the run was stopped or cancelled while the call waited. The first answer for a call stands, but for a stop's
|
package/dist/runnable.js
CHANGED
|
@@ -79,8 +79,9 @@ export async function blockersOf(env, revision, settings = {}, { capped = false,
|
|
|
79
79
|
};
|
|
80
80
|
const harness = revision.harness ?? DEFAULT_HARNESS;
|
|
81
81
|
const offer = (offers ?? (await harnessOffers(env))).find((h) => h.id === harness);
|
|
82
|
+
// One the table hides (HarnessEntry.hidden: Goose before its owner installs it) has no offer: its entry says why.
|
|
82
83
|
if (!offer?.available)
|
|
83
|
-
out.push({ field: "definition.harness", reason: NOT_SET_UP, message: offer?.reason ?? `This server does not run ${harness}.`, host: true, harness });
|
|
84
|
+
out.push({ field: "definition.harness", reason: NOT_SET_UP, message: offer?.reason ?? harnessOf(env, harness)?.hidden?.(env) ?? `This server does not run ${harness}.`, host: true, harness });
|
|
84
85
|
const { place } = revision;
|
|
85
86
|
// A workflow's model and call nodes run on the runner here; in a box they do not run yet. Its fix names the runner: an
|
|
86
87
|
// edit that leaves the place out keeps the agent's (agents-store.ts), so removing the field would change nothing.
|