diff --git a/cli/docs/local-agent-bridge.md b/cli/docs/local-agent-bridge.md index 7cabde1f6..cea4f34d5 100644 --- a/cli/docs/local-agent-bridge.md +++ b/cli/docs/local-agent-bridge.md @@ -500,6 +500,13 @@ delivery, and restart recovery then use that child identity. Approvals appear as Inline action buttons in the conversation where the turn is running, including its reply thread. Only the owner can resolve them. +When Codex asks to run an MCP tool, the card names the tool (`server · tool`), +shows its arguments (bounded, control characters removed) and offers Codex's +own choices: Allow, the remember options Codex allows, and Cancel, which skips +that one call while the turn goes on. An unanswered card closes as no longer +needed when its turn ends or is interrupted. Every question card also ends +with Cancel, which tells the agent the question went unanswered, and `/stop` +with no turn running cancels whatever the open cards still wait on. Mid-turn owner directions steer when the provider supports steering; `/queue` always queues explicitly and provides Undo until work starts. An uncertain steering response is never automatically retried as another prompt: Inline diff --git a/cli/src/bridge/v2/blocks/fixtures/approval/codex-mcp-tool.golden.json b/cli/src/bridge/v2/blocks/fixtures/approval/codex-mcp-tool.golden.json new file mode 100644 index 000000000..27b253d1e --- /dev/null +++ b/cli/src/bridge/v2/blocks/fixtures/approval/codex-mcp-tool.golden.json @@ -0,0 +1,78 @@ +[ + { + "label": "open", + "text": "Codex wants to use linear · create_issue\n{\n \"labels\": [\n \"bug\"\n ],\n \"team\": \"ENG\",\n \"title\": \"Parser drops trailing commas\"\n}", + "markdown": false, + "blocks": [ + { + "approval": { + "subject": "SUBJECT_TOOL", + "title": "Codex wants to use linear · create_issue", + "children": [ + { + "code": { + "text": "{\n \"labels\": [\n \"bug\"\n ],\n \"team\": \"ENG\",\n \"title\": \"Parser drops trailing commas\"\n}", + "language": "json" + } + } + ], + "state": "BLOCK_DECISION_STATE_PENDING", + "action_ids": [ + "v2-0", + "v2-1", + "v2-2", + "v2-3" + ] + } + } + ], + "buttons": [ + { + "id": "v2-0", + "label": "Allow", + "style": "primary" + }, + { + "id": "v2-1", + "label": "Allow for this session", + "style": "default" + }, + { + "id": "v2-2", + "label": "Always allow", + "style": "default" + }, + { + "id": "v2-3", + "label": "Cancel", + "style": "default" + } + ] + }, + { + "label": "decided", + "text": "Codex wants to use linear · create_issue\n{\n \"labels\": [\n \"bug\"\n ],\n \"team\": \"ENG\",\n \"title\": \"Parser drops trailing commas\"\n}\nAllow (answered by Dena)", + "markdown": false, + "blocks": [ + { + "approval": { + "subject": "SUBJECT_TOOL", + "title": "Codex wants to use linear · create_issue", + "children": [ + { + "code": { + "text": "{\n \"labels\": [\n \"bug\"\n ],\n \"team\": \"ENG\",\n \"title\": \"Parser drops trailing commas\"\n}", + "language": "json" + } + } + ], + "state": "BLOCK_DECISION_STATE_ACCEPTED", + "decided_by_user_id": 7 + } + }, + { + "footer": "Allow (answered by Dena)" + } + ] + } +] diff --git a/cli/src/bridge/v2/blocks/fixtures/approval/codex-mcp-tool.json b/cli/src/bridge/v2/blocks/fixtures/approval/codex-mcp-tool.json new file mode 100644 index 000000000..144da7744 --- /dev/null +++ b/cli/src/bridge/v2/blocks/fixtures/approval/codex-mcp-tool.json @@ -0,0 +1,77 @@ +{ + "source": "Codex app-server v2 mcpServer/elicitation/request for an MCP tool call: a message-only form with codex_approval_kind mcp_tool_call (see crates/agent-bridge/tests/fixtures/harness/codex/mcp-tool-approval.json).", + "native": { + "method": "mcpServer/elicitation/request", + "id": 51, + "params": { + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "persist": [ + "session", + "always" + ], + "tool_name": "create_issue", + "tool_params": { + "labels": [ + "bug" + ], + "team": "ENG", + "title": "Parser drops trailing commas" + } + }, + "message": "Allow the linear MCP server to run tool \"create_issue\"?", + "mode": "form", + "requestedSchema": { + "properties": {}, + "type": "object" + }, + "serverName": "linear", + "threadId": "thr-1", + "turnId": "turn-1" + } + }, + "input": { + "agent": "Codex", + "folder": "/work/inline", + "interaction": { + "id": "51", + "turn": "turn-1", + "kind": { + "decisions": [ + { + "id": "accept", + "kind": "accept", + "label": "Allow" + }, + { + "id": "acceptForSession", + "kind": "accept_for_session", + "label": "Allow for this session" + }, + { + "id": "acceptAlways", + "kind": "accept_and_remember", + "label": "Always allow" + }, + { + "id": "cancel", + "kind": "decline", + "label": "Cancel" + } + ], + "kind": "approval", + "subject": { + "input": { + "labels": [ + "bug" + ], + "team": "ENG", + "title": "Parser drops trailing commas" + }, + "kind": "tool", + "name": "linear · create_issue" + } + } + } + } +} diff --git a/cli/src/bridge/v2/faults.rs b/cli/src/bridge/v2/faults.rs index 67639f663..7a09f1051 100644 --- a/cli/src/bridge/v2/faults.rs +++ b/cli/src/bridge/v2/faults.rs @@ -83,6 +83,9 @@ struct FakeSession { live: Mutex>, /// Interactions the session waits on, as `live_work` reports them. open: Mutex>, + /// Answers that reached the session (interaction, decision), each + /// claimed once as a harness does. + answers: Mutex>, } impl FakeSession { @@ -174,6 +177,25 @@ impl Session for FakeSession { if let Op::Mode { mode } = &op { self.modes.lock().unwrap().push(mode.as_str().to_owned()); } + if let Op::Answer { + interaction, + response, + .. + } = &op + { + let mut answers = self.answers.lock().unwrap(); + if answers.iter().any(|(id, _)| id == interaction.as_str()) { + return Box::pin(async { Err(OpError::InteractionNotPending) }); + } + let decision = match response { + inline_agent_bridge::harness::InteractionResponse::Decision { + decision, .. + } => decision.as_str().to_owned(), + inline_agent_bridge::harness::InteractionResponse::Cancel => "(cancel)".to_owned(), + _ => "(answers)".to_owned(), + }; + answers.push((interaction.as_str().to_owned(), decision)); + } Box::pin(async { Ok(OpOutcome::accepted()) }) } @@ -327,6 +349,7 @@ fn session_fixture( steers, live: Mutex::new(None), open: Mutex::new(Vec::new()), + answers: Mutex::new(Vec::new()), }); let harness = Arc::new(FakeHarness { session, @@ -2326,6 +2349,44 @@ async fn a_dismissed_task_suggestion_never_starts_and_a_next_step_answers_once() assert!(state(&runtime, &input_id(2, 9, 42, "widget-81")).is_none()); } +#[tokio::test] +async fn codex_mcp_tool_cards_answer_once_and_a_withdrawn_one_reaches_nothing() { + let (runtime, harness, _cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + work::recovery_tests::codex_mcp_tool_card_taps( + runtime.agent.clone(), + harness.session.clone() as Arc, + ) + .await; + // Allow and Cancel each reached Codex once; the second Allow and the + // tap on the withdrawn card reached nothing. + assert_eq!( + *harness.session.answers.lock().unwrap(), + [ + ("51".to_owned(), "accept".to_owned()), + ("52".to_owned(), "cancel".to_owned()) + ] + ); +} + +#[tokio::test] +async fn a_question_card_can_be_cancelled_and_stop_ends_a_request_with_no_turn() { + let (runtime, harness, _cleanup) = fixture(false); + runtime.agent.names.remember(1, "Owner".into()).await; + work::recovery_tests::question_cancel_and_turnless_stop( + runtime.agent.clone(), + harness.session.clone() as Arc, + ) + .await; + assert_eq!( + *harness.session.answers.lock().unwrap(), + [ + ("61".to_owned(), "(cancel)".to_owned()), + ("62".to_owned(), "(cancel)".to_owned()) + ] + ); +} + #[tokio::test] async fn plan_cards_are_superseded_unless_someone_decided_them() { let (runtime, _, _cleanup) = fixture(false); diff --git a/cli/src/bridge/v2/render.rs b/cli/src/bridge/v2/render.rs index 8f196bd08..e5abc6f82 100644 --- a/cli/src/bridge/v2/render.rs +++ b/cli/src/bridge/v2/render.rs @@ -252,6 +252,16 @@ impl Renderer { self.card_answers.insert(interaction.clone(), kept); } + /// Whether an open interaction blocks on nothing a stop could end: no + /// turn, not a sub-agent's, and not a question left open on purpose. + pub(crate) fn waits_on_no_turn(&self, id: &InteractionId) -> bool { + self.interactions.get(id).is_some_and(|interaction| { + interaction.turn.is_none() + && interaction.parent.is_none() + && !matches!(&interaction.kind, InteractionKind::Question { form } if form.asynchronous) + }) + } + pub(crate) fn apply(&mut self, envelope: &Envelope) -> Vec { let mut ops = Vec::new(); let now = envelope.at_ms; diff --git a/cli/src/bridge/v2/work.rs b/cli/src/bridge/v2/work.rs index 0c2957087..2e3651987 100644 --- a/cli/src/bridge/v2/work.rs +++ b/cli/src/bridge/v2/work.rs @@ -59,6 +59,7 @@ const PUBLISH_RETRIES: [Duration; 3] = [ /// The longest a rate-limited answer waits within one publish attempt. const MAX_PUBLISH_WAIT: Duration = Duration::from_secs(30); const NOT_PENDING: &str = "This request is no longer pending."; +const NOTHING_RUNNING: &str = "Nothing is running."; /// Trusted instructions for the speak gate's side call. const SPEAK_GATE_GUIDE: &str = "You take part in this Inline thread but nobody addressed you. \ Decide whether a reply from you would clearly help the people here right now. Stay quiet \ @@ -247,6 +248,9 @@ pub(crate) enum ActionData { /// Option `o` of question `f` on a question card asked with buttons. #[serde(rename = "q")] Pick { i: String, f: usize, o: usize }, + /// Cancel a question card: the harness hears it was not answered. + #[serde(rename = "qx")] + Dismiss { i: String }, /// A Codex plan card: approve (leave Plan mode and implement) or keep /// planning. #[serde(rename = "pp")] @@ -1101,7 +1105,14 @@ impl Actor { return Some(NO_ACCESS.to_owned()); } match control { - Control::Stop => self.stop(false).await, + // A request that waits on no turn (Codex elicitations may name + // none) is what a stop then ends. + Control::Stop => match self.stop(false).await { + Some(text) if text == NOTHING_RUNNING && self.cancel_open_cards(actor).await => { + None + } + other => other, + }, Control::Pause => self.stop(true).await, Control::Resume => self.resume().await, Control::Release(cause) => { @@ -1114,6 +1125,35 @@ impl Actor { } } + /// Cancels the requests behind open cards that wait on no turn: a turn's + /// own requests end with it (a sub-agent's too), and an asynchronous + /// question stays open on purpose. Whether any was. + async fn cancel_open_cards(&mut self, actor: i64) -> bool { + let Some(session) = self.held_session() else { + return false; + }; + let mut open: Vec = self + .cards + .values() + .map(|card| card.interaction.clone()) + .filter(|interaction| self.renderer.waits_on_no_turn(interaction)) + .collect(); + open.sort_by(|left, right| left.as_str().cmp(right.as_str())); + open.dedup(); + let mut cancelled = false; + for interaction in open { + cancelled |= session + .control(Op::Answer { + interaction, + response: InteractionResponse::Cancel, + by: UserId(actor), + }) + .await + .is_ok(); + } + cancelled + } + /// Stop the running turn. Pause also takes this bridge's queued input out /// of the native queue first, so nothing runs until a resume. async fn stop(&mut self, pause: bool) -> Option { @@ -1123,7 +1163,7 @@ impl Actor { self.report().await; return None; } - return Some("Nothing is running.".to_owned()); + return Some(NOTHING_RUNNING.to_owned()); }; if pause { self.paused = true; @@ -1175,7 +1215,7 @@ impl Actor { return Some(format!("Could not stop: {error}")); } } else if !pause { - return Some("Nothing is running.".to_owned()); + return Some(NOTHING_RUNNING.to_owned()); } self.report().await; None @@ -1248,6 +1288,20 @@ impl Actor { }; self.pick(message_id, actor, &i, f, label).await } + ActionData::Dismiss { i } => { + if !grants.any() { + return Some(NO_ACCESS.to_owned()); + } + let Some(card) = self.cards.get(&message_id) else { + return Some(NOT_PENDING.to_owned()); + }; + if card.form.is_none() || card.interaction.as_str() != i { + return Some(NOT_PENDING.to_owned()); + } + let interaction = card.interaction.clone(); + self.answer(interaction, InteractionResponse::Cancel, actor) + .await + } ActionData::Decision { i, d } => { let Some(card) = self.cards.get(&message_id).cloned() else { // A card from before a restart: its request ended with the old session. @@ -1366,7 +1420,10 @@ impl Actor { (card.chat, card.interaction.clone(), card.answered.clone()); if answered.len() < form.fields.len() { let doc = render::pick_card(&self.agent.agent_name, &form, answered.len(), &answered); - let actions = pick_actions(&interaction, &form, answered.len()); + let actions = with_dismiss( + pick_actions(&interaction, &form, answered.len()), + &interaction, + ); if self.edit_in(chat, message_id, &doc, actions).await { return None; } @@ -3567,8 +3624,11 @@ impl Actor { form, } => { let buttons = match &form { - Some(form) if render::pickable(form) => pick_actions(&interaction, form, 0), - _ => card_actions(&interaction, &actions), + Some(form) if render::pickable(form) => { + with_dismiss(pick_actions(&interaction, form, 0), &interaction) + } + Some(_) => with_dismiss(card_actions(&interaction, &actions), &interaction), + None => card_actions(&interaction, &actions), }; let long = long_labels(&actions); let doc = if long.is_empty() { @@ -4464,6 +4524,47 @@ pub(crate) fn pick_actions( Some(proto::MessageActions { rows }) } +/// A question card's last button: Cancel, so a question is never answered +/// only by `/stop`. Anyone who may answer may cancel. +pub(crate) fn with_dismiss( + actions: Option, + interaction: &InteractionId, +) -> Option { + let mut actions = actions.unwrap_or_default(); + let Ok(data) = serde_json::to_vec(&ActionData::Dismiss { + i: interaction.to_string(), + }) else { + return Some(actions); + }; + let cancel = proto::MessageAction { + action_id: "v2-qx".to_owned(), + text: QUESTION_CANCEL.to_owned(), + action: Some(proto::message_action::Action::Callback( + proto::MessageActionCallback { data }, + )), + style: proto::message_action::Style::Default as i32, + required_grant: proto::AgentGrantRequirement::Access as i32, + ..Default::default() + }; + // Inline takes at most eight rows: with eight options, Cancel shares + // the last one. + let full = actions.rows.len() >= MAX_ACTION_ROWS; + match actions.rows.last_mut() { + Some(last) if full => last.actions.push(cancel), + _ => actions.rows.push(proto::MessageActionRow { + actions: vec![cancel], + }), + } + Some(actions) +} + +/// Rows of buttons Inline takes on one message +/// (`server/src/modules/message/messageActions.ts` `maxRows`). +const MAX_ACTION_ROWS: usize = 8; + +/// The label of a question card's cancel button. +pub(crate) const QUESTION_CANCEL: &str = "Cancel"; + /// Approval buttons with the harness's own labels, one per row. pub(crate) fn card_actions( interaction: &InteractionId, @@ -4776,6 +4877,50 @@ mod tests { assert!(buttons.rows[0].actions[0].text.encode_utf16().count() <= MAX_BUTTON_UTF16); } + #[test] + fn an_eight_option_question_keeps_cancel_within_inlines_eight_rows() { + use inline_agent_bridge::harness::{FieldOption, FormField}; + let interaction = InteractionId::new("q-8").unwrap(); + let form = QuestionForm { + title: None, + fields: vec![FormField { + id: FieldId::new("pick").unwrap(), + header: None, + prompt: "Pick one".to_owned(), + input: FieldInput::Select { + options: (0..8) + .map(|index| FieldOption { + label: format!("option {index}"), + description: None, + preview: None, + }) + .collect(), + multiple: false, + allow_other: false, + }, + required: true, + }], + asynchronous: false, + auto_resolution_ms: None, + }; + assert!(render::pickable(&form)); + let actions = with_dismiss(pick_actions(&interaction, &form, 0), &interaction).unwrap(); + assert_eq!(actions.rows.len(), MAX_ACTION_ROWS); + let last: Vec<&str> = actions.rows[7] + .actions + .iter() + .map(|action| action.text.as_str()) + .collect(); + assert_eq!(last, ["option 7", QUESTION_CANCEL]); + // Fewer options: Cancel has a row of its own. + let mut short = form.clone(); + if let FieldInput::Select { options, .. } = &mut short.fields[0].input { + options.truncate(3); + } + let actions = with_dismiss(pick_actions(&interaction, &short, 0), &interaction).unwrap(); + assert_eq!(actions.rows.len(), 4); + } + #[test] fn approval_buttons_carry_the_decision_and_require_approve() { let interaction = InteractionId::new("req-1").unwrap(); @@ -5215,6 +5360,295 @@ pub(crate) mod recovery_tests { assert!(work.outbox.iter().any(|outgoing| outgoing.plan)); } + /// Codex asking to run MCP tools, as its driver reports it: a tool card + /// with Codex's choices. Allow is answered once, Cancel answers its own + /// card, and a card Codex withdrew (its turn ended) answers nothing. + pub(crate) async fn codex_mcp_tool_card_taps(agent: Arc, session: Arc) { + use inline_agent_bridge::harness::{ + ApprovalSubject, ClosedBy, Decision, DecisionKind, Envelope, Interaction, + InteractionKind, + }; + + let decision = |id: &str, label: &str, kind| Decision { + id: inline_agent_bridge::harness::DecisionId::new(id).unwrap(), + label: label.to_owned(), + kind, + description: None, + accepts_message: false, + native: serde_json::Value::Null, + }; + let key = session.key().clone(); + let mut seq = 0; + let mut envelope = |event| { + seq += 1; + Envelope { + session: key.clone(), + seq, + checkpoint: None, + at_ms: 0, + event, + } + }; + let mut work = actor(agent); + work.hold + .handle(HoldEvent::AcquireRequested { input: None }, 0); + work.hold.handle(HoldEvent::Acquired, 0); + work.session = Some(session); + + for (message_id, id, tool) in [ + (50, "51", "create_issue"), + (51, "52", "delete_issue"), + (52, "53", "list_issues"), + ] { + let interaction = InteractionId::new(id).unwrap(); + work.envelope(envelope(Event::Interaction(Interaction { + id: interaction.clone(), + turn: Some(TurnId::new("turn-1").unwrap()), + item: None, + parent: None, + kind: InteractionKind::Approval { + subject: ApprovalSubject::Tool { + name: format!("linear · {tool}"), + input: serde_json::json!({"team": "ENG"}), + reason: None, + }, + decisions: vec![ + decision("accept", "Allow", DecisionKind::Accept), + decision( + "acceptForSession", + "Allow for this session", + DecisionKind::AcceptForSession, + ), + decision("cancel", "Cancel", DecisionKind::Decline), + ], + }, + native: serde_json::Value::Null, + }))) + .await; + // The card goes out with Codex's choices as its buttons. + let outgoing = work + .outbox + .iter() + .find(|outgoing| { + outgoing + .card + .as_ref() + .is_some_and(|(card, _)| card == &interaction) + }) + .expect("a card"); + assert!(outgoing.doc.text.contains(&format!("linear · {tool}"))); + let labels: Vec<&str> = outgoing + .actions + .iter() + .flat_map(|actions| &actions.rows) + .flat_map(|row| &row.actions) + .map(|action| action.text.as_str()) + .collect(); + assert_eq!(labels, ["Allow", "Allow for this session", "Cancel"]); + // As if Inline took the post (no server here). + work.card_by_interaction + .insert(interaction.clone(), message_id); + work.cards.insert( + message_id, + Card { + chat: 9, + interaction, + approval: true, + form: None, + answered: Vec::new(), + }, + ); + } + let tap = |id: &str, decision: &str| ActionData::Decision { + i: id.to_owned(), + d: decision.to_owned(), + }; + + // Allow reaches Codex; a second press finds nothing pending. + assert_eq!(work.action(50, 1, tap("51", "accept")).await, None); + assert_eq!( + work.action(50, 1, tap("51", "accept")).await.as_deref(), + Some(NOT_PENDING) + ); + // Cancel answers its own card. + assert_eq!(work.action(51, 1, tap("52", "cancel")).await, None); + + // Codex withdraws the third when its turn ends: the card closes + // with no buttons, and a late tap reaches nothing. + work.envelope(envelope(Event::InteractionClosed { + id: InteractionId::new("53").unwrap(), + by: ClosedBy::Cancelled, + })) + .await; + assert!(!work.cards.contains_key(&52)); + let closed = work + .outbox + .iter() + .find(|outgoing| outgoing.closed && outgoing.doc.text.contains("list_issues")) + .expect("the closed card"); + assert!(closed.doc.text.contains("No longer needed")); + assert!(closed.actions.iter().all(|actions| actions.rows.is_empty())); + // A tap on the withdrawn card reaches nothing and says so. + assert_eq!( + work.action(52, 1, tap("53", "accept")).await.as_deref(), + Some(NOT_PENDING) + ); + } + + /// A question card ends with Cancel, which tells the harness it was not + /// answered; `/stop` with no turn running cancels what the open cards + /// wait on (a Codex elicitation may name no turn). + pub(crate) async fn question_cancel_and_turnless_stop( + agent: Arc, + session: Arc, + ) { + use inline_agent_bridge::harness::{ + ApprovalSubject, Envelope, FieldOption, FormField, Interaction, InteractionKind, + }; + + let key = session.key().clone(); + let mut work = actor(agent); + work.hold + .handle(HoldEvent::AcquireRequested { input: None }, 0); + work.hold.handle(HoldEvent::Acquired, 0); + work.session = Some(session); + + let form = QuestionForm { + title: Some("Where should it deploy?".to_owned()), + fields: vec![FormField { + id: FieldId::new("region").unwrap(), + header: None, + prompt: "Region".to_owned(), + input: FieldInput::Select { + options: ["fra", "iad"] + .into_iter() + .map(|label| FieldOption { + label: label.to_owned(), + description: None, + preview: None, + }) + .collect(), + multiple: false, + allow_other: false, + }, + required: true, + }], + asynchronous: false, + auto_resolution_ms: None, + }; + let approval = || InteractionKind::Approval { + subject: ApprovalSubject::Other { + title: "Share your notes with this server?".to_owned(), + detail: None, + }, + decisions: Vec::new(), + }; + let asynchronous = QuestionForm { + asynchronous: true, + ..form.clone() + }; + let cards = [ + ( + "61", + 60, + InteractionKind::Question { form: form.clone() }, + None, + ), + ("62", 61, approval(), None), + // Left open on purpose, and a running turn's own request: a + // stop with nothing running leaves both. + ( + "63", + 62, + InteractionKind::Question { form: asynchronous }, + None, + ), + ("64", 63, approval(), Some("sub-agent-turn")), + ]; + for (seq, (id, message_id, kind, turn)) in cards.into_iter().enumerate() { + let interaction = InteractionId::new(id).unwrap(); + let card_form = match &kind { + InteractionKind::Question { form } => Some(form.clone()), + _ => None, + }; + let question = card_form.is_some(); + work.envelope(Envelope { + session: key.clone(), + seq: seq as u64 + 1, + checkpoint: None, + at_ms: 0, + event: Event::Interaction(Interaction { + id: interaction.clone(), + turn: turn.map(|turn| TurnId::new(turn).unwrap()), + item: None, + parent: None, + kind, + native: serde_json::Value::Null, + }), + }) + .await; + if id == "61" { + let outgoing = work + .outbox + .iter() + .find(|outgoing| { + outgoing + .card + .as_ref() + .is_some_and(|(card, _)| card == &interaction) + }) + .expect("a card"); + let labels: Vec<&str> = outgoing + .actions + .iter() + .flat_map(|actions| &actions.rows) + .flat_map(|row| &row.actions) + .map(|action| action.text.as_str()) + .collect(); + assert_eq!(labels, ["fra", "iad", QUESTION_CANCEL]); + } + work.card_by_interaction + .insert(interaction.clone(), message_id); + work.cards.insert( + message_id, + Card { + chat: 9, + interaction, + approval: !question, + form: card_form, + answered: Vec::new(), + }, + ); + } + + // Cancel on the question; a cancel on an approval card is refused. + assert_eq!( + work.action(61, 1, ActionData::Dismiss { i: "62".into() }) + .await + .as_deref(), + Some(NOT_PENDING) + ); + assert_eq!( + work.action(60, 1, ActionData::Dismiss { i: "61".into() }) + .await, + None + ); + // No turn is running: /stop cancels what the open cards wait on. + work.cards.remove(&60); + assert_eq!(work.control(Control::Stop, 1).await, None); + // Again: 62 is answered, and 63 and 64 are not a stop's to end. + assert_eq!( + work.control(Control::Stop, 1).await.as_deref(), + Some(NOTHING_RUNNING) + ); + // With nothing open, it says so. + work.cards.clear(); + assert_eq!( + work.control(Control::Stop, 1).await.as_deref(), + Some(NOTHING_RUNNING) + ); + } + pub(crate) async fn pending_output_survives_restart(agent: Arc) { let mut work = actor(agent.clone()); work.render(vec![RenderOp::Final { diff --git a/crates/agent-bridge/tests/fixtures/harness/codex/mcp-tool-approval.json b/crates/agent-bridge/tests/fixtures/harness/codex/mcp-tool-approval.json new file mode 100644 index 000000000..3d5a8b7a3 --- /dev/null +++ b/crates/agent-bridge/tests/fixtures/harness/codex/mcp-tool-approval.json @@ -0,0 +1,416 @@ +{ + "provider": "codex", + "harness": "codex app-server (codex-rs main 33b3f80a, 2026-11-07)", + "recorded": false, + "source": "request shape from codex-rs core/src/mcp_tool_call.rs build_mcp_tool_approval_elicitation_request and app-server-protocol v2 McpServerElicitationRequestParams; choices, labels and responses from tui/src/bottom_pane/mcp_server_elicitation.rs", + "description": "Codex asks to run MCP tools through message-only form elicitations: each is a tool approval card with Codex's own choices (remember options only as `_meta.persist` allows), answered with the whole elicitation response. A call app-server could not correlate to a turn belongs to the running one, and an unanswered card closes when the interrupted turn ends.", + "steps": [ + { + "name": "turn started", + "native": { + "method": "turn/started", + "params": { + "threadId": "thr-1", + "turn": { + "id": "turn-1", + "items": [], + "status": "inProgress" + } + } + }, + "events": [ + { + "phase": { + "phase": "started" + }, + "turn": "turn-1", + "type": "turn" + } + ] + }, + { + "name": "Codex asks to run an MCP tool, as a message-only form with its choices in _meta", + "native": { + "id": 51, + "method": "mcpServer/elicitation/request", + "params": { + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "persist": [ + "session", + "always" + ], + "tool_name": "create_issue", + "tool_params": { + "labels": [ + "bug" + ], + "team": "ENG", + "title": "Parser drops trailing commas" + } + }, + "message": "Allow the linear MCP server to run tool \"create_issue\"?", + "mode": "form", + "requestedSchema": { + "properties": {}, + "type": "object" + }, + "serverName": "linear", + "threadId": "thr-1", + "turnId": "turn-1" + } + }, + "events": [ + { + "id": "51", + "kind": { + "decisions": [ + { + "id": "accept", + "kind": "accept", + "label": "Allow", + "native": { + "action": "accept" + } + }, + { + "id": "acceptForSession", + "kind": "accept_for_session", + "label": "Allow for this session", + "native": { + "_meta": { + "persist": "session" + }, + "action": "accept" + } + }, + { + "id": "acceptAlways", + "kind": "accept_and_remember", + "label": "Always allow", + "native": { + "_meta": { + "persist": "always" + }, + "action": "accept" + } + }, + { + "id": "cancel", + "kind": "decline", + "label": "Cancel", + "native": { + "_meta": { + "codex_approval_cancellation_reason": "user" + }, + "action": "cancel" + } + } + ], + "kind": "approval", + "subject": { + "input": { + "labels": [ + "bug" + ], + "team": "ENG", + "title": "Parser drops trailing commas" + }, + "kind": "tool", + "name": "linear · create_issue" + } + }, + "native": { + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "persist": [ + "session", + "always" + ], + "tool_name": "create_issue", + "tool_params": { + "labels": [ + "bug" + ], + "team": "ENG", + "title": "Parser drops trailing commas" + } + }, + "message": "Allow the linear MCP server to run tool \"create_issue\"?", + "mode": "form", + "requestedSchema": { + "properties": {}, + "type": "object" + }, + "serverName": "linear", + "threadId": "thr-1", + "turnId": "turn-1" + }, + "turn": "turn-1", + "type": "interaction" + } + ] + }, + { + "name": "a second call with no correlated turn belongs to the running one", + "native": { + "id": 52, + "method": "mcpServer/elicitation/request", + "params": { + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "persist": "session", + "tool_name": "delete_issue", + "tool_params": { + "id": "ENG-12" + } + }, + "message": "Allow the linear MCP server to run tool \"delete_issue\"?", + "mode": "form", + "requestedSchema": { + "properties": {}, + "type": "object" + }, + "serverName": "linear", + "threadId": "thr-1", + "turnId": null + } + }, + "events": [ + { + "id": "52", + "kind": { + "decisions": [ + { + "id": "accept", + "kind": "accept", + "label": "Allow", + "native": { + "action": "accept" + } + }, + { + "id": "acceptForSession", + "kind": "accept_for_session", + "label": "Allow for this session", + "native": { + "_meta": { + "persist": "session" + }, + "action": "accept" + } + }, + { + "id": "cancel", + "kind": "decline", + "label": "Cancel", + "native": { + "_meta": { + "codex_approval_cancellation_reason": "user" + }, + "action": "cancel" + } + } + ], + "kind": "approval", + "subject": { + "input": { + "id": "ENG-12" + }, + "kind": "tool", + "name": "linear · delete_issue" + } + }, + "native": { + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "persist": "session", + "tool_name": "delete_issue", + "tool_params": { + "id": "ENG-12" + } + }, + "message": "Allow the linear MCP server to run tool \"delete_issue\"?", + "mode": "form", + "requestedSchema": { + "properties": {}, + "type": "object" + }, + "serverName": "linear", + "threadId": "thr-1" + }, + "turn": "turn-1", + "type": "interaction" + } + ] + }, + { + "name": "a third call, left unanswered", + "native": { + "id": 53, + "method": "mcpServer/elicitation/request", + "params": { + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "tool_name": "list_issues", + "tool_params": {} + }, + "message": "Allow the linear MCP server to run tool \"list_issues\"?", + "mode": "form", + "requestedSchema": { + "properties": {}, + "type": "object" + }, + "serverName": "linear", + "threadId": "thr-1", + "turnId": "turn-1" + } + }, + "events": [ + { + "id": "53", + "kind": { + "decisions": [ + { + "id": "accept", + "kind": "accept", + "label": "Allow", + "native": { + "action": "accept" + } + }, + { + "id": "cancel", + "kind": "decline", + "label": "Cancel", + "native": { + "_meta": { + "codex_approval_cancellation_reason": "user" + }, + "action": "cancel" + } + } + ], + "kind": "approval", + "subject": { + "kind": "tool", + "name": "linear · list_issues" + } + }, + "native": { + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "tool_name": "list_issues", + "tool_params": {} + }, + "message": "Allow the linear MCP server to run tool \"list_issues\"?", + "mode": "form", + "requestedSchema": { + "properties": {}, + "type": "object" + }, + "serverName": "linear", + "threadId": "thr-1", + "turnId": "turn-1" + }, + "turn": "turn-1", + "type": "interaction" + } + ] + }, + { + "name": "the interrupted turn withdraws the unanswered card", + "native": { + "method": "turn/completed", + "params": { + "threadId": "thr-1", + "turn": { + "id": "turn-1", + "status": "interrupted" + } + } + }, + "events": [ + { + "by": { + "kind": "cancelled" + }, + "id": "53", + "type": "interaction_closed" + }, + { + "phase": { + "outcome": "interrupted", + "phase": "completed" + }, + "turn": "turn-1", + "type": "turn" + } + ] + } + ], + "responses": [ + { + "name": "allow for this session", + "after_step": "Codex asks to run an MCP tool, as a message-only form with its choices in _meta", + "interaction": "51", + "by": 101, + "response": { + "decision": "acceptForSession", + "kind": "decision" + }, + "events": [ + { + "by": { + "decision": "acceptForSession", + "kind": "inline", + "user": 101 + }, + "id": "51", + "type": "interaction_closed" + } + ], + "native": { + "id": 51, + "result": { + "_meta": { + "persist": "session" + }, + "action": "accept", + "content": null + } + } + }, + { + "name": "cancel only that call, as the person's choice", + "after_step": "a second call with no correlated turn belongs to the running one", + "interaction": "52", + "by": 101, + "response": { + "decision": "cancel", + "kind": "decision" + }, + "events": [ + { + "by": { + "decision": "cancel", + "kind": "inline", + "user": 101 + }, + "id": "52", + "type": "interaction_closed" + } + ], + "native": { + "id": 52, + "result": { + "_meta": { + "codex_approval_cancellation_reason": "user" + }, + "action": "cancel", + "content": null + } + } + } + ] +} diff --git a/crates/agent-driver-codex/src/harness/connection.rs b/crates/agent-driver-codex/src/harness/connection.rs index 6eb33807d..66d9c61f3 100644 --- a/crates/agent-driver-codex/src/harness/connection.rs +++ b/crates/agent-driver-codex/src/harness/connection.rs @@ -1149,6 +1149,16 @@ async fn dispatch( .await } _ => { + // Codex reads the error as a refusal. A request from a + // thread no session knows (a sub-agent Inline has not + // seen yet) says so where the work is, when there is + // one place it can be. + if let [session] = sessions.as_slice() + && let Some(notice) = + super::mapper::unowned_request_notice(&method, ¶ms) + { + session.emit_all(vec![notice]); + } connection .peer .respond_error(id, -32601, "not supported by Inline") diff --git a/crates/agent-driver-codex/src/harness/decisions.rs b/crates/agent-driver-codex/src/harness/decisions.rs index cb4434947..fd3a06054 100644 --- a/crates/agent-driver-codex/src/harness/decisions.rs +++ b/crates/agent-driver-codex/src/harness/decisions.rs @@ -32,11 +32,24 @@ pub(crate) fn command_decisions(params: &Value) -> Vec { &legacy } }; - available + let mut decisions: Vec = available .iter() .enumerate() .filter_map(|(index, native)| command_decision(index, native, network, extra_permissions)) - .collect() + .collect(); + // A card must always be answerable: when Codex advertised no way to say + // no (or every advertised choice was hidden), offer its cancel, which + // every app-server accepts. + if !decisions.iter().any(|decision| { + matches!( + decision.kind, + DecisionKind::Decline | DecisionKind::DeclineAndRemember | DecisionKind::Cancel + ) + }) && let Some(cancel) = command_decision(available.len(), &json!("cancel"), network, false) + { + decisions.push(cancel); + } + decisions } fn command_decision( @@ -218,6 +231,89 @@ pub(crate) fn elicitation_decisions() -> Vec { ] } +/// Decisions for a message-only form elicitation (an empty `requestedSchema`), +/// as the Codex TUI offers them (`tui/src/bottom_pane/mcp_server_elicitation.rs`). +/// Codex asks to run an MCP tool this way, with `_meta.codex_approval_kind` +/// `mcp_tool_call` and the remember choices it allows in `_meta.persist`. +/// The native value is the whole response. +/// +/// A tool approval offers Cancel, not Deny: Codex skips that one call and +/// the turn goes on, so it reads as declined. The cancel says the person +/// chose it, as the TUI's does. +pub(crate) fn message_only_decisions(params: &Value) -> Vec { + let meta = params.get("_meta"); + let mut decisions = vec![decision( + "accept", + "Allow", + DecisionKind::Accept, + false, + &json!({"action": "accept", "content": null}), + )]; + if allows_persist(meta, "session") { + decisions.push(decision( + "acceptForSession", + "Allow for this session", + DecisionKind::AcceptForSession, + false, + &json!({"action": "accept", "content": null, "_meta": {"persist": "session"}}), + )); + } + if allows_persist(meta, "always") { + decisions.push(decision( + "acceptAlways", + "Always allow", + DecisionKind::AcceptAndRemember, + false, + &json!({"action": "accept", "content": null, "_meta": {"persist": "always"}}), + )); + } + if is_tool_approval(params) { + decisions.push(decision( + "cancel", + "Cancel", + DecisionKind::Decline, + false, + &json!({ + "action": "cancel", + "content": null, + "_meta": {"codex_approval_cancellation_reason": "user"}, + }), + )); + } else { + decisions.push(decision( + "decline", + "Deny", + DecisionKind::Decline, + false, + &json!({"action": "decline", "content": null}), + )); + decisions.push(decision( + "cancel", + "Cancel", + DecisionKind::Cancel, + false, + &json!({"action": "cancel", "content": null}), + )); + } + decisions +} + +/// Whether an elicitation is Codex asking to run an MCP tool. +pub(crate) fn is_tool_approval(params: &Value) -> bool { + params + .pointer("/_meta/codex_approval_kind") + .and_then(Value::as_str) + == Some("mcp_tool_call") +} + +fn allows_persist(meta: Option<&Value>, mode: &str) -> bool { + match meta.and_then(|meta| meta.get("persist")) { + Some(Value::String(value)) => value == mode, + Some(Value::Array(values)) => values.iter().any(|value| value.as_str() == Some(mode)), + _ => false, + } +} + fn decision( id: &str, label: &str, @@ -280,6 +376,61 @@ fn shell_quote(part: &str) -> String { mod tests { use super::*; + #[test] + fn mcp_tool_approvals_offer_what_codex_allows_and_cancel_only_that_call() { + let decisions = message_only_decisions(&json!({ + "_meta": {"codex_approval_kind": "mcp_tool_call", "persist": ["session", "always"]} + })); + assert_eq!( + labels(&decisions), + ["Allow", "Allow for this session", "Always allow", "Cancel"] + ); + assert_eq!( + decisions[0].native, + json!({"action": "accept", "content": null}) + ); + assert_eq!( + decisions[1].native, + json!({"action": "accept", "content": null, "_meta": {"persist": "session"}}) + ); + assert_eq!( + decisions[2].native, + json!({"action": "accept", "content": null, "_meta": {"persist": "always"}}) + ); + // Codex skips the call and the turn goes on: declined, and said to + // be the person's choice. + assert_eq!(decisions[3].kind, DecisionKind::Decline); + assert_eq!( + decisions[3].native, + json!({ + "action": "cancel", + "content": null, + "_meta": {"codex_approval_cancellation_reason": "user"}, + }) + ); + + let session_only = message_only_decisions(&json!({ + "_meta": {"codex_approval_kind": "mcp_tool_call", "persist": "session"} + })); + assert_eq!( + labels(&session_only), + ["Allow", "Allow for this session", "Cancel"] + ); + let plain = message_only_decisions(&json!({ + "_meta": {"codex_approval_kind": "mcp_tool_call"} + })); + assert_eq!(labels(&plain), ["Allow", "Cancel"]); + + // Any other message-only request: Deny goes on without it. + let other = message_only_decisions(&json!({})); + assert_eq!(labels(&other), ["Allow", "Deny", "Cancel"]); + assert_eq!( + other[1].native, + json!({"action": "decline", "content": null}) + ); + assert_eq!(other[2].kind, DecisionKind::Cancel); + } + fn labels(decisions: &[Decision]) -> Vec<&str> { decisions .iter() @@ -350,7 +501,12 @@ mod tests { })); assert_eq!( labels(&decisions), - ["Yes, proceed", "acceptAlways", "futureChoice"] + [ + "Yes, proceed", + "acceptAlways", + "futureChoice", + "No, and tell Codex what to do differently" + ] ); assert_eq!(decisions[2].native, json!({"futureChoice": {"x": 1}})); } @@ -367,6 +523,28 @@ mod tests { assert_eq!(command_decisions(&json!({})).len(), 4); } + #[test] + fn a_command_card_can_always_say_no() { + // Every advertised choice hidden, or none advertised: Codex's cancel. + for available in [ + json!([{"acceptWithExecpolicyAmendment": {"execpolicy_amendment": ["bash", "-lc", "a\nb"]}}]), + json!([]), + ] { + let decisions = command_decisions(&json!({"availableDecisions": available})); + assert_eq!( + labels(&decisions), + ["No, and tell Codex what to do differently"] + ); + assert_eq!(decisions[0].native, json!("cancel")); + } + // Only yes: cancel joins it. + let decisions = command_decisions(&json!({"availableDecisions": ["accept"]})); + assert_eq!( + labels(&decisions), + ["Yes, proceed", "No, and tell Codex what to do differently"] + ); + } + #[test] fn prefixes_follow_the_tui_shell_rendering() { assert_eq!( diff --git a/crates/agent-driver-codex/src/harness/mapper.rs b/crates/agent-driver-codex/src/harness/mapper.rs index f059ff2a9..ce01cdba5 100644 --- a/crates/agent-driver-codex/src/harness/mapper.rs +++ b/crates/agent-driver-codex/src/harness/mapper.rs @@ -83,6 +83,9 @@ enum Pending { Permissions, ElicitationUrl, ElicitationForm, + /// A message-only form (Codex asking to run an MCP tool): answered with + /// the picked decision's native response. + ElicitationApproval, UserInput, AsyncQuestions, } @@ -115,6 +118,8 @@ pub(crate) struct CodexMapper { requests: HashMap, answered: HashSet, children: HashMap, + /// A sub-agent thread's running turn, for its requests that name none. + child_turns: HashMap, /// When the account's exhausted limit window resets, from the latest /// `account/rateLimits/updated`. limit_resets_at: Option, @@ -134,6 +139,7 @@ impl CodexMapper { requests: HashMap::new(), answered: HashSet::new(), children: HashMap::new(), + child_turns: HashMap::new(), limit_resets_at: None, lost: false, } @@ -269,6 +275,8 @@ impl CodexMapper { return mapped; }; if let Some(child) = parent { + self.child_turns + .insert(child.id.as_str().to_owned(), turn.clone()); events.push(child_update(child, ChildStatus::Running, None, params)); } else { self.active_turn = Some(turn.clone()); @@ -435,6 +443,27 @@ impl CodexMapper { }); } } + // A sub-agent's thread can ask for approval before the spawn + // item that names it arrives; its start names its parent. + "thread/started" => { + if let (Some(thread), Some(parent_thread)) = ( + string(params.pointer("/thread/id")), + string(params.pointer("/thread/parentThreadId")), + ) && thread != self.thread + && self.owns_thread(Some(&parent_thread)) + && !self.children.contains_key(&thread) + && let Ok(id) = inline_agent_bridge::harness::ChildId::new(thread.clone()) + { + self.children.insert( + thread, + ChildRef { + id, + kind: ChildKind::Subagent, + }, + ); + } + events.push(notice(NoticeLevel::Info, method, params)); + } "thread/status/changed" if parent.is_none() => { match params.pointer("/status/type").and_then(Value::as_str) { Some("idle") => events.push(Event::State { @@ -591,17 +620,10 @@ impl CodexMapper { }, }); } - if let Some(child) = parent { - let status = match outcome { - TurnOutcome::Completed => ChildStatus::Completed, - TurnOutcome::Interrupted => ChildStatus::Stopped, - _ => ChildStatus::Failed, - }; - events.push(child_update(child, status, None, params)); - return; - } - // Codex withdraws a turn's blocking requests when the turn ends. - let closed: Vec = self + // Codex withdraws a thread's blocking requests when its turn ends, + // a sub-agent's included; closed here they read as no longer needed, + // not as answered elsewhere. + let mut closed: Vec = self .requests .iter() .filter(|(_, request)| { @@ -610,6 +632,7 @@ impl CodexMapper { }) .map(|(id, _)| id.clone()) .collect(); + closed.sort(); for id in closed { self.requests.remove(&id); if let Ok(id) = InteractionId::new(id) { @@ -619,6 +642,18 @@ impl CodexMapper { }); } } + if let Some(child) = parent { + if self.child_turns.get(child.id.as_str()) == Some(&turn) { + self.child_turns.remove(child.id.as_str()); + } + let status = match outcome { + TurnOutcome::Completed => ChildStatus::Completed, + TurnOutcome::Interrupted => ChildStatus::Stopped, + _ => ChildStatus::Failed, + }; + events.push(child_update(child, status, None, params)); + return; + } if self.active_turn.as_ref() == Some(&turn) { self.active_turn = None; } @@ -813,9 +848,18 @@ impl CodexMapper { let Some(id) = request_id_string(Some(rpc_id)) else { return RequestMapped::NotMine; }; - let turn = turn_id(params.get("turnId")); + let mut turn = turn_id(params.get("turnId")); let item = item_id(params.get("itemId")); let parent = self.parent_of(params); + // An elicitation's `turnId` is nullable. Codex withdraws a thread's + // requests when its turn ends, so one seen during a thread's turn + // belongs to it, and its card closes with it. + if turn.is_none() && method == "mcpServer/elicitation/request" { + turn = match &parent { + None => self.active_turn.clone(), + Some(child) => self.child_turns.get(child.id.as_str()).cloned(), + }; + } let (kind, pending, decisions) = match method { "item/commandExecution/requestApproval" => { let decisions = decisions::command_decisions(params); @@ -878,6 +922,17 @@ impl CodexMapper { None => return self.cancel_dialog(id, method, params), }, "mcpServer/elicitation/request" => match params.get("mode").and_then(Value::as_str) { + Some("form") if is_message_only(params) => { + let decisions = decisions::message_only_decisions(params); + ( + InteractionKind::Approval { + subject: message_only_subject(params), + decisions: decisions.clone(), + }, + Pending::ElicitationApproval, + decisions, + ) + } Some("form") => match elicitation_form(params) { Some(form) => ( InteractionKind::Question { form }, @@ -1025,7 +1080,13 @@ impl CodexMapper { (Pending::ElicitationUrl, InteractionResponse::Decision { .. }) => { json!({"action": picked.as_ref().expect("picked").native}) } - (Pending::ElicitationUrl | Pending::ElicitationForm, InteractionResponse::Cancel) => { + (Pending::ElicitationApproval, InteractionResponse::Decision { .. }) => { + picked.as_ref().expect("picked").native.clone() + } + ( + Pending::ElicitationUrl | Pending::ElicitationForm | Pending::ElicitationApproval, + InteractionResponse::Cancel, + ) => { json!({"action": "cancel"}) } (Pending::ElicitationForm, InteractionResponse::Answers { answers }) => { @@ -1245,6 +1306,178 @@ fn user_input_form(params: &Value) -> Option { }) } +/// A form that asks for nothing but a yes or no: no schema, or an object +/// schema with no properties. Codex asks to run an MCP tool this way. +fn is_message_only(params: &Value) -> bool { + match params.get("requestedSchema") { + None | Some(Value::Null) => true, + Some(schema) => schema + .get("properties") + .and_then(Value::as_object) + .is_some_and(Map::is_empty), + } +} + +/// Arguments a tool approval shows, at most. +const MAX_TOOL_PARAMS: usize = 12; +/// Characters of one text argument a tool approval shows. +const MAX_TOOL_PARAM_CHARS: usize = 600; +/// Items of an array, or entries of an object, inside an argument. +const MAX_TOOL_PARAM_ITEMS: usize = 8; +/// Nesting kept inside an argument; deeper values read `…`. +const MAX_TOOL_PARAM_DEPTH: usize = 3; + +/// What a message-only elicitation asks. Codex's tool approval is the tool, +/// named as other agents' tool cards name it (`server · tool`), with its +/// arguments; Codex's message is kept when it says more than the generic +/// question. +fn message_only_subject(params: &Value) -> ApprovalSubject { + let message = string(params.get("message")).map(|message| sanitized(&message, 2_000)); + let tool = params + .pointer("/_meta/tool_title") + .or_else(|| params.pointer("/_meta/tool_name")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|tool| !tool.is_empty()); + match tool { + Some(tool) if decisions::is_tool_approval(params) => { + let tool = sanitized(tool, 120); + let name = match string(params.get("serverName")) { + Some(server) => format!("{} · {tool}", sanitized(&server, 120)), + None => tool.clone(), + }; + // "Allow the x MCP server to run tool "y"?" (by the tool's raw + // name) says nothing the card does not; a consequential tool's + // own message does. + let raw = params + .pointer("/_meta/tool_name") + .and_then(Value::as_str) + .map(|raw| sanitized(raw, 120)); + let generic = |message: &String| { + message.starts_with("Allow ") + && [Some(&tool), raw.as_ref()] + .into_iter() + .flatten() + .any(|name| message.ends_with(&format!("run tool \"{name}\"?"))) + }; + ApprovalSubject::Tool { + name, + input: tool_params(params), + reason: message.filter(|message| !generic(message)), + } + } + _ => ApprovalSubject::Other { + title: message.unwrap_or_else(|| "Allow this request?".to_owned()), + detail: None, + }, + } +} + +/// The arguments of an MCP tool Codex asks to run, as the Codex TUI picks +/// them (`tool_params_display` names, else `tool_params` by name), bounded +/// and with control and direction-override characters removed. Codex sends +/// the whole call; a card shows enough to decide on. +fn tool_params(params: &Value) -> Value { + let Some(meta) = params.get("_meta") else { + return Value::Null; + }; + let mut rows: Vec<(String, &Value)> = meta + .get("tool_params_display") + .and_then(Value::as_array) + .map(|rows| { + rows.iter() + .filter_map(|row| { + let name = + string(row.get("display_name")).or_else(|| string(row.get("name")))?; + Some((name, row.get("value")?)) + }) + .collect() + }) + .unwrap_or_default(); + if rows.is_empty() { + rows = meta + .get("tool_params") + .and_then(Value::as_object) + .map(|object| { + object + .iter() + .map(|(name, value)| (name.clone(), value)) + .collect() + }) + .unwrap_or_default(); + rows.sort_by(|left, right| left.0.cmp(&right.0)); + } + if rows.is_empty() { + return Value::Null; + } + let total = rows.len(); + let mut shown = Map::new(); + for (name, value) in rows.into_iter().take(MAX_TOOL_PARAMS) { + shown.insert(sanitized(&name, 120), bounded(value, 0)); + } + if total > MAX_TOOL_PARAMS { + shown.insert( + "…".to_owned(), + json!(format!("{} more", total - MAX_TOOL_PARAMS)), + ); + } + Value::Object(shown) +} + +fn bounded(value: &Value, depth: usize) -> Value { + match value { + Value::String(text) => Value::String(sanitized(text, MAX_TOOL_PARAM_CHARS)), + Value::Array(_) | Value::Object(_) if depth >= MAX_TOOL_PARAM_DEPTH => json!("…"), + Value::Array(items) => { + let mut shown: Vec = items + .iter() + .take(MAX_TOOL_PARAM_ITEMS) + .map(|item| bounded(item, depth + 1)) + .collect(); + if items.len() > MAX_TOOL_PARAM_ITEMS { + shown.push(json!(format!( + "… {} more", + items.len() - MAX_TOOL_PARAM_ITEMS + ))); + } + Value::Array(shown) + } + Value::Object(object) => { + let mut shown: Map = object + .iter() + .take(MAX_TOOL_PARAM_ITEMS) + .map(|(key, value)| (sanitized(key, 120), bounded(value, depth + 1))) + .collect(); + if object.len() > MAX_TOOL_PARAM_ITEMS { + shown.insert( + "…".to_owned(), + json!(format!("{} more", object.len() - MAX_TOOL_PARAM_ITEMS)), + ); + } + Value::Object(shown) + } + other => other.clone(), + } +} + +/// `text` without control characters (newlines and tabs stay) or bidi +/// overrides that could disguise it, cut to `max` characters. +fn sanitized(text: &str, max: usize) -> String { + let mut clean = text + .chars() + .filter(|character| { + (!character.is_control() || matches!(character, '\n' | '\t')) + && !matches!(character, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') + }) + .take(max + 1) + .collect::(); + if clean.chars().count() > max { + clean = clean.chars().take(max).collect(); + clean.push('…'); + } + clean +} + fn elicitation_form(params: &Value) -> Option { let schema = params.get("requestedSchema")?; let required: HashSet<&str> = schema @@ -1319,8 +1552,10 @@ fn enum_options(property: &Value) -> Vec { if !direct.is_empty() { return direct; } - if let Some(one_of) = property.get("oneOf").and_then(Value::as_array) { - return one_of + // Titled choices: `oneOf` for one, `items.anyOf` for several (MCP + // 2025-11-25 `TitledSingleSelectEnumSchema` / `TitledMultiSelectEnumSchema`). + let titled = |choices: &Vec| -> Vec { + choices .iter() .filter_map(|option| { Some(FieldOption { @@ -1329,7 +1564,15 @@ fn enum_options(property: &Value) -> Vec { preview: None, }) }) - .collect(); + .collect() + }; + for pointer in ["/oneOf", "/anyOf", "/items/anyOf", "/items/oneOf"] { + if let Some(choices) = property.pointer(pointer).and_then(Value::as_array) { + let options = titled(choices); + if !options.is_empty() { + return options; + } + } } from(property.pointer("/items/enum"), None) } @@ -1778,6 +2021,23 @@ fn command_text(value: Option<&Value>) -> Option { } } +/// The notice for a thread's request no session took: Codex hears it was +/// refused, and the chat says so (an error notice, so it is shown, titled as +/// Claude's declined requests are). `None` for connection-level requests, +/// which name no thread. +pub(crate) fn unowned_request_notice(method: &str, params: &Value) -> Option { + params.get("threadId").and_then(Value::as_str)?; + Some(Event::Notice(Notice { + level: NoticeLevel::Error, + code: "Request declined".to_owned(), + message: Some(format!( + "Codex asked for `{}` from a sub-agent Inline hadn't seen yet, so it was declined.", + sanitized(method, 80) + )), + native: params.clone(), + })) +} + fn notice(level: NoticeLevel, code: &str, native: &Value) -> Event { Event::Notice(Notice { level, @@ -1875,6 +2135,466 @@ mod tests { assert!(mapped.events.is_empty()); } + /// Codex asking to run an MCP tool (codex-rs `core/src/mcp_tool_call.rs` + /// `build_mcp_tool_approval_elicitation_request`), as app-server sends it. + fn mcp_tool_approval(turn: Value, meta: Value) -> Value { + let mut meta_object = json!({ + "codex_approval_kind": "mcp_tool_call", + "persist": ["session", "always"], + "tool_name": "execute", + "tool_params": {"code": "async () => 1", "account": "acme"} + }); + if let (Some(base), Some(extra)) = (meta_object.as_object_mut(), meta.as_object()) { + base.extend(extra.clone()); + } + json!({ + "threadId": "thread-1", + "turnId": turn, + "serverName": "cloudflare-api", + "mode": "form", + "message": "Allow the cloudflare-api MCP server to run tool \"execute\"?", + "requestedSchema": {"type": "object", "properties": {}}, + "_meta": meta_object + }) + } + + fn approval_of(mapped: RequestMapped) -> (ApprovalSubject, Vec) { + let RequestMapped::Interaction(events) = mapped else { + panic!("expected an interaction, got {mapped:?}"); + }; + match events.into_iter().next() { + Some(Event::Interaction(Interaction { + kind: InteractionKind::Approval { subject, decisions }, + .. + })) => (subject, decisions), + other => panic!("expected an approval, got {other:?}"), + } + } + + fn respond(mapper: &mut CodexMapper, id: &str, decision: &str) -> Value { + match mapper.answer( + &InteractionId::new(id).expect("id"), + &InteractionResponse::Decision { + decision: DecisionId::new(decision).expect("id"), + message: None, + }, + UserId(1), + ) { + Ok(AnswerPlan::Respond { result, events, .. }) => { + assert!(matches!( + events.as_slice(), + [Event::InteractionClosed { + by: ClosedBy::Inline { .. }, + .. + }] + )); + result + } + other => panic!("unexpected {other:?}"), + } + } + + /// Live repro (Nov 23): Codex asked to run coolify's `manage_notifications` + /// and Inline showed only the message, with nothing to press, while + /// Codex waited. The message-only form was a question with no fields. + #[test] + fn the_message_only_tool_approval_form_is_never_a_fieldless_question() { + let mut mapper = CodexMapper::new("thread-1"); + let mapped = mapper.server_request( + &json!(0), + "mcpServer/elicitation/request", + &json!({ + "threadId": "thread-1", + "turnId": "turn-1", + "serverName": "coolify", + "mode": "form", + "message": "Allow the coolify MCP server to run tool \"manage_notifications\"?", + "requestedSchema": {"type": "object", "properties": {}}, + "_meta": { + "codex_approval_kind": "mcp_tool_call", + "persist": ["session", "always"], + "tool_name": "manage_notifications", + "tool_params": {"action": "list"} + } + }), + ); + let (subject, decisions) = approval_of(mapped); + assert_eq!( + subject, + ApprovalSubject::Tool { + name: "coolify · manage_notifications".to_owned(), + input: json!({"action": "list"}), + reason: None, + } + ); + let labels: Vec<&str> = decisions.iter().map(|d| d.label.as_str()).collect(); + assert_eq!( + labels, + ["Allow", "Allow for this session", "Always allow", "Cancel"] + ); + // Codex is waiting on this request until Inline answers it. + assert_eq!( + respond(&mut mapper, "0", "accept"), + json!({"action": "accept", "content": null}) + ); + } + + #[test] + fn an_mcp_tool_approval_is_a_tool_card_and_allow_answers_codex() { + let mut mapper = CodexMapper::new("thread-1"); + let (subject, decisions) = approval_of(mapper.server_request( + &json!(9), + "mcpServer/elicitation/request", + &mcp_tool_approval(json!("turn-1"), json!({})), + )); + assert_eq!( + subject, + ApprovalSubject::Tool { + name: "cloudflare-api · execute".to_owned(), + input: json!({"account": "acme", "code": "async () => 1"}), + // Codex's generic question adds nothing to the card. + reason: None, + } + ); + let ids: Vec<&str> = decisions.iter().map(|d| d.id.as_str()).collect(); + assert_eq!( + ids, + ["accept", "acceptForSession", "acceptAlways", "cancel"] + ); + + assert_eq!( + respond(&mut mapper, "9", "accept"), + json!({"action": "accept", "content": null}) + ); + // Claimed once: a second tap finds nothing pending. + assert_eq!( + mapper.answer( + &InteractionId::new("9").expect("id"), + &InteractionResponse::Decision { + decision: DecisionId::new("accept").expect("id"), + message: None, + }, + UserId(1), + ), + Err(OpError::InteractionNotPending) + ); + + // Allow for this session asks Codex to remember it. + mapper.server_request( + &json!(10), + "mcpServer/elicitation/request", + &mcp_tool_approval(json!("turn-1"), json!({})), + ); + assert_eq!( + respond(&mut mapper, "10", "acceptForSession"), + json!({"action": "accept", "content": null, "_meta": {"persist": "session"}}) + ); + + // A titled tool is named by its title; the generic question still + // names the raw tool and adds nothing. + let (subject, _) = approval_of(mapper.server_request( + &json!(13), + "mcpServer/elicitation/request", + &mcp_tool_approval(json!("turn-1"), json!({"tool_title": "Run code"})), + )); + assert!(matches!( + subject, + ApprovalSubject::Tool { ref name, reason: None, .. } if name == "cloudflare-api · Run code" + )); + } + + #[test] + fn denying_an_mcp_tool_cancels_that_call_as_the_persons_choice() { + let mut mapper = CodexMapper::new("thread-1"); + let (subject, decisions) = approval_of( + mapper.server_request( + &json!("e-1"), + "mcpServer/elicitation/request", + &mcp_tool_approval( + json!("turn-1"), + json!({ + "persist": null, + "tool_title": "Send email", + "tool_params_display": [ + {"name": "to", "display_name": "To", "value": "pat@example.com"}, + {"name": "subject", "display_name": "Subject", "value": "Hi"} + ] + }), + ) + .as_object() + .map(|params| { + let mut params = params.clone(); + params.insert( + "message".to_owned(), + json!("Allow Gmail to send an email to pat@example.com?"), + ); + Value::Object(params) + }) + .expect("object"), + ), + ); + // A consequential tool's own message is the reason; the display + // names Codex rendered win over the raw arguments. + assert_eq!( + subject, + ApprovalSubject::Tool { + name: "cloudflare-api · Send email".to_owned(), + input: json!({"To": "pat@example.com", "Subject": "Hi"}), + reason: Some("Allow Gmail to send an email to pat@example.com?".to_owned()), + } + ); + let labels: Vec<&str> = decisions.iter().map(|d| d.label.as_str()).collect(); + assert_eq!(labels, ["Allow", "Cancel"]); + assert_eq!( + respond(&mut mapper, "e-1", "cancel"), + json!({ + "action": "cancel", + "content": null, + "_meta": {"codex_approval_cancellation_reason": "user"}, + }) + ); + } + + #[test] + fn an_unanswered_mcp_tool_card_closes_when_its_turn_ends() { + let mut mapper = CodexMapper::new("thread-1"); + mapper.notification( + "turn/started", + &json!({"threadId": "thread-1", "turn": {"id": "turn-1"}}), + ); + // app-server could not correlate the turn: the elicitation still + // belongs to the running one. + approval_of(mapper.server_request( + &json!(11), + "mcpServer/elicitation/request", + &mcp_tool_approval(Value::Null, json!({})), + )); + let mapped = mapper.notification( + "turn/completed", + &json!({"threadId": "thread-1", "turn": {"id": "turn-1", "status": "interrupted"}}), + ); + assert!(mapped.events.iter().any(|event| matches!( + event, + Event::InteractionClosed { id, by: ClosedBy::Cancelled } if id.as_str() == "11" + ))); + // A tap on the stale card reaches nothing. + assert_eq!( + mapper.answer( + &InteractionId::new("11").expect("id"), + &InteractionResponse::Decision { + decision: DecisionId::new("accept").expect("id"), + message: None, + }, + UserId(1), + ), + Err(OpError::InteractionNotPending) + ); + // Withdrawn by Codex before anyone answered: no second close. + let mapped = mapper.notification( + "serverRequest/resolved", + &json!({"threadId": "thread-1", "requestId": 11}), + ); + assert!(mapped.events.is_empty()); + } + + #[test] + fn a_sub_agent_asks_before_its_spawn_item_and_its_card_closes_with_its_turn() { + let mut mapper = CodexMapper::new("thread-1"); + mapper.notification( + "thread/started", + &json!({"thread": {"id": "child-1", "parentThreadId": "thread-1"}}), + ); + mapper.notification( + "turn/started", + &json!({"threadId": "child-1", "turn": {"id": "child-turn-1"}}), + ); + let mut params = mcp_tool_approval(Value::Null, json!({})); + params["threadId"] = json!("child-1"); + let RequestMapped::Interaction(events) = + mapper.server_request(&json!(15), "mcpServer/elicitation/request", ¶ms) + else { + panic!("the sub-agent's request is this session's"); + }; + assert!(matches!( + events.first(), + Some(Event::Interaction(Interaction { parent: Some(child), .. })) + if child.id.as_str() == "child-1" + )); + let mapped = mapper.notification( + "turn/completed", + &json!({"threadId": "child-1", "turn": {"id": "child-turn-1", "status": "interrupted"}}), + ); + assert!(mapped.events.iter().any(|event| matches!( + event, + Event::InteractionClosed { id, by: ClosedBy::Cancelled } if id.as_str() == "15" + ))); + // Codex's later resolved notice is not "answered outside Inline". + assert!( + mapper + .notification( + "serverRequest/resolved", + &json!({"threadId": "child-1", "requestId": 15}), + ) + .events + .is_empty() + ); + // Someone else's thread stays someone else's. + mapper.notification( + "thread/started", + &json!({"thread": {"id": "stranger", "parentThreadId": "other"}}), + ); + assert!(!mapper.owns_thread(Some("stranger"))); + } + + #[test] + fn a_refused_request_from_an_unknown_thread_is_said_aloud() { + let Some(Event::Notice(notice)) = unowned_request_notice( + "mcpServer/elicitation/request", + &json!({"threadId": "child-9", "mode": "form"}), + ) else { + panic!("expected a notice"); + }; + // Errors are what the chat shows. + assert_eq!(notice.level, NoticeLevel::Error); + assert_eq!(notice.code, "Request declined"); + assert!( + notice + .message + .as_deref() + .is_some_and(|text| text.contains("mcpServer/elicitation/request")) + ); + assert!(unowned_request_notice("currentTime/read", &json!({})).is_none()); + } + + #[test] + fn tool_arguments_on_a_card_are_bounded_and_cleaned() { + let long = "x".repeat(MAX_TOOL_PARAM_CHARS + 50); + let mut many = Map::new(); + for index in 0..MAX_TOOL_PARAMS + 3 { + many.insert(format!("p{index:02}"), json!(index)); + } + many.insert("body".to_owned(), json!(long)); + many.insert( + "evil".to_owned(), + json!("safe\u{202E}gpj.exe\u{1b}[2J\nnext"), + ); + many.insert( + "deep".to_owned(), + json!({"a": {"b": {"c": {"d": 1}}}, "list": (0..20).collect::>()}), + ); + let input = tool_params(&json!({"_meta": {"tool_params": many}})); + let object = input.as_object().expect("object"); + assert_eq!(object.len(), MAX_TOOL_PARAMS + 1); + assert_eq!(object["…"], json!("6 more")); + let body = object["body"].as_str().expect("text"); + assert_eq!(body.chars().count(), MAX_TOOL_PARAM_CHARS + 1); + assert!(body.ends_with('…')); + assert_eq!(object["evil"], json!("safegpj.exe[2J\nnext")); + assert_eq!(object["deep"]["a"]["b"], json!({"c": "…"})); + let list = object["deep"]["list"].as_array().expect("list"); + assert_eq!(list.len(), MAX_TOOL_PARAM_ITEMS + 1); + assert_eq!(list[MAX_TOOL_PARAM_ITEMS], json!("… 12 more")); + // No arguments: nothing to show. + assert_eq!(tool_params(&json!({"_meta": {}})), Value::Null); + } + + #[test] + fn a_titled_multi_select_is_a_choice_answered_with_its_values() { + let mut mapper = CodexMapper::new("thread-1"); + let mapped = mapper.server_request( + &json!(14), + "mcpServer/elicitation/request", + &json!({ + "threadId": "thread-1", + "turnId": "turn-1", + "serverName": "deploy", + "mode": "form", + "message": "Where should it deploy?", + "requestedSchema": {"type": "object", "properties": {"regions": { + "type": "array", + "title": "Regions", + "items": {"anyOf": [ + {"const": "fra", "title": "Frankfurt"}, + {"const": "iad", "title": "Virginia"} + ]} + }}} + }), + ); + let RequestMapped::Interaction(events) = mapped else { + panic!("expected an interaction"); + }; + let Some(Event::Interaction(Interaction { + kind: InteractionKind::Question { form }, + .. + })) = events.first() + else { + panic!("expected a question"); + }; + let FieldInput::Select { + options, multiple, .. + } = &form.fields[0].input + else { + panic!("expected a choice, got {:?}", form.fields[0].input); + }; + assert!(*multiple); + let labels: Vec<(&str, Option<&str>)> = options + .iter() + .map(|option| (option.label.as_str(), option.description.as_deref())) + .collect(); + assert_eq!( + labels, + [("fra", Some("Frankfurt")), ("iad", Some("Virginia"))] + ); + let plan = mapper + .answer( + &InteractionId::new("14").expect("id"), + &InteractionResponse::Answers { + answers: vec![inline_agent_bridge::harness::FieldAnswer { + field: FieldId::new("regions").expect("id"), + values: vec!["fra".to_owned(), "iad".to_owned()], + }], + }, + UserId(1), + ) + .expect("answer"); + let AnswerPlan::Respond { result, .. } = plan else { + panic!("expected a response"); + }; + assert_eq!( + result, + json!({"action": "accept", "content": {"regions": ["fra", "iad"]}}) + ); + } + + #[test] + fn a_message_only_request_that_is_not_a_tool_is_an_allow_or_deny_card() { + let mut mapper = CodexMapper::new("thread-1"); + let (subject, decisions) = approval_of(mapper.server_request( + &json!(12), + "mcpServer/elicitation/request", + &json!({ + "threadId": "thread-1", + "turnId": "turn-1", + "serverName": "notes", + "mode": "form", + "message": "Share your notes with this server?", + "requestedSchema": {"type": "object", "properties": {}} + }), + )); + assert_eq!( + subject, + ApprovalSubject::Other { + title: "Share your notes with this server?".to_owned(), + detail: None, + } + ); + assert_eq!(decisions.len(), 3); + assert_eq!( + respond(&mut mapper, "12", "decline"), + json!({"action": "decline", "content": null}) + ); + } + #[test] fn decisions_that_were_not_offered_are_rejected() { let mut mapper = CodexMapper::new("thread-1");