use std::collections::BTreeMap;
use std::fmt;
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Map, Value, json};
macro_rules! forward_compatible_string_enum {
(
$(#[$meta:meta])*
pub enum $name:ident {
$($variant:ident = $value:literal),+ $(,)?
}
) => {
$(#[$meta])*
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum $name {
$($variant),+,
Unknown(String),
}
impl $name {
pub fn as_str(&self) -> &str {
match self {
$(Self::$variant => $value),+,
Self::Unknown(value) => value,
}
}
}
impl Serialize for $name {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Ok(match value.as_str() {
$($value => Self::$variant),+,
_ => Self::Unknown(value),
})
}
}
impl fmt::Display for $name {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
};
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ApprovalMode {
DenyAll,
#[default]
AutoReview,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Sandbox {
ReadOnly,
WorkspaceWrite,
FullAccess,
}
impl Sandbox {
pub(crate) fn mode(self) -> &'static str {
match self {
Self::ReadOnly => "read-only",
Self::WorkspaceWrite => "workspace-write",
Self::FullAccess => "danger-full-access",
}
}
pub(crate) fn policy(self) -> Value {
match self {
Self::ReadOnly => json!({
"networkAccess": false,
"type": "readOnly",
}),
Self::WorkspaceWrite => json!({
"excludeSlashTmp": false,
"excludeTmpdirEnvVar": false,
"networkAccess": false,
"type": "workspaceWrite",
"writableRoots": [],
}),
Self::FullAccess => json!({"type": "dangerFullAccess"}),
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalsReviewer {
User,
AutoReview,
GuardianSubagent,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AskForApprovalValue {
#[serde(rename = "untrusted")]
Untrusted,
#[serde(rename = "on-request")]
OnRequest,
#[serde(rename = "never")]
Never,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(untagged)]
pub enum AskForApproval {
Preset(AskForApprovalValue),
Granular(Value),
}
forward_compatible_string_enum! {
pub enum ReasoningEffort {
None = "none",
Minimal = "minimal",
Low = "low",
Medium = "medium",
High = "high",
XHigh = "xhigh",
Max = "max",
Ultra = "ultra"
}
}
forward_compatible_string_enum! {
pub enum PlanType {
Free = "free",
Go = "go",
Plus = "plus",
Pro = "pro",
Prolite = "prolite",
Team = "team",
SelfServeBusinessUsageBased = "self_serve_business_usage_based",
Business = "business",
EnterpriseCbpUsageBased = "enterprise_cbp_usage_based",
Enterprise = "enterprise",
Edu = "edu",
UnknownPlan = "unknown"
}
}
forward_compatible_string_enum! {
pub enum ThreadSource {
User = "user",
Subagent = "subagent",
MemoryConsolidation = "memory_consolidation"
}
}
forward_compatible_string_enum! {
pub enum MessagePhase {
Commentary = "commentary",
FinalAnswer = "final_answer"
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Personality {
None,
Friendly,
Pragmatic,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ReasoningSummary {
Auto,
Concise,
Detailed,
None,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum SandboxMode {
#[serde(rename = "read-only")]
ReadOnly,
#[serde(rename = "workspace-write")]
WorkspaceWrite,
#[serde(rename = "danger-full-access")]
DangerFullAccess,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(transparent)]
pub struct SandboxPolicy(pub Value);
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SortDirection {
Asc,
Desc,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ThreadSortKey {
#[serde(rename = "created_at")]
CreatedAt,
#[serde(rename = "updated_at")]
UpdatedAt,
#[serde(rename = "recency_at")]
RecencyAt,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ThreadSourceKind {
#[serde(rename = "cli")]
Cli,
#[serde(rename = "vscode")]
Vscode,
#[serde(rename = "exec")]
Exec,
#[serde(rename = "appServer")]
AppServer,
#[serde(rename = "subAgent")]
SubAgent,
#[serde(rename = "subAgentReview")]
SubAgentReview,
#[serde(rename = "subAgentCompact")]
SubAgentCompact,
#[serde(rename = "subAgentThreadSpawn")]
SubAgentThreadSpawn,
#[serde(rename = "subAgentOther")]
SubAgentOther,
#[serde(rename = "unknown")]
Unknown,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ThreadStartSource {
Startup,
Clear,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(untagged)]
pub enum ThreadListCwdFilter {
One(String),
Many(Vec<String>),
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum TurnStatus {
#[serde(rename = "completed")]
Completed,
#[serde(rename = "interrupted")]
Interrupted,
#[serde(rename = "failed")]
Failed,
#[serde(rename = "inProgress")]
InProgress,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum InputItem {
#[serde(rename = "text")]
Text { text: String },
#[serde(rename = "image")]
Image { url: String },
#[serde(rename = "localImage")]
LocalImage { path: String },
#[serde(rename = "skill")]
Skill { name: String, path: String },
#[serde(rename = "mention")]
Mention { name: String, path: String },
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TextInput {
pub text: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ImageInput {
pub url: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct LocalImageInput {
pub path: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct SkillInput {
pub name: String,
pub path: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MentionInput {
pub name: String,
pub path: String,
}
impl InputItem {
pub fn text(text: impl Into<String>) -> Self {
Self::Text { text: text.into() }
}
pub fn image(url: impl Into<String>) -> Self {
Self::Image { url: url.into() }
}
pub fn local_image(path: impl Into<String>) -> Self {
Self::LocalImage { path: path.into() }
}
pub fn skill(name: impl Into<String>, path: impl Into<String>) -> Self {
Self::Skill {
name: name.into(),
path: path.into(),
}
}
pub fn mention(name: impl Into<String>, path: impl Into<String>) -> Self {
Self::Mention {
name: name.into(),
path: path.into(),
}
}
}
impl From<TextInput> for InputItem {
fn from(input: TextInput) -> Self {
Self::Text { text: input.text }
}
}
impl From<ImageInput> for InputItem {
fn from(input: ImageInput) -> Self {
Self::Image { url: input.url }
}
}
impl From<LocalImageInput> for InputItem {
fn from(input: LocalImageInput) -> Self {
Self::LocalImage { path: input.path }
}
}
impl From<SkillInput> for InputItem {
fn from(input: SkillInput) -> Self {
Self::Skill {
name: input.name,
path: input.path,
}
}
}
impl From<MentionInput> for InputItem {
fn from(input: MentionInput) -> Self {
Self::Mention {
name: input.name,
path: input.path,
}
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(transparent)]
pub struct Input(pub Vec<InputItem>);
impl From<Vec<InputItem>> for Input {
fn from(items: Vec<InputItem>) -> Self {
Self(items)
}
}
impl From<String> for Input {
fn from(text: String) -> Self {
Self(vec![InputItem::text(text)])
}
}
impl From<&str> for Input {
fn from(text: &str) -> Self {
Self::from(text.to_owned())
}
}
impl<T> From<T> for Input
where
T: Into<InputItem>,
{
fn from(item: T) -> Self {
Self(vec![item.into()])
}
}
pub type RunInput = Input;
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerInfo {
pub name: Option<String>,
pub version: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResponse {
pub server_info: Option<ServerInfo>,
pub user_agent: Option<String>,
pub platform_family: Option<String>,
pub platform_os: Option<String>,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TurnError {
pub message: String,
pub additional_details: Option<String>,
pub codex_error_info: Option<Value>,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenUsageBreakdown {
pub cached_input_tokens: u64,
pub input_tokens: u64,
pub output_tokens: u64,
pub reasoning_output_tokens: u64,
pub total_tokens: u64,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadTokenUsage {
pub last: TokenUsageBreakdown,
pub model_context_window: Option<u64>,
pub total: TokenUsageBreakdown,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentMessageThreadItem {
pub id: String,
pub text: String,
pub phase: Option<MessagePhase>,
pub memory_citation: Option<Value>,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RawThreadItem {
pub fields: Map<String, Value>,
}
impl RawThreadItem {
pub fn kind(&self) -> Option<&str> {
self.fields.get("type").and_then(Value::as_str)
}
pub fn id(&self) -> Option<&str> {
self.fields.get("id").and_then(Value::as_str)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ThreadItem {
AgentMessage(AgentMessageThreadItem),
Other(RawThreadItem),
}
impl ThreadItem {
pub fn id(&self) -> Option<&str> {
match self {
Self::AgentMessage(item) => Some(&item.id),
Self::Other(item) => item.id(),
}
}
pub fn kind(&self) -> Option<&str> {
match self {
Self::AgentMessage(_) => Some("agentMessage"),
Self::Other(item) => item.kind(),
}
}
pub fn as_agent_message(&self) -> Option<&AgentMessageThreadItem> {
match self {
Self::AgentMessage(item) => Some(item),
Self::Other(_) => None,
}
}
fn into_value(self) -> Value {
match self {
Self::AgentMessage(item) => {
let mut value =
serde_json::to_value(item).expect("serializing ThreadItem cannot fail");
value
.as_object_mut()
.expect("AgentMessageThreadItem serializes as an object")
.insert("type".into(), Value::String("agentMessage".into()));
value
}
Self::Other(item) => Value::Object(item.fields),
}
}
}
impl Serialize for ThreadItem {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
self.clone().into_value().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ThreadItem {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let Value::Object(mut fields) = Value::deserialize(deserializer)? else {
return Err(D::Error::custom("thread item must be an object"));
};
if fields.get("type").and_then(Value::as_str) == Some("agentMessage") {
fields.remove("type");
let candidate = serde_json::from_value(Value::Object(fields.clone()));
if let Ok(item) = candidate {
return Ok(Self::AgentMessage(item));
}
fields.insert("type".into(), Value::String("agentMessage".into()));
}
Ok(Self::Other(RawThreadItem { fields }))
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Turn {
pub completed_at: Option<i64>,
pub duration_ms: Option<i64>,
pub error: Option<TurnError>,
pub id: String,
pub items: Vec<ThreadItem>,
pub items_view: Option<String>,
pub started_at: Option<i64>,
pub status: TurnStatus,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadData {
pub agent_nickname: Option<String>,
pub agent_role: Option<String>,
pub cli_version: String,
pub created_at: i64,
pub cwd: String,
pub ephemeral: bool,
pub forked_from_id: Option<String>,
pub git_info: Option<Value>,
pub id: String,
pub model_provider: String,
pub name: Option<String>,
pub parent_thread_id: Option<String>,
pub path: Option<String>,
pub preview: String,
pub recency_at: Option<i64>,
pub session_id: String,
pub source: Value,
pub status: Value,
pub thread_source: Option<ThreadSource>,
pub turns: Vec<Turn>,
pub updated_at: i64,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
pub type ThreadRecord = ThreadData;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadListResponse {
pub backwards_cursor: Option<String>,
pub data: Vec<ThreadData>,
pub next_cursor: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ThreadReadResponse {
pub thread: ThreadData,
}
macro_rules! empty_response {
($($name:ident),+ $(,)?) => {
$(
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct $name {
#[serde(flatten)]
pub extra: Map<String, Value>,
}
)+
};
}
empty_response!(
ThreadArchiveResponse,
ThreadCompactStartResponse,
ThreadSetNameResponse,
TurnInterruptResponse,
);
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TurnSteerResponse {
pub turn_id: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum Account {
#[serde(rename = "apiKey")]
ApiKey,
#[serde(rename = "chatgpt")]
Chatgpt {
email: Option<String>,
#[serde(rename = "planType")]
plan_type: PlanType,
},
#[serde(rename = "amazonBedrock")]
AmazonBedrock {
#[serde(rename = "credentialSource")]
credential_source: Option<String>,
},
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAccountResponse {
pub account: Option<Account>,
pub requires_openai_auth: bool,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum CancelLoginAccountStatus {
#[serde(rename = "canceled")]
Canceled,
#[serde(rename = "notFound")]
NotFound,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CancelLoginAccountResponse {
pub status: CancelLoginAccountStatus,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Model {
#[serde(default = "default_additional_speed_tiers")]
pub additional_speed_tiers: Option<Vec<String>>,
pub availability_nux: Option<Value>,
pub default_reasoning_effort: ReasoningEffort,
pub default_service_tier: Option<String>,
pub description: String,
pub display_name: String,
pub hidden: bool,
pub id: String,
#[serde(default = "default_input_modalities")]
pub input_modalities: Option<Vec<String>>,
pub is_default: bool,
pub model: String,
#[serde(default = "default_service_tiers")]
pub service_tiers: Option<Vec<Value>>,
pub supported_reasoning_efforts: Vec<ReasoningEffortOption>,
#[serde(default = "default_supports_personality")]
pub supports_personality: Option<bool>,
pub upgrade: Option<String>,
pub upgrade_info: Option<Value>,
#[serde(flatten)]
pub extra: Map<String, Value>,
}
#[allow(clippy::unnecessary_wraps)]
fn default_additional_speed_tiers() -> Option<Vec<String>> {
Some(Vec::new())
}
#[allow(clippy::unnecessary_wraps)]
fn default_input_modalities() -> Option<Vec<String>> {
Some(vec!["text".into(), "image".into()])
}
#[allow(clippy::unnecessary_wraps)]
fn default_service_tiers() -> Option<Vec<Value>> {
Some(Vec::new())
}
#[allow(clippy::unnecessary_wraps)]
fn default_supports_personality() -> Option<bool> {
Some(false)
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReasoningEffortOption {
pub description: String,
pub reasoning_effort: ReasoningEffort,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelListResponse {
pub data: Vec<Model>,
pub next_cursor: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountLoginCompletedNotification {
pub error: Option<String>,
pub login_id: Option<String>,
pub success: bool,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentMessageDeltaNotification {
pub delta: String,
pub item_id: String,
pub thread_id: String,
pub turn_id: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ItemCompletedNotification {
pub completed_at_ms: i64,
pub item: ThreadItem,
pub thread_id: String,
pub turn_id: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ItemStartedNotification {
pub item: ThreadItem,
pub started_at_ms: i64,
pub thread_id: String,
pub turn_id: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TurnCompletedNotification {
pub thread_id: String,
pub turn: Turn,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TurnStartedNotification {
pub thread_id: String,
pub turn: Turn,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadTokenUsageUpdatedNotification {
pub thread_id: String,
pub token_usage: ThreadTokenUsage,
pub turn_id: String,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RawNotification {
pub params: Map<String, Value>,
}
pub type UnknownNotification = RawNotification;
#[derive(Clone, Debug, PartialEq)]
pub enum NotificationPayload {
AccountLoginCompleted(AccountLoginCompletedNotification),
AgentMessageDelta(AgentMessageDeltaNotification),
ItemCompleted(ItemCompletedNotification),
ItemStarted(ItemStartedNotification),
ThreadTokenUsageUpdated(ThreadTokenUsageUpdatedNotification),
TurnCompleted(TurnCompletedNotification),
TurnStarted(TurnStartedNotification),
Known(RawNotification),
Unknown(UnknownNotification),
}
impl NotificationPayload {
pub fn params(&self) -> Value {
match self {
Self::AccountLoginCompleted(value) => serde_json::to_value(value),
Self::AgentMessageDelta(value) => serde_json::to_value(value),
Self::ItemCompleted(value) => serde_json::to_value(value),
Self::ItemStarted(value) => serde_json::to_value(value),
Self::ThreadTokenUsageUpdated(value) => serde_json::to_value(value),
Self::TurnCompleted(value) => serde_json::to_value(value),
Self::TurnStarted(value) => serde_json::to_value(value),
Self::Known(value) | Self::Unknown(value) => Ok(Value::Object(value.params.clone())),
}
.unwrap_or(Value::Null)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Notification {
pub method: String,
pub payload: NotificationPayload,
}
impl Notification {
pub fn turn_id(&self) -> Option<&str> {
match &self.payload {
NotificationPayload::AgentMessageDelta(value) => Some(&value.turn_id),
NotificationPayload::ItemCompleted(value) => Some(&value.turn_id),
NotificationPayload::ItemStarted(value) => Some(&value.turn_id),
NotificationPayload::ThreadTokenUsageUpdated(value) => Some(&value.turn_id),
NotificationPayload::TurnCompleted(value) => Some(&value.turn.id),
NotificationPayload::TurnStarted(value) => Some(&value.turn.id),
NotificationPayload::Known(value) | NotificationPayload::Unknown(value) => value
.params
.get("turnId")
.and_then(Value::as_str)
.or_else(|| value.params.get("turn")?.get("id")?.as_str()),
NotificationPayload::AccountLoginCompleted(_) => None,
}
}
pub fn thread_id(&self) -> Option<&str> {
match &self.payload {
NotificationPayload::AgentMessageDelta(value) => Some(&value.thread_id),
NotificationPayload::ItemCompleted(value) => Some(&value.thread_id),
NotificationPayload::ItemStarted(value) => Some(&value.thread_id),
NotificationPayload::ThreadTokenUsageUpdated(value) => Some(&value.thread_id),
NotificationPayload::TurnCompleted(value) => Some(&value.thread_id),
NotificationPayload::TurnStarted(value) => Some(&value.thread_id),
NotificationPayload::Known(value) | NotificationPayload::Unknown(value) => {
value.params.get("threadId").and_then(Value::as_str)
}
NotificationPayload::AccountLoginCompleted(_) => None,
}
}
pub fn login_id(&self) -> Option<&str> {
match &self.payload {
NotificationPayload::AccountLoginCompleted(value) => value.login_id.as_deref(),
NotificationPayload::Known(value) | NotificationPayload::Unknown(value)
if self.method == "account/login/completed" =>
{
value.params.get("loginId").and_then(Value::as_str)
}
_ => None,
}
}
pub(crate) fn from_wire(method: String, params: Value) -> Self {
let params = match params {
Value::Object(params) => params,
_ => Map::new(),
};
let payload = parse_notification_payload(&method, ¶ms);
Self { method, payload }
}
}
fn parse_notification_payload(method: &str, params: &Map<String, Value>) -> NotificationPayload {
let value = Value::Object(params.clone());
macro_rules! parse {
($type:ty, $variant:ident) => {
serde_json::from_value::<$type>(value)
.map(NotificationPayload::$variant)
.unwrap_or_else(|_| {
NotificationPayload::Unknown(RawNotification {
params: params.clone(),
})
})
};
}
match method {
"account/login/completed" => {
parse!(AccountLoginCompletedNotification, AccountLoginCompleted)
}
"item/agentMessage/delta" => {
parse!(AgentMessageDeltaNotification, AgentMessageDelta)
}
"item/completed" => parse!(ItemCompletedNotification, ItemCompleted),
"item/started" => parse!(ItemStartedNotification, ItemStarted),
"thread/tokenUsage/updated" => {
parse!(ThreadTokenUsageUpdatedNotification, ThreadTokenUsageUpdated)
}
"turn/completed" => parse!(TurnCompletedNotification, TurnCompleted),
"turn/started" => parse!(TurnStartedNotification, TurnStarted),
method if KNOWN_NOTIFICATION_METHODS.contains(&method) => {
NotificationPayload::Known(RawNotification {
params: params.clone(),
})
}
_ => NotificationPayload::Unknown(RawNotification {
params: params.clone(),
}),
}
}
pub(crate) const KNOWN_NOTIFICATION_METHODS: &[&str] = &[
"account/rateLimits/updated",
"account/updated",
"app/list/updated",
"command/exec/outputDelta",
"configWarning",
"deprecationNotice",
"error",
"externalAgentConfig/import/completed",
"externalAgentConfig/import/progress",
"fs/changed",
"fuzzyFileSearch/sessionCompleted",
"fuzzyFileSearch/sessionUpdated",
"guardianWarning",
"hook/completed",
"hook/started",
"item/autoApprovalReview/completed",
"item/autoApprovalReview/started",
"item/commandExecution/outputDelta",
"item/commandExecution/terminalInteraction",
"item/fileChange/outputDelta",
"item/fileChange/patchUpdated",
"item/mcpToolCall/progress",
"item/plan/delta",
"item/reasoning/summaryPartAdded",
"item/reasoning/summaryTextDelta",
"item/reasoning/textDelta",
"mcpServer/oauthLogin/completed",
"mcpServer/startupStatus/updated",
"model/rerouted",
"model/safetyBuffering/updated",
"model/verification",
"process/exited",
"process/outputDelta",
"remoteControl/status/changed",
"serverRequest/resolved",
"skills/changed",
"thread/archived",
"thread/closed",
"thread/compacted",
"thread/deleted",
"thread/goal/cleared",
"thread/goal/updated",
"thread/name/updated",
"thread/realtime/closed",
"thread/realtime/error",
"thread/realtime/itemAdded",
"thread/realtime/outputAudio/delta",
"thread/realtime/sdp",
"thread/realtime/started",
"thread/realtime/transcript/delta",
"thread/realtime/transcript/done",
"thread/settings/updated",
"thread/started",
"thread/status/changed",
"thread/unarchived",
"turn/diff/updated",
"turn/moderationMetadata",
"turn/plan/updated",
"warning",
"windows/worldWritableWarning",
"windowsSandbox/setupCompleted",
];
#[derive(Clone, Debug, PartialEq)]
pub struct TurnResult {
pub id: String,
pub status: TurnStatus,
pub error: Option<TurnError>,
pub started_at: Option<i64>,
pub completed_at: Option<i64>,
pub duration_ms: Option<i64>,
pub final_response: Option<String>,
pub items: Vec<ThreadItem>,
pub usage: Option<ThreadTokenUsage>,
}
impl TurnResult {
pub(crate) fn from_events(
turn_id: &str,
events: impl IntoIterator<Item = Notification>,
) -> crate::Result<Self> {
let mut completed = None;
let mut items = Vec::new();
let mut usage = None;
for event in events {
match event.payload {
NotificationPayload::ItemCompleted(value) if value.turn_id == turn_id => {
items.push(value.item);
}
NotificationPayload::ThreadTokenUsageUpdated(value) if value.turn_id == turn_id => {
usage = Some(value.token_usage);
}
NotificationPayload::TurnCompleted(value) if value.turn.id == turn_id => {
completed = Some(value.turn);
}
_ => {}
}
}
let turn = completed.ok_or(crate::Error::MissingTurnCompletion)?;
if turn.status == TurnStatus::Failed {
return Err(crate::Error::TurnFailed(turn.error.as_ref().map_or_else(
|| "turn failed with status failed".into(),
|error| error.message.clone(),
)));
}
let final_response = items
.iter()
.rev()
.find_map(|item| {
let message = item.as_agent_message()?;
(message.phase == Some(MessagePhase::FinalAnswer)).then(|| message.text.clone())
})
.or_else(|| {
items.iter().rev().find_map(|item| {
let message = item.as_agent_message()?;
message.phase.is_none().then(|| message.text.clone())
})
});
Ok(Self {
id: turn.id,
status: turn.status,
error: turn.error,
started_at: turn.started_at,
completed_at: turn.completed_at,
duration_ms: turn.duration_ms,
final_response,
items,
usage,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RetryPolicy {
pub max_attempts: u32,
pub initial_delay: std::time::Duration,
pub max_delay: std::time::Duration,
pub jitter_ratio: f64,
}
impl Default for RetryPolicy {
fn default() -> Self {
Self {
max_attempts: 3,
initial_delay: std::time::Duration::from_millis(250),
max_delay: std::time::Duration::from_secs(2),
jitter_ratio: 0.2,
}
}
}
pub type JsonObject = Map<String, Value>;
pub type JsonValue = Value;
pub type OrderedJsonObject = BTreeMap<String, Value>;
#[cfg(test)]
mod tests {
use super::*;
fn turn(status: TurnStatus, error: Option<TurnError>) -> Turn {
Turn {
completed_at: Some(2),
duration_ms: Some(1_000),
error,
id: "turn-1".into(),
items: vec![],
items_view: Some("full".into()),
started_at: Some(1),
status,
extra: Map::new(),
}
}
#[test]
fn preserves_future_string_enum_values() {
let effort: ReasoningEffort = serde_json::from_str("\"future\"").unwrap();
assert_eq!(effort, ReasoningEffort::Unknown("future".into()));
assert_eq!(serde_json::to_string(&effort).unwrap(), "\"future\"");
assert_eq!(effort.to_string(), "future");
assert_eq!(ReasoningEffort::High.as_str(), "high");
}
#[test]
fn input_constructors_and_conversions_preserve_every_public_shape() {
let expected = vec![
InputItem::text("text"),
InputItem::image("https://example.test/image.png"),
InputItem::local_image("/tmp/image.png"),
InputItem::skill("review", "/tmp/SKILL.md"),
InputItem::mention("src", "/tmp/src"),
];
assert_eq!(
Input::from(vec![
TextInput {
text: "text".into()
}
.into(),
ImageInput {
url: "https://example.test/image.png".into()
}
.into(),
LocalImageInput {
path: "/tmp/image.png".into()
}
.into(),
SkillInput {
name: "review".into(),
path: "/tmp/SKILL.md".into()
}
.into(),
MentionInput {
name: "src".into(),
path: "/tmp/src".into()
}
.into(),
]),
Input(expected)
);
assert_eq!(Input::from("borrowed").0, [InputItem::text("borrowed")]);
assert_eq!(
Input::from("owned".to_owned()).0,
[InputItem::text("owned")]
);
assert_eq!(
Input::from(TextInput {
text: "single".into()
})
.0,
[InputItem::text("single")]
);
assert_eq!(Sandbox::ReadOnly.mode(), "read-only");
assert_eq!(Sandbox::WorkspaceWrite.mode(), "workspace-write");
assert_eq!(Sandbox::FullAccess.mode(), "danger-full-access");
assert_eq!(Sandbox::ReadOnly.policy()["type"], "readOnly");
assert_eq!(Sandbox::WorkspaceWrite.policy()["type"], "workspaceWrite");
assert_eq!(Sandbox::FullAccess.policy()["type"], "dangerFullAccess");
}
#[test]
fn thread_item_uses_typed_agent_messages_and_lossless_fallback() {
let item: ThreadItem = serde_json::from_value(json!({
"id": "item-1",
"phase": "final_answer",
"text": "",
"type": "agentMessage",
"newField": 1
}))
.unwrap();
assert_eq!(item.kind(), Some("agentMessage"));
assert_eq!(item.id(), Some("item-1"));
assert_eq!(item.as_agent_message().unwrap().text, "");
assert_eq!(serde_json::to_value(&item).unwrap()["newField"], 1);
let unknown: ThreadItem =
serde_json::from_value(json!({"id": "x", "type": "futureItem", "x": true})).unwrap();
assert_eq!(unknown.kind(), Some("futureItem"));
assert_eq!(unknown.id(), Some("x"));
assert!(unknown.as_agent_message().is_none());
assert_eq!(serde_json::to_value(unknown).unwrap()["x"], true);
assert!(serde_json::from_value::<ThreadItem>(json!("invalid")).is_err());
let malformed: ThreadItem = serde_json::from_value(json!({
"id": 1,
"text": false,
"type": "agentMessage"
}))
.unwrap();
assert_eq!(malformed.kind(), Some("agentMessage"));
assert_eq!(malformed.id(), None);
}
#[test]
fn notification_coercion_is_typed_or_lossless() {
let typed = Notification::from_wire(
"item/agentMessage/delta".into(),
json!({"delta":"x","itemId":"i","threadId":"th","turnId":"tu"}),
);
assert_eq!(typed.turn_id(), Some("tu"));
assert_eq!(typed.thread_id(), Some("th"));
assert!(matches!(
typed.payload,
NotificationPayload::AgentMessageDelta(_)
));
let invalid =
Notification::from_wire("item/agentMessage/delta".into(), json!({"turnId": "tu"}));
assert!(matches!(invalid.payload, NotificationPayload::Unknown(_)));
let unknown = Notification::from_wire("future/event".into(), json!({"turn": {"id": "tu"}}));
assert_eq!(unknown.turn_id(), Some("tu"));
assert!(matches!(unknown.payload, NotificationPayload::Unknown(_)));
}
#[test]
fn every_typed_notification_exposes_params_and_route_identifiers() {
let cases = [
(
"item/agentMessage/delta",
json!({
"delta":"x",
"itemId":"item-1",
"threadId":"thread-1",
"turnId":"turn-1"
}),
),
(
"account/login/completed",
json!({"error":null,"loginId":"login-1","success":true}),
),
(
"item/started",
json!({
"item":{"id":"item-1","text":"x","type":"agentMessage"},
"startedAtMs":1,
"threadId":"thread-1",
"turnId":"turn-1"
}),
),
(
"item/completed",
json!({
"completedAtMs":2,
"item":{"id":"item-1","text":"x","type":"agentMessage"},
"threadId":"thread-1",
"turnId":"turn-1"
}),
),
(
"thread/tokenUsage/updated",
json!({
"threadId":"thread-1",
"tokenUsage":{
"last": token_usage_value(),
"modelContextWindow":200_000,
"total":token_usage_value()
},
"turnId":"turn-1"
}),
),
(
"turn/started",
json!({"threadId":"thread-1","turn":turn_value("inProgress")}),
),
(
"turn/completed",
json!({"threadId":"thread-1","turn":turn_value("completed")}),
),
];
for (method, params) in cases {
let notification = Notification::from_wire(method.into(), params);
assert!(notification.payload.params().is_object());
if method == "account/login/completed" {
assert_eq!(notification.login_id(), Some("login-1"));
assert_eq!(notification.turn_id(), None);
assert_eq!(notification.thread_id(), None);
} else {
assert_eq!(notification.turn_id(), Some("turn-1"));
assert_eq!(notification.thread_id(), Some("thread-1"));
}
}
let known = Notification::from_wire("warning".into(), json!({"threadId":"thread-2"}));
assert_eq!(known.payload.params()["threadId"], "thread-2");
assert_eq!(known.thread_id(), Some("thread-2"));
assert_eq!(known.login_id(), None);
let raw_login = Notification {
method: "account/login/completed".into(),
payload: NotificationPayload::Unknown(RawNotification {
params: json!({"loginId":"login-2"}).as_object().unwrap().clone(),
}),
};
assert_eq!(raw_login.login_id(), Some("login-2"));
let empty = Notification::from_wire("future/event".into(), Value::Bool(true));
assert_eq!(empty.payload.params(), json!({}));
}
fn token_usage_value() -> Value {
json!({
"cachedInputTokens":1,
"inputTokens":2,
"outputTokens":3,
"reasoningOutputTokens":4,
"totalTokens":10
})
}
fn turn_value(status: &str) -> Value {
json!({
"completedAt":2,
"durationMs":1,
"error":null,
"id":"turn-1",
"items":[],
"itemsView":"full",
"startedAt":1,
"status":status
})
}
#[test]
fn model_optional_fields_match_python_defaults_and_accept_null() {
let base = json!({
"availabilityNux":null,
"defaultReasoningEffort":"medium",
"defaultServiceTier":null,
"description":"model",
"displayName":"Model",
"hidden":false,
"id":"model",
"isDefault":true,
"model":"model",
"supportedReasoningEfforts":[],
"upgrade":null,
"upgradeInfo":null
});
let model: Model = serde_json::from_value(base.clone()).unwrap();
assert_eq!(model.additional_speed_tiers, Some(vec![]));
assert_eq!(
model.input_modalities,
Some(vec!["text".into(), "image".into()])
);
assert_eq!(model.service_tiers, Some(vec![]));
assert_eq!(model.supports_personality, Some(false));
let mut nullable = base;
let object = nullable.as_object_mut().unwrap();
object.insert("additionalSpeedTiers".into(), Value::Null);
object.insert("inputModalities".into(), Value::Null);
object.insert("serviceTiers".into(), Value::Null);
object.insert("supportsPersonality".into(), Value::Null);
let model: Model = serde_json::from_value(nullable).unwrap();
assert_eq!(model.additional_speed_tiers, None);
assert_eq!(model.input_modalities, None);
assert_eq!(model.service_tiers, None);
assert_eq!(model.supports_personality, None);
}
#[test]
fn turn_result_prefers_final_answer_and_preserves_empty_text() {
let events = vec![
Notification::from_wire(
"item/completed".into(),
json!({
"completedAtMs": 1,
"item": {"id":"a","phase":null,"text":"fallback","type":"agentMessage"},
"threadId":"thread-1",
"turnId":"turn-1"
}),
),
Notification::from_wire(
"item/completed".into(),
json!({
"completedAtMs": 2,
"item": {"id":"b","phase":"final_answer","text":"","type":"agentMessage"},
"threadId":"thread-1",
"turnId":"turn-1"
}),
),
Notification {
method: "turn/completed".into(),
payload: NotificationPayload::TurnCompleted(TurnCompletedNotification {
thread_id: "thread-1".into(),
turn: turn(TurnStatus::Completed, None),
}),
},
];
assert_eq!(
TurnResult::from_events("turn-1", events)
.unwrap()
.final_response,
Some(String::new())
);
}
#[test]
fn failed_and_incomplete_turns_return_errors() {
let failure = Notification {
method: "turn/completed".into(),
payload: NotificationPayload::TurnCompleted(TurnCompletedNotification {
thread_id: "thread-1".into(),
turn: turn(
TurnStatus::Failed,
Some(TurnError {
message: "boom".into(),
additional_details: None,
codex_error_info: None,
extra: Map::new(),
}),
),
}),
};
assert!(matches!(
TurnResult::from_events("turn-1", [failure]),
Err(crate::Error::TurnFailed(message)) if message == "boom"
));
assert!(matches!(
TurnResult::from_events("turn-1", []),
Err(crate::Error::MissingTurnCompletion)
));
let failure_without_details = Notification {
method: "turn/completed".into(),
payload: NotificationPayload::TurnCompleted(TurnCompletedNotification {
thread_id: "thread-1".into(),
turn: turn(TurnStatus::Failed, None),
}),
};
assert!(matches!(
TurnResult::from_events("turn-1", [failure_without_details]),
Err(crate::Error::TurnFailed(message))
if message == "turn failed with status failed"
));
}
#[test]
fn retry_policy_defaults_match_python() {
let policy = RetryPolicy::default();
assert_eq!(policy.max_attempts, 3);
assert_eq!(policy.initial_delay, std::time::Duration::from_millis(250));
assert_eq!(policy.max_delay, std::time::Duration::from_secs(2));
assert!((policy.jitter_ratio - 0.2).abs() < f64::EPSILON);
}
#[test]
fn notification_registry_and_revision_match_upstream_snapshot() {
let snapshot: Value =
serde_json::from_str(include_str!("../upstream/python-sdk-contract.json")).unwrap();
assert_eq!(
snapshot["upstream"]["revision"],
crate::UPSTREAM_PYTHON_SDK_COMMIT
);
let mut expected = snapshot["notification_models"]
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect::<Vec<_>>();
let mut actual = KNOWN_NOTIFICATION_METHODS.to_vec();
actual.extend([
"account/login/completed",
"item/agentMessage/delta",
"item/completed",
"item/started",
"thread/tokenUsage/updated",
"turn/completed",
"turn/started",
]);
expected.sort_unstable();
actual.sort_unstable();
assert_eq!(actual, expected);
}
}