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 @@ -1334,7 +1334,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. The event is JSON on stdin; exit 2 on a pre-tool command denies; bounded at 10 s |
| `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 |
| `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
9 changes: 9 additions & 0 deletions src/acp_agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1343,6 +1343,15 @@ fn run_prompt(
say_text(&reply);
return Ok(acp::PromptResponse::new(acp::StopReason::EndTurn));
}
crate::cli::TurnPlan::Refused(why) => {
if pictures {
let _ = session.attach_images(Vec::new());
}
say_text(&format!(
"Not sent: the operator's user_prompt_submit hook refused it. {why}"
));
return Ok(acp::PromptResponse::new(acp::StopReason::EndTurn));
}
crate::cli::TurnPlan::Agent {
instruction,
context,
Expand Down
1 change: 1 addition & 0 deletions src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1605,6 +1605,7 @@ mod tests {
desktop_hooks: crate::hooks::HookConfig {
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()],
},
desktop_display: Some("xvfb:1280x800".to_string()),
desktop_limits: crate::desktop::limits::DesktopLimits {
Expand Down
79 changes: 79 additions & 0 deletions src/cli/agent_turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ pub struct AgentSession {
/// Set when the user asks to stop; cleared at the start of each turn so a
/// press at the prompt cannot leak into the next one.
cancel: Option<crate::runtime::cancel::CancelToken>,
/// The operator's own hook commands (`crate::hooks`), for the events this
/// session fires itself — a person's line, before it is sent. The tool
/// events are the toolbox's.
operator_hooks: Option<crate::hooks::HookRunner>,
/// How many turns this session has run.
turns: usize,
/// Directories beyond the workspace this session may reach.
Expand Down Expand Up @@ -236,6 +240,7 @@ impl AgentSession {
checkpoints: CheckpointStore::new(),
snapshot_complete: None,
cancel: None,
operator_hooks: None,
turns: 0,
quota: None,
notices: Vec::new(),
Expand Down Expand Up @@ -566,6 +571,32 @@ impl AgentSession {
}
}

/// The operator's own hook commands for the events this session fires.
pub fn set_operator_hooks(&mut self, hooks: Option<crate::hooks::HookRunner>) {
self.operator_hooks = hooks;
}

/// The operator's `user_prompt_submit` commands for a person's `line`,
/// before anything is sent: the context their stdout adds to the turn, or
/// `Err` with the reason one refused it (exit 2). The line is not changed.
///
/// Called by `cli::plan_turn`, so the REPL and `--acp` run it the same way.
pub fn prompt_hooks(&self, line: &str) -> Result<Vec<String>, String> {
let Some(hooks) = &self.operator_hooks else {
return Ok(Vec::new());
};
let ran =
hooks.user_prompt_submit(line, self.session_id().unwrap_or(""), Some(&self.workspace));
if ran.is_denied() {
return Err(ran.messages().join("\n"));
}
Ok(ran
.messages()
.iter()
.map(|said| crate::hooks::prompt_context_block(said))
.collect())
}

/// The person's line is about to go to the model: written to the session's
/// transcript, and the engine's context for it returned. The first one
/// waits for the session-start first, so the engine hears the session open
Expand Down Expand Up @@ -1904,6 +1935,54 @@ mod tests {
assert_eq!(seen.lock().expect("seen").context, ["BASE"]);
}

/// An operator hook command that prints `out`, writes `why` to stderr and
/// exits with `code`, as the shell runs it.
fn operator_hook(out: &str, why: &str, code: i32) -> String {
if cfg!(windows) {
format!("echo {out}& echo {why} 1>&2& exit /b {code}")
} else {
format!("echo '{out}'; echo '{why}' >&2; exit {code}")
}
}

/// **A REFUSED LINE REACHES NOTHING.** The operator's `user_prompt_submit`
/// hook exits 2: the plan is a refusal with its reason, and the memory
/// engine never hears the line. Allowed, the hook's output rides the turn
/// and the engine does hear it.
#[test]
fn a_prompt_refused_by_the_operators_hook_reaches_neither_engine_nor_agent() {
for (code, refused) in [(2, true), (0, false)] {
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 {
user_prompt_submit: vec![operator_hook("checked", "no secrets", code)],
..crate::hooks::HookConfig::default()
},
)));
let plan = crate::cli::plan_turn(&mut s, ws.path(), "fix it", "fix it");
let heard = fake::spawned(engine.path(), "user-prompt");
if refused {
match plan {
crate::cli::TurnPlan::Refused(why) => assert_eq!(why, "no secrets"),
_ => panic!("exit 2 did not refuse the line"),
}
assert_eq!(heard, 0, "the engine heard a refused line");
} else {
match plan {
crate::cli::TurnPlan::Agent { context, .. } => {
assert!(context.iter().any(|c| c.contains("checked")), "{context:?}")
}
_ => panic!("an allowing hook did not let the line through"),
}
assert_eq!(heard, 1, "the engine did not hear an allowed line");
}
assert!(seen.lock().expect("seen").prompts.is_empty());
}
}

fn start_context(text: &str) -> String {
serde_json::json!({
"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}
Expand Down
31 changes: 27 additions & 4 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,9 @@ pub(crate) fn prepare_session(
.with_standby(standby)
.with_cancel(cancel.clone())
.with_extra_dirs(config.additional_dirs.clone());
// 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());
if !config.additional_dirs.is_empty() {
render::print_info(&format!(
"Also working in {} additional director(ies) — guards and undo cover them.",
Expand Down Expand Up @@ -1743,6 +1746,12 @@ fn run_one_turn(
render::print_assistant(&reply);
Ok(())
}
TurnPlan::Refused(why) => {
render::print_error(&format!(
"Not sent: the operator's user_prompt_submit hook refused it. {why}"
));
Ok(())
}
TurnPlan::Agent {
instruction,
context,
Expand All @@ -1760,6 +1769,9 @@ pub(crate) enum TurnPlan {
NextQuestion(String),
/// A bare greeting, answered here without starting an agent.
Greeting(String),
/// The operator's `user_prompt_submit` hook refused the line: why. Nothing
/// is sent, and the memory engine does not hear it either.
Refused(String),
/// A turn for the agent: what it is asked, and the context that goes
/// before it.
Agent {
Expand Down Expand Up @@ -1789,9 +1801,14 @@ pub(crate) fn plan_turn(
return TurnPlan::NextQuestion(menu);
}
crate::cli::agent_turn::Answered::Ready(instruction) => {
// The answers are the person's line for this turn: the engine
// hears it, and its context for it rides the turn.
let context = session.memory_prompt(&instruction).into_iter().collect();
// The answers are the person's line for this turn: the operator's
// hooks see it first, then the engine hears it, and both their
// contexts ride the turn.
let mut context = match session.prompt_hooks(&instruction) {
Ok(added) => added,
Err(why) => return TurnPlan::Refused(why),
};
context.extend(session.memory_prompt(&instruction));
return TurnPlan::Agent {
instruction,
context,
Expand Down Expand Up @@ -1828,7 +1845,13 @@ pub(crate) fn plan_turn(
// itself: when it answers, incode's own per-turn rules are not fetched as
// well, so the rules are never sent twice. When it does not — no engine,
// or nothing to say — incode's own are.
let mut context = Vec::new();
//
// The operator's `user_prompt_submit` hooks first: one that refuses the
// line stops it here, before the engine or the agent hear it.
let mut context = match session.prompt_hooks(line) {
Ok(added) => added,
Err(why) => return TurnPlan::Refused(why),
};
match session.memory_prompt(line) {
Some(block) => context.push(block),
None => {
Expand Down
2 changes: 2 additions & 0 deletions src/desktop/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1753,6 +1753,7 @@ mod tests {
crate::hooks::HookConfig {
pre_tool_use: vec![deny.to_string()],
post_tool_use: Vec::new(),
user_prompt_submit: Vec::new(),
},
);

Expand Down Expand Up @@ -1789,6 +1790,7 @@ mod tests {
crate::hooks::HookConfig {
pre_tool_use: vec![allow.to_string()],
post_tool_use: Vec::new(),
user_prompt_submit: Vec::new(),
},
);

Expand Down
Loading
Loading