repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

new extension and bug fixes

292965fdf3c4c756b3d4d1d589a591629e0b43a1

Review <review@example.invalid> ·

unsigned

Browse filesCompare with HEAD

rtk: rust token killer extension
goal: correctly prune old errors on resume now
tune: fix html table header

Changed files (15)

AGENTS.md

Modified
52 52 ## Cross-platform Requirements
54 -Extensions must work on Windows, macOS, and Linux unless their README explicitly scopes them narrower.
54 +All extensions must work on Windows, macOS, and Linux.
55 +Do not add OS-scoped extensions.
55 56 Do not rely on shell-specific helpers such as `which`, `bash`, `sed`, `grep`, or `/tmp` when Node APIs can do the job.
56 57 If an extension uses platform tools, check their availability when the extension loads.
57 58 Notify missing required tools with warning severity.

CHANGELOG.md

Modified
2 2 # Changelog
4 4 ## Unreleased
6 +- Add the `rtk` extension for rewriting Pi `bash` tool calls through `rtk rewrite`
7 + when `rtk >= 0.23.0` is available
8 +- Warn once and keep `rtk` idle when the RTK binary is missing or too old
9 +- Add local `rtk summary` fallbacks only for noisy diagnostic commands
10 + (`journalctl`, `ps`, `systemctl status`, and selected `hyprctl` queries),
11 + without auto-wrapping `mise` gate commands
6 12 - Suppress leaks assignment-span false positives on common programmer-noun keys
7 13 (`seed`, `id`, `name`, `count`, `type`, `value`, `path`, `key`, `ts`, `time`,
8 14 `date`, `idx`, `mode`, `flag`, `opts`, `params`, `args`, `options`, `label`,
22 28 - Make Ctrl+C cancel an active goal and abort the current Pi run like Escape
23 29 - Prune goal transcript rows and persisted assistant failure messages from active
24 30 goal LLM context so reload/resume cannot resurrect failed retry payloads
31 +- Prune failed assistant tool-use/tool-result cascades from active goal LLM
32 + context before assistant error messages
25 33 - Pause the goal loop on terminal errors (auth 401/403, quota,
26 34 bad_request 400, `stopReason === "aborted"`) and after Pi core retry exhaustion
27 35 - Derive user-facing `lastReason` and notifications from the classifier instead
80 88 - Migrate legacy tune state before tune start and dashboard export flows
81 89 - Add `.pi/tune/config.json` `autoResumeLimit` to cap automatic tune resume turns;
82 90 default, null, missing, and invalid values mean unlimited
91 +- Make tune dashboard and current-best reporting ignore discarded runs, using kept
92 + runs only
93 +- Require tune ASI log entries to include a `next_action_hint` for dashboard and
94 + compaction guidance
83 95 - Add `wiki` as the research and persistent knowledge-base skill
84 96 - Make `research` a compatibility alias for the `wiki` workflow
85 97 - Route new research evidence to `~/Notes/Wiki/raw-sources/` and treat

README.md

Modified
91 91 | `q` | Follow-up question fork helper for Pi. | [README](extensions/q/README.md) |
92 92 | `quota` | Subscription quota dashboard for Pi providers. | [README](extensions/quota/README.md) |
93 93 | `runtime` | Runtime detection telemetry for Pi footer/status. | [README](extensions/runtime/README.md) |
94 +| `rtk` | RTK bash command rewrite hook for Pi. | [README](extensions/rtk/README.md) |
94 95 | `session-rename` | Automatic short session names for Pi. | [README](extensions/session-rename/README.md) |
95 96 | `ssh-tools` | SSH mode for Pi with remote read/write/edit/bash tools. | [README](extensions/ssh-tools/README.md) |
96 97 | `super` | Task branches and curated Super skills for Pi. | [README](extensions/super/README.md) |

extensions/goal/__tests__/unit.test.ts

Modified
160 160 expect(pruned).toEqual([messages[0], messages[5]]);
163 + it("removes persisted failed tool cascade before an assistant error", () => {
164 + const state = goal({ status: "active" }) as never;
165 + const messages = [
166 + { role: "user", content: "start" },
168 + role: "assistant",
169 + content: [{ type: "text", text: "useful progress" }],
170 + stopReason: "stop",
171 + },
173 + role: "assistant",
174 + content: [
176 + type: "toolCall",
177 + name: "edit",
178 + arguments: { path: "bad", edits: [] },
179 + },
180 + ],
181 + stopReason: "toolUse",
182 + },
184 + role: "toolResult",
185 + toolName: "edit",
186 + isError: true,
187 + content: "No changes made",
188 + },
190 + role: "assistant",
191 + content: [
192 + { type: "text", text: "retry" },
194 + type: "toolCall",
195 + name: "edit",
196 + arguments: { path: "bad", edits: [] },
197 + },
198 + ],
199 + stopReason: "toolUse",
200 + },
202 + role: "toolResult",
203 + toolName: "edit",
204 + isError: true,
205 + content: "No changes made",
206 + },
208 + role: "assistant",
209 + content: [],
210 + stopReason: "error",
211 + errorMessage:
212 + "Expected ',' or '}' after property value in JSON at position 1742",
213 + },
215 + role: "custom",
216 + customType: "goal-continuation",
217 + details: { goalId: "goal-1" },
218 + },
219 + ];
221 + const pruned = __goalTest.pruneGoalContextMessages(messages, state);
223 + expect(pruned).toEqual([messages[0], messages[1], messages[7]]);
224 + });
163 226 it("parses model refs and rejects invalid refs", () => {
164 227 expect(__goalTest.parseModelRef("provider/model/name")).toEqual({
165 228 provider: "provider",

extensions/goal/index.ts

Modified
2344 2344 return stopReason === "error" || stopReason === "aborted";
2347 +function isAssistantToolUseMessage(msg: Record<string, unknown>): boolean {
2348 + if (msg.role !== "assistant") return false;
2349 + if (msg.stopReason === "toolUse") return true;
2350 + const content = msg.content;
2351 + return (
2352 + Array.isArray(content) &&
2353 + content.some((part) => isRecord(part) && part.type === "toolCall")
2354 + );
2357 +function isToolResultMessage(msg: Record<string, unknown>): boolean {
2358 + return (
2359 + msg.role === "tool" || msg.role === "toolResult" || "toolCallId" in msg
2360 + );
2363 +function pruneFailedToolCascades(
2364 + messages: Array<Record<string, unknown>>,
2365 +): Array<Record<string, unknown>> {
2366 + const remove = new Set<number>();
2367 + for (let i = 0; i < messages.length; i++) {
2368 + if (!isAssistantErrorMessage(messages[i])) continue;
2369 + remove.add(i);
2370 + for (let j = i - 1; j >= 0; j--) {
2371 + const msg = messages[j];
2372 + if (!isAssistantToolUseMessage(msg) && !isToolResultMessage(msg)) break;
2373 + remove.add(j);
2376 + return messages.filter((_, index) => !remove.has(index));
2347 2379 function pruneGoalContextMessages(
2348 2380 messages: Array<Record<string, unknown>>,
2349 2381 state: GoalState | undefined,
2350 2382 ): Array<Record<string, unknown>> {
2351 2383 const goalIsActive = state?.status === "active";
2384 + const sourceMessages = goalIsActive
2385 + ? pruneFailedToolCascades(messages)
2386 + : messages;
2352 2387 return pruneContinuationMessages(
2353 - messages.filter((msg) => {
2388 + sourceMessages.filter((msg) => {
2354 2389 if (goalIsActive && isAssistantErrorMessage(msg)) return false;
2356 2391 msg.role === "custom" &&

extensions/rtk/CHANGELOG.md

Added
new file mode 100644
1 +# Changelog
3 +## Unreleased
5 +- add minimal RTK bash rewrite hook
6 +- warn once on load when RTK is missing or too old

extensions/rtk/README.md

Added
new file mode 100644
1 +# rtk
3 +Rewrites Pi `bash` tool calls through RTK.
5 +## Install / load
7 +Loaded through the root `pi-ext` package.
8 +See [../../README.md](../../README.md).
10 +Requires `rtk >= 0.23.0` on `PATH`.
11 +If missing or old, the extension prints one warning and stays idle.
13 +## Commands / tools / settings
15 +Pi commands:
16 +none.
18 +Pi tools:
19 +none.
21 +Pi hooks:
23 +- `tool_call`:
24 + watches builtin `bash` calls and may replace `input.command` with `rtk rewrite` output.
26 +Pi settings:
27 +none.
29 +Env vars:
31 +```text
32 +RTK_DISABLED=1
33 +```
35 +Prefix one command with `RTK_DISABLED=1` to bypass rewriting.
37 +## UI
39 +The bash tool widget is the indicator.
40 +When RTK applies, Pi shows the rewritten `rtk ...` command.
42 +## Behavior
44 +`rtk` does one thing:
46 +1. probes `rtk --version` on extension load
47 +2. warns once and registers nothing if `rtk` is missing or too old
48 +3. ignores non-bash tools
49 +4. ignores empty, already-`rtk`, and disabled commands
50 +5. calls `rtk rewrite <command>` with a 2s timeout
51 +6. applies exit `0` and `3` rewrites
52 +7. locally maps missing `journalctl`, `systemctl status`, `hyprctl clients`, and `ps` filters to `rtk summary`
53 +8. leaves other exit `1`, exit `2`, timeouts, errors, and empty output untouched
55 +No prompt injection.
56 +No status widget.
57 +No command gating.
58 +No output compaction.
59 +No shell-specific helpers.

extensions/rtk/__tests__/harness.test.ts

Added
new file mode 100644
1 +import { chmodSync, mkdtempSync, writeFileSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
4 +import { afterEach, beforeEach, describe, expect, it } from "vitest";
5 +import { createTestSession, type TestSession } from "../../../test/harness";
7 +let t: TestSession | undefined;
8 +let oldPath = "";
10 +function rtkPath(): string {
11 + return path.resolve(import.meta.dirname, "../index.ts");
14 +function installFakeRtk(): string {
15 + const dir = mkdtempSync(path.join(tmpdir(), "pi-ext-rtk-"));
16 + const script = [
17 + "#!/usr/bin/env node",
18 + "const [, , sub, command] = process.argv;",
19 + "if (sub === '--version') { console.log('rtk 0.37.2'); process.exit(0); }",
20 + "if (sub === 'rewrite' && command === 'git status') { console.log('rtk git status'); process.exit(0); }",
21 + "process.exit(1);",
22 + "",
23 + ].join("\n");
24 + const bin = path.join(dir, process.platform === "win32" ? "rtk.cmd" : "rtk");
25 + if (process.platform === "win32") {
26 + writeFileSync(
27 + bin,
28 + `@echo off\nnode "${path.join(dir, "rtk.js")}" %*\n`,
29 + "utf8",
30 + );
31 + writeFileSync(path.join(dir, "rtk.js"), script, "utf8");
32 + } else {
33 + writeFileSync(bin, script, "utf8");
34 + chmodSync(bin, 0o755);
35 + }
36 + return dir;
39 +beforeEach(async () => {
40 + oldPath = process.env.PATH ?? "";
41 + process.env.PATH = `${installFakeRtk()}${path.delimiter}${oldPath}`;
42 + t = await createTestSession({ extensions: [rtkPath()] });
43 +});
45 +afterEach(() => {
46 + t?.dispose();
47 + t = undefined;
48 + process.env.PATH = oldPath;
49 +});
51 +describe("rtk harness integration", () => {
52 + it("loads with no tools and no commands", () => {
53 + const [extension] = t?.session.extensionRunner.extensions ?? [];
54 + expect(extension?.path).toBe(rtkPath());
55 + expect([...(extension?.tools.keys() ?? [])]).toEqual([]);
56 + expect([...(extension?.commands.keys() ?? [])]).toEqual([]);
57 + });
59 + it("mutates bash tool calls before execution", async () => {
60 + const event = {
61 + type: "tool_call",
62 + toolName: "bash",
63 + toolCallId: "1",
64 + input: { command: "git status" },
65 + };
66 + await t?.session.extensionRunner.emitToolCall(event as never);
67 + expect(event.input.command).toBe("rtk git status");
68 + });
70 + it("mutates local fallback bash tool calls before execution", async () => {
71 + const event = {
72 + type: "tool_call",
73 + toolName: "bash",
74 + toolCallId: "2",
75 + input: { command: "ps aux" },
76 + };
77 + await t?.session.extensionRunner.emitToolCall(event as never);
78 + expect(event.input.command).toBe("rtk summary ps aux");
79 + });
80 +});

extensions/rtk/__tests__/rtk.test.ts

Added
new file mode 100644
1 +import { describe, expect, test, vi } from "vitest";
2 +import rtkExtension, { __test } from "../index.ts";
4 +const { localFallbackRewrite, parseRtkVersion, shouldSkipCommand } = __test;
6 +type Handler = (event: any, ctx: any) => unknown | Promise<unknown>;
8 +function fakePi(exec: (command: string, args: string[]) => Promise<any>) {
9 + const handlers: Record<string, Handler[]> = {};
10 + const notes: Array<[string, string]> = [];
11 + return {
12 + handlers,
13 + notes,
14 + ctx: {
15 + hasUI: true,
16 + ui: { notify: vi.fn((message, level) => notes.push([message, level])) },
17 + },
18 + pi: {
19 + exec: vi.fn(exec),
20 + on: vi.fn((event: string, handler: Handler) => {
21 + if (!handlers[event]) handlers[event] = [];
22 + handlers[event].push(handler);
23 + }),
24 + ui: { notify: vi.fn((message, level) => notes.push([message, level])) },
25 + },
26 + };
29 +async function loadWithRewrite(code: number, stdout = "") {
30 + const fx = fakePi(async (_command, args) =>
31 + args[0] === "--version"
32 + ? { code: 0, stdout: "rtk 0.42.4" }
33 + : { code, stdout },
34 + );
35 + await rtkExtension(fx.pi as never, fx.ctx as never);
36 + return fx;
39 +async function emit(
40 + fx: Awaited<ReturnType<typeof loadWithRewrite>>,
41 + command: string,
42 + toolName = "bash",
43 +) {
44 + const event = { toolName, input: { command } };
45 + await fx.handlers.tool_call?.[0]?.(event, { signal: AbortSignal.abort() });
46 + return event.input.command;
49 +describe("rtk extension", () => {
50 + test("parses versions and skip guards", () => {
51 + expect(parseRtkVersion("rtk 0.42.4")).toEqual([0, 42, 4]);
52 + expect(parseRtkVersion("garbage")).toBeNull();
53 + expect(shouldSkipCommand("rtk git status")).toBe(true);
54 + expect(shouldSkipCommand("env RTK_DISABLED=1 git status")).toBe(true);
55 + expect(shouldSkipCommand("git status")).toBe(false);
56 + });
58 + test("maps local noisy-output misses only", () => {
59 + expect(localFallbackRewrite("journalctl --user -n 100 --no-pager")).toBe(
60 + "rtk summary journalctl --user -n 100 --no-pager",
61 + );
62 + expect(localFallbackRewrite("systemctl --user status pipewire")).toBe(
63 + "rtk summary systemctl --user status pipewire",
64 + );
65 + expect(localFallbackRewrite("hyprctl clients")).toBe(
66 + "rtk summary hyprctl clients",
67 + );
68 + expect(localFallbackRewrite("ps aux")).toBe("rtk summary ps aux");
69 + expect(
70 + localFallbackRewrite("mise run test -- extensions/rtk"),
71 + ).toBeUndefined();
72 + expect(
73 + localFallbackRewrite("mise exec -- biome check extensions/rtk"),
74 + ).toBeUndefined();
75 + expect(
76 + localFallbackRewrite("journalctl --user | grep pipewire"),
77 + ).toBeUndefined();
78 + });
80 + test("warns once and registers nothing when rtk is missing", async () => {
81 + const fx = fakePi(async () => ({ code: 127, stdout: "" }));
82 + await rtkExtension(fx.pi as never, fx.ctx as never);
83 + expect(fx.handlers.tool_call).toBeUndefined();
84 + expect(fx.notes).toEqual([["rtk disabled: not found on PATH", "warning"]]);
85 + });
87 + test("warns through pi ui when no load ctx is passed", async () => {
88 + const fx = fakePi(async () => ({ code: 127, stdout: "" }));
89 + await rtkExtension(fx.pi as never);
90 + expect(fx.handlers.tool_call).toBeUndefined();
91 + expect(fx.notes).toEqual([["rtk disabled: not found on PATH", "warning"]]);
92 + });
94 + test("warns on startup hook when load ui is unavailable", async () => {
95 + const fx = fakePi(async () => ({ code: 127, stdout: "" }));
96 + const pi = { ...fx.pi, ui: undefined };
97 + await rtkExtension(pi as never);
98 + expect(fx.handlers.tool_call).toBeUndefined();
99 + expect(fx.notes).toEqual([]);
100 + fx.handlers.before_agent_start?.[0]?.({}, fx.ctx);
101 + expect(fx.notes).toEqual([["rtk disabled: not found on PATH", "warning"]]);
102 + fx.handlers.session_start?.[0]?.({}, fx.ctx);
103 + expect(fx.notes).toEqual([["rtk disabled: not found on PATH", "warning"]]);
104 + });
106 + test("warns once and registers nothing when rtk is old", async () => {
107 + const fx = fakePi(async () => ({ code: 0, stdout: "rtk 0.22.9" }));
108 + await rtkExtension(fx.pi as never, fx.ctx as never);
109 + expect(fx.handlers.tool_call).toBeUndefined();
110 + expect(fx.notes).toEqual([
111 + ["rtk disabled: too old (rtk 0.22.9); need >= 0.23.0", "warning"],
112 + ]);
113 + });
115 + test("registers only tool_call when rtk is available", async () => {
116 + const fx = await loadWithRewrite(1);
117 + expect(fx.pi.on).toHaveBeenCalledWith("tool_call", expect.any(Function));
118 + expect(fx.notes).toEqual([]);
119 + });
121 + test("rewrites via rtk and falls back only on no-match", async () => {
122 + expect(
123 + await emit(await loadWithRewrite(0, "rtk git status\n"), "git status"),
124 + ).toBe("rtk git status");
125 + expect(
126 + await emit(await loadWithRewrite(3, "rtk cargo test\n"), "cargo test"),
127 + ).toBe("rtk cargo test");
128 + expect(await emit(await loadWithRewrite(1), "ps aux")).toBe(
129 + "rtk summary ps aux",
130 + );
131 + expect(await emit(await loadWithRewrite(2), "ps aux")).toBe("ps aux");
132 + });
134 + test("uses local fallback when pi.exec throws exit 1", async () => {
135 + const fx = fakePi(async (_command, args) => {
136 + if (args[0] === "--version") return { code: 0, stdout: "rtk 0.42.4" };
137 + throw Object.assign(new Error("no match"), { exitCode: 1 });
138 + });
139 + await rtkExtension(fx.pi as never, fx.ctx as never);
140 + expect(await emit(fx as never, "ps aux")).toBe("rtk summary ps aux");
141 + });
143 + test("leaves non-bash and skipped commands untouched", async () => {
144 + const fx = await loadWithRewrite(0, "rtk git status\n");
145 + expect(await emit(fx, "git status", "read")).toBe("git status");
146 + expect(await emit(fx, "rtk git status")).toBe("rtk git status");
147 + });
148 +});

extensions/rtk/index.ts

Added
new file mode 100644
1 +import type {
2 + ExtensionAPI,
3 + ExtensionContext,
4 +} from "@earendil-works/pi-coding-agent";
5 +import { isToolCallEventType } from "@earendil-works/pi-coding-agent";
7 +const TIMEOUT_MS = 2_000;
8 +const MIN_MAJOR = 0;
9 +const MIN_MINOR = 23;
11 +type VersionTuple = [number, number, number];
13 +type ExecResult = {
14 + code?: number | null;
15 + stdout?: string;
16 + stderr?: string;
17 + killed?: boolean;
18 +};
20 +type RtkStatus =
21 + | { ok: true }
22 + | { ok: false; reason: "missing" | "old"; version?: string };
24 +export function parseRtkVersion(text: string): VersionTuple | null {
25 + const match = text.match(/(\d+)\.(\d+)\.(\d+)/);
26 + if (!match) return null;
27 + return [Number(match[1]), Number(match[2]), Number(match[3])];
30 +function supported(version: VersionTuple | null): boolean {
31 + if (version === null) return false;
32 + const [major, minor] = version;
33 + return major > MIN_MAJOR || (major === MIN_MAJOR && minor >= MIN_MINOR);
36 +export function shouldSkipCommand(command: string): boolean {
37 + const trimmed = command.trimStart();
38 + if (trimmed.trim() === "") return true;
39 + if (trimmed === "rtk" || trimmed.startsWith("rtk ")) return true;
40 + return /^(?:env\s+)?RTK_DISABLED=1(?:\s|$)/u.test(trimmed);
43 +function hasShellOperators(command: string): boolean {
44 + return /[|;<>`]|\$\(|&&|\|\|/u.test(command);
47 +export function localFallbackRewrite(command: string): string | undefined {
48 + const trimmed = command.trim();
49 + if (hasShellOperators(trimmed)) return undefined;
50 + if (/^(journalctl|ps)(\s|$)/u.test(trimmed)) return `rtk summary ${trimmed}`;
51 + if (/^systemctl\s+(?:--user\s+)?status(\s|$)/u.test(trimmed))
52 + return `rtk summary ${trimmed}`;
53 + if (
54 + /^hyprctl\s+(clients|monitors|workspaces|activewindow|activeworkspace)(\s|$)/u.test(
55 + trimmed,
56 + )
57 + )
58 + return `rtk summary ${trimmed}`;
59 + return undefined;
62 +type RewriteOutcome =
63 + | { kind: "rewrite"; command: string }
64 + | { kind: "fallback" }
65 + | { kind: "unchanged" };
67 +function execCode(error: unknown): number | null {
68 + if (typeof error !== "object" || error === null) return null;
69 + const maybe = error as {
70 + code?: unknown;
71 + exitCode?: unknown;
72 + status?: unknown;
73 + };
74 + for (const value of [maybe.code, maybe.exitCode, maybe.status])
75 + if (typeof value === "number") return value;
76 + return null;
79 +async function rewriteCommand(
80 + pi: ExtensionAPI,
81 + command: string,
82 + signal?: AbortSignal,
83 +): Promise<RewriteOutcome> {
84 + try {
85 + const result = (await pi.exec("rtk", ["rewrite", command], {
86 + timeout: TIMEOUT_MS,
87 + signal,
88 + })) as ExecResult;
89 + if (result.killed) return { kind: "unchanged" };
90 + if (result.code === 1) return { kind: "fallback" };
91 + if (result.code !== 0 && result.code !== 3) return { kind: "unchanged" };
92 + const rewritten = result.stdout?.trim();
93 + if (!rewritten || rewritten === command) return { kind: "fallback" };
94 + return { kind: "rewrite", command: rewritten };
95 + } catch (error) {
96 + return execCode(error) === 1 ? { kind: "fallback" } : { kind: "unchanged" };
97 + }
100 +async function rtkStatus(pi: ExtensionAPI): Promise<RtkStatus> {
101 + try {
102 + const result = (await pi.exec("rtk", ["--version"], {
103 + timeout: TIMEOUT_MS,
104 + })) as ExecResult;
105 + if (result.code !== 0) return { ok: false, reason: "missing" };
106 + const text = (result.stdout ?? result.stderr ?? "").trim();
107 + return supported(parseRtkVersion(text))
108 + ? { ok: true }
109 + : { ok: false, reason: "old", version: text };
110 + } catch {
111 + return { ok: false, reason: "missing" };
115 +function warnUnavailable(
116 + status: RtkStatus,
117 + pi: ExtensionAPI,
118 + ctx?: ExtensionContext,
119 +): boolean {
120 + if (status.ok) return false;
121 + const notify = ctx?.hasUI
122 + ? ctx.ui.notify.bind(ctx.ui)
123 + : (pi as { ui?: { notify?: (message: string, level: "warning") => void } })
124 + .ui?.notify;
125 + if (!notify) return false;
126 + const suffix =
127 + status.reason === "old"
128 + ? `too old (${status.version || "unknown"}); need >= 0.23.0`
129 + : "not found on PATH";
130 + notify(`rtk disabled: ${suffix}`, "warning");
131 + return true;
134 +export const __test = {
135 + localFallbackRewrite,
136 + parseRtkVersion,
137 + shouldSkipCommand,
140 +export default async function rtk(pi: ExtensionAPI, ctx?: ExtensionContext) {
141 + const status = await rtkStatus(pi);
142 + if (!status.ok) {
143 + let warned = warnUnavailable(status, pi, ctx);
144 + const warnOnce = (_event: unknown, hookCtx: ExtensionContext) => {
145 + if (!warned) warned = warnUnavailable(status, pi, hookCtx);
146 + };
147 + pi.on("session_start", warnOnce);
148 + pi.on("before_agent_start", warnOnce);
149 + return;
152 + pi.on("tool_call", async (event, ctx) => {
153 + if (!isToolCallEventType("bash", event)) return;
154 + const command = event.input.command;
155 + if (typeof command !== "string" || shouldSkipCommand(command)) return;
156 + const outcome = await rewriteCommand(pi, command, ctx.signal);
157 + const rewritten =
158 + outcome.kind === "rewrite"
159 + ? outcome.command
160 + : outcome.kind === "fallback"
161 + ? localFallbackRewrite(command)
162 + : undefined;
163 + if (rewritten) event.input.command = rewritten;
164 + });

extensions/rtk/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-rtk",
3 + "type": "module",
4 + "main": "index.ts",
5 + "scripts": {},
6 + "peerDependencies": {
7 + "@earendil-works/pi-coding-agent": "*"
8 + },
9 + "devDependencies": {
10 + "@marcfargas/pi-test-harness": "^0.6.1",
11 + "vitest": "^4.1.8"
12 + },
13 + "license": "MIT",
14 + "description": "Rewrites Pi bash tool calls through rtk.",
15 + "keywords": [
16 + "pi",
17 + "pi-extension",
18 + "rtk"
19 + ],
20 + "private": true

extensions/tune/__tests__/unit.test.ts

Modified
27 27 expect(html).toContain("th { position: sticky; top: var(--topbar-height);");
28 28 expect(html).not.toContain("th { position: sticky; top: 63px;");
31 + it("chooses the best dashboard run from kept runs only", () => {
32 + const html = fs.readFileSync(
33 + path.join(import.meta.dirname, "..", "assets", "template.html"),
34 + "utf8",
35 + );
37 + expect(html).toContain(
38 + 'state.runs.filter(r => r.status === "keep" && r.metric > 0)',
39 + );
40 + });
32 43 // ── Metric line parsing ───────────────────────────────────────────────────
131 +// ── Best metric ───────────────────────────────────────────────────────────
133 +describe("findBestMetric", () => {
134 + const { findBestMetric } = __test;
136 + it("ignores discarded runs", () => {
137 + expect(
138 + findBestMetric(
140 + { metric: 100, status: "keep", segment: 0 },
141 + { metric: 1, status: "discard", segment: 0 },
142 + { metric: 80, status: "keep", segment: 0 },
143 + ] as never,
144 + 0,
145 + "lower",
146 + ),
147 + ).toBe(80);
148 + });
149 +});
151 +// ── Tune prompt contracts ─────────────────────────────────────────────────
153 +describe("tune prompt contracts", () => {
154 + it("requires next action hints for dashboard and compaction", () => {
155 + expect(__test.LOG_ASI_GUIDELINE).toContain("next_action_hint");
156 + });
157 +});
120 159 // ── Number formatting ─────────────────────────────────────────────────────
122 161 describe("formatNum", () => {

extensions/tune/assets/template.html

Modified
475 - function bestRun() { return state.runs.filter(r => r.metric > 0).reduce((best, r) => !best || better(r.metric, best.metric) ? r : best, null); }
475 + function bestRun() { return state.runs.filter(r => r.status === "keep" && r.metric > 0).reduce((best, r) => !best || better(r.metric, best.metric) ? r : best, null); }
476 476 function better(a, b) { return state.config.bestDirection === "higher" ? a > b : a < b; }
477 477 function improvement(base, best) { if (!base || best == null) return null; return state.config.bestDirection === "higher" ? (best - base) / base * 100 : (base - best) / base * 100; }
478 478 function deltaPct(value, base) { return !base || value <= 0 ? null : (value - base) / base * 100; }

extensions/tune/index.ts

Modified
67 67 "run_experiment",
68 68 "log_experiment",
69 69 ] as const;
70 +const LOG_ASI_GUIDELINE =
71 + 'Always include asi with {"hypothesis": "what you tried", "next_action_hint": "what to try next"}.';
70 73 const TUNE_SUBCOMMAND_COMPLETIONS: AutocompleteItem[] = [
71 74 { value: "off", label: "off", description: "Turn tune mode off" },
1158 1161 keepVcsChanges,
1159 1162 discardVcsChanges,
1160 1163 readAutoResumeLimit,
1164 + findBestMetric,
1165 + LOG_ASI_GUIDELINE,
1163 1168 // ── Extension ─────────────────────────────────────────────────────────────
2275 2280 text += `✅ Checks passed in ${checksDuration.toFixed(1)}s\n`;
2278 - if (state.bestMetric !== null) {
2279 - text += `📊 Current best ${state.metricName}: ${formatNum(state.bestMetric, state.metricUnit)}\n`;
2283 + const bestMetric = findBestMetric(
2284 + state.results,
2285 + state.currentSegment,
2286 + state.bestDirection,
2287 + );
2288 + if (bestMetric !== null) {
2289 + text += `📊 Current best ${state.metricName}: ${formatNum(bestMetric, state.metricUnit)}\n`;
2282 2292 if (parsedMetrics) {
2468 2478 "Always call log_experiment after run_experiment.",
2469 2479 "log_experiment keeps changes on 'keep', discards changes on 'discard'/'crash'/'checks_failed' using the repo VCS.",
2470 2480 "Use status 'keep' if PRIMARY metric improved. 'discard' if worse. 'crash' if failed.",
2471 - 'Always include the asi parameter with at minimum {"hypothesis": "what you tried"}.',
2481 + LOG_ASI_GUIDELINE,
2473 2483 parameters: LogParams,

package-lock.json

Modified
297 297 "@earendil-works/pi-coding-agent": "*"
300 + "extensions/rtk": {
301 + "name": "@bugabinga/pi-ext-rtk",
302 + "license": "MIT",
303 + "devDependencies": {
304 + "@marcfargas/pi-test-harness": "^0.6.1",
305 + "vitest": "^4.1.8"
306 + },
307 + "peerDependencies": {
308 + "@earendil-works/pi-coding-agent": "*"
310 + },
300 311 "extensions/runtime": {
301 312 "name": "@bugabinga/pi-ext-runtime",
302 313 "license": "MIT",
1293 1304 "resolved": "extensions/quota",
1294 1305 "link": true
1307 + "node_modules/@bugabinga/pi-ext-rtk": {
1308 + "resolved": "extensions/rtk",
1309 + "link": true
1310 + },
1296 1311 "node_modules/@bugabinga/pi-ext-runtime": {
1297 1312 "resolved": "extensions/runtime",
1298 1313 "link": true