Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1344,7 +1344,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`; 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 a project's `.incode/lifecycle.json` (or the `lifecycle` section of `.incode.json`), whose `on_session_start`/`on_session_end` still run in the REPL — but only once you approve them as they are, since they arrive with whatever was cloned: `incode lifecycle show` lists them, `incode lifecycle approve` approves them, and any change needs approving again. `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 a project's `.incode/lifecycle.json` (or the `lifecycle` section of `.incode.json`), whose `on_session_start`/`on_session_end` still run in the REPL — but only once you approve them as they are, since they arrive with whatever was cloned: `incode lifecycle show` lists them, `incode lifecycle approve` approves them, and any change needs approving again. `subagent_stop` runs when a sub-agent (the `Agent` tool) has finished, told `agent_type` (its definition, role, or `sub-agent`), `task`, `last_assistant_message` and `outcome` (`completed`, `failed` or `cancelled`); it cannot keep it working, and its output is traced, not shown. `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 |
Expand Down
1 change: 1 addition & 0 deletions src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1611,6 +1611,7 @@ mod tests {
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()],
},
desktop_display: Some("xvfb:1280x800".to_string()),
desktop_limits: crate::desktop::limits::DesktopLimits {
Expand Down
2 changes: 2 additions & 0 deletions src/desktop/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1759,6 +1759,7 @@ mod tests {
notification: Vec::new(),
session_start: Vec::new(),
session_end: Vec::new(),
subagent_stop: Vec::new(),
},
);

Expand Down Expand Up @@ -1801,6 +1802,7 @@ mod tests {
notification: Vec::new(),
session_start: Vec::new(),
session_end: Vec::new(),
subagent_stop: Vec::new(),
},
);

Expand Down
84 changes: 84 additions & 0 deletions src/hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,10 @@ pub struct HookConfig {
/// shown where there is still somewhere to show it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub session_end: Vec<String>,
/// 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<String>,
}

impl HookConfig {
Expand All @@ -170,6 +174,7 @@ impl HookConfig {
&& self.notification.is_empty()
&& self.session_start.is_empty()
&& self.session_end.is_empty()
&& self.subagent_stop.is_empty()
}

/// How many commands, over every event. Used where a plugin's hooks are
Expand All @@ -184,6 +189,7 @@ impl HookConfig {
+ self.notification.len()
+ self.session_start.len()
+ self.session_end.len()
+ self.subagent_stop.len()
}

/// `other`'s commands after these, event by event (a plugin's after the
Expand All @@ -197,6 +203,7 @@ impl HookConfig {
self.notification.extend(other.notification);
self.session_start.extend(other.session_start);
self.session_end.extend(other.session_end);
self.subagent_stop.extend(other.subagent_stop);
}
}

Expand Down Expand Up @@ -511,6 +518,47 @@ impl HookRunner {
}
}

impl HookRunner {
/// The `subagent_stop` commands, once a sub-agent has finished: `agent`
/// names it (its definition, role, or `sub-agent`), `task` is what it was
/// handed, `last_message` what it reported, and `outcome` how it ended
/// (`completed`, `failed` or `cancelled`). They cannot keep it working:
/// exit 2 is an ordinary exit. Each one's stdout is a message.
///
/// Called by `toolbox::subagent` (`Toolbox::run_subagent`), the `Agent`
/// tool, on every route.
#[must_use]
pub fn subagent_stop(
&self,
stopped: &SubagentStopped<'_>,
session: &str,
cwd: Option<&Path>,
) -> HookRunResult {
run_event(
&self.config.subagent_stop,
"SubagentStop",
json!({
"agent_type": stopped.agent,
"task": stopped.task,
"last_assistant_message": stopped.last_message,
"outcome": stopped.outcome,
}),
session,
cwd,
false,
)
}
}

/// A sub-agent that has finished, as a `subagent_stop` hook is told it.
#[derive(Debug, Clone, Copy)]
pub struct SubagentStopped<'a> {
pub agent: &'a str,
pub task: &'a str,
pub last_message: &'a str,
pub outcome: &'a str,
}

/// 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,
Expand Down Expand Up @@ -700,6 +748,7 @@ mod tests {
notification: Vec::new(),
session_start: Vec::new(),
session_end: Vec::new(),
subagent_stop: Vec::new(),
});
let input = json!({"path": "a.txt", "content": "hi"});
let ran = runner.pre_tool(&call(&input, dir.path()));
Expand Down Expand Up @@ -729,6 +778,7 @@ mod tests {
notification: Vec::new(),
session_start: Vec::new(),
session_end: Vec::new(),
subagent_stop: Vec::new(),
});
let input = json!({"path": "a.txt"});
let pre = runner.pre_tool(&call(&input, dir.path()));
Expand Down Expand Up @@ -796,6 +846,40 @@ mod tests {
assert_eq!(event["session_id"], "s-1");
}

/// `subagent_stop` is told, never asked: exit 2 keeps nothing working,
/// stdout is a message, and the event says which agent, what it was
/// handed, what it said and how it ended.
#[test]
fn subagent_stop_is_told_who_finished_and_how_and_cannot_refuse() {
let dir = tempfile::tempdir().expect("dir");
let runner = HookRunner::new(HookConfig {
subagent_stop: vec![hook(dir.path(), 2, "")],
..HookConfig::default()
});
let ran = runner.subagent_stop(
&SubagentStopped {
agent: "explore",
task: "find the parser",
last_message: "it is in src/plan.rs",
outcome: "completed",
},
"s-3",
Some(dir.path()),
);
assert!(!ran.is_denied(), "a subagent_stop 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"], "SubagentStop");
assert_eq!(event["agent_type"], "explore");
assert_eq!(event["task"], "find the parser");
assert_eq!(event["last_assistant_message"], "it is in src/plan.rs");
assert_eq!(event["outcome"], "completed");
assert_eq!(event["session_id"], "s-3");
}

/// `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.
Expand Down
1 change: 1 addition & 0 deletions src/toolbox/hook_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ fn hooked(ws: &Path, pre: String, post: Vec<String>) -> Toolbox {
notification: Vec::new(),
session_start: Vec::new(),
session_end: Vec::new(),
subagent_stop: Vec::new(),
},
)))
}
Expand Down
117 changes: 116 additions & 1 deletion src/toolbox/subagent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,30 @@ impl Toolbox {
said.push_str(text);
}
});
let end = self.end_of(&outcome, &said);
if let Some(tap) = tap.as_mut() {
tap.ended(self.end_of(&outcome, &said));
tap.ended(end);
}
// The operator's `subagent_stop` commands: told how it ended, never
// asked whether it may. What they print is traced.
if let Some(hooks) = &self.hooks {
let named = match (definition.as_ref(), role.is_empty()) {
(Some(def), _) => def.name.clone(),
(None, true) => "sub-agent".to_string(),
(None, false) => role.to_string(),
};
let stopped = crate::hooks::SubagentStopped {
agent: &named,
task,
last_message: &said,
outcome: end.as_str(),
};
for told in hooks
.subagent_stop(&stopped, &self.session, Some(&self.workspace))
.messages()
{
crate::trace!("hooks", "subagent_stop hook: {told}");
}
}
// Its work is over however it ended: what it claimed, read and
// announced is let go now, not when a lease runs out.
Expand Down Expand Up @@ -481,6 +503,99 @@ mod tests {
);
}

/// A model service on 127.0.0.1 answering each of `times` requests with
/// `reply` as a whole (not streamed) message: its endpoint.
fn model_service(reply: &'static str, times: usize) -> String {
use std::io::{Read as _, Write as _};
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let port = listener.local_addr().expect("addr").port();
std::thread::spawn(move || {
for stream in listener.incoming().take(times) {
let Ok(mut stream) = stream else { continue };
let mut seen = Vec::new();
let mut buf = [0u8; 8192];
// Headers, then the body its content-length names.
while let Ok(n) = stream.read(&mut buf) {
if n == 0 {
break;
}
seen.extend_from_slice(&buf[..n]);
let text = String::from_utf8_lossy(&seen).to_string();
if let Some(end) = text.find("\r\n\r\n") {
let length = text[..end]
.lines()
.find_map(|l| {
l.to_ascii_lowercase()
.strip_prefix("content-length:")
.map(|v| v.trim().parse::<usize>().unwrap_or(0))
})
.unwrap_or(0);
if seen.len() >= end + 4 + length {
break;
}
}
}
let body = serde_json::json!({
"content": [{"type": "text", "text": reply}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 5, "output_tokens": 7}
})
.to_string();
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\
connection: close\r\n\r\n{body}",
body.len()
);
}
});
format!("http://127.0.0.1:{port}/v1/messages")
}

/// **WHEN A SUB-AGENT FINISHES, THE OPERATOR'S `subagent_stop` IS TOLD**:
/// which agent it was, what it was handed, what it reported and how it
/// ended — run in the workspace, after the real `Agent` tool ran it.
#[test]
fn a_finished_sub_agent_runs_the_operators_subagent_stop_hook() {
let ws = tempfile::tempdir().expect("ws");
let save_event = if cfg!(windows) {
"more > subagent-event.json"
} else {
"cat > subagent-event.json"
};
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()],
..crate::hooks::HookConfig::default()
}),
));
parent.set_api_route(crate::agent::api::Settings {
endpoint: model_service("the parser is in src/plan.rs", 4),
key: "k".to_string(),
model: "m".to_string(),
route: "local".to_string(),
..Default::default()
});
let said = parent
.run_subagent(&serde_json::json!({"task": "find the parser", "role": "explore"}))
.expect("the sub-agent reported");
assert_eq!(said, "the parser is in src/plan.rs");

let event: Value = serde_json::from_str(
&std::fs::read_to_string(ws.path().join("subagent-event.json"))
.expect("the subagent_stop hook did not run"),
)
.expect("one JSON event");
assert_eq!(event["hook_event_name"], "SubagentStop");
assert_eq!(event["agent_type"], "explore");
assert_eq!(event["task"], "find the parser");
assert_eq!(
event["last_assistant_message"],
"the parser is in src/plan.rs"
);
assert_eq!(event["outcome"], "completed");
}

/// A sub-agent never gets a tool its parent was not given: a definition's
/// list is narrowed to the parent's, and with no list it inherits it.
#[test]
Expand Down
Loading