From 7e84c054b9f2b9d213e8961359cf291ae1b51a6f Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:23:08 -0600 Subject: [PATCH 1/2] codex: with_tool_server built only where its one caller is The method was cfg(test) while its only caller, the bridged-turn test, is cfg(unix), so a Windows test build held it as dead code and clippy -D warnings refused the crate. --- src/agent/codex.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/agent/codex.rs b/src/agent/codex.rs index dd09571..9253a65 100644 --- a/src/agent/codex.rs +++ b/src/agent/codex.rs @@ -467,7 +467,9 @@ impl CodexBackend { } /// Have codex start `exe` as the tool server instead of this binary. - #[cfg(test)] + /// Unix only, as its one caller is (the bridged-turn test's fakes are + /// shell scripts). + #[cfg(all(test, unix))] fn with_tool_server(mut self, exe: PathBuf) -> Self { self.tool_server = Some(exe); self From c140a67090e6f1a9c4ab04f8c8393344922b781c Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:23:23 -0600 Subject: [PATCH 2/2] hooks: session_start and session_end, told and never asked (refs #26) The operator's hooks gain the session's own start and end. Start fires once the session exists (cli::prepare_session for the REPL and --acp, before the first line in -t); end fires beside the memory engine's own end, so the two stay paired. In -t a line refused by user_prompt_submit now ends what it started. Neither can refuse; stdout is shown. Project plugins still give only the tool events. lifecycle.json is marked superseded and still runs. --- README.md | 2 +- src/acp_agent/mod.rs | 5 ++ src/admin.rs | 2 + src/cli/agent_turn.rs | 71 ++++++++++++++++++++++++++++ src/cli/mod.rs | 8 ++++ src/desktop/mcp.rs | 4 ++ src/hooks/mod.rs | 91 ++++++++++++++++++++++++++++++++++++ src/runtime/lifecycle.rs | 4 ++ src/task_run.rs | 97 ++++++++++++++++++++++++++++++++++++++- src/toolbox/hook_tests.rs | 2 + 10 files changed, 283 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e3858af..e233bcc 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. `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. `notification` runs whenever incode would notify you (`notification_type`: `turn_done` or `input_needed`, plus `message`), in the background beside `notify_command`, in the REPL; its output is not shown | +| `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. `session_start` runs when a session opens (`source`: `startup`) and `session_end` when it closes (`reason`, e.g. `prompt_input_exit`, `other`), in the REPL, `--acp` and `-t`; neither can stop or keep anything, and their stdout is shown (on stderr for `-t`; a `--acp` session's end output goes to the trace, as the client has gone). They supersede `.incode/lifecycle.json`'s `on_session_start`/`on_session_end`, which still run. `notification` runs whenever incode would notify you (`notification_type`: `turn_done` or `input_needed`, plus `message`), in the background beside `notify_command`, in the REPL; its output is not shown | | `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/acp_agent/mod.rs b/src/acp_agent/mod.rs index 93d2f7e..1d53e2d 100644 --- a/src/acp_agent/mod.rs +++ b/src/acp_agent/mod.rs @@ -1184,6 +1184,11 @@ fn drive( // the session is over, and the memory engine is told — on this thread, // which owns the session, bounded by the engine runner. held.session.end_memory("other"); + // The operator's `session_end` commands. Nowhere to show their output + // once the client has closed the session: it is traced. + for said in held.session.operator_session_end("other") { + crate::trace!("hooks", "session_end hook: {said}"); + } } /// One open session, as its thread holds it. diff --git a/src/admin.rs b/src/admin.rs index 7fdfd91..bca000b 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -1609,6 +1609,8 @@ mod tests { 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()], }, 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 7da1340..de453f5 100644 --- a/src/cli/agent_turn.rs +++ b/src/cli/agent_turn.rs @@ -629,6 +629,44 @@ impl AgentSession { self.memory.prompt(line) } + /// The operator's `session_start` commands (`crate::hooks`): what they + /// printed, for the caller to show. `source` is `startup`. + /// + /// Called by `cli::prepare_session` (REPL and `--acp`); `task_run` fires + /// its own, as it has no `AgentSession`. + #[must_use] + pub fn operator_session_start(&self, source: &str) -> Vec { + self.operator_hooks.as_ref().map_or_else(Vec::new, |hooks| { + hooks + .session_start( + source, + self.session_id().unwrap_or(""), + Some(&self.workspace), + ) + .messages() + .to_vec() + }) + } + + /// The operator's `session_end` commands (`crate::hooks`): what they + /// printed, for the caller to show if it still can. + /// + /// Called beside `end_memory` by the REPL (`cli::mod`) and `--acp` + /// (`acp_agent`); `task_run` fires its own. + #[must_use] + pub fn operator_session_end(&self, reason: &str) -> Vec { + self.operator_hooks.as_ref().map_or_else(Vec::new, |hooks| { + hooks + .session_end( + reason, + self.session_id().unwrap_or(""), + Some(&self.workspace), + ) + .messages() + .to_vec() + }) + } + /// The session is over; `reason` says why. A session-start still being /// answered is collected first, so the engine hears the start before the /// end. @@ -2055,6 +2093,39 @@ mod tests { .any(|n| n.starts_with("[stop hook]"))); } + /// **THE SESSION'S START AND END HOOKS RUN IN ITS WORKSPACE**, and what + /// they print comes back for the caller to show; without hooks, nothing. + #[test] + fn session_start_and_end_hooks_run_in_the_workspace_and_are_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(|_| {})); + // Prints the directory it ran in: the workspace, or the hook was + // given the wrong `cwd`. + 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)], + ..crate::hooks::HookConfig::default() + }, + ))); + let started = s.operator_session_start("startup"); + let ran_in = std::fs::canonicalize(started.first().expect("start printed nothing")) + .expect("the hook printed a directory"); + assert_eq!( + ran_in, + std::fs::canonicalize(ws.path()).expect("ws"), + "{started:?}" + ); + assert_eq!(s.operator_session_end("prompt_input_exit"), ["bye"]); + + s.set_operator_hooks(None); + assert!(s.operator_session_start("startup").is_empty()); + assert!(s.operator_session_end("other").is_empty()); + } + fn start_context(text: &str) -> String { serde_json::json!({ "hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index e14941a..0fab8c9 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -647,6 +647,11 @@ pub(crate) fn prepare_session( // The operator's commands for the events the session fires itself (a // person's line); the toolbox has its own for the tool events. session.set_operator_hooks(crate::hooks::HookRunner::from_settings()); + // The operator's `session_start` commands, now the session exists — the + // REPL and `--acp` both come through here. Shown, never asked. + for said in session.operator_session_start("startup") { + render::print_info(&format!("[session_start hook] {said}")); + } if !config.additional_dirs.is_empty() { render::print_info(&format!( "Also working in {} additional director(ies) — guards and undo cover them.", @@ -1367,6 +1372,9 @@ impl CliApp { // The memory engine's end of the session, bounded by the engine // runner, before the operator's own end-of-session command. session.end_memory("prompt_input_exit"); + for said in session.operator_session_end("prompt_input_exit") { + render::print_info(&format!("[session_end hook] {said}")); + } // Run session end lifecycle hook (Feature 7) if let Some(result) = lifecycle_hooks.run_session_end(&workspace) { diff --git a/src/desktop/mcp.rs b/src/desktop/mcp.rs index dcfc926..0b1a81b 100644 --- a/src/desktop/mcp.rs +++ b/src/desktop/mcp.rs @@ -1757,6 +1757,8 @@ mod tests { pre_compact: Vec::new(), stop: Vec::new(), notification: Vec::new(), + session_start: Vec::new(), + session_end: Vec::new(), }, ); @@ -1797,6 +1799,8 @@ mod tests { pre_compact: Vec::new(), stop: Vec::new(), notification: Vec::new(), + session_start: Vec::new(), + session_end: Vec::new(), }, ); diff --git a/src/hooks/mod.rs b/src/hooks/mod.rs index 22bfb79..19fe14f 100644 --- a/src/hooks/mod.rs +++ b/src/hooks/mod.rs @@ -145,6 +145,14 @@ pub struct HookConfig { /// beside `notify_command`; they cannot change anything. #[serde(default, skip_serializing_if = "Vec::is_empty")] 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, + /// 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, } impl HookConfig { @@ -160,6 +168,8 @@ impl HookConfig { && self.pre_compact.is_empty() && self.stop.is_empty() && self.notification.is_empty() + && self.session_start.is_empty() + && self.session_end.is_empty() } /// How many commands, over every event. Used where a plugin's hooks are @@ -172,6 +182,8 @@ impl HookConfig { + self.pre_compact.len() + self.stop.len() + self.notification.len() + + self.session_start.len() + + self.session_end.len() } /// `other`'s commands after these, event by event (a plugin's after the @@ -183,6 +195,8 @@ impl HookConfig { self.pre_compact.extend(other.pre_compact); self.stop.extend(other.stop); self.notification.extend(other.notification); + self.session_start.extend(other.session_start); + self.session_end.extend(other.session_end); } } @@ -461,6 +475,42 @@ impl HookRunner { } } +impl HookRunner { + /// The `session_start` commands; `source` is `startup`. They cannot stop + /// it; stdout is a message. + /// + /// Called by `cli::agent_turn::AgentSession::operator_session_start` + /// (REPL and `--acp`) and `task_run` (`-t`). + #[must_use] + pub fn session_start(&self, source: &str, session: &str, cwd: Option<&Path>) -> HookRunResult { + run_event( + &self.config.session_start, + "SessionStart", + json!({ "source": source }), + session, + cwd, + false, + ) + } + + /// The `session_end` commands; `reason` says why it ended. They cannot + /// keep it open; stdout is a message. + /// + /// Called by `cli::agent_turn::AgentSession::operator_session_end` (REPL + /// and `--acp`, beside each `end_memory`) and `task_run` (`-t`). + #[must_use] + pub fn session_end(&self, reason: &str, session: &str, cwd: Option<&Path>) -> HookRunResult { + run_event( + &self.config.session_end, + "SessionEnd", + json!({ "reason": reason }), + 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, @@ -648,6 +698,8 @@ mod tests { pre_compact: Vec::new(), stop: Vec::new(), notification: Vec::new(), + session_start: Vec::new(), + session_end: Vec::new(), }); let input = json!({"path": "a.txt", "content": "hi"}); let ran = runner.pre_tool(&call(&input, dir.path())); @@ -675,6 +727,8 @@ mod tests { pre_compact: Vec::new(), stop: Vec::new(), notification: Vec::new(), + session_start: Vec::new(), + session_end: Vec::new(), }); let input = json!({"path": "a.txt"}); let pre = runner.pre_tool(&call(&input, dir.path())); @@ -742,6 +796,43 @@ mod tests { assert_eq!(event["session_id"], "s-1"); } + /// `session_start` and `session_end` are told, never asked: exit 2 keeps + /// nothing from starting or ending, stdout is a message, and the event + /// says why. + #[test] + fn session_start_and_end_are_told_and_cannot_refuse() { + let start_dir = tempfile::tempdir().expect("dir"); + let runner = HookRunner::new(HookConfig { + session_start: vec![hook(start_dir.path(), 2, "")], + ..HookConfig::default() + }); + let ran = runner.session_start("startup", "s-2", Some(start_dir.path())); + assert!(!ran.is_denied(), "a session_start hook refused"); + assert_eq!(ran.messages(), ["said"]); + let event: Value = serde_json::from_str( + &std::fs::read_to_string(start_dir.path().join("event.json")).expect("saved"), + ) + .expect("json"); + assert_eq!(event["hook_event_name"], "SessionStart"); + assert_eq!(event["source"], "startup"); + assert_eq!(event["session_id"], "s-2"); + + let end_dir = tempfile::tempdir().expect("dir"); + let runner = HookRunner::new(HookConfig { + session_end: vec![hook(end_dir.path(), 2, "")], + ..HookConfig::default() + }); + let ran = runner.session_end("prompt_input_exit", "s-2", Some(end_dir.path())); + assert!(!ran.is_denied(), "a session_end hook refused"); + assert_eq!(ran.messages(), ["said"]); + let event: Value = serde_json::from_str( + &std::fs::read_to_string(end_dir.path().join("event.json")).expect("saved"), + ) + .expect("json"); + assert_eq!(event["hook_event_name"], "SessionEnd"); + assert_eq!(event["reason"], "prompt_input_exit"); + } + fn prompt_runner(commands: Vec) -> HookRunner { HookRunner::new(HookConfig { user_prompt_submit: commands, diff --git a/src/runtime/lifecycle.rs b/src/runtime/lifecycle.rs index e705440..9fe6a51 100644 --- a/src/runtime/lifecycle.rs +++ b/src/runtime/lifecycle.rs @@ -4,6 +4,10 @@ //! - `on_session_start`: Run when a new session begins (e.g. "npm install") //! - `on_session_end`: Run when session ends (e.g. "cargo fmt") //! - `on_compact`: Run after compaction (e.g. custom cleanup) +//! +//! Superseded by the operator's `session_start` / `session_end` hooks +//! (`crate::hooks::HookConfig`); kept so an existing `lifecycle.json` still +//! runs. use std::path::Path; use std::process::Command; diff --git a/src/task_run.rs b/src/task_run.rs index 0d0a40c..31a5ab0 100644 --- a/src/task_run.rs +++ b/src/task_run.rs @@ -366,7 +366,8 @@ pub fn run_task_with_model( ) } -/// The run itself, telling `report` what happens. +/// The run itself, telling `report` what happens, with the operator's hooks +/// from `admin.json` and their own plugins. fn run_task_reporting( workspace: &Path, instruction: &str, @@ -374,6 +375,28 @@ fn run_task_reporting( command_tools: &[String], permission_mode: Option, report: &mut Report, +) -> Result { + run_task_hooked( + workspace, + instruction, + model, + command_tools, + permission_mode, + report, + crate::hooks::HookRunner::from_settings(), + ) +} + +/// [`run_task_reporting`] with the operator's hooks given, so a test can +/// give its own. +fn run_task_hooked( + workspace: &Path, + instruction: &str, + model: Option<&str>, + command_tools: &[String], + permission_mode: Option, + report: &mut Report, + operator_hooks: Option, ) -> Result { if instruction.trim().is_empty() { return Err("nothing to do: the instruction is empty".to_string()); @@ -402,10 +425,34 @@ fn run_task_reporting( // as in a session (`cli::plan_turn`): one that refuses it stops the run // before the memory engine or an agent hears it. What they print rides // the turn as context. - let hooked: Vec = match crate::hooks::HookRunner::from_settings() { + // + // `session_start` first, as a session's start comes before its first + // line; what it prints goes to stderr, which a JSON run keeps apart. + if let Some(hooks) = &operator_hooks { + for said in hooks + .session_start("startup", &session_id, Some(workspace)) + .messages() + { + eprintln!("incode: [session_start hook] {said}"); + } + } + // Every way out after the start runs this, a refused line included, so + // no `session_start` is left without its `session_end`. + let operator_end = || { + if let Some(hooks) = &operator_hooks { + for said in hooks + .session_end("other", &session_id, Some(workspace)) + .messages() + { + eprintln!("incode: [session_end hook] {said}"); + } + } + }; + let hooked: Vec = match &operator_hooks { Some(hooks) => { let ran = hooks.user_prompt_submit(instruction, &session_id, Some(workspace)); if ran.is_denied() { + operator_end(); return Err(format!( "not run: the operator's user_prompt_submit hook refused it. {}", ran.messages().join("\n") @@ -499,6 +546,7 @@ fn run_task_reporting( }; let ran = drive(&task, &mut memory, report); memory.end("other"); + operator_end(); ran } @@ -1058,6 +1106,51 @@ pub fn build_prompt( mod tests { use super::*; + /// **A REFUSED LINE STILL ENDS THE SESSION IT STARTED.** The operator's + /// `user_prompt_submit` hook refuses the instruction: the run stops with + /// the reason, and `session_end` runs after `session_start`, in the + /// workspace, so no start is left without its end. + #[test] + fn a_refused_instruction_still_runs_the_session_end_hook() { + let ws = tempfile::tempdir().expect("ws"); + let (refuse, mark) = if cfg!(windows) { + ( + "echo no secrets 1>&2& exit /b 2", + ["echo started> started.txt", "echo ended> ended.txt"], + ) + } else { + ( + "echo 'no secrets' >&2; exit 2", + ["echo started > started.txt", "echo ended > ended.txt"], + ) + }; + 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()], + ..crate::hooks::HookConfig::default() + }); + let ran = run_task_hooked( + ws.path(), + "fix it", + None, + &[], + None, + &mut Report::text(), + Some(hooks), + ); + let why = ran.expect_err("exit 2 did not refuse the instruction"); + assert!(why.contains("no secrets"), "{why}"); + assert!( + ws.path().join("started.txt").exists(), + "session_start did not run" + ); + assert!( + ws.path().join("ended.txt").exists(), + "a refused run left its session_start without a session_end" + ); + } + #[test] fn the_allowed_tools_are_a_comma_separated_list_or_all() { assert_eq!(parse_allowed_tools(""), None); diff --git a/src/toolbox/hook_tests.rs b/src/toolbox/hook_tests.rs index bf66e61..f4cc457 100644 --- a/src/toolbox/hook_tests.rs +++ b/src/toolbox/hook_tests.rs @@ -46,6 +46,8 @@ fn hooked(ws: &Path, pre: String, post: Vec) -> Toolbox { pre_compact: Vec::new(), stop: Vec::new(), notification: Vec::new(), + session_start: Vec::new(), + session_end: Vec::new(), }, ))) }