Hooks

Run deterministic shell commands at Droid lifecycle events for validation, policy, context injection, and automation.

Hooks are shell commands that run at defined points in a Droid session. Use them for deterministic behavior that should happen every time, such as validating tool calls, formatting changed files, injecting local context, logging activity, or enforcing team policy.

Warning

Hooks run automatically with your local environment and credentials. Review every hook command before registering it, use absolute script paths, and test in a safe environment first.

Quickstart

On macOS and Linux with jq installed, this example logs the command of each Execute tool call that reaches this PreToolUse hook.

  1. 1
    Open the hooks manager

    In Droid, run:

    /hooks

    The manager opens with User, Project, Plugins, and Effective tabs.

  2. 2
    Choose a level

    Select User to save the hook in ~/.factory/hooks.json, or Project to save it in .factory/hooks.json. The Plugins and Effective tabs are read-only.

  3. 3
    Add the hook

    Select Add hook command, choose the PreToolUse event, and set the matcher to Execute. Enter this command:

    Bash
    jq -r '.tool_input.command' >> ~/.factory/bash-command-log.txt
  4. 4
    Save and verify

    Save the hook, ask Droid to run a simple command, then inspect the log:

    Bash
    cat ~/.factory/bash-command-log.txt

The saved configuration looks like this:

~/.factory/hooks.json
{
  "PreToolUse": [
    {
      "matcher": "Execute",
      "hooks": [
        {
          "type": "command",
          "command": "jq -r '.tool_input.command' >> ~/.factory/bash-command-log.txt"
        }
      ]
    }
  ]
}

If you chose the Project tab, the same unwrapped structure is saved to .factory/hooks.json.

Droid reloads hooks when settings files change, with no restart needed. A change to the hooks that run posts a notice in the session (on stderr for droid exec, or as a hook_settings_changed event in stream-json) that lists up to 10 changes and counts the rest; changes that land within half a second of each other share one notice. Use /hooks to inspect the active configuration.

Configuration

Droid reads hooks from these levels, highest precedence first:

LevelSource
OrgOrg-managed settings from Enterprise Controls, and the hooks of plugins the org enables. See Org-managed hooks.
RuntimeThe file passed with --settings.
FolderInside a git repository, each .factory/ directory in the working directory and its parents below the git root, excluding the user settings directory, nearer ones first.
Project.factory/ at the git root, or in the working directory outside a git repository, excluding the user settings directory, and the hooks of plugins enabled for the project. Commit it to share hooks with teammates.
User~/.factory/, and the hooks of plugins enabled for your user.

Plugins contribute hooks at the level that enables them; see Plugin hooks.

Within one settings directory, Droid reads hooks from these files, highest precedence first:

FileNotes
settings.local.jsonUnder its hooks key. Never published by config sync.
hooks.json, or legacy hooks/hooks.json while hooks.json is absentKeyed directly by event name. The next save of a hook command writes hooks.json and archives the legacy file as hooks/hooks.migrated.json.
settings.jsonUnder its hooks key.

How sources combine

  • Matcher groups for the same event are concatenated across the levels and files whose hooks run, after the same-directory overrides below.
  • Within one settings directory, an event defined in hooks.json replaces the same event in that directory's settings.json. An explicit empty list in hooks.json, such as "Stop": [], clears that event's entries from the same directory's settings.json. Droid reports a replaced event whose entries differ.
  • A handler defined in more than one file or level runs once. Copies that differ only in timeout count as one handler, and that one run uses the longest timeout. A plugin's copy of the same handler stays separate.
  • When you save a hook command from /hooks, Droid writes it to the hooks.json of the level you chose. Hooks declared in settings.local.json, and settings.json entries replaced by hooks.json, are listed read-only with their file name.
Note

Use absolute paths in hook commands. Hooks execute from Droid's current working directory, not necessarily the repository root. FACTORY_PROJECT_DIR defaults to that same directory; it does not locate the repository root.

Disable hooks

hooksDisabled: true turns hooks off without deleting them; which hooks it stops depends on the level that sets it, as the list below describes. Set it at the top level of a hooks.json file, or inside the hooks key of settings.json, settings.local.json, a --settings file, or org-managed settings. The /hooks and /settings menus toggle it too, as a member setting that does not stop org-managed hooks.

.factory/settings.local.json
{
  "hooks": {
    "hooksDisabled": true
  }
}
  • Only an org true stops org-managed hooks and the hooks of org-enabled plugins. A member's true never does.
  • For user, project, and plugin hooks, the highest-precedence level that sets hooksDisabled decides: a --settings file, then folder, project, and user settings. An org false does not override a member's true.
  • Because a repository's project settings outrank your user settings, use a --settings file to keep hooks off in a repository you do not trust.
  • Under a member's hooksDisabled: true, /hooks lists the org hooks that still run under the heading "Organization hooks only".

Structure

Standalone hooks.json files are keyed directly by event name. Each event contains matcher groups, and each group contains an array of hook commands.

~/.factory/hooks.json
{
  "PreToolUse": [
    {
      "matcher": "Execute",
      "commandRegex": "^git ",
      "hooks": [
        {
          "type": "command",
          "command": "/usr/local/bin/audit-git-command.sh",
          "timeout": 30
        }
      ]
    }
  ]
}

When you declare hooks inside settings.json instead, wrap the same event map in a top-level hooks key:

~/.factory/settings.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Execute",
        "commandRegex": "^git ",
        "hooks": [
          {
            "type": "command",
            "command": "/usr/local/bin/audit-git-command.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}
FieldRequiredBehavior
matcherNoSelects when the group runs. See Matchers.
commandRegexNoDroid extension. On PreToolUse and PostToolUse, a regular expression tested against the shell command of an Execute call: the group runs only for Execute calls whose command matches. An empty string filters nothing, and other events ignore the field.
hooksYesArray of hook commands for the matcher group.
typeYesCurrently only "command" is supported.
commandYesShell command executed with JSON hook input on stdin. In a plugin hook file that sets args, the executable to run.
argsNoPlugin hook files only. Argument list for command. Outside per-command sandboxing, Droid spawns command directly with these arguments and no shell. See Exec form.
timeoutNoWhole seconds from 1 to 2147483. Defaults to 60.
preserveRiskLevelNoPreToolUse only. When this hook rewrites an Execute command through updatedInput, keep the model's riskLevel; with several hooks, every hook that returns updatedInput must set it. See PreToolUse control.
onFailureNo"continue" (default) or "block". With "block", a failure of this hook blocks the event the way exit 2 would, except on Stop, SubagentStop, and events that cannot block. See Block when a hook fails.

Validation

Droid validates hook settings entry by entry. An invalid hook command is dropped on its own, an invalid matcher group drops only its own commands, and an invalid timeout, preserveRiskLevel, or onFailure falls back to its default when the rest of the command is valid. Droid reports each one with the file and the JSON path of the entry, for example:

~/.factory/hooks.json: Stop[0].hooks[1].timeout: Expected a whole number of seconds from 1 to 2147483
InputResult
timeout that is not a whole number from 1 to 2147483Reported, and the hook runs with the default of 60 seconds.
preserveRiskLevel or onFailure with an invalid valueReported, and the hook runs as if the field were not set.
args outside a plugin hook fileThe hook command is ignored and reported: "args" (exec form) runs only in plugin hooks; write the whole command line in "command".
A matcher read as a regular expression that does not compile, on an event with a matched field, or a commandRegex that does not compile, on PreToolUse or PostToolUseThe matcher group is ignored and reported.
Unsupported hook type (prompt, agent, http, mcp_tool)Entry ignored and reported: Hook type "prompt" is not supported; only "command" hooks run.
Unknown or unsupported event key, such as PermissionRequestIgnored and reported with the list of supported events.
An exact matcher name that can never match on the event, such as PreCompact: "Execute"Group kept and reported as Hook matcher never matches:. Regular expressions are not checked this way.
JSONC comments or a UTF-8 byte order markAccepted.
JSON syntax errorThe file's hooks do not load, and the error is reported with its line and column.

Hook issues appear in /diagnostics. droid exec prints on stderr the issues from the levels whose hooks run. When hook settings change, the notice Droid posts lists the issues that were not there before the change. While hooks.json has entries Droid ignored or reset to a default, /hooks refuses to save that file, so a save cannot delete them.

Hook events

EventRuns whenCommon use
PreToolUseAfter Droid builds and validates tool parameters and before the tool runs. A call that input validation or a permission rule denies first does not reach it.Block risky operations, approve safe tools, rewrite tool input.
PostToolUseAfter a tool call completes and returns its result. A cancelled call, a call that ends in an error instead of a result, and a tool call made from inside the Script tool do not fire it. An Execute call ends in an error when Droid reports its command as failed: ls on a missing directory, for example, does not fire the hook.Format files, run validation, add feedback after an edit.
UserPromptSubmitBefore Droid processes a prompt the user submits. It does not run for a prompt SessionStart refused, in a Task subagent's session, for the turn that delivers a background Task's result, or for an answer to a question Droid asked.Validate prompts or inject extra context.
NotificationWhen Droid asks for permission, asks for structured input in an elicitation dialog, or the user stops a turn. See Notification types.Desktop alerts or compliance logging.
StopWhen a turn is about to end, unless the user stopped it.Require final checks or continue with follow-up instructions.
SubagentStopWhen a foreground or background Task subagent finishes, in the parent session.Validate or log subagent output.
PreCompactBefore manual or automatic compaction.Save context or audit compaction.
SessionStartWhen a session starts or resumes, and after a compaction of the current session completes. A /btw side question does not fire it.Load local context at session start.
SessionEndWhen a session ends. A /btw side question and a remote session you are only viewing do not fire it.Cleanup, audit logs, session summaries.

Notification types

TypeSent when
permission_promptDroid asks you for permission to run a tool call.
idle_promptThe user stops a turn, including during a running tool. A turn that ends on its own does not send it.
elicitation_dialogDroid needs structured input in an elicitation dialog.

Cancellation emits the informational Notification hook instead of Stop, so a hook cannot override the user's decision to stop the turn.

Matchers

The matcher field filters when a group runs. Droid reads a matcher as follows:

Matcher valueEvaluated asExample
"*", "", or omittedMatches everything.No matcher filter.
Only ASCII letters, digits, _, -, spaces, |, and ,A list of exact names separated by | or ,. Whitespace around names is trimmed and empty names are dropped.Read matches only Read. Create|Edit and Create, Edit each match either tool. Read| matches only Read.
Contains any other characterA case-sensitive JavaScript regular expression, not anchored.Edit.* matches Edit and any tool whose name contains Edit. Use ^Edit$ for a whole-name match.

A matcher also matches every call when the hook input has no value for the matched field.

Each event matches a different input field:

EventMatched fieldValues
PreToolUse, PostToolUsetool_nameTool names, such as Execute, Read, Edit, Create, ApplyPatch, LS, Glob, Grep, Task, FetchUrl, and WebSearch.
SessionStartsourcestartup, resume, clear, compact. See SessionStart timing.
SessionEndreasonclear, logout, prompt_input_exit, other
Notificationnotification_typepermission_prompt, idle_prompt, elicitation_dialog
PreCompacttriggermanual, auto. A compaction requested by the model uses auto.
UserPromptSubmit, Stop, SubagentStopNoneA string matcher is ignored.

Claude Code tool names

An exact-name matcher also accepts Claude Code tool names, so an exact-name matcher copied from Claude Code selects the Droid tool it names:

Claude Code nameDroid tool
BashExecute
WriteCreate
WebFetchFetchUrl
AgentTask
mcp__<server>__<tool>The MCP tool registered under that server and tool name.
  • A regular expression is tested against the Droid name only. A pattern that excludes Bash, such as ^(?!Bash$).*, still runs for Execute, because the Droid name Execute matches it.
  • ApplyPatch is not aliased to Edit, because its tool_input has no file_path. Add ApplyPatch to file-editing matchers explicitly.
  • Hook input always reports the Droid tool name. A script copied from Claude Code that checks tool_name == "Bash" takes the wrong branch; check for Execute as well.
  • commandRegex applies whenever tool_name is Execute, including under a Bash matcher.

MCP tools

Use the exact name mcp__<server>__<tool> for one MCP tool. A regular expression is tested against the Droid name of an MCP tool, <server>___<tool>, so mcp__.* does not select MCP tools by their Claude Code names; use <server>___.* to select every tool from one server. A server name with no tool part, such as mcp__memory, contains only exact-name characters, so it matches nothing; Droid reports it at load with the fix.

Hook input

Every hook receives JSON on stdin. These fields are common to every event:

TypeScript
{
  session_id: string
  transcript_path: string
  cwd: string
  permission_mode: "off" | "spec" | "auto-low" | "auto-medium" | "auto-high"
  hook_event_name: string
  message_id?: string
}

Event-specific fields:

EventFields
PreToolUsetool_name, tool_input
PostToolUsetool_name, tool_input (after any updatedInput rewrite), tool_response
UserPromptSubmitprompt (the text as typed, before slash-command or skill expansion), has_images, session_title (only when the title was set by hand)
Notificationmessage, notification_type
Stopstop_hook_active, tool_execution_count, elapsed_time
SubagentStoptask_name, task_result (an optional string), task_error (optional), stop_hook_active (always false)
PreCompacttrigger, custom_instructions, message_count, estimated_tokens
SessionStartsource, previous_session_id and calling_session_id when present, and CLAUDE_ENV_FILE when available (see Persist environment variables)
SessionEndreason, session_duration_ms (measured from when the session's transcript file was created), message_count (the number of message records in the transcript)

Tool hooks add tool-specific fields:

JSON
{
  "session_id": "abc123",
  "transcript_path": "/Users/.../.factory/projects/.../session.jsonl",
  "cwd": "/Users/me/project",
  "permission_mode": "off",
  "hook_event_name": "PreToolUse",
  "tool_name": "Create",
  "tool_input": {
    "file_path": "/Users/me/project/file.txt",
    "content": "file content"
  }
}

PostToolUse includes tool_response as well. The exact shape of tool_input and tool_response depends on the tool.

Environment variables

Hook processes inherit a filtered copy of Droid's environment, and Droid sets these variables:

VariableValue
session_id, transcript_path, cwd, permission_mode, hook_event_name, message_idThe hook input's value when it is a string without a NUL character; otherwise unset. A value inherited from the parent process, or set by an org or agent environment override, never replaces it.
CLAUDE_ENV_FILESessionStart hooks only. See Persist environment variables.
FACTORY_PROJECT_DIR, DROID_PROJECT_DIR, CLAUDE_PROJECT_DIRDroid's working directory when the hook runs, unless an agent environment override sets the variable.
CLAUDE_PLUGIN_ROOT, DROID_PLUGIN_ROOT, CLAUDE_PLUGIN_DATA, DROID_PLUGIN_DATASet for plugin hooks. See Plugin hooks.

Droid does not set other input fields, such as prompt, tool_name, or source, as environment variables; read them from stdin.

Permission mode

permission_mode reports the autonomy level in effect when the hook runs, after any maximum your organization sets. In droid exec, the flags map to the values below. A lower organization maximum lowers auto-low, auto-medium, and auto-high to that maximum, which can be off, and leaves spec as it is.

droid exec runpermission_mode
No --auto (read-only)auto-low
--auto low, --auto medium, --auto highauto-low, auto-medium, auto-high
--skip-permissions-unsafeauto-high
--use-specspec

How hooks run

  • Outside per-command sandboxing, Droid runs a hook command that has no args with /bin/sh -c on macOS and Linux. On Windows, it uses the command processor that the ComSpec environment variable names when that is an absolute path, and cmd.exe otherwise, with /d /s /c.
  • The hooks that match an event run in parallel, and Droid combines their results in configuration order. See Multiple hooks.
  • A hook that cannot start counts as exit 1 with the start error as its stderr; the other hooks' results are kept.
  • When per-command sandboxing is on, Droid wraps hook commands in the sandbox as it does Execute commands. See Sandbox.
  • During a /btw side question, only PreToolUse hooks run.
  • A cancelled hook's output does not apply, and the cancellation is not an error.
  • Once a hook's process exits, Droid waits up to one second for the rest of its output, even if a background process the hook started still holds stdout or stderr open.

Hooks on Windows

On Windows, cmd.exe runs hook commands, so a command written for a macOS or Linux shell fails there:

  • cmd.exe expands %NAME%, not $NAME. Write %FACTORY_PROJECT_DIR%; $FACTORY_PROJECT_DIR reaches cmd.exe as literal text.
  • cmd.exe cannot run a .sh script. Run the script with an interpreter such as python, node, or PowerShell, or write it as a .cmd file.

A command that cannot start fails each time its event fires. A PreToolUse hook with the command "$FACTORY_PROJECT_DIR"/.factory/hooks/check-command.sh reports this hook error on every matching tool call:

'"$FACTORY_PROJECT_DIR"' is not recognized as an internal or external command,
operable program or batch file.

This project hook runs a Python script on Windows, including from a project path that contains spaces:

.factory/hooks.json
{
  "PreToolUse": [
    {
      "matcher": "Execute",
      "hooks": [
        {
          "type": "command",
          "command": "python \"%FACTORY_PROJECT_DIR%\\.factory\\hooks\\check_command.py\""
        }
      ]
    }
  ]
}

Other kinds of script take the same form. In hooks.json, escape each " and \ in these commands as the example above does:

ScriptCommand
PowerShellpowershell -NoProfile -ExecutionPolicy Bypass -File "%FACTORY_PROJECT_DIR%\.factory\hooks\check-command.ps1"
Batch file"%FACTORY_PROJECT_DIR%\.factory\hooks\check-command.cmd"
Existing .sh script, run with the Bash that Git for Windows installs"%ProgramFiles%\Git\bin\bash.exe" "%FACTORY_PROJECT_DIR%/.factory/hooks/check-command.sh"

Name Git for Windows' bash.exe by its path: a bare bash can resolve to the WSL bash.exe in C:\Windows\System32 instead.

Hooks committed to a project, and org-managed hooks, run on every teammate's machine. To run one hook on Windows, macOS, and Linux, package it in a plugin and use exec form with an interpreter that every platform has, such as node. Exec form starts the program without a shell.

Hook output

Hooks communicate through exit codes, stderr, stdout, and optional JSON emitted on stdout. Exit code 2 always blocks where the event can block. On any other exit code, valid JSON on stdout decides the result. Output that looks like JSON but cannot be applied is a non-blocking error on any exit code but 2. With plain-text stdout, exit 0 is a success and any code other than 0 or 2 is a non-blocking error. A hook that sets onFailure: "block" on PreToolUse, PostToolUse, UserPromptSubmit, or PreCompact blocks instead of each of those non-blocking errors, and on a non-zero exit with valid JSON as well (see Block when a hook fails).

OutputEffect
Exit code 0Success, unless stdout looks like JSON that cannot be applied (see How Droid reads stdout). JSON on stdout applies its fields. Plain stdout is added as context for UserPromptSubmit and SessionStart; for other events, it is visible in transcript views.
Exit code 2Blocks, whatever stdout contains. The reason is stderr, unless the hook's JSON also blocks and gives its own reason; with empty stderr and no JSON reason, it is the event's default reason, such as Tool execution blocked by hook for PreToolUse. PreToolUse blocks the tool call, PostToolUse and Stop feed the reason back to Droid, UserPromptSubmit blocks the prompt, and a manual PreCompact is blocked. SubagentStop and automatic PreCompact cannot be blocked, so Droid shows the reason to the user. On Notification, SessionStart, and SessionEnd, exit 2 is a non-blocking error and none of the hook's JSON applies, continue: false included: Droid shows stderr; if stderr is empty, the plain text the hook printed to stdout; if there is neither, Hook exited with code 2.
Any other non-zero exitIf stdout is valid JSON, its fields apply exactly as on exit 0 and the hook counts as succeeded, unless the hook sets onFailure: "block" on PreToolUse, PostToolUse, UserPromptSubmit, or PreCompact (see Block when a hook fails). With plain-text or empty stdout, the hook is a non-blocking error: Droid shows the user stderr; if stderr is empty, the plain text the hook printed to stdout; if there is neither, Hook exited with code N. Droid then continues. Plain stdout is not added as context.
TimeoutNon-blocking error, shown as Hook timed out after Ns, unless the hook sets onFailure: "block" on PreToolUse, PostToolUse, UserPromptSubmit, or PreCompact. Anything the hook printed before the timeout is discarded, so a decision it printed does not count.
JSON continue: falseDroid shows stopReason to the user, or Hook requested to stop execution when the hook gives none. What stops, if anything, depends on the event: see Control by event. In droid exec, a stop from a hook on a tool call the model made directly ends the turn as an error whose message is the stopReason.
JSON systemMessageShown to the user as a hook warning, and never sent to the model. Droid truncates it to 10,000 characters.
JSON suppressOutput: trueHides successful hook output from the main chat view while preserving it in the detailed transcript.

On a hook's row, stdout, stderr, and error text share a limit of 1,000,000 characters. Droid reads the hook's decision before it cuts the text to fit the row.

How Droid reads stdout

Droid treats stdout as JSON only when the trimmed text starts with {, ends with }, and is either the empty object {} or an object that sets at least one output field: continue, stopReason, suppressOutput, systemMessage, decision, reason, or hookSpecificOutput. A leading byte-order mark is trimmed like whitespace. {} is valid JSON output that changes nothing.

Plain text is text that does not start with { and end with }, a single nonempty JSON object that sets none of those fields, such as the log line {"message": "done"}, or several JSON objects on separate lines, none of which sets one of those fields (blank lines between them are ignored). Text in braces that is neither JSON output nor plain text by these rules fails the hook, as described next.

Output that looks like JSON but cannot be applied makes the hook fail, even on exit 0, and none of its fields apply: the failure is a non-blocking error, or a block when the hook sets onFailure: "block" on an event where that blocks. The hook's row shows the parse or validation message. When hook rows are hidden, a non-blocking failure shows it as a notice, and a failure that blocks shows it in the block reason. This covers:

  • Text that starts with { and ends with } but does not parse, unless each of its lines is a JSON object that sets no output field, which is plain text as above.
  • A field with the wrong type or an unknown value, such as hookSpecificOutput.permissionDecision: "defer".
  • hookSpecificOutput.hookEventName naming a different event from the one that ran.

An output field set to null counts as absent, so "reason": null next to a deny still denies. Values inside updatedInput are tool parameters, and a null there is kept in the rewritten input, which must still pass tool validation.

Warning

By default, invalid JSON fails open: a policy hook whose output fails validation does not block the tool call. To make a policy hook fail closed, set onFailure: "block" on it (see Block when a hook fails), or exit 2 and write the reason to stderr.

Block when a hook fails

Set onFailure: "block" on a hook command to make its failures block instead of being non-blocking errors. A hook fails when:

  • It cannot start.
  • It times out.
  • It exits with a code other than 0 or 2 and its stdout is plain text or empty. On an event where "block" applies, any stdout fails it: valid JSON that allows the action, or {}, still counts as a failure. A hook that returns a JSON decision exits 0.
  • Its stdout looks like JSON but cannot be applied (see How Droid reads stdout).

A hook cancelled because you stopped Droid has not failed.

A failure under "block" acts as exit 2 on that event: PreToolUse denies the tool call, PostToolUse feeds the reason back to Droid, UserPromptSubmit blocks the prompt, and a manual PreCompact is blocked. The reason names the event and the failure, for example PreToolUse hook failed (onFailure: "block"): <error>, or after a timeout PreToolUse hook timed out after 60s (onFailure: "block"). onFailure has no effect on Stop, where a block would keep Droid running, on SubagentStop, or on events that cannot block; there a failure stays a non-blocking error.

.factory/hooks.json
{
  "PreToolUse": [
    {
      "matcher": "Execute",
      "hooks": [
        {
          "type": "command",
          "command": "\"$FACTORY_PROJECT_DIR\"/.factory/hooks/check-command.sh",
          "onFailure": "block"
        }
      ]
    }
  ]
}

A value other than "continue" or "block" is reported when Droid loads the settings (in /diagnostics, in the footer's configuration issue count, and on droid exec's stderr), and the hook runs with "continue".

Multiple hooks

When several hooks match one event, they run in parallel. Droid reads each hook's result as described above, then combines the results in configuration order:

  • The strongest result wins: continue: false, then a block or deny, then ask, then allow, then no decision. One deny blocks a tool call even when another hook allowed it.
  • Droid joins the distinct reasons for a block or a stop, one per line. It limits the joined reason to 1,000,000 characters for a block and 10,000 for a stop.
  • Context from the hooks that ran shares a limit of 1,000,000 characters. Whether it reaches the model depends on the event (see Control by event).
  • Droid keeps each systemMessage from a hook whose output applies and reports each non-blocking error. A failure that blocks is reported as the block reason instead.
  • For PreToolUse, unless the batch blocks or stops, every hook's updatedInput applies in configuration order, whatever the decision. When two hooks set the same field, the later one wins. When the combined updatedInput changes an Execute command, the model's riskLevel is kept only when every hook that returned updatedInput sets preserveRiskLevel.

PreToolUse control

Use hookSpecificOutput.permissionDecision for tool-call control:

JSON
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "Documentation reads are safe",
    "updatedInput": {
      "file_path": "/Users/me/project/README.md"
    }
  }
}
DecisionEffect
allowRuns the call without the permission prompt, even where the session's autonomy level would have asked. It does not get a call past input validation, a permission rule block, spec mode, the sandbox, or the restrictions of a /btw side question.
denyBlocks the tool call and sends the reason to Droid. Without permissionDecisionReason or reason, the reason is Tool execution blocked by hook.
askDoes not allow the call: normal permissions apply, at every autonomy level, so a call they would run without asking runs without a prompt. One ask overrides another hook's allow. A hook that wants the call stopped returns deny with a reason.

Droid also reads the older top-level decision field: decision: "approve" acts like allow, and decision: "block" acts like deny. When both are set, permissionDecision wins.

updatedInput sets the tool parameters it names before the tool runs; parameters it leaves out keep the values Droid chose. Droid checks the rewritten input again: a rewrite that makes the input invalid, or that a permission rule blocks, denies the tool call, and the sandbox applies to the rewritten input. When a hook changes an Execute command, Droid drops the model's riskLevel, unless the hook command sets preserveRiskLevel: true. Where permission checking depends on the risk level, a command without one counts as high risk. With several hooks, every hook that returned updatedInput must set it, as above. Set it only when the rewrite does not change what the command does, such as prepending environment setup.

  • hookSpecificOutput.additionalContext from a PreToolUse hook does not reach the model.
  • Each systemMessage from a hook whose output applies, and each non-blocking error, is shown to the user before the decision takes effect.
  • Hooks are code you or your organization register. Use org-managed hooks and allowManagedHooksOnly to control which hooks can approve calls.

Return a refusal reason to an SDK session

When your application starts the local CLI through the TypeScript SDK, pass a hook in a settings file with execArgs: ['--settings', path]. This is a CLI launch setting, not a typed SDK hook option. A PreToolUse hook that returns deny blocks the matching call without asking for approval. Droid receives permissionDecisionReason in the tool result and can quote it in the same turn.

To keep Droid from editing the launch file, enable the sandbox and keep the file outside both the session's repository and any other directory you let Droid write to. Set hooksDisabled: false in the launch file so a project setting cannot turn the hook off. Without it, a project hooksDisabled: true turns the launch hook off. Because --settings outranks folder, project, and user settings, its hooksDisabled: false also lets user and project hooks run, including hooks from plugins enabled at those levels, when a lower-precedence setting disabled them. Review the user, repository, and plugin hooks that will run before you start the session. Droid can still add a hook to the project's .factory/hooks.json: the project hook takes effect in the same session without replacing the launch hook.

Set onFailure: "block" on the hook so a timeout or hook failure denies the tool call. Without it, a failure does not block the call, and in this example Execute then runs at High autonomy without asking for approval. An explicit deny, or exit code 2, blocks the call either way.

If your Enterprise organization sets allowManagedHooksOnly, register the hook as an org-managed hook instead.

To try this on Linux, install bubblewrap and socat, use Node.js 22, and set FACTORY_API_KEY. Without either tool, the sandbox refuses the Execute call before the hook runs, so the example fails. Save these two files together in an empty directory. The hook matches Execute; the program gives Droid a separate, temporary working directory and checks the tool result, the approval count, and the file, and prints Droid's reply.

settings.json
{
  "sandbox": { "enabled": true },
  "hooks": {
    "hooksDisabled": false,
    "PreToolUse": [{
      "matcher": "Execute",
      "hooks": [{
        "type": "command",
        "command": "printf '%s\\n' '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"Shell commands are disabled in this editor.\"}}'",
        "onFailure": "block"
      }]
    }]
  }
}
example.mts
import assert from 'node:assert/strict';
import { existsSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { AutonomyLevel, ToolConfirmationOutcome, createSession } from '@factory/droid-sdk/node';
 
const cwd = mkdtempSync(join(tmpdir(), 'hook-demo-'));
const reason = 'Shell commands are disabled in this editor.';
let approvals = 0;
const session = await createSession({
  cwd,
  execPath: resolve('node_modules/.bin/droid'),
  execArgs: ['--settings', resolve('settings.json')],
  autonomyLevel: AutonomyLevel.High,
  permissionHandler: () => {
    approvals++;
    return ToolConfirmationOutcome.Cancel;
  },
});
try {
  const prompt = 'Use Execute once to run: touch ready.txt. If refused, reply only with the exact reason. Do not retry or create the file another way.';
  let sawReason = false;
  for await (const event of session.stream(prompt)) {
    if (event.type === 'tool_result' && event.toolName === 'Execute') {
      console.log('Execute:', event.content);
      sawReason = event.isError && String(event.content).includes(reason);
    }
    if (event.type === 'result') console.log('Droid:', event.text);
  }
  assert.ok(sawReason);
  assert.equal(approvals, 0);
  assert.equal(existsSync(join(cwd, 'ready.txt')), false);
  console.log('No approval request; ready.txt was not created.');
} finally {
  await session.close();
}

Run the example from the directory containing both files:

Bash
npm init -y
npm install @factory/[email protected] @factory/[email protected] [email protected]
npx tsx example.mts

Output from one run. When Droid makes the call from inside its Script tool, as current default models do, the tool result starts with Script policy rejected this inner tool call:. A direct call returns the reason after an Error: prefix. Droid's reply is worded by the model.

Execute: Script policy rejected this inner tool call: Shell commands are disabled in this editor.
Droid: Script policy rejected this inner tool call: Shell commands are disabled in this editor.
No approval request; ready.txt was not created.

Control by event

EventEffect
PreToolUsecontinue: false ends the turn before the tool runs. For a tool call made from inside the Script tool, it fails that one call instead, and the script can catch the error. For permission decisions and updatedInput, see PreToolUse control.
PostToolUsedecision: "block" sends reason back to Droid after the tool ran. Without a reason, Droid receives PostToolUse hook reported an issue. Droid saves the block reason and any hookSpecificOutput.additionalContext after the tool results so the model receives them even after you reload the session. continue: false keeps the tool's result, cancels the message's remaining tool calls, and ends the turn.
UserPromptSubmitdecision: "block" or continue: false prevents the prompt from being processed: Droid shows Hook blocked submission: <reason> and hands the prompt back unsent, except in a one-shot droid exec run, which fails without sending the prompt to the model. Without a reason, the reason is User prompt submission blocked by hook for a block and Hook requested to stop execution for continue: false. additionalContext is appended when not blocked. A hook cannot rewrite the prompt: hookSpecificOutput.updatedInput blocks it with UserPromptSubmit hooks cannot rewrite the prompt; return decision: "block" instead.
NotificationResults are informational: continue: false stops nothing.
Stopdecision: "block" asks Droid to keep going, and reason becomes Droid's next instruction. Without a reason, Droid continues with Stop hook requested continuation. When another hook returns continue: false, the turn stops; a Stop hook that exits 2 keeps its block even if its own JSON sets continue: false. See Stop continuations for when a block does not continue the turn.
SubagentStopNeither a block nor continue: false keeps the subagent running or changes its result. Droid shows the reason to the user as a hook warning; a block without a reason shows SubagentStop hook requested continuation.
PreCompactdecision: "block", continue: false, or exit 2 blocks a manual compaction. These hook decisions do not block automatic compaction. Droid shows the reason to the user, or PreCompact hook requested to block compaction when the hook gives none. Stdout and additionalContext stay on the hook's row and do not reach the summarizer.
SessionStarthookSpecificOutput.additionalContext, or plain stdout on exit 0, is added as context for the model. On session start or resume, continue: false refuses the next user prompt after the hooks finish, before UserPromptSubmit runs. It refuses only that prompt. After compaction of the current session, it does not refuse a prompt. See SessionStart timing.
SessionEndCannot block session termination, and continue: false stops nothing. Use it for cleanup and logging.

When a PreToolUse or PostToolUse hook ends a turn, Droid saves the stop reason so the model receives it on its next turn, even after you reload the session.

Stop continuations

The Stop input has stop_hook_active: true only when a Stop hook asked Droid to continue. Check it before blocking again. tool_execution_count is the number of tool calls that started running in the current agent run, and elapsed_time is the milliseconds since that run started; both start again after a continuation.

A Stop hook's additionalContext and plain stdout do not reach the model; only a block reason continues the turn. The turn ends without continuing, whatever a block asked for, when the user stops it, when Droid ended the turn for repeating identical tool calls, when a PreToolUse or PostToolUse hook ended the turn, or when Droid could not save the prompt, a tool result, or the hook feedback that follows it.

SessionStart timing

  • In a local session, /clear and /new start the replacement session with source: "clear" and the replaced session's ID in previous_session_id. Resuming the replacement later reports resume.
  • When you run /clear or /new while viewing a session on another machine in the TUI, the replacement also reports clear and previous_session_id. This applies from the CLI release after 1.13.1. In 1.13.0 and 1.13.1, the hooks on that machine receive startup with no previous_session_id.
  • SessionStart cannot prevent the session from opening. Exit 2 and other failures are non-blocking errors shown to the user, never to the model.
  • When a session starts or resumes, Droid waits up to 60 seconds by default for its SessionStart hooks. Their context goes with the first user prompt Droid accepts after they finish, even when they finish after that wait.
  • A Stop, such as pressing Esc, does not end the SessionStart hooks that run when a session starts or resumes. They end when they finish or reach their timeout, when the session closes or Droid shuts down, or, on macOS and Linux, when a one-shot droid exec run receives SIGINT, SIGTERM, or SIGHUP.
  • After a compaction, Droid waits for the compact hooks, each up to its own timeout, and files their context with the summary, so the next requests carry it.
  • If the session or Droid's working directory changes before the hooks finish, Droid discards their context and environment exports.

Task subagents

HookIn a Task subagent
SessionStartRuns when the subagent's session starts. For a subagent that Task starts, calling_session_id is the parent session's ID.
UserPromptSubmitDoes not run in a Task subagent's session, including when a person resumes that session directly.
SubagentStopRuns in the parent session when the subagent finishes. Its input has no agent_type, and the matcher is ignored.

Persist environment variables

SessionStart hooks can write export NAME=value lines to the file named by CLAUDE_ENV_FILE.

Bash
#!/bin/bash
echo 'export NODE_ENV=development' >> "$CLAUDE_ENV_FILE"

On macOS and Linux:

  • Each hook command gets its own file. If it exits 0 and writes a nonempty regular file, Droid saves that file for the session. A nonzero exit or an empty file leaves that command's previous file in place. Inside a whole-process sandbox, SessionStart gets no CLAUDE_ENV_FILE.
  • Before each Execute command outside a /btw side question, and before each TUI ! command, the shell sources the saved files. Files from the same run are sourced in configuration order. export PATH="$PATH:./bin" expands the shell's current PATH; use unset NAME to clear a variable in the shell.
  • Saved files survive a restart of the session. Outside a whole-process sandbox, a fork, handoff session, or Task subagent on the same machine starts with a copy of its parent session's files, when your current organization can see that session. A /btw side question does not copy them.
  • Removing a hook does not remove its saved file. The command shell skips files from member hooks while member hooks are disabled, and files from org hooks while org hooks are disabled.
  • When hooks run without a sandbox, Droid also sources the files in a separate Bash process and imports their exports for later hooks, newly started stdio MCP servers, and apiKeyHelper. This applies from the CLI release after 1.13.1. In 1.13.0 and 1.13.1, the files set up command shells but do not supply exports to Droid itself or those other processes. Droid does not import a variable that it sets itself for commands. Use names that your organization's settings do not also set.

On Windows, all the event's hooks share one file. Droid reads it after the hooks finish regardless of exit code, adds the accepted exports to its own environment, and deletes the file. It reads export NAME=value lines without running shell code: after trimming whitespace, it takes the value after the first = and removes one pair of surrounding quotes. References such as $PATH stay literal, and a later assignment to the same name wins.

When importing into its own environment, Droid rejects an entry that contains a NUL character or exceeds the operating system's per-entry limit. It rejects the batch if it would grow that environment beyond half the size limit for command arguments and environment combined. A notice names the rejected variables, not their values. These checks do not change the files that command shells source on macOS and Linux.

Plugin hooks

Installed plugins can provide hooks. Droid loads hooks/hooks.json from the plugin root, or hooks.json at the root when the plugin has no hooks/hooks.json, then the hooks field of the plugin manifest, and merges them with user, project, and managed hooks when the plugin is enabled. The hooks file can hold the event map directly or wrap it in a top-level hooks key.

my-plugin/
├── .factory-plugin/
│   └── plugin.json
├── hooks/
│   ├── hooks.json
│   └── format.sh
└── ...

On macOS and Linux, with an executable hooks/format.sh in the plugin:

JSON
{
  "PostToolUse": [
    {
      "matcher": "Create|Edit|ApplyPatch",
      "hooks": [
        {
          "type": "command",
          "command": "\"${DROID_PLUGIN_ROOT}/hooks/format.sh\"",
          "timeout": 30
        }
      ]
    }
  ]
}
VariableValue
CLAUDE_PLUGIN_ROOT, DROID_PLUGIN_ROOTThe installed plugin directory.
CLAUDE_PLUGIN_DATA, DROID_PLUGIN_DATAA persistent data directory for the plugin, kept across plugin updates and created on first use.
  • Droid sets these variables for the plugin's own hook processes.
  • In a shell-form command, Droid replaces ${DROID_PLUGIN_ROOT}, $DROID_PLUGIN_ROOT, ${CLAUDE_PLUGIN_ROOT}, $CLAUDE_PLUGIN_ROOT, and the same spellings of the data variables with their paths when it loads the plugin's hooks on macOS and Linux. On Windows, it rewrites them to %DROID_PLUGIN_ROOT%-style references, which cmd.exe reads from the hook's environment.
  • In exec form, Droid substitutes references such as ${DROID_PLUGIN_ROOT} when the hook runs.
  • A plugin's hook files contribute hook events only. hooksDisabled or showHookOutput in a plugin hook file is reported and ignored.

Outside plugins, use an absolute path.

Manifest hooks

The hooks field in .factory-plugin/plugin.json (or .claude-plugin/plugin.json, renamed at install) loads after hooks/hooks.json. It accepts:

  • A path that starts with ./, naming a file that wraps its event map in a top-level hooks key.
  • An inline event map.
  • An array of these.

Droid reports an unusable entry with its source file and JSON path, for example a missing ./ prefix, a path outside the plugin, a missing file, a file already loaded, or a file without the hooks wrapper.

Exec form

In a plugin hook file, args supplies the arguments for command, one per element. Outside per-command sandboxing, Droid spawns command directly with no shell. In command and in each argument, Droid substitutes a braced ${NAME} reference to one of the plugin variables above or to FACTORY_PROJECT_DIR, DROID_PROJECT_DIR, or CLAUDE_PROJECT_DIR. It leaves the unbraced $NAME form and references to other variables as written.

JSON
{
  "type": "command",
  "command": "node",
  "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/format.js", "--fix"]
}
  • Use shell form (no args) for pipes, &&, and redirects.
  • On Windows, exec form needs a real executable: the .cmd and .bat shims that npx and other tools install need shell form, or run the script with node directly.

Org-managed hooks

Organizations can define authoritative hooks in Enterprise Controls through managed settings. Org hooks run unless org-managed settings set hooks.hooksDisabled: true, and lower levels cannot remove them.

FieldDescription
hooksOrg-defined hook settings keyed by event name, using the same structure as hooks.json. Entries are validated as described under Validation, and saving managed settings rejects an entry with an invalid value.
hooks.hooksDisabledWhen true, no hooks run, org hooks included. See Disable hooks.
allowManagedHooksOnlyWhen true, only org-managed hooks and hooks from org-enabled plugins load. User, project, and other plugin hooks are ignored.
JSON
{
  "allowManagedHooksOnly": true,
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Execute",
        "hooks": [
          {
            "type": "command",
            "command": "/usr/local/bin/audit-command.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

See Enterprise Controls & Managed Settings for how org, project, folder, and user settings merge.

Hooks in droid exec

droid exec does not ask for folder trust, and an untrusted repository does not stop it from running project hooks or the hooks of plugins the project enables. To keep them off, pass a --settings file as described in Disable hooks. See Hooks in droid exec for how a blocked prompt ends a run and where droid exec prints hook notices.

Examples

These examples use macOS or Linux shell syntax; on Windows, write them as Hooks on Windows shows. Supply the scripts named in command; paths using $FACTORY_PROJECT_DIR are relative to Droid's working directory.

Format changed TypeScript files

JSON
{
  "PostToolUse": [
    {
      "matcher": "Create|Edit|ApplyPatch",
      "hooks": [
        {
          "type": "command",
          "command": "python3 \"$FACTORY_PROJECT_DIR\"/.factory/hooks/format_changed_file.py"
        }
      ]
    }
  ]
}

Block edits to sensitive files

JSON
{
  "PreToolUse": [
    {
      "matcher": "Create|Edit|ApplyPatch",
      "hooks": [
        {
          "type": "command",
          "command": "python3 \"$FACTORY_PROJECT_DIR\"/.factory/hooks/protect_paths.py"
        }
      ]
    }
  ]
}

A blocking script exits 2 and writes the reason to stderr.

Add context before each prompt

JSON
{
  "UserPromptSubmit": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "python3 \"$FACTORY_PROJECT_DIR\"/.factory/hooks/add_ticket_context.py"
        }
      ]
    }
  ]
}

Reload project context after compaction

JSON
{
  "SessionStart": [
    {
      "matcher": "startup|clear|compact",
      "hooks": [
        {
          "type": "command",
          "command": "cat \"$FACTORY_PROJECT_DIR\"/.factory/context.md"
        }
      ]
    }
  ]
}

Plain stdout from a SessionStart hook that exits 0 is context for the model, so when cat can read the file, this hook adds it when a new session starts and again after each compaction of the current session completes.

Security considerations

  • Treat hook input as untrusted JSON. Validate and sanitize paths, prompts, and command strings.
  • Quote path variables, for example "$FACTORY_PROJECT_DIR" on macOS and Linux or "%FACTORY_PROJECT_DIR%" on Windows, so a path with spaces stays one argument.
  • Block path traversal and sensitive paths such as .env, .git/, credentials, and deployment secrets.
  • Prefer small scripts checked into .factory/hooks/ over long inline one-liners.
  • Test hooks manually before enabling them for a team or organization.
  • Remember that hooks inherit your local environment. Avoid commands that exfiltrate data or mutate systems unexpectedly.
  • The TUI asks for folder trust before it enters an untrusted folder, and it runs no hooks until you trust it. droid exec does not ask; see Hooks in droid exec.

Droid reloads hooks when settings files change, and changed hooks run in the current session without an approval step. Review hook changes, for example in /hooks, before you rely on them.

Debugging

SymptomWhat to check
Hook does not runConfirm the event key, matcher casing, and that hooks are not disabled. Check /diagnostics and droid exec stderr for ignored entries. Use /hooks to inspect the active configuration.
Hook runs for the wrong toolMatchers are case-sensitive, and a matcher with any character outside ASCII letters, digits, _, -, spaces, |, and , is a regular expression. Use exact names, or anchor the regex with ^ and $.
Script cannot be foundUse an absolute script path. FACTORY_PROJECT_DIR defaults to Droid's working directory, not the repository root.
'"$FACTORY_PROJECT_DIR"' is not recognized as an internal or external command on Windowscmd.exe runs hook commands on Windows. It does not expand $NAME references or run .sh scripts. See Hooks on Windows.
JSON parsing failsRemember that hook input arrives on stdin. Test with sample JSON before registering the command.
Hook output has no effectPrint only the JSON object on stdout: a greeting printed before it makes Droid read all of stdout as plain text. Check the hook's row for Hook output is not valid JSON or Hook JSON output failed validation. See How Droid reads stdout.
Hook hangsSet a shorter timeout, inspect external network or process calls, and test the script outside Droid.