From 4b983c6c83e0bf94e8fb6a01ed8ae0b1bd122541 Mon Sep 17 00:00:00 2001 From: Vipin B Date: Sat, 14 Nov 2026 03:42:56 -0500 Subject: [PATCH 1/3] Add an Auto access mode that uses the agent's own reviewer Claude Code runs with --permission-mode auto and Codex with approvalsReviewer auto_review. Only agents with an auto mode offer it; on others it falls back to the nearest stricter mode they have. Reviews show on the tool call: its glyph becomes a shield tinted by the verdict, with the risk and reason in its tooltip. Codex reports every review; Claude Code only its blocks. --- apps/zgx/src/chat.rs | 16 +++ apps/zgx/ui/ds/activity.luau | 92 +++++++++++---- apps/zgx/ui/ds/composer.luau | 51 ++++++--- apps/zgx/ui/ds/model_picker.luau | 2 +- apps/zgx/ui/locales/en.json | 15 ++- apps/zgx/ui/locales/zh-Hans.json | 15 ++- apps/zgx/ui/screens/chat/composer.luau | 3 + apps/zgx/ui/screens/chat/lane_tab.luau | 3 + apps/zgx/ui/screens/chat/store.luau | 15 +++ apps/zgx/ui/templates/zeron-v2/.base.json | 4 +- .../zeron-v2/screens/chat/composer.luau | 3 + .../zeron-v2/screens/chat/lane_tab.luau | 3 + crates/client/src/demo/transcripts.rs | 1 + crates/client/src/session/mod.rs | 1 + crates/client/src/subagents.rs | 1 + crates/doc/src/parts.rs | 48 +++++++- crates/doc/src/rebuild.rs | 1 + crates/doc/src/schema.rs | 58 ++++++++++ crates/doc/src/transcript_delta.rs | 1 + crates/engine/src/registry.rs | 4 +- crates/engine/src/runner.rs | 1 + crates/engine/src/sessions.rs | 16 +++ crates/engine/tests/e2e.rs | 1 + crates/engine/tests/side_chats.rs | 1 + crates/harness/src/acp/mod.rs | 7 +- crates/harness/src/approval.rs | 4 +- crates/harness/src/claude/mod.rs | 34 +++++- crates/harness/src/claude/normalize.rs | 40 ++++++- crates/harness/src/codex/mod.rs | 59 ++++++++-- crates/harness/src/codex/normalize.rs | 59 +++++++++- crates/harness/src/opencode/mod.rs | 1 + crates/mcp/src/tools.rs | 2 +- crates/mcp/src/transcript.rs | 1 + crates/mobile/src/layout/tests.rs | 2 + crates/proto/src/agent.rs | 105 +++++++++++++++++- crates/ui/src/pickers.rs | 2 +- crates/ui/src/shell/session_lanes.rs | 1 + crates/ui/src/state.rs | 1 + crates/ui/src/todo_panel.rs | 2 + crates/ui/src/transcript.rs | 3 + 40 files changed, 608 insertions(+), 71 deletions(-) diff --git a/apps/zgx/src/chat.rs b/apps/zgx/src/chat.rs index 77a40ee23..7dad220fa 100644 --- a/apps/zgx/src/chat.rs +++ b/apps/zgx/src/chat.rs @@ -1700,6 +1700,11 @@ fn catalog_of(listed: &[Json], by: &HashMap>, done: bool, devi ("mark", Value::from(mark(id).as_str())), // An agent added from the ACP registry draws its own icon. ("icon", h["icon"].as_str().map_or(Value::Nil, Value::from)), + // It has an auto mode of its own: the access picker offers Auto. + ( + "auto", + Value::Bool(h["accessModes"].as_array().is_some_and(|m| m.iter().any(|x| x == "auto"))), + ), ])); for m in list { models.push(model_value(id, m)); @@ -3340,6 +3345,7 @@ fn merged_config(config: &Json, args: &Value) -> Json { match access.as_str() { "supervised" => c["access"] = json!("supervised"), "edits" => c["access"] = json!("auto-accept-edits"), + "auto" => c["access"] = json!("auto"), _ => { if let Some(map) = c.as_object_mut() { map.remove("access"); @@ -5537,6 +5543,15 @@ fn tool_row(part: &Json, live: bool) -> Option { if part["isError"].as_bool() == Some(true) { fields.push(("failed", Value::Bool(true))); } + // Auto's reviewer on it: reviewing, approved, denied or timed-out, its + // risk and why (as the agent's reviewer said). + if let Some(status) = part["review"]["status"].as_str() { + let text = |key: &str| part["review"][key].as_str().filter(|t| !t.trim().is_empty()).map_or(Value::Nil, Value::from); + fields.push(( + "review", + Value::record([("status", Value::from(status)), ("risk", text("risk")), ("reason", text("reason"))]), + )); + } // A subagent's spawn: the doc it runs in (its lane, a panel tab of its // own), how it stands, and its tab's title (the shipping app's). if kind == "agent" @@ -5770,6 +5785,7 @@ fn session_value(chats: &Chats, open: &Open, offline: bool) -> Value { let access = match config["access"].as_str() { Some("supervised") => "supervised", Some("auto-accept-edits") => "edits", + Some("auto") => "auto", _ => "full", }; let fast = fast_in(&config["modelOptions"]); diff --git a/apps/zgx/ui/ds/activity.luau b/apps/zgx/ui/ds/activity.luau index 4ecca2770..29cebb203 100644 --- a/apps/zgx/ui/ds/activity.luau +++ b/apps/zgx/ui/ds/activity.luau @@ -28,6 +28,7 @@ local Markdown = require("@self/markdown") local locale = require("@self/locale") local ReplyPicture = require("@self/reply_picture") local FoldButton = require("@self/fold_button") +local Tooltip = require("@self/tooltip") -- (`cloud`, `git`: a Cloud machine's own setup steps, the machine and its -- checkout.) @@ -52,6 +53,10 @@ export type Tool = { added: number?, removed: number?, failed: boolean?, + -- Auto's reviewer on it (the agent's own: Codex's auto-review, Claude + -- Code's auto mode): "reviewing", "approved", "denied" or "timed-out", + -- its risk ("low" to "critical") and why, as the reviewer said. + review: { status: string, risk: string?, reason: string? }?, -- What its row opens to beyond its call (ds/tool_detail): its output -- (as the harness gave it, escapes and all, growing while it runs), a -- command's exit code, its files' counts, an older doc's diff, and the @@ -587,6 +592,49 @@ local COUNTS: { [string]: boolean } = { edit = true, write = true } -- A row is built often (each comes into view, a long group's thousands), so -- what can't change once a tool has started is read once as it's made (its -- kind, its verb, its glyph); only what a tool's result changes follows it. +-- Auto's reviewer on a call: its glyph becomes a shield in the verdict's +-- hue (let through quiet, stopped in danger's, timed out in warning's), its +-- risk and why in the tooltip. A call no reviewer looked at keeps its own. +local REVIEW_TONE: { [string]: string } = { + reviewing = "$text.tertiary", + approved = "$text.secondary", + denied = "$danger", + ["timed-out"] = "$warning", +} +local function reviewed(now: () -> Tool): () -> boolean + return function(): boolean + return now().review ~= nil + end +end +local function review_glyph(now: () -> Tool, size: number): Node + local function review(): any + return now().review + end + return ui.div { + color = function(): string + local r = review() + return if r then REVIEW_TONE[r.status] or "$text.secondary" else "$text.secondary" + end, + tooltip = Tooltip { + function(): string + local r = review() + if not r then + return "" + end + local lines = { locale.s(`ds.activity.review.{r.status}`), locale.s(`ds.activity.review.{r.status}_hint`) } + if r.risk then + table.insert(lines, locale.s("ds.activity.review.risk", { risk = r.risk })) + end + if r.reason then + table.insert(lines, r.reason) + end + return table.concat(lines, "\n") + end, + }, + Icon { name = "shield-check", size = size }, + } +end + local function row( now: () -> Tool, below: () -> boolean, @@ -704,25 +752,29 @@ local function row( end, -- (A row before the group's last never runs: its glyph alone, placed -- and coloured itself. The last may be the one in flight.) - if settled - then Icon { - name = GLYPH[t.kind], - size = GLYPH_SIZE, - absolute = true, - left = GLYPH_LEFT, - top = (ROW - GLYPH_SIZE) / 2, - color = tint, - } - else ui.div { - absolute = true, - left = GLYPH_LEFT, - top = (ROW - GLYPH_SIZE) / 2, - color = tint, - ui.show(running, status.StatusIcon { kind = "working", size = GLYPH_SIZE }, Icon { - name = GLYPH[t.kind], - size = GLYPH_SIZE, - }), - }, + -- Its glyph, in a box of its own off the line (what shows in it + -- never moves the line): Auto's reviewer looked at it, a shield in + -- the glyph's place. + ui.div { + absolute = true, + left = GLYPH_LEFT, + top = (ROW - GLYPH_SIZE) / 2, + w = GLYPH_SIZE, + h = GLYPH_SIZE, + ui.show( + reviewed(now), + review_glyph(now, GLYPH_SIZE), + ui.div { + color = tint, + if settled + then Icon { name = GLYPH[t.kind], size = GLYPH_SIZE } + else ui.show(running, status.StatusIcon { kind = "working", size = GLYPH_SIZE }, Icon { + name = GLYPH[t.kind], + size = GLYPH_SIZE, + }), + } + ), + }, ui.row { pl = ui.raw(GUTTER, "past the tree's gutter"), grow = 1, @@ -799,6 +851,8 @@ local function row( } end + + return ui.component(function(props: Props): Node local live = props.live or function() return false diff --git a/apps/zgx/ui/ds/composer.luau b/apps/zgx/ui/ds/composer.luau index 7b876dd88..7e003b82f 100644 --- a/apps/zgx/ui/ds/composer.luau +++ b/apps/zgx/ui/ds/composer.luau @@ -123,9 +123,12 @@ export type Props = { -- A turn is running: Send becomes Stop while the draft is empty, and -- queues what is typed. running: State?, - -- What the agent may do unasked: "supervised", "edits" or "full"; and - -- plan mode (explore and propose before changing anything). + -- What the agent may do unasked: "supervised", "edits", "auto" or + -- "full"; and plan mode (explore and propose before changing anything). access: State?, + -- The chat's agent has an auto mode of its own (Claude Code's, Codex's + -- auto-review): the picker offers Auto. + access_auto: (() -> boolean)?, plan: State?, -- The model (a ModelPicker: its agents' tabs, its models, its reasoning, -- Fast mode and its other options' picks). @@ -362,23 +365,32 @@ end -- The access modes, as Zeron offers them; their icons (Central Icons, -- centralicons.com, round outlined, radius 2, stroke 1.5) say what each -- does: it waits for you (a raised hand), edits go through (a pencil with --- sparkles), nothing is held back (an open padlock). (Made as they're --- read, in the locale's words.) -local function ACCESS(): { Dropdown.Item } - return { - worded({ value = "supervised", icon = "access-supervised" }, { - label = "ds.composer.access.supervised", - description = "ds.composer.access.supervised_hint", - }), - worded({ value = "edits", icon = "access-edits" }, { - label = "ds.composer.access.edits", - description = "ds.composer.access.edits_hint", - }), - worded({ value = "full", icon = "access-full" }, { +-- sparkles), the agent's reviewer vets each action (a shield), nothing is +-- held back (an open padlock). Auto only where the agent has one (`auto`), +-- or while it's the mode chosen. (Made as they're read, in the locale's +-- words.) +local function ACCESS(auto: boolean): { Dropdown.Item } + local items = { + worded({ value = "supervised", icon = "access-supervised" }, { + label = "ds.composer.access.supervised", + description = "ds.composer.access.supervised_hint", + }), + worded({ value = "edits", icon = "access-edits" }, { + label = "ds.composer.access.edits", + description = "ds.composer.access.edits_hint", + }), + } + if auto then + table.insert(items, worded({ value = "auto", icon = "shield-check" }, { + label = "ds.composer.access.auto", + description = "ds.composer.access.auto_hint", + })) + end + table.insert(items, worded({ value = "full", icon = "access-full" }, { label = "ds.composer.access.full", description = "ds.composer.access.full_hint", - }), - } + })) + return items end -- Plan mode's row at the access panel's foot: an item's shape, its icon on @@ -1418,7 +1430,10 @@ return ui.component(function(props: Props): Node end else nil, value = props.access, - items = ACCESS, + items = function(): { Dropdown.Item } + local chosen = props.access and props.access:get() + return ACCESS(chosen == "auto" or (props.access_auto ~= nil and props.access_auto())) + end, tone = "chip", label = locale.t("ds.composer.access.label") :: any, search = false, diff --git a/apps/zgx/ui/ds/model_picker.luau b/apps/zgx/ui/ds/model_picker.luau index fee67e5d1..22d6ca993 100644 --- a/apps/zgx/ui/ds/model_picker.luau +++ b/apps/zgx/ui/ds/model_picker.luau @@ -31,7 +31,7 @@ local locale = require("@self/locale") -- An agent: a tab of its own. -- (`icon`: an agent from the ACP registry's one-ink SVG, in its mark's -- place.) -export type Harness = { id: string, label: string, mark: Mark.Name, icon: string? } +export type Harness = { id: string, label: string, mark: Mark.Name, icon: string?, auto: boolean? } -- One of a model option's choices. export type Choice = { id: string, label: string } -- An option of a model (Devin Fusion's lead and sidekick): its choices and diff --git a/apps/zgx/ui/locales/en.json b/apps/zgx/ui/locales/en.json index ca649afdb..785f9a27b 100644 --- a/apps/zgx/ui/locales/en.json +++ b/apps/zgx/ui/locales/en.json @@ -590,6 +590,8 @@ "supervised_hint": "Ask before commands and file changes.", "edits": "Auto-accept edits", "edits_hint": "Apply edits, ask before other actions.", + "auto": "Auto", + "auto_hint": "The agent's reviewer approves safe actions; risky ones ask.", "full": "Full access", "full_hint": "Run commands and edits without asking." }, @@ -718,7 +720,18 @@ "show_all_lines": "Show all {n} lines", "open_subagent": "Open subagent {title}", "subagent": "Subagent", - "worked_for": "Worked for {secs}s · {summary}" + "worked_for": "Worked for {secs}s · {summary}", + "review": { + "reviewing": "Reviewing…", + "approved": "Auto-approved", + "denied": "Blocked by auto-review", + "timed-out": "Review timed out", + "reviewing_hint": "The agent's reviewer is checking this before it runs.", + "approved_hint": "The agent's reviewer judged this safe and let it run.", + "denied_hint": "The agent's reviewer stopped this. It didn't run.", + "timed-out_hint": "The agent's reviewer didn't decide in time, so this didn't run.", + "risk": "Risk: {risk}" + } }, "transcript": { "copy_message": "Copy message", diff --git a/apps/zgx/ui/locales/zh-Hans.json b/apps/zgx/ui/locales/zh-Hans.json index bd31e2390..f983f4087 100644 --- a/apps/zgx/ui/locales/zh-Hans.json +++ b/apps/zgx/ui/locales/zh-Hans.json @@ -590,6 +590,8 @@ "supervised_hint": "运行命令和更改文件前先询问。", "edits": "自动接受编辑", "edits_hint": "应用编辑,执行其他操作前先询问。", + "auto": "自动", + "auto_hint": "由智能体自己的审查判断:安全的操作直接执行,有风险的会询问你。", "full": "完全访问", "full_hint": "运行命令和编辑时不询问。" }, @@ -718,7 +720,18 @@ "show_all_lines": "显示全部 {n} 行", "open_subagent": "打开子智能体 {title}", "subagent": "子智能体", - "worked_for": "运行了 {secs} 秒 · {summary}" + "worked_for": "运行了 {secs} 秒 · {summary}", + "review": { + "reviewing": "审查中…", + "approved": "已自动批准", + "denied": "已被自动审查拦截", + "timed-out": "审查超时", + "reviewing_hint": "智能体的审查正在检查此操作,之后才会执行。", + "approved_hint": "智能体的审查判断此操作安全,已允许执行。", + "denied_hint": "智能体的审查拦截了此操作,它没有执行。", + "timed-out_hint": "智能体的审查未能及时做出判断,此操作没有执行。", + "risk": "风险:{risk}" + } }, "transcript": { "copy_message": "拷贝消息", diff --git a/apps/zgx/ui/screens/chat/composer.luau b/apps/zgx/ui/screens/chat/composer.luau index 10038a95a..7979b1eac 100644 --- a/apps/zgx/ui/screens/chat/composer.luau +++ b/apps/zgx/ui/screens/chat/composer.luau @@ -1214,6 +1214,9 @@ local function Composer(): Node menus_below = shown_new, running = running, access = access, + access_auto = function(): boolean + return store.offers_auto(model:get()) + end, plan = plan, model = model, effort = effort, diff --git a/apps/zgx/ui/screens/chat/lane_tab.luau b/apps/zgx/ui/screens/chat/lane_tab.luau index 9dae81e70..f98bcc328 100644 --- a/apps/zgx/ui/screens/chat/lane_tab.luau +++ b/apps/zgx/ui/screens/chat/lane_tab.luau @@ -697,6 +697,9 @@ local function composer(chat: string, view: any, name: string, focus: State/") runs on has an auto mode of +-- its own (the catalog's `auto`): the access picker offers Auto. +function M.offers_auto(model: string?): boolean + if not model then + return false + end + local harness = string.match(model, "^([^/]+)/") + for _, h in (M.catalog:get() :: any).harnesses do + if h.id == harness then + return h.auto == true + end + end + return false +end -- A call nothing waits on: its failure lands in the session's notice (the -- host sets it), so the script needn't hear it. local function quietly(p: any) diff --git a/apps/zgx/ui/templates/zeron-v2/.base.json b/apps/zgx/ui/templates/zeron-v2/.base.json index a29cc3f9f..9f28e1fc7 100644 --- a/apps/zgx/ui/templates/zeron-v2/.base.json +++ b/apps/zgx/ui/templates/zeron-v2/.base.json @@ -1,8 +1,8 @@ { "ds/sidebar.luau": "f2abf7b60b5f4d00", "ds/tokens.luau": "296d1ea72675de0c", - "screens/chat/composer.luau": "9c0c79de53eae373", - "screens/chat/lane_tab.luau": "12c199c168515f49", + "screens/chat/composer.luau": "5a4b142a88915b87", + "screens/chat/lane_tab.luau": "43f35502c5d8818d", "screens/panel/init.luau": "3d5e0c712c4dda56", "screens/shell/init.luau": "c7b26c3a1ccf9a32", "screens/shell/page.luau": "c1debbce640a5d45", diff --git a/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau b/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau index d6cf62303..0a8589c60 100644 --- a/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau +++ b/apps/zgx/ui/templates/zeron-v2/screens/chat/composer.luau @@ -1212,6 +1212,9 @@ local function Composer(): Node menus_below = shown_new, running = running, access = access, + access_auto = function(): boolean + return store.offers_auto(model:get()) + end, plan = plan, model = model, effort = effort, diff --git a/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau b/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau index f4e3e08bf..4e963de97 100644 --- a/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau +++ b/apps/zgx/ui/templates/zeron-v2/screens/chat/lane_tab.luau @@ -478,6 +478,9 @@ local function composer(chat: string, view: any, name: string, focus: State bool { exit_code: None, output_truncated: false, output_lines: None, + review: None, }], created_at: created_at + 1, device_id: String::new(), diff --git a/crates/client/src/subagents.rs b/crates/client/src/subagents.rs index 4a5c762cb..8f5bb6e33 100644 --- a/crates/client/src/subagents.rs +++ b/crates/client/src/subagents.rs @@ -289,6 +289,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, } } diff --git a/crates/doc/src/parts.rs b/crates/doc/src/parts.rs index 64449be33..c29fc07ea 100644 --- a/crates/doc/src/parts.rs +++ b/crates/doc/src/parts.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; -use zeron_proto::{ +use zeron_proto::{ToolReview, AgentEvent, SUBAGENT_INPUT_KEEP, ToolCall, ToolDiff, UserInputAnswer, UserInputQuestion, }; @@ -321,6 +321,10 @@ pub enum MessagePart { /// is read from the host. #[serde(default, skip_serializing_if = "Option::is_none")] output_lines: Option, + /// The agent's own reviewer on this call, in Auto: reviewing it, or + /// its verdict (approved, denied, timed out) with its risk and why. + #[serde(default, skip_serializing_if = "Option::is_none")] + review: Option, }, #[serde(rename_all = "camelCase")] Input { @@ -539,9 +543,25 @@ pub fn fold_event_into_parts(out: &mut Vec, event: &AgentEvent) { exit_code: None, output_truncated: false, output_lines: None, + review: None, }); } } + AgentEvent::ToolReviewed { id, review } => { + // (A review names a call already shown; one for a call that + // isn't, a network check with no call, has nowhere to go.) + for p in out.iter_mut() { + if let MessagePart::Tool { + id: pid, + review: slot, + .. + } = p + && pid == id + { + *slot = Some(review.clone()); + } + } + } AgentEvent::ToolResult { id, is_error, @@ -942,6 +962,31 @@ pub fn join_continuations(entries: Vec>) -> Vec { mod tests { use super::*; + #[test] + fn a_review_folds_onto_its_call_and_a_later_one_replaces_it() { + use zeron_proto::ToolReviewStatus; + let mut parts = Vec::new(); + fold_event_into_parts(&mut parts, &AgentEvent::ToolCall { id: "c1".into(), call: ToolCall::Exec { command: "rm -rf x".into() } }); + let review = |status| AgentEvent::ToolReviewed { + id: "c1".into(), + review: ToolReview { status, risk: Some("high".into()), reason: Some("outside the workspace".into()) }, + }; + fold_event_into_parts(&mut parts, &review(ToolReviewStatus::Reviewing)); + fold_event_into_parts(&mut parts, &review(ToolReviewStatus::Denied)); + // One for a call that isn't shown changes nothing. + fold_event_into_parts(&mut parts, &AgentEvent::ToolReviewed { + id: "elsewhere".into(), + review: ToolReview { status: ToolReviewStatus::Approved, risk: None, reason: None }, + }); + match &parts[..] { + [MessagePart::Tool { review: Some(r), .. }] => { + assert_eq!(r.status, ToolReviewStatus::Denied); + assert_eq!(r.reason.as_deref(), Some("outside the workspace")); + } + other => panic!("{other:?}"), + } + } + fn text_delta(s: &str) -> AgentEvent { AgentEvent::TextDelta { text: s.into() } } @@ -1346,6 +1391,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }, ]; let chunks = split_parts(&parts); diff --git a/crates/doc/src/rebuild.rs b/crates/doc/src/rebuild.rs index 177147d7f..b79f6ed94 100644 --- a/crates/doc/src/rebuild.rs +++ b/crates/doc/src/rebuild.rs @@ -187,6 +187,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }, ], created_at: 5, diff --git a/crates/doc/src/schema.rs b/crates/doc/src/schema.rs index 66f854351..58014384c 100644 --- a/crates/doc/src/schema.rs +++ b/crates/doc/src/schema.rs @@ -159,6 +159,9 @@ struct DocPartJson { /// `outputTruncated`). #[serde(default, skip_serializing_if = "Option::is_none")] output_lines: Option, + /// The agent's own reviewer's verdict on the call (additive; Auto). + #[serde(default, skip_serializing_if = "Option::is_none")] + review: Option, } /// App parts → doc part json (mirror of `toDocParts`). @@ -215,6 +218,7 @@ fn to_doc_part(part: &MessagePart) -> Result { exit_code, output_truncated, output_lines, + review, } => DocPartJson { id: id.clone(), kind: "tool".into(), @@ -242,6 +246,7 @@ fn to_doc_part(part: &MessagePart) -> Result { exit_code: *exit_code, output_truncated: output_truncated.then_some(true), output_lines: *output_lines, + review: review.as_ref().map(serde_json::to_value).transpose()?, ..Default::default() }, MessagePart::Input { @@ -332,6 +337,7 @@ fn from_doc_part(p: DocPartJson) -> MessagePart { exit_code: p.exit_code, output_truncated: p.output_truncated.unwrap_or(false), output_lines: p.output_lines, + review: p.review.and_then(|value| serde_json::from_value(value).ok()), }, None => MessagePart::Text { id: p.id, @@ -1626,6 +1632,9 @@ fn push_part(parts: &LoroList, part: &MessagePart) -> Result<(), DocError> { if let Some(lines) = doc_part.output_lines { map.insert("outputLines", lines as i64)?; } + if let Some(review) = &doc_part.review { + map.insert("review", loro_value_from_json(review))?; + } Ok(()) } @@ -1803,6 +1812,9 @@ fn salvage_part(part: &serde_json::Value, entry_id: &str, ix: usize) -> Option Result<(), DocError> if let Some(lines) = doc_part.output_lines { map.insert("outputLines", lines as i64)?; } + if let Some(review) = &doc_part.review { + map.insert("review", loro_value_from_json(review))?; + } if let Some(text) = &doc_part.text { // Defensive path only — the fold never rewrites earlier text. if let Some(loro::ValueOrContainer::Container(loro::Container::Text(t))) = map.get("text") { @@ -2904,6 +2919,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }; let doc = SessionDoc::init("c1").unwrap(); let mut w = SegmentWriter::begin(&doc, "e1", "dev", 1).unwrap(); @@ -2972,6 +2988,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }; w.sync(std::slice::from_ref(&part)).unwrap(); if let MessagePart::Tool { @@ -3028,6 +3045,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }; let parts = vec![ tool( @@ -3503,6 +3521,45 @@ mod tests { )); } + /// A reviewer's verdict lands after its call was written: the call's + /// entry takes it in place, and a later verdict replaces the first. + #[test] + fn a_review_round_trips_through_the_doc() { + use zeron_proto::{ToolReview, ToolReviewStatus}; + let doc = SessionDoc::init("chat-5").unwrap(); + let mut writer = SegmentWriter::begin(&doc, "a1", "dev-a", 5).unwrap(); + let mut folded = Vec::new(); + fold_event_into_parts( + &mut folded, + &AgentEvent::ToolCall { id: "c1".into(), call: ToolCall::Exec { command: "rm -rf ~/x".into() } }, + ); + writer.sync(&folded).unwrap(); + for status in [ToolReviewStatus::Reviewing, ToolReviewStatus::Denied] { + fold_event_into_parts( + &mut folded, + &AgentEvent::ToolReviewed { + id: "c1".into(), + review: ToolReview { status, risk: Some("high".into()), reason: Some("outside the workspace".into()) }, + }, + ); + writer.sync(&folded).unwrap(); + } + writer.finish(&folded, MessageStatus::Complete).unwrap(); + let snapshot = doc.export_snapshot().unwrap(); + let replica = loro::LoroDoc::new(); + replica.import(&snapshot).unwrap(); + for entries in [doc.read_entries().unwrap(), SessionDoc::from_doc(replica).read_entries().unwrap()] { + match &entries[0].parts[0] { + MessagePart::Tool { review: Some(review), .. } => { + assert_eq!(review.status, ToolReviewStatus::Denied); + assert_eq!(review.risk.as_deref(), Some("high")); + assert_eq!(review.reason.as_deref(), Some("outside the workspace")); + } + other => panic!("unexpected {other:?}"), + } + } + } + /// Old pre-strip docs carry inline `output`/`diff` — they must still read /// back (schema changes are serde-additive ONLY; old readers, old docs). #[test] @@ -3535,6 +3592,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }], created_at: 1, device_id: "dev-a".into(), diff --git a/crates/doc/src/transcript_delta.rs b/crates/doc/src/transcript_delta.rs index bd5d4f1ba..6b0570f41 100644 --- a/crates/doc/src/transcript_delta.rs +++ b/crates/doc/src/transcript_delta.rs @@ -903,6 +903,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, preview_paths: Vec::new(), } } diff --git a/crates/engine/src/registry.rs b/crates/engine/src/registry.rs index 243848e35..04f6207c9 100644 --- a/crates/engine/src/registry.rs +++ b/crates/engine/src/registry.rs @@ -916,7 +916,7 @@ fn full_registry() -> HarnessRegistry { installed: true, can_install: false, enabled: None, - access_modes: AccessMode::ALL.to_vec(), + access_modes: AccessMode::WITH_AUTO.to_vec(), supports_plan: true, }, Box::new(|| zeron_harness::ClaudeHarness::new().installed()), @@ -947,7 +947,7 @@ fn full_registry() -> HarnessRegistry { installed: true, can_install: false, enabled: None, - access_modes: AccessMode::ALL.to_vec(), + access_modes: AccessMode::WITH_AUTO.to_vec(), supports_plan: true, }, Box::new(|| zeron_harness::CodexHarness::new().installed()), diff --git a/crates/engine/src/runner.rs b/crates/engine/src/runner.rs index 657a845f8..c1427296f 100644 --- a/crates/engine/src/runner.rs +++ b/crates/engine/src/runner.rs @@ -493,6 +493,7 @@ fn setup_parts( exit_code: None, output_truncated: false, output_lines: None, + review: None, } }) .collect() diff --git a/crates/engine/src/sessions.rs b/crates/engine/src/sessions.rs index 6f5f098d1..3ad60b27c 100644 --- a/crates/engine/src/sessions.rs +++ b/crates/engine/src/sessions.rs @@ -3947,6 +3947,15 @@ fn subagent_chip_update(event: &AgentEvent) -> Option<&'static str> { } } +/// A reviewer's reason as the doc keeps it: its first 600 characters. +fn cap_review_reason(why: &str) -> String { + const MAX: usize = 600; + match why.char_indices().nth(MAX) { + Some((at, _)) => format!("{}…", why[..at].trim_end()), + None => why.to_owned(), + } +} + /// Apply the render-parts privacy policy: strip heavy/sensitive tool inputs before doc /// entry. Full inputs live only in the local run journal. fn render_parts(parts: &[MessagePart]) -> Vec { @@ -3971,6 +3980,7 @@ fn render_parts(parts: &[MessagePart]) -> Vec { exit_code, output_truncated, output_lines, + review, } => MessagePart::Tool { id: id.clone(), call: sanitize_tool_call(call), @@ -3993,6 +4003,12 @@ fn render_parts(parts: &[MessagePart]) -> Vec { exit_code: *exit_code, output_truncated: *output_truncated, output_lines: *output_lines, + // The reviewer's verdict stays: it's what the person needs to + // see. Its reason is bounded, as an output summary is. + review: review.as_ref().map(|r| zeron_proto::ToolReview { + reason: r.reason.as_deref().map(|why| cap_review_reason(why)), + ..r.clone() + }), }, other => other.clone(), }) diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs index 4741290df..9c27707ca 100644 --- a/crates/engine/tests/e2e.rs +++ b/crates/engine/tests/e2e.rs @@ -1342,6 +1342,7 @@ fn spawn_chip(id: &str, status: SubagentStatus) -> MessagePart { exit_code: None, output_truncated: false, output_lines: None, + review: None, } } diff --git a/crates/engine/tests/side_chats.rs b/crates/engine/tests/side_chats.rs index 7b1ab535e..835bf66b6 100644 --- a/crates/engine/tests/side_chats.rs +++ b/crates/engine/tests/side_chats.rs @@ -438,6 +438,7 @@ async fn a_fork_settles_the_running_subagent_chips_it_copies() { exit_code: None, output_truncated: false, output_lines: None, + review: None, }; core.doc_host .open("main") diff --git a/crates/harness/src/acp/mod.rs b/crates/harness/src/acp/mod.rs index a2e0d9a91..d775d5677 100644 --- a/crates/harness/src/acp/mod.rs +++ b/crates/harness/src/acp/mod.rs @@ -1719,12 +1719,13 @@ impl AcpHarness { } /// The access mode `request` runs with: its own when this agent honors - /// it, else full access — as is any auto-approve run. + /// it, else as [`AccessMode::honored_by`] falls back — full access, but + /// never for Auto — and full access for any auto-approve run. fn access_for(&self, request: &RunRequest) -> AccessMode { - if request.auto_approve || !self.spec.access_modes.contains(&request.access) { + if request.auto_approve { AccessMode::FullAccess } else { - request.access + request.access.honored_by(self.spec.access_modes) } } diff --git a/crates/harness/src/approval.rs b/crates/harness/src/approval.rs index 920ac2fc6..6dcb17eb9 100644 --- a/crates/harness/src/approval.rs +++ b/crates/harness/src/approval.rs @@ -21,7 +21,9 @@ pub fn allowed_without_asking(access: AccessMode, action: Action) -> bool { match access { AccessMode::FullAccess => true, AccessMode::AutoAcceptEdits => action == Action::Edit, - AccessMode::Supervised => false, + // The agent's reviewer already let through what it judged safe: + // what reaches Zeron is what it escalated, so it's asked. + AccessMode::Auto | AccessMode::Supervised => false, } } diff --git a/crates/harness/src/claude/mod.rs b/crates/harness/src/claude/mod.rs index 41b4cc9c6..56347cebc 100644 --- a/crates/harness/src/claude/mod.rs +++ b/crates/harness/src/claude/mod.rs @@ -291,6 +291,9 @@ fn access_permission_mode(request: &RunRequest) -> &'static str { } match request.access { AccessMode::AutoAcceptEdits => "acceptEdits", + // The CLI's classifier decides; what it escalates comes as + // `can_use_tool`, and is asked. + AccessMode::Auto => "auto", AccessMode::Supervised | AccessMode::FullAccess => "default", } } @@ -309,9 +312,12 @@ fn permission_mode(request: &RunRequest) -> &'static str { fn strictness(mode: &str) -> u8 { match mode { "bypassPermissions" => 0, - "acceptEdits" => 1, - "default" => 2, - _ => 3, // plan + // (Its reviewer lets through more than acceptEdits does: commands + // it judges safe.) + "auto" => 1, + "acceptEdits" => 2, + "default" => 3, + _ => 4, // plan } } @@ -881,7 +887,7 @@ impl Harness for ClaudeHarness { && strictness(permission_mode(next)) <= strictness(permission_mode(live)) } fn access_modes(&self) -> &[AccessMode] { - &AccessMode::ALL + &AccessMode::WITH_AUTO } /// The CLI's own plan mode; approving `ExitPlanMode` ends it. fn supports_plan(&self) -> bool { @@ -1619,6 +1625,14 @@ async fn run_session(session: Session) { stdin.replay = None; } for ev in events { + // A refusal is Auto's reviewer's only in Auto; in + // another mode it was a rule's, and the failed call + // says enough. + if matches!(ev, AgentEvent::ToolReviewed { .. }) + && access(&config) != AccessMode::Auto + { + continue; + } match &ev { AgentEvent::ToolCall { id, .. } => { open_tools.insert(id.clone()); @@ -2430,7 +2444,7 @@ mod access_tests { #[test] fn modes_launch_with_their_permission_mode() { use AccessMode::*; - let cases: [(AccessMode, bool, bool, &[&str]); 8] = [ + let cases: [(AccessMode, bool, bool, &[&str]); 10] = [ // Full access launches exactly as before modes. ( FullAccess, @@ -2475,6 +2489,9 @@ mod access_tests { ), (AutoAcceptEdits, false, true, &["--permission-mode", "plan"]), (Supervised, false, true, &["--permission-mode", "plan"]), + // Auto is the CLI's own auto mode. + (Auto, false, false, &["--permission-mode", "auto"]), + (Auto, false, true, &["--permission-mode", "plan"]), ]; for (access, auto_approve, plan, expected) in cases { assert_eq!( @@ -2507,6 +2524,11 @@ mod access_tests { let auto_edits = request(AutoAcceptEdits, false, false); assert!(harness.reconfigures_in_place(&supervised, &auto_edits)); assert!(!harness.reconfigures_in_place(&auto_edits, &supervised)); + // Auto lets through more than auto-accept edits: switching to it is + // in place, and back from it relaunches. + let auto_mode = request(Auto, false, false); + assert!(harness.reconfigures_in_place(&auto_edits, &auto_mode)); + assert!(!harness.reconfigures_in_place(&auto_mode, &auto_edits)); let auto_planning = request(FullAccess, true, true); let auto = request(FullAccess, true, false); assert!(harness.reconfigures_in_place(&auto_planning, &auto)); @@ -2514,7 +2536,7 @@ mod access_tests { assert!(!harness.reconfigures_in_place(&full, &auto)); // Under `auto_approve` the mode changes nothing. assert!(harness.same_runtime(&auto, &request(Supervised, true, false))); - assert_eq!(harness.access_modes(), &AccessMode::ALL); + assert_eq!(harness.access_modes(), &AccessMode::WITH_AUTO); assert!(harness.supports_plan()); } diff --git a/crates/harness/src/claude/normalize.rs b/crates/harness/src/claude/normalize.rs index 1908e969b..6c7e1e881 100644 --- a/crates/harness/src/claude/normalize.rs +++ b/crates/harness/src/claude/normalize.rs @@ -2,7 +2,7 @@ //! decoding, error-code mapping). use serde_json::Value; -use zeron_proto::{AgentEvent, DoneStatus, HarnessId, TodoItem, TodoStatus, ToolCall}; +use zeron_proto::{AgentEvent, DoneStatus, HarnessId, TodoItem, TodoStatus, ToolCall, ToolReview, ToolReviewStatus}; use super::wire::{ContentBlock, Frame, MessageFrame, ResultFrame}; @@ -394,6 +394,16 @@ fn tool_result( } } +/// The CLI refused the call: "Permission to use Bash has been denied." (in +/// auto mode, its classifier's block). Not don't-ask mode's refusal, which +/// no reviewer made. +fn permission_denied(text: &str) -> bool { + let first = text.lines().next().unwrap_or_default(); + first.starts_with("Permission to use ") + && first.contains(" has been denied") + && !first.contains("don't ask mode") +} + /// A `tool_result`'s text: its string, or its text blocks joined. fn result_text(content: &Value) -> String { match content { @@ -712,6 +722,7 @@ impl Normalizer { clear_inline_skills: bool, ) -> Vec { let mut pending = Vec::new(); + let mut denials = Vec::new(); for block in frame.message.blocks() { if block.kind != "tool_result" { continue; @@ -724,8 +735,21 @@ impl Normalizer { .remove(&block.tool_use_id) .unwrap_or_else(|| "image.png".into()); let images = images_in_content(Some(&block.content), &name); + let denied = block.is_error.unwrap_or(false) && permission_denied(&result_text(&block.content)); let event = tool_result(&block, &mut self.command_calls); pending.push((event, name, images)); + // A denial is the reviewer's when the run is in Auto (the run + // keeps it only then: `ClaudeHarness`'s run loop). + if denied { + denials.push(AgentEvent::ToolReviewed { + id: block.tool_use_id.clone(), + review: ToolReview { + status: ToolReviewStatus::Denied, + risk: None, + reason: None, + }, + }); + } } if pending.len() == 1 && pending[0].2.is_empty() { let name = pending[0].1.clone(); @@ -733,7 +757,7 @@ impl Normalizer { pending[0].2.push(image); } } - pending + let mut events: Vec = pending .into_iter() .map(|(mut event, _name, images)| { if let AgentEvent::ToolResult { image_payloads, .. } = &mut event { @@ -741,7 +765,9 @@ impl Normalizer { } event }) - .collect() + .collect(); + events.append(&mut denials); + events } /// The CLI reported its session (`system:init`). @@ -1623,6 +1649,14 @@ impl Normalizer { #[cfg(test)] mod tests { use super::*; + + #[test] + fn a_refused_call_is_marked_denied() { + assert!(permission_denied("Permission to use Bash has been denied. If you believe this block is wrong, ask.")); + assert!(!permission_denied("Permission to use Bash has been denied because Claude Code is running in don't ask mode.")); + assert!(!permission_denied("Exit code 1\nls: no such file")); + assert!(!permission_denied("rm: Permission to use Bash has been denied")); + } use serde_json::json; #[test] diff --git a/crates/harness/src/codex/mod.rs b/crates/harness/src/codex/mod.rs index f92c9c62d..f92c74ae0 100644 --- a/crates/harness/src/codex/mod.rs +++ b/crates/harness/src/codex/mod.rs @@ -446,15 +446,30 @@ fn run_access(request: &RunRequest) -> AccessMode { /// supervised, asks before anything but codex's known-safe reads (under /// `"on-request"` a sandboxed `rm -rf` or `git push` would run unasked). /// A title run never asks and never writes, whatever its chat's mode. +/// Auto writes the workspace and asks on request, and its requests go to +/// codex's auto-review rather than the person ([`approvals_reviewer`]). fn permissions(access: AccessMode, title_only: bool) -> (&'static str, SandboxLevel) { match access { _ if title_only => ("never", SandboxLevel::ReadOnly), AccessMode::FullAccess => ("never", SandboxLevel::DangerFullAccess), + AccessMode::Auto => ("on-request", SandboxLevel::WorkspaceWrite), AccessMode::AutoAcceptEdits => ("untrusted", SandboxLevel::WorkspaceWrite), AccessMode::Supervised => ("untrusted", SandboxLevel::ReadOnly), } } +/// Who answers a run's approval requests: codex's auto-review in Auto (it +/// escalates what it won't decide), the person in the other asking modes, +/// and nobody to name in full access or a title run (they never ask). +fn approvals_reviewer(access: AccessMode, title_only: bool) -> Option<&'static str> { + match access { + _ if title_only => None, + AccessMode::FullAccess => None, + AccessMode::Auto => Some("auto_review"), + AccessMode::Supervised | AccessMode::AutoAcceptEdits => Some("user"), + } +} + /// `turn/start`'s `collaborationMode` (`plan` or `default`). Its settings /// take precedence over the turn's model and effort, so they repeat them; /// a null `developer_instructions` keeps the mode's built-in ones (0.164.0 @@ -739,7 +754,7 @@ impl Harness for CodexHarness { /// Supervised asks before what codex does not know to be safe, and /// auto-accept edits before stepping outside the workspace sandbox. fn access_modes(&self) -> &[AccessMode] { - &AccessMode::ALL + &AccessMode::WITH_AUTO } /// Codex's own `plan` collaboration mode. fn supports_plan(&self) -> bool { @@ -1388,7 +1403,7 @@ async fn run_session(session: Session) { // configured `approvals_reviewer` could otherwise hand them to an AI // reviewer instead. let (approval_policy, sandbox) = permissions(run_access(&request), title_only); - let asks_person = |live: &RunRequest| !title_only && !run_access(live).is_full_access(); + let reviewer = |live: &RunRequest| approvals_reviewer(run_access(live), title_only); let start_tier = service_tier(&request); let start_params = { @@ -1445,8 +1460,8 @@ async fn run_session(session: Session) { } p.insert("approvalPolicy".into(), approval_policy.into()); p.insert("sandbox".into(), sandbox_mode(sandbox).into()); - if asks_person(&request) { - p.insert("approvalsReviewer".into(), "user".into()); + if let Some(reviewer) = reviewer(&request) { + p.insert("approvalsReviewer".into(), reviewer.into()); } if let Some(model) = &request.model { p.insert("model".into(), Value::String(model.clone())); @@ -1697,8 +1712,8 @@ async fn run_session(session: Session) { let (approval_policy, sandbox) = permissions(run_access(live), title_only); p.insert("approvalPolicy".into(), approval_policy.into()); p.insert("sandboxPolicy".into(), sandbox_policy_value(sandbox)); - if asks_person(live) { - p.insert("approvalsReviewer".into(), "user".into()); + if let Some(reviewer) = reviewer(live) { + p.insert("approvalsReviewer".into(), reviewer.into()); } // Reasoning summaries stream (`item/reasoning/summaryTextDelta`) only // when asked for — without this codex "thinks" in silence for minutes: @@ -1906,6 +1921,15 @@ async fn run_session(session: Session) { } } + // Auto's reviewer on a call: shown on the call. + "item/autoApprovalReview/started" | "item/autoApprovalReview/completed" => { + if let Some(event) = normalize::auto_review_event(¶ms) + && !send(&event_tx, event).await + { + break 'main; + } + } + // Kept for commands still open: one that outlives its // turn shows its tail (`TurnControl::background_output`). "item/commandExecution/outputDelta" => { @@ -3157,7 +3181,24 @@ mod tests { wire(AccessMode::Supervised, false), ("untrusted", "read-only", json!({"type": "readOnly"})) ); - for access in AccessMode::ALL { + // Auto asks on request, and auto-review answers (it escalates what + // it won't decide); the other asking modes name the person. + assert_eq!( + wire(AccessMode::Auto, false), + ( + "on-request", + "workspace-write", + json!({"type": "workspaceWrite", "networkAccess": true}) + ) + ); + assert_eq!(approvals_reviewer(AccessMode::Auto, false), Some("auto_review")); + assert_eq!(approvals_reviewer(AccessMode::AutoAcceptEdits, false), Some("user")); + assert_eq!(approvals_reviewer(AccessMode::Supervised, false), Some("user")); + assert_eq!(approvals_reviewer(AccessMode::FullAccess, false), None); + for access in AccessMode::WITH_AUTO { + assert_eq!(approvals_reviewer(access, true), None); + } + for access in AccessMode::WITH_AUTO { assert_eq!( wire(access, true), ("never", "read-only", json!({"type": "readOnly"})) @@ -3184,6 +3225,8 @@ mod tests { assert_eq!(allowed(AccessMode::FullAccess), [true, true, true]); assert_eq!(allowed(AccessMode::AutoAcceptEdits), [true, false, false]); assert_eq!(allowed(AccessMode::Supervised), [false, false, false]); + // What auto-review escalates is asked. + assert_eq!(allowed(AccessMode::Auto), [false, false, false]); } #[test] @@ -3205,7 +3248,7 @@ mod tests { let mut moved = run_request(AccessMode::Supervised, false); moved.cwd = "/elsewhere".into(); assert!(!harness.reconfigures_in_place(&live, &moved)); - assert_eq!(harness.access_modes(), &AccessMode::ALL); + assert_eq!(harness.access_modes(), &AccessMode::WITH_AUTO); assert!(harness.supports_plan()); } diff --git a/crates/harness/src/codex/normalize.rs b/crates/harness/src/codex/normalize.rs index 72bd426e2..f7ab63395 100644 --- a/crates/harness/src/codex/normalize.rs +++ b/crates/harness/src/codex/normalize.rs @@ -6,7 +6,7 @@ //! types) are accepted, and unknown item types map to nothing. use serde_json::Value; -use zeron_proto::{AgentEvent, DoneStatus, TodoItem, TodoStatus, ToolCall}; +use zeron_proto::{AgentEvent, DoneStatus, TodoItem, TodoStatus, ToolCall, ToolReview, ToolReviewStatus}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Phase { @@ -97,6 +97,35 @@ impl ReasoningStream { } } +/// `item/autoApprovalReview/started` and `/completed` (Auto's reviewer, +/// codex's auto-review): its verdict on the call it names, for the call's +/// part. Nothing for a review that names no call (a network check) or that +/// was aborted with its turn. (Codex marks this payload unstable: read +/// tolerantly, and an unknown status is no verdict.) +pub(crate) fn auto_review_event(params: &Value) -> Option { + let id = str_field(params, &["targetItemId", "target_item_id"]); + if id.is_empty() { + return None; + } + let review = params.get("review")?; + let status = match str_field(review, &["status"]).as_str() { + "inProgress" | "in_progress" => ToolReviewStatus::Reviewing, + "approved" => ToolReviewStatus::Approved, + "denied" => ToolReviewStatus::Denied, + "timedOut" | "timed_out" => ToolReviewStatus::TimedOut, + _ => return None, + }; + let text = |keys: &[&str]| Some(str_field(review, keys)).filter(|s| !s.trim().is_empty()); + Some(AgentEvent::ToolReviewed { + id, + review: ToolReview { + status, + risk: text(&["riskLevel", "risk_level"]), + reason: text(&["rationale"]), + }, + }) +} + pub(crate) fn item_id(params: &Value) -> String { str_field(params, &["itemId", "item_id"]) } @@ -937,6 +966,34 @@ pub(crate) fn route_child_notification(method: &str) -> ChildRoute { #[cfg(test)] mod tests { use super::*; + + #[test] + fn auto_review_notifications_become_reviews_on_their_call() { + let completed = serde_json::json!({ + "threadId": "t", "turnId": "u", "reviewId": "r", "targetItemId": "call_1", + "review": { "status": "denied", "riskLevel": "high", "rationale": "Deletes files outside the workspace." }, + "action": { "type": "command", "command": "rm -rf ~/x", "cwd": "/w", "source": "shell" } + }); + assert_eq!( + auto_review_event(&completed), + Some(AgentEvent::ToolReviewed { + id: "call_1".into(), + review: ToolReview { + status: ToolReviewStatus::Denied, + risk: Some("high".into()), + reason: Some("Deletes files outside the workspace.".into()), + }, + }) + ); + let started = serde_json::json!({ "targetItemId": "call_1", "review": { "status": "inProgress" } }); + assert!(matches!( + auto_review_event(&started), + Some(AgentEvent::ToolReviewed { review: ToolReview { status: ToolReviewStatus::Reviewing, risk: None, reason: None }, .. }) + )); + // A network check names no call; an aborted review is no verdict. + assert_eq!(auto_review_event(&serde_json::json!({ "targetItemId": null, "review": { "status": "approved" } })), None); + assert_eq!(auto_review_event(&serde_json::json!({ "targetItemId": "c", "review": { "status": "aborted" } })), None); + } use serde_json::json; #[test] diff --git a/crates/harness/src/opencode/mod.rs b/crates/harness/src/opencode/mod.rs index 716c62f9c..6eae3c3b3 100644 --- a/crates/harness/src/opencode/mod.rs +++ b/crates/harness/src/opencode/mod.rs @@ -6239,6 +6239,7 @@ http.createServer((req, res) => { assert_eq!((edit, bash), (&json!("allow"), &json!("ask"))) } AccessMode::Supervised => assert_eq!((edit, bash), (&json!("ask"), &json!("ask"))), + AccessMode::Auto => unreachable!("OpenCode has no auto mode to offer"), } } } diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index d7d8165ab..af4ab8977 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -145,7 +145,7 @@ fn catalog() -> Vec { "model": { "type": "string", "description": "Model id from list_models on the chosen device. Omit for the harness default." }, "reasoning": { "type": "string", "description": "Reasoning level the model supports (e.g. low, medium, high, max)." }, "sandbox": { "type": "string", "enum": ["read-only", "workspace-write", "danger-full-access"], "default": "workspace-write", "description": "Never wider than the sandbox of the chat you are speaking from: more is lowered to it (accessCapped)." }, - "access": { "type": "string", "enum": ["supervised", "auto-accept-edits", "full-access"], "description": "What the agent may do without asking: supervised asks before commands and file changes, auto-accept-edits applies edits and asks before the rest, full-access asks nothing. Questions go to the person in the chat. Must be one of the harness's accessModes (list_harnesses). Defaults to the access of the chat you are speaking from, and never exceeds it: more is lowered to it (the reply's accessCapped says so)." }, + "access": { "type": "string", "enum": ["supervised", "auto-accept-edits", "auto", "full-access"], "description": "What the agent may do without asking: supervised asks before commands and file changes, auto-accept-edits applies edits and asks before the rest, auto lets the agent's own reviewer (Claude Code's auto mode, Codex's auto-review) approve safe actions and ask about the rest, full-access asks nothing. Questions go to the person in the chat. Must be one of the harness's accessModes (list_harnesses). Defaults to the access of the chat you are speaking from, and never exceeds it: more is lowered to it (the reply's accessCapped says so)." }, "plan": { "type": "boolean", "default": false, "description": "Plan mode: explore and propose a plan before changing anything. Only for harnesses with supportsPlan." }, "title": { "type": "string", "description": "Sidebar title. Otherwise the engine titles it from the first exchange." }, "branch": { "type": "string", "description": "Branch label to record on the chat." }, diff --git a/crates/mcp/src/transcript.rs b/crates/mcp/src/transcript.rs index 5c24ac3ad..53aa67ab9 100644 --- a/crates/mcp/src/transcript.rs +++ b/crates/mcp/src/transcript.rs @@ -288,6 +288,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }, MessagePart::Text { id: "t2".into(), diff --git a/crates/mobile/src/layout/tests.rs b/crates/mobile/src/layout/tests.rs index 5ee450734..335769a0b 100644 --- a/crates/mobile/src/layout/tests.rs +++ b/crates/mobile/src/layout/tests.rs @@ -165,6 +165,7 @@ fn messages_the_agent_sent_show_as_one_line_naming_the_recipient() { exit_code: None, output_truncated: false, output_lines: None, + review: None, }; let mut w = worker(390.0); w.input = TranscriptInput { @@ -688,6 +689,7 @@ fn running_subagent_shows_a_spinner_after_its_spawn_resolves() { exit_code: None, output_truncated: false, output_lines: None, + review: None, }; let frame_for = |status: SubagentStatus| { let mut w = worker(390.0); diff --git a/crates/proto/src/agent.rs b/crates/proto/src/agent.rs index 2ac0ee609..a69a66ecb 100644 --- a/crates/proto/src/agent.rs +++ b/crates/proto/src/agent.rs @@ -415,6 +415,10 @@ pub enum AccessMode { Supervised, /// Apply file changes without asking; ask before anything else. AutoAcceptEdits, + /// The agent's own auto mode: its reviewer (Claude Code's classifier, + /// Codex's auto-review) approves safe actions and blocks risky ones; + /// what it escalates is asked. Only agents that have one list it. + Auto, /// Run commands and change files without asking. Every run before modes /// existed ran this way, so it is the default. #[default] @@ -422,21 +426,51 @@ pub enum AccessMode { } impl AccessMode { - /// Every mode, least to most trusting (the picker's order). + /// The modes every permission-aware agent honors, least to most + /// trusting (the picker's order). [`AccessMode::Auto`] is offered only + /// by agents with an auto mode of their own ([`AccessMode::WITH_AUTO`]). pub const ALL: [AccessMode; 3] = [ AccessMode::Supervised, AccessMode::AutoAcceptEdits, AccessMode::FullAccess, ]; + /// [`AccessMode::ALL`] with the agent's own auto mode, in order. + pub const WITH_AUTO: [AccessMode; 4] = [ + AccessMode::Supervised, + AccessMode::AutoAcceptEdits, + AccessMode::Auto, + AccessMode::FullAccess, + ]; + pub fn is_full_access(&self) -> bool { *self == AccessMode::FullAccess } + /// The mode an agent offering `modes` runs a request for `self` in: + /// `self` when offered. Auto, on an agent without an auto mode, is the + /// nearest stricter mode it offers (auto-accept edits, else supervised) + /// rather than more trust than asked for. Anything else falls back to + /// full access, as it always has. + pub fn honored_by(self, modes: &[AccessMode]) -> AccessMode { + if modes.contains(&self) { + return self; + } + if self == AccessMode::Auto { + for stricter in [AccessMode::AutoAcceptEdits, AccessMode::Supervised] { + if modes.contains(&stricter) { + return stricter; + } + } + } + AccessMode::FullAccess + } + pub fn label(self) -> &'static str { match self { AccessMode::Supervised => "Supervised", AccessMode::AutoAcceptEdits => "Auto-accept edits", + AccessMode::Auto => "Auto", AccessMode::FullAccess => "Full access", } } @@ -445,6 +479,7 @@ impl AccessMode { match self { AccessMode::Supervised => "Ask before commands and file changes.", AccessMode::AutoAcceptEdits => "Apply edits, ask before other actions.", + AccessMode::Auto => "The agent's reviewer approves safe actions; risky ones ask.", AccessMode::FullAccess => "Run commands and edits without asking.", } } @@ -479,7 +514,10 @@ pub fn cap_access( all.iter().position(|y| y == x).unwrap_or(0) } let sandbox_over = rank(&SandboxLevel::ALL, &sandbox) > rank(&SandboxLevel::ALL, &max_sandbox); - let access_over = rank(&AccessMode::ALL, &access) > rank(&AccessMode::ALL, &max_access); + // (Ranked among every mode: one missing from the list would rank as the + // least trusting, and slip under any ceiling.) + let access_over = + rank(&AccessMode::WITH_AUTO, &access) > rank(&AccessMode::WITH_AUTO, &max_access); ( if sandbox_over { max_sandbox } else { sandbox }, if access_over { max_access } else { access }, @@ -1008,6 +1046,34 @@ pub struct ToolResultImage { } /// A file modification carried inline on a tool result (ACP +/// Where an agent's own reviewer (Codex's auto-review, Claude Code's auto +/// mode) stands on one of its tool calls, in [`AccessMode::Auto`]. Shown on +/// the call, so a person can tell what the reviewer let through or stopped. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ToolReviewStatus { + /// The reviewer is looking at it. + Reviewing, + /// The reviewer let it run. + Approved, + /// The reviewer stopped it; it didn't run. + Denied, + /// The reviewer didn't decide in time. + TimedOut, +} + +/// A reviewer's verdict on a tool call: its status, and, when the reviewer +/// says, how risky it judged the call (`low` to `critical`) and why. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ToolReview { + pub status: ToolReviewStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub risk: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + /// `ToolCallContent::Diff`). `old_text: None` means a new file. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1126,6 +1192,10 @@ pub enum AgentEvent { #[serde(default, skip_serializing_if = "Option::is_none")] exit_code: Option, }, + /// The agent's own reviewer on tool call `id` (Auto): reviewing it, + /// or its verdict. Folds onto the call's part; a later one replaces it. + #[serde(rename_all = "camelCase")] + ToolReviewed { id: String, review: ToolReview }, /// Latest context occupancy, independent of cumulative billing usage. /// Missing fields preserve the previous measurement; zero tokens is valid. #[serde(rename_all = "camelCase")] @@ -1219,6 +1289,37 @@ pub enum AgentEvent { mod tests { use super::*; + #[test] + fn auto_ranks_between_auto_accept_edits_and_full_access() { + let ws = SandboxLevel::WorkspaceWrite; + // A supervised or auto-accept-edits chat can't hand work to Auto. + for max in [AccessMode::Supervised, AccessMode::AutoAcceptEdits] { + assert_eq!(cap_access((ws, AccessMode::Auto), (ws, max)), (ws, max, true)); + } + // Auto caps full access, and lets Auto and what's below it through. + assert_eq!( + cap_access((ws, AccessMode::FullAccess), (ws, AccessMode::Auto)), + (ws, AccessMode::Auto, true) + ); + for asked in [AccessMode::Supervised, AccessMode::AutoAcceptEdits, AccessMode::Auto] { + assert_eq!(cap_access((ws, asked), (ws, AccessMode::Auto)), (ws, asked, false)); + } + assert_eq!(serde_json::to_string(&AccessMode::Auto).unwrap(), "\"auto\""); + } + + #[test] + fn auto_falls_back_to_the_nearest_stricter_mode() { + use AccessMode::*; + assert_eq!(Auto.honored_by(&AccessMode::WITH_AUTO), Auto); + assert_eq!(Auto.honored_by(&AccessMode::ALL), AutoAcceptEdits); + assert_eq!(Auto.honored_by(&[Supervised, FullAccess]), Supervised); + // An agent with full access alone has nothing stricter to give. + assert_eq!(Auto.honored_by(&[FullAccess]), FullAccess); + // The other modes fall back as before. + assert_eq!(Supervised.honored_by(&[FullAccess]), FullAccess); + assert_eq!(AutoAcceptEdits.honored_by(&AccessMode::ALL), AutoAcceptEdits); + } + #[test] fn agent_event_round_trips() { let ev = AgentEvent::ToolCall { diff --git a/crates/ui/src/pickers.rs b/crates/ui/src/pickers.rs index e15b5c807..23e6739cd 100644 --- a/crates/ui/src/pickers.rs +++ b/crates/ui/src/pickers.rs @@ -185,7 +185,7 @@ pub fn resolve_access(wanted: AccessMode, offered: &[AccessMode]) -> AccessMode if offered.contains(&wanted) { return wanted; } - let rank = |mode: AccessMode| AccessMode::ALL.iter().position(|m| *m == mode); + let rank = |mode: AccessMode| AccessMode::WITH_AUTO.iter().position(|m| *m == mode); offered .iter() .copied() diff --git a/crates/ui/src/shell/session_lanes.rs b/crates/ui/src/shell/session_lanes.rs index 8a9708e8f..7e1a84875 100644 --- a/crates/ui/src/shell/session_lanes.rs +++ b/crates/ui/src/shell/session_lanes.rs @@ -745,6 +745,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, } } diff --git a/crates/ui/src/state.rs b/crates/ui/src/state.rs index 428dbb1e2..febe3bec2 100644 --- a/crates/ui/src/state.rs +++ b/crates/ui/src/state.rs @@ -2215,6 +2215,7 @@ impl AppState { exit_code: None, output_truncated: false, output_lines: None, + review: None, }], created_at: created_at + 1, device_id: "local".into(), diff --git a/crates/ui/src/todo_panel.rs b/crates/ui/src/todo_panel.rs index edf5edd9b..8f1230f73 100644 --- a/crates/ui/src/todo_panel.rs +++ b/crates/ui/src/todo_panel.rs @@ -736,6 +736,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, } } @@ -996,6 +997,7 @@ mod composer_tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }], created_at: 0, device_id: "d".into(), diff --git a/crates/ui/src/transcript.rs b/crates/ui/src/transcript.rs index 8dd2f25ec..6d0a243a7 100644 --- a/crates/ui/src/transcript.rs +++ b/crates/ui/src/transcript.rs @@ -13357,6 +13357,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, }; let entry = assistant( "a1", @@ -14556,6 +14557,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, } } @@ -14682,6 +14684,7 @@ mod tests { exit_code: None, output_truncated: false, output_lines: None, + review: None, } } From e934f876fc84dd623855a578376fde81ebb06740 Mon Sep 17 00:00:00 2001 From: Wing <44917547+wingleeio@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:10:03 +0000 Subject: [PATCH 2/3] Fix Auto access fallback and untrusted reviewer verdicts Co-authored-by: zeronsh[bot] <346184242+zeronsh[bot]@users.noreply.github.com> --- apps/zgx/src/access_mode_tests.rs | 35 ++++++++++++++ apps/zgx/src/main.rs | 2 + apps/zgx/ui/auto_access_fixture.luau | 40 ++++++++++++++++ apps/zgx/ui/ds/composer.luau | 12 ++--- apps/zgx/ui/locales/en.json | 2 + apps/zgx/ui/locales/zh-Hans.json | 2 + crates/harness/src/acp/mod.rs | 18 ++++--- crates/harness/src/claude/mod.rs | 8 ---- crates/harness/src/claude/normalize.rs | 65 ++++++++++++-------------- crates/harness/tests/acp.rs | 35 ++++++++++++++ crates/proto/src/agent.rs | 45 +++++++++--------- 11 files changed, 184 insertions(+), 80 deletions(-) create mode 100644 apps/zgx/src/access_mode_tests.rs create mode 100644 apps/zgx/ui/auto_access_fixture.luau diff --git a/apps/zgx/src/access_mode_tests.rs b/apps/zgx/src/access_mode_tests.rs new file mode 100644 index 000000000..d92fc9128 --- /dev/null +++ b/apps/zgx/src/access_mode_tests.rs @@ -0,0 +1,35 @@ +//! Changing agents must not leave an unsupported Auto mode looking usable. +use zgx_script::{ScriptHost, Value, testing::TestApp}; + +#[test] +fn unsupported_auto_is_labelled_unavailable_until_explicitly_changed() { + let path = + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ui/auto_access_fixture.luau"); + let mut app = TestApp::new(|runtime| ScriptHost::new(runtime, path)); + app.ui.scene.borrow_mut().resize(900., 600.); + app.frames(30); + assert!(app.texts().iter().any(|text| text == "Auto")); + let offered = app.host.shared("test_composer_auto", Value::Bool(true)); + let access = app.host.shared("test_composer_access", Value::from("auto")); + offered.set(Value::Bool(false)); + app.frames(30); + // The animated label renders changing letters as separate text nodes. + assert!(app.texts().concat().contains("Auto unavailable")); + assert_eq!( + access.get(), + Value::from("auto"), + "never silently grant full access" + ); + app.click("role:button \"Access\""); + app.frames(30); + assert!( + app.texts() + .iter() + .any(|text| text.contains("Choose another access mode or agent.")) + ); + app.click("role:option \"Full access Run commands and edits without asking.\""); + app.frames(30); + assert_eq!(access.get(), Value::from("full")); + assert!(app.wait_until(|app| !app.texts().concat().contains("Auto unavailable"))); + assert_eq!(app.error(), None); +} diff --git a/apps/zgx/src/main.rs b/apps/zgx/src/main.rs index 11a592697..b27ce9eac 100644 --- a/apps/zgx/src/main.rs +++ b/apps/zgx/src/main.rs @@ -121,6 +121,8 @@ mod drop_tests; mod picker_settle_tests; #[cfg(test)] mod fit_tests; +#[cfg(test)] +mod access_mode_tests; // (Unix only: it reads thread CPU time through libc.) #[cfg(all(test, unix))] mod slide_bench_tests; diff --git a/apps/zgx/ui/auto_access_fixture.luau b/apps/zgx/ui/auto_access_fixture.luau new file mode 100644 index 000000000..134601994 --- /dev/null +++ b/apps/zgx/ui/auto_access_fixture.luau @@ -0,0 +1,40 @@ +-- Composer fixture for capability changes while Auto remains selected. +ui.theme.strict("warn") +local ds = require("@ds") +local Composer = require("@ds/composer") +local Cargo = require("@ds/composer_cargo") +local Ask = require("@ds/composer_ask") +ds.setup() + +local HARNESSES: { ds.Harness } = { { id = "claude", label = "Claude", mark = "claude" } } +local MODELS: { ds.Model } = { { value = "sonnet", label = "Sonnet", harness = "claude" } } +local access_auto = ui.shared("test_composer_auto", true) +local PROJECTS: { Composer.Project } = { + { value = "atlas", label = "Atlas", hue = "violet" }, + { value = "borealis", label = "Borealis", hue = "blue" }, + { value = "none", label = "No project" }, +} + +return ui.column { + w_full = true, + h_full = true, + p = "$space.4", + justify = "end", + ds.Composer { + value = ui.state("test_composer_draft", ""), + access = ui.shared("test_composer_access", "auto" :: string?), + access_auto = function(): boolean + return access_auto:get() + end, + model = ui.state("test_composer_model", "sonnet" :: string?), + effort = ui.state("test_composer_effort", "medium" :: string?), + harnesses = HARNESSES, + models = MODELS, + notice = ui.state("test_composer_notice", nil :: Composer.Notice?), + dictating = ui.state("test_composer_dictating", false), + cargo = ui.state("test_composer_cargo", {} :: { Cargo.Item }), + question = ui.state("test_composer_question", nil :: Ask.Question?), + project = ui.state("test_composer_project", "atlas" :: string?), + projects = PROJECTS, + }, +} diff --git a/apps/zgx/ui/ds/composer.luau b/apps/zgx/ui/ds/composer.luau index 7e003b82f..201c0a21c 100644 --- a/apps/zgx/ui/ds/composer.luau +++ b/apps/zgx/ui/ds/composer.luau @@ -369,7 +369,7 @@ end -- held back (an open padlock). Auto only where the agent has one (`auto`), -- or while it's the mode chosen. (Made as they're read, in the locale's -- words.) -local function ACCESS(auto: boolean): { Dropdown.Item } +local function ACCESS(auto: boolean, chosen: string?): { Dropdown.Item } local items = { worded({ value = "supervised", icon = "access-supervised" }, { label = "ds.composer.access.supervised", @@ -380,10 +380,10 @@ local function ACCESS(auto: boolean): { Dropdown.Item } description = "ds.composer.access.edits_hint", }), } - if auto then - table.insert(items, worded({ value = "auto", icon = "shield-check" }, { - label = "ds.composer.access.auto", - description = "ds.composer.access.auto_hint", + if auto or chosen == "auto" then + table.insert(items, worded({ value = "auto", icon = "shield-check", disabled = not auto }, { + label = if auto then "ds.composer.access.auto" else "ds.composer.access.auto_unavailable", + description = if auto then "ds.composer.access.auto_hint" else "ds.composer.access.auto_unavailable_hint", })) end table.insert(items, worded({ value = "full", icon = "access-full" }, { @@ -1432,7 +1432,7 @@ return ui.component(function(props: Props): Node value = props.access, items = function(): { Dropdown.Item } local chosen = props.access and props.access:get() - return ACCESS(chosen == "auto" or (props.access_auto ~= nil and props.access_auto())) + return ACCESS(props.access_auto ~= nil and props.access_auto(), chosen) end, tone = "chip", label = locale.t("ds.composer.access.label") :: any, diff --git a/apps/zgx/ui/locales/en.json b/apps/zgx/ui/locales/en.json index 785f9a27b..023ce3246 100644 --- a/apps/zgx/ui/locales/en.json +++ b/apps/zgx/ui/locales/en.json @@ -592,6 +592,8 @@ "edits_hint": "Apply edits, ask before other actions.", "auto": "Auto", "auto_hint": "The agent's reviewer approves safe actions; risky ones ask.", + "auto_unavailable": "Auto unavailable", + "auto_unavailable_hint": "This agent doesn't support Auto. Choose another access mode or agent.", "full": "Full access", "full_hint": "Run commands and edits without asking." }, diff --git a/apps/zgx/ui/locales/zh-Hans.json b/apps/zgx/ui/locales/zh-Hans.json index f983f4087..435d47889 100644 --- a/apps/zgx/ui/locales/zh-Hans.json +++ b/apps/zgx/ui/locales/zh-Hans.json @@ -592,6 +592,8 @@ "edits_hint": "应用编辑,执行其他操作前先询问。", "auto": "自动", "auto_hint": "由智能体自己的审查判断:安全的操作直接执行,有风险的会询问你。", + "auto_unavailable": "自动模式不可用", + "auto_unavailable_hint": "此智能体不支持自动模式。请选择其他访问模式或智能体。", "full": "完全访问", "full_hint": "运行命令和编辑时不询问。" }, diff --git a/crates/harness/src/acp/mod.rs b/crates/harness/src/acp/mod.rs index d775d5677..fb2a445b4 100644 --- a/crates/harness/src/acp/mod.rs +++ b/crates/harness/src/acp/mod.rs @@ -1718,12 +1718,11 @@ impl AcpHarness { } } - /// The access mode `request` runs with: its own when this agent honors - /// it, else as [`AccessMode::honored_by`] falls back — full access, but - /// never for Auto — and full access for any auto-approve run. - fn access_for(&self, request: &RunRequest) -> AccessMode { + /// Resolve access before launching. Auto must never become full access + /// just because an agent cannot honor it. + fn access_for(&self, request: &RunRequest) -> Option { if request.auto_approve { - AccessMode::FullAccess + Some(AccessMode::FullAccess) } else { request.access.honored_by(self.spec.access_modes) } @@ -3236,6 +3235,7 @@ impl Harness for AcpHarness { /// the session mode chosen at launch, so a new mode gets a new agent. fn reconfigures_in_place(&self, live: &RunRequest, next: &RunRequest) -> bool { live.cwd == next.cwd + && self.access_for(next).is_some() && self.access_for(live) == self.access_for(next) && (next.model.is_some() || live.model.is_none()) && (next.reasoning.is_some() || live.reasoning.is_none()) @@ -3442,6 +3442,12 @@ impl Harness for AcpHarness { request: RunRequest, controls: RunControls, ) -> Result>, HarnessError> { + let access = self.access_for(&request).ok_or_else(|| { + HarnessError::Protocol(format!( + "{} cannot run in Auto or a stricter access mode. Choose another agent or explicitly select Full access.", + self.spec.display_name + )) + })?; let (scratch, mut child, stderr_tail, sign_in_prompted) = self .spawn_agent( Some(&request.cwd), @@ -3501,7 +3507,7 @@ impl Harness for AcpHarness { incoming, event_tx, controls, - access: self.access_for(&request), + access, request, harness: self.spec.id, agent_name: self.spec.display_name, diff --git a/crates/harness/src/claude/mod.rs b/crates/harness/src/claude/mod.rs index 56347cebc..5894ce044 100644 --- a/crates/harness/src/claude/mod.rs +++ b/crates/harness/src/claude/mod.rs @@ -1625,14 +1625,6 @@ async fn run_session(session: Session) { stdin.replay = None; } for ev in events { - // A refusal is Auto's reviewer's only in Auto; in - // another mode it was a rule's, and the failed call - // says enough. - if matches!(ev, AgentEvent::ToolReviewed { .. }) - && access(&config) != AccessMode::Auto - { - continue; - } match &ev { AgentEvent::ToolCall { id, .. } => { open_tools.insert(id.clone()); diff --git a/crates/harness/src/claude/normalize.rs b/crates/harness/src/claude/normalize.rs index 6c7e1e881..25a5525b3 100644 --- a/crates/harness/src/claude/normalize.rs +++ b/crates/harness/src/claude/normalize.rs @@ -2,7 +2,7 @@ //! decoding, error-code mapping). use serde_json::Value; -use zeron_proto::{AgentEvent, DoneStatus, HarnessId, TodoItem, TodoStatus, ToolCall, ToolReview, ToolReviewStatus}; +use zeron_proto::{AgentEvent, DoneStatus, HarnessId, TodoItem, TodoStatus, ToolCall}; use super::wire::{ContentBlock, Frame, MessageFrame, ResultFrame}; @@ -394,16 +394,6 @@ fn tool_result( } } -/// The CLI refused the call: "Permission to use Bash has been denied." (in -/// auto mode, its classifier's block). Not don't-ask mode's refusal, which -/// no reviewer made. -fn permission_denied(text: &str) -> bool { - let first = text.lines().next().unwrap_or_default(); - first.starts_with("Permission to use ") - && first.contains(" has been denied") - && !first.contains("don't ask mode") -} - /// A `tool_result`'s text: its string, or its text blocks joined. fn result_text(content: &Value) -> String { match content { @@ -722,7 +712,6 @@ impl Normalizer { clear_inline_skills: bool, ) -> Vec { let mut pending = Vec::new(); - let mut denials = Vec::new(); for block in frame.message.blocks() { if block.kind != "tool_result" { continue; @@ -735,21 +724,8 @@ impl Normalizer { .remove(&block.tool_use_id) .unwrap_or_else(|| "image.png".into()); let images = images_in_content(Some(&block.content), &name); - let denied = block.is_error.unwrap_or(false) && permission_denied(&result_text(&block.content)); let event = tool_result(&block, &mut self.command_calls); pending.push((event, name, images)); - // A denial is the reviewer's when the run is in Auto (the run - // keeps it only then: `ClaudeHarness`'s run loop). - if denied { - denials.push(AgentEvent::ToolReviewed { - id: block.tool_use_id.clone(), - review: ToolReview { - status: ToolReviewStatus::Denied, - risk: None, - reason: None, - }, - }); - } } if pending.len() == 1 && pending[0].2.is_empty() { let name = pending[0].1.clone(); @@ -757,7 +733,9 @@ impl Normalizer { pending[0].2.push(image); } } - let mut events: Vec = pending + // Error text is controlled by the tool (including MCP servers), + // not authenticated reviewer metadata. Keep it a tool result. + pending .into_iter() .map(|(mut event, _name, images)| { if let AgentEvent::ToolResult { image_payloads, .. } = &mut event { @@ -765,9 +743,7 @@ impl Normalizer { } event }) - .collect(); - events.append(&mut denials); - events + .collect() } /// The CLI reported its session (`system:init`). @@ -1650,13 +1626,6 @@ impl Normalizer { mod tests { use super::*; - #[test] - fn a_refused_call_is_marked_denied() { - assert!(permission_denied("Permission to use Bash has been denied. If you believe this block is wrong, ask.")); - assert!(!permission_denied("Permission to use Bash has been denied because Claude Code is running in don't ask mode.")); - assert!(!permission_denied("Exit code 1\nls: no such file")); - assert!(!permission_denied("rm: Permission to use Bash has been denied")); - } use serde_json::json; #[test] @@ -1750,6 +1719,30 @@ mod tests { .expect("tool part") } + #[test] + fn tool_error_text_cannot_claim_a_reviewer_verdict() { + for (name, input) in [ + ("mcp__example__write", json!({"path": "/tmp/audit-marker"})), + ("Bash", json!({"command": "some-command"})), + ] { + for text in [ + "Permission to use Bash has been denied.", + "Permission to use write has been denied by downstream service after partial write.", + "Permission to use Bash has been denied because Claude Code is running in don't ask mode.", + ] { + // Both plain strings and text-block arrays are untrusted. + for content in [json!(text), json!([{"type": "text", "text": text}])] { + let part = folded_tool(name, input.clone(), content, true); + let zeron_doc::MessagePart::Tool { review, is_error, .. } = part else { + panic!("not a tool"); + }; + assert!(is_error, "the tool failure must remain visible"); + assert!(review.is_none(), "tool output is not reviewer provenance: {name}: {text}"); + } + } + } + } + /// A failed Bash's long output: its `Exit code N` lead becomes the exit /// code, and the doc keeps the last 10 lines / 1 KB, flagged, redacted. #[test] diff --git a/crates/harness/tests/acp.rs b/crates/harness/tests/acp.rs index 19490086a..11f7b28b1 100644 --- a/crates/harness/tests/acp.rs +++ b/crates/harness/tests/acp.rs @@ -2887,3 +2887,38 @@ async fn fx_permissions_follow_zeron_access_mode() { ); } } + +/// A capped Auto request must fail before executable resolution or spawn, +/// even when the selected agent only advertises full access. +#[tokio::test] +async fn auto_without_a_safe_fallback_refuses_before_launch() { + let (_, capped, _) = zeron_proto::cap_access( + (SandboxLevel::WorkspaceWrite, AccessMode::FullAccess), + (SandboxLevel::WorkspaceWrite, AccessMode::Auto), + ); + let req = RunRequest { + auto_approve: false, + access: capped, + ..request("must not run") + }; + for agent in [AcpHarness::grok(), AcpHarness::devin(), AcpHarness::hermes()] { + let agent = agent.with_executable(PathBuf::from("/nonexistent/auto-must-not-launch")); + assert!(!agent.reconfigures_in_place(&req, &req)); + let (controls, _sender, _token) = controls(); + match agent.run(req.clone(), controls).await { + Err(HarnessError::Protocol(message)) => { + assert!(message.contains("cannot run in Auto"), "{message}"); + assert!(message.contains("explicitly select Full access"), "{message}"); + } + Err(error) => panic!("access must be checked before launch: {error}"), + Ok(_) => panic!("unsupported Auto started a run"), + } + } + // Supported stricter fallbacks remain usable, and explicit full access + // retains the legacy auto_approve behavior. + let edits = RunRequest { access: AccessMode::AutoAcceptEdits, ..req.clone() }; + assert!(AcpHarness::antigravity().reconfigures_in_place(&req, &edits)); + let explicit = RunRequest { auto_approve: true, ..req }; + let full = RunRequest { auto_approve: false, access: AccessMode::FullAccess, ..explicit.clone() }; + assert!(AcpHarness::devin().reconfigures_in_place(&full, &explicit)); +} diff --git a/crates/proto/src/agent.rs b/crates/proto/src/agent.rs index a69a66ecb..5d1e70c50 100644 --- a/crates/proto/src/agent.rs +++ b/crates/proto/src/agent.rs @@ -447,23 +447,19 @@ impl AccessMode { *self == AccessMode::FullAccess } - /// The mode an agent offering `modes` runs a request for `self` in: - /// `self` when offered. Auto, on an agent without an auto mode, is the - /// nearest stricter mode it offers (auto-accept edits, else supervised) - /// rather than more trust than asked for. Anything else falls back to - /// full access, as it always has. - pub fn honored_by(self, modes: &[AccessMode]) -> AccessMode { + /// Resolve the requested mode against an agent's capabilities. Auto + /// falls back only to a stricter offered mode; None means the run must + /// be refused. Other unsupported modes retain their legacy fallback. + pub fn honored_by(self, modes: &[AccessMode]) -> Option { if modes.contains(&self) { - return self; + return Some(self); } if self == AccessMode::Auto { - for stricter in [AccessMode::AutoAcceptEdits, AccessMode::Supervised] { - if modes.contains(&stricter) { - return stricter; - } - } + return [AccessMode::AutoAcceptEdits, AccessMode::Supervised] + .into_iter() + .find(|mode| modes.contains(mode)); } - AccessMode::FullAccess + Some(AccessMode::FullAccess) } pub fn label(self) -> &'static str { @@ -1045,10 +1041,10 @@ pub struct ToolResultImage { pub data_base64: String, } -/// A file modification carried inline on a tool result (ACP -/// Where an agent's own reviewer (Codex's auto-review, Claude Code's auto -/// mode) stands on one of its tool calls, in [`AccessMode::Auto`]. Shown on -/// the call, so a person can tell what the reviewer let through or stopped. +/// A verdict from an agent's structured reviewer metadata, such as +/// Codex's auto-review, in [`AccessMode::Auto`]. Shown on the call so a +/// person can tell what the reviewer let through or stopped. Tool output +/// alone is not evidence that a reviewer made a decision. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum ToolReviewStatus { @@ -1310,14 +1306,15 @@ mod tests { #[test] fn auto_falls_back_to_the_nearest_stricter_mode() { use AccessMode::*; - assert_eq!(Auto.honored_by(&AccessMode::WITH_AUTO), Auto); - assert_eq!(Auto.honored_by(&AccessMode::ALL), AutoAcceptEdits); - assert_eq!(Auto.honored_by(&[Supervised, FullAccess]), Supervised); - // An agent with full access alone has nothing stricter to give. - assert_eq!(Auto.honored_by(&[FullAccess]), FullAccess); + assert_eq!(Auto.honored_by(&AccessMode::WITH_AUTO), Some(Auto)); + assert_eq!(Auto.honored_by(&AccessMode::ALL), Some(AutoAcceptEdits)); + assert_eq!(Auto.honored_by(&[Supervised, FullAccess]), Some(Supervised)); + // With no safe fallback, the caller must refuse to run. + assert_eq!(Auto.honored_by(&[FullAccess]), None); + assert_eq!(Auto.honored_by(&[]), None); // The other modes fall back as before. - assert_eq!(Supervised.honored_by(&[FullAccess]), FullAccess); - assert_eq!(AutoAcceptEdits.honored_by(&AccessMode::ALL), AutoAcceptEdits); + assert_eq!(Supervised.honored_by(&[FullAccess]), Some(FullAccess)); + assert_eq!(AutoAcceptEdits.honored_by(&AccessMode::ALL), Some(AutoAcceptEdits)); } #[test] From 31ac609b897e7c8228c2df73e525bca3cf9c121d Mon Sep 17 00:00:00 2001 From: Wing <44917547+wingleeio@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:21:36 -0700 Subject: [PATCH 3/3] Refuse Auto on agents that ignore the access mode; tidy the Auto change Cursor and Pi ignore the access mode, so Auto sent to them (the composer keeps it, marked unavailable, after an agent switch) ran with full access. The engine now refuses Auto before launch whenever the agent has neither an auto mode nor a stricter one to fall back to, for every harness, not only ACP ones. Also: cap the reviewer's risk text like its reason, show no review for a status this build doesn't know, restore ToolDiff's lost doc line, keep the activity row comment with its function, and rustfmt the new code. Co-Authored-By: Claude Opus 5.5 Co-authored-by: zeronsh[bot] <346184242+zeronsh[bot]@users.noreply.github.com> --- apps/zgx/src/chat.rs | 15 ++++++-- apps/zgx/ui/ds/activity.luau | 14 +++---- crates/doc/src/parts.rs | 42 +++++++++++++++----- crates/doc/src/schema.rs | 27 ++++++++++--- crates/engine/src/sessions.rs | 53 +++++++++++++++++++++----- crates/harness/src/claude/normalize.rs | 13 ++++--- crates/harness/src/codex/normalize.rs | 29 ++++++++++---- crates/harness/src/lib.rs | 4 +- crates/harness/tests/acp.rs | 27 ++++++++++--- crates/proto/src/agent.rs | 32 +++++++++++++--- 10 files changed, 199 insertions(+), 57 deletions(-) diff --git a/apps/zgx/src/chat.rs b/apps/zgx/src/chat.rs index 7dad220fa..b3010c26d 100644 --- a/apps/zgx/src/chat.rs +++ b/apps/zgx/src/chat.rs @@ -5544,9 +5544,18 @@ fn tool_row(part: &Json, live: bool) -> Option { fields.push(("failed", Value::Bool(true))); } // Auto's reviewer on it: reviewing, approved, denied or timed-out, its - // risk and why (as the agent's reviewer said). - if let Some(status) = part["review"]["status"].as_str() { - let text = |key: &str| part["review"][key].as_str().filter(|t| !t.trim().is_empty()).map_or(Value::Nil, Value::from); + // risk and why (as the agent's reviewer said). A status this build + // doesn't know (a newer peer's) shows nothing rather than a bare key. + if let Some(status) = part["review"]["status"] + .as_str() + .filter(|s| matches!(*s, "reviewing" | "approved" | "denied" | "timed-out")) + { + let text = |key: &str| { + part["review"][key] + .as_str() + .filter(|t| !t.trim().is_empty()) + .map_or(Value::Nil, Value::from) + }; fields.push(( "review", Value::record([("status", Value::from(status)), ("risk", text("risk")), ("reason", text("reason"))]), diff --git a/apps/zgx/ui/ds/activity.luau b/apps/zgx/ui/ds/activity.luau index 29cebb203..8a7d8aa07 100644 --- a/apps/zgx/ui/ds/activity.luau +++ b/apps/zgx/ui/ds/activity.luau @@ -585,13 +585,6 @@ local OPENS: { [string]: boolean } = { exec = true, read = true, edit = true, wr -- Kinds whose row counts lines added and removed (an edit's). local COUNTS: { [string]: boolean } = { edit = true, write = true } --- (`below`: a tool with a branch follows, so the trunk runs on under this --- one; `running`: it is the one in flight, its glyph the working loader; --- `resized`: told the row's size as it's laid out; `settled`: it is before --- the group's last, so never the one in flight.) --- A row is built often (each comes into view, a long group's thousands), so --- what can't change once a tool has started is read once as it's made (its --- kind, its verb, its glyph); only what a tool's result changes follows it. -- Auto's reviewer on a call: its glyph becomes a shield in the verdict's -- hue (let through quiet, stopped in danger's, timed out in warning's), its -- risk and why in the tooltip. A call no reviewer looked at keeps its own. @@ -635,6 +628,13 @@ local function review_glyph(now: () -> Tool, size: number): Node } end +-- (`below`: a tool with a branch follows, so the trunk runs on under this +-- one; `running`: it is the one in flight, its glyph the working loader; +-- `resized`: told the row's size as it's laid out; `settled`: it is before +-- the group's last, so never the one in flight.) +-- A row is built often (each comes into view, a long group's thousands), so +-- what can't change once a tool has started is read once as it's made (its +-- kind, its verb, its glyph); only what a tool's result changes follows it. local function row( now: () -> Tool, below: () -> boolean, diff --git a/crates/doc/src/parts.rs b/crates/doc/src/parts.rs index c29fc07ea..2ea5cc2c3 100644 --- a/crates/doc/src/parts.rs +++ b/crates/doc/src/parts.rs @@ -5,8 +5,9 @@ use serde::{Deserialize, Serialize}; -use zeron_proto::{ToolReview, - AgentEvent, SUBAGENT_INPUT_KEEP, ToolCall, ToolDiff, UserInputAnswer, UserInputQuestion, +use zeron_proto::{ + AgentEvent, SUBAGENT_INPUT_KEEP, ToolCall, ToolDiff, ToolReview, UserInputAnswer, + UserInputQuestion, }; use crate::constants::MSG_INLINE_MAX; @@ -966,20 +967,43 @@ mod tests { fn a_review_folds_onto_its_call_and_a_later_one_replaces_it() { use zeron_proto::ToolReviewStatus; let mut parts = Vec::new(); - fold_event_into_parts(&mut parts, &AgentEvent::ToolCall { id: "c1".into(), call: ToolCall::Exec { command: "rm -rf x".into() } }); + fold_event_into_parts( + &mut parts, + &AgentEvent::ToolCall { + id: "c1".into(), + call: ToolCall::Exec { + command: "rm -rf x".into(), + }, + }, + ); let review = |status| AgentEvent::ToolReviewed { id: "c1".into(), - review: ToolReview { status, risk: Some("high".into()), reason: Some("outside the workspace".into()) }, + review: ToolReview { + status, + risk: Some("high".into()), + reason: Some("outside the workspace".into()), + }, }; fold_event_into_parts(&mut parts, &review(ToolReviewStatus::Reviewing)); fold_event_into_parts(&mut parts, &review(ToolReviewStatus::Denied)); // One for a call that isn't shown changes nothing. - fold_event_into_parts(&mut parts, &AgentEvent::ToolReviewed { - id: "elsewhere".into(), - review: ToolReview { status: ToolReviewStatus::Approved, risk: None, reason: None }, - }); + fold_event_into_parts( + &mut parts, + &AgentEvent::ToolReviewed { + id: "elsewhere".into(), + review: ToolReview { + status: ToolReviewStatus::Approved, + risk: None, + reason: None, + }, + }, + ); match &parts[..] { - [MessagePart::Tool { review: Some(r), .. }] => { + [ + MessagePart::Tool { + review: Some(r), .. + }, + ] => { assert_eq!(r.status, ToolReviewStatus::Denied); assert_eq!(r.reason.as_deref(), Some("outside the workspace")); } diff --git a/crates/doc/src/schema.rs b/crates/doc/src/schema.rs index 58014384c..158f7a561 100644 --- a/crates/doc/src/schema.rs +++ b/crates/doc/src/schema.rs @@ -337,7 +337,9 @@ fn from_doc_part(p: DocPartJson) -> MessagePart { exit_code: p.exit_code, output_truncated: p.output_truncated.unwrap_or(false), output_lines: p.output_lines, - review: p.review.and_then(|value| serde_json::from_value(value).ok()), + review: p + .review + .and_then(|value| serde_json::from_value(value).ok()), }, None => MessagePart::Text { id: p.id, @@ -3531,7 +3533,12 @@ mod tests { let mut folded = Vec::new(); fold_event_into_parts( &mut folded, - &AgentEvent::ToolCall { id: "c1".into(), call: ToolCall::Exec { command: "rm -rf ~/x".into() } }, + &AgentEvent::ToolCall { + id: "c1".into(), + call: ToolCall::Exec { + command: "rm -rf ~/x".into(), + }, + }, ); writer.sync(&folded).unwrap(); for status in [ToolReviewStatus::Reviewing, ToolReviewStatus::Denied] { @@ -3539,7 +3546,11 @@ mod tests { &mut folded, &AgentEvent::ToolReviewed { id: "c1".into(), - review: ToolReview { status, risk: Some("high".into()), reason: Some("outside the workspace".into()) }, + review: ToolReview { + status, + risk: Some("high".into()), + reason: Some("outside the workspace".into()), + }, }, ); writer.sync(&folded).unwrap(); @@ -3548,9 +3559,15 @@ mod tests { let snapshot = doc.export_snapshot().unwrap(); let replica = loro::LoroDoc::new(); replica.import(&snapshot).unwrap(); - for entries in [doc.read_entries().unwrap(), SessionDoc::from_doc(replica).read_entries().unwrap()] { + for entries in [ + doc.read_entries().unwrap(), + SessionDoc::from_doc(replica).read_entries().unwrap(), + ] { match &entries[0].parts[0] { - MessagePart::Tool { review: Some(review), .. } => { + MessagePart::Tool { + review: Some(review), + .. + } => { assert_eq!(review.status, ToolReviewStatus::Denied); assert_eq!(review.risk.as_deref(), Some("high")); assert_eq!(review.reason.as_deref(), Some("outside the workspace")); diff --git a/crates/engine/src/sessions.rs b/crates/engine/src/sessions.rs index 3ad60b27c..1e9bb4c27 100644 --- a/crates/engine/src/sessions.rs +++ b/crates/engine/src/sessions.rs @@ -3947,12 +3947,25 @@ fn subagent_chip_update(event: &AgentEvent) -> Option<&'static str> { } } -/// A reviewer's reason as the doc keeps it: its first 600 characters. -fn cap_review_reason(why: &str) -> String { - const MAX: usize = 600; - match why.char_indices().nth(MAX) { - Some((at, _)) => format!("{}…", why[..at].trim_end()), - None => why.to_owned(), +/// Auto asked of an agent with no auto mode and no stricter mode to fall +/// back to (Cursor, Pi: they ignore the access mode, so they'd run it with +/// full access). Refused before launch, whatever the client sent. +fn auto_unavailable( + request: &RunRequest, + offered: &[zeron_proto::AccessMode], +) -> Option { + (!request.auto_approve && request.access.honored_by(offered).is_none()).then(|| { + zeron_harness::HarnessError::Protocol( + "This agent can't run in Auto. Choose another access mode or agent.".into(), + ) + }) +} + +/// A reviewer's words as the doc keeps them: their first `max` characters. +fn cap_review_text(text: &str, max: usize) -> String { + match text.char_indices().nth(max) { + Some((at, _)) => format!("{}…", text[..at].trim_end()), + None => text.to_owned(), } } @@ -4004,9 +4017,10 @@ fn render_parts(parts: &[MessagePart]) -> Vec { output_truncated: *output_truncated, output_lines: *output_lines, // The reviewer's verdict stays: it's what the person needs to - // see. Its reason is bounded, as an output summary is. + // see. Its words are bounded, as an output summary is. review: review.as_ref().map(|r| zeron_proto::ToolReview { - reason: r.reason.as_deref().map(|why| cap_review_reason(why)), + risk: r.risk.as_deref().map(|risk| cap_review_text(risk, 32)), + reason: r.reason.as_deref().map(|why| cap_review_text(why, 600)), ..r.clone() }), }, @@ -4372,7 +4386,9 @@ async fn drive_run( } crate::runner::mark_setup_shown(); } - let prepared = if harness_id == HarnessId::Cursor { + let prepared = if let Some(refused) = auto_unavailable(&request, harness.access_modes()) { + Err(refused) + } else if harness_id == HarnessId::Cursor { cursor_unstarted_history( &doc, &resume_state.user_message_id, @@ -6547,6 +6563,25 @@ mod tests { ); } + /// Auto on an agent that ignores the access mode (Cursor, Pi) would run + /// with full access: refused. Where a stricter mode exists, or Auto is + /// offered, or full access was asked for outright, the run goes ahead. + #[test] + fn auto_is_refused_where_it_would_become_full_access() { + use zeron_proto::AccessMode::{self, *}; + let asking = |access: AccessMode, auto_approve: bool| RunRequest { + access, + auto_approve, + ..request() + }; + assert!(auto_unavailable(&asking(Auto, false), &[FullAccess]).is_some()); + assert!(auto_unavailable(&asking(Auto, true), &[FullAccess]).is_none()); + assert!(auto_unavailable(&asking(Auto, false), &AccessMode::ALL).is_none()); + assert!(auto_unavailable(&asking(Auto, false), &AccessMode::WITH_AUTO).is_none()); + // The other modes keep their old fallback. + assert!(auto_unavailable(&asking(Supervised, false), &[FullAccess]).is_none()); + } + fn request() -> RunRequest { RunRequest { mcp: None, diff --git a/crates/harness/src/claude/normalize.rs b/crates/harness/src/claude/normalize.rs index 25a5525b3..d868a7498 100644 --- a/crates/harness/src/claude/normalize.rs +++ b/crates/harness/src/claude/normalize.rs @@ -733,8 +733,6 @@ impl Normalizer { pending[0].2.push(image); } } - // Error text is controlled by the tool (including MCP servers), - // not authenticated reviewer metadata. Keep it a tool result. pending .into_iter() .map(|(mut event, _name, images)| { @@ -1625,7 +1623,6 @@ impl Normalizer { #[cfg(test)] mod tests { use super::*; - use serde_json::json; #[test] @@ -1733,11 +1730,17 @@ mod tests { // Both plain strings and text-block arrays are untrusted. for content in [json!(text), json!([{"type": "text", "text": text}])] { let part = folded_tool(name, input.clone(), content, true); - let zeron_doc::MessagePart::Tool { review, is_error, .. } = part else { + let zeron_doc::MessagePart::Tool { + review, is_error, .. + } = part + else { panic!("not a tool"); }; assert!(is_error, "the tool failure must remain visible"); - assert!(review.is_none(), "tool output is not reviewer provenance: {name}: {text}"); + assert!( + review.is_none(), + "tool output is not reviewer provenance: {name}: {text}" + ); } } } diff --git a/crates/harness/src/codex/normalize.rs b/crates/harness/src/codex/normalize.rs index f7ab63395..8292444a0 100644 --- a/crates/harness/src/codex/normalize.rs +++ b/crates/harness/src/codex/normalize.rs @@ -6,7 +6,9 @@ //! types) are accepted, and unknown item types map to nothing. use serde_json::Value; -use zeron_proto::{AgentEvent, DoneStatus, TodoItem, TodoStatus, ToolCall, ToolReview, ToolReviewStatus}; +use zeron_proto::{ + AgentEvent, DoneStatus, TodoItem, TodoStatus, ToolCall, ToolReview, ToolReviewStatus, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Phase { @@ -966,10 +968,11 @@ pub(crate) fn route_child_notification(method: &str) -> ChildRoute { #[cfg(test)] mod tests { use super::*; + use serde_json::json; #[test] fn auto_review_notifications_become_reviews_on_their_call() { - let completed = serde_json::json!({ + let completed = json!({ "threadId": "t", "turnId": "u", "reviewId": "r", "targetItemId": "call_1", "review": { "status": "denied", "riskLevel": "high", "rationale": "Deletes files outside the workspace." }, "action": { "type": "command", "command": "rm -rf ~/x", "cwd": "/w", "source": "shell" } @@ -985,16 +988,28 @@ mod tests { }, }) ); - let started = serde_json::json!({ "targetItemId": "call_1", "review": { "status": "inProgress" } }); + let started = json!({ "targetItemId": "call_1", "review": { "status": "inProgress" } }); assert!(matches!( auto_review_event(&started), - Some(AgentEvent::ToolReviewed { review: ToolReview { status: ToolReviewStatus::Reviewing, risk: None, reason: None }, .. }) + Some(AgentEvent::ToolReviewed { + review: ToolReview { + status: ToolReviewStatus::Reviewing, + risk: None, + reason: None + }, + .. + }) )); // A network check names no call; an aborted review is no verdict. - assert_eq!(auto_review_event(&serde_json::json!({ "targetItemId": null, "review": { "status": "approved" } })), None); - assert_eq!(auto_review_event(&serde_json::json!({ "targetItemId": "c", "review": { "status": "aborted" } })), None); + assert_eq!( + auto_review_event(&json!({ "targetItemId": null, "review": { "status": "approved" } })), + None + ); + assert_eq!( + auto_review_event(&json!({ "targetItemId": "c", "review": { "status": "aborted" } })), + None + ); } - use serde_json::json; #[test] fn reasoning_parts_preserve_chunking_and_existing_paragraph_breaks() { diff --git a/crates/harness/src/lib.rs b/crates/harness/src/lib.rs index 287d3aa29..617e557da 100644 --- a/crates/harness/src/lib.rs +++ b/crates/harness/src/lib.rs @@ -339,7 +339,9 @@ pub trait Harness: Send + Sync { } /// The [`AccessMode`]s this driver honors, least to most trusting. A /// request for any other runs with full access (the composer offers - /// only these). + /// only these), except Auto: it falls back only to a stricter mode + /// listed here, and the engine refuses it when there is none + /// ([`AccessMode::honored_by`]). fn access_modes(&self) -> &[AccessMode] { &[AccessMode::FullAccess] } diff --git a/crates/harness/tests/acp.rs b/crates/harness/tests/acp.rs index 11f7b28b1..ea0a4fe92 100644 --- a/crates/harness/tests/acp.rs +++ b/crates/harness/tests/acp.rs @@ -2901,14 +2901,21 @@ async fn auto_without_a_safe_fallback_refuses_before_launch() { access: capped, ..request("must not run") }; - for agent in [AcpHarness::grok(), AcpHarness::devin(), AcpHarness::hermes()] { + for agent in [ + AcpHarness::grok(), + AcpHarness::devin(), + AcpHarness::hermes(), + ] { let agent = agent.with_executable(PathBuf::from("/nonexistent/auto-must-not-launch")); assert!(!agent.reconfigures_in_place(&req, &req)); let (controls, _sender, _token) = controls(); match agent.run(req.clone(), controls).await { Err(HarnessError::Protocol(message)) => { assert!(message.contains("cannot run in Auto"), "{message}"); - assert!(message.contains("explicitly select Full access"), "{message}"); + assert!( + message.contains("explicitly select Full access"), + "{message}" + ); } Err(error) => panic!("access must be checked before launch: {error}"), Ok(_) => panic!("unsupported Auto started a run"), @@ -2916,9 +2923,19 @@ async fn auto_without_a_safe_fallback_refuses_before_launch() { } // Supported stricter fallbacks remain usable, and explicit full access // retains the legacy auto_approve behavior. - let edits = RunRequest { access: AccessMode::AutoAcceptEdits, ..req.clone() }; + let edits = RunRequest { + access: AccessMode::AutoAcceptEdits, + ..req.clone() + }; assert!(AcpHarness::antigravity().reconfigures_in_place(&req, &edits)); - let explicit = RunRequest { auto_approve: true, ..req }; - let full = RunRequest { auto_approve: false, access: AccessMode::FullAccess, ..explicit.clone() }; + let explicit = RunRequest { + auto_approve: true, + ..req + }; + let full = RunRequest { + auto_approve: false, + access: AccessMode::FullAccess, + ..explicit.clone() + }; assert!(AcpHarness::devin().reconfigures_in_place(&full, &explicit)); } diff --git a/crates/proto/src/agent.rs b/crates/proto/src/agent.rs index 5d1e70c50..b8cc5d78a 100644 --- a/crates/proto/src/agent.rs +++ b/crates/proto/src/agent.rs @@ -1070,6 +1070,7 @@ pub struct ToolReview { pub reason: Option, } +/// A file modification carried inline on a tool result (ACP /// `ToolCallContent::Diff`). `old_text: None` means a new file. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -1191,7 +1192,10 @@ pub enum AgentEvent { /// The agent's own reviewer on tool call `id` (Auto): reviewing it, /// or its verdict. Folds onto the call's part; a later one replaces it. #[serde(rename_all = "camelCase")] - ToolReviewed { id: String, review: ToolReview }, + ToolReviewed { + id: String, + review: ToolReview, + }, /// Latest context occupancy, independent of cumulative billing usage. /// Missing fields preserve the previous measurement; zero tokens is valid. #[serde(rename_all = "camelCase")] @@ -1290,17 +1294,30 @@ mod tests { let ws = SandboxLevel::WorkspaceWrite; // A supervised or auto-accept-edits chat can't hand work to Auto. for max in [AccessMode::Supervised, AccessMode::AutoAcceptEdits] { - assert_eq!(cap_access((ws, AccessMode::Auto), (ws, max)), (ws, max, true)); + assert_eq!( + cap_access((ws, AccessMode::Auto), (ws, max)), + (ws, max, true) + ); } // Auto caps full access, and lets Auto and what's below it through. assert_eq!( cap_access((ws, AccessMode::FullAccess), (ws, AccessMode::Auto)), (ws, AccessMode::Auto, true) ); - for asked in [AccessMode::Supervised, AccessMode::AutoAcceptEdits, AccessMode::Auto] { - assert_eq!(cap_access((ws, asked), (ws, AccessMode::Auto)), (ws, asked, false)); + for asked in [ + AccessMode::Supervised, + AccessMode::AutoAcceptEdits, + AccessMode::Auto, + ] { + assert_eq!( + cap_access((ws, asked), (ws, AccessMode::Auto)), + (ws, asked, false) + ); } - assert_eq!(serde_json::to_string(&AccessMode::Auto).unwrap(), "\"auto\""); + assert_eq!( + serde_json::to_string(&AccessMode::Auto).unwrap(), + "\"auto\"" + ); } #[test] @@ -1314,7 +1331,10 @@ mod tests { assert_eq!(Auto.honored_by(&[]), None); // The other modes fall back as before. assert_eq!(Supervised.honored_by(&[FullAccess]), Some(FullAccess)); - assert_eq!(AutoAcceptEdits.honored_by(&AccessMode::ALL), Some(AutoAcceptEdits)); + assert_eq!( + AutoAcceptEdits.honored_by(&AccessMode::ALL), + Some(AutoAcceptEdits) + ); } #[test]