Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion .agents/scripts/instructions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const scripts = Object.keys(
).scripts,
)

const ROOTED = /^(src|scripts|docs|\.agents|\.github|\.claude|\.codex|\.cursor)\//
const ROOTED = /^(src|scripts|docs|\.agents|\.github|\.claude|\.codex|\.cursor|\.pi)\//
const FILE_NAME = /^[\w.-]+\.(md|json|ts|tsx|js|cjs|mjs|sh|yml|yaml)$/
// A path relative to the document, like `references/test-rules.md` in a skill.
const RELATIVE_FILE = /^[\w.-]+(\/[\w.-]+)+\.(md|json|ts|sh)$/
Expand Down
2 changes: 1 addition & 1 deletion .agents/scripts/package-contents.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { isolatedEnv, REPO_ROOT } from './lib/test-repo.ts'

// Agent tooling is development-only. `scripts/` ships in the npm package, so the tooling
// lives in `.agents/`, and must never be published.
const DEV_ONLY = ['.agents/', '.claude/', '.codex/', '.cursor/', '.tmp/']
const DEV_ONLY = ['.agents/', '.claude/', '.codex/', '.cursor/', '.pi/', '.tmp/']

// npm pack takes several seconds, more when `npm run verify` runs other checks alongside.
it('keeps agent tooling out of the published package', { timeout: 30_000 }, () => {
Expand Down
210 changes: 210 additions & 0 deletions .agents/scripts/pi-extension.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import { chmodSync, existsSync } from 'node:fs'
import { delimiter, join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { createTempRepo, markVerified, type TempRepo } from './lib/test-repo.ts'

// Drives a copy of .pi/extensions/agent-guard.ts the way Pi does, in its own node process:
// register the handlers, then call `tool_call` with one event, and print what the handler
// returned and the notes it showed. The extension guards the checkout it lives in, so it runs from
// a throwaway repo holding a copy of it and of .agents/scripts. Node loads it with type stripping,
// which also holds it to the erasable syntax the rest of the tooling uses.
const DRIVER = `
const { readFileSync } = await import('node:fs')
const [extension, cwd, eventFile] = process.argv.slice(1)
const event = JSON.parse(readFileSync(eventFile, 'utf8'))
const { default: agentGuard } = await import(extension)
const handlers = {}
const notes = []
agentGuard({ on: (name, handler) => (handlers[name] = handler) })
const hasUI = !process.env.HEADLESS
function notify(message) {
if (process.env.BROKEN_UI) throw new Error('the UI is gone')
notes.push(message)
}
const ctx = { cwd, hasUI, ui: { notify } }
const result = await handlers.tool_call(event, ctx)
console.log(JSON.stringify({ result: result ?? null, notes }))
`

type Driven = {
result: { block: true; reason?: string } | null
notes: string[]
stderr: string
}

let repo: TempRepo

function setUp(target: TempRepo, { withGuard = true } = {}): void {
const paths = ['.pi/extensions/agent-guard.ts']
if (withGuard) paths.push('.agents/scripts/guard.ts', '.agents/scripts/lib')
target.copyFromCheckout(...paths)
target.write('.gitignore', '.tmp/\n')
target.write('src/a.ts', 'export const a = 1\n')
target.git(['add', '.'])
target.git(['commit', '--quiet', '-m', 'initial'])
}

function drive(
event: { toolName: string; input: unknown },
options: { target?: TempRepo; cwd?: string; env?: Record<string, string> } = {},
): Driven {
const target = options.target ?? repo
const cwd = options.cwd ?? target.dir
target.write('.tmp/event.json', JSON.stringify(event))
const eventFile = join(target.dir, '.tmp/event.json')
const extension = join(target.dir, '.pi/extensions/agent-guard.ts')
const result = target.run(
process.execPath,
['--no-warnings', '--input-type=module', '-e', DRIVER, extension, cwd, eventFile],
{ cwd, env: options.env },
)
expect(result.status, result.stderr).toBe(0)
return { ...(JSON.parse(result.stdout) as Omit<Driven, 'stderr'>), stderr: result.stderr }
}

const bash = (command: string) => ({ toolName: 'bash', input: { command } })

/**
* A `node` first on PATH that notes each start before it runs the real one. The driver runs node
* by its full path, so only the extension's own `spawn('node', …)` of the guard goes through it.
*/
function watchNode(): { env: Record<string, string>; started: () => boolean } {
const bin = join(repo.dir, '.tmp/bin')
const log = join(bin, 'started')
repo.write(
'.tmp/bin/node',
`#!/bin/sh\necho started >> '${log}'\nexec '${process.execPath}' "$@"\n`,
)
chmodSync(join(bin, 'node'), 0o755)
return {
env: { PATH: `${bin}${delimiter}${process.env.PATH}` },
started: () => existsSync(log),
}
}

const commitOnBranch = (branch: string, path: string) => repo.commitOnBranch(branch, path)

beforeEach(() => {
repo = createTempRepo()
setUp(repo)
repo.addOrigin()
})

afterEach(() => repo.cleanup())

it("blocks an unverified push through tool_call with the guard's reason", () => {
commitOnBranch('feature', 'src/b.ts')
const { result, notes } = drive(bash('git push -u origin HEAD'))
expect(result).toEqual({ block: true, reason: expect.stringContaining('npm run verify') })
expect(notes).toEqual([])

// From a subfolder, with a pull request split across lines
const opened = drive(bash('gh pr \\\n create --fill'), { cwd: join(repo.dir, 'src') })
expect(opened.result?.reason).toContain('opens a pull request')
})

it('lets the push run once verify has passed on it', () => {
commitOnBranch('feature', 'src/b.ts')
markVerified(repo.dir)
const node = watchNode()
expect(drive(bash('git push -u origin HEAD'), { env: node.env })).toEqual({
result: null,
notes: [],
stderr: '',
})
expect(node.started()).toBe(true)
})

it('leaves every other tool call alone, without starting the guard', () => {
commitOnBranch('feature', 'src/b.ts')
const node = watchNode()
for (const event of [
bash('ls'),
bash('git status && npm test'),
{ toolName: 'read', input: { path: 'push.md' } },
{ toolName: 'grep', input: { command: 'git push' } },
{ toolName: 'bash', input: null },
]) {
expect(drive(event, { env: node.env }), JSON.stringify(event)).toEqual({
result: null,
notes: [],
stderr: '',
})
}
expect(node.started()).toBe(false)
})

it('does nothing with DISABLE_AGENT_GUARD=1', () => {
commitOnBranch('feature', 'src/b.ts')
const node = watchNode()
const off = drive(bash('git push'), { env: { ...node.env, DISABLE_AGENT_GUARD: '1' } })
expect(off).toEqual({ result: null, notes: [], stderr: '' })
expect(node.started()).toBe(false)
})

it('skips a checkout without the guard, such as an older branch, without a word', () => {
const older = createTempRepo()
try {
setUp(older, { withGuard: false })
older.write('src/b.ts', 'export const b = 1\n')
older.git(['add', '.'])
older.git(['commit', '--quiet', '-m', 'b'])
const node = watchNode()
expect(drive(bash('git push'), { target: older, env: node.env })).toEqual({
result: null,
notes: [],
stderr: '',
})
expect(node.started()).toBe(false)
} finally {
older.cleanup()
}
})

it("shows the guard's notes: a push it can't check, or a broken guard", () => {
commitOnBranch('feature', 'src/b.ts')
const unknown = drive(bash('cd "$REPO" && git push'))
expect(unknown.result).toBeNull()
expect(unknown.notes.join('\n')).toContain("can't tell which folder a push runs in")

repo.write('.agents/scripts/lib/push-check.ts', 'this is not valid typescript (\n')
const broken = drive(bash('git push'))
expect(broken.result).toBeNull()
expect(broken.notes.join('\n')).toContain('hook failed, so it allowed the action')
})

it('prints the notes on stderr when Pi has no UI', () => {
commitOnBranch('feature', 'src/b.ts')
const headless = drive(bash('cd "$REPO" && git push'), { env: { HEADLESS: '1' } })
expect(headless.notes).toEqual([])
expect(headless.stderr).toContain("can't tell which folder a push runs in")
})

it('allows the call when the extension itself fails, which Pi would treat as a block', () => {
commitOnBranch('feature', 'src/b.ts')
const failed = drive(bash('cd "$REPO" && git push'), { env: { BROKEN_UI: '1' } })
expect(failed.result).toBeNull()
expect(failed.stderr).toContain('the Pi extension failed, so it allowed the action')
})

it("notes a guard that can't run at all, such as one with a syntax error", () => {
commitOnBranch('feature', 'src/b.ts')
repo.write('.agents/scripts/guard.ts', 'this is not valid typescript (\n')
const broken = drive(bash('git push'))
expect(broken.result).toBeNull()
expect(broken.notes.join('\n')).toMatch(
/tool-start exited with code 1, so it allowed the action\. [\s\S]*SyntaxError/,
)
})

it('allows the call when the guard exits without reading its input or printing JSON', () => {
commitOnBranch('feature', 'src/b.ts')
// A command long enough that the write is still going when the guard closes the pipe
repo.write('.agents/scripts/guard.ts', 'process.exit(0)\n')
expect(drive(bash(`git push # ${'x'.repeat(512 * 1024)}`)).result).toBeNull()

repo.write('.agents/scripts/guard.ts', 'console.log("not json")\n')
const garbled = drive(bash('git push'))
expect(garbled.result).toBeNull()
expect(garbled.notes.join('\n')).toContain('printed no JSON, so it allowed the action')
})
5 changes: 3 additions & 2 deletions .agents/scripts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
// Agent tooling runs straight from source with Node's type stripping, so it may only use
// erasable TypeScript syntax and must import files with their .ts extension.
// erasable TypeScript syntax and must import files with their .ts extension. The Pi extension
// in .pi/ is agent tooling too, and its test loads it the same way.
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "../..",
Expand All @@ -12,5 +13,5 @@
"lib": ["es2023"],
"types": ["node", "vitest/globals"]
},
"include": ["."]
"include": [".", "../../.pi/**/*"]
}
146 changes: 146 additions & 0 deletions .pi/extensions/agent-guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Pi's wiring for the push check: the same `.agents/scripts/guard.ts` the Claude Code and Codex
// hooks call, so the rules can't drift apart per agent. Pi has no hook files; it has extension
// events, and `tool_call` fires before each tool runs and can block it. Before a `bash` call that
// could push, this asks the guard, and blocks the call with the guard's reason when it says no.
//
// Pi loads project extensions only once you trust the project, and only from the folder it starts
// in. The rest works as it does for the other agents: DISABLE_AGENT_GUARD=1 turns it off, a
// checkout without the guard (an older branch) is skipped without a word, and a guard that fails
// to run allows the call. See docs/agents.md.
//
// Its tests are in .agents/scripts/pi-extension.test.ts: Pi would load a test file in this folder
// as another extension.

import { spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

/** What the guard prints: the same JSON the Claude Code and Codex hooks read. */
type GuardOutput = {
hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string }
systemMessage?: string
}

/** What the handler reads of Pi's `tool_call` context. */
type ToolContext = {
cwd: string
hasUI: boolean
ui: { notify(message: string, type?: 'info' | 'warning' | 'error'): void }
}

type ToolCallResult = { block: true; reason?: string } | undefined

type ToolCallHandler = (
event: { toolName: string; input: unknown },
ctx: ToolContext,
) => Promise<ToolCallResult>

/** What this uses of Pi's extension API, declared here since Pi isn't a dependency. */
type ExtensionAPI = { on(event: 'tool_call', handler: ToolCallHandler): void }

/** The same quick test as the hook commands: a command without these words can't push. */
const MIGHT_PUSH = /push|pr\s.*(create|new)/s

/** The checkout this file lives in, two folders up, whichever folder Pi runs in. */
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..')

const GUARD = join(ROOT, '.agents/scripts/guard.ts')

/** As long as the Claude Code and Codex hooks wait for the guard. */
const TIMEOUT_MS = 30_000

/**
* Runs the guard the way the other agents' hooks do: a separate process with JSON on stdin that
* prints JSON on stdout. Any failure resolves to a note rather than a decision, so the call runs.
*/
function runGuard(payload: Record<string, unknown>): Promise<GuardOutput> {
return new Promise((done) => {
const child = spawn('node', [GUARD, 'tool-start'], { cwd: ROOT, env: process.env })
let stdout = ''
let stderr = ''
let finished = false
function finish(output: GuardOutput): void {
if (finished) return
finished = true
clearTimeout(timer)
done(output)
}
const timer = setTimeout(() => {
child.kill()
finish({
systemMessage:
`agent-guard: tool-start timed out, so it allowed the action. ${stderr.trim()}`.trim(),
})
}, TIMEOUT_MS)
child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString()))
child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString()))
child.on('error', (error) => {
finish({ systemMessage: `agent-guard: tool-start failed to run: ${error.message}` })
})
child.on('close', (code, signal) => {
// A guard that can't even load, such as one with a syntax error, prints nothing on
// stdout and says why on stderr.
if (code !== 0) {
const how = signal ? `was stopped by ${signal}` : `exited with code ${code}`
finish({
systemMessage:
`agent-guard: tool-start ${how}, so it allowed the action. ${stderr.trim()}`.trim(),
})
return
}
try {
finish(stdout.trim() ? (JSON.parse(stdout) as GuardOutput) : {})
Comment thread
scottlovegrove marked this conversation as resolved.
Resolved
} catch {
finish({
systemMessage: `agent-guard: tool-start printed no JSON, so it allowed the action. ${stderr.trim()}`,
})
}
})
// A guard that exits before reading its input closes the pipe; `close` still reports how
// it ended, so a write error must not crash Pi.
child.stdin.on('error', () => {})
child.stdin.end(JSON.stringify(payload))
})
}

/** Shows a note in Pi's UI, or on stderr in print and JSON modes, which have none. */
function tell(ctx: ToolContext, message: string): void {
if (ctx.hasUI) ctx.ui.notify(message, 'warning')
else process.stderr.write(`${message}\n`)
}

async function checkToolCall(
event: { toolName: string; input: unknown },
ctx: ToolContext,
): Promise<ToolCallResult> {
if (event.toolName !== 'bash') return undefined
const command = (event.input as { command?: unknown } | null | undefined)?.command
if (typeof command !== 'string' || !MIGHT_PUSH.test(command)) return undefined
// Not started at all when turned off, or on an older branch without the guard.
if (process.env.DISABLE_AGENT_GUARD === '1' || !existsSync(GUARD)) return undefined

const output = await runGuard({ tool_name: 'Bash', tool_input: { command }, cwd: ctx.cwd })
if (output.systemMessage) tell(ctx, output.systemMessage)
const decision = output.hookSpecificOutput
if (decision?.permissionDecision !== 'deny') return undefined
return { block: true, reason: decision.permissionDecisionReason }
}

// Pi loads an extension through its default export.
export default function agentGuard(pi: ExtensionAPI): void {
pi.on('tool_call', async (event, ctx) => {
// Pi blocks the tool call when a handler throws; a broken extension must allow it instead.
try {
return await checkToolCall(event, ctx)
} catch (error) {
const message = `agent-guard: the Pi extension failed, so it allowed the action. ${(error as Error)?.message ?? error}`
try {
tell(ctx, message)
} catch {
process.stderr.write(`${message}\n`)
}
return undefined
}
})
}
Loading
Loading