@agimon-ai/po-log 0.0.0-alpha.21 → 0.0.0-alpha.211
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/LICENSE +21 -149
- package/README.md +4 -10
- package/dist/apiContracts.cjs +81 -57
- package/dist/apiContracts.cjs.map +1 -1
- package/dist/apiContracts.d.mts +2 -2
- package/dist/apiContracts.mjs +82 -58
- package/dist/apiContracts.mjs.map +1 -1
- package/dist/extensions/native.mjs +403 -0
- package/dist/extensions/native.mjs.map +1 -0
- package/dist/extensions/server.cjs +835 -296
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.d.mts.map +1 -1
- package/dist/extensions/server.mjs +837 -298
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +735 -300
- package/dist/extensions/web.mjs.map +1 -1
- package/dist/findings-Bo4IHNpr.cjs +165 -0
- package/dist/findings-Bo4IHNpr.cjs.map +1 -0
- package/dist/findings-DAKeRG4O.mjs +160 -0
- package/dist/findings-DAKeRG4O.mjs.map +1 -0
- package/dist/http-D7IHAk6Y.mjs +29 -0
- package/dist/http-D7IHAk6Y.mjs.map +1 -0
- package/dist/http-Dhn2bpMh.cjs +40 -0
- package/dist/http-Dhn2bpMh.cjs.map +1 -0
- package/dist/index.cjs +3 -2
- package/dist/index.d.mts +8 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/{metrics-jCZe13Xg.cjs → metrics-Bml7TSZq.cjs} +9 -160
- package/dist/metrics-Bml7TSZq.cjs.map +1 -0
- package/dist/{metrics-DywCpDJ_.mjs → metrics-DwfV84Fy.mjs} +2 -159
- package/dist/metrics-DwfV84Fy.mjs.map +1 -0
- package/dist/metrics.cjs +3 -2
- package/dist/metrics.mjs +3 -1
- package/dist/{metricsSource-Cy8f47Q0.cjs → metricsSource-CF3cp-sf.cjs} +16 -43
- package/dist/metricsSource-CF3cp-sf.cjs.map +1 -0
- package/dist/{metricsSource-BaoBR_Ia.mjs → metricsSource-I5p5_t2L.mjs} +9 -42
- package/dist/metricsSource-I5p5_t2L.mjs.map +1 -0
- package/dist/{metricsSource-DNT8BrTF.d.mts → metricsSource-sO8OpIes.d.mts} +14 -3
- package/dist/metricsSource-sO8OpIes.d.mts.map +1 -0
- package/dist/metricsSource.cjs +1 -1
- package/dist/metricsSource.d.mts +1 -13
- package/dist/metricsSource.d.mts.map +1 -1
- package/dist/metricsSource.mjs +1 -1
- package/dist/metricsStore-BcjSOJGN.mjs +44 -0
- package/dist/metricsStore-BcjSOJGN.mjs.map +1 -0
- package/dist/metricsStore-nGI-c5NH.cjs +79 -0
- package/dist/metricsStore-nGI-c5NH.cjs.map +1 -0
- package/dist/metricsStore.cjs +476 -0
- package/dist/metricsStore.cjs.map +1 -0
- package/dist/metricsStore.d.mts +63 -0
- package/dist/metricsStore.d.mts.map +1 -0
- package/dist/metricsStore.mjs +471 -0
- package/dist/metricsStore.mjs.map +1 -0
- package/dist/po-runtime-identity.json +1 -0
- package/llms.txt +5 -1
- package/locales/vi.json +202 -0
- package/locales/zh-CN.json +202 -0
- package/package.json +81 -18
- package/src/prompts/codemode-how-to-logsink/SKILL.md +80 -0
- package/src/prompts/help-how-to-log/SKILL.md +28 -0
- package/dist/metrics-DywCpDJ_.mjs.map +0 -1
- package/dist/metrics-jCZe13Xg.cjs.map +0 -1
- package/dist/metricsSource-BaoBR_Ia.mjs.map +0 -1
- package/dist/metricsSource-Cy8f47Q0.cjs.map +0 -1
- package/dist/metricsSource-DNT8BrTF.d.mts.map +0 -1
- package/src/prompts/po-debug-agent/SKILL.md +0 -28
|
@@ -1,160 +1,3 @@
|
|
|
1
|
-
//#region src/services/findings/index.ts
|
|
2
|
-
/** Below this, the prompt prefix is churning and cache writes are being wasted. */
|
|
3
|
-
const LOW_CACHE_HIT_RATIO = .3;
|
|
4
|
-
/** Cache hit rate is meaningless on a session that has barely sent anything. */
|
|
5
|
-
const MIN_CACHE_SAMPLE_TOKENS = 5e4;
|
|
6
|
-
/** A tool is "expensive" only well clear of the session's typical turn. */
|
|
7
|
-
const EXPENSIVE_TOOL_RATIO = 1.5;
|
|
8
|
-
const MIN_TOOL_SAMPLES = 3;
|
|
9
|
-
const FAILING_TOOL_RATIO = .25;
|
|
10
|
-
const MIN_TOOL_CALLS = 3;
|
|
11
|
-
/** Sustained input this large per turn means context is carried, not scoped. */
|
|
12
|
-
const HEAVY_TURN_INPUT_TOKENS = 12e4;
|
|
13
|
-
const MIN_TURNS_FOR_AVERAGE = 3;
|
|
14
|
-
/** Tool calls per turn above this reads as search thrash rather than progress. */
|
|
15
|
-
const BUSY_TURN_TOOL_CALLS = 8;
|
|
16
|
-
const RATE_LIMITED = "rate_limited";
|
|
17
|
-
/** Kept short because the finding's subject column already says "provider". */
|
|
18
|
-
const SHORT_CATEGORY = {
|
|
19
|
-
[RATE_LIMITED]: "rate limited",
|
|
20
|
-
provider_unavailable: "unavailable"
|
|
21
|
-
};
|
|
22
|
-
const SEVERITY_RANK = {
|
|
23
|
-
critical: 0,
|
|
24
|
-
warning: 1,
|
|
25
|
-
info: 2
|
|
26
|
-
};
|
|
27
|
-
const PERCENT = 100;
|
|
28
|
-
const MILLION = 1e6;
|
|
29
|
-
const THOUSAND = 1e3;
|
|
30
|
-
const COMPACT_DECIMALS = 1;
|
|
31
|
-
const HEALTHY_FINDING = {
|
|
32
|
-
id: "healthy",
|
|
33
|
-
severity: "info",
|
|
34
|
-
subject: "session",
|
|
35
|
-
detail: "no failures, no outliers",
|
|
36
|
-
action: "nothing to act on yet"
|
|
37
|
-
};
|
|
38
|
-
function compact(value) {
|
|
39
|
-
if (value >= MILLION) return `${(value / MILLION).toFixed(COMPACT_DECIMALS)}M`;
|
|
40
|
-
if (value >= THOUSAND) return `${Math.round(value / THOUSAND)}k`;
|
|
41
|
-
return String(Math.round(value));
|
|
42
|
-
}
|
|
43
|
-
function percent(value) {
|
|
44
|
-
return `${Math.round(value * PERCENT)}%`;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Median rather than mean: one pathological tool would drag a mean up far
|
|
48
|
-
* enough to hide itself from the comparison that is meant to catch it.
|
|
49
|
-
*/
|
|
50
|
-
function medianTokens(tools) {
|
|
51
|
-
const sampled = tools.map((tool) => tool.p90Tokens).filter((tokens) => tokens !== void 0).sort((left, right) => left - right);
|
|
52
|
-
if (sampled.length === 0) return 0;
|
|
53
|
-
const middle = Math.floor(sampled.length / 2);
|
|
54
|
-
const lower = sampled[middle - 1] ?? 0;
|
|
55
|
-
const upper = sampled[middle] ?? 0;
|
|
56
|
-
return sampled.length % 2 === 0 ? (lower + upper) / 2 : upper;
|
|
57
|
-
}
|
|
58
|
-
function cacheFinding(snapshot) {
|
|
59
|
-
const { cacheRead, cacheWrite, input } = snapshot.tokens;
|
|
60
|
-
const cacheable = cacheRead + input;
|
|
61
|
-
if (cacheable < MIN_CACHE_SAMPLE_TOKENS) return void 0;
|
|
62
|
-
const hitRatio = cacheRead / cacheable;
|
|
63
|
-
if (hitRatio >= LOW_CACHE_HIT_RATIO) return void 0;
|
|
64
|
-
return {
|
|
65
|
-
id: "low-cache-hit",
|
|
66
|
-
severity: "warning",
|
|
67
|
-
subject: "cache",
|
|
68
|
-
detail: `${percent(hitRatio)} hit · ${compact(cacheWrite)} written`,
|
|
69
|
-
action: "pin stable context first"
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
function expensiveToolFinding(snapshot) {
|
|
73
|
-
const median = medianTokens(snapshot.toolCost);
|
|
74
|
-
if (median <= 0) return void 0;
|
|
75
|
-
const worst = snapshot.toolCost.find((tool) => tool.samples >= MIN_TOOL_SAMPLES && (tool.p90Tokens ?? 0) >= median * EXPENSIVE_TOOL_RATIO);
|
|
76
|
-
if (!worst?.p90Tokens) return void 0;
|
|
77
|
-
return {
|
|
78
|
-
id: "expensive-tool",
|
|
79
|
-
severity: "warning",
|
|
80
|
-
subject: worst.name,
|
|
81
|
-
detail: `${compact(worst.p90Tokens)} p90 · ${Math.round(worst.p90Tokens / median)}× median`,
|
|
82
|
-
action: "narrow what it pulls in"
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
function failingToolFindings(snapshot) {
|
|
86
|
-
return snapshot.toolCost.filter((tool) => tool.calls >= MIN_TOOL_CALLS && tool.failed / tool.calls >= FAILING_TOOL_RATIO).sort((left, right) => right.failed - left.failed).map((tool) => ({
|
|
87
|
-
id: `failing-tool:${tool.name}`,
|
|
88
|
-
severity: "critical",
|
|
89
|
-
subject: tool.name,
|
|
90
|
-
detail: `${tool.failed} of ${tool.calls} failed`,
|
|
91
|
-
action: "retries burn tokens"
|
|
92
|
-
}));
|
|
93
|
-
}
|
|
94
|
-
function abortedTurnFinding(snapshot) {
|
|
95
|
-
if (snapshot.abortedTurns + snapshot.failedTurns === 0) return void 0;
|
|
96
|
-
return {
|
|
97
|
-
id: "redone-turns",
|
|
98
|
-
severity: "critical",
|
|
99
|
-
subject: "turns",
|
|
100
|
-
detail: `${snapshot.abortedTurns} aborted · ${snapshot.failedTurns} failed`,
|
|
101
|
-
action: "paid for, then thrown away"
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
function providerFinding(snapshot) {
|
|
105
|
-
const category = snapshot.failureCategories.find((entry) => entry.name in SHORT_CATEGORY);
|
|
106
|
-
if (!category) return void 0;
|
|
107
|
-
return {
|
|
108
|
-
id: `provider:${category.name}`,
|
|
109
|
-
severity: "warning",
|
|
110
|
-
subject: "provider",
|
|
111
|
-
detail: `${category.count} × ${SHORT_CATEGORY[category.name] ?? category.name}`,
|
|
112
|
-
action: category.name === RATE_LIMITED ? "back off or drop concurrency" : "retry or switch provider"
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
function contextFinding(snapshot) {
|
|
116
|
-
if (snapshot.turns < MIN_TURNS_FOR_AVERAGE) return void 0;
|
|
117
|
-
const perTurn = snapshot.tokens.input / snapshot.turns;
|
|
118
|
-
if (perTurn < HEAVY_TURN_INPUT_TOKENS) return void 0;
|
|
119
|
-
return {
|
|
120
|
-
id: "heavy-context",
|
|
121
|
-
severity: "warning",
|
|
122
|
-
subject: "context",
|
|
123
|
-
detail: `${compact(perTurn)} input tok/turn`,
|
|
124
|
-
action: "compact or split the task"
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
function toolChurnFinding(snapshot) {
|
|
128
|
-
if (snapshot.turns < MIN_TURNS_FOR_AVERAGE) return void 0;
|
|
129
|
-
const perTurn = snapshot.toolCalls / snapshot.turns;
|
|
130
|
-
if (perTurn < BUSY_TURN_TOOL_CALLS) return void 0;
|
|
131
|
-
return {
|
|
132
|
-
id: "tool-churn",
|
|
133
|
-
severity: "info",
|
|
134
|
-
subject: "tools",
|
|
135
|
-
detail: `${perTurn.toFixed(1)} calls/turn`,
|
|
136
|
-
action: "give it a narrower target"
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Ranked most-actionable first. Severity leads because a failing tool costs
|
|
141
|
-
* more than an inefficient one, and the panel is read top-down under a
|
|
142
|
-
* height limit.
|
|
143
|
-
*/
|
|
144
|
-
function deriveFindings(snapshot) {
|
|
145
|
-
const findings = [
|
|
146
|
-
...failingToolFindings(snapshot),
|
|
147
|
-
abortedTurnFinding(snapshot),
|
|
148
|
-
providerFinding(snapshot),
|
|
149
|
-
cacheFinding(snapshot),
|
|
150
|
-
expensiveToolFinding(snapshot),
|
|
151
|
-
contextFinding(snapshot),
|
|
152
|
-
toolChurnFinding(snapshot)
|
|
153
|
-
].filter((finding) => finding !== void 0);
|
|
154
|
-
if (findings.length === 0) return snapshot.events > 0 ? [HEALTHY_FINDING] : [];
|
|
155
|
-
return findings.sort((left, right) => SEVERITY_RANK[left.severity] - SEVERITY_RANK[right.severity]);
|
|
156
|
-
}
|
|
157
|
-
//#endregion
|
|
158
1
|
//#region src/services/metrics/index.ts
|
|
159
2
|
/**
|
|
160
3
|
* Session-local aggregation of the log records the Pi telemetry extension
|
|
@@ -563,11 +406,17 @@ Object.defineProperty(exports, "TURN_FINISHED_RECORD", {
|
|
|
563
406
|
return TURN_FINISHED_RECORD;
|
|
564
407
|
}
|
|
565
408
|
});
|
|
566
|
-
Object.defineProperty(exports, "
|
|
409
|
+
Object.defineProperty(exports, "bucketIndex", {
|
|
410
|
+
enumerable: true,
|
|
411
|
+
get: function() {
|
|
412
|
+
return bucketIndex;
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
Object.defineProperty(exports, "bucketedQuantile", {
|
|
567
416
|
enumerable: true,
|
|
568
417
|
get: function() {
|
|
569
|
-
return
|
|
418
|
+
return bucketedQuantile;
|
|
570
419
|
}
|
|
571
420
|
});
|
|
572
421
|
|
|
573
|
-
//# sourceMappingURL=metrics-
|
|
422
|
+
//# sourceMappingURL=metrics-Bml7TSZq.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metrics-Bml7TSZq.cjs","names":[],"sources":["../src/services/metrics/index.ts"],"sourcesContent":["/**\n * Session-local aggregation of the log records the Pi telemetry extension\n * already emits.\n *\n * The aggregator is fed `(recordName, attributes)` pairs rather than Pi events\n * so it can only ever see what the sink sees: no extra instrumentation is added\n * for metrics, and nothing here depends on a live sink. Everything is scoped to\n * the current process, so there is no persistence and no query API.\n */\n\n/** Record names the aggregator derives numbers from. */\nexport const TOOL_RESULT_RECORD = 'pi.tool_result';\nexport const API_ERROR_RECORD = 'pi.api_error';\nexport const TURN_FINISHED_RECORD = 'pi.turn.finished';\nexport const TURN_FAILED_RECORD = 'pi.turn.failed';\nexport const TOOL_TOKEN_SAMPLE_RECORD = 'pi.tool_token_sample';\n\nconst UNKNOWN_TOOL = 'unknown';\nconst TOOL_ERROR_CODE = 'tool';\nconst RECORD_PREFIX = 'pi.';\nconst DEFAULT_MAX_RECENT_ERRORS = 8;\n/** Maximum entries retained in each cardinality-bearing metrics map, including overflow. */\nexport const MAX_RETAINED_METRIC_NAMES = 128;\n/** Snapshot row used to account for names that arrive after a metrics map reaches its bound. */\nexport const METRIC_OVERFLOW_NAME = '__overflow__';\nconst P95_QUANTILE = 0.95;\nconst P90_QUANTILE = 0.9;\nconst ABORTED_OUTCOME = 'aborted';\n\n/**\n * Failure taxonomy, mirroring log-sink's AgentIssueCategory closely enough that\n * a session-local category reads the same as the one the sink would report for\n * the same record. Rate limiting and provider outages are split out because\n * they call for different action: back off versus retry elsewhere.\n */\nconst RATE_LIMIT_STATUS = 429;\nconst SERVER_ERROR_STATUS = 500;\nconst CATEGORY_TOOL_FAILURE = 'tool_failure';\nconst CATEGORY_RATE_LIMITED = 'rate_limited';\nconst CATEGORY_PROVIDER_UNAVAILABLE = 'provider_unavailable';\nconst CATEGORY_API_ERROR = 'api_error';\nconst CATEGORY_ABORTED = 'aborted';\nconst CATEGORY_TURN_FAILED = 'turn_failed';\nconst CATEGORY_LOG_ERROR = 'log_error';\n\n/**\n * Latency is kept as a fixed logarithmic histogram rather than a sample array,\n * so a long session cannot grow the retained state without bound. Each bucket\n * is 10% wider than the last, which keeps the reported p95 within about 10% of\n * the true value while capping the state at one small map per tool.\n */\nconst LATENCY_BUCKET_GROWTH = 1.1;\nconst LATENCY_BUCKET_LOG_BASE = Math.log(LATENCY_BUCKET_GROWTH);\nconst MINIMUM_SAMPLE_MS = 1;\n\n/** Bucket ceiling per tool: covers 1ms to roughly an hour at 10% resolution. */\nexport const MAX_RETAINED_STATE_PER_TOOL = 160;\n\n/**\n * Token distributions reuse the same histogram at a higher ceiling: a turn's\n * total can run to millions once cache reads are counted, which the latency\n * ceiling would saturate and report as a flat maximum.\n */\nexport const MAX_RETAINED_TOKEN_BUCKETS = 200;\n\nexport interface LogMetricsTokenTotals {\n input: number;\n output: number;\n total: number;\n /**\n * Cached prompt tokens billed at the read rate. Held separately from `input`\n * because the ratio between them is the session's cache hit rate, which is\n * the single largest cost lever a user controls.\n */\n cacheRead: number;\n cacheWrite: number;\n}\n\nexport interface LogMetricsToolLatency {\n name: string;\n calls: number;\n p95Ms?: number;\n /** Buckets currently held for this tool, bounded by MAX_RETAINED_STATE_PER_TOOL. */\n retainedStateSize: number;\n}\n\nexport interface LogMetricsEventCount {\n name: string;\n count: number;\n}\n\nexport interface LogMetricsOperationDuration {\n name: string;\n calls: number;\n p95Ms?: number;\n retainedStateSize: number;\n}\n\nexport interface LogMetricsError {\n at: number;\n event: string;\n message: string;\n code: string;\n}\n\n/**\n * What a tool costs, rather than how long it takes.\n *\n * `p90Tokens` is the 90th percentile of the *turn* total for turns this tool\n * took part in, which is the only attribution the Pi extension emits\n * (`token_attribution: 'toolCallTurn'`). It answers \"when this tool runs, how\n * expensive is the turn\", not \"this tool consumed N tokens\" — a turn with\n * several tool calls attributes its total to each of them.\n */\nexport interface LogMetricsToolCost {\n name: string;\n calls: number;\n failed: number;\n /** Turns carrying usage that this tool took part in, i.e. the p90 sample count. */\n samples: number;\n p90Tokens?: number;\n}\n\nexport interface LogMetricsSnapshot {\n events: number;\n errors: number;\n toolCalls: number;\n failedToolCalls: number;\n /** Turns that reported usage, i.e. the denominator for per-turn averages. */\n turns: number;\n abortedTurns: number;\n failedTurns: number;\n tokens: LogMetricsTokenTotals;\n cost: number;\n toolLatency: LogMetricsToolLatency[];\n toolCost: LogMetricsToolCost[];\n failureCategories: LogMetricsEventCount[];\n eventVolume: LogMetricsEventCount[];\n packageEvents: LogMetricsEventCount[];\n sanitizedFailures: number;\n operationDuration: LogMetricsOperationDuration[];\n recentErrors: LogMetricsError[];\n}\n\nexport interface LogMetricsAggregatorOptions {\n now?: () => number;\n maxRecentErrors?: number;\n /** Per-map cardinality bound for tests, capped at MAX_RETAINED_METRIC_NAMES. */\n maxMetricNames?: number;\n}\n\n/** The slice of the aggregator the telemetry extension needs. */\nexport interface LogMetricsRecorder {\n record(name: string, attributes: Record<string, unknown>): void;\n}\n\ninterface ToolLatencyState {\n calls: number;\n samples: number;\n buckets: Map<number, number>;\n}\n\nexport interface SampleState {\n samples: number;\n buckets: Map<number, number>;\n}\n\nfunction emptySampleState(): SampleState {\n return { samples: 0, buckets: new Map<number, number>() };\n}\n\nfunction readNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction safeMetricName(value: string): string {\n const normalized = value.replace(/[^a-zA-Z0-9@/._:-]/g, '_').slice(0, 128);\n return normalized || 'unknown';\n}\n\n/** Keeps an existing key, admits a new one when space remains, or selects the overflow row. */\nfunction boundedMetricName<T>(map: Map<string, T>, name: string, maxNames: number): string {\n if (map.has(name)) return name;\n return map.size < maxNames - 1 ? name : METRIC_OVERFLOW_NAME;\n}\n\nfunction incrementBounded(map: Map<string, number>, name: string, maxNames: number): void {\n const boundedName = boundedMetricName(map, name, maxNames);\n map.set(boundedName, (map.get(boundedName) ?? 0) + 1);\n}\n\nfunction boundedState<T>(map: Map<string, T>, name: string, maxNames: number, create: () => T): T {\n const boundedName = boundedMetricName(map, name, maxNames);\n const state = map.get(boundedName) ?? create();\n map.set(boundedName, state);\n return state;\n}\n\nexport function bucketIndex(value: number, cap: number): number {\n const index = Math.ceil(Math.log(Math.max(value, MINIMUM_SAMPLE_MS)) / LATENCY_BUCKET_LOG_BASE);\n return Math.min(Math.max(index, 0), cap - 1);\n}\n\nfunction bucketUpperBound(index: number): number {\n return LATENCY_BUCKET_GROWTH ** index;\n}\n\nfunction observe(state: SampleState, value: number, cap: number): void {\n const bucket = bucketIndex(value, cap);\n state.buckets.set(bucket, (state.buckets.get(bucket) ?? 0) + 1);\n state.samples += 1;\n}\n\n/**\n * The upper edge of the first bucket whose cumulative count crosses the\n * quantile. Reporting the edge rather than a bucket midpoint keeps the answer\n * an upper bound, so a single 250ms call never reports faster than 250ms.\n */\nexport function bucketedQuantile(state: SampleState, quantile: number): number | undefined {\n if (state.samples === 0) return undefined;\n\n const target = state.samples * quantile;\n const indexes = [...state.buckets.keys()].sort((left, right) => left - right);\n let cumulative = 0;\n let selected = indexes[0] as number;\n for (const index of indexes) {\n cumulative += state.buckets.get(index) ?? 0;\n selected = index;\n if (cumulative >= target) break;\n }\n return Math.round(bucketUpperBound(selected));\n}\n\nfunction bucketedP95(state: SampleState): number | undefined {\n return bucketedQuantile(state, P95_QUANTILE);\n}\n\n/** Categorises an HTTP failure so the action it implies is distinguishable. */\nfunction apiErrorCategory(status: number): string {\n if (status === RATE_LIMIT_STATUS) return CATEGORY_RATE_LIMITED;\n if (status >= SERVER_ERROR_STATUS) return CATEGORY_PROVIDER_UNAVAILABLE;\n return CATEGORY_API_ERROR;\n}\n\n/** Strips the `pi.` prefix so an error entry reads as the event it came from. */\nfunction errorEventName(recordName: string): string {\n return recordName.startsWith(RECORD_PREFIX) ? recordName.slice(RECORD_PREFIX.length) : recordName;\n}\n\nexport class LogMetricsAggregator implements LogMetricsRecorder {\n private events = 0;\n private errors = 0;\n private toolCalls = 0;\n private failedToolCalls = 0;\n private turns = 0;\n private abortedTurns = 0;\n private failedTurns = 0;\n private cost = 0;\n private readonly tokens: LogMetricsTokenTotals = { input: 0, output: 0, total: 0, cacheRead: 0, cacheWrite: 0 };\n private readonly eventCounts = new Map<string, number>();\n private readonly packageCounts = new Map<string, number>();\n /** Shared admission registry keeps the union of every tool-related map within one bound. */\n private readonly toolNames = new Map<string, true>();\n private readonly tools = new Map<string, ToolLatencyState>();\n private readonly toolTokens = new Map<string, SampleState>();\n private readonly toolFailures = new Map<string, number>();\n private readonly failureCategories = new Map<string, number>();\n private readonly operations = new Map<string, ToolLatencyState>();\n private sanitizedFailures = 0;\n private readonly errorLog: LogMetricsError[] = [];\n private readonly now: () => number;\n private readonly maxRecentErrors: number;\n private readonly maxMetricNames: number;\n\n constructor(options: LogMetricsAggregatorOptions = {}) {\n this.now = options.now ?? Date.now;\n this.maxRecentErrors = options.maxRecentErrors ?? DEFAULT_MAX_RECENT_ERRORS;\n const requestedMaxNames = options.maxMetricNames ?? MAX_RETAINED_METRIC_NAMES;\n this.maxMetricNames = Number.isFinite(requestedMaxNames)\n ? Math.min(MAX_RETAINED_METRIC_NAMES, Math.max(1, Math.floor(requestedMaxNames)))\n : MAX_RETAINED_METRIC_NAMES;\n }\n\n record(name: string, attributes: Record<string, unknown>): void {\n const metricName = safeMetricName(name);\n this.events += 1;\n incrementBounded(this.eventCounts, metricName, this.maxMetricNames);\n const packageName = readString(attributes['telemetry.package']);\n if (packageName && !packageName.startsWith('/') && !packageName.includes('\\\\')) {\n incrementBounded(this.packageCounts, safeMetricName(packageName), this.maxMetricNames);\n }\n this.recordOperationDuration(metricName, attributes);\n this.recordSanitizedFailure(metricName, attributes);\n\n if (metricName === TOOL_RESULT_RECORD) this.recordToolResult(metricName, attributes);\n else if (metricName === API_ERROR_RECORD) this.recordApiError(metricName, attributes);\n else if (metricName === TURN_FINISHED_RECORD) this.recordTurnUsage(attributes);\n else if (metricName === TURN_FAILED_RECORD) this.recordTurnFailure(attributes);\n else if (metricName === TOOL_TOKEN_SAMPLE_RECORD) this.recordToolTokenSample(attributes);\n }\n\n snapshot(): LogMetricsSnapshot {\n const toolLatency = [...this.tools.entries()]\n .map(([name, state]) => {\n const p95Ms = bucketedP95(state);\n return {\n name,\n calls: state.calls,\n retainedStateSize: state.buckets.size,\n ...(p95Ms === undefined ? {} : { p95Ms }),\n };\n })\n .sort((left, right) => (right.p95Ms ?? -1) - (left.p95Ms ?? -1));\n\n const eventVolume = [...this.eventCounts.entries()]\n .map(([name, count]) => ({ name, count }))\n .sort((left, right) => right.count - left.count);\n const packageEvents = [...this.packageCounts.entries()]\n .map(([name, count]) => ({ name, count }))\n .sort((left, right) => right.count - left.count);\n const operationDuration = [...this.operations.entries()]\n .map(([name, state]) => {\n const p95Ms = bucketedP95(state);\n return {\n name,\n calls: state.calls,\n retainedStateSize: state.buckets.size,\n ...(p95Ms === undefined ? {} : { p95Ms }),\n };\n })\n .sort((left, right) => (right.p95Ms ?? -1) - (left.p95Ms ?? -1));\n\n return {\n events: this.events,\n errors: this.errors,\n toolCalls: this.toolCalls,\n failedToolCalls: this.failedToolCalls,\n turns: this.turns,\n abortedTurns: this.abortedTurns,\n failedTurns: this.failedTurns,\n tokens: { ...this.tokens },\n cost: this.cost,\n toolLatency,\n toolCost: this.toolCostRows(),\n failureCategories: [...this.failureCategories.entries()]\n .map(([name, count]) => ({ name, count }))\n .sort((left, right) => right.count - left.count),\n eventVolume,\n packageEvents,\n sanitizedFailures: this.sanitizedFailures,\n operationDuration,\n recentErrors: this.errorLog.map((entry) => ({ ...entry })),\n };\n }\n\n /**\n * Ranked by cost per call rather than call count: a tool invoked twice into a\n * 300k-token turn is the one worth changing, and a frequency ranking buries\n * it under the cheap tools that dominate any transcript.\n */\n private toolCostRows(): LogMetricsToolCost[] {\n const names = new Set([...this.tools.keys(), ...this.toolTokens.keys()]);\n return [...names]\n .map((name) => {\n const tokens = this.toolTokens.get(name);\n const p90Tokens = tokens ? bucketedQuantile(tokens, P90_QUANTILE) : undefined;\n return {\n name,\n calls: this.tools.get(name)?.calls ?? 0,\n failed: this.toolFailures.get(name) ?? 0,\n samples: tokens?.samples ?? 0,\n ...(p90Tokens === undefined ? {} : { p90Tokens }),\n };\n })\n .sort((left, right) => (right.p90Tokens ?? -1) - (left.p90Tokens ?? -1));\n }\n\n private boundedToolName(name: string): string {\n const boundedName = boundedMetricName(this.toolNames, name, this.maxMetricNames);\n this.toolNames.set(boundedName, true);\n return boundedName;\n }\n\n private countCategory(category: string): void {\n incrementBounded(this.failureCategories, category, this.maxMetricNames);\n }\n\n private recordOperationDuration(recordName: string, attributes: Record<string, unknown>): void {\n const duration = Object.entries(attributes).find(\n ([key, value]) =>\n key !== 'tool.duration_ms' &&\n (key === 'duration_ms' || key.endsWith('.duration_ms')) &&\n readNumber(value) !== undefined,\n );\n if (!duration) return;\n const operationName = safeMetricName(readString(attributes['operation.name']) ?? recordName);\n const state = boundedState(this.operations, operationName, this.maxMetricNames, () => ({\n calls: 0,\n samples: 0,\n buckets: new Map<number, number>(),\n }));\n state.calls += 1;\n const durationMs = readNumber(duration[1]);\n if (durationMs === undefined) return;\n observe(state, durationMs, MAX_RETAINED_STATE_PER_TOOL);\n }\n\n private recordSanitizedFailure(recordName: string, attributes: Record<string, unknown>): void {\n const outcome = readString(attributes.outcome);\n const failed =\n attributes['tool.result.error'] === true ||\n recordName === API_ERROR_RECORD ||\n outcome === 'error' ||\n outcome === 'failed' ||\n outcome === 'failure';\n if (!failed) return;\n this.sanitizedFailures += 1;\n if (recordName === TOOL_RESULT_RECORD || recordName === API_ERROR_RECORD) return;\n // Turn failures carry their own category, applied by recordTurnFailure.\n if (recordName !== TURN_FAILED_RECORD) this.countCategory(CATEGORY_LOG_ERROR);\n const code = readString(attributes['error.code']) ?? outcome ?? 'error';\n this.pushError(recordName, `${readString(attributes['error.type']) ?? 'operation'} failed`, safeMetricName(code));\n }\n\n private recordToolResult(recordName: string, attributes: Record<string, unknown>): void {\n const toolName = readString(attributes['tool.name']) ?? UNKNOWN_TOOL;\n const boundedToolName = this.boundedToolName(toolName);\n const state = boundedState(this.tools, boundedToolName, this.maxMetricNames, () => ({\n calls: 0,\n samples: 0,\n buckets: new Map<number, number>(),\n }));\n state.calls += 1;\n this.toolCalls += 1;\n\n // A call whose start was never seen carries no duration, so it counts as a\n // call but contributes no latency sample.\n const durationMs = readNumber(attributes['tool.duration_ms']);\n if (durationMs !== undefined) observe(state, durationMs, MAX_RETAINED_STATE_PER_TOOL);\n\n if (attributes['tool.result.error'] === true) {\n this.failedToolCalls += 1;\n incrementBounded(this.toolFailures, boundedToolName, this.maxMetricNames);\n this.countCategory(CATEGORY_TOOL_FAILURE);\n // Redaction is on by default, so the tool's own output is unavailable and\n // the tool name is the only detail this entry can carry.\n this.pushError(recordName, `${boundedToolName}: tool call failed`, TOOL_ERROR_CODE);\n }\n }\n\n /**\n * Attributes a turn's token total to every tool that ran in it. The Pi\n * extension emits one sample per tool result carrying the whole turn's usage,\n * so this builds a per-tool distribution of \"how expensive is a turn that\n * uses this tool\" — see LogMetricsToolCost for what that does and does not\n * claim.\n */\n private recordToolTokenSample(attributes: Record<string, unknown>): void {\n const totalTokens = readNumber(attributes['gen_ai.usage.total_tokens']);\n if (totalTokens === undefined || totalTokens <= 0) return;\n const toolName = readString(attributes['tool.name']) ?? UNKNOWN_TOOL;\n const boundedToolName = this.boundedToolName(toolName);\n const state = boundedState(this.toolTokens, boundedToolName, this.maxMetricNames, emptySampleState);\n observe(state, totalTokens, MAX_RETAINED_TOKEN_BUCKETS);\n }\n\n private recordApiError(recordName: string, attributes: Record<string, unknown>): void {\n this.errors += 1;\n const statusCode = readNumber(attributes['http.response.status_code']);\n const status = String(attributes['http.response.status_code']);\n this.countCategory(statusCode === undefined ? CATEGORY_API_ERROR : apiErrorCategory(statusCode));\n this.pushError(recordName, `provider responded ${status}`, status);\n }\n\n private recordTurnUsage(attributes: Record<string, unknown>): void {\n this.turns += 1;\n this.tokens.input += readNumber(attributes['gen_ai.usage.input_tokens']) ?? 0;\n this.tokens.output += readNumber(attributes['gen_ai.usage.output_tokens']) ?? 0;\n this.tokens.total += readNumber(attributes['gen_ai.usage.total_tokens']) ?? 0;\n this.tokens.cacheRead += readNumber(attributes['gen_ai.usage.cache_read_tokens']) ?? 0;\n this.tokens.cacheWrite += readNumber(attributes['gen_ai.usage.cache_write_tokens']) ?? 0;\n this.cost += readNumber(attributes['gen_ai.usage.cost']) ?? 0;\n }\n\n /** A turn the user has to redo: the most expensive failure mode there is. */\n private recordTurnFailure(attributes: Record<string, unknown>): void {\n const aborted = readString(attributes.outcome) === ABORTED_OUTCOME;\n if (aborted) this.abortedTurns += 1;\n else this.failedTurns += 1;\n this.countCategory(aborted ? CATEGORY_ABORTED : CATEGORY_TURN_FAILED);\n }\n\n private pushError(recordName: string, message: string, code: string): void {\n this.errorLog.unshift({ at: this.now(), event: errorEventName(recordName), message, code });\n if (this.errorLog.length > this.maxRecentErrors) this.errorLog.length = this.maxRecentErrors;\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,qBAAqB;A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ACnD,IAAI,SAAS,KAAK,gBAAgB;OAC7B,KAAK,eAAe;EACzB,KAAK,cAAc,UAAU,mBAAmB,oBAAoB;CACtE;CAEA,UAAkB,YAAoB,SAAiB,MAAoB;EACzE,KAAK,SAAS,QAAQ;GAAE,IAAI,KAAK,IAAI;GAAG,OAAO,eAAe,UAAU;GAAG;GAAS;EAAK,CAAC;EAC1F,IAAI,KAAK,SAAS,SAAS,KAAK,iBAAiB,KAAK,SAAS,SAAS,KAAK;CAC/E;AACF"}
|
|
@@ -1,160 +1,3 @@
|
|
|
1
|
-
//#region src/services/findings/index.ts
|
|
2
|
-
/** Below this, the prompt prefix is churning and cache writes are being wasted. */
|
|
3
|
-
const LOW_CACHE_HIT_RATIO = .3;
|
|
4
|
-
/** Cache hit rate is meaningless on a session that has barely sent anything. */
|
|
5
|
-
const MIN_CACHE_SAMPLE_TOKENS = 5e4;
|
|
6
|
-
/** A tool is "expensive" only well clear of the session's typical turn. */
|
|
7
|
-
const EXPENSIVE_TOOL_RATIO = 1.5;
|
|
8
|
-
const MIN_TOOL_SAMPLES = 3;
|
|
9
|
-
const FAILING_TOOL_RATIO = .25;
|
|
10
|
-
const MIN_TOOL_CALLS = 3;
|
|
11
|
-
/** Sustained input this large per turn means context is carried, not scoped. */
|
|
12
|
-
const HEAVY_TURN_INPUT_TOKENS = 12e4;
|
|
13
|
-
const MIN_TURNS_FOR_AVERAGE = 3;
|
|
14
|
-
/** Tool calls per turn above this reads as search thrash rather than progress. */
|
|
15
|
-
const BUSY_TURN_TOOL_CALLS = 8;
|
|
16
|
-
const RATE_LIMITED = "rate_limited";
|
|
17
|
-
/** Kept short because the finding's subject column already says "provider". */
|
|
18
|
-
const SHORT_CATEGORY = {
|
|
19
|
-
[RATE_LIMITED]: "rate limited",
|
|
20
|
-
provider_unavailable: "unavailable"
|
|
21
|
-
};
|
|
22
|
-
const SEVERITY_RANK = {
|
|
23
|
-
critical: 0,
|
|
24
|
-
warning: 1,
|
|
25
|
-
info: 2
|
|
26
|
-
};
|
|
27
|
-
const PERCENT = 100;
|
|
28
|
-
const MILLION = 1e6;
|
|
29
|
-
const THOUSAND = 1e3;
|
|
30
|
-
const COMPACT_DECIMALS = 1;
|
|
31
|
-
const HEALTHY_FINDING = {
|
|
32
|
-
id: "healthy",
|
|
33
|
-
severity: "info",
|
|
34
|
-
subject: "session",
|
|
35
|
-
detail: "no failures, no outliers",
|
|
36
|
-
action: "nothing to act on yet"
|
|
37
|
-
};
|
|
38
|
-
function compact(value) {
|
|
39
|
-
if (value >= MILLION) return `${(value / MILLION).toFixed(COMPACT_DECIMALS)}M`;
|
|
40
|
-
if (value >= THOUSAND) return `${Math.round(value / THOUSAND)}k`;
|
|
41
|
-
return String(Math.round(value));
|
|
42
|
-
}
|
|
43
|
-
function percent(value) {
|
|
44
|
-
return `${Math.round(value * PERCENT)}%`;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Median rather than mean: one pathological tool would drag a mean up far
|
|
48
|
-
* enough to hide itself from the comparison that is meant to catch it.
|
|
49
|
-
*/
|
|
50
|
-
function medianTokens(tools) {
|
|
51
|
-
const sampled = tools.map((tool) => tool.p90Tokens).filter((tokens) => tokens !== void 0).sort((left, right) => left - right);
|
|
52
|
-
if (sampled.length === 0) return 0;
|
|
53
|
-
const middle = Math.floor(sampled.length / 2);
|
|
54
|
-
const lower = sampled[middle - 1] ?? 0;
|
|
55
|
-
const upper = sampled[middle] ?? 0;
|
|
56
|
-
return sampled.length % 2 === 0 ? (lower + upper) / 2 : upper;
|
|
57
|
-
}
|
|
58
|
-
function cacheFinding(snapshot) {
|
|
59
|
-
const { cacheRead, cacheWrite, input } = snapshot.tokens;
|
|
60
|
-
const cacheable = cacheRead + input;
|
|
61
|
-
if (cacheable < MIN_CACHE_SAMPLE_TOKENS) return void 0;
|
|
62
|
-
const hitRatio = cacheRead / cacheable;
|
|
63
|
-
if (hitRatio >= LOW_CACHE_HIT_RATIO) return void 0;
|
|
64
|
-
return {
|
|
65
|
-
id: "low-cache-hit",
|
|
66
|
-
severity: "warning",
|
|
67
|
-
subject: "cache",
|
|
68
|
-
detail: `${percent(hitRatio)} hit · ${compact(cacheWrite)} written`,
|
|
69
|
-
action: "pin stable context first"
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
function expensiveToolFinding(snapshot) {
|
|
73
|
-
const median = medianTokens(snapshot.toolCost);
|
|
74
|
-
if (median <= 0) return void 0;
|
|
75
|
-
const worst = snapshot.toolCost.find((tool) => tool.samples >= MIN_TOOL_SAMPLES && (tool.p90Tokens ?? 0) >= median * EXPENSIVE_TOOL_RATIO);
|
|
76
|
-
if (!worst?.p90Tokens) return void 0;
|
|
77
|
-
return {
|
|
78
|
-
id: "expensive-tool",
|
|
79
|
-
severity: "warning",
|
|
80
|
-
subject: worst.name,
|
|
81
|
-
detail: `${compact(worst.p90Tokens)} p90 · ${Math.round(worst.p90Tokens / median)}× median`,
|
|
82
|
-
action: "narrow what it pulls in"
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
function failingToolFindings(snapshot) {
|
|
86
|
-
return snapshot.toolCost.filter((tool) => tool.calls >= MIN_TOOL_CALLS && tool.failed / tool.calls >= FAILING_TOOL_RATIO).sort((left, right) => right.failed - left.failed).map((tool) => ({
|
|
87
|
-
id: `failing-tool:${tool.name}`,
|
|
88
|
-
severity: "critical",
|
|
89
|
-
subject: tool.name,
|
|
90
|
-
detail: `${tool.failed} of ${tool.calls} failed`,
|
|
91
|
-
action: "retries burn tokens"
|
|
92
|
-
}));
|
|
93
|
-
}
|
|
94
|
-
function abortedTurnFinding(snapshot) {
|
|
95
|
-
if (snapshot.abortedTurns + snapshot.failedTurns === 0) return void 0;
|
|
96
|
-
return {
|
|
97
|
-
id: "redone-turns",
|
|
98
|
-
severity: "critical",
|
|
99
|
-
subject: "turns",
|
|
100
|
-
detail: `${snapshot.abortedTurns} aborted · ${snapshot.failedTurns} failed`,
|
|
101
|
-
action: "paid for, then thrown away"
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
function providerFinding(snapshot) {
|
|
105
|
-
const category = snapshot.failureCategories.find((entry) => entry.name in SHORT_CATEGORY);
|
|
106
|
-
if (!category) return void 0;
|
|
107
|
-
return {
|
|
108
|
-
id: `provider:${category.name}`,
|
|
109
|
-
severity: "warning",
|
|
110
|
-
subject: "provider",
|
|
111
|
-
detail: `${category.count} × ${SHORT_CATEGORY[category.name] ?? category.name}`,
|
|
112
|
-
action: category.name === RATE_LIMITED ? "back off or drop concurrency" : "retry or switch provider"
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
function contextFinding(snapshot) {
|
|
116
|
-
if (snapshot.turns < MIN_TURNS_FOR_AVERAGE) return void 0;
|
|
117
|
-
const perTurn = snapshot.tokens.input / snapshot.turns;
|
|
118
|
-
if (perTurn < HEAVY_TURN_INPUT_TOKENS) return void 0;
|
|
119
|
-
return {
|
|
120
|
-
id: "heavy-context",
|
|
121
|
-
severity: "warning",
|
|
122
|
-
subject: "context",
|
|
123
|
-
detail: `${compact(perTurn)} input tok/turn`,
|
|
124
|
-
action: "compact or split the task"
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
function toolChurnFinding(snapshot) {
|
|
128
|
-
if (snapshot.turns < MIN_TURNS_FOR_AVERAGE) return void 0;
|
|
129
|
-
const perTurn = snapshot.toolCalls / snapshot.turns;
|
|
130
|
-
if (perTurn < BUSY_TURN_TOOL_CALLS) return void 0;
|
|
131
|
-
return {
|
|
132
|
-
id: "tool-churn",
|
|
133
|
-
severity: "info",
|
|
134
|
-
subject: "tools",
|
|
135
|
-
detail: `${perTurn.toFixed(1)} calls/turn`,
|
|
136
|
-
action: "give it a narrower target"
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Ranked most-actionable first. Severity leads because a failing tool costs
|
|
141
|
-
* more than an inefficient one, and the panel is read top-down under a
|
|
142
|
-
* height limit.
|
|
143
|
-
*/
|
|
144
|
-
function deriveFindings(snapshot) {
|
|
145
|
-
const findings = [
|
|
146
|
-
...failingToolFindings(snapshot),
|
|
147
|
-
abortedTurnFinding(snapshot),
|
|
148
|
-
providerFinding(snapshot),
|
|
149
|
-
cacheFinding(snapshot),
|
|
150
|
-
expensiveToolFinding(snapshot),
|
|
151
|
-
contextFinding(snapshot),
|
|
152
|
-
toolChurnFinding(snapshot)
|
|
153
|
-
].filter((finding) => finding !== void 0);
|
|
154
|
-
if (findings.length === 0) return snapshot.events > 0 ? [HEALTHY_FINDING] : [];
|
|
155
|
-
return findings.sort((left, right) => SEVERITY_RANK[left.severity] - SEVERITY_RANK[right.severity]);
|
|
156
|
-
}
|
|
157
|
-
//#endregion
|
|
158
1
|
//#region src/services/metrics/index.ts
|
|
159
2
|
/**
|
|
160
3
|
* Session-local aggregation of the log records the Pi telemetry extension
|
|
@@ -503,6 +346,6 @@ var LogMetricsAggregator = class {
|
|
|
503
346
|
}
|
|
504
347
|
};
|
|
505
348
|
//#endregion
|
|
506
|
-
export { MAX_RETAINED_TOKEN_BUCKETS as a, TOOL_TOKEN_SAMPLE_RECORD as c,
|
|
349
|
+
export { MAX_RETAINED_TOKEN_BUCKETS as a, TOOL_TOKEN_SAMPLE_RECORD as c, bucketIndex as d, bucketedQuantile as f, MAX_RETAINED_STATE_PER_TOOL as i, TURN_FAILED_RECORD as l, LogMetricsAggregator as n, METRIC_OVERFLOW_NAME as o, MAX_RETAINED_METRIC_NAMES as r, TOOL_RESULT_RECORD as s, API_ERROR_RECORD as t, TURN_FINISHED_RECORD as u };
|
|
507
350
|
|
|
508
|
-
//# sourceMappingURL=metrics-
|
|
351
|
+
//# sourceMappingURL=metrics-DwfV84Fy.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metrics-DwfV84Fy.mjs","names":[],"sources":["../src/services/metrics/index.ts"],"sourcesContent":["/**\n * Session-local aggregation of the log records the Pi telemetry extension\n * already emits.\n *\n * The aggregator is fed `(recordName, attributes)` pairs rather than Pi events\n * so it can only ever see what the sink sees: no extra instrumentation is added\n * for metrics, and nothing here depends on a live sink. Everything is scoped to\n * the current process, so there is no persistence and no query API.\n */\n\n/** Record names the aggregator derives numbers from. */\nexport const TOOL_RESULT_RECORD = 'pi.tool_result';\nexport const API_ERROR_RECORD = 'pi.api_error';\nexport const TURN_FINISHED_RECORD = 'pi.turn.finished';\nexport const TURN_FAILED_RECORD = 'pi.turn.failed';\nexport const TOOL_TOKEN_SAMPLE_RECORD = 'pi.tool_token_sample';\n\nconst UNKNOWN_TOOL = 'unknown';\nconst TOOL_ERROR_CODE = 'tool';\nconst RECORD_PREFIX = 'pi.';\nconst DEFAULT_MAX_RECENT_ERRORS = 8;\n/** Maximum entries retained in each cardinality-bearing metrics map, including overflow. */\nexport const MAX_RETAINED_METRIC_NAMES = 128;\n/** Snapshot row used to account for names that arrive after a metrics map reaches its bound. */\nexport const METRIC_OVERFLOW_NAME = '__overflow__';\nconst P95_QUANTILE = 0.95;\nconst P90_QUANTILE = 0.9;\nconst ABORTED_OUTCOME = 'aborted';\n\n/**\n * Failure taxonomy, mirroring log-sink's AgentIssueCategory closely enough that\n * a session-local category reads the same as the one the sink would report for\n * the same record. Rate limiting and provider outages are split out because\n * they call for different action: back off versus retry elsewhere.\n */\nconst RATE_LIMIT_STATUS = 429;\nconst SERVER_ERROR_STATUS = 500;\nconst CATEGORY_TOOL_FAILURE = 'tool_failure';\nconst CATEGORY_RATE_LIMITED = 'rate_limited';\nconst CATEGORY_PROVIDER_UNAVAILABLE = 'provider_unavailable';\nconst CATEGORY_API_ERROR = 'api_error';\nconst CATEGORY_ABORTED = 'aborted';\nconst CATEGORY_TURN_FAILED = 'turn_failed';\nconst CATEGORY_LOG_ERROR = 'log_error';\n\n/**\n * Latency is kept as a fixed logarithmic histogram rather than a sample array,\n * so a long session cannot grow the retained state without bound. Each bucket\n * is 10% wider than the last, which keeps the reported p95 within about 10% of\n * the true value while capping the state at one small map per tool.\n */\nconst LATENCY_BUCKET_GROWTH = 1.1;\nconst LATENCY_BUCKET_LOG_BASE = Math.log(LATENCY_BUCKET_GROWTH);\nconst MINIMUM_SAMPLE_MS = 1;\n\n/** Bucket ceiling per tool: covers 1ms to roughly an hour at 10% resolution. */\nexport const MAX_RETAINED_STATE_PER_TOOL = 160;\n\n/**\n * Token distributions reuse the same histogram at a higher ceiling: a turn's\n * total can run to millions once cache reads are counted, which the latency\n * ceiling would saturate and report as a flat maximum.\n */\nexport const MAX_RETAINED_TOKEN_BUCKETS = 200;\n\nexport interface LogMetricsTokenTotals {\n input: number;\n output: number;\n total: number;\n /**\n * Cached prompt tokens billed at the read rate. Held separately from `input`\n * because the ratio between them is the session's cache hit rate, which is\n * the single largest cost lever a user controls.\n */\n cacheRead: number;\n cacheWrite: number;\n}\n\nexport interface LogMetricsToolLatency {\n name: string;\n calls: number;\n p95Ms?: number;\n /** Buckets currently held for this tool, bounded by MAX_RETAINED_STATE_PER_TOOL. */\n retainedStateSize: number;\n}\n\nexport interface LogMetricsEventCount {\n name: string;\n count: number;\n}\n\nexport interface LogMetricsOperationDuration {\n name: string;\n calls: number;\n p95Ms?: number;\n retainedStateSize: number;\n}\n\nexport interface LogMetricsError {\n at: number;\n event: string;\n message: string;\n code: string;\n}\n\n/**\n * What a tool costs, rather than how long it takes.\n *\n * `p90Tokens` is the 90th percentile of the *turn* total for turns this tool\n * took part in, which is the only attribution the Pi extension emits\n * (`token_attribution: 'toolCallTurn'`). It answers \"when this tool runs, how\n * expensive is the turn\", not \"this tool consumed N tokens\" — a turn with\n * several tool calls attributes its total to each of them.\n */\nexport interface LogMetricsToolCost {\n name: string;\n calls: number;\n failed: number;\n /** Turns carrying usage that this tool took part in, i.e. the p90 sample count. */\n samples: number;\n p90Tokens?: number;\n}\n\nexport interface LogMetricsSnapshot {\n events: number;\n errors: number;\n toolCalls: number;\n failedToolCalls: number;\n /** Turns that reported usage, i.e. the denominator for per-turn averages. */\n turns: number;\n abortedTurns: number;\n failedTurns: number;\n tokens: LogMetricsTokenTotals;\n cost: number;\n toolLatency: LogMetricsToolLatency[];\n toolCost: LogMetricsToolCost[];\n failureCategories: LogMetricsEventCount[];\n eventVolume: LogMetricsEventCount[];\n packageEvents: LogMetricsEventCount[];\n sanitizedFailures: number;\n operationDuration: LogMetricsOperationDuration[];\n recentErrors: LogMetricsError[];\n}\n\nexport interface LogMetricsAggregatorOptions {\n now?: () => number;\n maxRecentErrors?: number;\n /** Per-map cardinality bound for tests, capped at MAX_RETAINED_METRIC_NAMES. */\n maxMetricNames?: number;\n}\n\n/** The slice of the aggregator the telemetry extension needs. */\nexport interface LogMetricsRecorder {\n record(name: string, attributes: Record<string, unknown>): void;\n}\n\ninterface ToolLatencyState {\n calls: number;\n samples: number;\n buckets: Map<number, number>;\n}\n\nexport interface SampleState {\n samples: number;\n buckets: Map<number, number>;\n}\n\nfunction emptySampleState(): SampleState {\n return { samples: 0, buckets: new Map<number, number>() };\n}\n\nfunction readNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction safeMetricName(value: string): string {\n const normalized = value.replace(/[^a-zA-Z0-9@/._:-]/g, '_').slice(0, 128);\n return normalized || 'unknown';\n}\n\n/** Keeps an existing key, admits a new one when space remains, or selects the overflow row. */\nfunction boundedMetricName<T>(map: Map<string, T>, name: string, maxNames: number): string {\n if (map.has(name)) return name;\n return map.size < maxNames - 1 ? name : METRIC_OVERFLOW_NAME;\n}\n\nfunction incrementBounded(map: Map<string, number>, name: string, maxNames: number): void {\n const boundedName = boundedMetricName(map, name, maxNames);\n map.set(boundedName, (map.get(boundedName) ?? 0) + 1);\n}\n\nfunction boundedState<T>(map: Map<string, T>, name: string, maxNames: number, create: () => T): T {\n const boundedName = boundedMetricName(map, name, maxNames);\n const state = map.get(boundedName) ?? create();\n map.set(boundedName, state);\n return state;\n}\n\nexport function bucketIndex(value: number, cap: number): number {\n const index = Math.ceil(Math.log(Math.max(value, MINIMUM_SAMPLE_MS)) / LATENCY_BUCKET_LOG_BASE);\n return Math.min(Math.max(index, 0), cap - 1);\n}\n\nfunction bucketUpperBound(index: number): number {\n return LATENCY_BUCKET_GROWTH ** index;\n}\n\nfunction observe(state: SampleState, value: number, cap: number): void {\n const bucket = bucketIndex(value, cap);\n state.buckets.set(bucket, (state.buckets.get(bucket) ?? 0) + 1);\n state.samples += 1;\n}\n\n/**\n * The upper edge of the first bucket whose cumulative count crosses the\n * quantile. Reporting the edge rather than a bucket midpoint keeps the answer\n * an upper bound, so a single 250ms call never reports faster than 250ms.\n */\nexport function bucketedQuantile(state: SampleState, quantile: number): number | undefined {\n if (state.samples === 0) return undefined;\n\n const target = state.samples * quantile;\n const indexes = [...state.buckets.keys()].sort((left, right) => left - right);\n let cumulative = 0;\n let selected = indexes[0] as number;\n for (const index of indexes) {\n cumulative += state.buckets.get(index) ?? 0;\n selected = index;\n if (cumulative >= target) break;\n }\n return Math.round(bucketUpperBound(selected));\n}\n\nfunction bucketedP95(state: SampleState): number | undefined {\n return bucketedQuantile(state, P95_QUANTILE);\n}\n\n/** Categorises an HTTP failure so the action it implies is distinguishable. */\nfunction apiErrorCategory(status: number): string {\n if (status === RATE_LIMIT_STATUS) return CATEGORY_RATE_LIMITED;\n if (status >= SERVER_ERROR_STATUS) return CATEGORY_PROVIDER_UNAVAILABLE;\n return CATEGORY_API_ERROR;\n}\n\n/** Strips the `pi.` prefix so an error entry reads as the event it came from. */\nfunction errorEventName(recordName: string): string {\n return recordName.startsWith(RECORD_PREFIX) ? recordName.slice(RECORD_PREFIX.length) : recordName;\n}\n\nexport class LogMetricsAggregator implements LogMetricsRecorder {\n private events = 0;\n private errors = 0;\n private toolCalls = 0;\n private failedToolCalls = 0;\n private turns = 0;\n private abortedTurns = 0;\n private failedTurns = 0;\n private cost = 0;\n private readonly tokens: LogMetricsTokenTotals = { input: 0, output: 0, total: 0, cacheRead: 0, cacheWrite: 0 };\n private readonly eventCounts = new Map<string, number>();\n private readonly packageCounts = new Map<string, number>();\n /** Shared admission registry keeps the union of every tool-related map within one bound. */\n private readonly toolNames = new Map<string, true>();\n private readonly tools = new Map<string, ToolLatencyState>();\n private readonly toolTokens = new Map<string, SampleState>();\n private readonly toolFailures = new Map<string, number>();\n private readonly failureCategories = new Map<string, number>();\n private readonly operations = new Map<string, ToolLatencyState>();\n private sanitizedFailures = 0;\n private readonly errorLog: LogMetricsError[] = [];\n private readonly now: () => number;\n private readonly maxRecentErrors: number;\n private readonly maxMetricNames: number;\n\n constructor(options: LogMetricsAggregatorOptions = {}) {\n this.now = options.now ?? Date.now;\n this.maxRecentErrors = options.maxRecentErrors ?? DEFAULT_MAX_RECENT_ERRORS;\n const requestedMaxNames = options.maxMetricNames ?? MAX_RETAINED_METRIC_NAMES;\n this.maxMetricNames = Number.isFinite(requestedMaxNames)\n ? Math.min(MAX_RETAINED_METRIC_NAMES, Math.max(1, Math.floor(requestedMaxNames)))\n : MAX_RETAINED_METRIC_NAMES;\n }\n\n record(name: string, attributes: Record<string, unknown>): void {\n const metricName = safeMetricName(name);\n this.events += 1;\n incrementBounded(this.eventCounts, metricName, this.maxMetricNames);\n const packageName = readString(attributes['telemetry.package']);\n if (packageName && !packageName.startsWith('/') && !packageName.includes('\\\\')) {\n incrementBounded(this.packageCounts, safeMetricName(packageName), this.maxMetricNames);\n }\n this.recordOperationDuration(metricName, attributes);\n this.recordSanitizedFailure(metricName, attributes);\n\n if (metricName === TOOL_RESULT_RECORD) this.recordToolResult(metricName, attributes);\n else if (metricName === API_ERROR_RECORD) this.recordApiError(metricName, attributes);\n else if (metricName === TURN_FINISHED_RECORD) this.recordTurnUsage(attributes);\n else if (metricName === TURN_FAILED_RECORD) this.recordTurnFailure(attributes);\n else if (metricName === TOOL_TOKEN_SAMPLE_RECORD) this.recordToolTokenSample(attributes);\n }\n\n snapshot(): LogMetricsSnapshot {\n const toolLatency = [...this.tools.entries()]\n .map(([name, state]) => {\n const p95Ms = bucketedP95(state);\n return {\n name,\n calls: state.calls,\n retainedStateSize: state.buckets.size,\n ...(p95Ms === undefined ? {} : { p95Ms }),\n };\n })\n .sort((left, right) => (right.p95Ms ?? -1) - (left.p95Ms ?? -1));\n\n const eventVolume = [...this.eventCounts.entries()]\n .map(([name, count]) => ({ name, count }))\n .sort((left, right) => right.count - left.count);\n const packageEvents = [...this.packageCounts.entries()]\n .map(([name, count]) => ({ name, count }))\n .sort((left, right) => right.count - left.count);\n const operationDuration = [...this.operations.entries()]\n .map(([name, state]) => {\n const p95Ms = bucketedP95(state);\n return {\n name,\n calls: state.calls,\n retainedStateSize: state.buckets.size,\n ...(p95Ms === undefined ? {} : { p95Ms }),\n };\n })\n .sort((left, right) => (right.p95Ms ?? -1) - (left.p95Ms ?? -1));\n\n return {\n events: this.events,\n errors: this.errors,\n toolCalls: this.toolCalls,\n failedToolCalls: this.failedToolCalls,\n turns: this.turns,\n abortedTurns: this.abortedTurns,\n failedTurns: this.failedTurns,\n tokens: { ...this.tokens },\n cost: this.cost,\n toolLatency,\n toolCost: this.toolCostRows(),\n failureCategories: [...this.failureCategories.entries()]\n .map(([name, count]) => ({ name, count }))\n .sort((left, right) => right.count - left.count),\n eventVolume,\n packageEvents,\n sanitizedFailures: this.sanitizedFailures,\n operationDuration,\n recentErrors: this.errorLog.map((entry) => ({ ...entry })),\n };\n }\n\n /**\n * Ranked by cost per call rather than call count: a tool invoked twice into a\n * 300k-token turn is the one worth changing, and a frequency ranking buries\n * it under the cheap tools that dominate any transcript.\n */\n private toolCostRows(): LogMetricsToolCost[] {\n const names = new Set([...this.tools.keys(), ...this.toolTokens.keys()]);\n return [...names]\n .map((name) => {\n const tokens = this.toolTokens.get(name);\n const p90Tokens = tokens ? bucketedQuantile(tokens, P90_QUANTILE) : undefined;\n return {\n name,\n calls: this.tools.get(name)?.calls ?? 0,\n failed: this.toolFailures.get(name) ?? 0,\n samples: tokens?.samples ?? 0,\n ...(p90Tokens === undefined ? {} : { p90Tokens }),\n };\n })\n .sort((left, right) => (right.p90Tokens ?? -1) - (left.p90Tokens ?? -1));\n }\n\n private boundedToolName(name: string): string {\n const boundedName = boundedMetricName(this.toolNames, name, this.maxMetricNames);\n this.toolNames.set(boundedName, true);\n return boundedName;\n }\n\n private countCategory(category: string): void {\n incrementBounded(this.failureCategories, category, this.maxMetricNames);\n }\n\n private recordOperationDuration(recordName: string, attributes: Record<string, unknown>): void {\n const duration = Object.entries(attributes).find(\n ([key, value]) =>\n key !== 'tool.duration_ms' &&\n (key === 'duration_ms' || key.endsWith('.duration_ms')) &&\n readNumber(value) !== undefined,\n );\n if (!duration) return;\n const operationName = safeMetricName(readString(attributes['operation.name']) ?? recordName);\n const state = boundedState(this.operations, operationName, this.maxMetricNames, () => ({\n calls: 0,\n samples: 0,\n buckets: new Map<number, number>(),\n }));\n state.calls += 1;\n const durationMs = readNumber(duration[1]);\n if (durationMs === undefined) return;\n observe(state, durationMs, MAX_RETAINED_STATE_PER_TOOL);\n }\n\n private recordSanitizedFailure(recordName: string, attributes: Record<string, unknown>): void {\n const outcome = readString(attributes.outcome);\n const failed =\n attributes['tool.result.error'] === true ||\n recordName === API_ERROR_RECORD ||\n outcome === 'error' ||\n outcome === 'failed' ||\n outcome === 'failure';\n if (!failed) return;\n this.sanitizedFailures += 1;\n if (recordName === TOOL_RESULT_RECORD || recordName === API_ERROR_RECORD) return;\n // Turn failures carry their own category, applied by recordTurnFailure.\n if (recordName !== TURN_FAILED_RECORD) this.countCategory(CATEGORY_LOG_ERROR);\n const code = readString(attributes['error.code']) ?? outcome ?? 'error';\n this.pushError(recordName, `${readString(attributes['error.type']) ?? 'operation'} failed`, safeMetricName(code));\n }\n\n private recordToolResult(recordName: string, attributes: Record<string, unknown>): void {\n const toolName = readString(attributes['tool.name']) ?? UNKNOWN_TOOL;\n const boundedToolName = this.boundedToolName(toolName);\n const state = boundedState(this.tools, boundedToolName, this.maxMetricNames, () => ({\n calls: 0,\n samples: 0,\n buckets: new Map<number, number>(),\n }));\n state.calls += 1;\n this.toolCalls += 1;\n\n // A call whose start was never seen carries no duration, so it counts as a\n // call but contributes no latency sample.\n const durationMs = readNumber(attributes['tool.duration_ms']);\n if (durationMs !== undefined) observe(state, durationMs, MAX_RETAINED_STATE_PER_TOOL);\n\n if (attributes['tool.result.error'] === true) {\n this.failedToolCalls += 1;\n incrementBounded(this.toolFailures, boundedToolName, this.maxMetricNames);\n this.countCategory(CATEGORY_TOOL_FAILURE);\n // Redaction is on by default, so the tool's own output is unavailable and\n // the tool name is the only detail this entry can carry.\n this.pushError(recordName, `${boundedToolName}: tool call failed`, TOOL_ERROR_CODE);\n }\n }\n\n /**\n * Attributes a turn's token total to every tool that ran in it. The Pi\n * extension emits one sample per tool result carrying the whole turn's usage,\n * so this builds a per-tool distribution of \"how expensive is a turn that\n * uses this tool\" — see LogMetricsToolCost for what that does and does not\n * claim.\n */\n private recordToolTokenSample(attributes: Record<string, unknown>): void {\n const totalTokens = readNumber(attributes['gen_ai.usage.total_tokens']);\n if (totalTokens === undefined || totalTokens <= 0) return;\n const toolName = readString(attributes['tool.name']) ?? UNKNOWN_TOOL;\n const boundedToolName = this.boundedToolName(toolName);\n const state = boundedState(this.toolTokens, boundedToolName, this.maxMetricNames, emptySampleState);\n observe(state, totalTokens, MAX_RETAINED_TOKEN_BUCKETS);\n }\n\n private recordApiError(recordName: string, attributes: Record<string, unknown>): void {\n this.errors += 1;\n const statusCode = readNumber(attributes['http.response.status_code']);\n const status = String(attributes['http.response.status_code']);\n this.countCategory(statusCode === undefined ? CATEGORY_API_ERROR : apiErrorCategory(statusCode));\n this.pushError(recordName, `provider responded ${status}`, status);\n }\n\n private recordTurnUsage(attributes: Record<string, unknown>): void {\n this.turns += 1;\n this.tokens.input += readNumber(attributes['gen_ai.usage.input_tokens']) ?? 0;\n this.tokens.output += readNumber(attributes['gen_ai.usage.output_tokens']) ?? 0;\n this.tokens.total += readNumber(attributes['gen_ai.usage.total_tokens']) ?? 0;\n this.tokens.cacheRead += readNumber(attributes['gen_ai.usage.cache_read_tokens']) ?? 0;\n this.tokens.cacheWrite += readNumber(attributes['gen_ai.usage.cache_write_tokens']) ?? 0;\n this.cost += readNumber(attributes['gen_ai.usage.cost']) ?? 0;\n }\n\n /** A turn the user has to redo: the most expensive failure mode there is. */\n private recordTurnFailure(attributes: Record<string, unknown>): void {\n const aborted = readString(attributes.outcome) === ABORTED_OUTCOME;\n if (aborted) this.abortedTurns += 1;\n else this.failedTurns += 1;\n this.countCategory(aborted ? CATEGORY_ABORTED : CATEGORY_TURN_FAILED);\n }\n\n private pushError(recordName: string, message: string, code: string): void {\n this.errorLog.unshift({ at: this.now(), event: errorEventName(recordName), message, code });\n if (this.errorLog.length > this.maxRecentErrors) this.errorLog.length = this.maxRecentErrors;\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,qBAAqB;AAClC,MAAa,mBAAmB;AAChC,MAAa,uBAAuB;AACpC,MAAa,qBAAqB;AAClC,MAAa,2BAA2B;AAExC,MAAM,eAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,4BAA4B;;AAElC,MAAa,4BAA4B;;AAEzC,MAAa,uBAAuB;AACpC,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;AAQxB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,gCAAgC;AACtC,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;;;;;;;AAQ3B,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B,KAAK,IAAI,qBAAqB;AAC9D,MAAM,oBAAoB;;AAG1B,MAAa,8BAA8B;;;;;;AAO3C,MAAa,6BAA6B;AAwG1C,SAAS,mBAAgC;CACvC,OAAO;EAAE,SAAS;EAAG,yBAAS,IAAI,IAAoB;CAAE;AAC1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W,4BAA4B;EAC7D,KAAK,cAAc,eAAe,KAAA,IAAY,qBAAqB,iBAAiB,UAAU,CAAC;EAC/F,KAAK,UAAU,YAAY,sBAAsB,UAAU,MAAM;CACnE;CAEA,gBAAwB,YAA2C;EACjE,KAAK,SAAS;EACd,KAAK,OAAO,SAAS,WAAW,WAAW,4BAA4B,KAAK;EAC5E,KAAK,OAAO,UAAU,WAAW,WAAW,6BAA6B,KAAK;EAC9E,KAAK,OAAO,SAAS,WAAW,WAAW,4BAA4B,KAAK;EAC5E,KAAK,OAAO,aAAa,WAAW,WAAW,iCAAiC,KAAK;EACrF,KAAK,OAAO,cAAc,WAAW,WAAW,kCAAkC,KAAK;EACvF,KAAK,QAAQ,WAAW,WAAW,oBAAoB,KAAK;CAC9D;;CAGA,kBAA0B,YAA2C;EACnE,MAAM,UAAU,WAAW,WAAW,OAAO,MAAM;EACnD,IAAI,SAAS,KAAK,gBAAgB;OAC7B,KAAK,eAAe;EACzB,KAAK,cAAc,UAAU,mBAAmB,oBAAoB;CACtE;CAEA,UAAkB,YAAoB,SAAiB,MAAoB;EACzE,KAAK,SAAS,QAAQ;GAAE,IAAI,KAAK,IAAI;GAAG,OAAO,eAAe,UAAU;GAAG;GAAS;EAAK,CAAC;EAC1F,IAAI,KAAK,SAAS,SAAS,KAAK,iBAAiB,KAAK,SAAS,SAAS,KAAK;CAC/E;AACF"}
|
package/dist/metrics.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
2
|
+
const require_findings = require("./findings-Bo4IHNpr.cjs");
|
|
3
|
+
const require_metrics = require("./metrics-Bml7TSZq.cjs");
|
|
3
4
|
exports.API_ERROR_RECORD = require_metrics.API_ERROR_RECORD;
|
|
4
5
|
exports.LogMetricsAggregator = require_metrics.LogMetricsAggregator;
|
|
5
6
|
exports.MAX_RETAINED_METRIC_NAMES = require_metrics.MAX_RETAINED_METRIC_NAMES;
|
|
@@ -10,4 +11,4 @@ exports.TOOL_RESULT_RECORD = require_metrics.TOOL_RESULT_RECORD;
|
|
|
10
11
|
exports.TOOL_TOKEN_SAMPLE_RECORD = require_metrics.TOOL_TOKEN_SAMPLE_RECORD;
|
|
11
12
|
exports.TURN_FAILED_RECORD = require_metrics.TURN_FAILED_RECORD;
|
|
12
13
|
exports.TURN_FINISHED_RECORD = require_metrics.TURN_FINISHED_RECORD;
|
|
13
|
-
exports.deriveFindings =
|
|
14
|
+
exports.deriveFindings = require_findings.deriveFindings;
|
package/dist/metrics.mjs
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import { t as deriveFindings } from "./findings-DAKeRG4O.mjs";
|
|
2
|
+
import { a as MAX_RETAINED_TOKEN_BUCKETS, c as TOOL_TOKEN_SAMPLE_RECORD, i as MAX_RETAINED_STATE_PER_TOOL, l as TURN_FAILED_RECORD, n as LogMetricsAggregator, o as METRIC_OVERFLOW_NAME, r as MAX_RETAINED_METRIC_NAMES, s as TOOL_RESULT_RECORD, t as API_ERROR_RECORD, u as TURN_FINISHED_RECORD } from "./metrics-DwfV84Fy.mjs";
|
|
3
|
+
export { API_ERROR_RECORD, LogMetricsAggregator, MAX_RETAINED_METRIC_NAMES, MAX_RETAINED_STATE_PER_TOOL, MAX_RETAINED_TOKEN_BUCKETS, METRIC_OVERFLOW_NAME, TOOL_RESULT_RECORD, TOOL_TOKEN_SAMPLE_RECORD, TURN_FAILED_RECORD, TURN_FINISHED_RECORD, deriveFindings };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const require_http = require("./http-Dhn2bpMh.cjs");
|
|
1
2
|
let _agimon_ai_po_logsink = require("@agimon-ai/po-logsink");
|
|
2
3
|
//#region src/services/metricsSource/index.ts
|
|
3
4
|
/**
|
|
@@ -15,45 +16,11 @@ let _agimon_ai_po_logsink = require("@agimon-ai/po-logsink");
|
|
|
15
16
|
* would land on the local instance while the writer exported to the global one
|
|
16
17
|
* and the panel would report an empty history that no session ever filled.
|
|
17
18
|
*/
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const DEFAULT_TOOL_LIMIT = 1;
|
|
24
|
-
/** The panel ranks consumers, so ask for the biggest rather than the most recent. */
|
|
25
|
-
const TOKEN_SORT = "total-tokens";
|
|
26
|
-
const FILTER_QUERY_KEYS = {
|
|
27
|
-
sessionId: "sessionId",
|
|
28
|
-
agentName: "agentName",
|
|
29
|
-
model: "model",
|
|
30
|
-
provider: "provider"
|
|
31
|
-
};
|
|
32
|
-
function filterEntries(params) {
|
|
33
|
-
const filter = params.filter;
|
|
34
|
-
if (filter === void 0) return [];
|
|
35
|
-
return Object.keys(FILTER_QUERY_KEYS).flatMap((key) => {
|
|
36
|
-
const value = filter[key];
|
|
37
|
-
return value === void 0 || value === "" ? [] : [[key, value]];
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
function searchParams(params) {
|
|
41
|
-
const search = new URLSearchParams({
|
|
42
|
-
groupBy: params.groupBy,
|
|
43
|
-
period: params.period,
|
|
44
|
-
sort: TOKEN_SORT,
|
|
45
|
-
limit: String(params.limit),
|
|
46
|
-
toolLimit: String(params.toolLimit ?? DEFAULT_TOOL_LIMIT)
|
|
47
|
-
});
|
|
48
|
-
for (const [key, value] of filterEntries(params)) search.set(FILTER_QUERY_KEYS[key], value);
|
|
49
|
-
return search.toString();
|
|
50
|
-
}
|
|
51
|
-
async function queryHttp(endpoint, params, fetchImpl) {
|
|
52
|
-
const response = await fetchImpl(`${endpoint}/api/metrics?${searchParams(params)}`, { signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) });
|
|
53
|
-
if (!response.ok) throw new Error(`sink responded ${response.status}`);
|
|
54
|
-
const body = await response.json();
|
|
55
|
-
if (body.error || !Array.isArray(body.timeline)) throw new Error(body.error ?? "sink is an older version");
|
|
56
|
-
return body;
|
|
19
|
+
async function resolveMetricsEndpoint(options = {}) {
|
|
20
|
+
return (await (0, _agimon_ai_po_logsink.resolveLogSinkPort)({
|
|
21
|
+
...options,
|
|
22
|
+
healthCheck: true
|
|
23
|
+
}))?.endpoint;
|
|
57
24
|
}
|
|
58
25
|
/**
|
|
59
26
|
* A malformed `.logsink.yaml` must not take the overlay down with it. Both
|
|
@@ -102,7 +69,7 @@ function createMetricsSource(options = {}) {
|
|
|
102
69
|
async query(params) {
|
|
103
70
|
const httpEndpoint = await resolveEndpoint();
|
|
104
71
|
if (httpEndpoint && fetchImpl) try {
|
|
105
|
-
const report = await queryHttp(httpEndpoint, params, fetchImpl);
|
|
72
|
+
const report = await require_http.queryHttp(httpEndpoint, params, fetchImpl);
|
|
106
73
|
transport = "http";
|
|
107
74
|
return report;
|
|
108
75
|
} catch {
|
|
@@ -112,9 +79,9 @@ function createMetricsSource(options = {}) {
|
|
|
112
79
|
const report = await workerReader.getMetrics(params.filter, {
|
|
113
80
|
groupBy: params.groupBy,
|
|
114
81
|
period: params.period,
|
|
115
|
-
sort: TOKEN_SORT,
|
|
82
|
+
sort: require_http.TOKEN_SORT,
|
|
116
83
|
limit: params.limit,
|
|
117
|
-
toolLimit: params.toolLimit ??
|
|
84
|
+
toolLimit: params.toolLimit ?? 1
|
|
118
85
|
});
|
|
119
86
|
transport = "worker";
|
|
120
87
|
return report;
|
|
@@ -131,5 +98,11 @@ Object.defineProperty(exports, "createMetricsSource", {
|
|
|
131
98
|
return createMetricsSource;
|
|
132
99
|
}
|
|
133
100
|
});
|
|
101
|
+
Object.defineProperty(exports, "resolveMetricsEndpoint", {
|
|
102
|
+
enumerable: true,
|
|
103
|
+
get: function() {
|
|
104
|
+
return resolveMetricsEndpoint;
|
|
105
|
+
}
|
|
106
|
+
});
|
|
134
107
|
|
|
135
|
-
//# sourceMappingURL=metricsSource-
|
|
108
|
+
//# sourceMappingURL=metricsSource-CF3cp-sf.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metricsSource-CF3cp-sf.cjs","names":["resolveLogSinkPort","resolveLogSinkInstance","queryHttp","createAsyncLogMetricsReader","TOKEN_SORT"],"sources":["../src/services/metricsSource/index.ts"],"sourcesContent":["/**\n * Historical metrics access for the `SPC h l` overlay.\n *\n * Two transports, in order: the running sink's HTTP API, then a worker-backed\n * database reader. The sink daemon is long-lived and often lags the installed\n * package, so a daemon that rejects newer query parameters is treated as\n * unavailable rather than fatal. SQLite queries run in the package worker so a\n * one-day window cannot freeze the TUI.\n *\n * Both transports resolve the sink instance from the same identity the Pi\n * telemetry extension writes under. Without it log-sink falls back to\n * `npm_package_name`, which a running Pi process does not set, so the reader\n * would land on the local instance while the writer exported to the global one\n * and the panel would report an empty history that no session ever filled.\n */\nimport { createAsyncLogMetricsReader, resolveLogSinkInstance, resolveLogSinkPort } from '@agimon-ai/po-logsink';\n\nimport type { MetricsInstance, MetricsSource, MetricsSourceOptions, MetricsTransport } from '../../types/metricsSource';\nimport { DEFAULT_TOOL_LIMIT, queryHttp, TOKEN_SORT } from './http';\n\n/** The identity both transports resolve their sink instance from. */\ninterface ResolveIdentity {\n env?: NodeJS.ProcessEnv;\n cwd?: string;\n packageName?: string;\n serviceName?: string;\n}\n\nexport async function resolveMetricsEndpoint(options: MetricsSourceOptions = {}): Promise<string | undefined> {\n return (await resolveLogSinkPort({ ...options, healthCheck: true }))?.endpoint;\n}\n\n/**\n * A malformed `.logsink.yaml` must not take the overlay down with it. Both\n * transports still run when resolution fails; they fall back to log-sink's own\n * resolution and the panel reports an unknown instance.\n */\nfunction resolveInstance(identity: ResolveIdentity): MetricsInstance | undefined {\n try {\n const resolved = resolveLogSinkInstance(identity);\n return {\n scope: resolved.scope,\n dbPath: resolved.dbPath,\n ...(resolved.registeredName === undefined ? {} : { registeredName: resolved.registeredName }),\n };\n } catch {\n return undefined;\n }\n}\n\nexport function createMetricsSource(options: MetricsSourceOptions = {}): MetricsSource {\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n const identity = {\n env: options.env,\n cwd: options.cwd,\n packageName: options.packageName,\n serviceName: options.serviceName,\n };\n let transport: MetricsTransport | undefined;\n let endpoint: string | undefined | null;\n const instance = resolveInstance(identity);\n let workerReader = options.workerReader;\n\n const resolveEndpoint = async (): Promise<string | undefined> => {\n if (endpoint !== undefined) return endpoint ?? undefined;\n try {\n const resolved = await resolveLogSinkPort({ ...identity, healthCheck: true });\n endpoint = resolved?.endpoint ?? null;\n } catch {\n endpoint = null;\n }\n return endpoint ?? undefined;\n };\n\n return {\n lastTransport: () => transport,\n instance: () => instance,\n async query(params) {\n const httpEndpoint = await resolveEndpoint();\n if (httpEndpoint && fetchImpl) {\n try {\n const report = await queryHttp(httpEndpoint, params, fetchImpl);\n transport = 'http';\n return report;\n } catch {\n // A stale or unhealthy daemon must not hide data the worker can still read.\n endpoint = null;\n }\n }\n\n workerReader ??= createAsyncLogMetricsReader(\n instance === undefined ? { cwd: options.cwd } : { dbPath: instance.dbPath },\n );\n const report = await workerReader.getMetrics(params.filter, {\n groupBy: params.groupBy,\n period: params.period,\n sort: TOKEN_SORT,\n limit: params.limit,\n toolLimit: params.toolLimit ?? DEFAULT_TOOL_LIMIT,\n });\n transport = 'worker';\n return report;\n },\n async close() {\n await workerReader?.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,eAAsB,uBAAuB,UAAgC,CAAC,GAAgC;CAC5G,QAAQ,OAAA,GAAMA,sBAAAA,mBAAAA,CAAmB;EAAE,GAAG;EAAS,aAAa;CAAK,CAAC,EAAA,EAAI;AACxE;;;;;;AAOA,SAAS,gBAAgB,UAAwD;CAC/E,IAAI;EACF,MAAM,YAAA,GAAWC,sBAAAA,uBAAAA,CAAuB,QAAQ;EAChD,OAAO;GACL,OAAO,SAAS;GAChB,QAAQ,SAAS;GACjB,GAAI,SAAS,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB,SAAS,eAAe;EAC7F;CACF,QAAQ;EACN;CACF;AACF;AAEA,SAAgB,oBAAoB,UAAg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