@blackbelt-technology/pi-dashboard-context-budget 0.8.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/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # @blackbelt-technology/pi-dashboard-context-budget
2
+
3
+ Measure what a pi session actually sends the model, every turn, before any work happens.
4
+
5
+ The meter attaches to `before_provider_request`, which fires after the provider payload
6
+ is built and before it is sent — so the numbers are the real request, not a reconstruction
7
+ of one. `ctx.getSystemPrompt()` reports pi's system prompt string, which is not the same
8
+ thing as the serialized payload.
9
+
10
+ ## Why
11
+
12
+ A context trim can apply cleanly, produce a valid config, and change nothing on the wire.
13
+ That happened during this package's own development: a `"skills": ["-…"]` exclusion in
14
+ project settings was accepted, looked correct, and was a silent no-op (package-provided
15
+ skills must be excluded in the *package entry*). Only a before/after measurement caught it.
16
+
17
+ `diff --expect-removed` encodes that lesson: it exits non-zero when something you expected
18
+ to remove is still on the wire.
19
+
20
+ ## Usage
21
+
22
+ ```bash
23
+ # measure the current directory's session cost
24
+ npx context-budget measure -o before.json
25
+
26
+ # ...change settings / skills / tools...
27
+ npx context-budget measure -o after.json
28
+
29
+ # prove the change reached the wire
30
+ npx context-budget diff before.json after.json --expect-removed ctx-doctor,memory_remove
31
+ ```
32
+
33
+ `measure` runs one headless pi turn (`pi -e <meter> -p "reply with the single word: ok"`)
34
+ in the current working directory, so it reflects that project's settings, skills and
35
+ extensions.
36
+
37
+ To measure the effect of dropping tools without editing any config:
38
+
39
+ ```bash
40
+ CONTEXT_BUDGET_DROP=memory_remove,recall npx context-budget measure -o trimmed.json
41
+ ```
42
+
43
+ ## What it reports
44
+
45
+ - **payload** total, split into `system` / `tools` / `messages`
46
+ - **system-prompt blocks** — `skills-catalogue`, `project-context`, `memory-policy`, and
47
+ `other`. The parts always sum to the whole: a block that stops matching shows up as
48
+ `other` growing rather than as bytes disappearing.
49
+ - **per-tool schema bytes**, sorted — the cost of each registered tool
50
+ - **per-skill catalogue bytes** — what each advertised skill costs every turn
51
+
52
+ ## Library
53
+
54
+ ```ts
55
+ import { analyzePayload, comparePayloads, checkBudget } from "@blackbelt-technology/pi-dashboard-context-budget";
56
+
57
+ const b = analyzePayload(capturedPayload);
58
+ const { ok, violations } = checkBudget(b, { maxPayloadBytes: 120_000 });
59
+ ```
60
+
61
+ `analyzePayload` is pure — no pi, no network, no filesystem — so budget assertions can run
62
+ in CI against a stored capture.
63
+
64
+ ## Env
65
+
66
+ | Variable | Meaning |
67
+ |---|---|
68
+ | `CONTEXT_BUDGET_OUT` | where the meter writes its capture (default `./context-budget.json`) |
69
+ | `CONTEXT_BUDGET_DROP` | comma-separated tool names to deactivate via `setActiveTools` before measuring |
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * context-budget — measure the per-turn context cost of a pi session.
4
+ *
5
+ * context-budget measure [-o file] [--drop a,b] run pi headless, capture, report
6
+ * context-budget report <file> re-print a capture
7
+ * context-budget diff <before> <after> [--expect-removed a,b]
8
+ *
9
+ * `measure` spawns a real headless pi turn with the meter extension attached,
10
+ * so the numbers come from an actual provider request rather than a model of one.
11
+ */
12
+
13
+ import { spawnSync } from "node:child_process";
14
+ import { existsSync, readFileSync } from "node:fs";
15
+ import { dirname, resolve } from "node:path";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+
18
+ const here = dirname(fileURLToPath(import.meta.url));
19
+ const meter = resolve(here, "../src/meter.ts");
20
+
21
+ const argv = process.argv.slice(2);
22
+ const cmd = argv[0] ?? "measure";
23
+
24
+ function flag(name, fallback) {
25
+ const i = argv.indexOf(name);
26
+ return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;
27
+ }
28
+
29
+ const load = (f) => {
30
+ if (!existsSync(f)) {
31
+ console.error(`no such capture: ${f}`);
32
+ process.exit(2);
33
+ }
34
+ const parsed = JSON.parse(readFileSync(f, "utf8"));
35
+ return parsed.breakdown ?? parsed;
36
+ };
37
+
38
+ // Prefer the built output; fall back to source for tsx/pi-loaded contexts.
39
+ // `dist/` is gitignored and only produced by `prepublishOnly`, so both specifiers
40
+ // are computed at runtime — a literal "../dist/index.js" would read as a dangling
41
+ // relative import to the publish-correctness checker, which packs an unbuilt tree.
42
+ const distEntry = pathToFileURL(resolve(here, "../dist/index.js")).href;
43
+ const srcEntry = pathToFileURL(resolve(here, "../src/index.ts")).href;
44
+ const lib = await import(distEntry).catch(async () => {
45
+ try {
46
+ return await import(srcEntry);
47
+ } catch {
48
+ console.error("context-budget: no build found — run `npm run build --workspace=@blackbelt-technology/pi-dashboard-context-budget`");
49
+ process.exit(1);
50
+ }
51
+ });
52
+
53
+ if (cmd === "measure") {
54
+ const out = resolve(flag("-o", flag("--out", "./context-budget.json")));
55
+ const drop = flag("--drop", "");
56
+ // stderr is PIPED, never inherited: pi's dashboard bridge keeps an inherited
57
+ // stderr open after the turn ends, which hangs the CLI forever. The timeout is
58
+ // a second belt — the capture is written the moment the request is built, so a
59
+ // late-exiting pi must not block the report.
60
+ const res = spawnSync("pi", ["-e", meter, "-p", "reply with the single word: ok"], {
61
+ stdio: ["ignore", "ignore", "pipe"],
62
+ timeout: Number(process.env.CONTEXT_BUDGET_TIMEOUT_MS ?? 180_000),
63
+ env: { ...process.env, CONTEXT_BUDGET_OUT: out, CONTEXT_BUDGET_DROP: drop },
64
+ });
65
+ if (res.error && !existsSync(out)) {
66
+ console.error(`failed to run pi: ${res.error.message}`);
67
+ if (res.stderr?.length) console.error(String(res.stderr).slice(-2000));
68
+ process.exit(1);
69
+ }
70
+ if (!existsSync(out)) {
71
+ console.error("pi ran but no payload was captured — did the request reach the provider?");
72
+ if (res.stderr?.length) console.error(String(res.stderr).slice(-2000));
73
+ process.exit(1);
74
+ }
75
+ console.log(lib.formatReport(load(out)));
76
+ console.log(`\ncapture: ${out}`);
77
+ } else if (cmd === "report") {
78
+ console.log(lib.formatReport(load(resolve(argv[1]))));
79
+ } else if (cmd === "diff") {
80
+ const expect = flag("--expect-removed", "")
81
+ .split(",")
82
+ .map((s) => s.trim())
83
+ .filter(Boolean);
84
+ const delta = lib.comparePayloads(load(resolve(argv[1])), load(resolve(argv[2])), { expectRemoved: expect });
85
+ console.log(lib.formatDelta(delta));
86
+ if (delta.unmetExpectations.length) process.exit(1);
87
+ } else {
88
+ console.error(`unknown command: ${cmd}`);
89
+ process.exit(2);
90
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Pure analysis of a provider request payload.
3
+ *
4
+ * Everything here operates on a captured payload object — no pi, no network,
5
+ * no filesystem — so the accounting is unit-testable and the numbers are
6
+ * reproducible. Capture happens in meter.ts via `before_provider_request`.
7
+ */
8
+ export interface ToolCost {
9
+ name: string;
10
+ bytes: number;
11
+ }
12
+ export interface SystemBlock {
13
+ label: string;
14
+ bytes: number;
15
+ }
16
+ export interface SkillCost {
17
+ name: string;
18
+ bytes: number;
19
+ }
20
+ export interface Breakdown {
21
+ model: string;
22
+ payloadBytes: number;
23
+ systemBytes: number;
24
+ messagesBytes: number;
25
+ toolsBytes: number;
26
+ toolCount: number;
27
+ perTool: ToolCost[];
28
+ systemBlocks: SystemBlock[];
29
+ skills: SkillCost[];
30
+ }
31
+ export interface BudgetLimits {
32
+ maxPayloadBytes?: number;
33
+ maxToolsBytes?: number;
34
+ maxSkillsBytes?: number;
35
+ }
36
+ export interface BudgetViolation {
37
+ limit: keyof BudgetLimits;
38
+ actual: number;
39
+ allowed: number;
40
+ }
41
+ export interface Delta {
42
+ payloadBytesDelta: number;
43
+ systemBytesDelta: number;
44
+ toolsBytesDelta: number;
45
+ toolsAdded: string[];
46
+ toolsRemoved: string[];
47
+ skillsAdded: string[];
48
+ skillsRemoved: string[];
49
+ /** Names that were expected to disappear but are still on the wire. */
50
+ unmetExpectations: string[];
51
+ }
52
+ export declare function analyzePayload(payload: unknown): Breakdown;
53
+ export declare function comparePayloads(before: Breakdown, after: Breakdown, opts?: {
54
+ expectRemoved?: string[];
55
+ }): Delta;
56
+ export declare function checkBudget(b: Breakdown, limits: BudgetLimits): {
57
+ ok: boolean;
58
+ violations: BudgetViolation[];
59
+ };
60
+ export declare function formatReport(b: Breakdown, top?: number): string;
61
+ export declare function formatDelta(d: Delta): string;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Pure analysis of a provider request payload.
3
+ *
4
+ * Everything here operates on a captured payload object — no pi, no network,
5
+ * no filesystem — so the accounting is unit-testable and the numbers are
6
+ * reproducible. Capture happens in meter.ts via `before_provider_request`.
7
+ */
8
+ const bytes = (v) => (v === undefined ? 0 : Buffer.byteLength(JSON.stringify(v)));
9
+ const textBytes = (s) => Buffer.byteLength(s);
10
+ /** Provider payloads carry `system` as a string or as an array of text blocks. */
11
+ function systemText(system) {
12
+ if (typeof system === "string")
13
+ return system;
14
+ if (Array.isArray(system)) {
15
+ return system.map((b) => (b && typeof b === "object" && "text" in b ? String(b.text) : "")).join("\n");
16
+ }
17
+ return "";
18
+ }
19
+ function sliceBetween(haystack, open, close) {
20
+ const i = haystack.indexOf(open);
21
+ if (i < 0)
22
+ return undefined;
23
+ const j = haystack.indexOf(close, i);
24
+ if (j < 0)
25
+ return undefined;
26
+ return haystack.slice(i, j + close.length);
27
+ }
28
+ function parseSkills(system) {
29
+ const block = sliceBetween(system, "<available_skills>", "</available_skills>");
30
+ if (!block)
31
+ return [];
32
+ const entries = [...block.matchAll(/<name>([^<]+)<\/name>\s*<description>([\s\S]*?)<\/description>/g)];
33
+ return entries
34
+ .map((m) => ({ name: m[1].trim(), bytes: textBytes(m[0]) }))
35
+ .sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));
36
+ }
37
+ /**
38
+ * Attribute the system prompt to known blocks. `other` absorbs the remainder so
39
+ * the parts always sum to the whole — a block that silently stops matching shows
40
+ * up as `other` growing, rather than as bytes vanishing from the report.
41
+ */
42
+ function systemBlocks(system) {
43
+ const named = [];
44
+ const known = [
45
+ ["skills-catalogue", "<available_skills>", "</available_skills>"],
46
+ ["project-context", "<project_context>", "</project_context>"],
47
+ ["memory-policy", "<memory-policy>", "</memory-policy>"],
48
+ ];
49
+ for (const [label, open, close] of known) {
50
+ const found = sliceBetween(system, open, close);
51
+ if (found)
52
+ named.push({ label, bytes: textBytes(found) });
53
+ }
54
+ const accounted = named.reduce((sum, b) => sum + b.bytes, 0);
55
+ named.push({ label: "other", bytes: Math.max(0, textBytes(system) - accounted) });
56
+ return named;
57
+ }
58
+ export function analyzePayload(payload) {
59
+ const p = (payload ?? {});
60
+ const tools = Array.isArray(p.tools) ? p.tools : [];
61
+ const system = systemText(p.system);
62
+ const perTool = tools
63
+ .map((t) => {
64
+ const fn = t.function;
65
+ const name = String(t.name ?? fn?.name ?? "?");
66
+ return { name, bytes: bytes(t) };
67
+ })
68
+ .sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));
69
+ return {
70
+ model: String(p.model ?? "?"),
71
+ payloadBytes: bytes(p),
72
+ systemBytes: textBytes(system),
73
+ messagesBytes: bytes(p.messages),
74
+ toolsBytes: bytes(p.tools),
75
+ toolCount: tools.length,
76
+ perTool,
77
+ systemBlocks: systemBlocks(system),
78
+ skills: parseSkills(system),
79
+ };
80
+ }
81
+ export function comparePayloads(before, after, opts = {}) {
82
+ const beforeTools = before.perTool.map((t) => t.name);
83
+ const afterTools = after.perTool.map((t) => t.name);
84
+ const beforeSkills = before.skills.map((s) => s.name);
85
+ const afterSkills = after.skills.map((s) => s.name);
86
+ const stillPresent = new Set([...afterTools, ...afterSkills]);
87
+ return {
88
+ payloadBytesDelta: after.payloadBytes - before.payloadBytes,
89
+ systemBytesDelta: after.systemBytes - before.systemBytes,
90
+ toolsBytesDelta: after.toolsBytes - before.toolsBytes,
91
+ toolsAdded: afterTools.filter((n) => !beforeTools.includes(n)),
92
+ toolsRemoved: beforeTools.filter((n) => !afterTools.includes(n)),
93
+ skillsAdded: afterSkills.filter((n) => !beforeSkills.includes(n)),
94
+ skillsRemoved: beforeSkills.filter((n) => !afterSkills.includes(n)),
95
+ unmetExpectations: (opts.expectRemoved ?? []).filter((n) => stillPresent.has(n)),
96
+ };
97
+ }
98
+ export function checkBudget(b, limits) {
99
+ const skillsBytes = b.skills.reduce((sum, s) => sum + s.bytes, 0);
100
+ const checks = [
101
+ ["maxPayloadBytes", b.payloadBytes],
102
+ ["maxToolsBytes", b.toolsBytes],
103
+ ["maxSkillsBytes", skillsBytes],
104
+ ];
105
+ const violations = [];
106
+ for (const [limit, actual] of checks) {
107
+ const allowed = limits[limit];
108
+ if (allowed !== undefined && actual > allowed)
109
+ violations.push({ limit, actual, allowed });
110
+ }
111
+ return { ok: violations.length === 0, violations };
112
+ }
113
+ const kb = (n) => `${(n / 1024).toFixed(1)}KB`;
114
+ export function formatReport(b, top = 12) {
115
+ const skillsBytes = b.skills.reduce((sum, s) => sum + s.bytes, 0);
116
+ const lines = [
117
+ `model ${b.model}`,
118
+ `payload ${kb(b.payloadBytes)} (~${Math.round(b.payloadBytes / 3.8)} tokens)`,
119
+ ` system ${kb(b.systemBytes)}`,
120
+ ...b.systemBlocks.map((x) => ` ${x.label.padEnd(16)} ${kb(x.bytes)}`),
121
+ ` tools ${kb(b.toolsBytes)} (${b.toolCount} tools)`,
122
+ ` messages ${kb(b.messagesBytes)}`,
123
+ "",
124
+ `skills advertised: ${b.skills.length} (${kb(skillsBytes)})`,
125
+ "",
126
+ `top ${top} tool schemas:`,
127
+ ...b.perTool.slice(0, top).map((t) => ` ${String(t.bytes).padStart(6)} ${t.name}`),
128
+ "",
129
+ `top ${top} skill entries:`,
130
+ ...b.skills.slice(0, top).map((s) => ` ${String(s.bytes).padStart(6)} ${s.name}`),
131
+ ];
132
+ return lines.join("\n");
133
+ }
134
+ export function formatDelta(d) {
135
+ const sign = (n) => (n > 0 ? `+${n}` : String(n));
136
+ const lines = [
137
+ `payload ${sign(d.payloadBytesDelta)} B`,
138
+ `system ${sign(d.systemBytesDelta)} B`,
139
+ `tools ${sign(d.toolsBytesDelta)} B`,
140
+ ];
141
+ if (d.toolsRemoved.length)
142
+ lines.push(`tools removed: ${d.toolsRemoved.join(", ")}`);
143
+ if (d.toolsAdded.length)
144
+ lines.push(`tools added: ${d.toolsAdded.join(", ")}`);
145
+ if (d.skillsRemoved.length)
146
+ lines.push(`skills removed (${d.skillsRemoved.length}): ${d.skillsRemoved.join(", ")}`);
147
+ if (d.skillsAdded.length)
148
+ lines.push(`skills added (${d.skillsAdded.length}): ${d.skillsAdded.join(", ")}`);
149
+ if (d.unmetExpectations.length) {
150
+ lines.push(`UNMET EXPECTATIONS — still on the wire: ${d.unmetExpectations.join(", ")}`);
151
+ }
152
+ return lines.join("\n");
153
+ }
@@ -0,0 +1 @@
1
+ export { analyzePayload, type Breakdown, type BudgetLimits, type BudgetViolation, checkBudget, comparePayloads, type Delta, formatDelta, formatReport, type SkillCost, type SystemBlock, type ToolCost, } from "./analyze.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { analyzePayload, checkBudget, comparePayloads, formatDelta, formatReport, } from "./analyze.js";
@@ -0,0 +1,19 @@
1
+ /**
2
+ * pi extension: capture the real outgoing provider payload once per session.
3
+ *
4
+ * `before_provider_request` fires after the provider payload is built and
5
+ * before it is sent, so what we record is exactly what the model receives —
6
+ * not a reconstruction. Returning undefined leaves the payload untouched; this
7
+ * extension only observes.
8
+ *
9
+ * Env:
10
+ * CONTEXT_BUDGET_OUT where to write the capture (default: ./context-budget.json)
11
+ * CONTEXT_BUDGET_DROP comma-separated tool names to deactivate before measuring
12
+ */
13
+ interface MeterApi {
14
+ on(event: string, handler: (event: unknown, ctx: unknown) => void): void;
15
+ getActiveTools?(): string[];
16
+ setActiveTools?(names: string[]): void;
17
+ }
18
+ export default function (pi: MeterApi): void;
19
+ export {};
package/dist/meter.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * pi extension: capture the real outgoing provider payload once per session.
3
+ *
4
+ * `before_provider_request` fires after the provider payload is built and
5
+ * before it is sent, so what we record is exactly what the model receives —
6
+ * not a reconstruction. Returning undefined leaves the payload untouched; this
7
+ * extension only observes.
8
+ *
9
+ * Env:
10
+ * CONTEXT_BUDGET_OUT where to write the capture (default: ./context-budget.json)
11
+ * CONTEXT_BUDGET_DROP comma-separated tool names to deactivate before measuring
12
+ */
13
+ import { writeFileSync } from "node:fs";
14
+ import { analyzePayload } from "./analyze.js";
15
+ export default function (pi) {
16
+ const out = process.env.CONTEXT_BUDGET_OUT ?? "./context-budget.json";
17
+ const drop = (process.env.CONTEXT_BUDGET_DROP ?? "")
18
+ .split(",")
19
+ .map((s) => s.trim())
20
+ .filter(Boolean);
21
+ let captured = false;
22
+ pi.on("session_start", () => {
23
+ if (drop.length === 0)
24
+ return;
25
+ const active = pi.getActiveTools?.() ?? [];
26
+ pi.setActiveTools?.(active.filter((n) => !drop.includes(n)));
27
+ });
28
+ pi.on("before_provider_request", (event) => {
29
+ if (captured)
30
+ return;
31
+ captured = true;
32
+ const payload = event?.payload;
33
+ const breakdown = analyzePayload(payload);
34
+ writeFileSync(out, `${JSON.stringify({ capturedAt: new Date().toISOString(), dropped: drop, breakdown }, null, 2)}\n`);
35
+ });
36
+ }
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@blackbelt-technology/pi-dashboard-context-budget",
3
+ "version": "0.8.0",
4
+ "description": "Per-turn context budget meter: captures the real provider payload via before_provider_request and attributes it to system-prompt blocks, skill catalogue entries and per-tool schemas. Proves a context trim actually reached the wire.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
10
+ "directory": "packages/context-budget"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "keywords": [
16
+ "pi-package",
17
+ "pi-extension",
18
+ "context-window",
19
+ "observability"
20
+ ],
21
+ "pi": {
22
+ "extensions": [
23
+ "src/meter.ts"
24
+ ]
25
+ },
26
+ "bin": {
27
+ "context-budget": "./bin/context-budget.mjs"
28
+ },
29
+ "exports": {
30
+ ".": "./src/index.ts"
31
+ },
32
+ "files": [
33
+ "dist/",
34
+ "src/",
35
+ "bin/",
36
+ "!src/__tests__",
37
+ "README.md",
38
+ "!**/AGENTS.md",
39
+ "!**/*.AGENTS.md"
40
+ ],
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.json",
43
+ "prepublishOnly": "npm run build",
44
+ "test": "vitest run"
45
+ },
46
+ "peerDependencies": {
47
+ "@earendil-works/pi-coding-agent": ">=1.0.0"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@earendil-works/pi-coding-agent": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "devDependencies": {
55
+ "@earendil-works/pi-coding-agent": "^1.0.0"
56
+ }
57
+ }
package/src/analyze.ts ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Pure analysis of a provider request payload.
3
+ *
4
+ * Everything here operates on a captured payload object — no pi, no network,
5
+ * no filesystem — so the accounting is unit-testable and the numbers are
6
+ * reproducible. Capture happens in meter.ts via `before_provider_request`.
7
+ */
8
+
9
+ export interface ToolCost {
10
+ name: string;
11
+ bytes: number;
12
+ }
13
+
14
+ export interface SystemBlock {
15
+ label: string;
16
+ bytes: number;
17
+ }
18
+
19
+ export interface SkillCost {
20
+ name: string;
21
+ bytes: number;
22
+ }
23
+
24
+ export interface Breakdown {
25
+ model: string;
26
+ payloadBytes: number;
27
+ systemBytes: number;
28
+ messagesBytes: number;
29
+ toolsBytes: number;
30
+ toolCount: number;
31
+ perTool: ToolCost[];
32
+ systemBlocks: SystemBlock[];
33
+ skills: SkillCost[];
34
+ }
35
+
36
+ export interface BudgetLimits {
37
+ maxPayloadBytes?: number;
38
+ maxToolsBytes?: number;
39
+ maxSkillsBytes?: number;
40
+ }
41
+
42
+ export interface BudgetViolation {
43
+ limit: keyof BudgetLimits;
44
+ actual: number;
45
+ allowed: number;
46
+ }
47
+
48
+ export interface Delta {
49
+ payloadBytesDelta: number;
50
+ systemBytesDelta: number;
51
+ toolsBytesDelta: number;
52
+ toolsAdded: string[];
53
+ toolsRemoved: string[];
54
+ skillsAdded: string[];
55
+ skillsRemoved: string[];
56
+ /** Names that were expected to disappear but are still on the wire. */
57
+ unmetExpectations: string[];
58
+ }
59
+
60
+ const bytes = (v: unknown): number => (v === undefined ? 0 : Buffer.byteLength(JSON.stringify(v)));
61
+ const textBytes = (s: string): number => Buffer.byteLength(s);
62
+
63
+ /** Provider payloads carry `system` as a string or as an array of text blocks. */
64
+ function systemText(system: unknown): string {
65
+ if (typeof system === "string") return system;
66
+ if (Array.isArray(system)) {
67
+ return system.map((b) => (b && typeof b === "object" && "text" in b ? String((b as { text: unknown }).text) : "")).join("\n");
68
+ }
69
+ return "";
70
+ }
71
+
72
+ function sliceBetween(haystack: string, open: string, close: string): string | undefined {
73
+ const i = haystack.indexOf(open);
74
+ if (i < 0) return undefined;
75
+ const j = haystack.indexOf(close, i);
76
+ if (j < 0) return undefined;
77
+ return haystack.slice(i, j + close.length);
78
+ }
79
+
80
+ function parseSkills(system: string): SkillCost[] {
81
+ const block = sliceBetween(system, "<available_skills>", "</available_skills>");
82
+ if (!block) return [];
83
+ const entries = [...block.matchAll(/<name>([^<]+)<\/name>\s*<description>([\s\S]*?)<\/description>/g)];
84
+ return entries
85
+ .map((m) => ({ name: m[1].trim(), bytes: textBytes(m[0]) }))
86
+ .sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));
87
+ }
88
+
89
+ /**
90
+ * Attribute the system prompt to known blocks. `other` absorbs the remainder so
91
+ * the parts always sum to the whole — a block that silently stops matching shows
92
+ * up as `other` growing, rather than as bytes vanishing from the report.
93
+ */
94
+ function systemBlocks(system: string): SystemBlock[] {
95
+ const named: SystemBlock[] = [];
96
+ const known: Array<[string, string, string]> = [
97
+ ["skills-catalogue", "<available_skills>", "</available_skills>"],
98
+ ["project-context", "<project_context>", "</project_context>"],
99
+ ["memory-policy", "<memory-policy>", "</memory-policy>"],
100
+ ];
101
+
102
+ for (const [label, open, close] of known) {
103
+ const found = sliceBetween(system, open, close);
104
+ if (found) named.push({ label, bytes: textBytes(found) });
105
+ }
106
+
107
+ const accounted = named.reduce((sum, b) => sum + b.bytes, 0);
108
+ named.push({ label: "other", bytes: Math.max(0, textBytes(system) - accounted) });
109
+ return named;
110
+ }
111
+
112
+ export function analyzePayload(payload: unknown): Breakdown {
113
+ const p = (payload ?? {}) as Record<string, unknown>;
114
+ const tools = Array.isArray(p.tools) ? (p.tools as Array<Record<string, unknown>>) : [];
115
+ const system = systemText(p.system);
116
+
117
+ const perTool = tools
118
+ .map((t) => {
119
+ const fn = t.function as { name?: unknown } | undefined;
120
+ const name = String(t.name ?? fn?.name ?? "?");
121
+ return { name, bytes: bytes(t) };
122
+ })
123
+ .sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));
124
+
125
+ return {
126
+ model: String(p.model ?? "?"),
127
+ payloadBytes: bytes(p),
128
+ systemBytes: textBytes(system),
129
+ messagesBytes: bytes(p.messages),
130
+ toolsBytes: bytes(p.tools),
131
+ toolCount: tools.length,
132
+ perTool,
133
+ systemBlocks: systemBlocks(system),
134
+ skills: parseSkills(system),
135
+ };
136
+ }
137
+
138
+ export function comparePayloads(before: Breakdown, after: Breakdown, opts: { expectRemoved?: string[] } = {}): Delta {
139
+ const beforeTools = before.perTool.map((t) => t.name);
140
+ const afterTools = after.perTool.map((t) => t.name);
141
+ const beforeSkills = before.skills.map((s) => s.name);
142
+ const afterSkills = after.skills.map((s) => s.name);
143
+
144
+ const stillPresent = new Set([...afterTools, ...afterSkills]);
145
+
146
+ return {
147
+ payloadBytesDelta: after.payloadBytes - before.payloadBytes,
148
+ systemBytesDelta: after.systemBytes - before.systemBytes,
149
+ toolsBytesDelta: after.toolsBytes - before.toolsBytes,
150
+ toolsAdded: afterTools.filter((n) => !beforeTools.includes(n)),
151
+ toolsRemoved: beforeTools.filter((n) => !afterTools.includes(n)),
152
+ skillsAdded: afterSkills.filter((n) => !beforeSkills.includes(n)),
153
+ skillsRemoved: beforeSkills.filter((n) => !afterSkills.includes(n)),
154
+ unmetExpectations: (opts.expectRemoved ?? []).filter((n) => stillPresent.has(n)),
155
+ };
156
+ }
157
+
158
+ export function checkBudget(b: Breakdown, limits: BudgetLimits): { ok: boolean; violations: BudgetViolation[] } {
159
+ const skillsBytes = b.skills.reduce((sum, s) => sum + s.bytes, 0);
160
+ const checks: Array<[keyof BudgetLimits, number]> = [
161
+ ["maxPayloadBytes", b.payloadBytes],
162
+ ["maxToolsBytes", b.toolsBytes],
163
+ ["maxSkillsBytes", skillsBytes],
164
+ ];
165
+
166
+ const violations: BudgetViolation[] = [];
167
+ for (const [limit, actual] of checks) {
168
+ const allowed = limits[limit];
169
+ if (allowed !== undefined && actual > allowed) violations.push({ limit, actual, allowed });
170
+ }
171
+ return { ok: violations.length === 0, violations };
172
+ }
173
+
174
+ const kb = (n: number): string => `${(n / 1024).toFixed(1)}KB`;
175
+
176
+ export function formatReport(b: Breakdown, top = 12): string {
177
+ const skillsBytes = b.skills.reduce((sum, s) => sum + s.bytes, 0);
178
+ const lines = [
179
+ `model ${b.model}`,
180
+ `payload ${kb(b.payloadBytes)} (~${Math.round(b.payloadBytes / 3.8)} tokens)`,
181
+ ` system ${kb(b.systemBytes)}`,
182
+ ...b.systemBlocks.map((x) => ` ${x.label.padEnd(16)} ${kb(x.bytes)}`),
183
+ ` tools ${kb(b.toolsBytes)} (${b.toolCount} tools)`,
184
+ ` messages ${kb(b.messagesBytes)}`,
185
+ "",
186
+ `skills advertised: ${b.skills.length} (${kb(skillsBytes)})`,
187
+ "",
188
+ `top ${top} tool schemas:`,
189
+ ...b.perTool.slice(0, top).map((t) => ` ${String(t.bytes).padStart(6)} ${t.name}`),
190
+ "",
191
+ `top ${top} skill entries:`,
192
+ ...b.skills.slice(0, top).map((s) => ` ${String(s.bytes).padStart(6)} ${s.name}`),
193
+ ];
194
+ return lines.join("\n");
195
+ }
196
+
197
+ export function formatDelta(d: Delta): string {
198
+ const sign = (n: number) => (n > 0 ? `+${n}` : String(n));
199
+ const lines = [
200
+ `payload ${sign(d.payloadBytesDelta)} B`,
201
+ `system ${sign(d.systemBytesDelta)} B`,
202
+ `tools ${sign(d.toolsBytesDelta)} B`,
203
+ ];
204
+ if (d.toolsRemoved.length) lines.push(`tools removed: ${d.toolsRemoved.join(", ")}`);
205
+ if (d.toolsAdded.length) lines.push(`tools added: ${d.toolsAdded.join(", ")}`);
206
+ if (d.skillsRemoved.length) lines.push(`skills removed (${d.skillsRemoved.length}): ${d.skillsRemoved.join(", ")}`);
207
+ if (d.skillsAdded.length) lines.push(`skills added (${d.skillsAdded.length}): ${d.skillsAdded.join(", ")}`);
208
+ if (d.unmetExpectations.length) {
209
+ lines.push(`UNMET EXPECTATIONS — still on the wire: ${d.unmetExpectations.join(", ")}`);
210
+ }
211
+ return lines.join("\n");
212
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export {
2
+ analyzePayload,
3
+ type Breakdown,
4
+ type BudgetLimits,
5
+ type BudgetViolation,
6
+ checkBudget,
7
+ comparePayloads,
8
+ type Delta,
9
+ formatDelta,
10
+ formatReport,
11
+ type SkillCost,
12
+ type SystemBlock,
13
+ type ToolCost,
14
+ } from "./analyze.js";
package/src/meter.ts ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * pi extension: capture the real outgoing provider payload once per session.
3
+ *
4
+ * `before_provider_request` fires after the provider payload is built and
5
+ * before it is sent, so what we record is exactly what the model receives —
6
+ * not a reconstruction. Returning undefined leaves the payload untouched; this
7
+ * extension only observes.
8
+ *
9
+ * Env:
10
+ * CONTEXT_BUDGET_OUT where to write the capture (default: ./context-budget.json)
11
+ * CONTEXT_BUDGET_DROP comma-separated tool names to deactivate before measuring
12
+ */
13
+
14
+ import { writeFileSync } from "node:fs";
15
+ import { analyzePayload } from "./analyze.js";
16
+
17
+ // Structural type: avoids a hard dependency on the pi SDK's ExtensionAPI, which
18
+ // is an optional peer here.
19
+ interface MeterApi {
20
+ on(event: string, handler: (event: unknown, ctx: unknown) => void): void;
21
+ getActiveTools?(): string[];
22
+ setActiveTools?(names: string[]): void;
23
+ }
24
+
25
+ export default function (pi: MeterApi): void {
26
+ const out = process.env.CONTEXT_BUDGET_OUT ?? "./context-budget.json";
27
+ const drop = (process.env.CONTEXT_BUDGET_DROP ?? "")
28
+ .split(",")
29
+ .map((s) => s.trim())
30
+ .filter(Boolean);
31
+
32
+ let captured = false;
33
+
34
+ pi.on("session_start", () => {
35
+ if (drop.length === 0) return;
36
+ const active = pi.getActiveTools?.() ?? [];
37
+ pi.setActiveTools?.(active.filter((n) => !drop.includes(n)));
38
+ });
39
+
40
+ pi.on("before_provider_request", (event: unknown) => {
41
+ if (captured) return;
42
+ captured = true;
43
+
44
+ const payload = (event as { payload?: unknown } | undefined)?.payload;
45
+ const breakdown = analyzePayload(payload);
46
+
47
+ writeFileSync(out, `${JSON.stringify({ capturedAt: new Date().toISOString(), dropped: drop, breakdown }, null, 2)}\n`);
48
+ });
49
+ }