use std::{
path::{Path, PathBuf},
process::Stdio,
sync::Arc,
};
use anyhow::Context as _;
use futures::{
StreamExt as _,
future::BoxFuture,
stream::{self, BoxStream},
};
use tokio::{
io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _, BufReader},
process::{ChildStdin, Command},
sync::OnceCell,
};
use super::gpt_api::{image_url, strict_schema};
use crate::{
message::{
Delta as _, FinishReason, Message, MessageDeltaOutput, MessageOutput, Part, PartDelta,
PartDeltaFunction, Role, TokenUsage,
},
model::{InferLangModel, LangModelOptions, ThinkingEffort},
tool::ToolDesc,
};
const DISABLED_FEATURES: &[&str] = &[
"shell_tool",
"unified_exec",
"js_repl",
"code_mode",
"apply_patch_freeform",
"view_image",
"sleep_tool",
"search_tool",
"request_permissions_tool",
"multi_agent",
"apps",
"memories",
"hooks",
"goals",
"image_generation",
];
const CONFIG: &[&str] = &[
"web_search=\"disabled\"",
"mcp_servers={}",
"project_doc_max_bytes=0",
"include_permissions_instructions=false",
"include_apps_instructions=false",
"include_collaboration_mode_instructions=false",
"include_environment_context=false",
"skills.include_instructions=false",
"skills.bundled.enabled=false",
"tools.experimental_request_user_input.enabled=false",
];
const OWN_TOOL_ITEMS: &[&str] = &[
"commandExecution",
"fileChange",
"mcpToolCall",
"webSearch",
"imageView",
"imageGeneration",
"collabAgentToolCall",
];
#[derive(Clone, Debug)]
pub struct CodexCliModel {
program: String,
model: Option<String>,
catalog: Arc<OnceCell<String>>,
}
impl Default for CodexCliModel {
fn default() -> Self {
Self::new()
}
}
impl CodexCliModel {
pub fn new() -> Self {
Self {
program: "codex".to_owned(),
model: None,
catalog: Arc::default(),
}
}
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
pub fn with_program(mut self, program: impl Into<String>) -> Self {
self.program = program.into();
self.catalog = Arc::default();
self
}
async fn catalog(&self) -> anyhow::Result<&str> {
let catalog = self
.catalog
.get_or_try_init(|| async {
let output = Command::new(&self.program)
.args(["debug", "models"])
.env("CODEX_HOME", codex_home()?)
.stdin(Stdio::null())
.output()
.await
.context("failed to start the codex CLI")?;
if !output.status.success() {
anyhow::bail!(
"codex debug models failed with {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr)
);
}
let catalog = serde_json::from_slice(&output.stdout)
.context("codex debug models printed no JSON catalog")?;
Ok(serde_json::to_string(&direct_catalog(catalog))?)
})
.await?;
Ok(catalog)
}
fn command(&self, home: &Path, workdir: &Path, catalog: &Path) -> anyhow::Result<Command> {
let mut command = Command::new(&self.program);
command.arg("app-server");
for config in CONFIG {
command.args(["-c", config]);
}
command.args([
"-c".to_owned(),
format!("model_catalog_json={}", serde_json::to_string(catalog)?),
]);
for feature in DISABLED_FEATURES {
command.args(["--disable", feature]);
}
command
.env("CODEX_HOME", home)
.current_dir(workdir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
Ok(command)
}
}
fn codex_home() -> anyhow::Result<PathBuf> {
let home = private_dir("codex-home")?;
link_login(&home)?;
Ok(home)
}
fn user_login() -> anyhow::Result<PathBuf> {
let home = match std::env::var_os("CODEX_HOME") {
Some(home) if !home.is_empty() => PathBuf::from(home),
_ => dirs::home_dir()
.context("no home directory for this user")?
.join(".codex"),
};
Ok(home.join("auth.json"))
}
fn link_login(home: &Path) -> anyhow::Result<()> {
let link = home.join("auth.json");
let target = user_login()?;
match std::fs::symlink_metadata(&link) {
Ok(meta) if meta.file_type().is_symlink() => {
if std::fs::read_link(&link)? == target {
return Ok(());
}
std::fs::remove_file(&link)?;
}
Ok(meta) if meta.is_file() => {
let newer = match std::fs::metadata(&target) {
Ok(user) => meta.modified()? > user.modified()?,
Err(_) => true,
};
if newer {
let dir = target.parent().context("the login has no directory")?;
std::fs::create_dir_all(dir)?;
let staged = tempfile::NamedTempFile::new_in(dir)?;
std::fs::write(staged.path(), std::fs::read(&link)?)?;
staged.persist(&target)?;
}
std::fs::remove_file(&link)?;
}
Ok(_) => anyhow::bail!("{} is not a file", link.display()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(&target, &link);
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(&target, &link);
match linked {
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
linked => linked.with_context(|| format!("failed to link {}", link.display())),
}
}
pub(super) fn private_dir(name: &str) -> anyhow::Result<PathBuf> {
let base = dirs::cache_dir()
.context("no cache directory for this user")?
.join("ailoy");
std::fs::create_dir_all(&base)?;
let dir = base.join(name);
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
builder.mode(0o700);
}
match builder.create(&dir) {
Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists => {
Err(e).with_context(|| format!("failed to create {}", dir.display()))?
}
_ => {}
}
let meta = std::fs::symlink_metadata(&dir)?;
anyhow::ensure!(meta.is_dir(), "{} is not a directory", dir.display());
#[cfg(unix)]
{
use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
let uid = tempfile::tempfile()?.metadata()?.uid();
anyhow::ensure!(
meta.uid() == uid,
"{} belongs to another user",
dir.display()
);
if meta.mode() & 0o077 != 0 {
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?;
}
}
Ok(dir)
}
fn direct_catalog(mut catalog: serde_json::Value) -> serde_json::Value {
for model in catalog["models"].as_array_mut().into_iter().flatten() {
let Some(model) = model.as_object_mut() else {
continue;
};
model.remove("tool_mode");
model.insert(
"experimental_supported_tools".to_owned(),
serde_json::json!([]),
);
model.insert("use_responses_lite".to_owned(), false.into());
model.remove("multi_agent_version");
model.remove("multi_agent_reasoning_effort");
if let Some(messages) = model
.get_mut("model_messages")
.and_then(|m| m.as_object_mut())
{
messages.remove("multi_agent");
}
}
catalog
}
impl InferLangModel for CodexCliModel {
fn infer(
&self,
messages: &[Message],
tools: &[ToolDesc],
options: &LangModelOptions,
) -> BoxFuture<'static, anyhow::Result<MessageOutput>> {
let mut deltas = self.infer_stream(messages, tools, options);
Box::pin(async move {
let mut acc = MessageDeltaOutput::new();
while let Some(delta) = deltas.next().await {
acc = acc.accumulate(delta?)?;
}
acc.finish()
})
}
fn infer_stream(
&self,
messages: &[Message],
tools: &[ToolDesc],
options: &LangModelOptions,
) -> BoxStream<'static, anyhow::Result<MessageDeltaOutput>> {
let plan = match Plan::new(messages, tools) {
Ok(plan) => plan,
Err(e) => return Box::pin(stream::once(async move { Err(e) })),
};
let this = self.clone();
let mut turn = serde_json::json!({"input": []});
if let Some(effort) = options.thinking_effort {
turn["effort"] = match effort {
ThinkingEffort::Low => "low",
ThinkingEffort::Medium => "medium",
ThinkingEffort::High => "high",
}
.into();
}
if let Some(schema) = &options.output_schema {
turn["outputSchema"] = strict_schema(schema).into();
}
Box::pin(async_stream::try_stream! {
let home = codex_home()?;
let workdir = tempfile::tempdir()?;
let catalog = workdir.path().join("models.json");
tokio::fs::write(&catalog, this.catalog().await?).await?;
let mut child = this
.command(&home, workdir.path(), &catalog)?
.spawn()
.context("failed to start the codex CLI")?;
let mut stdin = child.stdin.take().expect("stdin is piped");
let stdout = child.stdout.take().expect("stdout is piped");
let mut stderr = child.stderr.take().expect("stderr is piped");
let stderr = tokio::spawn(async move {
let mut buf = String::new();
let _ = stderr.read_to_string(&mut buf).await;
buf
});
let mut lines = BufReader::new(stdout).lines();
send(&mut stdin, serde_json::json!({
"id": 0,
"method": "initialize",
"params": {
"clientInfo": {"name": "ailoy", "title": null, "version": env!("CARGO_PKG_VERSION")},
"capabilities": {"experimentalApi": true, "requestAttestation": false},
},
})).await?;
response(&mut lines, 0).await?;
send(&mut stdin, serde_json::json!({"method": "initialized"})).await?;
let mut thread = serde_json::json!({
"cwd": workdir.path(),
"approvalPolicy": "never",
"sandbox": "read-only",
"environments": [],
"ephemeral": true,
"baseInstructions": plan.instructions,
"dynamicTools": plan.tools,
"experimentalRawEvents": true,
});
if let Some(model) = &this.model {
thread["model"] = model.as_str().into();
}
send(&mut stdin, serde_json::json!({"id": 1, "method": "thread/start", "params": thread})).await?;
let thread_id = response(&mut lines, 1).await?["thread"]["id"]
.as_str()
.context("thread/start returned no thread id")?
.to_owned();
send(&mut stdin, serde_json::json!({
"id": 2,
"method": "thread/inject_items",
"params": {"threadId": thread_id, "items": plan.history},
})).await?;
response(&mut lines, 2).await?;
turn["threadId"] = thread_id.into();
send(&mut stdin, serde_json::json!({"id": 3, "method": "turn/start", "params": turn})).await?;
let mut reader = Reader::new(plan.tool_names, plan.history_call_ids);
let mut finished = false;
while let Some(line) = lines.next_line().await? {
if line.trim().is_empty() {
continue;
}
let message: serde_json::Value = serde_json::from_str(&line)
.with_context(|| format!("unexpected output from codex: {line}"))?;
if let Some(out) = reader.on_message(message)? {
finished = out.finish_reason.is_some();
yield out;
if finished {
break;
}
}
}
let _ = child.start_kill();
let status = child.wait().await?;
link_login(&home)?;
if !finished {
let stderr = stderr.await.unwrap_or_default();
Err(anyhow::anyhow!("codex exited with {status} before finishing: {stderr}"))?;
}
drop(workdir);
})
}
}
#[derive(Debug)]
struct Plan {
instructions: String,
tools: Vec<serde_json::Value>,
tool_names: Vec<String>,
history: Vec<serde_json::Value>,
history_call_ids: Vec<String>,
}
impl Plan {
fn new(messages: &[Message], tools: &[ToolDesc]) -> anyhow::Result<Self> {
let (system, conversation): (Vec<&Message>, Vec<&Message>) =
messages.iter().partition(|m| m.role == Role::System);
let instructions = system
.into_iter()
.map(text_of)
.collect::<anyhow::Result<Vec<_>>>()?
.join("\n\n");
let tool_names = tools
.iter()
.map(|tool| tool.name.clone())
.collect::<Vec<_>>();
let tools = tools
.iter()
.map(|tool| {
serde_json::json!({
"type": "function",
"name": tool.name,
"description": tool.description.clone().unwrap_or_default(),
"inputSchema": tool.parameters,
})
})
.collect();
let Some(latest) = conversation.last() else {
anyhow::bail!("no message to send");
};
if !matches!(latest.role, Role::User | Role::Tool) {
anyhow::bail!("the last message must be a user message or tool results");
}
let history: Vec<serde_json::Value> = conversation
.iter()
.map(|message| response_items(message))
.collect::<anyhow::Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect();
let history_call_ids = history
.iter()
.filter(|item| item["type"] == "function_call")
.filter_map(|item| item["call_id"].as_str().map(str::to_owned))
.collect();
Ok(Self {
instructions,
tools,
tool_names,
history,
history_call_ids,
})
}
}
fn response_items(message: &Message) -> anyhow::Result<Vec<serde_json::Value>> {
let mut items = Vec::new();
match message.role {
Role::User => items.push(serde_json::json!({
"type": "message",
"role": "user",
"content": content_items(user_contents(message)?)?,
})),
Role::Assistant => {
let text = texts_of(message)?;
if !text.is_empty() {
items.push(serde_json::json!({
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": text}],
}));
}
for part in message.tool_calls.iter().flatten() {
let Part::Function { id, function } = part else {
anyhow::bail!("a tool call must be a function part");
};
items.push(serde_json::json!({
"type": "function_call",
"call_id": id,
"name": function.name,
"arguments": serde_json::to_string(&function.arguments)?,
}));
}
}
Role::Tool => {
let call_id = message
.id
.as_deref()
.context("a tool result must carry its call id")?;
let output = if message.contents.iter().any(Part::is_image) {
serde_json::Value::Array(content_items(&message.contents)?)
} else {
content_text(&message.contents)?.into()
};
items.push(serde_json::json!({
"type": "function_call_output",
"call_id": call_id,
"output": output,
}));
}
ref role => anyhow::bail!("CodexCliModel does not support {role} messages here"),
}
Ok(items)
}
#[derive(Default)]
struct Reader {
tool_names: Vec<String>,
history_call_ids: Vec<String>,
started: bool,
message_id: Option<String>,
calls: Vec<PartDelta>,
usage: Option<TokenUsage>,
}
impl Reader {
fn new(tool_names: Vec<String>, history_call_ids: Vec<String>) -> Self {
Self {
tool_names,
history_call_ids,
..Default::default()
}
}
fn on_message(
&mut self,
message: serde_json::Value,
) -> anyhow::Result<Option<MessageDeltaOutput>> {
let Some(method) = message["method"].as_str() else {
if let Some(error) = message.get("error") {
anyhow::bail!("codex rejected a request: {error}");
}
return Ok(None);
};
let params = &message["params"];
let is_request = message.get("id").is_some();
let mut out = MessageDeltaOutput::new();
match method {
"item/tool/call" => return Ok(None),
_ if is_request => anyhow::bail!("codex asked for {method}, which is not supported"),
"rawResponseItem/completed" => {
let item = ¶ms["item"];
let name = item["name"].as_str().unwrap_or_default();
let call_id = item["call_id"].as_str().unwrap_or_default();
if item["type"] == "function_call"
&& item.get("namespace").is_none()
&& self.tool_names.iter().any(|n| n == name)
&& !self.history_call_ids.iter().any(|id| id == call_id)
{
let arguments = item["arguments"].as_str().unwrap_or("{}");
let arguments = serde_json::from_str(arguments)
.unwrap_or_else(|_| serde_json::Value::String(arguments.to_owned()));
self.calls.push(PartDelta::Function {
id: Some(call_id.to_owned()),
function: PartDeltaFunction::WithParsedArgs {
name: name.to_owned(),
arguments: arguments.into(),
},
});
}
return Ok(None);
}
"rawResponse/completed" => {
self.usage = parse_usage(¶ms["usage"]);
if self.calls.is_empty() {
return Ok(None);
}
out.delta = out.delta.with_tool_calls(std::mem::take(&mut self.calls));
out.finish_reason = Some(FinishReason::ToolCall {});
out.usage = self.usage.take();
}
"item/agentMessage/delta" => {
let mut text = params["delta"].as_str().unwrap_or_default().to_owned();
let item = params["itemId"].as_str().map(str::to_owned);
if self.message_id.is_some() && self.message_id != item {
text.insert_str(0, "\n\n");
}
self.message_id = item;
out.delta = out.delta.with_contents([PartDelta::Text { text }]);
}
"item/reasoning/summaryTextDelta" | "item/reasoning/textDelta" => {
out.delta.thinking = Some(params["delta"].as_str().unwrap_or_default().to_owned());
}
"item/started" => {
let kind = params["item"]["type"].as_str().unwrap_or_default();
if OWN_TOOL_ITEMS.contains(&kind) {
anyhow::bail!("codex used a tool of its own ({kind}): {}", params["item"]);
}
return Ok(None);
}
"thread/tokenUsage/updated" => {
self.usage = parse_usage(¶ms["tokenUsage"]["last"]);
return Ok(None);
}
"turn/completed" => {
let turn = ¶ms["turn"];
match turn["status"].as_str() {
Some("completed") => {
out.finish_reason = Some(FinishReason::Stop {});
out.usage = self.usage.take();
}
status => {
let error = turn["error"]["message"].as_str().unwrap_or_default();
anyhow::bail!("codex turn {}: {error}", status.unwrap_or("ended"));
}
}
}
_ => return Ok(None),
}
if !self.started {
out.delta.role = Some(Role::Assistant);
self.started = true;
}
Ok(Some(out))
}
}
async fn send(stdin: &mut ChildStdin, message: serde_json::Value) -> anyhow::Result<()> {
let mut line = serde_json::to_string(&message)?;
line.push('\n');
stdin.write_all(line.as_bytes()).await?;
stdin.flush().await?;
Ok(())
}
async fn response(
lines: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
id: u64,
) -> anyhow::Result<serde_json::Value> {
while let Some(line) = lines.next_line().await? {
let Ok(message) = serde_json::from_str::<serde_json::Value>(&line) else {
continue;
};
if message["id"] != id || message.get("method").is_some() {
continue;
}
if let Some(error) = message.get("error") {
anyhow::bail!("codex rejected request {id}: {error}");
}
return Ok(message["result"].clone());
}
anyhow::bail!("codex exited before answering request {id}")
}
fn text_of(message: &Message) -> anyhow::Result<String> {
if message.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty()) {
anyhow::bail!("only assistant messages can carry tool calls");
}
texts_of(message)
}
fn user_contents(message: &Message) -> anyhow::Result<&[Part]> {
if message.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty()) {
anyhow::bail!("only assistant messages can carry tool calls");
}
Ok(&message.contents)
}
fn content_items(parts: &[Part]) -> anyhow::Result<Vec<serde_json::Value>> {
parts
.iter()
.map(|part| {
Ok(match part {
Part::Image { image } => {
serde_json::json!({"type": "input_image", "image_url": image_url(image)})
}
_ => serde_json::json!({"type": "input_text", "text": part_text(part)?}),
})
})
.collect()
}
fn content_text(parts: &[Part]) -> anyhow::Result<String> {
let texts = parts
.iter()
.filter(|part| !part.is_image())
.map(part_text)
.collect::<anyhow::Result<Vec<_>>>()?;
Ok(texts.join("\n"))
}
fn part_text(part: &Part) -> anyhow::Result<String> {
Ok(match part {
Part::Text { text } => text.clone(),
Part::Value { value } => match value.as_str() {
Some(s) => s.to_owned(),
None => serde_json::to_string(value)?,
},
_ => anyhow::bail!("CodexCliModel takes only text, values and images in message contents"),
})
}
fn texts_of(message: &Message) -> anyhow::Result<String> {
let texts = message
.contents
.iter()
.map(|part| {
part.as_text()
.ok_or_else(|| anyhow::anyhow!("CodexCliModel supports only text parts"))
})
.collect::<anyhow::Result<Vec<_>>>()?;
Ok(texts.join("\n"))
}
fn parse_usage(u: &serde_json::Value) -> Option<TokenUsage> {
Some(TokenUsage {
input_tokens: u["inputTokens"].as_u64()?,
output_tokens: u["outputTokens"].as_u64()?,
cache_creation_input_tokens: u["cacheWriteInputTokens"].as_u64(),
cache_read_input_tokens: u["cachedInputTokens"].as_u64(),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn weather_call() -> [Message; 3] {
[
Message::new(Role::User).with_contents([Part::text("weather?")]),
Message::new(Role::Assistant).with_tool_calls([Part::function(
"c1",
"get_weather",
serde_json::json!({"city": "Seoul"}),
)]),
Message::new(Role::Tool)
.with_id("c1")
.with_contents([Part::text("sunny")]),
]
}
#[test]
fn tool_results_go_into_the_history() {
let mut messages =
vec![Message::new(Role::System).with_contents([Part::text("Be brief.")])];
messages.extend(weather_call());
let plan = Plan::new(&messages, &[]).unwrap();
assert_eq!(plan.instructions, "Be brief.");
assert_eq!(plan.history_call_ids, ["c1"]);
assert_eq!(
serde_json::Value::Array(plan.history),
serde_json::json!([
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "weather?"}]},
{"type": "function_call", "call_id": "c1", "name": "get_weather", "arguments": "{\"city\":\"Seoul\"}"},
{"type": "function_call_output", "call_id": "c1", "output": "sunny"},
])
);
}
#[test]
fn latest_user_message_goes_into_the_history() {
let mut messages = weather_call().to_vec();
messages.push(Message::new(Role::User).with_contents([Part::text("and Tokyo?")]));
let plan = Plan::new(&messages, &[]).unwrap();
assert_eq!(plan.history.len(), 4);
assert_eq!(
plan.history[3],
serde_json::json!({"type": "message", "role": "user", "content": [{"type": "input_text", "text": "and Tokyo?"}]})
);
}
fn read(messages: &[serde_json::Value]) -> anyhow::Result<Vec<MessageDeltaOutput>> {
let mut reader = Reader::new(vec!["get_weather".to_owned()], vec!["call_0".to_owned()]);
let mut outs = Vec::new();
for message in messages {
if let Some(out) = reader.on_message(message.clone())? {
let finished = out.finish_reason.is_some();
outs.push(out);
if finished {
break;
}
}
}
Ok(outs)
}
fn calls(out: &MessageDeltaOutput) -> Vec<(Option<String>, String, serde_json::Value)> {
out.delta
.tool_calls
.iter()
.map(|call| {
let PartDelta::Function {
id,
function: PartDeltaFunction::WithParsedArgs { name, arguments },
} = call
else {
panic!("not a parsed call: {call:?}");
};
(
id.clone(),
name.clone(),
serde_json::to_value(arguments).unwrap(),
)
})
.collect()
}
#[test]
fn all_calls_end_the_reply_with_usage() {
let function_call = |id: &str, name: &str, city: &str| {
serde_json::json!({"method": "rawResponseItem/completed", "params": {"item": {
"type": "function_call", "call_id": id, "name": name,
"arguments": format!("{{\"city\":\"{city}\"}}"),
}}})
};
let outs = read(&[
serde_json::json!({"id": 3, "result": {"turn": {"id": "t"}}}),
function_call("call_0", "get_weather", "Busan"),
serde_json::json!({"method": "item/agentMessage/delta", "params": {"itemId": "m1", "delta": "Let me check."}}),
function_call("call_1", "get_weather", "Seoul"),
serde_json::json!({"id": 0, "method": "item/tool/call", "params": {"callId": "call_1", "tool": "get_weather", "arguments": {"city": "Seoul"}}}),
function_call("call_2", "get_weather", "Tokyo"),
function_call("call_3", "not_ours", "Paris"),
serde_json::json!({"method": "rawResponse/completed", "params": {"responseId": "r", "usage": {"totalTokens": 15, "inputTokens": 10, "cachedInputTokens": 4, "cacheWriteInputTokens": 0, "outputTokens": 5, "reasoningOutputTokens": 0}}}),
])
.unwrap();
assert_eq!(outs[0].delta.role, Some(Role::Assistant));
let last = outs.last().unwrap();
assert!(matches!(
last.finish_reason,
Some(FinishReason::ToolCall {})
));
assert_eq!(
calls(last),
[
(
Some("call_1".to_owned()),
"get_weather".to_owned(),
serde_json::json!({"city": "Seoul"})
),
(
Some("call_2".to_owned()),
"get_weather".to_owned(),
serde_json::json!({"city": "Tokyo"})
),
]
);
let usage = last.usage.as_ref().unwrap();
assert_eq!(
(usage.input_tokens, usage.cache_read_input_tokens),
(10, Some(4))
);
}
#[test]
fn turn_end_closes_or_fails_the_reply() {
let outs = read(&[
serde_json::json!({"method": "item/agentMessage/delta", "params": {"itemId": "m1", "delta": "Hi."}}),
serde_json::json!({"method": "item/agentMessage/delta", "params": {"itemId": "m2", "delta": "Bye."}}),
serde_json::json!({"method": "turn/completed", "params": {"turn": {"status": "completed", "error": null}}}),
])
.unwrap();
assert!(
matches!(&outs[1].delta.contents[..], [PartDelta::Text { text }] if text == "\n\nBye.")
);
assert!(matches!(outs[2].finish_reason, Some(FinishReason::Stop {})));
let err = read(&[serde_json::json!({"method": "turn/completed", "params": {"turn": {"status": "failed", "error": {"message": "401 Unauthorized"}}}})])
.unwrap_err();
assert!(err.to_string().contains("401"), "{err}");
}
#[test]
fn catalog_drops_code_mode_and_multi_agent() {
let catalog = direct_catalog(serde_json::json!({"models": [{
"slug": "gpt",
"tool_mode": "code_mode_only",
"multi_agent_version": 2,
"model_messages": {"multi_agent": {}, "approvals": {}},
"experimental_supported_tools": ["clock"],
"use_responses_lite": true,
}]}));
assert_eq!(
catalog,
serde_json::json!({"models": [{
"slug": "gpt",
"model_messages": {"approvals": {}},
"experimental_supported_tools": [],
"use_responses_lite": false,
}]})
);
}
#[test]
fn own_tool_use_fails() {
let err = read(&[serde_json::json!({"method": "item/started", "params": {"item": {"type": "commandExecution", "id": "x"}}})])
.unwrap_err();
assert!(err.to_string().contains("commandExecution"), "{err}");
}
#[test]
fn images_go_as_input_images() {
let image = || Part::image_embedded("image/png", vec![1, 2, 3].into()).unwrap();
let url = "data:image/png;base64,AQID";
let messages = [
Message::new(Role::User).with_contents([Part::text("look"), image()]),
Message::new(Role::Assistant).with_tool_calls([Part::function(
"c1",
"imgread",
serde_json::json!({"path": "a.png"}),
)]),
Message::new(Role::Tool)
.with_id("c1")
.with_contents([image()]),
Message::new(Role::User).with_contents([Part::text("and this?"), image()]),
];
let plan = Plan::new(&messages, &[]).unwrap();
assert_eq!(
plan.history[0]["content"],
serde_json::json!([
{"type": "input_text", "text": "look"},
{"type": "input_image", "image_url": url},
])
);
assert_eq!(
plan.history[2]["output"],
serde_json::json!([{"type": "input_image", "image_url": url}])
);
assert_eq!(
plan.history[3]["content"],
serde_json::json!([
{"type": "input_text", "text": "and this?"},
{"type": "input_image", "image_url": url},
])
);
}
}