Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 37 additions & 8 deletions .pi/extensions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, handlePiInput } from "./input-args.js"

/**
* Minimal structural types mirroring `@earendil-works/pi-coding-agent`.
Expand Down Expand Up @@ -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> | InputEventResult
): void
on(
event: "session_start",
handler: (event: SessionStartEvent, ctx: ExtensionContext) => Promise<void> | void
Expand Down Expand Up @@ -670,7 +682,23 @@ function buildDoctorReport(ctx: ExtensionContext): string {
return lines.join("\n")
}

const getCommandBody = createCommandBodyReader(ECC_ROOT)

export default function (pi: ExtensionAPI): void {
pi.on("input", event => {
if (event.source === "extension" || event.streamingBehavior === "steer" || typeof pi.getCommands !== "function") {
return { action: "continue" }
}

return handlePiInput({
text: event.text,
eccRoot: ECC_ROOT,
env: process.env,
activeCommands: pi.getCommands(),
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
Expand Down Expand Up @@ -753,14 +781,15 @@ 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) => {
pi.sendMessage(
{
customType: "ecc-doctor",
content: buildDoctorReport(ctx),
display: true,
},
{ deliverAs: "nextTurn" }
)
// 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.
// Without options (and not streaming) Pi appends and displays it immediately
// without triggering a model turn.
pi.sendMessage({
customType: "ecc-doctor",
content: buildDoctorReport(ctx),
display: true,
})
},
})
}
134 changes: 134 additions & 0 deletions .pi/extensions/input-args.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
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: <args>` 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) {
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 {
return null
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
}

/**
* Returns the canonical ECC command path only when Pi's active prompt for
* `name` resolves to ECC's canonical `commands/<name>.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()}` }
}

/**
* 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) {
let cache = new Map()
return name => {
if (cache.has(name)) {
return cache.get(name) ?? null
}
const body = loadPlaceholderlessCommand(name, eccRoot)
cache = new Map(cache).set(name, body)
return body
}
}

module.exports = {
ARG_PLACEHOLDER,
DISABLED_VALUES,
isDisabledByEnv,
stripFrontmatter,
loadPlaceholderlessCommand,
createCommandBodyReader,
activeEccPromptPath,
handlePiInput,
}
Loading