@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.59
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 +376 -0
- package/README.md +393 -118
- package/dist/acp-package.d.ts +5 -1
- package/dist/acp-package.js +19 -2
- package/dist/adapters.d.ts +23 -2
- package/dist/adapters.js +106 -33
- package/dist/agents-store.js +1 -1
- package/dist/answer-text.d.ts +3 -0
- package/dist/answer-text.js +22 -0
- package/dist/api-only.d.ts +2 -4
- package/dist/api-only.js +2 -4
- package/dist/attach-conformance.js +5 -4
- package/dist/box-paths.d.ts +7 -5
- package/dist/box-paths.js +12 -8
- package/dist/browser-computer.d.ts +3 -8
- package/dist/browser-computer.js +12 -35
- package/dist/browser-cost.js +94 -20
- package/dist/capacity.d.ts +1 -1
- package/dist/capacity.js +3 -3
- package/dist/chatgpt-plan.d.ts +5 -0
- package/dist/chatgpt-plan.js +25 -11
- package/dist/claude-login-token.d.ts +121 -0
- package/dist/claude-login-token.js +797 -0
- package/dist/claude-login.d.ts +119 -34
- package/dist/claude-login.js +551 -79
- package/dist/claude-sign-in.d.ts +3 -0
- package/dist/claude-sign-in.js +10 -1
- package/dist/cli.js +325 -328
- package/dist/composio-made.d.ts +1 -6
- package/dist/composio-made.js +1 -6
- package/dist/composio-owners.d.ts +26 -0
- package/dist/composio-owners.js +36 -0
- package/dist/composio-preset.d.ts +56 -23
- package/dist/composio-preset.js +173 -77
- package/dist/composio-triggers.d.ts +4 -4
- package/dist/composio-triggers.js +6 -7
- package/dist/compute-cost.js +11 -2
- package/dist/computer-attach.d.ts +40 -19
- package/dist/computer-attach.js +326 -62
- package/dist/computer-held-routes.d.ts +1 -1
- package/dist/computer-held-routes.js +9 -4
- package/dist/computer-keys.d.ts +11 -1
- package/dist/computer-keys.js +26 -1
- package/dist/computer-record.js +3 -1
- package/dist/computer-view.d.ts +5 -3
- package/dist/computer-view.js +10 -6
- package/dist/computer-viewer.js +36 -7
- package/dist/computers.d.ts +12 -11
- package/dist/computers.js +11 -8
- package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
- package/dist/console/assets/backend-BztxEAvb.js +166 -0
- package/dist/console/assets/index-LwNL4L9q.js +619 -0
- package/dist/console/assets/share-L84tlUDW.js +6 -0
- package/dist/console/assets/styles-CaRKlHke.js +291 -0
- package/dist/console/assets/styles-DQo8rzY-.css +1 -0
- package/dist/console/index.html +4 -3
- package/dist/console/share.html +17 -0
- package/dist/decisions.d.ts +17 -7
- package/dist/decisions.js +41 -15
- package/dist/dial-relay.d.ts +25 -4
- package/dist/dial-relay.js +139 -5
- package/dist/docker-daemon.js +4 -5
- package/dist/docker-host-addresses.js +29 -11
- package/dist/email/account.d.ts +6 -0
- package/dist/email/account.js +6 -0
- package/dist/email/authentication.d.ts +21 -0
- package/dist/email/authentication.js +106 -0
- package/dist/email/email-faux.d.ts +11 -2
- package/dist/email/email-faux.js +21 -5
- package/dist/email/mail.d.ts +25 -0
- package/dist/email/mail.js +58 -2
- package/dist/email/names.js +2 -2
- package/dist/email/tools.d.ts +9 -4
- package/dist/email/tools.js +95 -13
- package/dist/env-switch.d.ts +13 -5
- package/dist/env-switch.js +24 -6
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +2 -0
- package/dist/fal-price.d.ts +12 -4
- package/dist/fal-price.js +110 -26
- package/dist/faux-computers.js +1 -1
- package/dist/filed-answer.d.ts +2 -2
- package/dist/filed-answer.js +2 -2
- package/dist/graph-served.d.ts +10 -5
- package/dist/graph-served.js +40 -10
- package/dist/handed-values.js +1 -2
- package/dist/harness-check.d.ts +2 -1
- package/dist/harness-check.js +45 -12
- package/dist/harness-keys.js +9 -6
- package/dist/harness-opencode/facts.js +2 -0
- package/dist/harness-recipe-entry.d.ts +9 -3
- package/dist/harness-recipe-entry.js +18 -9
- package/dist/harness-recipe.d.ts +21 -0
- package/dist/harness-recipe.js +25 -3
- package/dist/harness-table.d.ts +8 -0
- package/dist/harness-table.js +17 -6
- package/dist/helper-env.d.ts +4 -1
- package/dist/helper-env.js +4 -1
- package/dist/host-check.d.ts +2 -3
- package/dist/host-check.js +13 -7
- package/dist/hosted-search.js +1 -1
- package/dist/import.d.ts +11 -8
- package/dist/import.js +437 -186
- package/dist/key-refusal.d.ts +9 -2
- package/dist/key-refusal.js +86 -32
- package/dist/learn/audit.d.ts +8 -5
- package/dist/learn/audit.js +15 -7
- package/dist/learn/compile.d.ts +5 -2
- package/dist/learn/compile.js +45 -21
- package/dist/learn/field-check.d.ts +111 -0
- package/dist/learn/field-check.js +174 -0
- package/dist/learn/ledger.d.ts +173 -0
- package/dist/learn/ledger.js +225 -0
- package/dist/learn/promote.d.ts +82 -39
- package/dist/learn/promote.js +61 -66
- package/dist/learn/secrets.d.ts +4 -0
- package/dist/learn/secrets.js +12 -0
- package/dist/learned-nodes.d.ts +8 -5
- package/dist/learned-nodes.js +8 -5
- package/dist/learned-workflow.d.ts +2 -1
- package/dist/learned-workflow.js +13 -10
- package/dist/learning-cost.d.ts +40 -21
- package/dist/learning-cost.js +30 -21
- package/dist/learning-setting.d.ts +6 -0
- package/dist/learning-setting.js +11 -1
- package/dist/listen-first.d.ts +5 -4
- package/dist/listen-first.js +4 -5
- package/dist/live-reach.d.ts +9 -0
- package/dist/live-reach.js +9 -0
- package/dist/mcp-api-only-origins.d.ts +23 -3
- package/dist/mcp-api-only-origins.js +57 -17
- package/dist/mcp-gateway.d.ts +16 -2
- package/dist/mcp-gateway.js +41 -3
- package/dist/mcp-oauth.d.ts +1 -1
- package/dist/mcp-oauth.js +3 -2
- package/dist/mcp-probe.d.ts +3 -0
- package/dist/mcp-probe.js +3 -0
- package/dist/mcp-secret-writes.d.ts +24 -2
- package/dist/mcp-secret-writes.js +30 -2
- package/dist/mcp-servers-store.d.ts +52 -14
- package/dist/mcp-servers-store.js +165 -61
- package/dist/mcp-sources.d.ts +1 -2
- package/dist/mcp-sources.js +1 -2
- package/dist/mcp-store.d.ts +5 -5
- package/dist/mcp-store.js +3 -3
- package/dist/mcp.js +1 -1
- package/dist/micro.d.ts +2 -0
- package/dist/micro.js +2 -0
- package/dist/model-gateway.d.ts +1 -1
- package/dist/model-gateway.js +20 -36
- package/dist/model.d.ts +5 -4
- package/dist/model.js +7 -6
- package/dist/monid.d.ts +14 -1
- package/dist/monid.js +103 -26
- package/dist/ollama-provider.d.ts +23 -9
- package/dist/ollama-provider.js +49 -20
- package/dist/openapi.js +234 -61
- package/dist/otel/genai.d.ts +83 -7
- package/dist/otel/genai.js +69 -9
- package/dist/otel/tracer.d.ts +42 -13
- package/dist/otel/tracer.js +241 -56
- package/dist/page.d.ts +7 -1
- package/dist/page.js +76 -22
- package/dist/paid-calls.d.ts +6 -4
- package/dist/paid-calls.js +15 -7
- package/dist/place-offers.d.ts +59 -34
- package/dist/place-offers.js +100 -58
- package/dist/place.d.ts +13 -14
- package/dist/place.js +56 -41
- package/dist/print.js +1 -1
- package/dist/provider.d.ts +5 -4
- package/dist/provider.js +26 -13
- package/dist/redact/match.d.ts +27 -9
- package/dist/redact/match.js +266 -57
- package/dist/run-census.d.ts +1 -1
- package/dist/run-census.js +4 -5
- package/dist/run-cut.js +4 -5
- package/dist/run-export-store.d.ts +15 -0
- package/dist/run-export-store.js +30 -0
- package/dist/run-export.d.ts +139 -0
- package/dist/run-export.js +379 -0
- package/dist/run-file-cut.d.ts +5 -0
- package/dist/run-file-cut.js +13 -0
- package/dist/run-launch.js +16 -3
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-model-key.d.ts +15 -6
- package/dist/run-model-key.js +30 -31
- package/dist/run-reads-over-store.js +4 -4
- package/dist/run-secrets.js +3 -5
- package/dist/run-timeline-served.js +3 -1
- package/dist/run-view.d.ts +1 -2
- package/dist/run-view.js +2 -1
- package/dist/runnable.js +2 -2
- package/dist/runner/adapter-loop.d.ts +35 -18
- package/dist/runner/adapter-loop.js +97 -63
- package/dist/runner/adapter-run-spec.d.ts +34 -14
- package/dist/runner/adapter-run-spec.js +120 -75
- package/dist/runner/adapters/pi.js +4 -2
- package/dist/runner/audit.d.ts +8 -5
- package/dist/runner/audit.js +37 -17
- package/dist/runner/beside.d.ts +9 -2
- package/dist/runner/beside.js +29 -13
- package/dist/runner/claim-secrets.d.ts +27 -18
- package/dist/runner/claim-secrets.js +61 -47
- package/dist/runner/cli-run-spec.d.ts +18 -0
- package/dist/runner/cli-run-spec.js +93 -46
- package/dist/runner/compare-end.d.ts +2 -1
- package/dist/runner/compare-end.js +25 -10
- package/dist/runner/conformance/harness.js +2 -3
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/harness-loops.js +3 -3
- package/dist/runner/held.d.ts +19 -4
- package/dist/runner/journal-kinds.d.ts +4 -1
- package/dist/runner/journal-kinds.js +22 -4
- package/dist/runner/learned-first.js +20 -4
- package/dist/runner/learning-end.d.ts +2 -8
- package/dist/runner/learning-end.js +11 -19
- package/dist/runner/live-ticker.js +7 -5
- package/dist/runner/loop-contract.d.ts +0 -2
- package/dist/runner/loop.d.ts +7 -0
- package/dist/runner/loop.js +1 -0
- package/dist/runner/main.d.ts +11 -6
- package/dist/runner/main.js +24 -18
- package/dist/runner/mcp-claim.js +24 -7
- package/dist/runner/mcp-run.d.ts +3 -6
- package/dist/runner/mcp-run.js +3 -4
- package/dist/runner/meta-tools.js +3 -2
- package/dist/runner/metrics.d.ts +7 -0
- package/dist/runner/metrics.js +19 -0
- package/dist/runner/model-route.d.ts +10 -7
- package/dist/runner/model-route.js +79 -15
- package/dist/runner/native-loop.js +10 -8
- package/dist/runner/presence.d.ts +11 -4
- package/dist/runner/presence.js +11 -6
- package/dist/runner/promotion.d.ts +25 -13
- package/dist/runner/promotion.js +125 -50
- package/dist/runner/redact.d.ts +3 -1
- package/dist/runner/redact.js +5 -3
- package/dist/runner/reflect-hook.js +1 -1
- package/dist/runner/responses-fetch.d.ts +36 -0
- package/dist/runner/responses-fetch.js +511 -0
- package/dist/runner/run-child-host.d.ts +38 -12
- package/dist/runner/run-child-host.js +231 -83
- package/dist/runner/run-child.js +11 -4
- package/dist/runner/runner-check.js +5 -1
- package/dist/runner/runner.d.ts +5 -3
- package/dist/runner/runner.js +14 -10
- package/dist/runner/save-slots.js +2 -1
- package/dist/runner/sdk-loop.js +8 -8
- package/dist/runner/spec-holds.d.ts +8 -1
- package/dist/runner/spec-holds.js +9 -4
- package/dist/runner/subagent.d.ts +11 -0
- package/dist/runner/subagent.js +17 -3
- package/dist/runner/workflow-calls.d.ts +9 -0
- package/dist/runner/workflow-calls.js +150 -0
- package/dist/runner/workflow-first.d.ts +138 -37
- package/dist/runner/workflow-first.js +230 -99
- package/dist/runner/workflow-spec.js +2 -2
- package/dist/runs-over-store.js +8 -7
- package/dist/save-once.d.ts +14 -0
- package/dist/save-once.js +31 -0
- package/dist/scrub-command.d.ts +34 -31
- package/dist/scrub-command.js +116 -147
- package/dist/sdk/runs.d.ts +6 -0
- package/dist/sdk/runs.js +89 -10
- package/dist/seal-key.js +4 -4
- package/dist/secret-cut.d.ts +3 -0
- package/dist/secret-cut.js +7 -1
- package/dist/secret-rules.d.ts +8 -1
- package/dist/secret-rules.js +482 -53
- package/dist/secrets.d.ts +51 -9
- package/dist/secrets.js +311 -21
- package/dist/server-keys.d.ts +4 -3
- package/dist/server-keys.js +4 -3
- package/dist/server-secrets-store.js +2 -4
- package/dist/server.d.ts +33 -10
- package/dist/server.js +454 -136
- package/dist/share-context.d.ts +22 -0
- package/dist/share-context.js +76 -0
- package/dist/shell-lex.d.ts +105 -0
- package/dist/shell-lex.js +646 -0
- package/dist/sign-ins-store.d.ts +5 -7
- package/dist/sign-ins-store.js +12 -16
- package/dist/sign-ins.d.ts +7 -11
- package/dist/sign-ins.js +40 -41
- package/dist/skills/agentrun-serve/SKILL.md +5 -2
- package/dist/slots.d.ts +9 -0
- package/dist/slots.js +45 -0
- package/dist/start-switches.d.ts +6 -5
- package/dist/start-switches.js +8 -4
- package/dist/stats.d.ts +5 -1
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.js +2 -2
- package/dist/store/dialect.d.ts +4 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/mcp-record-keys.d.ts +10 -0
- package/dist/store/mcp-record-keys.js +13 -0
- package/dist/store/postgres/dialect.js +2 -0
- package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
- package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
- package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
- package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
- package/dist/store/postgres/store.js +4 -0
- package/dist/store/schema.d.ts +44 -4
- package/dist/store/schema.js +111 -11
- package/dist/store/seal.d.ts +4 -1
- package/dist/store/sqlite/run-launch.d.ts +3 -10
- package/dist/store/sqlite/run-launch.js +12 -23
- package/dist/store/sqlite/run-patch.d.ts +19 -2
- package/dist/store/sqlite/run-patch.js +67 -2
- package/dist/store/sqlite/store.d.ts +3 -0
- package/dist/store/sqlite/store.js +177 -32
- package/dist/store/store-schema.js +3 -4
- package/dist/store/store.d.ts +74 -25
- package/dist/store/store.js +14 -11
- package/dist/store-reads/analytics.d.ts +2 -1
- package/dist/store-reads/analytics.js +7 -5
- package/dist/store-reads/learning.d.ts +102 -136
- package/dist/store-reads/learning.js +251 -302
- package/dist/store-reads/stats.d.ts +2 -2
- package/dist/store-reads/stats.js +13 -7
- package/dist/store-view.js +10 -7
- package/dist/suggestions.d.ts +1 -1
- package/dist/suggestions.js +29 -13
- package/dist/template-eval.d.ts +91 -9
- package/dist/template-eval.js +448 -105
- package/dist/template-import.d.ts +0 -10
- package/dist/template-import.js +5 -10
- package/dist/timeline/labels.d.ts +1 -1
- package/dist/timeline/labels.js +4 -3
- package/dist/timeline/timeline.d.ts +23 -11
- package/dist/timeline/timeline.js +115 -31
- package/dist/timeline/web-calls.d.ts +14 -14
- package/dist/timeline/web-calls.js +18 -30
- package/dist/tool-gate.d.ts +13 -1
- package/dist/tool-gate.js +43 -3
- package/dist/tool-keys-store.js +2 -4
- package/dist/tool-keys.d.ts +11 -0
- package/dist/tool-keys.js +16 -0
- package/dist/tool-plane.d.ts +50 -11
- package/dist/tool-plane.js +94 -30
- package/dist/tools.d.ts +5 -1
- package/dist/tools.js +7 -7
- package/dist/trigger-email.js +12 -6
- package/dist/triggers.d.ts +15 -34
- package/dist/triggers.js +119 -126
- package/dist/validate.d.ts +8 -1
- package/dist/validate.js +163 -23
- package/dist/web-fake.d.ts +2 -1
- package/dist/web-fake.js +8 -6
- package/dist/web-fetch.d.ts +8 -6
- package/dist/web-fetch.js +13 -11
- package/dist/web-holds.d.ts +32 -0
- package/dist/web-holds.js +86 -0
- package/dist/web-run.d.ts +32 -5
- package/dist/web-run.js +75 -28
- package/dist/web-save.d.ts +4 -9
- package/dist/web-save.js +27 -55
- package/dist/web-search.js +14 -25
- package/dist/wires.d.ts +4 -3
- package/dist/wires.js +5 -4
- package/dist/workspace/archil-claim.d.ts +12 -5
- package/dist/workspace/archil-claim.js +45 -5
- package/dist/workspace/attach.js +52 -19
- package/dist/workspace/attached-computers.d.ts +38 -11
- package/dist/workspace/attached-computers.js +81 -16
- package/dist/workspace/computer-deps.d.ts +29 -7
- package/dist/workspace/computer-deps.js +36 -18
- package/dist/workspace/computer-for-claim.d.ts +21 -4
- package/dist/workspace/computer-for-claim.js +166 -57
- package/dist/workspace/computer-intervals.d.ts +2 -0
- package/dist/workspace/computer-intervals.js +1 -1
- package/dist/workspace/computer-janitor.d.ts +48 -14
- package/dist/workspace/computer-janitor.js +153 -44
- package/dist/workspace/computer-kept.d.ts +158 -32
- package/dist/workspace/computer-kept.js +288 -63
- package/dist/workspace/computer-providers.d.ts +8 -3
- package/dist/workspace/computer-providers.js +12 -5
- package/dist/workspace/index.d.ts +1 -1
- package/dist/workspace/index.js +1 -1
- package/dist/workspace/local.js +41 -1
- package/dist/workspace/mount-revoke-left.d.ts +31 -0
- package/dist/workspace/mount-revoke-left.js +72 -0
- package/dist/workspace/paired-route.d.ts +91 -0
- package/dist/workspace/paired-route.js +152 -0
- package/dist/workspace/resolve-computer.d.ts +5 -2
- package/dist/workspace/resolve-computer.js +9 -3
- package/dist/workspace/run-end-computers.d.ts +11 -5
- package/dist/workspace/run-end-computers.js +153 -28
- package/dist/workspace/run-tools.d.ts +22 -3
- package/dist/workspace/run-tools.js +17 -5
- package/dist/workspace/run-workspace.d.ts +14 -1
- package/dist/workspace/run-workspace.js +34 -1
- package/dist/workspace/workspace.d.ts +6 -0
- package/dist/wrapped.d.ts +8 -2
- package/dist/wrapped.js +21 -6
- package/package.json +12 -13
- package/skills/agentrun-serve/SKILL.md +5 -2
- package/templates/README.md +25 -9
- package/dist/console/assets/backend-DVhHzJX2.js +0 -166
- package/dist/console/assets/index-Bwn1oTem.css +0 -1
- package/dist/console/assets/index-okP-y8PK.js +0 -747
package/dist/otel/tracer.js
CHANGED
|
@@ -4,52 +4,55 @@
|
|
|
4
4
|
// type's), no exporter starts and nothing leaves the machine. On, the exporter is given its endpoint, headers and
|
|
5
5
|
// timeout from the OTEL_EXPORTER_OTLP_* variables, and the resource OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES
|
|
6
6
|
// (deployment.environment.name among them) over our service.name=agentrun and service.version. Those variables are the
|
|
7
|
-
// runner's own: no run's environment has them (runner/main.ts runEnv), and
|
|
8
|
-
// (
|
|
7
|
+
// runner's own: no run's environment has them (runner/main.ts runEnv), and no run's process is handed them. A run in its
|
|
8
|
+
// own process (run-child.ts) traces over its channel (postedTracing): its runner makes its spans and exports them
|
|
9
|
+
// (tracePosts), so its harness, tools and computer never see an OTLP header, and it loads no exporter.
|
|
9
10
|
//
|
|
10
11
|
// What a span says is genai.ts's. Here: the spans' lifecycle, and the rules that keep a trace from costing a run
|
|
11
12
|
// - one trace per run: its id is the run id's hash, so every claim of a run (a resume, a takeover) is in one trace, and
|
|
12
13
|
// the sampler (always parent-based, its root's ratio from OTEL_TRACES_SAMPLER/_ARG) decides once per run, never
|
|
13
14
|
// splitting a run's spans;
|
|
14
|
-
// -
|
|
15
|
-
// never
|
|
16
|
-
//
|
|
15
|
+
// - tracing on says so once, as it is made (at the runner's start), with the origin of the endpoint its spans go to,
|
|
16
|
+
// never its user, password, path, query or fragment (shownEndpoint);
|
|
17
|
+
// - an export that fails or throws is a log line with the endpoint's origin and the time, then at most one a minute counting
|
|
18
|
+
// the failures it did not say (safeExporter), each cut by the runner's redactor, which holds each OTLP header value
|
|
19
|
+
// of 8 characters or more, then of each header value at any length (saidOf), and its spans are dropped: never the run's failure. A run's end never waits on an export: the batch processor sends
|
|
20
|
+
// in the background, a run's process never flushes, and only the runner's close flushes once (flushTraces), for at
|
|
21
|
+
// most FLUSH_MS.
|
|
17
22
|
import { createHash, randomBytes } from "node:crypto";
|
|
18
23
|
import { readFileSync } from "node:fs";
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
|
|
24
|
+
import { runnerSecrets, secretRedactor } from "../runner/redact.js";
|
|
25
|
+
import { keyValues, otlpHeaderCut } from "../secrets.js";
|
|
26
|
+
import { agentAttributes, chatAttributes, spanName, toolAttributes, tracedAgent, written } from "./genai.js";
|
|
27
|
+
/** The most often a collector that keeps failing is said in the log: the failures between are counted in the next line. */
|
|
28
|
+
export const FAILURE_LINE_MS = 60_000;
|
|
29
|
+
/** The most the runner's closing flush waits for its spans' export. */
|
|
22
30
|
export const FLUSH_MS = 3_000;
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
export const
|
|
27
|
-
/** A `key=value,key=value` list (OTEL_EXPORTER_OTLP_HEADERS, OTEL_RESOURCE_ATTRIBUTES), each part percent-decoded; a
|
|
28
|
-
* part that is not one is skipped. */
|
|
29
|
-
function listOf(text) {
|
|
30
|
-
const out = {};
|
|
31
|
-
for (const part of (text ?? "").split(",")) {
|
|
32
|
-
const at = part.indexOf("=");
|
|
33
|
-
if (at <= 0)
|
|
34
|
-
continue;
|
|
35
|
-
try {
|
|
36
|
-
const key = decodeURIComponent(part.slice(0, at).trim());
|
|
37
|
-
if (key)
|
|
38
|
-
out[key] = decodeURIComponent(part.slice(at + 1).trim());
|
|
39
|
-
}
|
|
40
|
-
catch {
|
|
41
|
-
continue;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return out;
|
|
45
|
-
}
|
|
31
|
+
/** The most model requests, and apart the most tool calls, one claim's trace holds open at once: one started past it
|
|
32
|
+
* has no span. A run's process posts its own trace (tracePosts) and runs the agent's code, so one that starts calls and
|
|
33
|
+
* never ends them can't grow its runner's memory without bound. */
|
|
34
|
+
export const OPEN_MAX = 512;
|
|
46
35
|
/** The OTLP exporter's settings from `env`, as the spec reads them: the traces endpoint as given, else the endpoint's
|
|
47
36
|
* /v1/traces; the headers (the traces' over the general ones); the timeout. */
|
|
48
37
|
export function exporterConfig(env) {
|
|
49
38
|
const traces = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim();
|
|
50
39
|
const url = traces || `${(env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "").trim().replace(/\/+$/, "")}/v1/traces`;
|
|
51
40
|
const timeout = Number(env.OTEL_EXPORTER_OTLP_TRACES_TIMEOUT ?? env.OTEL_EXPORTER_OTLP_TIMEOUT);
|
|
52
|
-
return { url, headers: { ...
|
|
41
|
+
return { url, headers: { ...keyValues(env.OTEL_EXPORTER_OTLP_HEADERS), ...keyValues(env.OTEL_EXPORTER_OTLP_TRACES_HEADERS) }, ...(Number.isFinite(timeout) && timeout > 0 ? { timeoutMillis: timeout } : {}) };
|
|
42
|
+
}
|
|
43
|
+
/** The endpoint `url` as a log line shows it: its origin alone (scheme://host[:port]). That says where spans go, and
|
|
44
|
+
* holds none of the parts a credential can be written in: the user and password, the path, the query, the fragment.
|
|
45
|
+
* One that is not a URL, or names no host, is shown as that alone, never as written. */
|
|
46
|
+
export function shownEndpoint(url) {
|
|
47
|
+
try {
|
|
48
|
+
const { protocol, host } = new URL(url);
|
|
49
|
+
if (host)
|
|
50
|
+
return `${protocol}//${host}`;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Not a URL: said as that alone, below.
|
|
54
|
+
}
|
|
55
|
+
return "an endpoint that is not a URL";
|
|
53
56
|
}
|
|
54
57
|
const TRUE = new Set(["1", "true", "yes", "on"]);
|
|
55
58
|
/** Whether `env` turns tracing on: an OTLP endpoint is named, and the SDK is not disabled. */
|
|
@@ -58,16 +61,158 @@ export function otelOn(env) {
|
|
|
58
61
|
return false;
|
|
59
62
|
return Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim() || env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim());
|
|
60
63
|
}
|
|
64
|
+
/** A run's own process's tracing (run-child.ts): each call of its claim's trace posted to its runner (`post`, in order
|
|
65
|
+
* with the rest of its channel), whose tracing makes the spans and exports them (tracePosts). The process loads no
|
|
66
|
+
* OpenTelemetry module, holds no OTLP setting and never flushes: its end waits on no collector. */
|
|
67
|
+
export function postedTracing(post) {
|
|
68
|
+
return {
|
|
69
|
+
flush: async () => { },
|
|
70
|
+
open: ({ startedAt = Date.now() } = {}) => {
|
|
71
|
+
post("open", [startedAt]);
|
|
72
|
+
let requests = 0;
|
|
73
|
+
// An event that is no tool's or turn's end is read only as the first of its turn (a plan turn's start): one post.
|
|
74
|
+
let heard = false;
|
|
75
|
+
return {
|
|
76
|
+
known: (run) => post("known", [run]),
|
|
77
|
+
request: (model, route) => {
|
|
78
|
+
const id = requests++;
|
|
79
|
+
post("request", [id, model, route]);
|
|
80
|
+
return (usage, ended) => post("ended", [id, usage, ended]);
|
|
81
|
+
},
|
|
82
|
+
event: (event) => {
|
|
83
|
+
if (event.type === "other" && heard)
|
|
84
|
+
return;
|
|
85
|
+
heard = event.type !== "turn_end";
|
|
86
|
+
post("event", [event]);
|
|
87
|
+
},
|
|
88
|
+
end: async (failed) => post("end", [failed]),
|
|
89
|
+
};
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** The longest id a run's process posts (a call's, a parent's, a route's name) its runner keeps as given. */
|
|
94
|
+
const ID_MAX = 128;
|
|
95
|
+
const DIGEST = "sha256:";
|
|
96
|
+
/** An id a run's process posts, as its runner keeps it: as given when it is ID_MAX characters or fewer, else its
|
|
97
|
+
* SHA-256 (DIGEST and 64 hex), so every post of one id is kept as the same string of a fixed size. One given in that
|
|
98
|
+
* shape is hashed too, so no short id is ever taken for a long one. */
|
|
99
|
+
function keptId(id) {
|
|
100
|
+
return id.length > ID_MAX || id.startsWith(DIGEST) ? `${DIGEST}${createHash("sha256").update(id).digest("hex")}` : id;
|
|
101
|
+
}
|
|
102
|
+
const text = (value) => (typeof value === "string" ? value : undefined);
|
|
103
|
+
const fields = (value) => (value !== null && typeof value === "object" ? value : {});
|
|
104
|
+
const figure = (value) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
|
|
105
|
+
/** A provider id's shape (`anthropic`, `openrouter`, `claude-login`), and a host's (a DNS name, or a bracketed IPv6
|
|
106
|
+
* address as URL.hostname writes one). A name the redactor cut holds "[redacted]", which is neither. */
|
|
107
|
+
const PROVIDER_ID = /^[a-z0-9][a-z0-9._-]*$/i;
|
|
108
|
+
const HOST = /^(\[[0-9a-f:.]+\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)$/i;
|
|
109
|
+
/** A run failure's code (`run-error`, `sdk_failed`, `ECONNREFUSED`). */
|
|
110
|
+
const FAILURE_CODE = /^[a-z][a-z0-9_.-]*$/i;
|
|
111
|
+
/** Every label a request's end that did not answer can have (Ended): the only ones its span's error.type takes. */
|
|
112
|
+
const END_LABELS = Object.freeze({ status: true, never_left: true, refused: true, error_before: true, error_after: true, gateway_timeout: true, retried: true, cut: true });
|
|
113
|
+
const TURN_STATUSES = new Set(["completed", "interrupted", "failed"]);
|
|
114
|
+
/** A request's end as a post gives it, rebuilt of the fields its span reads alone: its kind, and a label only from the
|
|
115
|
+
* kernel's own (END_LABELS; an answer's `filtered` or `error`). No reason, no other words. An end of any other shape is
|
|
116
|
+
* read as none. */
|
|
117
|
+
function endedOf(value) {
|
|
118
|
+
const given = fields(value);
|
|
119
|
+
if (given.end === "answered")
|
|
120
|
+
return (given.label === "filtered" || given.label === "error" ? { end: "answered", usd: figure(given.usd) ?? null, label: given.label } : { end: "answered", usd: figure(given.usd) ?? null });
|
|
121
|
+
if (given.end === "stopped")
|
|
122
|
+
return { end: "stopped", streamedTokens: figure(given.streamedTokens) ?? 0 };
|
|
123
|
+
if ((given.end === "nothing" || given.end === "lost") && typeof given.label === "string" && Object.hasOwn(END_LABELS, given.label))
|
|
124
|
+
return { end: given.end, label: given.label };
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
/** A request's usage as a post gives it, rebuilt of the fields its span reads alone: its counts as numbers (anything
|
|
128
|
+
* else is no count, and its span then has none), a plan's billing, a cut. */
|
|
129
|
+
function usageOf(value) {
|
|
130
|
+
const given = fields(value);
|
|
131
|
+
const count = (key) => (figure(given[key]) === undefined ? {} : { [key]: figure(given[key]) });
|
|
132
|
+
return { input: figure(given.input) ?? Number.NaN, output: figure(given.output) ?? Number.NaN, ...count("cacheRead"), ...count("cacheWrite"), usd: figure(given.usd) ?? null, ...(given.billing === "plan" ? { billing: "plan" } : {}), ...(given.cut === true ? { cut: true } : {}) };
|
|
133
|
+
}
|
|
134
|
+
/** The runner's side of a run's process's trace (postedTracing): the claim's one trace, opened from `tracing` for run
|
|
135
|
+
* `runId` whatever the process names, and each post read as data alone (the process runs the agent's code). No string a
|
|
136
|
+
* post gives reaches a span as given:
|
|
137
|
+
* - a name (harness, model) is cut by the runner's redactor (`redact`) and at WRITTEN_MAX (written);
|
|
138
|
+
* - a provider id and a host are cut the same way, and dropped unless they still have their shape (PROVIDER_ID, HOST);
|
|
139
|
+
* - a call's id is shown cut (TraceEvent.shownId); its id, and a parent's, only match a call's end and children, and
|
|
140
|
+
* are kept at ID_MAX (keptId), as a route's name is;
|
|
141
|
+
* - a route's name a request gives only finds its route; it is on no span; at most OPEN_MAX routes are known;
|
|
142
|
+
* - a request's end and usage are rebuilt (endedOf, usageOf): error.type comes from the kernel's labels alone;
|
|
143
|
+
* - a turn's status is one of TurnStatus's, else `failed`; the claim's failure is a code's shape, else `run-error`;
|
|
144
|
+
* - at most OPEN_MAX requests, and OPEN_MAX calls, are open at once: one started past that, or again under an id still
|
|
145
|
+
* open, has no span.
|
|
146
|
+
* - the run's agent is the one its runner read (`agent`: its id and name, cut as tracedAgent cuts them), never one a
|
|
147
|
+
* post names;
|
|
148
|
+
* `end`: the claim's end, for a process that is gone without ending its trace (after its own end, nothing is left). */
|
|
149
|
+
export function tracePosts(tracing, runId, redact, agent) {
|
|
150
|
+
let trace;
|
|
151
|
+
const ofRun = agent ? { agent: tracedAgent(agent, redact) } : {};
|
|
152
|
+
const requests = new Map();
|
|
153
|
+
const name = (value) => (typeof value === "string" ? written(value, redact) : undefined);
|
|
154
|
+
const shaped = (value, shape) => {
|
|
155
|
+
const cut = name(value);
|
|
156
|
+
return cut && shape.test(cut) ? cut : undefined;
|
|
157
|
+
};
|
|
158
|
+
const via = (value) => {
|
|
159
|
+
const given = fields(value);
|
|
160
|
+
const [provider, serverAddress, model] = [shaped(given.provider, PROVIDER_ID), shaped(given.serverAddress, HOST), name(given.model)];
|
|
161
|
+
return { ...(provider ? { provider } : {}), ...(serverAddress ? { serverAddress } : {}), ...(model ? { model } : {}) };
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
post(method, args) {
|
|
165
|
+
if (method === "open")
|
|
166
|
+
trace ??= tracing.open(figure(args[0]) === undefined ? {} : { startedAt: figure(args[0]) });
|
|
167
|
+
if (!trace)
|
|
168
|
+
return;
|
|
169
|
+
if (method === "known") {
|
|
170
|
+
const run = fields(args[0]);
|
|
171
|
+
const routes = run.routes instanceof Map ? new Map([...run.routes].slice(0, OPEN_MAX).flatMap(([key, route]) => (typeof key === "string" ? [[keptId(key), via(route)]] : []))) : undefined;
|
|
172
|
+
trace.known({ runId, ...ofRun, harness: name(run.harness) ?? "unknown", ...(run.plan === true ? { plan: true } : {}), ...via(run), ...(routes ? { routes } : {}) });
|
|
173
|
+
}
|
|
174
|
+
else if (method === "request" && typeof args[0] === "number") {
|
|
175
|
+
const route = text(args[2]);
|
|
176
|
+
if (!requests.has(args[0]) && requests.size < OPEN_MAX)
|
|
177
|
+
requests.set(args[0], trace.request(name(args[1]), route === undefined ? undefined : keptId(route)));
|
|
178
|
+
}
|
|
179
|
+
else if (method === "ended" && typeof args[0] === "number") {
|
|
180
|
+
requests.get(args[0])?.(usageOf(args[1]), endedOf(args[2]));
|
|
181
|
+
requests.delete(args[0]);
|
|
182
|
+
}
|
|
183
|
+
else if (method === "event") {
|
|
184
|
+
const event = fields(args[0]);
|
|
185
|
+
const given = text(event.callId) ?? "";
|
|
186
|
+
const [callId, shownId] = [keptId(given), written(given, redact)];
|
|
187
|
+
const parentId = text(event.parent);
|
|
188
|
+
const parent = parentId ? { parent: keptId(parentId) } : {};
|
|
189
|
+
if (event.type === "tool_start" && event.refused === true)
|
|
190
|
+
trace.event({ type: "tool_start", callId, shownId, refused: true, ...parent });
|
|
191
|
+
else if (event.type === "tool_start")
|
|
192
|
+
trace.event({ type: "tool_start", callId, shownId, ...(name(event.name) ? { name: name(event.name) } : {}), ...(event.mcp === true ? { mcp: true } : {}), ...parent });
|
|
193
|
+
else if (event.type === "tool_end")
|
|
194
|
+
trace.event({ type: "tool_end", callId, isError: event.isError === true });
|
|
195
|
+
else if (event.type === "turn_end")
|
|
196
|
+
trace.event({ type: "turn_end", status: typeof event.status === "string" && TURN_STATUSES.has(event.status) ? event.status : "failed" });
|
|
197
|
+
else
|
|
198
|
+
trace.event({ type: "other" });
|
|
199
|
+
}
|
|
200
|
+
else if (method === "end")
|
|
201
|
+
void trace.end(args[0] === undefined || args[0] === null ? undefined : (shaped(args[0], FAILURE_CODE) ?? "run-error"));
|
|
202
|
+
},
|
|
203
|
+
end: async (failed) => trace?.end(failed),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
61
206
|
let shared;
|
|
62
207
|
/** This process's tracing, or undefined while `env` leaves it off: then no @opentelemetry module is ever loaded. Made
|
|
63
208
|
* once per process; a test's (`test`) is its own. */
|
|
64
|
-
export function genAiTracing(env =
|
|
209
|
+
export function genAiTracing(env = process.env, test) {
|
|
65
210
|
if (!otelOn(env))
|
|
66
211
|
return Promise.resolve(undefined);
|
|
67
212
|
if (test)
|
|
68
213
|
return made(env, test);
|
|
69
214
|
shared ??= made(env).catch((error) => {
|
|
70
|
-
|
|
215
|
+
saidOf(env)(`[otel] tracing is off: the OpenTelemetry SDK did not start: ${error?.message ?? error}`);
|
|
71
216
|
return undefined;
|
|
72
217
|
});
|
|
73
218
|
return shared;
|
|
@@ -81,10 +226,22 @@ export async function flushTraces() {
|
|
|
81
226
|
/** A trace id for `runId`: the same for every claim of the run. */
|
|
82
227
|
export const traceIdOf = (runId) => createHash("sha256").update(`agentrun-run:${runId}`).digest("hex").slice(0, 32);
|
|
83
228
|
const serveVersion = () => JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
229
|
+
/** The tracing's log (`given`, else the runner's console): each `[otel]` line cut first by the runner's redactor over
|
|
230
|
+
* `env` (runner/redact.ts runnerSecrets: its OTLP header values among them), since an exporter's error may quote a
|
|
231
|
+
* header it sent, then of every OTLP header value at any length (secrets.ts otlpHeaderCut): the redactor cuts none
|
|
232
|
+
* shorter than MIN_SECRET, and a tracing key may be. Every line of this module goes through here. */
|
|
233
|
+
function saidOf(env, given) {
|
|
234
|
+
const cut = secretRedactor(runnerSecrets(env));
|
|
235
|
+
const headers = otlpHeaderCut(env);
|
|
236
|
+
const log = given ?? ((line) => console.warn(line));
|
|
237
|
+
return (line) => log(headers(cut(line)));
|
|
238
|
+
}
|
|
84
239
|
async function made(env, test) {
|
|
85
|
-
const [api, sdk, resources
|
|
86
|
-
const log = test?.log
|
|
87
|
-
const
|
|
240
|
+
const [api, sdk, resources] = await Promise.all([import("@opentelemetry/api"), import("@opentelemetry/sdk-trace"), import("@opentelemetry/resources")]);
|
|
241
|
+
const log = saidOf(env, test?.log);
|
|
242
|
+
const config = exporterConfig(env);
|
|
243
|
+
const where = shownEndpoint(config.url);
|
|
244
|
+
const exporter = safeExporter(test?.exporter ?? new (await import("@opentelemetry/exporter-trace-otlp-http")).OTLPTraceExporter(config), log, where, test?.now ?? Date.now);
|
|
88
245
|
// The next root span's trace id (the run's), taken by the one startSpan that asks for it: startSpan is synchronous.
|
|
89
246
|
const ids = { next: undefined };
|
|
90
247
|
const idGenerator = {
|
|
@@ -95,12 +252,12 @@ async function made(env, test) {
|
|
|
95
252
|
},
|
|
96
253
|
generateSpanId: () => randomBytes(8).toString("hex"),
|
|
97
254
|
};
|
|
98
|
-
// The operator's resource attributes over ours, read from `env` (a
|
|
99
|
-
// its environment, so the SDK's own env detector would not see them).
|
|
255
|
+
// The operator's resource attributes over ours, read from `env` (a test's, or the runner's).
|
|
100
256
|
const named = env.OTEL_SERVICE_NAME?.trim();
|
|
101
257
|
const resource = resources.defaultResource()
|
|
102
|
-
|
|
103
|
-
.merge(resources.resourceFromAttributes({
|
|
258
|
+
// The resource's names as the spec writes them: no module is loaded for two strings.
|
|
259
|
+
.merge(resources.resourceFromAttributes({ "service.name": "agentrun", "service.version": serveVersion() }))
|
|
260
|
+
.merge(resources.resourceFromAttributes({ ...keyValues(env.OTEL_RESOURCE_ATTRIBUTES), ...(named ? { "service.name": named } : {}) }));
|
|
104
261
|
const provider = new sdk.TracerProvider({
|
|
105
262
|
resource,
|
|
106
263
|
idGenerator,
|
|
@@ -121,9 +278,11 @@ async function made(env, test) {
|
|
|
121
278
|
// A process that ends by running out of work (no close, no exit call) flushes once first.
|
|
122
279
|
if (!test)
|
|
123
280
|
process.once("beforeExit", () => void flush());
|
|
281
|
+
// Said once, as the tracing is made: that it is on, and where its spans go (the endpoint's origin; no header).
|
|
282
|
+
log(`[otel] tracing is on: spans export to ${where}`);
|
|
124
283
|
return {
|
|
125
284
|
flush,
|
|
126
|
-
open: ({ startedAt = Date.now()
|
|
285
|
+
open: ({ startedAt = Date.now() } = {}) => {
|
|
127
286
|
let run;
|
|
128
287
|
let root;
|
|
129
288
|
let rootContext;
|
|
@@ -168,7 +327,7 @@ async function made(env, test) {
|
|
|
168
327
|
rootContext = api.trace.setSpan(api.ROOT_CONTEXT, root);
|
|
169
328
|
},
|
|
170
329
|
request: (model, route) => {
|
|
171
|
-
if (!run || run.plan)
|
|
330
|
+
if (!run || run.plan || chats.size >= OPEN_MAX)
|
|
172
331
|
return () => { };
|
|
173
332
|
const on = run;
|
|
174
333
|
const asked = { ...(model ? { model } : {}), ...(route === undefined ? {} : { route }) };
|
|
@@ -193,17 +352,22 @@ async function made(env, test) {
|
|
|
193
352
|
if (on.plan && !turn)
|
|
194
353
|
turn = child(spanName.chat(on.model), api.SpanKind.CLIENT, chatAttributes(on, {}));
|
|
195
354
|
if (event.type === "tool_start") {
|
|
196
|
-
if (tools.has(event.callId))
|
|
355
|
+
if (tools.has(event.callId) || tools.size >= OPEN_MAX)
|
|
197
356
|
return;
|
|
198
357
|
const parent = event.parent ? tools.get(event.parent)?.span : undefined;
|
|
199
|
-
|
|
358
|
+
// A call its harness refused (a tool the session does not have) is never named: the name is the model's words.
|
|
359
|
+
const name = event.refused ? undefined : event.name;
|
|
360
|
+
const span = child(spanName.tool(name), api.SpanKind.INTERNAL, toolAttributes(on, { ...(name ? { name } : {}), callId: event.shownId ?? event.callId, ...(event.mcp ? { mcp: true } : {}) }), parent ? api.trace.setSpan(api.ROOT_CONTEXT, parent) : undefined);
|
|
361
|
+
if (event.refused)
|
|
362
|
+
failed(span, "tool_refused");
|
|
363
|
+
tools.set(event.callId, { span, turn: turns, refused: event.refused === true });
|
|
200
364
|
}
|
|
201
365
|
else if (event.type === "tool_end") {
|
|
202
366
|
const call = tools.get(event.callId);
|
|
203
367
|
if (!call)
|
|
204
368
|
return;
|
|
205
369
|
tools.delete(event.callId);
|
|
206
|
-
if (event.isError)
|
|
370
|
+
if (event.isError && !call.refused)
|
|
207
371
|
failed(call.span, "tool_error");
|
|
208
372
|
call.span.end();
|
|
209
373
|
}
|
|
@@ -276,24 +440,45 @@ function rootSampler(env, sdk) {
|
|
|
276
440
|
}
|
|
277
441
|
return new sdk.AlwaysOnSampler();
|
|
278
442
|
}
|
|
279
|
-
/** `exporter` made safe for a run: a throw or a failed export is said
|
|
280
|
-
*
|
|
281
|
-
|
|
282
|
-
|
|
443
|
+
/** `exporter` made safe for a run: a throw or a failed export drops its spans and is said in the log, with the endpoint
|
|
444
|
+
* (`where`, its origin: shownEndpoint) and the time (`now`): the first at once; after it, at most one line each FAILURE_LINE_MS,
|
|
445
|
+
* said by the next failure once that long has passed since the last line, counting every failure since that line, the
|
|
446
|
+
* current one among them. So a collector that is down is a line a minute at most, never one a batch or a span; a
|
|
447
|
+
* failure that no later one follows is counted in no line. */
|
|
448
|
+
function safeExporter(exporter, log, where, now) {
|
|
449
|
+
let saidAt;
|
|
450
|
+
let unsaid = 0;
|
|
451
|
+
const iso = (at) => new Date(at).toISOString();
|
|
452
|
+
const failedAt = (why) => {
|
|
453
|
+
const at = now();
|
|
454
|
+
const words = why?.message ?? why;
|
|
455
|
+
if (saidAt === undefined) {
|
|
456
|
+
log(`[otel] a trace export to ${where} failed at ${iso(at)}; its spans were dropped: ${words}`);
|
|
457
|
+
saidAt = at;
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
unsaid += 1;
|
|
461
|
+
if (at - saidAt < FAILURE_LINE_MS)
|
|
462
|
+
return;
|
|
463
|
+
log(`[otel] ${unsaid} more trace export${unsaid === 1 ? "" : "s"} to ${where} failed since ${iso(saidAt)}, the last at ${iso(at)}; ${unsaid === 1 ? "its" : "their"} spans were dropped: ${words}`);
|
|
464
|
+
saidAt = at;
|
|
465
|
+
unsaid = 0;
|
|
466
|
+
};
|
|
283
467
|
return {
|
|
284
468
|
export: (spans, done) => {
|
|
285
469
|
const failedWith = (why) => {
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
470
|
+
try {
|
|
471
|
+
failedAt(why);
|
|
472
|
+
}
|
|
473
|
+
catch {
|
|
474
|
+
// A log that throws loses its line, never the export's answer.
|
|
475
|
+
}
|
|
289
476
|
done({ code: 1 });
|
|
290
477
|
};
|
|
291
478
|
try {
|
|
292
479
|
exporter.export(spans, (result) => {
|
|
293
|
-
if (result.code === 0)
|
|
294
|
-
failing = false;
|
|
480
|
+
if (result.code === 0)
|
|
295
481
|
done(result);
|
|
296
|
-
}
|
|
297
482
|
else
|
|
298
483
|
failedWith(result.error ?? "the exporter said it failed");
|
|
299
484
|
});
|
package/dist/page.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
2
|
import type { Owner } from "./owner.js";
|
|
3
|
+
/** The share page's CSP (share.html at /share/<run>): this origin's scripts, styles, data and images, and nothing from
|
|
4
|
+
* anywhere else. It is the page a share host serves, under the same policy; no favicon host, so a URL in a run's answer
|
|
5
|
+
* can never make a third party fetch anything. */
|
|
6
|
+
export declare const SHARE_PAGE_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
|
3
7
|
/** Strict-Transport-Security for a server whose public address (AGENTRUN_PUBLIC_URL) is https: a browser that saw it
|
|
4
8
|
* once opens the address over https only, for a year. None over http or with no public address (a browser would pin
|
|
5
9
|
* the loopback address to https and lose the console). */
|
|
@@ -20,6 +24,7 @@ export declare class ConsoleSessions {
|
|
|
20
24
|
/** Whether `value` is a session this server made. */
|
|
21
25
|
holds(value: string): boolean;
|
|
22
26
|
}
|
|
27
|
+
/** The values of the request's cookies named `name`, in the order sent. */
|
|
23
28
|
export declare const cookiesOf: (req: IncomingMessage, name: string) => string[];
|
|
24
29
|
/** Whether the browser reached this server over TLS, as the proxy in front says (X-Forwarded-Proto): `https`, or `wss`,
|
|
25
30
|
* which some proxies (Traefik) send on a WebSocket upgrade. Both are the page's https origin and its `__Host-` cookie. */
|
|
@@ -70,7 +75,8 @@ export declare const byOwnerSession: (req: IncomingMessage) => boolean;
|
|
|
70
75
|
/** Whether `req` came from the accounts-off console's page session (answerPage). */
|
|
71
76
|
export declare const byConsoleSession: (req: IncomingMessage) => boolean;
|
|
72
77
|
/**
|
|
73
|
-
* Answers the console's paths ("/" and its /assets/*,
|
|
78
|
+
* Answers the console's paths ("/" and its /assets/*, the addresses that moved to "/", and the share preview under
|
|
79
|
+
* /share/), and returns true; returns false for every other path. On a /v2 path with no Authorization header, the browser's cookie
|
|
74
80
|
* becomes the Bearer header for a GET or HEAD, and for any other method only when the request's Origin is this server's
|
|
75
81
|
* own origin and its body is application/json, or the request is a PUT or POST to a route that takes bytes, with any
|
|
76
82
|
* content type.
|
package/dist/page.js
CHANGED
|
@@ -14,6 +14,10 @@ import { hostPort, hostRefusedPage, movedPage } from "./host-check.js";
|
|
|
14
14
|
// icon from it (apps/console/src/components/ProviderIcon.tsx), sent with no referrer. Everything else is this origin's.
|
|
15
15
|
const CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: https://www.google.com https://t0.gstatic.com https://t1.gstatic.com https://t2.gstatic.com https://t3.gstatic.com; base-uri 'none'; form-action https://github.com; frame-ancestors 'none'";
|
|
16
16
|
const SECURITY = { "content-security-policy": CSP, "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "cache-control": "no-store" };
|
|
17
|
+
/** The share page's CSP (share.html at /share/<run>): this origin's scripts, styles, data and images, and nothing from
|
|
18
|
+
* anywhere else. It is the page a share host serves, under the same policy; no favicon host, so a URL in a run's answer
|
|
19
|
+
* can never make a third party fetch anything. */
|
|
20
|
+
export const SHARE_PAGE_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
|
17
21
|
const HTML = "text/html; charset=utf-8";
|
|
18
22
|
/** Strict-Transport-Security for a server whose public address (AGENTRUN_PUBLIC_URL) is https: a browser that saw it
|
|
19
23
|
* once opens the address over https only, for a year. None over http or with no public address (a browser would pin
|
|
@@ -35,6 +39,16 @@ const CONSOLE_SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
|
|
|
35
39
|
/** Addresses the console had before it took "/", and the old page's setup and sign-in, which the printed setup link
|
|
36
40
|
* still names: each sends the browser to "/", which keeps the link's #code. */
|
|
37
41
|
const MOVED = new Set(["/console", "/console/", "/setup", "/sign-in"]);
|
|
42
|
+
/** The share preview's addresses (the console's second entry, share.html): the page at /share/<run>, and the console's
|
|
43
|
+
* assets under /share/assets/, where the page's relative URLs land. */
|
|
44
|
+
const SHARE = "/share/";
|
|
45
|
+
/** A run's id as the share page's address names it: one segment, never a dot segment, a trailing slash allowed. */
|
|
46
|
+
const SHARE_RUN = /^[A-Za-z0-9_-][A-Za-z0-9._-]*\/?$/;
|
|
47
|
+
/** The share page's answer to a browser without this server's session: a fixed page under the CSP, never share.html. */
|
|
48
|
+
const SIGN_IN_FIRST = `<!doctype html>
|
|
49
|
+
<html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="robots" content="noindex" /><title>Sign in first · AgentRun</title></head>
|
|
50
|
+
<body><main><h1>Sign in to this server first</h1><p>A share preview shows what a run's share would publish, and only this server's owner may read it. Sign in at <a href="/">the console</a>, or open the link this server printed when it started, then open this page again.</p></main></body></html>
|
|
51
|
+
`;
|
|
38
52
|
const digest = (text) => createHash("sha256").update(text).digest();
|
|
39
53
|
const same = (given, expected) => timingSafeEqual(digest(given), digest(expected));
|
|
40
54
|
/** The most console sessions a server keeps at once; past it, the oldest is forgotten (its browser opens the link again). */
|
|
@@ -70,7 +84,13 @@ export class ConsoleSessions {
|
|
|
70
84
|
* (7340, published at 7350), and so does another beside it. A Host with no port keeps the socket's. */
|
|
71
85
|
const browserPort = (req) => hostPort(req.headers.host) ?? req.socket.localPort;
|
|
72
86
|
const cookieName = (req) => `agentrun-${browserPort(req)}`;
|
|
73
|
-
|
|
87
|
+
/** The request's cookies, each name and value trimmed, in the order sent; a part with no name is left out. */
|
|
88
|
+
const cookiePairs = (req) => String(req.headers.cookie ?? "").split(";").flatMap((part) => {
|
|
89
|
+
const at = part.indexOf("=");
|
|
90
|
+
return at > 0 && part.slice(0, at).trim() ? [{ name: part.slice(0, at).trim(), value: part.slice(at + 1).trim() }] : [];
|
|
91
|
+
});
|
|
92
|
+
/** The values of the request's cookies named `name`, in the order sent. */
|
|
93
|
+
export const cookiesOf = (req, name) => cookiePairs(req).filter((pair) => pair.name === name).map((pair) => pair.value);
|
|
74
94
|
/** Whether the browser reached this server over TLS, as the proxy in front says (X-Forwarded-Proto): `https`, or `wss`,
|
|
75
95
|
* which some proxies (Traefik) send on a WebSocket upgrade. Both are the page's https origin and its `__Host-` cookie. */
|
|
76
96
|
export const overHttps = (req) => ["https", "wss"].includes(String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim().toLowerCase());
|
|
@@ -86,11 +106,7 @@ export const ownerCookie = (req, value, maxAgeS, name = ownerCookieName(req)) =>
|
|
|
86
106
|
* again through a tunnel at 8080 sends both to either. Which are this server's is the owner's to say (Owner.valid). */
|
|
87
107
|
export const sessionsAtEveryPort = (req) => {
|
|
88
108
|
const own = ownerCookieName(req);
|
|
89
|
-
return
|
|
90
|
-
const at = part.indexOf("=");
|
|
91
|
-
const name = part.slice(0, at).trim();
|
|
92
|
-
return at > 0 && (name === own || /^agentrun-\d{1,5}-session$/.test(name)) ? [{ name, value: part.slice(at + 1).trim() }] : [];
|
|
93
|
-
});
|
|
109
|
+
return cookiePairs(req).filter(({ name }) => name === own || /^agentrun-\d{1,5}-session$/.test(name));
|
|
94
110
|
};
|
|
95
111
|
/** The owner's session cookies the request holds, valid or not. */
|
|
96
112
|
export const heldSessions = (req) => cookiesOf(req, ownerCookieName(req));
|
|
@@ -115,7 +131,7 @@ const refuse = (req, res, error) => send(req, res, error.status, "application/js
|
|
|
115
131
|
const redirect = (res, location, headers = {}) => (res.writeHead(303, { ...SECURITY, location, "content-length": 0, ...headers }), void res.end());
|
|
116
132
|
/** A file of the console: a known type inside `dir`, read through no link that leaves it. Vite's hashed assets are cached
|
|
117
133
|
* for a year; index.html is no-store. */
|
|
118
|
-
async function file(req, res, raw, dir, rel, status = 200) {
|
|
134
|
+
async function file(req, res, raw, dir, rel, status = 200, headers = {}) {
|
|
119
135
|
const missing = () => refuse(req, res, new ApiError("not_found", `no file ${raw} in the console`));
|
|
120
136
|
const type = CONSOLE_TYPES[extname(rel).toLowerCase()];
|
|
121
137
|
if (!type || !rel.split("/").every((segment) => CONSOLE_SEGMENT.test(segment)))
|
|
@@ -127,31 +143,68 @@ async function file(req, res, raw, dir, rel, status = 200) {
|
|
|
127
143
|
}
|
|
128
144
|
if (!real.startsWith(root + sep) || !(await stat(real)).isFile())
|
|
129
145
|
return missing();
|
|
130
|
-
send(req, res, status, type, await readFile(real), { "cache-control": rel.startsWith("assets/") ? "public, max-age=31536000, immutable" : "no-store" });
|
|
146
|
+
send(req, res, status, type, await readFile(real), { "cache-control": rel.startsWith("assets/") ? "public, max-age=31536000, immutable" : "no-store", ...headers });
|
|
131
147
|
}
|
|
132
|
-
async function answer(req, res, raw, server) {
|
|
148
|
+
async function answer(req, res, raw, server, held) {
|
|
133
149
|
if (req.method !== "GET" && req.method !== "HEAD")
|
|
134
150
|
return refuse(req, res, new ApiError("method_not_allowed", `the console answers GET and HEAD; ${req.method} is not one`, {}, { allow: "GET, HEAD" }));
|
|
135
151
|
const dir = server.console ?? CONSOLE_DIR;
|
|
152
|
+
if (raw.startsWith(SHARE))
|
|
153
|
+
return share(req, res, raw, dir, server, held);
|
|
136
154
|
if (MOVED.has(raw))
|
|
137
155
|
return redirect(res, `/${(req.url ?? "").slice(raw.length)}`);
|
|
138
156
|
if (raw !== "/")
|
|
139
157
|
return file(req, res, raw, dir, raw.slice(1));
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
158
|
+
const given = launch(req, res, raw, server, raw);
|
|
159
|
+
if (given === "answered")
|
|
160
|
+
return;
|
|
161
|
+
return file(req, res, raw, dir, "index.html", given === "wrong" ? 401 : 200);
|
|
162
|
+
}
|
|
163
|
+
/** The printed link's code in a page's address (`raw`: `/`, or `/share/<run>` the CLI opens). Without accounts, a right
|
|
164
|
+
* code gives this browser a console session (ConsoleSessions) and a redirect to the same page without it; "answered".
|
|
165
|
+
* The token is for scripts and the CLI: a token in the address signs nothing in, here or with an owner, and leaves it
|
|
166
|
+
* (the same address without it, no cookie). With an owner the console is the owner's session alone, so a code leaves
|
|
167
|
+
* the same way. A wrong code is "wrong" and sets nothing (the page answers 401); none is "none". `where` names the page
|
|
168
|
+
* in the failure log. */
|
|
169
|
+
function launch(req, res, raw, server, where) {
|
|
143
170
|
const url = new URL(req.url ?? "/", "http://serve");
|
|
144
|
-
const without = () => (url.searchParams.delete("token"), url.searchParams.delete("launch"),
|
|
171
|
+
const without = () => (url.searchParams.delete("token"), url.searchParams.delete("launch"), `${raw}${url.searchParams.size ? `?${url.searchParams}` : ""}`);
|
|
145
172
|
const given = url.searchParams.get("launch");
|
|
146
173
|
if (url.searchParams.has("token") || (server.owner && given !== null))
|
|
147
|
-
return redirect(res, without());
|
|
174
|
+
return redirect(res, without()), "answered";
|
|
175
|
+
if (given === null)
|
|
176
|
+
return "none";
|
|
148
177
|
// A code holds no "+", but a space in the link is one that was not encoded all the same.
|
|
149
|
-
const id =
|
|
178
|
+
const id = server.sessions?.open(given) ?? server.sessions?.open(given.replaceAll(" ", "+"));
|
|
150
179
|
if (id !== undefined)
|
|
151
|
-
return redirect(res, without(), { "set-cookie": `${cookieName(req)}=${id}; HttpOnly; SameSite=Strict; Path=/${overHttps(req) ? "; Secure" : ""}` });
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
180
|
+
return redirect(res, without(), { "set-cookie": `${cookieName(req)}=${id}; HttpOnly; SameSite=Strict; Path=/${overHttps(req) ? "; Secure" : ""}` }), "answered";
|
|
181
|
+
server.authFailed?.(where, "wrong_launch_code");
|
|
182
|
+
return "wrong";
|
|
183
|
+
}
|
|
184
|
+
/** The share preview (share.html) at /share/<run>, the owner's alone: a browser without this server's session (`held`:
|
|
185
|
+
* the owner's signed-in session with accounts, the printed link's without) gets SIGN_IN_FIRST, a 401, and so does a
|
|
186
|
+
* wrong launch code; a right one opens the session here as on `/` (launch). The page reads the run's export with that
|
|
187
|
+
* session (GET /v2/runs/<run>/export) and nothing else. Its assets are the console's, public. */
|
|
188
|
+
async function share(req, res, raw, dir, server, held) {
|
|
189
|
+
const rest = raw.slice(SHARE.length);
|
|
190
|
+
if (rest.startsWith("assets/"))
|
|
191
|
+
return file(req, res, raw, dir, rest);
|
|
192
|
+
if (!SHARE_RUN.test(rest))
|
|
193
|
+
return refuse(req, res, new ApiError("not_found", `no page ${raw}: a share preview is /share/<run id>`));
|
|
194
|
+
// share.html's assets are relative (./assets/): under /share/<run>/ they resolve to /share/<run>/assets/, which is no
|
|
195
|
+
// file. So the slash goes, with the query kept, before anything else is asked.
|
|
196
|
+
if (rest.endsWith("/"))
|
|
197
|
+
return redirect(res, `${raw.slice(0, -1)}${new URL(req.url ?? "/", "http://serve").search}`);
|
|
198
|
+
// The CLI opens /share/<run>?launch=<code> when it knows the code: the same session as `/?launch=`, landing here.
|
|
199
|
+
const given = launch(req, res, raw, server, "/share");
|
|
200
|
+
if (given === "answered")
|
|
201
|
+
return;
|
|
202
|
+
if (given === "wrong" || !held) {
|
|
203
|
+
if (given === "none")
|
|
204
|
+
server.authFailed?.("/share", "no_session");
|
|
205
|
+
return send(req, res, 401, HTML, SIGN_IN_FIRST);
|
|
206
|
+
}
|
|
207
|
+
return file(req, res, raw, dir, "share.html", 200, { "content-security-policy": SHARE_PAGE_CSP });
|
|
155
208
|
}
|
|
156
209
|
/** The requests the owner's password session sends from the page (a write only from this server's own origin, with a
|
|
157
210
|
* JSON body), never under an accounts-off console session. */
|
|
@@ -166,7 +219,8 @@ const consoleSessions = new WeakSet();
|
|
|
166
219
|
/** Whether `req` came from the accounts-off console's page session (answerPage). */
|
|
167
220
|
export const byConsoleSession = (req) => consoleSessions.has(req);
|
|
168
221
|
/**
|
|
169
|
-
* Answers the console's paths ("/" and its /assets/*,
|
|
222
|
+
* Answers the console's paths ("/" and its /assets/*, the addresses that moved to "/", and the share preview under
|
|
223
|
+
* /share/), and returns true; returns false for every other path. On a /v2 path with no Authorization header, the browser's cookie
|
|
170
224
|
* becomes the Bearer header for a GET or HEAD, and for any other method only when the request's Origin is this server's
|
|
171
225
|
* own origin and its body is application/json, or the request is a PUT or POST to a route that takes bytes, with any
|
|
172
226
|
* content type.
|
|
@@ -187,12 +241,12 @@ export function answerPage(req, res, raw, server) {
|
|
|
187
241
|
}
|
|
188
242
|
return false;
|
|
189
243
|
}
|
|
190
|
-
if (raw !== "/" && !raw.startsWith("/assets/") && !MOVED.has(raw))
|
|
244
|
+
if (raw !== "/" && !raw.startsWith("/assets/") && !MOVED.has(raw) && !raw.startsWith(SHARE))
|
|
191
245
|
return false;
|
|
192
246
|
// Every page answer (the console, its assets, its redirects) at an https public address: HSTS.
|
|
193
247
|
for (const [name, value] of Object.entries(hstsHeaders(server.publicUrl)))
|
|
194
248
|
res.setHeader(name, value);
|
|
195
|
-
answer(req, res, raw, server).catch(() => {
|
|
249
|
+
answer(req, res, raw, server, held).catch(() => {
|
|
196
250
|
if (!res.headersSent)
|
|
197
251
|
refuse(req, res, new ApiError("internal", "the console could not be read"));
|
|
198
252
|
else
|