aiinfra-tools 0.3.0 → 0.5.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +43 -0
  3. package/bin/aiinfra.mjs +12 -0
  4. package/fleetops/deploy/grafana-dashboard.json +71 -0
  5. package/fleetops/deploy/shadow-live/README.md +8 -0
  6. package/fleetops/deploy/shadow-live/kit.yaml +2 -0
  7. package/fleetops/deploy/shadow-live/run.sh +6 -1
  8. package/fleetops/docs/SHADOW.md +25 -2
  9. package/fleetops/package.json +1 -1
  10. package/fleetops/src/api.mjs +8 -0
  11. package/fleetops/src/ingest.mjs +9 -2
  12. package/fleetops/src/schema.mjs +3 -0
  13. package/fleetops/src/serving.mjs +11 -1
  14. package/fleetops/src/shadow-quality.mjs +107 -0
  15. package/fleetops/src/shadow.mjs +12 -6
  16. package/fleetops/tools/cmd/help.mjs +4 -1
  17. package/fleetops/tools/cmd/shadow.mjs +14 -2
  18. package/fleetscope/build.mjs +4 -0
  19. package/fleetscope/dist/index.html +809 -4
  20. package/fleetscope/package.json +1 -1
  21. package/fleetscope/src/engine.js +19 -2
  22. package/fleetscope/src/index.src.html +23 -1
  23. package/gpu-health/package.json +1 -1
  24. package/gpu-ledger/package.json +1 -1
  25. package/harness-ledger/README.md +48 -0
  26. package/harness-ledger/integrations/README.md +11 -0
  27. package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
  28. package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
  29. package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
  30. package/harness-ledger/package.json +1 -1
  31. package/harness-ledger/src/advise.mjs +410 -0
  32. package/harness-ledger/src/assess.mjs +66 -0
  33. package/harness-ledger/src/doctor.mjs +202 -0
  34. package/harness-ledger/src/engine-metrics.mjs +35 -0
  35. package/harness-ledger/src/importers.mjs +14 -3
  36. package/harness-ledger/src/lint.mjs +115 -0
  37. package/harness-ledger/src/mooncake.mjs +83 -0
  38. package/harness-ledger/src/profile.mjs +164 -0
  39. package/harness-ledger/src/record.mjs +2 -2
  40. package/harness-ledger/src/suggest.mjs +177 -0
  41. package/harness-ledger/src/trajectory.mjs +81 -0
  42. package/harness-ledger/src/workload-demo.mjs +100 -0
  43. package/harness-ledger/tools/harness-ledger.mjs +224 -5
  44. package/hybrid-tracing/package.json +1 -1
  45. package/inference-sizer/build.mjs +1 -0
  46. package/inference-sizer/dist/index.html +192 -17
  47. package/inference-sizer/docs/CATALOG.md +71 -0
  48. package/inference-sizer/docs/METHOD.md +1 -1
  49. package/inference-sizer/package.json +1 -1
  50. package/inference-sizer/src/accelerators.js +23 -1
  51. package/inference-sizer/src/catalog.js +49 -3
  52. package/inference-sizer/src/index.src.html +7 -0
  53. package/inference-sizer/src/model.js +29 -9
  54. package/inference-sizer/src/suggest.js +70 -0
  55. package/inference-sizer/src/ui.js +14 -4
  56. package/inference-sizer/tools/validate-agentx.mjs +8 -2
  57. package/inference-sizer/tools/validate-inferencex.mjs +1 -1
  58. package/mcp/README.md +3 -0
  59. package/mcp/server.mjs +22 -0
  60. package/package.json +3 -1
  61. package/schemas/README.md +3 -0
  62. package/schemas/commands.mjs +7 -0
  63. package/schemas/harness-ledger.advise.schema.json +1102 -0
  64. package/schemas/harness-ledger.assess.schema.json +2823 -0
  65. package/schemas/harness-ledger.suggest.schema.json +326 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fleetscope",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "Node editor for replaying LLM traffic on a modelled hybrid (on-prem + neocloud) GPU fleet",
@@ -42,14 +42,31 @@
42
42
  'llama-405b': { label: 'Llama 3.1 405B', params: 405, active: 405, layers: 126, kvHeads: 8, headDim: 128, mla: 0 },
43
43
  'moe-671b': { label: 'MoE 671B, 37B active (MLA)', params: 671, active: 37, layers: 61, kvHeads: 0, headDim: 0, mla: 576 }
44
44
  };
45
+ // Every other model in the Inference Sizer's catalog (one list for both tools, kept current there). kvScale: the KV a
46
+ // token holds, averaged over a 32K context, against the plain kvDim × layers figure, so sliding-window, linear-attention
47
+ // and compressed layers count; it scales with the layers and heads if they are edited.
48
+ const node = typeof module !== 'undefined' && module.exports;
49
+ const CAT = node ? require('../../inference-sizer/src/catalog.js') : root.SizerCatalog, SZ = node ? require('../../inference-sizer/src/model.js') : root.SizerModel;
50
+ const kvDimTotal = m => (m.mla ? m.layers * m.mla : 2 * m.layers * m.kvHeads * m.headDim);
51
+ for (const k of Object.keys(MODELS)) MODELS[k].kvScale = 1;
52
+ const IN_LIST = { 'llama31-8b': 'llama-8b', 'llama33-70b': 'llama-70b', 'llama31-405b': 'llama-405b', 'deepseek-v3': 'moe-671b' };
53
+ if (CAT && SZ) {
54
+ for (const c of CAT.MODELS) {
55
+ if (IN_LIST[c.id] || MODELS[c.id]) continue;
56
+ const m = { label: c.name, params: c.total, active: c.active, layers: c.layers, kvHeads: c.attn === 'mla' ? 0 : c.kvHeads, headDim: c.attn === 'mla' ? 0 : c.headDim, mla: c.attn === 'mla' ? (c.mlaLatent || 512) + (c.mlaRope == null ? 64 : c.mlaRope) : 0 };
57
+ const md = SZ.derive(Object.assign({}, SZ.SETTINGS, CAT.MODEL_DEFAULTS, c, { kvprec: 'fp8', tfBf16: 1, hbmTBs: 1, scaleUpGBs: 1, nicGbps: 1, hbmGB: 1 }));
58
+ m.kvScale = +(SZ.kvBytes(md, 32768) / 32768 / kvDimTotal(m)).toFixed(4);
59
+ MODELS[c.id] = m;
60
+ }
61
+ }
45
62
 
46
63
  // ---------- performance profile ----------
47
64
  // tpFixed: GPUs per instance set on the pool (0 or absent = smallest power of two whose share of the weights fits).
48
65
  function profile(gpuKey, m, tpFixed) {
49
66
  const G = GPUS[gpuKey];
50
- const wBytes = m.params * 1e9 * (m.wPrec === 'bf16' ? 2 : 1);
67
+ const wBytes = m.params * 1e9 * (m.wPrec === 'bf16' ? 2 : m.wPrec === 'fp4' ? 0.5625 : 1);
51
68
  const kvElem = m.kvPrec === 'bf16' ? 2 : 1;
52
- const kvBytesPerToken = m.mla ? m.layers * m.mla * kvElem : 2 * m.layers * m.kvHeads * m.headDim * kvElem;
69
+ const kvBytesPerToken = kvDimTotal(m) * kvElem * (m.kvScale > 0 ? m.kvScale : 1);
53
70
  let tp = 1;
54
71
  if (tpFixed > 0) tp = Math.round(tpFixed);
55
72
  else while (tp < 16 && wBytes / tp > 0.65 * G.hbm * 1e9) tp *= 2;
@@ -228,6 +228,9 @@ button, select, input { font: inherit; color: inherit; }
228
228
  .mtx th:first-child, .mtx td:first-child { text-align: left; }
229
229
  .mtx input[type=number] { width: 52px; padding: 2px 4px; border: 1px solid var(--line); border-radius: 5px; background: var(--panel); }
230
230
  .kpi.wide { grid-column: span 2; cursor: pointer; }
231
+ .kpi.try { cursor: default; } .kpi.try .tries { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
232
+ .kpi.try .tryb, .kpi.try .tryt { font: 12px var(--font-ui); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); background: var(--bg); color: inherit; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
233
+ .kpi.try .tryb { cursor: pointer; } .kpi.try .tryb:hover { border-color: currentColor; }
231
234
  .kpi.wide .v { font-size: 13.5px; font-family: var(--font-ui); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
232
235
  .legendHud { position: absolute; left: 10px; bottom: 8px; display: flex; gap: 10px; font-size: 11px; color: var(--muted); background: color-mix(in srgb, var(--panel) 80%, transparent); padding: 3px 8px; border-radius: 6px; }
233
236
  .legendHud i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 4px; vertical-align: 0; }
@@ -388,6 +391,15 @@ button, select, input { font: inherit; color: inherit; }
388
391
  /*ACCELERATORS*/
389
392
  </script>
390
393
  <script>
394
+ /*SIZERCATALOG*/
395
+ </script>
396
+ <script>
397
+ /*SIZERMODEL*/
398
+ </script>
399
+ <script>
400
+ /*SIZERSUGGEST*/
401
+ </script>
402
+ <script>
391
403
  /*ENGINE*/
392
404
  </script>
393
405
  <script>
@@ -1678,9 +1690,19 @@ function renderKpis() {
1678
1690
  t1('Days / 100B tokens', t.daysPer100B.toFixed(1), 'train', t.daysPer100B, bt.daysPer100B, true, v => v.toFixed(1));
1679
1691
  t1('Training $ / hour', fUsd(t.costPerHr), 'train', t.costPerHr, bt.costPerHr, true, fUsd);
1680
1692
  }
1693
+ // what to try next: one-click what-ifs for the Ask box, from the first bottleneck and the cache (SizerSuggest.forFleet)
1694
+ if (s.requests && window.SizerSuggest) {
1695
+ const tries = SizerSuggest.forFleet(s);
1696
+ if (tries.length) tiles.push('<div class="kpi wide try"><div class="k">What to try</div><div class="tries">' + tries.map(x => x.ask
1697
+ ? '<button type="button" class="tryb" data-ask="' + esc(x.ask) + '" title="' + esc(x.title) + ': ' + esc(x.why) + ' \u2014 runs: ' + esc(x.ask) + '">' + esc(x.title) + '</button>'
1698
+ : '<span class="tryt" title="' + esc(x.why) + '">' + esc(x.title) + '</span>').join('') + '</div></div>');
1699
+ }
1681
1700
  $('#kpis').innerHTML = tiles.join('');
1682
1701
  }
1683
- $('#kpis').addEventListener('click', e => { const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek); });
1702
+ $('#kpis').addEventListener('click', e => {
1703
+ const a = e.target.closest('[data-ask]'); if (a) { $('#askBox').value = a.dataset.ask; $('#askForm').requestSubmit(); return; }
1704
+ const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek);
1705
+ });
1684
1706
 
1685
1707
  // ---------- charts ----------
1686
1708
  const CH = { w: 420, h: 150, l: 38, r: 8, t: 8, b: 18 };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gpu-health",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "GPU health checks, efficiency and savings analysis, and an approval queue that runs fixes once approved.",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gpu-ledger",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "GPU billing and waste for any cluster: who used which GPUs, what it cost, how much was useful, and where to save. Exports FOCUS.",
@@ -120,6 +120,54 @@ On TraceLab's workload, with SWE-bench success rates ([VALIDATION-ECONOMICS.md](
120
120
  - **Pooled teams:** at $3 a GPU-hour on B200 it wins from about 8–16× that volume.
121
121
  - **Context:** half the calls exceed those models' 128k context.
122
122
 
123
+ ## Assess, doctor, optimize
124
+
125
+ ```
126
+ harness-ledger assess traces/ [--requests gateway.jsonl] [--engine-metrics http://vllm:8000] # all three below, one report
127
+ harness-ledger profile traces/ --critical 'harness:payments-*' # classes, token ratios, what bounds each
128
+ harness-ledger doctor traces/ --requests gateway.jsonl # why the prefix cache misses, and what to change
129
+ harness-ledger advise traces/ --goal ttft [--model deepseek-v3 --gpu H200 --gpus 64] [--apply IDS] [--fail-if 'ttft>+5%']
130
+ ```
131
+
132
+ - **The profile** puts each session in one of five classes: critical, realtime, agentic, reasoning or batch. For each
133
+ class it reports input:output tokens, the share read from cache, fresh tokens per output token, context and output
134
+ percentiles and pauses past the cache lifetime, and from those, whether prefill, decode or the KV cache bounds it.
135
+ - **The doctor** compares the hit rate now with what the same calls could reach. With request bodies, it names the
136
+ first point where each request stops matching the previous one and why (a timestamp in the system prompt, reordered
137
+ tools, JSON key order and so on), keeping only hashes and positions. With the engine's metrics, it gives the
138
+ server-side hit rate against what the traces could reuse.
139
+ - **The optimizer** prices every change across the stack that moves the goal. On an API, each change is measured on
140
+ the recorded calls changed as the change would change them. Self-hosted, it also uses the Inference Sizer's operating
141
+ point. It gives the best combination, the best at no extra cost and the best with no quality risk, then a dry run of
142
+ the ones you pick.
143
+
144
+ See [docs/OPTIMIZE.md](../docs/OPTIMIZE.md).
145
+
146
+ ## Suggestions, prompt lint, and where they show up
147
+
148
+ ```
149
+ harness-ledger suggest traces/ [--watch 3600 --since 24h] [--store DIR] [--slack URL|--lark URL] [--langfuse] [--live]
150
+ harness-ledger suggest list | accept ID | dismiss ID | snooze ID --for 2w | reopen ID
151
+ harness-ledger lint prompts/ [--md] [--fail] # a per-call value before static text, in a template
152
+ harness-ledger mooncake trace.jsonl --sim-replicas 8 # prefix reuse by cache size; random vs prefix routing
153
+ harness-ledger mooncake --requests gateway.jsonl --out trace.jsonl # your traffic as a Mooncake trace, no text
154
+ ```
155
+
156
+ `suggest` raises each change once, again only if it grows by half, and remembers what people decided. It also feeds:
157
+
158
+ - the Claude Code hook and status line (`integrations/claude-code/`);
159
+ - the LiteLLM prefix linter (`integrations/litellm/`);
160
+ - the Grafana panel, through a fleetops store;
161
+ - Slack and Lark/Feishu cards;
162
+ - comments on Langfuse sessions.
163
+
164
+ Two more input formats are detected:
165
+
166
+ - **`trajectory`:** agent runs with full message lists, such as SWE-agent or OpenHands datasets exported to JSON lines.
167
+ - **`mooncake`:** serving traces with chained block hashes.
168
+
169
+ See [docs/SUGGEST.md](../docs/SUGGEST.md).
170
+
123
171
  ## On real data
124
172
 
125
173
  - **Real coding-agent use** ([VALIDATION-TRACELAB.md](docs/VALIDATION-TRACELAB.md)). On TraceLab (8,058 Claude Code
@@ -0,0 +1,11 @@
1
+ # Integrations
2
+
3
+ Where harness-ledger's findings show up without anyone running a report. See [docs/SUGGEST.md](../../docs/SUGGEST.md).
4
+
5
+ | Folder | What | Set up |
6
+ |---|---|---|
7
+ | [claude-code/](claude-code/) | Hooks that show cache misses and tool-output waste in Claude Code (last session at start, live warnings after a response), and a status line with the live cache hit rate | `aiinfra claude-code-hook --print-settings` → `~/.claude/settings.json` |
8
+ | [litellm/](litellm/) | A LiteLLM proxy callback that reports each request that breaks its session's prompt prefix, and why (Prometheus counters, one log line per template and cause) | `callbacks: aiinfra_prefix_lint.proxy_handler_instance` in the proxy's `litellm_settings` |
9
+
10
+ Both read only what passes through them, keep counts and hashes (no prompt text), and never block or change a session
11
+ or a request.
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+ // A Claude Code hook: tells you, in Claude Code, when a session wasted tokens on the prompt cache or on oversized tool
3
+ // output, at the moment you can still do something about it. It reads only the session's own transcript, on your
4
+ // machine, and keeps counts (no prompt or tool text) in ~/.aiinfra/claude-code/ (or $AIINFRA_STATE/claude-code/).
5
+ //
6
+ // SessionEnd analyzes the finished session and keeps a one-line summary
7
+ // SessionStart shows the previous session's summary once, if it found something worth changing
8
+ // Stop (optional; run it async) after each response, warns once per session per problem as it happens:
9
+ // a cache miss that re-sent a large context, a pause that let the cache expire, a huge tool result
10
+ // The message is a hook systemMessage, shown to you, not added to Claude's context.
11
+ //
12
+ // Settings (~/.claude/settings.json or .claude/settings.json): node aiinfra-hook.mjs --print-settings
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { claudeCode } from '../../src/importers.mjs';
18
+ import { ledger } from '../../src/ledger.mjs';
19
+
20
+ const HERE = fileURLToPath(import.meta.url);
21
+ export const THRESHOLDS = { missTokens: 50000, bigResult: 20000, minWasteShare: 0.15, minTokens: 100000 };
22
+ export const stateDir = () => path.join(process.env.AIINFRA_STATE || path.join(os.homedir(), '.aiinfra'), 'claude-code');
23
+ const n = v => (v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : v >= 1e3 ? `${Math.round(v / 1e3)}k` : String(Math.round(v)));
24
+
25
+ // one transcript (and its subagents' transcripts beside it) → what went to waste
26
+ export function analyze(transcriptPath, { cacheTtlS = 300 } = {}) {
27
+ const files = [transcriptPath], sub = path.join(path.dirname(transcriptPath), path.basename(transcriptPath, '.jsonl'), 'subagents');
28
+ if (fs.existsSync(sub)) for (const f of fs.readdirSync(sub)) if (f.endsWith('.jsonl')) files.push(path.join(sub, f));
29
+ const calls = files.flatMap(f => { try { return claudeCode(fs.readFileSync(f, 'utf8'), { file: f }); } catch { return []; } });
30
+ if (!calls.length) return null;
31
+ const r = ledger(calls, { cacheTtlS }), T = r.report.totals;
32
+ const by = c => r.findings.filter(f => f.cause === c);
33
+ const sum = (xs, k) => xs.reduce((a, x) => a + (x[k] || 0), 0);
34
+ const miss = by('cache-miss'), exp = by('cache-expired'), bloat = by('tool-output-bloat');
35
+ const tools = {}; for (const f of bloat) tools[f.tool] = (tools[f.tool] || 0) + f.tokens;
36
+ return { session: calls[0].session, calls: calls.length, input: T.input, cacheRead: T.cacheRead, hit: T.input ? T.cacheRead / T.input : null, cost: T.cost,
37
+ missed: { count: miss.length, tokens: sum(miss, 'tokens'), cost: sum(miss, 'cost') }, expired: { count: exp.length, tokens: sum(exp, 'tokens'), cost: sum(exp, 'cost') },
38
+ bloat: { count: bloat.length, tokens: sum(bloat, 'tokens'), cost: sum(bloat, 'cost'), tools }, avoidable: T.avoidableTokens || 0, avoidableCost: T.avoidableCost || 0,
39
+ lastCallT: calls.reduce((a, c) => Math.max(a, c.t || 0), 0), findings: r.findings.map(f => ({ cause: f.cause, at: f.at, tokens: f.tokens, tool: f.tool })) };
40
+ }
41
+
42
+ // the summary worth showing, or null when the session was fine
43
+ export function message(A, { thresholds = THRESHOLDS, prefix = 'aiinfra', transcript = null } = {}) {
44
+ if (!A || A.input < thresholds.minTokens) return null;
45
+ const parts = [];
46
+ if (A.missed.tokens >= thresholds.missTokens) parts.push(`${n(A.missed.tokens)} tokens re-sent after ${A.missed.count} cache miss${A.missed.count === 1 ? '' : 'es'} (the prompt prefix changed)`);
47
+ if (A.expired.tokens >= thresholds.missTokens) parts.push(`${n(A.expired.tokens)} re-sent after ${A.expired.count} pause${A.expired.count === 1 ? '' : 's'} past the cache lifetime`);
48
+ const top = Object.entries(A.bloat.tools).sort((a, b) => b[1] - a[1])[0];
49
+ if (top && A.bloat.tokens >= thresholds.bigResult) parts.push(`${n(A.bloat.tokens)} from oversized tool output (mostly ${top[0]})`);
50
+ if (!parts.length || A.avoidable / A.input < thresholds.minWasteShare && A.missed.tokens < thresholds.missTokens * 4) return null;
51
+ return `${prefix}: ${Math.round(100 * (A.hit ?? 0))}% of input came from cache; ${parts.join('; ')}.` + (A.avoidableCost ? ` About $${A.avoidableCost.toFixed(2)} avoidable.` : '') + ` Details: aiinfra harness-ledger doctor ${transcript ? JSON.stringify(transcript) : '<transcript>'}`;
52
+ }
53
+
54
+ // Stop: problems that appeared since the last check of this session, each kind raised once per session
55
+ export function live(A, seen, { thresholds = THRESHOLDS } = {}) {
56
+ const out = [];
57
+ const add = (key, text) => { if (!seen.includes(key)) { seen.push(key); out.push(text); } };
58
+ const big = A.findings.filter(f => (f.cause === 'cache-miss' || f.cause === 'cache-expired') && f.tokens >= thresholds.missTokens);
59
+ if (big.some(f => f.cause === 'cache-miss')) add('miss', `a cache miss re-sent ${n(Math.max(...big.filter(f => f.cause === 'cache-miss').map(f => f.tokens)))} tokens: something early in the prompt changed (a file re-read into the system prompt, tools changing, a /model switch)`);
60
+ if (big.some(f => f.cause === 'cache-expired')) add('expired', 'a pause past the cache lifetime made the next turn re-read the whole context: after a long pause, /compact first (the cache is gone anyway, so the summary is the cheapest thing to re-read)');
61
+ const huge = A.findings.filter(f => f.cause === 'tool-output-bloat' && f.tokens >= thresholds.bigResult);
62
+ if (huge.length) add(`bloat:${huge[0].tool}`, `${huge[0].tool} returned more than ${n(thresholds.bigResult)} tokens, which every later turn re-sends: narrow it (a line range, a head, a grep)`);
63
+ return out.length ? `aiinfra: ${out.join('; ')}.` : null;
64
+ }
65
+
66
+ const readJson = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
67
+ const writeJson = (f, v) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, JSON.stringify(v, null, 1) + '\n'); };
68
+
69
+ export function handle(input, { dir = stateDir(), thresholds = THRESHOLDS } = {}) {
70
+ const ev = input.hook_event_name, tp = input.transcript_path && input.transcript_path.replace(/^~(?=\/)/, os.homedir());
71
+ if (ev === 'SessionEnd') {
72
+ if (!tp || !fs.existsSync(tp)) return null;
73
+ const A = analyze(tp); if (!A) return null;
74
+ const msg = message(A, { thresholds, transcript: tp });
75
+ fs.mkdirSync(dir, { recursive: true });
76
+ fs.appendFileSync(path.join(dir, 'sessions.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), session: input.session_id || A.session, cwd: input.cwd || null, calls: A.calls, input: A.input, hit: A.hit, missed: A.missed.tokens, expired: A.expired.tokens, bloat: A.bloat.tokens, avoidable: A.avoidable, avoidableCost: A.avoidableCost }) + '\n');
77
+ writeJson(path.join(dir, 'last.json'), { session: input.session_id || A.session, message: msg, shown: false, t: Math.floor(Date.now() / 1000) });
78
+ return null;
79
+ }
80
+ if (ev === 'SessionStart') {
81
+ const f = path.join(dir, 'last.json'), last = readJson(f);
82
+ if (!last || last.shown || !last.message || last.session === input.session_id) return null;
83
+ last.shown = true; writeJson(f, last);
84
+ return { systemMessage: `${last.message.replace(/^aiinfra:/, 'aiinfra (last session):')}` };
85
+ }
86
+ if (ev === 'Stop' || ev === 'SubagentStop') {
87
+ if (!tp || !fs.existsSync(tp)) return null;
88
+ const A = analyze(tp); if (!A) return null;
89
+ const f = path.join(dir, 'live', `${String(input.session_id || A.session).replace(/[^\w.-]/g, '_')}.json`), st = readJson(f) || { seen: [] };
90
+ const msg = live(A, st.seen, { thresholds }); writeJson(f, st);
91
+ return msg ? { systemMessage: msg } : null;
92
+ }
93
+ return null;
94
+ }
95
+
96
+ export function settingsSnippet(script = HERE) {
97
+ const cmd = `node "${script}"`;
98
+ return { hooks: {
99
+ SessionEnd: [{ hooks: [{ type: 'command', command: cmd, timeout: 10 }] }],
100
+ SessionStart: [{ hooks: [{ type: 'command', command: cmd, timeout: 10 }] }],
101
+ Stop: [{ hooks: [{ type: 'command', command: cmd, async: true, timeout: 30 }] }],
102
+ }, statusLine: { type: 'command', command: `node "${path.join(path.dirname(script), 'aiinfra-statusline.mjs')}"` } };
103
+ }
104
+
105
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === HERE) {
106
+ if (process.argv.includes('--print-settings')) { process.stdout.write(JSON.stringify(settingsSnippet(), null, 2) + '\n'); process.exit(0); }
107
+ let raw = ''; process.stdin.setEncoding('utf8');
108
+ process.stdin.on('data', c => { raw += c; if (raw.length > 1 << 20) process.stdin.destroy(); });
109
+ process.stdin.on('end', () => {
110
+ // a hook must never get in the way of the session: any failure is silent (exit 0, nothing printed)
111
+ try { const out = handle(JSON.parse(raw || '{}')); if (out) process.stdout.write(JSON.stringify(out) + '\n'); } catch (e) { if (process.env.AIINFRA_DEBUG) process.stderr.write(`aiinfra-hook: ${e.message}\n`); }
112
+ });
113
+ }
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ // A Claude Code status line: the session's prompt-cache hit rate and what went to waste so far, always in view.
3
+ // cache 84% · re-sent 1.2M · ~$0.80 avoidable
4
+ // Claude Code runs it with the session as JSON on stdin (transcript_path among it); the result is cached by the
5
+ // transcript's size so a refresh doesn't re-read an unchanged session. Settings: aiinfra-hook.mjs --print-settings
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { analyze, stateDir } from './aiinfra-hook.mjs';
11
+
12
+ const n = v => (v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : v >= 1e3 ? `${Math.round(v / 1e3)}k` : String(Math.round(v)));
13
+ export function line(A) {
14
+ if (!A) return 'cache –';
15
+ const resent = A.missed.tokens + A.expired.tokens, parts = [`cache ${A.hit == null ? '–' : Math.round(100 * A.hit) + '%'}`];
16
+ if (resent >= 1000) parts.push(`re-sent ${n(resent)}`);
17
+ if (A.bloat.tokens >= 1000) parts.push(`tool output +${n(A.bloat.tokens)}`);
18
+ if (A.avoidableCost >= 0.01) parts.push(`~$${A.avoidableCost.toFixed(2)} avoidable`);
19
+ return parts.join(' · ');
20
+ }
21
+ export function statusFor(input, { dir = stateDir() } = {}) {
22
+ const tp = input.transcript_path && input.transcript_path.replace(/^~(?=\/)/, os.homedir());
23
+ if (!tp || !fs.existsSync(tp)) return 'cache –';
24
+ const size = fs.statSync(tp).size, f = path.join(dir, 'statusline', `${path.basename(tp)}.json`);
25
+ try { const c = JSON.parse(fs.readFileSync(f, 'utf8')); if (c.size === size) return c.line; } catch { /* first look */ }
26
+ const out = line(analyze(tp));
27
+ try { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, JSON.stringify({ size, line: out })); } catch { /* read-only home: still print */ }
28
+ return out;
29
+ }
30
+
31
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
32
+ let raw = ''; process.stdin.setEncoding('utf8');
33
+ process.stdin.on('data', c => { raw += c; });
34
+ process.stdin.on('end', () => { try { process.stdout.write(statusFor(JSON.parse(raw || '{}')) + '\n'); } catch { process.stdout.write('cache –\n'); } });
35
+ }
@@ -0,0 +1,247 @@
1
+ """A prefix-cache linter for the LiteLLM proxy: watches requests as they pass and reports, live, every request that
2
+ breaks its session's prompt prefix and why, and every prompt that carries a changing value near its front.
3
+
4
+ It never changes or blocks a request. It keeps, per session, only hashes of the previous request's parts (tools,
5
+ system prompt, each message) and their estimated token counts; no prompt text is stored or logged.
6
+
7
+ What it reports (the same causes as `harness-ledger doctor --requests`):
8
+ model-switch, tools-changed, tools-reordered, json-key-order, whitespace, system-dynamic (a timestamp, date, id or
9
+ number changed in the system prompt), system-edited, history-edited, history-truncated
10
+ dynamic-in-prefix: a timestamp, date, UUID or request id in the tools or system prompt of a session's first request
11
+
12
+ Where it reports:
13
+ Prometheus (when prometheus_client is installed; the proxy's /metrics):
14
+ aiinfra_prefix_breaks_total{cause, model} requests that broke their session's prefix
15
+ aiinfra_prefix_broken_tokens_total{cause, model} tokens re-prefilled because of it
16
+ aiinfra_dynamic_in_prefix_total{kind, model} first requests with a changing value in their prefix
17
+ the log (logger "aiinfra.prefix_lint"): one warning per prompt template and cause, not one per request
18
+ a JSON-lines file of events, counts and hashes only, when AIINFRA_PREFIX_LINT_LOG names one
19
+
20
+ LiteLLM proxy config:
21
+ litellm_settings:
22
+ callbacks: aiinfra_prefix_lint.proxy_handler_instance
23
+ (with this file on the proxy's Python path, e.g. next to config.yaml). The session comes from the request's
24
+ metadata.session_id (or litellm_session_id, or the "user" field); requests with none are linted for layout only.
25
+ """
26
+ import hashlib
27
+ import json
28
+ import logging
29
+ import os
30
+ import re
31
+ import threading
32
+ import time
33
+ from collections import OrderedDict
34
+
35
+ try: # the proxy provides it; the tests run without LiteLLM installed
36
+ from litellm.integrations.custom_logger import CustomLogger
37
+ except ImportError: # pragma: no cover - exercised only when LiteLLM is absent
38
+ class CustomLogger: # type: ignore
39
+ pass
40
+
41
+ try:
42
+ from prometheus_client import Counter
43
+ except ImportError: # pragma: no cover
44
+ Counter = None
45
+
46
+ LOG = logging.getLogger("aiinfra.prefix_lint")
47
+ DYNAMIC = [
48
+ ("timestamp", re.compile(r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?\b")),
49
+ ("date", re.compile(r"\b(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{2,4}|(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*,? \w+ \d{1,2})\b")),
50
+ ("time", re.compile(r"\b\d{1,2}:\d{2}(?::\d{2})?\s?(?:[AaPp][Mm])?\b")),
51
+ ("uuid", re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.I)),
52
+ ("id", re.compile(r"\b(?:req|msg|run|sess|trace|span|call|chatcmpl)[-_][A-Za-z0-9]{6,}\b|\b[0-9a-f]{16,}\b", re.I)),
53
+ ("number", re.compile(r"\b\d{3,}\b")),
54
+ ]
55
+
56
+
57
+ def _h(s):
58
+ return hashlib.sha256(s.encode("utf-8")).hexdigest()[:12]
59
+
60
+
61
+ def _j(v):
62
+ return v if isinstance(v, str) else json.dumps(v, ensure_ascii=False, separators=(",", ":"))
63
+
64
+
65
+ def _canon(v):
66
+ if isinstance(v, list):
67
+ return [_canon(x) for x in v]
68
+ if isinstance(v, dict):
69
+ return {k: _canon(v[k]) for k in sorted(v)}
70
+ return v
71
+
72
+
73
+ def _strip(s):
74
+ for _, rx in DYNAMIC:
75
+ s = rx.sub("∎", s)
76
+ return s
77
+
78
+
79
+ def _ws(s):
80
+ return re.sub(r"\s+", " ", s).strip()
81
+
82
+
83
+ def found(s):
84
+ """The kinds of changing value in a text; each match is removed before the next kind is looked for."""
85
+ out = []
86
+ for kind, rx in DYNAMIC:
87
+ if rx.search(s):
88
+ out.append(kind)
89
+ s = rx.sub("∎", s)
90
+ return out
91
+
92
+
93
+ def segments(req):
94
+ """A request's parts in the order a prompt cache sees them: tools, system, messages."""
95
+ segs = []
96
+
97
+ def add(kind, v, names=None):
98
+ raw = _j(v)
99
+ segs.append({"kind": kind, "raw": _h(raw), "canon": _h(_j(_canon(v))), "ws": _h(_ws(raw)), "dyn": _h(_ws(_strip(raw))),
100
+ "tokens": (len(raw) + 3) // 4, "dynamic": found(raw) if kind != "message" else [], "names": names})
101
+
102
+ tools = req.get("tools") or req.get("functions")
103
+ if isinstance(tools, list) and tools:
104
+ add("tools", tools, [t.get("name") or (t.get("function") or {}).get("name") or "?" for t in tools if isinstance(t, dict)])
105
+ msgs = req.get("messages") if isinstance(req.get("messages"), list) else []
106
+ system, i0 = req.get("system"), 0
107
+ if system is None:
108
+ parts = []
109
+ while i0 < len(msgs) and isinstance(msgs[i0], dict) and msgs[i0].get("role") in ("system", "developer"):
110
+ parts.append(msgs[i0].get("content"))
111
+ i0 += 1
112
+ if parts:
113
+ system = parts[0] if len(parts) == 1 else parts
114
+ if system is not None:
115
+ add("system", system)
116
+ for m in msgs[i0:]:
117
+ add("message", m)
118
+ return segs
119
+
120
+
121
+ def diverge(prev_model, prev, model, cur):
122
+ """Where and why this request stops matching the previous one, or None when the previous one is its prefix."""
123
+ if prev_model and model and prev_model != model:
124
+ return {"cause": "model-switch", "stable": 0, "patterns": []}
125
+ stable = 0
126
+ for i, a in enumerate(prev):
127
+ b = cur[i] if i < len(cur) else None
128
+ if b is None:
129
+ return {"cause": "history-truncated", "stable": stable, "patterns": []}
130
+ if a["kind"] != b["kind"]:
131
+ k = "tools-changed" if "tools" in (a["kind"], b["kind"]) else "system-edited" if "system" in (a["kind"], b["kind"]) else "history-edited"
132
+ return {"cause": k, "stable": stable, "patterns": []}
133
+ if a["raw"] == b["raw"]:
134
+ stable += a["tokens"]
135
+ continue
136
+ if a["canon"] == b["canon"]:
137
+ cause = "json-key-order"
138
+ elif a["ws"] == b["ws"]:
139
+ cause = "whitespace"
140
+ elif a["kind"] == "tools":
141
+ same = len(a["names"]) == len(b["names"]) and sorted(a["names"]) == sorted(b["names"]) and a["names"] != b["names"]
142
+ cause = "tools-reordered" if same else "tools-changed"
143
+ elif a["dyn"] == b["dyn"]:
144
+ cause = "system-dynamic" if a["kind"] == "system" else "history-edited"
145
+ else:
146
+ cause = "system-edited" if a["kind"] == "system" else "history-edited"
147
+ pats = sorted(set(a["dynamic"]) | set(b["dynamic"])) if cause == "system-dynamic" else []
148
+ return {"cause": cause, "stable": stable, "patterns": pats}
149
+ return None
150
+
151
+
152
+ class PrefixLint(CustomLogger):
153
+ def __init__(self, max_sessions=20000, log_file=None, now=time.time):
154
+ self.sessions = OrderedDict()
155
+ self.max_sessions = max_sessions
156
+ self.warned = set()
157
+ self.lock = threading.Lock()
158
+ self.log_file = log_file if log_file is not None else os.environ.get("AIINFRA_PREFIX_LINT_LOG")
159
+ self.now = now
160
+ self.counts = {}
161
+ self.metrics = None
162
+ if Counter is not None:
163
+ try:
164
+ self.metrics = {
165
+ "breaks": Counter("aiinfra_prefix_breaks_total", "Requests that broke their session's prompt prefix", ["cause", "model"]),
166
+ "tokens": Counter("aiinfra_prefix_broken_tokens_total", "Tokens re-prefilled after a broken prefix", ["cause", "model"]),
167
+ "dynamic": Counter("aiinfra_dynamic_in_prefix_total", "First requests with a changing value in their prefix", ["kind", "model"]),
168
+ }
169
+ except ValueError: # already registered (a second instance in one process): count locally only
170
+ self.metrics = None
171
+
172
+ @staticmethod
173
+ def session_of(data):
174
+ md = data.get("metadata") or {}
175
+ for v in (md.get("session_id"), md.get("litellm_session_id"), data.get("litellm_session_id"), data.get("user")):
176
+ if v:
177
+ return str(v)
178
+ return None
179
+
180
+ def _event(self, ev):
181
+ key = (ev["kind"], ev.get("cause") or ev.get("pattern"))
182
+ self.counts[key] = self.counts.get(key, 0) + 1
183
+ if self.log_file:
184
+ try:
185
+ with open(self.log_file, "a", encoding="utf-8") as f:
186
+ f.write(json.dumps(ev) + "\n")
187
+ except OSError:
188
+ pass
189
+
190
+ def observe(self, data):
191
+ """Lint one request body. Returns the events it produced (also counted, logged once per template and cause)."""
192
+ if not isinstance(data, dict):
193
+ return []
194
+ model, session = str(data.get("model") or ""), self.session_of(data)
195
+ segs = segments(data)
196
+ prefix = [s for s in segs if s["kind"] != "message"]
197
+ template = _h("|".join(s["canon"] if s["kind"] == "tools" else s["dyn"] for s in prefix))
198
+ events, t = [], round(self.now(), 3)
199
+ with self.lock:
200
+ prev = self.sessions.pop(session, None) if session else None
201
+ if session:
202
+ self.sessions[session] = (model, segs)
203
+ while len(self.sessions) > self.max_sessions:
204
+ self.sessions.popitem(last=False)
205
+ if prev is None:
206
+ total, pos = sum(s["tokens"] for s in prefix), 0
207
+ for s in prefix:
208
+ for kind in s["dynamic"]:
209
+ if kind in ("number", "time"):
210
+ continue
211
+ events.append({"t": t, "kind": "dynamic-in-prefix", "pattern": kind, "segment": s["kind"], "at": round(pos / total, 3) if total else 0, "template": template, "model": model, "session": session})
212
+ pos += s["tokens"]
213
+ else:
214
+ d = diverge(prev[0], prev[1], model, segs)
215
+ if d:
216
+ prev_total = sum(s["tokens"] for s in prev[1])
217
+ lost = max(0, min(prev_total, sum(s["tokens"] for s in segs)) - d["stable"])
218
+ events.append({"t": t, "kind": "prefix-break", "cause": d["cause"], "tokens": lost, "patterns": d["patterns"], "template": template, "model": model, "session": session})
219
+ for ev in events:
220
+ self._event(ev)
221
+ if self.metrics:
222
+ if ev["kind"] == "prefix-break":
223
+ self.metrics["breaks"].labels(ev["cause"], model).inc()
224
+ self.metrics["tokens"].labels(ev["cause"], model).inc(ev["tokens"])
225
+ else:
226
+ self.metrics["dynamic"].labels(ev["pattern"], model).inc()
227
+ wkey = (template, ev.get("cause") or ev.get("pattern"))
228
+ if wkey not in self.warned:
229
+ self.warned.add(wkey)
230
+ if ev["kind"] == "prefix-break":
231
+ LOG.warning("aiinfra prefix lint: %s broke the prompt prefix (%s tokens re-prefilled%s; template %s, model %s)",
232
+ ev["cause"], ev["tokens"], ", " + "/".join(ev["patterns"]) if ev["patterns"] else "", template, model)
233
+ else:
234
+ LOG.warning("aiinfra prefix lint: a %s in the %s, %d%% into the prefix, will break the cache on every request (template %s, model %s)",
235
+ ev["pattern"], "system prompt" if ev["segment"] == "system" else "tool definitions", int(100 * ev["at"]), template, model)
236
+ return events
237
+
238
+ # LiteLLM proxy hook: called with the request body before it is sent; returned unchanged
239
+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
240
+ try:
241
+ self.observe(data)
242
+ except Exception as e: # pragma: no cover - a linter must never fail a request
243
+ LOG.debug("aiinfra prefix lint skipped a request: %s", e)
244
+ return data
245
+
246
+
247
+ proxy_handler_instance = PrefixLint()
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-ledger",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "Where agent harnesses waste model resources, across harnesses: cache misses, bloated tool output, repeats, retries, unused tools; in tokens, dollars and GPU time.",