@agent-watch-ai/edge 0.6.0 → 0.7.0
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 +219 -9
- package/README.md +303 -4
- package/dist/billing/billing-mode.d.ts +37 -5
- package/dist/billing/billing-mode.js +28 -19
- package/dist/billing/constants/billing.constants.d.ts +0 -2
- package/dist/billing/constants/billing.constants.js +0 -2
- package/dist/billing/index.d.ts +2 -1
- package/dist/billing/index.js +1 -1
- package/dist/billing/session-billing.d.ts +3 -2
- package/dist/billing/session-billing.js +8 -8
- package/dist/billing/types/billing.types.d.ts +7 -0
- package/dist/capture/capture-env.d.ts +147 -0
- package/dist/capture/capture-env.js +301 -0
- package/dist/capture/captured-step.d.ts +88 -0
- package/dist/capture/captured-step.js +479 -0
- package/dist/capture/constants/capture.constants.d.ts +70 -0
- package/dist/capture/constants/capture.constants.js +72 -0
- package/dist/capture/launched-runs.d.ts +16 -0
- package/dist/capture/launched-runs.js +151 -0
- package/dist/capture/node.cjs +697 -0
- package/dist/capture/node.d.cts +32 -0
- package/dist/capture/python/sitecustomize.py +823 -0
- package/dist/capture/schemas/capture.schema.d.ts +35 -0
- package/dist/capture/schemas/capture.schema.js +31 -0
- package/dist/capture/types/capture.types.d.ts +20 -0
- package/dist/cli/constants/cli.constants.d.ts +2 -6
- package/dist/cli/constants/cli.constants.js +3 -7
- package/dist/cli/context.d.ts +19 -22
- package/dist/cli/context.js +23 -54
- package/dist/cli/doctor-run-capture.d.ts +13 -0
- package/dist/cli/doctor-run-capture.js +19 -0
- package/dist/cli/doctor.js +16 -67
- package/dist/cli/hook.d.ts +14 -0
- package/dist/cli/hook.js +40 -0
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/misc.js +10 -2
- package/dist/cli/replay.d.ts +33 -0
- package/dist/cli/replay.js +193 -0
- package/dist/cli/setup.d.ts +10 -2
- package/dist/cli/setup.js +154 -26
- package/dist/cli/status.js +45 -5
- package/dist/cli/toggle.js +10 -0
- package/dist/cli/types/cli.types.d.ts +15 -1
- package/dist/cli/uninstall.js +8 -22
- package/dist/cli.js +104 -17
- package/dist/config/config.d.ts +0 -2
- package/dist/config/config.js +0 -1
- package/dist/config/constants/config.constants.js +2 -0
- package/dist/config/events-transport.d.ts +15 -0
- package/dist/config/events-transport.js +29 -0
- package/dist/config/index.d.ts +2 -1
- package/dist/config/index.js +1 -0
- package/dist/config/root-config.d.ts +12 -0
- package/dist/config/root-config.js +24 -0
- package/dist/config/schemas/config.schema.d.ts +13 -0
- package/dist/config/schemas/config.schema.js +42 -6
- package/dist/config/types/config.types.d.ts +7 -0
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.js +1 -1
- package/dist/core/version.d.ts +9 -0
- package/dist/core/version.js +14 -0
- package/dist/core/which.d.ts +11 -0
- package/dist/core/which.js +18 -0
- package/dist/credentials/cloud-claim.d.ts +32 -0
- package/dist/credentials/cloud-claim.js +42 -0
- package/dist/credentials/constants/credentials.constants.d.ts +8 -1
- package/dist/credentials/constants/credentials.constants.js +9 -2
- package/dist/credentials/device-api.d.ts +15 -1
- package/dist/credentials/device-api.js +12 -1
- package/dist/credentials/sign-in.d.ts +27 -0
- package/dist/credentials/sign-in.js +31 -1
- package/dist/credentials/token-refresher.d.ts +5 -1
- package/dist/credentials/token-refresher.js +10 -2
- package/dist/events/constants/events.constants.d.ts +5 -2
- package/dist/events/constants/events.constants.js +4 -1
- package/dist/events/index.d.ts +1 -0
- package/dist/events/product-event.d.ts +6 -3
- package/dist/events/types/events.types.d.ts +6 -0
- package/dist/events/types/replay-progress.types.d.ts +26 -0
- package/dist/events/types/replay-progress.types.js +1 -0
- package/dist/events/types/repo-tree.types.d.ts +2 -1
- package/dist/feature/ticket-candidates.d.ts +1 -1
- package/dist/git/checkout-root.d.ts +15 -0
- package/dist/git/checkout-root.js +18 -0
- package/dist/git/code-state.d.ts +2 -16
- package/dist/git/code-state.js +11 -12
- package/dist/git/constants/git.constants.d.ts +31 -11
- package/dist/git/constants/git.constants.js +36 -12
- package/dist/git/fingerprint.d.ts +3 -6
- package/dist/git/fingerprint.js +5 -8
- package/dist/git/git-context.js +5 -1
- package/dist/git/index.d.ts +1 -2
- package/dist/git/index.js +1 -1
- package/dist/git/repo-snapshot.d.ts +13 -4
- package/dist/git/repo-snapshot.js +47 -9
- package/dist/git/types/snapshot.types.d.ts +2 -0
- package/dist/pipeline/constants/pipeline.constants.d.ts +3 -0
- package/dist/pipeline/constants/pipeline.constants.js +3 -0
- package/dist/pipeline/hook-pipeline.js +81 -57
- package/dist/privacy/product-capture.js +2 -0
- package/dist/providers/antigravity/antigravity.capture.d.ts +2 -0
- package/dist/providers/antigravity/antigravity.capture.js +5 -0
- package/dist/providers/antigravity/antigravity.detect.js +8 -22
- package/dist/providers/antigravity/antigravity.provider.js +10 -3
- package/dist/providers/antigravity/constants/antigravity.constants.d.ts +1 -0
- package/dist/providers/antigravity/constants/antigravity.constants.js +1 -0
- package/dist/providers/claude/claude.adapter.js +9 -6
- package/dist/providers/claude/claude.detect.js +2 -17
- package/dist/providers/claude/claude.otel.d.ts +21 -3
- package/dist/providers/claude/claude.otel.js +216 -61
- package/dist/providers/claude/claude.provider.js +17 -1
- package/dist/providers/claude/claude.version.d.ts +9 -0
- package/dist/providers/claude/claude.version.js +28 -0
- package/dist/providers/claude/constants/claude.constants.d.ts +27 -0
- package/dist/providers/claude/constants/claude.constants.js +27 -0
- package/dist/providers/claude/constants/claude.otel.constants.d.ts +27 -0
- package/dist/providers/claude/constants/claude.otel.constants.js +45 -5
- package/dist/providers/claude/types/claude.types.d.ts +13 -0
- package/dist/providers/codex/codex.capture.d.ts +76 -0
- package/dist/providers/codex/codex.capture.js +454 -0
- package/dist/providers/codex/codex.detect.js +2 -4
- package/dist/providers/codex/codex.otel.d.ts +38 -2
- package/dist/providers/codex/codex.otel.js +50 -6
- package/dist/providers/codex/codex.provider.js +8 -0
- package/dist/providers/codex/codex.surface.d.ts +9 -0
- package/dist/{turns/codex-originator.js → providers/codex/codex.surface.js} +17 -3
- package/dist/providers/codex/codex.titles.d.ts +14 -0
- package/dist/providers/codex/codex.titles.js +35 -0
- package/dist/providers/codex/constants/codex.constants.d.ts +4 -0
- package/dist/providers/codex/constants/codex.constants.js +4 -0
- package/dist/providers/cursor/constants/cursor.constants.d.ts +17 -4
- package/dist/providers/cursor/constants/cursor.constants.js +25 -5
- package/dist/providers/cursor/cursor-mcp-memo.d.ts +34 -0
- package/dist/providers/cursor/cursor-mcp-memo.js +94 -0
- package/dist/providers/cursor/cursor.adapter.js +20 -82
- package/dist/providers/cursor/cursor.capture.d.ts +1 -0
- package/dist/providers/cursor/cursor.capture.js +4 -0
- package/dist/providers/cursor/cursor.detect.d.ts +5 -1
- package/dist/providers/cursor/cursor.detect.js +11 -26
- package/dist/providers/cursor/cursor.hooks.js +2 -2
- package/dist/providers/cursor/cursor.provider.js +16 -7
- package/dist/providers/cursor/cursor.titles.d.ts +14 -0
- package/dist/providers/cursor/cursor.titles.js +20 -0
- package/dist/providers/cursor/schemas/cursor.schema.d.ts +3 -3
- package/dist/providers/cursor/schemas/cursor.schema.js +5 -3
- package/dist/providers/gemini/constants/gemini.constants.d.ts +16 -0
- package/dist/providers/gemini/constants/gemini.constants.js +17 -0
- package/dist/providers/gemini/gemini.capture.d.ts +81 -0
- package/dist/providers/gemini/gemini.capture.js +210 -0
- package/dist/providers/gemini/gemini.detect.js +57 -24
- package/dist/providers/gemini/gemini.otel.d.ts +38 -2
- package/dist/providers/gemini/gemini.otel.js +56 -125
- package/dist/providers/gemini/gemini.provider.js +5 -0
- package/dist/providers/index.d.ts +1 -0
- package/dist/providers/index.js +1 -0
- package/dist/providers/provider.d.ts +8 -0
- package/dist/providers/provider.js +9 -0
- package/dist/providers/registry.d.ts +14 -0
- package/dist/providers/registry.js +14 -0
- package/dist/providers/shared/constants/hook-config.constants.d.ts +2 -0
- package/dist/providers/shared/constants/hook-config.constants.js +2 -0
- package/dist/providers/shared/constants/terminal-capture.constants.d.ts +6 -0
- package/dist/providers/shared/constants/terminal-capture.constants.js +6 -0
- package/dist/providers/shared/editor-paths.d.ts +8 -0
- package/dist/providers/shared/editor-paths.js +18 -0
- package/dist/providers/shared/hook-config.d.ts +5 -0
- package/dist/providers/shared/hook-config.js +39 -1
- package/dist/providers/shared/hooks-marker.d.ts +14 -0
- package/dist/providers/shared/hooks-marker.js +23 -0
- package/dist/providers/shared/install-record.d.ts +29 -0
- package/dist/providers/shared/install-record.js +52 -0
- package/dist/providers/shared/session-title-store.d.ts +23 -0
- package/dist/providers/shared/session-title-store.js +50 -0
- package/dist/providers/shared/terminal-capture.d.ts +41 -0
- package/dist/providers/shared/terminal-capture.js +109 -0
- package/dist/providers/shared/tooling.d.ts +21 -0
- package/dist/providers/shared/tooling.js +36 -1
- package/dist/providers/types/provider.types.d.ts +57 -4
- package/dist/replay/checkout-resolver.d.ts +29 -0
- package/dist/replay/checkout-resolver.js +69 -0
- package/dist/replay/codex-turns.d.ts +24 -0
- package/dist/replay/codex-turns.js +221 -0
- package/dist/replay/constants/replay.constants.d.ts +99 -0
- package/dist/replay/constants/replay.constants.js +102 -0
- package/dist/replay/describe.d.ts +10 -0
- package/dist/replay/describe.js +31 -0
- package/dist/replay/gemini-turns.d.ts +36 -0
- package/dist/replay/gemini-turns.js +192 -0
- package/dist/replay/machine.d.ts +34 -0
- package/dist/replay/machine.js +68 -0
- package/dist/replay/progress-event.d.ts +21 -0
- package/dist/replay/progress-event.js +45 -0
- package/dist/replay/replay-runner.d.ts +58 -0
- package/dist/replay/replay-runner.js +529 -0
- package/dist/replay/replay-scan.d.ts +83 -0
- package/dist/replay/replay-scan.js +170 -0
- package/dist/replay/replay-state.d.ts +108 -0
- package/dist/replay/replay-state.js +199 -0
- package/dist/replay/resume.d.ts +18 -0
- package/dist/replay/resume.js +34 -0
- package/dist/replay/start.d.ts +23 -0
- package/dist/replay/start.js +39 -0
- package/dist/replay/throttle.d.ts +35 -0
- package/dist/replay/throttle.js +41 -0
- package/dist/replay/transcript-turns.d.ts +35 -0
- package/dist/replay/transcript-turns.js +215 -0
- package/dist/replay/turn-event.d.ts +38 -0
- package/dist/replay/turn-event.js +116 -0
- package/dist/replay/types/replay.types.d.ts +162 -0
- package/dist/replay/types/replay.types.js +1 -0
- package/dist/replay/window.d.ts +28 -0
- package/dist/replay/window.js +41 -0
- package/dist/snapshot/branch-selection.d.ts +40 -23
- package/dist/snapshot/branch-selection.js +71 -41
- package/dist/snapshot/constants/snapshot-stages.constants.d.ts +3 -1
- package/dist/snapshot/constants/snapshot-stages.constants.js +3 -1
- package/dist/snapshot/constants/snapshot.constants.d.ts +34 -7
- package/dist/snapshot/constants/snapshot.constants.js +34 -7
- package/dist/snapshot/index.d.ts +2 -2
- package/dist/snapshot/index.js +1 -1
- package/dist/snapshot/snapshot-pipeline.js +89 -26
- package/dist/snapshot/snapshot-state.js +6 -2
- package/dist/snapshot/tree-pipeline.d.ts +1 -1
- package/dist/snapshot/tree-pipeline.js +34 -15
- package/dist/snapshot/types/snapshot.types.d.ts +20 -3
- package/dist/storage/schemas/storage.schema.d.ts +2 -0
- package/dist/storage/schemas/storage.schema.js +6 -0
- package/dist/transport/delivery-stats.d.ts +13 -1
- package/dist/transport/delivery-stats.js +18 -2
- package/dist/transport/delivery.d.ts +4 -3
- package/dist/transport/delivery.js +21 -7
- package/dist/transport/identity-delivery.d.ts +20 -0
- package/dist/transport/identity-delivery.js +41 -0
- package/dist/transport/index.d.ts +2 -0
- package/dist/transport/index.js +1 -0
- package/dist/transport/types/delivery-flow.types.d.ts +7 -0
- package/dist/turns/claude-transcript.js +4 -12
- package/dist/turns/codex-transcript.d.ts +9 -0
- package/dist/turns/codex-transcript.js +27 -19
- package/dist/turns/constants/turns.constants.d.ts +13 -12
- package/dist/turns/constants/turns.constants.js +15 -19
- package/dist/turns/gemini-transcript.d.ts +19 -1
- package/dist/turns/gemini-transcript.js +29 -18
- package/dist/turns/index.d.ts +3 -4
- package/dist/turns/index.js +2 -3
- package/dist/turns/run-state.d.ts +71 -0
- package/dist/turns/run-state.js +114 -0
- package/dist/turns/tool-events.d.ts +11 -1
- package/dist/turns/tool-events.js +32 -9
- package/dist/turns/transcript.d.ts +15 -14
- package/dist/turns/transcript.js +23 -4
- package/dist/turns/turn-state.d.ts +49 -7
- package/dist/turns/turn-state.js +78 -10
- package/dist/turns/turn-summary.js +7 -2
- package/dist/turns/turn-tracker.d.ts +9 -16
- package/dist/turns/turn-tracker.js +162 -86
- package/dist/turns/types/transcript.types.d.ts +11 -1
- package/dist/turns/types/turn-provider.types.d.ts +33 -0
- package/dist/turns/types/turn-provider.types.js +1 -0
- package/dist/turns/types/turn-state.types.d.ts +9 -0
- package/dist/turns/types/turn-summary.types.d.ts +17 -1
- package/dist/turns/types/turn-tracker.types.d.ts +3 -1
- package/dist/turns/work-checkout.js +1 -2
- package/docs/AUDIT_PROMPT.md +10 -0
- package/docs/DATA_HANDLING.md +193 -7
- package/docs/ENTERPRISE_DEPLOYMENT.md +1 -1
- package/docs/PERFORMANCE.md +10 -0
- package/package.json +3 -2
- package/dist/events/canonical-event.d.ts +0 -10
- package/dist/events/canonical-event.js +0 -9
- package/dist/git/repository-root.d.ts +0 -39
- package/dist/git/repository-root.js +0 -131
- package/dist/git/types/repository-root.types.d.ts +0 -11
- package/dist/transport/transport.d.ts +0 -6
- package/dist/turns/codex-originator.d.ts +0 -11
- package/dist/turns/cursor-transcript.d.ts +0 -21
- package/dist/turns/cursor-transcript.js +0 -66
- package/dist/turns/native-session-titles.d.ts +0 -26
- package/dist/turns/native-session-titles.js +0 -102
- /package/dist/{git/types/repository-root.types.js → billing/types/billing.types.js} +0 -0
- /package/dist/{transport/transport.js → capture/types/capture.types.js} +0 -0
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Run capture for Node, loaded into a process a coding agent starts through
|
|
4
|
+
* `NODE_OPTIONS=--require`. Built to dist/capture/node.cjs.
|
|
5
|
+
*
|
|
6
|
+
* It runs inside the customer's process, so it keeps four promises: it never
|
|
7
|
+
* opens a socket, never reads a request body or a request header but the host,
|
|
8
|
+
* never throws into the host, and never holds the process open (no timers; each
|
|
9
|
+
* call is one synchronous append). A fault costs a record, never the run.
|
|
10
|
+
*
|
|
11
|
+
* Node core imports only, unprefixed, and no `?.` or `??`, so it loads on any Node
|
|
12
|
+
* from 12 up that the customer's code may run on: a preload that fails to load takes
|
|
13
|
+
* the process down with it. `src/capture/python/sitecustomize.py` mirrors the
|
|
14
|
+
* table and the readers; `conformance/capture/cases.json` holds both to one result.
|
|
15
|
+
*/
|
|
16
|
+
// A .cts under verbatimModuleSyntax imports with `require`, and wrapping `emit` is the point.
|
|
17
|
+
/* eslint-disable @typescript-eslint/no-require-imports, no-param-reassign */
|
|
18
|
+
const childProcess = require("child_process");
|
|
19
|
+
const fs = require("fs");
|
|
20
|
+
const https = require("https");
|
|
21
|
+
const nodeModule = require("module");
|
|
22
|
+
const os = require("os");
|
|
23
|
+
const path = require("path");
|
|
24
|
+
const zlib = require("zlib");
|
|
25
|
+
const EXACT_HOSTS = {
|
|
26
|
+
'api.anthropic.com': 'anthropic',
|
|
27
|
+
'api.openai.com': 'openai',
|
|
28
|
+
'generativelanguage.googleapis.com': 'google',
|
|
29
|
+
'aiplatform.googleapis.com': 'vertex'
|
|
30
|
+
};
|
|
31
|
+
const RE_VERTEX_HOST = /^[a-z0-9-]+-aiplatform\.googleapis\.com$/;
|
|
32
|
+
const RE_BEDROCK_HOST = /^bedrock-runtime(?:-fips)?\.[a-z0-9-]+\.amazonaws\.com(?:\.cn)?$/;
|
|
33
|
+
const REQUEST_ID_HEADERS = {
|
|
34
|
+
anthropic: ['request-id', 'x-request-id'],
|
|
35
|
+
openai: ['x-request-id'],
|
|
36
|
+
google: ['x-goog-request-id', 'x-request-id'],
|
|
37
|
+
vertex: ['request-id', 'x-request-id', 'x-goog-request-id'],
|
|
38
|
+
bedrock: ['x-amzn-requestid', 'x-amz-request-id']
|
|
39
|
+
};
|
|
40
|
+
/** Bedrock's plain invoke states its usage in response headers only. */
|
|
41
|
+
const BEDROCK_USAGE_HEADERS = [
|
|
42
|
+
['x-amzn-bedrock-input-token-count', 'input_tokens'],
|
|
43
|
+
['x-amzn-bedrock-output-token-count', 'output_tokens'],
|
|
44
|
+
['x-amzn-bedrock-cache-read-input-token-count', 'cached_input_tokens'],
|
|
45
|
+
['x-amzn-bedrock-cache-write-input-token-count', 'cache_creation_input_tokens']
|
|
46
|
+
];
|
|
47
|
+
const RE_URL_MODEL = /\/models\/([^/:]+):/;
|
|
48
|
+
const RE_BEDROCK_MODEL = /\/model\/([^/]+)\//;
|
|
49
|
+
const RE_ARN = /^arn(?::|%3a)/i;
|
|
50
|
+
/** `"bytes"` is Bedrock's envelope, opened and asked this again. */
|
|
51
|
+
const RE_INTERESTING = /sage|Metrics|"bytes"/;
|
|
52
|
+
/** A coding agent's own process reports its own calls; capturing it would count them twice. */
|
|
53
|
+
const AGENT_ENTRIES = new Set(['claude', 'codex', 'gemini', 'agentwatch', 'cursor', 'cursor-agent', 'antigravity', 'agy']);
|
|
54
|
+
const AGENT_PACKAGES = /[\\/](?:@anthropic-ai[\\/]claude-code|@anthropic-ai[\\/]claude-agent-sdk|@openai[\\/]codex|@google[\\/]gemini-cli|@agent-watch-ai[\\/]edge|claude[\\/]versions|cursor-agent[\\/]versions|Cursor\.app|Antigravity\.app|\.gemini[\\/]antigravity-cli)[\\/]/;
|
|
55
|
+
const RE_WINDOWS_EXEC = /\.(?:exe|cmd)$/i;
|
|
56
|
+
const SPOOL_DIR = 'captured';
|
|
57
|
+
const DISABLED_MARKER = 'disabled.json';
|
|
58
|
+
const MAX_LINES_PER_FILE = 10000;
|
|
59
|
+
/** Absolute: a repository's folder on PATH must not be handed a `ps` to run. */
|
|
60
|
+
const PS_PATHS = ['/bin/ps', '/usr/bin/ps'];
|
|
61
|
+
/** Past this, a JSON or compressed body costs its usage rather than memory. */
|
|
62
|
+
const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
|
63
|
+
const MAX_ANCESTORS = 16;
|
|
64
|
+
const PS_TIMEOUT_MS = 2000;
|
|
65
|
+
const RE_PS_ROW = /^\s*(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ \d\d:\d\d:\d\d \d{4})/;
|
|
66
|
+
function count(value) {
|
|
67
|
+
return typeof value === 'number' && value >= 0 ? value : undefined;
|
|
68
|
+
}
|
|
69
|
+
function difference(whole, part) {
|
|
70
|
+
return whole === undefined ? undefined : Math.max(0, whole - (part || 0));
|
|
71
|
+
}
|
|
72
|
+
function record(value) {
|
|
73
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
74
|
+
}
|
|
75
|
+
/*
|
|
76
|
+
* Every reader answers in one convention: `input_tokens` excludes cache reads and
|
|
77
|
+
* `output_tokens` includes reasoning. Which of those the ledger wants on the wire
|
|
78
|
+
* depends on the launching agent, and the attach step decides that.
|
|
79
|
+
*/
|
|
80
|
+
function readUsageObject(usage) {
|
|
81
|
+
if (usage['prompt_tokens'] !== undefined || usage['completion_tokens'] !== undefined) {
|
|
82
|
+
const cached = count(record(usage['prompt_tokens_details'])['cached_tokens']);
|
|
83
|
+
return {
|
|
84
|
+
input_tokens: difference(count(usage['prompt_tokens']), cached),
|
|
85
|
+
cached_input_tokens: cached,
|
|
86
|
+
output_tokens: count(usage['completion_tokens']),
|
|
87
|
+
reasoning_output_tokens: count(record(usage['completion_tokens_details'])['reasoning_tokens']),
|
|
88
|
+
total_tokens: count(usage['total_tokens'])
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (usage['input_tokens_details'] !== undefined || usage['output_tokens_details'] !== undefined) {
|
|
92
|
+
const cached = count(record(usage['input_tokens_details'])['cached_tokens']);
|
|
93
|
+
return {
|
|
94
|
+
input_tokens: difference(count(usage['input_tokens']), cached),
|
|
95
|
+
cached_input_tokens: cached,
|
|
96
|
+
output_tokens: count(usage['output_tokens']),
|
|
97
|
+
reasoning_output_tokens: count(record(usage['output_tokens_details'])['reasoning_tokens']),
|
|
98
|
+
total_tokens: count(usage['total_tokens'])
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
if (usage['inputTokens'] !== undefined || usage['outputTokens'] !== undefined) {
|
|
102
|
+
return {
|
|
103
|
+
input_tokens: count(usage['inputTokens']),
|
|
104
|
+
cached_input_tokens: count(usage['cacheReadInputTokens']),
|
|
105
|
+
cache_creation_input_tokens: count(usage['cacheWriteInputTokens']),
|
|
106
|
+
output_tokens: count(usage['outputTokens']),
|
|
107
|
+
total_tokens: count(usage['totalTokens'])
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
input_tokens: count(usage['input_tokens']),
|
|
112
|
+
cached_input_tokens: count(usage['cache_read_input_tokens']),
|
|
113
|
+
cache_creation_input_tokens: count(usage['cache_creation_input_tokens']),
|
|
114
|
+
output_tokens: count(usage['output_tokens'])
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function readGeminiUsage(usage) {
|
|
118
|
+
const cached = count(usage['cachedContentTokenCount']);
|
|
119
|
+
const reasoning = count(usage['thoughtsTokenCount']);
|
|
120
|
+
const candidates = count(usage['candidatesTokenCount']);
|
|
121
|
+
return {
|
|
122
|
+
input_tokens: difference(count(usage['promptTokenCount']), cached),
|
|
123
|
+
cached_input_tokens: cached,
|
|
124
|
+
output_tokens: candidates === undefined && reasoning === undefined ? undefined : (candidates || 0) + (reasoning || 0),
|
|
125
|
+
reasoning_output_tokens: reasoning,
|
|
126
|
+
total_tokens: count(usage['totalTokenCount'])
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function readBedrockMetrics(metrics) {
|
|
130
|
+
return {
|
|
131
|
+
input_tokens: count(metrics['inputTokenCount']),
|
|
132
|
+
cached_input_tokens: count(metrics['cacheReadInputTokenCount']),
|
|
133
|
+
cache_creation_input_tokens: count(metrics['cacheWriteInputTokenCount']),
|
|
134
|
+
output_tokens: count(metrics['outputTokenCount'])
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/** The usage readers, by the key each provider's usage sits under. */
|
|
138
|
+
const USAGE_READERS = [
|
|
139
|
+
['usage', readUsageObject],
|
|
140
|
+
['usageMetadata', readGeminiUsage],
|
|
141
|
+
['amazon-bedrock-invocationMetrics', readBedrockMetrics]
|
|
142
|
+
];
|
|
143
|
+
/** One response being read: what it says so far, and its framing's leftovers. */
|
|
144
|
+
class ResponseTap {
|
|
145
|
+
onFinish;
|
|
146
|
+
call;
|
|
147
|
+
framing;
|
|
148
|
+
encoding;
|
|
149
|
+
carry = Buffer.alloc(0);
|
|
150
|
+
overflowed = false;
|
|
151
|
+
finished = false;
|
|
152
|
+
bodyRequestId;
|
|
153
|
+
constructor(meta, status, headers, onFinish, decoded) {
|
|
154
|
+
this.onFinish = onFinish;
|
|
155
|
+
this.call = { provider: meta.provider, model: meta.model, request_id: requestIdOf(meta.provider, headers), status };
|
|
156
|
+
this.framing = framingOf(headers('content-type'));
|
|
157
|
+
this.encoding = decoded ? '' : (headers('content-encoding') || '').toLowerCase().trim();
|
|
158
|
+
if (meta.provider === 'bedrock')
|
|
159
|
+
this.absorbHeaders(headers);
|
|
160
|
+
}
|
|
161
|
+
absorbHeaders(headers) {
|
|
162
|
+
const usage = {};
|
|
163
|
+
for (const [name, field] of BEDROCK_USAGE_HEADERS) {
|
|
164
|
+
const value = Number(headers(name));
|
|
165
|
+
if (headers(name) !== undefined && Number.isFinite(value))
|
|
166
|
+
usage[field] = value;
|
|
167
|
+
}
|
|
168
|
+
this.merge(usage);
|
|
169
|
+
}
|
|
170
|
+
merge(usage) {
|
|
171
|
+
const merged = { ...this.call.usage };
|
|
172
|
+
for (const key of Object.keys(usage)) {
|
|
173
|
+
if (usage[key] !== undefined)
|
|
174
|
+
merged[key] = usage[key];
|
|
175
|
+
}
|
|
176
|
+
if (Object.keys(merged).length > 0)
|
|
177
|
+
this.call.usage = merged;
|
|
178
|
+
}
|
|
179
|
+
absorb(value) {
|
|
180
|
+
if (Array.isArray(value)) {
|
|
181
|
+
for (const item of value)
|
|
182
|
+
this.absorb(item);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const event = record(value);
|
|
186
|
+
// Anthropic's message_start and OpenAI's response.* nest the whole message.
|
|
187
|
+
if (event['message'] !== undefined)
|
|
188
|
+
this.absorb(event['message']);
|
|
189
|
+
if (event['response'] !== undefined)
|
|
190
|
+
this.absorb(event['response']);
|
|
191
|
+
if (typeof event['model'] === 'string')
|
|
192
|
+
this.call.model = modelName(event['model']);
|
|
193
|
+
if (typeof event['modelVersion'] === 'string')
|
|
194
|
+
this.call.model = event['modelVersion'];
|
|
195
|
+
if (typeof event['responseId'] === 'string')
|
|
196
|
+
this.bodyRequestId = event['responseId'];
|
|
197
|
+
for (const [key, read] of USAGE_READERS) {
|
|
198
|
+
if (event[key] !== null && typeof event[key] === 'object')
|
|
199
|
+
this.merge(read(event[key]));
|
|
200
|
+
}
|
|
201
|
+
// A Bedrock stream chunk carries the provider's own event as base64.
|
|
202
|
+
if (typeof event['bytes'] === 'string')
|
|
203
|
+
this.absorbText(Buffer.from(event['bytes'], 'base64').toString('utf8'));
|
|
204
|
+
}
|
|
205
|
+
// Only what can hold usage is parsed: a text delta is never looked into.
|
|
206
|
+
absorbText(text) {
|
|
207
|
+
if (!RE_INTERESTING.test(text) && !(this.call.model === undefined && text.includes('"model')) && !text.includes('responseId'))
|
|
208
|
+
return;
|
|
209
|
+
try {
|
|
210
|
+
this.absorb(JSON.parse(text));
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
// Not JSON, or cut short; it holds no usage we can read.
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
lines(flush) {
|
|
217
|
+
let start = 0;
|
|
218
|
+
for (let end = this.carry.indexOf(10); end !== -1; end = this.carry.indexOf(10, start)) {
|
|
219
|
+
this.line(this.carry.toString('utf8', start, end));
|
|
220
|
+
start = end + 1;
|
|
221
|
+
}
|
|
222
|
+
this.carry = start === 0 ? this.carry : this.carry.subarray(start);
|
|
223
|
+
if (flush && this.carry.length > 0)
|
|
224
|
+
this.line(this.carry.toString('utf8'));
|
|
225
|
+
}
|
|
226
|
+
line(raw) {
|
|
227
|
+
const text = raw.trim();
|
|
228
|
+
if (text.startsWith('data:'))
|
|
229
|
+
this.absorbText(text.slice(5).trim());
|
|
230
|
+
}
|
|
231
|
+
frames() {
|
|
232
|
+
while (this.carry.length >= 12) {
|
|
233
|
+
const total = this.carry.readUInt32BE(0);
|
|
234
|
+
const headersLength = this.carry.readUInt32BE(4);
|
|
235
|
+
if (total < 16 || total > MAX_BODY_BYTES || 12 + headersLength > total - 4) {
|
|
236
|
+
this.overflowed = true;
|
|
237
|
+
this.carry = Buffer.alloc(0);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (this.carry.length < total)
|
|
241
|
+
return;
|
|
242
|
+
this.absorbText(this.carry.toString('utf8', 12 + headersLength, total - 4));
|
|
243
|
+
this.carry = this.carry.subarray(total);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/** Take one chunk of the body as the host read it. */
|
|
247
|
+
feed(chunk) {
|
|
248
|
+
if (this.overflowed || this.finished)
|
|
249
|
+
return;
|
|
250
|
+
this.carry = this.carry.length === 0 ? chunk : Buffer.concat([this.carry, chunk]);
|
|
251
|
+
if (this.carry.length > MAX_BODY_BYTES) {
|
|
252
|
+
this.overflowed = true;
|
|
253
|
+
this.carry = Buffer.alloc(0);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (this.encoding !== '')
|
|
257
|
+
return;
|
|
258
|
+
if (this.framing === 'sse')
|
|
259
|
+
this.lines(false);
|
|
260
|
+
if (this.framing === 'eventstream')
|
|
261
|
+
this.frames();
|
|
262
|
+
}
|
|
263
|
+
decodedBody() {
|
|
264
|
+
// Bounded: a small compressed body can expand to gigabytes in the host's memory.
|
|
265
|
+
const bound = { maxOutputLength: MAX_BODY_BYTES };
|
|
266
|
+
if (this.encoding === 'gzip' || this.encoding === 'x-gzip')
|
|
267
|
+
return zlib.gunzipSync(this.carry, bound);
|
|
268
|
+
if (this.encoding === 'deflate')
|
|
269
|
+
return zlib.inflateSync(this.carry, bound);
|
|
270
|
+
if (this.encoding === 'br')
|
|
271
|
+
return zlib.brotliDecompressSync(this.carry, bound);
|
|
272
|
+
return this.carry;
|
|
273
|
+
}
|
|
274
|
+
/** The body ended, failed or was abandoned: say what is known, once. */
|
|
275
|
+
finish() {
|
|
276
|
+
if (this.finished)
|
|
277
|
+
return;
|
|
278
|
+
try {
|
|
279
|
+
if (!this.overflowed) {
|
|
280
|
+
this.carry = this.decodedBody();
|
|
281
|
+
if (this.framing === 'sse')
|
|
282
|
+
this.lines(true);
|
|
283
|
+
if (this.framing === 'eventstream')
|
|
284
|
+
this.frames();
|
|
285
|
+
if (this.framing === 'json' && this.carry.length > 0)
|
|
286
|
+
this.absorb(JSON.parse(this.carry.toString('utf8')));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
// An unreadable body costs the usage, nothing more.
|
|
291
|
+
}
|
|
292
|
+
this.finished = true;
|
|
293
|
+
this.carry = Buffer.alloc(0);
|
|
294
|
+
if (this.call.request_id === undefined)
|
|
295
|
+
this.call.request_id = this.bodyRequestId;
|
|
296
|
+
this.onFinish(this.call);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function framingOf(contentType) {
|
|
300
|
+
const type = (contentType || '').toLowerCase();
|
|
301
|
+
if (type.includes('text/event-stream'))
|
|
302
|
+
return 'sse';
|
|
303
|
+
if (type.includes('vnd.amazon.eventstream'))
|
|
304
|
+
return 'eventstream';
|
|
305
|
+
return 'json';
|
|
306
|
+
}
|
|
307
|
+
function requestIdOf(provider, headers) {
|
|
308
|
+
for (const name of REQUEST_ID_HEADERS[provider] || []) {
|
|
309
|
+
const value = headers(name);
|
|
310
|
+
if (value)
|
|
311
|
+
return value;
|
|
312
|
+
}
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
function providerOfHost(host) {
|
|
316
|
+
const name = host.toLowerCase().replace(/:\d+$/, '');
|
|
317
|
+
if (Object.prototype.hasOwnProperty.call(EXACT_HOSTS, name))
|
|
318
|
+
return EXACT_HOSTS[name];
|
|
319
|
+
if (RE_VERTEX_HOST.test(name))
|
|
320
|
+
return 'vertex';
|
|
321
|
+
return RE_BEDROCK_HOST.test(name) ? 'bedrock' : undefined;
|
|
322
|
+
}
|
|
323
|
+
// Everything after `?` is cut first: Gemini's API key can travel there.
|
|
324
|
+
function modelFromPath(rawPath) {
|
|
325
|
+
const pathname = rawPath.split('?')[0] || '';
|
|
326
|
+
const match = RE_BEDROCK_MODEL.exec(pathname) || RE_URL_MODEL.exec(pathname);
|
|
327
|
+
if (!match || !match[1])
|
|
328
|
+
return undefined;
|
|
329
|
+
try {
|
|
330
|
+
const model = modelName(decodeURIComponent(match[1]));
|
|
331
|
+
// An ARN that stopped at its first `/`, or was encoded twice, still names the account.
|
|
332
|
+
return RE_ARN.test(model) ? undefined : model;
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return undefined;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// An inference profile's ARN names the customer's account; the last segment names the model.
|
|
339
|
+
function modelName(model) {
|
|
340
|
+
return model.includes('/') ? model.slice(model.lastIndexOf('/') + 1) : model;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* What the shim knows of a request, from its host, method and URL path alone.
|
|
344
|
+
* Only a POST is a model call: a model listing or a health check is not spend.
|
|
345
|
+
*/
|
|
346
|
+
function callMeta(host, method, requestPath) {
|
|
347
|
+
const provider = providerOfHost(host);
|
|
348
|
+
if (!provider || method.toUpperCase() !== 'POST')
|
|
349
|
+
return undefined;
|
|
350
|
+
return { provider, model: modelFromPath(requestPath) };
|
|
351
|
+
}
|
|
352
|
+
function isAgentEntry(entry) {
|
|
353
|
+
if (!entry)
|
|
354
|
+
return false;
|
|
355
|
+
return AGENT_ENTRIES.has(path.basename(entry).replace(RE_WINDOWS_EXEC, '')) || AGENT_PACKAGES.test(entry);
|
|
356
|
+
}
|
|
357
|
+
function dataDir(vars) {
|
|
358
|
+
if (vars['AGENTWATCH_DATA_DIR'])
|
|
359
|
+
return vars['AGENTWATCH_DATA_DIR'];
|
|
360
|
+
if (process.platform === 'win32' && vars['LOCALAPPDATA'])
|
|
361
|
+
return path.join(vars['LOCALAPPDATA'], 'agentwatch');
|
|
362
|
+
if (vars['XDG_DATA_HOME'])
|
|
363
|
+
return path.join(vars['XDG_DATA_HOME'], 'agentwatch');
|
|
364
|
+
return path.join(vars['HOME'] || os.homedir(), '.local', 'share', 'agentwatch');
|
|
365
|
+
}
|
|
366
|
+
/** Appends records to this process's spool. Every method swallows its own faults. */
|
|
367
|
+
class Spool {
|
|
368
|
+
dir;
|
|
369
|
+
started = new Date().toISOString();
|
|
370
|
+
ancestors;
|
|
371
|
+
seq = 0;
|
|
372
|
+
lines = 0;
|
|
373
|
+
constructor(vars) {
|
|
374
|
+
this.dir = path.join(dataDir(vars), SPOOL_DIR);
|
|
375
|
+
}
|
|
376
|
+
// Edge's hook creates the folder once it holds a credential. No folder, no capture.
|
|
377
|
+
// `agentwatch off` writes a marker beside it, and a session already running still has
|
|
378
|
+
// the shim loaded: asked per call, so nothing made while off is sent after `on`.
|
|
379
|
+
armed() {
|
|
380
|
+
try {
|
|
381
|
+
return fs.statSync(this.dir).isDirectory() && !fs.existsSync(path.join(path.dirname(this.dir), DISABLED_MARKER));
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Read the ancestry now, while the launching shell still stands.
|
|
389
|
+
*
|
|
390
|
+
* ponytail: one `ps -A` per process, at its first provider call, so a process with
|
|
391
|
+
* no such call pays nothing. A process already orphaned by then (`cmd &` in a
|
|
392
|
+
* shell that exited) attaches to no session, and is dropped and counted.
|
|
393
|
+
*/
|
|
394
|
+
rememberAncestors() {
|
|
395
|
+
if (this.ancestors !== undefined)
|
|
396
|
+
return;
|
|
397
|
+
try {
|
|
398
|
+
const ps = PS_PATHS.find((candidate) => fs.existsSync(candidate));
|
|
399
|
+
if (!ps) {
|
|
400
|
+
this.ancestors = [];
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
// No inherited environment: it holds the customer's keys. TZ stays, because a
|
|
404
|
+
// start time is compared as text with the one the hook's own `ps` printed.
|
|
405
|
+
const listing = childProcess.spawnSync(ps, ['-A', '-o', 'pid=,ppid=,lstart='], {
|
|
406
|
+
encoding: 'utf8',
|
|
407
|
+
timeout: PS_TIMEOUT_MS,
|
|
408
|
+
maxBuffer: MAX_BODY_BYTES,
|
|
409
|
+
windowsHide: true,
|
|
410
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
411
|
+
env: process.env['TZ'] ? { LC_ALL: 'C', TZ: process.env['TZ'] } : { LC_ALL: 'C' }
|
|
412
|
+
});
|
|
413
|
+
this.ancestors = walkAncestors(typeof listing.stdout === 'string' ? listing.stdout : '', process.pid);
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
this.ancestors = [];
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
open(file) {
|
|
420
|
+
return fs.openSync(path.join(this.dir, file), fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | (fs.constants.O_NOFOLLOW || 0), 0o600);
|
|
421
|
+
}
|
|
422
|
+
/** One synchronous append, so a call made just before exit is on disk. */
|
|
423
|
+
write(call) {
|
|
424
|
+
try {
|
|
425
|
+
this.rememberAncestors();
|
|
426
|
+
const line = JSON.stringify({
|
|
427
|
+
pid: process.pid,
|
|
428
|
+
started: this.started,
|
|
429
|
+
ancestors: this.ancestors,
|
|
430
|
+
at: new Date().toISOString(),
|
|
431
|
+
seq: this.seq++,
|
|
432
|
+
script: process.argv[1] ? path.basename(process.argv[1]) : undefined,
|
|
433
|
+
...call
|
|
434
|
+
});
|
|
435
|
+
const fd = this.open(`${process.pid}.jsonl`);
|
|
436
|
+
try {
|
|
437
|
+
// The hook renames a file to consume it, so an empty one is a new count.
|
|
438
|
+
if (fs.fstatSync(fd).size === 0)
|
|
439
|
+
this.lines = 0;
|
|
440
|
+
if (this.lines >= MAX_LINES_PER_FILE) {
|
|
441
|
+
this.drop();
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
fs.writeSync(fd, `${line}\n`);
|
|
445
|
+
this.lines++;
|
|
446
|
+
}
|
|
447
|
+
finally {
|
|
448
|
+
fs.closeSync(fd);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
catch {
|
|
452
|
+
// A fault costs a record, never the run.
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
// One byte per call past the bound: the file's size is the count the hook reads.
|
|
456
|
+
drop() {
|
|
457
|
+
const fd = this.open(`${process.pid}.dropped`);
|
|
458
|
+
try {
|
|
459
|
+
fs.writeSync(fd, '.');
|
|
460
|
+
}
|
|
461
|
+
finally {
|
|
462
|
+
fs.closeSync(fd);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
function walkAncestors(listing, pid) {
|
|
467
|
+
const rows = new Map();
|
|
468
|
+
for (const line of listing.split('\n')) {
|
|
469
|
+
const match = RE_PS_ROW.exec(line);
|
|
470
|
+
if (match)
|
|
471
|
+
rows.set(Number(match[1]), { ppid: Number(match[2]), started: match[3] });
|
|
472
|
+
}
|
|
473
|
+
const chain = [];
|
|
474
|
+
const seen = new Set([pid]);
|
|
475
|
+
let current = rows.get(pid);
|
|
476
|
+
while (current && current.ppid > 1 && !seen.has(current.ppid) && chain.length < MAX_ANCESTORS) {
|
|
477
|
+
const parent = rows.get(current.ppid);
|
|
478
|
+
if (!parent)
|
|
479
|
+
break;
|
|
480
|
+
chain.push({ pid: current.ppid, started: parent.started });
|
|
481
|
+
seen.add(current.ppid);
|
|
482
|
+
current = parent;
|
|
483
|
+
}
|
|
484
|
+
return chain;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Whether a finished call is worth a record: a failure always (status only), a
|
|
488
|
+
* success only when it carried usage. A success with none is no model call
|
|
489
|
+
* (`count_tokens`), or a body the shim could not read.
|
|
490
|
+
*/
|
|
491
|
+
function worthRecording(call) {
|
|
492
|
+
return call.status < 200 || call.status >= 300 || call.usage !== undefined;
|
|
493
|
+
}
|
|
494
|
+
function installFetch(spool) {
|
|
495
|
+
const original = globalThis.fetch;
|
|
496
|
+
if (typeof original !== 'function')
|
|
497
|
+
return;
|
|
498
|
+
const wrapped = function fetch(input, init) {
|
|
499
|
+
let meta;
|
|
500
|
+
try {
|
|
501
|
+
meta = metaOfFetch(input, init);
|
|
502
|
+
if (meta && !spool.armed())
|
|
503
|
+
meta = undefined;
|
|
504
|
+
if (meta)
|
|
505
|
+
spool.rememberAncestors();
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
meta = undefined;
|
|
509
|
+
}
|
|
510
|
+
const pending = original.call(this, input, init);
|
|
511
|
+
if (!meta)
|
|
512
|
+
return pending;
|
|
513
|
+
const call = meta;
|
|
514
|
+
return pending.then((response) => {
|
|
515
|
+
try {
|
|
516
|
+
return tapResponse(response, call, spool);
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
return response;
|
|
520
|
+
}
|
|
521
|
+
});
|
|
522
|
+
};
|
|
523
|
+
globalThis.fetch = wrapped;
|
|
524
|
+
}
|
|
525
|
+
function metaOfFetch(input, init) {
|
|
526
|
+
const request = input instanceof Request ? input : undefined;
|
|
527
|
+
const url = new URL(request ? request.url : String(input));
|
|
528
|
+
const method = (init && init.method) || (request && request.method) || 'GET';
|
|
529
|
+
return callMeta(url.host, method, url.pathname);
|
|
530
|
+
}
|
|
531
|
+
/*
|
|
532
|
+
* The body is passed through chunk by chunk as the host asks for it: no read-ahead
|
|
533
|
+
* (highWaterMark 0), no tee, so the host's backpressure and its choice not to read
|
|
534
|
+
* are unchanged. The record is on disk before the host sees the end of the body.
|
|
535
|
+
*/
|
|
536
|
+
function tapResponse(response, meta, spool) {
|
|
537
|
+
const headerOf = (name) => response.headers.get(name) || undefined;
|
|
538
|
+
const finished = (call) => {
|
|
539
|
+
if (worthRecording(call))
|
|
540
|
+
spool.write(call);
|
|
541
|
+
};
|
|
542
|
+
const tap = new ResponseTap(meta, response.status, headerOf, finished, true);
|
|
543
|
+
if (!response.ok || !response.body) {
|
|
544
|
+
tap.finish();
|
|
545
|
+
return response;
|
|
546
|
+
}
|
|
547
|
+
const source = response.body.getReader();
|
|
548
|
+
const safely = (work) => {
|
|
549
|
+
try {
|
|
550
|
+
work();
|
|
551
|
+
}
|
|
552
|
+
catch {
|
|
553
|
+
// A fault costs a record, never the run.
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
const body = new ReadableStream({
|
|
557
|
+
type: 'bytes',
|
|
558
|
+
async pull(controller) {
|
|
559
|
+
// A loop: with highWaterMark 0 a pull that enqueues nothing is not called again,
|
|
560
|
+
// so an empty chunk would leave the host's read waiting for ever.
|
|
561
|
+
for (;;) {
|
|
562
|
+
let read;
|
|
563
|
+
try {
|
|
564
|
+
read = await source.read();
|
|
565
|
+
}
|
|
566
|
+
catch (error) {
|
|
567
|
+
safely(() => tap.finish());
|
|
568
|
+
controller.error(error);
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
if (read.done) {
|
|
572
|
+
safely(() => tap.finish());
|
|
573
|
+
controller.close();
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const chunk = read.value;
|
|
577
|
+
// A copy: the stream takes ownership of `chunk` on enqueue.
|
|
578
|
+
safely(() => tap.feed(Buffer.from(chunk)));
|
|
579
|
+
if (chunk.byteLength > 0) {
|
|
580
|
+
controller.enqueue(chunk);
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
},
|
|
585
|
+
cancel(reason) {
|
|
586
|
+
safely(() => tap.finish());
|
|
587
|
+
return source.cancel(reason);
|
|
588
|
+
}
|
|
589
|
+
}, { highWaterMark: 0 });
|
|
590
|
+
const tapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
591
|
+
Object.defineProperty(tapped, 'url', { value: response.url });
|
|
592
|
+
Object.defineProperty(tapped, 'redirected', { value: response.redirected });
|
|
593
|
+
Object.defineProperty(tapped, 'type', { value: response.type });
|
|
594
|
+
return tapped;
|
|
595
|
+
}
|
|
596
|
+
/*
|
|
597
|
+
* `emit` is wrapped, not `on`: a 'data' listener would switch the stream to flowing
|
|
598
|
+
* mode, and a 'response' listener would stop Node discarding an unread response. A
|
|
599
|
+
* patched `emit` sees 'data' on every read path (flowing, `read()`, async iterator,
|
|
600
|
+
* `pipe`) and changes none of them.
|
|
601
|
+
*/
|
|
602
|
+
function watchRequest(request, spool, seen) {
|
|
603
|
+
if (seen.has(request))
|
|
604
|
+
return;
|
|
605
|
+
seen.add(request);
|
|
606
|
+
const host = request.host || String(request.getHeader('host') || '');
|
|
607
|
+
const meta = callMeta(host, request.method, request.path);
|
|
608
|
+
if (!meta || !spool.armed())
|
|
609
|
+
return;
|
|
610
|
+
spool.rememberAncestors();
|
|
611
|
+
const emit = request.emit;
|
|
612
|
+
request.emit = function patched(name, ...args) {
|
|
613
|
+
if (name === 'response') {
|
|
614
|
+
try {
|
|
615
|
+
tapIncoming(args[0], meta, spool);
|
|
616
|
+
}
|
|
617
|
+
catch {
|
|
618
|
+
// A fault costs a record, never the run.
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
return emit.call(this, name, ...args);
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
function tapIncoming(response, meta, spool) {
|
|
625
|
+
const headerOf = (name) => {
|
|
626
|
+
const value = response.headers[name];
|
|
627
|
+
return Array.isArray(value) ? value[0] : value;
|
|
628
|
+
};
|
|
629
|
+
const status = response.statusCode || 0;
|
|
630
|
+
const tap = new ResponseTap(meta, status, headerOf, (call) => {
|
|
631
|
+
if (worthRecording(call))
|
|
632
|
+
spool.write(call);
|
|
633
|
+
}, false);
|
|
634
|
+
if (status < 200 || status >= 300) {
|
|
635
|
+
tap.finish();
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
const emit = response.emit;
|
|
639
|
+
response.emit = function patched(name, ...args) {
|
|
640
|
+
try {
|
|
641
|
+
if (name === 'data')
|
|
642
|
+
tap.feed(typeof args[0] === 'string' ? Buffer.from(args[0]) : args[0]);
|
|
643
|
+
if (name === 'end' || name === 'close' || name === 'error')
|
|
644
|
+
tap.finish();
|
|
645
|
+
}
|
|
646
|
+
catch {
|
|
647
|
+
// A fault costs a record, never the run.
|
|
648
|
+
}
|
|
649
|
+
return emit.call(this, name, ...args);
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
function installHttps(spool) {
|
|
653
|
+
const seen = new WeakSet();
|
|
654
|
+
for (const method of ['request', 'get']) {
|
|
655
|
+
const original = https[method];
|
|
656
|
+
https[method] = function wrapped(...args) {
|
|
657
|
+
const request = original.apply(this, args);
|
|
658
|
+
try {
|
|
659
|
+
watchRequest(request, spool, seen);
|
|
660
|
+
}
|
|
661
|
+
catch {
|
|
662
|
+
// A fault costs a record, never the run.
|
|
663
|
+
}
|
|
664
|
+
return request;
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
// `import { request } from 'node:https'` reads a snapshot of the exports.
|
|
668
|
+
nodeModule.syncBuiltinESMExports();
|
|
669
|
+
}
|
|
670
|
+
function install() {
|
|
671
|
+
if (process.env['AGENTWATCH_CAPTURE'] === 'off' || isAgentEntry(process.argv[1]) || isAgentEntry(process.execPath))
|
|
672
|
+
return;
|
|
673
|
+
const spool = new Spool(process.env);
|
|
674
|
+
installFetch(spool);
|
|
675
|
+
installHttps(spool);
|
|
676
|
+
}
|
|
677
|
+
try {
|
|
678
|
+
install();
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
// Never into the host.
|
|
682
|
+
}
|
|
683
|
+
// For the conformance suite only; `--require` ignores it.
|
|
684
|
+
function replay(meta, status, headers, chunks) {
|
|
685
|
+
const call = callMeta(meta.host, meta.method, meta.path);
|
|
686
|
+
if (!call)
|
|
687
|
+
return undefined;
|
|
688
|
+
let result;
|
|
689
|
+
const tap = new ResponseTap(call, status, (name) => headers[name], (finished) => {
|
|
690
|
+
result = worthRecording(finished) ? finished : undefined;
|
|
691
|
+
}, false);
|
|
692
|
+
for (const chunk of chunks)
|
|
693
|
+
tap.feed(chunk);
|
|
694
|
+
tap.finish();
|
|
695
|
+
return result;
|
|
696
|
+
}
|
|
697
|
+
module.exports = { replay, isAgentEntry, walkAncestors };
|