Merge branch 'codex/centralize-approval-prompts' into codex/pretooluse-allow-ask

This commit is contained in:
Abhinav
2026-05-02 13:06:32 -07:00
committed by GitHub
39 changed files with 919 additions and 939 deletions
@@ -556,10 +556,15 @@ async fn run_websocket_response_stream(
trace!("websocket request: {request_text}");
let request_start = Instant::now();
let result = ws_stream
.send(Message::Text(request_text.into()))
.await
.map_err(|err| ApiError::Stream(format!("failed to send websocket request: {err}")));
let result = tokio::time::timeout(
idle_timeout,
ws_stream.send(Message::Text(request_text.into())),
)
.await
.map_err(|_| ApiError::Stream("idle timeout sending websocket request".into()))
.and_then(|result| {
result.map_err(|err| ApiError::Stream(format!("failed to send websocket request: {err}")))
});
if let Some(t) = telemetry.as_ref() {
t.on_ws_request(
+6 -5
View File
@@ -31,13 +31,14 @@ use tokio_util::sync::CancellationToken;
use crate::config::Config;
use crate::environment_selection::ResolvedTurnEnvironments;
use crate::guardian::ApprovalRequest;
use crate::guardian::is_mcp_tool_approval_question_id;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::new_guardian_review_id;
use crate::guardian::routes_approval_to_guardian;
use crate::guardian::spawn_approval_request_review;
use crate::mcp_tool_call::build_mcp_tool_approval_request;
use crate::mcp_tool_call::is_mcp_tool_approval_question_id;
use crate::mcp_tool_call::lookup_mcp_tool_metadata;
use crate::mcp_tool_call::mcp_tool_approval_compat_response;
use crate::session::Codex;
use crate::session::CodexSpawnArgs;
use crate::session::CodexSpawnOk;
@@ -450,7 +451,7 @@ async fn handle_exec_approval(
..
} = event;
let hook_command = shlex_join(&command);
let approval_request = ApprovalRequest::Shell {
let approval_request = GuardianApprovalRequest::Shell {
id: call_id.clone(),
command,
hook_command,
@@ -555,7 +556,7 @@ async fn handle_patch_approval(
})
.collect::<Vec<_>>()
.join("\n");
let approval_request = ApprovalRequest::ApplyPatch {
let approval_request = GuardianApprovalRequest::ApplyPatch {
id: approval_id.clone(),
cwd: parent_ctx.cwd.clone(),
files: changes
@@ -707,7 +708,7 @@ async fn maybe_auto_review_mcp_request_user_input(
Some(&review_cancel),
)
.await;
approval_request.mcp_tool_approval_compat_response(question, decision)
mcp_tool_approval_compat_response(&approval_request, question, decision)
}
async fn handle_request_permissions(
+3 -4
View File
@@ -1,6 +1,5 @@
use super::*;
use crate::guardian::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC;
use crate::guardian::MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX;
use crate::mcp_tool_call::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC;
use async_channel::bounded;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::models::NetworkPermissions;
@@ -504,7 +503,7 @@ async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() {
call_id: "call-1".to_string(),
turn_id: "child-turn-1".to_string(),
questions: vec![RequestUserInputQuestion {
id: format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_call-1"),
id: "mcp_tool_call_approval_call-1".to_string(),
header: "Approve app tool call?".to_string(),
question: "Allow this app tool?".to_string(),
is_other: false,
@@ -520,7 +519,7 @@ async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() {
response,
Some(RequestUserInputResponse {
answers: HashMap::from([(
format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_call-1"),
"mcp_tool_call_approval_call-1".to_string(),
RequestUserInputAnswer {
answers: vec![MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()],
},
+75 -492
View File
@@ -16,19 +16,12 @@ use codex_protocol::protocol::FileChange;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::request_permissions::RequestPermissionProfile;
use codex_protocol::request_permissions::RequestPermissionsEvent;
use codex_protocol::request_user_input::RequestUserInputAnswer;
use codex_protocol::request_user_input::RequestUserInputQuestion;
use codex_protocol::request_user_input::RequestUserInputQuestionOption;
use codex_protocol::request_user_input::RequestUserInputResponse;
use codex_shell_command::parse_command::shlex_join;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde::Serialize;
use serde_json::Value;
use super::GUARDIAN_MAX_ACTION_STRING_TOKENS;
use super::prompt::guardian_truncate_text;
use crate::mcp_tool_approval_templates::RenderedMcpToolApprovalParam;
use crate::mcp_tool_approval_templates::render_mcp_tool_approval_template;
use crate::tools::hook_names::HookToolName;
use crate::tools::sandboxing::PermissionRequestPayload;
@@ -38,7 +31,7 @@ use crate::tools::sandboxing::PermissionRequestPayload;
/// guardian review, approval hooks, and user-prompt transports deriving their
/// own projections from it.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ApprovalRequest {
pub(crate) enum GuardianApprovalRequest {
Shell {
id: String,
command: Vec<String>,
@@ -106,42 +99,7 @@ pub(crate) enum ApprovalRequest {
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct McpToolApprovalPromptOptions {
pub(crate) allow_session_remember: bool,
pub(crate) allow_persistent_approval: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct McpToolApprovalPrompt {
pub(crate) question: RequestUserInputQuestion,
pub(crate) message_override: Option<String>,
pub(crate) tool_params: Option<Value>,
pub(crate) tool_params_display: Option<Vec<RenderedMcpToolApprovalParam>>,
}
pub(crate) const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow";
pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session";
pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER: &str = "Allow and don't ask me again";
pub(crate) const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel";
pub(crate) const MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC: &str = "__codex_mcp_decline__";
pub(crate) const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval";
pub(crate) const MCP_TOOL_APPROVAL_KIND_KEY: &str = "codex_approval_kind";
pub(crate) const MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call";
pub(crate) const MCP_TOOL_APPROVAL_PERSIST_KEY: &str = "persist";
pub(crate) const MCP_TOOL_APPROVAL_PERSIST_SESSION: &str = "session";
pub(crate) const MCP_TOOL_APPROVAL_PERSIST_ALWAYS: &str = "always";
pub(crate) const MCP_TOOL_APPROVAL_SOURCE_KEY: &str = "source";
pub(crate) const MCP_TOOL_APPROVAL_SOURCE_CONNECTOR: &str = "connector";
pub(crate) const MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY: &str = "connector_id";
pub(crate) const MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY: &str = "connector_name";
pub(crate) const MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY: &str = "connector_description";
pub(crate) const MCP_TOOL_APPROVAL_TOOL_TITLE_KEY: &str = "tool_title";
pub(crate) const MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY: &str = "tool_description";
pub(crate) const MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: &str = "tool_params";
pub(crate) const MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display";
impl ApprovalRequest {
impl GuardianApprovalRequest {
pub(crate) fn permission_request_payload(&self) -> Option<PermissionRequestPayload> {
match self {
Self::Shell {
@@ -163,7 +121,10 @@ impl ApprovalRequest {
if argv.len() > 1 {
command.extend_from_slice(&argv[1..]);
}
Some(PermissionRequestPayload::bash(shlex_join(&command), None))
Some(PermissionRequestPayload::bash(
codex_shell_command::parse_command::shlex_join(&command),
/*description*/ None,
))
}
Self::ApplyPatch { patch, .. } => Some(PermissionRequestPayload {
tool_name: HookToolName::apply_patch(),
@@ -348,311 +309,6 @@ impl ApprovalRequest {
Self::Execve { .. } => None,
}
}
pub(crate) fn mcp_tool_approval_prompt(
&self,
question_id: String,
prompt_options: McpToolApprovalPromptOptions,
monitor_reason: Option<&str>,
) -> Option<McpToolApprovalPrompt> {
let Self::McpToolCall {
server,
tool_name,
arguments,
connector_id,
connector_name,
tool_title,
..
} = self
else {
return None;
};
let rendered_template = render_mcp_tool_approval_template(
server,
connector_id.as_deref(),
connector_name.as_deref(),
tool_title.as_deref(),
arguments.as_ref(),
);
let tool_params_display = rendered_template
.as_ref()
.map(|rendered_template| rendered_template.tool_params_display.clone())
.or_else(|| build_mcp_tool_approval_display_params(arguments.as_ref()));
let question_override = rendered_template
.as_ref()
.map(|rendered_template| rendered_template.question.as_str());
let mut question = build_mcp_tool_approval_question(
question_id,
server,
tool_name,
connector_name.as_deref(),
prompt_options,
question_override,
);
question.question = mcp_tool_approval_question_text(question.question, monitor_reason);
Some(McpToolApprovalPrompt {
question,
message_override: rendered_template.as_ref().and_then(|rendered_template| {
monitor_reason
.is_none()
.then_some(rendered_template.elicitation_message.clone())
}),
tool_params: rendered_template
.as_ref()
.and_then(|rendered_template| rendered_template.tool_params.clone())
.or_else(|| arguments.clone()),
tool_params_display,
})
}
pub(crate) fn mcp_tool_approval_elicitation_meta(
&self,
tool_params: Option<&Value>,
tool_params_display: Option<&[RenderedMcpToolApprovalParam]>,
prompt_options: McpToolApprovalPromptOptions,
) -> Option<Value> {
let Self::McpToolCall {
server,
connector_id,
connector_name,
connector_description,
tool_title,
tool_description,
..
} = self
else {
return None;
};
let mut meta = serde_json::Map::new();
meta.insert(
MCP_TOOL_APPROVAL_KIND_KEY.to_string(),
serde_json::Value::String(MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL.to_string()),
);
match (
prompt_options.allow_session_remember,
prompt_options.allow_persistent_approval,
) {
(true, true) => {
meta.insert(
MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(),
serde_json::json!([
MCP_TOOL_APPROVAL_PERSIST_SESSION,
MCP_TOOL_APPROVAL_PERSIST_ALWAYS,
]),
);
}
(true, false) => {
meta.insert(
MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(),
serde_json::Value::String(MCP_TOOL_APPROVAL_PERSIST_SESSION.to_string()),
);
}
(false, true) => {
meta.insert(
MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(),
serde_json::Value::String(MCP_TOOL_APPROVAL_PERSIST_ALWAYS.to_string()),
);
}
(false, false) => {}
}
if let Some(tool_title) = tool_title.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_TOOL_TITLE_KEY.to_string(),
serde_json::Value::String(tool_title.clone()),
);
}
if let Some(tool_description) = tool_description.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY.to_string(),
serde_json::Value::String(tool_description.clone()),
);
}
if server == "codex_apps"
&& (connector_id.is_some()
|| connector_name.is_some()
|| connector_description.is_some())
{
meta.insert(
MCP_TOOL_APPROVAL_SOURCE_KEY.to_string(),
serde_json::Value::String(MCP_TOOL_APPROVAL_SOURCE_CONNECTOR.to_string()),
);
if let Some(connector_id) = connector_id.as_deref() {
meta.insert(
MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY.to_string(),
serde_json::Value::String(connector_id.to_string()),
);
}
if let Some(connector_name) = connector_name.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY.to_string(),
serde_json::Value::String(connector_name.clone()),
);
}
if let Some(connector_description) = connector_description.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY.to_string(),
serde_json::Value::String(connector_description.clone()),
);
}
}
if let Some(tool_params) = tool_params {
meta.insert(
MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY.to_string(),
tool_params.clone(),
);
}
if let Some(tool_params_display) = tool_params_display
&& let Ok(tool_params_display) = serde_json::to_value(tool_params_display)
{
meta.insert(
MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY.to_string(),
tool_params_display,
);
}
(!meta.is_empty()).then_some(serde_json::Value::Object(meta))
}
pub(crate) fn mcp_tool_approval_compat_response(
&self,
question: &RequestUserInputQuestion,
decision: ReviewDecision,
) -> Option<RequestUserInputResponse> {
let Self::McpToolCall { .. } = self else {
return None;
};
let selected_label = match decision {
ReviewDecision::ApprovedForSession => question
.options
.as_ref()
.and_then(|options| {
options
.iter()
.find(|option| option.label == MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION)
})
.map(|option| option.label.clone())
.unwrap_or_else(|| MCP_TOOL_APPROVAL_ACCEPT.to_string()),
ReviewDecision::Approved
| ReviewDecision::ApprovedExecpolicyAmendment { .. }
| ReviewDecision::NetworkPolicyAmendment { .. } => MCP_TOOL_APPROVAL_ACCEPT.to_string(),
ReviewDecision::Denied | ReviewDecision::TimedOut | ReviewDecision::Abort => {
MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()
}
};
Some(RequestUserInputResponse {
answers: HashMap::from([(
question.id.clone(),
RequestUserInputAnswer {
answers: vec![selected_label],
},
)]),
})
}
}
pub(crate) fn mcp_tool_approval_question_id(call_id: &str) -> String {
format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}")
}
pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool {
question_id
.strip_prefix(MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX)
.is_some_and(|suffix| suffix.starts_with('_'))
}
fn build_mcp_tool_approval_question(
question_id: String,
server: &str,
tool_name: &str,
connector_name: Option<&str>,
prompt_options: McpToolApprovalPromptOptions,
question_override: Option<&str>,
) -> RequestUserInputQuestion {
let question = question_override
.map(ToString::to_string)
.unwrap_or_else(|| {
build_mcp_tool_approval_fallback_message(server, tool_name, connector_name)
});
let question = format!("{}?", question.trim_end_matches('?'));
let mut options = vec![RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT.to_string(),
description: "Run the tool and continue.".to_string(),
}];
if prompt_options.allow_session_remember {
options.push(RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(),
description: "Run the tool and remember this choice for this session.".to_string(),
});
}
if prompt_options.allow_persistent_approval {
options.push(RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(),
description: "Run the tool and remember this choice for future tool calls.".to_string(),
});
}
options.push(RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_CANCEL.to_string(),
description: "Cancel this tool call.".to_string(),
});
RequestUserInputQuestion {
id: question_id,
header: "Approve app tool call?".to_string(),
question,
is_other: false,
is_secret: false,
options: Some(options),
}
}
fn build_mcp_tool_approval_fallback_message(
server: &str,
tool_name: &str,
connector_name: Option<&str>,
) -> String {
let actor = connector_name
.map(str::trim)
.filter(|name| !name.is_empty())
.map(ToString::to_string)
.unwrap_or_else(|| {
if server == "codex_apps" {
"this app".to_string()
} else {
format!("the {server} MCP server")
}
});
format!("Allow {actor} to run tool \"{tool_name}\"?")
}
fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String {
match monitor_reason.map(str::trim) {
Some(reason) if !reason.is_empty() => {
format!("Tool call needs your approval. Reason: {reason}")
}
_ => question,
}
}
fn build_mcp_tool_approval_display_params(
tool_params: Option<&Value>,
) -> Option<Vec<RenderedMcpToolApprovalParam>> {
let tool_params = tool_params?.as_object()?;
let mut display_params = tool_params
.iter()
.map(|(name, value)| RenderedMcpToolApprovalParam {
name: name.clone(),
value: value.clone(),
display_name: name.clone(),
})
.collect::<Vec<_>>();
display_params.sort_by(|left, right| left.name.cmp(&right.name));
Some(display_params)
}
#[derive(Debug, Clone, PartialEq, Serialize)]
@@ -836,10 +492,10 @@ pub(crate) struct FormattedGuardianAction {
}
pub(crate) fn guardian_approval_request_to_json(
action: &ApprovalRequest,
action: &GuardianApprovalRequest,
) -> serde_json::Result<Value> {
match action {
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: _,
command,
cwd,
@@ -856,7 +512,7 @@ pub(crate) fn guardian_approval_request_to_json(
justification.as_ref(),
/*tty*/ None,
),
ApprovalRequest::ExecCommand {
GuardianApprovalRequest::ExecCommand {
id: _,
command,
cwd,
@@ -875,7 +531,7 @@ pub(crate) fn guardian_approval_request_to_json(
Some(*tty),
),
#[cfg(unix)]
ApprovalRequest::Execve {
GuardianApprovalRequest::Execve {
id: _,
source,
program,
@@ -889,7 +545,7 @@ pub(crate) fn guardian_approval_request_to_json(
cwd,
additional_permissions: additional_permissions.as_ref(),
}),
ApprovalRequest::ApplyPatch {
GuardianApprovalRequest::ApplyPatch {
id: _,
cwd,
files,
@@ -901,7 +557,7 @@ pub(crate) fn guardian_approval_request_to_json(
"files": files,
"patch": patch,
})),
ApprovalRequest::NetworkAccess {
GuardianApprovalRequest::NetworkAccess {
id: _,
turn_id: _,
target,
@@ -918,7 +574,7 @@ pub(crate) fn guardian_approval_request_to_json(
port: *port,
trigger: trigger.as_ref(),
}),
ApprovalRequest::McpToolCall {
GuardianApprovalRequest::McpToolCall {
id: _,
server,
tool_name,
@@ -942,7 +598,7 @@ pub(crate) fn guardian_approval_request_to_json(
tool_description: tool_description.as_ref(),
annotations: annotations.as_ref(),
}),
ApprovalRequest::RequestPermissions {
GuardianApprovalRequest::RequestPermissions {
id: _,
turn_id,
reason,
@@ -957,16 +613,18 @@ pub(crate) fn guardian_approval_request_to_json(
}
}
pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAssessmentAction {
pub(crate) fn guardian_assessment_action(
action: &GuardianApprovalRequest,
) -> GuardianAssessmentAction {
match action {
ApprovalRequest::Shell { command, cwd, .. } => {
GuardianApprovalRequest::Shell { command, cwd, .. } => {
command_assessment_action(GuardianCommandSource::Shell, command, cwd)
}
ApprovalRequest::ExecCommand { command, cwd, .. } => {
GuardianApprovalRequest::ExecCommand { command, cwd, .. } => {
command_assessment_action(GuardianCommandSource::UnifiedExec, command, cwd)
}
#[cfg(unix)]
ApprovalRequest::Execve {
GuardianApprovalRequest::Execve {
source,
program,
argv,
@@ -978,11 +636,13 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs
argv: argv.clone(),
cwd: cwd.clone(),
},
ApprovalRequest::ApplyPatch { cwd, files, .. } => GuardianAssessmentAction::ApplyPatch {
cwd: cwd.clone(),
files: files.clone(),
},
ApprovalRequest::NetworkAccess {
GuardianApprovalRequest::ApplyPatch { cwd, files, .. } => {
GuardianAssessmentAction::ApplyPatch {
cwd: cwd.clone(),
files: files.clone(),
}
}
GuardianApprovalRequest::NetworkAccess {
id: _id,
turn_id: _turn_id,
target,
@@ -997,7 +657,7 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs
protocol: *protocol,
port: *port,
},
ApprovalRequest::McpToolCall {
GuardianApprovalRequest::McpToolCall {
server,
tool_name,
connector_id,
@@ -1011,7 +671,7 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs
connector_name: connector_name.clone(),
tool_title: tool_title.clone(),
},
ApprovalRequest::RequestPermissions {
GuardianApprovalRequest::RequestPermissions {
reason,
permissions,
..
@@ -1022,9 +682,11 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs
}
}
pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianReviewedAction {
pub(crate) fn guardian_reviewed_action(
request: &GuardianApprovalRequest,
) -> GuardianReviewedAction {
match request {
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
sandbox_permissions,
additional_permissions,
..
@@ -1032,7 +694,7 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev
sandbox_permissions: *sandbox_permissions,
additional_permissions: additional_permissions.clone(),
},
ApprovalRequest::ExecCommand {
GuardianApprovalRequest::ExecCommand {
sandbox_permissions,
additional_permissions,
tty,
@@ -1043,7 +705,7 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev
tty: *tty,
},
#[cfg(unix)]
ApprovalRequest::Execve {
GuardianApprovalRequest::Execve {
source,
program,
additional_permissions,
@@ -1053,14 +715,14 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev
program: program.clone(),
additional_permissions: additional_permissions.clone(),
},
ApprovalRequest::ApplyPatch { .. } => GuardianReviewedAction::ApplyPatch {},
ApprovalRequest::NetworkAccess { protocol, port, .. } => {
GuardianApprovalRequest::ApplyPatch { .. } => GuardianReviewedAction::ApplyPatch {},
GuardianApprovalRequest::NetworkAccess { protocol, port, .. } => {
GuardianReviewedAction::NetworkAccess {
protocol: *protocol,
port: *port,
}
}
ApprovalRequest::McpToolCall {
GuardianApprovalRequest::McpToolCall {
server,
tool_name,
connector_id,
@@ -1074,41 +736,43 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev
connector_name: connector_name.clone(),
tool_title: tool_title.clone(),
},
ApprovalRequest::RequestPermissions { .. } => GuardianReviewedAction::RequestPermissions {},
GuardianApprovalRequest::RequestPermissions { .. } => {
GuardianReviewedAction::RequestPermissions {}
}
}
}
pub(crate) fn guardian_request_target_item_id(request: &ApprovalRequest) -> Option<&str> {
pub(crate) fn guardian_request_target_item_id(request: &GuardianApprovalRequest) -> Option<&str> {
match request {
ApprovalRequest::Shell { id, .. }
| ApprovalRequest::ExecCommand { id, .. }
| ApprovalRequest::ApplyPatch { id, .. }
| ApprovalRequest::McpToolCall { id, .. }
| ApprovalRequest::RequestPermissions { id, .. } => Some(id),
ApprovalRequest::NetworkAccess { .. } => None,
GuardianApprovalRequest::Shell { id, .. }
| GuardianApprovalRequest::ExecCommand { id, .. }
| GuardianApprovalRequest::ApplyPatch { id, .. }
| GuardianApprovalRequest::McpToolCall { id, .. }
| GuardianApprovalRequest::RequestPermissions { id, .. } => Some(id),
GuardianApprovalRequest::NetworkAccess { .. } => None,
#[cfg(unix)]
ApprovalRequest::Execve { id, .. } => Some(id),
GuardianApprovalRequest::Execve { id, .. } => Some(id),
}
}
pub(crate) fn guardian_request_turn_id<'a>(
request: &'a ApprovalRequest,
request: &'a GuardianApprovalRequest,
default_turn_id: &'a str,
) -> &'a str {
match request {
ApprovalRequest::NetworkAccess { turn_id, .. }
| ApprovalRequest::RequestPermissions { turn_id, .. } => turn_id,
ApprovalRequest::Shell { .. }
| ApprovalRequest::ExecCommand { .. }
| ApprovalRequest::ApplyPatch { .. }
| ApprovalRequest::McpToolCall { .. } => default_turn_id,
GuardianApprovalRequest::NetworkAccess { turn_id, .. }
| GuardianApprovalRequest::RequestPermissions { turn_id, .. } => turn_id,
GuardianApprovalRequest::Shell { .. }
| GuardianApprovalRequest::ExecCommand { .. }
| GuardianApprovalRequest::ApplyPatch { .. }
| GuardianApprovalRequest::McpToolCall { .. } => default_turn_id,
#[cfg(unix)]
ApprovalRequest::Execve { .. } => default_turn_id,
GuardianApprovalRequest::Execve { .. } => default_turn_id,
}
}
pub(crate) fn format_guardian_action_pretty(
action: &ApprovalRequest,
action: &GuardianApprovalRequest,
) -> serde_json::Result<FormattedGuardianAction> {
let value = guardian_approval_request_to_json(action)?;
let (value, truncated) = truncate_guardian_action_value(value);
@@ -1122,14 +786,13 @@ pub(crate) fn format_guardian_action_pretty(
mod tests {
use super::*;
use codex_protocol::protocol::FileChange;
use codex_protocol::protocol::ReviewDecision;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
#[test]
fn exec_approval_event_is_projected_from_shell_request() {
let request = ApprovalRequest::Shell {
let request = GuardianApprovalRequest::Shell {
id: "call-1".to_string(),
command: vec!["echo".to_string(), "hi".to_string()],
hook_command: "echo hi".to_string(),
@@ -1144,9 +807,9 @@ mod tests {
"turn-1".to_string(),
Some("approval-1".to_string()),
Some("retry".to_string()),
None,
None,
None,
/*network_approval_context*/ None,
/*proposed_execpolicy_amendment*/ None,
/*proposed_network_policy_amendments*/ None,
Some(vec![ReviewDecision::Approved, ReviewDecision::Abort]),
/*fallback_cwd*/ None,
)
@@ -1167,7 +830,7 @@ mod tests {
fn apply_patch_approval_event_is_projected_from_request() {
let path = test_path_buf("/tmp/file.txt");
let abs_path = path.abs();
let request = ApprovalRequest::ApplyPatch {
let request = GuardianApprovalRequest::ApplyPatch {
id: "call-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
files: vec![abs_path],
@@ -1181,7 +844,11 @@ mod tests {
};
let event = request
.apply_patch_approval_event("turn-1".to_string(), Some("needs write".to_string()), None)
.apply_patch_approval_event(
"turn-1".to_string(),
Some("needs write".to_string()),
/*grant_root*/ None,
)
.expect("apply_patch approval event");
assert_eq!(event.call_id, "call-1");
@@ -1200,7 +867,7 @@ mod tests {
#[test]
fn request_permissions_event_is_projected_from_request() {
let request = ApprovalRequest::RequestPermissions {
let request = GuardianApprovalRequest::RequestPermissions {
id: "call-1".to_string(),
turn_id: "turn-1".to_string(),
reason: Some("need outbound network".to_string()),
@@ -1234,7 +901,7 @@ mod tests {
#[test]
fn network_exec_approval_event_is_projected_from_request() {
let request = ApprovalRequest::NetworkAccess {
let request = GuardianApprovalRequest::NetworkAccess {
id: "network-1".to_string(),
turn_id: "turn-1".to_string(),
target: "https://example.com:443".to_string(),
@@ -1248,12 +915,12 @@ mod tests {
let event = request
.exec_approval_event(
"ignored-turn".to_string(),
None,
/*approval_id*/ None,
Some("need network".to_string()),
None,
None,
None,
None,
/*network_approval_context*/ None,
/*proposed_execpolicy_amendment*/ None,
/*proposed_network_policy_amendments*/ None,
/*available_decisions*/ None,
Some(test_path_buf("/tmp").abs()),
)
.expect("network exec approval event");
@@ -1290,88 +957,4 @@ mod tests {
])
);
}
#[test]
fn mcp_tool_approval_compat_response_uses_session_label_when_present() {
let request = ApprovalRequest::McpToolCall {
id: "call-1".to_string(),
server: "custom_server".to_string(),
tool_name: "dangerous_tool".to_string(),
hook_tool_name: "custom_server__dangerous_tool".to_string(),
arguments: None,
connector_id: None,
connector_name: None,
connector_description: None,
tool_title: None,
tool_description: None,
annotations: None,
};
let question = RequestUserInputQuestion {
id: "q-1".to_string(),
header: "Approve app tool call?".to_string(),
question: "Allow this app tool?".to_string(),
is_other: false,
is_secret: false,
options: Some(vec![RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(),
description: "Remember until session ends".to_string(),
}]),
};
let response = request
.mcp_tool_approval_compat_response(&question, ReviewDecision::ApprovedForSession)
.expect("compat response");
assert_eq!(
response.answers.get("q-1"),
Some(&RequestUserInputAnswer {
answers: vec![MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string()],
})
);
}
#[test]
fn mcp_tool_approval_compat_response_uses_synthetic_decline_for_abort() {
let request = ApprovalRequest::McpToolCall {
id: "call-1".to_string(),
server: "custom_server".to_string(),
tool_name: "dangerous_tool".to_string(),
hook_tool_name: "custom_server__dangerous_tool".to_string(),
arguments: None,
connector_id: None,
connector_name: None,
connector_description: None,
tool_title: None,
tool_description: None,
annotations: None,
};
let question = RequestUserInputQuestion {
id: "q-1".to_string(),
header: "Approve app tool call?".to_string(),
question: "Allow this app tool?".to_string(),
is_other: false,
is_secret: false,
options: None,
};
let response = request
.mcp_tool_approval_compat_response(&question, ReviewDecision::Abort)
.expect("compat response");
assert_eq!(
response.answers.get("q-1"),
Some(&RequestUserInputAnswer {
answers: vec![MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()],
})
);
}
#[test]
fn mcp_tool_approval_question_id_helpers_round_trip() {
let question_id = mcp_tool_approval_question_id("call-1");
assert_eq!(question_id, "mcp_tool_call_approval_call-1");
assert!(is_mcp_tool_approval_question_id(&question_id));
assert!(!is_mcp_tool_approval_question_id("other_question"));
}
}
+1 -44
View File
@@ -23,53 +23,10 @@ use codex_protocol::protocol::GuardianAssessmentOutcome;
use serde::Deserialize;
use serde::Serialize;
pub(crate) use approval_request::ApprovalRequest;
pub(crate) use approval_request::GuardianApprovalRequest;
pub(crate) use approval_request::GuardianMcpAnnotations;
pub(crate) use approval_request::GuardianNetworkAccessTrigger;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_ACCEPT;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_CANCEL;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_KIND_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_PERSIST_ALWAYS;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_PERSIST_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_PERSIST_SESSION;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_SOURCE_CONNECTOR;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_SOURCE_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY;
#[allow(unused_imports)]
pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_TITLE_KEY;
pub(crate) use approval_request::McpToolApprovalPromptOptions;
pub(crate) use approval_request::guardian_approval_request_to_json;
pub(crate) use approval_request::is_mcp_tool_approval_question_id;
pub(crate) use approval_request::mcp_tool_approval_question_id;
pub(crate) use review::guardian_rejection_message;
pub(crate) use review::guardian_timeout_message;
pub(crate) use review::is_guardian_reviewer_source;
+3 -3
View File
@@ -15,12 +15,12 @@ use codex_utils_output_truncation::approx_token_count;
use codex_utils_output_truncation::approx_tokens_from_byte_count;
use super::AUTO_REVIEW_DENIED_ACTION_APPROVAL_DEVELOPER_PREFIX;
use super::ApprovalRequest;
use super::GUARDIAN_MAX_MESSAGE_ENTRY_TOKENS;
use super::GUARDIAN_MAX_MESSAGE_TRANSCRIPT_TOKENS;
use super::GUARDIAN_MAX_TOOL_ENTRY_TOKENS;
use super::GUARDIAN_MAX_TOOL_TRANSCRIPT_TOKENS;
use super::GUARDIAN_RECENT_ENTRY_LIMIT;
use super::GuardianApprovalRequest;
use super::GuardianAssessment;
use super::TRUNCATION_TAG;
use super::approval_request::format_guardian_action_pretty;
@@ -89,7 +89,7 @@ pub(crate) enum GuardianPromptMode {
pub(crate) async fn build_guardian_prompt_items(
session: &Session,
retry_reason: Option<String>,
request: ApprovalRequest,
request: GuardianApprovalRequest,
mode: GuardianPromptMode,
) -> serde_json::Result<GuardianPromptItems> {
let history = session.clone_history().await;
@@ -173,7 +173,7 @@ pub(crate) async fn build_guardian_prompt_items(
push_text(format!("\n{note}\n"));
}
match &request {
ApprovalRequest::NetworkAccess { trigger, .. } => {
GuardianApprovalRequest::NetworkAccess { trigger, .. } => {
push_text(">>> APPROVAL REQUEST START\n".to_string());
push_text("Below is a proposed network access request under review.\n".to_string());
if trigger.is_some() {
+6 -6
View File
@@ -24,9 +24,9 @@ use tokio_util::sync::CancellationToken;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use super::ApprovalRequest;
use super::GUARDIAN_REVIEW_TIMEOUT;
use super::GUARDIAN_REVIEWER_NAME;
use super::GuardianApprovalRequest;
use super::GuardianAssessment;
use super::GuardianAssessmentOutcome;
use super::GuardianRejection;
@@ -234,7 +234,7 @@ async fn run_guardian_review(
session: Arc<Session>,
turn: Arc<TurnContext>,
review_id: String,
request: ApprovalRequest,
request: GuardianApprovalRequest,
retry_reason: Option<String>,
approval_request_source: GuardianApprovalRequestSource,
external_cancel: Option<CancellationToken>,
@@ -523,7 +523,7 @@ pub(crate) async fn review_approval_request(
session: &Arc<Session>,
turn: &Arc<TurnContext>,
review_id: String,
request: ApprovalRequest,
request: GuardianApprovalRequest,
retry_reason: Option<String>,
) -> ReviewDecision {
// Box the delegated review future so callers do not inline the entire
@@ -544,7 +544,7 @@ pub(crate) async fn review_approval_request_with_cancel(
session: &Arc<Session>,
turn: &Arc<TurnContext>,
review_id: String,
request: ApprovalRequest,
request: GuardianApprovalRequest,
retry_reason: Option<String>,
approval_request_source: GuardianApprovalRequestSource,
cancel_token: CancellationToken,
@@ -565,7 +565,7 @@ pub(crate) fn spawn_approval_request_review(
session: Arc<Session>,
turn: Arc<TurnContext>,
review_id: String,
request: ApprovalRequest,
request: GuardianApprovalRequest,
retry_reason: Option<String>,
approval_request_source: GuardianApprovalRequestSource,
cancel_token: CancellationToken,
@@ -610,7 +610,7 @@ pub(crate) fn spawn_approval_request_review(
pub(super) async fn run_guardian_review_session(
session: Arc<Session>,
turn: Arc<TurnContext>,
request: ApprovalRequest,
request: GuardianApprovalRequest,
retry_reason: Option<String>,
schema: serde_json::Value,
external_cancel: Option<CancellationToken>,
+3 -3
View File
@@ -44,9 +44,9 @@ use codex_features::Feature;
use codex_model_provider_info::ModelProviderInfo;
use codex_utils_absolute_path::AbsolutePathBuf;
use super::ApprovalRequest;
use super::GUARDIAN_REVIEW_TIMEOUT;
use super::GUARDIAN_REVIEWER_NAME;
use super::GuardianApprovalRequest;
use super::prompt::GuardianPromptMode;
use super::prompt::GuardianTranscriptCursor;
use super::prompt::build_guardian_prompt_items;
@@ -67,7 +67,7 @@ pub(crate) struct GuardianReviewSessionParams {
pub(crate) parent_session: Arc<Session>,
pub(crate) parent_turn: Arc<TurnContext>,
pub(crate) spawn_config: Config,
pub(crate) request: ApprovalRequest,
pub(crate) request: GuardianApprovalRequest,
pub(crate) retry_reason: Option<String>,
pub(crate) schema: Value,
pub(crate) model: String,
@@ -1101,7 +1101,7 @@ mod tests {
parent_session: Arc::new(session),
parent_turn: Arc::new(turn),
spawn_config,
request: ApprovalRequest::Shell {
request: GuardianApprovalRequest::Shell {
id: "shell-1".to_string(),
command: vec!["git".to_string(), "status".to_string()],
hook_command: "git status".to_string(),
+26 -26
View File
@@ -313,7 +313,7 @@ async fn build_guardian_prompt_full_mode_preserves_initial_review_format() -> an
let prompt = build_guardian_prompt_items(
session.as_ref(),
Some("Sandbox denied outbound git push to github.com.".to_string()),
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-1".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -368,7 +368,7 @@ async fn build_guardian_prompt_delta_mode_preserves_original_numbering() -> anyh
let prompt = build_guardian_prompt_items(
session.as_ref(),
/*retry_reason*/ None,
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-2".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -407,7 +407,7 @@ async fn build_guardian_prompt_delta_mode_handles_empty_delta() -> anyhow::Resul
let prompt = build_guardian_prompt_items(
session.as_ref(),
/*retry_reason*/ None,
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-2".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -443,7 +443,7 @@ async fn build_guardian_prompt_stale_delta_cursor_falls_back_to_full_prompt() ->
let prompt = build_guardian_prompt_items(
session.as_ref(),
/*retry_reason*/ None,
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-3".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -525,7 +525,7 @@ async fn build_guardian_prompt_stale_delta_version_falls_back_to_full_prompt() -
let prompt = build_guardian_prompt_items(
session.as_ref(),
/*retry_reason*/ None,
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-4".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -690,7 +690,7 @@ fn guardian_truncate_text_keeps_prefix_suffix_and_xml_marker() {
#[test]
fn format_guardian_action_pretty_truncates_large_string_fields() -> serde_json::Result<()> {
let patch = "line\n".repeat(100_000);
let action = ApprovalRequest::ApplyPatch {
let action = GuardianApprovalRequest::ApplyPatch {
id: "patch-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
files: Vec::new(),
@@ -710,7 +710,7 @@ fn format_guardian_action_pretty_truncates_large_string_fields() -> serde_json::
#[test]
fn format_guardian_action_pretty_reports_no_truncation_for_small_payload() -> serde_json::Result<()>
{
let action = ApprovalRequest::ApplyPatch {
let action = GuardianApprovalRequest::ApplyPatch {
id: "patch-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
files: Vec::new(),
@@ -727,7 +727,7 @@ fn format_guardian_action_pretty_reports_no_truncation_for_small_payload() -> se
#[test]
fn guardian_approval_request_to_json_renders_mcp_tool_call_shape() -> serde_json::Result<()> {
let action = ApprovalRequest::McpToolCall {
let action = GuardianApprovalRequest::McpToolCall {
id: "call-1".to_string(),
server: "mcp_server".to_string(),
tool_name: "browser_navigate".to_string(),
@@ -770,7 +770,7 @@ fn guardian_approval_request_to_json_renders_mcp_tool_call_shape() -> serde_json
#[test]
fn guardian_approval_request_to_json_renders_network_access_trigger() -> serde_json::Result<()> {
let cwd = test_path_buf("/repo").abs();
let action = ApprovalRequest::NetworkAccess {
let action = GuardianApprovalRequest::NetworkAccess {
id: "network-1".to_string(),
turn_id: "turn-1".to_string(),
target: "https://example.com:443".to_string(),
@@ -821,7 +821,7 @@ async fn build_guardian_prompt_items_explains_network_access_review_scope() -> a
let prompt = build_guardian_prompt_items(
session.as_ref(),
Some("Network access to \"example.com\" is blocked by policy.".to_string()),
ApprovalRequest::NetworkAccess {
GuardianApprovalRequest::NetworkAccess {
id: "network-1".to_string(),
turn_id: "turn-1".to_string(),
target: "https://example.com:443".to_string(),
@@ -886,7 +886,7 @@ async fn build_guardian_prompt_items_explains_network_access_review_scope() -> a
fn guardian_assessment_action_redacts_apply_patch_patch_text() {
let cwd = test_path_buf("/tmp").abs();
let file = test_path_buf("/tmp/guardian.txt").abs();
let action = ApprovalRequest::ApplyPatch {
let action = GuardianApprovalRequest::ApplyPatch {
id: "patch-1".to_string(),
cwd: cwd.clone(),
files: vec![file.clone()],
@@ -907,7 +907,7 @@ fn guardian_assessment_action_redacts_apply_patch_patch_text() {
#[test]
fn guardian_request_turn_id_prefers_network_access_owner_turn() {
let network_access = ApprovalRequest::NetworkAccess {
let network_access = GuardianApprovalRequest::NetworkAccess {
id: "network-1".to_string(),
turn_id: "owner-turn".to_string(),
target: "https://example.com:443".to_string(),
@@ -917,7 +917,7 @@ fn guardian_request_turn_id_prefers_network_access_owner_turn() {
port: 443,
trigger: None,
};
let apply_patch = ApprovalRequest::ApplyPatch {
let apply_patch = GuardianApprovalRequest::ApplyPatch {
id: "patch-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
files: vec![test_path_buf("/tmp/guardian.txt").abs()],
@@ -938,7 +938,7 @@ fn guardian_request_turn_id_prefers_network_access_owner_turn() {
#[test]
fn guardian_request_target_item_id_omits_network_access_trigger_call_id() {
let network_access = ApprovalRequest::NetworkAccess {
let network_access = GuardianApprovalRequest::NetworkAccess {
id: "network-1".to_string(),
turn_id: "owner-turn".to_string(),
target: "https://example.com:443".to_string(),
@@ -971,7 +971,7 @@ async fn cancelled_guardian_review_emits_terminal_abort_without_warning() {
&session,
&turn,
"review-cancelled-guardian".to_string(),
ApprovalRequest::ApplyPatch {
GuardianApprovalRequest::ApplyPatch {
id: "patch-1".to_string(),
cwd: test_path_buf("/tmp").abs(),
files: vec![test_path_buf("/tmp/guardian.txt").abs()],
@@ -1261,7 +1261,7 @@ async fn guardian_review_request_layout_matches_model_visible_request_snapshot()
let turn = Arc::new(turn);
seed_guardian_parent_history(&session, &turn).await;
let request = ApprovalRequest::Shell {
let request = GuardianApprovalRequest::Shell {
id: "shell-1".to_string(),
command: vec![
"git".to_string(),
@@ -1372,7 +1372,7 @@ async fn build_guardian_prompt_items_includes_parent_session_id() -> anyhow::Res
let prompt = build_guardian_prompt_items(
&session,
/*retry_reason*/ None,
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-1".to_string(),
command: vec!["git".to_string(), "status".to_string()],
hook_command: "git status".to_string(),
@@ -1447,7 +1447,7 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow:
let (session, turn) = guardian_test_session_and_turn(&server).await;
seed_guardian_parent_history(&session, &turn).await;
let first_request = ApprovalRequest::Shell {
let first_request = GuardianApprovalRequest::Shell {
id: "shell-1".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -1488,7 +1488,7 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow:
turn.as_ref(),
)
.await;
let second_request = ApprovalRequest::Shell {
let second_request = GuardianApprovalRequest::Shell {
id: "shell-2".to_string(),
command: vec![
"git".to_string(),
@@ -1533,7 +1533,7 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow:
turn.as_ref(),
)
.await;
let third_request = ApprovalRequest::Shell {
let third_request = GuardianApprovalRequest::Shell {
id: "shell-3".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -1729,7 +1729,7 @@ async fn guardian_reused_trunk_ignores_stale_prior_turn_completion() -> anyhow::
let first_outcome = run_guardian_review_session_for_test(
Arc::clone(&session),
Arc::clone(&turn),
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-1".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -1772,7 +1772,7 @@ async fn guardian_reused_trunk_ignores_stale_prior_turn_completion() -> anyhow::
let second_outcome = run_guardian_review_session_for_test(
Arc::clone(&session),
Arc::clone(&turn),
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-2".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -1852,7 +1852,7 @@ async fn guardian_review_surfaces_responses_api_errors_in_rejection_reason() ->
&session,
&turn,
"review-shell-guardian-error".to_string(),
ApprovalRequest::Shell {
GuardianApprovalRequest::Shell {
id: "shell-guardian-error".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
@@ -1987,7 +1987,7 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a
let (session, turn) = guardian_test_session_and_turn_with_base_url(server.uri()).await;
seed_guardian_parent_history(&session, &turn).await;
let initial_request = ApprovalRequest::Shell {
let initial_request = GuardianApprovalRequest::Shell {
id: "shell-guardian-1".to_string(),
command: vec!["git".to_string(), "status".to_string()],
hook_command: "git status".to_string(),
@@ -2031,7 +2031,7 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a
)
.await;
let second_request = ApprovalRequest::Shell {
let second_request = GuardianApprovalRequest::Shell {
id: "shell-guardian-2".to_string(),
command: vec!["git".to_string(), "diff".to_string()],
hook_command: "git diff".to_string(),
@@ -2040,7 +2040,7 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a
additional_permissions: None,
justification: Some("Inspect pending changes before proceeding.".to_string()),
};
let third_request = ApprovalRequest::Shell {
let third_request = GuardianApprovalRequest::Shell {
id: "shell-guardian-3".to_string(),
command: vec!["git".to_string(), "push".to_string()],
hook_command: "git push".to_string(),
+352 -16
View File
@@ -17,26 +17,18 @@ use crate::config::edit::ConfigEdit;
use crate::config::edit::ConfigEditsBuilder;
use crate::config::load_global_mcp_servers;
use crate::connectors;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::GuardianMcpAnnotations;
use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT;
use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER;
use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION;
use crate::guardian::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC;
use crate::guardian::MCP_TOOL_APPROVAL_PERSIST_ALWAYS;
use crate::guardian::MCP_TOOL_APPROVAL_PERSIST_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_PERSIST_SESSION;
use crate::guardian::McpToolApprovalPromptOptions;
use crate::guardian::guardian_approval_request_to_json;
use crate::guardian::guardian_rejection_message;
use crate::guardian::guardian_timeout_message;
use crate::guardian::mcp_tool_approval_question_id;
use crate::guardian::new_guardian_review_id;
use crate::guardian::review_approval_request;
use crate::guardian::routes_approval_to_guardian;
use crate::hook_runtime::run_permission_request_hooks;
use crate::mcp_openai_file::rewrite_mcp_tool_arguments_for_openai_files;
use crate::mcp_tool_approval_templates::RenderedMcpToolApprovalParam;
use crate::mcp_tool_approval_templates::render_mcp_tool_approval_template;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use codex_analytics::AppInvocation;
@@ -62,6 +54,7 @@ use codex_protocol::protocol::ReviewDecision;
use codex_protocol::request_user_input::RequestUserInputAnswer;
use codex_protocol::request_user_input::RequestUserInputArgs;
use codex_protocol::request_user_input::RequestUserInputQuestion;
use codex_protocol::request_user_input::RequestUserInputQuestionOption;
use codex_protocol::request_user_input::RequestUserInputResponse;
use codex_rmcp_client::ElicitationAction;
use codex_rmcp_client::ElicitationResponse;
@@ -886,9 +879,15 @@ fn with_mcp_tool_call_thread_id_meta(
}
}
#[derive(Clone, Copy)]
struct McpToolApprovalPromptOptions {
allow_session_remember: bool,
allow_persistent_approval: bool,
}
struct McpToolApprovalElicitationRequest<'a> {
server: &'a str,
approval_request: &'a ApprovalRequest,
approval_request: &'a GuardianApprovalRequest,
tool_params: Option<&'a serde_json::Value>,
tool_params_display: Option<&'a [RenderedMcpToolApprovalParam]>,
question: RequestUserInputQuestion,
@@ -896,9 +895,48 @@ struct McpToolApprovalElicitationRequest<'a> {
prompt_options: McpToolApprovalPromptOptions,
}
#[derive(Clone, Debug, PartialEq)]
struct McpToolApprovalPrompt {
question: RequestUserInputQuestion,
message_override: Option<String>,
tool_params: Option<JsonValue>,
tool_params_display: Option<Vec<RenderedMcpToolApprovalParam>>,
}
pub(crate) const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval";
pub(crate) const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow";
pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session";
// Internal-only token used when guardian auto-reviews delegated MCP approvals on the
// RequestUserInput compatibility path. That legacy MCP prompt has allow/cancel labels but no
// real "Decline" answer, so this lets guardian denials round-trip distinctly from user cancel.
// This is not a user-facing option.
pub(crate) const MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC: &str = "__codex_mcp_decline__";
const MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER: &str = "Allow and don't ask me again";
const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel";
const MCP_TOOL_APPROVAL_KIND_KEY: &str = "codex_approval_kind";
const MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call";
const MCP_TOOL_APPROVAL_PERSIST_KEY: &str = "persist";
const MCP_TOOL_APPROVAL_PERSIST_SESSION: &str = "session";
const MCP_TOOL_APPROVAL_PERSIST_ALWAYS: &str = "always";
const MCP_TOOL_APPROVAL_SOURCE_KEY: &str = "source";
const MCP_TOOL_APPROVAL_SOURCE_CONNECTOR: &str = "connector";
const MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY: &str = "connector_id";
const MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY: &str = "connector_name";
const MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY: &str = "connector_description";
const MCP_TOOL_APPROVAL_TOOL_TITLE_KEY: &str = "tool_title";
const MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY: &str = "tool_description";
const MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: &str = "tool_params";
const MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display";
const MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_DEFAULT: &str = "mcp_tool_call__default";
const MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_ALWAYS_ALLOW: &str = "mcp_tool_call__always_allow";
pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool {
question_id
.strip_prefix(MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX)
.is_some_and(|suffix| suffix.starts_with('_'))
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
struct McpToolApprovalKey {
server: String,
@@ -906,6 +944,105 @@ struct McpToolApprovalKey {
tool_name: String,
}
/// Builds the user-facing MCP approval prompt from the canonical approval request.
fn mcp_tool_approval_prompt(
approval_request: &GuardianApprovalRequest,
question_id: String,
prompt_options: McpToolApprovalPromptOptions,
monitor_reason: Option<&str>,
) -> Option<McpToolApprovalPrompt> {
let GuardianApprovalRequest::McpToolCall {
server,
tool_name,
arguments,
connector_id,
connector_name,
tool_title,
..
} = approval_request
else {
return None;
};
let rendered_template = render_mcp_tool_approval_template(
server,
connector_id.as_deref(),
connector_name.as_deref(),
tool_title.as_deref(),
arguments.as_ref(),
);
let tool_params_display = rendered_template
.as_ref()
.map(|rendered_template| rendered_template.tool_params_display.clone())
.or_else(|| build_mcp_tool_approval_display_params(arguments.as_ref()));
let question_override = rendered_template
.as_ref()
.map(|rendered_template| rendered_template.question.as_str());
let mut question = build_mcp_tool_approval_question(
question_id,
server,
tool_name,
connector_name.as_deref(),
prompt_options,
question_override,
);
question.question = mcp_tool_approval_question_text(question.question, monitor_reason);
Some(McpToolApprovalPrompt {
question,
message_override: rendered_template.as_ref().and_then(|rendered_template| {
monitor_reason
.is_none()
.then_some(rendered_template.elicitation_message.clone())
}),
tool_params: rendered_template
.as_ref()
.and_then(|rendered_template| rendered_template.tool_params.clone())
.or_else(|| arguments.clone()),
tool_params_display,
})
}
/// Converts a guardian MCP approval decision into the legacy RequestUserInput
/// response shape used by delegated compatibility flows.
pub(crate) fn mcp_tool_approval_compat_response(
approval_request: &GuardianApprovalRequest,
question: &RequestUserInputQuestion,
decision: ReviewDecision,
) -> Option<RequestUserInputResponse> {
let GuardianApprovalRequest::McpToolCall { .. } = approval_request else {
return None;
};
let selected_label = match decision {
ReviewDecision::ApprovedForSession => question
.options
.as_ref()
.and_then(|options| {
options
.iter()
.find(|option| option.label == MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION)
})
.map(|option| option.label.clone())
.unwrap_or_else(|| MCP_TOOL_APPROVAL_ACCEPT.to_string()),
ReviewDecision::Approved
| ReviewDecision::ApprovedExecpolicyAmendment { .. }
| ReviewDecision::NetworkPolicyAmendment { .. } => MCP_TOOL_APPROVAL_ACCEPT.to_string(),
ReviewDecision::Denied | ReviewDecision::TimedOut | ReviewDecision::Abort => {
MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()
}
};
Some(RequestUserInputResponse {
answers: HashMap::from([(
question.id.clone(),
RequestUserInputAnswer {
answers: vec![selected_label],
},
)]),
})
}
fn mcp_tool_approval_prompt_options(
session_approval_key: Option<&McpToolApprovalKey>,
persistent_approval_key: Option<&McpToolApprovalKey>,
@@ -1074,8 +1211,9 @@ async fn maybe_request_mcp_tool_approval_with_pre_tool_use_decision(
persistent_approval_key.as_ref(),
tool_call_mcp_elicitation_enabled,
);
let question_id = mcp_tool_approval_question_id(call_id);
let Some(prompt) = approval_request.mcp_tool_approval_prompt(
let question_id = format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}");
let Some(prompt) = mcp_tool_approval_prompt(
&approval_request,
question_id.clone(),
prompt_options,
monitor_reason.as_deref(),
@@ -1201,8 +1339,8 @@ pub(crate) fn build_mcp_tool_approval_request(
hook_tool_name: &str,
invocation: &McpInvocation,
metadata: Option<&McpToolApprovalMetadata>,
) -> ApprovalRequest {
ApprovalRequest::McpToolCall {
) -> GuardianApprovalRequest {
GuardianApprovalRequest::McpToolCall {
id: call_id.to_string(),
server: invocation.server.clone(),
tool_name: invocation.tool.clone(),
@@ -1380,6 +1518,80 @@ async fn lookup_mcp_app_usage_metadata(
})
}
fn build_mcp_tool_approval_question(
question_id: String,
server: &str,
tool_name: &str,
connector_name: Option<&str>,
prompt_options: McpToolApprovalPromptOptions,
question_override: Option<&str>,
) -> RequestUserInputQuestion {
let question = question_override
.map(ToString::to_string)
.unwrap_or_else(|| {
build_mcp_tool_approval_fallback_message(server, tool_name, connector_name)
});
let question = format!("{}?", question.trim_end_matches('?'));
let mut options = vec![RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT.to_string(),
description: "Run the tool and continue.".to_string(),
}];
if prompt_options.allow_session_remember {
options.push(RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(),
description: "Run the tool and remember this choice for this session.".to_string(),
});
}
if prompt_options.allow_persistent_approval {
options.push(RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(),
description: "Run the tool and remember this choice for future tool calls.".to_string(),
});
}
options.push(RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_CANCEL.to_string(),
description: "Cancel this tool call.".to_string(),
});
RequestUserInputQuestion {
id: question_id,
header: "Approve app tool call?".to_string(),
question,
is_other: false,
is_secret: false,
options: Some(options),
}
}
fn build_mcp_tool_approval_fallback_message(
server: &str,
tool_name: &str,
connector_name: Option<&str>,
) -> String {
let actor = connector_name
.map(str::trim)
.filter(|name| !name.is_empty())
.map(ToString::to_string)
.unwrap_or_else(|| {
if server == CODEX_APPS_MCP_SERVER_NAME {
"this app".to_string()
} else {
format!("the {server} MCP server")
}
});
format!("Allow {actor} to run tool \"{tool_name}\"?")
}
fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String {
match monitor_reason.map(str::trim) {
Some(reason) if !reason.is_empty() => {
format!("Tool call needs your approval. Reason: {reason}")
}
_ => question,
}
}
fn arc_monitor_interrupt_message(reason: &str) -> String {
let reason = reason.trim();
if reason.is_empty() {
@@ -1404,7 +1616,8 @@ fn build_mcp_tool_approval_elicitation_request(
turn_id: Some(turn_context.sub_id.clone()),
server_name: request.server.to_string(),
request: McpServerElicitationRequest::Form {
meta: request.approval_request.mcp_tool_approval_elicitation_meta(
meta: build_mcp_tool_approval_elicitation_meta(
request.approval_request,
request.tool_params,
request.tool_params_display,
request.prompt_options,
@@ -1420,6 +1633,129 @@ fn build_mcp_tool_approval_elicitation_request(
}
}
fn build_mcp_tool_approval_elicitation_meta(
approval_request: &GuardianApprovalRequest,
tool_params: Option<&JsonValue>,
tool_params_display: Option<&[RenderedMcpToolApprovalParam]>,
prompt_options: McpToolApprovalPromptOptions,
) -> Option<JsonValue> {
let GuardianApprovalRequest::McpToolCall {
server,
connector_id,
connector_name,
connector_description,
tool_title,
tool_description,
..
} = approval_request
else {
return None;
};
let mut meta = serde_json::Map::new();
meta.insert(
MCP_TOOL_APPROVAL_KIND_KEY.to_string(),
JsonValue::String(MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL.to_string()),
);
match (
prompt_options.allow_session_remember,
prompt_options.allow_persistent_approval,
) {
(true, true) => {
meta.insert(
MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(),
serde_json::json!([
MCP_TOOL_APPROVAL_PERSIST_SESSION,
MCP_TOOL_APPROVAL_PERSIST_ALWAYS,
]),
);
}
(true, false) => {
meta.insert(
MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(),
JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_SESSION.to_string()),
);
}
(false, true) => {
meta.insert(
MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(),
JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_ALWAYS.to_string()),
);
}
(false, false) => {}
}
if let Some(tool_title) = tool_title.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_TOOL_TITLE_KEY.to_string(),
JsonValue::String(tool_title.clone()),
);
}
if let Some(tool_description) = tool_description.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY.to_string(),
JsonValue::String(tool_description.clone()),
);
}
if server == CODEX_APPS_MCP_SERVER_NAME
&& (connector_id.is_some() || connector_name.is_some() || connector_description.is_some())
{
meta.insert(
MCP_TOOL_APPROVAL_SOURCE_KEY.to_string(),
JsonValue::String(MCP_TOOL_APPROVAL_SOURCE_CONNECTOR.to_string()),
);
if let Some(connector_id) = connector_id.as_deref() {
meta.insert(
MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY.to_string(),
JsonValue::String(connector_id.to_string()),
);
}
if let Some(connector_name) = connector_name.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY.to_string(),
JsonValue::String(connector_name.clone()),
);
}
if let Some(connector_description) = connector_description.as_ref() {
meta.insert(
MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY.to_string(),
JsonValue::String(connector_description.clone()),
);
}
}
if let Some(tool_params) = tool_params {
meta.insert(
MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY.to_string(),
tool_params.clone(),
);
}
if let Some(tool_params_display) = tool_params_display
&& let Ok(tool_params_display) = serde_json::to_value(tool_params_display)
{
meta.insert(
MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY.to_string(),
tool_params_display,
);
}
(!meta.is_empty()).then_some(JsonValue::Object(meta))
}
fn build_mcp_tool_approval_display_params(
tool_params: Option<&JsonValue>,
) -> Option<Vec<RenderedMcpToolApprovalParam>> {
let tool_params = tool_params?.as_object()?;
let mut display_params = tool_params
.iter()
.map(|(name, value)| RenderedMcpToolApprovalParam {
name: name.clone(),
value: value.clone(),
display_name: name.clone(),
})
.collect::<Vec<_>>();
display_params.sort_by(|left, right| left.name.cmp(&right.name));
Some(display_params)
}
fn parse_mcp_tool_approval_elicitation_response(
response: Option<ElicitationResponse>,
question_id: &str,
+150 -79
View File
@@ -1,20 +1,7 @@
use super::*;
use crate::config::ConfigBuilder;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::GuardianMcpAnnotations;
use crate::guardian::MCP_TOOL_APPROVAL_CANCEL;
use crate::guardian::MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC;
use crate::guardian::MCP_TOOL_APPROVAL_KIND_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL;
use crate::guardian::MCP_TOOL_APPROVAL_SOURCE_CONNECTOR;
use crate::guardian::MCP_TOOL_APPROVAL_SOURCE_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY;
use crate::guardian::MCP_TOOL_APPROVAL_TOOL_TITLE_KEY;
use crate::session::tests::make_session_and_context;
use crate::session::tests::make_session_and_context_with_rx;
use crate::state::ActiveTurn;
@@ -123,7 +110,7 @@ fn approval_prompt_request(
tool_name: &str,
arguments: Option<serde_json::Value>,
metadata: Option<&McpToolApprovalMetadata>,
) -> ApprovalRequest {
) -> GuardianApprovalRequest {
build_mcp_tool_approval_request(
"call-1",
tool_name,
@@ -320,22 +307,90 @@ fn approval_question_text_prepends_safety_reason() {
/*metadata*/ None,
);
assert_eq!(
request
.mcp_tool_approval_prompt(
"q".to_string(),
prompt_options(
/*allow_session_remember*/ false,
/*allow_persistent_approval*/ false,
),
Some("This tool may contact an external system."),
)
.expect("mcp approval prompt")
.question
.question,
mcp_tool_approval_prompt(
&request,
"q".to_string(),
prompt_options(
/*allow_session_remember*/ false, /*allow_persistent_approval*/ false,
),
Some("This tool may contact an external system."),
)
.expect("mcp approval prompt")
.question
.question,
"Tool call needs your approval. Reason: This tool may contact an external system."
);
}
#[test]
fn mcp_tool_approval_compat_response_uses_session_label_when_present() {
let request = approval_prompt_request(
"custom_server",
"dangerous_tool",
/*arguments*/ None,
/*metadata*/ None,
);
let question = RequestUserInputQuestion {
id: "q-1".to_string(),
header: "Approve app tool call?".to_string(),
question: "Allow this app tool?".to_string(),
is_other: false,
is_secret: false,
options: Some(vec![RequestUserInputQuestionOption {
label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(),
description: "Remember until session ends".to_string(),
}]),
};
let response =
mcp_tool_approval_compat_response(&request, &question, ReviewDecision::ApprovedForSession)
.expect("compat response");
assert_eq!(
response.answers.get("q-1"),
Some(&RequestUserInputAnswer {
answers: vec![MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string()],
})
);
}
#[test]
fn mcp_tool_approval_compat_response_uses_synthetic_decline_for_abort() {
let request = approval_prompt_request(
"custom_server",
"dangerous_tool",
/*arguments*/ None,
/*metadata*/ None,
);
let question = RequestUserInputQuestion {
id: "q-1".to_string(),
header: "Approve app tool call?".to_string(),
question: "Allow this app tool?".to_string(),
is_other: false,
is_secret: false,
options: None,
};
let response = mcp_tool_approval_compat_response(&request, &question, ReviewDecision::Abort)
.expect("compat response");
assert_eq!(
response.answers.get("q-1"),
Some(&RequestUserInputAnswer {
answers: vec![MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()],
})
);
}
#[test]
fn mcp_tool_approval_question_id_detection_round_trips() {
let question_id = format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_call-1");
assert_eq!(question_id, "mcp_tool_call_approval_call-1");
assert!(is_mcp_tool_approval_question_id(&question_id));
assert!(!is_mcp_tool_approval_question_id("other_question"));
}
#[tokio::test]
async fn mcp_tool_call_span_records_expected_fields() {
let buffer: &'static std::sync::Mutex<Vec<u8>> =
@@ -543,15 +598,15 @@ async fn approval_elicitation_request_uses_message_override_and_preserves_tool_p
})),
Some(&metadata),
);
let prompt = approval_request
.mcp_tool_approval_prompt(
"q".to_string(),
prompt_options(
/*allow_session_remember*/ true, /*allow_persistent_approval*/ true,
),
/*monitor_reason*/ None,
)
.expect("mcp approval prompt");
let prompt = mcp_tool_approval_prompt(
&approval_request,
"q".to_string(),
prompt_options(
/*allow_session_remember*/ true, /*allow_persistent_approval*/ true,
),
/*monitor_reason*/ None,
)
.expect("mcp approval prompt");
let request = build_mcp_tool_approval_elicitation_request(
&session,
@@ -625,13 +680,13 @@ async fn approval_elicitation_request_uses_message_override_and_preserves_tool_p
#[test]
fn custom_mcp_tool_question_mentions_server_name() {
let question = approval_prompt_request(
"custom_server",
"run_action",
/*arguments*/ None,
/*metadata*/ None,
)
.mcp_tool_approval_prompt(
let question = mcp_tool_approval_prompt(
&approval_prompt_request(
"custom_server",
"run_action",
/*arguments*/ None,
/*metadata*/ None,
),
"q".to_string(),
prompt_options(
/*allow_session_remember*/ false, /*allow_persistent_approval*/ false,
@@ -658,13 +713,13 @@ fn custom_mcp_tool_question_mentions_server_name() {
#[test]
fn codex_apps_tool_question_uses_fallback_app_label() {
let question = approval_prompt_request(
CODEX_APPS_MCP_SERVER_NAME,
"run_action",
/*arguments*/ None,
/*metadata*/ None,
)
.mcp_tool_approval_prompt(
let question = mcp_tool_approval_prompt(
&approval_prompt_request(
CODEX_APPS_MCP_SERVER_NAME,
"run_action",
/*arguments*/ None,
/*metadata*/ None,
),
"q".to_string(),
prompt_options(
/*allow_session_remember*/ true, /*allow_persistent_approval*/ true,
@@ -682,14 +737,20 @@ fn codex_apps_tool_question_uses_fallback_app_label() {
#[test]
fn trusted_codex_apps_tool_question_offers_always_allow() {
let metadata = approval_metadata(Some("calendar"), Some("Calendar"), None, None, None);
let question = approval_prompt_request(
CODEX_APPS_MCP_SERVER_NAME,
"run_action",
/*arguments*/ None,
Some(&metadata),
)
.mcp_tool_approval_prompt(
let metadata = approval_metadata(
Some("calendar"),
Some("Calendar"),
/*connector_description*/ None,
/*tool_title*/ None,
/*tool_description*/ None,
);
let question = mcp_tool_approval_prompt(
&approval_prompt_request(
CODEX_APPS_MCP_SERVER_NAME,
"run_action",
/*arguments*/ None,
Some(&metadata),
),
"q".to_string(),
prompt_options(
/*allow_session_remember*/ true, /*allow_persistent_approval*/ true,
@@ -730,14 +791,20 @@ fn codex_apps_tool_question_without_elicitation_omits_always_allow() {
tool_name: "run_action".to_string(),
};
let persistent_key = session_key.clone();
let metadata = approval_metadata(Some("calendar"), Some("Calendar"), None, None, None);
let question = approval_prompt_request(
CODEX_APPS_MCP_SERVER_NAME,
"run_action",
/*arguments*/ None,
Some(&metadata),
)
.mcp_tool_approval_prompt(
let metadata = approval_metadata(
Some("calendar"),
Some("Calendar"),
/*connector_description*/ None,
/*tool_title*/ None,
/*tool_description*/ None,
);
let question = mcp_tool_approval_prompt(
&approval_prompt_request(
CODEX_APPS_MCP_SERVER_NAME,
"run_action",
/*arguments*/ None,
Some(&metadata),
),
"q".to_string(),
mcp_tool_approval_prompt_options(
Some(&session_key),
@@ -766,13 +833,13 @@ fn codex_apps_tool_question_without_elicitation_omits_always_allow() {
#[test]
fn custom_mcp_tool_question_offers_session_remember_and_always_allow() {
let question = approval_prompt_request(
"custom_server",
"run_action",
/*arguments*/ None,
/*metadata*/ None,
)
.mcp_tool_approval_prompt(
let question = mcp_tool_approval_prompt(
&approval_prompt_request(
"custom_server",
"run_action",
/*arguments*/ None,
/*metadata*/ None,
),
"q".to_string(),
prompt_options(
/*allow_session_remember*/ true, /*allow_persistent_approval*/ true,
@@ -1169,7 +1236,8 @@ fn approval_elicitation_meta_marks_tool_approvals() {
/*metadata*/ None,
);
assert_eq!(
request.mcp_tool_approval_elicitation_meta(
build_mcp_tool_approval_elicitation_meta(
&request,
/*tool_params*/ None,
/*tool_params_display*/ None,
prompt_options(
@@ -1198,7 +1266,8 @@ fn approval_elicitation_meta_merges_session_and_always_persist_for_custom_server
Some(&metadata),
);
assert_eq!(
request.mcp_tool_approval_elicitation_meta(
build_mcp_tool_approval_elicitation_meta(
&request,
Some(&serde_json::json!({"id": 1})),
/*tool_params_display*/ None,
prompt_options(
@@ -1245,7 +1314,7 @@ fn guardian_mcp_review_request_includes_invocation_metadata() {
assert_eq!(
request,
ApprovalRequest::McpToolCall {
GuardianApprovalRequest::McpToolCall {
id: "call-1".to_string(),
server: CODEX_APPS_MCP_SERVER_NAME.to_string(),
tool_name: "browser_navigate".to_string(),
@@ -1287,7 +1356,7 @@ fn guardian_mcp_review_request_includes_annotations_when_present() {
assert_eq!(
request,
ApprovalRequest::McpToolCall {
GuardianApprovalRequest::McpToolCall {
id: "call-1".to_string(),
server: "custom_server".to_string(),
tool_name: "dangerous_tool".to_string(),
@@ -1421,7 +1490,8 @@ fn approval_elicitation_meta_includes_connector_source_for_codex_apps() {
Some(&metadata),
);
assert_eq!(
request.mcp_tool_approval_elicitation_meta(
build_mcp_tool_approval_elicitation_meta(
&request,
Some(&serde_json::json!({
"calendar_id": "primary",
})),
@@ -1463,7 +1533,8 @@ fn approval_elicitation_meta_merges_session_and_always_persist_with_connector_so
Some(&metadata),
);
assert_eq!(
request.mcp_tool_approval_elicitation_meta(
build_mcp_tool_approval_elicitation_meta(
&request,
Some(&serde_json::json!({
"calendar_id": "primary",
})),
+4 -4
View File
@@ -32,7 +32,7 @@ use crate::context::PersonalitySpecInstructions;
use crate::default_skill_metadata_budget;
use crate::environment_selection::ResolvedTurnEnvironments;
use crate::exec_policy::ExecPolicyManager;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::installation_id::resolve_installation_id;
use crate::parse_turn_item;
use crate::path_utils::normalize_for_native_workdir;
@@ -1845,7 +1845,7 @@ impl Session {
pub async fn request_command_approval_for_request(
&self,
turn_context: &TurnContext,
approval_request: ApprovalRequest,
approval_request: GuardianApprovalRequest,
approval_id: Option<String>,
reason: Option<String>,
network_approval_context: Option<NetworkApprovalContext>,
@@ -1930,7 +1930,7 @@ impl Session {
pub async fn request_patch_approval_for_request(
&self,
turn_context: &TurnContext,
approval_request: ApprovalRequest,
approval_request: GuardianApprovalRequest,
reason: Option<String>,
grant_root: Option<PathBuf>,
) -> oneshot::Receiver<ReviewDecision> {
@@ -2029,7 +2029,7 @@ impl Session {
}
let requested_permissions = args.permissions;
let approval_request = ApprovalRequest::RequestPermissions {
let approval_request = GuardianApprovalRequest::RequestPermissions {
id: call_id.clone(),
turn_id: turn_context.sub_id.clone(),
reason: args.reason.clone(),
+2 -2
View File
@@ -97,7 +97,7 @@ use codex_protocol::protocol::TurnDiffEvent;
use codex_protocol::protocol::WarningEvent;
use codex_protocol::user_input::UserInput;
use codex_tools::ToolName;
use codex_tools::filter_tool_suggest_discoverable_tools_for_client;
use codex_tools::filter_request_plugin_install_discoverable_tools_for_client;
use codex_utils_stream_parser::AssistantTextChunk;
use codex_utils_stream_parser::AssistantTextStreamParser;
use codex_utils_stream_parser::ProposedPlanSegment;
@@ -1170,7 +1170,7 @@ pub(crate) async fn built_tools(
)
.await
.map(|discoverable_tools| {
filter_tool_suggest_discoverable_tools_for_client(
filter_request_plugin_install_discoverable_tools_for_client(
discoverable_tools,
turn_context.app_server_client_name.as_deref(),
)
+2 -2
View File
@@ -10,11 +10,11 @@ pub(crate) mod multi_agents_common;
pub(crate) mod multi_agents_v2;
mod plan;
mod request_permissions;
mod request_plugin_install;
mod request_user_input;
mod shell;
mod test_sync;
mod tool_search;
mod tool_suggest;
mod unavailable_tool;
pub(crate) mod unified_exec;
mod view_image;
@@ -43,12 +43,12 @@ pub use mcp::McpHandler;
pub use mcp_resource::McpResourceHandler;
pub use plan::PlanHandler;
pub use request_permissions::RequestPermissionsHandler;
pub use request_plugin_install::RequestPluginInstallHandler;
pub use request_user_input::RequestUserInputHandler;
pub use shell::ShellCommandHandler;
pub use shell::ShellHandler;
pub use test_sync::TestSyncHandler;
pub use tool_search::ToolSearchHandler;
pub use tool_suggest::ToolSuggestHandler;
pub use unavailable_tool::UnavailableToolHandler;
pub(crate) use unavailable_tool::unavailable_tool_message;
pub use unified_exec::UnifiedExecHandler;
@@ -8,15 +8,15 @@ use codex_rmcp_client::ElicitationResponse;
use codex_tools::DiscoverableTool;
use codex_tools::DiscoverableToolAction;
use codex_tools::DiscoverableToolType;
use codex_tools::TOOL_SUGGEST_PERSIST_ALWAYS_VALUE;
use codex_tools::TOOL_SUGGEST_PERSIST_KEY;
use codex_tools::TOOL_SUGGEST_TOOL_NAME;
use codex_tools::ToolSuggestArgs;
use codex_tools::ToolSuggestResult;
use codex_tools::all_suggested_connectors_picked_up;
use codex_tools::build_tool_suggestion_elicitation_request;
use codex_tools::filter_tool_suggest_discoverable_tools_for_client;
use codex_tools::verified_connector_suggestion_completed;
use codex_tools::REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE;
use codex_tools::REQUEST_PLUGIN_INSTALL_PERSIST_KEY;
use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME;
use codex_tools::RequestPluginInstallArgs;
use codex_tools::RequestPluginInstallResult;
use codex_tools::all_requested_connectors_picked_up;
use codex_tools::build_request_plugin_install_elicitation_request;
use codex_tools::filter_request_plugin_install_discoverable_tools_for_client;
use codex_tools::verified_connector_install_completed;
use rmcp::model::RequestId;
use serde_json::Value;
use tracing::warn;
@@ -32,9 +32,9 @@ use crate::tools::handlers::parse_arguments;
use crate::tools::registry::ToolHandler;
use crate::tools::registry::ToolKind;
pub struct ToolSuggestHandler;
pub struct RequestPluginInstallHandler;
impl ToolHandler for ToolSuggestHandler {
impl ToolHandler for RequestPluginInstallHandler {
type Output = FunctionToolOutput;
fn kind(&self) -> ToolKind {
@@ -43,7 +43,7 @@ impl ToolHandler for ToolSuggestHandler {
#[expect(
clippy::await_holding_invalid_type,
reason = "tool suggestion discovery reads through the session-owned manager guard"
reason = "plugin install discovery reads through the session-owned manager guard"
)]
async fn handle(&self, invocation: ToolInvocation) -> Result<Self::Output, FunctionCallError> {
let ToolInvocation {
@@ -58,12 +58,12 @@ impl ToolHandler for ToolSuggestHandler {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::Fatal(format!(
"{TOOL_SUGGEST_TOOL_NAME} handler received unsupported payload"
"{REQUEST_PLUGIN_INSTALL_TOOL_NAME} handler received unsupported payload"
)));
}
};
let args: ToolSuggestArgs = parse_arguments(&arguments)?;
let args: RequestPluginInstallArgs = parse_arguments(&arguments)?;
let suggest_reason = args.suggest_reason.trim();
if suggest_reason.is_empty() {
return Err(FunctionCallError::RespondToModel(
@@ -72,14 +72,15 @@ impl ToolHandler for ToolSuggestHandler {
}
if args.action_type != DiscoverableToolAction::Install {
return Err(FunctionCallError::RespondToModel(
"tool suggestions currently support only action_type=\"install\"".to_string(),
"plugin install requests currently support only action_type=\"install\""
.to_string(),
));
}
if args.tool_type == DiscoverableToolType::Plugin
&& turn.app_server_client_name.as_deref() == Some("codex-tui")
{
return Err(FunctionCallError::RespondToModel(
"plugin tool suggestions are not available in codex-tui yet".to_string(),
"plugin install requests are not available in codex-tui yet".to_string(),
));
}
@@ -98,14 +99,14 @@ impl ToolHandler for ToolSuggestHandler {
)
.await
.map(|discoverable_tools| {
filter_tool_suggest_discoverable_tools_for_client(
filter_request_plugin_install_discoverable_tools_for_client(
discoverable_tools,
turn.app_server_client_name.as_deref(),
)
})
.map_err(|err| {
FunctionCallError::RespondToModel(format!(
"tool suggestions are unavailable right now: {err}"
"plugin install requests are unavailable right now: {err}"
))
})?;
@@ -114,12 +115,12 @@ impl ToolHandler for ToolSuggestHandler {
.find(|tool| tool.tool_type() == args.tool_type && tool.id() == args.tool_id)
.ok_or_else(|| {
FunctionCallError::RespondToModel(format!(
"tool_id must match one of the discoverable tools exposed by {TOOL_SUGGEST_TOOL_NAME}"
"tool_id must match one of the discoverable tools exposed by {REQUEST_PLUGIN_INSTALL_TOOL_NAME}"
))
})?;
let request_id = RequestId::String(format!("tool_suggestion_{call_id}").into());
let params = build_tool_suggestion_elicitation_request(
let request_id = RequestId::String(format!("request_plugin_install_{call_id}").into());
let params = build_request_plugin_install_elicitation_request(
CODEX_APPS_MCP_SERVER_NAME,
session.conversation_id.to_string(),
turn.sub_id.clone(),
@@ -131,14 +132,14 @@ impl ToolHandler for ToolSuggestHandler {
.request_mcp_server_elicitation(turn.as_ref(), request_id, params)
.await;
if let Some(response) = response.as_ref() {
maybe_persist_tool_suggest_disable(&session, &turn, &tool, response).await;
maybe_persist_disabled_install_request(&session, &turn, &tool, response).await;
}
let user_confirmed = response
.as_ref()
.is_some_and(|response| response.action == ElicitationAction::Accept);
let completed = if user_confirmed {
verify_tool_suggestion_completed(&session, &turn, &tool, auth.as_ref()).await
verify_request_plugin_install_completed(&session, &turn, &tool, auth.as_ref()).await
} else {
false
};
@@ -149,7 +150,7 @@ impl ToolHandler for ToolSuggestHandler {
.await;
}
let content = serde_json::to_string(&ToolSuggestResult {
let content = serde_json::to_string(&RequestPluginInstallResult {
completed,
user_confirmed,
tool_type: args.tool_type,
@@ -160,7 +161,7 @@ impl ToolHandler for ToolSuggestHandler {
})
.map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize {TOOL_SUGGEST_TOOL_NAME} response: {err}"
"failed to serialize {REQUEST_PLUGIN_INSTALL_TOOL_NAME} response: {err}"
))
})?;
@@ -168,17 +169,17 @@ impl ToolHandler for ToolSuggestHandler {
}
}
async fn maybe_persist_tool_suggest_disable(
async fn maybe_persist_disabled_install_request(
session: &crate::session::session::Session,
turn: &crate::session::turn_context::TurnContext,
tool: &DiscoverableTool,
response: &ElicitationResponse,
) {
if !tool_suggest_response_requests_persistent_disable(response) {
if !request_plugin_install_response_requests_persistent_disable(response) {
return;
}
if let Err(err) = persist_tool_suggest_disable(&turn.config.codex_home, tool).await {
if let Err(err) = persist_disabled_install_request(&turn.config.codex_home, tool).await {
warn!(
error = %err,
tool_id = tool.id(),
@@ -190,7 +191,9 @@ async fn maybe_persist_tool_suggest_disable(
session.reload_user_config_layer().await;
}
fn tool_suggest_response_requests_persistent_disable(response: &ElicitationResponse) -> bool {
fn request_plugin_install_response_requests_persistent_disable(
response: &ElicitationResponse,
) -> bool {
if response.action != ElicitationAction::Decline {
return false;
}
@@ -199,24 +202,24 @@ fn tool_suggest_response_requests_persistent_disable(response: &ElicitationRespo
.meta
.as_ref()
.and_then(Value::as_object)
.and_then(|meta| meta.get(TOOL_SUGGEST_PERSIST_KEY))
.and_then(|meta| meta.get(REQUEST_PLUGIN_INSTALL_PERSIST_KEY))
.and_then(Value::as_str)
== Some(TOOL_SUGGEST_PERSIST_ALWAYS_VALUE)
== Some(REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE)
}
async fn persist_tool_suggest_disable(
async fn persist_disabled_install_request(
codex_home: &codex_utils_absolute_path::AbsolutePathBuf,
tool: &DiscoverableTool,
) -> anyhow::Result<()> {
ConfigEditsBuilder::new(codex_home)
.with_edits([ConfigEdit::AddToolSuggestDisabledTool(
disabled_tool_suggestion(tool),
disabled_install_request(tool),
)])
.apply()
.await
}
fn disabled_tool_suggestion(tool: &DiscoverableTool) -> ToolSuggestDisabledTool {
fn disabled_install_request(tool: &DiscoverableTool) -> ToolSuggestDisabledTool {
match tool {
DiscoverableTool::Connector(connector) => {
ToolSuggestDisabledTool::connector(connector.id.as_str())
@@ -225,14 +228,14 @@ fn disabled_tool_suggestion(tool: &DiscoverableTool) -> ToolSuggestDisabledTool
}
}
async fn verify_tool_suggestion_completed(
async fn verify_request_plugin_install_completed(
session: &crate::session::session::Session,
turn: &crate::session::turn_context::TurnContext,
tool: &DiscoverableTool,
auth: Option<&codex_login::CodexAuth>,
) -> bool {
match tool {
DiscoverableTool::Connector(connector) => refresh_missing_suggested_connectors(
DiscoverableTool::Connector(connector) => refresh_missing_requested_connectors(
session,
turn,
auth,
@@ -241,17 +244,17 @@ async fn verify_tool_suggestion_completed(
)
.await
.is_some_and(|accessible_connectors| {
verified_connector_suggestion_completed(connector.id.as_str(), &accessible_connectors)
verified_connector_install_completed(connector.id.as_str(), &accessible_connectors)
}),
DiscoverableTool::Plugin(plugin) => {
session.reload_user_config_layer().await;
let config = session.get_config().await;
let completed = verified_plugin_suggestion_completed(
let completed = verified_plugin_install_completed(
plugin.id.as_str(),
config.as_ref(),
session.services.plugins_manager.as_ref(),
);
let _ = refresh_missing_suggested_connectors(
let _ = refresh_missing_requested_connectors(
session,
turn,
auth,
@@ -268,7 +271,7 @@ async fn verify_tool_suggestion_completed(
clippy::await_holding_invalid_type,
reason = "connector cache refresh reads through the session-owned manager guard"
)]
async fn refresh_missing_suggested_connectors(
async fn refresh_missing_requested_connectors(
session: &crate::session::session::Session,
turn: &crate::session::turn_context::TurnContext,
auth: Option<&codex_login::CodexAuth>,
@@ -285,7 +288,7 @@ async fn refresh_missing_suggested_connectors(
connectors::accessible_connectors_from_mcp_tools(&mcp_tools),
&turn.config,
);
if all_suggested_connectors_picked_up(expected_connector_ids, &accessible_connectors) {
if all_requested_connectors_picked_up(expected_connector_ids, &accessible_connectors) {
return Some(accessible_connectors);
}
@@ -304,14 +307,14 @@ async fn refresh_missing_suggested_connectors(
}
Err(err) => {
warn!(
"failed to refresh codex apps tools cache after tool suggestion for {tool_id}: {err:#}"
"failed to refresh codex apps tools cache after plugin install request for {tool_id}: {err:#}"
);
None
}
}
}
fn verified_plugin_suggestion_completed(
fn verified_plugin_install_completed(
tool_id: &str,
config: &crate::config::Config,
plugins_manager: &codex_core_plugins::PluginsManager,
@@ -327,5 +330,5 @@ fn verified_plugin_suggestion_completed(
}
#[cfg(test)]
#[path = "tool_suggest_tests.rs"]
#[path = "request_plugin_install_tests.rs"]
mod tests;
@@ -22,7 +22,7 @@ use serde_json::json;
use tempfile::tempdir;
#[tokio::test]
async fn verified_plugin_suggestion_completed_requires_installed_plugin() {
async fn verified_plugin_install_completed_requires_installed_plugin() {
let codex_home = tempdir().expect("tempdir should succeed");
let curated_root = curated_plugins_repo_path(codex_home.path());
write_openai_curated_marketplace(&curated_root, &["sample"]);
@@ -32,7 +32,7 @@ async fn verified_plugin_suggestion_completed_requires_installed_plugin() {
let config = load_plugins_config(codex_home.path()).await;
let plugins_manager = PluginsManager::new(codex_home.path().to_path_buf());
assert!(!verified_plugin_suggestion_completed(
assert!(!verified_plugin_install_completed(
"sample@openai-curated",
&config,
&plugins_manager,
@@ -50,7 +50,7 @@ async fn verified_plugin_suggestion_completed_requires_installed_plugin() {
.expect("plugin should install");
let refreshed_config = load_plugins_config(codex_home.path()).await;
assert!(verified_plugin_suggestion_completed(
assert!(verified_plugin_install_completed(
"sample@openai-curated",
&refreshed_config,
&plugins_manager,
@@ -58,43 +58,47 @@ async fn verified_plugin_suggestion_completed_requires_installed_plugin() {
}
#[test]
fn tool_suggest_response_persists_only_decline_always_mode() {
assert!(tool_suggest_response_requests_persistent_disable(
fn request_plugin_install_response_persists_only_decline_always_mode() {
assert!(request_plugin_install_response_requests_persistent_disable(
&ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: Some(json!({ TOOL_SUGGEST_PERSIST_KEY: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE })),
meta: Some(json!({
REQUEST_PLUGIN_INSTALL_PERSIST_KEY: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE
})),
}
));
assert!(!tool_suggest_response_requests_persistent_disable(
&ElicitationResponse {
assert!(
!request_plugin_install_response_requests_persistent_disable(&ElicitationResponse {
action: ElicitationAction::Accept,
content: None,
meta: Some(json!({ TOOL_SUGGEST_PERSIST_KEY: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE })),
}
));
assert!(!tool_suggest_response_requests_persistent_disable(
&ElicitationResponse {
meta: Some(json!({
REQUEST_PLUGIN_INSTALL_PERSIST_KEY: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE
})),
})
);
assert!(
!request_plugin_install_response_requests_persistent_disable(&ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: Some(json!({ TOOL_SUGGEST_PERSIST_KEY: "session" })),
}
));
assert!(!tool_suggest_response_requests_persistent_disable(
&ElicitationResponse {
meta: Some(json!({ REQUEST_PLUGIN_INSTALL_PERSIST_KEY: "session" })),
})
);
assert!(
!request_plugin_install_response_requests_persistent_disable(&ElicitationResponse {
action: ElicitationAction::Decline,
content: None,
meta: None,
}
));
})
);
}
#[tokio::test]
async fn persist_tool_suggest_disable_writes_connector_config() {
async fn persist_disabled_install_request_writes_connector_config() {
let codex_home = tempdir().expect("tempdir should succeed");
let tool = connector_tool("connector_calendar", "Google Calendar");
persist_tool_suggest_disable(&codex_home.path().abs(), &tool)
persist_disabled_install_request(&codex_home.path().abs(), &tool)
.await
.expect("persist connector disable");
@@ -111,7 +115,7 @@ async fn persist_tool_suggest_disable_writes_connector_config() {
}
#[tokio::test]
async fn persist_tool_suggest_disable_writes_plugin_config() {
async fn persist_disabled_install_request_writes_plugin_config() {
let codex_home = tempdir().expect("tempdir should succeed");
let tool = DiscoverableTool::Plugin(Box::new(DiscoverablePluginInfo {
id: "slack@openai-curated".to_string(),
@@ -122,7 +126,7 @@ async fn persist_tool_suggest_disable_writes_plugin_config() {
app_connector_ids: Vec::new(),
}));
persist_tool_suggest_disable(&codex_home.path().abs(), &tool)
persist_disabled_install_request(&codex_home.path().abs(), &tool)
.await
.expect("persist plugin disable");
@@ -139,7 +143,7 @@ async fn persist_tool_suggest_disable_writes_plugin_config() {
}
#[tokio::test]
async fn persist_tool_suggest_disable_dedupes_existing_disabled_tools() {
async fn persist_disabled_install_request_dedupes_existing_disabled_tools() {
let codex_home = tempdir().expect("tempdir should succeed");
let tool = connector_tool("connector_calendar", "Google Calendar");
std::fs::write(
@@ -169,7 +173,7 @@ id = "slack@openai-curated"
)
.expect("write config");
persist_tool_suggest_disable(&codex_home.path().abs(), &tool)
persist_disabled_install_request(&codex_home.path().abs(), &tool)
.await
.expect("persist connector disable");
+2 -2
View File
@@ -1,4 +1,4 @@
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::GuardianNetworkAccessTrigger;
use crate::guardian::guardian_rejection_message;
use crate::guardian::guardian_timeout_message;
@@ -463,7 +463,7 @@ impl NetworkApprovalService {
|| format!("network-access {target}"),
|call| call.command.clone(),
);
let approval_request = ApprovalRequest::NetworkAccess {
let approval_request = GuardianApprovalRequest::NetworkAccess {
id: guardian_approval_id.clone(),
turn_id: owner_call
.as_ref()
+1 -1
View File
@@ -489,7 +489,7 @@ impl ToolOrchestrator {
if evaluate_permission_request_hooks
&& let Some(permission_request) = approval_request
.as_ref()
.and_then(crate::guardian::ApprovalRequest::permission_request_payload)
.and_then(crate::guardian::GuardianApprovalRequest::permission_request_payload)
{
match run_permission_request_hooks(
approval_ctx.session,
@@ -4,7 +4,7 @@
//! selected turn environment filesystem for both local and remote turns, with
//! sandboxing enforced by the explicit filesystem sandbox context.
use crate::exec::is_likely_sandbox_denied;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::review_approval_request;
use crate::tools::sandboxing::Approvable;
use crate::tools::sandboxing::ApprovalCtx;
@@ -51,8 +51,8 @@ impl ApplyPatchRuntime {
Self
}
fn build_approval_request(req: &ApplyPatchRequest, call_id: &str) -> ApprovalRequest {
ApprovalRequest::ApplyPatch {
fn build_approval_request(req: &ApplyPatchRequest, call_id: &str) -> GuardianApprovalRequest {
GuardianApprovalRequest::ApplyPatch {
id: call_id.to_string(),
cwd: req.action.cwd.clone(),
files: req.file_paths.clone(),
@@ -179,7 +179,7 @@ impl Approvable<ApplyPatchRequest> for ApplyPatchRuntime {
&self,
req: &ApplyPatchRequest,
ctx: &ApprovalCtx<'_>,
) -> Option<ApprovalRequest> {
) -> Option<GuardianApprovalRequest> {
Some(Self::build_approval_request(req, ctx.call_id))
}
}
@@ -1,5 +1,5 @@
use super::*;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::tools::sandboxing::SandboxAttempt;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::AdditionalPermissionProfile;
@@ -70,7 +70,7 @@ fn guardian_review_request_includes_patch_context() {
assert_eq!(
guardian_request,
ApprovalRequest::ApplyPatch {
GuardianApprovalRequest::ApplyPatch {
id: "call-1".to_string(),
cwd: expected_cwd,
files: request.file_paths,
+4 -4
View File
@@ -10,7 +10,7 @@ pub(crate) mod zsh_fork_backend;
use crate::command_canonicalization::canonicalize_command_for_approval;
use crate::exec::ExecCapturePolicy;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::GuardianNetworkAccessTrigger;
use crate::guardian::review_approval_request;
use crate::sandboxing::ExecOptions;
@@ -120,8 +120,8 @@ impl ShellRuntime {
})
}
fn build_approval_request(req: &ShellRequest, call_id: String) -> ApprovalRequest {
ApprovalRequest::Shell {
fn build_approval_request(req: &ShellRequest, call_id: String) -> GuardianApprovalRequest {
GuardianApprovalRequest::Shell {
id: call_id,
command: req.command.clone(),
hook_command: req.hook_command.clone(),
@@ -206,7 +206,7 @@ impl Approvable<ShellRequest> for ShellRuntime {
&self,
req: &ShellRequest,
ctx: &ApprovalCtx<'_>,
) -> Option<ApprovalRequest> {
) -> Option<GuardianApprovalRequest> {
Some(Self::build_approval_request(req, ctx.call_id.to_string()))
}
@@ -3,7 +3,7 @@ use crate::exec::ExecCapturePolicy;
use crate::exec::ExecExpiration;
use crate::exec::cancel_when_either;
use crate::exec::is_likely_sandbox_denied;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::guardian_rejection_message;
use crate::guardian::guardian_timeout_message;
use crate::guardian::new_guardian_review_id;
@@ -406,7 +406,7 @@ impl CoreShellActionProvider {
.pause_for(async move {
// 1) Run PermissionRequest hooks
let effective_approval_id = approval_id.clone().unwrap_or_else(|| call_id.clone());
let approval_request = ApprovalRequest::Execve {
let approval_request = GuardianApprovalRequest::Execve {
id: call_id.clone(),
source,
program: program.to_string_lossy().into_owned(),
@@ -7,7 +7,7 @@ the process manager to spawn PTYs once an ExecRequest is prepared.
use crate::command_canonicalization::canonicalize_command_for_approval;
use crate::exec::ExecCapturePolicy;
use crate::exec::ExecExpiration;
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::guardian::GuardianNetworkAccessTrigger;
use crate::guardian::review_approval_request;
use crate::sandboxing::ExecOptions;
@@ -110,8 +110,11 @@ impl<'a> UnifiedExecRuntime<'a> {
}
}
fn build_approval_request(req: &UnifiedExecRequest, call_id: String) -> ApprovalRequest {
ApprovalRequest::ExecCommand {
fn build_approval_request(
req: &UnifiedExecRequest,
call_id: String,
) -> GuardianApprovalRequest {
GuardianApprovalRequest::ExecCommand {
id: call_id,
command: req.command.clone(),
hook_command: req.hook_command.clone(),
@@ -202,7 +205,7 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
&self,
req: &UnifiedExecRequest,
ctx: &ApprovalCtx<'_>,
) -> Option<ApprovalRequest> {
) -> Option<GuardianApprovalRequest> {
Some(Self::build_approval_request(req, ctx.call_id.to_string()))
}
+6 -2
View File
@@ -4,7 +4,7 @@
//! `ApprovalCtx`, `Approvable`) together with the sandbox orchestration traits
//! and helpers (`Sandboxable`, `ToolRuntime`, `SandboxAttempt`, etc.).
use crate::guardian::ApprovalRequest;
use crate::guardian::GuardianApprovalRequest;
use crate::sandboxing::ExecOptions;
use crate::sandboxing::SandboxPermissions;
use crate::session::session::Session;
@@ -313,7 +313,11 @@ pub(crate) trait Approvable<Req> {
/// Return the canonical approval action for this request when the runtime
/// participates in approval hooks and/or guardian review.
fn approval_request(&self, _req: &Req, _ctx: &ApprovalCtx<'_>) -> Option<ApprovalRequest> {
fn approval_request(
&self,
_req: &Req,
_ctx: &ApprovalCtx<'_>,
) -> Option<GuardianApprovalRequest> {
None
}
+4 -4
View File
@@ -86,12 +86,12 @@ pub(crate) fn build_specs_with_discoverable_tools(
use crate::tools::handlers::McpResourceHandler;
use crate::tools::handlers::PlanHandler;
use crate::tools::handlers::RequestPermissionsHandler;
use crate::tools::handlers::RequestPluginInstallHandler;
use crate::tools::handlers::RequestUserInputHandler;
use crate::tools::handlers::ShellCommandHandler;
use crate::tools::handlers::ShellHandler;
use crate::tools::handlers::TestSyncHandler;
use crate::tools::handlers::ToolSearchHandler;
use crate::tools::handlers::ToolSuggestHandler;
use crate::tools::handlers::UnavailableToolHandler;
use crate::tools::handlers::UnifiedExecHandler;
use crate::tools::handlers::ViewImageHandler;
@@ -174,7 +174,7 @@ pub(crate) fn build_specs_with_discoverable_tools(
.cloned()
.collect::<Vec<_>>();
let mut tool_search_handler = None;
let tool_suggest_handler = Arc::new(ToolSuggestHandler);
let request_plugin_install_handler = Arc::new(RequestPluginInstallHandler);
let code_mode_handler = Arc::new(CodeModeExecuteHandler);
let code_mode_wait_handler = Arc::new(CodeModeWaitHandler);
let unavailable_tool_handler = Arc::new(UnavailableToolHandler);
@@ -281,8 +281,8 @@ pub(crate) fn build_specs_with_discoverable_tools(
builder.register_handler(handler.name, tool_search_handler.clone());
}
}
ToolHandlerKind::ToolSuggest => {
builder.register_handler(handler.name, tool_suggest_handler.clone());
ToolHandlerKind::RequestPluginInstall => {
builder.register_handler(handler.name, request_plugin_install_handler.clone());
}
ToolHandlerKind::UnifiedExec => {
builder.register_handler(handler.name, unified_exec_handler.clone());
+3 -3
View File
@@ -21,11 +21,11 @@ use codex_tools::ConfiguredToolSpec;
use codex_tools::DiscoverableTool;
use codex_tools::JsonSchema;
use codex_tools::LoadableToolSpec;
use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::ResponsesApiTool;
use codex_tools::ShellCommandBackendConfig;
use codex_tools::TOOL_SEARCH_TOOL_NAME;
use codex_tools::TOOL_SUGGEST_TOOL_NAME;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use codex_tools::ToolsConfig;
@@ -791,7 +791,7 @@ async fn multi_agent_v2_wait_agent_schema_uses_configured_min_timeout() {
}
#[tokio::test]
async fn tool_suggest_requires_apps_and_plugins_features() {
async fn request_plugin_install_requires_apps_and_plugins_features() {
let model_info = search_capable_model_info().await;
let discoverable_tools = Some(vec![discoverable_connector(
"connector_2128aebfecb84f64a069897515042a44",
@@ -831,7 +831,7 @@ async fn tool_suggest_requires_apps_and_plugins_features() {
assert!(
!tools
.iter()
.any(|tool| tool.name() == TOOL_SUGGEST_TOOL_NAME),
.any(|tool| tool.name() == REQUEST_PLUGIN_INSTALL_TOOL_NAME),
"tool_suggest should be absent when {disabled_feature:?} is disabled"
);
}
@@ -0,0 +1,29 @@
# Request plugin/connector install
Use this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.
Use this ONLY when all of the following are true:
- The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list.
- `tool_search` is not available, or it has already been called and did not find or make the requested tool callable.
- The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list.
Do not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful. Only use when the user explicitly asks to use that exact listed plugin or connector.
Known plugins/connectors available to install:
{{discoverable_tools}}
Workflow:
1. Check the current context and active `tools` list first. If current active tools aren't relevant and `tool_search` is available, only call this tool after `tool_search` has already been tried and found no relevant tool.
2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.
3. If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.
4. If one plugin or connector clearly fits, call `request_plugin_install` with:
- `tool_type`: `connector` or `plugin`
- `action_type`: `install`
- `tool_id`: exact id from the known plugin/connector list above
- `suggest_reason`: concise one-line user-facing reason this plugin or connector can help with the current request
5. After the request flow completes:
- if the user finished the install flow, continue by searching again or using the newly available plugin or connector
- if the user did not finish, continue without that plugin or connector, and don't request it again unless the user explicitly asks for it.
IMPORTANT: DO NOT call this tool in parallel with other tools.
@@ -1,29 +0,0 @@
# Tool suggestion discovery
Use this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.
Use this ONLY when all of the following are true:
- The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list.
- `tool_search` is not available, or it has already been called and did not find or make the requested tool callable.
- The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list.
Do not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful. The user's intent must clearly match one listed tool.
Known plugins/connectors available to install:
{{discoverable_tools}}
Workflow:
1. Check the current context and active `tools` list first. If `tool_search` is available, call `tool_search` before calling `tool_suggest`. Do not use tool suggestion if the needed tool is already available, found through `tool_search`, or callable after discovery.
2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.
3. If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.
4. If one tool clearly fits, call `tool_suggest` with:
- `tool_type`: `connector` or `plugin`
- `action_type`: `install`
- `tool_id`: exact id from the known plugin/connector list above
- `suggest_reason`: concise one-line user-facing reason this tool can help with the current request
5. After the suggestion flow completes:
- if the user finished the install flow, continue by searching again or using the newly available tool
- if the user did not finish, continue without that tool, and don't suggest that tool again unless the user explicitly asks for it.
IMPORTANT: DO NOT call this tool in parallel with other tools.
+1 -1
View File
@@ -77,6 +77,7 @@ mod request_compression;
mod request_permissions;
#[cfg(not(target_os = "windows"))]
mod request_permissions_tool;
mod request_plugin_install;
mod request_user_input;
mod responses_api_proxy_headers;
mod resume;
@@ -98,7 +99,6 @@ mod stream_no_completed;
mod subagent_notifications;
mod tool_harness;
mod tool_parallelism;
mod tool_suggest;
mod tools;
mod truncation;
mod turn_state;
@@ -22,7 +22,7 @@ use core_test_support::test_codex::test_codex;
use serde_json::Value;
const TOOL_SEARCH_TOOL_NAME: &str = "tool_search";
const TOOL_SUGGEST_TOOL_NAME: &str = "tool_suggest";
const REQUEST_PLUGIN_INSTALL_TOOL_NAME: &str = "request_plugin_install";
const DISCOVERABLE_GMAIL_ID: &str = "connector_68df038e0ba48191908c8434991bbac2";
fn tool_names(body: &Value) -> Vec<String> {
@@ -89,7 +89,8 @@ fn configure_apps_without_search_tool(config: &mut Config, apps_base_url: &str)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tool_suggest_is_available_without_search_tool_after_discovery_attempts() -> Result<()> {
async fn request_plugin_install_is_available_without_search_tool_after_discovery_attempts()
-> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -125,18 +126,23 @@ async fn tool_suggest_is_available_without_search_tool_after_discovery_attempts(
"tools list should not include {TOOL_SEARCH_TOOL_NAME}: {tools:?}"
);
assert!(
tools.iter().any(|name| name == TOOL_SUGGEST_TOOL_NAME),
"tools list should include {TOOL_SUGGEST_TOOL_NAME}: {tools:?}"
tools
.iter()
.any(|name| name == REQUEST_PLUGIN_INSTALL_TOOL_NAME),
"tools list should include {REQUEST_PLUGIN_INSTALL_TOOL_NAME}: {tools:?}"
);
let description =
function_tool_description(&body, TOOL_SUGGEST_TOOL_NAME).expect("description");
function_tool_description(&body, REQUEST_PLUGIN_INSTALL_TOOL_NAME).expect("description");
assert!(description.contains(
"Use this tool only to ask the user to install one known plugin or connector from the list below"
));
assert!(description.contains(
"`tool_search` is not available, or it has already been called and did not find or make the requested tool callable."
));
assert!(description.contains(
"Only use when the user explicitly asks to use that exact listed plugin or connector."
));
assert!(description.contains("IMPORTANT: DO NOT call this tool in parallel with other tools."));
assert!(!description.contains("tool_search fails to find a good match"));
+1 -1
View File
@@ -27,7 +27,7 @@ schema and Responses API tool primitives that no longer need to live in
- collaboration and agent-job `ToolSpec` builders for spawn/send/wait/close,
`request_user_input`, and CSV fanout/reporting
- discoverable-tool models, client filtering, and `ToolSpec` builders for
`tool_search` and `tool_suggest`
`tool_search` and `request_plugin_install`
- `parse_tool_input_schema()`
- `parse_dynamic_tool()`
- `parse_mcp_tool()`
+15 -15
View File
@@ -13,6 +13,7 @@ mod local_tool;
mod mcp_resource_tool;
mod mcp_tool;
mod plan_tool;
mod request_plugin_install;
mod request_user_input_tool;
mod responses_api;
mod tool_config;
@@ -21,7 +22,6 @@ mod tool_discovery;
mod tool_registry_plan;
mod tool_registry_plan_types;
mod tool_spec;
mod tool_suggest;
mod utility_tool;
mod view_image;
@@ -80,6 +80,15 @@ pub use mcp_resource_tool::create_read_mcp_resource_tool;
pub use mcp_tool::mcp_call_tool_result_output_schema;
pub use mcp_tool::parse_mcp_tool;
pub use plan_tool::create_update_plan_tool;
pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE;
pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE;
pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_PERSIST_KEY;
pub use request_plugin_install::RequestPluginInstallArgs;
pub use request_plugin_install::RequestPluginInstallMeta;
pub use request_plugin_install::RequestPluginInstallResult;
pub use request_plugin_install::all_requested_connectors_picked_up;
pub use request_plugin_install::build_request_plugin_install_elicitation_request;
pub use request_plugin_install::verified_connector_install_completed;
pub use request_user_input_tool::REQUEST_USER_INPUT_TOOL_NAME;
pub use request_user_input_tool::create_request_user_input_tool;
pub use request_user_input_tool::normalize_request_user_input_args;
@@ -110,18 +119,18 @@ pub use tool_discovery::DiscoverablePluginInfo;
pub use tool_discovery::DiscoverableTool;
pub use tool_discovery::DiscoverableToolAction;
pub use tool_discovery::DiscoverableToolType;
pub use tool_discovery::REQUEST_PLUGIN_INSTALL_TOOL_NAME;
pub use tool_discovery::RequestPluginInstallEntry;
pub use tool_discovery::TOOL_SEARCH_DEFAULT_LIMIT;
pub use tool_discovery::TOOL_SEARCH_TOOL_NAME;
pub use tool_discovery::TOOL_SUGGEST_TOOL_NAME;
pub use tool_discovery::ToolSearchResultSource;
pub use tool_discovery::ToolSearchSource;
pub use tool_discovery::ToolSearchSourceInfo;
pub use tool_discovery::ToolSuggestEntry;
pub use tool_discovery::collect_request_plugin_install_entries;
pub use tool_discovery::collect_tool_search_source_infos;
pub use tool_discovery::collect_tool_suggest_entries;
pub use tool_discovery::create_request_plugin_install_tool;
pub use tool_discovery::create_tool_search_tool;
pub use tool_discovery::create_tool_suggest_tool;
pub use tool_discovery::filter_tool_suggest_discoverable_tools_for_client;
pub use tool_discovery::filter_request_plugin_install_discoverable_tools_for_client;
pub use tool_discovery::tool_search_result_source_to_loadable_tool_spec;
pub use tool_registry_plan::build_tool_registry_plan;
pub use tool_registry_plan_types::ToolHandlerKind;
@@ -140,15 +149,6 @@ pub use tool_spec::create_image_generation_tool;
pub use tool_spec::create_local_shell_tool;
pub use tool_spec::create_tools_json_for_responses_api;
pub use tool_spec::create_web_search_tool;
pub use tool_suggest::TOOL_SUGGEST_APPROVAL_KIND_VALUE;
pub use tool_suggest::TOOL_SUGGEST_PERSIST_ALWAYS_VALUE;
pub use tool_suggest::TOOL_SUGGEST_PERSIST_KEY;
pub use tool_suggest::ToolSuggestArgs;
pub use tool_suggest::ToolSuggestMeta;
pub use tool_suggest::ToolSuggestResult;
pub use tool_suggest::all_suggested_connectors_picked_up;
pub use tool_suggest::build_tool_suggestion_elicitation_request;
pub use tool_suggest::verified_connector_suggestion_completed;
pub use utility_tool::create_list_dir_tool;
pub use utility_tool::create_test_sync_tool;
pub use view_image::ViewImageToolOptions;
@@ -13,12 +13,12 @@ use crate::DiscoverableTool;
use crate::DiscoverableToolAction;
use crate::DiscoverableToolType;
pub const TOOL_SUGGEST_APPROVAL_KIND_VALUE: &str = "tool_suggestion";
pub const TOOL_SUGGEST_PERSIST_KEY: &str = "persist";
pub const TOOL_SUGGEST_PERSIST_ALWAYS_VALUE: &str = "always";
pub const REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE: &str = "tool_suggestion";
pub const REQUEST_PLUGIN_INSTALL_PERSIST_KEY: &str = "persist";
pub const REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE: &str = "always";
#[derive(Debug, Deserialize)]
pub struct ToolSuggestArgs {
pub struct RequestPluginInstallArgs {
pub tool_type: DiscoverableToolType,
pub action_type: DiscoverableToolAction,
pub tool_id: String,
@@ -26,7 +26,7 @@ pub struct ToolSuggestArgs {
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct ToolSuggestResult {
pub struct RequestPluginInstallResult {
pub completed: bool,
pub user_confirmed: bool,
pub tool_type: DiscoverableToolType,
@@ -37,7 +37,7 @@ pub struct ToolSuggestResult {
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct ToolSuggestMeta<'a> {
pub struct RequestPluginInstallMeta<'a> {
pub codex_approval_kind: &'static str,
pub persist: &'static str,
pub tool_type: DiscoverableToolType,
@@ -49,11 +49,11 @@ pub struct ToolSuggestMeta<'a> {
pub install_url: Option<&'a str>,
}
pub fn build_tool_suggestion_elicitation_request(
pub fn build_request_plugin_install_elicitation_request(
server_name: &str,
thread_id: String,
turn_id: String,
args: &ToolSuggestArgs,
args: &RequestPluginInstallArgs,
suggest_reason: &str,
tool: &DiscoverableTool,
) -> McpServerElicitationRequestParams {
@@ -66,7 +66,7 @@ pub fn build_tool_suggestion_elicitation_request(
turn_id: Some(turn_id),
server_name: server_name.to_string(),
request: McpServerElicitationRequest::Form {
meta: Some(json!(build_tool_suggestion_meta(
meta: Some(json!(build_request_plugin_install_meta(
args.tool_type,
args.action_type,
suggest_reason,
@@ -85,16 +85,16 @@ pub fn build_tool_suggestion_elicitation_request(
}
}
pub fn all_suggested_connectors_picked_up(
pub fn all_requested_connectors_picked_up(
expected_connector_ids: &[String],
accessible_connectors: &[AppInfo],
) -> bool {
expected_connector_ids.iter().all(|connector_id| {
verified_connector_suggestion_completed(connector_id, accessible_connectors)
verified_connector_install_completed(connector_id, accessible_connectors)
})
}
pub fn verified_connector_suggestion_completed(
pub fn verified_connector_install_completed(
tool_id: &str,
accessible_connectors: &[AppInfo],
) -> bool {
@@ -104,17 +104,17 @@ pub fn verified_connector_suggestion_completed(
.is_some_and(|connector| connector.is_accessible)
}
fn build_tool_suggestion_meta<'a>(
fn build_request_plugin_install_meta<'a>(
tool_type: DiscoverableToolType,
action_type: DiscoverableToolAction,
suggest_reason: &'a str,
tool_id: &'a str,
tool_name: &'a str,
install_url: Option<&'a str>,
) -> ToolSuggestMeta<'a> {
ToolSuggestMeta {
codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE,
persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE,
) -> RequestPluginInstallMeta<'a> {
RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type,
suggest_type: action_type,
suggest_reason,
@@ -125,5 +125,5 @@ fn build_tool_suggestion_meta<'a>(
}
#[cfg(test)]
#[path = "tool_suggest_tests.rs"]
#[path = "request_plugin_install_tests.rs"]
mod tests;
@@ -4,8 +4,8 @@ use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn build_tool_suggestion_elicitation_request_uses_expected_shape() {
let args = ToolSuggestArgs {
fn build_request_plugin_install_elicitation_request_uses_expected_shape() {
let args = RequestPluginInstallArgs {
tool_type: DiscoverableToolType::Connector,
action_type: DiscoverableToolAction::Install,
tool_id: "connector_2128aebfecb84f64a069897515042a44".to_string(),
@@ -30,7 +30,7 @@ fn build_tool_suggestion_elicitation_request_uses_expected_shape() {
plugin_display_names: Vec::new(),
}));
let request = build_tool_suggestion_elicitation_request(
let request = build_request_plugin_install_elicitation_request(
"codex-apps",
"thread-1".to_string(),
"turn-1".to_string(),
@@ -46,9 +46,9 @@ fn build_tool_suggestion_elicitation_request_uses_expected_shape() {
turn_id: Some("turn-1".to_string()),
server_name: "codex-apps".to_string(),
request: McpServerElicitationRequest::Form {
meta: Some(json!(ToolSuggestMeta {
codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE,
persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE,
meta: Some(json!(RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type: DiscoverableToolType::Connector,
suggest_type: DiscoverableToolAction::Install,
suggest_reason: "Plan and reference events from your calendar",
@@ -71,8 +71,8 @@ fn build_tool_suggestion_elicitation_request_uses_expected_shape() {
}
#[test]
fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() {
let args = ToolSuggestArgs {
fn build_request_plugin_install_elicitation_request_for_plugin_omits_install_url() {
let args = RequestPluginInstallArgs {
tool_type: DiscoverableToolType::Plugin,
action_type: DiscoverableToolAction::Install,
tool_id: "sample@openai-curated".to_string(),
@@ -87,7 +87,7 @@ fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() {
app_connector_ids: vec!["connector_calendar".to_string()],
}));
let request = build_tool_suggestion_elicitation_request(
let request = build_request_plugin_install_elicitation_request(
"codex-apps",
"thread-1".to_string(),
"turn-1".to_string(),
@@ -103,9 +103,9 @@ fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() {
turn_id: Some("turn-1".to_string()),
server_name: "codex-apps".to_string(),
request: McpServerElicitationRequest::Form {
meta: Some(json!(ToolSuggestMeta {
codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE,
persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE,
meta: Some(json!(RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type: DiscoverableToolType::Plugin,
suggest_type: DiscoverableToolAction::Install,
suggest_reason: "Use the sample plugin's skills and MCP server",
@@ -126,8 +126,8 @@ fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() {
}
#[test]
fn build_tool_suggestion_meta_uses_expected_shape() {
let meta = build_tool_suggestion_meta(
fn build_request_plugin_install_meta_uses_expected_shape() {
let meta = build_request_plugin_install_meta(
DiscoverableToolType::Connector,
DiscoverableToolAction::Install,
"Find and reference emails from your inbox",
@@ -138,9 +138,9 @@ fn build_tool_suggestion_meta_uses_expected_shape() {
assert_eq!(
meta,
ToolSuggestMeta {
codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE,
persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE,
RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type: DiscoverableToolType::Connector,
suggest_type: DiscoverableToolAction::Install,
suggest_reason: "Find and reference emails from your inbox",
@@ -154,7 +154,7 @@ fn build_tool_suggestion_meta_uses_expected_shape() {
}
#[test]
fn verified_connector_suggestion_completed_requires_accessible_connector() {
fn verified_connector_install_completed_requires_accessible_connector() {
let accessible_connectors = vec![AppInfo {
id: "calendar".to_string(),
name: "Google Calendar".to_string(),
@@ -171,18 +171,18 @@ fn verified_connector_suggestion_completed_requires_accessible_connector() {
plugin_display_names: Vec::new(),
}];
assert!(verified_connector_suggestion_completed(
assert!(verified_connector_install_completed(
"calendar",
&accessible_connectors,
));
assert!(!verified_connector_suggestion_completed(
assert!(!verified_connector_install_completed(
"gmail",
&accessible_connectors,
));
}
#[test]
fn all_suggested_connectors_picked_up_requires_every_expected_connector() {
fn all_requested_connectors_picked_up_requires_every_expected_connector() {
let accessible_connectors = vec![AppInfo {
id: "calendar".to_string(),
name: "Google Calendar".to_string(),
@@ -199,11 +199,11 @@ fn all_suggested_connectors_picked_up_requires_every_expected_connector() {
plugin_display_names: Vec::new(),
}];
assert!(all_suggested_connectors_picked_up(
assert!(all_requested_connectors_picked_up(
&["calendar".to_string()],
&accessible_connectors,
));
assert!(!all_suggested_connectors_picked_up(
assert!(!all_requested_connectors_picked_up(
&["calendar".to_string(), "gmail".to_string()],
&accessible_connectors,
));
+16 -14
View File
@@ -15,7 +15,7 @@ use std::collections::BTreeMap;
const TUI_CLIENT_NAME: &str = "codex-tui";
pub const TOOL_SEARCH_TOOL_NAME: &str = "tool_search";
pub const TOOL_SEARCH_DEFAULT_LIMIT: usize = 8;
pub const TOOL_SUGGEST_TOOL_NAME: &str = "tool_suggest";
pub const REQUEST_PLUGIN_INSTALL_TOOL_NAME: &str = "request_plugin_install";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolSearchSourceInfo {
@@ -111,7 +111,7 @@ impl From<DiscoverablePluginInfo> for DiscoverableTool {
}
}
pub fn filter_tool_suggest_discoverable_tools_for_client(
pub fn filter_request_plugin_install_discoverable_tools_for_client(
discoverable_tools: Vec<DiscoverableTool>,
app_server_client_name: Option<&str>,
) -> Vec<DiscoverableTool> {
@@ -136,7 +136,7 @@ pub struct DiscoverablePluginInfo {
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolSuggestEntry {
pub struct RequestPluginInstallEntry {
pub id: String,
pub name: String,
pub description: Option<String>,
@@ -271,7 +271,9 @@ pub fn collect_tool_search_source_infos<'a>(
.collect()
}
pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> ToolSpec {
pub fn create_request_plugin_install_tool(
discoverable_tools: &[RequestPluginInstallEntry],
) -> ToolSpec {
let properties = BTreeMap::from([
(
"tool_type".to_string(),
@@ -291,7 +293,7 @@ pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> Tool
(
"suggest_reason".to_string(),
JsonSchema::string(Some(
"Concise one-line user-facing reason why this tool can help with the current request."
"Concise one-line user-facing reason why this plugin or connector can help with the current request."
.to_string(),
)),
),
@@ -299,11 +301,11 @@ pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> Tool
let discoverable_tools = format_discoverable_tools(discoverable_tools);
let description = format!(
"# Tool suggestion discovery\n\nUse this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.\n\nUse this ONLY when all of the following are true:\n- The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list.\n- `{TOOL_SEARCH_TOOL_NAME}` is not available, or it has already been called and did not find or make the requested tool callable.\n- The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list.\n\nDo not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful. The user's intent must clearly match one listed tool.\n\nKnown plugins/connectors available to install:\n{discoverable_tools}\n\nWorkflow:\n\n1. Check the current context and active `tools` list first. If `{TOOL_SEARCH_TOOL_NAME}` is available, call `{TOOL_SEARCH_TOOL_NAME}` before calling `{TOOL_SUGGEST_TOOL_NAME}`. Do not use tool suggestion if the needed tool is already available, found through `{TOOL_SEARCH_TOOL_NAME}`, or callable after discovery.\n2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.\n3. If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n4. If one tool clearly fits, call `{TOOL_SUGGEST_TOOL_NAME}` with:\n - `tool_type`: `connector` or `plugin`\n - `action_type`: `install`\n - `tool_id`: exact id from the known plugin/connector list above\n - `suggest_reason`: concise one-line user-facing reason this tool can help with the current request\n5. After the suggestion flow completes:\n - if the user finished the install flow, continue by searching again or using the newly available tool\n - if the user did not finish, continue without that tool, and don't suggest that tool again unless the user explicitly asks for it.\n\nIMPORTANT: DO NOT call this tool in parallel with other tools."
"# Request plugin/connector install\n\nUse this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.\n\nUse this ONLY when all of the following are true:\n- The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list.\n- `{TOOL_SEARCH_TOOL_NAME}` is not available, or it has already been called and did not find or make the requested tool callable.\n- The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list.\n\nDo not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful. Only use when the user explicitly asks to use that exact listed plugin or connector.\n\nKnown plugins/connectors available to install:\n{discoverable_tools}\n\nWorkflow:\n\n1. Check the current context and active `tools` list first. If current active tools aren't relevant and `{TOOL_SEARCH_TOOL_NAME}` is available, only call this tool after `{TOOL_SEARCH_TOOL_NAME}` has already been tried and found no relevant tool.\n2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.\n3. If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n4. If one plugin or connector clearly fits, call `{REQUEST_PLUGIN_INSTALL_TOOL_NAME}` with:\n - `tool_type`: `connector` or `plugin`\n - `action_type`: `install`\n - `tool_id`: exact id from the known plugin/connector list above\n - `suggest_reason`: concise one-line user-facing reason this plugin or connector can help with the current request\n5. After the request flow completes:\n - if the user finished the install flow, continue by searching again or using the newly available plugin or connector\n - if the user did not finish, continue without that plugin or connector, and don't request it again unless the user explicitly asks for it.\n\nIMPORTANT: DO NOT call this tool in parallel with other tools."
);
ToolSpec::Function(ResponsesApiTool {
name: TOOL_SUGGEST_TOOL_NAME.to_string(),
name: REQUEST_PLUGIN_INSTALL_TOOL_NAME.to_string(),
description,
strict: false,
defer_loading: None,
@@ -321,13 +323,13 @@ pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> Tool
})
}
pub fn collect_tool_suggest_entries(
pub fn collect_request_plugin_install_entries(
discoverable_tools: &[DiscoverableTool],
) -> Vec<ToolSuggestEntry> {
) -> Vec<RequestPluginInstallEntry> {
discoverable_tools
.iter()
.map(|tool| match tool {
DiscoverableTool::Connector(connector) => ToolSuggestEntry {
DiscoverableTool::Connector(connector) => RequestPluginInstallEntry {
id: connector.id.clone(),
name: connector.name.clone(),
description: connector.description.clone(),
@@ -336,7 +338,7 @@ pub fn collect_tool_suggest_entries(
mcp_server_names: Vec::new(),
app_connector_ids: Vec::new(),
},
DiscoverableTool::Plugin(plugin) => ToolSuggestEntry {
DiscoverableTool::Plugin(plugin) => RequestPluginInstallEntry {
id: plugin.id.clone(),
name: plugin.name.clone(),
description: plugin.description.clone(),
@@ -349,7 +351,7 @@ pub fn collect_tool_suggest_entries(
.collect()
}
fn format_discoverable_tools(discoverable_tools: &[ToolSuggestEntry]) -> String {
fn format_discoverable_tools(discoverable_tools: &[RequestPluginInstallEntry]) -> String {
let mut discoverable_tools = discoverable_tools.to_vec();
discoverable_tools.sort_by(|left, right| {
left.name
@@ -373,7 +375,7 @@ fn format_discoverable_tools(discoverable_tools: &[ToolSuggestEntry]) -> String
.join("\n")
}
fn tool_description_or_fallback(tool: &ToolSuggestEntry) -> String {
fn tool_description_or_fallback(tool: &RequestPluginInstallEntry) -> String {
if let Some(description) = tool
.description
.as_deref()
@@ -389,7 +391,7 @@ fn tool_description_or_fallback(tool: &ToolSuggestEntry) -> String {
}
}
fn plugin_summary(tool: &ToolSuggestEntry) -> String {
fn plugin_summary(tool: &RequestPluginInstallEntry) -> String {
let mut details = Vec::new();
if tool.has_skills {
details.push("skills".to_string());
+22 -19
View File
@@ -49,36 +49,36 @@ fn create_tool_search_tool_deduplicates_and_renders_enabled_sources() {
}
#[test]
fn create_tool_suggest_tool_uses_plugin_summary_fallback() {
fn create_request_plugin_install_tool_uses_plugin_summary_fallback() {
let expected_description = concat!(
"# Tool suggestion discovery\n\n",
"# Request plugin/connector install\n\n",
"Use this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.\n\n",
"Use this ONLY when all of the following are true:\n",
"- The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list.\n",
"- The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list.\n",
"- `tool_search` is not available, or it has already been called and did not find or make the requested tool callable.\n",
"- The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list.\n\n",
"Do not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful. The user's intent must clearly match one listed tool.\n\n",
"- The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list.\n\n",
"Do not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful. Only use when the user explicitly asks to use that exact listed plugin or connector.\n\n",
"Known plugins/connectors available to install:\n",
"- GitHub (id: `github`, type: plugin, action: install): skills; MCP servers: github-mcp; app connectors: github-app\n",
"- Slack (id: `slack@openai-curated`, type: connector, action: install): No description provided.\n\n",
"Workflow:\n\n",
"1. Check the current context and active `tools` list first. If `tool_search` is available, call `tool_search` before calling `tool_suggest`. Do not use tool suggestion if the needed tool is already available, found through `tool_search`, or callable after discovery.\n",
"1. Check the current context and active `tools` list first. If current active tools aren't relevant and `tool_search` is available, only call this tool after `tool_search` has already been tried and found no relevant tool.\n",
"2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.\n",
"3. If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n",
"4. If one tool clearly fits, call `tool_suggest` with:\n",
"3. If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n",
"4. If one plugin or connector clearly fits, call `request_plugin_install` with:\n",
" - `tool_type`: `connector` or `plugin`\n",
" - `action_type`: `install`\n",
" - `tool_id`: exact id from the known plugin/connector list above\n",
" - `suggest_reason`: concise one-line user-facing reason this tool can help with the current request\n",
"5. After the suggestion flow completes:\n",
" - if the user finished the install flow, continue by searching again or using the newly available tool\n",
" - if the user did not finish, continue without that tool, and don't suggest that tool again unless the user explicitly asks for it.\n\n",
" - `suggest_reason`: concise one-line user-facing reason this plugin or connector can help with the current request\n",
"5. After the request flow completes:\n",
" - if the user finished the install flow, continue by searching again or using the newly available plugin or connector\n",
" - if the user did not finish, continue without that plugin or connector, and don't request it again unless the user explicitly asks for it.\n\n",
"IMPORTANT: DO NOT call this tool in parallel with other tools.",
);
assert_eq!(
create_tool_suggest_tool(&[
ToolSuggestEntry {
create_request_plugin_install_tool(&[
RequestPluginInstallEntry {
id: "slack@openai-curated".to_string(),
name: "Slack".to_string(),
description: None,
@@ -87,7 +87,7 @@ fn create_tool_suggest_tool_uses_plugin_summary_fallback() {
mcp_server_names: Vec::new(),
app_connector_ids: Vec::new(),
},
ToolSuggestEntry {
RequestPluginInstallEntry {
id: "github".to_string(),
name: "GitHub".to_string(),
description: None,
@@ -98,7 +98,7 @@ fn create_tool_suggest_tool_uses_plugin_summary_fallback() {
},
]),
ToolSpec::Function(ResponsesApiTool {
name: "tool_suggest".to_string(),
name: "request_plugin_install".to_string(),
description: expected_description.to_string(),
strict: false,
defer_loading: None,
@@ -113,7 +113,7 @@ fn create_tool_suggest_tool_uses_plugin_summary_fallback() {
(
"suggest_reason".to_string(),
JsonSchema::string(Some(
"Concise one-line user-facing reason why this tool can help with the current request."
"Concise one-line user-facing reason why this plugin or connector can help with the current request."
.to_string(),
),),
),
@@ -157,7 +157,7 @@ fn discoverable_tool_enums_use_expected_wire_names() {
}
#[test]
fn filter_tool_suggest_discoverable_tools_for_codex_tui_omits_plugins() {
fn filter_request_plugin_install_discoverable_tools_for_codex_tui_omits_plugins() {
let discoverable_tools = vec![
DiscoverableTool::Connector(Box::new(AppInfo {
id: "connector_google_calendar".to_string(),
@@ -185,7 +185,10 @@ fn filter_tool_suggest_discoverable_tools_for_codex_tui_omits_plugins() {
];
assert_eq!(
filter_tool_suggest_discoverable_tools_for_client(discoverable_tools, Some("codex-tui"),),
filter_request_plugin_install_discoverable_tools_for_client(
discoverable_tools,
Some("codex-tui"),
),
vec![DiscoverableTool::Connector(Box::new(AppInfo {
id: "connector_google_calendar".to_string(),
name: "Google Calendar".to_string(),
+10 -5
View File
@@ -1,4 +1,5 @@
use crate::CommandToolOptions;
use crate::REQUEST_PLUGIN_INSTALL_TOOL_NAME;
use crate::REQUEST_USER_INPUT_TOOL_NAME;
use crate::ResponsesApiNamespace;
use crate::ResponsesApiNamespaceTool;
@@ -6,7 +7,6 @@ use crate::ShellToolOptions;
use crate::SpawnAgentToolOptions;
use crate::TOOL_SEARCH_DEFAULT_LIMIT;
use crate::TOOL_SEARCH_TOOL_NAME;
use crate::TOOL_SUGGEST_TOOL_NAME;
use crate::ToolHandlerKind;
use crate::ToolName;
use crate::ToolRegistryPlan;
@@ -19,8 +19,8 @@ use crate::ViewImageToolOptions;
use crate::WebSearchToolOptions;
use crate::coalesce_loadable_tool_specs;
use crate::collect_code_mode_exec_prompt_tool_definitions;
use crate::collect_request_plugin_install_entries;
use crate::collect_tool_search_source_infos;
use crate::collect_tool_suggest_entries;
use crate::create_apply_patch_freeform_tool;
use crate::create_apply_patch_json_tool;
use crate::create_close_agent_tool_v1;
@@ -39,6 +39,7 @@ use crate::create_local_shell_tool;
use crate::create_read_mcp_resource_tool;
use crate::create_report_agent_job_result_tool;
use crate::create_request_permissions_tool;
use crate::create_request_plugin_install_tool;
use crate::create_request_user_input_tool;
use crate::create_resume_agent_tool;
use crate::create_send_input_tool_v1;
@@ -50,7 +51,6 @@ use crate::create_spawn_agent_tool_v2;
use crate::create_spawn_agents_on_csv_tool;
use crate::create_test_sync_tool;
use crate::create_tool_search_tool;
use crate::create_tool_suggest_tool;
use crate::create_update_goal_tool;
use crate::create_update_plan_tool;
use crate::create_view_image_tool;
@@ -312,11 +312,16 @@ pub fn build_tool_registry_plan(
params.discoverable_tools.filter(|tools| !tools.is_empty())
{
plan.push_spec(
create_tool_suggest_tool(&collect_tool_suggest_entries(discoverable_tools)),
create_request_plugin_install_tool(&collect_request_plugin_install_entries(
discoverable_tools,
)),
/*supports_parallel_tool_calls*/ true,
/*code_mode_enabled*/ false,
);
plan.register_handler(TOOL_SUGGEST_TOOL_NAME, ToolHandlerKind::ToolSuggest);
plan.register_handler(
REQUEST_PLUGIN_INSTALL_TOOL_NAME,
ToolHandlerKind::RequestPluginInstall,
);
}
if config.has_environment
+18 -20
View File
@@ -1692,7 +1692,7 @@ fn search_tool_keeps_plain_deferred_dynamic_tools_when_namespace_tools_are_disab
}
#[test]
fn tool_suggest_is_not_registered_without_feature_flag() {
fn request_plugin_install_is_not_registered_without_feature_flag() {
let model_info = search_capable_model_info();
let mut features = Features::with_defaults();
features.enable(Feature::ToolSearch);
@@ -1725,12 +1725,12 @@ fn tool_suggest_is_not_registered_without_feature_flag() {
assert!(
!tools
.iter()
.any(|tool| tool.name() == TOOL_SUGGEST_TOOL_NAME)
.any(|tool| tool.name() == REQUEST_PLUGIN_INSTALL_TOOL_NAME)
);
}
#[test]
fn tool_suggest_can_be_registered_without_search_tool() {
fn request_plugin_install_can_be_registered_without_search_tool() {
let model_info = ModelInfo {
supports_search_tool: false,
..search_capable_model_info()
@@ -1762,12 +1762,13 @@ fn tool_suggest_can_be_registered_without_search_tool() {
&[],
);
assert_contains_tool_names(&tools, &[TOOL_SUGGEST_TOOL_NAME]);
let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME);
assert!(tool_suggest.supports_parallel_tool_calls);
assert_contains_tool_names(&tools, &[REQUEST_PLUGIN_INSTALL_TOOL_NAME]);
let request_plugin_install = find_tool(&tools, REQUEST_PLUGIN_INSTALL_TOOL_NAME);
assert!(request_plugin_install.supports_parallel_tool_calls);
assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME);
let ToolSpec::Function(ResponsesApiTool { description, .. }) = &tool_suggest.spec else {
let ToolSpec::Function(ResponsesApiTool { description, .. }) = &request_plugin_install.spec
else {
panic!("expected function tool");
};
assert!(description.contains(
@@ -1779,7 +1780,7 @@ fn tool_suggest_can_be_registered_without_search_tool() {
}
#[test]
fn tool_suggest_description_lists_discoverable_tools() {
fn request_plugin_install_description_lists_discoverable_tools() {
let model_info = search_capable_model_info();
let mut features = Features::with_defaults();
features.enable(Feature::Apps);
@@ -1827,16 +1828,16 @@ fn tool_suggest_description_lists_discoverable_tools() {
&[],
);
assert!(handlers.contains(&ToolHandlerSpec {
name: ToolName::plain(TOOL_SUGGEST_TOOL_NAME),
kind: ToolHandlerKind::ToolSuggest,
name: ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME),
kind: ToolHandlerKind::RequestPluginInstall,
}));
let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME);
let request_plugin_install = find_tool(&tools, REQUEST_PLUGIN_INSTALL_TOOL_NAME);
let ToolSpec::Function(ResponsesApiTool {
description,
parameters,
..
}) = &tool_suggest.spec
}) = &request_plugin_install.spec
else {
panic!("expected function tool");
};
@@ -1855,30 +1856,27 @@ fn tool_suggest_description_lists_discoverable_tools() {
);
assert!(
description.contains(
"The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list."
"The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list."
)
);
assert!(description.contains(
"`tool_search` is not available, or it has already been called and did not find or make the requested tool callable."
));
assert!(description.contains(
"The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list."
"The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list."
));
assert!(description.contains(
"Do not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful."
"Do not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful."
));
assert!(description.contains("IMPORTANT: DO NOT call this tool in parallel with other tools."));
assert!(description.contains(
"Do not use tool suggestion if the needed tool is already available, found through `tool_search`, or callable after discovery."
));
assert!(description.contains(
"If `tool_search` is available, call `tool_search` before calling `tool_suggest`."
"If current active tools aren't relevant and `tool_search` is available, only call this tool after `tool_search` has already been tried and found no relevant tool."
));
assert!(!description.contains("targeted lookup"));
assert!(!description.contains("broad or speculative searches"));
assert!(description.contains("Only proceed when one listed plugin or connector exactly fits."));
assert!(description.contains(
"If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not."
"If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not."
));
assert!(!description.contains("{{discoverable_tools}}"));
assert!(!description.contains("tool_search fails to find a good match"));
@@ -35,7 +35,7 @@ pub enum ToolHandlerKind {
SpawnAgentV2,
TestSync,
ToolSearch,
ToolSuggest,
RequestPluginInstall,
UnifiedExec,
ViewImage,
WaitAgentV1,