mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Deduplicate MCP text fallbacks in Code Mode output (#63540)
## Why MCP tools can return structured data alongside a JSON text fallback for clients that need it. Printing the whole result in Code Mode can show the same data twice. ## What changed Enable `features.code_mode_mcp_result_dedup` to let `text()` omit `content` when it prints an original, successful MCP result whose only content block is a plain text fallback that parses to the same JSON as `structuredContent`. The JavaScript result retains both fields. Carry the result format through gRPC so the host can distinguish MCP results from ordinary JSON. The feature is off by default. ## Testing Add coverage for both feature flag settings, for printing original MCP results and copies through gRPC, and for comparing equivalent JSON. GitOrigin-RevId: a8b0b42f5375d9744c235a0e663090dd5982e37e
This commit is contained in:
Generated
+2
@@ -2923,7 +2923,9 @@ dependencies = [
|
||||
"futures",
|
||||
"opentelemetry",
|
||||
"pretty_assertions",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_with",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeSessionCellExecutionLimits;
|
||||
use codex_code_mode_protocol::CodeModeToolKind;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::ExecuteRequest;
|
||||
use codex_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_protocol::ImageDetail;
|
||||
@@ -89,6 +90,17 @@ fn tool_definition(definition: proto::ToolDefinition) -> Result<ToolDefinition,
|
||||
})
|
||||
}
|
||||
|
||||
/// Prost defaults missing or unrecognized formats to plain JSON.
|
||||
pub(super) fn tool_result(result: &proto::ToolCallSucceeded) -> Result<CodeModeToolResult, Status> {
|
||||
let value = serde_json::from_slice(&result.output_json).map_err(|error| {
|
||||
Status::invalid_argument(format!("invalid code-mode tool output JSON: {error}"))
|
||||
})?;
|
||||
Ok(match result.result_format() {
|
||||
proto::ToolResultFormat::Json => CodeModeToolResult::Json(value),
|
||||
proto::ToolResultFormat::McpCallToolResult => CodeModeToolResult::McpCallToolResult(value),
|
||||
})
|
||||
}
|
||||
|
||||
fn json_field(value: Option<Vec<u8>>, field: &str) -> Result<Option<JsonValue>, Status> {
|
||||
value
|
||||
.map(|value| {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_protocol::ImageDetail;
|
||||
use codex_code_mode_protocol::MissingCodeModeHostDuration;
|
||||
@@ -12,8 +13,24 @@ use tonic::Code;
|
||||
|
||||
use super::execute_request;
|
||||
use super::execution_outcome;
|
||||
use super::tool_result;
|
||||
use super::wait_response;
|
||||
|
||||
#[test]
|
||||
fn missing_and_unknown_tool_result_formats_preserve_plain_json() {
|
||||
let value = serde_json::json!({"content": [], "structuredContent": {}});
|
||||
for result_format in [0, i32::MAX] {
|
||||
let reply = proto::ToolCallSucceeded {
|
||||
output_json: serde_json::to_vec(&value).unwrap(),
|
||||
result_format,
|
||||
};
|
||||
assert_eq!(
|
||||
tool_result(&reply).unwrap(),
|
||||
CodeModeToolResult::Json(value.clone())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_names_unknown_tool_kinds_and_invalid_json_schemas() {
|
||||
let definition = proto::ToolDefinition {
|
||||
|
||||
@@ -193,11 +193,9 @@ impl GrpcCodeModeHost {
|
||||
let session = self.state.session(&request.session_id)?;
|
||||
let invocation_id = validation::uuid(&request.invocation_id, "tool invocation ID")?;
|
||||
let result = match request.outcome {
|
||||
Some(proto::complete_tool_call_request::Outcome::Succeeded(result)) => Ok(
|
||||
serde_json::from_slice(&result.output_json).map_err(|error| {
|
||||
Status::invalid_argument(format!("invalid code-mode tool output JSON: {error}"))
|
||||
})?,
|
||||
),
|
||||
Some(proto::complete_tool_call_request::Outcome::Succeeded(result)) => {
|
||||
Ok(conversions::tool_result(&result)?)
|
||||
}
|
||||
Some(proto::complete_tool_call_request::Outcome::Failed(error)) => Err(error.message),
|
||||
None => {
|
||||
return Err(Status::invalid_argument(
|
||||
|
||||
@@ -72,6 +72,7 @@ async fn rejects_oversized_identifiers_and_subscription_filters() {
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: b"null".to_vec(),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
}))
|
||||
|
||||
@@ -2,13 +2,13 @@ use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use codex_protocol::ToolName;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use prost::Message;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
@@ -92,7 +92,7 @@ impl GrpcSession {
|
||||
execution_id: String,
|
||||
invocation_id: Uuid,
|
||||
input_json: Option<Vec<u8>>,
|
||||
response: oneshot::Sender<Result<JsonValue, String>>,
|
||||
response: oneshot::Sender<Result<CodeModeToolResult, String>>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), String> {
|
||||
let cell_id = invocation.cell_id.to_string();
|
||||
@@ -215,7 +215,7 @@ impl GrpcSession {
|
||||
pub(super) fn complete_invocation(
|
||||
&self,
|
||||
invocation_id: Uuid,
|
||||
result: Result<JsonValue, String>,
|
||||
result: Result<CodeModeToolResult, String>,
|
||||
) -> Result<(), Status> {
|
||||
let response = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
|
||||
@@ -361,6 +361,7 @@ async fn filtered_subscriptions_match_default_namespace_aliases() {
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: br#""done""#.to_vec(),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
}))
|
||||
@@ -434,6 +435,7 @@ async fn filtered_subscriptions_receive_ordered_calls_and_unary_completions() {
|
||||
outcome: Some(proto::complete_tool_call_request::Outcome::Succeeded(
|
||||
proto::ToolCallSucceeded {
|
||||
output_json: format!(r#""result-{sequence}""#).into_bytes(),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
}))
|
||||
|
||||
@@ -13,13 +13,13 @@ use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeSession;
|
||||
use codex_code_mode_protocol::CodeModeSessionOptions;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::TerminateRequest;
|
||||
use codex_code_mode_protocol::WaitOutcome;
|
||||
use codex_code_mode_protocol::grpc as proto;
|
||||
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
|
||||
use codex_code_mode_runtime::InProcessCodeModeSession;
|
||||
use codex_code_mode_runtime::ToolPreload;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -91,7 +91,7 @@ pub(super) struct ToolSubscription {
|
||||
|
||||
pub(super) struct PendingInvocation {
|
||||
pub(super) subscription_id: Uuid,
|
||||
pub(super) response: oneshot::Sender<Result<JsonValue, String>>,
|
||||
pub(super) response: oneshot::Sender<Result<CodeModeToolResult, String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -7,6 +7,7 @@ use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
@@ -42,7 +43,7 @@ impl CodeModeSessionDelegate for BlockingDelegate {
|
||||
tokio::select! {
|
||||
permit = self.release.acquire() => {
|
||||
permit.map_err(|error| error.to_string())?.forget();
|
||||
Ok(json!("done"))
|
||||
Ok(CodeModeToolResult::from(json!("done")))
|
||||
}
|
||||
_ = cancellation.cancelled() => Err("cancelled".to_string()),
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
use std::time::Duration;
|
||||
@@ -12,6 +13,7 @@ use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionOptions;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
@@ -215,6 +217,103 @@ async fn grpc_endpoints_reject_credentials_without_disclosing_them() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn text_omits_duplicate_fallback_only_for_the_original_mcp_result() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let session = GrpcCodeModeSessionProvider::new(host.endpoint)
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let fallback = r#"{ "rows": [ { "z": "ok", "a": 1.0 } ] }"#;
|
||||
let raw = json!({
|
||||
"content": [{"type": "text", "text": fallback}],
|
||||
"structuredContent": {"rows": [{"a": 1, "z": "ok"}]},
|
||||
"isError": false,
|
||||
});
|
||||
let mut req = request(
|
||||
r#"
|
||||
const [mcp, plain] = await Promise.all([
|
||||
tools.lookup({ format: "mcp" }),
|
||||
tools.lookup({ format: "json" }),
|
||||
]);
|
||||
text(mcp);
|
||||
text(mcp);
|
||||
text(JSON.stringify(mcp));
|
||||
text({ ...mcp });
|
||||
text(plain);
|
||||
store("saved", mcp);
|
||||
text(load("saved"));
|
||||
await tools.lookup(mcp);
|
||||
content(mcp.content);
|
||||
mcp.structuredContent = { edited: true };
|
||||
text(mcp);
|
||||
mcp.toJSON = function () { delete this.toJSON; return plain; };
|
||||
text(mcp);
|
||||
let reads = 0;
|
||||
Object.setPrototypeOf(mcp, {
|
||||
get toJSON() {
|
||||
reads++;
|
||||
return () => plain;
|
||||
},
|
||||
});
|
||||
text(mcp);
|
||||
text(reads);
|
||||
"#,
|
||||
);
|
||||
req.enabled_tools = vec![tool("lookup")];
|
||||
let delegate = Arc::new(RecordingDelegate {
|
||||
results_by_input: HashMap::from([
|
||||
(
|
||||
json!({"format": "mcp"}),
|
||||
CodeModeToolResult::McpCallToolResult(raw.clone()),
|
||||
),
|
||||
(
|
||||
json!({"format": "json"}),
|
||||
CodeModeToolResult::Json(raw.clone()),
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
});
|
||||
let response = execute(&session, req, delegate.clone()).await?;
|
||||
let RuntimeResponse::Result {
|
||||
content_items,
|
||||
error_text: None,
|
||||
..
|
||||
} = response
|
||||
else {
|
||||
panic!("unexpected response {response:?}");
|
||||
};
|
||||
let reduced = json!({"structuredContent": raw["structuredContent"], "isError": false});
|
||||
let mut edited = raw.clone();
|
||||
edited["structuredContent"] = json!({"edited": true});
|
||||
let expected = [
|
||||
reduced.to_string(),
|
||||
reduced.to_string(),
|
||||
raw.to_string(),
|
||||
raw.to_string(),
|
||||
raw.to_string(),
|
||||
raw.to_string(),
|
||||
fallback.to_string(),
|
||||
edited.to_string(),
|
||||
raw.to_string(),
|
||||
raw.to_string(),
|
||||
"1".to_string(),
|
||||
]
|
||||
.map(|text| FunctionCallOutputContentItem::InputText { text });
|
||||
assert_eq!(content_items, expected);
|
||||
assert_eq!(
|
||||
delegate
|
||||
.invocations
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.last()
|
||||
.and_then(|call| call.input.as_ref()),
|
||||
Some(&raw)
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_session_persists_values_and_forwards_tools_notifications_and_closure() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
|
||||
@@ -8,6 +8,7 @@ use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
@@ -40,7 +41,7 @@ impl CodeModeSessionDelegate for SlowDelegate {
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
tokio::select! {
|
||||
_ = self.release.notified() => Ok(json!("slow")),
|
||||
_ = self.release.notified() => Ok(CodeModeToolResult::from(json!("slow"))),
|
||||
_ = cancellation.cancelled() => Err("cancelled".to_string()),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -16,6 +16,7 @@ use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionOptions;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
@@ -60,7 +61,7 @@ impl CodeModeSessionDelegate for OversizedResultDelegate {
|
||||
_invocation: CodeModeNestedToolCall,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async { Ok(json!("x".repeat(MAX_FRAME_BYTES))) })
|
||||
Box::pin(async { Ok(CodeModeToolResult::from(json!("x".repeat(MAX_FRAME_BYTES)))) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
@@ -114,7 +115,7 @@ impl CodeModeSessionDelegate for CancellationDelegate {
|
||||
.await
|
||||
.map_err(|_| "slow tool barrier closed".to_string())?;
|
||||
permit.forget();
|
||||
return Ok(json!({ "tool": tool_name }));
|
||||
return Ok(CodeModeToolResult::from(json!({ "tool": tool_name })));
|
||||
}
|
||||
if tool_name == "tool_call_slow" {
|
||||
self.slow_cancellation
|
||||
@@ -135,7 +136,7 @@ impl CodeModeSessionDelegate for CancellationDelegate {
|
||||
.await
|
||||
.map_err(|_| "fast tool release closed".to_string())?;
|
||||
permit.forget();
|
||||
Ok(json!({ "tool": tool_name }))
|
||||
Ok(CodeModeToolResult::from(json!({ "tool": tool_name })))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use codex_protocol::ToolName;
|
||||
@@ -22,7 +23,7 @@ impl CodeModeSessionDelegate for LargeToolResultDelegate {
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
if invocation.tool_name == ToolName::plain("fast") {
|
||||
return Ok(json!({ "value": "isolated" }));
|
||||
return Ok(CodeModeToolResult::from(json!({ "value": "isolated" })));
|
||||
}
|
||||
assert_eq!(invocation.tool_name, ToolName::plain("large"));
|
||||
self.started.add_permits(/*n*/ 1);
|
||||
@@ -31,7 +32,9 @@ impl CodeModeSessionDelegate for LargeToolResultDelegate {
|
||||
.await
|
||||
.map_err(|_| "large tool release closed".to_string())?
|
||||
.forget();
|
||||
Ok(json!({ "value": "x".repeat(8 * 1024 * 1024) }))
|
||||
Ok(CodeModeToolResult::from(
|
||||
json!({ "value": "x".repeat(8 * 1024 * 1024) }),
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use serde_json::json;
|
||||
@@ -12,6 +14,7 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RecordingDelegate {
|
||||
pub(crate) results_by_input: HashMap<serde_json::Value, CodeModeToolResult>,
|
||||
pub(crate) invocations: Mutex<Vec<CodeModeNestedToolCall>>,
|
||||
pub(crate) notifications: Mutex<Vec<(String, CellId, String)>>,
|
||||
pub(crate) notification_delivered: Notify,
|
||||
@@ -24,11 +27,17 @@ impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
invocation: CodeModeNestedToolCall,
|
||||
_cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
let result = invocation
|
||||
.input
|
||||
.as_ref()
|
||||
.and_then(|input| self.results_by_input.get(input))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| CodeModeToolResult::from(json!({ "value": "output" })));
|
||||
self.invocations
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(invocation);
|
||||
Box::pin(async { Ok(json!({ "value": "output" })) })
|
||||
Box::pin(async move { Ok(result) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
|
||||
@@ -151,6 +151,13 @@ message CompleteToolCallRequest {
|
||||
|
||||
message ToolCallSucceeded {
|
||||
bytes output_json = 1;
|
||||
ToolResultFormat result_format = 2;
|
||||
}
|
||||
|
||||
enum ToolResultFormat {
|
||||
// The default preserves the full JSON value when the format is omitted or unknown.
|
||||
TOOL_RESULT_FORMAT_JSON = 0;
|
||||
TOOL_RESULT_FORMAT_MCP_CALL_TOOL_RESULT = 1;
|
||||
}
|
||||
|
||||
message ToolCallFailed {
|
||||
|
||||
@@ -55,6 +55,7 @@ pub use session::CodeModeSessionOptions;
|
||||
pub use session::CodeModeSessionProvider;
|
||||
pub use session::CodeModeSessionProviderFuture;
|
||||
pub use session::CodeModeSessionResultFuture;
|
||||
pub use session::CodeModeToolResult;
|
||||
pub use session::NoopCodeModeSessionDelegate;
|
||||
pub use session::NotificationFuture;
|
||||
pub use session::StartedCell;
|
||||
|
||||
@@ -20,10 +20,31 @@ pub type CodeModeSessionResultFuture<'a, T> =
|
||||
Pin<Box<dyn Future<Output = Result<T, String>> + Send + 'a>>;
|
||||
pub type CodeModeSessionProviderFuture<'a> =
|
||||
CodeModeSessionResultFuture<'a, Arc<dyn CodeModeSession>>;
|
||||
pub type ToolInvocationFuture<'a> =
|
||||
Pin<Box<dyn Future<Output = Result<JsonValue, String>> + Send + 'a>>;
|
||||
pub type ToolInvocationFuture<'a> = CodeModeSessionResultFuture<'a, CodeModeToolResult>;
|
||||
pub type NotificationFuture<'a> = Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>>;
|
||||
|
||||
/// A nested call's JSON value and how the runtime should treat it when printed.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum CodeModeToolResult {
|
||||
Json(JsonValue),
|
||||
McpCallToolResult(JsonValue),
|
||||
}
|
||||
|
||||
impl CodeModeToolResult {
|
||||
/// Returns the full script-visible value without its format tag.
|
||||
pub fn into_json(self) -> JsonValue {
|
||||
match self {
|
||||
Self::Json(value) | Self::McpCallToolResult(value) => value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonValue> for CodeModeToolResult {
|
||||
fn from(value: JsonValue) -> Self {
|
||||
Self::Json(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Optional resource limits shared by every cell in one code-mode session.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct CodeModeSessionCellExecutionLimits {
|
||||
|
||||
@@ -23,7 +23,9 @@ codex-utils-string = { workspace = true }
|
||||
deno_core_icudata = { workspace = true }
|
||||
futures = { workspace = true, features = ["executor", "std"] }
|
||||
opentelemetry = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true, features = ["raw_value"] }
|
||||
serde_with = { workspace = true, features = ["macros"] }
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
|
||||
tokio-util = { workspace = true, features = ["codec", "compat", "rt"] }
|
||||
tracing = { workspace = true }
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::sync::Arc;
|
||||
use std::sync::mpsc as std_mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -24,7 +25,7 @@ impl CellHost for PanickingCallbackHost {
|
||||
&self,
|
||||
_invocation: CellToolCall,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> Result<JsonValue, String> {
|
||||
) -> Result<CodeModeToolResult, String> {
|
||||
panic!("tool callback panic probe");
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::sync::mpsc as std_mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::host::BOUNDED_OUTPUT_MAX_IMAGE_BYTES;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value as JsonValue;
|
||||
@@ -33,7 +34,7 @@ impl CellHost for TestHost {
|
||||
&self,
|
||||
_invocation: CellToolCall,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> Result<JsonValue, String> {
|
||||
) -> Result<CodeModeToolResult, String> {
|
||||
Err("unexpected tool call".to_string())
|
||||
}
|
||||
|
||||
@@ -67,7 +68,7 @@ impl CellHost for RecordingHost {
|
||||
&self,
|
||||
_invocation: CellToolCall,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> Result<JsonValue, String> {
|
||||
) -> Result<CodeModeToolResult, String> {
|
||||
Err("unexpected tool call".to_string())
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
@@ -43,7 +44,7 @@ pub(crate) trait CellHost: Send + Sync + 'static {
|
||||
&self,
|
||||
invocation: CellToolCall,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> impl Future<Output = Result<JsonValue, String>> + Send;
|
||||
) -> impl Future<Output = Result<CodeModeToolResult, String>> + Send;
|
||||
|
||||
fn notify(
|
||||
&self,
|
||||
|
||||
@@ -87,7 +87,9 @@ pub(super) fn text_callback(
|
||||
} else {
|
||||
args.get(0)
|
||||
};
|
||||
let can_omit_fallback = super::mcp_result::can_omit_fallback(scope, value);
|
||||
let text = match serialize_output_text(scope, value) {
|
||||
Ok(text) if can_omit_fallback => super::mcp_result::without_fallback(&text).unwrap_or(text),
|
||||
Ok(text) => text,
|
||||
Err(error_text) => {
|
||||
throw_type_error(scope, &error_text);
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Compare validated JSON without rounding numbers or dropping repeated keys.
|
||||
//! Index container boundaries once so visiting a field never reparses its descendants.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
const MAX_DEPTH: usize = 64;
|
||||
|
||||
/// Ignore formatting and object key order. Keep the sign of zero and decline
|
||||
/// comparisons that require rounding or ambiguous matches of repeated keys.
|
||||
pub(super) fn equivalent(left: &RawValue, right: &RawValue) -> bool {
|
||||
let (left, right) = (left.get(), right.get());
|
||||
if left == right {
|
||||
return true;
|
||||
}
|
||||
let left = Json {
|
||||
text: left,
|
||||
spans: &index(left),
|
||||
};
|
||||
let right = Json {
|
||||
text: right,
|
||||
spans: &index(right),
|
||||
};
|
||||
left.compare(right, MAX_DEPTH).is_some()
|
||||
}
|
||||
|
||||
/// The text and index lengths of a subtree, including its own entry.
|
||||
struct Span {
|
||||
bytes: usize,
|
||||
entries: usize,
|
||||
}
|
||||
|
||||
/// Serde has checked the grammar. Skip escaped quotes and punctuation inside strings.
|
||||
fn brackets(text: &str) -> impl Iterator<Item = (usize, u8)> {
|
||||
let mut bytes = text.bytes().enumerate();
|
||||
std::iter::from_fn(move || {
|
||||
while let Some((offset, byte)) = bytes.next() {
|
||||
match byte {
|
||||
b'[' | b'{' | b']' | b'}' => return Some((offset, byte)),
|
||||
b'"' => {
|
||||
while let Some((_, byte)) = bytes.next() {
|
||||
match byte {
|
||||
b'"' => break,
|
||||
b'\\' => {
|
||||
bytes.next();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// Only containers with nested containers need an index entry. The first
|
||||
/// bracket inside a flat container already gives us its end.
|
||||
fn index(text: &str) -> Vec<Span> {
|
||||
let mut spans = Vec::new();
|
||||
let mut open = Vec::new();
|
||||
let mut brackets = brackets(text).peekable();
|
||||
let mut depth = 0;
|
||||
while let Some((offset, bracket)) = brackets.next() {
|
||||
if matches!(bracket, b'{' | b'[') {
|
||||
if matches!(brackets.peek(), Some((_, b'}' | b']'))) {
|
||||
brackets.next();
|
||||
continue;
|
||||
}
|
||||
// At MAX_DEPTH we still need the outer span for an exact match.
|
||||
if depth <= MAX_DEPTH {
|
||||
open.push((offset, spans.len()));
|
||||
spans.push(Span {
|
||||
bytes: 0,
|
||||
entries: 0,
|
||||
});
|
||||
}
|
||||
depth += 1;
|
||||
} else {
|
||||
depth -= 1;
|
||||
if depth <= MAX_DEPTH
|
||||
&& let Some((start, slot)) = open.pop()
|
||||
{
|
||||
spans[slot] = Span {
|
||||
bytes: offset + 1 - start,
|
||||
entries: spans.len() - slot,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
spans
|
||||
}
|
||||
|
||||
/// A value, or the remaining members of a container, borrowed from the same two slices.
|
||||
struct Json<'a> {
|
||||
text: &'a str,
|
||||
spans: &'a [Span],
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Key<'a>(#[serde(borrow)] Cow<'a, str>);
|
||||
|
||||
impl<'a> Json<'a> {
|
||||
fn members(self) -> Self {
|
||||
Self {
|
||||
text: self.text[1..self.text.len() - 1].trim_ascii_start(),
|
||||
spans: self.spans.get(1..).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn take_key(&mut self) -> Option<Cow<'a, str>> {
|
||||
let mut keys = serde_json::Deserializer::from_str(self.text).into_iter::<Key>();
|
||||
let Key(key) = keys.next()?.ok()?;
|
||||
self.text = self.text[keys.byte_offset()..]
|
||||
.trim_ascii_start()
|
||||
.strip_prefix(':')?
|
||||
.trim_ascii_start();
|
||||
Some(key)
|
||||
}
|
||||
|
||||
/// Advance past one member, jumping directly over nested containers.
|
||||
fn take_value(&mut self) -> Option<Self> {
|
||||
let (len, count) = match self.text.as_bytes().first()? {
|
||||
b'{' | b'[' => {
|
||||
let (offset, bracket) = brackets(&self.text[1..]).next()?;
|
||||
if matches!(bracket, b'}' | b']') {
|
||||
(offset + 2, 0)
|
||||
} else {
|
||||
let span = self.spans.first()?;
|
||||
(span.bytes, span.entries)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let mut values =
|
||||
serde_json::Deserializer::from_str(self.text).into_iter::<&RawValue>();
|
||||
(values.next()?.ok()?.get().len(), 0)
|
||||
}
|
||||
};
|
||||
let (text, rest) = self.text.split_at(len);
|
||||
let (spans, tail) = self.spans.split_at(count);
|
||||
let rest = rest.trim_ascii_start();
|
||||
self.text = rest.strip_prefix(',').unwrap_or(rest).trim_ascii_start();
|
||||
self.spans = tail;
|
||||
Some(Self { text, spans })
|
||||
}
|
||||
|
||||
/// A mismatch or a value we can't compare losslessly ends the comparison.
|
||||
fn compare(self, other: Self, remaining_depth: usize) -> Option<()> {
|
||||
// Byte-compare leaves and their immediate parents. Comparing at every parent could rescan
|
||||
// a large common prefix at each level when a difference is near the end.
|
||||
if (self.spans.len() <= 1 || remaining_depth == 0) && self.text == other.text {
|
||||
return Some(());
|
||||
}
|
||||
let depth = remaining_depth.checked_sub(1)?;
|
||||
match (
|
||||
self.text.as_bytes().first()?,
|
||||
other.text.as_bytes().first()?,
|
||||
) {
|
||||
(b'{', b'{') => self.members().compare_fields(other.members(), depth),
|
||||
(b'[', b'[') => {
|
||||
let (mut left, mut right) = (self.members(), other.members());
|
||||
while !left.text.is_empty() {
|
||||
left.take_value()?.compare(right.take_value()?, depth)?;
|
||||
}
|
||||
right.text.is_empty().then_some(())
|
||||
}
|
||||
(b'"', b'"') => {
|
||||
let a: String = serde_json::from_str(self.text).ok()?;
|
||||
let b: String = serde_json::from_str(other.text).ok()?;
|
||||
(a == b).then_some(())
|
||||
}
|
||||
(b'-' | b'0'..=b'9', b'-' | b'0'..=b'9') => {
|
||||
(decimal_parts(self.text)? == decimal_parts(other.text)?).then_some(())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the common prefix in order. If the keys diverge, look up the
|
||||
/// remaining fields by name and consume each once. Refuse ambiguous repeats.
|
||||
fn compare_fields(mut self, mut other: Self, depth: usize) -> Option<()> {
|
||||
while !self.text.is_empty() {
|
||||
let key = self.take_key()?;
|
||||
let name = other.take_key()?;
|
||||
if key == name {
|
||||
self.take_value()?.compare(other.take_value()?, depth)?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut fields = HashMap::from([(name, other.take_value()?)]);
|
||||
while !other.text.is_empty() {
|
||||
if fields
|
||||
.insert(other.take_key()?, other.take_value()?)
|
||||
.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
self.take_value()?.compare(fields.remove(&key)?, depth)?;
|
||||
while !self.text.is_empty() {
|
||||
let key = self.take_key()?;
|
||||
self.take_value()?.compare(fields.remove(&key)?, depth)?;
|
||||
}
|
||||
return fields.is_empty().then_some(());
|
||||
}
|
||||
other.text.is_empty().then_some(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Express a valid JSON number as a sign, significant digits and a power of ten.
|
||||
/// For example, 0.0120 and 12e-3 both have digits "12" and exponent -3.
|
||||
/// Return None if the exponent is too large to compare exactly.
|
||||
fn decimal_parts(number: &str) -> Option<(bool, Cow<'_, str>, i64)> {
|
||||
let negative = number.starts_with('-');
|
||||
let unsigned = number.trim_start_matches('-');
|
||||
let (mantissa, exponent) = unsigned.split_once(['e', 'E']).unwrap_or((unsigned, "0"));
|
||||
let (integer, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
|
||||
let fraction = fraction.trim_end_matches('0');
|
||||
if integer == "0" && fraction.is_empty() {
|
||||
// Do not discard the sign even if the significand is zero.
|
||||
return Some((negative, Cow::Borrowed("0"), 0));
|
||||
}
|
||||
|
||||
let exponent = exponent.parse::<i64>().ok()?;
|
||||
if fraction.is_empty() {
|
||||
let digits = integer.trim_end_matches('0');
|
||||
let trailing_zeros = i64::try_from(integer.len() - digits.len()).ok()?;
|
||||
return Some((
|
||||
negative,
|
||||
Cow::Borrowed(digits),
|
||||
exponent.checked_add(trailing_zeros)?,
|
||||
));
|
||||
}
|
||||
let exponent = exponent.checked_sub(i64::try_from(fraction.len()).ok()?)?;
|
||||
let digits = if integer == "0" {
|
||||
Cow::Borrowed(fraction.trim_start_matches('0'))
|
||||
} else {
|
||||
Cow::Owned(format!("{integer}{fraction}"))
|
||||
};
|
||||
Some((negative, digits, exponent))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "json_equality_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Checks lossless comparison independently of the MCP envelope.
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn equivalent(left: &str, right: &str) -> bool {
|
||||
let a = serde_json::from_str(left).unwrap();
|
||||
let b = serde_json::from_str(right).unwrap();
|
||||
let matched = super::equivalent(a, b);
|
||||
assert_eq!(matched, super::equivalent(b, a));
|
||||
matched
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reordered_fields_can_skip_over_nested_or_flat_values_after_a_common_prefix() {
|
||||
assert!(equivalent(
|
||||
r#"{"id":1,"a":[{"s":"\\\"],{","t":[[]]},{}],"b":{"\u006b":"x"},"c":null}"#,
|
||||
r#"{ "id":1.0,"c":null,"b":{"k":"\u0078"},"\u0061":[{"t":[ [] ],"s":"\\\"],{"},{}] }"#,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_objects_can_reorder_around_a_large_value_at_every_level() {
|
||||
let leaf = format!("[{}0]", "1,".repeat(32_768));
|
||||
let left = format!(
|
||||
"{}{leaf}{}",
|
||||
r#"{"first":true,"v":"#.repeat(60),
|
||||
"}".repeat(60)
|
||||
);
|
||||
let right = format!(
|
||||
"{}{leaf}{}",
|
||||
r#"{"v": "#.repeat(60),
|
||||
r#","first":true}"#.repeat(60)
|
||||
);
|
||||
assert!(equivalent(&left, &right));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_identical_subtrees_at_the_recursion_limit() {
|
||||
let deep = format!("{}0{}", "[".repeat(1_000), "]".repeat(1_000));
|
||||
assert!(equivalent(&format!("[{deep}]"), &format!("[ {deep}]")));
|
||||
assert!(!equivalent(&deep, &deep.replace('0', "0.0")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_values_and_repeated_keys_do_not_disappear() {
|
||||
for (left, right) in [
|
||||
("9007199254740993", "9007199254740992"),
|
||||
("[1.00000000000000001]", "[1]"),
|
||||
("1.25000000000000001", "1.25"),
|
||||
("1e-500", "0"),
|
||||
("-0", "0"),
|
||||
("-0.0", "0"),
|
||||
("[-0e3]", "[0]"),
|
||||
("10e9223372036854775807", "1"),
|
||||
("-1.0", "1"),
|
||||
(r#""1.0""#, "1"),
|
||||
("[2,1]", "[1,2]"),
|
||||
("[1]", "[1,2]"),
|
||||
(r#""a b""#, r#""ab""#),
|
||||
(r#"{"a":2,"a":1}"#, r#"{"a":1}"#),
|
||||
(r#"{"a":1,"b":0}"#, r#"{"b":0,"\u0061":2,"a":1}"#),
|
||||
(r#"{"a":1,"b":0}"#, r#"{"b":0,"c":1}"#),
|
||||
(r#"{"a":[],"b":{}}"#, r#"{"b":[],"a":{}}"#),
|
||||
] {
|
||||
assert!(!equivalent(left, right), "{left} vs {right}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_arrays_can_contain_reordered_objects_and_equivalent_decimals() {
|
||||
let rows = r#"{"a":1,"b":2},"#.repeat(20_000);
|
||||
let other_rows = r#"{"b":2,"a":1},"#.repeat(20_000);
|
||||
assert!(equivalent(
|
||||
&format!("[{rows}1]"),
|
||||
&format!("[{other_rows}1.0]")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_objects_can_match_with_reordered_fields() {
|
||||
let mut fields: Vec<_> = (0..1_000).map(|i| format!(r#""k{i}":{i}"#)).collect();
|
||||
let structured = format!("{{{}}}", fields.join(","));
|
||||
fields.reverse();
|
||||
let reordered = format!("{{{}}}", fields.join(", "));
|
||||
assert!(equivalent(&structured, &reordered));
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! MCP call results receive a private marker on the returned V8 object.
|
||||
//! Only `text()` consults it. Copies and JSON round trips produce ordinary unmarked objects.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::value::RawValue;
|
||||
use serde_with::Map;
|
||||
use serde_with::serde_as;
|
||||
|
||||
fn marker<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Private> {
|
||||
let name = v8::String::new(scope, "codex.mcp_result");
|
||||
v8::Private::for_api(scope, name)
|
||||
}
|
||||
|
||||
pub(super) fn mark(scope: &mut v8::PinScope<'_, '_>, value: v8::Local<'_, v8::Value>) {
|
||||
if let Ok(object) = v8::Local::<v8::Object>::try_from(value) {
|
||||
let key = marker(scope);
|
||||
let marked = v8::Local::<v8::Value>::from(v8::Boolean::new(scope, true));
|
||||
object.set_private(scope, key, marked);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check before serialization, since a `toJSON` hook can delete itself and return a replacement.
|
||||
/// Look for the property without invoking getters or proxy traps.
|
||||
pub(super) fn can_omit_fallback(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
value: v8::Local<'_, v8::Value>,
|
||||
) -> bool {
|
||||
let Ok(mut object) = v8::Local::<v8::Object>::try_from(value) else {
|
||||
return false;
|
||||
};
|
||||
let key = marker(scope);
|
||||
if object.has_private(scope, key) != Some(true) {
|
||||
return false;
|
||||
}
|
||||
let Some(to_json) = v8::String::new(scope, "toJSON") else {
|
||||
return false;
|
||||
};
|
||||
let to_json = v8::Local::<v8::Name>::from(to_json);
|
||||
loop {
|
||||
if object.is_proxy() || object.has_own_property(scope, to_json) != Some(false) {
|
||||
return false;
|
||||
}
|
||||
let Some(prototype) = object.get_prototype(scope) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(parent) = v8::Local::<v8::Object>::try_from(prototype) else {
|
||||
return prototype.is_null();
|
||||
};
|
||||
object = parent;
|
||||
}
|
||||
}
|
||||
|
||||
#[serde_as]
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Object<'a>(
|
||||
#[serde(borrow)]
|
||||
#[serde_as(as = "Map<_, _>")]
|
||||
Vec<(String, &'a RawValue)>,
|
||||
);
|
||||
|
||||
impl<'a> Object<'a> {
|
||||
fn field(&self, name: &str) -> Option<&'a RawValue> {
|
||||
self.0
|
||||
.iter()
|
||||
.find(|(key, _)| key == name)
|
||||
.map(|(_, value)| *value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Inspect a single V8 serialization, so getters and toJSON run exactly once.
|
||||
/// Raw fields preserve the order and spelling of the rest of the envelope.
|
||||
pub(super) fn without_fallback(serialized: &str) -> Option<String> {
|
||||
let mut result: Object<'_> = serde_json::from_str(serialized).ok()?;
|
||||
if result
|
||||
.field("isError")
|
||||
.is_some_and(|value| value.get() != "false")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let structured = result.field("structuredContent")?;
|
||||
let [block]: [Object; 1] = serde_json::from_str(result.field("content")?.get()).ok()?;
|
||||
if structured.get() == "null" || block.0.len() != 2 || block.field("type")?.get() != r#""text""# {
|
||||
return None;
|
||||
}
|
||||
let text: String = serde_json::from_str(block.field("text")?.get()).ok()?;
|
||||
let fallback: &RawValue = serde_json::from_str(&text).ok()?;
|
||||
if !super::json_equality::equivalent(structured, fallback) {
|
||||
return None;
|
||||
}
|
||||
// Release the decoded copy before allocating the new output.
|
||||
drop(text);
|
||||
result.0.retain(|(key, _)| key != "content");
|
||||
serde_json::to_string(&result).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mcp_result_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Coverage for exact matching and a lossless projection of the envelope.
|
||||
|
||||
use super::without_fallback;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn preserves_the_serialized_fields_around_the_fallback() {
|
||||
let raw = r#"{"extra":1e+27,"content":[{"text":" [\"\\u0061\", true] ","type":"text"}],"structuredContent":["a",true],"last":42}"#;
|
||||
assert_eq!(
|
||||
without_fallback(raw).as_deref(),
|
||||
Some(r#"{"extra":1e+27,"structuredContent":["a",true],"last":42}"#)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_decimal_spellings_keep_the_structured_numbers() {
|
||||
let raw = r#"{"content":[{"type":"text","text":"[1.0,1e0,-12.300E+2,0.0120,1000000000000000000000,0.0]"}],"structuredContent":[1,1,-1230,12e-3,1e+21,0]}"#;
|
||||
assert_eq!(
|
||||
without_fallback(raw).as_deref(),
|
||||
Some(r#"{"structuredContent":[1,1,-1230,12e-3,1e+21,0]}"#)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_or_invalid_fallbacks_are_preserved() {
|
||||
for text in ["note", "null", "1.1", "1 trailing", "+1", "1,"] {
|
||||
let raw = json!({"structuredContent": 1, "content": [{"type":"text","text":text}]});
|
||||
assert_eq!(without_fallback(&raw.to_string()), None, "{raw}");
|
||||
}
|
||||
let raw = r#"{"structuredContent":null,"content":[{"type":"text","text":"null"}]}"#;
|
||||
assert_eq!(without_fallback(raw), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_and_richer_blocks_are_preserved() {
|
||||
let text = json!({"type":"text", "text": "{}"});
|
||||
for (content, is_error) in [
|
||||
(json!([text]), true),
|
||||
(json!([text, {"type":"image","data":"abc"}]), false),
|
||||
(json!([{"type":"text","text":"{}","annotations":{}}]), false),
|
||||
(json!([{"type":"text","text":"{}","_meta":{}}]), false),
|
||||
(json!([["text", "{}"]]), false),
|
||||
] {
|
||||
let raw = json!({"structuredContent": {}, "content": content, "isError": is_error});
|
||||
assert_eq!(without_fallback(&raw.to_string()), None, "{raw}");
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ mod audio;
|
||||
mod callbacks;
|
||||
mod event_channel;
|
||||
mod globals;
|
||||
mod json_equality;
|
||||
mod mcp_result;
|
||||
mod module_loader;
|
||||
mod timers;
|
||||
mod value;
|
||||
@@ -20,6 +22,7 @@ use crate::session_runtime::OutputItem;
|
||||
use crate::session_runtime::ToolCatalog;
|
||||
use crate::v8_init::ensure_v8_initialized;
|
||||
use codex_code_mode_protocol::CodeModeToolKind;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_protocol::ToolName;
|
||||
pub(crate) use event_channel::RuntimeEventReceiver;
|
||||
pub(crate) use event_channel::RuntimeEventSender;
|
||||
@@ -28,9 +31,17 @@ use serde_json::Value as JsonValue;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RuntimeCommand {
|
||||
ToolResponse { id: String, result: JsonValue },
|
||||
ToolError { id: String, error_text: String },
|
||||
TimeoutFired { id: u64 },
|
||||
ToolResponse {
|
||||
id: String,
|
||||
result: CodeModeToolResult,
|
||||
},
|
||||
ToolError {
|
||||
id: String,
|
||||
error_text: String,
|
||||
},
|
||||
TimeoutFired {
|
||||
id: u64,
|
||||
},
|
||||
ObservePendingFrontier,
|
||||
Terminate,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use serde_json::Value as JsonValue;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
|
||||
use super::CompletionState;
|
||||
use super::RuntimeState;
|
||||
@@ -50,7 +50,7 @@ pub(super) fn evaluate_main_module(
|
||||
pub(super) fn resolve_tool_response(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
id: &str,
|
||||
response: Result<JsonValue, String>,
|
||||
response: Result<CodeModeToolResult, String>,
|
||||
) -> Result<(), String> {
|
||||
let resolver = {
|
||||
let state = scope
|
||||
@@ -67,8 +67,12 @@ pub(super) fn resolve_tool_response(
|
||||
let resolver = v8::Local::new(&tc, &resolver);
|
||||
match response {
|
||||
Ok(result) => {
|
||||
let value = json_to_v8(&mut tc, &result)
|
||||
let is_mcp = matches!(result, CodeModeToolResult::McpCallToolResult(_));
|
||||
let value = json_to_v8(&mut tc, &result.into_json())
|
||||
.ok_or_else(|| "failed to serialize tool response".to_string())?;
|
||||
if is_mcp {
|
||||
super::mcp_result::mark(&mut tc, value);
|
||||
}
|
||||
resolver.resolve(&tc, value);
|
||||
}
|
||||
Err(error_text) => {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::mpsc as std_mpsc;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -48,7 +49,8 @@ fn discarded_tool_response_is_collectible_before_cell_ends() {
|
||||
v8::Global::new(scope, promise)
|
||||
};
|
||||
let response = json!({"content": [{"type": "text", "text": "tool result"}]});
|
||||
resolve_tool_response(scope, "tool", Ok(response.clone())).expect("resolve tool promise");
|
||||
let result = CodeModeToolResult::McpCallToolResult(response.clone());
|
||||
resolve_tool_response(scope, "tool", Ok(result)).expect("resolve tool promise");
|
||||
scope.perform_microtask_checkpoint();
|
||||
scope.low_memory_notification();
|
||||
|
||||
@@ -57,6 +59,7 @@ fn discarded_tool_response_is_collectible_before_cell_ends() {
|
||||
let promise = v8::Local::new(scope, &promise);
|
||||
assert_eq!(promise.state(), v8::PromiseState::Fulfilled);
|
||||
let result = promise.result(scope);
|
||||
assert!(super::super::mcp_result::can_omit_fallback(scope, result));
|
||||
assert_eq!(v8_value_to_json(scope, result), Ok(Some(response)));
|
||||
v8::Weak::new(scope, result)
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ use codex_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use codex_code_mode_protocol::CodeModeSessionOptions;
|
||||
use codex_code_mode_protocol::CodeModeSessionResultFuture;
|
||||
use codex_code_mode_protocol::CodeModeToolKind;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::DEFAULT_EXEC_YIELD_TIME_MS;
|
||||
use codex_code_mode_protocol::ExecuteRequest;
|
||||
use codex_code_mode_protocol::ExecuteToPendingOutcome;
|
||||
@@ -25,7 +26,6 @@ use codex_code_mode_protocol::WaitOutcome;
|
||||
use codex_code_mode_protocol::WaitRequest;
|
||||
use codex_code_mode_protocol::WaitToPendingOutcome;
|
||||
use codex_code_mode_protocol::WaitToPendingRequest;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -421,7 +421,7 @@ impl runtime::SessionRuntimeDelegate for ProtocolDelegate {
|
||||
&self,
|
||||
invocation: runtime::NestedToolCall,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Result<JsonValue, String> {
|
||||
) -> Result<CodeModeToolResult, String> {
|
||||
self.delegate
|
||||
.invoke_tool(
|
||||
CodeModeNestedToolCall {
|
||||
|
||||
@@ -119,7 +119,7 @@ impl CodeModeSessionDelegate for BlockingDelegate {
|
||||
tokio::select! {
|
||||
_ = self.tool_release.notified() => {
|
||||
self.tool_finished.store(true, Ordering::Release);
|
||||
Ok(serde_json::Value::Null)
|
||||
Ok(CodeModeToolResult::from(serde_json::Value::Null))
|
||||
}
|
||||
_ = cancellation_token.cancelled() => {
|
||||
self.tool_finished.store(true, Ordering::Release);
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::FunctionCallOutputContentItem;
|
||||
use crate::ToolDefinition;
|
||||
use codex_code_mode_protocol::CodeModeSession;
|
||||
use codex_code_mode_protocol::CodeModeSessionCellExecutionLimits;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::NotificationFuture;
|
||||
use codex_code_mode_protocol::ToolInvocationFuture;
|
||||
use codex_protocol::ToolName;
|
||||
@@ -500,7 +501,7 @@ impl CodeModeSessionDelegate for ReleasableToolDelegate {
|
||||
self.tool_started.notify_one();
|
||||
Box::pin(async move {
|
||||
tokio::select! {
|
||||
_ = self.tool_release.notified() => Ok(JsonValue::Null),
|
||||
_ = self.tool_release.notified() => Ok(CodeModeToolResult::from(JsonValue::Null)),
|
||||
_ = cancellation_token.cancelled() => Err("cancelled".to_string()),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
pub(crate) use codex_code_mode_protocol::FunctionCallOutputContentItem as OutputItem;
|
||||
use opentelemetry::context::FutureExt;
|
||||
use serde_json::Value as JsonValue;
|
||||
@@ -256,7 +257,7 @@ impl<D: SessionRuntimeDelegate> CellHost for RuntimeCellHost<D> {
|
||||
&self,
|
||||
invocation: CellToolCall,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Result<JsonValue, String> {
|
||||
) -> Result<CodeModeToolResult, String> {
|
||||
self.delegate
|
||||
.invoke_tool(
|
||||
NestedToolCall {
|
||||
|
||||
@@ -24,8 +24,8 @@ impl SessionRuntimeDelegate for RecordingDelegate {
|
||||
&self,
|
||||
_invocation: NestedToolCall,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> Result<JsonValue, String> {
|
||||
Ok(JsonValue::Null)
|
||||
) -> Result<CodeModeToolResult, String> {
|
||||
Ok(CodeModeToolResult::from(JsonValue::Null))
|
||||
}
|
||||
|
||||
async fn notify(
|
||||
@@ -46,8 +46,8 @@ impl SessionRuntimeDelegate for PanickingClosedDelegate {
|
||||
&self,
|
||||
_invocation: NestedToolCall,
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> Result<JsonValue, String> {
|
||||
Ok(JsonValue::Null)
|
||||
) -> Result<CodeModeToolResult, String> {
|
||||
Ok(CodeModeToolResult::from(JsonValue::Null))
|
||||
}
|
||||
|
||||
async fn notify(
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -126,7 +127,7 @@ pub(crate) trait SessionRuntimeDelegate: Send + Sync + 'static {
|
||||
&self,
|
||||
invocation: NestedToolCall,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> impl Future<Output = Result<JsonValue, String>> + Send;
|
||||
) -> impl Future<Output = Result<CodeModeToolResult, String>> + Send;
|
||||
|
||||
fn notify(
|
||||
&self,
|
||||
|
||||
@@ -9,6 +9,7 @@ use codex_code_mode_runtime::CellId;
|
||||
use codex_code_mode_runtime::CodeModeNestedToolCall;
|
||||
use codex_code_mode_runtime::CodeModeSessionDelegate;
|
||||
use codex_code_mode_runtime::CodeModeToolKind;
|
||||
use codex_code_mode_runtime::CodeModeToolResult;
|
||||
use codex_code_mode_runtime::ExecuteRequest;
|
||||
use codex_code_mode_runtime::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_runtime::InProcessCodeModeSession;
|
||||
@@ -39,7 +40,7 @@ impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(invocation.tool_name);
|
||||
Box::pin(async { Ok(json!({"ok": true})) })
|
||||
Box::pin(async { Ok(CodeModeToolResult::from(json!({"ok": true}))) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::grpc;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use futures::FutureExt;
|
||||
@@ -206,7 +207,7 @@ impl SessionInner {
|
||||
&self,
|
||||
invocation_id: String,
|
||||
cancellation: CancellationToken,
|
||||
result: Result<serde_json::Value, String>,
|
||||
result: Result<CodeModeToolResult, String>,
|
||||
) {
|
||||
let request = completion::request(&self.id, &invocation_id, result);
|
||||
tokio::select! {
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::sync::atomic::AtomicBool;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode_protocol::CodeModeOutputTruncation;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::grpc;
|
||||
use http_body_util::Full;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -42,7 +43,7 @@ async fn missing_invocation_completion_racing_cancellation_preserves_session() {
|
||||
.complete_tool_call(
|
||||
"invocation".to_string(),
|
||||
cancellation,
|
||||
Ok(serde_json::Value::Null),
|
||||
Ok(CodeModeToolResult::from(serde_json::Value::Null)),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -104,7 +105,7 @@ async fn cancelled_completion_does_not_wait_for_delivery_capacity() {
|
||||
let completion = session.complete_tool_call(
|
||||
"queued".to_string(),
|
||||
cancellation.clone(),
|
||||
Ok(serde_json::Value::Null),
|
||||
Ok(CodeModeToolResult::from(serde_json::Value::Null)),
|
||||
);
|
||||
tokio::pin!(completion);
|
||||
assert!(futures::poll!(completion.as_mut()).is_pending());
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::grpc;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use prost::Message;
|
||||
@@ -5,7 +6,7 @@ use prost::Message;
|
||||
pub(super) fn request(
|
||||
session_id: &str,
|
||||
invocation_id: &str,
|
||||
result: Result<serde_json::Value, String>,
|
||||
result: Result<CodeModeToolResult, String>,
|
||||
) -> grpc::CompleteToolCallRequest {
|
||||
request_with_maximum(session_id, invocation_id, result, MAX_FRAME_BYTES)
|
||||
}
|
||||
@@ -13,20 +14,25 @@ pub(super) fn request(
|
||||
fn request_with_maximum(
|
||||
session_id: &str,
|
||||
invocation_id: &str,
|
||||
result: Result<serde_json::Value, String>,
|
||||
result: Result<CodeModeToolResult, String>,
|
||||
maximum_message_bytes: usize,
|
||||
) -> grpc::CompleteToolCallRequest {
|
||||
let outcome = match result {
|
||||
Ok(value) => match serde_json::to_vec(&value) {
|
||||
Ok(output_json) => {
|
||||
grpc::complete_tool_call_request::Outcome::Succeeded(grpc::ToolCallSucceeded {
|
||||
output_json,
|
||||
})
|
||||
let reply = result.and_then(|result| {
|
||||
let (value, format) = match result {
|
||||
CodeModeToolResult::Json(value) => (value, grpc::ToolResultFormat::Json),
|
||||
CodeModeToolResult::McpCallToolResult(value) => {
|
||||
(value, grpc::ToolResultFormat::McpCallToolResult)
|
||||
}
|
||||
Err(error) => grpc::complete_tool_call_request::Outcome::Failed(grpc::ToolCallFailed {
|
||||
message: format!("failed to encode code-mode tool result: {error}"),
|
||||
}),
|
||||
},
|
||||
};
|
||||
let output_json = serde_json::to_vec(&value)
|
||||
.map_err(|error| format!("failed to encode code-mode tool result: {error}"))?;
|
||||
Ok(grpc::ToolCallSucceeded {
|
||||
output_json,
|
||||
result_format: format as i32,
|
||||
})
|
||||
});
|
||||
let outcome = match reply {
|
||||
Ok(reply) => grpc::complete_tool_call_request::Outcome::Succeeded(reply),
|
||||
Err(message) => {
|
||||
grpc::complete_tool_call_request::Outcome::Failed(grpc::ToolCallFailed { message })
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::grpc;
|
||||
use pretty_assertions::assert_eq;
|
||||
use prost::Message;
|
||||
@@ -9,7 +10,12 @@ use super::request_with_maximum;
|
||||
fn completion_size_includes_the_protobuf_envelope() {
|
||||
let output = serde_json::Value::String("a".repeat(100));
|
||||
let raw_json_bytes = serde_json::to_vec(&output).expect("valid JSON").len();
|
||||
let completion = request_with_maximum("session", "invocation", Ok(output), raw_json_bytes);
|
||||
let completion = request_with_maximum(
|
||||
"session",
|
||||
"invocation",
|
||||
Ok(CodeModeToolResult::from(output)),
|
||||
raw_json_bytes,
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
completion.outcome,
|
||||
@@ -33,7 +39,7 @@ fn delegate_errors_larger_than_64_kib_are_preserved() {
|
||||
|
||||
#[test]
|
||||
fn completion_at_exact_message_limit_is_accepted() {
|
||||
let value = serde_json::json!({ "ok": true });
|
||||
let value = CodeModeToolResult::McpCallToolResult(serde_json::json!({ "content": [] }));
|
||||
let expected = request("session", "invocation", Ok(value.clone()));
|
||||
let actual = request_with_maximum("session", "invocation", Ok(value), expected.encoded_len());
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeNestedToolCall;
|
||||
use codex_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use codex_code_mode_protocol::CodeModeToolKind;
|
||||
use codex_code_mode_protocol::CodeModeToolResult;
|
||||
use codex_code_mode_protocol::FunctionCallOutputContentItem;
|
||||
use codex_code_mode_protocol::NotificationFuture;
|
||||
use codex_code_mode_protocol::RuntimeResponse;
|
||||
@@ -40,7 +41,7 @@ impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
_cancellation_token: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
self.calls.lock().expect("calls lock").push(invocation);
|
||||
Box::pin(async { Ok(json!({ "ok": true })) })
|
||||
Box::pin(async { Ok(CodeModeToolResult::from(json!({ "ok": true }))) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
@@ -128,7 +129,7 @@ async fn reconnect_maps_every_delegate_callback_to_its_generation() {
|
||||
delegate
|
||||
.invoke_tool(invocation.clone(), CancellationToken::new())
|
||||
.await,
|
||||
Ok(json!({ "ok": true }))
|
||||
Ok(CodeModeToolResult::from(json!({ "ok": true })))
|
||||
);
|
||||
assert_eq!(
|
||||
delegate
|
||||
|
||||
@@ -934,6 +934,9 @@
|
||||
"code_mode_interrupt": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"code_mode_mcp_result_dedup": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"code_mode_only": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -8341,6 +8344,9 @@
|
||||
"code_mode_interrupt": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"code_mode_mcp_result_dedup": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"code_mode_only": {
|
||||
"type": "boolean"
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::tools::context::ToolCallOrigin;
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use codex_history::CodexHarnessMetadata;
|
||||
@@ -16,7 +17,6 @@ use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_tool_call_id::ToolCallId;
|
||||
use codex_utils_output_truncation::with_serialization_allowance;
|
||||
use serde_json::Value as JsonValue;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -413,7 +413,7 @@ enum DispatchMessage {
|
||||
step_context: Weak<StepContext>,
|
||||
dispatch_trace: Box<NestedToolDispatchTrace>,
|
||||
cancellation_token: CancellationToken,
|
||||
response_tx: oneshot::Sender<Result<JsonValue, String>>,
|
||||
response_tx: oneshot::Sender<Result<CodeModeToolResult, String>>,
|
||||
},
|
||||
Notify {
|
||||
call_id: String,
|
||||
@@ -449,7 +449,8 @@ impl CoreTurnHost {
|
||||
step_context: Arc<StepContext>,
|
||||
call_id: ToolCallId,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> impl std::future::Future<Output = Result<JsonValue, String>> + Send + 'static {
|
||||
) -> impl std::future::Future<Output = Result<CodeModeToolResult, String>> + Send + 'static
|
||||
{
|
||||
let invocation = submit_nested_tool(
|
||||
Arc::clone(&self.session),
|
||||
step_context,
|
||||
|
||||
@@ -8,6 +8,7 @@ use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_tools::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -174,7 +175,10 @@ async fn detached_code_mode_callback_keeps_thread_id_on_dispatch_span() -> anyho
|
||||
})
|
||||
.await?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(result, serde_json::json!("audit-probe-ok"));
|
||||
assert_eq!(
|
||||
result,
|
||||
CodeModeToolResult::from(serde_json::json!("audit-probe-ok"))
|
||||
);
|
||||
let records = records.lock().unwrap();
|
||||
let [(fields, has_turn_ancestor)] = records.as_slice() else {
|
||||
panic!("expected one nested dispatch span, got {records:?}");
|
||||
|
||||
@@ -20,7 +20,9 @@ use codex_code_mode::CodeModeSession;
|
||||
use codex_code_mode::CodeModeSessionOptions;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_tool_call_id::ToolCallId;
|
||||
@@ -358,7 +360,7 @@ fn submit_nested_tool(
|
||||
call_id: ToolCallId,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> Result<
|
||||
impl std::future::Future<Output = Result<JsonValue, FunctionCallError>> + Send + 'static,
|
||||
impl std::future::Future<Output = Result<CodeModeToolResult, FunctionCallError>> + Send + 'static,
|
||||
FunctionCallError,
|
||||
> {
|
||||
let dispatch_started = std::time::Instant::now();
|
||||
@@ -423,6 +425,11 @@ fn submit_nested_tool(
|
||||
call_id: call.call_id.to_string(),
|
||||
cell_id: cell_id.to_string(),
|
||||
});
|
||||
let dedup_mcp_result = step_context
|
||||
.turn
|
||||
.config
|
||||
.features
|
||||
.enabled(Feature::CodeModeMcpResultDedup);
|
||||
let result = tool_runtime.handle_tool_call_with_source(
|
||||
step_context,
|
||||
call,
|
||||
@@ -433,7 +440,14 @@ fn submit_nested_tool(
|
||||
cancellation_token,
|
||||
Arc::default(),
|
||||
);
|
||||
Ok(async move { Ok(result.await?.code_mode_result()) })
|
||||
Ok(async move {
|
||||
Ok(match result.await?.code_mode_result() {
|
||||
CodeModeToolResult::McpCallToolResult(value) if !dedup_mcp_result => {
|
||||
CodeModeToolResult::Json(value)
|
||||
}
|
||||
result => result,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn build_nested_tool_payload(
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::tools::executed_tool_calls::PendingResultBody;
|
||||
use crate::turn_diff_tracker::TurnDiffTracker;
|
||||
use crate::unified_exec::output::CapturedStream;
|
||||
use crate::unified_exec::resolve_max_tokens;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_extension_api::ToolCallOutcome;
|
||||
use codex_protocol::ResponseItemId;
|
||||
use codex_protocol::mcp::CallToolResult;
|
||||
@@ -215,7 +216,7 @@ impl ToolOutput for McpToolOutput {
|
||||
}
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult {
|
||||
self.result.code_mode_result(payload)
|
||||
}
|
||||
|
||||
@@ -402,8 +403,8 @@ impl ToolOutput for ApplyPatchToolOutput {
|
||||
Some(JsonValue::String(self.text.clone()))
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
JsonValue::Object(serde_json::Map::new())
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
CodeModeToolResult::from(JsonValue::Object(serde_json::Map::new()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,7 +515,7 @@ impl ToolOutput for ExecCommandToolOutput {
|
||||
))
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
#[derive(Serialize)]
|
||||
struct UnifiedExecCodeModeResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -541,9 +542,10 @@ impl ToolOutput for ExecCommandToolOutput {
|
||||
},
|
||||
};
|
||||
|
||||
serde_json::to_value(result).unwrap_or_else(|err| {
|
||||
let value = serde_json::to_value(result).unwrap_or_else(|err| {
|
||||
JsonValue::String(format!("failed to serialize exec result: {err}"))
|
||||
})
|
||||
});
|
||||
CodeModeToolResult::from(value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ fn mcp_code_mode_result_omits_private_metadata() {
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
serde_json::json!({
|
||||
CodeModeToolResult::McpCallToolResult(serde_json::json!({
|
||||
"content": [{
|
||||
"type": "text",
|
||||
"text": "ignored",
|
||||
@@ -81,7 +81,7 @@ fn mcp_code_mode_result_omits_private_metadata() {
|
||||
"content": "done",
|
||||
},
|
||||
"isError": false,
|
||||
})
|
||||
}))
|
||||
);
|
||||
assert_eq!(output.meta, Some(serde_json::json!({ "source": "mcp" })));
|
||||
}
|
||||
@@ -276,7 +276,7 @@ fn mcp_tool_output_code_mode_result_preserves_content_without_private_metadata(
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
serde_json::json!({
|
||||
CodeModeToolResult::McpCallToolResult(serde_json::json!({
|
||||
"content": [{
|
||||
"type": "text",
|
||||
"text": "ignored",
|
||||
@@ -285,7 +285,7 @@ fn mcp_tool_output_code_mode_result_preserves_content_without_private_metadata(
|
||||
"content": "large structured value ".repeat(1_000),
|
||||
},
|
||||
"isError": false,
|
||||
})
|
||||
}))
|
||||
);
|
||||
assert_eq!(
|
||||
output.result.meta,
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::tools::context::ToolPayload;
|
||||
use crate::tools::context::boxed_tool_output;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_tools::JsonSchema;
|
||||
@@ -17,7 +18,6 @@ use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ResponsesApiTool;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolSpec;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -40,10 +40,10 @@ impl ToolOutput for CurrentTimeOutput {
|
||||
.to_response_item(call_id, payload)
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
json!({
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
CodeModeToolResult::from(json!({
|
||||
"current_time": self.0.formatted_time(),
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,12 @@ use crate::tools::context::boxed_tool_output;
|
||||
use crate::tools::handlers::get_context_remaining_spec::GET_CONTEXT_REMAINING_TOOL_NAME;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::openai_models::ToolMessage;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolSpec;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -50,10 +50,10 @@ impl ToolOutput for GetContextRemainingOutput {
|
||||
.to_response_item(call_id, payload)
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
json!({
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
CodeModeToolResult::from(json!({
|
||||
"tokens_left": self.tokens_left,
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -433,7 +433,7 @@ impl CoreToolRuntime for McpHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
let result = result.code_mode_result(&invocation.payload);
|
||||
let result = result.code_mode_result(&invocation.payload).into_json();
|
||||
let Some(content) = result.get("content").and_then(Value::as_array) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -17,6 +17,7 @@ use crate::tools::handlers::multi_agents_spec::MULTI_AGENT_V1_NAMESPACE;
|
||||
use crate::tools::handlers::parse_arguments;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::items::CollabAgentTool;
|
||||
use codex_protocol::items::CollabAgentToolCallItem;
|
||||
@@ -31,7 +32,6 @@ use codex_tools::ToolSearchInfo;
|
||||
use codex_tools::ToolSearchSourceInfo;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
const MULTI_AGENT_TOOL_SEARCH_SOURCE_NAME: &str = "Multi-agent tools";
|
||||
const MULTI_AGENT_TOOL_SEARCH_SOURCE_DESCRIPTION: &str = "Spawn and manage sub-agents.";
|
||||
|
||||
@@ -141,7 +141,7 @@ impl ToolOutput for CloseAgentResult {
|
||||
tool_output_response_item(call_id, payload, self, Some(true), "close_agent")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "close_agent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ impl ToolOutput for ResumeAgentResult {
|
||||
tool_output_response_item(call_id, payload, self, Some(true), "resume_agent")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "resume_agent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ impl ToolOutput for SendInputResult {
|
||||
tool_output_response_item(call_id, payload, self, Some(true), "send_input")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "send_input")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,7 +266,7 @@ impl ToolOutput for SpawnAgentResult {
|
||||
tool_output_response_item(call_id, payload, self, Some(true), "spawn_agent")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "spawn_agent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ impl ToolOutput for WaitAgentResult {
|
||||
tool_output_response_item(call_id, payload, self, /*success*/ None, "wait_agent")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "wait_agent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::function_tool::FunctionCallError;
|
||||
use crate::tools::context::FunctionToolOutput;
|
||||
use crate::tools::context::ToolOutput;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -54,13 +55,14 @@ where
|
||||
.to_response_item(call_id, payload)
|
||||
}
|
||||
|
||||
pub(crate) fn tool_output_code_mode_result<T>(value: &T, tool_name: &str) -> JsonValue
|
||||
pub(crate) fn tool_output_code_mode_result<T>(value: &T, tool_name: &str) -> CodeModeToolResult
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
serde_json::to_value(value).unwrap_or_else(|err| {
|
||||
let value = serde_json::to_value(value).unwrap_or_else(|err| {
|
||||
JsonValue::String(format!("failed to serialize {tool_name} result: {err}"))
|
||||
})
|
||||
});
|
||||
CodeModeToolResult::from(value)
|
||||
}
|
||||
|
||||
pub(crate) fn collab_spawn_error(err: CodexErr) -> FunctionCallError {
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::tools::handlers::multi_agents_common::*;
|
||||
use crate::tools::handlers::parse_arguments;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_protocol::items::CollabAgentTool;
|
||||
use codex_protocol::items::CollabAgentToolCallItem;
|
||||
use codex_protocol::items::CollabAgentToolCallStatus;
|
||||
@@ -23,7 +24,6 @@ use codex_protocol::protocol::SubAgentActivityKind;
|
||||
use codex_tools::ToolName;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
pub(crate) use followup_task::Handler as FollowupTaskHandler;
|
||||
pub(crate) use interrupt_agent::Handler as InterruptAgentHandler;
|
||||
|
||||
@@ -114,7 +114,7 @@ impl ToolOutput for InterruptAgentResult {
|
||||
tool_output_response_item(call_id, payload, self, Some(true), "interrupt_agent")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "interrupt_agent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ impl ToolOutput for ListAgentsResult {
|
||||
tool_output_response_item(call_id, payload, self, Some(true), "list_agents")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "list_agents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,7 +266,7 @@ impl ToolOutput for SpawnAgentResult {
|
||||
tool_output_response_item(call_id, payload, self, Some(true), "spawn_agent")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "spawn_agent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +186,7 @@ impl ToolOutput for WaitAgentResult {
|
||||
tool_output_response_item(call_id, payload, self, /*success*/ None, "wait_agent")
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
tool_output_code_mode_result(self, "wait_agent")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::tools::context::boxed_tool_output;
|
||||
use crate::tools::handlers::plan_spec::create_update_plan_tool;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::models::FunctionCallOutputPayload;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
@@ -40,8 +41,8 @@ impl ToolOutput for PlanToolOutput {
|
||||
}
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
JsonValue::Object(serde_json::Map::new())
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
CodeModeToolResult::from(JsonValue::Object(serde_json::Map::new()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_protocol::items::ImageViewItem;
|
||||
@@ -273,15 +274,16 @@ impl ToolOutput for ViewImageOutput {
|
||||
}
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> serde_json::Value {
|
||||
if self.unified_image_budget {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
let value = if self.unified_image_budget {
|
||||
serde_json::json!({ "image_url": self.image_url })
|
||||
} else {
|
||||
serde_json::json!({
|
||||
"image_url": self.image_url,
|
||||
"detail": self.image_detail
|
||||
})
|
||||
}
|
||||
};
|
||||
CodeModeToolResult::from(value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -365,9 +367,11 @@ mod tests {
|
||||
unified_image_budget: false,
|
||||
};
|
||||
|
||||
let result = output.code_mode_result(&ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
});
|
||||
let result = output
|
||||
.code_mode_result(&ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
})
|
||||
.into_json();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
|
||||
@@ -31,6 +31,7 @@ use crate::tools::router::tool_log_payload;
|
||||
use crate::tools::tool_dispatch_trace::ToolDispatchTrace;
|
||||
use crate::util::error_or_panic;
|
||||
use codex_analytics::ControlToolCallStatus;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_extension_api::ToolCallOutcome;
|
||||
use codex_extension_api::ToolPolicy;
|
||||
use codex_history::CodexHarnessMetadata;
|
||||
@@ -357,7 +358,7 @@ impl AnyToolResult {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn code_mode_result(self) -> serde_json::Value {
|
||||
pub(crate) fn code_mode_result(self) -> CodeModeToolResult {
|
||||
let Self {
|
||||
payload, result, ..
|
||||
} = self;
|
||||
@@ -391,7 +392,7 @@ impl ToolOutput for PostToolUseFeedbackOutput {
|
||||
self.model_visible.to_response_item(call_id, payload)
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> Value {
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult {
|
||||
self.original.code_mode_result(payload)
|
||||
}
|
||||
|
||||
|
||||
@@ -746,7 +746,7 @@ fn post_tool_use_feedback_output_keeps_code_mode_result_typed() {
|
||||
|
||||
assert_eq!(
|
||||
result.code_mode_result(),
|
||||
serde_json::json!({ "typed": true })
|
||||
CodeModeToolResult::Json(serde_json::json!({ "typed": true }))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -783,12 +783,17 @@ fn post_tool_use_feedback_output_preserves_mcp_result_metadata(tool_error: bool)
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
};
|
||||
let original_result = result.original.code_mode_result(&payload);
|
||||
assert_eq!(
|
||||
result.tool_result_metadata(),
|
||||
ToolResultMetadata::new(&metadata)
|
||||
);
|
||||
assert_eq!(result.code_mode_result(&payload), original_result);
|
||||
assert_eq!(
|
||||
result.code_mode_result(&payload),
|
||||
CodeModeToolResult::McpCallToolResult(serde_json::json!({
|
||||
"content": [{"type": "text", "text": "original result"}],
|
||||
"isError": tool_error,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -104,7 +104,7 @@ fn tool_dispatch_result(
|
||||
})
|
||||
}
|
||||
ToolCallSource::CodeMode { .. } => Some(ToolDispatchResult::CodeModeResponse {
|
||||
value: result.code_mode_result(payload),
|
||||
value: result.code_mode_result(payload).into_json(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
@@ -52,7 +53,7 @@ impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
self.contexts
|
||||
.send(codex_otel::current_span_w3c_trace_context().expect("context after await"))
|
||||
.expect("context receiver remains open");
|
||||
Ok(serde_json::json!("ready"))
|
||||
Ok(CodeModeToolResult::from(serde_json::json!("ready")))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -7423,6 +7423,54 @@ async fn code_mode_can_apply_patch_via_nested_tool() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(false; "default")]
|
||||
#[test_case(true; "enabled")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn code_mode_deduplicates_printed_mcp_results_only_when_enabled(enabled: bool) -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let apps = AppsTestServer::mount_searchable(&server).await?;
|
||||
let result = serde_json::json!({
|
||||
"isError": false,
|
||||
"content": [{"type": "text", "text": r#"{"timezone":"UTC"}"#}],
|
||||
"structuredContent": {"timezone": "UTC"},
|
||||
});
|
||||
let mut expected = result.clone();
|
||||
if enabled {
|
||||
expected.as_object_mut().unwrap().remove("content");
|
||||
}
|
||||
Mock::given(method("POST"))
|
||||
.and(body_partial_json(serde_json::json!({
|
||||
"method": "tools/call", "params": {"name": "calendar_timezone_option_99"}
|
||||
})))
|
||||
.respond_with(move |request: &Request| {
|
||||
let body: Value = serde_json::from_slice(&request.body).unwrap();
|
||||
ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"jsonrpc": "2.0", "id": body["id"], "result": result
|
||||
}))
|
||||
})
|
||||
.with_priority(/*p*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let builder = search_capable_apps_builder(apps.chatgpt_base_url).with_config(move |config| {
|
||||
config.features.enable(Feature::CodeModeOnly).unwrap();
|
||||
if enabled {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::CodeModeMcpResultDedup)
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let code =
|
||||
r#"text(await tools.mcp__codex_apps__calendar_timezone_option_99({ timezone: "UTC" }));"#;
|
||||
let (_test, follow_up) =
|
||||
run_code_mode_turn_with_builder(&server, "Check the timezone", code, builder).await?;
|
||||
let (output, _) = custom_tool_output_body_and_success(&follow_up.single_request(), "call-1");
|
||||
assert_eq!(serde_json::from_str::<Value>(&output)?, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn code_mode_can_print_structured_mcp_tool_result_fields() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -69,7 +69,7 @@ async fn installed_goal_tools_create_goal_and_fill_empty_preview() -> anyhow::Re
|
||||
}),
|
||||
);
|
||||
let output = create_tool.handle(invocation.clone()).await?;
|
||||
let result = output.code_mode_result(&invocation.payload);
|
||||
let result = output.code_mode_result(&invocation.payload).into_json();
|
||||
assert_eq!(
|
||||
result,
|
||||
json!({
|
||||
@@ -142,7 +142,7 @@ async fn installed_goal_tools_apply_maximum_token_budget() -> anyhow::Result<()>
|
||||
);
|
||||
let output = create_tool.handle(invocation.clone()).await?;
|
||||
assert_eq!(
|
||||
output.code_mode_result(&invocation.payload)["goal"]["tokenBudget"],
|
||||
output.code_mode_result(&invocation.payload).into_json()["goal"]["tokenBudget"],
|
||||
json!(100)
|
||||
);
|
||||
Ok(())
|
||||
@@ -250,7 +250,7 @@ async fn installed_goal_tools_only_replace_complete_goal() -> anyhow::Result<()>
|
||||
json!({ "objective": "replacement goal" }),
|
||||
);
|
||||
let output = create_tool.handle(invocation.clone()).await?;
|
||||
let result = output.code_mode_result(&invocation.payload);
|
||||
let result = output.code_mode_result(&invocation.payload).into_json();
|
||||
|
||||
assert_eq!(json!("replacement goal"), result["goal"]["objective"]);
|
||||
assert_eq!(json!("active"), result["goal"]["status"]);
|
||||
@@ -588,7 +588,7 @@ async fn subagent_usage_resets_when_root_goal_is_replaced() -> anyhow::Result<()
|
||||
.await?;
|
||||
assert_eq!(
|
||||
json!(25),
|
||||
completed.code_mode_result(&completion.payload)["goal"]["tokensUsed"]
|
||||
completed.code_mode_result(&completion.payload).into_json()["goal"]["tokensUsed"]
|
||||
);
|
||||
|
||||
child
|
||||
@@ -1140,7 +1140,7 @@ async fn update_goal_can_stop_and_accounts_final_progress() -> anyhow::Result<()
|
||||
json!({ "status": status }),
|
||||
);
|
||||
let output = update_tool.handle(invocation.clone()).await?;
|
||||
let result = output.code_mode_result(&invocation.payload);
|
||||
let result = output.code_mode_result(&invocation.payload).into_json();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
|
||||
@@ -22,7 +22,7 @@ pub(crate) async fn invoke(
|
||||
.with_context(|| format!("missing reviewer tool {name}"))?;
|
||||
let call = reviewer_tool_call(&tool.tool_name(), &arguments, /*byte_limit*/ 8_000);
|
||||
let result = tool.handle(call.clone()).await?;
|
||||
Ok(result.code_mode_result(&call.payload))
|
||||
Ok(result.code_mode_result(&call.payload).into_json())
|
||||
}
|
||||
|
||||
pub(crate) fn reviewer_tool_call(
|
||||
|
||||
@@ -164,7 +164,7 @@ async fn searches_live_and_unsubscribed_guardian_posts() -> anyhow::Result<()> {
|
||||
/*byte_limit*/ 8_000,
|
||||
);
|
||||
let result = search.handle(call.clone()).await?;
|
||||
let output = result.code_mode_result(&call.payload);
|
||||
let output = result.code_mode_result(&call.payload).into_json();
|
||||
assert_eq!(result.log_output(), output.to_string());
|
||||
let page: codex_message_board::Page<codex_message_board::PostPreview> =
|
||||
serde_json::from_value(output)?;
|
||||
@@ -225,7 +225,7 @@ async fn lists_only_the_reviewers_own_subscriptions_across_pages() -> anyhow::Re
|
||||
let call = reviewer_tool_call(&name, &arguments, /*byte_limit*/ 96);
|
||||
let result = tool.handle(call.clone()).await?;
|
||||
Ok(serde_json::from_value(
|
||||
result.code_mode_result(&call.payload),
|
||||
result.code_mode_result(&call.payload).into_json(),
|
||||
)?)
|
||||
};
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ async fn subscription_tools_only_change_the_callers_channels() -> anyhow::Result
|
||||
let result = tool.handle(call.clone()).await;
|
||||
if succeeds {
|
||||
let result = result?;
|
||||
let response = result.code_mode_result(&call.payload);
|
||||
let response = result.code_mode_result(&call.payload).into_json();
|
||||
assert_eq!(result.log_output(), response.to_string());
|
||||
assert_eq!(
|
||||
response,
|
||||
|
||||
@@ -33,6 +33,7 @@ use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::openai_models::HistoryToolMessages;
|
||||
use codex_protocol::openai_models::NotesToolMessages;
|
||||
use codex_protocol::openai_models::ToolMessage;
|
||||
use codex_tools::CodeModeToolResult;
|
||||
use codex_tools::JsonToolOutput;
|
||||
use codex_tools::ResponsesApiNamespace;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
@@ -300,8 +301,10 @@ impl ToolOutput for HistoryNotesToolOutput {
|
||||
}
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> Value {
|
||||
Value::String("History tools are unavailable in code mode.".to_string())
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
CodeModeToolResult::from(Value::String(
|
||||
"History tools are unavailable in code mode.".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -604,7 +604,7 @@ fn generated_output_returns_generated_image_helper_input_in_code_mode() {
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
output.code_mode_result(&function_payload()),
|
||||
output.code_mode_result(&function_payload()).into_json(),
|
||||
serde_json::json!({
|
||||
"image_url": format!("data:image/png;base64,{RESULT}"),
|
||||
"output_hint": "generated image save hint",
|
||||
@@ -621,7 +621,7 @@ fn generated_output_omits_oversized_output_hint() {
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
output.code_mode_result(&function_payload()),
|
||||
output.code_mode_result(&function_payload()).into_json(),
|
||||
serde_json::json!({
|
||||
"image_url": format!("data:image/png;base64,{RESULT}"),
|
||||
})
|
||||
|
||||
@@ -42,6 +42,7 @@ use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ImageGenerationBeginEvent;
|
||||
use codex_protocol::protocol::ImageGenerationEndEvent;
|
||||
use codex_tools::CodeModeToolResult;
|
||||
use codex_tools::ResponsesApiNamespace;
|
||||
use codex_tools::ResponsesApiNamespaceTool;
|
||||
use codex_tools::ResponsesApiTool;
|
||||
@@ -774,7 +775,7 @@ impl ToolOutput for GeneratedImageOutput {
|
||||
}
|
||||
|
||||
/// Returns the object consumed by the code-mode `generatedImage()` helper.
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> Value {
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
let mut result = Map::from_iter([(
|
||||
"image_url".to_string(),
|
||||
Value::String(format!(
|
||||
@@ -789,7 +790,7 @@ impl ToolOutput for GeneratedImageOutput {
|
||||
Value::String(output_hint.clone()),
|
||||
);
|
||||
}
|
||||
Value::Object(result)
|
||||
CodeModeToolResult::from(Value::Object(result))
|
||||
}
|
||||
|
||||
/// Returns generated bytes and persisted-artifact context for model follow-up.
|
||||
|
||||
@@ -156,6 +156,8 @@ pub enum Feature {
|
||||
CodeMode,
|
||||
/// Expose ranked tool discovery inside JavaScript code mode.
|
||||
CodeModeToolSearch,
|
||||
/// Omit duplicate MCP text fallbacks when Code Mode prints the original result.
|
||||
CodeModeMcpResultDedup,
|
||||
/// Removed compatibility flag for the configurable code-mode exec yield timeout.
|
||||
CodeModeBufferedExec,
|
||||
/// Run JavaScript code mode in the standalone host process.
|
||||
@@ -1394,6 +1396,12 @@ pub const FEATURES: &[FeatureSpec] = &[
|
||||
stage: Stage::UnderDevelopment,
|
||||
default_enabled: false,
|
||||
},
|
||||
FeatureSpec {
|
||||
id: Feature::CodeModeMcpResultDedup,
|
||||
key: "code_mode_mcp_result_dedup",
|
||||
stage: Stage::UnderDevelopment,
|
||||
default_enabled: false,
|
||||
},
|
||||
FeatureSpec {
|
||||
id: Feature::CodeModeBufferedExec,
|
||||
key: "code_mode_buffered_exec",
|
||||
|
||||
@@ -126,7 +126,7 @@ impl ServerHandler for MessageBoardMcpServer {
|
||||
};
|
||||
let result = match executor.handle(call).await {
|
||||
Ok(output) => {
|
||||
let value = output.code_mode_result(&payload);
|
||||
let value = output.code_mode_result(&payload).into_json();
|
||||
let mut result = if value.is_object() {
|
||||
CallToolResult::structured(value)
|
||||
} else {
|
||||
|
||||
@@ -101,7 +101,7 @@ async fn discovery_and_calls_reuse_board_schemas_identity_and_bounded_results()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut expected =
|
||||
CallToolResult::structured(native_read.code_mode_result(&payload.payload));
|
||||
CallToolResult::structured(native_read.code_mode_result(&payload.payload).into_json());
|
||||
// The negotiated legacy wire format omits the newer resultType discriminator.
|
||||
expected.result_type = None;
|
||||
assert_eq!(read, expected);
|
||||
|
||||
@@ -30,6 +30,7 @@ pub use code_mode::code_mode_name_for_tool_name;
|
||||
pub use code_mode::collect_code_mode_exec_prompt_tool_definitions;
|
||||
pub use code_mode::collect_code_mode_tool_definitions;
|
||||
pub use code_mode::tool_spec_to_code_mode_tool_definition;
|
||||
pub use codex_code_mode::CodeModeToolResult;
|
||||
pub use codex_protocol::ToolName;
|
||||
pub use dynamic_tool::parse_dynamic_tool;
|
||||
pub use function_call_error::FunctionCallError;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use codex_code_mode::CodeModeToolResult;
|
||||
use codex_protocol::models::AudioReference;
|
||||
use codex_protocol::models::FunctionCallOutputBody;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
@@ -76,8 +77,11 @@ pub trait ToolOutput: Send {
|
||||
None
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> JsonValue {
|
||||
response_input_to_code_mode_result(self.to_response_item("", payload))
|
||||
/// Returns the script-visible value with its format for Code Mode's output helpers.
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult {
|
||||
CodeModeToolResult::from(response_input_to_code_mode_result(
|
||||
self.to_response_item("", payload),
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns the host-observed result fields for executed-tool passthrough.
|
||||
@@ -138,7 +142,7 @@ where
|
||||
(**self).post_tool_use_response(call_id, payload)
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> JsonValue {
|
||||
fn code_mode_result(&self, payload: &ToolPayload) -> CodeModeToolResult {
|
||||
(**self).code_mode_result(payload)
|
||||
}
|
||||
|
||||
@@ -214,8 +218,8 @@ impl ToolOutput for JsonToolOutput {
|
||||
Some(self.value.clone())
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
self.value.clone()
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
CodeModeToolResult::from(self.value.clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,15 +241,20 @@ impl ToolOutput for codex_protocol::mcp::CallToolResult {
|
||||
}
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
let mut result = serde_json::to_value(self).unwrap_or_else(|err| {
|
||||
JsonValue::String(format!("failed to serialize mcp result: {err}"))
|
||||
});
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> CodeModeToolResult {
|
||||
let mut result = match serde_json::to_value(self) {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
return CodeModeToolResult::Json(JsonValue::String(format!(
|
||||
"failed to serialize mcp result: {err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
// MCP result metadata is private to clients and must not reach Code Mode.
|
||||
if let JsonValue::Object(fields) = &mut result {
|
||||
fields.remove("_meta");
|
||||
}
|
||||
result
|
||||
CodeModeToolResult::McpCallToolResult(result)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user