From f472fa32d3e41d957960a10cfaee44085422b8f5 Mon Sep 17 00:00:00 2001
From: RealZST
Date: Fri, 4 Dec 2026 22:57:26 +0800
Subject: [PATCH 1/4] fix(hooks): keep a hook's matcher and kind when
installing to another agent
Installing a hook to another agent now translates the tool names in its
matcher for Cursor and Gemini CLI, writes the matcher for Cursor and
Copilot (it was dropped), and reports a matcher it had to copy as
written. Prompt and agent hooks go only to agents that run them instead
of being written as shell commands. Install failures show the reason.
Disable and delete now find a hook in its file by id, so a matcher that
holds `:` or `*`, an entry with extra fields, and a prompt hook can all
be disabled and restored.
Co-Authored-By: Claude Fable 5.2
---
crates/hk-core/src/adapter/claude.rs | 3 +
crates/hk-core/src/adapter/codex.rs | 51 +----
crates/hk-core/src/adapter/copilot.rs | 15 +-
crates/hk-core/src/adapter/cursor.rs | 17 +-
crates/hk-core/src/adapter/gemini.rs | 49 +----
crates/hk-core/src/adapter/grok.rs | 1 +
crates/hk-core/src/adapter/hermes.rs | 4 +
crates/hk-core/src/adapter/hook_tools.rs | 161 +++++++++++++++
crates/hk-core/src/adapter/kiro.rs | 4 +
crates/hk-core/src/adapter/mod.rs | 67 ++++++-
crates/hk-core/src/adapter/qoder_cn.rs | 3 +
crates/hk-core/src/adapter/windsurf.rs | 4 +
crates/hk-core/src/deployer.rs | 142 ++++++-------
crates/hk-core/src/manager.rs | 186 +++++++++++-------
crates/hk-core/src/service.rs | 182 +++++++++++++----
crates/hk-desktop/src/commands/install.rs | 2 +-
crates/hk-web/src/handlers/install.rs | 2 +-
.../__tests__/bulk-install-dialog.test.tsx | 4 +-
.../extensions/bulk-install-dialog.tsx | 47 +++--
.../extensions/extension-detail.tsx | 27 ++-
src/lib/i18n/locales/en/extensions.json | 4 +-
src/lib/i18n/locales/zh-TW/extensions.json | 4 +-
src/lib/i18n/locales/zh/extensions.json | 4 +-
src/lib/install-plan.ts | 6 +
src/lib/invoke.ts | 3 +-
src/lib/types.ts | 8 +
src/stores/__tests__/extension-store.test.ts | 15 +-
src/stores/extension-store.ts | 24 ++-
.../content/docs/docs/guides/extensions.mdx | 5 +-
.../docs/how-it-works/installing-a-hook.mdx | 24 +--
.../src/content/docs/docs/troubleshooting.md | 6 +-
.../docs/zh/docs/guides/extensions.mdx | 5 +-
.../docs/how-it-works/installing-a-hook.mdx | 22 +--
.../content/docs/zh/docs/troubleshooting.md | 6 +-
34 files changed, 735 insertions(+), 372 deletions(-)
create mode 100644 crates/hk-core/src/adapter/hook_tools.rs
diff --git a/crates/hk-core/src/adapter/claude.rs b/crates/hk-core/src/adapter/claude.rs
index d6555b6f..808f16ab 100644
--- a/crates/hk-core/src/adapter/claude.rs
+++ b/crates/hk-core/src/adapter/claude.rs
@@ -142,6 +142,9 @@ impl AgentAdapter for ClaudeAdapter {
RemoteMcpSchema::TypeAndUrl
}
+ fn supports_hook_kind(&self, _kind: super::HookKind) -> bool {
+ true
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_claude(event)
}
diff --git a/crates/hk-core/src/adapter/codex.rs b/crates/hk-core/src/adapter/codex.rs
index aea28f81..f3c523a2 100644
--- a/crates/hk-core/src/adapter/codex.rs
+++ b/crates/hk-core/src/adapter/codex.rs
@@ -61,11 +61,6 @@ impl CodexAdapter {
Self { home }
}
- fn parse_json(path: &Path) -> Option {
- let content = std::fs::read_to_string(path).ok()?;
- serde_json::from_str(&content).ok()
- }
-
/// Resolved doc filename fallback list, in the order Codex itself searches.
/// Reads `project_doc_fallback_filenames` from `~/.codex/config.toml` if
/// the user has overridden the default; falls back to the built-in list
@@ -300,51 +295,7 @@ impl AgentAdapter for CodexAdapter {
}
fn read_hooks_from(&self, path: &Path) -> Vec {
- let Some(config) = Self::parse_json(path) else {
- return vec![];
- };
- let Some(hooks) = config.get("hooks").and_then(|v| v.as_object()) else {
- return vec![];
- };
- let mut entries = Vec::new();
- for (event, hook_list) in hooks {
- let Some(arr) = hook_list.as_array() else {
- continue;
- };
- for hook in arr {
- let matcher = hook
- .get("matcher")
- .and_then(|v| v.as_str())
- .map(String::from);
- if let Some(cmds) = hook.get("hooks").and_then(|v| v.as_array()) {
- for cmd in cmds {
- // String format: "echo test"
- let cmd_str = if let Some(s) = cmd.as_str() {
- Some(s.to_string())
- }
- // Object format: {"type": "command", "command": "echo test"}
- else if let Some(s) = cmd.get("command").and_then(|v| v.as_str()) {
- Some(s.to_string())
- }
- // Prompt/agent hook: {"type": "prompt", "prompt": "..."}
- else {
- cmd.get("prompt")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- };
- if let Some(command) = cmd_str {
- entries.push(HookEntry {
- event: event.clone(),
- matcher: matcher.clone(),
- command,
- enabled: true,
- });
- }
- }
- }
- }
- }
- entries
+ super::read_claude_like_hooks(path)
}
fn read_plugins(&self) -> Vec {
diff --git a/crates/hk-core/src/adapter/copilot.rs b/crates/hk-core/src/adapter/copilot.rs
index a4ded90a..bd0386eb 100644
--- a/crates/hk-core/src/adapter/copilot.rs
+++ b/crates/hk-core/src/adapter/copilot.rs
@@ -380,6 +380,15 @@ impl AgentAdapter for CopilotAdapter {
RemoteMcpSchema::TypeAndUrl
}
+ /// PascalCase events match Claude's tool names, camelCase events
+ /// Copilot's runtime names.
+ fn hook_tool_names(&self, event: &str) -> super::hook_tools::ToolNames {
+ if event.starts_with(char::is_uppercase) {
+ super::hook_tools::ToolNames::Claude
+ } else {
+ super::hook_tools::ToolNames::CopilotRuntime
+ }
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_copilot(event)
}
@@ -443,8 +452,12 @@ impl AgentAdapter for CopilotAdapter {
if let Some(cmd_str) = cmd {
entries.push(HookEntry {
event: event.clone(),
- matcher: None,
+ matcher: hook
+ .get("matcher")
+ .and_then(|v| v.as_str())
+ .map(String::from),
command: cmd_str.to_string(),
+ kind: super::HookKind::Command,
enabled: true,
});
}
diff --git a/crates/hk-core/src/adapter/cursor.rs b/crates/hk-core/src/adapter/cursor.rs
index 51788580..2c66e84f 100644
--- a/crates/hk-core/src/adapter/cursor.rs
+++ b/crates/hk-core/src/adapter/cursor.rs
@@ -119,6 +119,12 @@ impl AgentAdapter for CursorAdapter {
RemoteMcpSchema::PlainUrl
}
+ fn supports_hook_kind(&self, kind: super::HookKind) -> bool {
+ kind != super::HookKind::Agent
+ }
+ fn hook_tool_names(&self, _event: &str) -> super::hook_tools::ToolNames {
+ super::hook_tools::ToolNames::Cursor
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_cursor(event)
}
@@ -140,12 +146,15 @@ impl AgentAdapter for CursorAdapter {
continue;
};
for hook in arr {
- // Cursor format: {"command": "..."} — no matcher, no nested hooks array
- if let Some(cmd) = hook.get("command").and_then(|v| v.as_str()) {
+ if let Some((command, kind)) = hook.as_object().and(super::hook_handler(hook)) {
entries.push(HookEntry {
event: event.clone(),
- matcher: None,
- command: cmd.to_string(),
+ matcher: hook
+ .get("matcher")
+ .and_then(|v| v.as_str())
+ .map(String::from),
+ command: command.to_string(),
+ kind,
enabled: true,
});
}
diff --git a/crates/hk-core/src/adapter/gemini.rs b/crates/hk-core/src/adapter/gemini.rs
index 115d4c72..73d905f7 100644
--- a/crates/hk-core/src/adapter/gemini.rs
+++ b/crates/hk-core/src/adapter/gemini.rs
@@ -266,6 +266,9 @@ impl AgentAdapter for GeminiAdapter {
entries
}
+ fn hook_tool_names(&self, _event: &str) -> super::hook_tools::ToolNames {
+ super::hook_tools::ToolNames::Gemini
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_gemini(event)
}
@@ -275,51 +278,7 @@ impl AgentAdapter for GeminiAdapter {
}
fn read_hooks_from(&self, path: &Path) -> Vec {
- let Some(settings) = Self::parse_json(path) else {
- return vec![];
- };
- let Some(hooks) = settings.get("hooks").and_then(|v| v.as_object()) else {
- return vec![];
- };
- let mut entries = Vec::new();
- for (event, hook_list) in hooks {
- let Some(arr) = hook_list.as_array() else {
- continue;
- };
- for hook in arr {
- let matcher = hook
- .get("matcher")
- .and_then(|v| v.as_str())
- .map(String::from);
- if let Some(cmds) = hook.get("hooks").and_then(|v| v.as_array()) {
- for cmd in cmds {
- // String format: "echo test"
- let cmd_str = if let Some(s) = cmd.as_str() {
- Some(s.to_string())
- }
- // Object format: {"type": "command", "command": "echo test"}
- else if let Some(s) = cmd.get("command").and_then(|v| v.as_str()) {
- Some(s.to_string())
- }
- // Prompt/agent hook: {"type": "prompt", "prompt": "..."}
- else {
- cmd.get("prompt")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- };
- if let Some(command) = cmd_str {
- entries.push(HookEntry {
- event: event.clone(),
- matcher: matcher.clone(),
- command,
- enabled: true,
- });
- }
- }
- }
- }
- }
- entries
+ super::read_claude_like_hooks(path)
}
}
diff --git a/crates/hk-core/src/adapter/grok.rs b/crates/hk-core/src/adapter/grok.rs
index 980ec04b..4c31b548 100644
--- a/crates/hk-core/src/adapter/grok.rs
+++ b/crates/hk-core/src/adapter/grok.rs
@@ -711,6 +711,7 @@ impl GrokAdapter {
event: event.canonical.to_string(),
matcher: matcher.clone(),
command,
+ kind: super::HookKind::Command,
enabled,
},
));
diff --git a/crates/hk-core/src/adapter/hermes.rs b/crates/hk-core/src/adapter/hermes.rs
index c0a621ba..b25afd38 100644
--- a/crates/hk-core/src/adapter/hermes.rs
+++ b/crates/hk-core/src/adapter/hermes.rs
@@ -376,6 +376,7 @@ impl AgentAdapter for HermesAdapter {
event: event.to_string(),
matcher,
command: command.to_string(),
+ kind: super::HookKind::Command,
enabled: true,
});
}
@@ -383,6 +384,9 @@ impl AgentAdapter for HermesAdapter {
out
}
+ fn hook_tool_names(&self, _event: &str) -> super::hook_tools::ToolNames {
+ super::hook_tools::ToolNames::Hermes
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_hermes(event)
}
diff --git a/crates/hk-core/src/adapter/hook_tools.rs b/crates/hk-core/src/adapter/hook_tools.rs
new file mode 100644
index 00000000..3edc1f67
--- /dev/null
+++ b/crates/hk-core/src/adapter/hook_tools.rs
@@ -0,0 +1,161 @@
+//! Tool names as each agent spells them in a hook `matcher`.
+//!
+//! A matcher on a tool event names the tools the hook fires for, and agents
+//! disagree on those names: Claude's `Bash` is Cursor's `Shell` and Gemini's
+//! `run_shell_command`. Copying a matcher unchanged between two vocabularies
+//! leaves a hook that never fires.
+//!
+//! Sources, read 2026-12:
+//! - Claude Code: https://code.claude.com/docs/en/hooks
+//! - Codex CLI: https://developers.openai.com/codex/hooks (shell "Match as `Bash`")
+//! - Qoder CLI: https://docs.qoder.com/cli/hooks
+//! - Grok Build: https://docs.grok.com/build/features/hooks (Claude names are mapped)
+//! - Copilot: https://docs.github.com/en/copilot/reference/hooks-configuration
+//! - Cursor: https://cursor.com/docs/agent/hooks
+//! - Gemini CLI: https://geminicli.com/docs/reference/tools/
+
+use super::hook_events;
+
+/// The vocabulary an agent's matchers are written in.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ToolNames {
+ /// Claude Code's names, which Codex, Qoder, Grok Build and Copilot's
+ /// PascalCase events also match against.
+ Claude,
+ Cursor,
+ Gemini,
+ /// A vocabulary of the agent's own that has no table here yet.
+ Hermes,
+ Kiro,
+ Windsurf,
+ /// Copilot's camelCase events, which match its runtime names (`bash`).
+ CopilotRuntime,
+}
+
+impl ToolNames {
+ fn column(self) -> Option {
+ match self {
+ Self::Claude => Some(0),
+ Self::Cursor => Some(1),
+ Self::Gemini => Some(2),
+ Self::Hermes | Self::Kiro | Self::Windsurf | Self::CopilotRuntime => None,
+ }
+ }
+}
+
+/// One row per tool, one column per `ToolNames::column`. `None` where the
+/// agent's documentation names no equivalent.
+const TOOLS: &[[Option<&str>; 3]] = &[
+ [Some("Bash"), Some("Shell"), Some("run_shell_command")],
+ [Some("Read"), Some("Read"), Some("read_file")],
+ [Some("Write"), Some("Write"), Some("write_file")],
+ [Some("Edit"), None, Some("replace")],
+ [Some("Grep"), Some("Grep"), Some("grep_search")],
+ [Some("Glob"), None, Some("glob")],
+ [Some("WebFetch"), None, Some("web_fetch")],
+ [Some("WebSearch"), None, Some("google_web_search")],
+];
+
+/// Canonical events whose matcher is a tool name. Other events match a field
+/// of their own (a session source, a subagent type).
+const TOOL_EVENTS: &[&str] = &[
+ "PreToolUse",
+ "PostToolUse",
+ "PostToolUseFailure",
+ "PermissionRequest",
+];
+
+pub struct TranslatedMatcher {
+ pub matcher: String,
+ /// False when any part was copied as written between two vocabularies,
+ /// so the hook may not fire for the tools the source meant.
+ pub exact: bool,
+}
+
+/// Rewrite the matcher of a hook on `event` from one vocabulary to another.
+/// Only plain names and `|` lists of them are translated; anything else is
+/// kept as written and reported through `exact`.
+pub fn translate_matcher(
+ matcher: &str,
+ event: &str,
+ from: ToolNames,
+ to: ToolNames,
+) -> TranslatedMatcher {
+ if from == to || matcher.is_empty() || matcher == "*" {
+ return TranslatedMatcher {
+ matcher: matcher.to_string(),
+ exact: true,
+ };
+ }
+ let columns = from.column().zip(to.column()).filter(|_| {
+ hook_events::to_claude(event)
+ .is_some_and(|canonical| TOOL_EVENTS.contains(&canonical.as_str()))
+ });
+ let mut exact = true;
+ let names: Vec<&str> = matcher
+ .split('|')
+ .map(|name| {
+ let translated = columns.and_then(|(from, to)| {
+ TOOLS
+ .iter()
+ .find(|row| row[from] == Some(name))
+ .and_then(|row| row[to])
+ });
+ exact &= translated.is_some();
+ translated.unwrap_or(name)
+ })
+ .collect();
+ TranslatedMatcher {
+ matcher: names.join("|"),
+ exact,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tool_names_are_rewritten_and_anything_else_is_kept_and_reported() {
+ let to_gemini = translate_matcher(
+ "Bash|Edit",
+ "PreToolUse",
+ ToolNames::Claude,
+ ToolNames::Gemini,
+ );
+ assert_eq!(to_gemini.matcher, "run_shell_command|replace");
+ assert!(to_gemini.exact);
+
+ let from_cursor =
+ translate_matcher("Shell", "preToolUse", ToolNames::Cursor, ToolNames::Claude);
+ assert_eq!(from_cursor.matcher, "Bash");
+
+ // Cursor documents no edit tool, and an MCP pattern is not a plain name.
+ let partial = translate_matcher(
+ "Bash|Edit|mcp__github__.*",
+ "PreToolUse",
+ ToolNames::Claude,
+ ToolNames::Cursor,
+ );
+ assert_eq!(partial.matcher, "Shell|Edit|mcp__github__.*");
+ assert!(!partial.exact);
+
+ let no_table =
+ translate_matcher("Bash", "PreToolUse", ToolNames::Claude, ToolNames::Hermes);
+ assert_eq!(no_table.matcher, "Bash");
+ assert!(!no_table.exact);
+
+ // A session source is not a tool name, even where it spells one.
+ let not_a_tool =
+ translate_matcher("Read", "SessionStart", ToolNames::Claude, ToolNames::Gemini);
+ assert_eq!(not_a_tool.matcher, "Read");
+ assert!(!not_a_tool.exact);
+
+ for unchanged in ["*", ""] {
+ assert!(
+ translate_matcher(unchanged, "PreToolUse", ToolNames::Claude, ToolNames::Kiro)
+ .exact
+ );
+ }
+ }
+}
diff --git a/crates/hk-core/src/adapter/kiro.rs b/crates/hk-core/src/adapter/kiro.rs
index df09f794..2adc13d0 100644
--- a/crates/hk-core/src/adapter/kiro.rs
+++ b/crates/hk-core/src/adapter/kiro.rs
@@ -57,6 +57,7 @@ impl KiroAdapter {
.and_then(|v| v.as_str())
.map(String::from),
command: command.to_string(),
+ kind: super::HookKind::Command,
// Kiro's native per-hook flag: default true, false = skipped
// without deleting (https://kiro.dev/docs/hooks/).
enabled: value
@@ -171,6 +172,9 @@ impl AgentAdapter for KiroAdapter {
hooks.iter().filter_map(Self::parse_hook).collect()
}
+ fn hook_tool_names(&self, _event: &str) -> super::hook_tools::ToolNames {
+ super::hook_tools::ToolNames::Kiro
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_kiro(event)
}
diff --git a/crates/hk-core/src/adapter/mod.rs b/crates/hk-core/src/adapter/mod.rs
index c8eeb3b6..d3c6355c 100644
--- a/crates/hk-core/src/adapter/mod.rs
+++ b/crates/hk-core/src/adapter/mod.rs
@@ -8,6 +8,7 @@ pub mod gemini;
pub mod grok;
pub mod hermes;
pub mod hook_events;
+pub mod hook_tools;
pub mod kiro;
pub mod omp;
pub mod openclaw;
@@ -304,21 +305,62 @@ pub(crate) fn read_ts_extensions(dir: &Path) -> Vec {
entries
}
+/// What a hook runs when it fires.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum HookKind {
+ /// A shell command.
+ Command,
+ /// A prompt the agent has a model evaluate (`"type": "prompt"`).
+ Prompt,
+ /// A prompt handed to a subagent that can use tools (`"type": "agent"`).
+ Agent,
+}
+
+impl HookKind {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Command => "command",
+ Self::Prompt => "prompt",
+ Self::Agent => "agent",
+ }
+ }
+}
+
/// Represents a hook entry parsed from an agent's config
#[derive(Debug, Clone)]
pub struct HookEntry {
pub event: String,
pub matcher: Option,
+ /// The shell command, or the prompt text of a prompt or agent hook.
pub command: String,
+ pub kind: HookKind,
/// On-disk enable state. Only agents with a native per-hook flag (Kiro's
/// `enabled`) ever report `false`; formats without one are always `true`.
pub enabled: bool,
}
+/// What one hook handler runs: a bare command string, `{"command": ...}`, or
+/// a prompt or agent hook `{"prompt": ...}`.
+pub(crate) fn hook_handler(handler: &serde_json::Value) -> Option<(&str, HookKind)> {
+ handler
+ .as_str()
+ .or_else(|| handler.get("command").and_then(|v| v.as_str()))
+ .map(|command| (command, HookKind::Command))
+ .or_else(|| {
+ handler
+ .get("prompt")
+ .and_then(|v| v.as_str())
+ .map(
+ |prompt| match handler.get("type").and_then(|v| v.as_str()) {
+ Some("agent") => (prompt, HookKind::Agent),
+ _ => (prompt, HookKind::Prompt),
+ },
+ )
+ })
+}
+
/// Read the `hooks` object of a Claude-shaped settings file:
-/// `{"hooks": {"Event": [{"matcher": "...", "hooks": []}]}}`, where a
-/// hook is a bare command string, `{"command": ...}`, or a prompt/agent hook
-/// `{"prompt": ...}`. Shared by Claude Code and Qoder CN.
+/// `{"hooks": {"Event": [{"matcher": "...", "hooks": []}]}}`.
pub(crate) fn read_claude_like_hooks(path: &Path) -> Vec {
let Some(settings) = std::fs::read_to_string(path)
.ok()
@@ -344,15 +386,12 @@ pub(crate) fn read_claude_like_hooks(path: &Path) -> Vec {
continue;
};
for cmd in cmds {
- let command = cmd
- .as_str()
- .or_else(|| cmd.get("command").and_then(|v| v.as_str()))
- .or_else(|| cmd.get("prompt").and_then(|v| v.as_str()));
- if let Some(command) = command {
+ if let Some((command, kind)) = hook_handler(cmd) {
entries.push(HookEntry {
event: event.clone(),
matcher: matcher.clone(),
command: command.to_string(),
+ kind,
enabled: true,
});
}
@@ -724,6 +763,18 @@ pub trait AgentAdapter: Send + Sync {
true
}
+ /// Whether the agent runs hooks of this kind. `install_to_agent` refuses
+ /// a kind the agent does not run, since writing a prompt as a command
+ /// would have the agent execute the prompt text.
+ fn supports_hook_kind(&self, kind: HookKind) -> bool {
+ kind == HookKind::Command
+ }
+
+ /// The tool names this agent's matchers on `event` are written in.
+ fn hook_tool_names(&self, _event: &str) -> hook_tools::ToolNames {
+ hook_tools::ToolNames::Claude
+ }
+
/// Translate a hook event name from any agent's convention to this agent's convention.
/// Returns None if the event has no equivalent in this agent.
/// Mappings are centralized in `hook_events.rs`.
diff --git a/crates/hk-core/src/adapter/qoder_cn.rs b/crates/hk-core/src/adapter/qoder_cn.rs
index 898482b8..1b78948e 100644
--- a/crates/hk-core/src/adapter/qoder_cn.rs
+++ b/crates/hk-core/src/adapter/qoder_cn.rs
@@ -124,6 +124,9 @@ impl AgentAdapter for QoderCnAdapter {
fn project_hook_config_relpath(&self) -> Option {
Some(".qoder/settings.json".into())
}
+ fn supports_hook_kind(&self, kind: super::HookKind) -> bool {
+ kind != super::HookKind::Agent
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_claude(event)
}
diff --git a/crates/hk-core/src/adapter/windsurf.rs b/crates/hk-core/src/adapter/windsurf.rs
index 90891365..99b1796f 100644
--- a/crates/hk-core/src/adapter/windsurf.rs
+++ b/crates/hk-core/src/adapter/windsurf.rs
@@ -140,6 +140,9 @@ impl AgentAdapter for WindsurfAdapter {
RemoteMcpSchema::ServerUrl
}
+ fn hook_tool_names(&self, _event: &str) -> super::hook_tools::ToolNames {
+ super::hook_tools::ToolNames::Windsurf
+ }
fn translate_hook_event(&self, event: &str) -> Option {
super::hook_events::to_windsurf(event)
}
@@ -171,6 +174,7 @@ impl AgentAdapter for WindsurfAdapter {
event: event.clone(),
matcher: None,
command: command.to_string(),
+ kind: super::HookKind::Command,
enabled: true,
});
}
diff --git a/crates/hk-core/src/deployer.rs b/crates/hk-core/src/deployer.rs
index d60c749a..2186114f 100644
--- a/crates/hk-core/src/deployer.rs
+++ b/crates/hk-core/src/deployer.rs
@@ -1,6 +1,7 @@
use crate::HkError;
use crate::adapter::{
- HookEntry, HookFormat, McpFormat, McpServerEntry, McpTransport, RemoteMcpSchema,
+ HookEntry, HookFormat, HookKind, McpFormat, McpServerEntry, McpTransport, RemoteMcpSchema,
+ hook_handler,
};
use fs2::FileExt;
use std::io::{Read as _, Seek as _, SeekFrom, Write as _};
@@ -1793,6 +1794,27 @@ fn kiro_hook_matches(
== Some(command)
}
+/// A hook handler in the typed form Claude-shaped files and Copilot share.
+fn hook_handler_value(entry: &HookEntry) -> serde_json::Value {
+ match entry.kind {
+ HookKind::Command => serde_json::json!({ "type": "command", "command": entry.command }),
+ HookKind::Prompt | HookKind::Agent => {
+ serde_json::json!({ "type": entry.kind.as_str(), "prompt": entry.command })
+ }
+ }
+}
+
+/// True if a handler runs `command`, as a command or as a prompt.
+fn handler_runs(handler: &serde_json::Value, command: &str) -> bool {
+ hook_handler(handler).is_some_and(|(text, _)| text == command)
+}
+
+/// True if an entry of a flat event array (Cursor, Copilot) is the
+/// (matcher, command) hook.
+fn flat_hook_matches(hook: &serde_json::Value, matcher: Option<&str>, command: &str) -> bool {
+ hook.get("matcher").and_then(|v| v.as_str()) == matcher && handler_runs(hook, command)
+}
+
fn kiro_hook_value(entry: &HookEntry) -> serde_json::Value {
let mut hook = serde_json::json!({
"name": format!("{} {}", entry.event, entry.command),
@@ -2007,8 +2029,7 @@ pub fn deploy_hook(
let group = arr.iter_mut().find(|h| {
h.get("matcher").and_then(|v| v.as_str()).map(String::from) == entry.matcher
});
- // Use object format {"type":"command","command":"..."} — accepted by Claude, required by Codex/Gemini
- let cmd_obj = serde_json::json!({ "type": "command", "command": entry.command });
+ let cmd_obj = hook_handler_value(entry);
if let Some(group) = group {
let cmds = group.as_object_mut().and_then(|o| {
o.entry("hooks")
@@ -2016,9 +2037,7 @@ pub fn deploy_hook(
.as_array_mut()
});
if let Some(cmds) = cmds
- && !cmds.iter().any(|c| {
- c.get("command").and_then(|v| v.as_str()) == Some(&entry.command)
- })
+ && !cmds.iter().any(|c| handler_runs(c, &entry.command))
{
cmds.push(cmd_obj);
}
@@ -2033,7 +2052,7 @@ pub fn deploy_hook(
arr.push(group);
}
}
- HookFormat::Cursor => {
+ HookFormat::Cursor | HookFormat::Copilot => {
config
.as_object_mut()
.ok_or_else(|| HkError::ConfigCorrupted("Config is not an object".into()))?
@@ -2052,9 +2071,23 @@ pub fn deploy_hook(
let arr = event_arr
.as_array_mut()
.ok_or_else(|| HkError::ConfigCorrupted("event is not an array".into()))?;
- let hook_val = serde_json::json!({ "command": entry.command });
- if !arr.contains(&hook_val) {
- arr.push(hook_val);
+ // Cursor's own files leave `type` off a command hook.
+ let mut hook = match (format, entry.kind) {
+ (HookFormat::Cursor, HookKind::Command) => {
+ serde_json::json!({ "command": entry.command })
+ }
+ _ => hook_handler_value(entry),
+ };
+ // "All tools" is the absence of a matcher in these files.
+ let matcher = entry.matcher.as_deref().filter(|m| !matches!(*m, "" | "*"));
+ if let Some(matcher) = matcher {
+ hook["matcher"] = serde_json::Value::from(matcher);
+ }
+ if !arr
+ .iter()
+ .any(|h| flat_hook_matches(h, matcher, &entry.command))
+ {
+ arr.push(hook);
}
}
HookFormat::Windsurf => {
@@ -2076,30 +2109,6 @@ pub fn deploy_hook(
arr.push(hook_val);
}
}
- HookFormat::Copilot => {
- config
- .as_object_mut()
- .ok_or_else(|| HkError::ConfigCorrupted("Config is not an object".into()))?
- .entry("version")
- .or_insert(serde_json::json!(1));
- let hooks = config
- .as_object_mut()
- .unwrap()
- .entry("hooks")
- .or_insert_with(|| serde_json::json!({}));
- let event_arr = hooks
- .as_object_mut()
- .ok_or_else(|| HkError::ConfigCorrupted("hooks is not an object".into()))?
- .entry(&entry.event)
- .or_insert_with(|| serde_json::json!([]));
- let arr = event_arr
- .as_array_mut()
- .ok_or_else(|| HkError::ConfigCorrupted("event is not an array".into()))?;
- let hook_val = serde_json::json!({ "type": "command", "command": entry.command });
- if !arr.contains(&hook_val) {
- arr.push(hook_val);
- }
- }
HookFormat::HermesYaml => {
// Handled by the early return above; YAML is not JSON.
unreachable!("HermesYaml handled before locked_modify_json")
@@ -2308,16 +2317,7 @@ pub fn remove_hook(
continue;
}
if let Some(cmds) = group.get_mut("hooks").and_then(|v| v.as_array_mut()) {
- // Match both string format "cmd" and object format {"type":"command","command":"cmd"}
- cmds.retain(|c| {
- if c.as_str() == Some(command) {
- return false;
- }
- if c.get("command").and_then(|v| v.as_str()) == Some(command) {
- return false;
- }
- true
- });
+ cmds.retain(|c| !handler_runs(c, command));
}
}
event_arr.retain(|h| {
@@ -2331,12 +2331,11 @@ pub fn remove_hook(
}
}
}
- HookFormat::Cursor => {
+ HookFormat::Cursor | HookFormat::Copilot => {
if let Some(hooks) = config.get_mut("hooks").and_then(|v| v.as_object_mut())
&& let Some(event_arr) = hooks.get_mut(event).and_then(|v| v.as_array_mut())
{
- let cmd_val = serde_json::json!({ "command": command });
- event_arr.retain(|h| h != &cmd_val);
+ event_arr.retain(|h| !flat_hook_matches(h, matcher, command));
if event_arr.is_empty() {
hooks.remove(event);
}
@@ -2355,17 +2354,6 @@ pub fn remove_hook(
}
}
}
- HookFormat::Copilot => {
- if let Some(hooks) = config.get_mut("hooks").and_then(|v| v.as_object_mut())
- && let Some(event_arr) = hooks.get_mut(event).and_then(|v| v.as_array_mut())
- {
- event_arr
- .retain(|h| h.get("command").and_then(|v| v.as_str()) != Some(command));
- if event_arr.is_empty() {
- hooks.remove(event);
- }
- }
- }
HookFormat::HermesYaml => {
// Handled by the early return above; YAML is not JSON.
unreachable!("HermesYaml handled before locked_modify_json")
@@ -3070,26 +3058,17 @@ pub fn read_hook_config(
continue;
}
if let Some(cmds) = group.get("hooks").and_then(|v| v.as_array())
- && cmds.iter().any(|c| {
- // Match both string format "cmd" and object format {"command":"cmd"}
- c.as_str() == Some(command)
- || c.get("command").and_then(|v| v.as_str()) == Some(command)
- })
+ && cmds.iter().any(|c| handler_runs(c, command))
{
return Ok(Some(group.clone()));
}
}
Ok(None)
}
- HookFormat::Cursor => {
- let cmd_val = serde_json::json!({ "command": command });
- for entry in event_arr {
- if entry == &cmd_val {
- return Ok(Some(entry.clone()));
- }
- }
- Ok(None)
- }
+ HookFormat::Cursor | HookFormat::Copilot => Ok(event_arr
+ .iter()
+ .find(|hook| flat_hook_matches(hook, matcher, command))
+ .cloned()),
HookFormat::Windsurf => {
for entry in event_arr {
if entry.get("command").and_then(|v| v.as_str()) == Some(command)
@@ -3100,14 +3079,6 @@ pub fn read_hook_config(
}
Ok(None)
}
- HookFormat::Copilot => {
- for entry in event_arr {
- if entry.get("command").and_then(|v| v.as_str()) == Some(command) {
- return Ok(Some(entry.clone()));
- }
- }
- Ok(None)
- }
HookFormat::KiroIde => Ok(None),
// Handled by the early return above; YAML is not JSON.
HookFormat::HermesYaml => Ok(None),
@@ -4436,6 +4407,7 @@ mod tests {
event: "PreToolUse".into(),
matcher: Some("Bash".into()),
command: "echo test".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::ClaudeLike).unwrap();
@@ -4464,6 +4436,7 @@ mod tests {
event: "PreToolUse".into(),
matcher: Some("Bash".into()),
command: "echo second".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::ClaudeLike).unwrap();
@@ -4489,6 +4462,7 @@ mod tests {
event: "PreToolUse".into(),
matcher: Some("Bash".into()),
command: "echo test".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::ClaudeLike).unwrap();
@@ -4736,6 +4710,7 @@ mod tests {
event: "stop".into(),
matcher: None,
command: "echo done".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::Cursor).unwrap();
@@ -4757,6 +4732,7 @@ mod tests {
event: "PreToolUse".into(),
matcher: None,
command: "./check.sh".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::Copilot).unwrap();
@@ -4776,6 +4752,7 @@ mod tests {
event: "pre_user_prompt".into(),
matcher: None,
command: "echo hi".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::Windsurf).unwrap();
@@ -4794,6 +4771,7 @@ mod tests {
event: "PostFileSave".into(),
matcher: Some("\\.ts$".into()),
command: "npm run lint".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::KiroIde).unwrap();
@@ -4966,6 +4944,7 @@ mod tests {
event: "PostFileSave".into(),
matcher: Some("\\.ts$".into()),
command: "npm run lint".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&config, &entry, HookFormat::KiroIde).unwrap();
@@ -5078,6 +5057,7 @@ mod tests {
event: "pre_tool_call".into(),
matcher: Some("terminal".into()),
command: "~/.hermes/agent-hooks/block.sh".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&cfg, &entry, HookFormat::HermesYaml).unwrap();
@@ -5141,6 +5121,7 @@ mod tests {
event: "pre_tool_call".into(),
matcher: Some("terminal".into()),
command: "~/.hermes/agent-hooks/block.sh".into(),
+ kind: HookKind::Command,
enabled: true,
};
// Deploying the identical hook twice must not duplicate the list item.
@@ -5165,6 +5146,7 @@ mod tests {
event: "on_session_start".into(),
matcher: None,
command: "~/.hermes/agent-hooks/log.sh".into(),
+ kind: HookKind::Command,
enabled: true,
};
deploy_hook(&cfg, &entry, HookFormat::HermesYaml).unwrap();
diff --git a/crates/hk-core/src/manager.rs b/crates/hk-core/src/manager.rs
index e2eaec83..adb45619 100644
--- a/crates/hk-core/src/manager.rs
+++ b/crates/hk-core/src/manager.rs
@@ -384,19 +384,7 @@ fn toggle_hook(
store: &Store,
adapters: &[Box],
) -> Result<(), HkError> {
- let parts: Vec<&str> = ext.name.splitn(3, ':').collect();
- if parts.len() < 3 {
- return Err(HkError::Validation(format!(
- "Invalid hook name: {}",
- ext.name
- )));
- }
- let (event, matcher_str, command) = (parts[0], parts[1], parts[2]);
- let matcher = if matcher_str == "*" {
- None
- } else {
- Some(matcher_str)
- };
+ let not_found = || HkError::NotFound(format!("Hook '{}' not found in config", ext.name));
for a in adapters {
if !ext.agents.contains(&a.name().to_string()) {
continue;
@@ -410,23 +398,18 @@ fn toggle_hook(
// $GROK_HOME/disabled-hooks; the hook file itself stays untouched
// and no DB snapshot is taken (read_hooks reads the state back).
if a.name() == "grok" {
- let source_path = ext
- .source_path
- .as_ref()
- .map(PathBuf::from)
- .or_else(|| config_paths.into_iter().next());
- let Some(source_path) = source_path else {
- return Err(HkError::NotFound(format!(
- "No hook config path for '{}'",
- ext.name
- )));
- };
+ let (source_path, hook) = hooks_on_disk(ext, a.as_ref(), &config_paths)
+ .next()
+ .ok_or_else(not_found)?;
let grok = adapter::grok::GrokAdapter::with_grok_home(a.base_dir());
let spec = grok
- .hook_spec_name_for(&source_path, event, matcher, command)
- .ok_or_else(|| {
- HkError::NotFound(format!("Hook '{}' not found in config", ext.name))
- })?;
+ .hook_spec_name_for(
+ &source_path,
+ &hook.event,
+ hook.matcher.as_deref(),
+ &hook.command,
+ )
+ .ok_or_else(not_found)?;
deployer::set_grok_hook_enabled(&a.base_dir().join("disabled-hooks"), &spec, enabled)?;
store.set_disabled_config(&ext.id, None)?;
continue;
@@ -436,27 +419,16 @@ fn toggle_hook(
// the entry, and take NO DB snapshot: the on-disk state is read back by
// read_hooks on rescan (same pattern as the native MCP toggle above).
if a.hook_format() == adapter::HookFormat::KiroIde {
- let mut flipped = false;
- for config_path in &config_paths {
- if !config_path.is_file() {
- continue;
- }
- match deployer::set_kiro_hook_enabled(config_path, event, matcher, command, enabled)
- {
- Ok(()) => {
- flipped = true;
- break;
- }
- Err(HkError::NotFound(_)) => continue,
- Err(e) => return Err(e),
- }
- }
- if !flipped {
- return Err(HkError::NotFound(format!(
- "Hook '{}' not found in config",
- ext.name
- )));
- }
+ let (config_path, hook) = hooks_on_disk(ext, a.as_ref(), &config_paths)
+ .next()
+ .ok_or_else(not_found)?;
+ deployer::set_kiro_hook_enabled(
+ &config_path,
+ &hook.event,
+ hook.matcher.as_deref(),
+ &hook.command,
+ enabled,
+ )?;
// Clear any stale snapshot so the store upsert CASE trusts the
// scanner's on-disk enabled state (disabled_config IS NULL).
store.set_disabled_config(&ext.id, None)?;
@@ -470,37 +442,62 @@ fn toggle_hook(
let config_path = config_paths.first().ok_or_else(|| {
HkError::NotFound(format!("No hook config path for '{}'", ext.name))
})?;
+ // An event name never contains `:`, unlike a matcher.
+ let event = ext.name.split(':').next().unwrap_or_default();
deployer::restore_hook(config_path, event, &entry, a.hook_format())?;
store.set_disabled_config(&ext.id, None)?;
} else {
- let mut found = None;
- let mut found_path = None;
- for config_path in &config_paths {
- if let Some(entry) = deployer::read_hook_config(
- config_path,
- event,
- matcher,
- command,
- a.hook_format(),
- )? {
- found = Some(entry);
- found_path = Some(config_path.clone());
- break;
- }
- }
- let entry = found.ok_or_else(|| {
- HkError::NotFound(format!("Hook '{}' not found in config", ext.name))
- })?;
- let config_path = found_path.ok_or_else(|| {
- HkError::NotFound(format!("Hook '{}' not found in config", ext.name))
- })?;
+ let (config_path, hook) = hooks_on_disk(ext, a.as_ref(), &config_paths)
+ .next()
+ .ok_or_else(not_found)?;
+ let matcher = hook.matcher.as_deref();
+ let entry = deployer::read_hook_config(
+ &config_path,
+ &hook.event,
+ matcher,
+ &hook.command,
+ a.hook_format(),
+ )?
+ .ok_or_else(not_found)?;
store.set_disabled_config(&ext.id, Some(&entry.to_string()))?;
- deployer::remove_hook(&config_path, event, matcher, command, a.hook_format())?;
+ deployer::remove_hook(
+ &config_path,
+ &hook.event,
+ matcher,
+ &hook.command,
+ a.hook_format(),
+ )?;
}
}
Ok(())
}
+/// The entries in `config_paths` that `ext` is the row for. A row's name
+/// cannot be split back into event, matcher and command (a matcher may hold
+/// a `:`), so each entry is matched by recomputing its id.
+pub(crate) fn hooks_on_disk<'a>(
+ ext: &'a Extension,
+ adapter: &'a dyn adapter::AgentAdapter,
+ config_paths: &'a [PathBuf],
+) -> impl Iterator- + 'a {
+ config_paths.iter().flat_map(move |config_path| {
+ adapter
+ .read_hooks_from(config_path)
+ .into_iter()
+ .filter(|hook| {
+ let name = format!(
+ "{}:{}:{}",
+ hook.event,
+ hook.matcher.as_deref().unwrap_or("*"),
+ hook.command
+ );
+ crate::scanner::stable_id_with_scope_for(&name, "hook", adapter.name(), &ext.scope)
+ == ext.id
+ })
+ .map(move |hook| (config_path.clone(), hook))
+ })
+}
+
/// Reconstruct the config-file plugin key (e.g. "name@marketplace") from extension metadata.
/// Scanner sets description to "Plugin from {source}" or "Plugin for {agent}".
fn plugin_key_from_ext(ext: &Extension) -> String {
@@ -2900,6 +2897,53 @@ mod tests {
assert!(store.get_extension(&ext.id).unwrap().unwrap().enabled);
}
+ #[test]
+ fn a_hook_is_disabled_and_restored_whatever_its_matcher_holds() {
+ let dir = TempDir::new().unwrap();
+ let home = dir.path();
+ std::fs::create_dir_all(home.join(".cursor")).unwrap();
+ let hooks_file = home.join(".cursor/hooks.json");
+ let original = serde_json::json!({
+ "version": 1,
+ "hooks": { "preToolUse": [
+ { "command": "./guard.sh", "matcher": "MCP:create_issue", "timeout": 30 },
+ { "command": "./all.sh", "matcher": "*" }
+ ] }
+ });
+ std::fs::write(&hooks_file, original.to_string()).unwrap();
+
+ let store = crate::store::Store::open(&home.join("test.db")).unwrap();
+ let adapters: Vec> = vec![Box::new(
+ adapter::cursor::CursorAdapter::with_home(home.to_path_buf()),
+ )];
+ store
+ .sync_extensions(&scanner::scan_hooks(&*adapters[0]))
+ .unwrap();
+ let hooks = store
+ .list_extensions(Some(ExtensionKind::Hook), None)
+ .unwrap();
+ assert_eq!(hooks.len(), 2);
+ let on_disk = || -> serde_json::Value {
+ serde_json::from_str(&std::fs::read_to_string(&hooks_file).unwrap()).unwrap()
+ };
+
+ for hook in &hooks {
+ toggle_extension_with_adapters(&store, &adapters, &hook.id, false).unwrap();
+ }
+ assert!(
+ !on_disk().to_string().contains(".sh"),
+ "both hooks are out of the file"
+ );
+
+ for hook in &hooks {
+ toggle_extension_with_adapters(&store, &adapters, &hook.id, true).unwrap();
+ }
+ let restored = on_disk()["hooks"]["preToolUse"].clone();
+ for entry in original["hooks"]["preToolUse"].as_array().unwrap() {
+ assert!(restored.as_array().unwrap().contains(entry), "{restored}");
+ }
+ }
+
// -----------------------------------------------------------------------
// Task 3: manifest candidate list + silent failure
// -----------------------------------------------------------------------
diff --git a/crates/hk-core/src/service.rs b/crates/hk-core/src/service.rs
index 3ebc4d8c..22df07b3 100644
--- a/crates/hk-core/src/service.rs
+++ b/crates/hk-core/src/service.rs
@@ -927,30 +927,16 @@ pub fn delete_extension(
.as_ref()
.map(|p| vec![std::path::PathBuf::from(p)])
.unwrap_or_else(|| adapter.hook_config_paths_for(&ext.scope));
- for config_path in config_paths {
- for hook in adapter.read_hooks_from(&config_path) {
- let hook_name = format!(
- "{}:{}:{}",
- hook.event,
- hook.matcher.as_deref().unwrap_or("*"),
- hook.command
- );
- let candidate = scanner::stable_id_with_scope_for(
- &hook_name,
- "hook",
- adapter.name(),
- &ext.scope,
- );
- if candidate == id {
- deployer::remove_hook(
- &config_path,
- &hook.event,
- hook.matcher.as_deref(),
- &hook.command,
- adapter.hook_format(),
- )?;
- }
- }
+ let on_disk: Vec<_> =
+ manager::hooks_on_disk(&ext, adapter.as_ref(), &config_paths).collect();
+ for (config_path, hook) in on_disk {
+ deployer::remove_hook(
+ &config_path,
+ &hook.event,
+ hook.matcher.as_deref(),
+ &hook.command,
+ adapter.hook_format(),
+ )?;
}
}
}
@@ -1387,10 +1373,27 @@ pub(crate) fn skill_target_dir(
})
}
+/// What `install_to_agent` deployed.
+#[derive(Debug, serde::Serialize)]
+pub struct AgentInstall {
+ /// Skill name, MCP server name, or `event:command` for a hook.
+ pub name: String,
+ /// The matcher written for a hook when part of it could not be rewritten
+ /// in the target agent's tool names, so the user knows to check it.
+ pub matcher_copied_as_written: Option,
+}
+
+impl From for AgentInstall {
+ fn from(name: String) -> Self {
+ Self {
+ name,
+ matcher_copied_as_written: None,
+ }
+ }
+}
+
/// Cross-agent deploy: copy a Skill / MCP / Hook / CLI from its source agent
-/// into `target_agent` at `target_scope`. Returns a human-readable identifier
-/// of what was deployed (skill name, MCP server name, or `event:command` for
-/// hooks). The caller rescans afterwards.
+/// into `target_agent` at `target_scope`. The caller rescans afterwards.
pub fn install_to_agent(
store: &Mutex,
adapters: &[Box],
@@ -1398,7 +1401,7 @@ pub fn install_to_agent(
target_agent: &str,
hermes_category: Option<&str>,
target_scope: &ConfigScope,
-) -> Result {
+) -> Result {
let (ext, projects) = {
let store = store.lock();
let ext = store
@@ -1455,7 +1458,7 @@ pub fn install_to_agent(
target_scope,
)?;
}
- Ok(deployed_name)
+ Ok(deployed_name.into())
}
ExtensionKind::Mcp => {
let mut source_entry = None;
@@ -1496,7 +1499,7 @@ pub fn install_to_agent(
))
})?;
deployer::deploy_mcp_server(&config_path, &entry, target_adapter.as_ref())?;
- Ok(entry.name)
+ Ok(entry.name.into())
}
ExtensionKind::Hook => {
let mut source_entry = None;
@@ -1524,7 +1527,7 @@ pub fn install_to_agent(
&ext.scope,
);
if candidate == extension_id {
- source_entry = Some(hook);
+ source_entry = Some((adapter, hook));
break;
}
}
@@ -1533,9 +1536,16 @@ pub fn install_to_agent(
}
}
}
- let mut entry = source_entry
+ let (source_adapter, mut entry) = source_entry
.ok_or_else(|| HkError::Internal("Could not find source hook config".into()))?;
+ if !target_adapter.supports_hook_kind(entry.kind) {
+ return Err(HkError::Validation(format!(
+ "{target_agent} does not support {} hooks",
+ entry.kind.as_str()
+ )));
+ }
+
// Translate event name to the target agent's convention. Agents
// disagree on hook event names (Claude `PreToolUse` vs Codex
// `pre_tool_use`, etc.) so a missing translation is a hard error.
@@ -1547,6 +1557,19 @@ pub fn install_to_agent(
entry.event, target_agent
))
})?;
+ let matcher = entry.matcher.as_deref().map(|matcher| {
+ crate::adapter::hook_tools::translate_matcher(
+ matcher,
+ &entry.event,
+ source_adapter.hook_tool_names(&entry.event),
+ target_adapter.hook_tool_names(&translated_event),
+ )
+ });
+ let matcher_copied_as_written = matcher
+ .as_ref()
+ .filter(|translated| !translated.exact)
+ .map(|translated| translated.matcher.clone());
+ entry.matcher = matcher.map(|translated| translated.matcher);
entry.event = translated_event;
// Global installs bail out for agents that don't load user-level
@@ -1578,7 +1601,10 @@ pub fn install_to_agent(
})?;
deployer::deploy_hook(&config_path, &entry, target_adapter.hook_format())?;
- Ok(format!("{}:{}", entry.event, entry.command))
+ Ok(AgentInstall {
+ name: format!("{}:{}", entry.event, entry.command),
+ matcher_copied_as_written,
+ })
}
ExtensionKind::Cli => {
// Deploy the CLI's associated skill to the target agent.
@@ -1603,7 +1629,7 @@ pub fn install_to_agent(
))
})?;
let deployed_name = deployer::deploy_skill(&source_path, &target_dir)?;
- Ok(deployed_name)
+ Ok(deployed_name.into())
}
other => Err(HkError::Internal(format!(
"Cross-agent deploy not supported for '{}' extensions",
@@ -3384,6 +3410,94 @@ mod tests {
assert!(!home.join(".openclaw").join("openclaw.json").exists());
}
+ #[test]
+ fn a_hook_keeps_its_tool_scope_and_its_kind_when_installed_to_another_agent() {
+ use crate::adapter;
+
+ let dir = TempDir::new().unwrap();
+ let home = dir.path();
+ let store = Mutex::new(Store::open(&home.join("test.db")).unwrap());
+ std::fs::create_dir_all(home.join(".claude")).unwrap();
+ std::fs::write(
+ home.join(".claude").join("settings.json"),
+ r#"{"hooks":{
+ "PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"echo hi"}]}],
+ "PostToolUse":[{"matcher":"*","hooks":[{"type":"command","command":"echo all"}]}],
+ "Stop":[{"hooks":[{"type":"prompt","prompt":"Is the work done?"}]}],
+ "SubagentStop":[{"hooks":[{"type":"agent","prompt":"Verify the tests"}]}]
+ }}"#,
+ )
+ .unwrap();
+ let home_dir = home.to_path_buf();
+ let adapters: Vec> = vec![
+ Box::new(adapter::claude::ClaudeAdapter::with_home(home_dir.clone())),
+ Box::new(adapter::codex::CodexAdapter::with_home(home_dir.clone())),
+ Box::new(adapter::gemini::GeminiAdapter::with_home(home_dir.clone())),
+ Box::new(adapter::cursor::CursorAdapter::with_home(home_dir.clone())),
+ Box::new(adapter::copilot::CopilotAdapter::with_home(
+ home_dir.clone(),
+ )),
+ Box::new(adapter::hermes::HermesAdapter::with_home(home_dir)),
+ ];
+ let hooks = scanner::scan_hooks(adapters[0].as_ref());
+ for hook in &hooks {
+ store.lock().insert_extension(hook).unwrap();
+ }
+ let id_of = |event: &str| {
+ let hook = hooks.iter().find(|h| h.name.starts_with(event)).unwrap();
+ hook.id.clone()
+ };
+ let (shell_hook, prompt_hook) = (id_of("PreToolUse"), id_of("Stop"));
+ let install = |id: &str, agent: &str| {
+ install_to_agent(&store, &adapters, id, agent, None, &ConfigScope::Global)
+ };
+ let written = |agent: &str| {
+ let target = adapters.iter().find(|a| a.name() == agent).unwrap();
+ target.read_hooks()
+ };
+
+ // Each agent gets the shell tool under the name it matches on.
+ for (agent, matcher) in [
+ ("gemini", "run_shell_command"),
+ ("cursor", "Shell"),
+ ("copilot", "Bash"),
+ ] {
+ let installed = install(&shell_hook, agent).unwrap();
+ assert_eq!(installed.matcher_copied_as_written, None, "{agent}");
+ assert_eq!(written(agent)[0].matcher.as_deref(), Some(matcher));
+ }
+ // Cursor spells "all tools" as no matcher at all.
+ install(&id_of("PostToolUse"), "cursor").unwrap();
+ assert!(
+ written("cursor")
+ .iter()
+ .any(|h| h.command == "echo all" && h.matcher.is_none())
+ );
+ // No table for Hermes yet: the matcher is copied and the caller told.
+ let installed = install(&shell_hook, "hermes").unwrap();
+ assert_eq!(installed.matcher_copied_as_written.as_deref(), Some("Bash"));
+
+ // Codex skips prompt hooks, so it must not receive one as a command.
+ let err = install(&prompt_hook, "codex").unwrap_err();
+ assert!(
+ matches!(&err, HkError::Validation(msg) if msg.contains("prompt hooks")),
+ "got: {err:?}"
+ );
+ assert!(written("codex").is_empty());
+ // Cursor runs prompt hooks but has no agent hooks.
+ let err = install(&id_of("SubagentStop"), "cursor").unwrap_err();
+ assert!(
+ matches!(&err, HkError::Validation(msg) if msg.contains("agent hooks")),
+ "got: {err:?}"
+ );
+ install(&prompt_hook, "cursor").unwrap();
+ assert!(
+ written("cursor")
+ .iter()
+ .any(|h| h.kind == adapter::HookKind::Prompt && h.command == "Is the work done?")
+ );
+ }
+
#[test]
fn test_install_to_agent_remote_mcp_claude_to_codex() {
// Issue #105 repro: `claude mcp add --transport http linear `
diff --git a/crates/hk-desktop/src/commands/install.rs b/crates/hk-desktop/src/commands/install.rs
index 83c6f920..db0b3e45 100644
--- a/crates/hk-desktop/src/commands/install.rs
+++ b/crates/hk-desktop/src/commands/install.rs
@@ -102,7 +102,7 @@ pub async fn install_to_agent(
target_agent: String,
hermes_category: Option,
target_scope: ConfigScope,
-) -> Result {
+) -> Result {
let store = state.store.clone();
let adapters = state.adapters.clone();
blocking(move || {
diff --git a/crates/hk-web/src/handlers/install.rs b/crates/hk-web/src/handlers/install.rs
index a8342a9f..380374a4 100644
--- a/crates/hk-web/src/handlers/install.rs
+++ b/crates/hk-web/src/handlers/install.rs
@@ -77,7 +77,7 @@ pub struct InstallToAgentParams {
pub async fn install_to_agent(
State(state): State,
Json(params): Json,
-) -> Result {
+) -> Result {
blocking(move || {
service::install_to_agent(
&state.store,
diff --git a/src/components/extensions/__tests__/bulk-install-dialog.test.tsx b/src/components/extensions/__tests__/bulk-install-dialog.test.tsx
index 3a3be3b1..64c37856 100644
--- a/src/components/extensions/__tests__/bulk-install-dialog.test.tsx
+++ b/src/components/extensions/__tests__/bulk-install-dialog.test.tsx
@@ -76,7 +76,9 @@ function groupOf(instances: Extension[]): GroupedExtension {
const onClaude = ext({ id: "pdf-claude" });
beforeEach(() => {
- installToAgent.mockReset().mockResolvedValue("new-id");
+ installToAgent
+ .mockReset()
+ .mockResolvedValue({ name: "new-id", matcher_copied_as_written: null });
useAgentStore.setState({
agents: [agent("claude"), agent("codex")],
agentOrder: ["claude", "codex"],
diff --git a/src/components/extensions/bulk-install-dialog.tsx b/src/components/extensions/bulk-install-dialog.tsx
index c6a768ce..f289ed69 100644
--- a/src/components/extensions/bulk-install-dialog.tsx
+++ b/src/components/extensions/bulk-install-dialog.tsx
@@ -1,5 +1,5 @@
import { clsx } from "clsx";
-import { Check, Loader2, X } from "lucide-react";
+import { Check, Loader2, TriangleAlert, X } from "lucide-react";
import { Fragment, useEffect, useId, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { extensionDisplayName } from "@/components/extensions/extension-name";
@@ -12,6 +12,7 @@ import {
buildInstallPlan,
groupBy,
type InstallItemRef,
+ type InstallOutcome,
type InstallPair,
type InstallPlan,
type InstallSkip,
@@ -69,9 +70,8 @@ function coveredBy(plan: InstallPlan, groupKey: string): string[] | null {
return [...new Set(skips.flatMap((s) => s.via ?? []))];
}
-interface AttemptResult {
+interface AttemptResult extends InstallOutcome {
pair: InstallPair;
- error?: string;
}
/** A run in progress or finished. The plan is snapshotted when the run
@@ -176,8 +176,10 @@ export function BulkInstallDialog({
}
await installPairs(plan.pairs, target, {
hermesCategory,
- onResult: (pair, error) =>
- setRun((r) => r && { ...r, results: [...r.results, { pair, error }] }),
+ onResult: (pair, outcome) =>
+ setRun(
+ (r) => r && { ...r, results: [...r.results, { pair, ...outcome }] },
+ ),
shouldStop: () => stopRef.current,
});
setRun((r) => r && { ...r, done: true });
@@ -205,6 +207,8 @@ export function BulkInstallDialog({
const close = done ? onDone : onClose;
const installedCount = run?.results.filter((r) => !r.error).length ?? 0;
const failedCount = (run?.results.length ?? 0) - installedCount;
+ const notable =
+ run?.results.filter((r) => r.error || r.matcherCopiedAsWritten) ?? [];
const runSkipped = run ? countSkipped(run) : 0;
const notRun = done && run ? run.pairs.length - run.results.length : 0;
@@ -385,29 +389,44 @@ export function BulkInstallDialog({
)}
- {failedCount > 0 && (
+ {notable.length > 0 && (
- {run.results
- .filter((r) => r.error)
- .map((r) => (
+ {notable.map((r) => {
+ const detail =
+ r.error ??
+ t("bulkInstall.matcherCopied", {
+ matcher: r.matcherCopiedAsWritten,
+ });
+ return (
-
-
+ {r.error ? (
+
+ ) : (
+
+ )}
{itemLabel(run.groups, r.pair)} →{" "}
{agentDisplayName(r.pair.targetAgent)}
- {r.error}
+ {detail}
- ))}
+ );
+ })}
)}
{/* A bundle whose parts were selected on their own has no
diff --git a/src/components/extensions/extension-detail.tsx b/src/components/extensions/extension-detail.tsx
index 5e003c7e..b9f99e16 100644
--- a/src/components/extensions/extension-detail.tsx
+++ b/src/components/extensions/extension-detail.tsx
@@ -32,7 +32,7 @@ import {
} from "@/lib/agent-capabilities";
import { copyPathToClipboard } from "@/lib/copy-path";
import i18n from "@/lib/i18n";
-import { buildInstallPlan } from "@/lib/install-plan";
+import { buildInstallPlan, type InstallOutcome } from "@/lib/install-plan";
import { api } from "@/lib/invoke";
import { isDesktop, isMac } from "@/lib/transport";
import type {
@@ -179,25 +179,32 @@ export function ExtensionDetail() {
return;
}
setDeploying(agent.name);
- let failed = false;
+ const outcomes: InstallOutcome[] = [];
await installPairs(pairs, effectiveTarget, {
hermesCategory,
- onResult: (_pair, error) => {
- if (error) failed = true;
- },
+ onResult: (_pair, outcome) => outcomes.push(outcome),
});
setDeploying(null);
setHermesCategoryPicker(false);
- if (failed) {
+ const agentName = agentDisplayName(agent.name);
+ const error = outcomes.find((o) => o.error)?.error;
+ if (error) {
toast.error(
- t("detail.installToFailed", { agent: agentDisplayName(agent.name) }),
+ t("detail.installToFailed", { agent: agentName, reason: error }),
);
return;
}
flashInstalled(agent.name);
- toast.success(
- t("detail.installToSuccess", { agent: agentDisplayName(agent.name) }),
- );
+ const matcher = outcomes.find(
+ (o) => o.matcherCopiedAsWritten,
+ )?.matcherCopiedAsWritten;
+ if (matcher) {
+ toast.warning(
+ t("detail.installToMatcherCopied", { agent: agentName, matcher }),
+ );
+ return;
+ }
+ toast.success(t("detail.installToSuccess", { agent: agentName }));
};
const [activeInstanceId, setActiveInstanceId] = useState(null);
const [showDelete, setShowDelete] = useState(false);
diff --git a/src/lib/i18n/locales/en/extensions.json b/src/lib/i18n/locales/en/extensions.json
index e2ae96d7..82655bd3 100644
--- a/src/lib/i18n/locales/en/extensions.json
+++ b/src/lib/i18n/locales/en/extensions.json
@@ -98,7 +98,8 @@
"cliChildrenSkipped_one": "Skipped {{count}} bundled item this agent can't take here",
"cliChildrenSkipped_other": "Skipped {{count}} bundled items this agent can't take here",
"installToSuccess": "Installed to {{agent}}. Takes effect in new sessions",
- "installToFailed": "Failed to install to {{agent}}",
+ "installToFailed": "Failed to install to {{agent}}: {{reason}}",
+ "installToMatcherCopied": "Installed to {{agent}}. Matcher “{{matcher}}” was copied as written; check that {{agent}} matches on it",
"nothingToInstall": "Nothing to install on {{agent}}",
"permissions": "Permissions",
"documentation": "Documentation",
@@ -184,6 +185,7 @@
"planSkipped_one": "{{count}} skipped",
"planSkipped_other": "{{count}} skipped",
"hermesNote": "Skills sent to Hermes go to its default category.",
+ "matcherCopied": "matcher “{{matcher}}” copied as written; check that the agent matches on it",
"start": "Install ({{count}})",
"installing": "Installing {{done}} of {{total}}…",
"installed_one": "{{count}} installed",
diff --git a/src/lib/i18n/locales/zh-TW/extensions.json b/src/lib/i18n/locales/zh-TW/extensions.json
index 673138e5..febf5a5e 100644
--- a/src/lib/i18n/locales/zh-TW/extensions.json
+++ b/src/lib/i18n/locales/zh-TW/extensions.json
@@ -98,7 +98,8 @@
"cliChildrenSkipped_one": "已跳過 {{count}} 個該代理在此範圍無法安裝的隨附項目",
"cliChildrenSkipped_other": "已跳過 {{count}} 個該代理在此範圍無法安裝的隨附項目",
"installToSuccess": "已安裝到 {{agent}}。將在新 session 生效",
- "installToFailed": "安裝到 {{agent}} 失敗",
+ "installToFailed": "安裝到 {{agent}} 失敗:{{reason}}",
+ "installToMatcherCopied": "已安裝到 {{agent}}。matcher「{{matcher}}」依原樣寫入,請確認 {{agent}} 能比對該寫法",
"nothingToInstall": "{{agent}} 沒有需要安裝的項目",
"permissions": "權限",
"documentation": "文件",
@@ -184,6 +185,7 @@
"planSkipped_one": "跳過 {{count}} 項",
"planSkipped_other": "跳過 {{count}} 項",
"hermesNote": "傳送到 Hermes 的 skill 會放入其預設分類。",
+ "matcherCopied": "matcher「{{matcher}}」依原樣寫入,請確認該 agent 能比對",
"start": "安裝 ({{count}})",
"installing": "正在安裝 {{done}}/{{total}}…",
"installed_one": "已安裝 {{count}} 項",
diff --git a/src/lib/i18n/locales/zh/extensions.json b/src/lib/i18n/locales/zh/extensions.json
index e32dc3a0..275069ea 100644
--- a/src/lib/i18n/locales/zh/extensions.json
+++ b/src/lib/i18n/locales/zh/extensions.json
@@ -98,7 +98,8 @@
"cliChildrenSkipped_one": "已跳过 {{count}} 个该智能体在此范围无法安装的捆绑项",
"cliChildrenSkipped_other": "已跳过 {{count}} 个该智能体在此范围无法安装的捆绑项",
"installToSuccess": "已安装到 {{agent}}。将在新会话中生效",
- "installToFailed": "安装到 {{agent}} 失败",
+ "installToFailed": "安装到 {{agent}} 失败:{{reason}}",
+ "installToMatcherCopied": "已安装到 {{agent}}。matcher「{{matcher}}」按原样写入,请确认 {{agent}} 能匹配该写法",
"nothingToInstall": "{{agent}} 没有需要安装的项",
"permissions": "权限",
"documentation": "文档",
@@ -184,6 +185,7 @@
"planSkipped_one": "跳过 {{count}} 项",
"planSkipped_other": "跳过 {{count}} 项",
"hermesNote": "发送到 Hermes 的 skill 会放入其默认分类。",
+ "matcherCopied": "matcher「{{matcher}}」按原样写入,请确认该 agent 能匹配",
"start": "安装 ({{count}})",
"installing": "正在安装 {{done}}/{{total}}…",
"installed_one": "已安装 {{count}} 项",
diff --git a/src/lib/install-plan.ts b/src/lib/install-plan.ts
index 18fb023e..107e8a1a 100644
--- a/src/lib/install-plan.ts
+++ b/src/lib/install-plan.ts
@@ -26,6 +26,12 @@ export interface InstallPair extends InstallItemRef {
isHermesSkill: boolean;
}
+/** How one pair of a run ended. Neither field set means a clean install. */
+export interface InstallOutcome {
+ error?: string;
+ matcherCopiedAsWritten?: string;
+}
+
export type InstallSkipReason =
| "already-installed"
| InstallBlockReason
diff --git a/src/lib/invoke.ts b/src/lib/invoke.ts
index 02da2661..e5189bd5 100644
--- a/src/lib/invoke.ts
+++ b/src/lib/invoke.ts
@@ -15,6 +15,7 @@ import { transport } from "./transport";
import type {
AgentDetail,
AgentInfo,
+ AgentInstall,
AuditResult,
ConfigScope,
DashboardStats,
@@ -231,7 +232,7 @@ export const api = {
targetAgent: string,
targetScope: ConfigScope,
hermesCategory?: string,
- ): Promise {
+ ): Promise {
return transport("install_to_agent", {
extensionId,
targetAgent,
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 1888ddac..646dcbad 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -503,6 +503,14 @@ export interface InstallResult {
skipped?: boolean;
}
+/** What a cross-agent install deployed. */
+export interface AgentInstall {
+ name: string;
+ /** A hook matcher part of which was not rewritten in the target agent's
+ * tool names. */
+ matcher_copied_as_written: string | null;
+}
+
export interface ToggleOutcome {
redacted_secret_keys: string[];
}
diff --git a/src/stores/__tests__/extension-store.test.ts b/src/stores/__tests__/extension-store.test.ts
index 560424dc..3be531ed 100644
--- a/src/stores/__tests__/extension-store.test.ts
+++ b/src/stores/__tests__/extension-store.test.ts
@@ -177,7 +177,10 @@ describe("extension-store installPairs", () => {
beforeEach(() => {
useExtensionStore.setState({ extensions: [dshPlugin] });
vi.resetAllMocks();
- vi.mocked(api.installToAgent).mockResolvedValue("timer");
+ vi.mocked(api.installToAgent).mockResolvedValue({
+ name: "timer",
+ matcher_copied_as_written: null,
+ });
vi.mocked(api.listExtensions).mockResolvedValue([]);
vi.mocked(api.getAllTags).mockResolvedValue([]);
vi.mocked(api.getAllPacks).mockResolvedValue([]);
@@ -193,14 +196,18 @@ describe("extension-store installPairs", () => {
const onResult = vi.fn();
const gemini = { ...pair, targetAgent: "gemini" };
vi.mocked(api.installToAgent)
- .mockResolvedValueOnce("timer")
+ .mockResolvedValueOnce({ name: "t", matcher_copied_as_written: "Bash" })
.mockRejectedValueOnce('{"kind":"Io","message":"Permission denied"}');
const run = useExtensionStore
.getState()
.installPairs([pair, gemini], { type: "global" }, { onResult });
await vi.waitFor(() => expect(onResult).toHaveBeenCalledTimes(2));
- expect(onResult).toHaveBeenNthCalledWith(1, pair, undefined);
- expect(onResult).toHaveBeenNthCalledWith(2, gemini, "Permission denied");
+ expect(onResult).toHaveBeenNthCalledWith(1, pair, {
+ matcherCopiedAsWritten: "Bash",
+ });
+ expect(onResult).toHaveBeenNthCalledWith(2, gemini, {
+ error: "Permission denied",
+ });
// The Codex placeholder is in the list before the rescan completes;
// the failed Gemini one never is.
const rows = useExtensionStore.getState().extensions;
diff --git a/src/stores/extension-store.ts b/src/stores/extension-store.ts
index 949c830c..4df85f09 100644
--- a/src/stores/extension-store.ts
+++ b/src/stores/extension-store.ts
@@ -1,7 +1,11 @@
import { create } from "zustand";
import { parseError } from "@/lib/error-types";
import i18n from "@/lib/i18n";
-import { type InstallPair, pendingCopyId } from "@/lib/install-plan";
+import {
+ type InstallOutcome,
+ type InstallPair,
+ pendingCopyId,
+} from "@/lib/install-plan";
import { api } from "@/lib/invoke";
import {
type ConfigScope,
@@ -134,7 +138,7 @@ interface ExtensionState {
targetScope: ConfigScope,
opts?: {
hermesCategory?: string;
- onResult?: (pair: InstallPair, error?: string) => void;
+ onResult?: (pair: InstallPair, outcome: InstallOutcome) => void;
/** Checked before each install; true stops the run there. */
shouldStop?: () => boolean;
},
@@ -339,8 +343,7 @@ export const useExtensionStore = create((set, get) => ({
/** Run a plan's installs in order. Each copy that lands is shown in the
* table at once (a placeholder row the closing rescan replaces), so a
* long run lights up one agent at a time without a rescan per
- * install. `onResult` fires per pair, with the backend's message on
- * failure; the run itself never throws. */
+ * install. `onResult` fires per pair; the run itself never throws. */
async installPairs(
pairs,
targetScope,
@@ -349,19 +352,22 @@ export const useExtensionStore = create((set, get) => ({
for (const pair of pairs) {
// A stop lets the install in flight finish, then attempts no more.
if (shouldStop?.()) break;
- let error: string | undefined;
+ const outcome: InstallOutcome = {};
try {
- await api.installToAgent(
+ const installed = await api.installToAgent(
pair.sourceId,
pair.targetAgent,
targetScope,
pair.isHermesSkill ? hermesCategory : undefined,
);
+ outcome.matcherCopiedAsWritten =
+ installed.matcher_copied_as_written ?? undefined;
} catch (e) {
- error = parseError(e).message;
+ outcome.error = parseError(e).message;
}
- if (!error) set((s) => showPendingCopy(s.extensions, pair, targetScope));
- onResult?.(pair, error);
+ if (!outcome.error)
+ set((s) => showPendingCopy(s.extensions, pair, targetScope));
+ onResult?.(pair, outcome);
}
// One rescan for the whole run; if the scan itself fails, at least
// refetch so no placeholder row survives.
diff --git a/website/src/content/docs/docs/guides/extensions.mdx b/website/src/content/docs/docs/guides/extensions.mdx
index c5dcc623..fda63d43 100644
--- a/website/src/content/docs/docs/guides/extensions.mdx
+++ b/website/src/content/docs/docs/guides/extensions.mdx
@@ -102,9 +102,8 @@ What changes on disk depends on the kind:
When it works, a toast says the install takes effect in new sessions.
:::caution[Hooks]
-- A hook's matcher is copied as written. Tool names differ between agents, so a matcher such as `Bash` may never match on the new agent, and the hook never runs. After you install, change the matcher in that agent's hook file to its name for the tool.
-- Cursor, Copilot and Devin Desktop hooks have no matcher. Installing there drops it, so the hook runs for every tool.
-- When an agent has no event that matches, the install fails. The detail panel only says it failed. The reason shows in the **Install to agents** summary.
+- Tool names differ between agents. HarnessKit rewrites the ones in a hook's matcher for Cursor and Gemini CLI. When it copies a matcher as written, it tells you, and you check the matcher in that agent's hook file.
+- When an agent has no event that matches, the install fails and the message says why.
:::
## Select several
diff --git a/website/src/content/docs/docs/how-it-works/installing-a-hook.mdx b/website/src/content/docs/docs/how-it-works/installing-a-hook.mdx
index 92d05d41..4034adf6 100644
--- a/website/src/content/docs/docs/how-it-works/installing-a-hook.mdx
+++ b/website/src/content/docs/docs/how-it-works/installing-a-hook.mdx
@@ -1,6 +1,6 @@
---
title: "Installing a hook: event translation"
-description: "How HarnessKit translates hook events between agents, and where it can't."
+description: "How HarnessKit translates hook events and tool names between agents, and where it can't."
sidebar:
order: 4
label: "Installing a hook"
@@ -8,7 +8,7 @@ sidebar:
import { CardGrid, LinkCard } from "@astrojs/starlight/components";
:::note[In short]
-When you install a hook to another agent, HarnessKit renames its event to the target agent's name for it. Then it adds the command to the target's hook file. Claude Code's event names serve as the common vocabulary. The matcher, which picks the tools a hook applies to, is copied unchanged. Cursor, Copilot and Devin Desktop get no matcher at all.
+When you install a hook to another agent, HarnessKit renames its event to the target agent's name for it. Then it adds the command to the target's hook file. Claude Code's event names serve as the common vocabulary. The matcher, which picks the tools a hook applies to, has its tool names rewritten for Cursor and Gemini CLI.
:::
## How agents name hook events
@@ -18,8 +18,9 @@ Claude Code runs a hook before a tool call on the `PreToolUse` event. Gemini CLI
## What HarnessKit does
1. **Read.** HarnessKit reads the hook's event, matcher and command from the source agent. Nothing else travels, such as a timeout.
-2. **Translate the event.** HarnessKit looks the event up in a table keyed by Claude Code's names. If the target has no equivalent, the install fails. The detail panel says only "Failed to install to Hermes". The reason, such as "Hook event 'Stop' is not supported by hermes", shows only in the summary of a bulk install.
-3. **Append.** HarnessKit adds the command under the translated event in the target's hook file. A command that is already there is not added twice.
+2. **Translate the event.** HarnessKit looks the event up in a table keyed by Claude Code's names. If the target has no equivalent, the install fails and says why, such as "Hook event 'Stop' is not supported by hermes".
+3. **Translate the matcher.** Codex, Copilot, Grok Build and Qoder CN match on Claude Code's tool names, so the matcher goes across unchanged. When the hook goes to or comes from Cursor or Gemini CLI, HarnessKit rewrites each tool name it knows: `Bash` becomes `Shell` on Cursor and `run_shell_command` on Gemini CLI.
+4. **Append.** HarnessKit adds the command under the translated event in the target's hook file. A command that is already there is not added twice.
Some real pairs from that table:
@@ -64,14 +65,14 @@ After you install it to Gemini CLI, Gemini CLI's settings file gains this entry:
"type": "command"
}
],
- "matcher": "Bash"
+ "matcher": "run_shell_command"
}
]
}
}
```
-The event became `BeforeTool`. The matcher is still `Bash`, and Gemini CLI has no tool by that name. Change it to `run_shell_command` and the hook fires.
+The event became `BeforeTool`, and the matcher became Gemini CLI's name for its shell tool.
### Enable and disable
@@ -84,16 +85,15 @@ Grok Build keeps a `disabled-hooks` file, and Kiro has an `enabled` flag on each
## Limitations
:::caution[Limitations]
-- **Matchers are copied as they are.** Tool names differ between agents. A Gemini CLI hook on `run_shell_command` lands unchanged in Claude Code or Qoder CN. No tool there has that name, so it never runs. Edit the matcher in the target's file after you install.
-- **Cursor, Copilot and Devin Desktop lose the matcher.** HarnessKit writes their hooks with no matcher at all. On Cursor and Copilot, a hook meant for one tool then runs on every tool call. Before you install a hook there, make sure it can run on every call.
-- **Prompt hooks become shell commands.** HarnessKit reads a Claude Code `prompt` hook's text as its command. The other agent gets a command hook, such as `{"type": "command", "command": ""}`, and tries to run the prompt as a shell command. Don't install a prompt hook to another agent.
+- **Some matchers are copied as written.** That covers a pattern such as `mcp__github__.*`, a tool the target has no name for, and any matcher going to Hermes or Kiro. HarnessKit tells you when it does this. Check the matcher in the target's file.
+- **Prompt hooks go only to agents that run them.** Those are Claude Code, Cursor and Qoder CN. On any other agent the install fails.
:::
## Under the hood
-- `crates/hk-core/src/adapter/hook_events.rs` holds the event tables, keyed by Claude Code's names.
-- `crates/hk-core/src/service.rs` translates the event during an install, and nothing else.
-- `crates/hk-core/src/deployer.rs` has one writer per hook format and decides which formats keep the matcher.
+- `crates/hk-core/src/adapter/hook_events.rs` holds the event tables, keyed by Claude Code's names, and `crates/hk-core/src/adapter/hook_tools.rs` the tool names used in matchers.
+- `crates/hk-core/src/service.rs` translates the event and the matcher during an install.
+- `crates/hk-core/src/deployer.rs` has one writer per hook format.
- `crates/hk-core/src/manager.rs` enables and disables hooks.
- `src/lib/agent-capabilities.ts` greys out Install to Agent tiles by hook and scope support, not by event.
diff --git a/website/src/content/docs/docs/troubleshooting.md b/website/src/content/docs/docs/troubleshooting.md
index a10b1c5d..373f3a29 100644
--- a/website/src/content/docs/docs/troubleshooting.md
+++ b/website/src/content/docs/docs/troubleshooting.md
@@ -97,17 +97,17 @@ When the port is taken on your own computer instead, `ssh -L` prints a warning s
### A hook installed on another agent never runs
-**Why.** HarnessKit translates a hook's event name, but copies its matcher as it is, and agents name their tools differently. A Gemini CLI hook on `run_shell_command` lands unchanged in Claude Code, where no tool has that name. A Claude Code prompt hook arrives as a shell command, so the agent tries to run the prompt's text. On Cursor and Copilot it goes the other way: HarnessKit drops the matcher, so the hook runs on every tool call.
+**Why.** Agents name their tools differently. HarnessKit rewrites the tool names in a hook's matcher for Cursor and Gemini CLI. A matcher it can't rewrite is copied as written, and the install tells you so. A Claude Code hook on `Bash` lands unchanged in Hermes, where no tool has that name.
**What to do.** Open the hook in the target agent's hook file and change the matcher to that agent's name for the tool. [Supported agents and file locations](/docs/reference/agents/) lists each agent's hook file. [Installing a hook](/docs/how-it-works/installing-a-hook/#limitations) lists what else changes when a hook moves to another agent.
### Installing fails when the agent's config file has comments
-The detail panel says only "Failed to install to Copilot", or whichever agent it was. The MCP servers or hooks in that file are missing from HarnessKit too.
+The install fails with a parse error. The MCP servers or hooks in that file are missing from HarnessKit too.
**Why.** HarnessKit reads and writes most agents' JSON config files as strict JSON. A file with comments or trailing commas, such as VS Code's `mcp.json` for Copilot, doesn't parse. HarnessKit then lists nothing from that file, and it refuses to write the file rather than lose your comments. OpenCode's and OpenClaw's config files are the exceptions: HarnessKit keeps their comments.
-**What to do.** Take the comments and trailing commas out of the file, then install again. To see why an install failed, tick the row's checkbox and use **Install to agents**: its summary lists each failure with its error. [Installing an MCP server](/docs/how-it-works/installing-an-mcp-server/#limitations) says which files keep their comments when HarnessKit writes them.
+**What to do.** Take the comments and trailing commas out of the file, then install again. [Installing an MCP server](/docs/how-it-works/installing-an-mcp-server/#limitations) says which files keep their comments when HarnessKit writes them.
## Overview
diff --git a/website/src/content/docs/zh/docs/guides/extensions.mdx b/website/src/content/docs/zh/docs/guides/extensions.mdx
index e398626d..b7029687 100644
--- a/website/src/content/docs/zh/docs/guides/extensions.mdx
+++ b/website/src/content/docs/zh/docs/guides/extensions.mdx
@@ -102,9 +102,8 @@ skill、MCP server、hook 和 CLI 都可以安装到另一个 agent。安装 CLI
安装成功后,提示会说明改动在新会话中生效。
:::caution[hook]
-- hook 的 matcher 按原样复制。各 agent 的工具名称不同,`Bash` 这类 matcher 在新 agent 上可能永远无法匹配,hook 也就永远不会运行。安装后,请在该 agent 的 hook 文件中把 matcher 改为它对应的工具名称。
-- Cursor、Copilot 和 Devin Desktop 的 hook 没有 matcher。安装到这几个 agent 时 matcher 会被丢弃,hook 对所有工具都会运行。
-- agent 没有对应的事件时,安装会失败。详情面板只提示安装失败,具体原因只在批量**安装到智能体**的结果中显示。
+- 各 agent 的工具名称不同。安装到 Cursor 和 Gemini CLI 时,HarnessKit 会改写 hook 的 matcher 中的工具名称。matcher 按原样写入时会给出提示,请在该 agent 的 hook 文件中检查。
+- agent 没有对应的事件时,安装会失败,并提示原因。
:::
## 批量操作
diff --git a/website/src/content/docs/zh/docs/how-it-works/installing-a-hook.mdx b/website/src/content/docs/zh/docs/how-it-works/installing-a-hook.mdx
index ca237b44..3250ad41 100644
--- a/website/src/content/docs/zh/docs/how-it-works/installing-a-hook.mdx
+++ b/website/src/content/docs/zh/docs/how-it-works/installing-a-hook.mdx
@@ -1,6 +1,6 @@
---
title: "安装 hook:转换事件"
-description: "HarnessKit 如何在 agent 之间转换 hook 事件,以及哪些事件无法转换。"
+description: "HarnessKit 如何在 agent 之间转换 hook 事件和工具名称,以及哪些无法转换。"
sidebar:
order: 4
label: "安装 hook"
@@ -8,7 +8,7 @@ sidebar:
import { CardGrid, LinkCard } from "@astrojs/starlight/components";
:::note[简单来说]
-把 hook 安装到另一个 agent 时,HarnessKit 先把它的事件改为目标 agent 中对应的名称,再把命令添加到目标的 hook 文件中。Claude Code 的事件名是各 agent 之间的通用名称。matcher(决定 hook 作用于哪些工具)原样复制;写给 Cursor、Copilot 和 Devin Desktop 的 hook 则完全没有 matcher。
+把 hook 安装到另一个 agent 时,HarnessKit 先把它的事件改为目标 agent 中对应的名称,再把命令添加到目标的 hook 文件中。Claude Code 的事件名是各 agent 之间的通用名称。matcher(决定 hook 作用于哪些工具)中的工具名称,在安装到 Cursor 和 Gemini CLI 时会改写为目标 agent 的名称。
:::
## 各 agent 如何命名 hook 事件
@@ -18,8 +18,9 @@ Claude Code 在调用工具前运行 hook,使用的是 `PreToolUse` 事件。G
## HarnessKit 怎么做
1. **读取**。HarnessKit 从来源 agent 读取 hook 的事件、matcher 和命令,其他内容(例如超时)都不会带过去。
-2. **转换事件**。在一张以 Claude Code 事件名为键的表中查找该事件。若目标没有对应的事件,安装失败。详情面板只提示「安装到 Hermes 失败」;具体原因(例如「Hook event 'Stop' is not supported by hermes」)只能在批量安装的汇总中看到。
-3. **追加**。在目标的 hook 文件中,把命令添加到转换后的事件下。已有的命令不会重复添加。
+2. **转换事件**。在一张以 Claude Code 事件名为键的表中查找该事件。若目标没有对应的事件,安装失败并给出原因,例如「Hook event 'Stop' is not supported by hermes」。
+3. **转换 matcher**。Codex、Copilot、Grok Build 和 Qoder CN 按 Claude Code 的工具名称匹配,matcher 原样写入。hook 安装到 Cursor 或 Gemini CLI,或者来自这两个 agent 时,HarnessKit 会改写其中已知的工具名称:`Bash` 在 Cursor 中改为 `Shell`,在 Gemini CLI 中改为 `run_shell_command`。
+4. **追加**。在目标的 hook 文件中,把命令添加到转换后的事件下。已有的命令不会重复添加。
表中的几组实际对应关系:
@@ -71,7 +72,7 @@ Devin Desktop 有 12 个 hook 事件,HarnessKit 有意只映射了其中 2 个
}
```
-事件变为 `BeforeTool`。matcher 仍是 `Bash`,但 Gemini CLI 没有这个名称的工具。将其改为 `run_shell_command` 后,hook 才会触发。
+事件变为 `BeforeTool`,matcher 变为 Gemini CLI 中 shell 工具的名称。
### 启用和禁用
@@ -84,16 +85,15 @@ Grok Build 有 `disabled-hooks` 文件,Kiro 的每个 hook 都有 `enabled`
## 局限
:::caution[局限]
-- **matcher 原样复制**。各 agent 的工具名称不同。Gemini CLI 中针对 `run_shell_command` 的 hook 安装到 Claude Code 或 Qoder CN 后,matcher 保持不变,而目标中没有这个名称的工具,hook 永远不会运行。安装后,请到目标的文件中修改 matcher。
-- **Cursor、Copilot 和 Devin Desktop 会丢失 matcher**。HarnessKit 为它们写入的 hook 完全没有 matcher。在 Cursor 和 Copilot 上,原本只针对一个工具的 hook,会在每次调用工具时运行。安装到这两个 agent 之前,请确认该 hook 可以在每次调用工具时运行。
-- **prompt hook 会变成 shell 命令**。HarnessKit 把 Claude Code `prompt` hook 的文本当作命令读取。另一个 agent 收到的是 command hook,例如 `{"type": "command", "command": ""}`,会尝试把这段 prompt 当作 shell 命令运行。不要把 prompt hook 安装到其他 agent。
+- **部分 matcher 按原样写入**。包括 `mcp__github__.*` 这类模式、目标 agent 中没有对应名称的工具,以及安装到 Hermes 或 Kiro 的所有 matcher。出现这种情况时 HarnessKit 会给出提示,请到目标的文件中检查 matcher。
+- **prompt hook 只能安装到支持它的 agent**,即 Claude Code、Cursor 和 Qoder CN。安装到其他 agent 会失败。
:::
## 相关源码
-- `crates/hk-core/src/adapter/hook_events.rs` 存放事件对应表,以 Claude Code 的事件名为键。
-- `crates/hk-core/src/service.rs` 在安装时转换事件,此外不转换任何内容。
-- `crates/hk-core/src/deployer.rs` 每种 hook 格式一个写入器,并决定哪些格式保留 matcher。
+- `crates/hk-core/src/adapter/hook_events.rs` 存放事件对应表,以 Claude Code 的事件名为键;`crates/hk-core/src/adapter/hook_tools.rs` 存放 matcher 中使用的工具名称。
+- `crates/hk-core/src/service.rs` 在安装时转换事件和 matcher。
+- `crates/hk-core/src/deployer.rs` 每种 hook 格式一个写入器。
- `crates/hk-core/src/manager.rs` 负责启用和禁用 hook。
- `src/lib/agent-capabilities.ts` 按是否支持 hook、是否支持该范围,把**安装到智能体**下的 agent 按钮置灰,不看事件。
diff --git a/website/src/content/docs/zh/docs/troubleshooting.md b/website/src/content/docs/zh/docs/troubleshooting.md
index 7cd16a0a..5821d6cd 100644
--- a/website/src/content/docs/zh/docs/troubleshooting.md
+++ b/website/src/content/docs/zh/docs/troubleshooting.md
@@ -97,17 +97,17 @@ description: HarnessKit 的常见问题:出现的原因,以及相应的解
### 安装到其他 agent 的 hook 从不触发
-**原因**。HarnessKit 会转换 hook 的事件名,但 matcher 原样复制,而各个 agent 的工具名称并不相同。Gemini CLI 中匹配 `run_shell_command` 的 hook 原样写入 Claude Code 后,Claude Code 中并没有这个名称的工具。Claude Code 的 prompt hook 安装到其他 agent 后会变成 shell 命令,agent 会尝试把 prompt 文本当作命令运行。Cursor 和 Copilot 的情况相反:HarnessKit 去掉了 matcher,hook 会在每次调用工具时运行。
+**原因**。各个 agent 的工具名称并不相同。安装到 Cursor 和 Gemini CLI 时,HarnessKit 会改写 hook 的 matcher 中的工具名称。无法改写的 matcher 按原样写入,安装时会给出提示。例如 Claude Code 中匹配 `Bash` 的 hook 原样写入 Hermes 后,Hermes 中并没有这个名称的工具。
**解决办法**。在目标 agent 的 hook 文件中找到该 hook,把 matcher 改为该 agent 中对应工具的名称。各 agent 的 hook 文件请参阅[支持的 agent 和文件位置](/zh/docs/reference/agents/)。hook 安装到其他 agent 后还有哪些变化,请参阅[安装 hook](/zh/docs/how-it-works/installing-a-hook/#局限)。
### agent 的配置文件中有注释时安装失败
-详情面板只提示「安装到 Copilot 失败」(Copilot 处显示的是出错的 agent)。HarnessKit 中也看不到该文件中的 MCP server 或 hook。
+安装失败并提示解析错误。HarnessKit 中也看不到该文件中的 MCP server 或 hook。
**原因**。大多数 agent 的 JSON 配置文件,HarnessKit 都按严格的 JSON 读写。带注释或末尾有多余逗号的文件(例如 Copilot 使用的 VS Code `mcp.json`)无法解析。因此 HarnessKit 不会列出该文件中的任何内容,也会拒绝写入,以免丢失你的注释。OpenCode 和 OpenClaw 的配置文件例外,HarnessKit 会保留它们的注释。
-**解决办法**。删除文件中的注释和末尾多余的逗号,再重新安装。如需查看安装失败的原因,请勾选这一行并使用**安装到智能体**:结果摘要会列出每个失败项及其报错。哪些文件在 HarnessKit 写入后仍保留注释,请参阅[安装 MCP server](/zh/docs/how-it-works/installing-an-mcp-server/#局限)。
+**解决办法**。删除文件中的注释和末尾多余的逗号,再重新安装。哪些文件在 HarnessKit 写入后仍保留注释,请参阅[安装 MCP server](/zh/docs/how-it-works/installing-an-mcp-server/#局限)。
## 概览
From 690dd1d3a3b711cfead79ff789f3c59c7a2bbf8c Mon Sep 17 00:00:00 2001
From: RealZST
Date: Fri, 4 Dec 2026 22:58:47 +0800
Subject: [PATCH 2/4] fix(hooks): snapshot only the disabled handler of a hook
group
Disabling one handler of a Claude-shaped group saved the whole group, so
enabling it again pushed the group's other handlers back a second time.
Co-Authored-By: Claude Fable 5.2
---
crates/hk-core/src/deployer.rs | 12 ++++++++----
crates/hk-core/src/manager.rs | 34 ++++++++++++++++++++++++++++++++++
2 files changed, 42 insertions(+), 4 deletions(-)
diff --git a/crates/hk-core/src/deployer.rs b/crates/hk-core/src/deployer.rs
index 2186114f..2da77657 100644
--- a/crates/hk-core/src/deployer.rs
+++ b/crates/hk-core/src/deployer.rs
@@ -3057,10 +3057,14 @@ pub fn read_hook_config(
if group_matcher != matcher {
continue;
}
- if let Some(cmds) = group.get("hooks").and_then(|v| v.as_array())
- && cmds.iter().any(|c| handler_runs(c, command))
- {
- return Ok(Some(group.clone()));
+ // Keep only this hook's handler: the group's other handlers
+ // stay in the file, and restoring them too would run them twice.
+ let mut snapshot = group.clone();
+ if let Some(handlers) = snapshot.get_mut("hooks").and_then(|v| v.as_array_mut()) {
+ handlers.retain(|handler| handler_runs(handler, command));
+ if !handlers.is_empty() {
+ return Ok(Some(snapshot));
+ }
}
}
Ok(None)
diff --git a/crates/hk-core/src/manager.rs b/crates/hk-core/src/manager.rs
index adb45619..54b8d934 100644
--- a/crates/hk-core/src/manager.rs
+++ b/crates/hk-core/src/manager.rs
@@ -2944,6 +2944,40 @@ mod tests {
}
}
+ #[test]
+ fn restoring_a_hook_leaves_the_other_handlers_of_its_group_alone() {
+ let dir = TempDir::new().unwrap();
+ let home = dir.path();
+ std::fs::create_dir_all(home.join(".claude")).unwrap();
+ let settings = home.join(".claude/settings.json");
+ std::fs::write(
+ &settings,
+ r#"{"hooks":{"PostToolUse":[{"matcher":"Write","hooks":[
+ {"type":"command","command":"fmt.sh"},
+ {"type":"command","command":"lint.sh"}
+ ]}]}}"#,
+ )
+ .unwrap();
+ let store = crate::store::Store::open(&home.join("test.db")).unwrap();
+ let adapters: Vec> = vec![Box::new(
+ adapter::claude::ClaudeAdapter::with_home(home.to_path_buf()),
+ )];
+ let scanned = scanner::scan_hooks(&*adapters[0]);
+ store.sync_extensions(&scanned).unwrap();
+ let fmt = scanned.iter().find(|h| h.name.ends_with("fmt.sh")).unwrap();
+
+ toggle_extension_with_adapters(&store, &adapters, &fmt.id, false).unwrap();
+ toggle_extension_with_adapters(&store, &adapters, &fmt.id, true).unwrap();
+
+ let mut commands: Vec = adapters[0]
+ .read_hooks()
+ .into_iter()
+ .map(|hook| hook.command)
+ .collect();
+ commands.sort();
+ assert_eq!(commands, ["fmt.sh", "lint.sh"]);
+ }
+
// -----------------------------------------------------------------------
// Task 3: manifest candidate list + silent failure
// -----------------------------------------------------------------------
From 5e3ce86f497dca752823135f31f456573baa6926 Mon Sep 17 00:00:00 2001
From: RealZST
Date: Fri, 4 Dec 2026 23:00:37 +0800
Subject: [PATCH 3/4] fix(hooks): disable and delete a Copilot hook kept under
a shell key
A Copilot hook whose command sits under `bash` or a platform key was
listed but could not be disabled or deleted, because only `command` was
matched. The reader and the matcher now share one lookup.
Co-Authored-By: Claude Fable 5.2
---
crates/hk-core/src/adapter/copilot.rs | 35 ++++++++++++---------------
crates/hk-core/src/deployer.rs | 7 ++++--
crates/hk-core/src/manager.rs | 22 +++++++++++++++++
3 files changed, 43 insertions(+), 21 deletions(-)
diff --git a/crates/hk-core/src/adapter/copilot.rs b/crates/hk-core/src/adapter/copilot.rs
index bd0386eb..36006d85 100644
--- a/crates/hk-core/src/adapter/copilot.rs
+++ b/crates/hk-core/src/adapter/copilot.rs
@@ -430,25 +430,7 @@ impl AgentAdapter for CopilotAdapter {
continue;
};
for hook in arr {
- // Copilot format: {"type": "command", "command": "..."} or platform-specific {"osx": "...", "linux": "...", "windows": "..."}
- let cmd = hook
- .get("command")
- .and_then(|v| v.as_str())
- .or_else(|| {
- #[cfg(target_os = "macos")]
- {
- hook.get("osx").and_then(|v| v.as_str())
- }
- #[cfg(target_os = "windows")]
- {
- hook.get("windows").and_then(|v| v.as_str())
- }
- #[cfg(not(any(target_os = "macos", target_os = "windows")))]
- {
- hook.get("linux").and_then(|v| v.as_str())
- }
- })
- .or_else(|| hook.get("bash").and_then(|v| v.as_str()));
+ let cmd = hook_command(hook);
if let Some(cmd_str) = cmd {
entries.push(HookEntry {
event: event.clone(),
@@ -468,6 +450,21 @@ impl AgentAdapter for CopilotAdapter {
}
}
+/// The command a Copilot hook entry runs here: `command`, else the key for
+/// this platform, else `bash`.
+pub(crate) fn hook_command(hook: &serde_json::Value) -> Option<&str> {
+ let platform_key = if cfg!(target_os = "macos") {
+ "osx"
+ } else if cfg!(target_os = "windows") {
+ "windows"
+ } else {
+ "linux"
+ };
+ ["command", platform_key, "bash"]
+ .iter()
+ .find_map(|key| hook.get(key).and_then(|v| v.as_str()))
+}
+
#[cfg(test)]
mod tests {
use super::super::{AgentAdapter, McpTransport};
diff --git a/crates/hk-core/src/deployer.rs b/crates/hk-core/src/deployer.rs
index 2da77657..2c5b199a 100644
--- a/crates/hk-core/src/deployer.rs
+++ b/crates/hk-core/src/deployer.rs
@@ -1810,9 +1810,12 @@ fn handler_runs(handler: &serde_json::Value, command: &str) -> bool {
}
/// True if an entry of a flat event array (Cursor, Copilot) is the
-/// (matcher, command) hook.
+/// (matcher, command) hook. Copilot may keep the command under a shell or
+/// platform key instead of `command`.
fn flat_hook_matches(hook: &serde_json::Value, matcher: Option<&str>, command: &str) -> bool {
- hook.get("matcher").and_then(|v| v.as_str()) == matcher && handler_runs(hook, command)
+ hook.get("matcher").and_then(|v| v.as_str()) == matcher
+ && (handler_runs(hook, command)
+ || crate::adapter::copilot::hook_command(hook) == Some(command))
}
fn kiro_hook_value(entry: &HookEntry) -> serde_json::Value {
diff --git a/crates/hk-core/src/manager.rs b/crates/hk-core/src/manager.rs
index 54b8d934..ab33e5a1 100644
--- a/crates/hk-core/src/manager.rs
+++ b/crates/hk-core/src/manager.rs
@@ -2944,6 +2944,28 @@ mod tests {
}
}
+ #[test]
+ fn a_copilot_hook_under_a_shell_key_is_disabled_and_restored() {
+ let dir = TempDir::new().unwrap();
+ let home = dir.path();
+ std::fs::create_dir_all(home.join(".copilot/hooks")).unwrap();
+ let hooks_file = home.join(".copilot/hooks/hooks.json");
+ let original =
+ r#"{"version":1,"hooks":{"sessionStart":[{"type":"command","bash":"./start.sh"}]}}"#;
+ std::fs::write(&hooks_file, original).unwrap();
+ let store = crate::store::Store::open(&home.join("test.db")).unwrap();
+ let adapters: Vec> = vec![Box::new(
+ adapter::copilot::CopilotAdapter::with_home(home.to_path_buf()),
+ )];
+ let scanned = scanner::scan_hooks(&*adapters[0]);
+ store.sync_extensions(&scanned).unwrap();
+
+ toggle_extension_with_adapters(&store, &adapters, &scanned[0].id, false).unwrap();
+ assert!(adapters[0].read_hooks().is_empty());
+ toggle_extension_with_adapters(&store, &adapters, &scanned[0].id, true).unwrap();
+ assert_eq!(adapters[0].read_hooks()[0].command, "./start.sh");
+ }
+
#[test]
fn restoring_a_hook_leaves_the_other_handlers_of_its_group_alone() {
let dir = TempDir::new().unwrap();
From 695526a1746307330e4b9547463a57d0b4cf5347 Mon Sep 17 00:00:00 2001
From: RealZST
Date: Fri, 4 Dec 2026 23:35:30 +0800
Subject: [PATCH 4/4] fix(hooks): restore exactly what disabling a hook took
out
- Match a Cursor or Copilot entry the way that agent's reader lists it,
so an entry the reader skips is never saved or removed in its place.
- Entries that differ only in other keys are one row; save all of them,
since disabling removes all of them.
- Trim a whole-group snapshot saved by an earlier version to the row's
own handler before restoring it.
Co-Authored-By: Claude Fable 5.2
---
crates/hk-core/src/deployer.rs | 44 ++++++++++++++++-------
crates/hk-core/src/manager.rs | 66 +++++++++++++++++++++++++++++-----
2 files changed, 88 insertions(+), 22 deletions(-)
diff --git a/crates/hk-core/src/deployer.rs b/crates/hk-core/src/deployer.rs
index 2c5b199a..d86d8e21 100644
--- a/crates/hk-core/src/deployer.rs
+++ b/crates/hk-core/src/deployer.rs
@@ -1810,12 +1810,18 @@ fn handler_runs(handler: &serde_json::Value, command: &str) -> bool {
}
/// True if an entry of a flat event array (Cursor, Copilot) is the
-/// (matcher, command) hook. Copilot may keep the command under a shell or
-/// platform key instead of `command`.
-fn flat_hook_matches(hook: &serde_json::Value, matcher: Option<&str>, command: &str) -> bool {
- hook.get("matcher").and_then(|v| v.as_str()) == matcher
- && (handler_runs(hook, command)
- || crate::adapter::copilot::hook_command(hook) == Some(command))
+/// (matcher, command) hook, read the way that agent's reader lists it.
+fn flat_hook_matches(
+ format: HookFormat,
+ hook: &serde_json::Value,
+ matcher: Option<&str>,
+ command: &str,
+) -> bool {
+ let runs = match format {
+ HookFormat::Copilot => crate::adapter::copilot::hook_command(hook) == Some(command),
+ _ => hook.is_object() && handler_runs(hook, command),
+ };
+ runs && hook.get("matcher").and_then(|v| v.as_str()) == matcher
}
fn kiro_hook_value(entry: &HookEntry) -> serde_json::Value {
@@ -2088,7 +2094,7 @@ pub fn deploy_hook(
}
if !arr
.iter()
- .any(|h| flat_hook_matches(h, matcher, &entry.command))
+ .any(|h| flat_hook_matches(format, h, matcher, &entry.command))
{
arr.push(hook);
}
@@ -2338,7 +2344,7 @@ pub fn remove_hook(
if let Some(hooks) = config.get_mut("hooks").and_then(|v| v.as_object_mut())
&& let Some(event_arr) = hooks.get_mut(event).and_then(|v| v.as_array_mut())
{
- event_arr.retain(|h| !flat_hook_matches(h, matcher, command));
+ event_arr.retain(|h| !flat_hook_matches(format, h, matcher, command));
if event_arr.is_empty() {
hooks.remove(event);
}
@@ -2579,7 +2585,10 @@ pub fn restore_hook(
let arr = event_arr
.as_array_mut()
.ok_or_else(|| HkError::ConfigCorrupted("hook event is not an array".into()))?;
- arr.push(entry.clone());
+ match entry {
+ serde_json::Value::Array(entries) => arr.extend(entries.iter().cloned()),
+ _ => arr.push(entry.clone()),
+ }
}
HookFormat::Windsurf => {
let hooks = config
@@ -3072,10 +3081,19 @@ pub fn read_hook_config(
}
Ok(None)
}
- HookFormat::Cursor | HookFormat::Copilot => Ok(event_arr
- .iter()
- .find(|hook| flat_hook_matches(hook, matcher, command))
- .cloned()),
+ HookFormat::Cursor | HookFormat::Copilot => {
+ // Entries that differ only in other keys are one row, and
+ // `remove_hook` takes them all out, so all of them are saved.
+ let mut entries: Vec = event_arr
+ .iter()
+ .filter(|hook| flat_hook_matches(format, hook, matcher, command))
+ .cloned()
+ .collect();
+ Ok(match entries.len() {
+ 0 | 1 => entries.pop(),
+ _ => Some(serde_json::Value::Array(entries)),
+ })
+ }
HookFormat::Windsurf => {
for entry in event_arr {
if entry.get("command").and_then(|v| v.as_str()) == Some(command)
diff --git a/crates/hk-core/src/manager.rs b/crates/hk-core/src/manager.rs
index ab33e5a1..488f34a4 100644
--- a/crates/hk-core/src/manager.rs
+++ b/crates/hk-core/src/manager.rs
@@ -438,12 +438,15 @@ fn toggle_hook(
let saved = store.get_disabled_config(&ext.id)?.ok_or_else(|| {
HkError::NotFound(format!("No saved config for hook '{}'", ext.name))
})?;
- let entry: serde_json::Value = serde_json::from_str(&saved)?;
+ let mut entry: serde_json::Value = serde_json::from_str(&saved)?;
let config_path = config_paths.first().ok_or_else(|| {
HkError::NotFound(format!("No hook config path for '{}'", ext.name))
})?;
// An event name never contains `:`, unlike a matcher.
let event = ext.name.split(':').next().unwrap_or_default();
+ if a.hook_format() == adapter::HookFormat::ClaudeLike {
+ keep_own_handlers(&mut entry, ext, a.as_ref(), event);
+ }
deployer::restore_hook(config_path, event, &entry, a.hook_format())?;
store.set_disabled_config(&ext.id, None)?;
} else {
@@ -485,19 +488,53 @@ pub(crate) fn hooks_on_disk<'a>(
.read_hooks_from(config_path)
.into_iter()
.filter(|hook| {
- let name = format!(
- "{}:{}:{}",
- hook.event,
- hook.matcher.as_deref().unwrap_or("*"),
- hook.command
- );
- crate::scanner::stable_id_with_scope_for(&name, "hook", adapter.name(), &ext.scope)
- == ext.id
+ is_row_for(
+ ext,
+ adapter,
+ &hook.event,
+ hook.matcher.as_deref(),
+ &hook.command,
+ )
})
.map(move |hook| (config_path.clone(), hook))
})
}
+fn is_row_for(
+ ext: &Extension,
+ adapter: &dyn adapter::AgentAdapter,
+ event: &str,
+ matcher: Option<&str>,
+ command: &str,
+) -> bool {
+ let name = format!("{event}:{}:{command}", matcher.unwrap_or("*"));
+ crate::scanner::stable_id_with_scope_for(&name, "hook", adapter.name(), &ext.scope) == ext.id
+}
+
+/// Earlier versions saved a hook's whole group when disabling it. Trim such a
+/// snapshot to the row's own handler, since the others never left the file.
+fn keep_own_handlers(
+ group: &mut serde_json::Value,
+ ext: &Extension,
+ adapter: &dyn adapter::AgentAdapter,
+ event: &str,
+) {
+ let matcher = group
+ .get("matcher")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+ let Some(handlers) = group.get_mut("hooks").and_then(|v| v.as_array_mut()) else {
+ return;
+ };
+ let is_own = |handler: &serde_json::Value| {
+ adapter::hook_handler(handler)
+ .is_some_and(|(text, _)| is_row_for(ext, adapter, event, matcher.as_deref(), text))
+ };
+ if handlers.iter().any(is_own) {
+ handlers.retain(is_own);
+ }
+}
+
/// Reconstruct the config-file plugin key (e.g. "name@marketplace") from extension metadata.
/// Scanner sets description to "Plugin from {source}" or "Plugin for {agent}".
fn plugin_key_from_ext(ext: &Extension) -> String {
@@ -2907,6 +2944,7 @@ mod tests {
"version": 1,
"hooks": { "preToolUse": [
{ "command": "./guard.sh", "matcher": "MCP:create_issue", "timeout": 30 },
+ { "command": "./guard.sh", "matcher": "MCP:create_issue", "timeout": 5 },
{ "command": "./all.sh", "matcher": "*" }
] }
});
@@ -2998,6 +3036,16 @@ mod tests {
.collect();
commands.sort();
assert_eq!(commands, ["fmt.sh", "lint.sh"]);
+
+ // A snapshot from an earlier version holds the whole group.
+ toggle_extension_with_adapters(&store, &adapters, &fmt.id, false).unwrap();
+ let whole_group = r#"{"matcher":"Write","hooks":[
+ {"type":"command","command":"fmt.sh"},{"type":"command","command":"lint.sh"}]}"#;
+ store
+ .set_disabled_config(&fmt.id, Some(whole_group))
+ .unwrap();
+ toggle_extension_with_adapters(&store, &adapters, &fmt.id, true).unwrap();
+ assert_eq!(adapters[0].read_hooks().len(), 2);
}
// -----------------------------------------------------------------------