Remove async-trait from ToolExecutor

This commit is contained in:
jif-oai
2026-06-10 14:38:10 +01:00
parent d2f6d23c6c
commit 81509e8d03
56 changed files with 2097 additions and 2117 deletions
-5
View File
@@ -3047,7 +3047,6 @@ name = "codex-goal-extension"
version = "0.0.0"
dependencies = [
"anyhow",
"async-trait",
"chrono",
"codex-analytics",
"codex-core",
@@ -3101,7 +3100,6 @@ dependencies = [
name = "codex-image-generation-extension"
version = "0.0.0"
dependencies = [
"async-trait",
"codex-api",
"codex-core",
"codex-extension-api",
@@ -3301,7 +3299,6 @@ dependencies = [
name = "codex-memories-extension"
version = "0.0.0"
dependencies = [
"async-trait",
"codex-core",
"codex-extension-api",
"codex-features",
@@ -3916,7 +3913,6 @@ dependencies = [
name = "codex-tools"
version = "0.0.0"
dependencies = [
"async-trait",
"codex-app-server-protocol",
"codex-code-mode",
"codex-features",
@@ -4297,7 +4293,6 @@ dependencies = [
name = "codex-web-search-extension"
version = "0.0.0"
dependencies = [
"async-trait",
"codex-api",
"codex-core",
"codex-extension-api",
@@ -91,7 +91,6 @@ impl CodeModeExecuteHandler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for CodeModeExecuteHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain(PUBLIC_TOOL_NAME)
@@ -101,28 +100,27 @@ impl ToolExecutor<ToolInvocation> for CodeModeExecuteHandler {
self.spec.clone()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id,
tool_name,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation {
session,
turn,
call_id,
tool_name,
payload,
..
} = invocation;
match payload {
ToolPayload::Custom { input } if is_exec_tool_name(&tool_name) => self
.execute(session, turn, call_id, input)
.await
.map(boxed_tool_output),
_ => Err(FunctionCallError::RespondToModel(format!(
"{PUBLIC_TOOL_NAME} expects raw JavaScript source text"
))),
}
match payload {
ToolPayload::Custom { input } if is_exec_tool_name(&tool_name) => self
.execute(session, turn, call_id, input)
.await
.map(boxed_tool_output),
_ => Err(FunctionCallError::RespondToModel(format!(
"{PUBLIC_TOOL_NAME} expects raw JavaScript source text"
))),
}
})
}
}
@@ -44,7 +44,6 @@ where
})
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for CodeModeWaitHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain(WAIT_TOOL_NAME)
@@ -54,76 +53,82 @@ impl ToolExecutor<ToolInvocation> for CodeModeWaitHandler {
create_wait_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
tool_name,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
tool_name,
payload,
..
} = invocation;
match payload {
ToolPayload::Function { arguments }
if tool_name.namespace.is_none() && tool_name.name.as_str() == WAIT_TOOL_NAME =>
{
let args: ExecWaitArgs = parse_arguments(&arguments)?;
let exec = ExecContext { session, turn };
let started_at = std::time::Instant::now();
let cell_id = codex_code_mode::CellId::new(args.cell_id);
let wait_response = if args.terminate {
exec.session
.services
.code_mode_service
.terminate(cell_id)
.await
} else {
exec.session
.services
.code_mode_service
.wait(codex_code_mode::WaitRequest {
cell_id,
yield_time_ms: args.yield_time_ms,
})
.await
}
.map_err(FunctionCallError::RespondToModel)?;
if let codex_code_mode::WaitOutcome::LiveCell(response) = &wait_response
&& !matches!(response, codex_code_mode::RuntimeResponse::Yielded { .. })
match payload {
ToolPayload::Function { arguments }
if tool_name.namespace.is_none()
&& tool_name.name.as_str() == WAIT_TOOL_NAME =>
{
// Only a live-cell wait can close a CodeCell. A missing
// cell is still an ordinary `wait` tool result, but there
// is no runtime object for the reducer to complete.
let runtime_cell_id = match response {
codex_code_mode::RuntimeResponse::Yielded { cell_id, .. }
| codex_code_mode::RuntimeResponse::Terminated { cell_id, .. }
| codex_code_mode::RuntimeResponse::Result { cell_id, .. } => cell_id,
};
exec.session
.services
.rollout_thread_trace
.code_cell_trace_context(
exec.turn.sub_id.as_str(),
runtime_cell_id.as_str(),
)
.record_ended(response);
exec.session
.services
.code_mode_service
.finish_cell_dispatch(runtime_cell_id);
}
handle_runtime_response(&exec, wait_response.into(), args.max_tokens, started_at)
let args: ExecWaitArgs = parse_arguments(&arguments)?;
let exec = ExecContext { session, turn };
let started_at = std::time::Instant::now();
let cell_id = codex_code_mode::CellId::new(args.cell_id);
let wait_response = if args.terminate {
exec.session
.services
.code_mode_service
.terminate(cell_id)
.await
} else {
exec.session
.services
.code_mode_service
.wait(codex_code_mode::WaitRequest {
cell_id,
yield_time_ms: args.yield_time_ms,
})
.await
}
.map_err(FunctionCallError::RespondToModel)?;
if let codex_code_mode::WaitOutcome::LiveCell(response) = &wait_response
&& !matches!(response, codex_code_mode::RuntimeResponse::Yielded { .. })
{
// Only a live-cell wait can close a CodeCell. A missing
// cell is still an ordinary `wait` tool result, but there
// is no runtime object for the reducer to complete.
let runtime_cell_id = match response {
codex_code_mode::RuntimeResponse::Yielded { cell_id, .. }
| codex_code_mode::RuntimeResponse::Terminated { cell_id, .. }
| codex_code_mode::RuntimeResponse::Result { cell_id, .. } => cell_id,
};
exec.session
.services
.rollout_thread_trace
.code_cell_trace_context(
exec.turn.sub_id.as_str(),
runtime_cell_id.as_str(),
)
.record_ended(response);
exec.session
.services
.code_mode_service
.finish_cell_dispatch(runtime_cell_id);
}
handle_runtime_response(
&exec,
wait_response.into(),
args.max_tokens,
started_at,
)
.await
.map(boxed_tool_output)
.map_err(FunctionCallError::RespondToModel)
}
_ => Err(FunctionCallError::RespondToModel(format!(
"{WAIT_TOOL_NAME} expects JSON arguments"
))),
}
_ => Err(FunctionCallError::RespondToModel(format!(
"{WAIT_TOOL_NAME} expects JSON arguments"
))),
}
})
}
}
@@ -13,7 +13,6 @@ use super::*;
pub struct ReportAgentJobResultHandler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ReportAgentJobResultHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("report_agent_job_result")
@@ -23,24 +22,24 @@ impl ToolExecutor<ToolInvocation> for ReportAgentJobResultHandler {
create_report_agent_job_result_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session, payload, ..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session, payload, ..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"report_agent_job_result handler received unsupported payload".to_string(),
));
}
};
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"report_agent_job_result handler received unsupported payload".to_string(),
));
}
};
handle(session, arguments).await.map(boxed_tool_output)
handle(session, arguments).await.map(boxed_tool_output)
})
}
}
@@ -14,7 +14,6 @@ use super::*;
pub struct SpawnAgentsOnCsvHandler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for SpawnAgentsOnCsvHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("spawn_agents_on_csv")
@@ -24,29 +23,29 @@ impl ToolExecutor<ToolInvocation> for SpawnAgentsOnCsvHandler {
create_spawn_agents_on_csv_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"agent jobs handler received unsupported payload".to_string(),
));
}
};
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"agent jobs handler received unsupported payload".to_string(),
));
}
};
handle(session, turn, arguments)
.await
.map(boxed_tool_output)
handle(session, turn, arguments)
.await
.map(boxed_tool_output)
})
}
}
+137 -129
View File
@@ -305,7 +305,6 @@ async fn effective_patch_permissions(
)
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ApplyPatchHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("apply_patch")
@@ -315,144 +314,153 @@ impl ToolExecutor<ToolInvocation> for ApplyPatchHandler {
create_apply_patch_freeform_tool(self.multi_environment)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
tracker,
call_id,
tool_name,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation {
session,
turn,
tracker,
call_id,
tool_name,
payload,
..
} = invocation;
let ToolPayload::Custom { input: patch_input } = payload else {
return Err(FunctionCallError::RespondToModel(
"apply_patch handler received unsupported payload".to_string(),
));
};
let args = match codex_apply_patch::parse_patch(&patch_input) {
Ok(args) => args,
Err(parse_error) => {
return Err(FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {parse_error}"
)));
}
};
let selected_environment_id =
require_environment_id(args.environment_id.as_deref(), self.multi_environment)?;
let ToolPayload::Custom { input: patch_input } = payload else {
return Err(FunctionCallError::RespondToModel(
"apply_patch handler received unsupported payload".to_string(),
));
};
let args = match codex_apply_patch::parse_patch(&patch_input) {
Ok(args) => args,
Err(parse_error) => {
return Err(FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {parse_error}"
)));
}
};
let selected_environment_id =
require_environment_id(args.environment_id.as_deref(), self.multi_environment)?;
// Verify the parsed patch against the selected environment filesystem.
let Some(turn_environment) =
resolve_tool_environment(turn.as_ref(), selected_environment_id.as_deref())?
else {
return Err(FunctionCallError::RespondToModel(
"apply_patch is unavailable in this session".to_string(),
));
};
let cwd = turn_environment.cwd.clone();
let fs = turn_environment.environment.get_filesystem();
let sandbox = turn.file_system_sandbox_context(/*additional_permissions*/ None, &cwd);
match codex_apply_patch::verify_apply_patch_args(args, &cwd, fs.as_ref(), Some(&sandbox))
// Verify the parsed patch against the selected environment filesystem.
let Some(turn_environment) =
resolve_tool_environment(turn.as_ref(), selected_environment_id.as_deref())?
else {
return Err(FunctionCallError::RespondToModel(
"apply_patch is unavailable in this session".to_string(),
));
};
let cwd = turn_environment.cwd.clone();
let fs = turn_environment.environment.get_filesystem();
let sandbox =
turn.file_system_sandbox_context(/*additional_permissions*/ None, &cwd);
match codex_apply_patch::verify_apply_patch_args(
args,
&cwd,
fs.as_ref(),
Some(&sandbox),
)
.await
{
codex_apply_patch::MaybeApplyPatchVerified::Body(changes) => {
let (file_paths, effective_additional_permissions, file_system_sandbox_policy) =
effective_patch_permissions(
session.as_ref(),
{
codex_apply_patch::MaybeApplyPatchVerified::Body(changes) => {
let (file_paths, effective_additional_permissions, file_system_sandbox_policy) =
effective_patch_permissions(
session.as_ref(),
turn.as_ref(),
&turn_environment.environment_id,
&changes,
&cwd,
)
.await;
match apply_patch::apply_patch(
turn.as_ref(),
&turn_environment.environment_id,
&changes,
&cwd,
&file_system_sandbox_policy,
changes,
)
.await;
match apply_patch::apply_patch(turn.as_ref(), &file_system_sandbox_policy, changes)
.await
{
InternalApplyPatchInvocation::Output(item) => {
let content = item?;
Ok(boxed_tool_output(ApplyPatchToolOutput::from_text(content)))
}
InternalApplyPatchInvocation::DelegateToRuntime(apply) => {
let changes = convert_apply_patch_to_protocol(&apply.action);
let emitter = ToolEmitter::apply_patch_for_environment(
changes.clone(),
apply.auto_approved,
turn_environment.environment_id.clone(),
);
let event_ctx = ToolEventCtx::new(
session.as_ref(),
turn.as_ref(),
&call_id,
Some(&tracker),
);
emitter.begin(event_ctx).await;
let req = ApplyPatchRequest {
turn_environment: turn_environment.clone(),
action: apply.action,
file_paths,
changes,
exec_approval_requirement: apply.exec_approval_requirement,
additional_permissions: effective_additional_permissions
.additional_permissions,
permissions_preapproved: effective_additional_permissions
.permissions_preapproved,
};
let mut orchestrator = ToolOrchestrator::new();
let mut runtime = ApplyPatchRuntime::new();
let tool_ctx = ToolCtx {
session: session.clone(),
turn: turn.clone(),
call_id: call_id.clone(),
tool_name: tool_name.clone(),
};
let out = orchestrator
.run(
&mut runtime,
&req,
&tool_ctx,
{
InternalApplyPatchInvocation::Output(item) => {
let content = item?;
Ok(boxed_tool_output(ApplyPatchToolOutput::from_text(content)))
}
InternalApplyPatchInvocation::DelegateToRuntime(apply) => {
let changes = convert_apply_patch_to_protocol(&apply.action);
let emitter = ToolEmitter::apply_patch_for_environment(
changes.clone(),
apply.auto_approved,
turn_environment.environment_id.clone(),
);
let event_ctx = ToolEventCtx::new(
session.as_ref(),
turn.as_ref(),
turn.approval_policy.value(),
)
.await
.map(|result| result.output);
let (out, delta) = match out {
Ok(output) => (Ok(output.exec_output), Some(output.delta)),
Err(error) => (Err(error), Some(runtime.committed_delta().clone())),
};
let event_ctx = ToolEventCtx::new(
session.as_ref(),
turn.as_ref(),
&call_id,
Some(&tracker),
);
let content = emitter.finish(event_ctx, out, delta.as_ref()).await?;
Ok(boxed_tool_output(ApplyPatchToolOutput::from_text(content)))
&call_id,
Some(&tracker),
);
emitter.begin(event_ctx).await;
let req = ApplyPatchRequest {
turn_environment: turn_environment.clone(),
action: apply.action,
file_paths,
changes,
exec_approval_requirement: apply.exec_approval_requirement,
additional_permissions: effective_additional_permissions
.additional_permissions,
permissions_preapproved: effective_additional_permissions
.permissions_preapproved,
};
let mut orchestrator = ToolOrchestrator::new();
let mut runtime = ApplyPatchRuntime::new();
let tool_ctx = ToolCtx {
session: session.clone(),
turn: turn.clone(),
call_id: call_id.clone(),
tool_name: tool_name.clone(),
};
let out = orchestrator
.run(
&mut runtime,
&req,
&tool_ctx,
turn.as_ref(),
turn.approval_policy.value(),
)
.await
.map(|result| result.output);
let (out, delta) = match out {
Ok(output) => (Ok(output.exec_output), Some(output.delta)),
Err(error) => (Err(error), Some(runtime.committed_delta().clone())),
};
let event_ctx = ToolEventCtx::new(
session.as_ref(),
turn.as_ref(),
&call_id,
Some(&tracker),
);
let content = emitter.finish(event_ctx, out, delta.as_ref()).await?;
Ok(boxed_tool_output(ApplyPatchToolOutput::from_text(content)))
}
}
}
codex_apply_patch::MaybeApplyPatchVerified::CorrectnessError(parse_error) => {
Err(FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {parse_error}"
)))
}
codex_apply_patch::MaybeApplyPatchVerified::ShellParseError(error) => {
tracing::trace!("Failed to parse apply_patch input, {error:?}");
Err(FunctionCallError::RespondToModel(
"apply_patch handler received invalid patch input".to_string(),
))
}
codex_apply_patch::MaybeApplyPatchVerified::NotApplyPatch => {
Err(FunctionCallError::RespondToModel(
"apply_patch handler received non-apply_patch input".to_string(),
))
}
}
codex_apply_patch::MaybeApplyPatchVerified::CorrectnessError(parse_error) => {
Err(FunctionCallError::RespondToModel(format!(
"apply_patch verification failed: {parse_error}"
)))
}
codex_apply_patch::MaybeApplyPatchVerified::ShellParseError(error) => {
tracing::trace!("Failed to parse apply_patch input, {error:?}");
Err(FunctionCallError::RespondToModel(
"apply_patch handler received invalid patch input".to_string(),
))
}
codex_apply_patch::MaybeApplyPatchVerified::NotApplyPatch => {
Err(FunctionCallError::RespondToModel(
"apply_patch handler received non-apply_patch input".to_string(),
))
}
}
})
}
}
+43 -45
View File
@@ -61,7 +61,6 @@ impl DynamicToolHandler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for DynamicToolHandler {
fn tool_name(&self) -> ToolName {
self.tool_name.clone()
@@ -86,54 +85,53 @@ impl ToolExecutor<ToolInvocation> for DynamicToolHandler {
)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"dynamic tool handler received unsupported payload".to_string(),
));
}
};
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"dynamic tool handler received unsupported payload".to_string(),
));
}
};
let args: Value = parse_arguments(&arguments)?;
let response = request_dynamic_tool(
&session,
turn.as_ref(),
call_id,
self.tool_name.clone(),
args,
)
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(
"dynamic tool call was cancelled before receiving a response".to_string(),
let args: Value = parse_arguments(&arguments)?;
let response = request_dynamic_tool(
&session,
turn.as_ref(),
call_id,
self.tool_name.clone(),
args,
)
})?;
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(
"dynamic tool call was cancelled before receiving a response".to_string(),
)
})?;
let DynamicToolResponse {
content_items,
success,
} = response;
let body = content_items
.into_iter()
.map(FunctionCallOutputContentItem::from)
.collect::<Vec<_>>();
Ok(boxed_tool_output(FunctionToolOutput::from_content(
body,
Some(success),
)))
let DynamicToolResponse {
content_items,
success,
} = response;
let body = content_items
.into_iter()
.map(FunctionCallOutputContentItem::from)
.collect::<Vec<_>>();
Ok(boxed_tool_output(FunctionToolOutput::from_content(
body,
Some(success),
)))
})
}
}
@@ -11,13 +11,11 @@ use codex_tools::ToolSpec;
use codex_tools::TurnItemEmissionFuture;
use codex_tools::TurnItemEmitter;
use crate::function_tool::FunctionCallError;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use crate::stream_events_utils::TurnItemContributorPolicy;
use crate::stream_events_utils::finalize_turn_item;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolOutput;
use crate::tools::context::ToolPayload;
use crate::tools::registry::CoreToolRuntime;
use crate::tools::registry::ToolExecutor;
@@ -30,7 +28,6 @@ impl ExtensionToolAdapter {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ExtensionToolAdapter {
fn tool_name(&self) -> ToolName {
self.0.tool_name()
@@ -52,11 +49,8 @@ impl ToolExecutor<ToolInvocation> for ExtensionToolAdapter {
self.0.search_info()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
self.0.handle(to_extension_call(&invocation).await).await
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move { self.0.handle(to_extension_call(&invocation).await).await })
}
}
@@ -162,7 +156,6 @@ mod tests {
struct StubExtensionExecutor;
#[async_trait::async_trait]
impl codex_extension_api::ToolExecutor<codex_tools::ToolCall> for StubExtensionExecutor {
fn tool_name(&self) -> codex_tools::ToolName {
codex_tools::ToolName::plain("extension_echo")
@@ -187,13 +180,18 @@ mod tests {
})
}
async fn handle(
&self,
fn handle<'a>(
&'a self,
_call: codex_tools::ToolCall,
) -> Result<Box<dyn codex_tools::ToolOutput>, codex_tools::FunctionCallError> {
Ok(Box::new(codex_tools::JsonToolOutput::new(
json!({ "ok": true }),
)))
) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let _invocation = _call;
Ok(
Box::new(codex_tools::JsonToolOutput::new(json!({ "ok": true })))
as Box<dyn codex_tools::ToolOutput>,
)
})
}
}
@@ -201,7 +199,6 @@ mod tests {
captured_call: Arc<Mutex<Option<codex_tools::ToolCall>>>,
}
#[async_trait::async_trait]
impl codex_extension_api::ToolExecutor<codex_tools::ToolCall> for CapturingExtensionExecutor {
fn tool_name(&self) -> codex_tools::ToolName {
codex_tools::ToolName::plain("extension_echo")
@@ -218,24 +215,27 @@ mod tests {
})
}
async fn handle(
&self,
fn handle<'a>(
&'a self,
call: codex_tools::ToolCall,
) -> Result<Box<dyn codex_tools::ToolOutput>, codex_tools::FunctionCallError> {
let item = ExtensionTurnItem::WebSearch(WebSearchItem {
id: call.call_id.clone(),
query: "rust trait object".to_string(),
action: WebSearchAction::Search {
query: Some("rust trait object".to_string()),
queries: None,
},
});
call.turn_item_emitter.emit_started(item.clone()).await;
call.turn_item_emitter.emit_completed(item).await;
*self.captured_call.lock().await = Some(call);
Ok(Box::new(codex_tools::JsonToolOutput::new(
json!({ "ok": true }),
)))
) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let item = ExtensionTurnItem::WebSearch(WebSearchItem {
id: call.call_id.clone(),
query: "rust trait object".to_string(),
action: WebSearchAction::Search {
query: Some("rust trait object".to_string()),
queries: None,
},
});
call.turn_item_emitter.emit_started(item.clone()).await;
call.turn_item_emitter.emit_completed(item).await;
*self.captured_call.lock().await = Some(call);
Ok(
Box::new(codex_tools::JsonToolOutput::new(json!({ "ok": true })))
as Box<dyn codex_tools::ToolOutput>,
)
})
}
}
@@ -432,7 +432,6 @@ mod tests {
);
}
#[async_trait::async_trait]
impl codex_extension_api::ToolExecutor<codex_tools::ToolCall> for ImageGenerationExtensionExecutor {
fn tool_name(&self) -> codex_tools::ToolName {
codex_tools::ToolName::namespaced("image_gen", "imagegen")
@@ -449,35 +448,39 @@ mod tests {
})
}
async fn handle(
&self,
fn handle<'a>(
&'a self,
call: codex_tools::ToolCall,
) -> Result<Box<dyn codex_tools::ToolOutput>, codex_tools::FunctionCallError> {
call.turn_item_emitter
.emit_started(ExtensionTurnItem::ImageGeneration(
codex_protocol::items::ImageGenerationItem {
id: call.call_id.clone(),
status: "in_progress".to_string(),
revised_prompt: None,
result: String::new(),
saved_path: None,
},
))
.await;
call.turn_item_emitter
.emit_completed(ExtensionTurnItem::ImageGeneration(
codex_protocol::items::ImageGenerationItem {
id: call.call_id,
status: "completed".to_string(),
revised_prompt: Some("A tiny blue square".to_string()),
result: "cG5n".to_string(),
saved_path: Some(test_path_buf("/tmp/extension-claimed.png").abs()),
},
))
.await;
Ok(Box::new(codex_tools::JsonToolOutput::new(
json!({ "ok": true }),
)))
) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
call.turn_item_emitter
.emit_started(ExtensionTurnItem::ImageGeneration(
codex_protocol::items::ImageGenerationItem {
id: call.call_id.clone(),
status: "in_progress".to_string(),
revised_prompt: None,
result: String::new(),
saved_path: None,
},
))
.await;
call.turn_item_emitter
.emit_completed(ExtensionTurnItem::ImageGeneration(
codex_protocol::items::ImageGenerationItem {
id: call.call_id,
status: "completed".to_string(),
revised_prompt: Some("A tiny blue square".to_string()),
result: "cG5n".to_string(),
saved_path: Some(test_path_buf("/tmp/extension-claimed.png").abs()),
},
))
.await;
Ok(
Box::new(codex_tools::JsonToolOutput::new(json!({ "ok": true })))
as Box<dyn codex_tools::ToolOutput>,
)
})
}
}
@@ -54,7 +54,6 @@ impl ListAvailablePluginsToInstallHandler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ListAvailablePluginsToInstallHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain(LIST_AVAILABLE_PLUGINS_TO_INSTALL_TOOL_NAME)
@@ -68,30 +67,29 @@ impl ToolExecutor<ToolInvocation> for ListAvailablePluginsToInstallHandler {
false
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation { payload, .. } = invocation;
match payload {
ToolPayload::Function { .. } => {}
_ => {
return Err(FunctionCallError::Fatal(format!(
"{LIST_AVAILABLE_PLUGINS_TO_INSTALL_TOOL_NAME} handler received unsupported payload"
)));
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation { payload, .. } = invocation;
match payload {
ToolPayload::Function { .. } => {}
_ => {
return Err(FunctionCallError::Fatal(format!(
"{LIST_AVAILABLE_PLUGINS_TO_INSTALL_TOOL_NAME} handler received unsupported payload"
)));
}
}
}
let content = serde_json::to_string(&self.result()).map_err(|err| {
let content = serde_json::to_string(&self.result()).map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize {LIST_AVAILABLE_PLUGINS_TO_INSTALL_TOOL_NAME} response: {err}"
))
})?;
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
})
}
}
+38 -38
View File
@@ -64,7 +64,6 @@ fn ensure_mcp_prefix(name: &str) -> String {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for McpHandler {
fn tool_name(&self) -> ToolName {
self.tool_info.canonical_tool_name()
@@ -113,46 +112,47 @@ impl ToolExecutor<ToolInvocation> for McpHandler {
)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
let payload = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"mcp handler received unsupported payload".to_string(),
));
}
};
let payload = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"mcp handler received unsupported payload".to_string(),
));
}
};
let started = Instant::now();
let result = handle_mcp_tool_call(
Arc::clone(&session),
&turn,
call_id.clone(),
self.tool_info.server_name.clone(),
self.tool_info.tool.name.to_string(),
self.hook_tool_name(),
payload,
)
.await;
let started = Instant::now();
let result = handle_mcp_tool_call(
Arc::clone(&session),
&turn,
call_id.clone(),
self.tool_info.server_name.clone(),
self.tool_info.tool.name.to_string(),
self.hook_tool_name(),
payload,
)
.await;
Ok(boxed_tool_output(McpToolOutput {
result: result.result,
tool_input: result.tool_input,
wall_time: started.elapsed(),
original_image_detail_supported: can_request_original_image_detail(&turn.model_info),
truncation_policy: turn.truncation_policy,
}))
Ok(boxed_tool_output(McpToolOutput {
result: result.result,
tool_input: result.tool_input,
wall_time: started.elapsed(),
original_image_detail_supported: can_request_original_image_detail(
&turn.model_info,
),
truncation_policy: turn.truncation_policy,
}))
})
}
}
@@ -26,7 +26,6 @@ use super::serialize_function_output;
pub struct ListMcpResourceTemplatesHandler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ListMcpResourceTemplatesHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("list_mcp_resource_templates")
@@ -44,95 +43,110 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourceTemplatesHandler {
clippy::await_holding_invalid_type,
reason = "MCP resource template listing reads through the session-owned manager guard"
)]
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"list_mcp_resource_templates handler received unsupported payload".to_string(),
));
}
};
let arguments = parse_arguments(arguments.as_str())?;
let args: ListResourceTemplatesArgs = parse_args_with_default(arguments.clone())?;
let ListResourceTemplatesArgs { server, cursor } = args;
let server = normalize_optional_string(server);
let cursor = normalize_optional_string(cursor);
let invocation = McpInvocation {
server: server.clone().unwrap_or_else(|| "codex".to_string()),
tool: "list_mcp_resource_templates".to_string(),
arguments: arguments.clone(),
};
emit_tool_call_begin(&session, turn.as_ref(), &call_id, invocation.clone()).await;
let start = Instant::now();
let payload_result: Result<ListResourceTemplatesPayload, FunctionCallError> = async {
if let Some(server_name) = server.clone() {
let params = cursor
.clone()
.map(|value| PaginatedRequestParams::default().with_cursor(Some(value)));
let result = session
.list_resource_templates(&server_name, params)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!(
"resources/templates/list failed: {err:#}"
))
})?;
Ok(ListResourceTemplatesPayload::from_single_server(
server_name,
result,
))
} else {
if cursor.is_some() {
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"cursor can only be used when a server is specified".to_string(),
"list_mcp_resource_templates handler received unsupported payload"
.to_string(),
));
}
};
let templates = session
.services
.mcp_connection_manager
.read()
.await
.list_all_resource_templates()
.await;
Ok(ListResourceTemplatesPayload::from_all_servers(templates))
}
}
.await;
let arguments = parse_arguments(arguments.as_str())?;
let args: ListResourceTemplatesArgs = parse_args_with_default(arguments.clone())?;
let ListResourceTemplatesArgs { server, cursor } = args;
let server = normalize_optional_string(server);
let cursor = normalize_optional_string(cursor);
match payload_result {
Ok(payload) => match serialize_function_output(payload, turn.truncation_policy) {
Ok(output) => {
let content = function_call_output_content_items_to_text(&output.body)
.unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(&content, output.success)),
)
.await;
Ok(boxed_tool_output(output))
let invocation = McpInvocation {
server: server.clone().unwrap_or_else(|| "codex".to_string()),
tool: "list_mcp_resource_templates".to_string(),
arguments: arguments.clone(),
};
emit_tool_call_begin(&session, turn.as_ref(), &call_id, invocation.clone()).await;
let start = Instant::now();
let payload_result: Result<ListResourceTemplatesPayload, FunctionCallError> = async {
if let Some(server_name) = server.clone() {
let params = cursor
.clone()
.map(|value| PaginatedRequestParams::default().with_cursor(Some(value)));
let result = session
.list_resource_templates(&server_name, params)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!(
"resources/templates/list failed: {err:#}"
))
})?;
Ok(ListResourceTemplatesPayload::from_single_server(
server_name,
result,
))
} else {
if cursor.is_some() {
return Err(FunctionCallError::RespondToModel(
"cursor can only be used when a server is specified".to_string(),
));
}
let templates = session
.services
.mcp_connection_manager
.read()
.await
.list_all_resource_templates()
.await;
Ok(ListResourceTemplatesPayload::from_all_servers(templates))
}
}
.await;
match payload_result {
Ok(payload) => match serialize_function_output(payload, turn.truncation_policy) {
Ok(output) => {
let content = function_call_output_content_items_to_text(&output.body)
.unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(&content, output.success)),
)
.await;
Ok(boxed_tool_output(output))
}
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Err(message.clone()),
)
.await;
Err(err)
}
},
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
@@ -147,22 +161,8 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourceTemplatesHandler {
.await;
Err(err)
}
},
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Err(message.clone()),
)
.await;
Err(err)
}
}
})
}
}
@@ -26,7 +26,6 @@ use super::serialize_function_output;
pub struct ListMcpResourcesHandler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ListMcpResourcesHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("list_mcp_resources")
@@ -44,93 +43,110 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourcesHandler {
clippy::await_holding_invalid_type,
reason = "MCP resource listing reads through the session-owned manager guard"
)]
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"list_mcp_resources handler received unsupported payload".to_string(),
));
}
};
let arguments = parse_arguments(arguments.as_str())?;
let args: ListResourcesArgs = parse_args_with_default(arguments.clone())?;
let ListResourcesArgs { server, cursor } = args;
let server = normalize_optional_string(server);
let cursor = normalize_optional_string(cursor);
let invocation = McpInvocation {
server: server.clone().unwrap_or_else(|| "codex".to_string()),
tool: "list_mcp_resources".to_string(),
arguments: arguments.clone(),
};
emit_tool_call_begin(&session, turn.as_ref(), &call_id, invocation.clone()).await;
let start = Instant::now();
let payload_result: Result<ListResourcesPayload, FunctionCallError> = async {
if let Some(server_name) = server.clone() {
let params = cursor
.clone()
.map(|value| PaginatedRequestParams::default().with_cursor(Some(value)));
let result = session
.list_resources(&server_name, params)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("resources/list failed: {err:#}"))
})?;
Ok(ListResourcesPayload::from_single_server(
server_name,
result,
))
} else {
if cursor.is_some() {
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"cursor can only be used when a server is specified".to_string(),
"list_mcp_resources handler received unsupported payload".to_string(),
));
}
};
let resources = session
.services
.mcp_connection_manager
.read()
.await
.list_all_resources()
.await;
Ok(ListResourcesPayload::from_all_servers(resources))
}
}
.await;
let arguments = parse_arguments(arguments.as_str())?;
let args: ListResourcesArgs = parse_args_with_default(arguments.clone())?;
let ListResourcesArgs { server, cursor } = args;
let server = normalize_optional_string(server);
let cursor = normalize_optional_string(cursor);
match payload_result {
Ok(payload) => match serialize_function_output(payload, turn.truncation_policy) {
Ok(output) => {
let content = function_call_output_content_items_to_text(&output.body)
.unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(&content, output.success)),
)
.await;
Ok(boxed_tool_output(output))
let invocation = McpInvocation {
server: server.clone().unwrap_or_else(|| "codex".to_string()),
tool: "list_mcp_resources".to_string(),
arguments: arguments.clone(),
};
emit_tool_call_begin(&session, turn.as_ref(), &call_id, invocation.clone()).await;
let start = Instant::now();
let payload_result: Result<ListResourcesPayload, FunctionCallError> = async {
if let Some(server_name) = server.clone() {
let params = cursor
.clone()
.map(|value| PaginatedRequestParams::default().with_cursor(Some(value)));
let result =
session
.list_resources(&server_name, params)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!(
"resources/list failed: {err:#}"
))
})?;
Ok(ListResourcesPayload::from_single_server(
server_name,
result,
))
} else {
if cursor.is_some() {
return Err(FunctionCallError::RespondToModel(
"cursor can only be used when a server is specified".to_string(),
));
}
let resources = session
.services
.mcp_connection_manager
.read()
.await
.list_all_resources()
.await;
Ok(ListResourcesPayload::from_all_servers(resources))
}
}
.await;
match payload_result {
Ok(payload) => match serialize_function_output(payload, turn.truncation_policy) {
Ok(output) => {
let content = function_call_output_content_items_to_text(&output.body)
.unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(&content, output.success)),
)
.await;
Ok(boxed_tool_output(output))
}
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Err(message.clone()),
)
.await;
Err(err)
}
},
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
@@ -145,22 +161,8 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourcesHandler {
.await;
Err(err)
}
},
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Err(message.clone()),
)
.await;
Err(err)
}
}
})
}
}
@@ -26,7 +26,6 @@ use super::serialize_function_output;
pub struct ReadMcpResourceHandler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ReadMcpResourceHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("read_mcp_resource")
@@ -40,75 +39,89 @@ impl ToolExecutor<ToolInvocation> for ReadMcpResourceHandler {
true
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"read_mcp_resource handler received unsupported payload".to_string(),
));
}
};
let arguments = parse_arguments(arguments.as_str())?;
let args: ReadResourceArgs = parse_args(arguments.clone())?;
let ReadResourceArgs { server, uri } = args;
let server = normalize_required_string("server", server)?;
let uri = normalize_required_string("uri", uri)?;
let invocation = McpInvocation {
server: server.clone(),
tool: "read_mcp_resource".to_string(),
arguments: arguments.clone(),
};
emit_tool_call_begin(&session, turn.as_ref(), &call_id, invocation.clone()).await;
let start = Instant::now();
let payload_result: Result<ReadResourcePayload, FunctionCallError> = async {
let result = session
.read_resource(&server, ReadResourceRequestParams::new(uri.clone()))
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("resources/read failed: {err:#}"))
})?;
Ok(ReadResourcePayload {
server,
uri,
result,
})
}
.await;
match payload_result {
Ok(payload) => match serialize_function_output(payload, turn.truncation_policy) {
Ok(output) => {
let content = function_call_output_content_items_to_text(&output.body)
.unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(&content, output.success)),
)
.await;
Ok(boxed_tool_output(output))
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"read_mcp_resource handler received unsupported payload".to_string(),
));
}
};
let arguments = parse_arguments(arguments.as_str())?;
let args: ReadResourceArgs = parse_args(arguments.clone())?;
let ReadResourceArgs { server, uri } = args;
let server = normalize_required_string("server", server)?;
let uri = normalize_required_string("uri", uri)?;
let invocation = McpInvocation {
server: server.clone(),
tool: "read_mcp_resource".to_string(),
arguments: arguments.clone(),
};
emit_tool_call_begin(&session, turn.as_ref(), &call_id, invocation.clone()).await;
let start = Instant::now();
let payload_result: Result<ReadResourcePayload, FunctionCallError> = async {
let result = session
.read_resource(&server, ReadResourceRequestParams::new(uri.clone()))
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("resources/read failed: {err:#}"))
})?;
Ok(ReadResourcePayload {
server,
uri,
result,
})
}
.await;
match payload_result {
Ok(payload) => match serialize_function_output(payload, turn.truncation_policy) {
Ok(output) => {
let content = function_call_output_content_items_to_text(&output.body)
.unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(&content, output.success)),
)
.await;
Ok(boxed_tool_output(output))
}
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Err(message.clone()),
)
.await;
Err(err)
}
},
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
@@ -123,22 +136,8 @@ impl ToolExecutor<ToolInvocation> for ReadMcpResourceHandler {
.await;
Err(err)
}
},
Err(err) => {
let duration = start.elapsed();
let message = err.to_string();
emit_tool_call_end(
&session,
turn.as_ref(),
&call_id,
invocation,
duration,
Err(message.clone()),
)
.await;
Err(err)
}
}
})
}
}
@@ -6,7 +6,6 @@ use codex_tools::ToolSpec;
pub(crate) struct Handler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(MULTI_AGENT_V1_NAMESPACE, "close_agent")
@@ -23,11 +22,11 @@ impl ToolExecutor<ToolInvocation> for Handler {
)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
handle_close_agent(invocation).await.map(boxed_tool_output)
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
handle_close_agent(invocation).await.map(boxed_tool_output)
})
}
}
@@ -7,7 +7,6 @@ use std::sync::Arc;
pub(crate) struct Handler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(MULTI_AGENT_V1_NAMESPACE, "resume_agent")
@@ -24,11 +23,11 @@ impl ToolExecutor<ToolInvocation> for Handler {
)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
handle_resume_agent(invocation).await.map(boxed_tool_output)
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
handle_resume_agent(invocation).await.map(boxed_tool_output)
})
}
}
@@ -6,7 +6,6 @@ use codex_tools::ToolSpec;
pub(crate) struct Handler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(MULTI_AGENT_V1_NAMESPACE, "send_input")
@@ -23,86 +22,86 @@ impl ToolExecutor<ToolInvocation> for Handler {
)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: SendInputArgs = parse_arguments(&arguments)?;
let receiver_thread_id = parse_agent_id_target(&args.target)?;
let input_items = parse_collab_input(args.message, args.items)?;
let prompt = render_input_preview(&input_items);
let receiver_agent = session
.services
.agent_control
.get_agent_metadata(receiver_thread_id);
if receiver_agent.is_some() {
let resume_config = build_agent_resume_config(turn.as_ref())?;
session
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: SendInputArgs = parse_arguments(&arguments)?;
let receiver_thread_id = parse_agent_id_target(&args.target)?;
let input_items = parse_collab_input(args.message, args.items)?;
let prompt = render_input_preview(&input_items);
let receiver_agent = session
.services
.agent_control
.ensure_v2_agent_loaded(resume_config, receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
}
let receiver_agent = receiver_agent.unwrap_or_default();
if args.interrupt {
.get_agent_metadata(receiver_thread_id);
if receiver_agent.is_some() {
let resume_config = build_agent_resume_config(turn.as_ref())?;
session
.services
.agent_control
.ensure_v2_agent_loaded(resume_config, receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
}
let receiver_agent = receiver_agent.unwrap_or_default();
if args.interrupt {
session
.services
.agent_control
.interrupt_agent(receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
}
session
.send_event(
&turn,
CollabAgentInteractionBeginEvent {
call_id: call_id.clone(),
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id,
prompt: prompt.clone(),
}
.into(),
)
.await;
let agent_control = session.services.agent_control.clone();
let result = agent_control
.send_input(receiver_thread_id, input_items)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err));
let status = session
.services
.agent_control
.interrupt_agent(receiver_thread_id)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
}
session
.send_event(
&turn,
CollabAgentInteractionBeginEvent {
call_id: call_id.clone(),
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id,
prompt: prompt.clone(),
}
.into(),
)
.await;
let agent_control = session.services.agent_control.clone();
let result = agent_control
.send_input(receiver_thread_id, input_items)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err));
let status = session
.services
.agent_control
.get_status(receiver_thread_id)
.await;
session
.send_event(
&turn,
CollabAgentInteractionEndEvent {
call_id,
completed_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id,
receiver_agent_nickname: receiver_agent.agent_nickname,
receiver_agent_role: receiver_agent.agent_role,
prompt,
status,
}
.into(),
)
.await;
let submission_id = result?;
.get_status(receiver_thread_id)
.await;
session
.send_event(
&turn,
CollabAgentInteractionEndEvent {
call_id,
completed_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_id,
receiver_agent_nickname: receiver_agent.agent_nickname,
receiver_agent_role: receiver_agent.agent_role,
prompt,
status,
}
.into(),
)
.await;
let submission_id = result?;
Ok(boxed_tool_output(SendInputResult { submission_id }))
Ok(boxed_tool_output(SendInputResult { submission_id }))
})
}
}
@@ -22,7 +22,6 @@ impl Handler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(MULTI_AGENT_V1_NAMESPACE, "spawn_agent")
@@ -39,11 +38,11 @@ impl ToolExecutor<ToolInvocation> for Handler {
)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
handle_spawn_agent(invocation).await.map(boxed_tool_output)
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
handle_spawn_agent(invocation).await.map(boxed_tool_output)
})
}
}
@@ -27,7 +27,6 @@ impl Handler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(MULTI_AGENT_V1_NAMESPACE, "wait_agent")
@@ -44,168 +43,168 @@ impl ToolExecutor<ToolInvocation> for Handler {
)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: WaitArgs = parse_arguments(&arguments)?;
let receiver_thread_ids = parse_agent_id_targets(args.targets)?;
let mut receiver_agents = Vec::with_capacity(receiver_thread_ids.len());
let mut target_by_thread_id = HashMap::with_capacity(receiver_thread_ids.len());
for receiver_thread_id in &receiver_thread_ids {
let agent_metadata = session
.services
.agent_control
.get_agent_metadata(*receiver_thread_id)
.unwrap_or_default();
target_by_thread_id.insert(
*receiver_thread_id,
agent_metadata
.agent_path
.as_ref()
.map(ToString::to_string)
.unwrap_or_else(|| receiver_thread_id.to_string()),
);
receiver_agents.push(CollabAgentRef {
thread_id: *receiver_thread_id,
agent_nickname: agent_metadata.agent_nickname,
agent_role: agent_metadata.agent_role,
});
}
let timeout_ms = args.timeout_ms.unwrap_or(DEFAULT_WAIT_TIMEOUT_MS);
let timeout_ms = match timeout_ms {
ms if ms <= 0 => {
return Err(FunctionCallError::RespondToModel(
"timeout_ms must be greater than zero".to_owned(),
));
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: WaitArgs = parse_arguments(&arguments)?;
let receiver_thread_ids = parse_agent_id_targets(args.targets)?;
let mut receiver_agents = Vec::with_capacity(receiver_thread_ids.len());
let mut target_by_thread_id = HashMap::with_capacity(receiver_thread_ids.len());
for receiver_thread_id in &receiver_thread_ids {
let agent_metadata = session
.services
.agent_control
.get_agent_metadata(*receiver_thread_id)
.unwrap_or_default();
target_by_thread_id.insert(
*receiver_thread_id,
agent_metadata
.agent_path
.as_ref()
.map(ToString::to_string)
.unwrap_or_else(|| receiver_thread_id.to_string()),
);
receiver_agents.push(CollabAgentRef {
thread_id: *receiver_thread_id,
agent_nickname: agent_metadata.agent_nickname,
agent_role: agent_metadata.agent_role,
});
}
ms => ms.clamp(MIN_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),
};
session
.send_event(
&turn,
CollabWaitingBeginEvent {
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_ids: receiver_thread_ids.clone(),
receiver_agents: receiver_agents.clone(),
call_id: call_id.clone(),
let timeout_ms = args.timeout_ms.unwrap_or(DEFAULT_WAIT_TIMEOUT_MS);
let timeout_ms = match timeout_ms {
ms if ms <= 0 => {
return Err(FunctionCallError::RespondToModel(
"timeout_ms must be greater than zero".to_owned(),
));
}
.into(),
)
.await;
ms => ms.clamp(MIN_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),
};
let mut status_rxs = Vec::with_capacity(receiver_thread_ids.len());
let mut initial_final_statuses = Vec::new();
for id in &receiver_thread_ids {
match session.services.agent_control.subscribe_status(*id).await {
Ok(rx) => {
let status = rx.borrow().clone();
if is_final(&status) {
initial_final_statuses.push((*id, status));
session
.send_event(
&turn,
CollabWaitingBeginEvent {
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_ids: receiver_thread_ids.clone(),
receiver_agents: receiver_agents.clone(),
call_id: call_id.clone(),
}
status_rxs.push((*id, rx));
}
Err(CodexErr::ThreadNotFound(_)) => {
initial_final_statuses.push((*id, AgentStatus::NotFound));
}
Err(err) => {
let mut statuses = HashMap::with_capacity(1);
statuses.insert(*id, session.services.agent_control.get_status(*id).await);
session
.send_event(
&turn,
CollabWaitingEndEvent {
sender_thread_id: session.thread_id,
call_id: call_id.clone(),
completed_at_ms: now_unix_timestamp_ms(),
agent_statuses: build_wait_agent_statuses(
&statuses,
&receiver_agents,
),
statuses,
}
.into(),
)
.await;
return Err(collab_agent_error(*id, err));
}
}
}
.into(),
)
.await;
let statuses = if !initial_final_statuses.is_empty() {
initial_final_statuses
} else {
let mut futures = FuturesUnordered::new();
for (id, rx) in status_rxs.into_iter() {
let session = session.clone();
futures.push(wait_for_final_status(session, id, rx));
}
let mut results = Vec::new();
let deadline = Instant::now() + Duration::from_millis(timeout_ms as u64);
loop {
match timeout_at(deadline, futures.next()).await {
Ok(Some(Some(result))) => {
results.push(result);
break;
let mut status_rxs = Vec::with_capacity(receiver_thread_ids.len());
let mut initial_final_statuses = Vec::new();
for id in &receiver_thread_ids {
match session.services.agent_control.subscribe_status(*id).await {
Ok(rx) => {
let status = rx.borrow().clone();
if is_final(&status) {
initial_final_statuses.push((*id, status));
}
status_rxs.push((*id, rx));
}
Err(CodexErr::ThreadNotFound(_)) => {
initial_final_statuses.push((*id, AgentStatus::NotFound));
}
Err(err) => {
let mut statuses = HashMap::with_capacity(1);
statuses.insert(*id, session.services.agent_control.get_status(*id).await);
session
.send_event(
&turn,
CollabWaitingEndEvent {
sender_thread_id: session.thread_id,
call_id: call_id.clone(),
completed_at_ms: now_unix_timestamp_ms(),
agent_statuses: build_wait_agent_statuses(
&statuses,
&receiver_agents,
),
statuses,
}
.into(),
)
.await;
return Err(collab_agent_error(*id, err));
}
Ok(Some(None)) => continue,
Ok(None) | Err(_) => break,
}
}
if !results.is_empty() {
let statuses = if !initial_final_statuses.is_empty() {
initial_final_statuses
} else {
let mut futures = FuturesUnordered::new();
for (id, rx) in status_rxs.into_iter() {
let session = session.clone();
futures.push(wait_for_final_status(session, id, rx));
}
let mut results = Vec::new();
let deadline = Instant::now() + Duration::from_millis(timeout_ms as u64);
loop {
match futures.next().now_or_never() {
Some(Some(Some(result))) => results.push(result),
Some(Some(None)) => continue,
Some(None) | None => break,
match timeout_at(deadline, futures.next()).await {
Ok(Some(Some(result))) => {
results.push(result);
break;
}
Ok(Some(None)) => continue,
Ok(None) | Err(_) => break,
}
}
}
results
};
let timed_out = statuses.is_empty();
let statuses_by_id = statuses.clone().into_iter().collect::<HashMap<_, _>>();
let agent_statuses = build_wait_agent_statuses(&statuses_by_id, &receiver_agents);
let result = WaitAgentResult {
status: statuses
.into_iter()
.filter_map(|(thread_id, status)| {
target_by_thread_id
.get(&thread_id)
.cloned()
.map(|target| (target, status))
})
.collect(),
timed_out,
};
session
.send_event(
&turn,
CollabWaitingEndEvent {
sender_thread_id: session.thread_id,
call_id,
completed_at_ms: now_unix_timestamp_ms(),
agent_statuses,
statuses: statuses_by_id,
if !results.is_empty() {
loop {
match futures.next().now_or_never() {
Some(Some(Some(result))) => results.push(result),
Some(Some(None)) => continue,
Some(None) | None => break,
}
}
}
.into(),
)
.await;
results
};
Ok(boxed_tool_output(result))
let timed_out = statuses.is_empty();
let statuses_by_id = statuses.clone().into_iter().collect::<HashMap<_, _>>();
let agent_statuses = build_wait_agent_statuses(&statuses_by_id, &receiver_agents);
let result = WaitAgentResult {
status: statuses
.into_iter()
.filter_map(|(thread_id, status)| {
target_by_thread_id
.get(&thread_id)
.cloned()
.map(|target| (target, status))
})
.collect(),
timed_out,
};
session
.send_event(
&turn,
CollabWaitingEndEvent {
sender_thread_id: session.thread_id,
call_id,
completed_at_ms: now_unix_timestamp_ms(),
agent_statuses,
statuses: statuses_by_id,
}
.into(),
)
.await;
Ok(boxed_tool_output(result))
})
}
}
@@ -7,7 +7,6 @@ use codex_tools::ToolSpec;
pub(crate) struct Handler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::plain("followup_task")
@@ -17,20 +16,20 @@ impl ToolExecutor<ToolInvocation> for Handler {
create_followup_task_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let arguments = function_arguments(invocation.payload.clone())?;
let args: FollowupTaskArgs = parse_arguments(&arguments)?;
handle_message_string_tool(
invocation,
MessageDeliveryMode::TriggerTurn,
args.target,
args.message,
)
.await
.map(boxed_tool_output)
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let arguments = function_arguments(invocation.payload.clone())?;
let args: FollowupTaskArgs = parse_arguments(&arguments)?;
handle_message_string_tool(
invocation,
MessageDeliveryMode::TriggerTurn,
args.target,
args.message,
)
.await
.map(boxed_tool_output)
})
}
}
@@ -6,7 +6,6 @@ use codex_tools::ToolSpec;
pub(crate) struct Handler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::plain("interrupt_agent")
@@ -16,13 +15,13 @@ impl ToolExecutor<ToolInvocation> for Handler {
create_interrupt_agent_tool_v2()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
handle_interrupt_agent(invocation)
.await
.map(boxed_tool_output)
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
handle_interrupt_agent(invocation)
.await
.map(boxed_tool_output)
})
}
}
@@ -5,7 +5,6 @@ use codex_tools::ToolSpec;
pub(crate) struct Handler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::plain("list_agents")
@@ -15,30 +14,30 @@ impl ToolExecutor<ToolInvocation> for Handler {
create_list_agents_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: ListAgentsArgs = parse_arguments(&arguments)?;
session
.services
.agent_control
.register_session_root(session.thread_id, turn.parent_thread_id);
let agents = session
.services
.agent_control
.list_agents(&turn.session_source, args.path_prefix.as_deref())
.await
.map_err(collab_spawn_error)?;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
payload,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: ListAgentsArgs = parse_arguments(&arguments)?;
session
.services
.agent_control
.register_session_root(session.thread_id, turn.parent_thread_id);
let agents = session
.services
.agent_control
.list_agents(&turn.session_source, args.path_prefix.as_deref())
.await
.map_err(collab_spawn_error)?;
Ok(boxed_tool_output(ListAgentsResult { agents }))
Ok(boxed_tool_output(ListAgentsResult { agents }))
})
}
}
@@ -7,7 +7,6 @@ use codex_tools::ToolSpec;
pub(crate) struct Handler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::plain("send_message")
@@ -17,20 +16,20 @@ impl ToolExecutor<ToolInvocation> for Handler {
create_send_message_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let arguments = function_arguments(invocation.payload.clone())?;
let args: SendMessageArgs = parse_arguments(&arguments)?;
handle_message_string_tool(
invocation,
MessageDeliveryMode::QueueOnly,
args.target,
args.message,
)
.await
.map(boxed_tool_output)
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let arguments = function_arguments(invocation.payload.clone())?;
let args: SendMessageArgs = parse_arguments(&arguments)?;
handle_message_string_tool(
invocation,
MessageDeliveryMode::QueueOnly,
args.target,
args.message,
)
.await
.map(boxed_tool_output)
})
}
}
@@ -22,7 +22,6 @@ impl Handler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::plain("spawn_agent")
@@ -32,11 +31,11 @@ impl ToolExecutor<ToolInvocation> for Handler {
create_spawn_agent_tool_v2(self.options.clone())
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
handle_spawn_agent(invocation).await.map(boxed_tool_output)
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
handle_spawn_agent(invocation).await.map(boxed_tool_output)
})
}
}
@@ -19,7 +19,6 @@ impl Handler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for Handler {
fn tool_name(&self) -> ToolName {
ToolName::plain("wait_agent")
@@ -29,72 +28,72 @@ impl ToolExecutor<ToolInvocation> for Handler {
create_wait_agent_tool_v2(self.options)
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: WaitArgs = parse_arguments(&arguments)?;
let min_timeout_ms = turn.config.multi_agent_v2.min_wait_timeout_ms;
let max_timeout_ms = turn.config.multi_agent_v2.max_wait_timeout_ms;
let default_timeout_ms = turn.config.multi_agent_v2.default_wait_timeout_ms;
let timeout_ms = match args.timeout_ms {
Some(ms) if ms < min_timeout_ms => {
return Err(FunctionCallError::RespondToModel(format!(
"timeout_ms must be at least {min_timeout_ms}"
)));
}
Some(ms) if ms > max_timeout_ms => {
return Err(FunctionCallError::RespondToModel(format!(
"timeout_ms must be at most {max_timeout_ms}"
)));
}
Some(ms) => ms,
None => default_timeout_ms,
};
let mut mailbox_rx = session.input_queue.subscribe_mailbox().await;
session
.send_event(
&turn,
CollabWaitingBeginEvent {
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_ids: Vec::new(),
receiver_agents: Vec::new(),
call_id: call_id.clone(),
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: WaitArgs = parse_arguments(&arguments)?;
let min_timeout_ms = turn.config.multi_agent_v2.min_wait_timeout_ms;
let max_timeout_ms = turn.config.multi_agent_v2.max_wait_timeout_ms;
let default_timeout_ms = turn.config.multi_agent_v2.default_wait_timeout_ms;
let timeout_ms = match args.timeout_ms {
Some(ms) if ms < min_timeout_ms => {
return Err(FunctionCallError::RespondToModel(format!(
"timeout_ms must be at least {min_timeout_ms}"
)));
}
.into(),
)
.await;
let deadline = Instant::now() + Duration::from_millis(timeout_ms as u64);
let timed_out = !wait_for_mailbox_change(&mut mailbox_rx, deadline).await;
let result = WaitAgentResult::from_timed_out(timed_out);
session
.send_event(
&turn,
CollabWaitingEndEvent {
sender_thread_id: session.thread_id,
call_id,
completed_at_ms: now_unix_timestamp_ms(),
agent_statuses: Vec::new(),
statuses: HashMap::new(),
Some(ms) if ms > max_timeout_ms => {
return Err(FunctionCallError::RespondToModel(format!(
"timeout_ms must be at most {max_timeout_ms}"
)));
}
.into(),
)
.await;
Some(ms) => ms,
None => default_timeout_ms,
};
Ok(boxed_tool_output(result))
let mut mailbox_rx = session.input_queue.subscribe_mailbox().await;
session
.send_event(
&turn,
CollabWaitingBeginEvent {
started_at_ms: now_unix_timestamp_ms(),
sender_thread_id: session.thread_id,
receiver_thread_ids: Vec::new(),
receiver_agents: Vec::new(),
call_id: call_id.clone(),
}
.into(),
)
.await;
let deadline = Instant::now() + Duration::from_millis(timeout_ms as u64);
let timed_out = !wait_for_mailbox_change(&mut mailbox_rx, deadline).await;
let result = WaitAgentResult::from_timed_out(timed_out);
session
.send_event(
&turn,
CollabWaitingEndEvent {
sender_thread_id: session.thread_id,
call_id,
completed_at_ms: now_unix_timestamp_ms(),
agent_statuses: Vec::new(),
statuses: HashMap::new(),
}
.into(),
)
.await;
Ok(boxed_tool_output(result))
})
}
}
+28 -28
View File
@@ -45,7 +45,6 @@ impl ToolOutput for PlanToolOutput {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for PlanHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("update_plan")
@@ -55,39 +54,40 @@ impl ToolExecutor<ToolInvocation> for PlanHandler {
create_update_plan_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id: _,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
call_id: _,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"update_plan handler received unsupported payload".to_string(),
));
}
};
if turn.collaboration_mode.mode == ModeKind::Plan {
return Err(FunctionCallError::RespondToModel(
"update_plan handler received unsupported payload".to_string(),
"update_plan is a TODO/checklist tool and is not allowed in Plan mode"
.to_string(),
));
}
};
if turn.collaboration_mode.mode == ModeKind::Plan {
return Err(FunctionCallError::RespondToModel(
"update_plan is a TODO/checklist tool and is not allowed in Plan mode".to_string(),
));
}
let args = parse_update_plan_arguments(&arguments)?;
session
.send_event(turn.as_ref(), EventMsg::PlanUpdate(args))
.await;
let args = parse_update_plan_arguments(&arguments)?;
session
.send_event(turn.as_ref(), EventMsg::PlanUpdate(args))
.await;
Ok(boxed_tool_output(PlanToolOutput))
Ok(boxed_tool_output(PlanToolOutput))
})
}
}
@@ -25,7 +25,6 @@ struct RequestPermissionsEnvironmentArgs {
environment_id: Option<String>,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for RequestPermissionsHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("request_permissions")
@@ -35,72 +34,74 @@ impl ToolExecutor<ToolInvocation> for RequestPermissionsHandler {
create_request_permissions_tool(request_permissions_tool_description())
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
cancellation_token,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
cancellation_token,
call_id,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"request_permissions handler received unsupported payload".to_string(),
));
}
};
let environment_args: RequestPermissionsEnvironmentArgs = parse_arguments(&arguments)?;
let Some(turn_environment) = resolve_tool_environment(
turn.as_ref(),
environment_args.environment_id.as_deref(),
)?
else {
return Err(FunctionCallError::RespondToModel(
"request_permissions handler received unsupported payload".to_string(),
"request_permissions requires a primary environment".to_string(),
));
};
let mut args: RequestPermissionsArgs =
parse_arguments_with_base_path(&arguments, &turn_environment.cwd)?;
args.permissions = normalize_additional_permissions(args.permissions.into())
.map(codex_protocol::request_permissions::RequestPermissionProfile::from)
.map_err(FunctionCallError::RespondToModel)?;
if args.permissions.is_empty() {
return Err(FunctionCallError::RespondToModel(
"request_permissions requires at least one permission".to_string(),
));
}
};
let environment_args: RequestPermissionsEnvironmentArgs = parse_arguments(&arguments)?;
let Some(turn_environment) =
resolve_tool_environment(turn.as_ref(), environment_args.environment_id.as_deref())?
else {
return Err(FunctionCallError::RespondToModel(
"request_permissions requires a primary environment".to_string(),
));
};
let mut args: RequestPermissionsArgs =
parse_arguments_with_base_path(&arguments, &turn_environment.cwd)?;
args.permissions = normalize_additional_permissions(args.permissions.into())
.map(codex_protocol::request_permissions::RequestPermissionProfile::from)
.map_err(FunctionCallError::RespondToModel)?;
if args.permissions.is_empty() {
return Err(FunctionCallError::RespondToModel(
"request_permissions requires at least one permission".to_string(),
));
}
let response = session
.request_permissions_for_environment(
&turn,
call_id,
args,
turn_environment.selection(),
cancellation_token,
)
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(
"request_permissions was cancelled before receiving a response".to_string(),
let response = session
.request_permissions_for_environment(
&turn,
call_id,
args,
turn_environment.selection(),
cancellation_token,
)
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(
"request_permissions was cancelled before receiving a response".to_string(),
)
})?;
let content = serde_json::to_string(&response).map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize request_permissions response: {err}"
))
})?;
let content = serde_json::to_string(&response).map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize request_permissions response: {err}"
))
})?;
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
})
}
}
@@ -48,7 +48,6 @@ impl RequestPluginInstallHandler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for RequestPluginInstallHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME)
@@ -62,54 +61,52 @@ impl ToolExecutor<ToolInvocation> for RequestPluginInstallHandler {
true
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
payload,
session,
turn,
call_id,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation {
payload,
session,
turn,
call_id,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::Fatal(format!(
"{REQUEST_PLUGIN_INSTALL_TOOL_NAME} handler received unsupported payload"
)));
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::Fatal(format!(
"{REQUEST_PLUGIN_INSTALL_TOOL_NAME} handler received unsupported payload"
)));
}
};
let args: RequestPluginInstallArgs = parse_arguments(&arguments)?;
let suggest_reason = args.suggest_reason.trim();
if suggest_reason.is_empty() {
return Err(FunctionCallError::RespondToModel(
"suggest_reason must not be empty".to_string(),
));
}
if args.action_type != DiscoverableToolAction::Install {
return Err(FunctionCallError::RespondToModel(
"plugin install requests currently support only action_type=\"install\""
.to_string(),
));
}
if args.tool_type == DiscoverableToolType::Plugin
&& turn.app_server_client_name.as_deref() == Some("codex-tui")
{
return Err(FunctionCallError::RespondToModel(
"plugin install requests are not available in codex-tui yet".to_string(),
));
}
};
let args: RequestPluginInstallArgs = parse_arguments(&arguments)?;
let suggest_reason = args.suggest_reason.trim();
if suggest_reason.is_empty() {
return Err(FunctionCallError::RespondToModel(
"suggest_reason must not be empty".to_string(),
));
}
if args.action_type != DiscoverableToolAction::Install {
return Err(FunctionCallError::RespondToModel(
"plugin install requests currently support only action_type=\"install\""
.to_string(),
));
}
if args.tool_type == DiscoverableToolType::Plugin
&& turn.app_server_client_name.as_deref() == Some("codex-tui")
{
return Err(FunctionCallError::RespondToModel(
"plugin install requests are not available in codex-tui yet".to_string(),
));
}
let discoverable_tools = filter_request_plugin_install_discoverable_tools_for_client(
self.discoverable_tools.clone(),
turn.app_server_client_name.as_deref(),
);
let discoverable_tools = filter_request_plugin_install_discoverable_tools_for_client(
self.discoverable_tools.clone(),
turn.app_server_client_name.as_deref(),
);
let tool = discoverable_tools
let tool = discoverable_tools
.into_iter()
.find(|tool| tool.tool_type() == args.tool_type && tool.id() == args.tool_id)
.ok_or_else(|| {
@@ -118,79 +115,80 @@ impl ToolExecutor<ToolInvocation> for RequestPluginInstallHandler {
))
})?;
let request_id = RequestId::String(format!("request_plugin_install_{call_id}").into());
let params = build_request_plugin_install_elicitation_request(
CODEX_APPS_MCP_SERVER_NAME,
session.thread_id.to_string(),
turn.sub_id.clone(),
&args,
suggest_reason,
&tool,
);
let elicitation = session
.request_mcp_server_elicitation(turn.as_ref(), request_id, params)
.await;
let response = elicitation.response;
if let Some(response) = response.as_ref() {
maybe_persist_disabled_install_request(&session, &turn, &tool, response).await;
}
let user_confirmed = response
.as_ref()
.is_some_and(|response| response.action == ElicitationAction::Accept);
let auth = session.services.auth_manager.auth().await;
let completed = if user_confirmed {
verify_request_plugin_install_completed(&session, &turn, &tool, auth.as_ref()).await
} else {
false
};
if completed && let DiscoverableTool::Connector(connector) = &tool {
session
.merge_connector_selection(HashSet::from([connector.id.clone()]))
.await;
}
if elicitation.sent {
let tool_type = match args.tool_type {
DiscoverableToolType::Connector => "connector",
DiscoverableToolType::Plugin => "plugin",
};
let response_action = match response.as_ref().map(|response| &response.action) {
Some(ElicitationAction::Accept) => "accept",
Some(ElicitationAction::Decline) => "decline",
Some(ElicitationAction::Cancel) => "cancel",
None => "unavailable",
};
turn.session_telemetry.record_plugin_install_suggestion(
tool_type,
tool.id(),
tool.name(),
response_action,
user_confirmed,
completed,
let request_id = RequestId::String(format!("request_plugin_install_{call_id}").into());
let params = build_request_plugin_install_elicitation_request(
CODEX_APPS_MCP_SERVER_NAME,
session.thread_id.to_string(),
turn.sub_id.clone(),
&args,
suggest_reason,
&tool,
);
}
let elicitation = session
.request_mcp_server_elicitation(turn.as_ref(), request_id, params)
.await;
let response = elicitation.response;
if let Some(response) = response.as_ref() {
maybe_persist_disabled_install_request(&session, &turn, &tool, response).await;
}
let user_confirmed = response
.as_ref()
.is_some_and(|response| response.action == ElicitationAction::Accept);
let content = serde_json::to_string(&RequestPluginInstallResult {
completed,
user_confirmed,
tool_type: args.tool_type,
action_type: args.action_type,
tool_id: tool.id().to_string(),
tool_name: tool.name().to_string(),
suggest_reason: suggest_reason.to_string(),
let auth = session.services.auth_manager.auth().await;
let completed = if user_confirmed {
verify_request_plugin_install_completed(&session, &turn, &tool, auth.as_ref()).await
} else {
false
};
if completed && let DiscoverableTool::Connector(connector) = &tool {
session
.merge_connector_selection(HashSet::from([connector.id.clone()]))
.await;
}
if elicitation.sent {
let tool_type = match args.tool_type {
DiscoverableToolType::Connector => "connector",
DiscoverableToolType::Plugin => "plugin",
};
let response_action = match response.as_ref().map(|response| &response.action) {
Some(ElicitationAction::Accept) => "accept",
Some(ElicitationAction::Decline) => "decline",
Some(ElicitationAction::Cancel) => "cancel",
None => "unavailable",
};
turn.session_telemetry.record_plugin_install_suggestion(
tool_type,
tool.id(),
tool.name(),
response_action,
user_confirmed,
completed,
);
}
let content = serde_json::to_string(&RequestPluginInstallResult {
completed,
user_confirmed,
tool_type: args.tool_type,
action_type: args.action_type,
tool_id: tool.id().to_string(),
tool_name: tool.name().to_string(),
suggest_reason: suggest_reason.to_string(),
})
.map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize {REQUEST_PLUGIN_INSTALL_TOOL_NAME} response: {err}"
))
})?;
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
})
.map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize {REQUEST_PLUGIN_INSTALL_TOOL_NAME} response: {err}"
))
})?;
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
}
}
@@ -20,7 +20,6 @@ pub struct RequestUserInputHandler {
pub available_modes: Vec<ModeKind>,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for RequestUserInputHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain(REQUEST_USER_INPUT_TOOL_NAME)
@@ -30,60 +29,61 @@ impl ToolExecutor<ToolInvocation> for RequestUserInputHandler {
create_request_user_input_tool(request_user_input_tool_description(&self.available_modes))
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation {
session,
turn,
call_id,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(format!(
"{REQUEST_USER_INPUT_TOOL_NAME} handler received unsupported payload"
)));
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(format!(
"{REQUEST_USER_INPUT_TOOL_NAME} handler received unsupported payload"
)));
}
};
if turn.session_source.is_non_root_agent() {
return Err(FunctionCallError::RespondToModel(
"request_user_input can only be used by the root thread".to_string(),
));
}
};
if turn.session_source.is_non_root_agent() {
return Err(FunctionCallError::RespondToModel(
"request_user_input can only be used by the root thread".to_string(),
));
}
let mode = session.collaboration_mode().await.mode;
if let Some(message) =
request_user_input_unavailable_message(mode, &self.available_modes)
{
return Err(FunctionCallError::RespondToModel(message));
}
let mode = session.collaboration_mode().await.mode;
if let Some(message) = request_user_input_unavailable_message(mode, &self.available_modes) {
return Err(FunctionCallError::RespondToModel(message));
}
let args: RequestUserInputArgs = parse_arguments(&arguments)?;
let args = normalize_request_user_input_args(args)
.map_err(FunctionCallError::RespondToModel)?;
let response = session
.request_user_input(turn.as_ref(), call_id, args)
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(format!(
"{REQUEST_USER_INPUT_TOOL_NAME} was cancelled before receiving a response"
))
})?;
let args: RequestUserInputArgs = parse_arguments(&arguments)?;
let args =
normalize_request_user_input_args(args).map_err(FunctionCallError::RespondToModel)?;
let response = session
.request_user_input(turn.as_ref(), call_id, args)
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(format!(
"{REQUEST_USER_INPUT_TOOL_NAME} was cancelled before receiving a response"
let content = serde_json::to_string(&response).map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize {REQUEST_USER_INPUT_TOOL_NAME} response: {err}"
))
})?;
let content = serde_json::to_string(&response).map_err(|err| {
FunctionCallError::Fatal(format!(
"failed to serialize {REQUEST_USER_INPUT_TOOL_NAME} response: {err}"
))
})?;
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
Ok(boxed_tool_output(FunctionToolOutput::from_text(
content,
Some(true),
)))
})
}
}
@@ -124,7 +124,6 @@ impl From<ShellCommandBackendConfig> for ShellCommandHandler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ShellCommandHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("shell_command")
@@ -141,64 +140,64 @@ impl ToolExecutor<ToolInvocation> for ShellCommandHandler {
true
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
cancellation_token,
tracker,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation {
session,
turn,
cancellation_token,
tracker,
call_id,
payload,
..
} = invocation;
let tool_name = self.tool_name();
let ToolPayload::Function { arguments } = payload else {
return Err(FunctionCallError::RespondToModel(format!(
"unsupported payload for shell_command handler: {tool_name}"
)));
};
let tool_name = self.tool_name();
let ToolPayload::Function { arguments } = payload else {
return Err(FunctionCallError::RespondToModel(format!(
"unsupported payload for shell_command handler: {tool_name}"
)));
};
#[allow(deprecated)]
let cwd = resolve_workdir_base_path(&arguments, &turn.cwd)?;
let params: ShellCommandToolCallParams = parse_arguments_with_base_path(&arguments, &cwd)?;
#[allow(deprecated)]
let workdir = turn.resolve_path(params.workdir.clone());
maybe_emit_implicit_skill_invocation(
session.as_ref(),
turn.as_ref(),
&params.command,
&workdir,
)
.await;
let prefix_rule = params.prefix_rule.clone();
let exec_params = Self::to_exec_params(
&params,
session.as_ref(),
turn.as_ref(),
session.thread_id,
turn.config.permissions.allow_login_shell,
)?;
let shell_type = Some(session.user_shell().shell_type);
run_exec_like(RunExecLikeArgs {
tool_name,
exec_params,
cancellation_token,
hook_command: params.command,
shell_type,
additional_permissions: params.additional_permissions.clone(),
prefix_rule,
session,
turn,
tracker,
call_id,
shell_runtime_backend: self.shell_runtime_backend(),
#[allow(deprecated)]
let cwd = resolve_workdir_base_path(&arguments, &turn.cwd)?;
let params: ShellCommandToolCallParams =
parse_arguments_with_base_path(&arguments, &cwd)?;
#[allow(deprecated)]
let workdir = turn.resolve_path(params.workdir.clone());
maybe_emit_implicit_skill_invocation(
session.as_ref(),
turn.as_ref(),
&params.command,
&workdir,
)
.await;
let prefix_rule = params.prefix_rule.clone();
let exec_params = Self::to_exec_params(
&params,
session.as_ref(),
turn.as_ref(),
session.thread_id,
turn.config.permissions.allow_login_shell,
)?;
let shell_type = Some(session.user_shell().shell_type);
run_exec_like(RunExecLikeArgs {
tool_name,
exec_params,
cancellation_token,
hook_command: params.command,
shell_type,
additional_permissions: params.additional_permissions.clone(),
prefix_rule,
session,
turn,
tracker,
call_id,
shell_runtime_backend: self.shell_runtime_backend(),
})
.await
.map(boxed_tool_output)
})
.await
.map(boxed_tool_output)
}
}
+32 -33
View File
@@ -57,7 +57,6 @@ fn barrier_map() -> &'static tokio::sync::Mutex<HashMap<String, BarrierState>> {
BARRIERS.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for TestSyncHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("test_sync_tool")
@@ -71,43 +70,43 @@ impl ToolExecutor<ToolInvocation> for TestSyncHandler {
true
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation { payload, .. } = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation { payload, .. } = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"test_sync_tool handler received unsupported payload".to_string(),
));
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"test_sync_tool handler received unsupported payload".to_string(),
));
}
};
let args: TestSyncArgs = parse_arguments(&arguments)?;
if let Some(delay) = args.sleep_before_ms
&& delay > 0
{
sleep(Duration::from_millis(delay)).await;
}
};
let args: TestSyncArgs = parse_arguments(&arguments)?;
if let Some(barrier) = args.barrier {
wait_on_barrier(barrier).await?;
}
if let Some(delay) = args.sleep_before_ms
&& delay > 0
{
sleep(Duration::from_millis(delay)).await;
}
if let Some(delay) = args.sleep_after_ms
&& delay > 0
{
sleep(Duration::from_millis(delay)).await;
}
if let Some(barrier) = args.barrier {
wait_on_barrier(barrier).await?;
}
if let Some(delay) = args.sleep_after_ms
&& delay > 0
{
sleep(Duration::from_millis(delay)).await;
}
Ok(boxed_tool_output(FunctionToolOutput::from_text(
"ok".to_string(),
Some(true),
)))
Ok(boxed_tool_output(FunctionToolOutput::from_text(
"ok".to_string(),
Some(true),
)))
})
}
}
+29 -31
View File
@@ -53,7 +53,6 @@ impl ToolSearchHandler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ToolSearchHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain(TOOL_SEARCH_TOOL_NAME)
@@ -67,42 +66,41 @@ impl ToolExecutor<ToolInvocation> for ToolSearchHandler {
true
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation { payload, .. } = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let ToolInvocation { payload, .. } = invocation;
let args = match payload {
ToolPayload::ToolSearch { arguments } => arguments,
_ => {
return Err(FunctionCallError::Fatal(format!(
"{TOOL_SEARCH_TOOL_NAME} handler received unsupported payload"
)));
let args = match payload {
ToolPayload::ToolSearch { arguments } => arguments,
_ => {
return Err(FunctionCallError::Fatal(format!(
"{TOOL_SEARCH_TOOL_NAME} handler received unsupported payload"
)));
}
};
let query = args.query.trim();
if query.is_empty() {
return Err(FunctionCallError::RespondToModel(
"query must not be empty".to_string(),
));
}
};
let limit = args.limit.unwrap_or(TOOL_SEARCH_DEFAULT_LIMIT);
let query = args.query.trim();
if query.is_empty() {
return Err(FunctionCallError::RespondToModel(
"query must not be empty".to_string(),
));
}
let limit = args.limit.unwrap_or(TOOL_SEARCH_DEFAULT_LIMIT);
if limit == 0 {
return Err(FunctionCallError::RespondToModel(
"limit must be greater than zero".to_string(),
));
}
if limit == 0 {
return Err(FunctionCallError::RespondToModel(
"limit must be greater than zero".to_string(),
));
}
if self.entries.is_empty() {
return Ok(boxed_tool_output(ToolSearchOutput { tools: Vec::new() }));
}
if self.entries.is_empty() {
return Ok(boxed_tool_output(ToolSearchOutput { tools: Vec::new() }));
}
let tools = self.search(query, limit)?;
let tools = self.search(query, limit)?;
Ok(boxed_tool_output(ToolSearchOutput { tools }))
Ok(boxed_tool_output(ToolSearchOutput { tools }))
})
}
}
@@ -71,7 +71,6 @@ impl ExecCommandHandler {
}
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ExecCommandHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("exec_command")
@@ -92,218 +91,220 @@ impl ToolExecutor<ToolInvocation> for ExecCommandHandler {
true
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
tracker,
call_id,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
tracker,
call_id,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"exec_command handler received unsupported payload".to_string(),
));
}
};
let manager: &UnifiedExecProcessManager = &session.services.unified_exec_manager;
let context = UnifiedExecContext::new(session.clone(), turn.clone(), call_id.clone());
let environment_args: ExecCommandEnvironmentArgs = parse_arguments(&arguments)?;
let Some(turn_environment) = resolve_tool_environment(
turn.as_ref(),
environment_args.environment_id.as_deref(),
)?
else {
return Err(FunctionCallError::RespondToModel(
"exec_command handler received unsupported payload".to_string(),
"unified exec is unavailable in this session".to_string(),
));
}
};
let manager: &UnifiedExecProcessManager = &session.services.unified_exec_manager;
let context = UnifiedExecContext::new(session.clone(), turn.clone(), call_id.clone());
let environment_args: ExecCommandEnvironmentArgs = parse_arguments(&arguments)?;
let Some(turn_environment) =
resolve_tool_environment(turn.as_ref(), environment_args.environment_id.as_deref())?
else {
return Err(FunctionCallError::RespondToModel(
"unified exec is unavailable in this session".to_string(),
));
};
let cwd = environment_args
.workdir
.as_deref()
.filter(|workdir| !workdir.is_empty())
.map_or_else(
|| turn_environment.cwd.clone(),
|workdir| turn_environment.cwd.join(workdir),
);
let environment = Arc::clone(&turn_environment.environment);
let fs = environment.get_filesystem();
let args: ExecCommandArgs = parse_arguments_with_base_path(&arguments, &cwd)?;
let hook_command = args.cmd.clone();
maybe_emit_implicit_skill_invocation(
session.as_ref(),
context.turn.as_ref(),
&hook_command,
&cwd,
)
.await;
let process_id = manager.allocate_process_id().await;
let shell_mode =
shell_mode_for_environment(&turn.unified_exec_shell_mode, environment.as_ref());
let resolved_command = get_command(
&args,
session.user_shell(),
&shell_mode,
turn.config.permissions.allow_login_shell,
)
.map_err(FunctionCallError::RespondToModel)?;
let command = resolved_command.command;
let shell_type = resolved_command.shell_type;
let command_for_display = codex_shell_command::parse_command::shlex_join(&command);
let ExecCommandArgs {
tty,
yield_time_ms,
max_output_tokens,
sandbox_permissions,
additional_permissions,
justification,
prefix_rule,
..
} = args;
let exec_permission_approvals_enabled =
session.features().enabled(Feature::ExecPermissionApprovals);
let requested_additional_permissions = additional_permissions.clone();
let effective_additional_permissions = apply_granted_turn_permissions(
context.session.as_ref(),
&turn_environment.environment_id,
cwd.as_path(),
sandbox_permissions,
additional_permissions,
)
.await;
let additional_permissions_allowed = exec_permission_approvals_enabled
|| (session.features().enabled(Feature::RequestPermissionsTool)
&& effective_additional_permissions.permissions_preapproved);
// Sticky turn permissions have already been approved, so they should
// continue through the normal exec approval flow for the command.
if effective_additional_permissions
.sandbox_permissions
.requests_sandbox_override()
&& !effective_additional_permissions.permissions_preapproved
&& !matches!(
context.turn.approval_policy.value(),
codex_protocol::protocol::AskForApproval::OnRequest
};
let cwd = environment_args
.workdir
.as_deref()
.filter(|workdir| !workdir.is_empty())
.map_or_else(
|| turn_environment.cwd.clone(),
|workdir| turn_environment.cwd.join(workdir),
);
let environment = Arc::clone(&turn_environment.environment);
let fs = environment.get_filesystem();
let args: ExecCommandArgs = parse_arguments_with_base_path(&arguments, &cwd)?;
let hook_command = args.cmd.clone();
maybe_emit_implicit_skill_invocation(
session.as_ref(),
context.turn.as_ref(),
&hook_command,
&cwd,
)
{
let approval_policy = context.turn.approval_policy.value();
manager.release_process_id(process_id).await;
return Err(FunctionCallError::RespondToModel(format!(
"approval policy is {approval_policy:?}; reject command — you cannot ask for escalated permissions if the approval policy is {approval_policy:?}"
)));
}
.await;
let process_id = manager.allocate_process_id().await;
let shell_mode =
shell_mode_for_environment(&turn.unified_exec_shell_mode, environment.as_ref());
let resolved_command = get_command(
&args,
session.user_shell(),
&shell_mode,
turn.config.permissions.allow_login_shell,
)
.map_err(FunctionCallError::RespondToModel)?;
let command = resolved_command.command;
let shell_type = resolved_command.shell_type;
let command_for_display = codex_shell_command::parse_command::shlex_join(&command);
let normalized_additional_permissions = match implicit_granted_permissions(
sandbox_permissions,
requested_additional_permissions.as_ref(),
&effective_additional_permissions,
)
.map_or_else(
|| {
normalize_and_validate_additional_permissions(
additional_permissions_allowed,
context.turn.approval_policy.value(),
effective_additional_permissions.sandbox_permissions,
effective_additional_permissions.additional_permissions,
effective_additional_permissions.permissions_preapproved,
&cwd,
)
},
|permissions| Ok(Some(permissions)),
) {
Ok(normalized) => normalized,
Err(err) => {
manager.release_process_id(process_id).await;
return Err(FunctionCallError::RespondToModel(err));
}
};
if let Some(output) = intercept_apply_patch(
&command,
&cwd,
fs.as_ref(),
turn_environment.clone(),
context.session.clone(),
context.turn.clone(),
Some(&tracker),
&context.call_id,
"exec_command",
)
.await?
{
manager.release_process_id(process_id).await;
return Ok(boxed_tool_output(ExecCommandToolOutput {
event_call_id: String::new(),
chunk_id: String::new(),
wall_time: std::time::Duration::ZERO,
raw_output: output.into_text().into_bytes(),
truncation_policy: turn.truncation_policy,
let ExecCommandArgs {
tty,
yield_time_ms,
max_output_tokens,
process_id: None,
exit_code: None,
original_token_count: None,
hook_command: None,
}));
}
sandbox_permissions,
additional_permissions,
justification,
prefix_rule,
..
} = args;
emit_unified_exec_tty_metric(&turn.session_telemetry, tty);
match manager
.exec_command(
ExecCommandRequest {
command,
shell_type,
hook_command: hook_command.clone(),
process_id,
yield_time_ms,
max_output_tokens,
cwd,
sandbox_cwd: turn_environment.cwd.clone(),
environment,
shell_mode,
network: context.turn.network.clone(),
tty,
sandbox_permissions: effective_additional_permissions.sandbox_permissions,
additional_permissions: normalized_additional_permissions,
additional_permissions_preapproved: effective_additional_permissions
.permissions_preapproved,
justification,
prefix_rule,
},
&context,
let exec_permission_approvals_enabled =
session.features().enabled(Feature::ExecPermissionApprovals);
let requested_additional_permissions = additional_permissions.clone();
let effective_additional_permissions = apply_granted_turn_permissions(
context.session.as_ref(),
&turn_environment.environment_id,
cwd.as_path(),
sandbox_permissions,
additional_permissions,
)
.await
{
Ok(response) => Ok(boxed_tool_output(response)),
Err(UnifiedExecError::SandboxDenied { output, .. }) => {
let output_text = output.aggregated_output.text;
let original_token_count = approx_token_count(&output_text);
Ok(boxed_tool_output(ExecCommandToolOutput {
event_call_id: context.call_id.clone(),
chunk_id: generate_chunk_id(),
wall_time: output.duration,
raw_output: output_text.into_bytes(),
.await;
let additional_permissions_allowed = exec_permission_approvals_enabled
|| (session.features().enabled(Feature::RequestPermissionsTool)
&& effective_additional_permissions.permissions_preapproved);
// Sticky turn permissions have already been approved, so they should
// continue through the normal exec approval flow for the command.
if effective_additional_permissions
.sandbox_permissions
.requests_sandbox_override()
&& !effective_additional_permissions.permissions_preapproved
&& !matches!(
context.turn.approval_policy.value(),
codex_protocol::protocol::AskForApproval::OnRequest
)
{
let approval_policy = context.turn.approval_policy.value();
manager.release_process_id(process_id).await;
return Err(FunctionCallError::RespondToModel(format!(
"approval policy is {approval_policy:?}; reject command — you cannot ask for escalated permissions if the approval policy is {approval_policy:?}"
)));
}
let normalized_additional_permissions = match implicit_granted_permissions(
sandbox_permissions,
requested_additional_permissions.as_ref(),
&effective_additional_permissions,
)
.map_or_else(
|| {
normalize_and_validate_additional_permissions(
additional_permissions_allowed,
context.turn.approval_policy.value(),
effective_additional_permissions.sandbox_permissions,
effective_additional_permissions.additional_permissions,
effective_additional_permissions.permissions_preapproved,
&cwd,
)
},
|permissions| Ok(Some(permissions)),
) {
Ok(normalized) => normalized,
Err(err) => {
manager.release_process_id(process_id).await;
return Err(FunctionCallError::RespondToModel(err));
}
};
if let Some(output) = intercept_apply_patch(
&command,
&cwd,
fs.as_ref(),
turn_environment.clone(),
context.session.clone(),
context.turn.clone(),
Some(&tracker),
&context.call_id,
"exec_command",
)
.await?
{
manager.release_process_id(process_id).await;
return Ok(boxed_tool_output(ExecCommandToolOutput {
event_call_id: String::new(),
chunk_id: String::new(),
wall_time: std::time::Duration::ZERO,
raw_output: output.into_text().into_bytes(),
truncation_policy: turn.truncation_policy,
max_output_tokens,
// Sandbox denial is terminal, so there is no live
// process for write_stdin to resume.
process_id: None,
exit_code: Some(output.exit_code),
original_token_count: Some(original_token_count),
hook_command: Some(hook_command),
}))
exit_code: None,
original_token_count: None,
hook_command: None,
}));
}
Err(err) => Err(FunctionCallError::RespondToModel(format!(
"exec_command failed for `{command_for_display}`: {err:?}"
))),
}
emit_unified_exec_tty_metric(&turn.session_telemetry, tty);
match manager
.exec_command(
ExecCommandRequest {
command,
shell_type,
hook_command: hook_command.clone(),
process_id,
yield_time_ms,
max_output_tokens,
cwd,
sandbox_cwd: turn_environment.cwd.clone(),
environment,
shell_mode,
network: context.turn.network.clone(),
tty,
sandbox_permissions: effective_additional_permissions.sandbox_permissions,
additional_permissions: normalized_additional_permissions,
additional_permissions_preapproved: effective_additional_permissions
.permissions_preapproved,
justification,
prefix_rule,
},
&context,
)
.await
{
Ok(response) => Ok(boxed_tool_output(response)),
Err(UnifiedExecError::SandboxDenied { output, .. }) => {
let output_text = output.aggregated_output.text;
let original_token_count = approx_token_count(&output_text);
Ok(boxed_tool_output(ExecCommandToolOutput {
event_call_id: context.call_id.clone(),
chunk_id: generate_chunk_id(),
wall_time: output.duration,
raw_output: output_text.into_bytes(),
truncation_policy: turn.truncation_policy,
max_output_tokens,
// Sandbox denial is terminal, so there is no live
// process for write_stdin to resume.
process_id: None,
exit_code: Some(output.exit_code),
original_token_count: Some(original_token_count),
hook_command: Some(hook_command),
}))
}
Err(err) => Err(FunctionCallError::RespondToModel(format!(
"exec_command failed for `{command_for_display}`: {err:?}"
))),
}
})
}
}
@@ -31,7 +31,6 @@ struct WriteStdinArgs {
pub struct WriteStdinHandler;
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for WriteStdinHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("write_stdin")
@@ -41,59 +40,59 @@ impl ToolExecutor<ToolInvocation> for WriteStdinHandler {
create_write_stdin_tool()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
..
} = invocation;
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let ToolInvocation {
session,
turn,
payload,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"write_stdin handler received unsupported payload".to_string(),
));
}
};
let args: WriteStdinArgs = parse_arguments(&arguments)?;
let response = session
.services
.unified_exec_manager
.write_stdin(WriteStdinRequest {
process_id: args.session_id,
input: &args.chars,
yield_time_ms: args.yield_time_ms,
max_output_tokens: args.max_output_tokens,
truncation_policy: turn.truncation_policy,
})
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("write_stdin failed: {err}"))
})?;
// Empty stdin is a background poll, so emit it only while there is
// still a live process for the UI to wait on. Non-empty stdin is a real
// terminal interaction and should remain visible even if it completes
// the process before the response returns.
if !args.chars.is_empty() || response.process_id.is_some() {
let process_id = response.process_id.unwrap_or(args.session_id);
let interaction = TerminalInteractionEvent {
call_id: response.event_call_id.clone(),
process_id: process_id.to_string(),
stdin: args.chars.clone(),
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"write_stdin handler received unsupported payload".to_string(),
));
}
};
session
.send_event(turn.as_ref(), EventMsg::TerminalInteraction(interaction))
.await;
}
Ok(boxed_tool_output(response))
let args: WriteStdinArgs = parse_arguments(&arguments)?;
let response = session
.services
.unified_exec_manager
.write_stdin(WriteStdinRequest {
process_id: args.session_id,
input: &args.chars,
yield_time_ms: args.yield_time_ms,
max_output_tokens: args.max_output_tokens,
truncation_policy: turn.truncation_policy,
})
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("write_stdin failed: {err}"))
})?;
// Empty stdin is a background poll, so emit it only while there is
// still a live process for the UI to wait on. Non-empty stdin is a real
// terminal interaction and should remain visible even if it completes
// the process before the response returns.
if !args.chars.is_empty() || response.process_id.is_some() {
let process_id = response.process_id.unwrap_or(args.session_id);
let interaction = TerminalInteractionEvent {
call_id: response.event_call_id.clone(),
process_id: process_id.to_string(),
stdin: args.chars.clone(),
};
session
.send_event(turn.as_ref(), EventMsg::TerminalInteraction(interaction))
.await;
}
Ok(boxed_tool_output(response))
})
}
}
+114 -113
View File
@@ -64,7 +64,6 @@ enum ViewImageDetail {
Original,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ViewImageHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("view_image")
@@ -78,129 +77,131 @@ impl ToolExecutor<ToolInvocation> for ViewImageHandler {
true
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
if !invocation
.turn
.model_info
.input_modalities
.contains(&InputModality::Image)
{
return Err(FunctionCallError::RespondToModel(
VIEW_IMAGE_UNSUPPORTED_MESSAGE.to_string(),
));
}
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
if !invocation
.turn
.model_info
.input_modalities
.contains(&InputModality::Image)
{
return Err(FunctionCallError::RespondToModel(
"view_image handler received unsupported payload".to_string(),
VIEW_IMAGE_UNSUPPORTED_MESSAGE.to_string(),
));
}
};
let ViewImageArgs {
path,
environment_id,
detail,
} = parse_arguments(&arguments)?;
// `high` is the explicit spelling of the default resized path.
// Other string values remain invalid rather than being silently reinterpreted.
let detail = match detail.as_deref() {
None => None,
Some("high") => Some(ViewImageDetail::High),
Some("original") => Some(ViewImageDetail::Original),
Some(detail) => {
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = match payload {
ToolPayload::Function { arguments } => arguments,
_ => {
return Err(FunctionCallError::RespondToModel(
"view_image handler received unsupported payload".to_string(),
));
}
};
let ViewImageArgs {
path,
environment_id,
detail,
} = parse_arguments(&arguments)?;
// `high` is the explicit spelling of the default resized path.
// Other string values remain invalid rather than being silently reinterpreted.
let detail = match detail.as_deref() {
None => None,
Some("high") => Some(ViewImageDetail::High),
Some("original") => Some(ViewImageDetail::Original),
Some(detail) => {
return Err(FunctionCallError::RespondToModel(format!(
"view_image.detail only supports `high` or `original`; omit `detail` for default high resized behavior, got `{detail}`"
)));
}
};
let Some(turn_environment) =
resolve_tool_environment(turn.as_ref(), environment_id.as_deref())?
else {
return Err(FunctionCallError::RespondToModel(
"view_image is unavailable in this session".to_string(),
));
};
let cwd = turn_environment.cwd.clone();
let abs_path = cwd.join(path);
let sandbox =
turn.file_system_sandbox_context(/*additional_permissions*/ None, &cwd);
let fs = turn_environment.environment.get_filesystem();
let metadata = fs
.get_metadata(&abs_path, Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to locate image at `{}`: {error}",
abs_path.display()
))
})?;
if !metadata.is_file {
return Err(FunctionCallError::RespondToModel(format!(
"view_image.detail only supports `high` or `original`; omit `detail` for default high resized behavior, got `{detail}`"
"image path `{}` is not a file",
abs_path.display()
)));
}
};
let file_bytes = fs
.read_file(&abs_path, Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to read image at `{}`: {error}",
abs_path.display()
))
})?;
let event_path = abs_path.clone();
let Some(turn_environment) =
resolve_tool_environment(turn.as_ref(), environment_id.as_deref())?
else {
return Err(FunctionCallError::RespondToModel(
"view_image is unavailable in this session".to_string(),
));
};
let cwd = turn_environment.cwd.clone();
let abs_path = cwd.join(path);
let sandbox = turn.file_system_sandbox_context(/*additional_permissions*/ None, &cwd);
let fs = turn_environment.environment.get_filesystem();
let can_request_original_detail = can_request_original_image_detail(&turn.model_info);
let use_original_detail =
can_request_original_detail && matches!(detail, Some(ViewImageDetail::Original));
let image_mode = if use_original_detail {
PromptImageMode::Original
} else {
PromptImageMode::ResizeToFit
};
let image_detail = if use_original_detail {
ImageDetail::Original
} else {
DEFAULT_IMAGE_DETAIL
};
let metadata = fs
.get_metadata(&abs_path, Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to locate image at `{}`: {error}",
abs_path.display()
))
})?;
let image = load_for_prompt_bytes(abs_path.as_path(), file_bytes, image_mode).map_err(
|error| {
FunctionCallError::RespondToModel(format!(
"unable to process image at `{}`: {error}",
abs_path.display()
))
},
)?;
let image_url = image.into_data_url();
if !metadata.is_file {
return Err(FunctionCallError::RespondToModel(format!(
"image path `{}` is not a file",
abs_path.display()
)));
}
let file_bytes = fs
.read_file(&abs_path, Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to read image at `{}`: {error}",
abs_path.display()
))
})?;
let event_path = abs_path.clone();
let item = TurnItem::ImageView(ImageViewItem {
id: call_id,
path: event_path,
});
session.emit_turn_item_started(turn.as_ref(), &item).await;
session.emit_turn_item_completed(turn.as_ref(), item).await;
let can_request_original_detail = can_request_original_image_detail(&turn.model_info);
let use_original_detail =
can_request_original_detail && matches!(detail, Some(ViewImageDetail::Original));
let image_mode = if use_original_detail {
PromptImageMode::Original
} else {
PromptImageMode::ResizeToFit
};
let image_detail = if use_original_detail {
ImageDetail::Original
} else {
DEFAULT_IMAGE_DETAIL
};
let image =
load_for_prompt_bytes(abs_path.as_path(), file_bytes, image_mode).map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to process image at `{}`: {error}",
abs_path.display()
))
})?;
let image_url = image.into_data_url();
let item = TurnItem::ImageView(ImageViewItem {
id: call_id,
path: event_path,
});
session.emit_turn_item_started(turn.as_ref(), &item).await;
session.emit_turn_item_completed(turn.as_ref(), item).await;
Ok(boxed_tool_output(ViewImageOutput {
image_url,
image_detail,
}))
Ok(boxed_tool_output(ViewImageOutput {
image_url,
image_detail,
}))
})
}
}
+39 -35
View File
@@ -257,7 +257,6 @@ mod tests {
tool_name: codex_tools::ToolName,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ImmediateHandler {
fn tool_name(&self) -> codex_tools::ToolName {
self.tool_name.clone()
@@ -274,14 +273,18 @@ mod tests {
})
}
async fn handle(
&self,
_invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
Ok(Box::new(FunctionToolOutput::from_text(
"ok".to_string(),
Some(true),
)))
fn handle<'a>(
&'a self,
invocation: ToolInvocation,
) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let _invocation = invocation;
Ok(
Box::new(FunctionToolOutput::from_text("ok".to_string(), Some(true)))
as Box<dyn codex_tools::ToolOutput>,
)
})
}
}
@@ -294,7 +297,6 @@ mod tests {
allow_cleanup: Arc<Notify>,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for CancellationCleanupHandler {
fn tool_name(&self) -> codex_tools::ToolName {
self.tool_name.clone()
@@ -311,32 +313,34 @@ mod tests {
})
}
async fn handle(
&self,
fn handle<'a>(
&'a self,
invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
let started = self
.started
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(started) = started {
let _ = started.send(());
}
invocation.cancellation_token.cancelled().await;
let cleanup_started = self
.cleanup_started
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(cleanup_started) = cleanup_started {
let _ = cleanup_started.send(());
}
self.allow_cleanup.notified().await;
Ok(Box::new(FunctionToolOutput::from_text(
"cleanup complete".to_string(),
Some(false),
)))
) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let started = self
.started
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(started) = started {
let _ = started.send(());
}
invocation.cancellation_token.cancelled().await;
let cleanup_started = self
.cleanup_started
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(cleanup_started) = cleanup_started {
let _ = cleanup_started.send(());
}
self.allow_cleanup.notified().await;
Ok(Box::new(FunctionToolOutput::from_text(
"cleanup complete".to_string(),
Some(false),
)) as Box<dyn codex_tools::ToolOutput>)
})
}
}
+2 -6
View File
@@ -250,7 +250,6 @@ struct ExposureOverride {
exposure: ToolExposure,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for ExposureOverride {
fn tool_name(&self) -> ToolName {
self.handler.tool_name()
@@ -272,11 +271,8 @@ impl ToolExecutor<ToolInvocation> for ExposureOverride {
self.handler.search_info()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
self.handler.handle(invocation).await
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move { self.handler.handle(invocation).await })
}
}
+27 -24
View File
@@ -5,7 +5,6 @@ struct TestHandler {
tool_name: codex_tools::ToolName,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for TestHandler {
fn tool_name(&self) -> codex_tools::ToolName {
self.tool_name.clone()
@@ -15,13 +14,17 @@ impl ToolExecutor<ToolInvocation> for TestHandler {
test_spec(&self.tool_name)
}
async fn handle(
&self,
_invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
Ok(Box::new(
crate::tools::context::FunctionToolOutput::from_text("ok".to_string(), Some(true)),
))
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let _invocation = invocation;
Ok(
Box::new(crate::tools::context::FunctionToolOutput::from_text(
"ok".to_string(),
Some(true),
)) as Box<dyn codex_tools::ToolOutput>,
)
})
}
}
@@ -38,7 +41,6 @@ struct LifecycleTestHandler {
result: LifecycleTestResult,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for LifecycleTestHandler {
fn tool_name(&self) -> codex_tools::ToolName {
self.tool_name.clone()
@@ -48,21 +50,22 @@ impl ToolExecutor<ToolInvocation> for LifecycleTestHandler {
test_spec(&self.tool_name)
}
async fn handle(
&self,
_invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
match self.result.clone() {
LifecycleTestResult::Ok { success } => Ok(Box::new(
crate::tools::context::FunctionToolOutput::from_text(
"ok".to_string(),
Some(success),
),
)),
LifecycleTestResult::Err => Err(FunctionCallError::RespondToModel(
"handler failed".to_string(),
)),
}
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _invocation = invocation;
match self.result.clone() {
LifecycleTestResult::Ok { success } => Ok(Box::new(
crate::tools::context::FunctionToolOutput::from_text(
"ok".to_string(),
Some(success),
),
)
as Box<dyn codex_tools::ToolOutput>),
LifecycleTestResult::Err => Err(FunctionCallError::RespondToModel(
"handler failed".to_string(),
)),
}
})
}
}
+12 -13
View File
@@ -44,7 +44,6 @@ impl codex_extension_api::ToolContributor for ExtensionEchoContributor {
struct ExtensionEchoExecutor;
#[async_trait::async_trait]
impl ToolExecutor<ExtensionToolCall> for ExtensionEchoExecutor {
fn tool_name(&self) -> ToolName {
ToolName::namespaced("extension/", "echo")
@@ -73,18 +72,18 @@ impl ToolExecutor<ExtensionToolCall> for ExtensionEchoExecutor {
})
}
async fn handle(
&self,
call: ExtensionToolCall,
) -> Result<Box<dyn codex_tools::ToolOutput>, codex_tools::FunctionCallError> {
let arguments: serde_json::Value =
serde_json::from_str(call.function_arguments()?).expect("test arguments should parse");
Ok(Box::new(codex_tools::JsonToolOutput::new(json!({
"arguments": arguments,
"callId": call.call_id,
"conversationHistory": call.conversation_history.items(),
"ok": true,
}))))
fn handle<'a>(&'a self, call: ExtensionToolCall) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let arguments: serde_json::Value = serde_json::from_str(call.function_arguments()?)
.expect("test arguments should parse");
Ok(Box::new(codex_tools::JsonToolOutput::new(json!({
"arguments": arguments,
"callId": call.call_id,
"conversationHistory": call.conversation_history.items(),
"ok": true,
}))) as Box<dyn codex_tools::ToolOutput>)
})
}
}
+2 -7
View File
@@ -72,7 +72,6 @@ use codex_tools::ToolCall as ExtensionToolCall;
use codex_tools::ToolEnvironmentMode;
use codex_tools::ToolExecutor;
use codex_tools::ToolName;
use codex_tools::ToolOutput;
use codex_tools::ToolSearchInfo;
use codex_tools::ToolSpec;
use codex_tools::UnifiedExecShellMode;
@@ -946,7 +945,6 @@ struct MultiAgentV2NamespaceOverride {
namespace: String,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for MultiAgentV2NamespaceOverride {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(self.namespace.clone(), self.handler.tool_name().name)
@@ -975,11 +973,8 @@ impl ToolExecutor<ToolInvocation> for MultiAgentV2NamespaceOverride {
self.handler.search_info()
}
async fn handle(
&self,
invocation: ToolInvocation,
) -> Result<Box<dyn ToolOutput>, codex_tools::FunctionCallError> {
self.handler.handle(invocation).await
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move { self.handler.handle(invocation).await })
}
}
+13 -13
View File
@@ -25,7 +25,6 @@ use codex_tools::ToolCall as ExtensionToolCall;
use codex_tools::ToolExecutor;
use codex_tools::ToolExposure;
use codex_tools::ToolName;
use codex_tools::ToolOutput;
use codex_tools::ToolSpec;
use pretty_assertions::assert_eq;
use serde_json::json;
@@ -285,7 +284,6 @@ fn use_bedrock_provider(turn: &mut TurnContext) {
struct WebRunExtensionTool;
#[async_trait::async_trait]
impl ToolExecutor<ExtensionToolCall> for WebRunExtensionTool {
fn tool_name(&self) -> ToolName {
ToolName::namespaced("web", "run")
@@ -306,17 +304,18 @@ impl ToolExecutor<ExtensionToolCall> for WebRunExtensionTool {
})
}
async fn handle(
&self,
_call: ExtensionToolCall,
) -> Result<Box<dyn ToolOutput>, codex_tools::FunctionCallError> {
Ok(Box::new(codex_tools::JsonToolOutput::new(json!({}))))
fn handle<'a>(&'a self, call: ExtensionToolCall) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let _call = call;
Ok(Box::new(codex_tools::JsonToolOutput::new(json!({})))
as Box<dyn codex_tools::ToolOutput>)
})
}
}
struct DeferredExtensionTool;
#[async_trait::async_trait]
impl ToolExecutor<ExtensionToolCall> for DeferredExtensionTool {
fn tool_name(&self) -> ToolName {
ToolName::plain("extension_echo")
@@ -344,11 +343,12 @@ impl ToolExecutor<ExtensionToolCall> for DeferredExtensionTool {
ToolExposure::Deferred
}
async fn handle(
&self,
_call: ExtensionToolCall,
) -> Result<Box<dyn ToolOutput>, codex_tools::FunctionCallError> {
panic!("spec planning should not execute extension tools")
fn handle<'a>(&'a self, call: ExtensionToolCall) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let _call = call;
panic!("spec planning should not execute extension tools")
})
}
}
@@ -30,7 +30,6 @@ struct TestHandler {
tool_name: codex_tools::ToolName,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolInvocation> for TestHandler {
fn tool_name(&self) -> codex_tools::ToolName {
self.tool_name.clone()
@@ -47,14 +46,15 @@ impl ToolExecutor<ToolInvocation> for TestHandler {
})
}
async fn handle(
&self,
_invocation: ToolInvocation,
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
Ok(Box::new(FunctionToolOutput::from_text(
"ok".to_string(),
Some(true),
)))
fn handle<'a>(&'a self, invocation: ToolInvocation) -> codex_tools::ToolExecutionFuture<'a> {
Box::pin(async move {
let _self = self;
let _invocation = invocation;
Ok(
Box::new(FunctionToolOutput::from_text("ok".to_string(), Some(true)))
as Box<dyn codex_tools::ToolOutput>,
)
})
}
}
+1
View File
@@ -19,6 +19,7 @@ pub use codex_tools::JsonToolOutput;
pub use codex_tools::NoopTurnItemEmitter;
pub use codex_tools::ResponsesApiTool;
pub use codex_tools::ToolCall;
pub use codex_tools::ToolExecutionFuture;
pub use codex_tools::ToolExecutor;
pub use codex_tools::ToolName;
pub use codex_tools::ToolOutput;
-1
View File
@@ -14,7 +14,6 @@ doctest = false
workspace = true
[dependencies]
async-trait = { workspace = true }
codex-analytics = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
+8 -8
View File
@@ -1,6 +1,5 @@
use std::sync::Arc;
use async_trait::async_trait;
use codex_extension_api::FunctionCallError;
use codex_extension_api::JsonToolOutput;
use codex_extension_api::ToolCall;
@@ -132,7 +131,6 @@ impl GoalToolExecutor {
}
}
#[async_trait]
impl ToolExecutor<ToolCall> for GoalToolExecutor {
fn tool_name(&self) -> ToolName {
ToolName::plain(match self.kind {
@@ -150,12 +148,14 @@ impl ToolExecutor<ToolCall> for GoalToolExecutor {
}
}
async fn handle(&self, invocation: ToolCall) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
match self.kind {
GoalToolKind::Get => self.handle_get(invocation).await,
GoalToolKind::Create => self.handle_create(invocation).await,
GoalToolKind::Update => self.handle_update(invocation).await,
}
fn handle<'a>(&'a self, invocation: ToolCall) -> codex_extension_api::ToolExecutionFuture<'a> {
Box::pin(async move {
match self.kind {
GoalToolKind::Get => self.handle_get(invocation).await,
GoalToolKind::Create => self.handle_create(invocation).await,
GoalToolKind::Update => self.handle_update(invocation).await,
}
})
}
}
-1
View File
@@ -13,7 +13,6 @@ doctest = false
workspace = true
[dependencies]
async-trait = { workspace = true }
codex-api = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
+46 -45
View File
@@ -78,7 +78,6 @@ struct ImagegenArgs {
num_last_images_to_include: Option<usize>,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolCall> for ImageGenerationTool {
/// Keeps the tool in the existing image-generation Responses namespace.
fn tool_name(&self) -> ToolName {
@@ -96,50 +95,52 @@ impl ToolExecutor<ToolCall> for ImageGenerationTool {
}
/// Executes the selected image operation and returns the completed image result.
async fn handle(&self, call: ToolCall) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let args = parse_args(&call)?;
let request = request_for_args(&args, call.conversation_history.items())?;
call.turn_item_emitter
.emit_started(ExtensionTurnItem::ImageGeneration(ImageGenerationItem {
id: call.call_id.clone(),
status: "in_progress".to_string(),
revised_prompt: None,
result: String::new(),
saved_path: None,
}))
.await;
let response = match request {
ImageRequest::Generate(request) => self.backend.generate(request).await,
ImageRequest::Edit(request) => self.backend.edit(request).await,
}
.map_err(|err| {
FunctionCallError::RespondToModel(format!("image generation failed: {err}"))
})?;
let Some(result) = response.data.into_iter().next().map(|data| data.b64_json) else {
return Err(FunctionCallError::RespondToModel(
"image generation returned no image data".to_string(),
));
};
call.turn_item_emitter
.emit_completed(ExtensionTurnItem::ImageGeneration(ImageGenerationItem {
id: call.call_id.clone(),
status: "completed".to_string(),
revised_prompt: Some(args.prompt),
result: result.clone(),
saved_path: None,
}))
.await;
let output_path =
image_generation_artifact_path(&self.codex_home, &self.thread_id, &call.call_id);
let output_dir = output_path
.parent()
.unwrap_or_else(|| self.codex_home.clone());
let output_hint =
extension_image_generation_output_hint(output_dir.display(), output_path.display());
Ok(Box::new(GeneratedImageOutput {
result,
output_hint,
}))
fn handle<'a>(&'a self, call: ToolCall) -> codex_extension_api::ToolExecutionFuture<'a> {
Box::pin(async move {
let args = parse_args(&call)?;
let request = request_for_args(&args, call.conversation_history.items())?;
call.turn_item_emitter
.emit_started(ExtensionTurnItem::ImageGeneration(ImageGenerationItem {
id: call.call_id.clone(),
status: "in_progress".to_string(),
revised_prompt: None,
result: String::new(),
saved_path: None,
}))
.await;
let response = match request {
ImageRequest::Generate(request) => self.backend.generate(request).await,
ImageRequest::Edit(request) => self.backend.edit(request).await,
}
.map_err(|err| {
FunctionCallError::RespondToModel(format!("image generation failed: {err}"))
})?;
let Some(result) = response.data.into_iter().next().map(|data| data.b64_json) else {
return Err(FunctionCallError::RespondToModel(
"image generation returned no image data".to_string(),
));
};
call.turn_item_emitter
.emit_completed(ExtensionTurnItem::ImageGeneration(ImageGenerationItem {
id: call.call_id.clone(),
status: "completed".to_string(),
revised_prompt: Some(args.prompt),
result: result.clone(),
saved_path: None,
}))
.await;
let output_path =
image_generation_artifact_path(&self.codex_home, &self.thread_id, &call.call_id);
let output_dir = output_path
.parent()
.unwrap_or_else(|| self.codex_home.clone());
let output_hint =
extension_image_generation_output_hint(output_dir.display(), output_path.display());
Ok(Box::new(GeneratedImageOutput {
result,
output_hint,
}) as Box<dyn ToolOutput>)
})
}
}
-1
View File
@@ -13,7 +13,6 @@ doctest = false
workspace = true
[dependencies]
async-trait = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
codex-features = { workspace = true }
+21 -23
View File
@@ -2,6 +2,7 @@ use codex_extension_api::JsonToolOutput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolName;
use codex_extension_api::ToolOutput;
use codex_extension_api::ToolSpec;
use codex_otel::MetricsClient;
use schemars::JsonSchema;
@@ -41,7 +42,6 @@ pub(super) struct AddAdHocNoteTool<B> {
pub(super) metrics_client: Option<MetricsClient>,
}
#[async_trait::async_trait]
impl<B> ToolExecutor<ToolCall> for AddAdHocNoteTool<B>
where
B: MemoriesBackend,
@@ -57,27 +57,25 @@ where
)
}
async fn handle(
&self,
call: ToolCall,
) -> Result<Box<dyn codex_extension_api::ToolOutput>, codex_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: AddAdHocNoteArgs = parse_args(&call)?;
let response = backend
.add_ad_hoc_note(AddAdHocMemoryNoteRequest {
filename: args.filename,
note: args.note,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
ADD_AD_HOC_NOTE_TOOL_NAME,
"ad_hoc_notes",
response.is_ok(),
"not_applicable",
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
fn handle<'a>(&'a self, call: ToolCall) -> codex_extension_api::ToolExecutionFuture<'a> {
Box::pin(async move {
let backend = self.backend.clone();
let args: AddAdHocNoteArgs = parse_args(&call)?;
let response = backend
.add_ad_hoc_note(AddAdHocMemoryNoteRequest {
filename: args.filename,
note: args.note,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
ADD_AD_HOC_NOTE_TOOL_NAME,
"ad_hoc_notes",
response.is_ok(),
"not_applicable",
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))) as Box<dyn ToolOutput>)
})
}
}
+27 -29
View File
@@ -2,6 +2,7 @@ use codex_extension_api::JsonToolOutput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolName;
use codex_extension_api::ToolOutput;
use codex_extension_api::ToolSpec;
use codex_otel::MetricsClient;
use schemars::JsonSchema;
@@ -39,7 +40,6 @@ pub(super) struct ListTool<B> {
pub(super) metrics_client: Option<MetricsClient>,
}
#[async_trait::async_trait]
impl<B> ToolExecutor<ToolCall> for ListTool<B>
where
B: MemoriesBackend,
@@ -55,33 +55,31 @@ where
)
}
async fn handle(
&self,
call: ToolCall,
) -> Result<Box<dyn codex_extension_api::ToolOutput>, codex_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: ListArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "root");
let response = backend
.list(ListMemoriesRequest {
path: args.path,
cursor: args.cursor,
max_results: clamp_max_results(
args.max_results,
DEFAULT_LIST_MAX_RESULTS,
MAX_LIST_RESULTS,
),
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
LIST_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
fn handle<'a>(&'a self, call: ToolCall) -> codex_extension_api::ToolExecutionFuture<'a> {
Box::pin(async move {
let backend = self.backend.clone();
let args: ListArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "root");
let response = backend
.list(ListMemoriesRequest {
path: args.path,
cursor: args.cursor,
max_results: clamp_max_results(
args.max_results,
DEFAULT_LIST_MAX_RESULTS,
MAX_LIST_RESULTS,
),
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
LIST_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))) as Box<dyn ToolOutput>)
})
}
}
+25 -27
View File
@@ -2,6 +2,7 @@ use codex_extension_api::JsonToolOutput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolName;
use codex_extension_api::ToolOutput;
use codex_extension_api::ToolSpec;
use codex_otel::MetricsClient;
use schemars::JsonSchema;
@@ -38,7 +39,6 @@ pub(super) struct ReadTool<B> {
pub(super) metrics_client: Option<MetricsClient>,
}
#[async_trait::async_trait]
impl<B> ToolExecutor<ToolCall> for ReadTool<B>
where
B: MemoriesBackend,
@@ -54,31 +54,29 @@ where
)
}
async fn handle(
&self,
call: ToolCall,
) -> Result<Box<dyn codex_extension_api::ToolOutput>, codex_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: ReadArgs = parse_args(&call)?;
let path = args.path;
let scope = scope_from_path(path.as_str());
let response = backend
.read(ReadMemoryRequest {
path: path.clone(),
line_offset: args.line_offset.unwrap_or(1),
max_lines: args.max_lines,
max_tokens: DEFAULT_READ_MAX_TOKENS,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
READ_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
fn handle<'a>(&'a self, call: ToolCall) -> codex_extension_api::ToolExecutionFuture<'a> {
Box::pin(async move {
let backend = self.backend.clone();
let args: ReadArgs = parse_args(&call)?;
let path = args.path;
let scope = scope_from_path(path.as_str());
let response = backend
.read(ReadMemoryRequest {
path: path.clone(),
line_offset: args.line_offset.unwrap_or(1),
max_lines: args.max_lines,
max_tokens: DEFAULT_READ_MAX_TOKENS,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
READ_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))) as Box<dyn ToolOutput>)
})
}
}
+17 -19
View File
@@ -2,6 +2,7 @@ use codex_extension_api::JsonToolOutput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolName;
use codex_extension_api::ToolOutput;
use codex_extension_api::ToolSpec;
use codex_otel::MetricsClient;
use schemars::JsonSchema;
@@ -47,7 +48,6 @@ pub(super) struct SearchTool<B> {
pub(super) metrics_client: Option<MetricsClient>,
}
#[async_trait::async_trait]
impl<B> ToolExecutor<ToolCall> for SearchTool<B>
where
B: MemoriesBackend,
@@ -63,24 +63,22 @@ where
)
}
async fn handle(
&self,
call: ToolCall,
) -> Result<Box<dyn codex_extension_api::ToolOutput>, codex_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: SearchArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "all");
let response = backend.search(args.into_request()).await;
record_tool_call(
self.metrics_client.as_ref(),
SEARCH_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
fn handle<'a>(&'a self, call: ToolCall) -> codex_extension_api::ToolExecutionFuture<'a> {
Box::pin(async move {
let backend = self.backend.clone();
let args: SearchArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "all");
let response = backend.search(args.into_request()).await;
record_tool_call(
self.metrics_client.as_ref(),
SEARCH_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))) as Box<dyn ToolOutput>)
})
}
}
-1
View File
@@ -13,7 +13,6 @@ doctest = false
workspace = true
[dependencies]
async-trait = { workspace = true }
codex-api = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
+42 -41
View File
@@ -39,7 +39,6 @@ pub(crate) struct WebSearchTool {
pub(crate) settings: SearchSettings,
}
#[async_trait::async_trait]
impl ToolExecutor<ToolCall> for WebSearchTool {
fn tool_name(&self) -> ToolName {
ToolName::namespaced(WEB_NAMESPACE, RUN_TOOL_NAME)
@@ -74,47 +73,49 @@ impl ToolExecutor<ToolCall> for WebSearchTool {
true
}
async fn handle(&self, call: ToolCall) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let commands = parse_commands(&call)?;
let command_action = command_action(&commands);
let provider = self
.provider
.api_provider()
.await
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
let auth = self
.provider
.api_auth()
.await
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
let client = SearchClient::new(
ReqwestTransport::new(build_reqwest_client()),
provider,
auth,
);
let request = SearchRequest {
id: self.session_id.clone(),
model: call.model.clone(),
reasoning: None,
input: recent_input(call.conversation_history.items()),
commands: Some(commands),
settings: Some(self.settings.clone()),
max_output_tokens: Some(
u64::try_from(call.truncation_policy.token_budget()).unwrap_or(u64::MAX),
),
};
call.turn_item_emitter
.emit_started(web_search_item(&call.call_id, WebSearchAction::Other))
.await;
let response = client
.search(&request, HeaderMap::new())
.await
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
call.turn_item_emitter
.emit_completed(web_search_item(&call.call_id, command_action))
.await;
fn handle<'a>(&'a self, call: ToolCall) -> codex_extension_api::ToolExecutionFuture<'a> {
Box::pin(async move {
let commands = parse_commands(&call)?;
let command_action = command_action(&commands);
let provider = self
.provider
.api_provider()
.await
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
let auth = self
.provider
.api_auth()
.await
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
let client = SearchClient::new(
ReqwestTransport::new(build_reqwest_client()),
provider,
auth,
);
let request = SearchRequest {
id: self.session_id.clone(),
model: call.model.clone(),
reasoning: None,
input: recent_input(call.conversation_history.items()),
commands: Some(commands),
settings: Some(self.settings.clone()),
max_output_tokens: Some(
u64::try_from(call.truncation_policy.token_budget()).unwrap_or(u64::MAX),
),
};
call.turn_item_emitter
.emit_started(web_search_item(&call.call_id, WebSearchAction::Other))
.await;
let response = client
.search(&request, HeaderMap::new())
.await
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
call.turn_item_emitter
.emit_completed(web_search_item(&call.call_id, command_action))
.await;
Ok(Box::new(SearchOutput::new(response.output)))
Ok(Box::new(SearchOutput::new(response.output)) as Box<dyn ToolOutput>)
})
}
}
-1
View File
@@ -8,7 +8,6 @@ version.workspace = true
workspace = true
[dependencies]
async-trait = { workspace = true }
codex-app-server-protocol = { workspace = true }
codex-code-mode = { workspace = true }
codex-features = { workspace = true }
+1
View File
@@ -92,6 +92,7 @@ pub use tool_discovery::TOOL_SEARCH_TOOL_NAME;
pub use tool_discovery::ToolSearchSourceInfo;
pub use tool_discovery::collect_request_plugin_install_entries;
pub use tool_discovery::filter_request_plugin_install_discoverable_tools_for_client;
pub use tool_executor::ToolExecutionFuture;
pub use tool_executor::ToolExecutor;
pub use tool_executor::ToolExposure;
pub use tool_output::JsonToolOutput;
+8 -5
View File
@@ -1,9 +1,16 @@
use std::future::Future;
use std::pin::Pin;
use crate::FunctionCallError;
use crate::ToolName;
use crate::ToolOutput;
use crate::ToolSearchInfo;
use crate::ToolSpec;
/// Boxed, sendable future returned by a tool executor.
pub type ToolExecutionFuture<'a> =
Pin<Box<dyn Future<Output = Result<Box<dyn ToolOutput>, FunctionCallError>> + Send + 'a>>;
/// Controls where a tool is exposed to the model.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ToolExposure {
@@ -40,7 +47,6 @@ impl ToolExposure {
/// Implementations keep the model-visible spec tied to the executable runtime.
/// Host crates can layer routing, hooks, telemetry, or other orchestration on
/// top without reopening the spec/runtime split.
#[async_trait::async_trait]
pub trait ToolExecutor<Invocation>: Send + Sync {
/// The concrete tool name handled by this runtime instance.
fn tool_name(&self) -> ToolName;
@@ -60,8 +66,5 @@ pub trait ToolExecutor<Invocation>: Send + Sync {
false
}
async fn handle(
&self,
invocation: Invocation,
) -> Result<Box<dyn ToolOutput>, FunctionCallError>;
fn handle<'a>(&'a self, invocation: Invocation) -> ToolExecutionFuture<'a>;
}