import { execSync, spawn } from "child_process";
const HOME = process.env.HOME || process.env.USERPROFILE || "";
const SQUEEZ_BIN = `${HOME}/.claude/squeez/bin/squeez`;
const BUDGET_TOOL_SLUG = {
read: "Read",
grep: "Grep",
};
function squeezExists() {
try {
execSync(`test -x "${SQUEEZ_BIN}"`, { timeout: 500 });
return true;
} catch {
return false;
}
}
function runInit() {
try {
execSync(`"${SQUEEZ_BIN}" init --host=opencode`, { timeout: 5000 });
} catch {
}
}
function budgetPatch(tool) {
const slug = BUDGET_TOOL_SLUG[tool];
if (!slug) return null;
try {
const out = execSync(`"${SQUEEZ_BIN}" budget-params ${slug}`, {
timeout: 2000,
encoding: "utf8",
}).trim();
if (!out) return null;
return JSON.parse(out);
} catch {
return null;
}
}
function trackResult(tool) {
try {
spawn(SQUEEZ_BIN, ["track-result", tool], {
stdio: "ignore",
detached: true,
}).unref();
} catch {
}
}
export const SqueezPlugin = async (ctx) => {
if (!squeezExists()) {
return;
}
ctx.hook?.("session.created", async () => {
runInit();
});
ctx.hook?.("tool.execute.before", async (input, output) => {
if (!input || !output || !output.args) return;
if (input.tool === "bash") {
const command = output.args.command;
if (!command || typeof command !== "string") return;
if (command.startsWith(SQUEEZ_BIN)) return;
if (command.includes("squeez wrap")) return;
if (command.startsWith("--no-squeez")) return;
output.args.command = `${SQUEEZ_BIN} wrap ${command}`;
return;
}
const patch = budgetPatch(input.tool);
if (!patch) return;
for (const [k, v] of Object.entries(patch)) {
if (output.args[k] === undefined) {
output.args[k] = v;
}
}
});
ctx.hook?.("tool.execute.after", async (input) => {
if (!input || !input.tool) return;
if (["bash", "read", "grep", "glob"].includes(input.tool)) {
trackResult(input.tool);
}
});
};