diff --git a/crates/agent/src/panel/composer_renderer.rs b/crates/agent/src/panel/composer_renderer.rs index f1c1b22f..89ec0515 100644 --- a/crates/agent/src/panel/composer_renderer.rs +++ b/crates/agent/src/panel/composer_renderer.rs @@ -21,6 +21,14 @@ use super::{ }; use crate::thread::{AgentThread, config_label}; +fn codex_goal_mode_notice(thread: &AgentThread) -> bool { + thread.document().agent_id() == "codex" + && thread.draft_text().is_some_and(|draft| { + nocterm_ai::commands::invocation(draft, thread.configuration().commands()) + .is_some_and(|command| command.name == "goal") + }) +} + fn remove_image(origin: gpui_kit::EntityId, index: usize, cx: &mut Context) -> Button { Button::new(("remove-image", index)) .ghost() @@ -389,6 +397,17 @@ impl ComposerRenderer { .into_any_element(), ); } + if codex_goal_mode_notice(thread.read(cx)) { + notices.push( + div() + .id("codex-goal-mode-notice") + .test_support() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child("Codex goal commands may retain the last applied permission mode. After changing mode, send a regular message before starting or resuming a goal.") + .into_any_element(), + ); + } if thread.read(cx).ended() && !thread.read(cx).session_generating() { notices.push( Button::new("agent-restart") diff --git a/crates/agent/src/panel/entries/tool_output.rs b/crates/agent/src/panel/entries/tool_output.rs index 4f7e3dd4..75cf4f18 100644 --- a/crates/agent/src/panel/entries/tool_output.rs +++ b/crates/agent/src/panel/entries/tool_output.rs @@ -6,7 +6,7 @@ use gpui_kit::{ px, }; use nocterm_ai::model::content::Content; -use nocterm_ai::model::tools::{ToolContent, ToolRecord}; +use nocterm_ai::model::tools::{ToolContent, ToolRecord, ToolStatus}; use nocterm_ai::tool_display::{self, ToolDisplay, ToolOutcome}; use serde_json::Value; @@ -91,6 +91,19 @@ pub(in crate::panel) fn source(call: &ToolRecord, redact: bool) -> Option, text: &str, cx: &mut Tes } } +#[gpui_kit::test] +fn codex_goal_warns_about_the_effective_mode_instead_of_assuming_full_access( + cx: &mut TestAppContext, +) { + let f = fixture(cx); + f.commands.config.set_options(vec![ + ConfigOption::select( + "mode", + "Mode", + "agent-full-access", + vec![ + ConfigChoice::new("agent-full-access", "Full access"), + ConfigChoice::new("workspace-write", "Workspace access"), + ], + ) + .category(ConfigCategory::Mode), + ]); + new_chat(&f, cx); + let goals = || vec![AvailableCommand::new("goal", "Work towards an objective")]; + commands(&f, goals(), "Ordinary message", cx); + cx.update_window(f.handle, |_, window, _cx| { + assert!(window.try_find("codex-goal-mode-notice").is_none()); + }) + .unwrap(); + + commands(&f, goals(), "/goal resume", cx); + cx.update_window(f.handle, |_, window, cx| { + assert!(window.try_find("codex-goal-mode-notice").is_some()); + window.click("config-picker-mode", cx); + window.render_frame(cx); + window.click("config-mode-workspace-write", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("codex-goal-mode-notice").is_some()); + }) + .unwrap(); + assert_eq!(f.commands.config.requests().len(), 1); + assert!( + f.commands.prompts.lock().unwrap().is_empty(), + "the notice must not send an implicit prompt" + ); + + commands(&f, goals(), "/goals", cx); + cx.update_window(f.handle, |_, window, _cx| { + assert!(window.try_find("codex-goal-mode-notice").is_none()); + }) + .unwrap(); +} + #[gpui_kit::test] fn clicked_unicode_command_keeps_focus_and_appends_at_end(cx: &mut TestAppContext) { let f = fixture(cx); diff --git a/crates/agent/src/panel/tests/tool_sections.rs b/crates/agent/src/panel/tests/tool_sections.rs index 381457c3..42e3537e 100644 --- a/crates/agent/src/panel/tests/tool_sections.rs +++ b/crates/agent/src/panel/tests/tool_sections.rs @@ -1,6 +1,6 @@ use super::tool_output::exec_result; use crate::panel::entries::{tool_input, tool_output}; -use nocterm_ai::model::tools::ToolRecord; +use nocterm_ai::model::tools::{ToolRecord, ToolStatus}; use nocterm_ai::tool_display; use serde_json::json; @@ -78,3 +78,48 @@ fn explicit_registered_envelopes_work_without_a_provider_name() { assert!(tool_display::requested_arguments(&foreign).is_none()); assert!(tool_display::header(&foreign).starts_with("Tool call")); } + +#[test] +fn codex_approval_policy_failure_explains_the_provider_gate() { + let error = "MCP tool call requires approval, but approval policy is never"; + let call = ToolRecord::new("denied", "nocterm-26: exec_command") + .status(ToolStatus::Failed) + .raw_input(json!({"server":"nocterm-26","tool":"exec_command","arguments":{"terminal_id":"t5","program":"pwd","args":[],"yield_ms":1000}})) + .raw_output(json!({"result":null,"error":{"message":error}})); + let output = tool_output::source(&call, false).unwrap(); + assert!( + output + .sections + .iter() + .any(|section| section.text.contains(error)) + ); + let help = output + .sections + .iter() + .find(|section| section.label == "Codex approval mode") + .unwrap(); + assert!(help.text.contains("Workspace access")); + assert!(help.text.contains("displayed mode can differ")); + assert!(help.text.contains("/goal")); + assert!(help.text.contains("send a regular message")); + assert!( + help.text + .contains("Nocterm terminal permissions still apply") + ); + + for unrelated in [ + call.clone() + .raw_input(json!({"server":"external","tool":"exec_command","arguments":{}})), + call.clone() + .raw_output(json!({"error":{"message":"Vault is locked"}})), + call.status(ToolStatus::Succeeded), + ] { + assert!( + !tool_output::source(&unrelated, false) + .unwrap() + .sections + .iter() + .any(|section| section.label == "Codex approval mode") + ); + } +} diff --git a/crates/ai/src/mcp.rs b/crates/ai/src/mcp.rs index 91b440ed..c996eabd 100644 --- a/crates/ai/src/mcp.rs +++ b/crates/ai/src/mcp.rs @@ -69,7 +69,7 @@ impl McpSession { _ if !self.initialized => error(id, -32002, "Initialize first"), "tools/list" => { let tools: Vec<_> = offer.tools().map(|spec| { - json!({"name":spec.name,"description":spec.description,"inputSchema":(spec.schema)()}) + json!({"name":spec.name,"description":spec.description,"inputSchema":(spec.schema)(),"annotations":{"readOnlyHint":spec.read_only}}) }).collect(); McpStep::Reply(json!({"jsonrpc":"2.0","id":id,"result":{"tools":tools}})) } diff --git a/crates/ai/src/tools/catalog.rs b/crates/ai/src/tools/catalog.rs index 9c1c1db8..617b99f5 100644 --- a/crates/ai/src/tools/catalog.rs +++ b/crates/ai/src/tools/catalog.rs @@ -8,6 +8,8 @@ pub struct ToolSpec { /// Terminal tools are always listed; file tools only while a chat offers them. pub group: ToolGroup, pub description: &'static str, + /// MCP metadata only; never an authorization decision. + pub read_only: bool, pub schema: fn() -> Value, /// Shape only: execution limits are checked separately by `validate`. pub parse: fn(Value) -> Option, @@ -50,7 +52,7 @@ impl ToolOffer { // The exhaustive name match makes each TerminalCall variant require a row here. macro_rules! catalog { - ($($variant:ident $(($arguments:ty))? => $name:literal, $label:literal, $group:ident, $description:literal;)*) => { + ($($variant:ident $(($arguments:ty))? => $name:literal, $label:literal, $group:ident, $read_only:literal, $description:literal;)*) => { enum Index { $($variant,)* } pub static TOOLS: &[ToolSpec] = &[$(ToolSpec { @@ -58,6 +60,7 @@ macro_rules! catalog { label: $label, group: ToolGroup::$group, description: $description, + read_only: $read_only, schema: catalog!(@schema $($arguments)?), parse: catalog!(@parse $variant $($arguments)?), },)*]; @@ -86,41 +89,41 @@ macro_rules! catalog { } catalog! { - ListTerminals => "list_terminals", "List terminals", Terminals, + ListTerminals => "list_terminals", "List terminals", Terminals, true, "List terminals attached to this chat, and attached servers that have no session yet (offline_servers). These are the only servers you can reach: nocterm holds their credentials, so never connect on your own with ssh. When the list is empty, tell the user to attach a terminal or server to the chat"; - OpenTerminal(OpenTerminal) => "open_terminal", "Connect", Terminals, + OpenTerminal(OpenTerminal) => "open_terminal", "Connect", Terminals, false, "Connect to an attached offline server in the background, without disturbing the user; returns its terminal_id once connected. If it fails, tell the user in one short sentence why and stop"; - ReadTerminal(ReadTerminal) => "read_terminal", "Read terminal", Terminals, + ReadTerminal(ReadTerminal) => "read_terminal", "Read terminal", Terminals, true, "Read bounded output of an attached terminal"; - SendInput(SendInput) => "send_input", "Send input", Terminals, + SendInput(SendInput) => "send_input", "Send input", Terminals, false, "Send text to an attached terminal with user approval"; - RunCommand(RunCommand) => "run_command", "Run command", Terminals, + RunCommand(RunCommand) => "run_command", "Run command", Terminals, false, "Type one command into a known empty live shell prompt. Requires shell integration; an output pause never proves completion. Prefer exec_command for a reliable exit status"; - ExecCommand(ExecCommand) => "exec_command", "Execute program", Terminals, + ExecCommand(ExecCommand) => "exec_command", "Execute program", Terminals, false, "Run program with separate args and optional stdin on the attached terminal host over its current connection. Local execution passes args directly; SSH renders a POSIX command line, so arbitrary args require a POSIX-compatible remote command shell and are not guaranteed on Windows SSH. Fresh process: no inherited terminal cwd, environment, aliases or functions. Use an explicit shell for shell syntax. Returns actual exit status or an owned command_id for read_command/cancel_command. Output is bounded and continuously drained"; - ReadCommand(ReadCommand) => "read_command", "Read command", Terminals, + ReadCommand(ReadCommand) => "read_command", "Read command", Terminals, true, "Read a bounded full snapshot of a command owned by this chat. Does not start or cancel a command; optional yield_ms waits briefly"; - CancelCommand(CancelCommand) => "cancel_command", "Cancel command", Terminals, + CancelCommand(CancelCommand) => "cancel_command", "Cancel command", Terminals, false, "Cancel a command owned by this chat. SSH sends TERM and closes its channel; remote descendant termination is best effort"; - TransferFiles(TransferFiles) => "transfer_files", "Transfer files", Terminals, + TransferFiles(TransferFiles) => "transfer_files", "Transfer files", Terminals, false, "Copy files and folders between the hosts of two attached terminals: this computer (a local terminal) to a server, a server to this computer, or a server to another server. nocterm relays the data over the connections it already holds, so servers need no credentials for each other and you must never use scp, rsync or ssh between them. Every path is absolute (no ~, no .. components). sources are files or folders on the source host; folders copy recursively, and each source is copied into destination under its own name. destination must be an existing folder; it is never created. Existing files are skipped and counted as skipped unless overwrite is true. Symbolic links and special files are skipped. At most 64 sources per call. Two local terminals are refused: use exec_command. Some environments only allow copies within one server. The copy runs in the background: after optional yield_ms (default 1000) it returns the current state and a transfer_id for read_transfer/cancel_transfer. Poll read_transfer until the state is completed, failed or cancelled. Whole files are published atomically; a cancelled or failed file leaves no partial file"; - ReadTransfer(ReadTransfer) => "read_transfer", "Read transfer", Terminals, + ReadTransfer(ReadTransfer) => "read_transfer", "Read transfer", Terminals, true, "Read a snapshot of a transfer started by this chat: state, file and byte counts and up to 16 failures. Does not start or cancel a transfer; optional yield_ms waits briefly while it is active"; - CancelTransfer(CancelTransfer) => "cancel_transfer", "Cancel transfer", Terminals, + CancelTransfer(CancelTransfer) => "cancel_transfer", "Cancel transfer", Terminals, false, "Cancel a transfer started by this chat. Files already published stay in place; files being copied are discarded"; - ListFiles(ListFiles) => "list_files", "List files", Files, + ListFiles(ListFiles) => "list_files", "List files", Files, true, "List a folder of an attached terminal whose list_terminals entry has file_tools: true. Such a terminal serves files but runs no programs (for example a console tab a plugin opened for a game server panel): exec_command and run_command cannot reach its files, so use the file tools for them. Paths are absolute from / with no ~, . or .. parts. Folders come first; at most 1000 entries. The file tools act only on terminals with file_tools: true, never on other terminals or this computer"; - ReadFile(ReadFile) => "read_file", "Read file", Files, + ReadFile(ReadFile) => "read_file", "Read file", Files, true, "Read a UTF-8 text file of an attached terminal with file_tools: true, up to 1 MiB, a range of lines at a time (start_line from 1, max_lines up to 2000, at most 64 KiB per answer; next_start_line says where to continue). The content is exactly the file's text, except where it is shown as [REDACTED]: such text is hidden from you, so change other parts with edit_file and never write the marker back"; - WriteFile(WriteFile) => "write_file", "Write file", Files, + WriteFile(WriteFile) => "write_file", "Write file", Files, false, "Write a whole UTF-8 text file (at most 512 KiB) on an attached terminal with file_tools: true, with user approval. An existing file is refused unless overwrite is true; prefer edit_file to change part of a file. The parent folder must exist"; - EditFile(EditFile) => "edit_file", "Edit file", Files, + EditFile(EditFile) => "edit_file", "Edit file", Files, false, "Replace exact text in a file of an attached terminal with file_tools: true, with user approval. old_text must occur exactly once, copied exactly from read_file with its whitespace, unless replace_all is true. Send only the part that changes; the file is changed on its host"; - MakeDirectory(MakeDirectory) => "make_directory", "Create folder", Files, + MakeDirectory(MakeDirectory) => "make_directory", "Create folder", Files, false, "Create a folder on an attached terminal with file_tools: true, with user approval. Its parent must exist; an existing folder is accepted"; - DeletePath(DeletePath) => "delete_path", "Delete", Files, + DeletePath(DeletePath) => "delete_path", "Delete", Files, false, "Delete a file or folder on an attached terminal with file_tools: true, with user approval. A folder is removed as the terminal's host removes folders, which may include its contents; it cannot be undone"; - MovePath(MovePath) => "move_path", "Move", Files, + MovePath(MovePath) => "move_path", "Move", Files, false, "Move or rename a file or folder within one attached terminal with file_tools: true, with user approval. Both paths are absolute"; } diff --git a/crates/ai/src/tools/catalog/tests.rs b/crates/ai/src/tools/catalog/tests.rs index 18057d9e..2db067f8 100644 --- a/crates/ai/src/tools/catalog/tests.rs +++ b/crates/ai/src/tools/catalog/tests.rs @@ -82,6 +82,32 @@ fn tools_list_preserves_original_order_descriptions_and_schemas() { ); } +#[test] +fn only_observation_tools_are_advertised_as_read_only() { + let McpStep::Reply(reply) = + session().handle(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#, ALL) + else { + panic!("expected tools/list reply"); + }; + for tool in reply["result"]["tools"].as_array().unwrap() { + let name = tool["name"].as_str().unwrap(); + let observation = matches!( + name, + "list_terminals" + | "read_terminal" + | "read_command" + | "read_transfer" + | "list_files" + | "read_file" + ); + assert_eq!( + tool["annotations"]["readOnlyHint"], + json!(observation), + "{name}" + ); + } +} + #[test] fn file_tools_are_listed_and_admitted_only_while_offered() { let listed = |offer| { diff --git a/crates/ai/src/tools/fixtures/tools-list.json b/crates/ai/src/tools/fixtures/tools-list.json index bb5550c2..7cb84c08 100644 --- a/crates/ai/src/tools/fixtures/tools-list.json +++ b/crates/ai/src/tools/fixtures/tools-list.json @@ -5,6 +5,9 @@ "tools": [ { "name": "list_terminals", + "annotations": { + "readOnlyHint": true + }, "description": "List terminals attached to this chat, and attached servers that have no session yet (offline_servers). These are the only servers you can reach: nocterm holds their credentials, so never connect on your own with ssh. When the list is empty, tell the user to attach a terminal or server to the chat", "inputSchema": { "type": "object", @@ -14,6 +17,9 @@ }, { "name": "open_terminal", + "annotations": { + "readOnlyHint": false + }, "description": "Connect to an attached offline server in the background, without disturbing the user; returns its terminal_id once connected. If it fails, tell the user in one short sentence why and stop", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -34,6 +40,9 @@ }, { "name": "read_terminal", + "annotations": { + "readOnlyHint": true + }, "description": "Read bounded output of an attached terminal", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -68,6 +77,9 @@ }, { "name": "send_input", + "annotations": { + "readOnlyHint": false + }, "description": "Send text to an attached terminal with user approval", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -94,6 +106,9 @@ }, { "name": "run_command", + "annotations": { + "readOnlyHint": false + }, "description": "Type one command into a known empty live shell prompt. Requires shell integration; an output pause never proves completion. Prefer exec_command for a reliable exit status", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -132,6 +147,9 @@ }, { "name": "exec_command", + "annotations": { + "readOnlyHint": false + }, "description": "Run program with separate args and optional stdin on the attached terminal host over its current connection. Local execution passes args directly; SSH renders a POSIX command line, so arbitrary args require a POSIX-compatible remote command shell and are not guaranteed on Windows SSH. Fresh process: no inherited terminal cwd, environment, aliases or functions. Use an explicit shell for shell syntax. Returns actual exit status or an owned command_id for read_command/cancel_command. Output is bounded and continuously drained", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -184,6 +202,9 @@ }, { "name": "read_command", + "annotations": { + "readOnlyHint": true + }, "description": "Read a bounded full snapshot of a command owned by this chat. Does not start or cancel a command; optional yield_ms waits briefly", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -214,6 +235,9 @@ }, { "name": "cancel_command", + "annotations": { + "readOnlyHint": false + }, "description": "Cancel a command owned by this chat. SSH sends TERM and closes its channel; remote descendant termination is best effort", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -236,6 +260,9 @@ }, { "name": "transfer_files", + "annotations": { + "readOnlyHint": false + }, "description": "Copy files and folders between the hosts of two attached terminals: this computer (a local terminal) to a server, a server to this computer, or a server to another server. nocterm relays the data over the connections it already holds, so servers need no credentials for each other and you must never use scp, rsync or ssh between them. Every path is absolute (no ~, no .. components). sources are files or folders on the source host; folders copy recursively, and each source is copied into destination under its own name. destination must be an existing folder; it is never created. Existing files are skipped and counted as skipped unless overwrite is true. Symbolic links and special files are skipped. At most 64 sources per call. Two local terminals are refused: use exec_command. Some environments only allow copies within one server. The copy runs in the background: after optional yield_ms (default 1000) it returns the current state and a transfer_id for read_transfer/cancel_transfer. Poll read_transfer until the state is completed, failed or cancelled. Whole files are published atomically; a cancelled or failed file leaves no partial file", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -287,6 +314,9 @@ }, { "name": "read_transfer", + "annotations": { + "readOnlyHint": true + }, "description": "Read a snapshot of a transfer started by this chat: state, file and byte counts and up to 16 failures. Does not start or cancel a transfer; optional yield_ms waits briefly while it is active", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -313,6 +343,9 @@ }, { "name": "cancel_transfer", + "annotations": { + "readOnlyHint": false + }, "description": "Cancel a transfer started by this chat. Files already published stay in place; files being copied are discarded", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", diff --git a/docs/AI_AGENTS.md b/docs/AI_AGENTS.md index 3ed77b20..4d4893f5 100644 --- a/docs/AI_AGENTS.md +++ b/docs/AI_AGENTS.md @@ -478,6 +478,17 @@ If the provider supplies no valid one-time choice, the request remains as a card with an explanation and the provider's options for manual review. Stop, disabled AI and requests from an obsolete or different session cancel instead of approving. +Codex can refuse MCP tools before their requests reach Nocterm when its +effective approval policy is `never`, even with an unlocked vault and an +attached, connected terminal. In codex-acp 2.13.0 the mode picker changes the +adapter's selection, but regular prompts apply that selection to the Codex +thread. The `/goal` command starts or resumes a goal directly and can retain +the thread's previous policy instead. The displayed selection is therefore +not proof of the effective policy for a running goal. If this error occurs, +stop the goal, select **Workspace access**, send a regular message and wait for +it to finish before resuming the goal. Review any permission requests. +Nocterm's attachment and terminal approval rules still apply independently. + The terminal read cursor is inclusive: a resumed read may replace the previous last logical line after more text is appended. It is not an exact byte-stream cursor. Alternate screens expose the visible page only. A local OSC 133 prompt diff --git a/docs/architecture/domain.md b/docs/architecture/domain.md index 9664b398..5d6fd39b 100644 --- a/docs/architecture/domain.md +++ b/docs/architecture/domain.md @@ -363,6 +363,9 @@ that format; command reports share explicit redaction policy and retain the actu exit, byte count and truncation. The panel decodes the same DTOs while retaining its labels, unknown-field display and historical provider-envelope fallbacks. These reports are observations, never execution or cancellation capabilities. +The tool catalog advertises MCP read-only hints for observation tools only. +Hints describe side effects, not grants; attachment scope and approvals are +enforced independently of the advertised metadata. `nocterm-ai::agents` describes how a known agent deviates from plain ACP as an `AgentProfile`: its pinned launch, the home directories it writes, how it reports