进阶 zcode.z.ai 2026-11-25 14:51:22 · 0 阅读

第50章 Hooks

Core FeaturesHooks A hook runs a local command automatically when a specific event occurs, for example injecting team guidelines when a session starts, checking paths before a file is written, or verifying test results before ZCode Agent finishes. Hooks are designed for project maintainers and plugin developers who need consistent checks or policies at each stage of a task. Security notice: Hooks run commands on your computer and can run outside of the sandbox. Review the source and script of every hook before enabling it. 1234 1Switch scope2Refresh and create3Trust and enable4Import legacy hooks Entry point: open Settings → Hooks. How Hooks Work At each trigger point, ZCode writes the event details as JSON to the hook command's stdin, then decides what to do next from its output and exit code. For example, blocking writes to .env at PreToolUse: ZCode Agent is about to call a toolWrite.envPreToolUseThe hook receives on stdin{  "hook_event_name": "PreToolUse",  "tool_name": "Write",  "tool_input": { "file_path": ".env" }}The hook runs a local command, and its result decides what happens to the callAllowExit code 0 with empty stdoutDenyReturn permissionDecision: "deny" with a reason, or exit code 2The reason is passed to ZCode AgentRewrite, then runReturn updatedInput to replace this tool inputCombining resultsSeveral hooksdeny > ask > allowThe hook itself errorsallowed by default, with a diagnostic For the fields each event receives and what it can return, see stdin Input and stdout and Exit Codes. Manage Hooks Use the scope selector at the top of the Hooks page to choose what to view: hooks in the User scope apply to all projects, and selecting a project under Workspaces shows the hooks specific to that project. The list is grouped by source: Installed: hooks created or imported in ZCode. Use the switch to enable or disable them. Click a row to open its editor, where you can also delete the hook. Hooks provided by plugins: grouped by plugin and read-only. They are enabled and disabled together with their plugin; manage them in Manage Plugins. Legacy: hooks read from .claude/settings.json and .agents/settings.json. They are shown for reference only and are not executed. Click Import to write a hook into the ZCode configuration of the current scope and enable it. Use the search box to find hooks. Create a Hook On the Hooks page, click New, fill in the fields below, and click Save: Runner · ProcessRunner · Shell command FieldDescriptionEventWhen the hook runs. See EventsRunnerProcess: starts the command with its arguments directly, without a shell, for clear argument boundaries and better cross-platform behavior. Shell command: passes the whole command to the system shell; you can choose the shell and run it in the backgroundScopeSave to User (all projects) or a Workspace (that project only). The scope cannot be changed after creation; delete the hook and create it again to move itMatcherNarrows when the hook runs, for example only when files are written. Leave blank to match everything for the event. See MatcherCommand / ArgumentsThe program to run. With the Process runner, enter one argument per lineRun in backgroundShell command only. ZCode does not wait for the result, and the hook's output does not affect the current operationAdvancedTimeout in seconds (default 60), a status message, and custom fields JSON saved as is A new hook takes effect in the next session. Each session reads the hook configuration once when it starts, so start a new session, or send /reload in the current task, to verify changes to the configuration or to plugins. Review Workspace Hooks Workspace hooks live in the project directory and may be changed by others through the code repository, so ZCode requires a review before they run: New or modified workspace hooks show a Trust button, and a review notice appears at the top of the page. After confirming the command, click Trust; the hook then runs in later sessions. While workspace hooks are pending review, the conversation continues as usual and those hooks do not run. A hook icon appears to the right of the execution mode selector in the composer; click it to see "N workspace hook(s) pending review; disabled for this session", then click Review to open the Hooks settings page, or Dismiss to hide the reminder. User hooks and plugin hooks do not need a separate review. Events New sessionSession startsSessionStartUser submitsBefore the modelUserPromptSubmitModel requests a toolBefore the tool runsPreToolUsePermissionRequestPermissionRequest only fires when confirmation is neededAfter the toolSuccess / failurePostToolUsePostToolUseFailureModel is about to finishFinal checkStopCan ask ZCode Agent to continue, up to 3 times in a rowEvery tool call in a turn goes through PreToolUse and PostToolUse again EventMatches againstMain useSessionStartSession source: startup / resumePrepare the environment and inject project guidelines or instructions before the first requestUserPromptSubmitNot matched; always runsAdd context before the model is called, or block the request; cannot rewrite the user's inputPreToolUseTool nameAllow, ask, or deny a tool call, or replace its inputPermissionRequestTool nameRuns only when a permission prompt is needed; can allow or deny automaticallyPostToolUseTool nameAdd context after a tool succeeds; cannot replace the tool outputPostToolUseFailureTool nameAdd diagnostics, recovery suggestions, or retry constraints after a tool failsStopNot matched; always runsCheck results before finishing; can ask ZCode Agent to continue, up to 3 times in a row Configuration Files SourceLocationNotesUser hooks~/.zcode/cli/config.jsonApply to all projects of the current userWorkspace hooks/.zcode/config.json or /zcode.jsonApply to that project only and require reviewPlugin hookshooks/hooks.json in the plugin directoryInstalled, distributed, enabled, and disabled with the pluginLegacy configuration.claude/settings.json, .agents/settings.jsonShown read-only; run only after being imported in Settings Hooks run in this order: user hooks → reviewed workspace hooks → hooks from enabled plugins. Within a source, hooks run in configuration order. Enabling a hook in Settings writes hooks.enabled: true automatically; keep this field when editing the configuration by hand. Example configuration: { "hooks": { "enabled": true, "timeoutMs": 60000, "maxOutputBytes": 32768, "events": { "PreToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "process", "command": "node", "args": ["scripts/check-write.mjs"], "enabled": true, "timeoutMs": 10000 } ] } ] } } } Quick Start: Your First Plugin Hook The plugin below adds a team guideline for ZCode Agent when a new session starts. The example requires node to be available on the system. context-guard/ ├── .zcode-plugin/ │ └── plugin.json └── hooks/ ├── hooks.json └── context.mjs plugin.json (hooks/hooks.json is in the standard location and is loaded automatically, so the manifest does not need to declare it): { "name": "context-guard", "version": "0.1.0", "description": "Inject team development guidelines when a session starts" } hooks/hooks.json: { "description": "Context Guard hooks", "hooks": { "SessionStart": [ { "matcher": "startup|resume", "hooks": [ { "type": "process", "command": "node", "args": ["${ZCODE_PLUGIN_ROOT}/hooks/context.mjs"], "timeoutMs": 5000 } ] } ] } } hooks/context.mjs: let raw = ""; process.stdin.setEncoding("utf8"); for await (const chunk of process.stdin) raw += chunk; const input = JSON.parse(raw); process.stderr.write("[context-guard] " + input.hook_event_name + "\n"); process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: input.hook_event_name, additionalContext: "Run type checks and affected tests before committing in this project." } })); To verify: In Settings → Plugins, add the local plugin source, then install and enable the plugin. Open Settings → Hooks and confirm that the SessionStart hook appears in the plugin's group. The plugin details page shows its matcher and source path. Start a new session and send a request. The first reply should reflect the injected guideline. Write debug output to stderr and only protocol JSON to stdout, so diagnostics do not break parsing. Runners, Timeouts, and Matchers TypeDescriptionRecommendationprocesscommand + args[], executed directly from the argument list without a shell; waits for the resultClear argument boundaries and better cross-platform behavior; recommended for Node, Python, or binariescommandPasses the whole string to the system shell; supports shell, async, and timeoutConvenient for existing Claude Code plugins; mind shell and quoting differences across systems timeoutMs is in milliseconds; the compatible field timeout is in seconds. When both are set, timeoutMs wins. The default timeout is 60000 ms and the default stdout limit is 32768 bytes. Set enabled: false on a hook to skip it at runtime. A command hook with async: true runs in the background: the event continues immediately, and its output cannot block the operation, change input, or inject context. statusMessage is shown in Settings and on the plugin details page. onError decides what happens when the hook itself fails (an exit code other than 0 or 2, a timeout, or a wrong field type in the output JSON): the default allow lets the operation proceed and records a diagnostic; deny applies to PreToolUse only and treats the failure like exit code 2, rejecting the tool call. Hooks running in the background are not affected. Adding or removing onError: "deny" on a workspace hook requires reviewing it again. Matcher Missing or *: matches everything. Do not use an empty string ""; it prevents the whole configuration file from loading. Only letters, digits, underscores, and |: an exact list of names, such as Write|Edit. Any other characters: a JavaScript regular expression. An invalid expression matches nothing. Tool events match the actual tool name, with aliases: Agent and Task match each other, and ApplyPatch is matched by Write and Edit. SessionStart matches the session source; UserPromptSubmit and Stop are not matched. stdin Input ZCode writes one line of JSON to each hook's stdin. The input contains both camelCase fields and Claude Code-style snake_case fields, so existing plugins can keep reading snake_case. { "session_id": "session-123", "transcript_path": "/tmp/zcode-hook/transcript.jsonl", "cwd": "/workspace/demo", "permission_mode": "default", "hook_event_name": "PreToolUse", "tool_name": "Write", "tool_input": { "file_path": "src/index.ts", "content": "..." }, "tool_use_id": "tool-123" } EventMain fieldsAll eventssession_id, transcript_path, cwd, permission_mode, hook_event_name, agent_typeSessionStartsource, and possibly modelUserPromptSubmitpromptPreToolUsetool_name, tool_input, tool_use_idPermissionRequesttool_name, tool_input, and permission_suggestions when availablePostToolUsetool_response, plus the tool name, input, and call IDPostToolUseFailureerror, error_details, is_interrupt, plus the tool fieldsStopstop_hook_active, last_assistant_message transcript_path points to a temporary file readable during this run. It is cleaned up after the hook finishes, so do not use it for long-term storage. Hook processes can also read these environment variables: ZCODE_PROJECT_DIR, ZCODE_SESSION_ID, and the compatible CLAUDE_PROJECT_DIR and CLAUDE_SESSION_ID. stdout and Exit Codes Empty stdout means success with no further effect. Output that is not JSON is ignored and never enters the model context. Only valid JSON that starts with { after leading whitespace is parsed by the protocol. Unknown fields are ignored; a wrong field type or mismatched event name marks the current hook as failed without affecting later hooks. Add context (recommended inside hookSpecificOutput; top-level additionalContext / additional_context is also accepted): { "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": "Only modify files related to the current task." } } PreToolUse: Modify or Deny a Tool Call { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow", "permissionDecisionReason": "Redirected to an allowed directory", "updatedInput": { "file_path": "generated/index.ts", "content": "..." }, "additionalContext": "The file was redirected to the generated directory." } } updatedInput replaces the original input entirely, and ZCode validates it again against the tool's parameter schema. To deny, return permissionDecision: "deny" with a permissionDecisionReason. When results from several hooks are combined, deny takes precedence over ask, and ask over allow. PermissionRequest: Allow or Deny Automatically { "hookSpecificOutput": { "hookEventName": "PermissionRequest", "decision": { "behavior": "deny", "message": "Production directories can only be changed through the release process" } } } To allow, set behavior to allow; decision can also return updatedInput and updatedPermissions (the older permissionUpdates field is accepted). UserPromptSubmit: Block the Request { "continue": false, "reason": "Please provide a ticket number first", "hookSpecificOutput": { "hookEventName": "UserPromptSubmit", "additionalContext": "This request was blocked by team policy." } } Stop: Ask ZCode Agent to Continue { "decision": "block", "reason": "Test commands and results are missing. Add them before finishing." } decision: "block" continues only when reason or additionalContext is provided; continue: true with additionalContext is also accepted. After 3 consecutive continuations, the task finishes to prevent infinite loops. Exit Codes Exit codeMeaning0Success; stdout is parsed2Block: treated as a denial in events that can be blocked, and as a request to continue in StopOther non-zero valuesThe current hook failed; a diagnostic is recorded and the task continues Plugin Hooks Manifest lookup order: .zcode-plugin/plugin.json → .claude-plugin/plugin.json → .codex-plugin/plugin.json. hooks/hooks.json in the standard location is loaded automatically. The manifest's hooks field can also point to other JSON files, contain inline configuration, or combine both. Do not point it at the standard file again; duplicates are skipped. Plugin hooks can read ZCODE_PLUGIN_ROOT, ZCODE_PLUGIN_DATA, ZCODE_PLUGIN_ID, and ZCODE_PLUGIN_NAME, plus the compatible CLAUDE_PLUGIN_ROOT and CLAUDE_PLUGIN_DATA. These variables are substituted in commands and arguments before execution. Store long-lived data in ZCODE_PLUGIN_DATA, not in the plugin installation directory. Hooks for events ZCode does not support are skipped, and a diagnostic is recorded. Troubleshooting If a hook does not take effect, check the following in order: The hook and its plugin are enabled. Workspace hooks have been approved with Trust in Settings. You started a new session, or sent /reload in the current task, after changing the configuration; sessions already in progress do not read new configuration automatically. The matcher matches the actual tool name or session source. If the problem persists, check the log at ~/.zcode/cli/log/zcode-.jsonl: failed hook runs are recorded as hook.run.failed (with source, event, matcher, and duration), and workspace hooks pending review as config.project_hooks.pending_trust. Next Steps PluginBrowse, install, and manage ZCode plugins, or build your own.CommandSave common prompts as commands and invoke them from the input box with /.MCPConnect external tools to ZCode Agent.

评论 (0)