Skip to content

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.

  • matcher is a regular-expression string (compiled with new 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 example Stop has no matcher).
{
"hooks": {
"PreToolUse": [{
"matcher": "bash|edit|write",
"hooks": [{
"type": "command",
"command": "echo matched"
}]
}]
}
}
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)
  • The matcher accepts a string only; other types fail configuration.
  • The regex tests the target string (such as the bash tool 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.
  • Commands run through the system shell: POSIX /bin/sh -c <command>; Windows cmd /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
{
"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).

  • Allowed top-level fields: systemMessage (all events); Stop additionally allows decision ("block" only) and reason; other events use hookSpecificOutput with per-event allowlists.
  • systemMessage must be a string, scrubbed of control characters, truncated to 2000 characters, and forwarded to the diagnostic sink (stdout/stderr).
  • hookSpecificOutput.hookEventName must 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 0 with empty stdout: no-op.
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow"
}
}
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
  • 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.
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
  1. PreToolUse hook decision (including updatedInput and additionalContext).
  2. After an input update, re-validate everything: schema (fails as hook.invalid_updated_input), structured file path, risk classification, and permissions.
  3. Policy layer (manual/smart/auto).
  4. When a human is needed, fire the PermissionRequest hook (reason: "policy"; "hook" when a hook requested human review).
  5. Human confirmation (inline in CLI/TUI).
  6. Execute the tool and fire PostToolUse/PostToolUseFailure.

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 updatedInput values conflict and are all discarded (inputConflict); no update applies.
  • Any blocked blocks the whole result.
  • Each additionalContext injects as a separate [CodeN hook context: <event>] message; the total is capped at 10KB.
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)

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
}]
}]
}
}

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"
}]
}]
}
}

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\"}'"
}]
}]
}
}

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"