import { readFileSync } from "node:fs"; import { dirname, extname, join, resolve } from "node:path"; import type { CustomMessageEntryDraft, TurnEndEvent, TurnEndEventResult, } from "@earendil-works/pi-coding-agent"; import { getAgentDir } from "@earendil-works/pi-coding-agent"; // --- Configuration --- /** Name of the user-level config file inside the agent config directory. */ export const AUTO_CHECK_CONFIG_FILE = "pi-lsp.json"; /** User-level config file shape. */ export interface LspConfig { /** Opt-in: absent/false keeps auto-check off, true enables it. */ autoCheckBeforeReply?: boolean; } /** * Auto-check before reply: when Pi wraps up a turn having modified code * without a diagnostics check since, nudge it to call lsp_checks. Disabled * by default; enable via ~/.pi/agent/pi-lsp.json ("autoCheckBeforeReply": * true) or the PI_LSP_AUTO_CHECK environment variable, which overrides the * file. */ export function autoCheckEnabled(envValue: string): boolean { if (envValue.trim() === "") return false; return !["0", "false", "off", "no"].includes(envValue.trim().toLowerCase()); } /** * Read autoCheckBeforeReply from the user-level config file. Missing file, * missing field, or unreadable/broken file all mean "use the default" * (disabled) — a broken config must not silently enable the feature or * break event handlers. */ export function readAutoCheckConfig(agentDir?: string): boolean { const filePath = join(agentDir ?? getAgentDir(), AUTO_CHECK_CONFIG_FILE); try { const raw = readFileSync(filePath, "utf8").replace(/^\uFEFF/, ""); const config = JSON.parse(raw) as LspConfig; return config.autoCheckBeforeReply === true; } catch { return false; } } /** * Combined setting: the PI_LSP_AUTO_CHECK environment variable (explicit * values only) overrides the config file; otherwise the config file decides; * otherwise disabled. */ export function resolveAutoCheckEnabled(options?: { agentDir?: string; envValue?: string; }): boolean { const envValue = options?.envValue ?? process.env.PI_LSP_AUTO_CHECK; if (envValue !== undefined && envValue.trim() !== "") { return autoCheckEnabled(envValue); } return readAutoCheckConfig(options?.agentDir); } // --- Tool sets --- // Tools whose successful execution lands code changes on disk. bash is // deliberately absent: its command line does not name edited files reliably. export const EDIT_TOOL_NAMES: ReadonlySet = new Set([ "write", // pi built-in "edit", // pi built-in "ide_webstorm_apply_patch", "ide_webstorm_create_new_file", "ide_webstorm_rename_refactoring", "ide_webstorm_reformat_file", "ide_webstorm_optimize_imports", "lsp_fix", // this extension's fix tool ]); // Tools that count as "the agent checked diagnostics" and settle the nudger. export const CHECK_TOOL_NAMES: ReadonlySet = new Set([ "lsp_checks", "lsp_diagnostics", ]); /** Stop nudging after this many consecutive un-heeded reminders. */ export const MAX_CONSECUTIVE_AUTO_CHECKS = 3; export const AUTO_CHECK_CUSTOM_TYPE = "lsp-auto-check"; export const MAX_LISTED_FILES = 5; // --- Path extraction --- const APPLY_PATCH_HEADER = /^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm; const APPLY_PATCH_MOVE_TO = /^\*\*\* Move to: (.+)$/gm; const UNIFIED_DIFF_TARGET = /^\+\+\+ (?!\/dev\/null)(?:[ab]\/)?(.+)$/gm; /** * Best-effort extraction of the file paths a tool call is about to modify, * from the tool's input. For renames both the old and the new path are * returned (the new path also needs a check). Returns [] when nothing * recognizable is present. */ export function editedPathsFromInput( toolName: string, input: unknown, ): string[] { if (typeof input !== "object" || input === null) return []; const record = input as Record; const paths: string[] = []; collectString(record, "path", paths); collectString(record, "filePath", paths); collectString(record, "pathInProject", paths); collectString(record, "file_path", paths); collectStringArray(record, "paths", paths); collectStringArray(record, "files", paths); if ( toolName === "ide_webstorm_rename_refactoring" && typeof record.newName === "string" && record.newName.length > 0 && typeof record.pathInProject === "string" ) { paths.push(join(dirname(record.pathInProject), record.newName)); } const patch = record.patch ?? record.input; if (typeof patch === "string") extractPatchPaths(patch, paths); return [...new Set(paths.filter((p) => p.length > 0))]; } function collectString( record: Record, key: string, out: string[], ) { const value = record[key]; if (typeof value === "string") out.push(value); } function collectStringArray( record: Record, key: string, out: string[], ) { const value = record[key]; if (!Array.isArray(value)) return; for (const item of value) { if (typeof item === "string") out.push(item); } } function extractPatchPaths(patch: string, out: string[]) { for (const match of patch.matchAll(APPLY_PATCH_HEADER)) { out.push(match[1].trim()); } // A moved file ends up under the new path; both old (Update File) and // new (Move to) paths deserve a check. for (const match of patch.matchAll(APPLY_PATCH_MOVE_TO)) { out.push(match[1].trim()); } for (const match of patch.matchAll(UNIFIED_DIFF_TARGET)) { out.push(match[1].trim()); } } /** * Paths a check tool is asked to look at, from its input. `undefined` means * "no paths restriction" — the tool collects across the whole workspace. */ function checkPathsFromInput(input: unknown): string[] | undefined { if (typeof input !== "object" || input === null) return undefined; const record = input as Record; const requested: string[] = []; collectString(record, "path", requested); collectString(record, "filePath", requested); collectStringArray(record, "paths", requested); const unique = [...new Set(requested.filter((p) => p.length > 0))]; return unique.length > 0 ? unique : undefined; } // --- Path keys --- const CASE_INSENSITIVE_PATHS = process.platform === "win32"; /** * Normalized comparison key for a path: absolute, forward slashes, and * (on Windows) case-folded. Relative inputs resolve against cwd. */ export function normalizePathKey(filePath: string, cwd: string): string { const key = resolve(cwd, filePath).replace(/\\/g, "/"); return CASE_INSENSITIVE_PATHS ? key.toLowerCase() : key; } // --- Tracker --- interface ToolCallShape { toolCallId: string; toolName: string; input?: unknown; } interface ToolExecutionEndShape { toolCallId: string; toolName: string; isError: boolean; } interface ArmedEdit { /** Display paths, shown in the reminder message. */ paths: string[]; } interface ArmedCheck { /** * Pending keys at call time. Only these can be settled by this check, so * edits landing while the check runs (parallel tool execution) stay due. */ snapshot: Set; /** Restricted scope (normalized); undefined means the whole workspace. */ paths?: Set; } /** * Per-session state for the edit-follow-up check. Edits arm on tool_call * (where input is available), commit on successful tool_execution_end, and * are settled by a successful check tool or consumed by a wrap-up-turn * reminder. */ export class AutoCheckTracker { /** toolCallId -> edit paths, awaiting the tool's execution outcome. */ private armedEdits = new Map(); /** toolCallId -> check scope snapshot, awaiting the tool's outcome. */ private armedChecks = new Map(); /** Normalized key -> display path, changed since the last settling check. */ private pending = new Map(); /** Reminders issued since the last settling check or the last user input. */ private consecutive = 0; /** * File extensions the current check routes can actually examine (LSP * adapters + CLI runners). When set, files outside the set are not * tracked — editing a README must not trigger a code check that can * never say anything about it. Undefined means "track everything". */ private supportedExtensions?: ReadonlySet; setSupportedExtensions(extensions: ReadonlySet): void { this.supportedExtensions = extensions; } onToolCall(event: ToolCallShape, cwd: string): void { if (EDIT_TOOL_NAMES.has(event.toolName)) { const paths = editedPathsFromInput(event.toolName, event.input); if (paths.length > 0) { this.armedEdits.set(event.toolCallId, { paths }); } return; } if (CHECK_TOOL_NAMES.has(event.toolName)) { const requested = checkPathsFromInput(event.input); this.armedChecks.set(event.toolCallId, { snapshot: new Set(this.pending.keys()), paths: requested ? new Set(requested.map((p) => normalizePathKey(p, cwd))) : undefined, }); } } onToolExecutionEnd(event: ToolExecutionEndShape, cwd: string): void { if (CHECK_TOOL_NAMES.has(event.toolName)) { const armedCheck = this.armedChecks.get(event.toolCallId); this.armedChecks.delete(event.toolCallId); if (!event.isError && armedCheck) this.settleCheck(armedCheck); return; } const armedEdit = this.armedEdits.get(event.toolCallId); this.armedEdits.delete(event.toolCallId); if (!armedEdit || event.isError) return; for (const filePath of armedEdit.paths) { if (this.supportedExtensions && !this.isTrackable(filePath)) continue; this.pending.set(normalizePathKey(filePath, cwd), filePath); } } private isTrackable(filePath: string): boolean { const extension = extname(filePath).toLowerCase(); return ( extension.length > 0 && (this.supportedExtensions?.has(extension) ?? true) ); } /** * Settle only what the check actually covered: the intersection of its * call-time snapshot and (when given) its requested paths. The reminder * streak resets too — a successful check means the agent is listening. */ private settleCheck(armedCheck: ArmedCheck): void { for (const key of armedCheck.snapshot) { if (armedCheck.paths && !armedCheck.paths.has(key)) continue; this.pending.delete(key); } this.consecutive = 0; } /** * A new user message starts a fresh tolerance window for reminders. * Pending edits stay due — they still have not been checked. */ onUserInput(): void { this.consecutive = 0; } /** * Nudge on a completed wrap-up turn (no tool results — the assistant * answered without calling tools) that leaves un-checked edits behind. * Returns the turn_end handler result, or undefined to stay silent. */ onTurnEnd(event: TurnEndEvent): TurnEndEventResult | undefined { if (event.outcome !== "completed") return undefined; // A turn that executed tools is still mid-work; only a wrap-up turn // means "Pi considers its code changes done". if (event.toolResults.length > 0) return undefined; if (this.pending.size === 0) return undefined; if (this.consecutive >= MAX_CONSECUTIVE_AUTO_CHECKS) return undefined; const files = [...this.pending.values()]; this.pending.clear(); this.consecutive++; const draft: CustomMessageEntryDraft = { type: "custom_message", customType: AUTO_CHECK_CUSTOM_TYPE, display: true, content: buildReminderMessage(files), }; return { entries: [...event.entries, draft], continue: true }; } /** Drop all state (session start/shutdown). */ reset(): void { this.armedEdits.clear(); this.armedChecks.clear(); this.pending.clear(); this.consecutive = 0; } } function buildReminderMessage(files: string[]): string { const shown = files.slice(0, MAX_LISTED_FILES); const rest = files.length - shown.length; const list = [ ...shown.map((filePath) => `- ${filePath}`), ...(rest > 0 ? [`- …and ${rest} more`] : []), ].join("\n"); return [ "[pi-lsp] Code changed since the last diagnostics check:", list, "", "Call the lsp_checks tool on these files now. If it reports issues, fix them (lsp_fix or further edits) — new edits will be checked again on your next wrap-up. If no check is needed, briefly say why and continue.", ].join("\n"); }