← Catalog

@jordyvanvorselen/pi-claude-hooks

Run Claude Code hooks from .claude/ inside pi

Package

Install

Install with PiG

pig install npm:@jordyvanvorselen/pi-claude-hooks

Install with Pi

pi install npm:@jordyvanvorselen/pi-claude-hooks
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./extensions/claude-hooks.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.1.2 (README.md). PiG does not review it.

pi-claude-hooks

Run your Claude Code hooks inside pi. The extension reads the hook configuration your team already deploys to .claude/ and runs those command hooks on pi's events. Existing hook scripts keep working unchanged, including scripts that read .tool_input.file_path or match on Edit|Write.

Quick start

Install the package:

pi install npm:@jordyvanvorselen/pi-claude-hooks

Or install from a local checkout:

pi install /path/to/pi-claude-hooks

Or try it for one run without installing:

pi -e npm:@jordyvanvorselen/pi-claude-hooks
pi -e /path/to/pi-claude-hooks

Open pi in a project that has .claude/settings.json hooks. Run /claude-hooks to see what was loaded.

Hooks only run for trusted projects. If pi has not trusted the project yet, only your user-level ~/.claude/settings.json hooks load, and you get a warning.

Config sources

Hook files are read in this order. Later files append to the earlier ones.

OrderFileNotes
1~/.claude/settings.jsonYour user hooks. Turn off with loadUserSettings: false.
2<project>/.claude/settings.jsonTeam hooks. Only for trusted projects.
3<project>/.claude/settings.local.jsonPersonal project hooks. Only for trusted projects.
4<project>/.claude/*.jsonAny other JSON file that contains hooks, for example apm-hooks.json. Glob is configurable.

A file counts as a hook file when it has a top-level hooks object, or when it has event names such as PreToolUse at the top level (the shape APM writes to apm-hooks.json). The extra-file scan is a pi-claude-hooks extension rather than a Claude standard-settings feature; malformed matching JSON is skipped with a warning.

Hook declarations are not deduplicated. When settings.json and apm-hooks.json contain the same event, matcher and command, both declarations run. disableAllHooks is read only from these three standard settings files, with local > project > user precedence; extra files cannot override it.

Only type: "command" hooks run. http, prompt, agent and mcp_tool hooks are skipped with one warning per type.

Options

Put options in ~/.pi/agent/claude-hooks.json or <project>/.pi/claude-hooks.json. The project file overrides the user file.

{
  "enabled": true,
  "loadUserSettings": true,
  "extraFiles": ["*.json"],
  "defaultTimeoutSeconds": 600,
  "sessionEndTimeoutSeconds": 1.5,
  "shell": "/bin/bash",
  "verbose": false,
  "startupSummary": "compact"
}
OptionDefaultWhat it does
enabledtrueSet to false to load nothing.
loadUserSettingstrueRead ~/.claude/settings.json.
extraFiles["*.json"]Filename globs, matched inside .claude/, for extra hook files. settings.json and settings.local.json are always excluded here because they load on their own. Use [] to load no extra files.
defaultTimeoutSeconds600Timeout for hooks without their own timeout. UserPromptSubmit hooks are capped at 30 seconds, matching Claude Code.
sessionEndTimeoutSeconds1.5Timeout for SessionEnd hooks so quitting pi stays fast. A hook's own timeout wins.
shell/bin/bash when presentShell used to run hook commands.
verbosefalseLog every hook run and exit code.

Environment variables for quick overrides: PI_CLAUDE_HOOKS_EXTRA_FILES (comma separated globs), PI_CLAUDE_HOOKS_VERBOSE=1, PI_CLAUDE_HOOKS_DISABLED=1.

Startup summary

When a session starts, the extension adds a [Claude hooks] block to the chat in the same style as pi's own [Skills] and [Extensions] sections.

[Claude hooks]
  SessionStart (1), PreToolUse (3), PostToolUse (1)

Press the expand shortcut (the one that expands tool output) to see every hook grouped by source file, with its matcher and a shortened command:

[Claude hooks]
  ~/.claude/settings.json
    SessionStart [startup] bash ~/.claude/hooks/agent-state.sh session
  ~/projects/app/.claude/settings.json
    PreToolUse [Bash] if jq -re '.tool_input.command // empty' | grep -qE '(rm\s+(-[a-z]*...
    PreToolUse [Edit|Write] p=$(jq -re '.tool_input.file_path // empty') || exit 0; root=...
    PostToolUse [Edit|Write] if jq -re 'select((.tool_input.file_path // "") | (test("(co...

Set startupSummary in the options file:

ValueBehaviour
"compact"Default. Event names with counts. Expands on demand.
"full"Always show the grouped list.
"off"Show nothing.

The block is a pi custom entry. It is stored in the session file but never sent to the model. It appears once per session: resuming a session does not add another one, and nothing is shown when no hooks loaded or when pi runs without a UI (print and JSON modes).

Commands

CommandWhat it does
/claude-hooksList loaded sources and hooks per event.
/claude-hooks-reloadRe-read all hook files.
/claude-hooks-verboseToggle logging of every hook run.

Event mapping

Claude Code eventPi eventMatcher valueCan block
PreToolUsetool_callTool name (pi and Claude names)Yes. Blocks the tool call.
PostToolUsetool_result with isError: falseTool nameNo. Feedback goes to the model.
PostToolUseFailuretool_result with isError: trueTool nameNo. Feedback goes to the model.
UserPromptSubmitinputnoneYes. Drops the prompt.
SessionStartsession_startstartup, resume, clear, forkNo
SessionEndsession_shutdownclear, resume, otherNo
Stopagent_before_settlenoneYes. Appends the reason as context and runs one more turn.
PreCompactsession_before_compactmanual, autoYes. Cancels compaction.
PostCompactsession_compactmanual, autoNo

Session source mapping: pi startup and reload become startup, new becomes clear, resume stays resume, fork stays fork. Session end reasons: pi new becomes clear, resume stays resume, everything else becomes other.

Matchers follow Claude Code rules and are case-sensitive. Known tool names and names separated by | or , are exact, trimmed alternatives; anything else is an unanchored, case-sensitive JavaScript regular expression. Pi and Claude tool aliases are tested as separate candidates. Empty, missing or * matches everything.

Tool name and field normalisation

Claude Code scripts see capitalised tool names and file_path style fields. Pi uses lowercase names and different field names. The extension presents both, so scripts written for either side work.

Tool names

Matchers are tested against separate, case-sensitive Pi and Claude Code names. Empty/* match all; known tool names (Bash, bash, etc.) and |/, lists are exact, trimmed alternatives. Other patterns are unanchored JavaScript regular expressions. Invalid regular expressions match nothing and produce one warning. tool_name in the stdin payload is the Claude Code name. pi_tool_name holds the pi name.

Pi toolClaude Code name
bashBash
powershellBash
readRead
writeWrite
editEdit
grepGrep
findGlob
lsLS
anything elseunchanged

tool_input fields

Pi's own fields are always present. These Claude Code fields are added next to them.

Pi toolPi inputAdded Claude Code fields
editpath, edits: [{oldText, newText}]file_path = path, old_string = all oldText joined with newlines, new_string = all newText joined with newlines
writepath, contentfile_path = path
readpath, offset, limitfile_path = path
bashcommand, timeoutnone, command already matches
greppattern, path, glob, ignoreCase, ...-i = ignoreCase
findpattern, path, limitnone, matches Claude Code Glob

updatedInput mapping back

When a PreToolUse hook returns hookSpecificOutput.updatedInput, the extension translates Claude Code fields back before pi runs the tool.

Returned fieldApplied as
file_pathpath (for read, write, edit)
old_string, new_stringedits[0].oldText, edits[0].newText when the call has exactly one edit. With several edits the change is ignored and you get a warning.
-iignoreCase (for grep)
anything elsepassed through as is

Stdin payload

Every hook gets JSON on stdin:

{
  "session_id": "...",
  "transcript_path": "/path/to/pi/session.jsonl",
  "cwd": "/path/to/project",
  "hook_event_name": "PreToolUse",
  "permission_mode": "default",
  "tool_name": "Edit",
  "pi_tool_name": "edit",
  "tool_input": { "path": "a.ts", "edits": [...], "file_path": "a.ts", "old_string": "...", "new_string": "..." },
  "tool_use_id": "call_123"
}

Event specific fields: tool_response: { output, content, details, is_error } on PostToolUse, error and is_interrupt on PostToolUseFailure, prompt on UserPromptSubmit, source and model on SessionStart, reason on SessionEnd, stop_hook_active and last_assistant_message on Stop, trigger and custom_instructions on PreCompact, trigger and compaction_summary on PostCompact. output is rendered text; content and details are the original Pi values. Image blocks render as [image] in output but remain intact in content. is_interrupt is inferred from the Pi abort signal and common abort text (such as Command aborted).

Environment

Hook commands run in the project directory with your environment plus:

VariableValue
CLAUDE_PROJECT_DIRProject root (pi's cwd)
PI_SESSION_IDPi session id
PI_SESSION_FILEPi session file, when the session is saved
PI_PROVIDER, PI_MODELCurrent model
PI_REASONING_LEVELCurrent thinking level
PI_CLAUDE_HOOKS1, so scripts can tell they run under pi

Exit code contract

Exit codePreToolUsePostToolUseUserPromptSubmitStopPreCompactOthers
0Parse stdout as JSON if it is a JSON objectSameSame. Plain stdout is added as context for the modelSameSameSame. SessionStart plain stdout is added as context
2Block the tool. stderr is the reason the model seesTool already ran. stderr is appended to the tool result for the modelDrop the prompt. stderr is shown to youKeep going. stderr is added as context and one more turn runsCancel compactionstderr is shown to you
otherNon-blocking. stderr is shown as an error. Valid JSON on stdout still appliesSameSameSameSameSame

A hook that hits its timeout is reported as an error and never blocks.

JSON output contract

Print a JSON object on stdout with exit code 0.

FieldSupportedBehaviour
continue: false, stopReasonYesOn PreToolUse the tool is blocked and the agent stops. On PostToolUse the run is aborted. Elsewhere it counts as a block.
systemMessageYesShown to you as a warning.
suppressOutputIgnoredStdout is never shown in the transcript anyway.
decision: "block", reasonYesBlocks on PreToolUse, UserPromptSubmit, Stop, PreCompact. Feeds reason to the model on PostToolUse.
decision: "approve"YesSame as permissionDecision: "allow".
hookSpecificOutput.permissionDecisionYesdeny blocks. ask opens a confirm dialog, or blocks when there is no UI. allow lets the call through. deny wins over ask wins over allow when several hooks answer.
hookSpecificOutput.permissionDecisionReasonYesReason for the block or the dialog.
hookSpecificOutput.updatedInputYesReplaces the tool input. See the mapping above.
hookSpecificOutput.additionalContextYesPreToolUse and PostToolUse: appended to the tool result. UserPromptSubmit and SessionStart: sent as a hidden message before the next turn.

Supported and unsupported

Supported: command hooks, all events in the mapping table, matchers, per-hook timeout, exit codes 0 and 2, the JSON fields listed above, stop_hook_active loop protection on Stop. Settings merge additively in user → project → local → configured extra-file order, including duplicate declarations. Extra JSON files are an explicit pi-claude-hooks extension (and support Claude's bare-event APM shape); malformed extras are skipped with a warning. disableAllHooks uses only standard settings, with local > project > user precedence.

Not supported: http, prompt, agent and mcp_tool hook types. Events pi has no equivalent for: Notification, PermissionRequest, PermissionDenied, SubagentStart, SubagentStop, PostToolBatch, PreModelSwitch, PostModelSwitch, Elicitation, worktree, teammate and task events. Hook fields if, once, async, statusMessage, args. CLAUDE_ENV_FILE. Managed settings, CLI settings, plugins, skill frontmatter hooks, and CLAUDE_CONFIG_DIR are warned about and ignored. allowManagedHooksOnly is not supported.

Pi has no permission prompts of its own, so permissionDecision: "allow" has nothing to bypass. It simply lets the call proceed.

Development

npm install
npm run lint
npm run typecheck
npm test

Run npm run lint:fix to fix lint and formatting problems.

The integration tests run the real hook commands from a Hertek project against pi-shaped tool inputs. One of those hooks needs GNU realpath -m. On macOS install coreutils with Homebrew, the tests add its gnubin directory to PATH automatically.

Versioning and releases

This package follows semantic versioning. Every pull request must raise the version in package.json. CI fails the pull request when the version is not higher than on main.

Pick the bump that matches the change:

ChangeCommandExample
Bug fix, docs, internal changenpm version patch --no-git-tag-version0.1.0 → 0.1.1
New feature or setting that keeps old behaviournpm version minor --no-git-tag-version0.1.1 → 0.2.0
Breaking change, such as a removed or renamed settingnpm version major --no-git-tag-version0.2.0 → 1.0.0

The command updates both package.json and package-lock.json. Commit both files.

When a pull request merges, GitHub Actions runs the checks again and publishes the new version to npm. It then creates a GitHub release tagged with the version number, such as 0.1.2. GitHub generates the release notes from the merged pull requests.