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. `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 |
Expand Down
34 changes: 34 additions & 0 deletions src/acp_agent/worker_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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"]
}
Expand Down
42 changes: 41 additions & 1 deletion src/acp_agent/workers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())),
)]
Expand Down Expand Up @@ -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<Value> = 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());
}
}
}
43 changes: 43 additions & 0 deletions src/agent/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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");
Expand Down
5 changes: 5 additions & 0 deletions src/agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
44 changes: 44 additions & 0 deletions src/agent/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,9 @@ pub struct AgentBackendWorker<B: AgentBackend> {
/// 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<crate::runner::Handoff>,
/// What the operator's `user_prompt_submit` hooks added for the next
/// task (`TaskWorker::operator_context`), sent after its instruction.
operator_context: Vec<String>,
/// 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
Expand Down Expand Up @@ -272,6 +275,7 @@ impl<B: AgentBackend> AgentBackendWorker<B> {
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`.
Expand Down Expand Up @@ -693,6 +697,10 @@ impl<B: AgentBackend> TaskWorker for AgentBackendWorker<B> {
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.
Expand Down Expand Up @@ -833,6 +841,12 @@ impl<B: AgentBackend> TaskWorker for AgentBackendWorker<B> {
};

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.
Expand Down Expand Up @@ -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,
&[
"<operator-hook event=\"UserPromptSubmit\">\nticket ABC-1\n</operator-hook>"
.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
Expand Down
Loading
Loading