This document describes the current hook subsystem code in packages/coding-agent/src/extensibility/hooks/*.
The default CLI runtime initializes the extension runner path. In current startup flow:
--hookis treated as an alias for--extension(CLI paths are merged intoadditionalExtensionPaths)- JS/TS hook factories discovered through
hookCapability(for example.omp/hooks/pre/*.ts) are loaded as extension modules so theirpi.on(...)handlers bind to the runtime event bus - tools are wrapped by
ExtensionToolWrapper, notHookToolWrapper - context transforms and lifecycle emissions go through
ExtensionRunner
So this file documents the legacy hook subsystem implementation itself (types/loader/runner/wrapper), plus the factory shape still accepted when a discovered hook path is loaded by the extension runner.
packages/coding-agent/src/extensibility/hooks/types.ts— hook context, event types, and result contractspackages/coding-agent/src/extensibility/hooks/loader.ts— module loading and hook discovery bridgepackages/coding-agent/src/extensibility/hooks/runner.ts— event dispatch, command lookup, error signalingpackages/coding-agent/src/extensibility/hooks/tool-wrapper.ts— pre/post tool interception wrapperpackages/coding-agent/src/extensibility/hooks/index.ts— exports/re-exports
A hook module must default-export a factory:
import type { HookAPI } from "@oh-my-pi/pi-coding-agent/extensibility/hooks";
export default function hook(pi: HookAPI): void {
pi.on("tool_call", async (event, ctx) => {
if (
event.toolName === "bash" &&
String(event.input.command ?? "").includes("rm -rf")
) {
return { block: true, reason: "blocked by policy" };
}
});
}The factory can:
- register event handlers with
pi.on(...) - send persistent custom messages with
pi.sendMessage(...) - persist non-LLM state with
pi.appendEntry(...) - register slash commands via
pi.registerCommand(...) - register custom message renderers via
pi.registerMessageRenderer(...) - run shell commands via
pi.exec(...)and log throughpi.logger - use the injected Zod-compatible builder
pi.zod, native omptype builderpi.arktype, legacypi.typebox, and package exports viapi.pi
Default sessions load JS/TS hook factories discovered by hookCapability through the extension runner. discoverExtensionPaths(configuredPaths, cwd) does:
- Load native extension modules from the capability registry
- Load importable
.ts/.jshook factories from the hook capability registry - Append plugin extension entry points
- Append explicitly configured paths
The native provider scans only two subdirectories per config root — a factory placed directly in hooks/ is not discovered:
- Project:
<cwd>/.omp/hooks/pre/*.{ts,js}and<cwd>/.omp/hooks/post/*.{ts,js} - User:
<agentDir>/hooks/pre/*.{ts,js}and<agentDir>/hooks/post/*.{ts,js}(default~/.omp/agent/hooks/...; profile- andPI_CODING_AGENT_DIR-aware)
So <cwd>/.omp/hooks/psy-guards.ts (no pre//post/ subdirectory) loads nothing and reports no error — move it into pre/ or post/, e.g. <cwd>/.omp/hooks/pre/psy-guards.ts. This mirrors .claude/hooks/pre|post/. Only .ts/.js factories are appended to the extension pipeline and bound through the extension runner. See Extension Loading for the shared module pipeline these factories flow through (native .omp/extensions/ roots, plugin entries, configured paths, load order, and disable controls).
The legacy discoverAndLoadHooks(configuredPaths, cwd) helper still exists and does:
- Load discovered hooks from capability registry (
loadCapability("hooks")) - Append explicitly configured paths (deduped by absolute path)
- Call
loadHooks(allPaths, cwd)
loadHooks then imports each path and expects a default function.
loader.ts resolves hook paths as:
- absolute path: used as-is
~path: expanded- relative path: resolved against
cwd
Hook events are strongly typed in types.ts.
session_startsession_before_switch→ can return{ cancel?: boolean }session_switchsession_before_branch→ can return{ cancel?: boolean; skipConversationRestore?: boolean }session_branchsession_before_compact→ can return{ cancel?: boolean; compaction?: CompactionResult }session.compacting→ can return{ context?: string[]; prompt?: string; preserveData?: Record<string, unknown> }session_compactsession_before_tree→ can return{ cancel?: boolean; summary?: { summary: string; details?: unknown } }session_treesession_shutdown
context→ can return{ messages?: Message[] }before_agent_start→ can return{ message?: { customType; content; display; details; attribution } }agent_startagent_endturn_startturn_endauto_compaction_startauto_compaction_endauto_retry_startauto_retry_endttsr_triggeredtodo_reminder
tool_call(pre-execution) → can return{ block?: boolean; reason?: string; input?: Record<string, unknown>; additionalContext?: string }. A non-blocking handler that returnsinputreplaces the arguments the tool executes with (the raw execution input, not the normalizedevent.inputview); ignored whenblockis true. Distinct non-emptyadditionalContextvalues from all non-blocking handlers carry trusted handler-authored instructions delivered after the tool results and before th 8000 e next provider request, with developer/system priority where the transport supports it; raw tool output and other untrusted data must stay in the tool result.tool_result(post-execution) → can return{ content?; details?; isError?; additionalContext?: string }. Context is delivered outside tool output on both success and failure; checkevent.isErrorwhen guidance applies to only one outcome. Overrides merge per field across handlers, so a later return that omits a field (including a context-only return) never erases an earlier handler's value for it.
This is the hook subsystem’s core pre/post interception model. Eval prelude invocations such as browser.open(...), direct BrowserTab helpers, tab.run(...), direct computer helpers, and computer.run(fnOrCode, options) are host bridge calls, not AgentTool calls, so they do not emit tool_call or tool_result.
Hook tool interception flow
tool_call handlers
│
├─ any { block: true }? ── yes ──> throw (tool blocked)
│
└─ no
│
▼
execute underlying tool
│
├─ success ──> tool_result handlers can override { content, details }
│ and attach passive additionalContext
│
└─ error ──> emit tool_result(isError=true), deliver returned
additionalContext, then rethrow original error
HookToolWrapper.execute() emits tool_call before tool execution.
- if any handler returns
{ block: true }, execution stops and context already collected for that call is discarded - if handler throws, wrapper fails closed, blocks execution, and discards collected context
- collected context is forwarded only after the tool returns a non-error result; a throwing or
isErrorresult discards it - returned
reasonbecomes the thrown error text
Underlying tool executes normally if not blocked.
After success, wrapper emits tool_result with:
toolName,toolCallId,inputcontentdetailsisError: false
If a handler returns overrides:
contentcan replace result contentdetailscan replace result detailsadditionalContextcarries trusted guidance outside the tool result; distinct non-blank values from every handler are joined in registration order (repeats, compared ignoring surrounding whitespace, are dropped) and delivered before the call'stool_callcontext. A call whose joined context is identical to an earlier call's in the same batch is delivered once
On tool failure, the wrapper emits tool_result with isError: true and error text content, delivers any returned additionalContext, then rethrows the original error. A handler that should run only after failure must test event.isError; a PostToolUse-equivalent handler must reject it.
- LLM context for a single call via
context(messagesreplacement chain) - passive context for the next provider request via
additionalContextfromtool_callortool_result - raw tool execution arguments by returning
inputfromtool_call - tool output content/details on successful tool calls (
tool_resultpath) - pre-agent injected message via
before_agent_start - cancellation/custom compaction/tree behavior via
session_before_*andsession.compacting
- execution continuation after thrown tool errors (error path rethrows)
- final success/error status in wrapper behavior (returned
isErroris typed but not applied byHookToolWrapper)
Capability providers are priority-sorted (higher first). Dedupe is by capability key, first wins.
For hooks, capability key is ${type}:${tool}:${name}. Shadowed duplicates from lower-priority providers are marked and excluded from effective discovered list.
discoverAndLoadHooks builds a flat allPaths list, deduped by resolved absolute path, then loadHooks iterates in that order.
File order within each discovered directory depends on readdir output; the hook loader does not perform an additional sort.
Inside HookRunner, order is deterministic by registration sequence:
- hooks array order
- handler registration order per hook/event
Conflict behavior by event type:
tool_call: every distinct non-emptyadditionalContextis preserved in handler order (a value identical to an earlier handler's on the same call is dropped, as is a call's joined context identical to an earlier call's in the same batch);inputremains last-wins; first block short-circuits and discards context collected for that call. Handlers do not observe each other's input revisionstool_result:content/details/isErroroverrides merge per field across handlers (no short-circuit): a later handler's defined field wins and a field it leaves unset keeps the earlier handler's value, so a details-only, isError-only, or context-only return never erases an earlier redaction. Every distinct non-emptyadditionalContextis preserved in handler order, with the same repeat-dropping astool_callcontext: chained; each handler receives prior handler’s message outputbefore_agent_start: first returned message is kept; later messages ignoredsession_before_*: latest returned result is tracked;cancel: trueshort-circuits immediatelysession.compacting: latest returned result wins
Command/renderer conflicts:
getCommand(name)returns first match across hooks (first loaded wins)getMessageRenderer(customType)returns first matchgetRegisteredCommands()returns all commands (no dedupe)
HookUIContext includes:
select,confirm,input,editornotifysetStatuscustomsetEditorText,getEditorTextthemegetter
ctx includes hasUI, cwd, sessionManager, modelRegistry, current model, isIdle(), abort(), and hasQueuedMessages().
When running with no UI, the default no-op context behavior is:
select/input/editorreturnundefinedconfirmreturnsfalsenotify,setStatus,setEditorTextare no-opsgetEditorTextreturns""
Hook status text set via ctx.ui.setStatus(key, text) is:
- stored per key
- sorted by key name
- sanitized (ANSI/VT escape sequences stripped; control characters mapped to spaces; repeated spaces collapsed; trimmed)
- joined and width-truncated for display
- invalid module or missing default export → captured in
LoadHooksResult.errors - loading continues for other hooks
HookRunner.emit(...) catches handler errors for most events and emits HookError to listeners (hookPath, event, error), then continues.
emitToolCall(...) is stricter: handler errors are not swallowed there; they propagate to caller. In HookToolWrapper, this blocks the tool call (fail-safe).
import type { HookAPI } from "@oh-my-pi/pi-coding-agent/extensibility/hooks";
export default function (pi: HookAPI): void {
pi.on("tool_call", async (event, ctx) => {
if (event.toolName !== "bash") return;
const cmd = String(event.input.command ?? "");
if (!cmd.includes("rm -rf")) return;
if (!ctx.hasUI) return { block: true, reason: "rm -rf blocked (no UI)" };
const ok = await ctx.ui.confirm("Dangerous command", `Allow: ${cmd}`);
if (!ok) return { block: true, reason: "user denied command" };
});
}import type { HookAPI } from "@oh-my-pi/pi-coding-agent/extensibility/hooks";
export default function (pi: HookAPI): void {
pi.on("tool_result", async (event) => {
if (event.toolName !== "read" || event.isError) return;
const redacted = event.content.map((chunk) => {
if (chunk.type !== "text") return chunk;
return {
...chunk,
text: chunk.text.replaceAll(/API_KEY=\S+/g, "API_KEY=[REDACTED]"),
};
});
return { content: redacted };
});
}import type { HookAPI } from "@oh-my-pi/pi-coding-agent/extensibility/hooks";
export default function (pi: HookAPI): void {
pi.on("context", async (event) => {
const filtered = event.messages.filter(
(msg) => !(msg.role === "custom" && msg.customType === "debug-only"),
);
return { messages: filtered };
});
}import type { HookAPI } from "@oh-my-pi/pi-coding-agent/extensibility/hooks";
export default function (pi: HookAPI): void {
pi.registerCommand("handoff", {
description: "Create a new session with setup message",
handler: async (_args, ctx) => {
await ctx.waitForIdle();
await ctx.newSession({
parentSession: ctx.sessionManager.getSessionFile(),
setup: async (sm) => {
sm.appendMessage({
role: "user",
content: [
{ type: "text", text: "Continue from prior session summary." },
],
timestamp: Date.now(),
});
},
});
},
});
}packages/coding-agent/src/extensibility/hooks/index.ts and the package subpath @oh-my-pi/pi-coding-agent/extensibility/hooks export:
- loading APIs (
discoverAndLoadHooks,loadHooks) - runner and wrapper (
HookRunner,HookToolWrapper) - all hook types
execCommandre-export
The package root (@oh-my-pi/pi-coding-agent) does not re-export HookAPI; import legacy hook types from the hooks subpath.