Hooks
A Hook is a command process launched by CodeN at lifecycle event boundaries and can observe, block, or adjust parts of the flow. Hooks inherit the CodeN process permissions and environment; they are not a sandbox.
Matchers
Section titled “Matchers”Syntax
Section titled “Syntax”matcheris a regular-expression string (compiled withnew RegExp(matcherSource)) at config parse time; omitting it or using"*"matches everything.- An invalid regex fails config parsing (startup error).
- With no match target, the matcher is treated as
"*"(for exampleStophas no matcher).
{ "hooks": { "PreToolUse": [{ "matcher": "bash|edit|write", "hooks": [{ "type": "command", "command": "echo matched" }] }] }}Matchable events and targets
Section titled “Matchable events and targets”| Event | Match target |
|---|---|
PreToolUse |
toolName |
PermissionRequest |
toolName |
PostToolUse |
toolName |
PostToolUseFailure |
toolName |
SessionStart |
source (startup/resume) |
Notification |
notificationType (permission_prompt/attention_required) |
UserPromptSubmit, Stop, SessionEnd |
matcher not accepted (config with a matcher errors) |
Matching semantics
Section titled “Matching semantics”- The matcher accepts a string only; other types fail configuration.
- The regex tests the target string (such as the
bashtool name), not the full input. - Multiple groups may target the same event; all matching hooks run in parallel in config order (see Execution).
- At most 64 commands per event across merged user + project scopes.
Related references
Section titled “Related references”Protocol
Section titled “Protocol”Process conventions
Section titled “Process conventions”- Commands run through the system shell: POSIX
/bin/sh -c <command>; Windowscmd /d /s /c. - The working directory is the CodeN workspace; the environment inherits the CodeN process plus:
| Variable | Value |
|---|---|
CODEN_PROJECT_DIR |
workspace path |
CODEN_SESSION_ID |
current session ID |
CODEN_HOOK_EVENT |
event name |
stdin: one JSON object
Section titled “stdin: one JSON object”{ "schemaVersion": 1, "hookEventName": "PreToolUse", "sessionId": "…", "turnId": "…", "cwd": "/path/to/workspace", "permissionMode": "manual", "toolName": "bash", "callId": "…", "input": { "command": "git status" }, "risk": "modify"}Common fields: schemaVersion, hookEventName, sessionId, optional turnId, cwd, permissionMode, followed by the event payload. The input limit is 1MB (over limit counts as a failure).
stdout: one JSON object
Section titled “stdout: one JSON object”- Allowed top-level fields:
systemMessage(all events);Stopadditionally allowsdecision("block"only) andreason; other events usehookSpecificOutputwith per-event allowlists. systemMessagemust be a string, scrubbed of control characters, truncated to 2000 characters, and forwarded to the diagnostic sink (stdout/stderr).hookSpecificOutput.hookEventNamemust match the event; unknown fields count as failures.- Output limit is 10KB per stream (stdout and stderr independently); exceeding it terminates the process and marks
outputExceeded. - Exit code
0with empty stdout: no-op.
Output example
Section titled “Output example”{ "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow" }}Exit-code semantics
Section titled “Exit-code semantics”| Exit code | Meaning |
|---|---|
0 |
success; stdout optional |
2 |
explicit block (controllable events only) |
| other / timeout / output or input over limit | hook failure: warn and fail open, producing no decision |
Security notes
Section titled “Security notes”- The event JSON is the only data channel: never interpolate event fields into shell command strings.
- Commands should read JSON from stdin and emit valid JSON, avoiding injection and escaping issues.
- Hook output is scrubbed of terminal control characters; do not rely on stdout to echo sensitive information.
Related references
Section titled “Related references”Decisions
Section titled “Decisions”Decision entry points
Section titled “Decision entry points”| Event | Decision field | Effect |
|---|---|---|
PreToolUse |
hookSpecificOutput.permissionDecision: allow/ask/deny |
predicates permission: deny rejects outright (permission.hook_denied); ask forces human; allow bypasses the policy layer |
PermissionRequest |
hookSpecificOutput.decision.behavior: allow/ask/deny (optional message) |
fires when the policy layer needs a human; can override the final decision |
Stop |
top-level decision: "block" + reason |
injects feedback asking the model to continue |
controllable event + exit code 2 |
stderr as blockReason |
equivalent to deny/block |
Full PreToolUse order
Section titled “Full PreToolUse order”PreToolUsehook decision (includingupdatedInputandadditionalContext).- After an input update, re-validate everything: schema (fails as
hook.invalid_updated_input), structured file path, risk classification, and permissions. - Policy layer (
manual/smart/auto). - When a human is needed, fire the
PermissionRequesthook (reason: "policy";"hook"when a hook requested human review). - Human confirmation (inline in CLI/TUI).
- Execute the tool and fire
PostToolUse/PostToolUseFailure.
Merge semantics
Section titled “Merge semantics”Multiple hooks for the same event run in parallel, with results ordered by config order:
- Permission decisions merge as
deny > ask > allow(the most conservative wins). - Multiple
updatedInputvalues conflict and are all discarded (inputConflict); no update applies. - Any
blockedblocks the whole result. - Each
additionalContextinjects as a separate[CodeN hook context: <event>]message; the total is capped at 10KB.
Interaction with approval modes
Section titled “Interaction with approval modes”| Mode | Hook behavior |
|---|---|
manual |
PreToolUse decisions apply; policy asks a human; PermissionRequest can override |
smart |
same; ordinary modifications first go through LLM review, and hook deny beats an LLM allow |
auto |
PreToolUse still runs: deny applies; ask safely rejects (permission.hook_requires_interaction) |
Related references
Section titled “Related references”Examples
Section titled “Examples”macOS authorization notification
Section titled “macOS authorization notification”The PermissionRequest event fires when human authorization is needed. This sends a system notification while waiting (macOS):
{ "hooks": { "PermissionRequest": [{ "matcher": "bash|edit|write", "hooks": [{ "type": "command", "command": "osascript -e 'display notification \"CodeN 正在等待授权\" with title \"CodeN\"'; afplay /System/Library/Sounds/Glass.aiff", "timeout": 5 }] }] }}PreToolUse approval script (Node)
Section titled “PreToolUse approval script (Node)”Reads JSON from stdin and emits an allow decision; on parse failure it emits nothing (fail-open to the policy layer).
let input = "";process.stdin.setEncoding("utf8");process.stdin.on("data", (chunk) => (input += chunk));process.stdin.on("end", () => { JSON.parse(input); process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow" } }));});Matching configuration:
{ "hooks": { "PreToolUse": [{ "matcher": "bash", "hooks": [{ "type": "command", "command": "node /path/to/approve.js" }] }] }}Stop demand-more-work
Section titled “Stop demand-more-work”When the model stops, decision: "block" injects reason into the conversation and asks it to continue (still bounded by maxSteps):
{ "hooks": { "Stop": [{ "hooks": [{ "type": "command", "command": "echo '{\"decision\":\"block\",\"reason\":\"tests have not been run yet\"}'" }] }] }}Reading session variables
Section titled “Reading session variables”Hook environments provide CODEN_PROJECT_DIR, CODEN_SESSION_ID, and CODEN_HOOK_EVENT:
echo "project=$CODEN_PROJECT_DIR session=$CODEN_SESSION_ID event=$CODEN_HOOK_EVENT"