From 3d674a54302356c19b82b30e4784c81dbb05e83a Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:58:06 -0600 Subject: [PATCH 1/2] hooks: pre_compact and stop, told and never asked (refs #26) #26 item 5, second slice. Two more events for the operator's hooks (admin.json `hooks`, and approved plugins): - pre_compact: run before /compact compacts the conversation. The event carries trigger (`manual`) and custom_instructions. What the commands print is shown with the compaction's result. - stop: run once a person's turn has ended, after any continuation the memory engine asked for. The event carries last_assistant_message. What the commands print joins the turn's notices. Neither can refuse anything: exit 2 is an ordinary exit for them. The three non-tool events now share one runner, hooks::run_event (the event as JSON on stdin with hook_event_name, session_id and cwd, bounded at 10 s), where only user_prompt_submit may refuse. Known limit, in the README: pre_compact runs when /compact is asked even on a route whose agent compacts its own conversation, where incode compacts nothing. Automatic compaction inside the API backend does not fire it yet (the agreed follow-up). Tests: the events carry their fields and exit 2 refuses nothing; a real turn with a stop hook shows its output among the notices, and none without one. Controls: with the stop firing removed, or exit 2 refusing for every event, the tests fail. --- README.md | 2 +- src/admin.rs | 2 + src/cli/agent_turn.rs | 74 +++++++++++++++- src/desktop/mcp.rs | 4 + src/hooks/mod.rs | 182 +++++++++++++++++++++++++++++++------- src/toolbox/hook_tests.rs | 2 + 6 files changed, 231 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index ea9f6a4..2f22335 100644 --- a/README.md +++ b/README.md @@ -1343,7 +1343,7 @@ and `--admin` prints which layer decided each value. | `sandbox_network` | `allow` (default) · `deny` — see [the OS sandbox](#the-os-sandbox) | | `sandbox_engine` · `sandbox_allow_hosts` · `sandbox_backend` | `builtin` (default) · `sbx`; under sbx, the hosts a command may reach and, on Windows, `native` · `wsl` · `auto` — see [the OS sandbox](#the-os-sandbox) | | `codex_tools` | `own` (default) · `incode` — whose tools a `codex` model runs; see [the codex route](#the-codex-route-whose-tools) | -| `hooks` (also `desktop_hooks`) | Your `pre_tool_use` / `post_tool_use` commands, run for every tool, and `user_prompt_submit`, run for each line you send. The event is JSON on stdin (`hook_event_name`, `session_id`, `cwd`, and `tool_name`/`tool_input` or `prompt`); exit 2 on a pre-tool command denies the call, on a prompt command refuses the line (the reason is shown and nothing is sent — not to the agent, not to the memory engine); a prompt command's stdout is added to that turn's context, and your line is never changed; bounded at 10 s. The prompt hook runs for lines typed in the REPL or sent over `--acp`, and for `-t`; `/review` and `/run` do not run it. It is taken from here and from your own plugins (`~/.incode/plugins/`), never from a project's `.incode/plugins/`, which arrives with whatever was cloned | +| `hooks` (also `desktop_hooks`) | Your `pre_tool_use` / `post_tool_use` commands, run for every tool, and `user_prompt_submit`, run for each line you send. The event is JSON on stdin (`hook_event_name`, `session_id`, `cwd`, and `tool_name`/`tool_input` or `prompt`); exit 2 on a pre-tool command denies the call, on a prompt command refuses the line (the reason is shown and nothing is sent — not to the agent, not to the memory engine); a prompt command's stdout is added to that turn's context, and your line is never changed; bounded at 10 s. The prompt hook runs for lines typed in the REPL or sent over `--acp`, and for `-t`; `/review` and `/run` do not run it. It is taken from here and from your own plugins (`~/.incode/plugins/`), never from a project's `.incode/plugins/`, which arrives with whatever was cloned. `pre_compact` runs before `/compact` (event field `trigger`: `manual`, plus `custom_instructions`; when the agent compacts its own conversation, as a CLI agent does, it still runs and nothing is compacted by incode), and `stop` when one of your turns has ended (`last_assistant_message`); neither can refuse anything, and their stdout is shown — with the compaction result, and with the turn's notices | | `desktop_limits` | The desktop's limits, each optional: `max_actions_per_minute` (120), `heartbeat_deadline_secs` (30), `tree_depth` (12), `tree_max_elements` (400), `journal_max_bytes` (262144), `xvfb_start_timeout_secs` (10), `clipboard_timeout_secs` (5), `accessibility_call_timeout_ms` (1000), `paste_restore_delay_ms` (500, how long the pasted text stays on the clipboard before the old one is put back), `settle_ms` (300, the pause before a `screenshot_after`), `max_scroll_steps` (50, wheel steps in one `scroll`), `tree_max_visited` (4000, elements one tree walk may visit), and `blocked_apps` (application names, matched case-insensitively as a part of the name, added to the built-in password managers: 1Password, Bitwarden, LastPass, Dashlane, KeePass, NordPass, Proton Pass, Enpass, RoboForm, Keeper). The first two are safety limits and may only be lowered; zero and unknown keys are refused, and the desktop does not start on a malformed admin.json | | `desktop_display` | Linux computer use: `":N"` drives a running X display; `"xvfb"` or `"xvfb:1280x800"` starts a private Xvfb for the desktop server's lifetime (default 1920x1080). Unset refuses rather than using `$DISPLAY`. `paste_text` needs `xclip` or `xsel`; `ui_tree` needs a D-Bus session with at-spi2-core | | `plugins` | Which memory-service parts are used; all on by default | diff --git a/src/admin.rs b/src/admin.rs index 20faab3..200b874 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -1606,6 +1606,8 @@ mod tests { 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()], }, desktop_display: Some("xvfb:1280x800".to_string()), desktop_limits: crate::desktop::limits::DesktopLimits { diff --git a/src/cli/agent_turn.rs b/src/cli/agent_turn.rs index 5dd9ddf..7da1340 100644 --- a/src/cli/agent_turn.rs +++ b/src/cli/agent_turn.rs @@ -506,7 +506,30 @@ impl AgentSession { /// [`crate::agent::AgentBackend::compact`]. `None` when the lead is an /// agent CLI, which compacts its own. pub fn compact(&mut self, instructions: &str) -> Option> { - self.backend.compact(instructions) + // The operator's `pre_compact` commands first (`crate::hooks`): told, + // never asked — what they print is shown with the result. + let said: Vec = match &self.operator_hooks { + Some(hooks) => hooks + .pre_compact( + "manual", + instructions, + self.session_id().unwrap_or(""), + Some(&self.workspace), + ) + .messages() + .to_vec(), + None => Vec::new(), + }; + match self.backend.compact(instructions) { + Some(Ok(done)) if !said.is_empty() => { + let lines: Vec = said + .iter() + .map(|s| format!("[pre_compact hook] {s}")) + .collect(); + Some(Ok(format!("{}\n{done}", lines.join("\n")))) + } + other => other, + } } /// Start a fresh agent session on the next turn. @@ -1220,6 +1243,26 @@ impl AgentSession { } } + // The operator's `stop` commands, once the turn is over — after any + // continuation above (`crate::hooks`). Told what the agent said + // last; what they print joins the turn's notices. They cannot reopen + // the turn. + if outcome.is_ok() { + let told: Vec = match &self.operator_hooks { + Some(hooks) => hooks + .stop( + said.last(), + self.session_id().unwrap_or(""), + Some(&self.workspace), + ) + .messages() + .to_vec(), + None => Vec::new(), + }; + self.notices + .extend(told.into_iter().map(|m| format!("[stop hook] {m}"))); + } + // HOW MUCH MOVED, in one line, once the turn is over. // // The per-change blocks answer "what changed here"; after a dozen of @@ -1983,6 +2026,35 @@ mod tests { } } + /// **A STOP HOOK RUNS WHEN THE TURN ENDS**, and what it prints is shown + /// with the turn's notices; without one, no such notice appears. + #[test] + fn a_stop_hook_runs_after_the_turn_and_its_output_is_shown() { + let ws = tempfile::tempdir().expect("ws"); + let engine = tempfile::tempdir().expect("engine"); + let seen = Arc::new(Mutex::new(Seen::default())); + 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)], + ..crate::hooks::HookConfig::default() + }, + ))); + one_turn(&mut s, ws.path(), "do the work"); + let notices = s.take_notices(); + assert!( + notices.iter().any(|n| n == "[stop hook] turn noted"), + "{notices:?}" + ); + + s.set_operator_hooks(None); + one_turn(&mut s, ws.path(), "again"); + assert!(!s + .take_notices() + .iter() + .any(|n| n.starts_with("[stop hook]"))); + } + fn start_context(text: &str) -> String { serde_json::json!({ "hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text} diff --git a/src/desktop/mcp.rs b/src/desktop/mcp.rs index f721b7b..2cc829e 100644 --- a/src/desktop/mcp.rs +++ b/src/desktop/mcp.rs @@ -1754,6 +1754,8 @@ mod tests { pre_tool_use: vec![deny.to_string()], post_tool_use: Vec::new(), user_prompt_submit: Vec::new(), + pre_compact: Vec::new(), + stop: Vec::new(), }, ); @@ -1791,6 +1793,8 @@ mod tests { pre_tool_use: vec![allow.to_string()], post_tool_use: Vec::new(), user_prompt_submit: Vec::new(), + pre_compact: Vec::new(), + stop: Vec::new(), }, ); diff --git a/src/hooks/mod.rs b/src/hooks/mod.rs index 1c778b4..bf1afbd 100644 --- a/src/hooks/mod.rs +++ b/src/hooks/mod.rs @@ -131,6 +131,15 @@ pub struct HookConfig { /// 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, + /// 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, + /// 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, } impl HookConfig { @@ -143,6 +152,8 @@ impl HookConfig { self.pre_tool_use.is_empty() && self.post_tool_use.is_empty() && self.user_prompt_submit.is_empty() + && self.pre_compact.is_empty() + && self.stop.is_empty() } /// `other`'s commands after these, event by event (a plugin's after the @@ -151,6 +162,8 @@ impl HookConfig { self.pre_tool_use.extend(other.pre_tool_use); self.post_tool_use.extend(other.post_tool_use); self.user_prompt_submit.extend(other.user_prompt_submit); + self.pre_compact.extend(other.pre_compact); + self.stop.extend(other.stop); } } @@ -359,43 +372,106 @@ impl HookRunner { session: &str, cwd: Option<&Path>, ) -> HookRunResult { - let commands = &self.config.user_prompt_submit; - if commands.is_empty() { - return HookRunResult::allow(Vec::new()); - } - let mut payload = json!({ - "hook_event_name": "UserPromptSubmit", - "prompt": prompt, - "session_id": session, - "cwd": cwd.map(|p| p.to_string_lossy().into_owned()), - }) - .to_string() - .into_bytes(); - payload.push(b'\n'); - let mut messages = Vec::new(); - for command in commands { - match run_shell_command(command, &[], cwd, &payload) { - Ok((2, stdout, stderr)) => { - let reason = if stderr.is_empty() { stdout } else { stderr }; - return HookRunResult { - denied: true, - messages: vec![if reason.is_empty() { - format!("the operator's hook `{command}` refused this prompt") - } else { - reason - }], - }; - } - Ok((_, stdout, _)) => { - if !stdout.is_empty() { - messages.push(stdout); - } + run_event( + &self.config.user_prompt_submit, + "UserPromptSubmit", + json!({ "prompt": prompt }), + session, + cwd, + true, + ) + } + + /// The `pre_compact` commands, before `/compact` compacts the + /// conversation (`trigger` is `manual`). They cannot stop it: exit 2 is + /// an ordinary exit here. Each one's stdout is a message to show. + /// + /// Called by `cli::agent_turn::AgentSession::compact`. + #[must_use] + pub fn pre_compact( + &self, + trigger: &str, + instructions: &str, + session: &str, + cwd: Option<&Path>, + ) -> HookRunResult { + run_event( + &self.config.pre_compact, + "PreCompact", + json!({ "trigger": trigger, "custom_instructions": instructions }), + session, + cwd, + false, + ) + } + + /// The `stop` commands, once a person's turn has ended, told what the + /// agent said last. They cannot reopen the turn; each one's stdout is a + /// message to show. + /// + /// Called by `cli::agent_turn::AgentSession::turn_observed`. + #[must_use] + pub fn stop(&self, last_message: &str, session: &str, cwd: Option<&Path>) -> HookRunResult { + run_event( + &self.config.stop, + "Stop", + json!({ "last_assistant_message": last_message }), + session, + cwd, + false, + ) + } +} + +/// Run `commands` for one event that is not a tool call: the event as JSON on +/// stdin — `hook_event_name`, `session_id`, `cwd` and `fields` — bounded at +/// [`HOOK_TIMEOUT`]. With `can_refuse`, exit 2 refuses (stderr, else stdout, +/// 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], + name: &str, + fields: Value, + session: &str, + cwd: Option<&Path>, + can_refuse: bool, +) -> HookRunResult { + if commands.is_empty() { + return HookRunResult::allow(Vec::new()); + } + let mut event = json!({ + "hook_event_name": name, + "session_id": session, + "cwd": cwd.map(|p| p.to_string_lossy().into_owned()), + }); + if let (Some(event), Value::Object(fields)) = (event.as_object_mut(), fields) { + event.extend(fields); + } + let mut payload = event.to_string().into_bytes(); + payload.push(b'\n'); + let mut messages = Vec::new(); + for command in commands { + match run_shell_command(command, &[], cwd, &payload) { + Ok((2, stdout, stderr)) if can_refuse => { + let reason = if stderr.is_empty() { stdout } else { stderr }; + return HookRunResult { + denied: true, + messages: vec![if reason.is_empty() { + format!("the operator's hook `{command}` refused this") + } else { + reason + }], + }; + } + Ok((_, stdout, _)) => { + if !stdout.is_empty() { + messages.push(stdout); } - Err(e) => messages.push(format!("Hook `{command}` failed: {e}")), } + Err(e) => messages.push(format!("Hook `{command}` failed: {e}")), } - HookRunResult::allow(messages) } + HookRunResult::allow(messages) } /// A `user_prompt_submit` command's output as the turn's context block, with @@ -531,6 +607,8 @@ mod tests { pre_tool_use: vec![hook(dir.path(), 2, "no writes today")], post_tool_use: Vec::new(), user_prompt_submit: Vec::new(), + pre_compact: Vec::new(), + stop: Vec::new(), }); let input = json!({"path": "a.txt", "content": "hi"}); let ran = runner.pre_tool(&call(&input, dir.path())); @@ -555,6 +633,8 @@ mod tests { pre_tool_use: vec![hook(dir.path(), 0, "fine")], post_tool_use: vec![hook(dir.path(), 2, "too late")], user_prompt_submit: Vec::new(), + pre_compact: Vec::new(), + stop: Vec::new(), }); let input = json!({"path": "a.txt"}); let pre = runner.pre_tool(&call(&input, dir.path())); @@ -586,6 +666,42 @@ mod tests { assert!(block.contains("fine< /operator-hook>"), "{block}"); } + /// `pre_compact` and `stop` are told, never asked: exit 2 refuses + /// nothing, stdout is a message, and the event carries its own fields. + #[test] + fn pre_compact_and_stop_are_told_and_cannot_refuse() { + let dir = tempfile::tempdir().expect("dir"); + let runner = HookRunner::new(HookConfig { + pre_compact: vec![hook(dir.path(), 2, "")], + ..HookConfig::default() + }); + let ran = runner.pre_compact("manual", "keep the API notes", "s-1", Some(dir.path())); + assert!(!ran.is_denied(), "a pre_compact hook refused"); + assert_eq!(ran.messages(), ["said"]); + let event: Value = serde_json::from_str( + &std::fs::read_to_string(dir.path().join("event.json")).expect("saved"), + ) + .expect("json"); + assert_eq!(event["hook_event_name"], "PreCompact"); + assert_eq!(event["trigger"], "manual"); + assert_eq!(event["custom_instructions"], "keep the API notes"); + + let stop_dir = tempfile::tempdir().expect("dir"); + let runner = HookRunner::new(HookConfig { + stop: vec![hook(stop_dir.path(), 2, "")], + ..HookConfig::default() + }); + let ran = runner.stop("all done", "s-1", Some(stop_dir.path())); + assert!(!ran.is_denied(), "a stop hook refused"); + let event: Value = serde_json::from_str( + &std::fs::read_to_string(stop_dir.path().join("event.json")).expect("saved"), + ) + .expect("json"); + assert_eq!(event["hook_event_name"], "Stop"); + assert_eq!(event["last_assistant_message"], "all done"); + assert_eq!(event["session_id"], "s-1"); + } + fn prompt_runner(commands: Vec) -> HookRunner { HookRunner::new(HookConfig { user_prompt_submit: commands, diff --git a/src/toolbox/hook_tests.rs b/src/toolbox/hook_tests.rs index f18d235..229622f 100644 --- a/src/toolbox/hook_tests.rs +++ b/src/toolbox/hook_tests.rs @@ -43,6 +43,8 @@ fn hooked(ws: &Path, pre: String, post: Vec) -> Toolbox { pre_tool_use: vec![pre], post_tool_use: post, user_prompt_submit: Vec::new(), + pre_compact: Vec::new(), + stop: Vec::new(), }, ))) } From 00eae2e6628a5b949524a5647a8cc14c900d49ec Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:11:02 -0600 Subject: [PATCH 2/2] plugins: a project's plugin gives only the tool hooks, by allowlist From a security review of 3d674a5. hooks_of dropped only a project plugin's user_prompt_submit, so the new stop and pre_compact commands of a cloned repository's (approved) plugin still ran, and every hook event added later would have too. A project's plugin now gives only pre_tool_use and post_tool_use, by allowlist; the rest are left out and traced. The operator's own plugins give every event. And what an approval is shown counted only the two tool lists: plugins::contents now uses HookConfig::count, over every event. Test: a project plugin's prompt, stop and pre_compact hooks are left out while the user plugin's are kept, and its summary counts all four. Control: with the allowlist replaced by the whole config, it fails. --- src/hooks/mod.rs | 11 +++++++++++ src/plugins.rs | 46 +++++++++++++++++++++++++++++++--------------- 2 files changed, 42 insertions(+), 15 deletions(-) diff --git a/src/hooks/mod.rs b/src/hooks/mod.rs index bf1afbd..76b439f 100644 --- a/src/hooks/mod.rs +++ b/src/hooks/mod.rs @@ -156,6 +156,17 @@ impl HookConfig { && self.stop.is_empty() } + /// How many commands, over every event. Used where a plugin's hooks are + /// shown for approval (`plugins::contents`), so none is left uncounted. + #[must_use] + pub fn count(&self) -> usize { + self.pre_tool_use.len() + + self.post_tool_use.len() + + self.user_prompt_submit.len() + + self.pre_compact.len() + + self.stop.len() + } + /// `other`'s commands after these, event by event (a plugin's after the /// operator's). pub fn extend(&mut self, other: Self) { diff --git a/src/plugins.rs b/src/plugins.rs index 6cab1d5..5690a0f 100644 --- a/src/plugins.rs +++ b/src/plugins.rs @@ -446,23 +446,29 @@ fn hooks_of(plugins: &[Plugin]) -> crate::hooks::HookConfig { let mut all = crate::hooks::HookConfig::default(); for plugin in plugins { match plugin.hooks() { - // Every event, not a list of them: a field added to `HookConfig` - // reaches plugins without this needing to know. - // - // Except `user_prompt_submit` from a PROJECT plugin: that folder - // arrives with whatever was cloned, and this event runs on the - // first line typed, before any tool. It is taken from admin.json - // and the operator's own plugins only. - Ok(mut config) => { - if plugin.scope == Scope::Project && !config.user_prompt_submit.is_empty() { + // The operator's own plugin: every event, so a field added to + // `HookConfig` reaches it without this needing to know. + Ok(config) if plugin.scope == Scope::User => all.extend(config), + // A PROJECT's plugin — approved, or it would not be here — gives + // only the tool events, by an allowlist: an event added later is + // refused to it by default. Its folder arrives with whatever was + // cloned, and the session events (a line typed, a turn ending, a + // compaction) run with no tool call to weigh them against. + Ok(config) => { + let tool_only = crate::hooks::HookConfig { + pre_tool_use: config.pre_tool_use.clone(), + post_tool_use: config.post_tool_use.clone(), + ..crate::hooks::HookConfig::default() + }; + if config.count() > tool_only.count() { crate::trace!( "plugins", - "{}: user_prompt_submit is not run from a project's plugin", + "{}: a project's plugin may run only pre_tool_use and post_tool_use \ + hooks; its others are left out", plugin.root.display() ); - config.user_prompt_submit.clear(); } - all.extend(config); + all.extend(tool_only); } Err(why) => crate::trace!("plugins", "{why}"), } @@ -623,7 +629,8 @@ fn contents(plugin: &Plugin) -> String { let skills = plugin.skills().len(); let hooks = plugin .hooks() - .map(|h| h.pre_tool_use.len() + h.post_tool_use.len()) + // Every event's commands: this is what an approval is shown. + .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)") @@ -1058,7 +1065,8 @@ mod tests { #[test] fn a_project_plugins_prompt_hook_is_not_run_and_a_users_is() { let dir = tempfile::tempdir().expect("dir"); - let hooks = r#"{"pre_tool_use": ["tool-check"], "user_prompt_submit": ["prompt-check"]}"#; + let hooks = r#"{"pre_tool_use": ["tool-check"], "user_prompt_submit": ["prompt-check"], + "stop": ["stop-check"], "pre_compact": ["compact-check"]}"#; let project = plugin(&dir.path().join("project"), "cloned", "d"); write(&project.join("hooks.json"), hooks); let user = plugin(&dir.path().join("user"), "mine", "d"); @@ -1073,8 +1081,16 @@ mod tests { "only the user's" ); assert_eq!(merged.pre_tool_use, ["tool-check", "tool-check"]); + // Only the tool events, by allowlist: a project's plugin gives none + // of the session events, now or added later. + assert_eq!(merged.stop, ["stop-check"], "only the user's"); + assert_eq!(merged.pre_compact, ["compact-check"], "only the user's"); let project_only = hooks_of(&[load_one(&project, Scope::Project).expect("project plugin")]); - assert!(project_only.user_prompt_submit.is_empty()); + assert_eq!(project_only.count(), 1, "{project_only:?}"); + assert_eq!(project_only.pre_tool_use, ["tool-check"]); + // What an approval is shown counts every event's commands. + let shown = contents(&load_one(&project, Scope::Project).expect("project plugin")); + assert!(shown.contains("4 hook(s)"), "{shown}"); } #[test]