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
@@ -0,0 +1,164 @@
1
+ // Workload profile: what kinds of traffic the model calls are, how their tokens split, and what each kind needs.
2
+ //
3
+ // Each session gets one class:
4
+ // critical only from a class map (a business decision, not something the traces can show)
5
+ // batch single-call sessions without tools that arrive in bursts, or whose harness/agent is named like a job
6
+ // (batch, eval, offline, nightly, bulk, etl); or from the class map
7
+ // reasoning reasoning tokens are ≥ 30% of output, or long answers to short prompts (output ≥ 2,000 and input:output ≤ 5)
8
+ // agentic tool calls, or three or more calls in the session
9
+ // realtime the rest: short interactive exchanges
10
+ // A class map ({ "critical": ["agent:payments-*"], "batch": ["harness:nightly-eval"] }) overrides the heuristics; a
11
+ // pattern is field:glob over harness, agent, session or model.
12
+ //
13
+ // Per class: calls and sessions, the input:output token ratio, how much input came from the prompt cache, fresh input
14
+ // per output token (what prefill does for each token decode makes), context and output percentiles, calls per session,
15
+ // the pauses between calls (and how many outlast the cache), the busiest minute, and what share of the context's growth
16
+ // is tool results. From those, the class's likely bottleneck (prefill, decode or the KV cache) and advice for it.
17
+ import { sessionsOf } from './record.mjs';
18
+
19
+ export const CLASSES = ['critical', 'realtime', 'agentic', 'reasoning', 'batch'];
20
+ const JOB = /batch|eval|offline|nightly|bulk|etl|backfill|cron/i;
21
+ const q = (xs, p) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(p * (s.length - 1)))]; };
22
+ const sum = (xs, f) => xs.reduce((a, x) => a + (f(x) || 0), 0);
23
+ const glob = g => new RegExp('^' + String(g).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$', 'i');
24
+
25
+ // { class: [patterns] } → (session calls) → class | null
26
+ export function classMatcher(map) {
27
+ if (!map) return () => null;
28
+ const rules = [];
29
+ for (const [cls, pats] of Object.entries(map)) {
30
+ if (!CLASSES.includes(cls)) throw new Error(`class map: unknown class "${cls}" (one of ${CLASSES.join(', ')})`);
31
+ for (const p of [].concat(pats)) {
32
+ const m = String(p).match(/^(harness|agent|session|model):(.+)$/);
33
+ if (!m) throw new Error(`class map: "${p}" should be field:pattern, field one of harness, agent, session, model`);
34
+ rules.push({ cls, field: m[1], re: glob(m[2]) });
35
+ }
36
+ }
37
+ // critical first: a session that matches two rules gets the stricter one
38
+ rules.sort((a, b) => CLASSES.indexOf(a.cls) - CLASSES.indexOf(b.cls));
39
+ return calls => { for (const r of rules) if (calls.some(c => r.re.test(String(c[r.field] ?? (r.field === 'agent' ? 'main' : ''))))) return r.cls; return null; };
40
+ }
41
+
42
+ // single-call, tool-free sessions of one harness arriving at least `min` within `windowS`: a job, not people
43
+ function bursts(sessions, { windowS = 60, min = 20 } = {}) {
44
+ const singles = sessions.filter(s => s.calls.length === 1 && !s.calls[0].toolCalls.length), by = new Map(), out = new Set();
45
+ for (const s of singles) { const k = s.calls[0].harness; if (!by.has(k)) by.set(k, []); by.get(k).push(s); }
46
+ for (const list of by.values()) {
47
+ list.sort((a, b) => a.calls[0].t - b.calls[0].t);
48
+ for (let i = 0, j = 0; i < list.length; i++) {
49
+ while (list[i].calls[0].t - list[j].calls[0].t > windowS) j++;
50
+ if (i - j + 1 >= min) for (let k = j; k <= i; k++) out.add(list[k]);
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+
56
+ export function classify(calls, { classMap = null } = {}) {
57
+ const match = classMatcher(classMap);
58
+ const sessions = [...sessionsOf(calls).values()].map(cs => ({ calls: cs }));
59
+ const burst = bursts(sessions);
60
+ for (const s of sessions) {
61
+ const cs = s.calls, out = sum(cs, c => c.output), reasoning = sum(cs, c => c.reasoning), inp = sum(cs, c => c.input), tools = sum(cs, c => c.toolCalls.length);
62
+ const named = cs.some(c => JOB.test(c.harness || '') || JOB.test(c.agent || ''));
63
+ s.cls = match(cs)
64
+ || (!tools && cs.length === 1 && (burst.has(s) || named) ? 'batch'
65
+ : out && (reasoning / out >= 0.3 || (out / cs.length >= 2000 && inp / Math.max(1, out) <= 5)) ? 'reasoning'
66
+ : tools || cs.length >= 3 ? 'agentic' : named ? 'batch' : 'realtime');
67
+ s.by = match(cs) ? 'class map' : 'traces';
68
+ for (const c of cs) c.cls = s.cls;
69
+ }
70
+ return sessions;
71
+ }
72
+
73
+ // what the class's calls ask of a server: the bottleneck it is most likely to hit
74
+ function bound(st) {
75
+ if (st.cachedShare >= 0.7 && st.context.p90 >= 32000) return { bound: 'kv-cache', why: `${pct(st.cachedShare)} of input re-read from cache at p90 contexts of ${n(st.context.p90)} tokens: the KV cache (its size and where it lives) sets throughput` };
76
+ if (st.freshPerOutput >= 8) return { bound: 'prefill', why: `${st.freshPerOutput.toFixed(0)} fresh input tokens prefilled for every output token` };
77
+ if (st.freshPerOutput <= 1) return { bound: 'decode', why: `${st.freshPerOutput.toFixed(2)} fresh input tokens per output token: decode time dominates` };
78
+ return { bound: 'mixed', why: `${st.freshPerOutput.toFixed(1)} fresh input tokens per output token: both phases matter` };
79
+ }
80
+
81
+ function stats(sessions, ttlS) {
82
+ const calls = sessions.flatMap(s => s.calls), input = sum(calls, c => c.input), output = sum(calls, c => c.output), cacheRead = sum(calls, c => c.cacheRead), cacheWrite = sum(calls, c => c.cacheWrite);
83
+ const gaps = sessions.flatMap(s => s.calls.slice(1).map((c, i) => c.t - s.calls[i].t)).filter(g => Number.isFinite(g) && g >= 0);
84
+ const minute = new Map(); for (const c of calls) if (Number.isFinite(c.t)) { const k = Math.floor(c.t / 60); minute.set(k, (minute.get(k) || 0) + 1); }
85
+ const results = sum(calls, c => sum(c.toolCalls, t => t.resultTokens));
86
+ // what the context grew by: the first prompt and every later increase (compaction resets it)
87
+ const growth = sum(sessions, s => s.calls.reduce((g, c, i) => g + (i ? Math.max(0, c.input - s.calls[i - 1].input) : c.input), 0));
88
+ const resultSizes = calls.flatMap(c => c.toolCalls.map(t => t.resultTokens).filter(x => x > 0));
89
+ // prefilled: everything not read from the cache (cache writes are prefilled too)
90
+ const fr = sum(calls, c => Math.max(0, (c.input || 0) - (c.cacheRead || 0))), reported = calls.filter(c => c.cacheRead != null).length;
91
+ return {
92
+ sessions: sessions.length, calls: calls.length, input, output, reasoning: sum(calls, c => c.reasoning), cacheRead, cacheWrite, fresh: fr,
93
+ inOut: output ? input / output : null, cachedShare: input && reported ? cacheRead / input : null, cacheReported: calls.length ? reported / calls.length : 0,
94
+ freshPerOutput: output ? fr / output : null, reasoningShare: output ? sum(calls, c => c.reasoning) / output : 0,
95
+ context: { p50: q(calls.map(c => c.input), 0.5), p90: q(calls.map(c => c.input), 0.9), p99: q(calls.map(c => c.input), 0.99) },
96
+ outputTokens: { p50: q(calls.map(c => c.output), 0.5), p90: q(calls.map(c => c.output), 0.9), p99: q(calls.map(c => c.output), 0.99) },
97
+ callsPerSession: { p50: q(sessions.map(s => s.calls.length), 0.5), p90: q(sessions.map(s => s.calls.length), 0.9) },
98
+ gapS: { p50: q(gaps, 0.5), p90: q(gaps, 0.9), overTtl: gaps.length ? gaps.filter(g => g > ttlS).length / gaps.length : 0 },
99
+ peakPerMin: minute.size ? Math.max(...minute.values()) : 0, toolResultShare: growth ? Math.min(1, results / growth) : 0, toolResultP90: q(resultSizes, 0.9),
100
+ subagents: new Set(calls.filter(c => c.agent && c.agent !== 'main').map(c => `${c.session}|${c.agent}`)).size,
101
+ };
102
+ }
103
+
104
+ const pct = x => (x == null ? '–' : `${(100 * x).toFixed(x < 0.1 ? 1 : 0)}%`);
105
+ const n = v => (v == null ? '–' : v >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : v >= 1e3 ? (v / 1e3).toFixed(1) + 'k' : String(Math.round(v)));
106
+ export const ratio = (a, b) => (a == null || !b ? '–' : a / b >= 10 ? `${Math.round(a / b)}:1` : a / b >= 1 ? `${(a / b).toFixed(1)}:1` : `1:${(b / Math.max(a, 1e-9)).toFixed(1)}`);
107
+
108
+ // advice per class, from its numbers: { id, layer, text, why }
109
+ function advise(cls, st, b, ctx) {
110
+ const A = [], add = (id, layer, text, why) => A.push({ id, layer, text, why });
111
+ if (cls === 'realtime' || cls === 'critical') {
112
+ add('ttft-slo', 'scheduling', 'Set TTFT and TPOT targets for this class and size for its busiest minute', `peak ${st.peakPerMin} calls a minute; p90 prompt ${n(st.context.p90)} tokens`);
113
+ if (ctx.hasBatch) add('priority', 'scheduling', 'Give it priority over batch traffic (a priority class in the engine or the gateway)', 'batch traffic shares the fleet: without priority it queues ahead of people');
114
+ if (st.context.p99 > 16000) add('chunked-prefill', 'serving', 'Chunk long prefills so they don\'t stall other requests\' tokens', `p99 prompt ${n(st.context.p99)} tokens`);
115
+ }
116
+ if (cls === 'critical') {
117
+ add('reserve', 'capacity', 'Reserve capacity with a spare instance (N+1), sized by an outage drill, and never preempt it', 'a failure here costs more than idle GPUs');
118
+ add('quality-gate', 'process', 'Gate every infra change on a quality test of real tasks, not latency alone', 'a faster but worse answer is a regression');
119
+ }
120
+ if (cls === 'agentic' || cls === 'critical') {
121
+ if (st.cachedShare != null && st.cachedShare >= 0.5) add('cache-routing', 'serving', 'Route each session to the replica that holds its prefix (prefix-aware routing or session affinity)', `${pct(st.cachedShare)} of input is re-read from cache: a replica without it prefills it all again`);
122
+ if (st.cachedShare != null && st.cachedShare < 0.5 && st.callsPerSession.p50 >= 3) add('cache-layout', 'prompt', 'Make the prompt prefix stable (static first, dynamic last) and mark it cacheable', `only ${pct(st.cachedShare)} of input came from cache in ${n(st.callsPerSession.p50)}-call sessions: run the prefix-cache doctor`);
123
+ if (st.gapS.overTtl >= 0.05) add('cache-ttl', 'cache', 'Keep the cache across long pauses: a longer cache lifetime (e.g. 1-hour writes), or KV offload to host memory on self-hosted engines', `${pct(st.gapS.overTtl)} of pauses outlast a ${ctx.ttlS} s cache`);
124
+ if (st.toolResultShare >= 0.3 && st.toolResultP90 >= 4000) add('tool-output', 'harness', 'Cap or summarize large tool results before they enter the context', `tool results are ${pct(st.toolResultShare)} of what the context grows by (p90 result ${n(st.toolResultP90)} tokens), and every later call re-sends them`);
125
+ if (st.context.p90 >= 64000) add('compaction', 'context', 'Compact long sessions, at points where the cache is cold anyway (after a long pause)', `p90 context ${n(st.context.p90)} tokens`);
126
+ if (st.subagents) add('subagents', 'agent', 'Give subagents a short, stable prefix of their own; don\'t cache a one-shot subagent\'s last turn', `${st.subagents} subagent runs`);
127
+ }
128
+ if (b.bound === 'prefill') add('more-prefill', 'serving', 'Give prefill more capacity than decode (disaggregated prefill/decode with more prefill GPUs, or a larger chunked-prefill budget)', b.why);
129
+ if (b.bound === 'kv-cache') add('kv-capacity', 'serving', 'Add KV capacity: FP8 KV cache, KV offload to host memory, or GPUs with more HBM', b.why);
130
+ if (cls === 'reasoning' || b.bound === 'decode') {
131
+ add('spec-decode', 'model-options', 'Speculative decoding (MTP heads where the model has them, or a draft model)', `${b.why}; long outputs (p90 ${n(st.outputTokens.p90)})`);
132
+ add('fp8-kv', 'model-options', 'FP8 KV cache: more sequences per GPU in decode', 'decode batches are bounded by KV memory');
133
+ if (st.reasoningShare >= 0.3) add('reasoning-budget', 'model', 'Cap reasoning effort or output tokens where answers allow it (check with the quality gate)', `${pct(st.reasoningShare)} of output is reasoning`);
134
+ }
135
+ if (cls === 'batch') {
136
+ add('batch-api', 'scheduling', 'Run it off-peak or through a batch endpoint (discounted where the provider offers one), at lower priority', `${st.calls} calls with no person waiting`);
137
+ add('throughput', 'serving', 'Size for throughput, not latency: large batches, cheaper or spot GPUs, its own pool or time window', `peak ${st.peakPerMin} calls a minute`);
138
+ }
139
+ return A;
140
+ }
141
+
142
+ export function profile(calls, { classMap = null, cacheTtlS = 300 } = {}) {
143
+ const sessions = classify(calls, { classMap }), total = stats(sessions, cacheTtlS), classes = [];
144
+ const present = new Set(sessions.map(s => s.cls));
145
+ for (const cls of CLASSES) {
146
+ const ss = sessions.filter(s => s.cls === cls); if (!ss.length) continue;
147
+ const st = stats(ss, cacheTtlS), b = bound(st);
148
+ classes.push({ class: cls, by: ss.some(s => s.by === 'class map') ? 'class map' : 'traces', share: { calls: total.calls ? st.calls / total.calls : 0, input: total.input ? st.input / total.input : 0, output: total.output ? st.output / total.output : 0 },
149
+ ...st, ...b, advice: advise(cls, st, b, { hasBatch: present.has('batch'), ttlS: cacheTtlS }) });
150
+ }
151
+ return { kind: 'harness-ledger.profile', cacheTtlS, total, classes };
152
+ }
153
+
154
+ export function profileText(P) {
155
+ const L = [`Workload profile: ${P.total.calls} calls in ${P.total.sessions} sessions; input:output ${ratio(P.total.input, P.total.output)}, ${pct(P.total.cachedShare)} of input from cache`, ''];
156
+ L.push(' class calls share in:out from cache fresh/out context p50/p90 output p90 bound');
157
+ for (const c of P.classes) L.push(` ${c.class.padEnd(9)} ${String(c.calls).padStart(6)} ${pct(c.share.calls).padStart(5)} ${ratio(c.input, c.output).padStart(7)} ${pct(c.cachedShare).padStart(10)} ${(c.freshPerOutput == null ? '–' : c.freshPerOutput.toFixed(1)).padStart(9)} ${`${n(c.context.p50)}/${n(c.context.p90)}`.padStart(15)} ${n(c.outputTokens.p90).padStart(10)} ${c.bound}${c.by === 'class map' ? ' (class map)' : ''}`);
158
+ for (const c of P.classes) {
159
+ if (!c.advice.length) continue;
160
+ L.push('', `${c.class}: ${c.why}`);
161
+ for (const a of c.advice) L.push(` · [${a.layer}] ${a.text} (${a.why})`);
162
+ }
163
+ return L.join('\n') + '\n';
164
+ }
@@ -9,7 +9,7 @@
9
9
  // toolsOffered? [names] tool definitions sent with the request (null = the harness doesn't log them)
10
10
  // toolDefTokens? estimated tokens of those definitions
11
11
  // toolCalls [{ name, id?, argHash?, resultTokens?, error? }] tools the response asked for, with what came back
12
- // finish?, error?, durS?, costUSD? (when the harness recorded a cost), outcome? ('success'|'failure') }
12
+ // finish?, error?, durS?, ttftS? (time to first token), costUSD? (when the harness recorded a cost), outcome? ('success'|'failure') }
13
13
  //
14
14
  // Records hold counts, names and hashes only. No prompt, completion, argument or tool-result text is kept: the
15
15
  // importers read transcripts that can hold anything, and what they write out has to be safe to share.
@@ -31,7 +31,7 @@ export const fresh = c => Math.max(0, (c.input || 0) - (c.cacheRead || 0) - (c.c
31
31
  export function call(o) {
32
32
  const r = { kind: 'llm_call', t: o.t, harness: o.harness, session: o.session ?? 'unknown', id: o.id, model: o.model ?? null,
33
33
  input: o.input || 0, cacheRead: o.cacheRead ?? null, cacheWrite: o.cacheWrite ?? null, output: o.output || 0, toolCalls: o.toolCalls || [] };
34
- for (const k of ['agent', 'parent', 'traceId', 'spanId', 'provider', 'reasoning', 'toolsOffered', 'toolDefTokens', 'finish', 'error', 'durS', 'costUSD', 'outcome', 'source'])
34
+ for (const k of ['agent', 'parent', 'traceId', 'spanId', 'provider', 'reasoning', 'toolsOffered', 'toolDefTokens', 'finish', 'error', 'durS', 'ttftS', 'costUSD', 'outcome', 'source'])
35
35
  if (o[k] != null && o[k] !== '') r[k] = o[k];
36
36
  return r;
37
37
  }
@@ -0,0 +1,177 @@
1
+ // Suggestions: the optimizer's and the doctor's findings turned into a short list of things to change, each raised
2
+ // once, where people already look, and remembered (accepted, dismissed, snoozed) so the same advice doesn't come back.
3
+ //
4
+ // suggestions(r, A) r: ledger(calls) (for the sessions each suggestion is about), A: assess(r, …)
5
+ // triage(list, state) which are new (or grew since they were last raised), which are silenced
6
+ // sinks text, JSON lines, a fleetops store (Grafana reads it), Slack and Lark/Feishu webhooks, and
7
+ // comments on the Langfuse sessions a suggestion is about. Only Slack, Lark and Langfuse send
8
+ // anything off the machine, and only with live: true.
9
+ //
10
+ // A suggestion: { id, change, layer, title, effects: { goal: change }, best: { goal, change }, saves ($/month),
11
+ // risk, confidence: 'traces' (counted from the recorded calls) | 'model' (the sizer, a latency fit or an assumption),
12
+ // sessions: the most affected session ids, command: the dry run, why }
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import os from 'node:os';
16
+ import { createHash } from 'node:crypto';
17
+ import { GOALS } from './advise.mjs';
18
+
19
+ export const DEFAULTS = { minGain: 0.05, minSaves: 1, growth: 0.5, top: 5 };
20
+ // which waste findings a change removes: the sessions to show it on
21
+ const CAUSES = { 'prompt-layout': ['cache-miss'], 'cache-lifetime': ['cache-expired'], 'compact-cold': ['cache-expired'], 'tool-output-cap': ['tool-output-bloat'], 'unused-tools': ['unused-tools'],
22
+ 'prefix-stable': ['cache-miss'], 'prefix-routing': ['cache-miss', 'cache-expired'] };
23
+ // workload changes whose token and cost effect is counted from the calls themselves (latency is always a model)
24
+ const COUNTED = new Set(['prompt-layout', 'cache-lifetime', 'tool-output-cap', 'unused-tools', 'compact-cold', 'step-cap', 'batch-offpeak', 'output-budget']);
25
+ const hid = s => createHash('sha256').update(s).digest('hex').slice(0, 10);
26
+
27
+ function sessionsFor(r, change, n = 5) {
28
+ // request-body findings (prefix-*, lint-*) are about the gateway log's sessions, not these calls: none are named
29
+ const causes = CAUSES[change] || (change.startsWith('cap-') ? ['tool-output-bloat'] : null);
30
+ if (!causes) return [];
31
+ const tool = change.startsWith('cap-') ? change.slice(4) : null, by = new Map();
32
+ for (const f of r.findings) { if (!causes.includes(f.cause) || (tool && f.tool !== tool)) continue; const k = `${f.harness}\u0000${f.session}`; by.set(k, (by.get(k) || 0) + (f.tokens || 0)); }
33
+ return [...by].sort((a, b) => b[1] - a[1]).slice(0, n).map(([k, tokens]) => { const [harness, session] = k.split('\u0000'); return { harness, session, tokens: Math.round(tokens) }; });
34
+ }
35
+
36
+ export function suggestions(r, A, { scope = 'all', minGain = DEFAULTS.minGain, minSaves = DEFAULTS.minSaves, inputs = '', requests = null } = {}) {
37
+ const by = new Map(), mode = A.mode, units = r.report && r.report.pricing && r.report.pricing.currency === 'units';
38
+ for (const [goal, R] of Object.entries(A.optimize || {})) {
39
+ for (const l of R.levers) {
40
+ const ch = l.effect[goal] && l.effect[goal].change; if (ch == null) continue;
41
+ const gain = GOALS[goal].lower ? -ch : ch; if (gain < minGain) continue;
42
+ const s = by.get(l.id) || { change: l.id, layer: l.layer, title: l.title, risk: l.risk, how: l.how, verify: l.verify, effects: {}, saves: null };
43
+ s.effects[goal] = ch;
44
+ if (goal === 'cost' && !units && l.effect.cost && l.effect.cost.before != null && l.effect.cost.after != null) s.saves = l.effect.cost.before - l.effect.cost.after;
45
+ by.set(l.id, s);
46
+ }
47
+ }
48
+ // the doctor's request-body findings name the exact cause of a broken prefix (a timestamp in the system prompt,
49
+ // reordered tools…): the optimizer can't, so they come as their own suggestions
50
+ for (const a of (A.doctor && A.doctor.advice) || []) {
51
+ if (!(a.id.startsWith('prefix-') && a.id !== 'prefix-stable') && !a.id.startsWith('lint-')) continue;
52
+ by.set(a.id, { change: a.id, layer: a.layer, title: a.text, risk: 'none', how: null, verify: 'harness-ledger doctor on new request logs', effects: {}, saves: null, why: a.why });
53
+ }
54
+ const out = [];
55
+ for (const s of by.values()) {
56
+ const goals = Object.entries(s.effects).sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));
57
+ if (!goals.length && s.saves == null && !s.change.startsWith('prefix-') && !s.change.startsWith('lint-')) continue;
58
+ if (s.saves != null && s.saves < minSaves && goals.every(([g]) => g === 'cost')) continue;
59
+ const latencyOnly = goals.length && goals.every(([g]) => g !== 'cost' && g !== 'gpus');
60
+ const confidence = mode === 'api' && COUNTED.has(s.change) && !latencyOnly ? 'traces' : s.change.startsWith('prefix-') || s.change.startsWith('lint-') ? 'traces' : 'model';
61
+ const best = goals[0] ? { goal: goals[0][0], change: goals[0][1] } : null;
62
+ out.push(Object.assign(s, { id: hid(`${scope}|${s.change}`), scope, best, confidence, sessions: sessionsFor(r, s.change),
63
+ command: COUNTED.has(s.change) || /^(fp|spec|prefix-routing|priority|disaggregate|add-replica|gpu-|model-)/.test(s.change) ? `aiinfra advise ${inputs || 'PATH'} --goal ${best ? best.goal : 'cost'} --apply ${s.change}` : `aiinfra harness-ledger doctor ${inputs || 'PATH'}${requests === false ? '' : ` --requests ${requests || 'REQUESTS'}`}`,
64
+ why: s.why || (best ? `${GOALS[best.goal].label} ${fmt(best.change)} on your recorded calls${s.saves ? `; saves about $${Math.round(s.saves).toLocaleString('en-US')} a month` : ''}` : 'found in your request bodies') }));
65
+ }
66
+ const rank = s => Math.max(0, ...Object.entries(s.effects).map(([g, c]) => (GOALS[g].lower ? -c : c))) + (s.change.startsWith('lint-') || s.change.startsWith('prefix-') ? 0.01 : 0);
67
+ const sorted = out.sort((a, b) => rank(b) - rank(a));
68
+ // when nothing clears the bar, say why, so an empty answer isn't mistaken for "nothing to improve"
69
+ const near = [];
70
+ for (const [goal, R] of Object.entries(A.optimize || {})) for (const l of R.levers) { const c = l.effect[goal] && l.effect[goal].change; if (c != null && (GOALS[goal].lower ? -c : c) > 0.001) near.push({ change: l.id, goal, effect: c }); }
71
+ near.sort((a, b) => Math.abs(b.effect) - Math.abs(a.effect));
72
+ Object.defineProperty(sorted, 'why', { enumerable: false, value: {
73
+ minGain, near: near.slice(0, 3), noLatency: Object.values(A.optimize || {}).some(R => R.mode === 'api' && R.latencyModel && !R.latencyModel.ok), units } });
74
+ return sorted;
75
+ }
76
+ const fmt = c => `${c > 0 ? '+' : ''}${(100 * c).toFixed(Math.abs(c) < 0.1 ? 1 : 0)}%`;
77
+
78
+ // ---------- state: what was raised, accepted, dismissed or snoozed ----------
79
+ export const defaultStatePath = () => path.join(process.env.AIINFRA_STATE || path.join(os.homedir(), '.aiinfra'), 'suggestions.json');
80
+ export function loadState(file) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { version: 1, items: {}, feedback: [] }; } }
81
+ export function saveState(file, st) { fs.mkdirSync(path.dirname(file), { recursive: true }); const tmp = file + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(st, null, 1) + '\n'); fs.renameSync(tmp, file); }
82
+
83
+ // how strong a suggestion is: its largest relative effect on a goal (request-body findings: 0, raised once)
84
+ const strength = s => Math.max(0, ...Object.entries(s.effects).map(([g, c]) => (GOALS[g].lower ? -c : c)));
85
+ // → { fresh: raise now, silenced: dismissed/snoozed/accepted, open: everything still current }
86
+ export function triage(list, st, { now = Date.now() / 1000, growth = DEFAULTS.growth } = {}) {
87
+ const fresh = [], silenced = [], open = [];
88
+ for (const s of list) {
89
+ const it = st.items[s.id] || (st.items[s.id] = { change: s.change, scope: s.scope, status: 'open', firstSeen: now });
90
+ it.lastSeen = now; it.title = s.title;
91
+ if (it.status === 'snoozed' && it.until && it.until <= now) { it.status = 'open'; delete it.until; }
92
+ if (it.status !== 'open') { silenced.push(Object.assign({}, s, { status: it.status })); continue; }
93
+ open.push(Object.assign({}, s, { status: 'open' }));
94
+ const k = strength(s);
95
+ if (it.raisedAt == null || (it.raisedStrength != null && k > it.raisedStrength * (1 + growth))) { fresh.push(Object.assign({}, s, { status: 'open', again: it.raisedAt != null })); it.raisedAt = now; it.raisedStrength = k; }
96
+ }
97
+ return { fresh, silenced, open, why: list.why || null };
98
+ }
99
+ export function setStatus(st, id, status, { by = null, untilS = null, now = Date.now() / 1000, note = null } = {}) {
100
+ const key = Object.keys(st.items).find(k => k === id || k.startsWith(id));
101
+ if (!key) throw new Error(`no suggestion ${id} (aiinfra suggest list shows the ids)`);
102
+ if (!['open', 'accepted', 'dismissed', 'snoozed'].includes(status)) throw new Error(`status: open, accepted, dismissed or snoozed`);
103
+ const it = st.items[key]; it.status = status; it.changedAt = now; if (status === 'snoozed') it.until = now + (untilS || 7 * 86400); else delete it.until;
104
+ if (status === 'open') { delete it.raisedAt; delete it.raisedStrength; }
105
+ st.feedback.push({ t: now, id: key, change: it.change, status, by, note });
106
+ return key;
107
+ }
108
+ export function duration(v) { const m = String(v || '7d').match(/^(\d+(?:\.\d+)?)([mhdw])$/); if (!m) throw new Error(`--for: like 12h, 7d or 2w`); return Number(m[1]) * { m: 60, h: 3600, d: 86400, w: 604800 }[m[2]]; }
109
+
110
+ // ---------- sinks ----------
111
+ export function suggestText(T, { all = false } = {}) {
112
+ const list = all ? T.open : T.fresh, L = [];
113
+ if (!list.length) L.push(T.open.length ? `no new suggestions (${T.open.length} open, ${T.silenced.length} silenced): aiinfra suggest list, or --all to print them` : `no suggestions${T.silenced.length ? ` (${T.silenced.length} silenced)` : ''}`);
114
+ const W = T.why;
115
+ if (!T.open.length && W) {
116
+ L.push(` nothing moves a goal by ${Math.round(100 * W.minGain)}% or more (--min-gain)${W.near.length ? `; the largest: ${W.near.map(x => `${x.change} ${x.goal} ${fmt(x.effect)}`).join(', ')}` : ''}`);
117
+ if (W.noLatency) L.push(' these calls carry no timings, so TTFT changes can\'t be estimated from them (Claude Code transcripts don\'t record time to first token)');
118
+ L.push(' the full menu: aiinfra assess <same inputs>');
119
+ }
120
+ for (const s of list) {
121
+ L.push(`${s.again ? '↑' : '•'} [${s.id}] ${s.title}`);
122
+ L.push(` ${s.why} · ${s.layer} · risk ${s.risk} · ${s.confidence === 'traces' ? 'counted from your traces' : 'modelled'}`);
123
+ if (s.sessions.length) L.push(` most affected: ${s.sessions.slice(0, 3).map(x => `${x.harness}/${x.session}`).join(', ')}`);
124
+ L.push(` dry run: ${s.command} · aiinfra suggest accept|dismiss|snooze ${s.id}`);
125
+ }
126
+ return L.join('\n') + '\n';
127
+ }
128
+ // fleetops store records (kind "suggestion"): one per raise or status change; fleetops serve's /api/suggestions keeps the latest per id
129
+ export function storeRecords(T, { now = Date.now() / 1000 } = {}) {
130
+ const rec = s => ({ t: now, id: s.id, change: s.change, layer: s.layer, title: s.title, status: s.status, risk: s.risk, confidence: s.confidence, goal: s.best ? s.best.goal : null,
131
+ effect: s.best ? s.best.change : null, saves: s.saves, command: s.command, scope: s.scope, sessions: s.sessions.slice(0, 5).map(x => `${x.harness}/${x.session}`) });
132
+ return [...T.open, ...T.silenced].map(rec);
133
+ }
134
+ export function slackPayload(list, { link = null, title = 'AIInfraTools suggestions' } = {}) {
135
+ const blocks = [{ type: 'header', text: { type: 'plain_text', text: `${title}: ${list.length} new` } }];
136
+ for (const s of list.slice(0, 10)) {
137
+ blocks.push({ type: 'section', text: { type: 'mrkdwn', text: `*${s.title}*\n${s.why}\n_${s.layer} · risk ${s.risk} · ${s.confidence === 'traces' ? 'counted from traces' : 'modelled'}_` } });
138
+ blocks.push({ type: 'context', elements: [{ type: 'mrkdwn', text: `dry run: \`${s.command}\` · \`aiinfra suggest dismiss ${s.id}\`` }] });
139
+ }
140
+ if (link) blocks.push({ type: 'actions', elements: [{ type: 'button', text: { type: 'plain_text', text: 'Open the dashboard' }, url: link }] });
141
+ return { text: `${title}: ${list.map(s => s.title).slice(0, 3).join('; ')}`, blocks };
142
+ }
143
+ export function larkPayload(list, { link = null, title = 'AIInfraTools suggestions' } = {}) {
144
+ const elements = [];
145
+ for (const s of list.slice(0, 10)) elements.push({ tag: 'div', text: { tag: 'lark_md', content: `**${s.title}**\n${s.why}\n${s.layer} · risk ${s.risk} · ${s.confidence === 'traces' ? 'counted from traces' : 'modelled'}\ndry run: \`${s.command}\`` } }, { tag: 'hr' });
146
+ if (link) elements.push({ tag: 'action', actions: [{ tag: 'button', text: { tag: 'plain_text', content: 'Open the dashboard' }, type: 'primary', url: link }] });
147
+ return { msg_type: 'interactive', card: { config: { wide_screen_mode: true }, header: { template: 'blue', title: { tag: 'plain_text', content: `${title}: ${list.length} new` } }, elements } };
148
+ }
149
+ async function post(url, body, { fetchImpl = fetch, headers = {}, timeoutS = 20 } = {}) {
150
+ const ac = new AbortController(), timer = setTimeout(() => ac.abort(), timeoutS * 1000);
151
+ try { const res = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal: ac.signal }); return { ok: res.ok, status: res.status, body: await res.text().catch(() => '') }; }
152
+ catch (e) { return { ok: false, error: e.message }; } finally { clearTimeout(timer); }
153
+ }
154
+ // Slack incoming webhook, or a Lark/Feishu custom bot webhook
155
+ export async function sendWebhook(kind, url, list, { live = false, link = null, fetchImpl } = {}) {
156
+ if (!list.length) return { sent: 0 };
157
+ const body = kind === 'lark' ? larkPayload(list, { link }) : slackPayload(list, { link });
158
+ if (!live) return { sent: 0, dryRun: true, would: `${list.length} suggestions to ${kind}` };
159
+ const r = await post(url, body, { fetchImpl });
160
+ return { sent: r.ok ? list.length : 0, status: r.status, error: r.ok ? null : r.error || r.body.slice(0, 200) };
161
+ }
162
+ // comments on the Langfuse sessions each suggestion is about (POST /api/public/comments; Basic auth with the project's keys)
163
+ export async function sendLangfuse(list, { host, publicKey, secretKey, projectId = null, live = false, fetchImpl = fetch, perSuggestion = 3 } = {}) {
164
+ const targets = list.flatMap(s => s.sessions.slice(0, perSuggestion).map(x => ({ s, session: x.session })));
165
+ if (!targets.length) return { sent: 0 };
166
+ if (!live) return { sent: 0, dryRun: true, would: `${targets.length} comments on Langfuse sessions` };
167
+ if (!host || !publicKey || !secretKey) throw new Error('Langfuse: LANGFUSE_HOST, LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY');
168
+ const auth = { authorization: 'Basic ' + Buffer.from(`${publicKey}:${secretKey}`).toString('base64') }, base = host.replace(/\/$/, '');
169
+ if (!projectId) { const r = await fetchImpl(`${base}/api/public/projects`, { headers: auth }); if (!r.ok) return { sent: 0, error: `projects: HTTP ${r.status}` }; const j = await r.json(); projectId = j.data && j.data[0] && j.data[0].id; }
170
+ let sent = 0; const errors = [];
171
+ for (const { s, session } of targets) {
172
+ const content = `**AIInfraTools:** ${s.title}\n${s.why} (${s.confidence === 'traces' ? 'counted from traces' : 'modelled'}, risk ${s.risk}).\nDry run: \`${s.command}\``.slice(0, 3000);
173
+ const r = await post(`${base}/api/public/comments`, { projectId, objectType: 'SESSION', objectId: session, content }, { fetchImpl, headers: auth });
174
+ if (r.ok) sent++; else errors.push(`${session}: ${r.status || r.error}`);
175
+ }
176
+ return { sent, errors };
177
+ }
@@ -0,0 +1,81 @@
1
+ // Agent trajectories with full message lists (SWE-agent, OpenHands, mini-SWE-agent and the public datasets built from
2
+ // them: nebius/SWE-agent-trajectories, nvidia/Nemotron-SWE, Open-SWE-Traces, SWE-smith…) → llm_call records and the
3
+ // request bodies the prefix-cache doctor reads.
4
+ //
5
+ // Input: JSON lines or a JSON array of rows (a dataset exported with `datasets`' to_json), or a datasets-server page
6
+ // ({ rows: [{ row: {…} }] }). A row holds one task's run:
7
+ // messages OpenAI-style [{ role, content, tool_calls? }] (or that list as a JSON string)
8
+ // trajectory SWE-agent style [{ role: system|user|ai|assistant, system_prompt?|text?|content?, … }]
9
+ // tools tool definitions, when the run offered them
10
+ // resolved | target whether the task was solved (an outcome); instance_id | traj_id | uuid | id the session
11
+ // model | model_name
12
+ // Each assistant message is one model call. Its request is everything before it (tools, system, messages). Token counts
13
+ // are estimated from text (4 characters a token) and the cache accounting is what an ideal prefix cache would give:
14
+ // the previous request and its answer are cached when this request starts with them. There are no real timings:
15
+ // calls are spaced --step-gap seconds apart (20 by default) and sessions an hour apart, so latency and arrival-rate
16
+ // results don't apply; prompt layout, context growth, tool output and outcomes do.
17
+ import { createHash } from 'node:crypto';
18
+ import { call, estTokens } from './record.mjs';
19
+
20
+ const H = s => createHash('sha256').update(s).digest('hex').slice(0, 16);
21
+ const text = v => (v == null ? '' : typeof v === 'string' ? v : Array.isArray(v) ? v.map(p => (typeof p === 'string' ? p : p && (p.text ?? p.content ?? JSON.stringify(p)))).join('\n') : JSON.stringify(v));
22
+ const ROLE = { ai: 'assistant', model: 'assistant', assistant: 'assistant', system: 'system', developer: 'system', user: 'user', human: 'user', tool: 'tool', function: 'tool', observation: 'user' };
23
+
24
+ export function rowsOf(input) {
25
+ const s = String(input).trim();
26
+ if (!s) return [];
27
+ if (s[0] === '[') return JSON.parse(s);
28
+ if (s[0] === '{' && /^\{\s*"(rows|features)"/.test(s)) { const j = JSON.parse(s); return (j.rows || []).map(r => r.row || r); }
29
+ return s.split(/\r?\n/).filter(l => l.trim()).map(l => JSON.parse(l));
30
+ }
31
+
32
+ // one row → [{ role, content, toolCalls? }]
33
+ export function messagesOf(row) {
34
+ let ms = row.messages ?? row.trajectory ?? row.conversation ?? row.conversations;
35
+ if (typeof ms === 'string') ms = JSON.parse(ms);
36
+ if (!Array.isArray(ms)) return [];
37
+ return ms.map(m => {
38
+ const role = ROLE[String(m.role ?? m.from ?? '').toLowerCase()] || 'user';
39
+ const content = text(m.content ?? m.text ?? m.value ?? m.system_prompt ?? [m.thought, m.action].filter(Boolean).join('\n'));
40
+ const tc = Array.isArray(m.tool_calls) ? m.tool_calls.map(t => ({ name: (t.function && t.function.name) || t.name || '?', args: (t.function && t.function.arguments) ?? t.arguments ?? '' })) : null;
41
+ return { role, content, toolCalls: tc && tc.length ? tc : null };
42
+ });
43
+ }
44
+
45
+ // the command an agent without tool calls ran: the last fenced block's first word (SWE-agent's ``` blocks)
46
+ const commandOf = s => { const blocks = [...String(s).matchAll(/```[^\n]*\n([\s\S]*?)```/g)]; const c = blocks.length ? blocks[blocks.length - 1][1].trim() : ''; return c ? { name: c.split(/\s+/)[0].slice(0, 40), args: c } : null; };
47
+ const outcomeOf = row => { for (const k of ['resolved', 'target', 'success', 'solved']) if (typeof row[k] === 'boolean') return row[k] ? 'success' : 'failure'; return undefined; };
48
+
49
+ export function trajectories(input, { harness = 'trajectories', stepGapS = 20, t0 = 1_800_000_000, model = null } = {}) {
50
+ const rows = rowsOf(input), calls = [], requests = [];
51
+ rows.forEach((row, ri) => {
52
+ const msgs = messagesOf(row); if (!msgs.length) return;
53
+ const session = String(row.instance_id ?? row.traj_id ?? row.uuid ?? row.id ?? `traj-${ri}`) + (row.instance_id && (row.traj_id || row.model_name) ? `#${ri}` : '');
54
+ const m = row.model ?? row.model_name ?? model, tools = Array.isArray(row.tools) ? row.tools : typeof row.tools === 'string' && row.tools.trim().startsWith('[') ? JSON.parse(row.tools) : null;
55
+ const toolTok = tools ? estTokens(tools) : 0, outcome = outcomeOf(row);
56
+ let prevIn = 0, prevOut = 0, prevPrefix = null, k = 0, t = t0 + ri * 3600;
57
+ for (let i = 0; i < msgs.length; i++) {
58
+ if (msgs[i].role !== 'assistant' || i === 0) continue;
59
+ const before = msgs.slice(0, i), a = msgs[i];
60
+ const reqMsgs = before.map(x => ({ role: x.role, content: x.content }));
61
+ const input = toolTok + estTokens(reqMsgs), output = Math.max(1, estTokens(a.content) + (a.toolCalls ? estTokens(a.toolCalls) : 0));
62
+ // an ideal prefix cache holds the previous request and its answer, if this request starts with them
63
+ const prefix = H(JSON.stringify(reqMsgs.slice(0, prevPrefix ? prevPrefix.n : 0)));
64
+ const cached = prevPrefix && prefix === prevPrefix.h ? Math.min(input, prevIn + prevOut) : 0;
65
+ // what the agent did with this answer, and how big the result was (the next tool or user message)
66
+ const results = []; for (let j = i + 1; j < msgs.length && msgs[j].role !== 'assistant'; j++) if (msgs[j].role === 'tool' || msgs[j].role === 'user') results.push(msgs[j]);
67
+ const acts = a.toolCalls || [commandOf(a.content)].filter(Boolean);
68
+ const toolCalls = acts.map((x, n) => ({ name: x.name, id: `${session}-${k}-${n}`, argHash: H(String(x.args)), resultTokens: results[n] ? estTokens(results[n].content) : results.length && n === acts.length - 1 ? estTokens(results.slice(n).map(r => r.content).join('\n')) : 0,
69
+ error: results[n] ? /\b(Traceback|Error:|error:|command not found|No such file)\b/.test(results[n].content.slice(0, 2000)) : false }));
70
+ calls.push(call({ t, harness, session, id: `${session}-${k}`, model: m, input, cacheRead: cached, cacheWrite: input - cached, output, toolCalls, outcome,
71
+ toolsOffered: tools ? tools.map(x => x.name || (x.function && x.function.name) || '?') : undefined, toolDefTokens: toolTok || undefined, source: 'trajectory' }));
72
+ requests.push({ t, session, request: Object.assign({ model: m, messages: reqMsgs }, tools ? { tools } : {}) });
73
+ prevIn = input; prevOut = output; prevPrefix = { n: i + 1, h: H(JSON.stringify([...reqMsgs, { role: 'assistant', content: a.content }])) };
74
+ k++; t += stepGapS;
75
+ }
76
+ });
77
+ return { calls, requests };
78
+ }
79
+ // strict: the dataset's own marks; loose (tried after every other format): any row that opens with a message list
80
+ export const looksLikeTrajectories = (head, loose = false) => /"trajectory"\s*:\s*\[\s*\{|"rows"\s*:\s*\[\s*\{\s*"row_idx"/.test(head) || (/"messages"\s*:/.test(head) && /"(resolved|instance_id|traj_id|exit_status)"\s*:/.test(head))
81
+ || (loose && /^\s*\[?\s*\{[^\n]{0,200}"messages"\s*:\s*(\[\s*\{\s*"role"|"\[)/.test(head));
@@ -0,0 +1,100 @@
1
+ // A synthetic, mixed workload for the profile, the prefix-cache doctor and the optimizer: two hours of a team's model
2
+ // traffic, as llm_call records (and, for the doctor, request bodies of a few agent sessions; and a self-hosted engine's
3
+ // Prometheus counters). Every text field is a placeholder: no real prompts or tool output.
4
+ //
5
+ // support chat people asking short questions: 1-2 calls, small prompts, short answers → realtime
6
+ // payments agent a support agent with tools that the class map marks critical → critical
7
+ // coding agent long tool-using sessions: growing context, big tool results, pauses, a system
8
+ // prompt with a timestamp in it (so some calls miss the cache), compaction → agentic
9
+ // research single long answers with most of the output spent reasoning → reasoning
10
+ // nightly eval hundreds of single calls in a burst → batch
11
+ import { call } from './record.mjs';
12
+
13
+ const T0 = Date.parse('2026-11-24T16:00:00Z') / 1000;
14
+ function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32); }
15
+ const between = (r, a, b) => Math.round(a + r() * (b - a));
16
+ // a call's duration: a fixed overhead, prefill of fresh tokens, a tenth of that for cached ones, decode, and noise
17
+ const first = (r, o) => 0.25 + 4e-5 * Math.max(0, o.input - (o.cacheRead || 0)) + 4e-6 * (o.cacheRead || 0) + 0.1 * r();
18
+ const timing = (r, o) => { const ttftS = first(r, o); return { ttftS, durS: ttftS + 0.012 * o.output * (0.9 + 0.2 * r()) }; };
19
+
20
+ export const DEMO_CLASS_MAP = { critical: ['harness:payments-agent'] };
21
+
22
+ export function mixedWorkload({ seed = 3 } = {}) {
23
+ const r = rng(seed), calls = [];
24
+ let id = 0;
25
+ const push = o => calls.push(call({ id: `c${++id}`, ...o, ...timing(r, o) }));
26
+
27
+ // support chat: 1-2 calls, a cached 1.2k system prompt on the second call
28
+ for (let s = 0; s < 160; s++) {
29
+ let t = T0 + r() * 7200; const n = r() < 0.4 ? 2 : 1, sys = 1200; let ctx = sys + between(r, 200, 3500);
30
+ for (let k = 0; k < n; k++) {
31
+ push({ t, harness: 'support-chat', session: `chat-${s}`, model: 'gpt-5-mini', input: ctx, cacheRead: k ? sys : 0, cacheWrite: 0, output: between(r, 120, 520), durS: 1 + r() * 3 });
32
+ t += between(r, 20, 90); ctx += between(r, 300, 900);
33
+ }
34
+ }
35
+ // payments agent: tools, 3-6 calls, a stable prefix (good caching)
36
+ for (let s = 0; s < 24; s++) {
37
+ let t = T0 + r() * 7200, ctx = 6000 + between(r, 0, 2000); const n = between(r, 3, 6);
38
+ for (let k = 0; k < n; k++) {
39
+ const res = between(r, 300, 1500);
40
+ push({ t, harness: 'payments-agent', session: `pay-${s}`, model: 'claude-sonnet-4-5', input: ctx, cacheRead: k ? Math.round(ctx * 0.9) : 0, cacheWrite: k ? 0 : ctx, output: between(r, 80, 300), durS: 2 + r() * 4,
41
+ toolCalls: k < n - 1 ? [{ name: ['lookup_order', 'refund_status', 'customer_profile'][k % 3], id: `p${s}_${k}`, argHash: `a${s}_${k}`, resultTokens: res }] : [] });
42
+ t += between(r, 4, 15); ctx += res + 200;
43
+ }
44
+ }
45
+ // coding agent: long sessions; the system prompt carries a timestamp, so a call that lands in a new minute re-sends
46
+ // everything uncached; a few long pauses outlast the 5-minute cache; big tool results; compaction past 120k
47
+ for (let s = 0; s < 36; s++) {
48
+ let t = T0 + r() * 3600, ctx = 18000; const n = between(r, 15, 45);
49
+ for (let k = 0; k < n; k++) {
50
+ const pause = k && r() < 0.08 ? between(r, 400, 1800) : between(r, 3, 25);
51
+ const prevT = t; t += k ? pause : 0;
52
+ const newMinute = k && Math.floor(t / 60) !== Math.floor(prevT / 60) && r() < 0.35;
53
+ const miss = k === 0 || pause > 300 || newMinute;
54
+ const big = r() < 0.12, res = big ? between(r, 12000, 30000) : between(r, 300, 4000);
55
+ const tool = big ? (r() < 0.5 ? 'Read' : 'Bash') : ['Read', 'Edit', 'Grep', 'Bash'][between(r, 0, 3)];
56
+ push({ t, harness: 'coding-agent', session: `code-${s}`, agent: k % 9 === 8 ? 'explore' : 'main', model: 'claude-sonnet-4-5', input: ctx,
57
+ cacheRead: miss ? 0 : Math.round((ctx - 600) * 0.99), cacheWrite: miss ? ctx : 600, output: between(r, 60, 900), reasoning: 0, durS: 3 + r() * 10,
58
+ toolsOffered: ['Read', 'Edit', 'Grep', 'Bash', 'WebFetch', 'NotebookEdit', 'TodoWrite'], toolDefTokens: 4200,
59
+ toolCalls: [{ name: tool, id: `t${s}_${k}`, argHash: `h${s}_${k % 7 === 6 ? 0 : k}`, resultTokens: res, error: tool === 'Bash' && r() < 0.06 ? 'exit 1' : undefined }] });
60
+ ctx += res + 400; if (ctx > 120000) ctx = 22000; // compaction
61
+ }
62
+ }
63
+ // research: one long answer, mostly reasoning
64
+ for (let s = 0; s < 40; s++) {
65
+ const out = between(r, 3000, 9000);
66
+ push({ t: T0 + r() * 7200, harness: 'research', session: `res-${s}`, model: 'gpt-5', input: between(r, 1500, 4000), cacheRead: 0, cacheWrite: 0, output: out, reasoning: Math.round(out * 0.72), durS: 20 + r() * 60 });
67
+ }
68
+ // nightly eval: a burst of single calls
69
+ for (let s = 0; s < 400; s++)
70
+ push({ t: T0 + 5400 + r() * 600, harness: 'nightly-eval', session: `eval-${s}`, model: 'gpt-5-mini', input: between(r, 2000, 4000), cacheRead: 1800, cacheWrite: 0, output: between(r, 100, 400), durS: 1 + r() * 2 });
71
+ return calls.sort((a, b) => a.t - b.t);
72
+ }
73
+
74
+ // Request bodies of three coding-agent sessions (OpenAI chat format), as a gateway that logs requests would write them:
75
+ // one line per call, { t, session, request }. The system prompt starts with a timestamp, and one session's tool
76
+ // definitions come in a different order on some calls: the two most common ways a prefix breaks.
77
+ export function demoRequests({ seed = 5 } = {}) {
78
+ const r = rng(seed), lines = [];
79
+ const TOOLS = ['Read', 'Edit', 'Grep', 'Bash'].map(name => ({ type: 'function', function: { name, description: `placeholder description for ${name} `.repeat(20), parameters: { type: 'object', properties: { path: { type: 'string' } } } } }));
80
+ for (let s = 0; s < 3; s++) {
81
+ let t = T0 + s * 900; const msgs = [];
82
+ for (let k = 0; k < 10; k++) {
83
+ t += between(r, 5, 40);
84
+ const stamp = new Date(Math.floor(t / 60) * 60 * 1000).toISOString();
85
+ const tools = s === 2 && k % 3 === 2 ? [TOOLS[1], TOOLS[0], TOOLS[2], TOOLS[3]] : TOOLS;
86
+ msgs.push({ role: 'user', content: 'placeholder request text '.repeat(between(r, 10, 40)) });
87
+ lines.push({ t, session: `req-${s}`, request: { model: 'claude-sonnet-4-5', messages: [{ role: 'system', content: `Current time: ${stamp}. ` + 'placeholder system instructions '.repeat(300) }, ...msgs.map(m => ({ ...m }))], tools } });
88
+ msgs.push({ role: 'assistant', content: 'placeholder answer '.repeat(between(r, 5, 30)) });
89
+ }
90
+ }
91
+ return lines;
92
+ }
93
+
94
+ // A self-hosted engine's counters (vLLM's Prometheus names): the server-side prefix-cache hit rate across replicas
95
+ export function demoEngineMetrics() {
96
+ return ['# TYPE vllm:prefix_cache_queries_total counter',
97
+ 'vllm:prefix_cache_queries_total{model_name="deepseek-v3",pod="vllm-0"} 8.4e8', 'vllm:prefix_cache_queries_total{model_name="deepseek-v3",pod="vllm-1"} 8.1e8',
98
+ '# TYPE vllm:prefix_cache_hits_total counter',
99
+ 'vllm:prefix_cache_hits_total{model_name="deepseek-v3",pod="vllm-0"} 4.2e8', 'vllm:prefix_cache_hits_total{model_name="deepseek-v3",pod="vllm-1"} 3.9e8', ''].join('\n');
100
+ }