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.
- package/CHANGELOG.md +154 -0
- package/README.md +43 -0
- package/bin/aiinfra.mjs +12 -0
- package/fleetops/deploy/grafana-dashboard.json +71 -0
- package/fleetops/deploy/shadow-live/README.md +8 -0
- package/fleetops/deploy/shadow-live/kit.yaml +2 -0
- package/fleetops/deploy/shadow-live/run.sh +6 -1
- package/fleetops/docs/SHADOW.md +25 -2
- package/fleetops/package.json +1 -1
- package/fleetops/src/api.mjs +8 -0
- package/fleetops/src/ingest.mjs +9 -2
- package/fleetops/src/schema.mjs +3 -0
- package/fleetops/src/serving.mjs +11 -1
- package/fleetops/src/shadow-quality.mjs +107 -0
- package/fleetops/src/shadow.mjs +12 -6
- package/fleetops/tools/cmd/help.mjs +4 -1
- package/fleetops/tools/cmd/shadow.mjs +14 -2
- package/fleetscope/build.mjs +4 -0
- package/fleetscope/dist/index.html +809 -4
- package/fleetscope/package.json +1 -1
- package/fleetscope/src/engine.js +19 -2
- package/fleetscope/src/index.src.html +23 -1
- package/gpu-health/package.json +1 -1
- package/gpu-ledger/package.json +1 -1
- package/harness-ledger/README.md +48 -0
- package/harness-ledger/integrations/README.md +11 -0
- package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
- package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
- package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
- package/harness-ledger/package.json +1 -1
- package/harness-ledger/src/advise.mjs +410 -0
- package/harness-ledger/src/assess.mjs +66 -0
- package/harness-ledger/src/doctor.mjs +202 -0
- package/harness-ledger/src/engine-metrics.mjs +35 -0
- package/harness-ledger/src/importers.mjs +14 -3
- package/harness-ledger/src/lint.mjs +115 -0
- package/harness-ledger/src/mooncake.mjs +83 -0
- package/harness-ledger/src/profile.mjs +164 -0
- package/harness-ledger/src/record.mjs +2 -2
- package/harness-ledger/src/suggest.mjs +177 -0
- package/harness-ledger/src/trajectory.mjs +81 -0
- package/harness-ledger/src/workload-demo.mjs +100 -0
- package/harness-ledger/tools/harness-ledger.mjs +224 -5
- package/hybrid-tracing/package.json +1 -1
- package/inference-sizer/build.mjs +1 -0
- package/inference-sizer/dist/index.html +192 -17
- package/inference-sizer/docs/CATALOG.md +71 -0
- package/inference-sizer/docs/METHOD.md +1 -1
- package/inference-sizer/package.json +1 -1
- package/inference-sizer/src/accelerators.js +23 -1
- package/inference-sizer/src/catalog.js +49 -3
- package/inference-sizer/src/index.src.html +7 -0
- package/inference-sizer/src/model.js +29 -9
- package/inference-sizer/src/suggest.js +70 -0
- package/inference-sizer/src/ui.js +14 -4
- package/inference-sizer/tools/validate-agentx.mjs +8 -2
- package/inference-sizer/tools/validate-inferencex.mjs +1 -1
- package/mcp/README.md +3 -0
- package/mcp/server.mjs +22 -0
- package/package.json +3 -1
- package/schemas/README.md +3 -0
- package/schemas/commands.mjs +7 -0
- package/schemas/harness-ledger.advise.schema.json +1102 -0
- package/schemas/harness-ledger.assess.schema.json +2823 -0
- package/schemas/harness-ledger.suggest.schema.json +326 -0
|
@@ -6,7 +6,8 @@ import path from 'node:path';
|
|
|
6
6
|
import zlib from 'node:zlib';
|
|
7
7
|
import readline from 'node:readline';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
|
-
import { importText, detect, IMPORTERS, tracelabCall } from '../src/importers.mjs';
|
|
9
|
+
import { importText, importAll, detect, IMPORTERS, tracelabCall } from '../src/importers.mjs';
|
|
10
|
+
import { rows as mooncakeRows, reuseCurve, routing, toMooncake } from '../src/mooncake.mjs';
|
|
10
11
|
import { dedupe } from '../src/record.mjs';
|
|
11
12
|
import { ledger, text, loadOutcomes } from '../src/ledger.mjs';
|
|
12
13
|
import { DEFAULT_PRICES } from '../src/prices.mjs';
|
|
@@ -15,6 +16,14 @@ import { demoInputs } from '../src/demo.mjs';
|
|
|
15
16
|
import { tasksFromSwebench, tasksFromRows, outcomeReport, outcomeText } from '../src/outcomes.mjs';
|
|
16
17
|
import { economics, economicsText } from '../src/economics.mjs';
|
|
17
18
|
import { fromRest as opencostRest, fromPrometheus as opencostProm, toSelfHostPrice } from '../src/opencost.mjs';
|
|
19
|
+
import { profile, profileText, CLASSES } from '../src/profile.mjs';
|
|
20
|
+
import { doctor, doctorText, parseRequests } from '../src/doctor.mjs';
|
|
21
|
+
import { prefixCacheFromProm } from '../src/engine-metrics.mjs';
|
|
22
|
+
import { advise, adviseText, GOALS } from '../src/advise.mjs';
|
|
23
|
+
import { assess, assessText, assessMarkdown, adviseMarkdown } from '../src/assess.mjs';
|
|
24
|
+
import * as Sg from '../src/suggest.mjs';
|
|
25
|
+
import { lintFile, lintReport, lintText, lintMarkdown, EXT as LINT_EXT } from '../src/lint.mjs';
|
|
26
|
+
import { mixedWorkload, demoRequests, demoEngineMetrics, DEMO_CLASS_MAP } from '../src/workload-demo.mjs';
|
|
18
27
|
|
|
19
28
|
const HELP = `harness-ledger: where agent harnesses waste model resources (tokens, dollars, GPU time), across harnesses.
|
|
20
29
|
|
|
@@ -25,6 +34,22 @@ const HELP = `harness-ledger: where agent harnesses waste model resources (token
|
|
|
25
34
|
or tasks as JSON/CSV): cost per success, spend on failures, call caps
|
|
26
35
|
harness-ledger economics PATH… [--outcomes FILE] [self-host options] [--json] cost per resolved task, fixes ranked by
|
|
27
36
|
what they save per resolved task, and self-host vs API
|
|
37
|
+
harness-ledger assess PATH… [--goals ttft,cost] [options] [--md|--json] one report: workload classes and token ratios,
|
|
38
|
+
the prefix-cache doctor, and the optimizer per goal
|
|
39
|
+
harness-ledger profile PATH… [--class-map FILE] workload classes (critical, realtime, agentic, reasoning,
|
|
40
|
+
batch): token ratios, what bounds each, what to change
|
|
41
|
+
harness-ledger doctor PATH… [--requests FILE] [--engine-metrics FILE|URL] why the prefix cache misses, and what to change
|
|
42
|
+
harness-ledger advise PATH… --goal ttft|tpot|e2e|cost|gpus|throughput [--apply IDS] [--fail-if COND]
|
|
43
|
+
every change across the stack that moves the goal, the
|
|
44
|
+
best combinations, and a dry run of the ones you pick
|
|
45
|
+
harness-ledger suggest PATH… [--watch S] [--store DIR] [--slack URL] [--lark URL] [--langfuse] [--live]
|
|
46
|
+
the changes worth making, raised once and remembered;
|
|
47
|
+
suggest list | accept | dismiss | snooze ID [--for 7d]
|
|
48
|
+
harness-ledger lint PATH… [--md|--json] [--fail] prompt templates and request bodies that will miss the prefix
|
|
49
|
+
cache (a per-call value before static text); --fail exits 3
|
|
50
|
+
harness-ledger mooncake TRACE… [--sim-replicas N --cache-tokens T] a Mooncake trace's prefix reuse by cache size, and random
|
|
51
|
+
vs prefix-aware routing across replicas
|
|
52
|
+
harness-ledger mooncake --requests FILE --out trace.jsonl request bodies → a Mooncake trace (no text; for AIPerf)
|
|
28
53
|
harness-ledger demo [--html FILE] [--json] three harnesses and a vLLM fleet, synthetic
|
|
29
54
|
harness-ledger formats what it reads
|
|
30
55
|
|
|
@@ -34,6 +59,11 @@ Inputs (detected from the file; --format to force):
|
|
|
34
59
|
otel OpenTelemetry GenAI or OpenInference spans: OTLP JSON or one span per line (any instrumented harness)
|
|
35
60
|
langfuse Langfuse observation exports (JSON or JSON lines)
|
|
36
61
|
tracelab the TraceLab coding-agent trace (syfi_coding_trace.jsonl.gz: Claude Code and Codex, streamed)
|
|
62
|
+
trajectory agent trajectories with full message lists (SWE-agent, OpenHands; datasets exported to JSON lines):
|
|
63
|
+
one call per assistant message, tokens estimated, ideal prefix-cache accounting, synthetic timing
|
|
64
|
+
(--step-gap S); their request bodies feed the prefix-cache doctor automatically
|
|
65
|
+
mooncake Mooncake-format serving traces (timestamp, input_length, output_length, hash_ids): cache hits from a
|
|
66
|
+
cache of --cache-tokens (unbounded by default); --sim-replicas N simulates the engine's hit rate
|
|
37
67
|
calls.jsonl llm_call records written by "import"
|
|
38
68
|
|
|
39
69
|
Report options:
|
|
@@ -64,8 +94,39 @@ Economics options (with the report options above):
|
|
|
64
94
|
--days N | --tasks-per-day N the period the input covers, or the volume to plan for
|
|
65
95
|
--unit-price $ (with --prices relative) dollars per relative unit (a million fresh input tokens) for the break-even
|
|
66
96
|
--demo the synthetic demo input
|
|
97
|
+
|
|
98
|
+
Assess, profile, doctor and advise options (with the report options above):
|
|
99
|
+
--class-map FILE { "critical": ["harness:payments-agent", "agent:billing*"], "batch": ["session:nightly-*"] }; or
|
|
100
|
+
--critical / --realtime / --agentic / --reasoning / --batch with comma-separated field:glob patterns
|
|
101
|
+
--requests FILE request bodies, one JSON per line ({ t, session, request }): which part of the prompt breaks the cache
|
|
102
|
+
(the bodies are read for hashes; nothing is written out)
|
|
103
|
+
--engine-metrics FILE|URL the engine's Prometheus metrics (vLLM, SGLang): its own prefix-cache hit rate
|
|
104
|
+
--model ID --gpu ID self-hosted: the open model and GPU (Inference Sizer catalog) the fleet runs; --gpus N its size
|
|
105
|
+
(default: what the sizer needs for --ttft/--tpot); --wprec bf16|fp8|fp4 --kvprec bf16|fp8 what it
|
|
106
|
+
runs today; --spec-on when it already decodes speculatively; --gpu-rate $/GPU-h
|
|
107
|
+
--alt-gpus IDS --alt-models IDS other GPUs and models to price (default: the next GPUs up from the same vendor)
|
|
108
|
+
--spec-accept 0.7 --spec-tokens 3 speculative decoding assumptions --batch-discount 0.5 a provider's batch price cut
|
|
109
|
+
--max-cost-increase 0.2 the best combination may raise cost by at most this share
|
|
110
|
+
--apply IDS dry run of these changes (comma-separated ids from the menu); --out FILE writes the change set
|
|
111
|
+
--fail-if COND with --apply: exit 3 when the dry run moves a metric past a bound ("ttft>+5%,cost>+0%,gpus>16")
|
|
112
|
+
--md Markdown (for a CI job summary or a PR comment)
|
|
113
|
+
|
|
114
|
+
Suggest options (with the assess options above):
|
|
115
|
+
--state FILE what was raised, accepted, dismissed or snoozed (default ~/.aiinfra/suggestions.json, or $AIINFRA_STATE);
|
|
116
|
+
--no-state lists every current suggestion without reading or writing it
|
|
117
|
+
--min-gain 0.05 raise a change that moves a goal by at least this share; one raised before comes back when it grows by half
|
|
118
|
+
--watch S re-read the inputs and re-run every S seconds (with --since 24h for a rolling window)
|
|
119
|
+
--all print every open suggestion, not only the new ones
|
|
120
|
+
--jsonl FILE append the new ones to a file --store DIR write them to a fleetops store (Grafana's suggestions panel)
|
|
121
|
+
--slack URL | --lark URL a Slack incoming webhook or a Lark/Feishu custom bot (or --slack with $SLACK_WEBHOOK_URL, --lark with
|
|
122
|
+
$LARK_WEBHOOK_URL); --link URL adds a button to it (your Grafana dashboard)
|
|
123
|
+
--langfuse a comment on the Langfuse sessions each suggestion is about ($LANGFUSE_HOST, $LANGFUSE_PUBLIC_KEY,
|
|
124
|
+
$LANGFUSE_SECRET_KEY; --langfuse-project ID)
|
|
125
|
+
--live actually send to Slack, Lark and Langfuse (without it they are dry runs that say what they would send)
|
|
67
126
|
`;
|
|
68
127
|
|
|
128
|
+
// ~ and ~/… mean the home folder on every OS (Windows' Command Prompt and PowerShell don't expand it themselves)
|
|
129
|
+
export const expandHome = p => (typeof p === 'string' && (p === '~' || /^~[\\/]/.test(p)) ? path.join(os.homedir(), p.slice(2)) : p);
|
|
69
130
|
function args(argv) {
|
|
70
131
|
const o = { _: [] };
|
|
71
132
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -100,17 +161,21 @@ function head(f, n = 65536) {
|
|
|
100
161
|
try { return zlib.gunzipSync(b.subarray(0, k), { finishFlush: zlib.constants.Z_SYNC_FLUSH }).toString('utf8'); } catch { return ''; }
|
|
101
162
|
}
|
|
102
163
|
async function load(paths, o) {
|
|
103
|
-
const files = paths.flatMap(p => walk(p)), calls = [], skipped = [];
|
|
164
|
+
const files = paths.flatMap(p => walk(p)), calls = [], skipped = [], requests = [], mooncake = [];
|
|
104
165
|
for (const f of files) {
|
|
105
166
|
if ((o.format || detect(head(f), f)) === 'tracelab') { await streamLines(f, x => { const c = x && x.input_tokens_total != null && tracelabCall(x); if (c) calls.push(c); }); continue; }
|
|
106
167
|
const txt = read(f);
|
|
107
168
|
if (/^\s*\{"kind":"llm_call"/.test(txt)) { for (const l of txt.split(/\r?\n/)) if (l.trim()) calls.push(JSON.parse(l)); continue; }
|
|
108
169
|
const kind = o.format || detect(txt, f);
|
|
109
170
|
if (!kind) { skipped.push(f); continue; }
|
|
110
|
-
try {
|
|
171
|
+
try {
|
|
172
|
+
const r = importAll(txt, { kind, file: f, harness: o.harness, model: o.model || undefined, cacheTokens: o['cache-tokens'] ? Number(o['cache-tokens']) : undefined, stepGapS: o['step-gap'] ? Number(o['step-gap']) : undefined });
|
|
173
|
+
calls.push(...r.calls); requests.push(...r.requests);
|
|
174
|
+
if (kind === 'mooncake') mooncake.push(...mooncakeRows(txt));
|
|
175
|
+
} catch (e) { skipped.push(`${f} (${e.message})`); }
|
|
111
176
|
}
|
|
112
177
|
const from = since(o.since);
|
|
113
|
-
return { calls: dedupe(calls).filter(c => c.t == null || c.t >= from), files: files.length, skipped };
|
|
178
|
+
return { calls: dedupe(calls).filter(c => c.t == null || c.t >= from), files: files.length, skipped, requests, mooncake };
|
|
114
179
|
}
|
|
115
180
|
|
|
116
181
|
function report(calls, o, extra = {}) {
|
|
@@ -127,8 +192,134 @@ function report(calls, o, extra = {}) {
|
|
|
127
192
|
return 0;
|
|
128
193
|
}
|
|
129
194
|
|
|
195
|
+
function classMapOf(o) {
|
|
196
|
+
const m = o['class-map'] ? readJson(o['class-map']) : {};
|
|
197
|
+
for (const c of CLASSES) if (o[c] && o[c] !== true) m[c] = [].concat(m[c] || [], String(o[c]).split(',').map(x => x.trim()).filter(Boolean));
|
|
198
|
+
return Object.keys(m).length ? m : null;
|
|
199
|
+
}
|
|
200
|
+
async function engineMetrics(src) {
|
|
201
|
+
if (!src) return null;
|
|
202
|
+
const s = String(src), txt = /^https?:\/\//.test(s) ? await (await fetch(/\/metrics\/?$/.test(s) ? s : `${s.replace(/\/$/, '')}/metrics`)).text() : read(s);
|
|
203
|
+
const m = prefixCacheFromProm(txt);
|
|
204
|
+
if (!m) throw new Error(`--engine-metrics: no prefix-cache metrics in ${s}`);
|
|
205
|
+
return m;
|
|
206
|
+
}
|
|
207
|
+
const list = v => (v && v !== true ? String(v).split(',').map(x => x.trim()).filter(Boolean) : undefined);
|
|
208
|
+
async function optimizeCmd(cmd, paths, o) {
|
|
209
|
+
const P = await prepare(cmd, paths, o); if (typeof P === 'number') return P;
|
|
210
|
+
const { r, opts, classMap, cacheTtlS, requests, server, model, gpu } = P;
|
|
211
|
+
return optimizeOut(cmd, o, { r, opts, classMap, cacheTtlS, requests, server, model, gpu });
|
|
212
|
+
}
|
|
213
|
+
async function prepare(cmd, paths, o) {
|
|
214
|
+
let calls, requests = null, server = null, classMap = classMapOf(o);
|
|
215
|
+
if (o.demo) { calls = mixedWorkload(); requests = parseRequests(demoRequests().map(x => JSON.stringify(x)).join('\n')); server = o['self-host'] || o.model || o.gpu ? prefixCacheFromProm(demoEngineMetrics()) : null; classMap = classMap || DEMO_CLASS_MAP; }
|
|
216
|
+
else {
|
|
217
|
+
if (!paths.length) { process.stderr.write(`harness-ledger ${cmd}: give files or folders (or --demo)\n`); return 2; }
|
|
218
|
+
const L = await load(paths, o); calls = L.calls;
|
|
219
|
+
if (L.requests.length) requests = parseRequests(L.requests.map(x => JSON.stringify(x)).join('\n'));
|
|
220
|
+
// a Mooncake trace with --replicas: what those replicas get under random routing is the "engine" hit rate, and
|
|
221
|
+
// the traces' own reuse (unbounded cache) is what prefix routing could reach
|
|
222
|
+
if (L.mooncake.length && o['sim-replicas']) {
|
|
223
|
+
const R = routing(L.mooncake, { replicas: Number(o['sim-replicas']), cacheTokensPerReplica: o['cache-tokens'] ? Number(o['cache-tokens']) : 4e6 });
|
|
224
|
+
server = { engine: `simulated: ${R.replicas} replicas, random routing`, hitRate: R.random, prefixRouting: R.prefix };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (!calls.length) { process.stderr.write('harness-ledger: no model calls found in the input\n'); return 1; }
|
|
228
|
+
if (o.requests) requests = parseRequests(read(o.requests));
|
|
229
|
+
if (o['engine-metrics']) server = await engineMetrics(o['engine-metrics']);
|
|
230
|
+
const cacheTtlS = o['cache-ttl'] ? Number(o['cache-ttl']) : 300;
|
|
231
|
+
const lopts = { outcomes: loadOutcomes(o.outcomes ? read(o.outcomes) : null), cacheTtlS, bigResultTokens: o['big-result'] ? Number(o['big-result']) : undefined };
|
|
232
|
+
let r = ledger(calls, { ...lopts, prices: o.prices === 'relative' ? 'relative' : o.prices ? readJson(o.prices) : DEFAULT_PRICES });
|
|
233
|
+
// most calls on models the example price table doesn't list (a model newer than it): price them relatively, so cost
|
|
234
|
+
// changes still come out right as shares, rather than every change saving $0
|
|
235
|
+
const T0 = r.report.totals;
|
|
236
|
+
if (!o.prices && T0.calls && T0.unpricedCalls / T0.calls > 0.5) {
|
|
237
|
+
r = ledger(calls, { ...lopts, prices: 'relative' });
|
|
238
|
+
if (!o.json) process.stderr.write(`note: no example price for ${(T0.unpricedModels || []).slice(0, 3).join(', ')}${T0.unpricedModels && T0.unpricedModels.length > 3 ? '…' : ''}: costs are in relative units (--prices FILE for dollars)\n`);
|
|
239
|
+
}
|
|
240
|
+
const n = k => (o[k] != null && o[k] !== true ? Number(o[k]) : undefined);
|
|
241
|
+
const model = o.model || o['self-host-model'] || (o.demo && o['self-host'] ? 'deepseek-v3' : undefined), gpu = o.gpu || (o.demo && o['self-host'] ? 'H200' : undefined);
|
|
242
|
+
const opts = { classMap, cacheTtlS, requests, server, model, gpu, fleetGpus: n('gpus'), ttft: n('ttft'), tpot: n('tpot'), gpuRate: n('gpu-rate'), wprec: o.wprec, kvprec: o.kvprec, specOn: !!o['spec-on'],
|
|
243
|
+
altGpus: list(o['alt-gpus']), altModels: list(o['alt-models']), specAccept: n('spec-accept'), specTokens: n('spec-tokens'), batchDiscount: n('batch-discount'), maxCostIncrease: n('max-cost-increase'),
|
|
244
|
+
days: n('days'), calibration: o.calibration ? readJson(o.calibration) : undefined, toolKeep: n('tool-keep'), bigResult: n('big-result') };
|
|
245
|
+
for (const k of Object.keys(opts)) if (opts[k] === undefined) delete opts[k];
|
|
246
|
+
return { r, opts, classMap, cacheTtlS, requests, server, model, gpu };
|
|
247
|
+
}
|
|
248
|
+
function optimizeOut(cmd, o, { r, opts, classMap, cacheTtlS, requests, server, model, gpu }) {
|
|
249
|
+
const out = (j, txt, md) => process.stdout.write(o.json ? JSON.stringify(j, null, 1) + '\n' : o.md && md ? md : txt);
|
|
250
|
+
if (cmd === 'profile') { const P = profile(r.calls, { classMap, cacheTtlS }); out(P, profileText(P)); return 0; }
|
|
251
|
+
if (cmd === 'doctor') {
|
|
252
|
+
const D = doctor(r.calls, r.findings, { requests, engine: server, cacheTtlS });
|
|
253
|
+
if (D.server && D.hit.all) { D.server.potential = D.hit.all.hit; D.server.gap = D.server.potential - D.server.hitRate; }
|
|
254
|
+
out(D, doctorText(D)); return 0;
|
|
255
|
+
}
|
|
256
|
+
if (cmd === 'assess') {
|
|
257
|
+
const goals = list(o.goals) || (model || gpu ? ['ttft', 'tpot', 'cost'] : ['ttft', 'cost']);
|
|
258
|
+
const bad = goals.filter(g => !GOALS[g]); if (bad.length) { process.stderr.write(`--goals: ${bad.join(', ')}: one of ${Object.keys(GOALS).join(', ')}\n`); return 2; }
|
|
259
|
+
const A = assess(r, { ...opts, goals });
|
|
260
|
+
if (o.out) fs.writeFileSync(o.out, JSON.stringify(A, null, 1) + '\n');
|
|
261
|
+
out(A, assessText(A), assessMarkdown(A)); return 0;
|
|
262
|
+
}
|
|
263
|
+
const goal = o.goal && o.goal !== true ? String(o.goal) : 'ttft';
|
|
264
|
+
if (!GOALS[goal]) { process.stderr.write(`--goal: one of ${Object.keys(GOALS).join(', ')}\n`); return 2; }
|
|
265
|
+
if (o['fail-if'] && !o.apply) { process.stderr.write('--fail-if needs --apply (the changes to check)\n'); return 2; }
|
|
266
|
+
const apply = o.apply === true ? 'best' : o.apply;
|
|
267
|
+
let R = advise(r.calls, r.report, r.findings, { ...opts, goal });
|
|
268
|
+
if (apply) R = advise(r.calls, r.report, r.findings, { ...opts, goal, apply: apply === 'best' ? R.bundles.best.levers : apply === 'safe' ? R.bundles.safe.levers : list(apply), failIf: o['fail-if'] });
|
|
269
|
+
if (o.out && R.dryRun) fs.writeFileSync(o.out, JSON.stringify({ kind: 'harness-ledger.changes', goal, applied: R.dryRun.applied, before: R.dryRun.before, after: R.dryRun.after, changes: R.dryRun.changes, next: R.dryRun.next, gate: R.gate || null }, null, 1) + '\n');
|
|
270
|
+
out(R, adviseText(R), adviseMarkdown(R));
|
|
271
|
+
return R.gate && !R.gate.pass ? 3 : 0;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// suggest: assess, keep what is worth raising, raise it once, remember the answer
|
|
275
|
+
async function suggestCmd(paths, o) {
|
|
276
|
+
const stateFile = o.state && o.state !== true ? String(o.state) : Sg.defaultStatePath(), sub = paths[0];
|
|
277
|
+
if (['list', 'accept', 'dismiss', 'snooze', 'reopen'].includes(sub)) {
|
|
278
|
+
const st = Sg.loadState(stateFile);
|
|
279
|
+
if (sub === 'list') {
|
|
280
|
+
const items = Object.entries(st.items).map(([id, it]) => ({ id, ...it }));
|
|
281
|
+
if (o.json) { process.stdout.write(JSON.stringify({ kind: 'harness-ledger.suggestions', state: stateFile, items }, null, 1) + '\n'); return 0; }
|
|
282
|
+
process.stdout.write(items.length ? items.map(it => `${it.id} ${it.status.padEnd(9)} ${it.title || it.change}${it.until ? ` (until ${new Date(it.until * 1000).toISOString().slice(0, 10)})` : ''}`).join('\n') + '\n' : `no suggestions in ${stateFile}\n`);
|
|
283
|
+
return 0;
|
|
284
|
+
}
|
|
285
|
+
if (!paths[1]) { process.stderr.write(`harness-ledger suggest ${sub} ID [--by NAME] [--for 7d] [--note TEXT]\n`); return 2; }
|
|
286
|
+
const status = { accept: 'accepted', dismiss: 'dismissed', snooze: 'snoozed', reopen: 'open' }[sub];
|
|
287
|
+
const id = Sg.setStatus(st, paths[1], status, { by: o.by && o.by !== true ? String(o.by) : null, untilS: sub === 'snooze' ? Sg.duration(o.for) : null, note: o.note && o.note !== true ? String(o.note) : null });
|
|
288
|
+
Sg.saveState(stateFile, st); process.stdout.write(`${id}: ${status}\n`); return 0;
|
|
289
|
+
}
|
|
290
|
+
const watch = o.watch && o.watch !== true ? Number(o.watch) : 0, maxCycles = o['max-cycles'] ? Number(o['max-cycles']) : Infinity;
|
|
291
|
+
let code = 0;
|
|
292
|
+
for (let cycle = 1; ; cycle++) {
|
|
293
|
+
const P = await prepare('suggest', paths, o); if (typeof P === 'number') return P;
|
|
294
|
+
const goals = list(o.goals) || (P.model || P.gpu ? ['ttft', 'tpot', 'cost'] : ['ttft', 'cost']);
|
|
295
|
+
const A = assess(P.r, { ...P.opts, goals });
|
|
296
|
+
const sug = Sg.suggestions(P.r, A, { scope: o.scope && o.scope !== true ? String(o.scope) : 'all', minGain: o['min-gain'] ? Number(o['min-gain']) : undefined, inputs: o.demo ? '--demo' : paths.join(' '), requests: o.demo ? false : o.requests || null });
|
|
297
|
+
const noState = !!o['no-state'], st = noState ? { version: 1, items: {}, feedback: [] } : Sg.loadState(stateFile), T = Sg.triage(sug, st);
|
|
298
|
+
const sent = [];
|
|
299
|
+
if (o.jsonl) { fs.appendFileSync(String(o.jsonl), T.fresh.map(x => JSON.stringify({ t: Math.floor(Date.now() / 1000), ...x })).join('\n') + (T.fresh.length ? '\n' : '')); }
|
|
300
|
+
if (o.store) { const { DataStore } = await import('../../fleetops/src/store.mjs'); const recs = Sg.storeRecords(T); const w = new DataStore(String(o.store)).append('suggestion', recs, { source: 'aiinfra-suggest' }); sent.push(`${w.written ?? recs.length} records → fleetops store ${o.store}`); }
|
|
301
|
+
const link = o.link && o.link !== true ? String(o.link) : null, live = !!o.live;
|
|
302
|
+
for (const kind of ['slack', 'lark']) {
|
|
303
|
+
const url = o[kind] && o[kind] !== true ? String(o[kind]) : o[kind] === true ? process.env[kind === 'slack' ? 'SLACK_WEBHOOK_URL' : 'LARK_WEBHOOK_URL'] : null;
|
|
304
|
+
if (o[kind] && !url) { process.stderr.write(`--${kind}: give the webhook URL, or set ${kind === 'slack' ? 'SLACK_WEBHOOK_URL' : 'LARK_WEBHOOK_URL'}\n`); return 2; }
|
|
305
|
+
if (url) { const res = await Sg.sendWebhook(kind, url, T.fresh, { live, link }); sent.push(res.dryRun ? `dry run: would send ${res.would} (add --live)` : `${res.sent} sent to ${kind}${res.error ? ` (failed: ${res.error})` : ''}`); if (res.error) code = 1; }
|
|
306
|
+
}
|
|
307
|
+
if (o.langfuse) {
|
|
308
|
+
const res = await Sg.sendLangfuse(T.fresh, { host: process.env.LANGFUSE_HOST || process.env.LANGFUSE_BASE_URL, publicKey: process.env.LANGFUSE_PUBLIC_KEY, secretKey: process.env.LANGFUSE_SECRET_KEY, projectId: o['langfuse-project'] && o['langfuse-project'] !== true ? String(o['langfuse-project']) : null, live });
|
|
309
|
+
sent.push(res.dryRun ? `dry run: would post ${res.would} (add --live)` : `${res.sent} Langfuse comments${res.errors && res.errors.length ? `; failed: ${res.errors.slice(0, 3).join(', ')}` : ''}${res.error ? `; ${res.error}` : ''}`);
|
|
310
|
+
if (res.error || (res.errors && res.errors.length)) code = 1;
|
|
311
|
+
}
|
|
312
|
+
if (!noState) Sg.saveState(stateFile, st);
|
|
313
|
+
if (o.json) process.stdout.write(JSON.stringify({ kind: 'harness-ledger.suggest', cycle, state: noState ? null : stateFile, fresh: T.fresh, open: T.open, silenced: T.silenced.map(x => ({ id: x.id, change: x.change, status: x.status })), sinks: sent }, null, 1) + '\n');
|
|
314
|
+
else process.stdout.write((watch ? `--- ${new Date().toISOString()}\n` : '') + Sg.suggestText(T, { all: !!o.all }) + (sent.length ? sent.map(x => ` ${x}`).join('\n') + '\n' : ''));
|
|
315
|
+
if (!watch || cycle >= maxCycles) return code;
|
|
316
|
+
await new Promise(res => setTimeout(res, watch * 1000));
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
130
320
|
export async function main(argv) {
|
|
131
|
-
const o = args(argv), [cmd, ...
|
|
321
|
+
const o = args(argv), [cmd, ...rawPaths] = o._, paths = rawPaths.map(expandHome);
|
|
322
|
+
for (const k of ['requests', 'state', 'store', 'jsonl', 'out', 'outcomes', 'prices', 'engine', 'replicas', 'class-map', 'calibration', 'claude', 'codex', 'html', 'calls-out']) if (typeof o[k] === 'string') o[k] = expandHome(o[k]);
|
|
132
323
|
if (!cmd || o.help || cmd === 'help') { process.stdout.write(HELP); return 0; }
|
|
133
324
|
if (cmd === 'formats') { process.stdout.write(HELP.slice(HELP.indexOf('Inputs'), HELP.indexOf('Report options'))); return 0; }
|
|
134
325
|
if (cmd === 'demo') {
|
|
@@ -164,6 +355,34 @@ export async function main(argv) {
|
|
|
164
355
|
process.stdout.write(o.json ? JSON.stringify(E, null, 1) + '\n' : economicsText(E));
|
|
165
356
|
return 0;
|
|
166
357
|
}
|
|
358
|
+
if (['assess', 'profile', 'doctor', 'advise'].includes(cmd)) return optimizeCmd(cmd, paths, o);
|
|
359
|
+
if (cmd === 'suggest') return suggestCmd(paths, o);
|
|
360
|
+
if (cmd === 'lint') {
|
|
361
|
+
if (!paths.length) { process.stderr.write('harness-ledger lint PATH… [--static-after 1024] [--md|--json] [--fail]\n'); return 2; }
|
|
362
|
+
const files = []; const walkAll = p => { const st = fs.statSync(p); if (st.isDirectory()) { for (const e of fs.readdirSync(p)) if (!e.startsWith('.') && e !== 'node_modules') walkAll(path.join(p, e)); } else if (LINT_EXT.test(p) || paths.includes(p)) files.push(p); };
|
|
363
|
+
for (const p of paths) walkAll(p);
|
|
364
|
+
const R = lintReport(files.flatMap(f => lintFile(f, read(f), { staticAfter: o['static-after'] ? Number(o['static-after']) : undefined })));
|
|
365
|
+
process.stdout.write(o.json ? JSON.stringify(R, null, 1) + '\n' : o.md ? lintMarkdown(R) : lintText(R));
|
|
366
|
+
return o.fail && R.issues ? 3 : 0;
|
|
367
|
+
}
|
|
368
|
+
if (cmd === 'mooncake') {
|
|
369
|
+
if (o.requests) {
|
|
370
|
+
const rows = toMooncake(parseRequests(read(o.requests)), { block: o['block-size'] ? Number(o['block-size']) : undefined, salt: o.salt && o.salt !== true ? String(o.salt) : undefined });
|
|
371
|
+
const body = rows.map(r => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : '');
|
|
372
|
+
if (o.out) { fs.writeFileSync(o.out, body); process.stderr.write(`${rows.length} requests → ${o.out} (Mooncake format, no text)\n`); } else process.stdout.write(body);
|
|
373
|
+
return 0;
|
|
374
|
+
}
|
|
375
|
+
if (!paths.length) { process.stderr.write('harness-ledger mooncake TRACE.jsonl [--sim-replicas 8 --cache-tokens 4000000] | --requests FILE --out trace.jsonl\n'); return 2; }
|
|
376
|
+
const rs = paths.flatMap(p => walk(p)).flatMap(f => mooncakeRows(read(f)));
|
|
377
|
+
if (!rs.length) { process.stderr.write('no Mooncake rows (hash_ids, input_length) in the input\n'); return 1; }
|
|
378
|
+
const curve = reuseCurve(rs), R = o['sim-replicas'] ? routing(rs, { replicas: Number(o['sim-replicas']), cacheTokensPerReplica: o['cache-tokens'] ? Number(o['cache-tokens']) : 4e6 }) : null;
|
|
379
|
+
const res = { kind: 'harness-ledger.mooncake', requests: rs.length, inputTokens: rs.reduce((a, r) => a + r.input_length, 0), curve, routing: R };
|
|
380
|
+
if (o.json) { process.stdout.write(JSON.stringify(res, null, 1) + '\n'); return 0; }
|
|
381
|
+
const tok = v => (!Number.isFinite(v) ? 'unbounded' : v >= 1e6 ? `${v / 1e6}M` : `${v / 1e3}K`);
|
|
382
|
+
process.stdout.write(`${rs.length} requests, ${(res.inputTokens / 1e6).toFixed(1)}M input tokens\n\nprefix-cache hit rate by cache size (tokens):\n` + curve.map(c => ` ${tok(c.cacheTokens).padStart(9)} ${(100 * c.hitRate).toFixed(1)}%`).join('\n') + '\n' +
|
|
383
|
+
(R ? `\n${R.replicas} replicas × ${tok(R.cacheTokensPerReplica)} tokens: random routing ${(100 * R.random).toFixed(1)}%, prefix-aware routing ${(100 * R.prefix).toFixed(1)}% (ceiling ${(100 * R.ceiling).toFixed(1)}%)\n` : ''));
|
|
384
|
+
return 0;
|
|
385
|
+
}
|
|
167
386
|
if (cmd === 'outcomes') {
|
|
168
387
|
if (!paths.length) { process.stderr.write('harness-ledger outcomes: give per_instance_details.json files, folders of them, or task JSON/CSV\n'); return 2; }
|
|
169
388
|
const tasks = [];
|
|
@@ -11,6 +11,7 @@ const inlined = {
|
|
|
11
11
|
'/*ACCELERATORS*/': read('src/accelerators.js'),
|
|
12
12
|
'/*CATALOG*/': read('src/catalog.js'),
|
|
13
13
|
'/*MODEL*/': read('src/model.js'),
|
|
14
|
+
'/*SUGGEST*/': read('src/suggest.js'),
|
|
14
15
|
'/*FLEETSCOPE*/': read('src/fleetscope.js'),
|
|
15
16
|
'/*UI*/': read('src/ui.js'),
|
|
16
17
|
'/*FIT*/': read('src/fit.js'),
|