diff --git a/README.md b/README.md index e233bcc..a2b47af 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. `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 | +| `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`; for `/review` it sees the review prompt (the change included), and for `/run` each task's instruction before a worker or lane gets it — a refused task fails that attempt, and the hook's output rides that task's turn. 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 before the API route compacts on its own near the context window (`trigger`: `auto`, its output shown as incode's note during the turn); a CLI agent's own automatic compaction happens inside that agent and fires nothing, 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/worker_tests.rs b/src/acp_agent/worker_tests.rs index e690836..22acb96 100644 --- a/src/acp_agent/worker_tests.rs +++ b/src/acp_agent/worker_tests.rs @@ -50,6 +50,7 @@ pub(super) fn act( ) { if let Behaviour::Thinks = behaviour { on_event(&AgentEvent::Thinking("weighing it".to_string())); + on_event(&AgentEvent::Notice("[pre_compact hook] noted".to_string())); on_event(&AgentEvent::TextDelta("decided".to_string())); return; } @@ -345,6 +346,39 @@ fn reasoning_arrives_as_a_thought_chunk() { client.close(); } +/// **incode's OWN NOTICE IS SHOWN, AND IS NOT THE REPLY** — what an +/// operator's `pre_compact` hook printed mid-turn arrives as a thought. +/// +/// Exercises the `AgentEvent::Notice` arm in `src/acp_agent/workers.rs` +/// (`acp_agent::workers`), which turns it into an `agent_thought_chunk`, and +/// the REPL arm in `cli::agent_turn` standing aside for the observer. +#[test] +fn a_notice_arrives_as_a_thought_chunk_not_as_the_reply() { + let mut client = started(Script::new(Behaviour::Thinks), false); + let ws = tempfile::tempdir().expect("ws"); + let session = client.open_session(ws.path()); + let (seen, _) = prompt( + &mut client, + &session, + json!([{"type": "text", "text": "think"}]), + ); + let updates = updates_of(&seen); + assert!( + updates + .iter() + .any(|u| u["sessionUpdate"] == "agent_thought_chunk" + && u["content"]["text"] == "[pre_compact hook] noted"), + "{updates:#?}" + ); + let said: String = updates + .iter() + .filter(|u| u["sessionUpdate"] == "agent_message_chunk") + .filter_map(|u| u["content"]["text"].as_str()) + .collect(); + assert!(!said.contains("pre_compact"), "{said}"); + client.close(); +} + fn details(update: &Value) -> &Value { &update["_meta"]["incode"] } diff --git a/src/acp_agent/workers.rs b/src/acp_agent/workers.rs index 11365cb..9c3b0ed 100644 --- a/src/acp_agent/workers.rs +++ b/src/acp_agent/workers.rs @@ -185,7 +185,7 @@ impl Presenter { } updates } - AgentEvent::Thinking(text) if !text.is_empty() => { + AgentEvent::Thinking(text) | AgentEvent::Notice(text) if !text.is_empty() => { vec![acp::SessionUpdate::AgentThoughtChunk( acp::ContentChunk::new(acp::ContentBlock::from(text.as_str())), )] @@ -390,3 +390,43 @@ impl Drop for Tap { self.ended(WorkerEnd::Failed); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn presenter(voice: Voice, workspace: &Path) -> Presenter { + Presenter { + voice, + edits: present::Edits::new(workspace), + plans: present::Plans::new(), + notes: Arc::default(), + who: Arc::default(), + saw_deltas: false, + } + } + + /// **incode's NOTICE IS A THOUGHT**, for the session's own turn and for + /// a worker's alike, and never reply text; an empty one is nothing. + #[test] + fn a_notice_becomes_a_thought_chunk_for_the_session_and_a_worker() { + let ws = tempfile::tempdir().expect("ws"); + for voice in [Voice::Session, Voice::Worker] { + let mut shows = presenter(voice, ws.path()); + let updates = shows.updates( + &AgentEvent::Notice("[pre_compact hook] noted".to_string()), + &|_| Before::Unknown, + ); + let sent: Vec = updates + .iter() + .map(|u| serde_json::to_value(u).expect("json")) + .collect(); + assert_eq!(sent.len(), 1, "{sent:#?}"); + assert_eq!(sent[0]["sessionUpdate"], "agent_thought_chunk", "{sent:#?}"); + assert_eq!(sent[0]["content"]["text"], "[pre_compact hook] noted"); + assert!(shows + .updates(&AgentEvent::Notice(String::new()), &|_| Before::Unknown) + .is_empty()); + } + } +} diff --git a/src/agent/api.rs b/src/agent/api.rs index 33f867b..be3c7bd 100644 --- a/src/agent/api.rs +++ b/src/agent/api.rs @@ -963,6 +963,11 @@ impl ApiBackend { if !super::compact::over_threshold(estimate, self.settings.context_window) { return; } + // The operator's `pre_compact` commands first, as before `/compact`: + // told, never asked. What they print is incode's to show. + for said in self.tools.operator_pre_compact("auto") { + on_event(&AgentEvent::Notice(format!("[pre_compact hook] {said}"))); + } match self.compact_with(transport, "", super::compact::KEEP_TURNS) { Ok(Some(done)) => { crate::trace!("compact", "{}", done.describe()); @@ -1946,6 +1951,44 @@ mod tests { assert_eq!(notes.len(), 1, "the compaction is said once: {notes:?}"); } + /// **THE OPERATOR'S `pre_compact` RUNS BEFORE THE ROUTE COMPACTS ON ITS + /// OWN**, told `trigger: auto`, and what it prints is incode's notice — + /// before the compaction's own note, so before the summary was asked for. + #[test] + fn the_operators_pre_compact_hook_runs_before_an_automatic_compaction() { + let dir = tempfile::tempdir().expect("tmp"); + let transport = Canned::new(&[&said("one"), &said("THE SUMMARY"), &said("two")]); + // Prints the event it was given on stdin. + 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()], + ..crate::hooks::HookConfig::default() + }), + )); + agent.settings.context_window = 1; + agent + .run_turn_with(&transport, "first", &mut |_| {}) + .expect("turn one"); + let mut shown = Vec::new(); + agent + .run_turn_with(&transport, "second", &mut |e| match e { + AgentEvent::Notice(note) => shown.push(format!("notice: {note}")), + AgentEvent::Thinking(note) => shown.push(format!("thinking: {note}")), + _ => {} + }) + .expect("turn two"); + + assert_eq!(shown.len(), 2, "{shown:?}"); + assert!( + shown[0].starts_with("notice: [pre_compact hook]") + && shown[0].contains("\"trigger\":\"auto\"") + && shown[0].contains("\"hook_event_name\":\"PreCompact\""), + "the hook did not run first, or was not told why: {shown:?}" + ); + assert!(shown[1].starts_with("thinking: [context near"), "{shown:?}"); + } + #[test] fn a_window_of_zero_never_compacts_on_its_own() { let dir = tempfile::tempdir().expect("tmp"); diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 53b140a..da7c6fe 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -104,6 +104,11 @@ pub enum AgentEvent { /// in a window from a table, because a guessed window is a wrong /// percentage on the owner's screen. Context { used: u64, size: u64 }, + /// incode itself speaking during a turn, not the model — what the + /// operator's `pre_compact` commands printed before the API route + /// compacted on its own. Every front end shows it apart from the reply; + /// the transcript and the stop hook do not hear it. + Notice(String), } /// How a turn ended. diff --git a/src/agent/worker.rs b/src/agent/worker.rs index 302b73b..32c1579 100644 --- a/src/agent/worker.rs +++ b/src/agent/worker.rs @@ -161,6 +161,9 @@ pub struct AgentBackendWorker { /// owns the list, and a worker that accumulated its own copy would keep /// handing on notes from a task the runner had since abandoned. handoffs: Vec, + /// What the operator's `user_prompt_submit` hooks added for the next + /// task (`TaskWorker::operator_context`), sent after its instruction. + operator_context: Vec, /// Where this task's actions are being written down, once one is open. /// /// Opened per task rather than per worker: one file per task is what makes @@ -272,6 +275,7 @@ impl AgentBackendWorker { heard_up_to: None, conversation_for: None, handoffs: Vec::new(), + operator_context: Vec::new(), transcript: None, // OFF by default: a worker with no terminal behind it must not // start printing. Turned on with `showing_edits`. @@ -693,6 +697,10 @@ impl TaskWorker for AgentBackendWorker { self.handoffs = handoffs.to_vec(); } + fn operator_context(&mut self, blocks: &[String]) { + self.operator_context = blocks.to_vec(); + } + fn release(&mut self) { self.heard_up_to = None; // The run is over: its claims and reads go now, not at their TTL. @@ -833,6 +841,12 @@ impl TaskWorker for AgentBackendWorker { }; let mut instruction = crate::runner::task_instruction(task); + // The operator's hooks' context for this task, right after the task + // itself, as a person's turn carries it. + for block in &self.operator_context { + instruction.push_str("\n\n"); + instruction.push_str(block); + } // Appended AFTER the task's own instruction, so the work being asked for // is read first and the briefing is plainly context rather than the // brief itself. @@ -2620,6 +2634,36 @@ mod tests { ); } + /// The operator's prompt-hook context reaches the agent's prompt, after + /// the task itself. + #[test] + fn the_operators_hook_context_reaches_the_agents_prompt_after_the_task() { + let dir = workspace(); + let backend = ScriptedBackend::saying(vec![AgentEvent::Text("done".to_string())]); + let mut worker = AgentBackendWorker::in_workspace(backend, dir.path().to_path_buf()); + + crate::runner::TaskWorker::operator_context( + &mut worker, + &[ + "\nticket ABC-1\n" + .to_string(), + ], + ); + worker + .work(&Task::new("d1.2", "r-1", "fix the parser")) + .expect("the scripted turn succeeds"); + + let prompt = worker.backend.prompts.last().expect("a prompt was sent"); + let task_at = prompt.find("fix the parser").expect("the task was sent"); + let hook_at = prompt.find("ticket ABC-1").unwrap_or_else(|| { + panic!("the operator's hook context never reached the agent: {prompt}") + }); + assert!( + task_at < hook_at, + "the context came before the task: {prompt}" + ); + } + /// What one task found reaches the NEXT task's agent. /// /// Every task is a fresh session, so without this the finding dies with the diff --git a/src/cli/agent_turn.rs b/src/cli/agent_turn.rs index de453f5..128106f 100644 --- a/src/cli/agent_turn.rs +++ b/src/cli/agent_turn.rs @@ -1086,6 +1086,16 @@ impl AgentSession { AgentEvent::Quota { status, resets_at, .. } => *turn_quota = Some((status.clone(), *resets_at)), + // incode speaking mid-turn: a line of its own, never part + // of the reply. An observer presents it itself (`--acp`, + // as a thought), so it is not drawn into the reply too. + AgentEvent::Notice(note) if observer.is_none() => { + if *mid_line { + on_text("\n"); + *mid_line = false; + } + on_text(&format!("{note}\n")); + } AgentEvent::Usage { input_tokens, output_tokens, @@ -1224,8 +1234,12 @@ impl AgentSession { observe(event, &start); } replied.hear(event); - if let AgentEvent::TextDelta(fragment) = event { - on_text(fragment); + match event { + AgentEvent::TextDelta(fragment) => on_text(fragment), + AgentEvent::Notice(note) if observer.is_none() => { + on_text(&format!("\n{note}\n")); + } + _ => {} } }); if !replied.last().is_empty() { @@ -1938,6 +1952,64 @@ mod tests { } } + /// A backend that starts its reply, has incode say something mid-turn, + /// and finishes the reply. + struct Noticing; + + impl AgentBackend for Noticing { + fn id(&self) -> &str { + "claude-code" + } + fn run_turn( + &mut self, + _prompt: &str, + on_event: &mut dyn FnMut(&AgentEvent), + ) -> Result { + on_event(&AgentEvent::TextDelta("half a ".to_string())); + on_event(&AgentEvent::Notice("[pre_compact hook] noted".to_string())); + on_event(&AgentEvent::TextDelta("reply".to_string())); + on_event(&AgentEvent::Text("half a reply".to_string())); + Ok(TurnOutcome { + session_id: String::new(), + stop_reason: "end_turn".to_string(), + is_error: false, + detail: None, + served_by: Vec::new(), + }) + } + fn session_id(&self) -> Option<&str> { + None + } + } + + /// **incode's NOTICE IS SHOWN ON A LINE OF ITS OWN**, even when it lands + /// mid-reply, and is not part of the reply. + #[test] + fn a_notice_mid_turn_is_shown_on_its_own_line() { + let ws = tempfile::tempdir().expect("ws"); + let mut s = AgentSession::new( + ws.path().to_path_buf(), + "claude-code", + "claude".to_string(), + &crate::guards::Guards::default(), + Vec::new(), + ) + .with_backend(Box::new(Noticing)); + let mut shown = String::new(); + let outcome = s.turn( + ws.path(), + "go", + &[], + &mut |t| shown.push_str(t), + &mut |_| {}, + ); + assert!(outcome.is_ok(), "{outcome:?}"); + assert!( + shown.contains("half a \n[pre_compact hook] noted\nreply"), + "{shown:?}" + ); + } + /// A session over `ws` whose backend records into `seen`, with the /// memory lifecycle opened on the fake engine in `engine`. fn with_memory( @@ -2064,6 +2136,64 @@ mod tests { } } + /// A repository with one commit and one untracked file: a change to + /// review. + fn repo_with_a_change() -> tempfile::TempDir { + let dir = tempfile::tempdir().expect("ws"); + let git = |args: &[&str]| { + let status = std::process::Command::new("git") + .args(args) + .current_dir(dir.path()) + .env("GIT_AUTHOR_NAME", "t") + .env("GIT_AUTHOR_EMAIL", "t@example.com") + .env("GIT_COMMITTER_NAME", "t") + .env("GIT_COMMITTER_EMAIL", "t@example.com") + .status() + .expect("git runs"); + assert!(status.success(), "git {args:?}"); + }; + git(&["init", "-q", "-b", "main"]); + std::fs::write(dir.path().join("a.txt"), "one\n").expect("write"); + git(&["add", "."]); + git(&["commit", "-q", "-m", "first"]); + std::fs::write(dir.path().join("new.rs"), "fn new() {}\n").expect("write"); + dir + } + + /// **`/review` GOES THROUGH THE OPERATOR'S PROMPT HOOK.** Exit 2 sends + /// nothing to the agent and says why; allowed, the hook's output rides + /// the review turn. + #[test] + fn a_review_refused_by_the_operators_hook_reaches_no_agent() { + for (code, refused) in [(2, true), (0, false)] { + let ws = repo_with_a_change(); + 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 { + user_prompt_submit: vec![operator_hook("checked", "no secrets", code)], + ..crate::hooks::HookConfig::default() + }, + ))); + let ran = crate::cli::review_turn(&mut s, ws.path(), None); + let prompts = seen.lock().expect("seen").prompts.clone(); + if refused { + let why = ran.expect_err("exit 2 did not refuse the review"); + assert!(why.contains("no secrets"), "{why}"); + assert!(prompts.is_empty(), "a refused review reached the agent"); + } else { + assert!(ran.is_ok(), "{ran:?}"); + assert_eq!(prompts.len(), 1, "{prompts:?}"); + assert!( + prompts[0].contains("new.rs") && prompts[0].contains("checked"), + "{}", + prompts[0] + ); + } + } + } + /// **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] diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 0fab8c9..fb5ff24 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1003,23 +1003,8 @@ impl CliApp { } } SlashCommand::Review(base) => { - match crate::review::collect(&workspace, base.as_deref()) { - Ok(change) if change.is_empty() => render::print_info(&format!( - "No changes to review against {}.", - change.base - )), - Ok(change) => { - let ask = crate::review::prompt(&change); - if let Err(e) = one_turn_with_context( - &mut session, - &workspace, - &ask, - Vec::new(), - ) { - render::print_error(&e); - } - } - Err(why) => render::print_error(&why), + if let Err(why) = review_turn(&mut session, &workspace, base.as_deref()) { + render::print_error(&why); } } SlashCommand::Tools(arg) => { @@ -1875,6 +1860,30 @@ pub(crate) fn plan_turn( } } +/// `/review [base]`: the change in `workspace` against `base`, as one turn +/// for the agent. The operator's `user_prompt_submit` hooks see the review +/// prompt first, as they see a typed line: one that refuses it stops it here, +/// and what they print rides the turn. The memory engine is not told it — it +/// is incode's prompt, not the person's line. +/// +/// Called by the REPL's `/review` (`--acp` does not offer it). +pub(crate) fn review_turn( + session: &mut crate::cli::agent_turn::AgentSession, + workspace: &Path, + base: Option<&str>, +) -> Result<(), String> { + let change = crate::review::collect(workspace, base)?; + if change.is_empty() { + render::print_info(&format!("No changes to review against {}.", change.base)); + return Ok(()); + } + let ask = crate::review::prompt(&change); + let context = session.prompt_hooks(&ask).map_err(|why| { + format!("Not sent: the operator's user_prompt_submit hook refused it. {why}") + })?; + one_turn_with_context(session, workspace, &ask, context) +} + /// The turn itself: spinner, streaming, and what the outcome means. fn one_turn_with_context( session: &mut crate::cli::agent_turn::AgentSession, diff --git a/src/cli/run_ledger.rs b/src/cli/run_ledger.rs index ee245d7..53b7bc9 100644 --- a/src/cli/run_ledger.rs +++ b/src/cli/run_ledger.rs @@ -278,10 +278,14 @@ pub(crate) fn run(ctx: &RunContext<'_>, cancel: &CancelToken, watch: Watch<'_>) let worker = worker.showing_edits(Box::new(move |line: &str| { edit_writer.write_text(line); })); + // The operator's hooks, read once for the run: each task's instruction + // goes through their `user_prompt_submit`, on this worker and every lane. + let operator_hooks = crate::hooks::HookRunner::from_settings(); let mut worker = super::run_memory::Remembered::new( worker, crate::hooks::memory::MemoryHooks::new(engine.clone(), workspace, &worker_session), - ); + ) + .with_operator_hooks(operator_hooks.clone()); let mut watcher = RunWatcher { status: &run_status, width: crate::cli::activity::terminal_width(), @@ -341,6 +345,7 @@ pub(crate) fn run(ctx: &RunContext<'_>, cancel: &CancelToken, watch: Watch<'_>) opened: std::sync::atomic::AtomicUsize::new(0), engine, review: crate::parallel::lanes_as_pull_requests(), + operator_hooks, }; let outcome = work( &mut ledger, @@ -579,6 +584,8 @@ pub(crate) struct CliLaneWorkers { /// Lanes are opened as pull requests on GitHub rather than merged here /// (`INCODE_LANES_AS=pr`), read once when the run starts. pub review: bool, + /// The operator's hooks, handed to every lane's worker. + pub operator_hooks: Option, } impl crate::runner::LaneWorkers for CliLaneWorkers { @@ -611,6 +618,7 @@ impl crate::runner::LaneWorkers for CliLaneWorkers { cancel: self.cancel.clone(), lane, engine: self.engine.clone(), + operator_hooks: self.operator_hooks.clone(), })) } } @@ -632,6 +640,8 @@ struct LaneAgent { lane: usize, /// The memory engine its session is filed with, when there is one. engine: Option, + /// The operator's hooks, for each task's instruction. + operator_hooks: Option, } impl crate::runner::TaskWorker for LaneAgent { @@ -692,7 +702,8 @@ impl LaneAgent { let mut worker = super::run_memory::Remembered::new( agent, crate::hooks::memory::MemoryHooks::new(self.engine.clone(), &self.workspace, &session), - ); + ) + .with_operator_hooks(self.operator_hooks.clone()); let report = crate::runner::TaskWorker::work(&mut worker, task); // The conversation this lane opened is on the vendor's side and is @@ -882,6 +893,7 @@ mod tests { opened: std::sync::atomic::AtomicUsize::new(0), engine: None, review: false, + operator_hooks: None, }; let task = crate::ledger::Task::new("t-1", "r-1", "count the files").with_tier("implement"); // The lane's own agent, as `spawn_for` makes it, on a stand-in @@ -902,6 +914,7 @@ mod tests { cancel: lanes.cancel.clone(), lane: lanes.opened.load(std::sync::atomic::Ordering::Relaxed), engine: None, + operator_hooks: None, }; let report = lane.work_on(Box::new(Says("three files")), &task); assert!(report.is_ok(), "{report:?}"); diff --git a/src/cli/run_memory.rs b/src/cli/run_memory.rs index dafd3e6..809c008 100644 --- a/src/cli/run_memory.rs +++ b/src/cli/run_memory.rs @@ -19,6 +19,9 @@ use crate::runner::TaskWorker; pub(crate) struct Remembered { inner: W, memory: MemoryHooks, + /// The operator's hooks; their `user_prompt_submit` sees each task's + /// instruction, as it sees a person's line. + operator_hooks: Option, } impl Remembered { @@ -29,7 +32,19 @@ impl Remembered { // The start block is the engine's context for a person's session; // a task's context is the runner's to assemble, so it is not sent. let _ = memory.start("startup"); - Self { inner, memory } + Self { + inner, + memory, + operator_hooks: None, + } + } + + /// With the operator's hooks: each task's instruction goes through their + /// `user_prompt_submit` before the worker or the engine hears it. Given + /// by `cli::run_ledger` for the run's worker and for every lane's. + pub(crate) fn with_operator_hooks(mut self, hooks: Option) -> Self { + self.operator_hooks = hooks; + self } /// The worker inside. @@ -40,8 +55,30 @@ impl Remembered { impl TaskWorker for Remembered { fn work(&mut self, task: &Task) -> Result { - self.memory - .said(Speaker::Person, &crate::runner::task_instruction(task)); + let instruction = crate::runner::task_instruction(task); + // The operator's `user_prompt_submit` first, as for a person's line: + // one that refuses the instruction fails this attempt before the + // worker or the engine hears it; what they print rides the turn. + if let Some(hooks) = &self.operator_hooks { + let ran = hooks.user_prompt_submit( + &instruction, + self.memory.session(), + Some(self.memory.cwd()), + ); + if ran.is_denied() { + return Err(format!( + "not run: the operator's user_prompt_submit hook refused it. {}", + ran.messages().join("\n") + )); + } + let blocks: Vec = ran + .messages() + .iter() + .map(|said| crate::hooks::prompt_context_block(said)) + .collect(); + self.inner.operator_context(&blocks); + } + self.memory.said(Speaker::Person, &instruction); let report = self.inner.work(task); if let Ok(said) = &report { self.memory.said(Speaker::Agent, said); @@ -152,4 +189,64 @@ mod tests { assert_eq!(fake::calls(dir.path(), "capture"), 1); let _ = worker.inner_mut(); } + + /// Writes down whether it worked and what operator context it was given. + #[derive(Default)] + struct Heard { + worked: usize, + context: Vec, + } + + impl TaskWorker for Heard { + fn work(&mut self, _task: &Task) -> Result { + self.worked += 1; + Ok("done".to_string()) + } + fn operator_context(&mut self, blocks: &[String]) { + self.context = blocks.to_vec(); + } + } + + fn prompt_hook(out: &str, code: i32) -> crate::hooks::HookRunner { + let command = if cfg!(windows) { + format!("echo {out}& exit /b {code}") + } else { + format!("echo '{out}'; exit {code}") + }; + crate::hooks::HookRunner::new(crate::hooks::HookConfig { + user_prompt_submit: vec![command], + ..crate::hooks::HookConfig::default() + }) + } + + /// **A `/run` TASK GOES THROUGH THE OPERATOR'S PROMPT HOOK.** Exit 2 + /// fails the attempt with the reason and the worker never hears the + /// task; otherwise what the hook printed reaches the worker as an + /// `` block for that task's turn. + #[test] + fn a_task_refused_by_the_prompt_hook_is_not_worked_and_an_allowed_one_carries_its_context() { + let dir = tempfile::tempdir().expect("dir"); + let task = Task::new("t-1", "r-1", "do it"); + + let mut refused = Remembered::new(Heard::default(), MemoryHooks::off(dir.path())) + .with_operator_hooks(Some(prompt_hook("no deploys today", 2))); + let why = refused + .work(&task) + .expect_err("exit 2 did not refuse the task"); + assert!(why.contains("no deploys today"), "{why}"); + assert_eq!(refused.inner_mut().worked, 0, "a refused task was worked"); + + let mut allowed = Remembered::new(Heard::default(), MemoryHooks::off(dir.path())) + .with_operator_hooks(Some(prompt_hook("ticket ABC-1", 0))); + assert_eq!(allowed.work(&task).as_deref(), Ok("done")); + let heard = allowed.inner_mut(); + assert_eq!(heard.worked, 1); + assert_eq!(heard.context.len(), 1, "{:?}", heard.context); + assert!( + heard.context[0].starts_with(" &Path { + &self.cwd + } + fn at(&self) -> Conversation<'_> { Conversation { session: &self.session, diff --git a/src/runner.rs b/src/runner.rs index 8db3f84..0c3f3dc 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -714,6 +714,14 @@ pub trait TaskWorker { /// work — a script, a stub, a test — is unaffected. fn brief(&mut self, _handoffs: &[Handoff]) {} + /// What the operator's `user_prompt_submit` hooks printed for the next + /// task's instruction, each an `` block, to ride its turn. + /// Replaced on every call; given by `cli::run_memory::Remembered` just + /// before each `work`. + /// + /// Defaulted to ignoring it, for a worker with no agent turn to add it to. + fn operator_context(&mut self, _blocks: &[String]) {} + /// Who did the last attempt, and what they actually ran on. /// /// Defaulted to the harness itself: a worker that does not delegate is still diff --git a/src/task_run.rs b/src/task_run.rs index 31a5ab0..38fb290 100644 --- a/src/task_run.rs +++ b/src/task_run.rs @@ -145,6 +145,7 @@ impl Report { let line = match event { AgentEvent::Text(text) => json!({"type": "text", "text": text}), AgentEvent::Thinking(text) => json!({"type": "thinking", "text": text}), + AgentEvent::Notice(text) => json!({"type": "notice", "text": text}), AgentEvent::ToolUse { id, name, input } => json!({ "type": "tool_use", "id": id, @@ -966,6 +967,7 @@ fn show( ); } AgentEvent::Quota { status, .. } => outln!(" · quota: {status}"), + AgentEvent::Notice(note) => outln!(" · {note}"), AgentEvent::ToolResult { id, output, diff --git a/src/toolbox/mod.rs b/src/toolbox/mod.rs index 25bbeb5..e35da57 100644 --- a/src/toolbox/mod.rs +++ b/src/toolbox/mod.rs @@ -714,6 +714,22 @@ impl Toolbox { self } + /// The operator's `pre_compact` commands for this toolbox's session, in + /// its workspace: what they printed. Told, never asked. + /// + /// Called by `agent::api::ApiBackend::compact_if_near_window`, before the + /// route compacts on its own (`trigger` `auto`); a `/compact` by hand + /// fires them in `cli::agent_turn::AgentSession::compact` instead. + #[must_use] + pub fn operator_pre_compact(&self, trigger: &str) -> Vec { + self.hooks.as_ref().map_or_else(Vec::new, |hooks| { + hooks + .pre_compact(trigger, "", &self.session, Some(&self.workspace)) + .messages() + .to_vec() + }) + } + /// Offer and run only `names` from now on — narrowed further when a list /// is already in force, never widened. A call to any other tool is refused /// by [`Self::run_call`]'s gate before anything else is asked. diff --git a/src/transcript.rs b/src/transcript.rs index b9ebd35..2583498 100644 --- a/src/transcript.rs +++ b/src/transcript.rs @@ -136,6 +136,7 @@ pub fn line_for(event: &AgentEvent) -> Option { // Reasoning is not the work's record: the reply and the calls are. AgentEvent::TextDelta(_) | AgentEvent::Thinking(_) + | AgentEvent::Notice(_) | AgentEvent::Quota { .. } | AgentEvent::Usage { .. } | AgentEvent::Context { .. } => return None, diff --git a/src/wiring.rs b/src/wiring.rs index 3efe8b1..0a6dcb4 100644 --- a/src/wiring.rs +++ b/src/wiring.rs @@ -119,9 +119,9 @@ pub const DELIBERATELY_UNWIRED: &[(&str, &str)] = &[ "run_on_compact", "The operator's `on_compact` command, kept as configuration with nothing \ to fire it truthfully on the CLI routes: the model CLI compacts its \ - own, inside its own process. (The API route's compaction, \ - `agent::compact`, runs inside the backend, which holds no lifecycle \ - hooks.) The claude CLI's stream \ + own, inside its own process. (The API route's own compaction fires \ + the operator's `pre_compact` hooks instead, through \ + `Toolbox::operator_pre_compact`; those supersede this.) The claude CLI's stream \ does carry a `compact_boundary` system frame (found in the 2.1.283 \ binary, NOT measured live: a compaction needs a full context window), \ which is where this would be wired once it has been seen.",