use std::collections::HashSet;
use serde_json::{Map, Value, json};
use switchyard_protocol::ProviderExtensions;
pub const CUSTOM_TOOLS_KEY: &str = "switchyard_codex_custom_tools";
pub const ADDITIONAL_TOOLS_KEY: &str = "switchyard_codex_additional_tools";
pub fn attach_additional_tools(extensions: &mut ProviderExtensions, tools: Vec<Value>) {
if !tools.is_empty() {
extensions
.fields
.insert(ADDITIONAL_TOOLS_KEY.to_string(), Value::Array(tools));
}
}
pub fn additional_tools(extensions: &ProviderExtensions) -> Option<&Vec<Value>> {
extensions
.fields
.get(ADDITIONAL_TOOLS_KEY)
.and_then(Value::as_array)
}
pub const CUSTOM_CALL_OUTPUTS_KEY: &str = "switchyard_codex_custom_call_outputs";
pub fn attach_custom_call_outputs(extensions: &mut ProviderExtensions, call_ids: Vec<String>) {
if !call_ids.is_empty() {
extensions.fields.insert(
CUSTOM_CALL_OUTPUTS_KEY.to_string(),
Value::Array(call_ids.into_iter().map(Value::String).collect()),
);
}
}
pub fn custom_call_outputs(extensions: &ProviderExtensions) -> HashSet<String> {
extensions
.fields
.get(CUSTOM_CALL_OUTPUTS_KEY)
.and_then(Value::as_array)
.map(|ids| {
ids.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect()
})
.unwrap_or_default()
}
pub const INPUT_ARGUMENT: &str = "input";
pub fn input_schema() -> Value {
json!({
"type": "object",
"properties": {INPUT_ARGUMENT: {"type": "string"}},
"required": [INPUT_ARGUMENT],
"additionalProperties": false,
})
}
pub fn attach_custom_tools(extensions: &mut ProviderExtensions, tools: Map<String, Value>) {
if !tools.is_empty() {
extensions
.fields
.insert(CUSTOM_TOOLS_KEY.to_string(), Value::Object(tools));
}
}
pub fn custom_tools(extensions: &ProviderExtensions) -> Option<&Map<String, Value>> {
extensions
.fields
.get(CUSTOM_TOOLS_KEY)
.and_then(Value::as_object)
}
pub fn custom_tool_names(extensions: &ProviderExtensions) -> HashSet<String> {
custom_tools(extensions)
.map(|tools| tools.keys().cloned().collect())
.unwrap_or_default()
}
pub fn input_from_arguments(arguments: &Value) -> String {
match arguments {
Value::Object(object) => match object.get(INPUT_ARGUMENT) {
Some(Value::String(input)) => input.clone(),
Some(other) => other.to_string(),
None => arguments.to_string(),
},
Value::String(text) => match serde_json::from_str::<Value>(text) {
Ok(Value::Object(object)) => match object.get(INPUT_ARGUMENT) {
Some(Value::String(input)) => input.clone(),
_ => text.clone(),
},
_ => text.clone(),
},
other => other.to_string(),
}
}
fn rewrite_item(item: &mut Value, custom: &HashSet<String>) -> bool {
let Some(object) = item.as_object_mut() else {
return false;
};
if object.get("type").and_then(Value::as_str) != Some("function_call") {
return false;
}
let Some(name) = object.get("name").and_then(Value::as_str) else {
return false;
};
if !custom.contains(name) {
return false;
}
let input = object
.remove("arguments")
.map(|arguments| input_from_arguments(&arguments))
.unwrap_or_default();
object.insert(
"type".to_string(),
Value::String("custom_tool_call".to_string()),
);
object.insert("input".to_string(), Value::String(input));
if let Some(Value::String(id)) = object.get_mut("id")
&& let Some(rest) = id.strip_prefix("fc_")
{
*id = format!("ctc_{rest}");
}
true
}
pub fn restore_custom_tool_calls(body: &mut Value, custom: &HashSet<String>) {
if custom.is_empty() {
return;
}
if let Some(items) = body.get_mut("output").and_then(Value::as_array_mut) {
for item in items {
rewrite_item(item, custom);
}
}
}
#[derive(Default)]
pub struct CustomToolCallStreamState {
custom_indexes: HashSet<u64>,
}
pub fn restore_custom_tool_calls_in_event(
event: &mut Value,
custom: &HashSet<String>,
state: &mut CustomToolCallStreamState,
) -> bool {
if custom.is_empty() {
return true;
}
let kind = event
.get("type")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let index = event.get("output_index").and_then(Value::as_u64);
match kind.as_str() {
"response.output_item.added" | "response.output_item.done" => {
if let Some(item) = event.get_mut("item")
&& rewrite_item(item, custom)
&& let Some(index) = index
{
state.custom_indexes.insert(index);
}
true
}
"response.function_call_arguments.delta" | "response.function_call_arguments.done" => {
!index.is_some_and(|index| state.custom_indexes.contains(&index))
}
"response.completed" | "response.incomplete" | "response.failed" => {
if let Some(response) = event.get_mut("response") {
restore_custom_tool_calls(response, custom);
}
true
}
_ => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn input_is_read_from_the_input_argument_or_left_verbatim() {
assert_eq!(input_from_arguments(&json!({"input": "ls -la"})), "ls -la");
assert_eq!(input_from_arguments(&json!("{\"input\":\"pwd\"}")), "pwd");
assert_eq!(input_from_arguments(&json!("raw text")), "raw text");
assert_eq!(
input_from_arguments(&json!({"cmd": "x"})),
"{\"cmd\":\"x\"}"
);
}
#[test]
fn function_call_items_for_custom_tools_become_custom_tool_calls() {
let custom: HashSet<String> = ["exec".to_string()].into_iter().collect();
let mut body = json!({"output": [
{"type": "function_call", "call_id": "c1", "name": "exec", "arguments": "{\"input\":\"ls\"}"},
{"type": "function_call", "call_id": "c2", "name": "update_plan", "arguments": "{}"}
]});
restore_custom_tool_calls(&mut body, &custom);
assert_eq!(body["output"][0]["type"], "custom_tool_call");
assert_eq!(body["output"][0]["input"], "ls");
assert!(body["output"][0].get("arguments").is_none());
assert_eq!(body["output"][1]["type"], "function_call");
}
#[test]
fn rewritten_custom_tool_calls_take_the_ctc_id_prefix() {
let custom: HashSet<String> = ["exec".to_string()].into_iter().collect();
let mut body = json!({"output": [
{"type": "function_call", "id": "fc_abc_1", "call_id": "c1", "name": "exec", "arguments": "{\"input\":\"ls\"}"}
]});
restore_custom_tool_calls(&mut body, &custom);
assert_eq!(body["output"][0]["type"], "custom_tool_call");
assert_eq!(body["output"][0]["id"], "ctc_abc_1");
}
#[test]
fn streamed_argument_deltas_for_custom_tools_are_dropped() {
let custom: HashSet<String> = ["exec".to_string()].into_iter().collect();
let mut state = CustomToolCallStreamState::default();
let mut added = json!({"type": "response.output_item.added", "output_index": 1,
"item": {"type": "function_call", "call_id": "c1", "name": "exec", "arguments": ""}});
assert!(restore_custom_tool_calls_in_event(
&mut added, &custom, &mut state
));
assert_eq!(added["item"]["type"], "custom_tool_call");
let mut delta = json!({"type": "response.function_call_arguments.delta", "output_index": 1, "delta": "{\"in"});
assert!(!restore_custom_tool_calls_in_event(
&mut delta, &custom, &mut state
));
let mut other = json!({"type": "response.function_call_arguments.delta", "output_index": 2, "delta": "{}"});
assert!(restore_custom_tool_calls_in_event(
&mut other, &custom, &mut state
));
let mut done = json!({"type": "response.output_item.done", "output_index": 1,
"item": {"type": "function_call", "call_id": "c1", "name": "exec", "arguments": "{\"input\":\"ls -la\"}"}});
assert!(restore_custom_tool_calls_in_event(
&mut done, &custom, &mut state
));
assert_eq!(done["item"]["input"], "ls -la");
}
}