mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Allow async user messages through code mode (#63730)
## Why Agents could send async user messages only through a top-level tool call, even in code mode. ## What changed Set `features.send_message_to_user_async.direct_only` to `false` to make the tool follow the session's tool mode. Direct mode exposes it as a top-level tool, code mode allows both top-level and nested calls, and code-mode-only sessions require nested calls and reject direct calls. The default keeps the tool top-level only. Existing agent opt-ins still apply. ## Testing Add integration coverage for tool visibility, call results, and message delivery across all three tool modes with both values of `direct_only`. Improve failure diagnostics in the multiline shell snapshot test and paste `/status` as a single input event in the daemon compatibility test. GitOrigin-RevId: c69bb2fba8bf776eff01382d8869fc869fc9d479
This commit is contained in:
@@ -5070,8 +5070,12 @@
|
||||
},
|
||||
"SendMessageToUserAsyncConfigToml": {
|
||||
"additionalProperties": false,
|
||||
"description": "Controls which agents can send async user messages.",
|
||||
"description": "Controls which agents can send async user messages and how they call the tool.",
|
||||
"properties": {
|
||||
"direct_only": {
|
||||
"description": "Keep async user messages top-level only (default). Set to false to follow the session's tool mode.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"root_agent": {
|
||||
"description": "Sets the root agent's feature flag, just like the plain boolean shorthand. The model catalog can still enable the tool for the root when this is false.",
|
||||
"type": "boolean"
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::tools::registry::ToolExposure;
|
||||
use crate::tools::registry::ToolRegistry;
|
||||
#[cfg(test)]
|
||||
use crate::tools::spec_plan::finalize_tool_router;
|
||||
use crate::tools::spec_plan::is_hidden_by_code_mode_only;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::TOOL_REGISTRATIONS_METRIC;
|
||||
use codex_otel::TOOL_REGISTRATIONS_METRIC_BUCKETS;
|
||||
@@ -426,6 +427,25 @@ impl ToolRouter {
|
||||
..
|
||||
} = call;
|
||||
|
||||
// Only async messages require this dispatch restriction; other tools'
|
||||
// exposure remains advertisement policy.
|
||||
if tool_name.is_default_namespace()
|
||||
&& tool_name.name == "send_message_to_user_async"
|
||||
&& !matches!(source, ToolCallSource::CodeMode { .. })
|
||||
&& self
|
||||
.registry
|
||||
.registered_tool(&tool_name)
|
||||
.is_some_and(|tool| {
|
||||
tool.is_trusted
|
||||
&& is_hidden_by_code_mode_only(self.tool_mode, &tool_name, tool.exposure)
|
||||
})
|
||||
{
|
||||
let tool_name = codex_tools::code_mode_name_for_tool_name(&tool_name);
|
||||
return Err(FunctionCallError::RespondToModel(format!(
|
||||
"{tool_name} requires code mode"
|
||||
)));
|
||||
}
|
||||
|
||||
// Keep the legacy ToolInvocation.turn field tied to the same request state until handlers migrate.
|
||||
let turn = Arc::clone(&step_context.turn);
|
||||
let invocation = ToolInvocation {
|
||||
|
||||
@@ -852,13 +852,11 @@ fn agent_type_description(
|
||||
}
|
||||
}
|
||||
|
||||
fn is_hidden_by_code_mode_only(
|
||||
turn_context: &TurnContext,
|
||||
model_info: &ModelInfo,
|
||||
pub(super) fn is_hidden_by_code_mode_only(
|
||||
tool_mode: ToolMode,
|
||||
tool_name: &ToolName,
|
||||
exposure: ToolExposure,
|
||||
) -> bool {
|
||||
let tool_mode = effective_tool_mode(turn_context, model_info);
|
||||
tool_mode == ToolMode::CodeModeOnly
|
||||
&& exposure.is_available_in_code_mode()
|
||||
&& codex_code_mode::is_code_mode_nested_tool(&codex_tools::code_mode_name_for_tool_name(
|
||||
@@ -873,8 +871,7 @@ fn is_directly_visible(
|
||||
) -> bool {
|
||||
tool.exposure.is_direct()
|
||||
&& !is_hidden_by_code_mode_only(
|
||||
turn_context,
|
||||
model_info,
|
||||
effective_tool_mode(turn_context, model_info),
|
||||
&tool.runtime.tool_name(),
|
||||
tool.exposure,
|
||||
)
|
||||
@@ -1322,7 +1319,12 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, registry: &mut Tool
|
||||
let subagent_messages = features.subagent_async_messages_enabled
|
||||
&& turn_context.session_source.parent_thread_id().is_some();
|
||||
if root_messages || subagent_messages {
|
||||
registry.add_with_exposure(SendMessageToUserAsyncHandler, ToolExposure::DirectModelOnly);
|
||||
let exposure = if features.async_messages_in_code_mode {
|
||||
ToolExposure::Direct
|
||||
} else {
|
||||
ToolExposure::DirectModelOnly
|
||||
};
|
||||
registry.add_with_exposure(SendMessageToUserAsyncHandler, exposure);
|
||||
}
|
||||
|
||||
if features.enabled(Feature::RequestPermissionsTool) {
|
||||
|
||||
@@ -20,6 +20,7 @@ use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_custom_tool_call;
|
||||
use core_test_support::responses::ev_function_call_with_namespace;
|
||||
use core_test_support::responses::ev_response_created;
|
||||
use core_test_support::responses::mount_sse_once;
|
||||
@@ -294,6 +295,110 @@ async fn freeform_async_message_respects_independent_agent_opt_ins(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case::test_matrix([ToolMode::Direct, ToolMode::CodeMode, ToolMode::CodeModeOnly], [true, false])]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn freeform_async_message_follows_tool_mode(mode: ToolMode, direct_only: bool) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
const TOOL: &str = "send_message_to_user_async";
|
||||
const ACCEPTED: &str = r#"{"accepted":true}"#;
|
||||
let server = start_mock_server().await;
|
||||
let test = test_codex()
|
||||
.with_model_info_override("gpt-5.2", move |model| {
|
||||
model.tool_mode = Some(mode);
|
||||
model.experimental_supported_tools = vec!["test_sync_tool".to_string()];
|
||||
})
|
||||
.with_pre_build_hook(move |home| {
|
||||
let config = format!("{EXPLICIT_ROOT_MESSAGES}\ndirect_only = {direct_only}");
|
||||
std::fs::write(home.join("config.toml"), config).expect("write config");
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
// Attempt the direct send even when it is absent from the model's tool list.
|
||||
let args = r#"{"message":"direct"}"#;
|
||||
let mut calls = vec![
|
||||
ev_function_call_with_namespace("direct", "functions", TOOL, args),
|
||||
// Other tools remain callable directly even when CodeModeOnly hides them.
|
||||
ev_function_call_with_namespace("other", "functions", "test_sync_tool", "{}"),
|
||||
];
|
||||
if mode != ToolMode::Direct {
|
||||
let js =
|
||||
"text(await tools.send_message_to_user_async?.({message: 'nested'}) ?? 'unavailable')";
|
||||
calls.push(ev_custom_tool_call("nested", "exec", js));
|
||||
}
|
||||
calls.push(ev_completed("resp-1"));
|
||||
let done = sse(vec![ev_completed("resp-2")]);
|
||||
let responses = mount_sse_sequence(&server, vec![sse(calls), done]).await;
|
||||
test.codex
|
||||
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: "Report progress.".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await?;
|
||||
let mut started = Vec::new();
|
||||
let mut completed = Vec::new();
|
||||
wait_for_event(&test.codex, |event| {
|
||||
match event {
|
||||
EventMsg::ItemStarted(event) => {
|
||||
if let TurnItem::AgentMessage(message) = &event.item {
|
||||
started.push(message.clone());
|
||||
}
|
||||
}
|
||||
EventMsg::ItemCompleted(event) => {
|
||||
if let TurnItem::AgentMessage(message) = &event.item {
|
||||
completed.push(message.clone());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
matches!(event, EventMsg::TurnComplete(_))
|
||||
})
|
||||
.await;
|
||||
|
||||
let requests = responses.requests();
|
||||
let body = requests[0].body_json();
|
||||
let tools = body["tools"].as_array().expect("request tools");
|
||||
let direct = direct_only || mode != ToolMode::CodeModeOnly;
|
||||
assert_eq!(tools.iter().any(|tool| tool["name"] == TOOL), direct);
|
||||
let expected = if direct {
|
||||
ACCEPTED
|
||||
} else {
|
||||
"send_message_to_user_async requires code mode"
|
||||
};
|
||||
assert_eq!(
|
||||
requests[1].function_call_output("direct")["output"],
|
||||
expected
|
||||
);
|
||||
assert_eq!(requests[1].function_call_output("other")["output"], "ok");
|
||||
if mode != ToolMode::Direct {
|
||||
let nested = requests[1].custom_tool_call_output("nested");
|
||||
let expected = if direct_only { "unavailable" } else { ACCEPTED };
|
||||
assert_eq!(nested["output"][1]["text"], expected, "{nested}");
|
||||
}
|
||||
started.sort_by(|left, right| left.id.cmp(&right.id));
|
||||
completed.sort_by(|left, right| left.id.cmp(&right.id));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&started)?,
|
||||
serde_json::to_value(&completed)?,
|
||||
);
|
||||
let expected_messages = [
|
||||
direct.then_some("direct"),
|
||||
(mode != ToolMode::Direct && !direct_only).then_some("nested"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect::<Vec<_>>();
|
||||
let mut actual_messages = completed
|
||||
.iter()
|
||||
.map(|message| match message.content.as_slice() {
|
||||
[AgentMessageContent::Text { text }] => text.as_str(),
|
||||
content => panic!("unexpected message content: {content:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
actual_messages.sort_unstable();
|
||||
assert_eq!(actual_messages, expected_messages);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(Some("send_message_to_user_async"), &[]; "catalog_opt_in")]
|
||||
#[test_case(None, &[Feature::SendMessageToUserAsync]; "feature_opt_in")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
@@ -34,7 +34,7 @@ pub struct ToolRegistryConfigToml {
|
||||
pub turn_metadata_includes_tool_info: Option<bool>,
|
||||
}
|
||||
|
||||
/// Controls which agents can send async user messages.
|
||||
/// Controls which agents can send async user messages and how they call the tool.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SendMessageToUserAsyncConfigToml {
|
||||
@@ -46,6 +46,9 @@ pub struct SendMessageToUserAsyncConfigToml {
|
||||
/// and the model catalog. Defaults to false.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub subagents: Option<bool>,
|
||||
/// Keep async user messages top-level only (default). Set to false to follow the session's tool mode.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub direct_only: Option<bool>,
|
||||
}
|
||||
|
||||
impl FeatureConfig for SendMessageToUserAsyncConfigToml {
|
||||
|
||||
@@ -643,6 +643,7 @@ pub struct Features {
|
||||
legacy_usages: BTreeSet<LegacyFeatureUsage>,
|
||||
/// Spawned agents require their own opt-in, independent of the root feature flag.
|
||||
pub subagent_async_messages_enabled: bool,
|
||||
pub async_messages_in_code_mode: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -1058,10 +1059,13 @@ pub struct FeaturesToml {
|
||||
|
||||
impl Features {
|
||||
fn apply_toml(&mut self, features: &FeaturesToml) {
|
||||
if let Some(FeatureToml::Config(config)) = &features.send_message_to_user_async
|
||||
&& let Some(subagents) = config.subagents
|
||||
{
|
||||
self.subagent_async_messages_enabled = subagents;
|
||||
if let Some(FeatureToml::Config(config)) = &features.send_message_to_user_async {
|
||||
if let Some(subagents) = config.subagents {
|
||||
self.subagent_async_messages_enabled = subagents;
|
||||
}
|
||||
if let Some(direct_only) = config.direct_only {
|
||||
self.async_messages_in_code_mode = !direct_only;
|
||||
}
|
||||
}
|
||||
let entries = features.entries();
|
||||
self.apply_map(&entries);
|
||||
|
||||
@@ -538,7 +538,8 @@ fn brokered_snapshots_filter_complete_multiline_exports() -> Result<()> {
|
||||
allowed_brokered_keys: &[],
|
||||
},
|
||||
|_| true,
|
||||
);
|
||||
)
|
||||
.with_context(|| format!("{shell}: snapshot rejected multiline export {value:?}"))?;
|
||||
let path = dir.path().join("snapshot.sh");
|
||||
std::fs::write(&path, snapshot)?;
|
||||
let replayed = Command::new(shell)
|
||||
@@ -560,7 +561,8 @@ fn brokered_snapshots_filter_complete_multiline_exports() -> Result<()> {
|
||||
assert_eq!(
|
||||
replayed.stdout,
|
||||
format!("{value}\0unset\0kept\0original name\0original value\0original escaped{function_value}{exported_setting}").as_bytes(),
|
||||
"{shell}"
|
||||
"{shell}: replay stderr: {}",
|
||||
String::from_utf8_lossy(&replayed.stderr)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,8 +131,9 @@ async fn incompatible_daemon_can_run_embedded_for_explicit_features() -> Result<
|
||||
.context("missing warning line")?;
|
||||
insta::assert_snapshot!(snapshot, warning);
|
||||
terminal.write_input(b"\x14")?;
|
||||
terminal.write_input(b"/status")?;
|
||||
terminal.wait_for_screen("show current session configuration")?;
|
||||
// Submit the command as one paste event, not a partially buffered key burst.
|
||||
terminal.write_input(b"\x1b[200~/status\x1b[201~")?;
|
||||
terminal.wait_for_screen("/status")?;
|
||||
terminal.write_input(b"\r")?;
|
||||
terminal.wait_for_screen("Model:")?;
|
||||
ensure!(!terminal.screen_contains("unix://"));
|
||||
|
||||
Reference in New Issue
Block a user