@mmerterden/multi-agent-pipeline 20.41.0 → 20.42.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 +44 -0
- package/README.md +1 -1
- package/README.tr.md +1 -1
- package/docs/ecosystem.md +45 -8
- package/docs/facts.json +7 -7
- package/docs/features.md +9 -4
- package/install/claude.mjs +34 -1
- package/install/templates/claude-hooks.json +12 -1
- package/manifest.json +106 -86
- package/package.json +3 -2
- package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
- package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
- package/pipeline/lib/args.mjs +131 -4
- package/pipeline/lib/bg-launch.mjs +5 -2
- package/pipeline/lib/credential-store.sh +11 -1
- package/pipeline/lib/hook-once.mjs +134 -0
- package/pipeline/lib/isotonic.mjs +73 -0
- package/pipeline/lib/low-disk.mjs +153 -0
- package/pipeline/lib/mcp-schema-load.mjs +90 -0
- package/pipeline/lib/md2confluence-v3.py +8 -7
- package/pipeline/lib/model-dispatch.sh +26 -2
- package/pipeline/lib/normalize-text.mjs +135 -0
- package/pipeline/lib/outbound-gate.mjs +21 -3
- package/pipeline/lib/plan-todos.sh +17 -4
- package/pipeline/lib/redact.mjs +12 -3
- package/pipeline/lib/risky-settings.mjs +198 -0
- package/pipeline/lib/route-state.sh +1 -0
- package/pipeline/lib/secret-patterns.generated.mjs +6 -2
- package/pipeline/lib/session-usage.mjs +232 -0
- package/pipeline/lib/source-digest.mjs +211 -0
- package/pipeline/lib/tdd-evidence.mjs +250 -17
- package/pipeline/lib/untrusted-fence.mjs +132 -1
- package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
- package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
- package/pipeline/multi-agent-refs/features/doctor.md +51 -4
- package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
- package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
- package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
- package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
- package/pipeline/multi-agent-refs/help/en.md +1 -1
- package/pipeline/multi-agent-refs/help/tr.md +1 -1
- package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
- package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
- package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
- package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
- package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
- package/pipeline/multi-agent-refs/progress-contract.md +3 -1
- package/pipeline/office/toolkit.json +1 -1
- package/pipeline/rules/outside-the-pipeline.md +1 -1
- package/pipeline/schemas/doctor-report.schema.json +47 -0
- package/pipeline/schemas/plan-todos.schema.json +29 -1
- package/pipeline/schemas/prefs.schema.json +63 -0
- package/pipeline/schemas/route-config.schema.json +51 -0
- package/pipeline/schemas/secret-patterns.json +17 -1
- package/pipeline/schemas/toolkit-path-params.json +15 -1
- package/pipeline/scripts/_cost-advise.mjs +357 -0
- package/pipeline/scripts/_cost-budget.mjs +78 -0
- package/pipeline/scripts/_cost.mjs +29 -0
- package/pipeline/scripts/_decode_text.py +107 -0
- package/pipeline/scripts/_guard-probe.mjs +406 -0
- package/pipeline/scripts/_guard_rules.py +206 -0
- package/pipeline/scripts/_memory-policy.mjs +1 -25
- package/pipeline/scripts/_retrieval.mjs +148 -2
- package/pipeline/scripts/_secret-scan.mjs +6 -1
- package/pipeline/scripts/_stack-routing.mjs +1 -0
- package/pipeline/scripts/_test-gaming.mjs +346 -0
- package/pipeline/scripts/agent-guard.py +8 -1
- package/pipeline/scripts/argv-secret-scan.mjs +2 -1
- package/pipeline/scripts/autopilot-loop.mjs +407 -0
- package/pipeline/scripts/autopilot-runner.mjs +38 -25
- package/pipeline/scripts/capture-resume.sh +9 -1
- package/pipeline/scripts/cost-analyze.mjs +66 -4
- package/pipeline/scripts/cost-budget-check.mjs +5 -13
- package/pipeline/scripts/disk-cleaner.mjs +1418 -0
- package/pipeline/scripts/doctor.mjs +169 -44
- package/pipeline/scripts/evidence-gate.mjs +90 -0
- package/pipeline/scripts/gate-ledger.mjs +76 -21
- package/pipeline/scripts/gc-tmp.sh +5 -0
- package/pipeline/scripts/guard-probe-known-holes.json +3 -0
- package/pipeline/scripts/learnings-ledger.mjs +16 -12
- package/pipeline/scripts/note-agent-event.mjs +2 -0
- package/pipeline/scripts/note-mcp-failure.mjs +9 -2
- package/pipeline/scripts/note-skill-use.mjs +4 -1
- package/pipeline/scripts/pre-commit-check.sh +2 -2
- package/pipeline/scripts/pre-push-check.sh +8 -1
- package/pipeline/scripts/publish-staged.mjs +324 -0
- package/pipeline/scripts/route-learn.mjs +628 -0
- package/pipeline/scripts/run-scope-guard.mjs +55 -1
- package/pipeline/scripts/scan-agent-config.sh +1 -1
- package/pipeline/scripts/statusline.mjs +309 -0
- package/pipeline/scripts/test-integrity-gate.mjs +97 -2
- package/pipeline/scripts/triage-memory.mjs +12 -4
- package/pipeline/scripts/uninstall.mjs +1 -0
- package/pipeline/skills/.skill-manifest.json +8 -4
- package/pipeline/skills/.skills-index.json +14 -3
- package/pipeline/skills/shared/README.md +5 -4
- package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
- package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
- package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
- package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
- package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
- package/pipeline/skills/skill-copies.json +4 -0
- package/pipeline/skills/skills-index.md +3 -2
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file _cost-advise.mjs - what to change about the spend, each finding with
|
|
3
|
+
* the numbers it rests on and where they were read.
|
|
4
|
+
*
|
|
5
|
+
* cost-analyze.mjs says what the spend was and whether it is moving. This says
|
|
6
|
+
* which lever to pull. Every finding carries `numbers` (the measured values
|
|
7
|
+
* the judgement was made on), `source` (the transcripts and record count they
|
|
8
|
+
* came from) and `savingUsd`: a what-if repricing of the SAME tokens at
|
|
9
|
+
* another rate, or null when no defensible figure exists. A saving is never
|
|
10
|
+
* guessed to fill the column.
|
|
11
|
+
*
|
|
12
|
+
* cache-read-ratio too little input was served from the prompt cache
|
|
13
|
+
* ttl-1h-payback 1-hour cache writes (2x input) whose reads did not need
|
|
14
|
+
* the hour: a read counts for the 1h TTL only when it came
|
|
15
|
+
* more than five minutes after the session's previous
|
|
16
|
+
* turn, which is when a 5-minute entry would have lapsed
|
|
17
|
+
* and been written again at 1.25x
|
|
18
|
+
* subagent-tier-<r> sub-agent turns on a top rung, repriced one rung down,
|
|
19
|
+
* naming the personas pinned to that rung
|
|
20
|
+
* context-bloat sessions whose every turn carries a very large context
|
|
21
|
+
* unpriced models the price table does not know, so the totals
|
|
22
|
+
* and every saving above leave them out
|
|
23
|
+
*
|
|
24
|
+
* Quality is not measured here. A cheaper rung for a persona is a cost fact,
|
|
25
|
+
* not a recommendation that it will review as well; the action says so.
|
|
26
|
+
*
|
|
27
|
+
* Zero runtime dependencies (ADR-0004).
|
|
28
|
+
*
|
|
29
|
+
* @module pipeline/scripts/_cost-advise
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
33
|
+
import { join } from "node:path";
|
|
34
|
+
|
|
35
|
+
import {
|
|
36
|
+
CACHE_WRITE_1H_MULTIPLIER,
|
|
37
|
+
CACHE_WRITE_MULTIPLIER,
|
|
38
|
+
modelRateLookup,
|
|
39
|
+
priceUsage,
|
|
40
|
+
} from "./_cost.mjs";
|
|
41
|
+
import { readJsonl } from "./_jsonl.mjs";
|
|
42
|
+
|
|
43
|
+
export const ADVISE_THRESHOLDS = {
|
|
44
|
+
cacheRatioBelow: 0.8,
|
|
45
|
+
cacheVolumeTokens: 1_000_000,
|
|
46
|
+
ttlMinUsd: 0.5,
|
|
47
|
+
fiveMinutesMs: 5 * 60_000,
|
|
48
|
+
oneHourMs: 60 * 60_000,
|
|
49
|
+
downshiftMinUsd: 1,
|
|
50
|
+
bloatTurns: 20,
|
|
51
|
+
bloatAvgTokens: 150_000,
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const DOWN = { fable: "opus", opus: "sonnet" };
|
|
55
|
+
const SYNTHETIC = "<synthetic>";
|
|
56
|
+
|
|
57
|
+
const tokens = (v) => {
|
|
58
|
+
const n = Number(v);
|
|
59
|
+
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
60
|
+
};
|
|
61
|
+
const round = (n, places = 4) => Number(n.toFixed(places));
|
|
62
|
+
|
|
63
|
+
function listDir(dir) {
|
|
64
|
+
try {
|
|
65
|
+
return readdirSync(dir, { withFileTypes: true });
|
|
66
|
+
} catch {
|
|
67
|
+
return [];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Main and sub-agent transcripts under the projects root, newer than `sinceMs`. */
|
|
72
|
+
function transcriptFiles(root, sinceMs) {
|
|
73
|
+
const out = [];
|
|
74
|
+
const take = (path, session, sidechain) => {
|
|
75
|
+
try {
|
|
76
|
+
if (sinceMs && statSync(path).mtimeMs < sinceMs) return;
|
|
77
|
+
} catch {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
out.push({ path, session, sidechain });
|
|
81
|
+
};
|
|
82
|
+
for (const slug of listDir(root)) {
|
|
83
|
+
if (!slug.isDirectory()) continue;
|
|
84
|
+
const dir = join(root, slug.name);
|
|
85
|
+
for (const f of listDir(dir)) {
|
|
86
|
+
if (f.isFile() && f.name.endsWith(".jsonl")) {
|
|
87
|
+
take(join(dir, f.name), `${slug.name}/${f.name.slice(0, -6)}`, false);
|
|
88
|
+
} else if (f.isDirectory()) {
|
|
89
|
+
const sub = join(dir, f.name, "subagents");
|
|
90
|
+
for (const s of listDir(sub)) {
|
|
91
|
+
if (s.isFile() && s.name.endsWith(".jsonl"))
|
|
92
|
+
take(join(sub, s.name), `${slug.name}/${f.name}`, true);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return out.sort((a, b) => (a.path < b.path ? -1 : 1));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* One row per assistant message with usage, across main and sub-agent
|
|
102
|
+
* transcripts. A message id counts once; a record flagged `isSidechain`, or
|
|
103
|
+
* read from a `subagents/` file, is a sub-agent turn.
|
|
104
|
+
*
|
|
105
|
+
* @param {string} root `~/.claude/projects`
|
|
106
|
+
* @param {{sinceMs?: number}} [opts]
|
|
107
|
+
*/
|
|
108
|
+
export async function collectRows(root, { sinceMs = 0 } = {}) {
|
|
109
|
+
const files = existsSync(root) ? transcriptFiles(root, sinceMs) : [];
|
|
110
|
+
const seen = new Set();
|
|
111
|
+
const records = [];
|
|
112
|
+
for (const f of files) {
|
|
113
|
+
for await (const { record: d } of readJsonl(f.path, {
|
|
114
|
+
maxBytes: Infinity,
|
|
115
|
+
maxLineBytes: Infinity,
|
|
116
|
+
})) {
|
|
117
|
+
const msg = d?.message;
|
|
118
|
+
const u = msg?.usage;
|
|
119
|
+
if (d?.type !== "assistant" || !u || typeof u !== "object") continue;
|
|
120
|
+
if (typeof msg.model !== "string" || msg.model === SYNTHETIC) continue;
|
|
121
|
+
const ts = Date.parse(d.timestamp || "");
|
|
122
|
+
if (!Number.isFinite(ts) || (sinceMs && ts < sinceMs)) continue;
|
|
123
|
+
if (typeof msg.id === "string") {
|
|
124
|
+
if (seen.has(msg.id)) continue;
|
|
125
|
+
seen.add(msg.id);
|
|
126
|
+
}
|
|
127
|
+
const split =
|
|
128
|
+
u.cache_creation && typeof u.cache_creation === "object" ? u.cache_creation : {};
|
|
129
|
+
const write1h = tokens(split.ephemeral_1h_input_tokens);
|
|
130
|
+
const writes = Math.max(
|
|
131
|
+
tokens(u.cache_creation_input_tokens),
|
|
132
|
+
write1h + tokens(split.ephemeral_5m_input_tokens),
|
|
133
|
+
);
|
|
134
|
+
records.push({
|
|
135
|
+
model: msg.model,
|
|
136
|
+
session: f.session,
|
|
137
|
+
ts,
|
|
138
|
+
sidechain: f.sidechain || d.isSidechain === true,
|
|
139
|
+
input: tokens(u.input_tokens),
|
|
140
|
+
output: tokens(u.output_tokens),
|
|
141
|
+
cacheRead: tokens(u.cache_read_input_tokens),
|
|
142
|
+
cacheWrite5m: writes - write1h,
|
|
143
|
+
cacheWrite1h: write1h,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return { root, files: files.length, records };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The rung each persona's frontmatter pins it to.
|
|
152
|
+
*
|
|
153
|
+
* @param {string} dir an agents directory
|
|
154
|
+
* @returns {{name: string, model: string}[]}
|
|
155
|
+
*/
|
|
156
|
+
export function personaTiers(dir) {
|
|
157
|
+
const out = [];
|
|
158
|
+
for (const f of listDir(dir)) {
|
|
159
|
+
if (!f.isFile() || !f.name.endsWith(".md")) continue;
|
|
160
|
+
let text;
|
|
161
|
+
try {
|
|
162
|
+
text = readFileSync(join(dir, f.name), "utf8");
|
|
163
|
+
} catch {
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const fm = /^---\n([\s\S]*?)\n---\n/.exec(text);
|
|
167
|
+
const model = fm && /^model:\s*([A-Za-z0-9._-]+)\s*$/m.exec(fm[1]);
|
|
168
|
+
if (model) out.push({ name: f.name.slice(0, -3), model: model[1] });
|
|
169
|
+
}
|
|
170
|
+
return out.sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const usageOf = (r) => ({
|
|
174
|
+
input_tokens: r.input,
|
|
175
|
+
output_tokens: r.output,
|
|
176
|
+
cache_read_input_tokens: r.cacheRead,
|
|
177
|
+
cache_creation_input_tokens: r.cacheWrite5m + r.cacheWrite1h,
|
|
178
|
+
cache_creation: { ephemeral_1h_input_tokens: r.cacheWrite1h },
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
function cacheRatio(rows, t) {
|
|
182
|
+
const read = rows.reduce((a, r) => a + r.cacheRead, 0);
|
|
183
|
+
const fresh = rows.reduce((a, r) => a + r.input + r.cacheWrite5m + r.cacheWrite1h, 0);
|
|
184
|
+
if (read + fresh < t.cacheVolumeTokens) return null;
|
|
185
|
+
const ratio = read / (read + fresh);
|
|
186
|
+
if (ratio >= t.cacheRatioBelow) return null;
|
|
187
|
+
return {
|
|
188
|
+
id: "cache-read-ratio",
|
|
189
|
+
title: `${Math.round(ratio * 100)}% of input tokens were cache reads`,
|
|
190
|
+
numbers: {
|
|
191
|
+
cacheReadTokens: read,
|
|
192
|
+
freshInputTokens: fresh,
|
|
193
|
+
ratio: round(ratio, 3),
|
|
194
|
+
threshold: t.cacheRatioBelow,
|
|
195
|
+
},
|
|
196
|
+
savingUsd: null,
|
|
197
|
+
action:
|
|
198
|
+
"keep the system prompt, tool list and model stable within a session; start a new session between unrelated tasks rather than switching tools mid-session",
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function ttlPayback(rows, rateOf, t) {
|
|
203
|
+
const bySession = new Map();
|
|
204
|
+
for (const r of rows) {
|
|
205
|
+
if (!bySession.has(r.session)) bySession.set(r.session, []);
|
|
206
|
+
bySession.get(r.session).push(r);
|
|
207
|
+
}
|
|
208
|
+
let write1h = 0;
|
|
209
|
+
let lateRead = 0;
|
|
210
|
+
let surcharge = 0;
|
|
211
|
+
let saved = 0;
|
|
212
|
+
for (const turns of bySession.values()) {
|
|
213
|
+
turns.sort((a, b) => a.ts - b.ts);
|
|
214
|
+
let written = false;
|
|
215
|
+
let prev = null;
|
|
216
|
+
for (const r of turns) {
|
|
217
|
+
const rate = rateOf(r.model);
|
|
218
|
+
const perToken = (rate?.inPerMtok || 0) / 1e6;
|
|
219
|
+
const readRate = (rate?.cacheReadPerMtok ?? rate?.inPerMtok ?? 0) / 1e6;
|
|
220
|
+
const gap = prev === null ? 0 : r.ts - prev;
|
|
221
|
+
if (written && rate && gap > t.fiveMinutesMs && gap <= t.oneHourMs && r.cacheRead) {
|
|
222
|
+
lateRead += r.cacheRead;
|
|
223
|
+
saved += r.cacheRead * (CACHE_WRITE_MULTIPLIER * perToken - readRate);
|
|
224
|
+
}
|
|
225
|
+
if (r.cacheWrite1h && rate) {
|
|
226
|
+
written = true;
|
|
227
|
+
write1h += r.cacheWrite1h;
|
|
228
|
+
surcharge +=
|
|
229
|
+
r.cacheWrite1h * (CACHE_WRITE_1H_MULTIPLIER - CACHE_WRITE_MULTIPLIER) * perToken;
|
|
230
|
+
}
|
|
231
|
+
prev = r.ts;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (!write1h || surcharge - saved < t.ttlMinUsd) return null;
|
|
235
|
+
return {
|
|
236
|
+
id: "ttl-1h-payback",
|
|
237
|
+
title: "1-hour cache writes cost more than the late reads they made possible",
|
|
238
|
+
numbers: {
|
|
239
|
+
write1hTokens: write1h,
|
|
240
|
+
lateReadTokens: lateRead,
|
|
241
|
+
surchargeUsd: round(surcharge),
|
|
242
|
+
lateReadValueUsd: round(saved),
|
|
243
|
+
},
|
|
244
|
+
savingUsd: round(surcharge - saved),
|
|
245
|
+
action:
|
|
246
|
+
"use the 5-minute cache TTL for sessions whose turns follow each other within five minutes; keep the 1-hour TTL for sessions that pause between turns",
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function subagentTier(rows, rateOf, rungOf, table, personas, t) {
|
|
251
|
+
const out = [];
|
|
252
|
+
const byRung = new Map();
|
|
253
|
+
for (const r of rows) {
|
|
254
|
+
if (!r.sidechain) continue;
|
|
255
|
+
const rung = rungOf(r.model);
|
|
256
|
+
const down = DOWN[rung];
|
|
257
|
+
if (!down) continue;
|
|
258
|
+
const now = priceUsage(rateOf(r.model), usageOf(r));
|
|
259
|
+
const then = priceUsage(table.prices[down], usageOf(r));
|
|
260
|
+
if (now === null || then === null) continue;
|
|
261
|
+
const s = byRung.get(rung) || { rung, to: down, now: 0, then: 0, messages: 0 };
|
|
262
|
+
s.now += now;
|
|
263
|
+
s.then += then;
|
|
264
|
+
s.messages += 1;
|
|
265
|
+
byRung.set(rung, s);
|
|
266
|
+
}
|
|
267
|
+
for (const s of byRung.values()) {
|
|
268
|
+
if (s.now - s.then < t.downshiftMinUsd) continue;
|
|
269
|
+
const pinned = personas.filter((p) => p.model === s.rung).map((p) => p.name);
|
|
270
|
+
const action =
|
|
271
|
+
s.rung === "fable"
|
|
272
|
+
? `turn the fable rung off (/multi-agent:model off): agent-model-sync rewrites the installed personas pinned to fable (${pinned.join(", ") || "none found"}) to opus`
|
|
273
|
+
: `set model: ${s.to} in the frontmatter of the personas pinned to ${s.rung} (${pinned.join(", ") || "none found"}) where their output allows it; review quality is not measured here, so compare a few runs first`;
|
|
274
|
+
out.push({
|
|
275
|
+
id: `subagent-tier-${s.rung}`,
|
|
276
|
+
title: `sub-agents ran on ${s.rung}`,
|
|
277
|
+
numbers: {
|
|
278
|
+
messages: s.messages,
|
|
279
|
+
from: s.rung,
|
|
280
|
+
to: s.to,
|
|
281
|
+
nowUsd: round(s.now),
|
|
282
|
+
downshiftedUsd: round(s.then),
|
|
283
|
+
personas: pinned,
|
|
284
|
+
},
|
|
285
|
+
savingUsd: round(s.now - s.then),
|
|
286
|
+
action,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
return out;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function contextBloat(rows, t) {
|
|
293
|
+
const bySession = new Map();
|
|
294
|
+
for (const r of rows) {
|
|
295
|
+
if (r.sidechain) continue;
|
|
296
|
+
const s = bySession.get(r.session) || { session: r.session, turns: 0, context: 0 };
|
|
297
|
+
s.turns += 1;
|
|
298
|
+
s.context += r.input + r.cacheRead + r.cacheWrite5m + r.cacheWrite1h;
|
|
299
|
+
bySession.set(r.session, s);
|
|
300
|
+
}
|
|
301
|
+
const heavy = [...bySession.values()]
|
|
302
|
+
.filter((s) => s.turns >= t.bloatTurns && s.context / s.turns >= t.bloatAvgTokens)
|
|
303
|
+
.sort((a, b) => b.context - a.context)
|
|
304
|
+
.slice(0, 3)
|
|
305
|
+
.map((s) => ({
|
|
306
|
+
session: s.session,
|
|
307
|
+
turns: s.turns,
|
|
308
|
+
avgContextTokens: Math.round(s.context / s.turns),
|
|
309
|
+
}));
|
|
310
|
+
if (!heavy.length) return null;
|
|
311
|
+
return {
|
|
312
|
+
id: "context-bloat",
|
|
313
|
+
title: `${heavy.length} long session(s) carried a very large context on every turn`,
|
|
314
|
+
numbers: { sessions: heavy, threshold: t.bloatAvgTokens },
|
|
315
|
+
savingUsd: null,
|
|
316
|
+
action:
|
|
317
|
+
"compact at a natural break or start a new session between tasks; move standing instructions out of CLAUDE.md into skills that load on demand",
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Findings over usage rows, savings first and largest first. Pure: rows in,
|
|
323
|
+
* findings out.
|
|
324
|
+
*
|
|
325
|
+
* @param {object[]} rows collectRows().records
|
|
326
|
+
* @param {{table: object, personas?: {name: string, model: string}[], thresholds?: object, source?: object}} opts
|
|
327
|
+
*/
|
|
328
|
+
export function advise(rows, { table, personas = [], thresholds = {}, source = {} }) {
|
|
329
|
+
const t = { ...ADVISE_THRESHOLDS, ...thresholds };
|
|
330
|
+
const lookup = modelRateLookup(table);
|
|
331
|
+
const rateOf = (m) => {
|
|
332
|
+
const r = lookup(m);
|
|
333
|
+
return r && typeof r === "object" ? r : null;
|
|
334
|
+
};
|
|
335
|
+
const rungByRate = new Map(Object.entries(table.prices || {}).map(([k, v]) => [v, k]));
|
|
336
|
+
const rungOf = (m) => rungByRate.get(rateOf(m)) || null;
|
|
337
|
+
const unpriced = [...new Set(rows.filter((r) => !rateOf(r.model)).map((r) => r.model))].sort();
|
|
338
|
+
const priced = rows.filter((r) => rateOf(r.model));
|
|
339
|
+
const findings = [
|
|
340
|
+
cacheRatio(priced, t),
|
|
341
|
+
ttlPayback(priced, rateOf, t),
|
|
342
|
+
...subagentTier(priced, rateOf, rungOf, table, personas, t),
|
|
343
|
+
contextBloat(rows, t),
|
|
344
|
+
unpriced.length
|
|
345
|
+
? {
|
|
346
|
+
id: "unpriced",
|
|
347
|
+
title: `${unpriced.length} model(s) have no price, so their spend is outside every figure`,
|
|
348
|
+
numbers: { models: unpriced },
|
|
349
|
+
savingUsd: null,
|
|
350
|
+
action:
|
|
351
|
+
"add the model ids to cost-table.json (models or legacy) so totals and savings include them",
|
|
352
|
+
}
|
|
353
|
+
: null,
|
|
354
|
+
].filter(Boolean);
|
|
355
|
+
for (const f of findings) f.source = source;
|
|
356
|
+
return findings.sort((a, b) => (b.savingUsd ?? -1) - (a.savingUsd ?? -1));
|
|
357
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file _cost-budget.mjs - a run's estimated spend against
|
|
3
|
+
* prefs.global.costBudget, shared by the phase-end check
|
|
4
|
+
* (cost-budget-check.mjs) and the subagent spawn gate (run-scope-guard.mjs).
|
|
5
|
+
*
|
|
6
|
+
* The ladder has three steps: `ok` under warnPct of maxUsd, `warn` from there
|
|
7
|
+
* to the ceiling, `exceeded` above it. What each step does is the caller's:
|
|
8
|
+
* the phase-end check prints and exits 10 or 11, the spawn gate adds a note at
|
|
9
|
+
* `warn` and asks (or, with onExceed halt, refuses) at `exceeded`.
|
|
10
|
+
*
|
|
11
|
+
* @module pipeline/scripts/_cost-budget
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readFileSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
|
|
17
|
+
import { costUsd } from "./_cost.mjs";
|
|
18
|
+
|
|
19
|
+
const DEFAULTS = Object.freeze({
|
|
20
|
+
enabled: false,
|
|
21
|
+
maxUsd: 5,
|
|
22
|
+
warnPct: 80,
|
|
23
|
+
onExceed: "warn",
|
|
24
|
+
pricingModel: "fable",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The budget settings with defaults filled in. Off unless `enabled` is true,
|
|
29
|
+
* and off when maxUsd or warnPct is out of range, since a ladder built on
|
|
30
|
+
* them would mean nothing.
|
|
31
|
+
*
|
|
32
|
+
* @param {object|undefined|null} raw prefs.global.costBudget
|
|
33
|
+
*/
|
|
34
|
+
export function budgetConfig(raw) {
|
|
35
|
+
const cfg = { ...DEFAULTS, ...(raw && typeof raw === "object" ? raw : {}) };
|
|
36
|
+
cfg.enabled = cfg.enabled === true;
|
|
37
|
+
cfg.maxUsd = Number(cfg.maxUsd);
|
|
38
|
+
cfg.warnPct = Number(cfg.warnPct);
|
|
39
|
+
if (!(cfg.maxUsd > 0) || !(cfg.warnPct >= 1 && cfg.warnPct <= 99)) cfg.enabled = false;
|
|
40
|
+
if (cfg.onExceed !== "halt") cfg.onExceed = "warn";
|
|
41
|
+
return cfg;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The unit prices for a rung from cost-table.json, or null. */
|
|
45
|
+
export function rateFor(model) {
|
|
46
|
+
const table = JSON.parse(readFileSync(join(import.meta.dirname, "cost-table.json"), "utf8"));
|
|
47
|
+
return table.prices?.[model] ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The tracker's token totals across phases, priced at `rate`.
|
|
52
|
+
*
|
|
53
|
+
* @param {object} tracker tracker-state.json
|
|
54
|
+
* @param {object} rate a cost-table.json price row
|
|
55
|
+
*/
|
|
56
|
+
export function trackerSpend(tracker, rate) {
|
|
57
|
+
let tokensIn = 0;
|
|
58
|
+
let tokensOut = 0;
|
|
59
|
+
let tokensCached = 0;
|
|
60
|
+
for (const p of Object.values(tracker?.phases || {})) {
|
|
61
|
+
tokensIn += Number(p?.tokens_in || 0);
|
|
62
|
+
tokensOut += Number(p?.tokens_out || 0);
|
|
63
|
+
tokensCached += Number(p?.tokens_cached || 0);
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
usd: costUsd(rate, tokensIn, tokensOut, tokensCached) ?? 0,
|
|
67
|
+
tokensIn,
|
|
68
|
+
tokensOut,
|
|
69
|
+
tokensCached,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `ok`, `warn` or `exceeded` for a spend under `cfg`. */
|
|
74
|
+
export function budgetLevel(usd, cfg) {
|
|
75
|
+
if (usd > cfg.maxUsd) return "exceeded";
|
|
76
|
+
if ((usd / cfg.maxUsd) * 100 >= cfg.warnPct) return "warn";
|
|
77
|
+
return "ok";
|
|
78
|
+
}
|
|
@@ -35,6 +35,35 @@ export function costUsd(rate, tokensIn = 0, tokensOut = 0, tokensCached = 0) {
|
|
|
35
35
|
);
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* USD for one run from the per-phase token counts its tracker-state.json
|
|
40
|
+
* recorded (`phases` as a list or a map). A phase whose model the price table
|
|
41
|
+
* does not name is priced at `fallbackRung`: an over-estimate stops a spend
|
|
42
|
+
* ceiling early, an under-estimate stops it late. Null, never 0, when no phase
|
|
43
|
+
* recorded a token or there is no price table, so "cost nothing" and "cost is
|
|
44
|
+
* not known" stay apart.
|
|
45
|
+
*
|
|
46
|
+
* @param {{phases?: object[]|Record<string, object>}|null} tracker
|
|
47
|
+
* @param {Record<string, object>|null} prices cost-table.json `prices`
|
|
48
|
+
* @param {string} [fallbackRung]
|
|
49
|
+
* @returns {number|null}
|
|
50
|
+
*/
|
|
51
|
+
export function trackerUsd(tracker, prices, fallbackRung = "fable") {
|
|
52
|
+
if (!tracker || !prices) return null;
|
|
53
|
+
let usd = 0;
|
|
54
|
+
let tokens = 0;
|
|
55
|
+
for (const ph of Object.values(tracker.phases || {})) {
|
|
56
|
+
const tin = Number(ph?.tokens_in || 0);
|
|
57
|
+
const tout = Number(ph?.tokens_out || 0);
|
|
58
|
+
const tcached = Number(ph?.tokens_cached || 0);
|
|
59
|
+
if (!(tin + tout + tcached > 0)) continue;
|
|
60
|
+
tokens += tin + tout + tcached;
|
|
61
|
+
const rate = Object.hasOwn(prices, ph?.model) ? prices[ph.model] : prices[fallbackRung];
|
|
62
|
+
usd += costUsd(rate, tin, tout, tcached) ?? 0;
|
|
63
|
+
}
|
|
64
|
+
return tokens > 0 ? Math.round(usd * 10000) / 10000 : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
38
67
|
/**
|
|
39
68
|
* Spend across autopilot attempt-ledger rows (attempted.jsonl).
|
|
40
69
|
*
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Bounded decode of base64, hex and rot13 text, the Python twin of
|
|
2
|
+
decodedVariants in pipeline/lib/normalize-text.mjs.
|
|
3
|
+
|
|
4
|
+
Both sides take the same limits, find the same runs, decode with the same
|
|
5
|
+
hand-written decoders and return the same copies in the same order;
|
|
6
|
+
test/normalize-decode.test.mjs holds them to that on one set of samples.
|
|
7
|
+
The guard runs its credential-read rule over these copies, so a command that
|
|
8
|
+
hides `security find-generic-password -w` inside base64 is read as what it
|
|
9
|
+
decodes to. Stdlib only.
|
|
10
|
+
"""
|
|
11
|
+
import re
|
|
12
|
+
import string
|
|
13
|
+
|
|
14
|
+
DECODE_LIMITS = {
|
|
15
|
+
"maxDepth": 2,
|
|
16
|
+
"maxInputChars": 256 * 1024,
|
|
17
|
+
"maxVariants": 32,
|
|
18
|
+
"maxDecodedChars": 256 * 1024,
|
|
19
|
+
"minBytes": 8,
|
|
20
|
+
"minPrintable": 0.9,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
B64_RUN = re.compile(r"[A-Za-z0-9+/_-]{16,}={0,2}")
|
|
24
|
+
HEX_RUN = re.compile(r"(?:[0-9a-fA-F]{2}){8,}")
|
|
25
|
+
_ALPHA = string.ascii_uppercase + string.ascii_lowercase + string.digits
|
|
26
|
+
_B64_VALUE = {c: i for i, c in enumerate(_ALPHA)}
|
|
27
|
+
_B64_VALUE.update({"+": 62, "-": 62, "/": 63, "_": 63})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def decode_base64(run):
|
|
31
|
+
"""Standard or URL-safe base64, padding optional, as one char per byte."""
|
|
32
|
+
out, acc, bits = [], 0, 0
|
|
33
|
+
for ch in run.rstrip("="):
|
|
34
|
+
v = _B64_VALUE.get(ch)
|
|
35
|
+
if v is None:
|
|
36
|
+
return None
|
|
37
|
+
acc = ((acc << 6) | v) & 0xFFFFFF
|
|
38
|
+
bits += 6
|
|
39
|
+
if bits >= 8:
|
|
40
|
+
bits -= 8
|
|
41
|
+
out.append(chr((acc >> bits) & 0xFF))
|
|
42
|
+
return "".join(out)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def decode_hex(run):
|
|
46
|
+
return "".join(chr(int(run[i:i + 2], 16)) for i in range(0, len(run) - 1, 2))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def rot13(text):
|
|
50
|
+
out = []
|
|
51
|
+
for ch in text:
|
|
52
|
+
c = ord(ch)
|
|
53
|
+
if 65 <= c <= 90:
|
|
54
|
+
out.append(chr((c - 65 + 13) % 26 + 65))
|
|
55
|
+
elif 97 <= c <= 122:
|
|
56
|
+
out.append(chr((c - 97 + 13) % 26 + 97))
|
|
57
|
+
else:
|
|
58
|
+
out.append(ch)
|
|
59
|
+
return "".join(out)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _printable(data, min_bytes, min_printable):
|
|
63
|
+
if len(data) < min_bytes:
|
|
64
|
+
return False
|
|
65
|
+
ok = sum(1 for ch in data if 0x20 <= ord(ch) <= 0x7E or ch in "\t\n\r")
|
|
66
|
+
return ok / len(data) >= min_printable
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def decoded_variants(text, limits=None):
|
|
70
|
+
"""[{"kind", "text"}] decoded copies of the runs inside text; see
|
|
71
|
+
decodedVariants in normalize-text.mjs for the order and the limits."""
|
|
72
|
+
lim = dict(DECODE_LIMITS)
|
|
73
|
+
lim.update(limits or {})
|
|
74
|
+
out, seen = [], set()
|
|
75
|
+
budget = [lim["maxDecodedChars"]]
|
|
76
|
+
|
|
77
|
+
def keep(kind, decoded, nxt):
|
|
78
|
+
if len(out) >= lim["maxVariants"] or len(decoded) > budget[0] or decoded in seen:
|
|
79
|
+
return
|
|
80
|
+
seen.add(decoded)
|
|
81
|
+
budget[0] -= len(decoded)
|
|
82
|
+
out.append({"kind": kind, "text": decoded})
|
|
83
|
+
nxt.append({"kind": kind, "text": decoded})
|
|
84
|
+
|
|
85
|
+
frontier = [{"kind": "", "text": str(text or "")[: lim["maxInputChars"]]}]
|
|
86
|
+
depth = 1
|
|
87
|
+
while depth <= lim["maxDepth"] and frontier:
|
|
88
|
+
nxt = []
|
|
89
|
+
for item in frontier:
|
|
90
|
+
prefix = item["kind"] + ">" if item["kind"] else ""
|
|
91
|
+
for kind, pattern, decode, ratio in (
|
|
92
|
+
("base64", B64_RUN, decode_base64, 0.75),
|
|
93
|
+
("hex", HEX_RUN, decode_hex, 0.5),
|
|
94
|
+
):
|
|
95
|
+
for m in pattern.finditer(item["text"]):
|
|
96
|
+
if len(out) >= lim["maxVariants"]:
|
|
97
|
+
break
|
|
98
|
+
if len(m.group(0)) * ratio > budget[0]:
|
|
99
|
+
continue
|
|
100
|
+
data = decode(m.group(0))
|
|
101
|
+
if data is not None and _printable(data, lim["minBytes"], lim["minPrintable"]):
|
|
102
|
+
keep(prefix + kind, data, nxt)
|
|
103
|
+
if depth == 1 and re.search(r"[A-Za-z]", item["text"]):
|
|
104
|
+
keep("rot13", rot13(item["text"]), [])
|
|
105
|
+
frontier = nxt
|
|
106
|
+
depth += 1
|
|
107
|
+
return out
|