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 @@ -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 |
Expand Down
2 changes: 2 additions & 0 deletions src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
74 changes: 73 additions & 1 deletion src/cli/agent_turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result<String, String>> {
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<String> = 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<String> = 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.
Expand Down Expand Up @@ -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<String> = 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
Expand Down Expand Up @@ -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}
Expand Down
4 changes: 4 additions & 0 deletions src/desktop/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
},
);

Expand Down Expand Up @@ -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(),
},
);

Expand Down
193 changes: 160 additions & 33 deletions src/hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// 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<String>,
/// 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<String>,
}

impl HookConfig {
Expand All @@ -143,6 +152,19 @@ 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()
}

/// 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
Expand All @@ -151,6 +173,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);
}
}

Expand Down Expand Up @@ -359,43 +383,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
Expand Down Expand Up @@ -531,6 +618,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()));
Expand All @@ -555,6 +644,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()));
Expand Down Expand Up @@ -586,6 +677,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<String>) -> HookRunner {
HookRunner::new(HookConfig {
user_prompt_submit: commands,
Expand Down
Loading
Loading