@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.58
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 +281 -0
- package/README.md +246 -66
- package/dist/acp-package.d.ts +2 -0
- package/dist/adapters.d.ts +15 -3
- package/dist/adapters.js +17 -6
- package/dist/agent-package.d.ts +3 -3
- package/dist/agent-package.js +17 -8
- package/dist/api-keys.d.ts +76 -0
- package/dist/api-keys.js +217 -0
- package/dist/api-only.d.ts +15 -5
- package/dist/api-only.js +32 -8
- package/dist/box-paths.d.ts +4 -3
- package/dist/box-paths.js +7 -4
- package/dist/browser-hold.d.ts +23 -0
- package/dist/browser-hold.js +48 -0
- package/dist/browser-person.d.ts +3 -0
- package/dist/browser-person.js +4 -1
- package/dist/chatgpt-plan.d.ts +18 -8
- package/dist/chatgpt-plan.js +91 -34
- package/dist/claude-login-token.d.ts +117 -0
- package/dist/claude-login-token.js +737 -0
- package/dist/claude-login.d.ts +120 -22
- package/dist/claude-login.js +347 -63
- package/dist/claude-sign-in.d.ts +17 -6
- package/dist/claude-sign-in.js +42 -39
- package/dist/cli.js +33 -10
- package/dist/composio-made.d.ts +4 -0
- package/dist/composio-made.js +4 -0
- package/dist/composio-preset.d.ts +43 -2
- package/dist/composio-preset.js +92 -4
- package/dist/computer-attach.d.ts +35 -17
- package/dist/computer-attach.js +301 -49
- package/dist/computer-held-routes.d.ts +5 -4
- package/dist/computer-held-routes.js +29 -8
- package/dist/computer-held.d.ts +6 -1
- package/dist/computer-held.js +14 -0
- package/dist/computer-record.js +4 -2
- package/dist/computer-viewer.js +4 -1
- package/dist/computers.d.ts +10 -10
- package/dist/computers.js +5 -5
- package/dist/console/assets/{backend-Boh7tC4i.js → backend-CSAWUqtZ.js} +19 -19
- package/dist/console/assets/index-Bwn1oTem.css +1 -0
- package/dist/console/assets/index-DPh29cyz.js +747 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.d.ts +1 -1
- package/dist/decisions.js +1 -1
- package/dist/dial-relay.d.ts +25 -4
- package/dist/dial-relay.js +129 -1
- package/dist/docker-host-addresses.d.ts +22 -11
- package/dist/docker-host-addresses.js +38 -26
- package/dist/env-switch.d.ts +8 -0
- package/dist/env-switch.js +31 -2
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +2 -0
- package/dist/fal-price.d.ts +56 -20
- package/dist/fal-price.js +400 -90
- package/dist/handed-values.d.ts +43 -1
- package/dist/handed-values.js +119 -2
- package/dist/harness-archive.d.ts +13 -10
- package/dist/harness-archive.js +60 -34
- package/dist/harness-check.d.ts +3 -1
- package/dist/harness-check.js +25 -46
- package/dist/harness-keys.d.ts +73 -27
- package/dist/harness-keys.js +194 -61
- package/dist/harness-recipe-entry.d.ts +8 -7
- package/dist/harness-recipe-entry.js +21 -32
- package/dist/harness-recipe.d.ts +38 -25
- package/dist/harness-recipe.js +49 -36
- package/dist/harness-sign-in.js +12 -23
- package/dist/harness-table.d.ts +10 -3
- package/dist/harness-table.js +26 -21
- package/dist/harness.d.ts +1 -0
- package/dist/harness.js +17 -5
- package/dist/hosted-search.d.ts +1 -1
- package/dist/hosted-search.js +1 -2
- package/dist/import-worker.d.ts +4 -2
- package/dist/import-worker.js +9 -2
- package/dist/in-flight.d.ts +26 -0
- package/dist/in-flight.js +52 -0
- package/dist/key-refusal.d.ts +9 -4
- package/dist/key-refusal.js +107 -25
- package/dist/learn/ledger.d.ts +170 -0
- package/dist/learn/ledger.js +218 -0
- package/dist/learn/promote.d.ts +3 -3
- package/dist/learn/promote.js +1 -1
- package/dist/learn/secrets.d.ts +13 -3
- package/dist/learn/secrets.js +118 -17
- package/dist/learning-cost.d.ts +28 -23
- package/dist/learning-cost.js +19 -23
- package/dist/link-check.js +1 -1
- package/dist/live-reach.d.ts +2 -0
- package/dist/live-reach.js +2 -0
- package/dist/llms.txt +1 -1
- package/dist/marketplace.d.ts +77 -0
- package/dist/marketplace.js +224 -0
- package/dist/mcp-api-only-origins.d.ts +35 -0
- package/dist/mcp-api-only-origins.js +57 -0
- package/dist/mcp-gateway.d.ts +7 -5
- package/dist/mcp-gateway.js +9 -12
- package/dist/mcp-secret-writes.js +5 -3
- package/dist/mcp-servers-store.d.ts +28 -6
- package/dist/mcp-servers-store.js +53 -4
- package/dist/media-duration.d.ts +3 -0
- package/dist/media-duration.js +90 -9
- package/dist/micro.d.ts +2 -0
- package/dist/micro.js +2 -0
- package/dist/model-form.d.ts +5 -4
- package/dist/model-form.js +11 -7
- package/dist/model.d.ts +10 -6
- package/dist/model.js +16 -11
- package/dist/monid.d.ts +14 -1
- package/dist/monid.js +103 -26
- package/dist/ollama-provider.d.ts +7 -1
- package/dist/ollama-provider.js +14 -2
- package/dist/openapi.js +210 -37
- package/dist/otel/genai.d.ts +65 -0
- package/dist/otel/genai.js +116 -0
- package/dist/otel/tracer.d.ts +55 -0
- package/dist/otel/tracer.js +308 -0
- package/dist/page.d.ts +2 -0
- package/dist/page.js +3 -1
- package/dist/paid-calls.d.ts +1 -32
- package/dist/paid-calls.js +4 -39
- package/dist/place-offers.d.ts +4 -0
- package/dist/place-offers.js +7 -4
- package/dist/provider.d.ts +11 -2
- package/dist/provider.js +59 -8
- package/dist/redact/match.d.ts +30 -3
- package/dist/redact/match.js +422 -41
- package/dist/refusal-words.d.ts +11 -0
- package/dist/refusal-words.js +11 -0
- package/dist/run-census.d.ts +67 -0
- package/dist/run-census.js +240 -0
- package/dist/run-computer.d.ts +6 -3
- package/dist/run-computer.js +4 -1
- package/dist/run-cut.d.ts +15 -6
- package/dist/run-cut.js +30 -9
- package/dist/run-files.d.ts +3 -0
- package/dist/run-files.js +3 -0
- package/dist/run-launch.d.ts +12 -1
- package/dist/run-launch.js +9 -10
- package/dist/run-learning-served.d.ts +4 -2
- package/dist/run-model-key.d.ts +8 -0
- package/dist/run-model-key.js +31 -1
- package/dist/run-reads-over-store.d.ts +24 -6
- package/dist/run-reads-over-store.js +67 -23
- package/dist/run-recordings.d.ts +5 -1
- package/dist/run-recordings.js +39 -14
- package/dist/run-timeline-served.d.ts +2 -0
- package/dist/run-timeline-served.js +2 -2
- package/dist/run-usage.d.ts +1 -0
- package/dist/run-view.d.ts +1 -2
- package/dist/run-view.js +2 -1
- package/dist/runnable.d.ts +10 -1
- package/dist/runnable.js +20 -8
- package/dist/runner/adapter-loop.d.ts +11 -0
- package/dist/runner/adapter-loop.js +58 -26
- package/dist/runner/adapter-run-spec.d.ts +55 -11
- package/dist/runner/adapter-run-spec.js +183 -52
- package/dist/runner/adapters/pi.js +25 -3
- package/dist/runner/beside.d.ts +9 -2
- package/dist/runner/beside.js +27 -9
- package/dist/runner/big-writes.js +1 -10
- package/dist/runner/claim-secrets.d.ts +27 -10
- package/dist/runner/claim-secrets.js +49 -22
- package/dist/runner/cli-run-spec.d.ts +6 -0
- package/dist/runner/cli-run-spec.js +97 -38
- package/dist/runner/computer-journal.d.ts +9 -1
- package/dist/runner/computer-journal.js +26 -0
- package/dist/runner/conformance/harness.js +1 -1
- package/dist/runner/feedback-round.js +3 -0
- package/dist/runner/harness-loops.d.ts +6 -5
- package/dist/runner/harness-loops.js +7 -7
- package/dist/runner/held.d.ts +24 -6
- package/dist/runner/journal-kinds.d.ts +5 -0
- package/dist/runner/journal-kinds.js +5 -0
- package/dist/runner/main.d.ts +11 -6
- package/dist/runner/main.js +19 -9
- package/dist/runner/mcp-claim.js +31 -3
- package/dist/runner/mcp-run.d.ts +9 -0
- package/dist/runner/mcp-run.js +11 -5
- package/dist/runner/model-route.d.ts +17 -0
- package/dist/runner/model-route.js +120 -2
- package/dist/runner/presence.d.ts +11 -1
- package/dist/runner/presence.js +7 -0
- package/dist/runner/reflect-hook.js +1 -1
- package/dist/runner/run-child-host.d.ts +22 -8
- package/dist/runner/run-child-host.js +128 -41
- package/dist/runner/run-child.js +5 -2
- package/dist/runner/runner.d.ts +17 -3
- package/dist/runner/runner.js +130 -34
- package/dist/runner/save-slots.js +2 -1
- package/dist/runner/store-port.d.ts +1 -1
- package/dist/runner/store-secrets.d.ts +6 -0
- package/dist/runner/store-secrets.js +49 -7
- package/dist/runner/subagent.d.ts +11 -0
- package/dist/runner/subagent.js +16 -38
- package/dist/runner/workflow-first.d.ts +35 -15
- package/dist/runner/workflow-first.js +38 -25
- package/dist/runner/workflow-spec.js +4 -3
- package/dist/runs-over-store.d.ts +15 -6
- package/dist/runs-over-store.js +33 -21
- package/dist/scrub-command.d.ts +73 -0
- package/dist/scrub-command.js +307 -0
- package/dist/secret-cut.d.ts +73 -0
- package/dist/secret-cut.js +291 -4
- package/dist/secret-rules.d.ts +143 -0
- package/dist/secret-rules.js +2564 -0
- package/dist/secrets.d.ts +7 -0
- package/dist/secrets.js +20 -0
- package/dist/server-keys.d.ts +20 -0
- package/dist/server-keys.js +25 -6
- package/dist/server.d.ts +65 -13
- package/dist/server.js +470 -157
- package/dist/skills/agentrun-serve/SKILL.md +4 -0
- package/dist/slots.d.ts +9 -0
- package/dist/slots.js +45 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/journal/storage.js +1 -1
- package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
- package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
- package/dist/store/schema.d.ts +23 -0
- package/dist/store/schema.js +58 -2
- package/dist/store/seal.d.ts +6 -1
- package/dist/store/seal.js +5 -3
- package/dist/store/sqlite/run-launch.d.ts +9 -1
- package/dist/store/sqlite/run-launch.js +24 -13
- package/dist/store/sqlite/run-patch.d.ts +12 -2
- package/dist/store/sqlite/run-patch.js +42 -5
- package/dist/store/sqlite/store.js +105 -12
- package/dist/store/store.d.ts +57 -2
- package/dist/store/store.js +20 -0
- package/dist/store-reads/learning.d.ts +84 -124
- package/dist/store-reads/learning.js +210 -274
- package/dist/store-view.d.ts +3 -0
- package/dist/store-view.js +3 -3
- package/dist/suggestions.js +3 -2
- package/dist/template-eval.d.ts +39 -9
- package/dist/template-eval.js +191 -60
- package/dist/template-import.js +6 -2
- package/dist/templates.d.ts +10 -2
- package/dist/templates.js +28 -8
- package/dist/timeline/labels.d.ts +6 -4
- package/dist/timeline/labels.js +18 -6
- package/dist/timeline/timeline.d.ts +5 -0
- package/dist/timeline/timeline.js +14 -8
- package/dist/timeline/util.js +1 -1
- package/dist/timeline/web-calls.d.ts +22 -7
- package/dist/timeline/web-calls.js +106 -35
- package/dist/tool-gate.d.ts +42 -3
- package/dist/tool-gate.js +66 -5
- package/dist/tool-keys-store.d.ts +2 -4
- package/dist/tool-keys-store.js +5 -21
- package/dist/tool-keys.d.ts +2 -2
- package/dist/tool-keys.js +2 -2
- package/dist/tool-list.js +1 -1
- package/dist/tool-plane.d.ts +2 -2
- package/dist/tool-plane.js +35 -33
- package/dist/tools.js +13 -7
- package/dist/trigger-targets.d.ts +4 -0
- package/dist/trigger-targets.js +9 -2
- package/dist/triggers.d.ts +67 -4
- package/dist/triggers.js +171 -22
- package/dist/until.d.ts +3 -0
- package/dist/until.js +11 -0
- package/dist/web-fake.d.ts +1 -3
- package/dist/web-fake.js +7 -18
- package/dist/web-fetch.d.ts +6 -72
- package/dist/web-fetch.js +11 -265
- package/dist/web-run.d.ts +31 -0
- package/dist/web-run.js +90 -0
- package/dist/web-save.d.ts +10 -13
- package/dist/web-save.js +13 -55
- package/dist/web-search.d.ts +9 -127
- package/dist/web-search.js +23 -259
- package/dist/wires.d.ts +13 -0
- package/dist/wires.js +11 -0
- package/dist/workflow-run.d.ts +5 -4
- package/dist/workflow-run.js +5 -4
- package/dist/workspace/attached-computers.d.ts +32 -9
- package/dist/workspace/attached-computers.js +77 -13
- package/dist/workspace/computer-deps.d.ts +8 -2
- package/dist/workspace/computer-deps.js +10 -3
- package/dist/workspace/computer-for-claim.d.ts +12 -1
- package/dist/workspace/computer-for-claim.js +83 -11
- package/dist/workspace/computer-kept.d.ts +3 -0
- package/dist/workspace/computer-kept.js +11 -2
- package/dist/workspace/index.d.ts +1 -1
- package/dist/workspace/index.js +1 -1
- package/dist/workspace/kind-skills.d.ts +4 -0
- package/dist/workspace/kind-skills.js +9 -0
- package/dist/workspace/paired-route.d.ts +91 -0
- package/dist/workspace/paired-route.js +153 -0
- package/dist/workspace/synced-folder.js +3 -4
- package/dist/wrapped.d.ts +20 -6
- package/dist/wrapped.js +66 -25
- package/package.json +17 -11
- package/skills/agentrun-serve/SKILL.md +4 -0
- package/templates/README.md +32 -10
- package/dist/console/assets/index-CQ3cJRzI.js +0 -746
- package/dist/console/assets/index-DKkaS3a0.css +0 -1
- package/dist/exa-keyless.d.ts +0 -34
- package/dist/exa-keyless.js +0 -118
- package/dist/firecrawl-keyless.d.ts +0 -41
- package/dist/firecrawl-keyless.js +0 -152
- package/dist/keyless-mcp.d.ts +0 -36
- package/dist/keyless-mcp.js +0 -127
- package/dist/text-urls.d.ts +0 -38
- package/dist/text-urls.js +0 -170
- package/dist/web-fetch-direct.d.ts +0 -119
- package/dist/web-fetch-direct.js +0 -190
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type OtelUsage } from "@parcha/agentrun-import";
|
|
2
|
+
import type { Ended, ModelUsage } from "@parcha/agentrun-kernel";
|
|
3
|
+
/** The GenAI semantic conventions this mapping follows, stamped on every span until the spec has a schema URL. */
|
|
4
|
+
export declare const SEMCONV_VERSION = "genai-0.1.0";
|
|
5
|
+
export type Attributes = Record<string, string | number | boolean | string[]>;
|
|
6
|
+
/** The rename table: each of a request's counts, and every attribute name a backend reads it under. A cache write is
|
|
7
|
+
* sent under OpenTelemetry's name and Sentry's (`cache_creation`, the one its cost reads) until Sentry takes the other. */
|
|
8
|
+
export declare const USAGE_ATTRIBUTES: Readonly<Record<keyof OtelUsage, readonly string[]>>;
|
|
9
|
+
export declare const providerName: (provider: string) => string;
|
|
10
|
+
/** What a run's spans say of it, known once its spec is: its id, its harness, and the model route its requests take
|
|
11
|
+
* (AdapterRunSpec.trace), each where known. */
|
|
12
|
+
export interface TracedRun {
|
|
13
|
+
readonly runId: string;
|
|
14
|
+
readonly harness: string;
|
|
15
|
+
/** The harness's model is billed to a plan (its wire `plan`): its turns are its chat spans, with no usage. */
|
|
16
|
+
readonly plan?: boolean;
|
|
17
|
+
/** The provider id its model is named by (`anthropic`, `openai`, `openrouter`). */
|
|
18
|
+
readonly provider?: string;
|
|
19
|
+
/** The host its requests go to (its route's origin). */
|
|
20
|
+
readonly serverAddress?: string;
|
|
21
|
+
/** The model it runs on, named on a plan turn's span (its requests are never seen). */
|
|
22
|
+
readonly model?: string;
|
|
23
|
+
/** The session's other routes (a subagent's tier, a grader's), by the name a request that came by one carries
|
|
24
|
+
* (ModelRequest.route): its provider and host, in place of the run's. */
|
|
25
|
+
readonly routes?: ReadonlyMap<string, RouteTrace>;
|
|
26
|
+
}
|
|
27
|
+
/** A route as a trace names it: its provider id, its host, its model (routeTrace). */
|
|
28
|
+
export type RouteTrace = {
|
|
29
|
+
readonly provider?: string;
|
|
30
|
+
readonly serverAddress?: string;
|
|
31
|
+
readonly model?: string;
|
|
32
|
+
};
|
|
33
|
+
/** A spec's route as its trace names it (AdapterRunSpec.trace): the provider id a `provider/model` name begins with, the
|
|
34
|
+
* host of the origin its requests go to, its model id. Each only where given and well formed. */
|
|
35
|
+
export declare function routeTrace(route: {
|
|
36
|
+
readonly named?: string;
|
|
37
|
+
readonly origin?: string;
|
|
38
|
+
readonly model?: string;
|
|
39
|
+
}): RouteTrace;
|
|
40
|
+
/** Span names: low-cardinality, never an id, a command or an argument. */
|
|
41
|
+
export declare const spanName: {
|
|
42
|
+
agent: (run: TracedRun) => string;
|
|
43
|
+
chat: (model: string | undefined) => string;
|
|
44
|
+
tool: (name: string) => string;
|
|
45
|
+
};
|
|
46
|
+
export declare const agentAttributes: (run: TracedRun) => Attributes;
|
|
47
|
+
/** A request's counts on its span, by the rename table: gen_ai.usage.input_tokens INCLUSIVE of the cache (otelUsage, the
|
|
48
|
+
* import package's one reading of usage), never Anthropic's raw input. A request whose counts are not all counts has
|
|
49
|
+
* none. */
|
|
50
|
+
export declare function usageAttributes(usage: Pick<ModelUsage, "input" | "output" | "cacheRead" | "cacheWrite">): Attributes;
|
|
51
|
+
/** Why a request did not answer, as error.type, or undefined when it did. */
|
|
52
|
+
export declare function requestError(ended: Ended | undefined, usage: Pick<ModelUsage, "cut">): string | undefined;
|
|
53
|
+
/** A model request's span: its route (the run's, or the one it came by: `route`, a name the run does not know naming
|
|
54
|
+
* none), the model asked, how it ended and, when it answered and is billed by the token, its counts. A plan's request
|
|
55
|
+
* has no counts at all, and says it is the plan's. */
|
|
56
|
+
export declare function chatAttributes(run: TracedRun, request: {
|
|
57
|
+
readonly model?: string;
|
|
58
|
+
readonly route?: string;
|
|
59
|
+
}, usage?: ModelUsage, ended?: Ended): Attributes;
|
|
60
|
+
/** A tool call's span: its name, its id, and whether it is an MCP server's (an extension, called with tools/call). */
|
|
61
|
+
export declare function toolAttributes(run: TracedRun, call: {
|
|
62
|
+
readonly name: string;
|
|
63
|
+
readonly callId: string;
|
|
64
|
+
readonly mcp?: boolean;
|
|
65
|
+
}): Attributes;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// The one mapping from a run's events to OpenTelemetry GenAI spans (semantic-conventions-genai v0.1.0): its names, its
|
|
2
|
+
// attributes and its renames. No @opentelemetry module is imported here, so the mapping loads (and is tested) with
|
|
3
|
+
// tracing off; tracer.ts makes spans of what it says.
|
|
4
|
+
//
|
|
5
|
+
// A run is one trace:
|
|
6
|
+
// invoke_agent {harness} INTERNAL the claim's run of its agent; no usage, so a backend's sum never counts twice
|
|
7
|
+
// ├─ chat {request.model} CLIENT one per model request through the session's proxy, with its usage
|
|
8
|
+
// └─ execute_tool {tool.name} INTERNAL one per tool call (a nested call under the call that made it)
|
|
9
|
+
// A plan-billed harness (its wire `plan`: its requests never reach the host) has a chat span per turn, with no usage
|
|
10
|
+
// attributes at all and agentrun.billing=plan, never zeros; so does a request a plan billed (ModelUsage.billing).
|
|
11
|
+
// Content (messages, prompts, tool arguments and results) is never on a span here: no attribute below carries any.
|
|
12
|
+
import { normalizeUsage, otelUsage } from "@parcha/agentrun-import";
|
|
13
|
+
/** The GenAI semantic conventions this mapping follows, stamped on every span until the spec has a schema URL. */
|
|
14
|
+
export const SEMCONV_VERSION = "genai-0.1.0";
|
|
15
|
+
/** The rename table: each of a request's counts, and every attribute name a backend reads it under. A cache write is
|
|
16
|
+
* sent under OpenTelemetry's name and Sentry's (`cache_creation`, the one its cost reads) until Sentry takes the other. */
|
|
17
|
+
export const USAGE_ATTRIBUTES = Object.freeze({
|
|
18
|
+
input: ["gen_ai.usage.input_tokens"],
|
|
19
|
+
output: ["gen_ai.usage.output_tokens"],
|
|
20
|
+
cacheRead: ["gen_ai.usage.cache_read.input_tokens"],
|
|
21
|
+
cacheWrite: ["gen_ai.usage.cache_write.input_tokens", "gen_ai.usage.cache_creation.input_tokens"],
|
|
22
|
+
reasoning: ["gen_ai.usage.reasoning.output_tokens"],
|
|
23
|
+
});
|
|
24
|
+
/** A model provider's name as gen_ai.provider.name has it, from the provider id a run names its model by: the plan and
|
|
25
|
+
* sign-in routes (chatgpt-plan.ts PLAN_PROVIDER, claude-login.ts CLAUDE_LOGIN_PROVIDER) are their vendor's API. Any
|
|
26
|
+
* other id is its own name. */
|
|
27
|
+
const PROVIDER_NAMES = Object.freeze({ chatgpt: "openai", "claude-login": "anthropic" });
|
|
28
|
+
export const providerName = (provider) => PROVIDER_NAMES[provider] ?? provider;
|
|
29
|
+
/** A spec's route as its trace names it (AdapterRunSpec.trace): the provider id a `provider/model` name begins with, the
|
|
30
|
+
* host of the origin its requests go to, its model id. Each only where given and well formed. */
|
|
31
|
+
export function routeTrace(route) {
|
|
32
|
+
const slash = route.named?.indexOf("/") ?? -1;
|
|
33
|
+
let host;
|
|
34
|
+
try {
|
|
35
|
+
host = route.origin ? new URL(route.origin).hostname || undefined : undefined;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
host = undefined;
|
|
39
|
+
}
|
|
40
|
+
return { ...(slash > 0 ? { provider: route.named.slice(0, slash) } : {}), ...(host ? { serverAddress: host } : {}), ...(route.model ? { model: route.model } : {}) };
|
|
41
|
+
}
|
|
42
|
+
/** Span names: low-cardinality, never an id, a command or an argument. */
|
|
43
|
+
export const spanName = {
|
|
44
|
+
agent: (run) => `invoke_agent ${run.harness}`,
|
|
45
|
+
chat: (model) => (model ? `chat ${model}` : "chat"),
|
|
46
|
+
tool: (name) => `execute_tool ${name}`,
|
|
47
|
+
};
|
|
48
|
+
/** What every span of the run carries. */
|
|
49
|
+
function common(run, operation) {
|
|
50
|
+
return {
|
|
51
|
+
"gen_ai.operation.name": operation,
|
|
52
|
+
"gen_ai.conversation.id": run.runId,
|
|
53
|
+
"gen_ai.agent.name": run.harness,
|
|
54
|
+
"agentrun.harness": run.harness,
|
|
55
|
+
"agentrun.run.id": run.runId,
|
|
56
|
+
"session.id": run.runId,
|
|
57
|
+
"agentrun.semconv.version": SEMCONV_VERSION,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export const agentAttributes = (run) => common(run, "invoke_agent");
|
|
61
|
+
/** A request's counts on its span, by the rename table: gen_ai.usage.input_tokens INCLUSIVE of the cache (otelUsage, the
|
|
62
|
+
* import package's one reading of usage), never Anthropic's raw input. A request whose counts are not all counts has
|
|
63
|
+
* none. */
|
|
64
|
+
export function usageAttributes(usage) {
|
|
65
|
+
const read = normalizeUsage("pi", { input: usage.input, output: usage.output, cacheRead: usage.cacheRead ?? 0, cacheWrite: usage.cacheWrite ?? 0 });
|
|
66
|
+
if (!read)
|
|
67
|
+
return {};
|
|
68
|
+
const counts = otelUsage(read);
|
|
69
|
+
const out = {};
|
|
70
|
+
for (const [key, names] of Object.entries(USAGE_ATTRIBUTES)) {
|
|
71
|
+
const value = counts[key];
|
|
72
|
+
if (value !== undefined)
|
|
73
|
+
for (const name of names)
|
|
74
|
+
out[name] = value;
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
/** Why a request did not answer, as error.type, or undefined when it did. */
|
|
79
|
+
export function requestError(ended, usage) {
|
|
80
|
+
if (!ended)
|
|
81
|
+
return usage.cut ? "cut" : undefined;
|
|
82
|
+
if (ended.end === "answered")
|
|
83
|
+
return ended.label === "error" ? "provider_error" : undefined;
|
|
84
|
+
if (ended.end === "stopped")
|
|
85
|
+
return "stopped";
|
|
86
|
+
return ended.label;
|
|
87
|
+
}
|
|
88
|
+
/** A model request's span: its route (the run's, or the one it came by: `route`, a name the run does not know naming
|
|
89
|
+
* none), the model asked, how it ended and, when it answered and is billed by the token, its counts. A plan's request
|
|
90
|
+
* has no counts at all, and says it is the plan's. */
|
|
91
|
+
export function chatAttributes(run, request, usage, ended) {
|
|
92
|
+
const model = request.model ?? run.model;
|
|
93
|
+
const via = request.route === undefined ? run : (run.routes?.get(request.route) ?? {});
|
|
94
|
+
const plan = run.plan === true || usage?.billing === "plan";
|
|
95
|
+
const error = usage ? requestError(ended, usage) : undefined;
|
|
96
|
+
return {
|
|
97
|
+
...common(run, "chat"),
|
|
98
|
+
...(via.provider ? { "gen_ai.provider.name": providerName(via.provider) } : {}),
|
|
99
|
+
// The model asked for. gen_ai.response.model is never set: no usage the host reads names the model that answered.
|
|
100
|
+
...(model ? { "gen_ai.request.model": model } : {}),
|
|
101
|
+
...(via.serverAddress ? { "server.address": via.serverAddress } : {}),
|
|
102
|
+
...(ended?.end === "answered" && ended.label === "filtered" ? { "gen_ai.response.finish_reasons": ["content_filter"] } : {}),
|
|
103
|
+
...(plan ? { "agentrun.billing": "plan" } : usage && error === undefined ? usageAttributes(usage) : {}),
|
|
104
|
+
...(error ? { "error.type": error } : {}),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** A tool call's span: its name, its id, and whether it is an MCP server's (an extension, called with tools/call). */
|
|
108
|
+
export function toolAttributes(run, call) {
|
|
109
|
+
return {
|
|
110
|
+
...common(run, "execute_tool"),
|
|
111
|
+
"gen_ai.tool.name": call.name,
|
|
112
|
+
"gen_ai.tool.call.id": call.callId,
|
|
113
|
+
"gen_ai.tool.type": call.mcp ? "extension" : "function",
|
|
114
|
+
...(call.mcp ? { "mcp.method.name": "tools/call" } : {}),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { SpanExporter } from "@opentelemetry/sdk-trace";
|
|
2
|
+
import type { AdapterEvent, Ended, ModelUsage } from "@parcha/agentrun-kernel";
|
|
3
|
+
import { type TracedRun } from "./genai.js";
|
|
4
|
+
/** The most a process's closing flush waits for its spans' export. */
|
|
5
|
+
export declare const FLUSH_MS = 3000;
|
|
6
|
+
/** `env`'s OpenTelemetry settings: its OTEL_* variables. */
|
|
7
|
+
export declare const otelSettings: (env: NodeJS.ProcessEnv) => Record<string, string>;
|
|
8
|
+
/** This process's OpenTelemetry settings: what its pipe handed it (a run's process: its runner's), under its own. */
|
|
9
|
+
export declare const otelEnv: (env?: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
|
|
10
|
+
/** The OTLP exporter's settings from `env`, as the spec reads them: the traces endpoint as given, else the endpoint's
|
|
11
|
+
* /v1/traces; the headers (the traces' over the general ones); the timeout. */
|
|
12
|
+
export declare function exporterConfig(env: NodeJS.ProcessEnv): {
|
|
13
|
+
url: string;
|
|
14
|
+
headers: Record<string, string>;
|
|
15
|
+
timeoutMillis?: number;
|
|
16
|
+
};
|
|
17
|
+
/** Whether `env` turns tracing on: an OTLP endpoint is named, and the SDK is not disabled. */
|
|
18
|
+
export declare function otelOn(env: NodeJS.ProcessEnv): boolean;
|
|
19
|
+
/** A run's trace, for one claim of it. */
|
|
20
|
+
export interface RunTrace {
|
|
21
|
+
/** The run's facts, once its spec is known: its invoke_agent span starts then, at the claim's start. Said again (a
|
|
22
|
+
* restart's spec), nothing changes. */
|
|
23
|
+
known(run: TracedRun): void;
|
|
24
|
+
/** A model request admitted (`route`: the session's route it came by, where it names one): its chat span starts now,
|
|
25
|
+
* and the function it returns ends it with how it ended. One the claim's end finds still open ends interrupted. */
|
|
26
|
+
request(model: string | undefined, route?: string): (usage: ModelUsage, ended?: Ended) => void;
|
|
27
|
+
/** An event of the session: a tool call's start and end; on a plan-billed harness, its turns. */
|
|
28
|
+
event(event: AdapterEvent): void;
|
|
29
|
+
/** The claim ended (`failed`: why, when it failed): every span still open ends, and is handed to the exporter, which
|
|
30
|
+
* sends it in the background; this never waits on an export. Never throws. */
|
|
31
|
+
end(failed?: string): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
/** The tracing of one process: each claim of a run opens its trace. */
|
|
34
|
+
export interface GenAiTracing {
|
|
35
|
+
open(options?: {
|
|
36
|
+
readonly startedAt?: number;
|
|
37
|
+
readonly mcp?: (tool: string) => boolean;
|
|
38
|
+
}): RunTrace;
|
|
39
|
+
/** Every ended span sent, waited for at most FLUSH_MS: once, as the process closes. Never throws. */
|
|
40
|
+
flush(): Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
/** For tests: the exporter in place of OTLP's (the SDK's InMemorySpanExporter), spans exported as each ends, and the
|
|
43
|
+
* log lines said. */
|
|
44
|
+
export interface TracingTest {
|
|
45
|
+
readonly exporter: SpanExporter;
|
|
46
|
+
readonly log?: (line: string) => void;
|
|
47
|
+
}
|
|
48
|
+
/** This process's tracing, or undefined while `env` leaves it off: then no @opentelemetry module is ever loaded. Made
|
|
49
|
+
* once per process; a test's (`test`) is its own. */
|
|
50
|
+
export declare function genAiTracing(env?: NodeJS.ProcessEnv, test?: TracingTest): Promise<GenAiTracing | undefined>;
|
|
51
|
+
/** This process's closing flush (GenAiTracing.flush) of its tracing, when it was made; at once when it never was (off:
|
|
52
|
+
* nothing of OpenTelemetry is loaded for it). Never throws. */
|
|
53
|
+
export declare function flushTraces(): Promise<void>;
|
|
54
|
+
/** A trace id for `runId`: the same for every claim of the run. */
|
|
55
|
+
export declare const traceIdOf: (runId: string) => string;
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
// A run's GenAI trace, exported over OTLP with the official OpenTelemetry Node SDK, on only when the standard endpoint
|
|
2
|
+
// variable is set (OTEL_EXPORTER_OTLP_ENDPOINT, or OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) and OTEL_SDK_DISABLED is not
|
|
3
|
+
// true. Off, nothing of OpenTelemetry is imported (every import of it below is a dynamic one, after that check, or a
|
|
4
|
+
// type's), no exporter starts and nothing leaves the machine. On, the exporter is given its endpoint, headers and
|
|
5
|
+
// timeout from the OTEL_EXPORTER_OTLP_* variables, and the resource OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES
|
|
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 a run's own process reads them from its pipe
|
|
8
|
+
// (secrets.ts handedOtel), so its harness, tools and computer never see an OTLP header.
|
|
9
|
+
//
|
|
10
|
+
// What a span says is genai.ts's. Here: the spans' lifecycle, and the rules that keep a trace from costing a run
|
|
11
|
+
// - 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
|
+
// the sampler (always parent-based, its root's ratio from OTEL_TRACES_SAMPLER/_ARG) decides once per run, never
|
|
13
|
+
// splitting a run's spans;
|
|
14
|
+
// - an export that fails or throws is one log line, and its spans are dropped: never the run's failure. A claim's end
|
|
15
|
+
// never waits on an export: the batch processor sends in the background, and the process flushes once as it closes
|
|
16
|
+
// (flushTraces: the runner's close, a run's process before it exits), for at most FLUSH_MS.
|
|
17
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
18
|
+
import { readFileSync } from "node:fs";
|
|
19
|
+
import { handedOtel } from "../secrets.js";
|
|
20
|
+
import { agentAttributes, chatAttributes, spanName, toolAttributes } from "./genai.js";
|
|
21
|
+
/** The most a process's closing flush waits for its spans' export. */
|
|
22
|
+
export const FLUSH_MS = 3_000;
|
|
23
|
+
/** `env`'s OpenTelemetry settings: its OTEL_* variables. */
|
|
24
|
+
export const otelSettings = (env) => Object.fromEntries(Object.entries(env).filter((pair) => pair[0].startsWith("OTEL_") && typeof pair[1] === "string"));
|
|
25
|
+
/** This process's OpenTelemetry settings: what its pipe handed it (a run's process: its runner's), under its own. */
|
|
26
|
+
export const otelEnv = (env = process.env) => ({ ...handedOtel(), ...otelSettings(env) });
|
|
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
|
+
}
|
|
46
|
+
/** The OTLP exporter's settings from `env`, as the spec reads them: the traces endpoint as given, else the endpoint's
|
|
47
|
+
* /v1/traces; the headers (the traces' over the general ones); the timeout. */
|
|
48
|
+
export function exporterConfig(env) {
|
|
49
|
+
const traces = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim();
|
|
50
|
+
const url = traces || `${(env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "").trim().replace(/\/+$/, "")}/v1/traces`;
|
|
51
|
+
const timeout = Number(env.OTEL_EXPORTER_OTLP_TRACES_TIMEOUT ?? env.OTEL_EXPORTER_OTLP_TIMEOUT);
|
|
52
|
+
return { url, headers: { ...listOf(env.OTEL_EXPORTER_OTLP_HEADERS), ...listOf(env.OTEL_EXPORTER_OTLP_TRACES_HEADERS) }, ...(Number.isFinite(timeout) && timeout > 0 ? { timeoutMillis: timeout } : {}) };
|
|
53
|
+
}
|
|
54
|
+
const TRUE = new Set(["1", "true", "yes", "on"]);
|
|
55
|
+
/** Whether `env` turns tracing on: an OTLP endpoint is named, and the SDK is not disabled. */
|
|
56
|
+
export function otelOn(env) {
|
|
57
|
+
if (TRUE.has((env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase()))
|
|
58
|
+
return false;
|
|
59
|
+
return Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim() || env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim());
|
|
60
|
+
}
|
|
61
|
+
let shared;
|
|
62
|
+
/** This process's tracing, or undefined while `env` leaves it off: then no @opentelemetry module is ever loaded. Made
|
|
63
|
+
* once per process; a test's (`test`) is its own. */
|
|
64
|
+
export function genAiTracing(env = otelEnv(), test) {
|
|
65
|
+
if (!otelOn(env))
|
|
66
|
+
return Promise.resolve(undefined);
|
|
67
|
+
if (test)
|
|
68
|
+
return made(env, test);
|
|
69
|
+
shared ??= made(env).catch((error) => {
|
|
70
|
+
console.warn(`[otel] tracing is off: the OpenTelemetry SDK did not start: ${error?.message ?? error}`);
|
|
71
|
+
return undefined;
|
|
72
|
+
});
|
|
73
|
+
return shared;
|
|
74
|
+
}
|
|
75
|
+
/** This process's closing flush (GenAiTracing.flush) of its tracing, when it was made; at once when it never was (off:
|
|
76
|
+
* nothing of OpenTelemetry is loaded for it). Never throws. */
|
|
77
|
+
export async function flushTraces() {
|
|
78
|
+
const tracing = await shared;
|
|
79
|
+
await tracing?.flush();
|
|
80
|
+
}
|
|
81
|
+
/** A trace id for `runId`: the same for every claim of the run. */
|
|
82
|
+
export const traceIdOf = (runId) => createHash("sha256").update(`agentrun-run:${runId}`).digest("hex").slice(0, 32);
|
|
83
|
+
const serveVersion = () => JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
84
|
+
async function made(env, test) {
|
|
85
|
+
const [api, sdk, resources, semconv] = await Promise.all([import("@opentelemetry/api"), import("@opentelemetry/sdk-trace"), import("@opentelemetry/resources"), import("@opentelemetry/semantic-conventions")]);
|
|
86
|
+
const log = test?.log ?? ((line) => console.warn(line));
|
|
87
|
+
const exporter = safeExporter(test?.exporter ?? new (await import("@opentelemetry/exporter-trace-otlp-http")).OTLPTraceExporter(exporterConfig(env)), log);
|
|
88
|
+
// The next root span's trace id (the run's), taken by the one startSpan that asks for it: startSpan is synchronous.
|
|
89
|
+
const ids = { next: undefined };
|
|
90
|
+
const idGenerator = {
|
|
91
|
+
generateTraceId: () => {
|
|
92
|
+
const id = ids.next ?? randomBytes(16).toString("hex");
|
|
93
|
+
ids.next = undefined;
|
|
94
|
+
return id;
|
|
95
|
+
},
|
|
96
|
+
generateSpanId: () => randomBytes(8).toString("hex"),
|
|
97
|
+
};
|
|
98
|
+
// The operator's resource attributes over ours, read from `env` (a run's process has them from its pipe, never from
|
|
99
|
+
// its environment, so the SDK's own env detector would not see them).
|
|
100
|
+
const named = env.OTEL_SERVICE_NAME?.trim();
|
|
101
|
+
const resource = resources.defaultResource()
|
|
102
|
+
.merge(resources.resourceFromAttributes({ [semconv.ATTR_SERVICE_NAME]: "agentrun", [semconv.ATTR_SERVICE_VERSION]: serveVersion() }))
|
|
103
|
+
.merge(resources.resourceFromAttributes({ ...listOf(env.OTEL_RESOURCE_ATTRIBUTES), ...(named ? { [semconv.ATTR_SERVICE_NAME]: named } : {}) }));
|
|
104
|
+
const provider = new sdk.TracerProvider({
|
|
105
|
+
resource,
|
|
106
|
+
idGenerator,
|
|
107
|
+
sampler: new sdk.ParentBasedSampler({ root: rootSampler(env, sdk) }),
|
|
108
|
+
spanProcessors: [test ? new sdk.SimpleSpanProcessor({ exporter }) : new sdk.BatchSpanProcessor({ exporter })],
|
|
109
|
+
});
|
|
110
|
+
const tracer = provider.getTracer("agentrun", serveVersion());
|
|
111
|
+
const flush = async () => {
|
|
112
|
+
let timer;
|
|
113
|
+
const late = new Promise((resolve) => (timer = setTimeout(resolve, FLUSH_MS)));
|
|
114
|
+
try {
|
|
115
|
+
await Promise.race([Promise.resolve().then(() => provider.forceFlush()).catch(() => undefined), late]);
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
// A process that ends by running out of work (no close, no exit call) flushes once first.
|
|
122
|
+
if (!test)
|
|
123
|
+
process.once("beforeExit", () => void flush());
|
|
124
|
+
return {
|
|
125
|
+
flush,
|
|
126
|
+
open: ({ startedAt = Date.now(), mcp = () => false } = {}) => {
|
|
127
|
+
let run;
|
|
128
|
+
let root;
|
|
129
|
+
let rootContext;
|
|
130
|
+
// Each open tool call's span, and the turn it started in (`turns`, the turns ended so far): a turn that did not
|
|
131
|
+
// complete cuts its own calls, never one an earlier turn left going.
|
|
132
|
+
const tools = new Map();
|
|
133
|
+
let turns = 0;
|
|
134
|
+
// The chat spans of requests still waiting for their end (RunTrace.request).
|
|
135
|
+
const chats = new Set();
|
|
136
|
+
let turn;
|
|
137
|
+
const child = (name, kind, attributes, parent) => tracer.startSpan(name, { kind, attributes: attributes }, parent ?? rootContext);
|
|
138
|
+
const failed = (span, type) => {
|
|
139
|
+
span.setAttribute("error.type", type);
|
|
140
|
+
span.setStatus({ code: api.SpanStatusCode.ERROR });
|
|
141
|
+
};
|
|
142
|
+
// A trace's own failure is never its run's: said once, and the trace goes on without what failed.
|
|
143
|
+
let said = false;
|
|
144
|
+
const guarded = (fn, fallback) => (...args) => {
|
|
145
|
+
try {
|
|
146
|
+
return fn(...args);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (!said)
|
|
150
|
+
log(`[otel] a span of a run's trace was dropped: ${error?.message ?? error}`);
|
|
151
|
+
said = true;
|
|
152
|
+
return fallback;
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const trace = {
|
|
156
|
+
known: (given) => {
|
|
157
|
+
if (run)
|
|
158
|
+
return;
|
|
159
|
+
run = given;
|
|
160
|
+
ids.next = traceIdOf(given.runId);
|
|
161
|
+
try {
|
|
162
|
+
root = tracer.startSpan(spanName.agent(given), { kind: api.SpanKind.INTERNAL, startTime: startedAt, attributes: agentAttributes(given) }, api.ROOT_CONTEXT);
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
// Taken by that startSpan, or left by one that threw: never the next run's root's.
|
|
166
|
+
ids.next = undefined;
|
|
167
|
+
}
|
|
168
|
+
rootContext = api.trace.setSpan(api.ROOT_CONTEXT, root);
|
|
169
|
+
},
|
|
170
|
+
request: (model, route) => {
|
|
171
|
+
if (!run || run.plan)
|
|
172
|
+
return () => { };
|
|
173
|
+
const on = run;
|
|
174
|
+
const asked = { ...(model ? { model } : {}), ...(route === undefined ? {} : { route }) };
|
|
175
|
+
const span = child(spanName.chat(model ?? on.model), api.SpanKind.CLIENT, chatAttributes(on, asked));
|
|
176
|
+
chats.add(span);
|
|
177
|
+
return guarded((usage, ended) => {
|
|
178
|
+
if (!chats.delete(span))
|
|
179
|
+
return;
|
|
180
|
+
const attributes = chatAttributes(on, asked, usage, ended);
|
|
181
|
+
span.setAttributes(attributes);
|
|
182
|
+
if (attributes["error.type"] !== undefined)
|
|
183
|
+
span.setStatus({ code: api.SpanStatusCode.ERROR });
|
|
184
|
+
span.end();
|
|
185
|
+
}, undefined);
|
|
186
|
+
},
|
|
187
|
+
event: (event) => {
|
|
188
|
+
if (!run)
|
|
189
|
+
return;
|
|
190
|
+
const on = run;
|
|
191
|
+
// A plan-billed harness's turn is its model's: a chat span from its first event to its end, with no usage. A turn
|
|
192
|
+
// that ends with no event before (its drive failed at once) has one too, from its end.
|
|
193
|
+
if (on.plan && !turn)
|
|
194
|
+
turn = child(spanName.chat(on.model), api.SpanKind.CLIENT, chatAttributes(on, {}));
|
|
195
|
+
if (event.type === "tool_start") {
|
|
196
|
+
if (tools.has(event.callId))
|
|
197
|
+
return;
|
|
198
|
+
const parent = event.parent ? tools.get(event.parent)?.span : undefined;
|
|
199
|
+
tools.set(event.callId, { span: child(spanName.tool(event.name), api.SpanKind.INTERNAL, toolAttributes(on, { name: event.name, callId: event.callId, mcp: mcp(event.name) }), parent ? api.trace.setSpan(api.ROOT_CONTEXT, parent) : undefined), turn: turns });
|
|
200
|
+
}
|
|
201
|
+
else if (event.type === "tool_end") {
|
|
202
|
+
const call = tools.get(event.callId);
|
|
203
|
+
if (!call)
|
|
204
|
+
return;
|
|
205
|
+
tools.delete(event.callId);
|
|
206
|
+
if (event.isError)
|
|
207
|
+
failed(call.span, "tool_error");
|
|
208
|
+
call.span.end();
|
|
209
|
+
}
|
|
210
|
+
else if (event.type === "turn_end") {
|
|
211
|
+
// A call its own turn ended with no end of its own was cut with the turn. One an earlier turn left going (a
|
|
212
|
+
// call that outlived its turn) ends by its own end, or the claim's.
|
|
213
|
+
if (event.status !== "completed")
|
|
214
|
+
for (const [id, call] of tools) {
|
|
215
|
+
if (call.turn !== turns)
|
|
216
|
+
continue;
|
|
217
|
+
failed(call.span, "interrupted");
|
|
218
|
+
call.span.end();
|
|
219
|
+
tools.delete(id);
|
|
220
|
+
}
|
|
221
|
+
turns += 1;
|
|
222
|
+
if (turn) {
|
|
223
|
+
if (event.status !== "completed")
|
|
224
|
+
failed(turn, event.status);
|
|
225
|
+
turn.end();
|
|
226
|
+
turn = undefined;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
end: async (why) => {
|
|
231
|
+
try {
|
|
232
|
+
for (const { span } of tools.values()) {
|
|
233
|
+
failed(span, "interrupted");
|
|
234
|
+
span.end();
|
|
235
|
+
}
|
|
236
|
+
tools.clear();
|
|
237
|
+
// A request whose end the claim's end did not wait for (a booking still writing, a session closed past its
|
|
238
|
+
// bound, a restart's session that never answered it): its chat span ends with the claim, interrupted.
|
|
239
|
+
for (const span of chats) {
|
|
240
|
+
failed(span, "interrupted");
|
|
241
|
+
span.end();
|
|
242
|
+
}
|
|
243
|
+
chats.clear();
|
|
244
|
+
if (turn) {
|
|
245
|
+
failed(turn, "interrupted");
|
|
246
|
+
turn.end();
|
|
247
|
+
turn = undefined;
|
|
248
|
+
}
|
|
249
|
+
if (!root)
|
|
250
|
+
return;
|
|
251
|
+
if (why !== undefined)
|
|
252
|
+
failed(root, why);
|
|
253
|
+
root.end();
|
|
254
|
+
root = undefined;
|
|
255
|
+
// No flush here: the batch processor sends these spans in the background, and the process's close flushes
|
|
256
|
+
// what is left (flushTraces), so no claim's end waits on a collector.
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
log(`[otel] a run's trace was not ended, its spans dropped: ${error?.message ?? error}`);
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
return { known: guarded(trace.known, undefined), request: guarded(trace.request, () => { }), event: guarded(trace.event, undefined), end: trace.end };
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/** The root span's sampler: OTEL_TRACES_SAMPLER's ratio (traceidratio, with or without parentbased_), off, or on (the
|
|
268
|
+
* default); every other span follows its root's decision (ParentBasedSampler), so a run is sampled whole or not at all. */
|
|
269
|
+
function rootSampler(env, sdk) {
|
|
270
|
+
const name = (env.OTEL_TRACES_SAMPLER ?? "").trim().toLowerCase().replace(/^parentbased_/, "");
|
|
271
|
+
if (name === "always_off")
|
|
272
|
+
return new sdk.AlwaysOffSampler();
|
|
273
|
+
if (name === "traceidratio") {
|
|
274
|
+
const ratio = Number(env.OTEL_TRACES_SAMPLER_ARG ?? "1");
|
|
275
|
+
return new sdk.TraceIdRatioBasedSampler(Number.isFinite(ratio) ? Math.min(1, Math.max(0, ratio)) : 1);
|
|
276
|
+
}
|
|
277
|
+
return new sdk.AlwaysOnSampler();
|
|
278
|
+
}
|
|
279
|
+
/** `exporter` made safe for a run: a throw or a failed export is said once, in one line, and the spans are dropped; the
|
|
280
|
+
* next line is said only after an export has succeeded again, so a collector that is down is one line, not one a batch. */
|
|
281
|
+
function safeExporter(exporter, log) {
|
|
282
|
+
let failing = false;
|
|
283
|
+
return {
|
|
284
|
+
export: (spans, done) => {
|
|
285
|
+
const failedWith = (why) => {
|
|
286
|
+
if (!failing)
|
|
287
|
+
log(`[otel] a trace export failed; its spans were dropped: ${why?.message ?? why}`);
|
|
288
|
+
failing = true;
|
|
289
|
+
done({ code: 1 });
|
|
290
|
+
};
|
|
291
|
+
try {
|
|
292
|
+
exporter.export(spans, (result) => {
|
|
293
|
+
if (result.code === 0) {
|
|
294
|
+
failing = false;
|
|
295
|
+
done(result);
|
|
296
|
+
}
|
|
297
|
+
else
|
|
298
|
+
failedWith(result.error ?? "the exporter said it failed");
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
failedWith(error);
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
shutdown: () => exporter.shutdown().catch(() => undefined),
|
|
306
|
+
forceFlush: () => (exporter.forceFlush ? exporter.forceFlush().catch(() => undefined) : Promise.resolve()),
|
|
307
|
+
};
|
|
308
|
+
}
|
package/dist/page.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ export declare class ConsoleSessions {
|
|
|
21
21
|
holds(value: string): boolean;
|
|
22
22
|
}
|
|
23
23
|
export declare const cookiesOf: (req: IncomingMessage, name: string) => string[];
|
|
24
|
+
/** Whether the browser reached this server over TLS, as the proxy in front says (X-Forwarded-Proto): `https`, or `wss`,
|
|
25
|
+
* which some proxies (Traefik) send on a WebSocket upgrade. Both are the page's https origin and its `__Host-` cookie. */
|
|
24
26
|
export declare const overHttps: (req: IncomingMessage) => boolean;
|
|
25
27
|
export declare const ownOrigin: (req: IncomingMessage) => string;
|
|
26
28
|
export declare const isJson: (req: IncomingMessage) => boolean;
|
package/dist/page.js
CHANGED
|
@@ -71,7 +71,9 @@ export class ConsoleSessions {
|
|
|
71
71
|
const browserPort = (req) => hostPort(req.headers.host) ?? req.socket.localPort;
|
|
72
72
|
const cookieName = (req) => `agentrun-${browserPort(req)}`;
|
|
73
73
|
export const cookiesOf = (req, name) => String(req.headers.cookie ?? "").split(";").map((part) => part.trim()).filter((part) => part.startsWith(`${name}=`)).map((part) => part.slice(name.length + 1));
|
|
74
|
-
|
|
74
|
+
/** Whether the browser reached this server over TLS, as the proxy in front says (X-Forwarded-Proto): `https`, or `wss`,
|
|
75
|
+
* which some proxies (Traefik) send on a WebSocket upgrade. Both are the page's https origin and its `__Host-` cookie. */
|
|
76
|
+
export const overHttps = (req) => ["https", "wss"].includes(String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim().toLowerCase());
|
|
75
77
|
export const ownOrigin = (req) => `${overHttps(req) ? "https" : "http"}://${String(req.headers.host ?? "").toLowerCase()}`;
|
|
76
78
|
export const isJson = (req) => String(req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase() === "application/json";
|
|
77
79
|
/** The owner's session cookie: `__Host-` on https, so no other host or path can set it; else one per port the browser opened. */
|
package/dist/paid-calls.d.ts
CHANGED
|
@@ -1,37 +1,6 @@
|
|
|
1
1
|
import type { Refusal } from "@parcha/agentrun-kernel";
|
|
2
2
|
import type { ToolRegistration } from "@earendil-works/pi-durable";
|
|
3
|
-
|
|
4
|
-
export type ParallelSearchMode = "turbo" | "fast" | "basic" | "advanced";
|
|
5
|
-
/** Parallel's published prices (https://docs.parallel.ai/resources/pricing, read 2026-11-20). Search, by the request's
|
|
6
|
-
* `mode`: `turbo` or `fast` $1 per 1,000 requests, `basic` or `advanced` $5 per 1,000, each with 10 results included,
|
|
7
|
-
* and each result past those 10 $1 per 1,000. Extract: $1 per 1,000 URLs. */
|
|
8
|
-
export declare const PARALLEL_SEARCH_MODE_USD: Readonly<Record<ParallelSearchMode, number>>;
|
|
9
|
-
/** A `fast` search's price: the mode the web tools search in (web-search.ts). */
|
|
10
|
-
export declare const PARALLEL_SEARCH_USD = 0.001;
|
|
11
|
-
export declare const PARALLEL_SEARCH_RESULT_USD = 0.001;
|
|
12
|
-
export declare const PARALLEL_SEARCH_INCLUDED = 10;
|
|
13
|
-
export declare const PARALLEL_EXTRACT_USD = 0.001;
|
|
14
|
-
/** One paid request: `name` in the cap's refusal, `tool` and `by` on its records, `usd` its price, `basis` why. */
|
|
15
|
-
export type Fee = {
|
|
16
|
-
name: string;
|
|
17
|
-
by: string;
|
|
18
|
-
usd: number;
|
|
19
|
-
basis: string;
|
|
20
|
-
};
|
|
21
|
-
/** A search in `mode` for `n` results: the mode's price (PARALLEL_SEARCH_MODE_USD), and $0.001 for each past the 10 it
|
|
22
|
-
* includes. The web tools search `fast`: $0.001. */
|
|
23
|
-
export declare const parallelSearchFee: (n: number, mode?: ParallelSearchMode) => Fee;
|
|
24
|
-
/** An extract of `urls` URLs (the web tools ask one at a time). */
|
|
25
|
-
export declare const parallelExtractFee: (urls?: number) => Fee;
|
|
26
|
-
/** The fee of a request to Parallel's `url` with `body`: its search's, by its `mode` and the results it asks for (10 by
|
|
27
|
-
* default), or its extract's, by the URLs; undefined for an endpoint the web tools do not ask, and for a search whose
|
|
28
|
-
* mode has no price here (one naming none, or one Parallel added since): never $0, never another mode's price. */
|
|
29
|
-
export declare function parallelFeeOf(url: string, body: unknown): Fee | undefined;
|
|
30
|
-
/** A paid request the run's cap refused, whose hold could not be kept, or that has no run's ledger to book it on:
|
|
31
|
-
* nothing was sent. Its message is the refusal, in the cap's words. */
|
|
32
|
-
export declare class PaidRefused extends Error {
|
|
33
|
-
readonly name = "PaidRefused";
|
|
34
|
-
}
|
|
3
|
+
import { type Fee } from "@parcha/agentrun-web";
|
|
35
4
|
/** Where a paid request is booked: the call it is booked under, and the run's one ledger. */
|
|
36
5
|
export type Ledger = {
|
|
37
6
|
call: string;
|