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. `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 |
Expand Down
5 changes: 5 additions & 0 deletions src/acp_agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1184,6 +1184,11 @@ fn drive<F: SessionFactory>(
// 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.
Expand Down
2 changes: 2 additions & 0 deletions src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion src/agent/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
71 changes: 71 additions & 0 deletions src/cli/agent_turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
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<String> {
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.
Expand Down Expand Up @@ -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}
Expand Down
8 changes: 8 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 4 additions & 0 deletions src/desktop/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1757,6 +1757,8 @@ mod tests {
pre_compact: Vec::new(),
stop: Vec::new(),
notification: Vec::new(),
session_start: Vec::new(),
session_end: Vec::new(),
},
);

Expand Down Expand Up @@ -1797,6 +1799,8 @@ mod tests {
pre_compact: Vec::new(),
stop: Vec::new(),
notification: Vec::new(),
session_start: Vec::new(),
session_end: Vec::new(),
},
);

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

impl HookConfig {
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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);
}
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()));
Expand Down Expand Up @@ -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()));
Expand Down Expand Up @@ -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<String>) -> HookRunner {
HookRunner::new(HookConfig {
user_prompt_submit: commands,
Expand Down
4 changes: 4 additions & 0 deletions src/runtime/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading