repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/verboten/index.ts
RawFile outline
- ENTRY_TYPE line 23
- INSTRUCTION line 24
- RuntimeState line 33
- cache line 34
- initialState line 37
- humanWarning line 53
- ruleList line 69
- directBlockReason line 73
- shellBlockReason line 85
- cdata line 94
- systemPrompt line 98
- protectedPathRules line 105
- GrepRow line 129
- line line 130
- path line 131
- grepRow line 134
- grepBase line 139
- filterGrepResult line 153
- type line 187
- type line 212
- formatReport line 221
- verboten line 253
- text line 258
- path line 294
- tool line 294
- command line 324
- __test line 383
import { stat } from "node:fs/promises";
import path from "node:path";
import type {
ExtensionAPI,
ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import {
isGrepToolResult,
isToolCallEventType,
} from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
import { blocks, judgeCommand, VerdictCache } from "./src/judge.ts";
import {
buildBuiltinRules,
type LoadedVerbotenSettings,
lexicalCandidates,
loadVerbotenSettings,
matchingRules,
matchPath,
type VerbotenRule,
} from "./src/rules.ts";
const ENTRY_TYPE = "verboten-report-v1";
const INSTRUCTION = `Never expose protected-file contents, encodings, hashes, or copies to model context or tool output, directly or through a bypass.
Never create, modify, delete, rename, copy, execute, encode, or transmit protected files.
Trusted programs, hooks, filters, and credential helpers may consume protected files internally when they neither expose protected data nor mutate protected files.
Metadata-only listing, finding, status, stat, and existence checks are allowed.
Broad grep searches rooted outside a protected path are allowed; Verboten filters protected rows.
Mere textual mentions and exclusion patterns are allowed.
Never bypass Verboten through shells, symlinks, alternate tools, encoding, or delegation to expose or target protected files.
Reformulate a false positive only when the new operation avoids protected content and mutation.`;
interface RuntimeState extends LoadedVerbotenSettings {
cache: VerdictCache;
}
function initialState(): RuntimeState {
let rules: VerbotenRule[] = [];
try {
rules = buildBuiltinRules();
} catch {
// Session startup retries complete initialization and reports failures.
}
return {
rules,
judgeModel: null,
warnings: [],
projectIgnored: false,
cache: new VerdictCache(),
};
}
function humanWarning(
ctx: ExtensionContext,
reported: Set<string>,
key: string,
message: string,
): void {
if (reported.has(key)) return;
reported.add(key);
try {
if (ctx.hasUI) ctx.ui.notify(message, "warning");
else console.error(`[verboten] ${message.replace(/\s+/g, " ")}`);
} catch {
// Diagnostics never alter protection behavior.
}
}
function ruleList(rules: readonly VerbotenRule[]): string {
return rules.map((rule) => `/${rule.pattern}/iu`).join(", ");
}
function directBlockReason(
tool: string,
rules: readonly VerbotenRule[],
): string {
return [
`Verboten blocked ${tool}: protected content reads and protected-path mutations are forbidden.`,
`Matched: ${ruleList(rules)}.`,
"Do not bypass through shells, alternate tools, symlinks, encoding, or delegation.",
"Retry only against a non-protected target if this was a false positive.",
].join(" ");
}
function shellBlockReason(probability: number, reason: string): string {
return [
`Verboten blocked this command at ${Math.round(probability * 100)}%: ${reason}.`,
"This may be a false positive.",
"Do not bypass protected content or mutation.",
"If the operation is metadata-only or a mere mention, state that clearly and retry.",
].join(" ");
}
function cdata(value: string): string {
return value.replaceAll("]]>", "]]]]><![CDATA[>");
}
export function systemPrompt(rules: readonly VerbotenRule[]): string {
const patterns = rules
.map((rule) => ` <pattern><![CDATA[${cdata(rule.pattern)}]]></pattern>`)
.join("\n");
return `${INSTRUCTION}\n\n<verboten_paths>\n${patterns}\n</verboten_paths>`;
}
async function protectedPathRules(
rawPath: string,
ctx: ExtensionContext,
rules: readonly VerbotenRule[],
reported: Set<string>,
): Promise<VerbotenRule[]> {
try {
return (await matchPath(rawPath, ctx.cwd, rules)).matches;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
humanWarning(
ctx,
reported,
`realpath:${message}`,
`Verboten could not resolve a filesystem alias: ${message}; lexical protection remains active`,
);
const found = new Map<string, VerbotenRule>();
for (const candidate of lexicalCandidates(rawPath, ctx.cwd))
for (const rule of matchingRules(candidate, rules))
found.set(`${rule.group}\0${rule.pattern}`, rule);
return [...found.values()];
}
}
interface GrepRow {
line: string;
path?: string;
}
function grepRow(line: string): GrepRow {
const match = /^(.+?)(?::\d+:|-\d+-) /.exec(line);
return { line, path: match?.[1] };
}
async function grepBase(inputPath: unknown, cwd: string): Promise<string> {
const searchPath = path.resolve(
cwd,
typeof inputPath === "string" ? inputPath : ".",
);
try {
return (await stat(searchPath)).isDirectory()
? searchPath
: path.dirname(searchPath);
} catch {
return searchPath;
}
}
async function filterGrepResult(
event: Parameters<typeof isGrepToolResult>[0],
ctx: ExtensionContext,
rules: readonly VerbotenRule[],
reported: Set<string>,
) {
if (!isGrepToolResult(event)) return undefined;
const base = await grepBase(event.input.path, ctx.cwd);
let omitted = 0;
const content: typeof event.content = [];
for (const part of event.content) {
if (part.type !== "text") {
content.push(part);
continue;
}
const rows = part.text.split("\n").map(grepRow);
const kept: string[] = [];
for (const row of rows) {
if (!row.path) {
kept.push(row.line);
continue;
}
const source = path.isAbsolute(row.path)
? row.path
: path.resolve(base, row.path);
const matches = await protectedPathRules(source, ctx, rules, reported);
if (matches.length > 0) omitted++;
else kept.push(row.line);
}
content.push({ ...part, text: kept.join("\n") });
}
if (omitted === 0) return undefined;
const survivingRows = content
.filter(
(part): part is Extract<typeof part, { type: "text" }> =>
part.type === "text",
)
.flatMap((part) => part.text.split("\n"))
.filter((line) => grepRow(line).path !== undefined);
const notice = `Verboten omitted ${omitted} protected grep line${omitted === 1 ? "" : "s"}.`;
if (survivingRows.length === 0) {
const windowConsumed = Boolean(
event.details?.matchLimitReached || event.details?.truncation?.truncated,
);
return {
content: [
{
type: "text" as const,
text: windowConsumed
? `${notice} Protected hits consumed the result window; retry with a narrower path or glob.`
: notice,
},
],
isError: windowConsumed,
};
}
const lastText = [...content]
.reverse()
.find(
(part): part is Extract<typeof part, { type: "text" }> =>
part.type === "text",
);
if (lastText)
lastText.text = `${lastText.text.replace(/\s+$/, "")}\n\n${notice}`;
else content.push({ type: "text", text: notice });
return { content };
}
function formatReport(state: RuntimeState, ctx: ExtensionContext): string {
const effectiveModel =
state.judgeModel ??
(ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "unavailable");
const lines = [
"Verboten blocks protected content and mutation; metadata-only operations remain allowed.",
`Judge: ${effectiveModel}`,
];
const groups: Array<VerbotenRule["group"]> = [
"built-in static",
"built-in resolved",
"global setting",
"project setting",
];
for (const group of groups) {
const members = state.rules.filter((rule) => rule.group === group);
if (members.length === 0) continue;
lines.push("", `${group}:`);
for (const rule of members) {
lines.push(`- ${rule.label}: /${rule.pattern}/iu`);
if (rule.original) lines.push(` from ${rule.original}`);
}
}
if (state.projectIgnored)
lines.push("", "project settings ignored: untrusted");
if (state.warnings.length > 0) {
lines.push("", "skipped settings:");
for (const warning of state.warnings) lines.push(`- ${warning.message}`);
}
return lines.join("\n");
}
export default function verboten(pi: ExtensionAPI) {
let state = initialState();
const reported = new Set<string>();
pi.registerEntryRenderer(ENTRY_TYPE, (entry, _options, theme) => {
const data = entry.data as { text?: unknown };
return new Text(
theme.fg(
"customMessageText",
typeof data.text === "string"
? data.text
: "Verboten report unavailable",
),
1,
0,
);
});
pi.on("session_start", (_event, ctx) => {
try {
const loaded = loadVerbotenSettings(ctx.cwd, ctx.isProjectTrusted());
state = { ...loaded, cache: new VerdictCache() };
for (const warning of loaded.warnings)
humanWarning(ctx, reported, warning.key, warning.message);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
humanWarning(
ctx,
reported,
"startup",
`Verboten settings failed: ${message}; built-in rules remain active`,
);
state = { ...initialState(), cache: new VerdictCache() };
}
});
pi.on("before_agent_start", (event) => ({
systemPrompt: `${event.systemPrompt}\n\n${systemPrompt(state.rules)}`,
}));
pi.on("tool_call", async (event, ctx) => {
let direct: { tool: string; path: string } | undefined;
if (isToolCallEventType("read", event))
direct = { tool: "read", path: event.input.path };
else if (isToolCallEventType("write", event))
direct = { tool: "write", path: event.input.path };
else if (isToolCallEventType("edit", event))
direct = { tool: "edit", path: event.input.path };
else if (isToolCallEventType("grep", event))
direct = { tool: "grep", path: event.input.path ?? "." };
if (direct) {
const matches = await protectedPathRules(
direct.path,
ctx,
state.rules,
reported,
);
if (matches.length > 0)
return {
block: true,
reason: directBlockReason(direct.tool, matches),
};
return;
}
let shell: "bash" | "powershell" | undefined;
let command: string | undefined;
if (isToolCallEventType("bash", event)) {
shell = "bash";
command = event.input.command;
} else if (
isToolCallEventType<"powershell", { command: string }>(
"powershell",
event,
)
) {
shell = "powershell";
command = event.input.command;
}
if (!shell || command === undefined) return;
const matches = matchingRules(command, state.rules);
if (matches.length === 0) return;
const result = await judgeCommand(
ctx,
{
shell,
cwd: ctx.cwd,
command,
matchedRules: matches,
configuredModel: state.judgeModel,
},
state.cache,
(key, message) => humanWarning(ctx, reported, key, message),
);
if (result.type === "cancelled")
return {
block: true,
reason: "Verboten blocked the cancelled judgment.",
};
if (result.type === "verdict" && blocks(result.verdict))
return {
block: true,
reason: shellBlockReason(
result.verdict.forbiddenOperationProbability,
result.verdict.reason,
),
};
return;
});
pi.on("tool_result", async (event, ctx) =>
filterGrepResult(event, ctx, state.rules, reported),
);
pi.registerCommand("verboten", {
description: "Show effective protected path rules and judge model",
handler: async (args, ctx) => {
if (args.trim()) {
const message = "Usage: /verboten";
if (ctx.hasUI) ctx.ui.notify(message, "warning");
else console.error(message);
return;
}
const text = formatReport(state, ctx);
if (ctx.mode === "tui") pi.appendEntry(ENTRY_TYPE, { text });
else console.log(text);
},
});
}
export const __test = {
ENTRY_TYPE,
INSTRUCTION,
directBlockReason,
filterGrepResult,
formatReport,
grepRow,
shellBlockReason,
};