diff --git a/.pi/extensions/index.ts b/.pi/extensions/index.ts index 55a88892b..d6f5f66bf 100644 --- a/.pi/extensions/index.ts +++ b/.pi/extensions/index.ts @@ -29,6 +29,7 @@ import * as fs from "node:fs" import * as os from "node:os" import * as path from "node:path" import { resolveHookRuntime } from "./hook-runtime.js" +import { createCommandBodyReader, handlePiInputEvent } from "./input-args.js" /** * Minimal structural types mirroring `@earendil-works/pi-coding-agent`. @@ -70,7 +71,18 @@ interface BeforeAgentStartResult { systemPrompt?: string } +interface PiSlashCommandInfo { name: string; source: "extension" | "prompt" | "skill"; sourceInfo: { path: string } } + +interface InputEvent { text: string; source: "interactive" | "rpc" | "extension"; streamingBehavior?: "steer" | "followUp" } + +type InputEventResult = { action: "continue" } | { action: "transform"; text: string } + interface ExtensionAPI { + getCommands(): PiSlashCommandInfo[] + on( + event: "input", + handler: (event: InputEvent, ctx: ExtensionContext) => Promise | InputEventResult + ): void on( event: "session_start", handler: (event: SessionStartEvent, ctx: ExtensionContext) => Promise | void @@ -670,7 +682,17 @@ function buildDoctorReport(ctx: ExtensionContext): string { return lines.join("\n") } +const getCommandBody = createCommandBodyReader(ECC_ROOT) + export default function (pi: ExtensionAPI): void { + pi.on("input", event => + handlePiInputEvent(event, pi, { + eccRoot: ECC_ROOT, + env: process.env, + getBody: getCommandBody, + }) + ) + /** * ECC's SessionStart hook returns context for the model, but Pi has no * equivalent of Claude Code's `additionalContext` field. It is held here and @@ -753,6 +775,9 @@ export default function (pi: ExtensionAPI): void { pi.registerCommand("ecc-doctor", { description: "Report ECC adapter status: package root, canonical resources, hooks, companions", handler: async (_args, ctx) => { +// No deliverAs: "nextTurn" here. In Pi 1.x that queues the message until + // the user's next prompt, so the report never appears when the command runs. + // Explicitly suppress a model turn while displaying the report now. pi.sendMessage( { customType: "ecc-doctor", diff --git a/.pi/extensions/input-args.js b/.pi/extensions/input-args.js new file mode 100644 index 000000000..a1b93bf8b --- /dev/null +++ b/.pi/extensions/input-args.js @@ -0,0 +1,163 @@ +const fs = require("node:fs") +const path = require("node:path") + +/** + * Same placeholder set Pi's `substituteArgs` understands. + * + * Pi expands every form below, so a command body containing any of them must + * be left for Pi to expand rather than treated as placeholder-less: + * $ARGUMENTS, $@, $1, ${1:-default}, ${@:N}, ${@:N:L} + */ +const ARG_PLACEHOLDER = /\$\{(\d+|ARGUMENTS|@):-[^}]*\}|\$\{@:\d+(?::\d+)?\}|\$(ARGUMENTS|@|\d+)/ + +/** Values ECC treats as "off" across its existing environment switches. */ +const DISABLED_VALUES = new Set(["0", "false", "off", "none", "disabled"]) + +function isDisabledByEnv(value) { + return typeof value === "string" && DISABLED_VALUES.has(value.trim().toLowerCase()) +} + +function stripFrontmatter(raw) { + return raw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim() +} + +/** + * Body of an ECC command that has NO argument placeholder, or null. + * + * Claude Code appends `ARGUMENTS: ` when a command lacks `$ARGUMENTS`; + * Pi's template expansion silently drops the arguments instead. Most ECC + * commands rely on the Claude behaviour, so the adapter restores it. + */ +function loadPlaceholderlessCommand(name, eccRoot, commandPath, reportReadError = message => console.warn(message)) { + if (!/^[A-Za-z0-9._-]+$/.test(name)) { + return null + } + + const resolvedPath = commandPath || path.join(eccRoot, "commands", `${name}.md`) + try { + const raw = fs.readFileSync(resolvedPath, "utf8") + const stripped = stripFrontmatter(raw) + return ARG_PLACEHOLDER.test(stripped) ? null : stripped + } catch (error) { + const detail = error && error.message ? error.message : String(error) + reportReadError(`[ecc-pi] unable to read command ${resolvedPath}: ${detail}`) + return null + } +} + +/** + * Returns the canonical ECC command path only when Pi's active prompt for + * `name` resolves to ECC's canonical `commands/.md`. + * + * The input event fires before Pi expands prompt templates and does not expose + * the selected template directly. `pi.getCommands()` does expose the active + * prompt list (including source metadata), so this is the provenance check + * that keeps ECC from overriding a disabled, differently resolved, or + * extension-registered command with the same name. + */ +function activeEccPromptPath(name, eccRoot, activeCommands) { + if (!/^[A-Za-z0-9._-]+$/.test(name)) { + return null + } + + const activePrompt = (activeCommands || []).find( + command => command && command.name === name && command.source === "prompt" + ) + if (!activePrompt || !activePrompt.sourceInfo) { + return null + } + + const expectedPath = path.resolve(path.join(eccRoot, "commands", `${name}.md`)) + if (path.resolve(activePrompt.sourceInfo.path || "") !== expectedPath) { + return null + } + return expectedPath +} + +/** + * Pi input-handler transform shared by the TypeScript extension and tests. + * + * Keep this in a CommonJS module so the real registered handler can be loaded + * and exercised by the plain Node test suite; the extension itself delegates + * directly to this function. + */ +function handlePiInput({ text, eccRoot, env, activeCommands, getBody }) { + if (isDisabledByEnv(env.ECC_PI_COMMAND_ARGS)) { + return { action: "continue" } + } + + const match = text.match(/^\/([^\s:]+)\s+([\s\S]*\S[\s\S]*)$/) + if (!match) { + return { action: "continue" } + } + + const commandPath = activeEccPromptPath(match[1], eccRoot, activeCommands) + if (!commandPath) { + return { action: "continue" } + } + + const body = getBody + ? getBody(match[1], commandPath) + : loadPlaceholderlessCommand(match[1], eccRoot, commandPath) + if (!body) { + return { action: "continue" } + } + + return { action: "transform", text: `${body}\n\nARGUMENTS: ${match[2].trim()}` } +} + +/** + * The real Pi input-event callback the TypeScript extension registers. + * + * Extracted here (rather than being an anonymous arrow in index.ts) so the + * plain Node test suite can invoke the exact registered handler with a fake + * `pi` object and assert both its guard branches and its transform result. + */ +function handlePiInputEvent(event, pi, options) { + if ( + !event || + event.source === "extension" || + event.streamingBehavior === "steer" || + typeof pi.getCommands !== "function" + ) { + return { action: "continue" } + } + + return handlePiInput({ + text: event.text, + eccRoot: options.eccRoot, + env: options.env, + activeCommands: pi.getCommands(), + getBody: options.getBody, + }) +} + +/** + * Creates a body reader with its own cache. + * + * The returned function returns a fresh Map on each new lookup rather than + * mutating the previous cache, satisfying ECC's immutability rule. + */ +function createCommandBodyReader(eccRoot, reportReadError) { + let cache = new Map() + return name => { + if (cache.has(name)) { + return cache.get(name) ?? null + } + const body = loadPlaceholderlessCommand(name, eccRoot, undefined, reportReadError) + cache = new Map(cache).set(name, body) + return body + } +} + +module.exports = { + ARG_PLACEHOLDER, + DISABLED_VALUES, + isDisabledByEnv, + stripFrontmatter, + loadPlaceholderlessCommand, + createCommandBodyReader, + activeEccPromptPath, + handlePiInput, + handlePiInputEvent, +} diff --git a/tests/pi/pi-extension-adapter.test.js b/tests/pi/pi-extension-adapter.test.js index deb74c4db..c1972cf27 100644 --- a/tests/pi/pi-extension-adapter.test.js +++ b/tests/pi/pi-extension-adapter.test.js @@ -50,6 +50,15 @@ const { spawnSync, execFile } = require("child_process") const { resolveHookRuntime } = require( path.join(__dirname, "..", "..", ".pi", "extensions", "hook-runtime.js") ) +const { + ARG_PLACEHOLDER, + loadPlaceholderlessCommand, + createCommandBodyReader, + handlePiInput, + handlePiInputEvent, +} = require( + path.join(__dirname, "..", "..", ".pi", "extensions", "input-args.js") +) /** Run a single adapter test and report the result. */ async function runTest(name, fn) { @@ -113,6 +122,7 @@ function buildEccSkeleton(repoRoot) { "hook-input.js", "hook-input-limits.js", "run-with-flags.js", + "hook-watchdog.js", "session-end-marker.js", "pretooluse-visible-output.js", ]) { @@ -354,6 +364,14 @@ async function main() { const repoRoot = path.join(__dirname, "..", "..") const extensionPath = path.join(repoRoot, ".pi", "extensions", "index.ts") const extensionSource = fs.readFileSync(extensionPath, "utf8") + const inputArgsPath = path.join(repoRoot, ".pi", "extensions", "input-args.js") + const inputArgsSource = fs.readFileSync(inputArgsPath, "utf8") + + const eccPrompt = name => ({ + name, + source: "prompt", + sourceInfo: { path: path.join(repoRoot, "commands", `${name}.md`) }, + }) const tests = [ // ---- Group 1: source contract ------------------------------------- @@ -548,8 +566,8 @@ async function main() { __dirname: path.resolve(repoRoot, ".pi", "extensions"), process, require: name => { - if (name === "./hook-runtime.js") { - return require(path.resolve(repoRoot, ".pi", "extensions", "hook-runtime.js")) + if (name === "./hook-runtime.js" || name === "./input-args.js") { + return require(path.resolve(repoRoot, ".pi", "extensions", name)) } return require(name) }, @@ -1725,6 +1743,339 @@ async function main() { "systemPrompt-override return in before_agent_start" ) }], + + ["registers the Pi input event and delegates to the testable input-args module", () => { + assert.ok( + extensionSource.includes('pi.on("input"'), + "expected .pi/extensions/index.ts to register an input handler via pi.on(...); " + + "Pi runs input handlers before prompt-template expansion, which is the only " + + "place ECC can restore the ARGUMENTS payload Pi otherwise drops" + ) + assert.ok( + extensionSource.includes("handlePiInputEvent") && + extensionSource.includes('from "./input-args.js"'), + "expected .pi/extensions/index.ts to delegate the input handler to input-args.js " + + "so tests can load and exercise the real registered callback rather than a copy" + ) + assert.ok( + inputArgsSource.includes('event.source === "extension"') && + inputArgsSource.includes('event.streamingBehavior === "steer"') && + inputArgsSource.includes('typeof pi.getCommands !== "function"'), + "expected the registered callback to skip extension-injected and steering input, " + + "and to tolerate an API without getCommands; transforming those can double-expand " + + "ECC commands or crash the adapter" + ) + assert.ok( + inputArgsSource.includes("pi.getCommands()") && + inputArgsSource.includes("activeCommands:"), + "expected the registered callback to resolve active commands via pi.getCommands() " + + "and pass them into the testable input-args handler for provenance checks" + ) + assert.ok( + inputArgsSource.includes("ECC_PI_COMMAND_ARGS"), + "expected input-args.js to honor an ECC_PI_COMMAND_ARGS opt-out for " + + "argument restoration; an irreversible transform would make the workaround mandatory" + ) + assert.ok( + inputArgsSource.includes('action: "transform"') && + inputArgsSource.includes('action: "continue"'), + "expected the input handler to return Pi's action result shape, either " + + "transform (replace the command with its body plus ARGUMENTS) or continue " + + "(leave Pi's normal expansion untouched)" + ) + assert.ok( + inputArgsSource.includes(":-[^}]*") && + inputArgsSource.includes("(?::\\d+)?") && + inputArgsSource.includes("$(ARGUMENTS|@|\\d+)"), + "expected ARG_PLACEHOLDER to match Pi's full placeholder set, including " + + "${1:-default}, ${@:N}, and ${@:N:L}; missing those would transform commands " + + "Pi already expands" + ) + assert.ok( + inputArgsSource.includes('path.join(eccRoot, "commands"') && + inputArgsSource.includes("${name}.md"), + "expected input-args.js to read the canonical commands/ directory relative to eccRoot; " + + "reading from cwd would break global installs exactly like the original hook-root defect" + ) + assert.ok( + inputArgsSource.includes("new Map(cache).set(name, body)"), + "expected the command body cache to replace the old Map rather than mutate it; " + + "ECC's immutability rule forbids mutating an existing cache object" + ) + assert.ok( + inputArgsSource.includes("console.warn") && + inputArgsSource.includes("unable to read command"), + "expected input-args.js to report failed command reads instead of swallowing them; " + + "AGENTS.md requires errors to be surfaced even when the adapter keeps its fallback" + ) + }], + + ["registered input handler guard skips extension, steer, and missing getCommands", () => { + const fakePi = { getCommands: () => [eccPrompt("plan")] } + const options = { + eccRoot: repoRoot, + env: {}, + getBody: createCommandBodyReader(repoRoot), + } + + assert.deepStrictEqual( + handlePiInputEvent({ text: "/plan build it", source: "extension" }, fakePi, options), + { action: "continue" }, + "extension-injected input must pass through unchanged so ECC commands are not double-expanded" + ) + assert.deepStrictEqual( + handlePiInputEvent( + { text: "/plan build it", source: "interactive", streamingBehavior: "steer" }, + fakePi, + options + ), + { action: "continue" }, + "steering input must pass through unchanged rather than being transformed as a fresh command" + ) + assert.deepStrictEqual( + handlePiInputEvent({ text: "/plan build it", source: "interactive" }, {}, options), + { action: "continue" }, + "an extension API without getCommands must not crash the input handler" + ) + }], + + ["registered input handler transforms through the actual event callback", () => { + const fakePi = { getCommands: () => [eccPrompt("plan")] } + const readBody = createCommandBodyReader(repoRoot) + const result = handlePiInputEvent( + { text: "/plan add a hello world CLI", source: "interactive" }, + fakePi, + { eccRoot: repoRoot, env: {}, getBody: readBody } + ) + + assert.strictEqual(result.action, "transform") + assert.ok( + result.text.includes("ARGUMENTS: add a hello world CLI"), + "the registered event callback should append the user arguments to the canonical body" + ) + assert.ok( + result.text.startsWith(readBody("plan").split("\n")[0]), + "the registered event callback should use the real cached command body" + ) + }], + + ["input handler transforms /plan args when Pi's active prompt resolves to ECC", () => { + const planRaw = fs.readFileSync(path.join(repoRoot, "commands", "plan.md"), "utf8") + const planBody = ARG_PLACEHOLDER.test( + planRaw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim() + ) + ? "" + : planRaw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim() + assert.ok( + planBody, + "commands/plan.md must be placeholder-less in this repo for the test to be meaningful; " + + "if it gains a placeholder the transformation should no longer apply" + ) + + const result = handlePiInput({ + text: "/plan add a hello world CLI", + eccRoot: repoRoot, + env: {}, + activeCommands: [eccPrompt("plan")], + }) + + assert.strictEqual(result.action, "transform") + assert.ok( + result.text.includes("ARGUMENTS: add a hello world CLI"), + "transforming a placeholder-less command should append ARGUMENTS with the user text" + ) + assert.ok( + result.text.startsWith(planBody.split("\n")[0]), + "the transformed input should start with the real command body, not the slash command name" + ) + }], + + ["input handler passes /sessions through because the command has a placeholder", () => { + const stripFrontmatter = raw => raw.replace(/^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim() + const sessionsRaw = fs.readFileSync(path.join(repoRoot, "commands", "sessions.md"), "utf8") + assert.ok( + ARG_PLACEHOLDER.test(stripFrontmatter(sessionsRaw)), + "commands/sessions.md must contain a placeholder in this repo for the pass-through test to be meaningful" + ) + + assert.deepStrictEqual( + handlePiInput({ + text: "/sessions recent", + eccRoot: repoRoot, + env: {}, + activeCommands: [eccPrompt("sessions")], + }), + { action: "continue" } + ) + }], + + ["input handler passes through bare and unknown commands", () => { + assert.deepStrictEqual( + handlePiInput({ + text: "just a normal prompt", + eccRoot: repoRoot, + env: {}, + activeCommands: [], + }), + { action: "continue" } + ) + assert.deepStrictEqual( + handlePiInput({ + text: "/not-a-real-ecc-command args", + eccRoot: repoRoot, + env: {}, + activeCommands: [eccPrompt("plan")], + }), + { action: "continue" } + ) + }], + + ["input handler honors ECC_PI_COMMAND_ARGS=off", () => { + assert.deepStrictEqual( + handlePiInput({ + text: "/plan add a hello world CLI", + eccRoot: repoRoot, + env: { ECC_PI_COMMAND_ARGS: "off" }, + activeCommands: [eccPrompt("plan")], + }), + { action: "continue" } + ) + }], + + ["placeholder detection recognizes Pi's braced positional and slice forms", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-pi-args-")) + const commandsDir = path.join(root, "commands") + fs.mkdirSync(commandsDir, { recursive: true }) + + try { + fs.writeFileSync( + path.join(commandsDir, "braced.md"), + "---\ndescription: braced\n---\n${1:-default} plus ${@:2:3}\n" + ) + assert.strictEqual( + loadPlaceholderlessCommand("braced", root), + null, + "${1:-default} and ${@:2:3} are placeholders Pi expands, not placeholder-less bodies" + ) + + fs.writeFileSync( + path.join(commandsDir, "plain.md"), + "---\ndescription: plain\n---\nno placeholders here\n" + ) + assert.strictEqual( + loadPlaceholderlessCommand("plain", root), + "no placeholders here", + "a body without placeholders should be returned for argument restoration" + ) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }], + + ["command reader reports failed reads while keeping its null fallback", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-pi-readerr-")) + const commandsDir = path.join(root, "commands") + fs.mkdirSync(commandsDir, { recursive: true }) + + const warnings = [] + const originalWarn = console.warn + console.warn = (...args) => { + warnings.push(args.join(" ")) + } + + try { + assert.strictEqual( + loadPlaceholderlessCommand("unreadable", root, commandsDir), + null, + "a failed read must keep the fallback so argument restoration degrades rather than throws" + ) + assert.ok( + warnings.some( + message => + message.includes("[ecc-pi] unable to read command") && + message.includes(commandsDir) + ), + "the failed command read must be reported instead of being silently swallowed" + ) + } finally { + console.warn = originalWarn + fs.rmSync(root, { recursive: true, force: true }) + } + }], + + ["input handler leaves disabled, missing, and differently resolved prompts unchanged", () => { + const otherRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-pi-other-")) + const otherCommands = path.join(otherRoot, "commands") + fs.mkdirSync(otherCommands, { recursive: true }) + const otherPlan = path.join(otherCommands, "plan.md") + fs.writeFileSync(otherPlan, "---\ndescription: user plan\n---\nuser plan body\n") + + try { + assert.deepStrictEqual( + handlePiInput({ + text: "/plan add a hello world CLI", + eccRoot: repoRoot, + env: {}, + activeCommands: [], + }), + { action: "continue" }, + "a disabled or missing Pi prompt must not be overridden by ECC's canonical file" + ) + assert.deepStrictEqual( + handlePiInput({ + text: "/plan add a hello world CLI", + eccRoot: repoRoot, + env: {}, + activeCommands: [{ name: "plan", source: "prompt", sourceInfo: { path: otherPlan } }], + }), + { action: "continue" }, + "a same-named prompt resolved from outside ECC must be left for Pi to expand" + ) + } finally { + fs.rmSync(otherRoot, { recursive: true, force: true }) + } + }], + + ["command body cache replaces rather than mutates its previous Map", () => { + const readBody = createCommandBodyReader(repoRoot) + const first = readBody("plan") + assert.ok( + typeof first === "string" && first.includes("# Plan Command"), + "the body reader should return the real canonical plan body" + ) + assert.strictEqual( + readBody("plan"), + first, + "the cache should return the same body on subsequent lookups" + ) + }], + + ["command body cache returns the first body after the backing file changes", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "ecc-pi-cache-")) + const commandsDir = path.join(root, "commands") + fs.mkdirSync(commandsDir, { recursive: true }) + const planPath = path.join(commandsDir, "plan.md") + fs.writeFileSync(planPath, "---\ndescription: plan\n---\nfirst body\n") + + try { + const readBody = createCommandBodyReader(root) + assert.strictEqual(readBody("plan"), "first body") + + fs.writeFileSync(planPath, "---\ndescription: plan\n---\nsecond body\n") + assert.strictEqual( + loadPlaceholderlessCommand("plan", root), + "second body", + "the backing command file must actually change for the cache assertion to be meaningful" + ) + assert.strictEqual( + readBody("plan"), + "first body", + "the cached body must be immutable even after the backing command file changes" + ) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }], ] for (const [name, fn] of tests) {