@robhowley/pi-structured-return 1.6.1 → 1.7.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 CHANGED
@@ -161,8 +161,9 @@ Evaluated for structured parsing but raw output is already compact enough that a
161
161
  3. A parser converts noisy CLI output into a compact structured result. If no parser matches, the last 200 lines and the log path are returned as a fallback.
162
162
  4. The agent receives the structured result in context — signal only, no noise.
163
163
  5. The full log is always available on disk for both the agent and humans to inspect.
164
+ 6. Run `/sr-stats` to see how many tokens structured-return has saved — both in the current session and across all sessions.
164
165
 
165
- Run `/sr-parsers` in a pi session to see all registered parsers with their match rules.
166
+ Run `/sr-parsers` in a pi session to see all registered parsers with their match rules. Run `/sr-stats` to see token savings for the current session and lifetime.
166
167
 
167
168
  ## Extending with project-local parsers
168
169
 
@@ -9,6 +9,7 @@ import { ensureRunDir, writeRunArtifacts } from "./storage/log-store";
9
9
  import { loadProjectConfig } from "./config/project-config";
10
10
  import { resolveParser, listParsers } from "./config/registry";
11
11
  import { safeReadFile } from "./parsers/utils";
12
+ import { appendRun, readLifetimeStats, formatStatsBlock, type AggregatedStats } from "./storage/session-stats";
12
13
 
13
14
  export default function structuredReturn(pi: ExtensionAPI) {
14
15
  pi.registerCommand("sr-parsers", {
@@ -42,6 +43,40 @@ export default function structuredReturn(pi: ExtensionAPI) {
42
43
  },
43
44
  });
44
45
 
46
+ pi.registerCommand("sr-stats", {
47
+ description: "Show token savings from structured-return (current session + lifetime)",
48
+ handler: async (_args, ctx) => {
49
+ // Current session: walk session entries for our tool results
50
+ const sessionStats: AggregatedStats = { runs: 0, rawBytes: 0, parsedBytes: 0 };
51
+ try {
52
+ const entries = ctx.sessionManager?.getEntries?.() ?? [];
53
+ for (const entry of entries) {
54
+ if (entry.type !== "message") continue;
55
+ const msg = (entry as any).message;
56
+ if (msg?.role !== "toolResult" || msg?.toolName !== "structured_return") continue;
57
+ const details = msg.details;
58
+ if (details?.rawBytes != null && details?.parsedBytes != null) {
59
+ sessionStats.runs++;
60
+ sessionStats.rawBytes += details.rawBytes;
61
+ sessionStats.parsedBytes += details.parsedBytes;
62
+ }
63
+ }
64
+ } catch {
65
+ // session access may fail in some modes
66
+ }
67
+
68
+ // Lifetime: read all JSONL files
69
+ const lifetime = readLifetimeStats();
70
+
71
+ const lines: string[] = ["structured-return stats", ""];
72
+ lines.push(...formatStatsBlock("session", sessionStats));
73
+ lines.push("");
74
+ lines.push(...formatStatsBlock("lifetime", lifetime));
75
+
76
+ ctx.ui.notify(lines.join("\n"), "info");
77
+ },
78
+ });
79
+
45
80
  pi.registerTool({
46
81
  name: "structured_return",
47
82
  label: "Structured Return",
@@ -81,10 +116,26 @@ export default function structuredReturn(pi: ExtensionAPI) {
81
116
  const parser = await resolveParser({ cwd, parseAs: args.parseAs, argv, registrations });
82
117
  const parsed = await parser.parse(runCtx);
83
118
  const result = finalizeResult(parsed, exitCode, logs.logPath, cwd);
119
+ const resultText = formatResult(result);
120
+
121
+ const rawBytes = stdout.length + stderr.length;
122
+ const parsedBytes = resultText.length;
123
+ try {
124
+ appendRun({
125
+ ts: new Date().toISOString(),
126
+ session: ctx.sessionManager?.getSessionFile?.() ?? undefined,
127
+ parser: parser.id,
128
+ rawBytes,
129
+ parsedBytes,
130
+ command: stripCdPrefix(args.command),
131
+ });
132
+ } catch {
133
+ // stats are best-effort — never block the tool result
134
+ }
84
135
 
85
136
  return {
86
- content: [{ type: "text" as const, text: `${stripCdPrefix(args.command)} → ${formatResult(result)}` }],
87
- details: { exitCode, logPath: logs.logPath, parser: parser.id },
137
+ content: [{ type: "text" as const, text: `${stripCdPrefix(args.command)} → ${resultText}` }],
138
+ details: { exitCode, logPath: logs.logPath, parser: parser.id, rawBytes, parsedBytes },
88
139
  };
89
140
  },
90
141
  renderCall(args: ObservedRunArgs) {
@@ -0,0 +1,141 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import {
6
+ appendRun,
7
+ readLifetimeStats,
8
+ formatBytes,
9
+ estimateTokens,
10
+ formatStatsBlock,
11
+ type StatsEntry,
12
+ } from "./session-stats";
13
+
14
+ // Use a temp dir to avoid polluting ~/.pi during tests
15
+ let tempDir: string;
16
+
17
+ beforeEach(() => {
18
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "sr-stats-test-"));
19
+ // Override homedir so statsDir() resolves to our temp
20
+ vi.spyOn(os, "homedir").mockReturnValue(tempDir);
21
+ });
22
+
23
+ afterEach(() => {
24
+ vi.restoreAllMocks();
25
+ fs.rmSync(tempDir, { recursive: true, force: true });
26
+ });
27
+
28
+ function makeEntry(overrides: Partial<StatsEntry> = {}): StatsEntry {
29
+ return {
30
+ ts: new Date().toISOString(),
31
+ session: "/test/session.jsonl",
32
+ parser: "vitest-json",
33
+ rawBytes: 10000,
34
+ parsedBytes: 200,
35
+ command: "vitest run",
36
+ ...overrides,
37
+ };
38
+ }
39
+
40
+ describe("appendRun", () => {
41
+ it("creates the stats file on first append", () => {
42
+ appendRun(makeEntry());
43
+ const file = path.join(tempDir, ".pi", "structured-return-stats.000.jsonl");
44
+ expect(fs.existsSync(file)).toBe(true);
45
+ const lines = fs.readFileSync(file, "utf-8").trim().split("\n");
46
+ expect(lines).toHaveLength(1);
47
+ expect(JSON.parse(lines[0]).parser).toBe("vitest-json");
48
+ });
49
+
50
+ it("appends multiple entries to the same file", () => {
51
+ appendRun(makeEntry({ command: "first" }));
52
+ appendRun(makeEntry({ command: "second" }));
53
+ appendRun(makeEntry({ command: "third" }));
54
+ const file = path.join(tempDir, ".pi", "structured-return-stats.000.jsonl");
55
+ const lines = fs.readFileSync(file, "utf-8").trim().split("\n");
56
+ expect(lines).toHaveLength(3);
57
+ expect(JSON.parse(lines[1]).command).toBe("second");
58
+ });
59
+
60
+ it("spills over to a new file when current exceeds 3MB", () => {
61
+ const statsDir = path.join(tempDir, ".pi");
62
+ fs.mkdirSync(statsDir, { recursive: true });
63
+ // Create a file just at the threshold
64
+ const bigContent = "x".repeat(3 * 1024 * 1024);
65
+ fs.writeFileSync(path.join(statsDir, "structured-return-stats.000.jsonl"), bigContent);
66
+
67
+ appendRun(makeEntry());
68
+
69
+ const newFile = path.join(statsDir, "structured-return-stats.001.jsonl");
70
+ expect(fs.existsSync(newFile)).toBe(true);
71
+ const lines = fs.readFileSync(newFile, "utf-8").trim().split("\n");
72
+ expect(lines).toHaveLength(1);
73
+ });
74
+ });
75
+
76
+ describe("readLifetimeStats", () => {
77
+ it("returns zeros when no files exist", () => {
78
+ const stats = readLifetimeStats();
79
+ expect(stats).toEqual({ runs: 0, rawBytes: 0, parsedBytes: 0 });
80
+ });
81
+
82
+ it("sums entries across multiple files", () => {
83
+ const statsDir = path.join(tempDir, ".pi");
84
+ fs.mkdirSync(statsDir, { recursive: true });
85
+
86
+ const entry1 = JSON.stringify({ rawBytes: 1000, parsedBytes: 100 });
87
+ const entry2 = JSON.stringify({ rawBytes: 2000, parsedBytes: 200 });
88
+ const entry3 = JSON.stringify({ rawBytes: 3000, parsedBytes: 300 });
89
+
90
+ fs.writeFileSync(path.join(statsDir, "structured-return-stats.000.jsonl"), entry1 + "\n" + entry2 + "\n");
91
+ fs.writeFileSync(path.join(statsDir, "structured-return-stats.001.jsonl"), entry3 + "\n");
92
+
93
+ const stats = readLifetimeStats();
94
+ expect(stats.runs).toBe(3);
95
+ expect(stats.rawBytes).toBe(6000);
96
+ expect(stats.parsedBytes).toBe(600);
97
+ });
98
+
99
+ it("skips malformed lines", () => {
100
+ const statsDir = path.join(tempDir, ".pi");
101
+ fs.mkdirSync(statsDir, { recursive: true });
102
+
103
+ const content = [
104
+ JSON.stringify({ rawBytes: 1000, parsedBytes: 100 }),
105
+ "not valid json",
106
+ JSON.stringify({ rawBytes: 2000, parsedBytes: 200 }),
107
+ ].join("\n");
108
+ fs.writeFileSync(path.join(statsDir, "structured-return-stats.000.jsonl"), content + "\n");
109
+
110
+ const stats = readLifetimeStats();
111
+ expect(stats.runs).toBe(2);
112
+ expect(stats.rawBytes).toBe(3000);
113
+ });
114
+ });
115
+
116
+ describe("formatBytes", () => {
117
+ it("formats bytes", () => expect(formatBytes(500)).toBe("500 B"));
118
+ it("formats kilobytes", () => expect(formatBytes(2048)).toBe("2.0 KB"));
119
+ it("formats megabytes", () => expect(formatBytes(5 * 1024 * 1024)).toBe("5.0 MB"));
120
+ });
121
+
122
+ describe("estimateTokens", () => {
123
+ it("formats small counts", () => expect(estimateTokens(100)).toBe("25"));
124
+ it("formats thousands", () => expect(estimateTokens(40000)).toBe("10.0k"));
125
+ it("formats millions", () => expect(estimateTokens(8000000)).toBe("2.0M"));
126
+ });
127
+
128
+ describe("formatStatsBlock", () => {
129
+ it("formats a labeled stats block", () => {
130
+ const block = formatStatsBlock("session", { runs: 5, rawBytes: 50000, parsedBytes: 1000 });
131
+ expect(block[0]).toBe("session:");
132
+ expect(block[1]).toContain("runs: 5");
133
+ expect(block[4]).toContain("98.0% reduction");
134
+ });
135
+
136
+ it("handles zero runs gracefully", () => {
137
+ const block = formatStatsBlock("lifetime", { runs: 0, rawBytes: 0, parsedBytes: 0 });
138
+ expect(block[1]).toContain("runs: 0");
139
+ expect(block[4]).toContain("0.0%");
140
+ });
141
+ });
@@ -0,0 +1,122 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+
5
+ const FILE_PREFIX = "structured-return-stats.";
6
+ const FILE_SUFFIX = ".jsonl";
7
+ const MAX_FILE_BYTES = 3 * 1024 * 1024; // 3MB
8
+
9
+ function statsDir(): string {
10
+ return path.join(os.homedir(), ".pi");
11
+ }
12
+
13
+ export type StatsEntry = {
14
+ ts: string;
15
+ session: string | undefined;
16
+ parser: string;
17
+ rawBytes: number;
18
+ parsedBytes: number;
19
+ command: string;
20
+ };
21
+
22
+ export type AggregatedStats = {
23
+ runs: number;
24
+ rawBytes: number;
25
+ parsedBytes: number;
26
+ };
27
+
28
+ function statsFileName(index: number): string {
29
+ return `${FILE_PREFIX}${String(index).padStart(3, "0")}${FILE_SUFFIX}`;
30
+ }
31
+
32
+ function statsFilePath(index: number): string {
33
+ return path.join(statsDir(), statsFileName(index));
34
+ }
35
+
36
+ /** Find all stats files sorted by index. */
37
+ function listStatsFiles(): string[] {
38
+ const dir = statsDir();
39
+ if (!fs.existsSync(dir)) return [];
40
+ const files = fs
41
+ .readdirSync(dir)
42
+ .filter((f) => f.startsWith(FILE_PREFIX) && f.endsWith(FILE_SUFFIX))
43
+ .sort();
44
+ return files.map((f) => path.join(dir, f));
45
+ }
46
+
47
+ /** Get the current (latest) file index, creating 000 if none exist. */
48
+ function currentFileIndex(): number {
49
+ const files = listStatsFiles();
50
+ if (files.length === 0) return 0;
51
+ const last = path.basename(files[files.length - 1]);
52
+ const match = last.match(/\.(\d{3})\./);
53
+ return match ? parseInt(match[1], 10) : 0;
54
+ }
55
+
56
+ /** Append a stats entry, spilling over to a new file if needed. */
57
+ export function appendRun(entry: StatsEntry): void {
58
+ fs.mkdirSync(statsDir(), { recursive: true });
59
+ let index = currentFileIndex();
60
+ let filePath = statsFilePath(index);
61
+
62
+ // Check spillover
63
+ if (fs.existsSync(filePath)) {
64
+ const stat = fs.statSync(filePath);
65
+ if (stat.size >= MAX_FILE_BYTES) {
66
+ index++;
67
+ filePath = statsFilePath(index);
68
+ }
69
+ }
70
+
71
+ const line = JSON.stringify(entry) + "\n";
72
+ fs.appendFileSync(filePath, line);
73
+ }
74
+
75
+ /** Read and aggregate all stats files for lifetime totals. */
76
+ export function readLifetimeStats(): AggregatedStats {
77
+ const files = listStatsFiles();
78
+ const totals: AggregatedStats = { runs: 0, rawBytes: 0, parsedBytes: 0 };
79
+
80
+ for (const file of files) {
81
+ const content = fs.readFileSync(file, "utf-8");
82
+ for (const line of content.split("\n")) {
83
+ if (!line.trim()) continue;
84
+ try {
85
+ const entry: StatsEntry = JSON.parse(line);
86
+ totals.runs++;
87
+ totals.rawBytes += entry.rawBytes;
88
+ totals.parsedBytes += entry.parsedBytes;
89
+ } catch {
90
+ // skip malformed lines
91
+ }
92
+ }
93
+ }
94
+
95
+ return totals;
96
+ }
97
+
98
+ export function formatBytes(bytes: number): string {
99
+ if (bytes < 1024) return `${bytes} B`;
100
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
101
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
102
+ }
103
+
104
+ /** Approximate token count: ~4 bytes per token for English text across common tokenizers (GPT/Claude). */
105
+ export function estimateTokens(bytes: number): string {
106
+ const tokens = Math.round(bytes / 4);
107
+ if (tokens < 1000) return `${tokens}`;
108
+ if (tokens < 1_000_000) return `${(tokens / 1000).toFixed(1)}k`;
109
+ return `${(tokens / 1_000_000).toFixed(1)}M`;
110
+ }
111
+
112
+ export function formatStatsBlock(label: string, stats: AggregatedStats): string[] {
113
+ const saved = stats.rawBytes - stats.parsedBytes;
114
+ const pct = stats.rawBytes > 0 ? ((saved / stats.rawBytes) * 100).toFixed(1) : "0.0";
115
+ return [
116
+ `${label}:`,
117
+ ` runs: ${stats.runs}`,
118
+ ` raw output: ${formatBytes(stats.rawBytes)} (~${estimateTokens(stats.rawBytes)} tokens)`,
119
+ ` parsed output: ${formatBytes(stats.parsedBytes)} (~${estimateTokens(stats.parsedBytes)} tokens)`,
120
+ ` saved: ${formatBytes(saved)} (~${estimateTokens(saved)} tokens, ${pct}% reduction)`,
121
+ ];
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robhowley/pi-structured-return",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "description": "Turn noisy CLI output into compact structured results (fewer tokens), full logs preserved.",
5
5
  "license": "MIT",
6
6
  "repository": {