From ac125a6d2845adaadba36cff5e4e81612a51fcc0 Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:50:08 -0600 Subject: [PATCH] plugins: read plugins in the .claude-plugin layout as incode plugins A folder with .claude-plugin/plugin.json and no plugin.toml now installs and loads as an incode plugin, so its parts serve every agent incode drives (claude, codex, agy, the API route), not one CLI: - manifest: name/version/description from plugin.json - commands/, skills/ as before; agents/ now loaded for every plugin, as : (subagents::load); `model: inherit` means the parent's - hooks/hooks.json (or plugin.json `hooks`, a path inside the folder or the object) translated to incode's events; tool matchers kept, with mcp__plugin_

___ renamed to incode's mcp__

___; SessionStart and PreCompact matchers weighed against startup/manual; what incode cannot run (prompt hooks, unknown events, bad matchers) left out and listed by `incode plugin list` - .mcp.json (or plugin.json `mcpServers`), bare map or mcpServers, built by mcp_config::ServerEntry::to_spec with ${CLAUDE_PLUGIN_ROOT} hooks::HookCommand replaces the plain command string: an optional matcher (also accepted in admin.json and incode's own hooks.json as {"command", "matcher"}), the plugin's folder in CLAUDE_PLUGIN_ROOT and INCODE_PLUGIN_ROOT, and a posix flag that runs the command in the Bash tool's Git Bash on Windows instead of cmd. Tested: 9 new tests; six controls (matcher filter, Git Bash path, cmd root fill, matcher rename, path-inside check, inherit) each failed its test on the intended assertion and were restored byte-identical. Lib 2444 + bin 59 pass, clippy -D warnings and fmt clean (Windows). --- README.md | 14 +- src/admin/tests.rs | 18 +- src/agent/api.rs | 2 +- src/cli/agent_turn.rs | 10 +- src/cli/notify.rs | 2 +- src/cli/run_memory.rs | 2 +- src/desktop/mcp/tests.rs | 4 +- src/hooks/mod.rs | 333 +++++++++++++++++-- src/plugin_approvals.rs | 5 +- src/plugins.rs | 134 ++++++-- src/plugins/claude_layout.rs | 610 +++++++++++++++++++++++++++++++++++ src/subagents.rs | 75 ++++- src/task_run/tests.rs | 6 +- src/toolbox/hook_tests.rs | 4 +- src/toolbox/subagent.rs | 2 +- src/tools/shell_choice.rs | 13 + 16 files changed, 1156 insertions(+), 78 deletions(-) create mode 100644 src/plugins/claude_layout.rs diff --git a/README.md b/README.md index 82dd873..122928c 100644 --- a/README.md +++ b/README.md @@ -749,7 +749,19 @@ A **plugin** is a folder in `~/.incode/plugins//` or `hooks.json` (`{"pre_tool_use": [...], "post_tool_use": [...]}`, added to `admin.json`'s hooks) and `.mcp.json` (`{"mcpServers": {"db": {"command", "args", "env"}}}`, or `{"type": "http", "url", "headers"}`, started with the -session). `${INCODE_PLUGIN_ROOT}` in a hook or server is the plugin's folder. +session), and `agents/*.md` (sub-agents, as `:`). +`${INCODE_PLUGIN_ROOT}` in a hook or server is the plugin's folder. A hook may +be `{"command": "...", "matcher": "Edit|Write"}` to run only for the tools the +regular expression names (the whole name, as in `admin.json`). + +**Claude Code plugins install as they are.** A folder with +`.claude-plugin/plugin.json` and no `plugin.toml` is read in that layout: +the same `commands/`, `skills/` and `agents/`, its `hooks/hooks.json` +(events, `matcher`s and `command` hooks; the commands run in Git Bash on +Windows), its `.mcp.json` servers, and `${CLAUDE_PLUGIN_ROOT}`. Once installed +it is an incode plugin, used by every agent incode drives. `incode plugin +list` notes what it brings that incode does not run: `prompt` hooks, events +incode has no point for, and `plugin.json` keys it does not read. ```sh incode plugin list diff --git a/src/admin/tests.rs b/src/admin/tests.rs index b4b6ef2..3d371be 100644 --- a/src/admin/tests.rs +++ b/src/admin/tests.rs @@ -380,15 +380,15 @@ fn a_tool() -> crate::ext_tools::ToolEntry { /// fails to compile here until it is given a hook. fn a_hook_on_every_desktop_event() -> crate::hooks::HookConfig { crate::hooks::HookConfig { - pre_tool_use: vec!["a-guard-command".to_string()], - post_tool_use: vec!["a-logging-command".to_string()], - user_prompt_submit: vec!["a-prompt-check".to_string()], - pre_compact: vec!["a-compact-note".to_string()], - stop: vec!["a-stop-note".to_string()], - notification: vec!["a-notify-hook".to_string()], - session_start: vec!["a-start-note".to_string()], - session_end: vec!["a-end-note".to_string()], - subagent_stop: vec!["a-subagent-note".to_string()], + pre_tool_use: vec!["a-guard-command".into()], + post_tool_use: vec!["a-logging-command".into()], + user_prompt_submit: vec!["a-prompt-check".into()], + pre_compact: vec!["a-compact-note".into()], + stop: vec!["a-stop-note".into()], + notification: vec!["a-notify-hook".into()], + session_start: vec!["a-start-note".into()], + session_end: vec!["a-end-note".into()], + subagent_stop: vec!["a-subagent-note".into()], } } diff --git a/src/agent/api.rs b/src/agent/api.rs index ecfbb9b..f21b90e 100644 --- a/src/agent/api.rs +++ b/src/agent/api.rs @@ -1972,7 +1972,7 @@ mod tests { let echo_stdin = if cfg!(windows) { "more" } else { "cat" }; let mut agent = backend(dir.path()).with_operator_hooks(Some( crate::hooks::HookRunner::new(crate::hooks::HookConfig { - pre_compact: vec![echo_stdin.to_string()], + pre_compact: vec![echo_stdin.into()], ..crate::hooks::HookConfig::default() }), )); diff --git a/src/cli/agent_turn.rs b/src/cli/agent_turn.rs index 2afa480..dd7054c 100644 --- a/src/cli/agent_turn.rs +++ b/src/cli/agent_turn.rs @@ -1675,7 +1675,7 @@ mod tests { let mut s = with_memory(ws.path(), engine.path(), &[], &seen, Box::new(|_| {})); s.set_operator_hooks(Some(crate::hooks::HookRunner::new( crate::hooks::HookConfig { - user_prompt_submit: vec![operator_hook("checked", "no secrets", code)], + user_prompt_submit: vec![operator_hook("checked", "no secrets", code).into()], ..crate::hooks::HookConfig::default() }, ))); @@ -1736,7 +1736,7 @@ mod tests { let mut s = with_memory(ws.path(), engine.path(), &[], &seen, Box::new(|_| {})); s.set_operator_hooks(Some(crate::hooks::HookRunner::new( crate::hooks::HookConfig { - user_prompt_submit: vec![operator_hook("checked", "no secrets", code)], + user_prompt_submit: vec![operator_hook("checked", "no secrets", code).into()], ..crate::hooks::HookConfig::default() }, ))); @@ -1768,7 +1768,7 @@ mod tests { let mut s = with_memory(ws.path(), engine.path(), &[], &seen, Box::new(|_| {})); s.set_operator_hooks(Some(crate::hooks::HookRunner::new( crate::hooks::HookConfig { - stop: vec![operator_hook("turn noted", "", 0)], + stop: vec![operator_hook("turn noted", "", 0).into()], ..crate::hooks::HookConfig::default() }, ))); @@ -1800,8 +1800,8 @@ mod tests { let here = if cfg!(windows) { "cd" } else { "pwd" }; s.set_operator_hooks(Some(crate::hooks::HookRunner::new( crate::hooks::HookConfig { - session_start: vec![here.to_string()], - session_end: vec![operator_hook("bye", "", 2)], + session_start: vec![here.into()], + session_end: vec![operator_hook("bye", "", 2).into()], ..crate::hooks::HookConfig::default() }, ))); diff --git a/src/cli/notify.rs b/src/cli/notify.rs index 6929667..d315d1e 100644 --- a/src/cli/notify.rs +++ b/src/cli/notify.rs @@ -364,7 +364,7 @@ mod tests { let settings = Settings { mode: Mode::Off, hooks: Some(crate::hooks::HookRunner::new(crate::hooks::HookConfig { - notification: vec![command], + notification: vec![command.into()], ..crate::hooks::HookConfig::default() })), ..Settings::default() diff --git a/src/cli/run_memory.rs b/src/cli/run_memory.rs index 47037f8..6965578 100644 --- a/src/cli/run_memory.rs +++ b/src/cli/run_memory.rs @@ -358,7 +358,7 @@ mod tests { format!("echo '{out}'; exit {code}") }; crate::hooks::HookRunner::new(crate::hooks::HookConfig { - user_prompt_submit: vec![command], + user_prompt_submit: vec![command.into()], ..crate::hooks::HookConfig::default() }) } diff --git a/src/desktop/mcp/tests.rs b/src/desktop/mcp/tests.rs index 8fd3ed8..0227913 100644 --- a/src/desktop/mcp/tests.rs +++ b/src/desktop/mcp/tests.rs @@ -316,7 +316,7 @@ mod live { let mut s = Server::new(InputThread::start().expect("input thread")).with_hooks( crate::hooks::HookConfig { - pre_tool_use: vec![deny.to_string()], + pre_tool_use: vec![deny.into()], post_tool_use: Vec::new(), user_prompt_submit: Vec::new(), pre_compact: Vec::new(), @@ -359,7 +359,7 @@ mod live { }; let mut s = Server::new(InputThread::start().expect("input thread")).with_hooks( crate::hooks::HookConfig { - pre_tool_use: vec![allow.to_string()], + pre_tool_use: vec![allow.into()], post_tool_use: Vec::new(), user_prompt_submit: Vec::new(), pre_compact: Vec::new(), diff --git a/src/hooks/mod.rs b/src/hooks/mod.rs index 682efbd..d4bc452 100644 --- a/src/hooks/mod.rs +++ b/src/hooks/mod.rs @@ -32,6 +32,9 @@ //! - It runs in the workspace, and is killed with everything it started at //! [`HOOK_TIMEOUT`]; a command that could not run or ran past it allows //! the call, with a message saying so. +//! - A tool command with a `matcher` ([`HookCommand`]) runs only for the +//! tools it names. A plugin's commands have its folder in +//! `CLAUDE_PLUGIN_ROOT` and `INCODE_PLUGIN_ROOT`. //! //! # `HOOK_TOOL_INPUT` is the REAL input, not the redacted description //! @@ -110,6 +113,112 @@ pub(crate) fn run_piped( /// noticed rather than lived with. pub const HOOK_TIMEOUT: Duration = Duration::from_secs(10); +// --------------------------------------------------------------------------- +// HookCommand +// --------------------------------------------------------------------------- + +/// One hook command: a command line, as `admin.json` and an incode plugin's +/// `hooks.json` write it, or `{"command", "matcher"}`. +/// +/// `matcher` is read for `pre_tool_use` and `post_tool_use` only: the tool +/// names the command runs for, a regular expression matched against the WHOLE +/// name (`Bash`, `Edit|Write`, `mcp__db__.*`); none, `""` or `*` is every +/// tool. A matcher that is not a regular expression runs the command for no +/// tool, and says so. +/// +/// `plugin_root` and `posix` are never written: a plugin in the other +/// agent CLI's layout sets them as it is read (`plugins::claude_layout`). +#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +#[serde(from = "RawHookCommand", into = "RawHookCommand")] +pub struct HookCommand { + pub command: String, + pub matcher: Option, + /// The plugin's folder, set in the command's environment as + /// `CLAUDE_PLUGIN_ROOT` and `INCODE_PLUGIN_ROOT`. + pub plugin_root: Option, + /// Written for a POSIX shell: on Windows it runs in the `Bash` tool's + /// shell when that is Git Bash (`tools::shell_choice::posix`), and in + /// `cmd /C` like any other only when there is none. + pub posix: bool, +} + +/// How a [`HookCommand`] is written. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +enum RawHookCommand { + Plain(String), + Matched { + command: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + matcher: Option, + }, +} + +impl From for HookCommand { + fn from(raw: RawHookCommand) -> Self { + match raw { + RawHookCommand::Plain(command) => command.into(), + RawHookCommand::Matched { command, matcher } => Self { + command, + matcher, + ..Self::default() + }, + } + } +} + +impl From for RawHookCommand { + fn from(hook: HookCommand) -> Self { + match hook.matcher { + None => Self::Plain(hook.command), + matcher => Self::Matched { + command: hook.command, + matcher, + }, + } + } +} + +impl From for HookCommand { + fn from(command: String) -> Self { + Self { + command, + ..Self::default() + } + } +} + +impl From<&str> for HookCommand { + fn from(command: &str) -> Self { + command.to_string().into() + } +} + +impl PartialEq<&str> for HookCommand { + fn eq(&self, other: &&str) -> bool { + self.command == *other + } +} + +impl std::fmt::Display for HookCommand { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.command) + } +} + +impl HookCommand { + /// Whether this command runs for the tool `tool_name`, and why not when + /// its matcher cannot be read. + pub fn matches(&self, tool_name: &str) -> Result { + match self.matcher.as_deref().map(str::trim) { + None | Some("" | "*") => Ok(true), + Some(pattern) => regex::Regex::new(&format!("^(?:{pattern})$")) + .map(|re| re.is_match(tool_name)) + .map_err(|e| format!("its matcher `{pattern}` is not a regular expression: {e}")), + } + } +} + // --------------------------------------------------------------------------- // HookConfig // --------------------------------------------------------------------------- @@ -119,47 +228,62 @@ pub const HOOK_TIMEOUT: Duration = Duration::from_secs(10); pub struct HookConfig { /// Commands run BEFORE the tool. Exit code 2 refuses the call. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub pre_tool_use: Vec, + pub pre_tool_use: Vec, /// Commands run AFTER the tool, whatever it returned. /// /// These cannot refuse anything — the action has already happened, and a /// deny here would report a refusal for something that was done. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub post_tool_use: Vec, + pub post_tool_use: Vec, /// Commands run when a person's line is about to go to the agent. Exit /// code 2 refuses the line (the reason is shown, nothing is sent); stdout /// is added to that turn's context. The line itself is never changed. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub user_prompt_submit: Vec, + pub user_prompt_submit: Vec, /// Commands run before `/compact` compacts the conversation. They cannot /// stop it; stdout is shown with the result. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub pre_compact: Vec, + pub pre_compact: Vec, /// Commands run when a person's turn has ended (after any continuation /// the memory engine asked for). They cannot reopen it; stdout is shown /// with the turn's notices. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub stop: Vec, + pub stop: Vec, /// Commands run when incode would notify the person: a long turn /// finished, or the agent is waiting on them. Run in the background, /// beside `notify_command`; they cannot change anything. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub notification: Vec, + pub notification: Vec, /// Commands run when a session starts (REPL, `--acp`, `-t`). They cannot /// stop it; stdout is shown. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub session_start: Vec, + pub session_start: Vec, /// Commands run when a session ends. They cannot keep it open; stdout is /// shown where there is still somewhere to show it. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub session_end: Vec, + pub session_end: Vec, /// Commands run when a sub-agent (the `Agent` tool) has finished. They /// cannot keep it working; what they print is traced, not shown. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub subagent_stop: Vec, + pub subagent_stop: Vec, } impl HookConfig { + /// Every command, over every event, to be changed in place (a plugin's, + /// as it is read: `plugins::Plugin::hooks`). + pub fn commands_mut(&mut self) -> impl Iterator { + self.pre_tool_use + .iter_mut() + .chain(self.post_tool_use.iter_mut()) + .chain(self.user_prompt_submit.iter_mut()) + .chain(self.pre_compact.iter_mut()) + .chain(self.stop.iter_mut()) + .chain(self.notification.iter_mut()) + .chain(self.session_start.iter_mut()) + .chain(self.session_end.iter_mut()) + .chain(self.subagent_stop.iter_mut()) + } + /// Whether there is anything to run at all. /// /// Checked before a call so the ordinary case — no hooks configured — @@ -334,12 +458,25 @@ impl HookRunner { fn run_commands( &self, - commands: &[String], + commands: &[HookCommand], call: &HookCall<'_>, side: Side<'_>, ) -> HookRunResult { + let mut messages = Vec::new(); + // Only the commands whose matcher takes this tool; one whose matcher + // cannot be read runs for none, and says so. + let commands: Vec<&HookCommand> = commands + .iter() + .filter(|hook| match hook.matches(call.tool_name) { + Ok(runs) => runs, + Err(why) => { + messages.push(format!("Hook `{hook}` was not run: {why}")); + false + } + }) + .collect(); if commands.is_empty() { - return HookRunResult::allow(Vec::new()); + return HookRunResult::allow(messages); } let mut event = json!({ "hook_event_name": match side { Side::Pre => "PreToolUse", Side::Post { .. } => "PostToolUse" }, @@ -366,7 +503,6 @@ impl HookRunner { crate::text::head_bytes(&input, MAX_ENV_INPUT_BYTES).to_string(), ), ]; - let mut messages = Vec::new(); for command in commands { match run_shell_command(command, &env, call.cwd, &payload) { Ok((code, stdout, stderr)) => { @@ -565,7 +701,7 @@ pub struct SubagentStopped<'a> { /// is the reason) and the rest are not run; otherwise exit 2 is like any /// other. Each command's stdout is a message. fn run_event( - commands: &[String], + commands: &[HookCommand], name: &str, fields: Value, session: &str, @@ -637,35 +773,61 @@ fn parsed(tool_input: &str) -> Value { serde_json::from_str(tool_input).unwrap_or_else(|_| json!(tool_input)) } +/// The names a plugin's folder is given in its hook commands' environment. +const PLUGIN_ROOT_VARS: [&str; 2] = ["CLAUDE_PLUGIN_ROOT", "INCODE_PLUGIN_ROOT"]; + /// One operator command, run through the shell in `cwd` with `env` set and the /// event on its stdin: its exit code, stdout and stderr, each trimmed. fn run_shell_command( - command: &str, + hook: &HookCommand, env: &[(&str, String)], cwd: Option<&Path>, payload: &[u8], ) -> std::io::Result<(i32, String, String)> { - // Verbatim on Windows, as the Bash tool passes its command: `Command::arg` - // would escape a `"` the operator wrote as `\"`, which `cmd /C` does not - // read that way. + // A plugin's folder, with `/` on Windows too: Git Bash reads a `\` in an + // expanded path as written, but one in a command's own text as an escape. + let root = hook + .plugin_root + .as_ref() + .map(|root| root.to_string_lossy().replace('\\', "/")); + + // A command written for a POSIX shell runs in the `Bash` tool's shell + // when that is one. Otherwise, verbatim on Windows, as the Bash tool + // passes its command: `Command::arg` would escape a `"` the operator + // wrote as `\"`, which `cmd /C` does not read that way. cmd expands no + // `${…}`, so there the plugin's folder is written into the text. #[cfg(windows)] - let mut child = { - use std::os::windows::process::CommandExt; - let mut c = Command::new("cmd"); - c.arg("/C").raw_arg(command); - c + let mut child = match hook.posix.then(crate::tools::shell_choice::posix).flatten() { + Some(shell) => shell.command(&hook.command), + None => { + use std::os::windows::process::CommandExt; + let mut text = hook.command.clone(); + if let Some(root) = &root { + for var in PLUGIN_ROOT_VARS { + text = text.replace(&format!("${{{var}}}"), root); + } + } + let mut c = Command::new("cmd"); + c.arg("/C").raw_arg(text); + c + } }; #[cfg(not(windows))] let mut child = { let mut c = Command::new("sh"); - c.arg("-lc").arg(command); + c.arg("-lc").arg(&hook.command); c }; for (name, value) in env { child.env(name, value); } + if let Some(root) = &root { + for var in PLUGIN_ROOT_VARS { + child.env(var, root); + } + } if let Some(cwd) = cwd { child.current_dir(cwd); } @@ -693,7 +855,7 @@ mod tests { /// A hook command that saves its stdin next to it, prints `said`, and /// exits with `code` after writing `why` to stderr. - fn hook(dir: &Path, code: i32, why: &str) -> String { + fn hook(dir: &Path, code: i32, why: &str) -> HookCommand { #[cfg(windows)] { let script = dir.join(format!("hook{code}.cmd")); @@ -707,7 +869,7 @@ mod tests { .expect("hook"); // Quoted as an operator would: the command reaches `cmd /C` // verbatim. - format!("\"{}\"", script.display()) + format!("\"{}\"", script.display()).into() } #[cfg(not(windows))] { @@ -720,7 +882,7 @@ mod tests { ), ) .expect("hook"); - format!("sh '{}'", script.display()) + format!("sh '{}'", script.display()).into() } } @@ -764,6 +926,123 @@ mod tests { assert_eq!(event["session_id"], "sess-9"); } + /// **A TOOL HOOK WITH A MATCHER RUNS ONLY FOR THE TOOLS IT NAMES**, the + /// whole name matched: `Edit|Write` denies a `Write`, never runs for a + /// `Read` or a `WriteNotes`, and a matcher that is not a regular + /// expression runs for no tool and says so. + #[test] + fn a_tool_hook_with_a_matcher_runs_only_for_the_tools_it_names() { + let dir = tempfile::tempdir().expect("dir"); + let mut denying = hook(dir.path(), 2, "no edits"); + denying.matcher = Some("Edit|Write".to_string()); + let runner = HookRunner::new(HookConfig { + pre_tool_use: vec![denying], + ..HookConfig::default() + }); + let input = json!({"path": "a.txt"}); + let on = |tool_name| HookCall { + tool_name, + tool_input: &input, + session: "", + cwd: Some(dir.path()), + }; + for tool in ["Read", "WriteNotes"] { + let ran = runner.pre_tool(&on(tool)); + assert!(!ran.is_denied(), "{tool}: {ran:?}"); + assert!( + !dir.path().join("event.json").exists(), + "the hook ran for {tool}" + ); + } + let ran = runner.pre_tool(&on("Write")); + assert!(ran.is_denied(), "{ran:?}"); + assert_eq!(ran.messages(), ["no edits"]); + + let mut unreadable = hook(dir.path(), 2, "never"); + unreadable.matcher = Some("Edit(".to_string()); + let ran = HookRunner::new(HookConfig { + pre_tool_use: vec![unreadable], + ..HookConfig::default() + }) + .pre_tool(&on("Edit")); + assert!(!ran.is_denied(), "{ran:?}"); + assert!( + ran.messages()[0].contains("not a regular expression"), + "{ran:?}" + ); + } + + /// **A PLUGIN'S HOOK IS TOLD ITS FOLDER** as `CLAUDE_PLUGIN_ROOT`, with + /// `/` for every separator — in the environment where a shell expands + /// it, and in the text where `cmd` would not. + #[test] + fn a_plugin_hook_is_told_its_folder() { + let dir = tempfile::tempdir().expect("dir"); + let root = dir.path().join("my plugin"); + let command = if cfg!(windows) { + "echo ${CLAUDE_PLUGIN_ROOT}" + } else { + "echo \"$CLAUDE_PLUGIN_ROOT\"" + }; + let runner = HookRunner::new(HookConfig { + session_start: vec![HookCommand { + plugin_root: Some(root.clone()), + ..HookCommand::from(command) + }], + ..HookConfig::default() + }); + let ran = runner.session_start("startup", "", Some(dir.path())); + assert_eq!( + ran.messages(), + [root.to_string_lossy().replace('\\', "/")], + "{ran:?}" + ); + } + + /// **A HOOK WRITTEN FOR A POSIX SHELL RUNS IN ONE ON WINDOWS** — the + /// `Bash` tool's Git Bash — where `${CLAUDE_PLUGIN_ROOT}` is expanded by + /// the shell. Skipped where this machine has no POSIX shell to give it. + #[cfg(windows)] + #[test] + fn a_posix_hook_runs_in_the_posix_shell_on_windows() { + if crate::tools::shell_choice::posix().is_none() { + return; + } + let dir = tempfile::tempdir().expect("dir"); + let root = dir.path().join("plugin"); + let runner = HookRunner::new(HookConfig { + session_start: vec![HookCommand { + plugin_root: Some(root.clone()), + posix: true, + ..HookCommand::from( + "[ -n \"$BASH_VERSION\" ] && printf '%s' \"${CLAUDE_PLUGIN_ROOT}\"", + ) + }], + ..HookConfig::default() + }); + let ran = runner.session_start("startup", "", Some(dir.path())); + assert_eq!( + ran.messages(), + [root.to_string_lossy().replace('\\', "/")], + "{ran:?}" + ); + } + + /// **`admin.json` READS A HOOK AS A COMMAND LINE OR WITH A MATCHER**, and + /// writes each back the way it was written. + #[test] + fn a_hook_is_written_as_a_line_or_with_its_matcher() { + let text = r#"{"pre_tool_use":["check",{"command":"lint","matcher":"Edit|Write"}]}"#; + let config: HookConfig = serde_json::from_str(text).expect("parses"); + assert_eq!(config.pre_tool_use, ["check", "lint"]); + assert_eq!(config.pre_tool_use[0].matcher, None); + assert_eq!( + config.pre_tool_use[1].matcher.as_deref(), + Some("Edit|Write") + ); + assert_eq!(serde_json::to_string(&config).expect("writes"), text); + } + /// Any other exit allows, with what the hook printed; a post hook cannot /// deny, and is told the result. #[test] @@ -917,7 +1196,7 @@ mod tests { assert_eq!(event["reason"], "prompt_input_exit"); } - fn prompt_runner(commands: Vec) -> HookRunner { + fn prompt_runner(commands: Vec) -> HookRunner { HookRunner::new(HookConfig { user_prompt_submit: commands, ..HookConfig::default() diff --git a/src/plugin_approvals.rs b/src/plugin_approvals.rs index f071be2..834fc65 100644 --- a/src/plugin_approvals.rs +++ b/src/plugin_approvals.rs @@ -19,8 +19,9 @@ //! # Wired to //! //! - [`usable`] is the one gate: `plugins::session_hooks`, -//! `plugins::session_servers`, `plugins::session_skills` and -//! `custom_commands::Registry::load` take their plugins through it. +//! `plugins::session_servers`, `plugins::session_skills`, +//! `plugins::session_agents` and `custom_commands::Registry::load` take +//! their plugins through it. //! - `incode plugin approve ` (`plugins::cli`) calls [`approve`]; //! `incode plugin list` shows [`state`]. diff --git a/src/plugins.rs b/src/plugins.rs index ca380c8..76cd15a 100644 --- a/src/plugins.rs +++ b/src/plugins.rs @@ -26,9 +26,21 @@ //! "args", "env"} | {"type": "http", "url", "headers"}}}`, started beside //! the external tools' servers. //! +//! - `agents/*.md` — sub-agent definitions, listed as `:` +//! beside the operator's own ([`crate::subagents::load`]). +//! //! `${INCODE_PLUGIN_ROOT}` in a hook command or a server's command, arguments //! or environment is replaced with the plugin's folder. //! +//! # The other agent CLI's layout +//! +//! A folder with `.claude-plugin/plugin.json` and no `plugin.toml` is read +//! too, by [`claude_layout`]: the same `commands/`, `skills/` and `agents/`, +//! its `hooks/hooks.json` translated to these events, its `.mcp.json` +//! servers, and `${CLAUDE_PLUGIN_ROOT}`. Once installed it is an incode +//! plugin like any other — used by every agent incode drives, approved the +//! same way. +//! //! # Whose words these are //! //! A plugin is somebody else's bundle that the operator chose to install, so @@ -47,6 +59,8 @@ use std::path::{Path, PathBuf}; +pub mod claude_layout; + /// The folder plugins live in, under `~/.incode/` or a project's `.incode/`. pub const PLUGINS_DIR: &str = "plugins"; @@ -126,7 +140,8 @@ pub fn discover(workspace: &Path) -> Found { /// left out is a problem line saying how to approve it. /// /// Every consumer of a plugin's content goes through this: `session_hooks`, -/// `session_servers`, `session_skills` and `custom_commands::Registry::load` +/// `session_servers`, `session_skills`, `session_agents` (for +/// `subagents::load`) and `custom_commands::Registry::load` /// (whose warnings are where the left-out lines are shown, once). #[must_use] pub fn discover_usable(workspace: &Path) -> Found { @@ -197,16 +212,29 @@ pub fn discover_in(project: Option<&Path>, user: &Path) -> Found { found } -/// One plugin folder. +/// Whether `root` holds a plugin manifest of either layout. +fn has_manifest(root: &Path) -> bool { + root.join(MANIFEST).is_file() || root.join(claude_layout::MANIFEST).is_file() +} + +/// A manifest reader: [`parse_manifest`] or [`claude_layout::manifest`]. +type ManifestParser = fn(&str) -> Result; + +/// One plugin folder: its `plugin.toml`, else its `.claude-plugin/plugin.json`. fn load_one(root: &Path, scope: Scope) -> Result { - let path = root.join(MANIFEST); + let (path, parse): (PathBuf, ManifestParser) = if claude_layout::is_one(root) { + (root.join(claude_layout::MANIFEST), claude_layout::manifest) + } else { + (root.join(MANIFEST), parse_manifest) + }; let text = crate::text::read_authored(&path).map_err(|e| { format!( - "plugin at {} has no readable {MANIFEST}: {e}", - root.display() + "plugin at {} has no readable {MANIFEST} (or {}): {e}", + root.display(), + claude_layout::MANIFEST ) })?; - let manifest = parse_manifest(&text).map_err(|e| format!("{}: {e}", path.display()))?; + let manifest = parse(&text).map_err(|e| format!("{}: {e}", path.display()))?; Ok(Plugin { manifest, root: root.to_path_buf(), @@ -338,26 +366,62 @@ impl Plugin { .collect() } - /// Its hook commands, with [`ROOT_VAR`] filled in. + /// Where its sub-agent definitions are. + #[must_use] + pub fn agents_dir(&self) -> PathBuf { + self.root.join("agents") + } + + /// Its hook commands, with [`ROOT_VAR`] filled in and its folder in their + /// environment; in the other layout, translated by + /// [`claude_layout::hooks`] (what that leaves out is traced, and listed + /// by [`Self::notes`]). pub fn hooks(&self) -> Result { + if claude_layout::is_one(&self.root) { + let Some((config, left_out)) = claude_layout::hooks(&self.root)? else { + return Ok(crate::hooks::HookConfig::default()); + }; + for why in &left_out { + crate::trace!("plugins", "{}: left out {why}", self.manifest.name); + } + return Ok(config); + } let path = self.root.join("hooks.json"); let Ok(text) = crate::text::read_authored(&path) else { return Ok(crate::hooks::HookConfig::default()); }; let mut config: crate::hooks::HookConfig = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; - for command in config - .pre_tool_use - .iter_mut() - .chain(config.post_tool_use.iter_mut()) - { - *command = self.fill(command); + for hook in config.commands_mut() { + hook.command = self.fill(&hook.command); + hook.plugin_root = Some(self.root.clone()); } Ok(config) } + /// What this plugin brings that incode does not use, one line each, for + /// `incode plugin list` and an approval: only the other layout has any. + #[must_use] + pub fn notes(&self) -> Vec { + if !claude_layout::is_one(&self.root) { + return Vec::new(); + } + let mut notes = claude_layout::unread(&self.root); + match claude_layout::hooks(&self.root) { + Ok(Some((_, left_out))) => { + notes.extend(left_out.into_iter().map(|why| format!("left out {why}"))); + } + Ok(None) => {} + Err(why) => notes.push(why), + } + notes + } + /// Its MCP servers, named `_`. pub(crate) fn servers(&self) -> Result, String> { + if claude_layout::is_one(&self.root) { + return claude_layout::servers(&self.root, &self.manifest.name); + } let Some(path) = [".mcp.json", "mcp.json"] .iter() .map(|f| self.root.join(f)) @@ -434,6 +498,20 @@ pub fn session_skills() -> Vec { usable_here().iter().flat_map(Plugin::skills).collect() } +/// Every usable plugin's `agents/` folder for `workspace`, with the plugin's +/// name: read by `subagents::load`, which names each definition +/// `:`. Unapproved project plugins are left out here and said +/// by `custom_commands::Registry::load`, as for servers. +#[must_use] +pub fn session_agents(workspace: &Path) -> Vec<(String, PathBuf)> { + discover_usable(workspace) + .plugins + .iter() + .map(|p| (p.manifest.name.clone(), p.agents_dir())) + .filter(|(_, dir)| dir.is_dir()) + .collect() +} + /// Every plugin's hook commands, for the process's own directory. A plugin /// whose `hooks.json` does not parse contributes none, and is traced. #[must_use] @@ -600,8 +678,13 @@ pub fn listing(found: &Found) -> String { format!(" approval could not be checked: {why}\n") } }; + let notes: String = plugin + .notes() + .iter() + .map(|note| format!(" note: {note}\n")) + .collect(); out.push_str(&format!( - "{} {} ({}) — {}\n {}\n {}\n{approval}", + "{} {} ({}) — {}\n {}\n {}\n{notes}{approval}", m.name, if m.version.is_empty() { "-" @@ -633,7 +716,22 @@ fn contents(plugin: &Plugin) -> String { .map(|h| h.count()) .unwrap_or(0); let servers = plugin.servers().map(|s| s.len()).unwrap_or(0); - format!("{commands} command(s), {skills} skill(s), {hooks} hook(s), {servers} MCP server(s)") + let agents = std::fs::read_dir(plugin.agents_dir()) + .map(|entries| { + entries + .filter_map(Result::ok) + .filter(|e| { + e.path() + .extension() + .is_some_and(|x| x.eq_ignore_ascii_case("md")) + }) + .count() + }) + .unwrap_or(0); + format!( + "{commands} command(s), {skills} skill(s), {agents} agent(s), {hooks} hook(s), \ + {servers} MCP server(s)" + ) } /// Install a plugin from a local folder (copied) or a git URL (cloned with @@ -862,7 +960,7 @@ pub fn update_all(target: &Path) -> Result { .map(|entries| { entries .filter_map(Result::ok) - .filter(|e| e.path().join(MANIFEST).is_file()) + .filter(|e| has_manifest(&e.path())) .map(|e| e.file_name().to_string_lossy().into_owned()) .filter(|n| !n.starts_with('.')) .collect() @@ -932,7 +1030,7 @@ fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> { pub fn remove(name: &str, target: &Path) -> Result { check_name(name)?; let dest = target.join(name); - if !dest.join(MANIFEST).is_file() { + if !has_manifest(&dest) { return Err(format!( "no plugin `{name}` in {} (`incode plugin list` shows what is installed)", target.display() @@ -1143,7 +1241,7 @@ mod tests { let hooks = p.hooks().expect("hooks"); assert_eq!( hooks.pre_tool_use, - vec![format!("{}/check.sh", root.display())] + [format!("{}/check.sh", root.display()).as_str()] ); let servers = p.servers().expect("servers"); diff --git a/src/plugins/claude_layout.rs b/src/plugins/claude_layout.rs new file mode 100644 index 0000000..808e066 --- /dev/null +++ b/src/plugins/claude_layout.rs @@ -0,0 +1,610 @@ +//! Plugins in the layout the Claude Code CLI installs them in, read as incode +//! plugins: once installed (`incode plugin add`), their commands, skills, +//! sub-agents, hooks and MCP servers serve every agent incode drives, because +//! incode runs them — not the agent CLI. +//! +//! | In the plugin | Read as | +//! |---|---| +//! | `.claude-plugin/plugin.json`: `name`, `version`, `description` | its manifest ([`manifest`]) | +//! | `commands/`, `skills/`, `agents/` | the same folders as a `plugin.toml` plugin's | +//! | `hooks/hooks.json`, or `hooks` in `plugin.json` (a path or the object) | [`hooks`], translated | +//! | `.mcp.json`, or `mcpServers` in `plugin.json` (a path or the object) | [`servers`] | +//! | `${CLAUDE_PLUGIN_ROOT}` | the plugin's folder | +//! +//! A folder with both manifests is a `plugin.toml` plugin; this layout is +//! read only when there is no `plugin.toml` ([`is_one`]). +//! +//! # Hooks +//! +//! `{"hooks": {"PreToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": +//! "command", "command": "…"}]}]}}` — each event becomes the +//! [`crate::hooks::HookConfig`] field of the same name, each command a +//! [`crate::hooks::HookCommand`] marked `posix` (it was written for a POSIX +//! shell) with the plugin's folder in its environment. The stdin event they +//! are handed is already the shape they expect (`hooks` module doc). +//! +//! - `PreToolUse` / `PostToolUse` keep their `matcher`; incode's tools carry +//! the same names (`Bash`, `Read`, `Edit`, `mcp____`), and a +//! plugin's own servers' tools, `mcp__plugin____…` there, +//! are `mcp_____…` here, so the matcher is rewritten. +//! - `SessionStart` and `PreCompact` matchers are weighed as the hooks are +//! read, against what incode starts and compacts with (`startup`, +//! `manual`): a hook for `resume` alone is never run. +//! - A `Notification` hook with a matcher names notification kinds incode +//! does not have, so only the ones without are kept. +//! - Left out, and said: an event incode has no point for, a hook whose +//! `type` is not `command`, and a matcher that is not a regular expression. +//! - `timeout` is not read: every hook is bounded at +//! [`crate::hooks::HOOK_TIMEOUT`]. +//! +//! # Wired to +//! +//! Every reader is in [`super`]: `load_one` takes [`manifest`], +//! `Plugin::hooks` takes [`hooks`], `Plugin::servers` takes [`servers`], and +//! `plugins::session_agents` reads `agents/` for `subagents::load`. Servers +//! are built by the same `mcp_config::ServerEntry::to_spec` a `.mcp.json` +//! server is, so `${VAR}` and `${VAR:-default}` are expanded the same way. +//! The sibling layout, `plugin.toml`, is read in `super` itself. + +use std::path::{Component, Path, PathBuf}; + +use serde_json::Value; + +use crate::hooks::{HookCommand, HookConfig}; + +/// The manifest, under the plugin's folder. +pub const MANIFEST: &str = ".claude-plugin/plugin.json"; + +/// What the plugin's folder is called in its files. +pub const ROOT_VAR: &str = "CLAUDE_PLUGIN_ROOT"; + +/// Where its hooks are when `plugin.json` does not say. +const HOOKS_FILE: &str = "hooks/hooks.json"; + +/// Where its servers are when `plugin.json` does not say. +const SERVERS_FILE: &str = ".mcp.json"; + +/// The keys of `plugin.json` that name more than incode reads: extra +/// command or agent paths, and parts incode has no use for. +const UNREAD_KEYS: [&str; 4] = ["commands", "agents", "outputStyles", "lspServers"]; + +/// Whether `root` is a plugin in this layout and not a `plugin.toml` one. +#[must_use] +pub fn is_one(root: &Path) -> bool { + !root.join(super::MANIFEST).is_file() && root.join(MANIFEST).is_file() +} + +/// `plugin.json`'s name, version and description. Everything else it says is +/// read where it is used. +/// +/// # Errors +/// +/// It is not JSON, or names no usable plugin name. +pub fn manifest(text: &str) -> Result { + let value: Value = serde_json::from_str(text).map_err(|e| e.to_string())?; + let field = |key: &str| { + value + .get(key) + .and_then(Value::as_str) + .unwrap_or_default() + .trim() + .to_string() + }; + let manifest = super::Manifest { + name: field("name"), + version: field("version"), + description: field("description"), + }; + if manifest.name.is_empty() { + return Err("`name` is missing".to_string()); + } + super::check_name(&manifest.name)?; + Ok(manifest) +} + +/// The plugin's `plugin.json`, parsed. +fn plugin_json(root: &Path) -> Result { + let path = root.join(MANIFEST); + let text = crate::text::read_authored(&path).map_err(|e| format!("{}: {e}", path.display()))?; + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) +} + +/// What `plugin.json` says that incode does not read, one line each, for +/// `incode plugin list` — so a plugin that relies on them is not mistaken +/// for one that works whole. +#[must_use] +pub fn unread(root: &Path) -> Vec { + let Ok(json) = plugin_json(root) else { + return Vec::new(); + }; + UNREAD_KEYS + .iter() + .filter(|key| json.get(**key).is_some()) + .map(|key| match *key { + "commands" | "agents" => { + format!("`{key}` in plugin.json is not read; only its {key}/ folder is") + } + other => format!("`{other}` in plugin.json is not used by incode"), + }) + .collect() +} + +/// A part of the plugin `plugin.json` names under `key` — a path inside the +/// folder, or the object itself — else the file at `default`: the JSON, and +/// where it came from. `None` when there is neither. +fn part(root: &Path, key: &str, default: &str) -> Result, String> { + let named = plugin_json(root)?.get(key).cloned(); + let path = match named { + Some(Value::String(rel)) => inside(root, &rel)?, + Some(Value::Null) | None => root.join(default), + Some(object @ Value::Object(_)) => return Ok(Some((object, root.join(MANIFEST)))), + Some(other) => { + return Err(format!( + "{}: `{key}` is {other}, not a path or an object", + root.join(MANIFEST).display() + )) + } + }; + if !path.is_file() { + return Ok(None); + } + let text = crate::text::read_authored(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; + Ok(Some((value, path))) +} + +/// `rel` under `root`, refused when it would leave it: a plugin's files are +/// read from its own folder only. +fn inside(root: &Path, rel: &str) -> Result { + let rel = Path::new(rel); + if rel + .components() + .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir)) + { + return Err(format!( + "{}: `{}` is not a path inside the plugin", + root.join(MANIFEST).display(), + rel.display() + )); + } + Ok(root.join(rel)) +} + +/// The plugin's hooks, translated, and a line for each one left out. `None` +/// when it has none. +/// +/// # Errors +/// +/// Its hooks file or `plugin.json` cannot be read. +pub fn hooks(root: &Path) -> Result)>, String> { + let Some((value, from)) = part(root, "hooks", HOOKS_FILE)? else { + return Ok(None); + }; + let (mut config, left_out) = translate_hooks(&value); + for hook in config.commands_mut() { + hook.plugin_root = Some(root.to_path_buf()); + hook.posix = true; + } + let left_out = left_out + .into_iter() + .map(|why| format!("{}: {why}", from.display())) + .collect(); + Ok(Some((config, left_out))) +} + +/// `{"hooks": {Event: [{matcher, hooks: [{type, command}]}]}}` as incode's +/// events, and why each hook left out was. The object may also be the bare +/// event map. +#[must_use] +pub fn translate_hooks(value: &Value) -> (HookConfig, Vec) { + let mut config = HookConfig::default(); + let mut left_out = Vec::new(); + let events = value + .get("hooks") + .and_then(Value::as_object) + .or_else(|| value.as_object()); + let Some(events) = events else { + return (config, vec!["no `hooks` object".to_string()]); + }; + for (event, groups) in events { + if event == "description" { + continue; + } + let Some(field) = field_for(&mut config, event) else { + left_out.push(format!("`{event}` hooks: incode has no such event")); + continue; + }; + for group in groups.as_array().into_iter().flatten() { + let matcher = group + .get("matcher") + .and_then(Value::as_str) + .map(str::trim) + .filter(|m| !m.is_empty() && *m != "*") + .map(|m| m.replace("mcp__plugin_", "mcp__")); + if let Err(why) = kept(event, matcher.as_deref()) { + left_out.push(why); + continue; + } + for hook in group + .get("hooks") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let kind = hook + .get("type") + .and_then(Value::as_str) + .unwrap_or("command"); + let command = hook + .get("command") + .and_then(Value::as_str) + .map(str::trim) + .filter(|c| !c.is_empty()); + match (kind, command) { + ("command", Some(command)) => field.push(HookCommand { + command: command.to_string(), + matcher: tool_event(event).then(|| matcher.clone()).flatten(), + ..HookCommand::default() + }), + ("command", None) => { + left_out.push(format!("a `{event}` hook with no `command`")); + } + (other, _) => left_out.push(format!( + "a `{event}` hook of type `{other}`: incode runs only `command` hooks" + )), + } + } + } + } + (config, left_out) +} + +/// Whether a group with `matcher` under `event` is kept, and why not. +fn kept(event: &str, matcher: Option<&str>) -> Result<(), String> { + let Some(matcher) = matcher else { + return Ok(()); + }; + let probe = HookCommand { + matcher: Some(matcher.to_string()), + ..HookCommand::default() + }; + // What incode starts and compacts with: `cli::agent_turn` and `task_run` + // pass `startup`, and `/compact` is the only compaction. + let subject = match event { + "PreToolUse" | "PostToolUse" => { + return probe + .matches("") + .map(|_| ()) + .map_err(|why| format!("a `{event}` hook was left out: {why}")) + } + "SessionStart" => "startup", + "PreCompact" => "manual", + "Notification" => { + return Err(format!( + "a `Notification` hook for `{matcher}`: incode's notifications are not those \ + kinds" + )) + } + // The other events have no matcher to weigh. + _ => return Ok(()), + }; + match probe.matches(subject) { + Ok(true) => Ok(()), + Ok(false) => Err(format!( + "a `{event}` hook for `{matcher}`: incode's {event} is always `{subject}`" + )), + Err(why) => Err(format!("a `{event}` hook was left out: {why}")), + } +} + +/// Whether `event` is about one tool call, so its matcher is kept. +fn tool_event(event: &str) -> bool { + matches!(event, "PreToolUse" | "PostToolUse") +} + +/// The field of `config` that `event` fills, when incode has the event. +fn field_for<'a>(config: &'a mut HookConfig, event: &str) -> Option<&'a mut Vec> { + Some(match event { + "PreToolUse" => &mut config.pre_tool_use, + "PostToolUse" => &mut config.post_tool_use, + "UserPromptSubmit" => &mut config.user_prompt_submit, + "PreCompact" => &mut config.pre_compact, + "Stop" => &mut config.stop, + "Notification" => &mut config.notification, + "SessionStart" => &mut config.session_start, + "SessionEnd" => &mut config.session_end, + "SubagentStop" => &mut config.subagent_stop, + _ => return None, + }) +} + +/// The plugin's MCP servers, named `_`, with +/// `${CLAUDE_PLUGIN_ROOT}` as its folder and every other `${VAR}` from the +/// environment. The file may hold `{"mcpServers": {…}}` or the bare map. +/// +/// # Errors +/// +/// A file cannot be read, a server is not a server, or names a variable +/// that is unset. +pub(crate) fn servers( + root: &Path, + plugin: &str, +) -> Result, String> { + let Some((value, from)) = part(root, "mcpServers", SERVERS_FILE)? else { + return Ok(Vec::new()); + }; + let map = match value.get("mcpServers") { + Some(Value::Object(map)) => map.clone(), + _ => match value { + Value::Object(map) => map, + _ => return Err(format!("{}: not an object of servers", from.display())), + }, + }; + let folder = root.to_string_lossy().into_owned(); + let lookup = |name: &str| { + if name == ROOT_VAR || name == "INCODE_PLUGIN_ROOT" { + Some(folder.clone()) + } else { + std::env::var(name).ok() + } + }; + let mut specs = Vec::new(); + for (name, def) in map { + let entry: crate::mcp_config::ServerEntry = serde_json::from_value(def) + .map_err(|e| format!("{}: server `{name}`: {e}", from.display()))?; + let mut spec = entry + .to_spec(&format!("{plugin}_{name}"), &lookup) + .map_err(|e| format!("{}: server `{name}`: {e}", from.display()))?; + if let crate::toolbox::Transport::Stdio { env, .. } = &mut spec.transport { + if !env.iter().any(|(k, _)| k == ROOT_VAR) { + env.push((ROOT_VAR.to_string(), folder.clone())); + } + } + specs.push(spec); + } + Ok(specs) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plugins::{add, Scope}; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); + std::fs::write(path, text).expect("write"); + } + + /// A plugin in this layout with one of each part. + fn sample(dir: &Path) -> PathBuf { + let root = dir.join("source"); + write( + &root.join(MANIFEST), + r#"{"name": "review-kit", "version": "1.2.0", "description": "Reviews", + "author": {"name": "someone"}, "outputStyles": "./styles"}"#, + ); + write(&root.join("commands/check.md"), "Check $ARGUMENTS\n"); + write( + &root.join("skills/triage/SKILL.md"), + "---\nname: triage\ndescription: Sort the issues\n---\nbody\n", + ); + write( + &root.join("agents/critic.md"), + "---\nname: critic\ndescription: Finds faults\nmodel: inherit\n---\nFind them.\n", + ); + write( + &root.join(HOOKS_FILE), + r#"{"description": "guards", "hooks": { + "PreToolUse": [{"matcher": "Edit|Write", "hooks": [ + {"type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/guard.sh", "timeout": 30}]}], + "SessionStart": [{"matcher": "resume", "hooks": [ + {"type": "command", "command": "on-resume"}]}]}}"#, + ); + write( + &root.join(SERVERS_FILE), + r#"{"db": {"command": "${CLAUDE_PLUGIN_ROOT}/bin/db", "args": ["--root", "${CLAUDE_PLUGIN_ROOT}"]}, + "docs": {"type": "http", "url": "https://docs.example/mcp", + "headers": {"X-Key": "${INCODE_TEST_UNSET_VAR:-none}"}}}"#, + ); + root + } + + /// **A PLUGIN IN THE OTHER CLI'S LAYOUT INSTALLS AS AN INCODE PLUGIN**: + /// `incode plugin add` takes its folder, names it from `plugin.json`, and + /// every part reaches the loader incode already has — commands, skills, + /// agents, hooks (matcher kept, run in a POSIX shell, told the folder) + /// and servers (`${CLAUDE_PLUGIN_ROOT}` filled, `${VAR:-default}` + /// expanded). + #[test] + fn a_plugin_in_the_other_layout_installs_with_every_part() { + let dir = tempfile::tempdir().expect("dir"); + let source = sample(dir.path()); + let target = dir.path().join("plugins"); + let plugin = add(&source.to_string_lossy(), &target).expect("installs"); + assert_eq!(plugin.manifest.name, "review-kit"); + assert_eq!(plugin.manifest.version, "1.2.0"); + assert_eq!(plugin.scope, Scope::User); + let root = target.join("review-kit"); + assert!(is_one(&root)); + + let found = crate::plugins::discover_in(None, &target); + assert!(found.problems.is_empty(), "{:?}", found.problems); + assert_eq!(found.plugins.len(), 1); + let listing = crate::plugins::listing(&found); + assert!( + listing.contains("1 command(s), 1 skill(s), 1 agent(s), 1 hook(s), 2 MCP server(s)"), + "{listing}" + ); + assert!( + listing.contains("`outputStyles` in plugin.json"), + "{listing}" + ); + assert!( + listing.contains("`SessionStart` hook for `resume`"), + "{listing}" + ); + + let skills = plugin.skills(); + assert_eq!(skills[0].name, "review-kit:triage"); + + let hooks = plugin.hooks().expect("hooks"); + assert_eq!(hooks.pre_tool_use, ["${CLAUDE_PLUGIN_ROOT}/guard.sh"]); + let guard = &hooks.pre_tool_use[0]; + assert_eq!(guard.matcher.as_deref(), Some("Edit|Write")); + assert!(guard.posix); + assert_eq!(guard.plugin_root.as_deref(), Some(root.as_path())); + assert!(hooks.session_start.is_empty(), "a `resume` hook was kept"); + + let servers = plugin.servers().expect("servers"); + let names: Vec<&str> = servers.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["review-kit_db", "review-kit_docs"]); + let folder = root.to_string_lossy().into_owned(); + match &servers[0].transport { + crate::toolbox::Transport::Stdio { command, args, env } => { + assert_eq!(command, &PathBuf::from(format!("{folder}/bin/db"))); + assert_eq!(args, &["--root".to_string(), folder.clone()]); + assert!( + env.contains(&(ROOT_VAR.to_string(), folder.clone())), + "{env:?}" + ); + } + other => panic!("expected stdio, got {other:?}"), + } + match &servers[1].transport { + crate::toolbox::Transport::Http { headers, .. } => { + assert_eq!(headers, &[("X-Key".to_string(), "none".to_string())]); + } + other => panic!("expected http, got {other:?}"), + } + + assert_eq!( + crate::plugins::remove("review-kit", &target).expect("removes"), + root + ); + } + + /// **EACH EVENT BECOMES INCODE'S, AND WHAT INCODE CANNOT RUN IS SAID**: + /// a plugin's own server tools are renamed in the matcher; a start hook + /// for `startup` is kept and one for `clear` is not; a compaction hook + /// for `auto` is not; a notification hook with a matcher, a `prompt` + /// hook, an unknown event and a broken matcher are each left out. + #[test] + fn hooks_are_translated_and_what_is_left_out_is_said() { + let value: Value = serde_json::from_str( + r#"{"hooks": { + "PostToolUse": [{"matcher": "mcp__plugin_kit_db__.*", "hooks": [{"type": "command", "command": "log"}]}, + {"matcher": "*", "hooks": [{"type": "command", "command": "every"}]}, + {"matcher": "Edit(", "hooks": [{"type": "command", "command": "broken"}]}], + "SessionStart": [{"matcher": "startup|resume", "hooks": [{"type": "command", "command": "hello"}]}, + {"matcher": "clear", "hooks": [{"type": "command", "command": "cleared"}]}], + "PreCompact": [{"matcher": "auto", "hooks": [{"type": "command", "command": "auto-only"}]}], + "Notification": [{"matcher": "idle_prompt", "hooks": [{"type": "command", "command": "ping"}]}, + {"hooks": [{"command": "always"}]}], + "Stop": [{"hooks": [{"type": "prompt", "prompt": "Is it done?"}]}], + "UserPromptSubmit": [{"hooks": [{"type": "command", "command": "note"}]}], + "PermissionRequest": [{"hooks": [{"type": "command", "command": "perm"}]}] + }}"#, + ) + .expect("json"); + let (config, left_out) = translate_hooks(&value); + + assert_eq!(config.post_tool_use, ["log", "every"]); + assert_eq!( + config.post_tool_use[0].matcher.as_deref(), + Some("mcp__kit_db__.*") + ); + assert_eq!( + config.post_tool_use[0].matches("mcp__kit_db__query"), + Ok(true) + ); + assert_eq!(config.post_tool_use[1].matcher, None); + assert_eq!(config.session_start, ["hello"]); + assert_eq!(config.session_start[0].matcher, None); + assert!(config.pre_compact.is_empty()); + assert_eq!(config.notification, ["always"]); + assert!(config.stop.is_empty()); + assert_eq!(config.user_prompt_submit, ["note"]); + assert_eq!(config.count(), 5); + + let said = left_out.join("\n"); + for expected in [ + "not a regular expression", + "`SessionStart` hook for `clear`", + "`PreCompact` hook for `auto`", + "`Notification` hook for `idle_prompt`", + "of type `prompt`", + "`PermissionRequest` hooks", + ] { + assert!(said.contains(expected), "{expected} not said in:\n{said}"); + } + assert_eq!(left_out.len(), 6, "{said}"); + } + + /// **`plugin.json` MAY NAME ITS HOOKS AND SERVERS** — a path inside the + /// folder, or the object itself — and a path that leaves the folder is + /// refused rather than read. + #[test] + fn plugin_json_names_parts_inside_its_folder_only() { + let dir = tempfile::tempdir().expect("dir"); + let root = dir.path().join("kit"); + write( + &root.join(MANIFEST), + r#"{"name": "kit", "hooks": "./config/guards.json", + "mcpServers": {"db": {"command": "db"}}}"#, + ); + write( + &root.join("config/guards.json"), + r#"{"hooks": {"PreToolUse": [{"hooks": [{"type": "command", "command": "guard"}]}]}}"#, + ); + let (config, _) = hooks(&root).expect("reads").expect("has hooks"); + assert_eq!(config.pre_tool_use, ["guard"]); + let servers = servers(&root, "kit").expect("servers"); + assert_eq!(servers[0].name, "kit_db"); + + write( + dir.path().join("outside.json").as_path(), + r#"{"hooks": {}}"#, + ); + write( + &root.join(MANIFEST), + r#"{"name": "kit", "hooks": "../outside.json"}"#, + ); + let refused = hooks(&root).expect_err("a path outside the plugin"); + assert!( + refused.contains("not a path inside the plugin"), + "{refused}" + ); + } + + /// A folder with both manifests is a `plugin.toml` plugin, and a + /// `plugin.json` without a usable name is refused like a bad manifest. + #[test] + fn plugin_toml_wins_and_a_nameless_plugin_json_is_refused() { + let dir = tempfile::tempdir().expect("dir"); + let both = dir.path().join("both"); + write(&both.join(MANIFEST), r#"{"name": "json-name"}"#); + write( + &both.join(crate::plugins::MANIFEST), + "name = \"toml-name\"\n", + ); + assert!(!is_one(&both)); + + let nameless = dir.path().join("nameless"); + write(&nameless.join(MANIFEST), r#"{"version": "1.0.0"}"#); + let found = crate::plugins::discover_in(None, dir.path()); + let names: Vec<&str> = found + .plugins + .iter() + .map(|p| p.manifest.name.as_str()) + .collect(); + assert_eq!(names, ["toml-name"]); + assert!( + found + .problems + .iter() + .any(|p| p.contains("`name` is missing")), + "{:?}", + found.problems + ); + } +} diff --git a/src/subagents.rs b/src/subagents.rs index 7aead9d..7e7eda8 100644 --- a/src/subagents.rs +++ b/src/subagents.rs @@ -3,7 +3,9 @@ //! # Where they come from //! //! - `.incode/agents/*.md` in the workspace — the project's own; -//! - `~/.incode/agents/*.md` — the operator's, for every project. +//! - `~/.incode/agents/*.md` — the operator's, for every project; +//! - a usable plugin's `agents/*.md` (`plugins::session_agents`), named +//! `:`. //! //! A project's definition wins over the operator's of the same name. //! @@ -22,7 +24,8 @@ //! //! `name`, `description` and a non-empty body are required. `role` is one of //! [`crate::roles::KNOWN_ROLES`] and routes the model the way the `Agent` -//! tool's own `role` does; `model` names one outright. `tools` is an +//! tool's own `role` does; `model` names one outright (`inherit` is the +//! same as none: the parent's). `tools` is an //! allow-list of toolbox tool names, written `[A, B]`, `A, B` or as a list of //! `- A` lines: the sub-agent is offered only those, and a call to any other //! is refused by the toolbox's own gate. @@ -65,6 +68,8 @@ pub enum Scope { Harness, /// The operator's `~/.incode/agents`. User, + /// A plugin's `agents/`. + Plugin, } impl Scope { @@ -73,6 +78,7 @@ impl Scope { Self::Project => "project", Self::Harness => "harness", Self::User => "user", + Self::Plugin => "plugin", } } } @@ -168,7 +174,8 @@ impl Loaded { /// Every sub-agent defined for `workspace`: the project's, then the run's /// harness's, then the operator's — each only where an earlier one does not -/// already define the name. +/// already define the name — then each usable plugin's, as +/// `:`. #[must_use] pub fn load(workspace: &Path) -> Loaded { let project = workspace.join(PROJECT_DIR); @@ -179,7 +186,27 @@ pub fn load(workspace: &Path) -> Loaded { dirs.push((h.as_path(), Scope::Harness)); } dirs.push((user.as_path(), Scope::User)); - load_dirs(&dirs) + let mut loaded = load_dirs(&dirs); + add_plugin_agents(&mut loaded, &crate::plugins::session_agents(workspace)); + loaded +} + +/// The definitions in each plugin's `agents/` folder, each named +/// `:` so none can stand in for the operator's own. +fn add_plugin_agents(loaded: &mut Loaded, plugins: &[(String, PathBuf)]) { + for (plugin, dir) in plugins { + let mut problems = Vec::new(); + for mut found in read_dir(dir, Scope::Plugin, &mut problems) { + found.name = format!("{plugin}:{}", found.name); + if loaded.find(&found.name).is_none() { + loaded.agents.push(found); + } + } + for problem in &problems { + crate::trace!("agents", "left out: {problem}"); + } + loaded.problems.extend(problems); + } } /// [`load`], from a project and an operator directory. @@ -442,7 +469,7 @@ fn parse(text: &str, path: &Path, scope: Scope) -> Result { }; let model = match get("model") { None => None, - Some(Field::One(m)) if m.is_empty() => None, + Some(Field::One(m)) if m.is_empty() || m == "inherit" => None, Some(Field::One(m)) => Some(m), Some(Field::Many(_)) => return Err("`model` takes one value".to_string()), }; @@ -576,6 +603,44 @@ mod tests { problems.\nrole: review\nmodel: opus\ntools: [Read, Grep, \"Glob\"]\n---\nYou review \ changes.\n"; + /// **A plugin's agents arrive named for the plugin**, beside the + /// operator's own of the same bare name, and `model: inherit` (the other + /// layout's word for the parent's model) names none. + #[test] + fn a_plugins_agents_are_named_for_it_and_inherit_the_model() { + let dir = tempfile::tempdir().expect("dir"); + let user = dir.path().join("u"); + write(&user, "reviewer.md", REVIEWER); + let agents = dir.path().join("plugin").join("agents"); + write( + &agents, + "reviewer.md", + "---\nname: reviewer\ndescription: The plugin's reviewer.\nmodel: inherit\n\ + tools: Read, Grep\ncolor: blue\n---\nReview it.\n", + ); + write(&agents, "broken.md", "no front matter\n"); + + let mut loaded = load_from(&dir.path().join("p"), &user); + add_plugin_agents(&mut loaded, &[("web".to_string(), agents.clone())]); + + let own = loaded.find("reviewer").expect("the operator's own"); + assert_eq!(own.scope, Scope::User); + assert_eq!(own.model.as_deref(), Some("opus")); + let theirs = loaded.find("web:reviewer").expect("the plugin's"); + assert_eq!(theirs.scope, Scope::Plugin); + assert_eq!(theirs.model, None, "`inherit` is the parent's model"); + assert_eq!( + theirs.tools.as_deref(), + Some(&["Read".to_string(), "Grep".to_string()][..]) + ); + assert_eq!(theirs.description, "The plugin's reviewer."); + assert!( + loaded.problems.iter().any(|p| p.contains("broken.md")), + "{:?}", + loaded.problems + ); + } + /// **The shipped reviewers load, review, and can only look.** Seeded /// into an empty folder, both parse with the real loader, carry the /// `review` role, are offered only tools that observe, and are told to diff --git a/src/task_run/tests.rs b/src/task_run/tests.rs index c45eabc..61fea7e 100644 --- a/src/task_run/tests.rs +++ b/src/task_run/tests.rs @@ -23,9 +23,9 @@ fn a_refused_instruction_still_runs_the_session_end_hook() { ) }; let hooks = crate::hooks::HookRunner::new(crate::hooks::HookConfig { - session_start: vec![mark[0].to_string()], - user_prompt_submit: vec![refuse.to_string()], - session_end: vec![mark[1].to_string()], + session_start: vec![mark[0].to_string().into()], + user_prompt_submit: vec![refuse.to_string().into()], + session_end: vec![mark[1].to_string().into()], ..crate::hooks::HookConfig::default() }); let ran = run_task_hooked( diff --git a/src/toolbox/hook_tests.rs b/src/toolbox/hook_tests.rs index dc77f50..cb4e9e1 100644 --- a/src/toolbox/hook_tests.rs +++ b/src/toolbox/hook_tests.rs @@ -40,8 +40,8 @@ fn logging_hook(dir: &Path) -> (String, PathBuf) { fn hooked(ws: &Path, pre: String, post: Vec) -> Toolbox { Toolbox::new(ws, true).with_operator_hooks(Some(crate::hooks::HookRunner::new( crate::hooks::HookConfig { - pre_tool_use: vec![pre], - post_tool_use: post, + pre_tool_use: vec![pre.into()], + post_tool_use: post.into_iter().map(Into::into).collect(), user_prompt_submit: Vec::new(), pre_compact: Vec::new(), stop: Vec::new(), diff --git a/src/toolbox/subagent.rs b/src/toolbox/subagent.rs index b934cf2..ea3c4d5 100644 --- a/src/toolbox/subagent.rs +++ b/src/toolbox/subagent.rs @@ -613,7 +613,7 @@ mod tests { }; let mut parent = Toolbox::new(ws.path(), true).with_operator_hooks(Some( crate::hooks::HookRunner::new(crate::hooks::HookConfig { - subagent_stop: vec![save_event.to_string()], + subagent_stop: vec![save_event.to_string().into()], ..crate::hooks::HookConfig::default() }), )); diff --git a/src/tools/shell_choice.rs b/src/tools/shell_choice.rs index acb9cfa..50c7373 100644 --- a/src/tools/shell_choice.rs +++ b/src/tools/shell_choice.rs @@ -314,6 +314,19 @@ pub(crate) fn for_sandbox(sandbox: &crate::sandbox::Sandbox) -> Result Option { + chosen() + .as_ref() + .ok() + .filter(|shell| shell.flavor == Flavor::Posix) + .cloned() +} + /// The sentence the `Bash` tool's description carries about its shell, for a /// session whose commands run under `sandbox` — so the model writes the syntax /// that shell reads.