Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 1 addition & 11 deletions codex-rs/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions codex-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ members = [
"test-binary-support",
"thread-manager-sample",
"thread-store",
"tool-api",
"uds",
"codex-experimental-api-macros",
"plugin",
Expand Down Expand Up @@ -209,7 +208,6 @@ codex-stdio-to-uds = { path = "stdio-to-uds" }
codex-terminal-detection = { path = "terminal-detection" }
codex-test-binary-support = { path = "test-binary-support" }
codex-thread-store = { path = "thread-store" }
codex-tool-api = { path = "tool-api" }
codex-tools = { path = "tools" }
codex-tui = { path = "tui" }
codex-uds = { path = "uds" }
Expand Down
1 change: 0 additions & 1 deletion codex-rs/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ codex-sandboxing = { workspace = true }
codex-state = { workspace = true }
codex-terminal-detection = { workspace = true }
codex-thread-store = { workspace = true }
codex-tool-api = { workspace = true }
codex-tools = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-cache = { workspace = true }
Expand Down
4 changes: 2 additions & 2 deletions codex-rs/core/src/session/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ fn test_tool_runtime(session: Arc<Session>, turn_context: Arc<TurnContext>) -> T
mcp_tools: None,
deferred_mcp_tools: None,
discoverable_tools: None,
extension_tool_bundles: Vec::new(),
extension_tool_executors: Vec::new(),
dynamic_tools: turn_context.dynamic_tools.as_slice(),
},
));
Expand Down Expand Up @@ -8607,7 +8607,7 @@ async fn fatal_tool_error_stops_turn_and_reports_error() {
deferred_mcp_tools,
mcp_tools: Some(tools),
discoverable_tools: None,
extension_tool_bundles: Vec::new(),
extension_tool_executors: Vec::new(),
dynamic_tools: turn_context.dynamic_tools.as_slice(),
},
);
Expand Down
4 changes: 2 additions & 2 deletions codex-rs/core/src/session/turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ use crate::tools::context::SharedTurnDiffTracker;
use crate::tools::parallel::ToolCallRuntime;
use crate::tools::registry::ToolArgumentDiffConsumer;
use crate::tools::router::ToolRouterParams;
use crate::tools::router::extension_tool_bundles;
use crate::tools::router::extension_tool_executors;
use crate::turn_diff_tracker::TurnDiffTracker;
use crate::turn_timing::record_turn_ttft_metric;
use crate::util::backoff;
Expand Down Expand Up @@ -1250,7 +1250,7 @@ pub(crate) async fn built_tools(
mcp_tools,
deferred_mcp_tools,
discoverable_tools,
extension_tool_bundles: extension_tool_bundles(sess),
extension_tool_executors: extension_tool_executors(sess),
dynamic_tools: turn_context.dynamic_tools.as_slice(),
},
)))
Expand Down
167 changes: 55 additions & 112 deletions codex-rs/core/src/tools/handlers/extension_tools.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseInputItem;
use codex_tool_api::ToolBundle as ExtensionToolBundle;
use codex_tool_api::ToolError as ExtensionToolError;
use codex_tools::ResponsesApiTool;
use std::sync::Arc;

use codex_extension_api::ExtensionToolExecutor;
use codex_extension_api::ExtensionToolOutput;
use codex_tools::ToolCall as ExtensionToolCall;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use serde_json::Value;
Expand All @@ -19,46 +18,13 @@ use crate::tools::registry::PreToolUsePayload;
use crate::tools::registry::ToolExecutor;
use crate::tools::registry::ToolHandler;

pub(crate) struct BundledToolOutput {
value: Value,
}

impl ToolOutput for BundledToolOutput {
fn log_preview(&self) -> String {
self.value.to_string()
}

fn success_for_logging(&self) -> bool {
true
}

fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::Text(self.value.to_string()),
success: Some(true),
},
}
}

fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<Value> {
Some(self.value.clone())
}

fn code_mode_result(&self, _payload: &ToolPayload) -> Value {
self.value.clone()
}
}

pub(crate) struct BundledToolHandler {
bundle: ExtensionToolBundle,
spec: ToolSpec,
pub(crate) struct ExtensionToolHandler {
executor: Arc<dyn ExtensionToolExecutor>,
}

impl BundledToolHandler {
pub(crate) fn new(bundle: ExtensionToolBundle, spec: ToolSpec) -> Self {
Self { bundle, spec }
impl ExtensionToolHandler {
pub(crate) fn new(executor: Arc<dyn ExtensionToolExecutor>) -> Self {
Self { executor }
}

fn arguments_from_payload<'a>(&self, payload: &'a ToolPayload) -> Option<&'a str> {
Expand All @@ -69,41 +35,23 @@ impl BundledToolHandler {
}
}

impl ToolExecutor<ToolInvocation> for BundledToolHandler {
type Output = BundledToolOutput;
impl ToolExecutor<ToolInvocation> for ExtensionToolHandler {
type Output = ExtensionToolOutput;

fn tool_name(&self) -> ToolName {
ToolName::plain(self.bundle.tool_name())
self.executor.tool_name()
}

fn spec(&self) -> Option<ToolSpec> {
Some(self.spec.clone())
self.executor.spec()
}

async fn handle(&self, invocation: ToolInvocation) -> Result<Self::Output, FunctionCallError> {
let arguments = self
.arguments_from_payload(&invocation.payload)
.ok_or_else(|| {
FunctionCallError::Fatal(format!(
"tool {} invoked with incompatible payload",
self.bundle.tool_name()
))
})?
.to_string();
let value = self
.bundle
.executor()
.execute(codex_tool_api::ToolCall {
call_id: invocation.call_id,
arguments,
})
.await
.map_err(map_extension_tool_error)?;
Ok(BundledToolOutput { value })
self.executor.handle(to_extension_call(&invocation)).await
}
}

impl ToolHandler for BundledToolHandler {
impl ToolHandler for ExtensionToolHandler {
fn matches_kind(&self, payload: &ToolPayload) -> bool {
self.arguments_from_payload(payload).is_some()
Comment thread
jif-oai marked this conversation as resolved.
Resolved
}
Expand Down Expand Up @@ -132,23 +80,11 @@ impl ToolHandler for BundledToolHandler {
}
}

pub(crate) fn extension_tool_spec(
spec: &codex_tool_api::FunctionToolSpec,
) -> Result<ToolSpec, serde_json::Error> {
Ok(ToolSpec::Function(ResponsesApiTool {
name: spec.name.clone(),
description: spec.description.clone(),
strict: spec.strict,
defer_loading: None,
parameters: codex_tools::parse_tool_input_schema(&spec.parameters)?,
output_schema: None,
}))
}

fn map_extension_tool_error(error: ExtensionToolError) -> FunctionCallError {
match error {
ExtensionToolError::RespondToModel(message) => FunctionCallError::RespondToModel(message),
ExtensionToolError::Fatal(message) => FunctionCallError::Fatal(message),
fn to_extension_call(invocation: &ToolInvocation) -> ExtensionToolCall {
ExtensionToolCall {
call_id: invocation.call_id.clone(),
tool_name: invocation.tool_name.clone(),
payload: invocation.payload.clone(),
}
}

Expand All @@ -167,9 +103,7 @@ mod tests {
use pretty_assertions::assert_eq;
use serde_json::json;

use super::BundledToolHandler;
use super::BundledToolOutput;
use super::extension_tool_spec;
use super::ExtensionToolHandler;
use crate::tools::context::ToolCallSource;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
Expand All @@ -181,32 +115,43 @@ mod tests {

struct StubExtensionExecutor;

impl codex_tool_api::ToolExecutor for StubExtensionExecutor {
fn execute(&self, _call: codex_tool_api::ToolCall) -> codex_tool_api::ToolFuture<'_> {
Box::pin(async { Ok(json!({ "ok": true })) })
impl codex_extension_api::ExtensionToolExecutor for StubExtensionExecutor {
fn tool_name(&self) -> codex_tools::ToolName {
codex_tools::ToolName::plain("extension_echo")
}

fn spec(&self) -> Option<codex_tools::ToolSpec> {
Some(codex_tools::ToolSpec::Function(
codex_tools::ResponsesApiTool {
name: "extension_echo".to_string(),
description: "Echoes arguments.".to_string(),
strict: true,
parameters: codex_tools::parse_tool_input_schema(&json!({
"type": "object",
"properties": {
"message": { "type": "string" },
},
"required": ["message"],
"additionalProperties": false,
}))
.expect("extension schema should parse"),
output_schema: None,
defer_loading: None,
},
))
}

fn handle(
&self,
_call: codex_tools::ToolCall,
) -> codex_extension_api::ExtensionToolFuture<'_> {
Box::pin(async { Ok(codex_tools::JsonToolOutput::new(json!({ "ok": true }))) })
}
}

#[tokio::test]
async fn exposes_generic_hook_payloads() {
let bundle = codex_tool_api::ToolBundle::new(
codex_tool_api::FunctionToolSpec {
name: "extension_echo".to_string(),
description: "Echoes arguments.".to_string(),
strict: true,
parameters: json!({
"type": "object",
"properties": {
"message": { "type": "string" },
},
"required": ["message"],
"additionalProperties": false,
}),
},
Arc::new(StubExtensionExecutor),
);
let spec = extension_tool_spec(bundle.spec()).expect("extension spec should convert");
let handler = BundledToolHandler::new(bundle, spec);
let handler = ExtensionToolHandler::new(Arc::new(StubExtensionExecutor));
let (session, turn) = crate::session::tests::make_session_and_context().await;
let invocation = ToolInvocation {
session: session.into(),
Expand All @@ -220,9 +165,7 @@ mod tests {
arguments: json!({ "message": "hello" }).to_string(),
},
};
let output = BundledToolOutput {
value: json!({ "ok": true }),
};
let output = codex_tools::JsonToolOutput::new(json!({ "ok": true }));

assert_eq!(
ToolHandler::pre_tool_use_payload(&handler, &invocation),
Expand Down
24 changes: 8 additions & 16 deletions codex-rs/core/src/tools/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,14 @@ use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolOutput;
use crate::tools::context::ToolPayload;
use crate::tools::flat_tool_name;
use crate::tools::handlers::extension_tools::BundledToolHandler;
use crate::tools::handlers::extension_tools::extension_tool_spec;
use crate::tools::handlers::extension_tools::ExtensionToolHandler;
use crate::tools::hook_names::HookToolName;
use crate::tools::tool_dispatch_trace::ToolDispatchTrace;
use crate::tools::tool_search_entry::ToolSearchInfo;
use crate::util::error_or_panic;
use codex_extension_api::ExtensionToolExecutor;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::protocol::EventMsg;
use codex_tool_api::ToolBundle as ExtensionToolBundle;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use futures::future::BoxFuture;
Expand Down Expand Up @@ -584,25 +583,18 @@ impl ToolRegistryBuilder {
self.handlers.insert(name, handler);
}

pub fn register_tool_bundle(&mut self, bundle: ExtensionToolBundle) {
let tool_name = ToolName::plain(bundle.tool_name());
pub fn register_extension_tool_executor(&mut self, executor: Arc<dyn ExtensionToolExecutor>) {
let tool_name = executor.tool_name();
if self.handlers.contains_key(&tool_name) {
warn!("Skipping extension tool `{tool_name}`: handler already registered");
return;
}

let spec = match extension_tool_spec(bundle.spec()) {
Ok(spec) => spec,
Err(error) => {
error_or_panic(format!(
"failed to convert extension tool `{tool_name}` to a host spec: {error}"
));
return;
}
};
self.push_spec(spec.clone());
if let Some(spec) = executor.spec() {
self.push_spec(spec);
Comment thread
jif-oai marked this conversation as resolved.
Resolved
}

let handler: Arc<dyn AnyToolHandler> = Arc::new(BundledToolHandler::new(bundle, spec));
let handler: Arc<dyn AnyToolHandler> = Arc::new(ExtensionToolHandler::new(executor));
self.handlers.insert(tool_name, handler);
}

Expand Down
Loading
Loading