use std::{
ffi::OsStr,
path::Path,
time::{Duration, Instant},
};
use kcode_codex_terra_protocol::{
MODEL, NotificationKind, app_server_command, classify_notification, initialize_params,
thread_start_params, tool_success_result, turn_start_params,
};
use serde_json::{Value, json};
fn scope() -> Value {
json!({"threadId":"thread-1","turnId":"turn-1"})
}
fn scoped_item(kind: &str) -> Value {
json!({
"threadId":"thread-1",
"turnId":"turn-1",
"item":{"type":kind}
})
}
fn failure(method: &str, params: &Value) -> String {
classify_notification(method, params, "thread-1", "turn-1")
.unwrap_err()
.to_string()
}
#[test]
fn command_is_configured_without_spawning() {
let command = app_server_command(Path::new("/tools/codex"), Path::new("/work"));
let standard = command.as_std();
assert_eq!(standard.get_program(), OsStr::new("/tools/codex"));
assert_eq!(standard.get_current_dir(), Some(Path::new("/work")));
assert_eq!(
standard
.get_args()
.map(|argument| argument.to_string_lossy().into_owned())
.collect::<Vec<_>>(),
vec![
"-c",
"web_search=\"disabled\"",
"-c",
"mcp_servers={}",
"-c",
"features.shell_tool=false",
"-c",
"features.apps=false",
"-c",
"features.browser_use=false",
"-c",
"features.computer_use=false",
"-c",
"features.goals=false",
"-c",
"features.hooks=false",
"-c",
"features.image_generation=false",
"-c",
"features.multi_agent=false",
"-c",
"features.plugins=false",
"-c",
"features.tool_suggest=false",
"-c",
"features.remote_plugin=false",
"-c",
"model_auto_compact_token_limit=9223372036854775807",
"app-server",
"--stdio",
]
);
let environments = standard
.get_envs()
.map(|(name, value)| {
(
name.to_string_lossy().into_owned(),
value.map(|item| item.to_string_lossy().into_owned()),
)
})
.collect::<Vec<_>>();
assert!(environments.contains(&("OPENAI_API_KEY".into(), None)));
assert!(environments.contains(&("CODEX_API_KEY".into(), None)));
}
#[test]
fn request_values_are_exact() {
assert_eq!(MODEL, "gpt-5.6-terra");
assert_eq!(
initialize_params("0.1.0"),
json!({
"clientInfo":{"name":"kcode-codex-terra","version":"0.1.0"},
"capabilities":{"experimentalApi":true}
})
);
assert_eq!(
thread_start_params(
Path::new("/work"),
"extract".into(),
"Extract one value".into(),
json!({"type":"object"})
),
json!({
"model":"gpt-5.6-terra",
"cwd":"/work",
"approvalPolicy":"never",
"sandbox":"readOnly",
"baseInstructions":"",
"developerInstructions":
"Call the supplied dynamic function exactly once. Do not produce assistant prose.",
"dynamicTools":[{
"type":"function",
"name":"extract",
"description":"Extract one value",
"inputSchema":{"type":"object"}
}],
"ephemeral":true,
"environments":[]
})
);
assert_eq!(
turn_start_params("thread-1", "caller text".into()),
json!({
"threadId":"thread-1",
"input":[{"type":"text","text":"caller text"}],
"approvalPolicy":"never"
})
);
assert_eq!(
tool_success_result(),
json!({"success":true,"contentItems":[{"type":"inputText","text":"ok"}]})
);
}
#[test]
fn recognized_notifications_are_classified() {
assert_eq!(
classify_notification(
"thread/started",
&json!({"thread":{"id":"thread-1"}}),
"thread-1",
"turn-1"
)
.unwrap(),
NotificationKind::Continue
);
assert_eq!(
classify_notification(
"thread/tokenUsage/updated",
&json!({"threadId":"thread-1","turnId":"turn-1","tokenUsage":{}}),
"thread-1",
"turn-1"
)
.unwrap(),
NotificationKind::Usage
);
assert_eq!(
classify_notification(
"turn/started",
&json!({"threadId":"thread-1","turn":{"id":"turn-1"}}),
"thread-1",
"turn-1"
)
.unwrap(),
NotificationKind::Continue
);
for item in [
"userMessage",
"agentMessage",
"reasoning",
"dynamicToolCall",
] {
for method in ["item/started", "item/completed", "item/updated"] {
assert_eq!(
classify_notification(method, &scoped_item(item), "thread-1", "turn-1").unwrap(),
NotificationKind::Continue
);
}
}
assert_eq!(
classify_notification(
"turn/completed",
&json!({
"threadId":"thread-1",
"turn":{"id":"turn-1","status":"completed"}
}),
"thread-1",
"turn-1"
)
.unwrap(),
NotificationKind::TurnCompleted
);
}
#[test]
fn generic_notification_rules_are_preserved() {
for method in ["model/safetyBuffering/updated", "model/verification"] {
assert_eq!(
classify_notification(method, &scope(), "thread-1", "turn-1").unwrap(),
NotificationKind::Continue
);
}
assert_eq!(
classify_notification(
"thread/updated",
&json!({"threadId":"thread-1"}),
"thread-1",
"turn-1"
)
.unwrap(),
NotificationKind::Continue
);
assert_eq!(
classify_notification("turn/updated", &scope(), "thread-1", "turn-1").unwrap(),
NotificationKind::Continue
);
assert_eq!(
classify_notification("item/updated", &scope(), "thread-1", "turn-1").unwrap(),
NotificationKind::Continue
);
}
#[test]
fn invalid_identifiers_and_required_values_fail() {
assert_eq!(
failure("thread/started", &json!({"thread":{"id":"other"}})),
"Codex used a mismatched identifier"
);
assert_eq!(
failure(
"thread/tokenUsage/updated",
&json!({"threadId":"thread-1","turnId":"turn-1"})
),
"Codex omitted token usage"
);
assert_eq!(
failure(
"turn/started",
&json!({"threadId":"thread-1","turn":{"id":"other"}})
),
"Codex used a mismatched identifier"
);
assert_eq!(
failure(
"item/started",
&json!({"threadId":"thread-1","turnId":"turn-1"})
),
"Codex item event omitted its item type"
);
assert_eq!(
failure(
"turn/completed",
&json!({
"threadId":"thread-1",
"turn":{"id":"turn-1","status":"failed"}
})
),
"Codex turn failed"
);
assert_eq!(
failure("thread/updated", &json!({"threadId":"other"})),
"Codex used a mismatched identifier"
);
assert_eq!(
failure(
"turn/updated",
&json!({"threadId":"thread-1","turnId":"other"})
),
"Codex used a mismatched identifier"
);
}
#[test]
fn disabled_items_and_events_fail() {
assert_eq!(
failure("item/completed", &scoped_item("commandExecution")),
"Codex attempted a disabled built-in tool"
);
assert_eq!(
failure("item/updated", &scoped_item("imageView")),
"Codex attempted a disabled built-in tool"
);
for disabled in [
"commandExecution",
"fileChange",
"mcpToolCall",
"webSearch",
"imageView",
"imageGeneration",
"collabAgentToolCall",
"subAgentActivity",
] {
assert_eq!(
failure(&format!("event/{disabled}"), &json!({})),
"Codex attempted a disabled capability"
);
}
assert_eq!(
failure("model/rerouted", &json!({})),
"Codex attempted a disabled capability"
);
assert_eq!(
failure("unexpected/event", &json!({})),
"Codex emitted an unexpected event"
);
}
#[test]
fn local_canary() {
let notification = json!({
"threadId":"thread-1",
"turnId":"turn-1",
"item":{
"type":"dynamicToolCall",
"payload":"x".repeat(900)
}
});
let start = Instant::now();
for _ in 0..100_000 {
assert_eq!(
classify_notification("item/updated", ¬ification, "thread-1", "turn-1").unwrap(),
NotificationKind::Continue
);
}
let limit = if cfg!(debug_assertions) {
Duration::from_secs(5)
} else {
Duration::from_secs(1)
};
assert!(start.elapsed() < limit);
}