repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/rtk/index.ts
RawFile outline
- TIMEOUT_MS line 12
- COMMAND_PREFIX_END line 13
- MIN_MAJOR line 14
- MIN_MINOR line 15
- VersionTuple line 17
- ExecResult line 19
- RtkStatus line 26
- parseRtkVersion line 30
- supported line 36
- shouldSkipCommand line 42
- splitCommandPrefix line 49
- hasShellOperators line 62
- isFindRewrite line 66
- localFallbackRewrite line 70
- RewriteOutcome line 85
- rtkCommand line 90
- execRtk line 111
- execCode line 127
- code line 130
- exitCode line 131
- status line 132
- rewriteCommand line 139
- rtkStatus line 160
- supportsFindPath line 175
- notifyUser line 202
- ui line 212
- warnUnavailable line 228
- __test line 241
- rtk line 249
- generation line 254
- promise line 255
- ensureInitialized line 262
import { constants } from "node:fs";
import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { delimiter, join } from "node:path";
import type {
ExecOptions,
ExtensionAPI,
ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import { isToolCallEventType } from "@earendil-works/pi-coding-agent";
const TIMEOUT_MS = 2_000;
const COMMAND_PREFIX_END = "# pi-command-prefix-end\n";
const MIN_MAJOR = 0;
const MIN_MINOR = 23;
type VersionTuple = [number, number, number];
type ExecResult = {
code?: number | null;
stdout?: string;
stderr?: string;
killed?: boolean;
};
type RtkStatus =
| { ok: true }
| { ok: false; reason: "missing" | "old"; version?: string };
export function parseRtkVersion(text: string): VersionTuple | null {
const match = text.match(/(\d+)\.(\d+)\.(\d+)/);
if (!match) return null;
return [Number(match[1]), Number(match[2]), Number(match[3])];
}
function supported(version: VersionTuple | null): boolean {
if (version === null) return false;
const [major, minor] = version;
return major > MIN_MAJOR || (major === MIN_MAJOR && minor >= MIN_MINOR);
}
export function shouldSkipCommand(command: string): boolean {
const trimmed = command.trimStart();
if (trimmed.trim() === "") return true;
if (trimmed === "rtk" || trimmed.startsWith("rtk ")) return true;
return /^(?:env\s+)?RTK_DISABLED=1(?:\s|$)/u.test(trimmed);
}
export function splitCommandPrefix(command: string): {
prefix: string;
command: string;
} {
const end = command.indexOf(COMMAND_PREFIX_END);
if (end < 0) return { prefix: "", command };
const bodyStart = end + COMMAND_PREFIX_END.length;
return {
prefix: command.slice(0, bodyStart),
command: command.slice(bodyStart),
};
}
function hasShellOperators(command: string): boolean {
return /[|;<>`]|\$\(|&&|\|\|/u.test(command);
}
export function isFindRewrite(command: string): boolean {
return command === "rtk find" || command.includes("rtk find ");
}
export function localFallbackRewrite(command: string): string | undefined {
const trimmed = command.trim();
if (hasShellOperators(trimmed)) return undefined;
if (/^(journalctl|ps)(\s|$)/u.test(trimmed)) return `rtk summary ${trimmed}`;
if (/^systemctl\s+(?:--user\s+)?status(\s|$)/u.test(trimmed))
return `rtk summary ${trimmed}`;
if (
/^hyprctl\s+(clients|monitors|workspaces|activewindow|activeworkspace)(\s|$)/u.test(
trimmed,
)
)
return `rtk summary ${trimmed}`;
return undefined;
}
type RewriteOutcome =
| { kind: "rewrite"; command: string }
| { kind: "fallback" }
| { kind: "unchanged" };
async function rtkCommand(): Promise<string> {
if (process.platform !== "win32") return "rtk";
const pathKey = Object.keys(process.env).find(
(k) => k.toLowerCase() === "path",
);
const dirs = (pathKey ? process.env[pathKey] : "")?.split(delimiter) ?? [];
const exts = (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD")
.split(";")
.filter(Boolean);
for (const dir of dirs) {
for (const ext of exts) {
const candidate = join(dir, `rtk${ext.toLowerCase()}`);
try {
await access(candidate, constants.F_OK);
return candidate;
} catch {}
}
}
return "rtk";
}
async function execRtk(
pi: ExtensionAPI,
args: string[],
options?: ExecOptions,
): Promise<ExecResult> {
const command = await rtkCommand();
if (process.platform === "win32" && /\.(?:cmd|bat)$/iu.test(command)) {
return (await pi.exec(
process.env.ComSpec || process.env.COMSPEC || "cmd.exe",
["/d", "/c", "call", command, ...args],
options,
)) as ExecResult;
}
return (await pi.exec(command, args, options)) as ExecResult;
}
function execCode(error: unknown): number | null {
if (typeof error !== "object" || error === null) return null;
const maybe = error as {
code?: unknown;
exitCode?: unknown;
status?: unknown;
};
for (const value of [maybe.code, maybe.exitCode, maybe.status])
if (typeof value === "number") return value;
return null;
}
async function rewriteCommand(
pi: ExtensionAPI,
command: string,
signal?: AbortSignal,
): Promise<RewriteOutcome> {
try {
const result = await execRtk(pi, ["rewrite", command], {
timeout: TIMEOUT_MS,
signal,
});
if (result.killed) return { kind: "unchanged" };
if (result.code === 1) return { kind: "fallback" };
if (result.code !== 0 && result.code !== 3) return { kind: "unchanged" };
const rewritten = result.stdout?.trim();
if (!rewritten || rewritten === command) return { kind: "fallback" };
return { kind: "rewrite", command: rewritten };
} catch (error) {
return execCode(error) === 1 ? { kind: "fallback" } : { kind: "unchanged" };
}
}
async function rtkStatus(pi: ExtensionAPI): Promise<RtkStatus> {
try {
const result = await execRtk(pi, ["--version"], {
timeout: TIMEOUT_MS,
});
if (result.code !== 0) return { ok: false, reason: "missing" };
const text = (result.stdout ?? result.stderr ?? "").trim();
return supported(parseRtkVersion(text))
? { ok: true }
: { ok: false, reason: "old", version: text };
} catch {
return { ok: false, reason: "missing" };
}
}
async function supportsFindPath(pi: ExtensionAPI): Promise<boolean> {
const marker = "rtk-find-path-capability-marker";
let root: string | undefined;
try {
root = await mkdtemp(join(tmpdir(), "pi-rtk-find-"));
const nested = join(root, "nested");
await mkdir(nested);
await writeFile(join(nested, marker), "");
const result = await execRtk(
pi,
["find", root, "-path", `*nested/${marker}`],
{ timeout: TIMEOUT_MS },
);
const output = result.stdout ?? "";
return (
result.code === 0 &&
!result.killed &&
output.includes(marker) &&
!/^\s*0 for /u.test(output)
);
} catch {
return false;
} finally {
if (root) await rm(root, { force: true, recursive: true }).catch(() => {});
}
}
function notifyUser(
pi: ExtensionAPI,
ctx: ExtensionContext | undefined,
message: string,
): boolean {
try {
const notify = ctx?.hasUI
? ctx.ui.notify.bind(ctx.ui)
: (
pi as {
ui?: { notify?: (message: string, level: "warning") => void };
}
).ui?.notify;
if (!notify) return false;
notify(message, "warning");
return true;
} catch (error) {
if (
error instanceof Error &&
error.message.includes("ctx is stale after session replacement or reload")
)
return false;
throw error;
}
}
function warnUnavailable(
status: RtkStatus,
pi: ExtensionAPI,
ctx?: ExtensionContext,
): boolean {
if (status.ok) return false;
const suffix =
status.reason === "old"
? `too old (${status.version || "unknown"}); need >= 0.23.0`
: "not found on PATH";
return notifyUser(pi, ctx, `rtk disabled: ${suffix}`);
}
export const __test = {
isFindRewrite,
localFallbackRewrite,
parseRtkVersion,
shouldSkipCommand,
splitCommandPrefix,
};
export default function rtk(pi: ExtensionAPI) {
let generation = 0;
let announced = false;
let initialization:
| {
generation: number;
promise: Promise<{
status: RtkStatus;
findPathSupported: boolean;
}>;
}
| undefined;
const ensureInitialized = async (ctx: ExtensionContext) => {
if (initialization?.generation !== generation) {
const ticket = generation;
const promise = (async () => {
const status = await rtkStatus(pi);
return {
status,
findPathSupported: status.ok ? await supportsFindPath(pi) : false,
};
})();
initialization = { generation: ticket, promise };
}
const ticket = initialization.generation;
const support = await initialization.promise;
if (ticket !== generation) return undefined;
if (!announced) {
announced = support.status.ok
? notifyUser(
pi,
ctx,
support.findPathSupported
? "rtk find -path works: remove the compatibility guard"
: "rtk find rewrites disabled: -path semantics unsupported",
)
: warnUnavailable(support.status, pi, ctx);
}
return support;
};
pi.on("session_start", () => {
generation++;
announced = false;
initialization = undefined;
});
pi.on("session_shutdown", () => {
generation++;
announced = false;
initialization = undefined;
});
pi.on("tool_call", async (event, ctx) => {
if (!isToolCallEventType("bash", event)) return;
const support = await ensureInitialized(ctx);
if (!support?.status.ok) return;
const framed = splitCommandPrefix(event.input.command);
if (shouldSkipCommand(framed.command)) return;
const outcome = await rewriteCommand(pi, framed.command, ctx.signal);
const rewritten =
outcome.kind === "rewrite"
? outcome.command
: outcome.kind === "fallback"
? localFallbackRewrite(framed.command)
: undefined;
if (rewritten && (support.findPathSupported || !isFindRewrite(rewritten)))
event.input.command = framed.prefix + rewritten;
});
}