diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index 1b11fb28c25..382c2e75607 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -862,13 +862,16 @@ dependencies = [ name = "opencode-api" version = "0.1.0" dependencies = [ + "base64", "bytes", "futures-util", "log", + "percent-encoding", "rand", "reqwest", "serde", "serde_json", + "serde_path_to_error", "thiserror", "tokio", "tokio-tungstenite", @@ -1428,6 +1431,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "sha1" version = "0.11.0" diff --git a/packages/cli-rs/Cargo.toml b/packages/cli-rs/Cargo.toml index 676db33f4d4..0f1934134cf 100644 --- a/packages/cli-rs/Cargo.toml +++ b/packages/cli-rs/Cargo.toml @@ -51,6 +51,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls", "j rustix = { version = "1", features = ["fs", "process"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } +serde_path_to_error = "0.1" sha1 = "0.11" similar = "3" tempfile = "3" diff --git a/packages/cli-rs/crates/api/Cargo.toml b/packages/cli-rs/crates/api/Cargo.toml index 40c09e7c866..60eceed67c5 100644 --- a/packages/cli-rs/crates/api/Cargo.toml +++ b/packages/cli-rs/crates/api/Cargo.toml @@ -10,12 +10,16 @@ publish.workspace = true workspace = true [dependencies] +base64.workspace = true bytes.workspace = true futures-util.workspace = true log.workspace = true +percent-encoding.workspace = true rand.workspace = true +reqwest.workspace = true serde.workspace = true serde_json.workspace = true +serde_path_to_error.workspace = true thiserror.workspace = true tokio.workspace = true tokio-tungstenite.workspace = true @@ -23,5 +27,4 @@ tokio-util.workspace = true url.workspace = true [dev-dependencies] -reqwest.workspace = true tokio = { workspace = true, features = ["test-util"] } diff --git a/packages/cli-rs/crates/api/src/client.rs b/packages/cli-rs/crates/api/src/client.rs index f96e216f5df..7f15b7089de 100644 --- a/packages/cli-rs/crates/api/src/client.rs +++ b/packages/cli-rs/crates/api/src/client.rs @@ -1 +1,423 @@ -//! Request core: base URL, authentication, per-call headers, and declared errors (F.2). +//! Request core: base URL, authentication, per-call headers, and declared errors. It follows the +//! `make` function of the TypeScript Promise client (`packages/client/src/promise/generated/client.ts:354-473`). +//! The generated methods (`generated/methods.rs`) build a [`Call`] and send it here. + +use std::sync::Arc; + +use base64::Engine; +use bytes::Bytes; +use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode}; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::Value; + +use crate::error::{DeclaredError, Error}; +use crate::query; +use crate::transport::{Request, Reqwest, Response, SseResponse, Transport}; + +/// The query parameter the server reads credentials from when a request cannot carry headers. +pub const AUTH_TOKEN_QUERY: &str = "auth_token"; + +/// How the client authenticates. The server accepts `Basic` credentials in the `authorization` header or, +/// base64-encoded the same way, in the `auth_token` query parameter +/// (`packages/server/src/middleware/authorization.ts:33-40`). +#[derive(Clone, PartialEq, Eq)] +pub enum Auth { + /// `authorization: Basic base64(username:password)`. + Basic { username: String, password: String }, + /// `?auth_token=base64(username:password)`. + Query { username: String, password: String }, +} + +impl Auth { + /// Basic credentials with the user name the CLI uses for its local service. + pub fn password(password: impl Into) -> Self { + Self::Basic { + username: "opencode".to_owned(), + password: password.into(), + } + } + + /// `base64(username:password)`, the value of the header after `Basic ` and of `auth_token`. + pub fn token(&self) -> String { + let (Self::Basic { username, password } | Self::Query { username, password }) = self; + base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}")) + } +} + +impl std::fmt::Debug for Auth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (kind, username) = match self { + Self::Basic { username, .. } => ("Basic", username), + Self::Query { username, .. } => ("Query", username), + }; + write!( + f, + "Auth::{kind} {{ username: {username:?}, password: }}" + ) + } +} + +/// Per-call options. Headers here replace client and input headers of the same name. +#[derive(Debug, Clone, Default)] +pub struct RequestOptions { + pub headers: Vec<(String, String)>, +} + +impl RequestOptions { + pub fn header(mut self, name: impl Into, value: impl Into) -> Self { + self.headers.push((name.into(), value.into())); + self + } +} + +/// The API client. Cheap to clone. +#[derive(Clone)] +pub struct Client { + base_url: url::Url, + auth: Option, + headers: Vec<(String, String)>, + transport: Arc, +} + +impl std::fmt::Debug for Client { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Client") + .field("base_url", &self.base_url.as_str()) + .field("auth", &self.auth) + .finish_non_exhaustive() + } +} + +impl Client { + /// A client on the `reqwest` transport. + pub fn new(base_url: &str) -> Result { + Self::with_transport(base_url, Arc::new(Reqwest::default())) + } + + pub fn with_transport(base_url: &str, transport: Arc) -> Result { + let mut base_url = url::Url::parse(base_url) + .map_err(|error| Error::Transport(format!("{base_url}: {error}")))?; + // A leading slash would replace any path prefix on the base URL, so paths join relative to it. + if !base_url.path().ends_with('/') { + let path = format!("{}/", base_url.path()); + base_url.set_path(&path); + } + Ok(Self { + base_url, + auth: None, + headers: Vec::new(), + transport, + }) + } + + pub fn auth(mut self, auth: Auth) -> Self { + self.auth = Some(auth); + self + } + + /// Adds a header to every request. + pub fn header(mut self, name: impl Into, value: impl Into) -> Self { + set_header(&mut self.headers, name.into(), value.into()); + self + } + + pub fn base_url(&self) -> &url::Url { + &self.base_url + } + + pub fn credentials(&self) -> Option<&Auth> { + self.auth.as_ref() + } + + pub fn transport(&self) -> &Arc { + &self.transport + } + + /// The URL of `path` (which starts with `/`) on this server, with `query` and no credentials. + pub fn url(&self, path: &str, query: &[(String, String)]) -> Result { + let mut url = self + .base_url + .join(path.trim_start_matches('/')) + .map_err(|error| Error::Transport(format!("{path}: {error}")))?; + if !query.is_empty() { + url.set_query(Some(&query::encode(query))); + } + Ok(url) + } + + /// Builds the request for `call`, as `prepare` does in TypeScript. + pub fn prepare(&self, call: Call, options: &RequestOptions) -> Result { + let mut query = call.query; + if let Some(auth @ Auth::Query { .. }) = &self.auth { + query.push((AUTH_TOKEN_QUERY.to_owned(), auth.token())); + } + let url = self.url(&call.path, &query)?; + let mut headers = Vec::new(); + if let Some(auth @ Auth::Basic { .. }) = &self.auth { + headers.push(( + "authorization".to_owned(), + format!("Basic {}", auth.token()), + )); + } + for (name, value) in self + .headers + .iter() + .chain(&call.headers) + .chain(&options.headers) + { + set_header(&mut headers, name.clone(), value.clone()); + } + let body = match call.body { + None => None, + Some(Body::Bytes(bytes)) => { + default_header(&mut headers, "content-type", "application/octet-stream"); + Some(bytes) + } + Some(Body::Json(value)) => { + default_header(&mut headers, "content-type", "application/json"); + Some(Bytes::from( + serde_json::to_vec(&value).map_err(encode_error)?, + )) + } + }; + Ok(Request { + method: call.method, + url, + headers, + body, + }) + } + + async fn execute(&self, call: Call, options: &RequestOptions) -> Result { + let success = call.success_status; + let declared = call.declared_statuses; + let request = self.prepare(call, options)?; + let response = self + .transport + .send(request) + .await + .map_err(Error::Transport)?; + if response.status != success { + return Err(response_error(response, declared).await); + } + Ok(response) + } + + pub(crate) async fn json( + &self, + call: Call, + options: &RequestOptions, + ) -> Result { + let bytes = json_body(self.execute(call, options).await?).await?; + let mut deserializer = serde_json::Deserializer::from_slice(&bytes); + // The JSON path of the first failure goes in the message, so a schema mismatch names its field. + serde_path_to_error::deserialize(&mut deserializer) + .map_err(|error| Error::MalformedResponse(error.to_string())) + } + + pub(crate) async fn data( + &self, + call: Call, + options: &RequestOptions, + ) -> Result { + #[derive(serde::Deserialize)] + struct Data { + data: T, + } + self.json::>(call, options) + .await + .map(|value| value.data) + } + + pub(crate) async fn empty(&self, call: Call, options: &RequestOptions) -> Result<(), Error> { + self.execute(call, options).await.map(|_| ()) + } + + pub(crate) async fn binary( + &self, + call: Call, + options: &RequestOptions, + ) -> Result { + let response = self.execute(call, options).await?; + response.bytes().await.map_err(Error::Transport) + } + + pub(crate) async fn sse( + &self, + call: Call, + options: &RequestOptions, + ) -> Result, Error> { + let response = self.execute(call, options).await?; + if !is_content_type(&response, "text/event-stream") { + return Err(Error::UnsupportedContentType( + response.header("content-type").map(str::to_owned), + )); + } + Ok(SseResponse::new(response)) + } +} + +/// One request a generated method describes. +#[derive(Debug)] +pub struct Call { + pub method: &'static str, + pub path: String, + pub query: Vec<(String, String)>, + pub headers: Vec<(String, String)>, + pub body: Option, + pub success_status: u16, + pub declared_statuses: &'static [u16], +} + +#[derive(Debug)] +pub enum Body { + Json(Value), + Bytes(Bytes), +} + +impl Call { + pub fn new( + method: &'static str, + path: String, + success_status: u16, + declared_statuses: &'static [u16], + ) -> Self { + Self { + method, + path, + query: Vec::new(), + headers: Vec::new(), + body: None, + success_status, + declared_statuses, + } + } + + /// Adds a query value, bracket-encoded like `appendQuery`. + pub fn query(&mut self, key: &str, value: &T) -> Result<(), Error> { + query::append( + &mut self.query, + key, + &serde_json::to_value(value).map_err(encode_error)?, + ); + Ok(()) + } + + /// Sets a header from an input field; `null` is skipped. + pub fn header(&mut self, name: &str, value: &T) -> Result<(), Error> { + let value = serde_json::to_value(value).map_err(encode_error)?; + if !value.is_null() { + set_header(&mut self.headers, name.to_owned(), query::js_string(&value)); + } + Ok(()) + } + + /// Starts a JSON object body; [`Call::field`] fills it. + pub fn object(&mut self) { + self.body = Some(Body::Json(Value::Object(serde_json::Map::new()))); + } + + pub fn field(&mut self, key: &str, value: &T) -> Result<(), Error> { + let value = serde_json::to_value(value).map_err(encode_error)?; + if let Some(Body::Json(Value::Object(map))) = &mut self.body { + map.insert(key.to_owned(), value); + } + Ok(()) + } + + /// Sets the whole JSON body, for payloads that are not flattened into fields. + pub fn json(&mut self, value: &T) -> Result<(), Error> { + self.body = Some(Body::Json( + serde_json::to_value(value).map_err(encode_error)?, + )); + Ok(()) + } + + pub fn bytes(&mut self, value: Bytes) { + self.body = Some(Body::Bytes(value)); + } +} + +/// A path parameter: `String(value)` encoded like `encodeURIComponent`. +pub fn path_param(value: &T) -> Result { + let value = serde_json::to_value(value).map_err(encode_error)?; + Ok(utf8_percent_encode(&query::js_string(&value), COMPONENT).to_string()) +} + +/// A trailing wildcard path, each segment encoded like `encodeURIComponent`. +pub fn path_wildcard(value: &str) -> String { + value + .split('/') + .map(|segment| utf8_percent_encode(segment, COMPONENT).to_string()) + .collect::>() + .join("/") +} + +/// The characters `encodeURIComponent` escapes: everything except `A-Z a-z 0-9 - _ . ! ~ * ' ( )`. +const COMPONENT: &AsciiSet = &NON_ALPHANUMERIC + .remove(b'-') + .remove(b'_') + .remove(b'.') + .remove(b'!') + .remove(b'~') + .remove(b'*') + .remove(b'\'') + .remove(b'(') + .remove(b')'); + +fn set_header(headers: &mut Vec<(String, String)>, name: String, value: String) { + let name = name.to_ascii_lowercase(); + headers.retain(|(key, _)| *key != name); + headers.push((name, value)); +} + +fn default_header(headers: &mut Vec<(String, String)>, name: &str, value: &str) { + if !headers.iter().any(|(key, _)| key == name) { + headers.push((name.to_owned(), value.to_owned())); + } +} + +fn encode_error(error: serde_json::Error) -> Error { + Error::Transport(format!("encode request: {error}")) +} + +async fn response_error(response: Response, declared: &[u16]) -> Error { + let status = response.status; + if !declared.contains(&status) { + return Error::UnexpectedStatus { status }; + } + let body = match json_body(response).await { + Ok(body) => body, + Err(error) => return error, + }; + match serde_json::from_slice(&body) { + Ok(body) => Error::Declared(Box::new(DeclaredError::new(status, body))), + Err(error) => Error::MalformedResponse(error.to_string()), + } +} + +/// The body of a JSON response: checks the content type and rejects an empty body, as `json` does in +/// TypeScript. +async fn json_body(response: Response) -> Result { + let content_type = response.header("content-type").map(str::to_owned); + if !is_content_type(&response, "application/json") + && !content_type + .as_deref() + .is_some_and(|value| value.contains("+json")) + { + return Err(Error::UnsupportedContentType(content_type)); + } + let bytes = response.bytes().await.map_err(Error::Transport)?; + if bytes.is_empty() { + return Err(Error::MalformedResponse("empty body".to_owned())); + } + Ok(bytes) +} + +fn is_content_type(response: &Response, expected: &str) -> bool { + response + .header("content-type") + .and_then(|value| value.split(';').next()) + .is_some_and(|value| value.trim().eq_ignore_ascii_case(expected)) +} diff --git a/packages/cli-rs/crates/api/src/de.rs b/packages/cli-rs/crates/api/src/de.rs new file mode 100644 index 00000000000..19b955f76df --- /dev/null +++ b/packages/cli-rs/crates/api/src/de.rs @@ -0,0 +1,17 @@ +//! Serde helpers the generated types use. + +use serde::de::{DeserializeOwned, Error}; +use serde::{Deserialize, Deserializer}; + +/// For an optional and nullable field: absent is `None` (through `#[serde(default)]`), `null` is +/// `Some(None)`, and a value is `Some(Some(value))`. +pub fn double_option<'de, T: Deserialize<'de>, D: Deserializer<'de>>( + deserializer: D, +) -> Result>, D::Error> { + Option::::deserialize(deserializer).map(Some) +} + +/// Decodes the member of a tagged union once its tag is known. +pub fn variant(value: serde_json::Value) -> Result { + serde_json::from_value(value).map_err(E::custom) +} diff --git a/packages/cli-rs/crates/api/src/error.rs b/packages/cli-rs/crates/api/src/error.rs index b43da82f6b3..9ce3d5f6195 100644 --- a/packages/cli-rs/crates/api/src/error.rs +++ b/packages/cli-rs/crates/api/src/error.rs @@ -1 +1,88 @@ -//! Client errors, mirroring the reasons of the TypeScript `ClientError` (F.2). +//! Client errors, mirroring the reasons of the TypeScript `ClientError` +//! (`packages/client/src/promise/generated/client-error.ts`), plus declared error bodies. + +use serde::de::DeserializeOwned; +use serde_json::Value; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The request could not be sent or the response could not be read. + #[error("Transport: {0}")] + Transport(String), + /// A status that is neither the success status nor a declared error status. + #[error("UnexpectedStatus: {status}")] + UnexpectedStatus { status: u16 }, + /// The response has the wrong content type. + #[error("UnsupportedContentType: {}", .0.as_deref().unwrap_or("none"))] + UnsupportedContentType(Option), + /// The response body is empty or not valid for its type. + #[error("MalformedResponse: {0}")] + MalformedResponse(String), + /// One server-sent event exceeds the size limit. + #[error("SseEventTooLarge")] + SseEventTooLarge, + /// A declared error the server returned, such as `SessionNotFoundError`. + #[error("{0}")] + Declared(Box), +} + +impl Error { + /// The `ClientError` reason, or the declared error's tag. + pub fn reason(&self) -> &str { + match self { + Self::Transport(_) => "Transport", + Self::UnexpectedStatus { .. } => "UnexpectedStatus", + Self::UnsupportedContentType(_) => "UnsupportedContentType", + Self::MalformedResponse(_) => "MalformedResponse", + Self::SseEventTooLarge => "SseEventTooLarge", + Self::Declared(error) => error.tag.as_deref().unwrap_or("DeclaredError"), + } + } + + /// The declared error, if the server returned one. + pub fn declared(&self) -> Option<&DeclaredError> { + match self { + Self::Declared(error) => Some(error), + _ => None, + } + } +} + +/// A declared error body. The tag is `_tag`, else `name`; the message is `message`, else `data.message`, +/// as `declared` in the TypeScript client. +#[derive(Debug, Clone, PartialEq)] +pub struct DeclaredError { + pub status: u16, + pub tag: Option, + pub message: Option, + pub body: Value, +} + +impl DeclaredError { + pub fn new(status: u16, body: Value) -> Self { + let text = |value: Option<&Value>| value.and_then(Value::as_str).map(str::to_owned); + Self { + status, + tag: text(body.get("_tag")).or_else(|| text(body.get("name"))), + message: text(body.get("message")) + .or_else(|| text(body.get("data").and_then(|data| data.get("message")))), + body, + } + } + + /// Decodes the body into a generated error type, such as `SessionNotFoundError`. + pub fn decode(&self) -> Result { + serde_json::from_value(self.body.clone()) + } +} + +impl std::fmt::Display for DeclaredError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match (&self.tag, &self.message) { + (Some(tag), Some(message)) => write!(f, "{tag}: {message}"), + (Some(tag), None) => f.write_str(tag), + (None, Some(message)) => f.write_str(message), + (None, None) => write!(f, "declared error {}", self.status), + } + } +} diff --git a/packages/cli-rs/crates/api/src/generated/methods.rs b/packages/cli-rs/crates/api/src/generated/methods.rs new file mode 100644 index 00000000000..854469e95c2 --- /dev/null +++ b/packages/cli-rs/crates/api/src/generated/methods.rs @@ -0,0 +1,3398 @@ +// Generated by script/gen/api.ts from ClientApi. Do not edit. +#![allow(clippy::all, clippy::pedantic)] + +use super::types::*; +use crate::client::{Call, Client, RequestOptions}; +use crate::error::Error; +use crate::transport::SseResponse; + +impl Client { + /// `GET /api/info` (`info`) + pub async fn server_info(&self, options: &RequestOptions) -> Result { + let call = Call::new("GET", "/api/info".to_owned(), 200, &[400, 401]); + + self.json(call, options).await + } + + /// `POST /api/pair` (`pair`) + pub async fn server_pair(&self, options: &RequestOptions) -> Result { + let call = Call::new("POST", "/api/pair".to_owned(), 200, &[400, 401]); + + self.json(call, options).await + } + + /// `GET /auth/connect/:code` (`connect`) + pub async fn server_connect( + &self, + input: &ServerConnectInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!("/auth/connect/{}", crate::client::path_param(&input.code)?), + 200, + &[400, 401], + ); + + self.json(call, options).await + } + + /// `GET /api/location` (`get`) + pub async fn location_get( + &self, + input: &LocationGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/location".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/location/reload` (`reload`) + pub async fn location_reload(&self, options: &RequestOptions) -> Result<(), Error> { + let call = Call::new( + "POST", + "/api/location/reload".to_owned(), + 200, + &[400, 401, 503], + ); + + self.empty(call, options).await + } + + /// `GET /api/agent` (`list`) + pub async fn agent_list( + &self, + input: &AgentListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/agent".to_owned(), 200, &[400, 401, 404, 503]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/agent/:agentID` (`get`) + pub async fn agent_get( + &self, + input: &AgentGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!("/api/agent/{}", crate::client::path_param(&input.agent_id)?), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/plugin` (`list`) + pub async fn plugin_list( + &self, + input: &PluginListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/plugin".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/plugin/gui` (`gui`) + pub async fn plugin_gui( + &self, + input: &PluginGuiInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/plugin/gui".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.query("id", &input.id)?; + self.json(call, options).await + } + + /// `POST /api/plugin/check` (`check`) + pub async fn plugin_check( + &self, + input: &PluginCheckInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/plugin/check".to_owned(), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.target { + call.field("target", value)?; + } + self.json(call, options).await + } + + /// `POST /api/plugin/update` (`update`) + pub async fn plugin_update( + &self, + input: &PluginUpdateInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + "/api/plugin/update".to_owned(), + 200, + &[400, 401, 404, 503], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("targets", &input.targets)?; + self.empty(call, options).await + } + + /// `GET /api/session` (`list`) + pub async fn session_list( + &self, + input: &SessionListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/session".to_owned(), 200, &[400, 401]); + if let Some(value) = &input.limit { + call.query("limit", value)?; + } + if let Some(value) = &input.order { + call.query("order", value)?; + } + if let Some(value) = &input.search { + call.query("search", value)?; + } + if let Some(value) = &input.parent_id { + call.query("parentID", value)?; + } + if let Some(value) = &input.archived { + call.query("archived", value)?; + } + if let Some(value) = &input.directory { + call.query("directory", value)?; + } + if let Some(value) = &input.project { + call.query("project", value)?; + } + if let Some(value) = &input.subpath { + call.query("subpath", value)?; + } + if let Some(value) = &input.cursor { + call.query("cursor", value)?; + } + self.json(call, options).await + } + + /// `POST /api/session` (`create`) + pub async fn session_create( + &self, + input: &SessionCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("POST", "/api/session".to_owned(), 200, &[400, 401, 404]); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + if let Some(value) = &input.parent_id { + call.field("parentID", value)?; + } + if let Some(value) = &input.title { + call.field("title", value)?; + } + if let Some(value) = &input.agent { + call.field("agent", value)?; + } + if let Some(value) = &input.model { + call.field("model", value)?; + } + if let Some(value) = &input.location { + call.field("location", value)?; + } + if let Some(value) = &input.metadata { + call.field("metadata", value)?; + } + if let Some(value) = &input.permissions { + call.field("permissions", value)?; + } + self.data(call, options).await + } + + /// `GET /api/session/active` (`active`) + pub async fn session_active( + &self, + options: &RequestOptions, + ) -> Result { + let call = Call::new("GET", "/api/session/active".to_owned(), 200, &[400, 401]); + + self.data(call, options).await + } + + /// `GET /api/session/:sessionID` (`get`) + pub async fn session_get( + &self, + input: &SessionGetInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `DELETE /api/session/:sessionID` (`remove`) + pub async fn session_remove( + &self, + input: &SessionRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/session/{}", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/fork` (`fork`) + pub async fn session_fork( + &self, + input: &SessionForkInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/fork", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.before { + call.field("before", value)?; + } + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/agent` (`switchAgent`) + pub async fn session_switch_agent( + &self, + input: &SessionSwitchAgentInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/agent", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("agent", &input.agent)?; + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/model` (`switchModel`) + pub async fn session_switch_model( + &self, + input: &SessionSwitchModelInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/model", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("model", &input.model)?; + self.empty(call, options).await + } + + /// `PATCH /api/session/:sessionID` (`update`) + pub async fn session_update( + &self, + input: &SessionUpdateInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "PATCH", + format!( + "/api/session/{}", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.title { + call.field("title", value)?; + } + if let Some(value) = &input.metadata { + call.field("metadata", value)?; + } + if let Some(value) = &input.permissions { + call.field("permissions", value)?; + } + if let Some(value) = &input.archived { + call.field("archived", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/move` (`move`) + pub async fn session_move( + &self, + input: &SessionMoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/move", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("directory", &input.directory)?; + if let Some(value) = &input.delivery { + call.field("delivery", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/prompt` (`prompt`) + pub async fn session_prompt( + &self, + input: &SessionPromptInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/prompt", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 409], + ); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + call.field("text", &input.text)?; + if let Some(value) = &input.files { + call.field("files", value)?; + } + if let Some(value) = &input.agents { + call.field("agents", value)?; + } + if let Some(value) = &input.skills { + call.field("skills", value)?; + } + if let Some(value) = &input.metadata { + call.field("metadata", value)?; + } + if let Some(value) = &input.delivery { + call.field("delivery", value)?; + } + if let Some(value) = &input.resume { + call.field("resume", value)?; + } + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/command` (`command`) + pub async fn session_command( + &self, + input: &SessionCommandInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/command", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 500], + ); + call.object(); + call.field("name", &input.name)?; + call.field("text", &input.text)?; + if let Some(value) = &input.files { + call.field("files", value)?; + } + if let Some(value) = &input.agents { + call.field("agents", value)?; + } + if let Some(value) = &input.skills { + call.field("skills", value)?; + } + if let Some(value) = &input.delivery { + call.field("delivery", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/synthetic` (`synthetic`) + pub async fn session_synthetic( + &self, + input: &SessionSyntheticInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/synthetic", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 409], + ); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + call.field("text", &input.text)?; + if let Some(value) = &input.description { + call.field("description", value)?; + } + if let Some(value) = &input.metadata { + call.field("metadata", value)?; + } + if let Some(value) = &input.delivery { + call.field("delivery", value)?; + } + if let Some(value) = &input.resume { + call.field("resume", value)?; + } + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/shell` (`shell`) + pub async fn session_shell( + &self, + input: &SessionShellInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/shell", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + call.field("command", &input.command)?; + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/compact` (`compact`) + pub async fn session_compact( + &self, + input: &SessionCompactInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/compact", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 409], + ); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + if let Some(value) = &input.delivery { + call.field("delivery", value)?; + } + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/revert/stage` (`revert.stage`) + pub async fn session_revert_stage( + &self, + input: &SessionRevertStageInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/revert/stage", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 409, 500], + ); + call.object(); + call.field("messageID", &input.message_id)?; + if let Some(value) = &input.files { + call.field("files", value)?; + } + self.data(call, options).await + } + + /// `DELETE /api/session/:sessionID/revert` (`revert.clear`) + pub async fn session_revert_clear( + &self, + input: &SessionRevertClearInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/session/{}/revert", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 409, 500], + ); + + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/revert/commit` (`revert.commit`) + pub async fn session_revert_commit( + &self, + input: &SessionRevertCommitInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "POST", + format!( + "/api/session/{}/revert/commit", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 409], + ); + + self.empty(call, options).await + } + + /// `GET /api/session/:sessionID/context` (`context`) + pub async fn session_context( + &self, + input: &SessionContextInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}/context", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 500], + ); + + self.data(call, options).await + } + + /// `GET /api/session/:sessionID/diff` (`diff`) + pub async fn session_diff( + &self, + input: &SessionDiffInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/session/{}/diff", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 500], + ); + if let Some(value) = &input.from { + call.query("from", value)?; + } + if let Some(value) = &input.to { + call.query("to", value)?; + } + if let Some(value) = &input.context { + call.query("context", value)?; + } + self.data(call, options).await + } + + /// `GET /api/session/:sessionID/inbox` (`inbox.list`) + pub async fn session_inbox_list( + &self, + input: &SessionInboxListInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}/inbox", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `DELETE /api/session/:sessionID/inbox/:inboxID` (`inbox.cancel`) + pub async fn session_inbox_cancel( + &self, + input: &SessionInboxCancelInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/session/{}/inbox/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.inbox_id)? + ), + 200, + &[400, 401, 404], + ); + + self.empty(call, options).await + } + + /// `PATCH /api/session/:sessionID/inbox/:inboxID` (`inbox.update`) + pub async fn session_inbox_update( + &self, + input: &SessionInboxUpdateInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "PATCH", + format!( + "/api/session/{}/inbox/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.inbox_id)? + ), + 200, + &[400, 401, 404, 409], + ); + call.object(); + call.field("delivery", &input.delivery)?; + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/generate` (`generate`) + pub async fn session_generate( + &self, + input: &SessionGenerateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/generate", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 503], + ); + call.object(); + call.field("prompt", &input.prompt)?; + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/interrupt` (`interrupt`) + pub async fn session_interrupt( + &self, + input: &SessionInterruptInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/interrupt", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.resume { + call.query("resume", value)?; + } + self.json(call, options).await + } + + /// `POST /api/session/:sessionID/background` (`background`) + pub async fn session_background( + &self, + input: &SessionBackgroundInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "POST", + format!( + "/api/session/{}/background", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + + self.empty(call, options).await + } + + /// `GET /api/session/:sessionID/message/:messageID` (`message.get`) + pub async fn session_message_get( + &self, + input: &SessionMessageGetInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}/message/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.message_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `GET /api/session/:sessionID/form` (`form.list`) + pub async fn session_form_list( + &self, + input: &SessionFormListInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}/form", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/form` (`form.create`) + pub async fn session_form_create( + &self, + input: &SessionFormCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/form", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 409], + ); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + call.field("title", &input.title)?; + if let Some(value) = &input.metadata { + call.field("metadata", value)?; + } + call.field("fields", &input.fields)?; + self.data(call, options).await + } + + /// `GET /api/session/:sessionID/form/:formID` (`form.get`) + pub async fn session_form_get( + &self, + input: &SessionFormGetInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}/form/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.form_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/form/:formID/reply` (`form.reply`) + pub async fn session_form_reply( + &self, + input: &SessionFormReplyInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/form/{}/reply", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.form_id)? + ), + 200, + &[400, 401, 404, 409], + ); + call.object(); + call.field("answer", &input.answer)?; + self.empty(call, options).await + } + + /// `DELETE /api/session/:sessionID/form/:formID` (`form.cancel`) + pub async fn session_form_cancel( + &self, + input: &SessionFormCancelInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + format!( + "/api/session/{}/form/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.form_id)? + ), + 200, + &[400, 401, 404, 409], + ); + if let Some(value) = &input.message { + call.query("message", value)?; + } + self.empty(call, options).await + } + + /// `PUT /api/session/:sessionID/environment` (`environment`) + pub async fn session_environment( + &self, + input: &SessionEnvironmentInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "PUT", + format!( + "/api/session/{}/environment", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("variables", &input.variables)?; + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/view` (`view`) + pub async fn session_view( + &self, + input: &SessionViewInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/view", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("idle", &input.idle)?; + self.empty(call, options).await + } + + /// `GET /api/experimental/session/stats` (`stats`) + pub async fn experimental_session_stats( + &self, + input: &ExperimentalSessionStatsInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/experimental/session/stats".to_owned(), + 200, + &[400, 401], + ); + if let Some(value) = &input.from { + call.query("from", value)?; + } + if let Some(value) = &input.to { + call.query("to", value)?; + } + if let Some(value) = &input.project { + call.query("project", value)?; + } + if let Some(value) = &input.timezone { + call.query("timezone", value)?; + } + if let Some(value) = &input.tools { + call.query("tools", value)?; + } + self.data(call, options).await + } + + /// `POST /api/experimental/session/import` (`import`) + pub async fn experimental_session_import( + &self, + input: &ExperimentalSessionImportInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/session/import".to_owned(), + 200, + &[400, 401, 404, 409], + ); + call.object(); + call.field("info", &input.info)?; + call.field("messages", &input.messages)?; + if let Some(value) = &input.location { + call.field("location", value)?; + } + self.data(call, options).await + } + + /// `GET /api/experimental/session/:sessionID/export` (`export`) + pub async fn experimental_session_export( + &self, + input: &ExperimentalSessionExportInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/experimental/session/{}/export", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 500], + ); + if let Some(value) = &input.sanitize { + call.query("sanitize", value)?; + } + self.data(call, options).await + } + + /// `POST /api/experimental/session/:sessionID/skill` (`skill`) + pub async fn experimental_session_skill( + &self, + input: &ExperimentalSessionSkillInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/experimental/session/{}/skill", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("id", &input.id)?; + if let Some(value) = &input.resume { + call.field("resume", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/experimental/session/:sessionID/wait` (`wait`) + pub async fn experimental_session_wait( + &self, + input: &ExperimentalSessionWaitInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "POST", + format!( + "/api/experimental/session/{}/wait", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 503], + ); + + self.empty(call, options).await + } + + /// `GET /api/experimental/session/:sessionID/instructions/entries` (`instructions.entry.list`) + pub async fn experimental_session_instructions_entry_list( + &self, + input: &ExperimentalSessionInstructionsEntryListInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/experimental/session/{}/instructions/entries", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `PUT /api/experimental/session/:sessionID/instructions/entries/:key` (`instructions.entry.put`) + pub async fn experimental_session_instructions_entry_put( + &self, + input: &ExperimentalSessionInstructionsEntryPutInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "PUT", + format!( + "/api/experimental/session/{}/instructions/entries/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.key)? + ), + 200, + &[400, 401, 404, 413], + ); + call.object(); + call.field("value", &input.value)?; + self.empty(call, options).await + } + + /// `DELETE /api/experimental/session/:sessionID/instructions/entries/:key` (`instructions.entry.remove`) + pub async fn experimental_session_instructions_entry_remove( + &self, + input: &ExperimentalSessionInstructionsEntryRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/experimental/session/{}/instructions/entries/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.key)? + ), + 200, + &[400, 401, 404], + ); + + self.empty(call, options).await + } + + /// `GET /api/experimental/session/:sessionID/log` (`log`) + pub async fn experimental_session_log( + &self, + input: &ExperimentalSessionLogInput, + options: &RequestOptions, + ) -> Result, Error> { + let mut call = Call::new( + "GET", + format!( + "/api/experimental/session/{}/log", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.after { + call.query("after", value)?; + } + if let Some(value) = &input.follow { + call.query("follow", value)?; + } + self.sse(call, options).await + } + + /// `GET /api/session/:sessionID/message` (`list`) + pub async fn message_list( + &self, + input: &MessageListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/session/{}/message", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404, 500], + ); + if let Some(value) = &input.limit { + call.query("limit", value)?; + } + if let Some(value) = &input.order { + call.query("order", value)?; + } + if let Some(value) = &input.cursor { + call.query("cursor", value)?; + } + if let Some(value) = &input.r#type { + call.query("type", value)?; + } + self.json(call, options).await + } + + /// `GET /api/model` (`list`) + pub async fn model_list( + &self, + input: &ModelListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/model".to_owned(), 200, &[400, 401, 404, 503]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.types { + call.query("types", value)?; + } + self.json(call, options).await + } + + /// `GET /api/model/default` (`default`) + pub async fn model_default( + &self, + input: &ModelDefaultInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/model/default".to_owned(), + 200, + &[400, 401, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/experimental/generate/text` (`text`) + pub async fn experimental_generate_text( + &self, + input: &ExperimentalGenerateTextInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/generate/text".to_owned(), + 200, + &[400, 401, 404, 422, 502, 503], + ); + call.object(); + call.field("prompt", &input.prompt)?; + if let Some(value) = &input.model { + call.field("model", value)?; + } + self.data(call, options).await + } + + /// `POST /api/experimental/generate/image` (`image`) + pub async fn experimental_generate_image( + &self, + input: &ExperimentalGenerateImageInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/generate/image".to_owned(), + 200, + &[400, 401, 404, 422, 502, 503], + ); + call.object(); + call.field("model", &input.model)?; + call.field("prompt", &input.prompt)?; + if let Some(value) = &input.images { + call.field("images", value)?; + } + if let Some(value) = &input.n { + call.field("n", value)?; + } + if let Some(value) = &input.aspect { + call.field("aspect", value)?; + } + if let Some(value) = &input.resolution { + call.field("resolution", value)?; + } + self.data(call, options).await + } + + /// `POST /api/experimental/generate/decisions` (`decisions`) + pub async fn experimental_generate_decisions( + &self, + input: &ExperimentalGenerateDecisionsInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/generate/decisions".to_owned(), + 200, + &[400, 401, 404, 422, 502, 503], + ); + call.object(); + call.field("model", &input.model)?; + call.field("input", &input.input)?; + call.field("questions", &input.questions)?; + self.data(call, options).await + } + + /// `GET /api/experimental/voice/models` (`models`) + pub async fn experimental_voice_models( + &self, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + "/api/experimental/voice/models".to_owned(), + 200, + &[400, 401, 404, 503], + ); + + self.data(call, options).await + } + + /// `POST /api/experimental/voice/session` (`session`) + pub async fn experimental_voice_session( + &self, + input: &ExperimentalVoiceSessionInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/voice/session".to_owned(), + 200, + &[400, 401, 404, 503], + ); + call.object(); + call.field("model", &input.model)?; + if let Some(value) = &input.session { + call.field("session", value)?; + } + call.field("transport", &input.transport)?; + self.data(call, options).await + } + + /// `GET /api/provider` (`list`) + pub async fn provider_list( + &self, + input: &ProviderListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/provider".to_owned(), + 200, + &[400, 401, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/provider/:providerID` (`get`) + pub async fn provider_get( + &self, + input: &ProviderGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/provider/{}", + crate::client::path_param(&input.provider_id)? + ), + 200, + &[400, 401, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/integration` (`list`) + pub async fn integration_list( + &self, + input: &IntegrationListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/integration".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/integration/:integrationID` (`get`) + pub async fn integration_get( + &self, + input: &IntegrationGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/integration/{}", + crate::client::path_param(&input.integration_id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/integration/:integrationID/connect/key` (`connect.key`) + pub async fn integration_connect_key( + &self, + input: &IntegrationConnectKeyInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/integration/{}/connect/key", + crate::client::path_param(&input.integration_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("key", &input.key)?; + if let Some(value) = &input.answer { + call.field("answer", value)?; + } + if let Some(value) = &input.label { + call.field("label", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/integration/:integrationID/connect/external` (`connect.external`) + pub async fn integration_connect_external( + &self, + input: &IntegrationConnectExternalInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/integration/{}/connect/external", + crate::client::path_param(&input.integration_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("methodID", &input.method_id)?; + if let Some(value) = &input.answer { + call.field("answer", value)?; + } + if let Some(value) = &input.label { + call.field("label", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/integration/:integrationID/connect/oauth` (`oauth.connect`) + pub async fn integration_oauth_connect( + &self, + input: &IntegrationOauthConnectInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/integration/{}/connect/oauth", + crate::client::path_param(&input.integration_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("methodID", &input.method_id)?; + if let Some(value) = &input.answer { + call.field("answer", value)?; + } + if let Some(value) = &input.label { + call.field("label", value)?; + } + self.json(call, options).await + } + + /// `GET /api/integration/:integrationID/connect/oauth/:attemptID` (`oauth.status`) + pub async fn integration_oauth_status( + &self, + input: &IntegrationOauthStatusInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/integration/{}/connect/oauth/{}", + crate::client::path_param(&input.integration_id)?, + crate::client::path_param(&input.attempt_id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/integration/:integrationID/connect/oauth/:attemptID/complete` (`oauth.complete`) + pub async fn integration_oauth_complete( + &self, + input: &IntegrationOauthCompleteInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/integration/{}/connect/oauth/{}/complete", + crate::client::path_param(&input.integration_id)?, + crate::client::path_param(&input.attempt_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.code { + call.field("code", value)?; + } + self.empty(call, options).await + } + + /// `DELETE /api/integration/:integrationID/connect/oauth/:attemptID` (`oauth.cancel`) + pub async fn integration_oauth_cancel( + &self, + input: &IntegrationOauthCancelInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + format!( + "/api/integration/{}/connect/oauth/{}", + crate::client::path_param(&input.integration_id)?, + crate::client::path_param(&input.attempt_id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/integration/:integrationID/connect/command` (`command.connect`) + pub async fn integration_command_connect( + &self, + input: &IntegrationCommandConnectInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/integration/{}/connect/command", + crate::client::path_param(&input.integration_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("methodID", &input.method_id)?; + if let Some(value) = &input.label { + call.field("label", value)?; + } + self.json(call, options).await + } + + /// `GET /api/integration/:integrationID/connect/command/:attemptID` (`command.status`) + pub async fn integration_command_status( + &self, + input: &IntegrationCommandStatusInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/integration/{}/connect/command/{}", + crate::client::path_param(&input.integration_id)?, + crate::client::path_param(&input.attempt_id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `DELETE /api/integration/:integrationID/connect/command/:attemptID` (`command.cancel`) + pub async fn integration_command_cancel( + &self, + input: &IntegrationCommandCancelInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + format!( + "/api/integration/{}/connect/command/{}", + crate::client::path_param(&input.integration_id)?, + crate::client::path_param(&input.attempt_id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/experimental/integration/wellknown` (`wellknown.add`) + pub async fn experimental_integration_wellknown_add( + &self, + input: &ExperimentalIntegrationWellknownAddInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + "/api/experimental/integration/wellknown".to_owned(), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("url", &input.url)?; + self.empty(call, options).await + } + + /// `GET /api/mcp` (`list`) + pub async fn mcp_list( + &self, + input: &McpListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/mcp".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/mcp/resource` (`resource.catalog`) + pub async fn mcp_resource_catalog( + &self, + input: &McpResourceCatalogInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/mcp/resource".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `PUT /api/experimental/mcp/:server` (`add`) + pub async fn experimental_mcp_add( + &self, + input: &ExperimentalMcpAddInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "PUT", + format!( + "/api/experimental/mcp/{}", + crate::client::path_param(&input.server)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("config", &input.config)?; + self.empty(call, options).await + } + + /// `DELETE /api/experimental/mcp/:server` (`remove`) + pub async fn experimental_mcp_remove( + &self, + input: &ExperimentalMcpRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + format!( + "/api/experimental/mcp/{}", + crate::client::path_param(&input.server)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/experimental/mcp/:server/connect` (`connect`) + pub async fn experimental_mcp_connect( + &self, + input: &ExperimentalMcpConnectInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/experimental/mcp/{}/connect", + crate::client::path_param(&input.server)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/experimental/mcp/:server/disconnect` (`disconnect`) + pub async fn experimental_mcp_disconnect( + &self, + input: &ExperimentalMcpDisconnectInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/experimental/mcp/{}/disconnect", + crate::client::path_param(&input.server)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/experimental/client-mcp/token` (`client.token`) + pub async fn experimental_mcp_client_token( + &self, + input: &ExperimentalMcpClientTokenInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/client-mcp/token".to_owned(), + 200, + &[400, 401, 403, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.query("name", &input.name)?; + if let Some(value) = &input.x_opencode_ticket { + call.header("x-opencode-ticket", value)?; + } + self.json(call, options).await + } + + /// `GET /api/credential` (`list`) + pub async fn credential_list( + &self, + options: &RequestOptions, + ) -> Result { + let call = Call::new("GET", "/api/credential".to_owned(), 200, &[400, 401]); + + self.data(call, options).await + } + + /// `POST /api/credential` (`create`) + pub async fn credential_create( + &self, + input: &CredentialCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("POST", "/api/credential".to_owned(), 200, &[400, 401, 409]); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + call.field("integrationID", &input.integration_id)?; + if let Some(value) = &input.label { + call.field("label", value)?; + } + call.field("value", &input.value)?; + if let Some(value) = &input.activate { + call.field("activate", value)?; + } + self.data(call, options).await + } + + /// `PATCH /api/credential/:credentialID` (`update`) + pub async fn credential_update( + &self, + input: &CredentialUpdateInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "PATCH", + format!( + "/api/credential/{}", + crate::client::path_param(&input.credential_id)? + ), + 200, + &[400, 401], + ); + call.object(); + call.field("label", &input.label)?; + self.empty(call, options).await + } + + /// `POST /api/credential/:credentialID/activate` (`activate`) + pub async fn credential_activate( + &self, + input: &CredentialActivateInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "POST", + format!( + "/api/credential/{}/activate", + crate::client::path_param(&input.credential_id)? + ), + 200, + &[400, 401], + ); + + self.empty(call, options).await + } + + /// `DELETE /api/credential/:credentialID` (`remove`) + pub async fn credential_remove( + &self, + input: &CredentialRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/credential/{}", + crate::client::path_param(&input.credential_id)? + ), + 200, + &[400, 401], + ); + + self.empty(call, options).await + } + + /// `GET /api/project` (`list`) + pub async fn project_list( + &self, + input: &ProjectListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/project".to_owned(), 200, &[400, 401]); + if let Some(value) = &input.archived { + call.query("archived", value)?; + } + self.json(call, options).await + } + + /// `PATCH /api/project/:projectID` (`update`) + pub async fn project_update( + &self, + input: &ProjectUpdateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "PATCH", + format!( + "/api/project/{}", + crate::client::path_param(&input.project_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.canonical { + call.field("canonical", value)?; + } + if let Some(value) = &input.name { + call.field("name", value)?; + } + if let Some(value) = &input.icon { + call.field("icon", value)?; + } + if let Some(value) = &input.commands { + call.field("commands", value)?; + } + self.json(call, options).await + } + + /// `GET /api/form` (`list`) + pub async fn form_list( + &self, + input: &FormListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/form".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/permission/request` (`request.list`) + pub async fn permission_request_list( + &self, + input: &PermissionRequestListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/permission/request".to_owned(), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/permission/saved` (`saved.list`) + pub async fn permission_saved_list( + &self, + input: &PermissionSavedListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/permission/saved".to_owned(), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.project_id { + call.query("projectID", value)?; + } + self.data(call, options).await + } + + /// `PATCH /api/permission/saved/:id` (`saved.update`) + pub async fn permission_saved_update( + &self, + input: &PermissionSavedUpdateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "PATCH", + format!( + "/api/permission/saved/{}", + crate::client::path_param(&input.id)? + ), + 200, + &[400, 401, 404, 409], + ); + call.object(); + if let Some(value) = &input.action { + call.field("action", value)?; + } + if let Some(value) = &input.resource { + call.field("resource", value)?; + } + self.data(call, options).await + } + + /// `DELETE /api/permission/saved/:id` (`saved.remove`) + pub async fn permission_saved_remove( + &self, + input: &PermissionSavedRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/permission/saved/{}", + crate::client::path_param(&input.id)? + ), + 200, + &[400, 401], + ); + + self.empty(call, options).await + } + + /// `POST /api/session/:sessionID/permission` (`create`) + pub async fn permission_create( + &self, + input: &PermissionCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/permission", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.id { + call.field("id", value)?; + } + call.field("action", &input.action)?; + call.field("resources", &input.resources)?; + if let Some(value) = &input.save { + call.field("save", value)?; + } + if let Some(value) = &input.metadata { + call.field("metadata", value)?; + } + if let Some(value) = &input.source { + call.field("source", value)?; + } + if let Some(value) = &input.agent { + call.field("agent", value)?; + } + self.data(call, options).await + } + + /// `GET /api/session/:sessionID/permission` (`list`) + pub async fn permission_list( + &self, + input: &PermissionListInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}/permission", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `GET /api/session/:sessionID/permission/:requestID` (`get`) + pub async fn permission_get( + &self, + input: &PermissionGetInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/session/{}/permission/{}", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.request_id)? + ), + 200, + &[400, 401, 404], + ); + + self.data(call, options).await + } + + /// `POST /api/session/:sessionID/permission/:requestID/reply` (`reply`) + pub async fn permission_reply( + &self, + input: &PermissionReplyInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + format!( + "/api/session/{}/permission/{}/reply", + crate::client::path_param(&input.session_id)?, + crate::client::path_param(&input.request_id)? + ), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("decision", &input.decision)?; + if let Some(value) = &input.message { + call.field("message", value)?; + } + self.empty(call, options).await + } + + /// `GET /api/fs/read/*` (`read`) + pub async fn file_read( + &self, + input: &FileReadInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!("/api/fs/read/{}", crate::client::path_wildcard(&input.path)), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.binary(call, options).await + } + + /// `GET /api/fs/list` (`list`) + pub async fn file_list( + &self, + input: &FileListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/fs/list".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.path { + call.query("path", value)?; + } + self.json(call, options).await + } + + /// `GET /api/fs/find` (`find`) + pub async fn file_find( + &self, + input: &FileFindInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/fs/find".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.query("query", &input.query)?; + if let Some(value) = &input.r#type { + call.query("type", value)?; + } + if let Some(value) = &input.limit { + call.query("limit", value)?; + } + self.json(call, options).await + } + + /// `POST /api/experimental/fs/write` (`write`) + pub async fn experimental_file_write( + &self, + input: &ExperimentalFileWriteInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/fs/write".to_owned(), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.query("path", &input.path)?; + call.bytes(input.payload.clone()); + self.json(call, options).await + } + + /// `POST /api/experimental/fs/watch` (`watch`) + pub async fn experimental_file_watch( + &self, + input: &ExperimentalFileWatchInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + "/api/experimental/fs/watch".to_owned(), + 200, + &[400, 401, 404, 503], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("path", &input.path)?; + self.empty(call, options).await + } + + /// `DELETE /api/experimental/fs/watch` (`unwatch`) + pub async fn experimental_file_unwatch( + &self, + input: &ExperimentalFileUnwatchInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + "/api/experimental/fs/watch".to_owned(), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("path", &input.path)?; + self.empty(call, options).await + } + + /// `GET /api/command` (`list`) + pub async fn command_list( + &self, + input: &CommandListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/command".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/skill` (`list`) + pub async fn skill_list( + &self, + input: &SkillListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/skill".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/rpc/:rpcID/:method` (`call`) + pub async fn rpc_call( + &self, + input: &RpcCallInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/rpc/{}/{}", + crate::client::path_param(&input.rpc_id)?, + crate::client::path_param(&input.method)? + ), + 200, + &[400, 401, 404, 500], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.input { + call.field("input", value)?; + } + self.json(call, options).await + } + + /// `GET /api/event` (`subscribe`) + pub async fn event_subscribe( + &self, + input: &EventSubscribeInput, + options: &RequestOptions, + ) -> Result, Error> { + let mut call = Call::new("GET", "/api/event".to_owned(), 200, &[400, 401]); + if let Some(value) = &input.types { + call.query("types", value)?; + } + self.sse(call, options).await + } + + /// `GET /api/pty` (`list`) + pub async fn pty_list( + &self, + input: &PtyListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/pty".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/pty` (`create`) + pub async fn pty_create( + &self, + input: &PtyCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("POST", "/api/pty".to_owned(), 200, &[400, 401, 404]); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.command { + call.field("command", value)?; + } + if let Some(value) = &input.args { + call.field("args", value)?; + } + if let Some(value) = &input.cwd { + call.field("cwd", value)?; + } + if let Some(value) = &input.title { + call.field("title", value)?; + } + if let Some(value) = &input.env { + call.field("env", value)?; + } + self.json(call, options).await + } + + /// `GET /api/pty/:ptyID` (`get`) + pub async fn pty_get( + &self, + input: &PtyGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!("/api/pty/{}", crate::client::path_param(&input.pty_id)?), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `PUT /api/pty/:ptyID` (`update`) + pub async fn pty_update( + &self, + input: &PtyUpdateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "PUT", + format!("/api/pty/{}", crate::client::path_param(&input.pty_id)?), + 200, + &[400, 401, 404], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.title { + call.field("title", value)?; + } + if let Some(value) = &input.size { + call.field("size", value)?; + } + self.json(call, options).await + } + + /// `DELETE /api/pty/:ptyID` (`remove`) + pub async fn pty_remove( + &self, + input: &PtyRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + format!("/api/pty/{}", crate::client::path_param(&input.pty_id)?), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `POST /api/pty/:ptyID/connect-token` (`connect.token`) + pub async fn pty_connect_token( + &self, + input: &PtyConnectTokenInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/pty/{}/connect-token", + crate::client::path_param(&input.pty_id)? + ), + 200, + &[400, 401, 403, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.x_opencode_ticket { + call.header("x-opencode-ticket", value)?; + } + self.json(call, options).await + } + + /// `GET /api/experimental/session/:sessionID/terminal/read` (`persistentPty.read`) + pub async fn experimental_persistent_pty_read( + &self, + input: &ExperimentalPersistentPtyReadInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/experimental/session/{}/terminal/read", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 503], + ); + if let Some(value) = &input.lines { + call.query("lines", value)?; + } + self.data(call, options).await + } + + /// `GET /api/experimental/session/:sessionID/terminal` (`persistentPty.list`) + pub async fn experimental_persistent_pty_list( + &self, + input: &ExperimentalPersistentPtyListInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/experimental/session/{}/terminal", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 503], + ); + + self.data(call, options).await + } + + /// `POST /api/experimental/session/:sessionID/terminal` (`persistentPty.create`) + pub async fn experimental_persistent_pty_create( + &self, + input: &ExperimentalPersistentPtyCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/experimental/session/{}/terminal", + crate::client::path_param(&input.session_id)? + ), + 200, + &[400, 401, 503], + ); + call.object(); + if let Some(value) = &input.command { + call.field("command", value)?; + } + call.field("args", &input.args)?; + if let Some(value) = &input.cwd { + call.field("cwd", value)?; + } + call.field("title", &input.title)?; + call.field("env", &input.env)?; + if let Some(value) = &input.size { + call.field("size", value)?; + } + self.data(call, options).await + } + + /// `POST /api/experimental/persistent-pty/shutdown` (`persistentPty.shutdown`) + pub async fn experimental_persistent_pty_shutdown( + &self, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "POST", + "/api/experimental/persistent-pty/shutdown".to_owned(), + 200, + &[400, 401, 503], + ); + + self.empty(call, options).await + } + + /// `POST /api/experimental/persistent-pty/handoff` (`persistentPty.handoff`) + pub async fn experimental_persistent_pty_handoff( + &self, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "POST", + "/api/experimental/persistent-pty/handoff".to_owned(), + 200, + &[400, 401, 503], + ); + + self.json(call, options).await + } + + /// `GET /api/experimental/persistent-pty/:ptyID` (`persistentPty.get`) + pub async fn experimental_persistent_pty_get( + &self, + input: &ExperimentalPersistentPtyGetInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/experimental/persistent-pty/{}", + crate::client::path_param(&input.pty_id)? + ), + 200, + &[400, 401, 404, 503], + ); + + self.data(call, options).await + } + + /// `PUT /api/experimental/persistent-pty/:ptyID` (`persistentPty.update`) + pub async fn experimental_persistent_pty_update( + &self, + input: &ExperimentalPersistentPtyUpdateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "PUT", + format!( + "/api/experimental/persistent-pty/{}", + crate::client::path_param(&input.pty_id)? + ), + 200, + &[400, 401, 404, 501, 503], + ); + call.object(); + if let Some(value) = &input.attachment_id { + call.field("attachmentID", value)?; + } + if let Some(value) = &input.size { + call.field("size", value)?; + } + if let Some(value) = &input.title { + call.field("title", value)?; + } + self.data(call, options).await + } + + /// `GET /api/experimental/persistent-pty/:ptyID/snapshot` (`persistentPty.snapshot`) + pub async fn experimental_persistent_pty_snapshot( + &self, + input: &ExperimentalPersistentPtySnapshotInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/experimental/persistent-pty/{}/snapshot", + crate::client::path_param(&input.pty_id)? + ), + 200, + &[400, 401, 404, 503], + ); + + self.data(call, options).await + } + + /// `DELETE /api/experimental/persistent-pty/:ptyID` (`persistentPty.remove`) + pub async fn experimental_persistent_pty_remove( + &self, + input: &ExperimentalPersistentPtyRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/experimental/persistent-pty/{}", + crate::client::path_param(&input.pty_id)? + ), + 200, + &[400, 401, 404, 503], + ); + + self.empty(call, options).await + } + + /// `POST /api/experimental/persistent-pty/:ptyID/connect-token` (`persistentPty.connectToken`) + pub async fn experimental_persistent_pty_connect_token( + &self, + input: &ExperimentalPersistentPtyConnectTokenInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + format!( + "/api/experimental/persistent-pty/{}/connect-token", + crate::client::path_param(&input.pty_id)? + ), + 200, + &[400, 401, 403, 404, 503], + ); + if let Some(value) = &input.x_opencode_ticket { + call.header("x-opencode-ticket", value)?; + } + self.data(call, options).await + } + + /// `GET /api/experimental/media/:hash` (`media.get`) + pub async fn experimental_media_get( + &self, + input: &ExperimentalMediaGetInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/experimental/media/{}", + crate::client::path_param(&input.hash)? + ), + 200, + &[400, 401, 404], + ); + + self.binary(call, options).await + } + + /// `POST /api/experimental/schedule` (`schedule.create`) + pub async fn experimental_schedule_create( + &self, + input: &ExperimentalScheduleCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/schedule".to_owned(), + 200, + &[400, 401, 403, 404], + ); + call.object(); + call.field("sessionID", &input.session_id)?; + if let Some(value) = &input.name { + call.field("name", value)?; + } + if let Some(value) = &input.when { + call.field("when", value)?; + } + if let Some(value) = &input.r#if { + call.field("if", value)?; + } + if let Some(value) = &input.until { + call.field("until", value)?; + } + if let Some(value) = &input.ends { + call.field("ends", value)?; + } + call.field("prompt", &input.prompt)?; + self.data(call, options).await + } + + /// `GET /api/experimental/schedule` (`schedule.list`) + pub async fn experimental_schedule_list( + &self, + input: &ExperimentalScheduleListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/experimental/schedule".to_owned(), + 200, + &[400, 401, 403, 404], + ); + call.query("sessionID", &input.session_id)?; + self.data(call, options).await + } + + /// `GET /api/experimental/schedule/:scheduleID` (`schedule.get`) + pub async fn experimental_schedule_get( + &self, + input: &ExperimentalScheduleGetInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + format!( + "/api/experimental/schedule/{}", + crate::client::path_param(&input.schedule_id)? + ), + 200, + &[400, 401, 403, 404], + ); + + self.data(call, options).await + } + + /// `POST /api/experimental/schedule/:scheduleID/pause` (`schedule.pause`) + pub async fn experimental_schedule_pause( + &self, + input: &ExperimentalSchedulePauseInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "POST", + format!( + "/api/experimental/schedule/{}/pause", + crate::client::path_param(&input.schedule_id)? + ), + 200, + &[400, 401, 403, 404], + ); + + self.data(call, options).await + } + + /// `POST /api/experimental/schedule/:scheduleID/resume` (`schedule.resume`) + pub async fn experimental_schedule_resume( + &self, + input: &ExperimentalScheduleResumeInput, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "POST", + format!( + "/api/experimental/schedule/{}/resume", + crate::client::path_param(&input.schedule_id)? + ), + 200, + &[400, 401, 403, 404], + ); + + self.data(call, options).await + } + + /// `DELETE /api/experimental/schedule/:scheduleID` (`schedule.delete`) + pub async fn experimental_schedule_delete( + &self, + input: &ExperimentalScheduleDeleteInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let call = Call::new( + "DELETE", + format!( + "/api/experimental/schedule/{}", + crate::client::path_param(&input.schedule_id)? + ), + 200, + &[400, 401, 403, 404], + ); + + self.empty(call, options).await + } + + /// `GET /api/experimental/artifacts/providers` (`artifacts.providers`) + pub async fn experimental_artifacts_providers( + &self, + input: &ExperimentalArtifactsProvidersInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/experimental/artifacts/providers".to_owned(), + 200, + &[400, 401, 403, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/experimental/artifacts` (`artifacts.list`) + pub async fn experimental_artifacts_list( + &self, + input: &ExperimentalArtifactsListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/experimental/artifacts".to_owned(), + 200, + &[400, 401, 403, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.session_id { + call.query("sessionID", value)?; + } + if let Some(value) = &input.provider { + call.query("provider", value)?; + } + self.json(call, options).await + } + + /// `POST /api/experimental/artifacts` (`artifacts.create`) + pub async fn experimental_artifacts_create( + &self, + input: &ExperimentalArtifactsCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/experimental/artifacts".to_owned(), + 200, + &[400, 401, 403, 404, 503], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("title", &input.title)?; + call.field("files", &input.files)?; + if let Some(value) = &input.entry { + call.field("entry", value)?; + } + if let Some(value) = &input.provider { + call.field("provider", value)?; + } + if let Some(value) = &input.session_id { + call.field("sessionID", value)?; + } + self.json(call, options).await + } + + /// `GET /api/experimental/artifacts/:artifactID` (`artifacts.get`) + pub async fn experimental_artifacts_get( + &self, + input: &ExperimentalArtifactsGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/experimental/artifacts/{}", + crate::client::path_param(&input.artifact_id)? + ), + 200, + &[400, 401, 403, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `PATCH /api/experimental/artifacts/:artifactID` (`artifacts.update`) + pub async fn experimental_artifacts_update( + &self, + input: &ExperimentalArtifactsUpdateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "PATCH", + format!( + "/api/experimental/artifacts/{}", + crate::client::path_param(&input.artifact_id)? + ), + 200, + &[400, 401, 403, 404, 503], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.title { + call.field("title", value)?; + } + call.field("files", &input.files)?; + if let Some(value) = &input.entry { + call.field("entry", value)?; + } + if let Some(value) = &input.session_id { + call.field("sessionID", value)?; + } + self.json(call, options).await + } + + /// `DELETE /api/experimental/artifacts/:artifactID` (`artifacts.delete`) + pub async fn experimental_artifacts_delete( + &self, + input: &ExperimentalArtifactsDeleteInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + format!( + "/api/experimental/artifacts/{}", + crate::client::path_param(&input.artifact_id)? + ), + 200, + &[400, 401, 403, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `GET /api/experimental/artifacts/:artifactID/view/*` (`artifacts.view`) + pub async fn experimental_artifacts_view( + &self, + input: &ExperimentalArtifactsViewInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/experimental/artifacts/{}/view/{}", + crate::client::path_param(&input.artifact_id)?, + crate::client::path_wildcard(&input.path) + ), + 200, + &[400, 401, 403, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.binary(call, options).await + } + + /// `GET /api/experimental/job` (`job.list`) + pub async fn experimental_job_list( + &self, + input: &ExperimentalJobListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/experimental/job".to_owned(), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.session_id { + call.query("sessionID", value)?; + } + if let Some(value) = &input.kind { + call.query("kind", value)?; + } + if let Some(value) = &input.status { + call.query("status", value)?; + } + if let Some(value) = &input.descendants { + call.query("descendants", value)?; + } + self.data(call, options).await + } + + /// `GET /api/shell` (`list`) + pub async fn shell_list( + &self, + input: &ShellListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/shell".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/shell` (`create`) + pub async fn shell_create( + &self, + input: &ShellCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("POST", "/api/shell".to_owned(), 200, &[400, 401, 404]); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("command", &input.command)?; + if let Some(value) = &input.cwd { + call.field("cwd", value)?; + } + if let Some(value) = &input.timeout { + call.field("timeout", value)?; + } + if let Some(value) = &input.metadata { + call.field("metadata", value)?; + } + self.json(call, options).await + } + + /// `GET /api/shell/:id` (`get`) + pub async fn shell_get( + &self, + input: &ShellGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!("/api/shell/{}", crate::client::path_param(&input.id)?), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/shell/:id/output` (`output`) + pub async fn shell_output( + &self, + input: &ShellOutputInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + format!( + "/api/shell/{}/output", + crate::client::path_param(&input.id)? + ), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.cursor { + call.query("cursor", value)?; + } + if let Some(value) = &input.limit { + call.query("limit", value)?; + } + self.json(call, options).await + } + + /// `DELETE /api/shell/:id` (`remove`) + pub async fn shell_remove( + &self, + input: &ShellRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "DELETE", + format!("/api/shell/{}", crate::client::path_param(&input.id)?), + 200, + &[400, 401, 404], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `GET /api/reference` (`list`) + pub async fn reference_list( + &self, + input: &ReferenceListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/reference".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/worktree` (`list`) + pub async fn worktree_list( + &self, + input: &WorktreeListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/worktree".to_owned(), 200, &[400, 401, 404]); + call.query("projectID", &input.project_id)?; + self.json(call, options).await + } + + /// `POST /api/worktree` (`create`) + pub async fn worktree_create( + &self, + input: &WorktreeCreateInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("POST", "/api/worktree".to_owned(), 200, &[400, 401, 404]); + call.object(); + call.field("projectID", &input.project_id)?; + if let Some(value) = &input.from { + call.field("from", value)?; + } + if let Some(value) = &input.branch { + call.field("branch", value)?; + } + if let Some(value) = &input.directory { + call.field("directory", value)?; + } + if let Some(value) = &input.name { + call.field("name", value)?; + } + self.json(call, options).await + } + + /// `DELETE /api/worktree` (`remove`) + pub async fn worktree_remove( + &self, + input: &WorktreeRemoveInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new("DELETE", "/api/worktree".to_owned(), 200, &[400, 401, 404]); + call.object(); + call.field("projectID", &input.project_id)?; + call.field("directory", &input.directory)?; + call.field("force", &input.force)?; + self.empty(call, options).await + } + + /// `POST /api/worktree/refresh` (`refresh`) + pub async fn worktree_refresh( + &self, + input: &WorktreeRefreshInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + "/api/worktree/refresh".to_owned(), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("projectID", &input.project_id)?; + self.empty(call, options).await + } + + /// `POST /api/vcs/init` (`init`) + pub async fn vcs_init( + &self, + input: &VcsInitInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "POST", + "/api/vcs/init".to_owned(), + 200, + &[400, 401, 404, 409, 501, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.provider { + call.query("provider", value)?; + } + self.empty(call, options).await + } + + /// `GET /api/vcs` (`get`) + pub async fn vcs_get( + &self, + input: &VcsGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/vcs".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/vcs/base` (`base`) + pub async fn vcs_base( + &self, + input: &VcsBaseInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/vcs/base".to_owned(), + 200, + &[400, 401, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/vcs/status` (`status`) + pub async fn vcs_status( + &self, + input: &VcsStatusInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/vcs/status".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/vcs/branch` (`branch.list`) + pub async fn vcs_branch_list( + &self, + input: &VcsBranchListInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/vcs/branch".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + if let Some(value) = &input.search { + call.query("search", value)?; + } + if let Some(value) = &input.limit { + call.query("limit", value)?; + } + self.json(call, options).await + } + + /// `GET /api/vcs/diff` (`diff`) + pub async fn vcs_diff( + &self, + input: &VcsDiffInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/vcs/diff".to_owned(), + 200, + &[400, 401, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.query("mode", &input.mode)?; + if let Some(value) = &input.base { + call.query("base", value)?; + } + if let Some(value) = &input.context { + call.query("context", value)?; + } + if let Some(value) = &input.untracked { + call.query("untracked", value)?; + } + self.json(call, options).await + } + + /// `POST /api/debug/heap-dump` (`heapDump`) + pub async fn debug_heap_dump( + &self, + input: &DebugHeapDumpInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/debug/heap-dump".to_owned(), + 200, + &[400, 401, 500], + ); + if let Some(value) = &input.directory { + call.query("directory", value)?; + } + self.json(call, options).await + } + + /// `GET /api/debug/location` (`location.list`) + pub async fn debug_location_list( + &self, + options: &RequestOptions, + ) -> Result { + let call = Call::new("GET", "/api/debug/location".to_owned(), 200, &[400, 401]); + + self.json(call, options).await + } + + /// `DELETE /api/debug/location` (`location.evict`) + pub async fn debug_location_evict( + &self, + input: &DebugLocationEvictInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new("DELETE", "/api/debug/location".to_owned(), 200, &[400, 401]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.empty(call, options).await + } + + /// `GET /api/experimental/migration/v1` (`v1.status`) + pub async fn experimental_migration_v1_status( + &self, + options: &RequestOptions, + ) -> Result { + let call = Call::new( + "GET", + "/api/experimental/migration/v1".to_owned(), + 200, + &[400, 401], + ); + + self.json(call, options).await + } + + /// `GET /api/websearch/provider` (`providers`) + pub async fn websearch_providers( + &self, + input: &WebsearchProvidersInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/websearch/provider".to_owned(), + 200, + &[400, 401, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `POST /api/websearch` (`query`) + pub async fn websearch_query( + &self, + input: &WebsearchQueryInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "POST", + "/api/websearch".to_owned(), + 200, + &[400, 401, 404, 503], + ); + call.object(); + if let Some(value) = &input.location { + call.query("location", value)?; + } + call.field("query", &input.query)?; + if let Some(value) = &input.provider_id { + call.field("providerID", value)?; + } + self.json(call, options).await + } + + /// `GET /api/experimental/usage/limits` (`limits`) + pub async fn experimental_usage_limits( + &self, + input: &ExperimentalUsageLimitsInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new( + "GET", + "/api/experimental/usage/limits".to_owned(), + 200, + &[400, 401, 404, 503], + ); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/config` (`get`) + pub async fn config_get( + &self, + input: &ConfigGetInput, + options: &RequestOptions, + ) -> Result { + let mut call = Call::new("GET", "/api/config".to_owned(), 200, &[400, 401, 404]); + if let Some(value) = &input.location { + call.query("location", value)?; + } + self.json(call, options).await + } + + /// `GET /api/config/shell` (`shells`) + pub async fn config_shells( + &self, + options: &RequestOptions, + ) -> Result { + let call = Call::new("GET", "/api/config/shell".to_owned(), 200, &[400, 401, 404]); + + self.json(call, options).await + } + + /// `PATCH /api/experimental/config` (`update`) + pub async fn experimental_config_update( + &self, + input: &ExperimentalConfigUpdateInput, + options: &RequestOptions, + ) -> Result<(), Error> { + let mut call = Call::new( + "PATCH", + "/api/experimental/config".to_owned(), + 200, + &[400, 401, 404], + ); + call.object(); + call.field("shell", &input.shell)?; + self.empty(call, options).await + } +} diff --git a/packages/cli-rs/crates/api/src/generated/mod.rs b/packages/cli-rs/crates/api/src/generated/mod.rs index 6d083dd96a2..c752301357a 100644 --- a/packages/cli-rs/crates/api/src/generated/mod.rs +++ b/packages/cli-rs/crates/api/src/generated/mod.rs @@ -1 +1,10 @@ +// Generated by script/gen/api.ts from ClientApi. Do not edit. //! Types and methods generated from `ClientApi` by `script/gen/api.ts` (F.2). + +mod methods; +pub mod types; + +pub use types::*; + +/// Endpoints in the generated client. +pub const ENDPOINTS: usize = 166; diff --git a/packages/cli-rs/crates/api/src/generated/types.rs b/packages/cli-rs/crates/api/src/generated/types.rs new file mode 100644 index 00000000000..32ef68e571c --- /dev/null +++ b/packages/cli-rs/crates/api/src/generated/types.rs @@ -0,0 +1,14016 @@ +// Generated by script/gen/api.ts from ClientApi. Do not edit. +#![allow(clippy::all, clippy::pedantic, non_camel_case_types)] + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ServerInfoPaths { + pub tmp: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ServerInfoCapabilities { + #[serde( + rename = "persistentPty", + default, + skip_serializing_if = "Option::is_none" + )] + pub persistent_pty: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ServerInfo { + pub version: String, + pub pid: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hostname: Option, + pub urls: Vec, + pub paths: ServerInfoPaths, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub capabilities: Option, +} + +/// Output of [`Client::server_info`]. +pub type ServerInfoOutput = ServerInfo; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PairingCode { + pub code: String, + pub expires_in: i64, +} + +/// Output of [`Client::server_pair`]. +pub type ServerPairOutput = PairingCode; + +/// Input of [`Client::server_connect`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ServerConnectInput { + pub code: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PairingSession { + pub token: String, +} + +/// Output of [`Client::server_connect`]. +pub type ServerConnectOutput = PairingSession; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::location_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct LocationGetInput { + pub location: Option, +} + +/// `AbsolutePath` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct AbsolutePath(pub String); + +impl AbsolutePath { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for AbsolutePath { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for AbsolutePath { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for AbsolutePath { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// `Project.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ProjectID(pub String); + +impl ProjectID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ProjectID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ProjectID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ProjectID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationPublicInfoProject { + pub id: ProjectID, + pub directory: AbsolutePath, + pub canonical: AbsolutePath, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationPublicInfo { + pub directory: AbsolutePath, + pub project: LocationPublicInfoProject, +} + +/// Output of [`Client::location_get`]. +pub type LocationGetOutput = LocationPublicInfo; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct AgentListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::agent_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct AgentListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationPublicRef { + pub directory: AbsolutePath, +} + +/// `Agent.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct AgentID(pub String); + +impl AgentID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for AgentID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for AgentID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for AgentID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// `Provider.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ProviderID(pub String); + +impl ProviderID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ProviderID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ProviderID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ProviderID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelRef { + pub id: String, + #[serde(rename = "providerID")] + pub provider_id: ProviderID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProviderSettingsTimeout { + Number(f64), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProviderSettingsHeaderTimeout { + Number(f64), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProviderSettingsChunkTimeout { + Number(f64), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderCompactionSummary { + pub r#type: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderCompactionNative { + pub r#type: String, +} + +/// `Provider.Compaction`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ProviderCompaction { + Summary(ProviderCompactionSummary), + Native(ProviderCompactionNative), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ProviderCompaction { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("summary") => crate::de::variant(value).map(Self::Summary), + Some("native") => crate::de::variant(value).map(Self::Native), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// `Provider.CacheTTL` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ProviderCacheTTL(pub String); + +impl ProviderCacheTTL { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ProviderCacheTTL { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ProviderCacheTTL { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ProviderCacheTTL { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderCacheWarmingObject { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub interval: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration: Option, +} + +/// `Provider.CacheWarming` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProviderCacheWarming { + Bool(bool), + Object(ProviderCacheWarmingObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderCache { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ttl: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub warming: Option, +} + +/// `Provider.Transport` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ProviderTransport { + Http, + Websocket, + Unknown(String), +} + +impl ProviderTransport { + pub fn as_str(&self) -> &str { + match self { + Self::Http => "http", + Self::Websocket => "websocket", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ProviderTransport { + fn from(value: &str) -> Self { + match value { + "http" => Self::Http, + "websocket" => Self::Websocket, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ProviderTransport { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ProviderTransport { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Provider.Encoding` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ProviderEncoding { + Zstd, + Gzip, + None, + Unknown(String), +} + +impl ProviderEncoding { + pub fn as_str(&self) -> &str { + match self { + Self::Zstd => "zstd", + Self::Gzip => "gzip", + Self::None => "none", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ProviderEncoding { + fn from(value: &str) -> Self { + match value { + "zstd" => Self::Zstd, + "gzip" => Self::Gzip, + "none" => Self::None, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ProviderEncoding { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ProviderEncoding { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde( + rename = "headerTimeout", + default, + skip_serializing_if = "Option::is_none" + )] + pub header_timeout: Option, + #[serde( + rename = "chunkTimeout", + default, + skip_serializing_if = "Option::is_none" + )] + pub chunk_timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encoding: Option, + #[serde(flatten)] + pub extra: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderRequest { + pub settings: ProviderSettings, + pub headers: BTreeMap, + pub body: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum AgentInfoMode { + Subagent, + Primary, + All, + Unknown(String), +} + +impl AgentInfoMode { + pub fn as_str(&self) -> &str { + match self { + Self::Subagent => "subagent", + Self::Primary => "primary", + Self::All => "all", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for AgentInfoMode { + fn from(value: &str) -> Self { + match value { + "subagent" => Self::Subagent, + "primary" => Self::Primary, + "all" => Self::All, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for AgentInfoMode { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for AgentInfoMode { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Agent.Color` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct AgentColor(pub String); + +impl AgentColor { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for AgentColor { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for AgentColor { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for AgentColor { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// `Permission.Effect` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PermissionEffect { + Allow, + Deny, + Ask, + Unknown(String), +} + +impl PermissionEffect { + pub fn as_str(&self) -> &str { + match self { + Self::Allow => "allow", + Self::Deny => "deny", + Self::Ask => "ask", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for PermissionEffect { + fn from(value: &str) -> Self { + match value { + "allow" => Self::Allow, + "deny" => Self::Deny, + "ask" => Self::Ask, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for PermissionEffect { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for PermissionEffect { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PermissionRule { + pub action: String, + pub resource: String, + pub effect: PermissionEffect, +} + +/// `Permission.Ruleset` +pub type PermissionRuleset = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AgentInfo { + pub id: AgentID, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + pub request: ProviderRequest, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub system: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + pub mode: AgentInfoMode, + pub hidden: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub steps: Option, + pub permissions: PermissionRuleset, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct AgentListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct AgentGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::agent_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct AgentGetInput { + pub agent_id: AgentID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AgentGetOutput { + pub location: LocationPublicRef, + pub data: AgentInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::plugin_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PluginListInput { + pub location: Option, +} + +/// `Plugin.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct PluginID(pub String); + +impl PluginID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for PluginID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for PluginID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for PluginID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginSourceBuiltin { + pub r#type: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginSourcePackage { + pub r#type: String, + pub target: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outdated: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updating: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginSourceLocal { + pub r#type: String, + pub path: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginSourceSdk { + pub r#type: String, +} + +/// `Plugin.Source`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum PluginSource { + Builtin(PluginSourceBuiltin), + Package(PluginSourcePackage), + Local(PluginSourceLocal), + Sdk(PluginSourceSdk), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for PluginSource { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("builtin") => crate::de::variant(value).map(Self::Builtin), + Some("package") => crate::de::variant(value).map(Self::Package), + Some("local") => crate::de::variant(value).map(Self::Local), + Some("sdk") => crate::de::variant(value).map(Self::Sdk), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginFeatures { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub server: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tui: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rpc: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gui: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginStateActive { + pub status: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginStateFailed { + pub status: String, + pub error: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub r#ref: Option, +} + +/// `Plugin.State`, tagged by `status`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum PluginState { + Active(PluginStateActive), + Failed(PluginStateFailed), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for PluginState { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("active") => crate::de::variant(value).map(Self::Active), + Some("failed") => crate::de::variant(value).map(Self::Failed), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PluginInfo { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + pub source: PluginSource, + pub features: PluginFeatures, + pub state: PluginState, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginGuiInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::plugin_gui`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PluginGuiInput { + pub location: Option, + pub id: PluginID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginGuiBundle { + pub code: String, + pub revision: String, + pub options: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginGuiOutput { + pub location: LocationPublicRef, + pub data: PluginGuiBundle, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginCheckInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::plugin_check`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PluginCheckInput { + pub location: Option, + pub target: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginCheckOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginUpdateInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::plugin_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PluginUpdateInput { + pub location: Option, + pub targets: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionListInputOrder { + Asc, + Desc, + Unknown(String), +} + +impl SessionListInputOrder { + pub fn as_str(&self) -> &str { + match self { + Self::Asc => "asc", + Self::Desc => "desc", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionListInputOrder { + fn from(value: &str) -> Self { + match value { + "asc" => Self::Asc, + "desc" => Self::Desc, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionListInputOrder { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionListInputOrder { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Session.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SessionID(pub String); + +impl SessionID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for SessionID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for SessionID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for SessionID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// `RelativePath` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct RelativePath(pub String); + +impl RelativePath { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for RelativePath { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for RelativePath { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for RelativePath { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// `SessionsCursor` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SessionsCursor(pub String); + +impl SessionsCursor { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for SessionsCursor { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for SessionsCursor { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for SessionsCursor { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// Input of [`Client::session_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionListInput { + pub limit: Option, + pub order: Option, + pub search: Option, + pub parent_id: Option>, + pub archived: Option, + pub directory: Option, + pub project: Option, + pub subpath: Option, + pub cursor: Option, +} + +/// `Session.Message.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SessionMessageID(pub String); + +impl SessionMessageID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for SessionMessageID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for SessionMessageID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for SessionMessageID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionForkBoundaryBefore { + pub r#type: String, + #[serde(rename = "messageID")] + pub message_id: SessionMessageID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionForkBoundaryThrough { + pub r#type: String, + #[serde(rename = "messageID")] + pub message_id: SessionMessageID, +} + +/// `Session.ForkBoundary`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionForkBoundary { + Before(SessionForkBoundaryBefore), + Through(SessionForkBoundaryThrough), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionForkBoundary { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("before") => crate::de::variant(value).map(Self::Before), + Some("through") => crate::de::variant(value).map(Self::Through), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInfoFork { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub boundary: SessionForkBoundary, +} + +/// `Money.USD` +pub type MoneyUSD = f64; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TokenUsageInfoCache { + pub read: f64, + pub write: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TokenUsageInfo { + pub input: f64, + pub output: f64, + pub reasoning: f64, + pub cache: TokenUsageInfoCache, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionInfoOutcome { + Succeeded, + Failed, + Interrupted, + Unknown(String), +} + +impl SessionInfoOutcome { + pub fn as_str(&self) -> &str { + match self { + Self::Succeeded => "succeeded", + Self::Failed => "failed", + Self::Interrupted => "interrupted", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionInfoOutcome { + fn from(value: &str) -> Self { + match value { + "succeeded" => Self::Succeeded, + "failed" => Self::Failed, + "interrupted" => Self::Interrupted, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionInfoOutcome { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionInfoOutcome { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInfoTime { + pub created: f64, + pub updated: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub busy: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub idle: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub viewed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub archived: Option, +} + +/// `Session.Metadata` +pub type SessionMetadata = BTreeMap; + +/// `Snapshot.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SnapshotID(pub String); + +impl SnapshotID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for SnapshotID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for SnapshotID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for SnapshotID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum FileDiffInfoStatus { + Added, + Deleted, + Modified, + Unknown(String), +} + +impl FileDiffInfoStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Added => "added", + Self::Deleted => "deleted", + Self::Modified => "modified", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for FileDiffInfoStatus { + fn from(value: &str) -> Self { + match value { + "added" => Self::Added, + "deleted" => Self::Deleted, + "modified" => Self::Modified, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for FileDiffInfoStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for FileDiffInfoStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FileDiffInfo { + pub file: String, + pub patch: String, + pub additions: i64, + pub deletions: i64, + pub status: FileDiffInfoStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub more: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevert { + #[serde(rename = "messageID")] + pub message_id: SessionMessageID, + #[serde(rename = "partID", default, skip_serializing_if = "Option::is_none")] + pub part_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub files: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInfo { + pub id: SessionID, + #[serde(rename = "parentID", default, skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fork: Option, + #[serde(rename = "projectID")] + pub project_id: ProjectID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + pub cost: MoneyUSD, + pub tokens: TokenUsageInfo, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outcome: Option, + pub time: SessionInfoTime, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subpath: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub permissions: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revert: Option, + pub location: LocationPublicRef, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionsResponseCursor { + #[serde( + default, + deserialize_with = "crate::de::double_option", + skip_serializing_if = "Option::is_none" + )] + pub previous: Option>, + #[serde( + default, + deserialize_with = "crate::de::double_option", + skip_serializing_if = "Option::is_none" + )] + pub next: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionsResponse { + pub data: Vec, + pub cursor: SessionsResponseCursor, +} + +/// Output of [`Client::session_list`]. +pub type SessionListOutput = SessionsResponse; + +/// Input of [`Client::session_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionCreateInput { + pub id: Option>, + pub parent_id: Option>, + pub title: Option>, + pub agent: Option>, + pub model: Option>, + pub location: Option>, + pub metadata: Option>, + pub permissions: Option>, +} + +/// Output of [`Client::session_create`]. +pub type SessionCreateOutput = SessionInfo; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionActive { + pub r#type: String, +} + +/// Output of [`Client::session_active`]. +pub type SessionActiveOutput = BTreeMap; + +/// Input of [`Client::session_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionGetInput { + pub session_id: SessionID, +} + +/// Output of [`Client::session_get`]. +pub type SessionGetOutput = SessionInfo; + +/// Input of [`Client::session_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionRemoveInput { + pub session_id: SessionID, +} + +/// Input of [`Client::session_fork`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionForkInput { + pub session_id: SessionID, + pub before: Option, +} + +/// Output of [`Client::session_fork`]. +pub type SessionForkOutput = SessionInfo; + +/// Input of [`Client::session_switch_agent`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionSwitchAgentInput { + pub session_id: SessionID, + pub agent: AgentID, +} + +/// Input of [`Client::session_switch_model`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionSwitchModelInput { + pub session_id: SessionID, + pub model: ModelRef, +} + +/// Input of [`Client::session_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionUpdateInput { + pub session_id: SessionID, + pub title: Option, + pub metadata: Option, + pub permissions: Option, + pub archived: Option, +} + +/// `Session.Inbox.Delivery` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionInboxDelivery { + Steer, + Queue, + Unknown(String), +} + +impl SessionInboxDelivery { + pub fn as_str(&self) -> &str { + match self { + Self::Steer => "steer", + Self::Queue => "queue", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionInboxDelivery { + fn from(value: &str) -> Self { + match value { + "steer" => Self::Steer, + "queue" => Self::Queue, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionInboxDelivery { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionInboxDelivery { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// Input of [`Client::session_move`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionMoveInput { + pub session_id: SessionID, + pub directory: AbsolutePath, + pub delivery: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PromptFileSourceInline { + pub r#type: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PromptFileSourceUri { + pub r#type: String, + pub uri: String, +} + +/// `Prompt.FileSource`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum PromptFileSource { + Inline(PromptFileSourceInline), + Uri(PromptFileSourceUri), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for PromptFileSource { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("inline") => crate::de::variant(value).map(Self::Inline), + Some("uri") => crate::de::variant(value).map(Self::Uri), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PromptMention { + pub start: f64, + pub end: f64, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PromptInputFileAttachment { + pub uri: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mention: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PromptAgentAttachment { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mention: Option, +} + +/// `Skill.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SkillID(pub String); + +impl SkillID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for SkillID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for SkillID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for SkillID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PromptInputSkillAttachment { + pub id: SkillID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mention: Option, +} + +/// Input of [`Client::session_prompt`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionPromptInput { + pub session_id: SessionID, + pub id: Option>, + pub text: String, + pub files: Option>, + pub agents: Option>, + pub skills: Option>, + pub metadata: Option>, + pub delivery: Option>, + pub resume: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxUserTime { + pub created: f64, +} + +/// `Prompt.Base64` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct PromptBase64(pub String); + +impl PromptBase64 { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for PromptBase64 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for PromptBase64 { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for PromptBase64 { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PromptFileAttachment { + pub data: PromptBase64, + pub mime: String, + pub source: PromptFileSource, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mention: Option, +} + +/// `Skill.Name` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SkillName(pub String); + +impl SkillName { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for SkillName { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for SkillName { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for SkillName { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PromptSkillAttachment { + pub id: SkillID, + pub name: SkillName, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mention: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxUserPayload { + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub files: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agents: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skills: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxUser { + pub id: SessionMessageID, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub time: SessionInboxUserTime, + pub r#type: String, + pub payload: SessionInboxUserPayload, + pub delivery: SessionInboxDelivery, +} + +/// Output of [`Client::session_prompt`]. +pub type SessionPromptOutput = SessionInboxUser; + +/// Input of [`Client::session_command`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionCommandInput { + pub session_id: SessionID, + pub name: String, + pub text: String, + pub files: Option>, + pub agents: Option>, + pub skills: Option>, + pub delivery: Option>, +} + +/// Input of [`Client::session_synthetic`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionSyntheticInput { + pub session_id: SessionID, + pub id: Option>, + pub text: String, + pub description: Option>, + pub metadata: Option>, + pub delivery: Option>, + pub resume: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxSyntheticTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxSyntheticPayload { + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxSynthetic { + pub id: SessionMessageID, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub time: SessionInboxSyntheticTime, + pub r#type: String, + pub payload: SessionInboxSyntheticPayload, + pub delivery: SessionInboxDelivery, +} + +/// Output of [`Client::session_synthetic`]. +pub type SessionSyntheticOutput = SessionInboxSynthetic; + +/// Input of [`Client::session_shell`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionShellInput { + pub session_id: SessionID, + pub id: Option, + pub command: String, +} + +/// Input of [`Client::session_compact`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionCompactInput { + pub session_id: SessionID, + pub id: Option, + pub delivery: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxCompactionTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxCompactionPayload {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxCompaction { + pub id: SessionMessageID, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub time: SessionInboxCompactionTime, + pub r#type: String, + pub payload: SessionInboxCompactionPayload, + pub delivery: SessionInboxDelivery, +} + +/// Output of [`Client::session_compact`]. +pub type SessionCompactOutput = SessionInboxCompaction; + +/// Input of [`Client::session_revert_stage`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionRevertStageInput { + pub session_id: SessionID, + pub message_id: SessionMessageID, + pub files: Option, +} + +/// Output of [`Client::session_revert_stage`]. +pub type SessionRevertStageOutput = SessionRevert; + +/// Input of [`Client::session_revert_clear`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionRevertClearInput { + pub session_id: SessionID, +} + +/// Input of [`Client::session_revert_commit`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionRevertCommitInput { + pub session_id: SessionID, +} + +/// Input of [`Client::session_context`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionContextInput { + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAgentSelectedTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAgentSelected { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageAgentSelectedTime, + pub r#type: String, + pub agent: AgentID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageModelSelectedTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageModelSelected { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageModelSelectedTime, + pub r#type: String, + pub model: ModelRef, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageLocationSwitchedTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageLocationSwitchedPrevious { + pub location: LocationPublicRef, + #[serde(rename = "projectID", default, skip_serializing_if = "Option::is_none")] + pub project_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subpath: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageLocationSwitched { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageLocationSwitchedTime, + pub r#type: String, + #[serde(rename = "projectID", default, skip_serializing_if = "Option::is_none")] + pub project_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subpath: Option, + pub location: LocationPublicRef, + #[serde( + default, + deserialize_with = "crate::de::double_option", + skip_serializing_if = "Option::is_none" + )] + pub previous: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageUserTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageUser { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageUserTime, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub files: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agents: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skills: Option>, + pub r#type: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageSyntheticTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageSynthetic { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageSyntheticTime, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + pub r#type: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageSystemTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageSystem { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageSystemTime, + pub r#type: String, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageSkillTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageSkill { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageSkillTime, + pub r#type: String, + pub skill: SkillID, + pub name: SkillName, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageShellTime { + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +/// `Shell.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ShellID(pub String); + +impl ShellID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ShellID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ShellID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ShellID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionMessageShellStatus { + Running, + Exited, + Timeout, + Killed, + Unknown(String), +} + +impl SessionMessageShellStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Running => "running", + Self::Exited => "exited", + Self::Timeout => "timeout", + Self::Killed => "killed", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionMessageShellStatus { + fn from(value: &str) -> Self { + match value { + "running" => Self::Running, + "exited" => Self::Exited, + "timeout" => Self::Timeout, + "killed" => Self::Killed, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionMessageShellStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionMessageShellStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SessionMessageShellExit { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageShellOutput { + pub output: String, + pub cursor: i64, + pub size: i64, + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionMessageShell { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageShellTime, + pub r#type: String, + #[serde(rename = "shellID")] + pub shell_id: ShellID, + pub command: String, + pub status: SessionMessageShellStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exit: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantTime { + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub streamed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +/// `Session.Message.Native` +pub type SessionMessageNative = BTreeMap; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantText { + pub r#type: String, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantReasoningTime { + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantReasoning { + pub r#type: String, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub time: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageToolStateStreaming { + pub status: String, + pub input: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageToolStateRunning { + pub status: String, + pub input: BTreeMap, + pub metadata: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageToolStateCompleted { + pub status: String, + pub input: BTreeMap, + pub content: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStructuredErrorResponse { + pub body: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStructuredError { + pub r#type: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub response: Option, + #[serde( + rename = "retryAfterMs", + default, + skip_serializing_if = "Option::is_none" + )] + pub retry_after_ms: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageToolStateError { + pub status: String, + pub input: BTreeMap, + pub error: SessionStructuredError, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub content: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionMessageAssistantToolState { + Streaming(SessionMessageToolStateStreaming), + Running(SessionMessageToolStateRunning), + Completed(SessionMessageToolStateCompleted), + Error(SessionMessageToolStateError), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionMessageAssistantToolState { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("streaming") => crate::de::variant(value).map(Self::Streaming), + Some("running") => crate::de::variant(value).map(Self::Running), + Some("completed") => crate::de::variant(value).map(Self::Completed), + Some("error") => crate::de::variant(value).map(Self::Error), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantToolTime { + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ran: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionMessageAssistantTool { + pub r#type: String, + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub executed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + pub state: SessionMessageAssistantToolState, + pub time: SessionMessageAssistantToolTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionMessageAssistantContentItem { + Text(SessionMessageAssistantText), + Reasoning(SessionMessageAssistantReasoning), + Tool(SessionMessageAssistantTool), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionMessageAssistantContentItem { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("text") => crate::de::variant(value).map(Self::Text), + Some("reasoning") => crate::de::variant(value).map(Self::Reasoning), + Some("tool") => crate::de::variant(value).map(Self::Tool), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantSnapshot { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub files: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionMessageAssistantFinish { + Stop, + Length, + ToolCalls, + ContentFilter, + Error, + Unknown2, + Unknown(String), +} + +impl SessionMessageAssistantFinish { + pub fn as_str(&self) -> &str { + match self { + Self::Stop => "stop", + Self::Length => "length", + Self::ToolCalls => "tool-calls", + Self::ContentFilter => "content-filter", + Self::Error => "error", + Self::Unknown2 => "unknown", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionMessageAssistantFinish { + fn from(value: &str) -> Self { + match value { + "stop" => Self::Stop, + "length" => Self::Length, + "tool-calls" => Self::ToolCalls, + "content-filter" => Self::ContentFilter, + "error" => Self::Error, + "unknown" => Self::Unknown2, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionMessageAssistantFinish { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionMessageAssistantFinish { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantRetry { + pub attempt: i64, + pub at: f64, + pub error: SessionStructuredError, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistant { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageAssistantTime, + pub r#type: String, + pub agent: AgentID, + pub model: ModelRef, + pub content: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finish: Option, + #[serde(rename = "rawFinish", default, skip_serializing_if = "Option::is_none")] + pub raw_finish: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retry: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageCompactionRunningTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionMessageCompactionRunningReason { + Auto, + Manual, + Unknown(String), +} + +impl SessionMessageCompactionRunningReason { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Manual => "manual", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionMessageCompactionRunningReason { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "manual" => Self::Manual, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionMessageCompactionRunningReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionMessageCompactionRunningReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionMessageCompactionRunning { + pub r#type: String, + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageCompactionRunningTime, + pub status: String, + pub reason: SessionMessageCompactionRunningReason, + pub summary: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageCompactionCompletedTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionMessageCompactionCompletedReason { + Auto, + Manual, + Unknown(String), +} + +impl SessionMessageCompactionCompletedReason { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Manual => "manual", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionMessageCompactionCompletedReason { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "manual" => Self::Manual, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionMessageCompactionCompletedReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionMessageCompactionCompletedReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionMessageCompactionCompleted { + pub r#type: String, + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageCompactionCompletedTime, + pub status: String, + pub reason: SessionMessageCompactionCompletedReason, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + pub summary: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageCompactionFailedTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionMessageCompactionFailedReason { + Auto, + Manual, + Unknown(String), +} + +impl SessionMessageCompactionFailedReason { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Manual => "manual", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionMessageCompactionFailedReason { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "manual" => Self::Manual, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionMessageCompactionFailedReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionMessageCompactionFailedReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionMessageCompactionFailed { + pub r#type: String, + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageCompactionFailedTime, + pub status: String, + pub reason: SessionMessageCompactionFailedReason, + pub error: SessionStructuredError, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +/// `Session.Message.Compaction`, tagged by `status`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionMessageCompaction { + Running(SessionMessageCompactionRunning), + Completed(SessionMessageCompactionCompleted), + Failed(SessionMessageCompactionFailed), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionMessageCompaction { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("running") => crate::de::variant(value).map(Self::Running), + Some("completed") => crate::de::variant(value).map(Self::Completed), + Some("failed") => crate::de::variant(value).map(Self::Failed), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageIdleTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionMessageIdleOutcome { + Succeeded, + Failed, + Interrupted, + Unknown(String), +} + +impl SessionMessageIdleOutcome { + pub fn as_str(&self) -> &str { + match self { + Self::Succeeded => "succeeded", + Self::Failed => "failed", + Self::Interrupted => "interrupted", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionMessageIdleOutcome { + fn from(value: &str) -> Self { + match value { + "succeeded" => Self::Succeeded, + "failed" => Self::Failed, + "interrupted" => Self::Interrupted, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionMessageIdleOutcome { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionMessageIdleOutcome { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionMessageIdle { + pub id: SessionMessageID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub time: SessionMessageIdleTime, + pub r#type: String, + pub outcome: SessionMessageIdleOutcome, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// `Session.Message.Info` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SessionMessageInfo { + AgentSelected(SessionMessageAgentSelected), + ModelSelected(SessionMessageModelSelected), + LocationSwitched(SessionMessageLocationSwitched), + User(SessionMessageUser), + Synthetic(SessionMessageSynthetic), + System(SessionMessageSystem), + Skill(SessionMessageSkill), + Shell(SessionMessageShell), + Assistant(SessionMessageAssistant), + Compaction(SessionMessageCompaction), + Idle(SessionMessageIdle), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +/// Output of [`Client::session_context`]. +pub type SessionContextOutput = Vec; + +/// Input of [`Client::session_diff`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionDiffInput { + pub session_id: SessionID, + pub from: Option, + pub to: Option, + pub context: Option, +} + +/// Output of [`Client::session_diff`]. +pub type SessionDiffOutput = Vec; + +/// Input of [`Client::session_inbox_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionInboxListInput { + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxMoveTime { + pub created: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxMovePayload { + #[serde(rename = "projectID")] + pub project_id: ProjectID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subpath: Option, + pub location: LocationPublicRef, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxMove { + pub id: SessionMessageID, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub time: SessionInboxMoveTime, + pub r#type: String, + pub delivery: SessionInboxDelivery, + pub payload: SessionInboxMovePayload, +} + +/// `Session.Inbox.Info`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionInboxInfo { + User(SessionInboxUser), + Synthetic(SessionInboxSynthetic), + Compaction(SessionInboxCompaction), + Move(SessionInboxMove), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionInboxInfo { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("user") => crate::de::variant(value).map(Self::User), + Some("synthetic") => crate::de::variant(value).map(Self::Synthetic), + Some("compaction") => crate::de::variant(value).map(Self::Compaction), + Some("move") => crate::de::variant(value).map(Self::Move), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Output of [`Client::session_inbox_list`]. +pub type SessionInboxListOutput = Vec; + +/// Input of [`Client::session_inbox_cancel`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionInboxCancelInput { + pub session_id: SessionID, + pub inbox_id: SessionMessageID, +} + +/// Input of [`Client::session_inbox_update`]. +#[derive(Debug, Clone, PartialEq)] +pub struct SessionInboxUpdateInput { + pub session_id: SessionID, + pub inbox_id: SessionMessageID, + pub delivery: SessionInboxDelivery, +} + +/// Input of [`Client::session_generate`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionGenerateInput { + pub session_id: SessionID, + pub prompt: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionGenerateOutput { + pub text: String, +} + +/// Input of [`Client::session_interrupt`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionInterruptInput { + pub session_id: SessionID, + pub resume: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInterruptResponse { + pub interrupted: bool, +} + +/// Output of [`Client::session_interrupt`]. +pub type SessionInterruptOutput = SessionInterruptResponse; + +/// Input of [`Client::session_background`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionBackgroundInput { + pub session_id: SessionID, +} + +/// Input of [`Client::session_message_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionMessageGetInput { + pub session_id: SessionID, + pub message_id: SessionMessageID, +} + +/// Output of [`Client::session_message_get`]. +pub type SessionMessageGetOutput = SessionMessageInfo; + +/// Input of [`Client::session_form_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionFormListInput { + pub session_id: String, +} + +/// `Form.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct FormID(pub String); + +impl FormID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for FormID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for FormID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for FormID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// `Form.Metadata` +pub type FormMetadata = BTreeMap; + +/// `Form.Fields` +pub type FormFields = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormInfo { + pub id: FormID, + #[serde(rename = "sessionID")] + pub session_id: String, + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option, + pub fields: FormFields, +} + +/// Output of [`Client::session_form_list`]. +pub type SessionFormListOutput = Vec; + +/// Input of [`Client::session_form_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionFormCreateInput { + pub session_id: String, + pub id: Option>, + pub title: String, + pub metadata: Option, + pub fields: FormFields, +} + +/// Output of [`Client::session_form_create`]. +pub type SessionFormCreateOutput = FormInfo; + +/// Input of [`Client::session_form_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionFormGetInput { + pub session_id: String, + pub form_id: FormID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormStatePending { + pub status: String, +} + +/// `Form.Value` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum FormValue { + String(String), + Number(f64), + Bool(bool), + Array(Vec), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +/// `Form.Answer` +pub type FormAnswer = BTreeMap; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormStateAnswered { + pub status: String, + pub answer: FormAnswer, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormStateCancelled { + pub status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +/// `Form.State`, tagged by `status`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum FormState { + Pending(FormStatePending), + Answered(FormStateAnswered), + Cancelled(FormStateCancelled), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for FormState { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("pending") => crate::de::variant(value).map(Self::Pending), + Some("answered") => crate::de::variant(value).map(Self::Answered), + Some("cancelled") => crate::de::variant(value).map(Self::Cancelled), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FormDetail { + pub id: FormID, + #[serde(rename = "sessionID")] + pub session_id: String, + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option, + pub fields: FormFields, + pub state: FormState, +} + +/// Output of [`Client::session_form_get`]. +pub type SessionFormGetOutput = FormDetail; + +/// `Form.Value_1` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum FormValue1 { + String(String), + Number(f64), + Bool(bool), + Array(Vec), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +/// `Form.Answer_1` +pub type FormAnswer1 = BTreeMap; + +/// Input of [`Client::session_form_reply`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionFormReplyInput { + pub session_id: String, + pub form_id: FormID, + pub answer: FormAnswer1, +} + +/// Input of [`Client::session_form_cancel`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionFormCancelInput { + pub session_id: String, + pub form_id: FormID, + pub message: Option, +} + +/// Input of [`Client::session_environment`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionEnvironmentInput { + pub session_id: SessionID, + pub variables: BTreeMap, +} + +/// Input of [`Client::session_view`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SessionViewInput { + pub session_id: SessionID, + pub idle: f64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ExperimentalSessionStatsInputTools { + None, + Summary, + Detail, + Unknown(String), +} + +impl ExperimentalSessionStatsInputTools { + pub fn as_str(&self) -> &str { + match self { + Self::None => "none", + Self::Summary => "summary", + Self::Detail => "detail", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ExperimentalSessionStatsInputTools { + fn from(value: &str) -> Self { + match value { + "none" => Self::None, + "summary" => Self::Summary, + "detail" => Self::Detail, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ExperimentalSessionStatsInputTools { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ExperimentalSessionStatsInputTools { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// Input of [`Client::experimental_session_stats`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionStatsInput { + pub from: Option, + pub to: Option, + pub project: Option, + pub timezone: Option, + pub tools: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsInfoRange { + pub from: f64, + pub to: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsToolsNone { + pub mode: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsToolTotals { + pub calls: i64, + pub succeeded: i64, + pub failed: i64, + pub unfinished: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsToolsSummary { + pub mode: String, + pub totals: SessionStatsToolTotals, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsToolUsage { + pub name: String, + pub calls: i64, + pub succeeded: i64, + pub failed: i64, + pub unfinished: i64, + #[serde( + rename = "durationP50", + default, + skip_serializing_if = "Option::is_none" + )] + pub duration_p50: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsToolsDetail { + pub mode: String, + pub totals: SessionStatsToolTotals, + pub usage: Vec, +} + +/// `SessionStats.Tools`, tagged by `mode`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionStatsTools { + None(SessionStatsToolsNone), + Summary(SessionStatsToolsSummary), + Detail(SessionStatsToolsDetail), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionStatsTools { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("mode").and_then(serde_json::Value::as_str) { + Some("none") => crate::de::variant(value).map(Self::None), + Some("summary") => crate::de::variant(value).map(Self::Summary), + Some("detail") => crate::de::variant(value).map(Self::Detail), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsActivity { + pub date: String, + pub steps: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatsModelUsage { + pub model: ModelRef, + pub steps: i64, + pub tokens: TokenUsageInfo, + pub cost: MoneyUSD, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionStatsInfo { + pub range: SessionStatsInfoRange, + pub sessions: i64, + pub subagents: i64, + pub prompts: i64, + pub steps: i64, + pub tokens: TokenUsageInfo, + pub cost: MoneyUSD, + pub tools: SessionStatsTools, + #[serde(rename = "activeDays")] + pub active_days: i64, + pub streak: i64, + pub activity: Vec, + pub models: Vec, +} + +/// Output of [`Client::experimental_session_stats`]. +pub type ExperimentalSessionStatsOutput = SessionStatsInfo; + +/// Input of [`Client::experimental_session_import`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionImportInput { + pub info: SessionInfo, + pub messages: Vec, + pub location: Option>, +} + +/// Output of [`Client::experimental_session_import`]. +pub type ExperimentalSessionImportOutput = SessionInfo; + +/// Input of [`Client::experimental_session_export`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionExportInput { + pub session_id: SessionID, + pub sanitize: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTransferData { + pub info: SessionInfo, + pub messages: Vec, +} + +/// Output of [`Client::experimental_session_export`]. +pub type ExperimentalSessionExportOutput = SessionTransferData; + +/// Input of [`Client::experimental_session_skill`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionSkillInput { + pub session_id: SessionID, + pub id: SkillID, + pub resume: Option, +} + +/// Input of [`Client::experimental_session_wait`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionWaitInput { + pub session_id: SessionID, +} + +/// Input of [`Client::experimental_session_instructions_entry_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionInstructionsEntryListInput { + pub session_id: SessionID, +} + +/// `InstructionEntry.Key` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct InstructionEntryKey(pub String); + +impl InstructionEntryKey { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for InstructionEntryKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for InstructionEntryKey { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for InstructionEntryKey { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InstructionEntryInfo { + pub key: InstructionEntryKey, + pub value: serde_json::Value, +} + +/// Output of [`Client::experimental_session_instructions_entry_list`]. +pub type ExperimentalSessionInstructionsEntryListOutput = Vec; + +/// Input of [`Client::experimental_session_instructions_entry_put`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionInstructionsEntryPutInput { + pub session_id: SessionID, + pub key: InstructionEntryKey, + pub value: serde_json::Value, +} + +/// Input of [`Client::experimental_session_instructions_entry_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionInstructionsEntryRemoveInput { + pub session_id: SessionID, + pub key: InstructionEntryKey, +} + +/// `Event.Seq` +pub type EventSeq = i64; + +/// Input of [`Client::experimental_session_log`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSessionLogInput { + pub session_id: SessionID, + pub after: Option, + pub follow: Option, +} + +/// `Event.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct EventID(pub String); + +impl EventID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for EventID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for EventID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for EventID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCreatedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +/// `Workspace.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct WorkspaceID(pub String); + +impl WorkspaceID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for WorkspaceID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for WorkspaceID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for WorkspaceID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationRef { + pub directory: AbsolutePath, + #[serde( + rename = "workspaceID", + default, + skip_serializing_if = "Option::is_none" + )] + pub workspace_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCreatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "projectID")] + pub project_id: ProjectID, + pub location: LocationRef, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subpath: Option, + #[serde(rename = "parentID", default, skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + pub slug: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub permissions: Option, + pub version: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCreated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionCreatedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionCreatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionAgentSelectedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionAgentSelectedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub agent: AgentID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionAgentSelected { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionAgentSelectedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionAgentSelectedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionModelSelectedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionModelSelectedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub model: ModelRef, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionModelSelected { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionModelSelectedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionModelSelectedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMovedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMovedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub location: LocationRef, + #[serde(rename = "projectID")] + pub project_id: ProjectID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subpath: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMoved { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionMovedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionMovedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRenamedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRenamedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub title: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRenamed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionRenamedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionRenamedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMetadataUpdatedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMetadataUpdatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub metadata: SessionMetadata, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMetadataUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionMetadataUpdatedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionMetadataUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionPermissionsDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionPermissionsData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub permissions: PermissionRuleset, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionPermissions { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionPermissionsDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionPermissionsData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionViewedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionViewedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub idle: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionViewed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionViewedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionViewedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionArchivedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionArchivedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionArchived { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionArchivedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionArchivedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionUnarchivedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionUnarchivedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionUnarchived { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionUnarchivedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionUnarchivedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionDeletedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionDeletedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionDeleted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionDeletedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionDeletedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionForkedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +/// `Instruction.Hash` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct InstructionHash(pub String); + +impl InstructionHash { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for InstructionHash { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for InstructionHash { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for InstructionHash { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InstructionEntrySnapshotItem { + pub key: InstructionEntryKey, + pub value: serde_json::Value, + pub removed: bool, +} + +/// `InstructionEntry.Snapshot` +pub type InstructionEntrySnapshot = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionForkedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "parentID")] + pub parent_id: SessionID, + pub boundary: SessionForkBoundary, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option>, + #[serde( + rename = "instructionEntries", + default, + skip_serializing_if = "Option::is_none" + )] + pub instruction_entries: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionForked { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionForkedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionForkedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxDeliveredDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxDeliveredData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "inboxID")] + pub inbox_id: SessionMessageID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxDelivered { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionInboxDeliveredDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionInboxDeliveredData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxEnqueuedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxUserPayload1 { + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub files: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agents: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skills: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxItemUser { + pub r#type: String, + pub payload: SessionInboxUserPayload1, + pub delivery: SessionInboxDelivery, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxSyntheticPayload1 { + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxItemSynthetic { + pub r#type: String, + pub payload: SessionInboxSyntheticPayload1, + pub delivery: SessionInboxDelivery, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxItemCompaction { + pub r#type: String, + pub payload: SessionInboxCompactionPayload, + pub delivery: SessionInboxDelivery, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxMovePayload1 { + pub location: LocationRef, + #[serde(rename = "projectID")] + pub project_id: ProjectID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subpath: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxItemMove { + pub r#type: String, + pub payload: SessionInboxMovePayload1, + pub delivery: SessionInboxDelivery, +} + +/// `Session.Inbox.Item`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionInboxItem { + User(SessionInboxItemUser), + Synthetic(SessionInboxItemSynthetic), + Compaction(SessionInboxItemCompaction), + Move(SessionInboxItemMove), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionInboxItem { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("user") => crate::de::variant(value).map(Self::User), + Some("synthetic") => crate::de::variant(value).map(Self::Synthetic), + Some("compaction") => crate::de::variant(value).map(Self::Compaction), + Some("move") => crate::de::variant(value).map(Self::Move), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxEnqueuedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "inboxID")] + pub inbox_id: SessionMessageID, + pub item: SessionInboxItem, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxEnqueued { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionInboxEnqueuedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionInboxEnqueuedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxCancelledDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxCancelledData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "inboxID")] + pub inbox_id: SessionMessageID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxCancelled { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionInboxCancelledDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionInboxCancelledData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInboxDeliveryChangedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxDeliveryChangedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "inboxID")] + pub inbox_id: SessionMessageID, + pub delivery: SessionInboxDelivery, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInboxDeliveryChanged { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionInboxDeliveryChangedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionInboxDeliveryChangedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionStartedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionStartedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionStarted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionExecutionStartedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionExecutionStartedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionSucceededDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionSucceededData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionSucceeded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionExecutionSucceededDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionExecutionSucceededData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionFailedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionFailedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub error: SessionStructuredError, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionFailed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionExecutionFailedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionExecutionFailedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionExecutionInterruptedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionExecutionInterruptedDataReason { + User, + Shutdown, + Superseded, + Inactivity, + Unknown(String), +} + +impl SessionExecutionInterruptedDataReason { + pub fn as_str(&self) -> &str { + match self { + Self::User => "user", + Self::Shutdown => "shutdown", + Self::Superseded => "superseded", + Self::Inactivity => "inactivity", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionExecutionInterruptedDataReason { + fn from(value: &str) -> Self { + match value { + "user" => Self::User, + "shutdown" => Self::Shutdown, + "superseded" => Self::Superseded, + "inactivity" => Self::Inactivity, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionExecutionInterruptedDataReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionExecutionInterruptedDataReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionExecutionInterruptedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub reason: SessionExecutionInterruptedDataReason, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionExecutionInterrupted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionExecutionInterruptedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionExecutionInterruptedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInstructionsUpdatedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInstructionsUpdatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub delta: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionInstructionsUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionInstructionsUpdatedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionInstructionsUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionSyntheticDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionSyntheticData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionSynthetic { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionSyntheticDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionSyntheticData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionSkillActivatedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionSkillActivatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub id: SkillID, + pub name: SkillName, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionSkillActivated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionSkillActivatedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionSkillActivatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionShellStartedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ShellInfoStatus { + Running, + Exited, + Timeout, + Killed, + Unknown(String), +} + +impl ShellInfoStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Running => "running", + Self::Exited => "exited", + Self::Timeout => "timeout", + Self::Killed => "killed", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ShellInfoStatus { + fn from(value: &str) -> Self { + match value { + "running" => Self::Running, + "exited" => Self::Exited, + "timeout" => Self::Timeout, + "killed" => Self::Killed, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ShellInfoStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ShellInfoStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellInfoTime { + pub started: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellInfo { + pub id: ShellID, + pub status: ShellInfoStatus, + pub command: String, + pub cwd: String, + pub shell: String, + pub file: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pid: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exit: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub signal: Option, + pub metadata: BTreeMap, + pub time: ShellInfoTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionShellStartedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub shell: ShellInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionShellStarted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionShellStartedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionShellStartedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionShellEndedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionShellEndedDataOutput { + pub output: String, + pub cursor: i64, + pub size: i64, + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionShellEndedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub shell: ShellInfo, + pub output: SessionShellEndedDataOutput, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionShellEnded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionShellEndedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionShellEndedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepStartedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepStartedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub agent: AgentID, + pub model: ModelRef, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + pub started: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepStarted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionStepStartedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionStepStartedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepStreamedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepStreamedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepStreamed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionStepStreamedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionStepStreamedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepEndedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionStepEndedDataFinish { + Stop, + Length, + ToolCalls, + ContentFilter, + Error, + Unknown2, + Unknown(String), +} + +impl SessionStepEndedDataFinish { + pub fn as_str(&self) -> &str { + match self { + Self::Stop => "stop", + Self::Length => "length", + Self::ToolCalls => "tool-calls", + Self::ContentFilter => "content-filter", + Self::Error => "error", + Self::Unknown2 => "unknown", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionStepEndedDataFinish { + fn from(value: &str) -> Self { + match value { + "stop" => Self::Stop, + "length" => Self::Length, + "tool-calls" => Self::ToolCalls, + "content-filter" => Self::ContentFilter, + "error" => Self::Error, + "unknown" => Self::Unknown2, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionStepEndedDataFinish { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionStepEndedDataFinish { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Session.Message.Native_1` +pub type SessionMessageNative1 = BTreeMap; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionStepEndedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub finish: SessionStepEndedDataFinish, + #[serde(rename = "rawFinish", default, skip_serializing_if = "Option::is_none")] + pub raw_finish: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + pub cost: MoneyUSD, + pub tokens: TokenUsageInfo, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub files: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionStepEnded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionStepEndedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionStepEndedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepFailedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepFailedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub error: SessionStructuredError, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finish: Option, + #[serde(rename = "rawFinish", default, skip_serializing_if = "Option::is_none")] + pub raw_finish: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub files: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStepFailed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionStepFailedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionStepFailedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextStartedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextStartedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub ordinal: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextStarted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionTextStartedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionTextStartedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextEndedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextEndedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub ordinal: i64, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextEnded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionTextEndedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionTextEndedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningStartedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningStartedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub ordinal: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningStarted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionReasoningStartedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionReasoningStartedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningEndedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningEndedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub ordinal: i64, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningEnded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionReasoningEndedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionReasoningEndedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputStartedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputStartedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputStarted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionToolInputStartedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionToolInputStartedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputEndedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputEndedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub id: String, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputEnded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionToolInputEndedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionToolInputEndedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolCalledDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolCalledData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub id: String, + pub input: BTreeMap, + pub executed: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolCalled { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionToolCalledDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionToolCalledData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolSuccessDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolSuccessData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub id: String, + pub content: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub executed: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolSuccess { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionToolSuccessDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionToolSuccessData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolFailedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolFailedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub id: String, + pub error: SessionStructuredError, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub content: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub executed: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolFailed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionToolFailedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionToolFailedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRetryScheduledDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRetryScheduledData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub attempt: i64, + pub at: i64, + pub error: SessionStructuredError, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRetryScheduled { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionRetryScheduledDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionRetryScheduledData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCompactionStartedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionCompactionStartedDataReason { + Auto, + Manual, + Unknown(String), +} + +impl SessionCompactionStartedDataReason { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Manual => "manual", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionCompactionStartedDataReason { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "manual" => Self::Manual, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionCompactionStartedDataReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionCompactionStartedDataReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionCompactionStartedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub reason: SessionCompactionStartedDataReason, + #[serde(rename = "inputID", default, skip_serializing_if = "Option::is_none")] + pub input_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionCompactionStarted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionCompactionStartedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionCompactionStartedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCompactionEndedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionCompactionEndedDataReason { + Auto, + Manual, + Unknown(String), +} + +impl SessionCompactionEndedDataReason { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Manual => "manual", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionCompactionEndedDataReason { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "manual" => Self::Manual, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionCompactionEndedDataReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionCompactionEndedDataReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionCompactionEndedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub reason: SessionCompactionEndedDataReason, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionCompactionEnded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionCompactionEndedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionCompactionEndedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCompactionFailedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionCompactionFailedDataReason { + Auto, + Manual, + Unknown(String), +} + +impl SessionCompactionFailedDataReason { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Manual => "manual", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionCompactionFailedDataReason { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "manual" => Self::Manual, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionCompactionFailedDataReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionCompactionFailedDataReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionCompactionFailedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub reason: SessionCompactionFailedDataReason, + pub error: SessionStructuredError, + #[serde(rename = "inputID", default, skip_serializing_if = "Option::is_none")] + pub input_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionCompactionFailed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionCompactionFailedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionCompactionFailedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertStagedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertStagedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub revert: SessionRevert, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertStaged { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionRevertStagedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionRevertStagedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertClearedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertClearedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertCleared { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionRevertClearedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionRevertClearedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertCommittedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertCommittedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub to: SessionMessageID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionRevertCommitted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionRevertCommittedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionRevertCommittedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionUsageRecordedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SessionUsageRecordedDataSource { + Title, + Compaction, + Unknown(String), +} + +impl SessionUsageRecordedDataSource { + pub fn as_str(&self) -> &str { + match self { + Self::Title => "title", + Self::Compaction => "compaction", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for SessionUsageRecordedDataSource { + fn from(value: &str) -> Self { + match value { + "title" => Self::Title, + "compaction" => Self::Compaction, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for SessionUsageRecordedDataSource { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for SessionUsageRecordedDataSource { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionUsageRecordedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub source: SessionUsageRecordedDataSource, + pub cost: MoneyUSD, + pub tokens: TokenUsageInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionUsageRecorded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionUsageRecordedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionUsageRecordedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageContentUpdatedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantText1 { + pub r#type: String, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantReasoning1Time { + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantReasoning1 { + pub r#type: String, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub time: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageToolStateRunning1 { + pub status: String, + pub input: BTreeMap, + pub metadata: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageToolStateCompleted1 { + pub status: String, + pub input: BTreeMap, + pub content: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageToolStateError1 { + pub status: String, + pub input: BTreeMap, + pub error: SessionStructuredError, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub content: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionMessageAssistantTool1State { + Streaming(SessionMessageToolStateStreaming), + Running(SessionMessageToolStateRunning1), + Completed(SessionMessageToolStateCompleted1), + Error(SessionMessageToolStateError1), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionMessageAssistantTool1State { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("streaming") => crate::de::variant(value).map(Self::Streaming), + Some("running") => crate::de::variant(value).map(Self::Running), + Some("completed") => crate::de::variant(value).map(Self::Completed), + Some("error") => crate::de::variant(value).map(Self::Error), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageAssistantTool1Time { + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ran: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionMessageAssistantTool1 { + pub r#type: String, + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub executed: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + pub state: SessionMessageAssistantTool1State, + pub time: SessionMessageAssistantTool1Time, +} + +/// `Session.Message.AssistantContent.Encoded`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionMessageAssistantContentEncoded { + Text(SessionMessageAssistantText1), + Reasoning(SessionMessageAssistantReasoning1), + Tool(SessionMessageAssistantTool1), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionMessageAssistantContentEncoded { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("text") => crate::de::variant(value).map(Self::Text), + Some("reasoning") => crate::de::variant(value).map(Self::Reasoning), + Some("tool") => crate::de::variant(value).map(Self::Tool), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageContentUpdatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "messageID")] + pub message_id: SessionMessageID, + pub content: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessageContentUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: SessionMessageContentUpdatedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionMessageContentUpdatedData, +} + +/// `Session.Event.Durable`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionEventDurable { + SessionCreated(SessionCreated), + SessionAgentSelected(SessionAgentSelected), + SessionModelSelected(SessionModelSelected), + SessionMoved(SessionMoved), + SessionRenamed(SessionRenamed), + SessionMetadataUpdated(SessionMetadataUpdated), + SessionPermissions(SessionPermissions), + SessionViewed(SessionViewed), + SessionArchived(SessionArchived), + SessionUnarchived(SessionUnarchived), + SessionDeleted(SessionDeleted), + SessionForked(SessionForked), + SessionInboxDelivered(SessionInboxDelivered), + SessionInboxEnqueued(SessionInboxEnqueued), + SessionInboxCancelled(SessionInboxCancelled), + SessionInboxDeliveryChanged(SessionInboxDeliveryChanged), + SessionExecutionStarted(SessionExecutionStarted), + SessionExecutionSucceeded(SessionExecutionSucceeded), + SessionExecutionFailed(SessionExecutionFailed), + SessionExecutionInterrupted(SessionExecutionInterrupted), + SessionInstructionsUpdated(SessionInstructionsUpdated), + SessionSynthetic(SessionSynthetic), + SessionSkillActivated(SessionSkillActivated), + SessionShellStarted(SessionShellStarted), + SessionShellEnded(SessionShellEnded), + SessionStepStarted(SessionStepStarted), + SessionStepStreamed(SessionStepStreamed), + SessionStepEnded(SessionStepEnded), + SessionStepFailed(SessionStepFailed), + SessionTextStarted(SessionTextStarted), + SessionTextEnded(SessionTextEnded), + SessionReasoningStarted(SessionReasoningStarted), + SessionReasoningEnded(SessionReasoningEnded), + SessionToolInputStarted(SessionToolInputStarted), + SessionToolInputEnded(SessionToolInputEnded), + SessionToolCalled(SessionToolCalled), + SessionToolSuccess(SessionToolSuccess), + SessionToolFailed(SessionToolFailed), + SessionRetryScheduled(SessionRetryScheduled), + SessionCompactionStarted(SessionCompactionStarted), + SessionCompactionEnded(SessionCompactionEnded), + SessionCompactionFailed(SessionCompactionFailed), + SessionRevertStaged(SessionRevertStaged), + SessionRevertCleared(SessionRevertCleared), + SessionRevertCommitted(SessionRevertCommitted), + SessionUsageRecorded(SessionUsageRecorded), + SessionMessageContentUpdated(SessionMessageContentUpdated), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionEventDurable { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("session.created") => crate::de::variant(value).map(Self::SessionCreated), + Some("session.agent.selected") => { + crate::de::variant(value).map(Self::SessionAgentSelected) + } + Some("session.model.selected") => { + crate::de::variant(value).map(Self::SessionModelSelected) + } + Some("session.moved") => crate::de::variant(value).map(Self::SessionMoved), + Some("session.renamed") => crate::de::variant(value).map(Self::SessionRenamed), + Some("session.metadata.updated") => { + crate::de::variant(value).map(Self::SessionMetadataUpdated) + } + Some("session.permissions") => crate::de::variant(value).map(Self::SessionPermissions), + Some("session.viewed") => crate::de::variant(value).map(Self::SessionViewed), + Some("session.archived") => crate::de::variant(value).map(Self::SessionArchived), + Some("session.unarchived") => crate::de::variant(value).map(Self::SessionUnarchived), + Some("session.deleted") => crate::de::variant(value).map(Self::SessionDeleted), + Some("session.forked") => crate::de::variant(value).map(Self::SessionForked), + Some("session.inbox.delivered") => { + crate::de::variant(value).map(Self::SessionInboxDelivered) + } + Some("session.inbox.enqueued") => { + crate::de::variant(value).map(Self::SessionInboxEnqueued) + } + Some("session.inbox.cancelled") => { + crate::de::variant(value).map(Self::SessionInboxCancelled) + } + Some("session.inbox.delivery.changed") => { + crate::de::variant(value).map(Self::SessionInboxDeliveryChanged) + } + Some("session.execution.started") => { + crate::de::variant(value).map(Self::SessionExecutionStarted) + } + Some("session.execution.succeeded") => { + crate::de::variant(value).map(Self::SessionExecutionSucceeded) + } + Some("session.execution.failed") => { + crate::de::variant(value).map(Self::SessionExecutionFailed) + } + Some("session.execution.interrupted") => { + crate::de::variant(value).map(Self::SessionExecutionInterrupted) + } + Some("session.instructions.updated") => { + crate::de::variant(value).map(Self::SessionInstructionsUpdated) + } + Some("session.synthetic") => crate::de::variant(value).map(Self::SessionSynthetic), + Some("session.skill.activated") => { + crate::de::variant(value).map(Self::SessionSkillActivated) + } + Some("session.shell.started") => { + crate::de::variant(value).map(Self::SessionShellStarted) + } + Some("session.shell.ended") => crate::de::variant(value).map(Self::SessionShellEnded), + Some("session.step.started") => crate::de::variant(value).map(Self::SessionStepStarted), + Some("session.step.streamed") => { + crate::de::variant(value).map(Self::SessionStepStreamed) + } + Some("session.step.ended") => crate::de::variant(value).map(Self::SessionStepEnded), + Some("session.step.failed") => crate::de::variant(value).map(Self::SessionStepFailed), + Some("session.text.started") => crate::de::variant(value).map(Self::SessionTextStarted), + Some("session.text.ended") => crate::de::variant(value).map(Self::SessionTextEnded), + Some("session.reasoning.started") => { + crate::de::variant(value).map(Self::SessionReasoningStarted) + } + Some("session.reasoning.ended") => { + crate::de::variant(value).map(Self::SessionReasoningEnded) + } + Some("session.tool.input.started") => { + crate::de::variant(value).map(Self::SessionToolInputStarted) + } + Some("session.tool.input.ended") => { + crate::de::variant(value).map(Self::SessionToolInputEnded) + } + Some("session.tool.called") => crate::de::variant(value).map(Self::SessionToolCalled), + Some("session.tool.success") => crate::de::variant(value).map(Self::SessionToolSuccess), + Some("session.tool.failed") => crate::de::variant(value).map(Self::SessionToolFailed), + Some("session.retry.scheduled") => { + crate::de::variant(value).map(Self::SessionRetryScheduled) + } + Some("session.compaction.started") => { + crate::de::variant(value).map(Self::SessionCompactionStarted) + } + Some("session.compaction.ended") => { + crate::de::variant(value).map(Self::SessionCompactionEnded) + } + Some("session.compaction.failed") => { + crate::de::variant(value).map(Self::SessionCompactionFailed) + } + Some("session.revert.staged") => { + crate::de::variant(value).map(Self::SessionRevertStaged) + } + Some("session.revert.cleared") => { + crate::de::variant(value).map(Self::SessionRevertCleared) + } + Some("session.revert.committed") => { + crate::de::variant(value).map(Self::SessionRevertCommitted) + } + Some("session.usage.recorded") => { + crate::de::variant(value).map(Self::SessionUsageRecorded) + } + Some("session.message.content.updated") => { + crate::de::variant(value).map(Self::SessionMessageContentUpdated) + } + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct EventLogSynced { + pub r#type: String, + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seq: Option, +} + +/// `SessionLogItem` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SessionLogItem { + Durable(SessionEventDurable), + Synced(EventLogSynced), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +/// Output of [`Client::experimental_session_log`]. +pub type ExperimentalSessionLogOutput = SessionLogItem; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum MessageListInputOrder { + Asc, + Desc, + Unknown(String), +} + +impl MessageListInputOrder { + pub fn as_str(&self) -> &str { + match self { + Self::Asc => "asc", + Self::Desc => "desc", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for MessageListInputOrder { + fn from(value: &str) -> Self { + match value { + "asc" => Self::Asc, + "desc" => Self::Desc, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for MessageListInputOrder { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for MessageListInputOrder { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum MessageListInputType { + AgentSwitched, + ModelSwitched, + LocationSwitched, + User, + Synthetic, + System, + Skill, + Shell, + Assistant, + Compaction, + Idle, + Unknown(String), +} + +impl MessageListInputType { + pub fn as_str(&self) -> &str { + match self { + Self::AgentSwitched => "agent-switched", + Self::ModelSwitched => "model-switched", + Self::LocationSwitched => "location-switched", + Self::User => "user", + Self::Synthetic => "synthetic", + Self::System => "system", + Self::Skill => "skill", + Self::Shell => "shell", + Self::Assistant => "assistant", + Self::Compaction => "compaction", + Self::Idle => "idle", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for MessageListInputType { + fn from(value: &str) -> Self { + match value { + "agent-switched" => Self::AgentSwitched, + "model-switched" => Self::ModelSwitched, + "location-switched" => Self::LocationSwitched, + "user" => Self::User, + "synthetic" => Self::Synthetic, + "system" => Self::System, + "skill" => Self::Skill, + "shell" => Self::Shell, + "assistant" => Self::Assistant, + "compaction" => Self::Compaction, + "idle" => Self::Idle, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for MessageListInputType { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for MessageListInputType { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// Input of [`Client::message_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct MessageListInput { + pub session_id: SessionID, + pub limit: Option, + pub order: Option, + pub cursor: Option, + pub r#type: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessagesResponseCursor { + #[serde( + default, + deserialize_with = "crate::de::double_option", + skip_serializing_if = "Option::is_none" + )] + pub previous: Option>, + #[serde( + default, + deserialize_with = "crate::de::double_option", + skip_serializing_if = "Option::is_none" + )] + pub next: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionMessagesResponse { + pub data: Vec, + pub cursor: SessionMessagesResponseCursor, +} + +/// Output of [`Client::message_list`]. +pub type MessageListOutput = SessionMessagesResponse; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::model_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ModelListInput { + pub location: Option, + pub types: Option>, +} + +/// `Model.MaxTokensField` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelMaxTokensField { + MaxCompletionTokens, + MaxTokens, + Unknown(String), +} + +impl ModelMaxTokensField { + pub fn as_str(&self) -> &str { + match self { + Self::MaxCompletionTokens => "max_completion_tokens", + Self::MaxTokens => "max_tokens", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ModelMaxTokensField { + fn from(value: &str) -> Self { + match value { + "max_completion_tokens" => Self::MaxCompletionTokens, + "max_tokens" => Self::MaxTokens, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ModelMaxTokensField { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ModelMaxTokensField { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Model.CacheFormat` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelCacheFormat { + Anthropic, + Alibaba, + Unknown(String), +} + +impl ModelCacheFormat { + pub fn as_str(&self) -> &str { + match self { + Self::Anthropic => "anthropic", + Self::Alibaba => "alibaba", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ModelCacheFormat { + fn from(value: &str) -> Self { + match value { + "anthropic" => Self::Anthropic, + "alibaba" => Self::Alibaba, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ModelCacheFormat { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ModelCacheFormat { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Model.MediaInput` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelMediaInput { + Assets, + State, + Root, + Unknown(String), +} + +impl ModelMediaInput { + pub fn as_str(&self) -> &str { + match self { + Self::Assets => "assets", + Self::State => "state", + Self::Root => "root", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ModelMediaInput { + fn from(value: &str) -> Self { + match value { + "assets" => Self::Assets, + "state" => Self::State, + "root" => Self::Root, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ModelMediaInput { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ModelMediaInput { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelCompatibility { + #[serde( + rename = "reasoningField", + default, + skip_serializing_if = "Option::is_none" + )] + pub reasoning_field: Option, + #[serde( + rename = "requireReasoning", + default, + skip_serializing_if = "Option::is_none" + )] + pub require_reasoning: Option, + #[serde( + rename = "maxTokensField", + default, + skip_serializing_if = "Option::is_none" + )] + pub max_tokens_field: Option, + #[serde( + rename = "requireFinishReason", + default, + skip_serializing_if = "Option::is_none" + )] + pub require_finish_reason: Option, + #[serde( + rename = "requireAssistantAfterTool", + default, + skip_serializing_if = "Option::is_none" + )] + pub require_assistant_after_tool: Option, + #[serde( + rename = "supportsPromptCacheKey", + default, + skip_serializing_if = "Option::is_none" + )] + pub supports_prompt_cache_key: Option, + #[serde( + rename = "streamUsage", + default, + skip_serializing_if = "Option::is_none" + )] + pub stream_usage: Option, + #[serde( + rename = "cacheFormat", + default, + skip_serializing_if = "Option::is_none" + )] + pub cache_format: Option, + #[serde( + rename = "supportsThinkingBlockBinding", + default, + skip_serializing_if = "Option::is_none" + )] + pub supports_thinking_block_binding: Option, + #[serde( + rename = "supportsEffortUpdates", + default, + skip_serializing_if = "Option::is_none" + )] + pub supports_effort_updates: Option, + #[serde( + rename = "mediaInput", + default, + skip_serializing_if = "Option::is_none" + )] + pub media_input: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encoding: Option, + #[serde(flatten)] + pub extra: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelCapabilities { + pub tools: bool, + pub input: Vec, + pub output: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub temperature: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelVariantSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encoding: Option, + #[serde(flatten)] + pub extra: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelVariant { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub settings: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelInfoTime { + pub released: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelCostTier { + pub r#type: String, + pub size: i64, +} + +/// `Money.USDPerMillionTokens` +pub type MoneyUSDPerMillionTokens = f64; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelCostCache { + pub read: MoneyUSDPerMillionTokens, + pub write: MoneyUSDPerMillionTokens, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelCost { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tier: Option, + pub input: MoneyUSDPerMillionTokens, + pub output: MoneyUSDPerMillionTokens, + pub cache: ModelCostCache, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ModelInfoStatus { + Alpha, + Beta, + Deprecated, + Active, + Unknown(String), +} + +impl ModelInfoStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Alpha => "alpha", + Self::Beta => "beta", + Self::Deprecated => "deprecated", + Self::Active => "active", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ModelInfoStatus { + fn from(value: &str) -> Self { + match value { + "alpha" => Self::Alpha, + "beta" => Self::Beta, + "deprecated" => Self::Deprecated, + "active" => Self::Active, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ModelInfoStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ModelInfoStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelInfoLimit { + pub context: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input: Option, + pub output: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ModelInfo { + pub id: String, + #[serde(rename = "modelID")] + pub model_id: String, + #[serde(rename = "providerID")] + pub provider_id: ProviderID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub canonical: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub r#type: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub family: Option, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compatibility: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub package: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub settings: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option>, + pub capabilities: ModelCapabilities, + pub variants: Vec, + pub time: ModelInfoTime, + pub cost: Vec, + pub status: ModelInfoStatus, + pub enabled: bool, + pub limit: ModelInfoLimit, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelDefaultInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::model_default`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ModelDefaultInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelDefaultOutput { + pub location: LocationPublicRef, + #[serde(default)] + pub data: Option, +} + +/// Input of [`Client::experimental_generate_text`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalGenerateTextInput { + pub prompt: String, + pub model: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalGenerateTextOutput { + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateFile { + pub data: PromptBase64, + pub mime: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, +} + +/// `Generate.ImageAspect` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct GenerateImageAspect(pub String); + +impl GenerateImageAspect { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for GenerateImageAspect { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for GenerateImageAspect { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for GenerateImageAspect { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// Input of [`Client::experimental_generate_image`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalGenerateImageInput { + pub model: ModelRef, + pub prompt: String, + pub images: Option>, + pub n: Option, + pub aspect: Option, + pub resolution: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateImageOutput { + pub r#type: String, + pub data: PromptBase64, + pub mime: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateUsage { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option, +} + +/// `Generate.Native` +pub type GenerateNative = BTreeMap; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateImageResult { + pub images: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +/// Output of [`Client::experimental_generate_image`]. +pub type ExperimentalGenerateImageOutput = GenerateImageResult; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateDecisionTextPart { + pub r#type: String, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateDecisionJsonPart { + pub r#type: String, + pub value: serde_json::Value, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateDecisionFilePart { + pub r#type: String, + pub data: PromptBase64, + pub mime: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, +} + +/// `Generate.DecisionPart`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum GenerateDecisionPart { + Text(GenerateDecisionTextPart), + Json(GenerateDecisionJsonPart), + File(GenerateDecisionFilePart), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for GenerateDecisionPart { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("text") => crate::de::variant(value).map(Self::Text), + Some("json") => crate::de::variant(value).map(Self::Json), + Some("file") => crate::de::variant(value).map(Self::File), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GeneratePredicateQuestion { + pub r#type: String, + pub name: String, + pub instructions: String, +} + +/// `Generate.ChoiceValue` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GenerateChoiceValue { + String(String), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct GenerateChoiceQuestionChoicesItem { + pub value: GenerateChoiceValue, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateChoiceQuestion { + pub r#type: String, + pub name: String, + pub instructions: String, + pub choices: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateScoreQuestionLevelsItem { + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateScoreQuestion { + pub r#type: String, + pub name: String, + pub instructions: String, + pub levels: Vec, +} + +/// `Generate.DecisionQuestion`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum GenerateDecisionQuestion { + Predicate(GeneratePredicateQuestion), + Choice(GenerateChoiceQuestion), + Score(GenerateScoreQuestion), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for GenerateDecisionQuestion { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("predicate") => crate::de::variant(value).map(Self::Predicate), + Some("choice") => crate::de::variant(value).map(Self::Choice), + Some("score") => crate::de::variant(value).map(Self::Score), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Input of [`Client::experimental_generate_decisions`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalGenerateDecisionsInput { + pub model: ModelRef, + pub input: Vec, + pub questions: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GeneratePredicateAnswer { + pub r#type: String, + pub name: String, + pub probability: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct GenerateChoiceAnswerProbabilitiesItem { + pub value: GenerateChoiceValue, + pub probability: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct GenerateChoiceAnswer { + pub r#type: String, + pub name: String, + pub choice: GenerateChoiceValue, + pub probabilities: Vec, + pub confidence: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateScoreAnswerProbabilitiesItem { + pub value: i64, + pub label: String, + pub probability: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateScoreAnswer { + pub r#type: String, + pub name: String, + pub score: f64, + pub probabilities: Vec, + pub confidence: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateErrorAnswer { + pub r#type: String, + pub name: String, + pub reason: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +/// `Generate.DecisionAnswer`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum GenerateDecisionAnswer { + Predicate(GeneratePredicateAnswer), + Choice(GenerateChoiceAnswer), + Score(GenerateScoreAnswer), + Error(GenerateErrorAnswer), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for GenerateDecisionAnswer { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("predicate") => crate::de::variant(value).map(Self::Predicate), + Some("choice") => crate::de::variant(value).map(Self::Choice), + Some("score") => crate::de::variant(value).map(Self::Score), + Some("error") => crate::de::variant(value).map(Self::Error), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct GenerateDecisionResult { + pub answers: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, +} + +/// Output of [`Client::experimental_generate_decisions`]. +pub type ExperimentalGenerateDecisionsOutput = GenerateDecisionResult; + +/// `VoiceTransportType` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum VoiceTransportType { + Webrtc, + Websocket, + Unknown(String), +} + +impl VoiceTransportType { + pub fn as_str(&self) -> &str { + match self { + Self::Webrtc => "webrtc", + Self::Websocket => "websocket", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for VoiceTransportType { + fn from(value: &str) -> Self { + match value { + "webrtc" => Self::Webrtc, + "websocket" => Self::Websocket, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for VoiceTransportType { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for VoiceTransportType { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VoiceModel { + pub model: String, + pub provider: String, + pub transports: Vec, + pub available: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalVoiceModelsOutput { + pub models: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VoiceWebRTCTransportInput { + pub r#type: String, + pub sdp: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dcid: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VoiceWebSocketTransportInput { + pub r#type: String, +} + +/// `VoiceTransportInput`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum VoiceTransportInput { + Webrtc(VoiceWebRTCTransportInput), + Websocket(VoiceWebSocketTransportInput), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for VoiceTransportInput { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("webrtc") => crate::de::variant(value).map(Self::Webrtc), + Some("websocket") => crate::de::variant(value).map(Self::Websocket), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Input of [`Client::experimental_voice_session`]. +#[derive(Debug, Clone, PartialEq)] +pub struct ExperimentalVoiceSessionInput { + pub model: String, + pub session: Option>, + pub transport: VoiceTransportInput, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VoiceWebRTCTransport { + pub r#type: String, + pub sdp: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VoiceWebSocketTransport { + pub r#type: String, + pub url: String, + pub token: String, + #[serde(rename = "expiresAt")] + pub expires_at: f64, +} + +/// `VoiceTransport`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum VoiceTransport { + Webrtc(VoiceWebRTCTransport), + Websocket(VoiceWebSocketTransport), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for VoiceTransport { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("webrtc") => crate::de::variant(value).map(Self::Webrtc), + Some("websocket") => crate::de::variant(value).map(Self::Websocket), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ExperimentalVoiceSessionOutput { + pub transport: VoiceTransport, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::provider_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ProviderListInput { + pub location: Option, +} + +/// `Integration.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct IntegrationID(pub String); + +impl IntegrationID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for IntegrationID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for IntegrationID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for IntegrationID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ProviderInfoActivation { + Auto, + Enabled, + Disabled, + Unknown(String), +} + +impl ProviderInfoActivation { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Enabled => "enabled", + Self::Disabled => "disabled", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ProviderInfoActivation { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "enabled" => Self::Enabled, + "disabled" => Self::Disabled, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ProviderInfoActivation { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ProviderInfoActivation { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderCompatibility { + #[serde( + rename = "reasoningField", + default, + skip_serializing_if = "Option::is_none" + )] + pub reasoning_field: Option, + #[serde( + rename = "requireReasoning", + default, + skip_serializing_if = "Option::is_none" + )] + pub require_reasoning: Option, + #[serde( + rename = "maxTokensField", + default, + skip_serializing_if = "Option::is_none" + )] + pub max_tokens_field: Option, + #[serde( + rename = "requireFinishReason", + default, + skip_serializing_if = "Option::is_none" + )] + pub require_finish_reason: Option, + #[serde( + rename = "requireAssistantAfterTool", + default, + skip_serializing_if = "Option::is_none" + )] + pub require_assistant_after_tool: Option, + #[serde( + rename = "supportsPromptCacheKey", + default, + skip_serializing_if = "Option::is_none" + )] + pub supports_prompt_cache_key: Option, + #[serde( + rename = "streamUsage", + default, + skip_serializing_if = "Option::is_none" + )] + pub stream_usage: Option, + #[serde( + rename = "cacheFormat", + default, + skip_serializing_if = "Option::is_none" + )] + pub cache_format: Option, + #[serde( + rename = "mediaInput", + default, + skip_serializing_if = "Option::is_none" + )] + pub media_input: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ProviderInfo { + pub id: ProviderID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub canonical: Option, + #[serde( + rename = "integrationID", + default, + skip_serializing_if = "Option::is_none" + )] + pub integration_id: Option, + pub name: String, + pub activation: ProviderInfoActivation, + pub package: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compatibility: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub settings: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::provider_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ProviderGetInput { + pub provider_id: ProviderID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ProviderGetOutput { + pub location: LocationPublicRef, + pub data: ProviderInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationListInput { + pub location: Option, +} + +/// `Integration.MethodID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct IntegrationMethodID(pub String); + +impl IntegrationMethodID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for IntegrationMethodID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for IntegrationMethodID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for IntegrationMethodID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationOAuthMethod { + pub id: IntegrationMethodID, + pub r#type: String, + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub form: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationCommandMethod { + pub id: IntegrationMethodID, + pub r#type: String, + pub label: String, + pub command: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationKeyMethod { + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub form: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationExternalMethod { + pub id: IntegrationMethodID, + pub r#type: String, + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub form: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationEnvMethod { + pub r#type: String, + pub names: Vec, +} + +/// `Integration.Method`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum IntegrationMethod { + Oauth(IntegrationOAuthMethod), + Command(IntegrationCommandMethod), + Key(IntegrationKeyMethod), + External(IntegrationExternalMethod), + Env(IntegrationEnvMethod), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for IntegrationMethod { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("oauth") => crate::de::variant(value).map(Self::Oauth), + Some("command") => crate::de::variant(value).map(Self::Command), + Some("key") => crate::de::variant(value).map(Self::Key), + Some("external") => crate::de::variant(value).map(Self::External), + Some("env") => crate::de::variant(value).map(Self::Env), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// `Credential.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct CredentialID(pub String); + +impl CredentialID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for CredentialID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for CredentialID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for CredentialID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConnectionCredentialInfoMethod { + Key, + Oauth, + External, + Unknown(String), +} + +impl ConnectionCredentialInfoMethod { + pub fn as_str(&self) -> &str { + match self { + Self::Key => "key", + Self::Oauth => "oauth", + Self::External => "external", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConnectionCredentialInfoMethod { + fn from(value: &str) -> Self { + match value { + "key" => Self::Key, + "oauth" => Self::Oauth, + "external" => Self::External, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConnectionCredentialInfoMethod { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConnectionCredentialInfoMethod { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConnectionStatus { + pub status: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ConnectionCredentialInfo { + pub r#type: String, + pub id: CredentialID, + pub label: String, + pub method: ConnectionCredentialInfoMethod, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConnectionEnvInfo { + pub r#type: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +/// `Connection.Info`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ConnectionInfo { + Credential(ConnectionCredentialInfo), + Env(ConnectionEnvInfo), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ConnectionInfo { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("credential") => crate::de::variant(value).map(Self::Credential), + Some("env") => crate::de::variant(value).map(Self::Env), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationInfo { + pub id: IntegrationID, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub methods: Vec, + pub connections: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationGetInput { + pub integration_id: IntegrationID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationGetOutput { + pub location: LocationPublicRef, + pub data: IntegrationInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationConnectKeyInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_connect_key`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationConnectKeyInput { + pub integration_id: IntegrationID, + pub location: Option, + pub key: String, + pub answer: Option, + pub label: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationConnectExternalInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_connect_external`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationConnectExternalInput { + pub integration_id: IntegrationID, + pub location: Option, + pub method_id: IntegrationMethodID, + pub answer: Option, + pub label: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationOauthConnectInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_oauth_connect`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationOauthConnectInput { + pub integration_id: IntegrationID, + pub location: Option, + pub method_id: IntegrationMethodID, + pub answer: Option, + pub label: Option, +} + +/// `Integration.AttemptID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct IntegrationAttemptID(pub String); + +impl IntegrationAttemptID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for IntegrationAttemptID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for IntegrationAttemptID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for IntegrationAttemptID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum IntegrationAttemptMode { + Auto, + Code, + Unknown(String), +} + +impl IntegrationAttemptMode { + pub fn as_str(&self) -> &str { + match self { + Self::Auto => "auto", + Self::Code => "code", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for IntegrationAttemptMode { + fn from(value: &str) -> Self { + match value { + "auto" => Self::Auto, + "code" => Self::Code, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for IntegrationAttemptMode { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for IntegrationAttemptMode { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptTime { + pub created: f64, + pub expires: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationAttempt { + #[serde(rename = "attemptID")] + pub attempt_id: IntegrationAttemptID, + pub url: String, + pub instructions: String, + pub mode: IntegrationAttemptMode, + pub time: IntegrationAttemptTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationOauthConnectOutput { + pub location: LocationPublicRef, + pub data: IntegrationAttempt, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationOauthStatusInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_oauth_status`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationOauthStatusInput { + pub integration_id: IntegrationID, + pub attempt_id: IntegrationAttemptID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusPendingTime { + pub created: f64, + pub expires: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusPending { + pub status: String, + pub time: IntegrationAttemptStatusPendingTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusCompleteTime { + pub created: f64, + pub expires: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusComplete { + pub status: String, + pub time: IntegrationAttemptStatusCompleteTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusFailedTime { + pub created: f64, + pub expires: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusFailed { + pub status: String, + pub message: String, + pub time: IntegrationAttemptStatusFailedTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusExpiredTime { + pub created: f64, + pub expires: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptStatusExpired { + pub status: String, + pub time: IntegrationAttemptStatusExpiredTime, +} + +/// `Integration.AttemptStatus`, tagged by `status`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum IntegrationAttemptStatus { + Pending(IntegrationAttemptStatusPending), + Complete(IntegrationAttemptStatusComplete), + Failed(IntegrationAttemptStatusFailed), + Expired(IntegrationAttemptStatusExpired), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for IntegrationAttemptStatus { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("pending") => crate::de::variant(value).map(Self::Pending), + Some("complete") => crate::de::variant(value).map(Self::Complete), + Some("failed") => crate::de::variant(value).map(Self::Failed), + Some("expired") => crate::de::variant(value).map(Self::Expired), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationOauthStatusOutput { + pub location: LocationPublicRef, + pub data: IntegrationAttemptStatus, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationOauthCompleteInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_oauth_complete`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationOauthCompleteInput { + pub integration_id: IntegrationID, + pub attempt_id: IntegrationAttemptID, + pub location: Option, + pub code: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationOauthCancelInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_oauth_cancel`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationOauthCancelInput { + pub integration_id: IntegrationID, + pub attempt_id: IntegrationAttemptID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationCommandConnectInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_command_connect`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationCommandConnectInput { + pub integration_id: IntegrationID, + pub location: Option, + pub method_id: IntegrationMethodID, + pub label: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationCommandAttemptTime { + pub created: f64, + pub expires: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationCommandAttempt { + #[serde(rename = "attemptID")] + pub attempt_id: IntegrationAttemptID, + pub time: IntegrationCommandAttemptTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationCommandConnectOutput { + pub location: LocationPublicRef, + pub data: IntegrationCommandAttempt, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationCommandStatusInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_command_status`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationCommandStatusInput { + pub integration_id: IntegrationID, + pub attempt_id: IntegrationAttemptID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusPendingTimeCreated { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusPendingTimeExpires { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusPendingTime { + pub created: IntegrationCommandAttemptStatusPendingTimeCreated, + pub expires: IntegrationCommandAttemptStatusPendingTimeExpires, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusPending { + pub status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, + pub time: IntegrationCommandAttemptStatusPendingTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusCompleteTimeCreated { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusCompleteTimeExpires { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusCompleteTime { + pub created: IntegrationCommandAttemptStatusCompleteTimeCreated, + pub expires: IntegrationCommandAttemptStatusCompleteTimeExpires, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusComplete { + pub status: String, + pub time: IntegrationCommandAttemptStatusCompleteTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusFailedTimeCreated { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusFailedTimeExpires { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusFailedTime { + pub created: IntegrationCommandAttemptStatusFailedTimeCreated, + pub expires: IntegrationCommandAttemptStatusFailedTimeExpires, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusFailed { + pub status: String, + pub message: String, + pub time: IntegrationCommandAttemptStatusFailedTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusExpiredTimeCreated { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatusExpiredTimeExpires { + Number(f64), + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusExpiredTime { + pub created: IntegrationCommandAttemptStatusExpiredTimeCreated, + pub expires: IntegrationCommandAttemptStatusExpiredTimeExpires, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandAttemptStatusExpired { + pub status: String, + pub time: IntegrationCommandAttemptStatusExpiredTime, +} + +/// `Integration.CommandAttemptStatus`, tagged by `status`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum IntegrationCommandAttemptStatus { + Pending(IntegrationCommandAttemptStatusPending), + Complete(IntegrationCommandAttemptStatusComplete), + Failed(IntegrationCommandAttemptStatusFailed), + Expired(IntegrationCommandAttemptStatusExpired), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for IntegrationCommandAttemptStatus { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("pending") => crate::de::variant(value).map(Self::Pending), + Some("complete") => crate::de::variant(value).map(Self::Complete), + Some("failed") => crate::de::variant(value).map(Self::Failed), + Some("expired") => crate::de::variant(value).map(Self::Expired), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntegrationCommandStatusOutput { + pub location: LocationPublicRef, + pub data: IntegrationCommandAttemptStatus, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationCommandCancelInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::integration_command_cancel`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct IntegrationCommandCancelInput { + pub integration_id: IntegrationID, + pub attempt_id: IntegrationAttemptID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalIntegrationWellknownAddInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_integration_wellknown_add`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalIntegrationWellknownAddInput { + pub location: Option, + pub url: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::mcp_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct McpListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpStatusConnected { + pub status: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpStatusPending { + pub status: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpStatusDisabled { + pub status: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpStatusFailed { + pub status: String, + pub error: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpStatusNeedsAuth { + pub status: String, + pub error: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum McpServerStatus { + Connected(McpStatusConnected), + Pending(McpStatusPending), + Disabled(McpStatusDisabled), + Failed(McpStatusFailed), + NeedsAuth(McpStatusNeedsAuth), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for McpServerStatus { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("connected") => crate::de::variant(value).map(Self::Connected), + Some("pending") => crate::de::variant(value).map(Self::Pending), + Some("disabled") => crate::de::variant(value).map(Self::Disabled), + Some("failed") => crate::de::variant(value).map(Self::Failed), + Some("needs_auth") => crate::de::variant(value).map(Self::NeedsAuth), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct McpServer { + pub name: String, + pub status: McpServerStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde( + rename = "integrationID", + default, + skip_serializing_if = "Option::is_none" + )] + pub integration_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpResourceCatalogInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::mcp_resource_catalog`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct McpResourceCatalogInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpResource { + pub server: String, + pub name: String, + pub uri: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + pub mime_type: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpResourceTemplate { + pub server: String, + pub name: String, + #[serde(rename = "uriTemplate")] + pub uri_template: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")] + pub mime_type: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpResourceCatalog { + pub resources: Vec, + pub templates: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpResourceCatalogOutput { + pub location: LocationPublicRef, + pub data: McpResourceCatalog, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpAddInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpAddInputConfigLocalTimeout { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub startup: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub catalog: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub execution: Option, +} + +/// `Mcp.Protocol` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum McpProtocol { + Legacy, + Auto, + V20260728, + Unknown(String), +} + +impl McpProtocol { + pub fn as_str(&self) -> &str { + match self { + Self::Legacy => "legacy", + Self::Auto => "auto", + Self::V20260728 => "2026-07-28", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for McpProtocol { + fn from(value: &str) -> Self { + match value { + "legacy" => Self::Legacy, + "auto" => Self::Auto, + "2026-07-28" => Self::V20260728, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for McpProtocol { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for McpProtocol { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpAddInputConfigLocal { + pub r#type: String, + pub command: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub environment: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub codemode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub protocol: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpAddInputConfigRemoteOauthObject { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scope: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub callback_port: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub redirect_uri: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth_server_metadata_url: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ExperimentalMcpAddInputConfigRemoteOauth { + Object(ExperimentalMcpAddInputConfigRemoteOauthObject), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpAddInputConfigRemoteTimeout { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub startup: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub catalog: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub execution: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpAddInputConfigRemote { + pub r#type: String, + pub url: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub oauth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub codemode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub protocol: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ExperimentalMcpAddInputConfig { + Local(ExperimentalMcpAddInputConfigLocal), + Remote(ExperimentalMcpAddInputConfigRemote), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ExperimentalMcpAddInputConfig { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("local") => crate::de::variant(value).map(Self::Local), + Some("remote") => crate::de::variant(value).map(Self::Remote), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Input of [`Client::experimental_mcp_add`]. +#[derive(Debug, Clone, PartialEq)] +pub struct ExperimentalMcpAddInput { + pub server: String, + pub location: Option, + pub config: ExperimentalMcpAddInputConfig, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpRemoveInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_mcp_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalMcpRemoveInput { + pub server: String, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpConnectInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_mcp_connect`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalMcpConnectInput { + pub server: String, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpDisconnectInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_mcp_disconnect`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalMcpDisconnectInput { + pub server: String, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpClientTokenInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_mcp_client_token`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalMcpClientTokenInput { + pub location: Option, + pub name: String, + pub x_opencode_ticket: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyTicketConnectToken { + pub ticket: String, + pub expires_in: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMcpClientTokenOutput { + pub location: LocationPublicRef, + pub data: PtyTicketConnectToken, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CredentialOAuth { + pub r#type: String, + #[serde(rename = "methodID")] + pub method_id: IntegrationMethodID, + pub refresh: String, + pub access: String, + pub expires: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CredentialKey { + pub r#type: String, + pub key: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CredentialExternal { + pub r#type: String, + #[serde(rename = "methodID")] + pub method_id: IntegrationMethodID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, +} + +/// `Credential.Value`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum CredentialValue { + Oauth(CredentialOAuth), + Key(CredentialKey), + External(CredentialExternal), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for CredentialValue { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("oauth") => crate::de::variant(value).map(Self::Oauth), + Some("key") => crate::de::variant(value).map(Self::Key), + Some("external") => crate::de::variant(value).map(Self::External), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CredentialEntry { + pub id: CredentialID, + #[serde(rename = "integrationID")] + pub integration_id: IntegrationID, + pub label: String, + pub active: bool, + pub value: CredentialValue, +} + +/// Output of [`Client::credential_list`]. +pub type CredentialListOutput = Vec; + +/// Input of [`Client::credential_create`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CredentialCreateInput { + pub id: Option, + pub integration_id: IntegrationID, + pub label: Option, + pub value: CredentialValue, + pub activate: Option, +} + +/// Output of [`Client::credential_create`]. +pub type CredentialCreateOutput = CredentialEntry; + +/// Input of [`Client::credential_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct CredentialUpdateInput { + pub credential_id: CredentialID, + pub label: String, +} + +/// Input of [`Client::credential_activate`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct CredentialActivateInput { + pub credential_id: CredentialID, +} + +/// Input of [`Client::credential_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct CredentialRemoveInput { + pub credential_id: CredentialID, +} + +/// Input of [`Client::project_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ProjectListInput { + pub archived: Option, +} + +/// `Project.Vcs` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ProjectVcs(pub String); + +impl ProjectVcs { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ProjectVcs { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ProjectVcs { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ProjectVcs { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProjectIcon { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub r#override: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProjectCommands { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProjectTime { + pub created: i64, + pub updated: i64, + pub active: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub archived: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct Project { + pub id: ProjectID, + pub canonical: AbsolutePath, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vcs: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub commands: Option, + pub time: ProjectTime, + pub sandboxes: Vec, +} + +/// Output of [`Client::project_list`]. +pub type ProjectListOutput = Vec; + +/// Input of [`Client::project_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ProjectUpdateInput { + pub project_id: ProjectID, + pub canonical: Option, + pub name: Option, + pub icon: Option, + pub commands: Option, +} + +/// Output of [`Client::project_update`]. +pub type ProjectUpdateOutput = Project; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::form_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct FormListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionRequestListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::permission_request_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PermissionRequestListInput { + pub location: Option, +} + +/// `Permission.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct PermissionID(pub String); + +impl PermissionID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for PermissionID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for PermissionID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for PermissionID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionSource { + pub r#type: String, + #[serde(rename = "messageID")] + pub message_id: String, + pub id: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionRequest { + pub id: PermissionID, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub action: String, + pub resources: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub save: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionRequestListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +/// Input of [`Client::permission_saved_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PermissionSavedListInput { + pub project_id: Option, +} + +/// `PermissionSaved.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct PermissionSavedID(pub String); + +impl PermissionSavedID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for PermissionSavedID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for PermissionSavedID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for PermissionSavedID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionSavedInfoTime { + pub created: f64, + pub updated: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionSavedInfo { + pub id: PermissionSavedID, + #[serde(rename = "projectID")] + pub project_id: ProjectID, + pub action: String, + pub resource: String, + pub time: PermissionSavedInfoTime, +} + +/// Output of [`Client::permission_saved_list`]. +pub type PermissionSavedListOutput = Vec; + +/// Input of [`Client::permission_saved_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PermissionSavedUpdateInput { + pub id: PermissionSavedID, + pub action: Option, + pub resource: Option, +} + +/// Output of [`Client::permission_saved_update`]. +pub type PermissionSavedUpdateOutput = PermissionSavedInfo; + +/// Input of [`Client::permission_saved_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PermissionSavedRemoveInput { + pub id: PermissionSavedID, +} + +/// Input of [`Client::permission_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PermissionCreateInput { + pub session_id: SessionID, + pub id: Option>, + pub action: String, + pub resources: Vec, + pub save: Option>, + pub metadata: Option>, + pub source: Option, + pub agent: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PermissionCreateOutput { + pub id: PermissionID, + pub effect: PermissionEffect, +} + +/// Input of [`Client::permission_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PermissionListInput { + pub session_id: SessionID, +} + +/// Output of [`Client::permission_list`]. +pub type PermissionListOutput = Vec; + +/// Input of [`Client::permission_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PermissionGetInput { + pub session_id: SessionID, + pub request_id: PermissionID, +} + +/// Output of [`Client::permission_get`]. +pub type PermissionGetOutput = PermissionRequest; + +/// `Permission.Reply` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PermissionReply { + Once, + Always, + Reject, + Unknown(String), +} + +impl PermissionReply { + pub fn as_str(&self) -> &str { + match self { + Self::Once => "once", + Self::Always => "always", + Self::Reject => "reject", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for PermissionReply { + fn from(value: &str) -> Self { + match value { + "once" => Self::Once, + "always" => Self::Always, + "reject" => Self::Reject, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for PermissionReply { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for PermissionReply { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// Input of [`Client::permission_reply`]. +#[derive(Debug, Clone, PartialEq)] +pub struct PermissionReplyInput { + pub session_id: SessionID, + pub request_id: PermissionID, + pub decision: PermissionReply, + pub message: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FileReadInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::file_read`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct FileReadInput { + pub location: Option, + pub path: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FileListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::file_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct FileListInput { + pub location: Option, + pub path: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum FileSystemEntryType { + File, + Directory, + Unknown(String), +} + +impl FileSystemEntryType { + pub fn as_str(&self) -> &str { + match self { + Self::File => "file", + Self::Directory => "directory", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for FileSystemEntryType { + fn from(value: &str) -> Self { + match value { + "file" => Self::File, + "directory" => Self::Directory, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for FileSystemEntryType { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for FileSystemEntryType { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FileSystemEntry { + pub path: RelativePath, + pub r#type: FileSystemEntryType, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FileListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FileFindInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum FileFindInputType { + File, + Directory, + Unknown(String), +} + +impl FileFindInputType { + pub fn as_str(&self) -> &str { + match self { + Self::File => "file", + Self::Directory => "directory", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for FileFindInputType { + fn from(value: &str) -> Self { + match value { + "file" => Self::File, + "directory" => Self::Directory, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for FileFindInputType { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for FileFindInputType { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// Input of [`Client::file_find`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct FileFindInput { + pub location: Option, + pub query: String, + pub r#type: Option, + pub limit: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FileFindOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalFileWriteInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_file_write`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalFileWriteInput { + pub location: Option, + pub path: String, + pub payload: bytes::Bytes, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FileSystemWrite { + pub path: AbsolutePath, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalFileWriteOutput { + pub location: LocationPublicRef, + pub data: FileSystemWrite, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalFileWatchInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_file_watch`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalFileWatchInput { + pub location: Option, + pub path: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalFileUnwatchInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_file_unwatch`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalFileUnwatchInput { + pub location: Option, + pub path: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CommandListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::command_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct CommandListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CommandInfo { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CommandListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SkillListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::skill_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SkillListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SkillInfo { + pub id: SkillID, + pub name: SkillName, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub autoinvoke: Option, + pub path: AbsolutePath, + pub content: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SkillListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct RpcCallInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::rpc_call`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct RpcCallInput { + pub rpc_id: String, + pub method: String, + pub location: Option, + pub input: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct RpcOutput { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option, +} + +/// Output of [`Client::rpc_call`]. +pub type RpcCallOutput = RpcOutput; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum EventSubscribeInputTypesItem { + String(String), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +/// Input of [`Client::event_subscribe`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct EventSubscribeInput { + pub types: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationShutdownData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationShutdown { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: LocationShutdownData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelsDevRefreshedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelsDevRefreshed { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ModelsDevRefreshedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CredentialUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CredentialUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: CredentialUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CredentialSwitchedData { + #[serde(rename = "integrationID")] + pub integration_id: IntegrationID, + #[serde(rename = "credentialID", default)] + pub credential_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CredentialSwitched { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: CredentialSwitchedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: IntegrationUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ProviderUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ModelUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct AgentUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct AgentUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: AgentUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionUsageUpdatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub cost: MoneyUSD, + pub tokens: TokenUsageInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionUsageUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionUsageUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextDeltaData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub ordinal: i64, + pub delta: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionTextDelta { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionTextDeltaData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningDeltaData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub ordinal: i64, + pub delta: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionReasoningDelta { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionReasoningDeltaData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputDeltaData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub id: String, + pub delta: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolInputDelta { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionToolInputDeltaData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolProgressData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "assistantMessageID")] + pub assistant_message_id: SessionMessageID, + pub id: String, + pub metadata: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionToolProgress { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionToolProgressData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCompactionDeltaData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionCompactionDelta { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionCompactionDeltaData, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum FilesystemChangedDataEvent { + Add, + Change, + Unlink, + Unknown(String), +} + +impl FilesystemChangedDataEvent { + pub fn as_str(&self) -> &str { + match self { + Self::Add => "add", + Self::Change => "change", + Self::Unlink => "unlink", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for FilesystemChangedDataEvent { + fn from(value: &str) -> Self { + match value { + "add" => Self::Add, + "change" => Self::Change, + "unlink" => Self::Unlink, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for FilesystemChangedDataEvent { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for FilesystemChangedDataEvent { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FilesystemChangedData { + pub file: String, + pub event: FilesystemChangedDataEvent, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FilesystemChanged { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: FilesystemChangedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ReferenceUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ReferenceUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ReferenceUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionAskedData { + pub id: PermissionID, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub action: String, + pub resources: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub save: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionAsked { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PermissionAskedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PermissionRepliedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "requestID")] + pub request_id: PermissionID, + pub reply: PermissionReply, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PermissionReplied { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PermissionRepliedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PluginUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProjectUpdatedData { + pub id: ProjectID, + pub canonical: AbsolutePath, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vcs: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub commands: Option, + pub time: ProjectTime, + pub sandboxes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProjectUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ProjectUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeUpdatedData { + #[serde(rename = "projectID")] + pub project_id: ProjectID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: WorktreeUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeResolvedDurable { + #[serde(rename = "aggregateID")] + pub aggregate_id: String, + pub seq: EventSeq, + pub version: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeResolvedData { + #[serde(rename = "projectID")] + pub project_id: ProjectID, + pub directory: AbsolutePath, + pub previous: ProjectID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub adopted: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeResolved { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub durable: WorktreeResolvedDurable, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: WorktreeResolvedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CommandUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CommandUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: CommandUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ConfigUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SkillUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SkillUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SkillUpdatedData, +} + +/// `Pty.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct PtyID(pub String); + +impl PtyID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for PtyID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for PtyID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for PtyID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PtyStatus { + Running, + Exited, + Unknown(String), +} + +impl PtyStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Running => "running", + Self::Exited => "exited", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for PtyStatus { + fn from(value: &str) -> Self { + match value { + "running" => Self::Running, + "exited" => Self::Exited, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for PtyStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for PtyStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Pty { + pub id: PtyID, + pub title: String, + pub command: String, + pub args: Vec, + pub cwd: String, + pub status: PtyStatus, + pub pid: i64, + #[serde(rename = "exitCode", default, skip_serializing_if = "Option::is_none")] + pub exit_code: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PtyCreatedData { + pub info: Pty, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PtyCreated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PtyCreatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PtyUpdatedData { + pub info: Pty, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PtyUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PtyUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyExitedData { + pub id: PtyID, + #[serde(rename = "exitCode")] + pub exit_code: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyExited { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PtyExitedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyDeletedData { + pub id: PtyID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyDeleted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PtyDeletedData, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PersistentPtyInfoStatus { + Running, + Exited, + Unknown(String), +} + +impl PersistentPtyInfoStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Running => "running", + Self::Exited => "exited", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for PersistentPtyInfoStatus { + fn from(value: &str) -> Self { + match value { + "running" => Self::Running, + "exited" => Self::Exited, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for PersistentPtyInfoStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for PersistentPtyInfoStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyInfoSize { + pub cols: i64, + pub rows: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyInfoOutput { + pub head: i64, + pub tail: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PersistentPtyInfo { + pub id: PtyID, + pub title: String, + pub command: String, + pub args: Vec, + pub cwd: String, + pub status: PersistentPtyInfoStatus, + pub pid: i64, + #[serde(rename = "exitCode", default, skip_serializing_if = "Option::is_none")] + pub exit_code: Option, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "userTitle", default)] + pub user_title: Option, + #[serde(rename = "foregroundProcess", default)] + pub foreground_process: Option, + pub size: PersistentPtyInfoSize, + pub output: PersistentPtyInfoOutput, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PersistentPtyAddedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub terminal: PersistentPtyInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PersistentPtyAdded { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PersistentPtyAddedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyRemovedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + #[serde(rename = "ptyID")] + pub pty_id: PtyID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyRemoved { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PersistentPtyRemovedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PersistentPtyUpdatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub terminal: PersistentPtyInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PersistentPtyUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: PersistentPtyUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellCreatedData { + pub info: ShellInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellCreated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ShellCreatedData, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ShellExitedDataStatus { + Running, + Exited, + Timeout, + Killed, + Unknown(String), +} + +impl ShellExitedDataStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Running => "running", + Self::Exited => "exited", + Self::Timeout => "timeout", + Self::Killed => "killed", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ShellExitedDataStatus { + fn from(value: &str) -> Self { + match value { + "running" => Self::Running, + "exited" => Self::Exited, + "timeout" => Self::Timeout, + "killed" => Self::Killed, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ShellExitedDataStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ShellExitedDataStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellExitedData { + pub id: ShellID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exit: Option, + pub status: ShellExitedDataStatus, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellExited { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ShellExitedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellDeletedData { + pub id: ShellID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellDeleted { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ShellDeletedData, +} + +/// `Form.Metadata_1` +pub type FormMetadata1 = BTreeMap; + +/// `Form.Fields_1` +pub type FormFields1 = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormInfo1 { + pub id: FormID, + #[serde(rename = "sessionID")] + pub session_id: String, + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option, + pub fields: FormFields1, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormCreatedData { + pub form: FormInfo1, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormCreated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: FormCreatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormRepliedData { + pub id: FormID, + #[serde(rename = "sessionID")] + pub session_id: String, + pub answer: FormAnswer1, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormReplied { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: FormRepliedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormCancelledData { + pub id: FormID, + #[serde(rename = "sessionID")] + pub session_id: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormCancelled { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: FormCancelledData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebsearchUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebsearchUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: WebsearchUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ArtifactUpdatedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ArtifactUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: ArtifactUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatusIdle { + pub r#type: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatusRetryAction { + pub reason: String, + pub provider: String, + pub title: String, + pub message: String, + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatusRetry { + pub r#type: String, + pub attempt: i64, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub action: Option, + pub next: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionStatusBusy { + pub r#type: String, +} + +/// `SessionStatus`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum SessionStatus { + Idle(SessionStatusIdle), + Retry(SessionStatusRetry), + Busy(SessionStatusBusy), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for SessionStatus { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("idle") => crate::de::variant(value).map(Self::Idle), + Some("retry") => crate::de::variant(value).map(Self::Retry), + Some("busy") => crate::de::variant(value).map(Self::Busy), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionStatusUpdatedData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub status: SessionStatus, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionStatusUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionStatusUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionIdleData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionIdle { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: SessionIdleData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TuiPromptAppendData { + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TuiPromptAppend { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: TuiPromptAppendData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TuiCommandExecuteData { + pub command: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TuiCommandExecute { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: TuiCommandExecuteData, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum TuiToastShowDataVariant { + Info, + Success, + Warning, + Error, + Unknown(String), +} + +impl TuiToastShowDataVariant { + pub fn as_str(&self) -> &str { + match self { + Self::Info => "info", + Self::Success => "success", + Self::Warning => "warning", + Self::Error => "error", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for TuiToastShowDataVariant { + fn from(value: &str) -> Self { + match value { + "info" => Self::Info, + "success" => Self::Success, + "warning" => Self::Warning, + "error" => Self::Error, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for TuiToastShowDataVariant { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for TuiToastShowDataVariant { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TuiToastShowData { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + pub message: String, + pub variant: TuiToastShowDataVariant, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TuiToastShow { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: TuiToastShowData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TuiSessionSelectData { + #[serde(rename = "sessionID")] + pub session_id: SessionID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct TuiSessionSelect { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: TuiSessionSelectData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InstallationUpdatedData { + pub version: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InstallationUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: InstallationUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InstallationUpdateAvailableData { + pub version: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InstallationUpdateAvailable { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: InstallationUpdateAvailableData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsBranchUpdatedData { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub branch: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsBranchUpdated { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: VcsBranchUpdatedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpStatusChangedData { + pub server: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpStatusChanged { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: McpStatusChangedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpResourcesChangedData { + pub server: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpResourcesChanged { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub data: McpResourcesChangedData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct V2EventRpc { + pub id: EventID, + pub created: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + pub r#type: String, + pub location: LocationPublicRef, + pub data: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct V2EventServerConnectedData {} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct V2EventServerConnected { + pub id: EventID, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, + pub r#type: String, + pub data: V2EventServerConnectedData, +} + +/// `V2Event`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum V2Event { + LocationShutdown(LocationShutdown), + ModelsDevRefreshed(ModelsDevRefreshed), + CredentialUpdated(CredentialUpdated), + CredentialSwitched(CredentialSwitched), + IntegrationUpdated(IntegrationUpdated), + ProviderUpdated(ProviderUpdated), + ModelUpdated(ModelUpdated), + AgentUpdated(AgentUpdated), + SessionCreated(SessionCreated), + SessionAgentSelected(SessionAgentSelected), + SessionModelSelected(SessionModelSelected), + SessionMoved(SessionMoved), + SessionRenamed(SessionRenamed), + SessionMetadataUpdated(SessionMetadataUpdated), + SessionPermissions(SessionPermissions), + SessionViewed(SessionViewed), + SessionArchived(SessionArchived), + SessionUnarchived(SessionUnarchived), + SessionUsageUpdated(SessionUsageUpdated), + SessionDeleted(SessionDeleted), + SessionForked(SessionForked), + SessionInboxDelivered(SessionInboxDelivered), + SessionInboxEnqueued(SessionInboxEnqueued), + SessionInboxCancelled(SessionInboxCancelled), + SessionInboxDeliveryChanged(SessionInboxDeliveryChanged), + SessionExecutionStarted(SessionExecutionStarted), + SessionExecutionSucceeded(SessionExecutionSucceeded), + SessionExecutionFailed(SessionExecutionFailed), + SessionExecutionInterrupted(SessionExecutionInterrupted), + SessionInstructionsUpdated(SessionInstructionsUpdated), + SessionSynthetic(SessionSynthetic), + SessionSkillActivated(SessionSkillActivated), + SessionShellStarted(SessionShellStarted), + SessionShellEnded(SessionShellEnded), + SessionStepStarted(SessionStepStarted), + SessionStepStreamed(SessionStepStreamed), + SessionStepEnded(SessionStepEnded), + SessionStepFailed(SessionStepFailed), + SessionTextStarted(SessionTextStarted), + SessionTextDelta(SessionTextDelta), + SessionTextEnded(SessionTextEnded), + SessionReasoningStarted(SessionReasoningStarted), + SessionReasoningDelta(SessionReasoningDelta), + SessionReasoningEnded(SessionReasoningEnded), + SessionToolInputStarted(SessionToolInputStarted), + SessionToolInputDelta(SessionToolInputDelta), + SessionToolInputEnded(SessionToolInputEnded), + SessionToolCalled(SessionToolCalled), + SessionToolProgress(SessionToolProgress), + SessionToolSuccess(SessionToolSuccess), + SessionToolFailed(SessionToolFailed), + SessionRetryScheduled(SessionRetryScheduled), + SessionCompactionStarted(SessionCompactionStarted), + SessionCompactionDelta(SessionCompactionDelta), + SessionCompactionEnded(SessionCompactionEnded), + SessionCompactionFailed(SessionCompactionFailed), + SessionRevertStaged(SessionRevertStaged), + SessionRevertCleared(SessionRevertCleared), + SessionRevertCommitted(SessionRevertCommitted), + FilesystemChanged(FilesystemChanged), + ReferenceUpdated(ReferenceUpdated), + PermissionAsked(PermissionAsked), + PermissionReplied(PermissionReplied), + PluginUpdated(PluginUpdated), + ProjectUpdated(ProjectUpdated), + WorktreeUpdated(WorktreeUpdated), + WorktreeResolved(WorktreeResolved), + CommandUpdated(CommandUpdated), + ConfigUpdated(ConfigUpdated), + SkillUpdated(SkillUpdated), + PtyCreated(PtyCreated), + PtyUpdated(PtyUpdated), + PtyExited(PtyExited), + PtyDeleted(PtyDeleted), + PersistentPtyAdded(PersistentPtyAdded), + PersistentPtyRemoved(PersistentPtyRemoved), + PersistentPtyUpdated(PersistentPtyUpdated), + ShellCreated(ShellCreated), + ShellExited(ShellExited), + ShellDeleted(ShellDeleted), + FormCreated(FormCreated), + FormReplied(FormReplied), + FormCancelled(FormCancelled), + WebsearchUpdated(WebsearchUpdated), + ArtifactUpdated(ArtifactUpdated), + SessionStatus(SessionStatusUpdated), + SessionIdle(SessionIdle), + TuiPromptAppend(TuiPromptAppend), + TuiCommandExecute(TuiCommandExecute), + TuiToastShow(TuiToastShow), + TuiSessionSelect(TuiSessionSelect), + InstallationUpdated(InstallationUpdated), + InstallationUpdateAvailable(InstallationUpdateAvailable), + VcsBranchUpdated(VcsBranchUpdated), + McpStatusChanged(McpStatusChanged), + McpResourcesChanged(McpResourcesChanged), + Rpc(V2EventRpc), + ServerConnected(V2EventServerConnected), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for V2Event { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("location.shutdown") => crate::de::variant(value).map(Self::LocationShutdown), + Some("models-dev.refreshed") => crate::de::variant(value).map(Self::ModelsDevRefreshed), + Some("credential.updated") => crate::de::variant(value).map(Self::CredentialUpdated), + Some("credential.switched") => crate::de::variant(value).map(Self::CredentialSwitched), + Some("integration.updated") => crate::de::variant(value).map(Self::IntegrationUpdated), + Some("provider.updated") => crate::de::variant(value).map(Self::ProviderUpdated), + Some("model.updated") => crate::de::variant(value).map(Self::ModelUpdated), + Some("agent.updated") => crate::de::variant(value).map(Self::AgentUpdated), + Some("session.created") => crate::de::variant(value).map(Self::SessionCreated), + Some("session.agent.selected") => { + crate::de::variant(value).map(Self::SessionAgentSelected) + } + Some("session.model.selected") => { + crate::de::variant(value).map(Self::SessionModelSelected) + } + Some("session.moved") => crate::de::variant(value).map(Self::SessionMoved), + Some("session.renamed") => crate::de::variant(value).map(Self::SessionRenamed), + Some("session.metadata.updated") => { + crate::de::variant(value).map(Self::SessionMetadataUpdated) + } + Some("session.permissions") => crate::de::variant(value).map(Self::SessionPermissions), + Some("session.viewed") => crate::de::variant(value).map(Self::SessionViewed), + Some("session.archived") => crate::de::variant(value).map(Self::SessionArchived), + Some("session.unarchived") => crate::de::variant(value).map(Self::SessionUnarchived), + Some("session.usage.updated") => { + crate::de::variant(value).map(Self::SessionUsageUpdated) + } + Some("session.deleted") => crate::de::variant(value).map(Self::SessionDeleted), + Some("session.forked") => crate::de::variant(value).map(Self::SessionForked), + Some("session.inbox.delivered") => { + crate::de::variant(value).map(Self::SessionInboxDelivered) + } + Some("session.inbox.enqueued") => { + crate::de::variant(value).map(Self::SessionInboxEnqueued) + } + Some("session.inbox.cancelled") => { + crate::de::variant(value).map(Self::SessionInboxCancelled) + } + Some("session.inbox.delivery.changed") => { + crate::de::variant(value).map(Self::SessionInboxDeliveryChanged) + } + Some("session.execution.started") => { + crate::de::variant(value).map(Self::SessionExecutionStarted) + } + Some("session.execution.succeeded") => { + crate::de::variant(value).map(Self::SessionExecutionSucceeded) + } + Some("session.execution.failed") => { + crate::de::variant(value).map(Self::SessionExecutionFailed) + } + Some("session.execution.interrupted") => { + crate::de::variant(value).map(Self::SessionExecutionInterrupted) + } + Some("session.instructions.updated") => { + crate::de::variant(value).map(Self::SessionInstructionsUpdated) + } + Some("session.synthetic") => crate::de::variant(value).map(Self::SessionSynthetic), + Some("session.skill.activated") => { + crate::de::variant(value).map(Self::SessionSkillActivated) + } + Some("session.shell.started") => { + crate::de::variant(value).map(Self::SessionShellStarted) + } + Some("session.shell.ended") => crate::de::variant(value).map(Self::SessionShellEnded), + Some("session.step.started") => crate::de::variant(value).map(Self::SessionStepStarted), + Some("session.step.streamed") => { + crate::de::variant(value).map(Self::SessionStepStreamed) + } + Some("session.step.ended") => crate::de::variant(value).map(Self::SessionStepEnded), + Some("session.step.failed") => crate::de::variant(value).map(Self::SessionStepFailed), + Some("session.text.started") => crate::de::variant(value).map(Self::SessionTextStarted), + Some("session.text.delta") => crate::de::variant(value).map(Self::SessionTextDelta), + Some("session.text.ended") => crate::de::variant(value).map(Self::SessionTextEnded), + Some("session.reasoning.started") => { + crate::de::variant(value).map(Self::SessionReasoningStarted) + } + Some("session.reasoning.delta") => { + crate::de::variant(value).map(Self::SessionReasoningDelta) + } + Some("session.reasoning.ended") => { + crate::de::variant(value).map(Self::SessionReasoningEnded) + } + Some("session.tool.input.started") => { + crate::de::variant(value).map(Self::SessionToolInputStarted) + } + Some("session.tool.input.delta") => { + crate::de::variant(value).map(Self::SessionToolInputDelta) + } + Some("session.tool.input.ended") => { + crate::de::variant(value).map(Self::SessionToolInputEnded) + } + Some("session.tool.called") => crate::de::variant(value).map(Self::SessionToolCalled), + Some("session.tool.progress") => { + crate::de::variant(value).map(Self::SessionToolProgress) + } + Some("session.tool.success") => crate::de::variant(value).map(Self::SessionToolSuccess), + Some("session.tool.failed") => crate::de::variant(value).map(Self::SessionToolFailed), + Some("session.retry.scheduled") => { + crate::de::variant(value).map(Self::SessionRetryScheduled) + } + Some("session.compaction.started") => { + crate::de::variant(value).map(Self::SessionCompactionStarted) + } + Some("session.compaction.delta") => { + crate::de::variant(value).map(Self::SessionCompactionDelta) + } + Some("session.compaction.ended") => { + crate::de::variant(value).map(Self::SessionCompactionEnded) + } + Some("session.compaction.failed") => { + crate::de::variant(value).map(Self::SessionCompactionFailed) + } + Some("session.revert.staged") => { + crate::de::variant(value).map(Self::SessionRevertStaged) + } + Some("session.revert.cleared") => { + crate::de::variant(value).map(Self::SessionRevertCleared) + } + Some("session.revert.committed") => { + crate::de::variant(value).map(Self::SessionRevertCommitted) + } + Some("filesystem.changed") => crate::de::variant(value).map(Self::FilesystemChanged), + Some("reference.updated") => crate::de::variant(value).map(Self::ReferenceUpdated), + Some("permission.asked") => crate::de::variant(value).map(Self::PermissionAsked), + Some("permission.replied") => crate::de::variant(value).map(Self::PermissionReplied), + Some("plugin.updated") => crate::de::variant(value).map(Self::PluginUpdated), + Some("project.updated") => crate::de::variant(value).map(Self::ProjectUpdated), + Some("worktree.updated") => crate::de::variant(value).map(Self::WorktreeUpdated), + Some("worktree.resolved") => crate::de::variant(value).map(Self::WorktreeResolved), + Some("command.updated") => crate::de::variant(value).map(Self::CommandUpdated), + Some("config.updated") => crate::de::variant(value).map(Self::ConfigUpdated), + Some("skill.updated") => crate::de::variant(value).map(Self::SkillUpdated), + Some("pty.created") => crate::de::variant(value).map(Self::PtyCreated), + Some("pty.updated") => crate::de::variant(value).map(Self::PtyUpdated), + Some("pty.exited") => crate::de::variant(value).map(Self::PtyExited), + Some("pty.deleted") => crate::de::variant(value).map(Self::PtyDeleted), + Some("persistent-pty.added") => crate::de::variant(value).map(Self::PersistentPtyAdded), + Some("persistent-pty.removed") => { + crate::de::variant(value).map(Self::PersistentPtyRemoved) + } + Some("persistent-pty.updated") => { + crate::de::variant(value).map(Self::PersistentPtyUpdated) + } + Some("shell.created") => crate::de::variant(value).map(Self::ShellCreated), + Some("shell.exited") => crate::de::variant(value).map(Self::ShellExited), + Some("shell.deleted") => crate::de::variant(value).map(Self::ShellDeleted), + Some("form.created") => crate::de::variant(value).map(Self::FormCreated), + Some("form.replied") => crate::de::variant(value).map(Self::FormReplied), + Some("form.cancelled") => crate::de::variant(value).map(Self::FormCancelled), + Some("websearch.updated") => crate::de::variant(value).map(Self::WebsearchUpdated), + Some("artifact.updated") => crate::de::variant(value).map(Self::ArtifactUpdated), + Some("session.status") => crate::de::variant(value).map(Self::SessionStatus), + Some("session.idle") => crate::de::variant(value).map(Self::SessionIdle), + Some("tui.prompt.append") => crate::de::variant(value).map(Self::TuiPromptAppend), + Some("tui.command.execute") => crate::de::variant(value).map(Self::TuiCommandExecute), + Some("tui.toast.show") => crate::de::variant(value).map(Self::TuiToastShow), + Some("tui.session.select") => crate::de::variant(value).map(Self::TuiSessionSelect), + Some("installation.updated") => { + crate::de::variant(value).map(Self::InstallationUpdated) + } + Some("installation.update-available") => { + crate::de::variant(value).map(Self::InstallationUpdateAvailable) + } + Some("vcs.branch.updated") => crate::de::variant(value).map(Self::VcsBranchUpdated), + Some("mcp.status.changed") => crate::de::variant(value).map(Self::McpStatusChanged), + Some("mcp.resources.changed") => { + crate::de::variant(value).map(Self::McpResourcesChanged) + } + Some("server.connected") => crate::de::variant(value).map(Self::ServerConnected), + Some(tag) if tag.starts_with("rpc.") => crate::de::variant(value).map(Self::Rpc), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Output of [`Client::event_subscribe`]. +pub type EventSubscribeOutput = V2Event; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::pty_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PtyListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyCreateInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::pty_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PtyCreateInput { + pub location: Option, + pub command: Option, + pub args: Option>, + pub cwd: Option, + pub title: Option, + pub env: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PtyCreateOutput { + pub location: LocationPublicRef, + pub data: Pty, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::pty_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PtyGetInput { + pub pty_id: PtyID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PtyGetOutput { + pub location: LocationPublicRef, + pub data: Pty, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyUpdateInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyUpdateInputSize { + pub rows: i64, + pub cols: i64, +} + +/// Input of [`Client::pty_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PtyUpdateInput { + pub pty_id: PtyID, + pub location: Option, + pub title: Option, + pub size: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PtyUpdateOutput { + pub location: LocationPublicRef, + pub data: Pty, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyRemoveInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::pty_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PtyRemoveInput { + pub pty_id: PtyID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyConnectTokenInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::pty_connect_token`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PtyConnectTokenInput { + pub pty_id: PtyID, + pub location: Option, + pub x_opencode_ticket: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyConnectTokenOutput { + pub location: LocationPublicRef, + pub data: PtyTicketConnectToken, +} + +/// `PersistentPty.ReadLines` +pub type PersistentPtyReadLines = i64; + +/// Input of [`Client::experimental_persistent_pty_read`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtyReadInput { + pub session_id: SessionID, + pub lines: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyReadResultScreenCursor { + pub x: i64, + pub y: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyReadResultScreen { + pub text: String, + pub cols: i64, + pub rows: i64, + pub cursor: PersistentPtyReadResultScreenCursor, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyReadResult { + #[serde(rename = "ptyID")] + pub pty_id: PtyID, + pub title: String, + pub cwd: String, + #[serde(rename = "foregroundProcess", default)] + pub foreground_process: Option, + pub screen: PersistentPtyReadResultScreen, +} + +/// Output of [`Client::experimental_persistent_pty_read`]. +pub type ExperimentalPersistentPtyReadOutput = Option; + +/// Input of [`Client::experimental_persistent_pty_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtyListInput { + pub session_id: SessionID, +} + +/// Output of [`Client::experimental_persistent_pty_list`]. +pub type ExperimentalPersistentPtyListOutput = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalPersistentPtyCreateInputSize { + pub cols: i64, + pub rows: i64, +} + +/// Input of [`Client::experimental_persistent_pty_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtyCreateInput { + pub session_id: SessionID, + pub command: Option, + pub args: Vec, + pub cwd: Option, + pub title: String, + pub env: BTreeMap, + pub size: Option, +} + +/// Output of [`Client::experimental_persistent_pty_create`]. +pub type ExperimentalPersistentPtyCreateOutput = PersistentPtyInfo; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtyHandoff { + pub directory: String, + #[serde(rename = "instanceID")] + pub instance_id: String, + pub ticket: String, + #[serde(rename = "expiresAt")] + pub expires_at: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalPersistentPtyHandoffOutput { + #[serde(default)] + pub handoff: Option, +} + +/// Input of [`Client::experimental_persistent_pty_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtyGetInput { + pub pty_id: PtyID, +} + +/// Output of [`Client::experimental_persistent_pty_get`]. +pub type ExperimentalPersistentPtyGetOutput = PersistentPtyInfo; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalPersistentPtyUpdateInputSize { + pub cols: i64, + pub rows: i64, +} + +/// Input of [`Client::experimental_persistent_pty_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtyUpdateInput { + pub pty_id: PtyID, + pub attachment_id: Option, + pub size: Option, + pub title: Option>, +} + +/// Output of [`Client::experimental_persistent_pty_update`]. +pub type ExperimentalPersistentPtyUpdateOutput = PersistentPtyInfo; + +/// Input of [`Client::experimental_persistent_pty_snapshot`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtySnapshotInput { + pub pty_id: PtyID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PersistentPtySnapshotCursor { + pub x: i64, + pub y: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PersistentPtySnapshot { + pub info: PersistentPtyInfo, + pub text: String, + pub checkpoint: String, + pub cursor: PersistentPtySnapshotCursor, +} + +/// Output of [`Client::experimental_persistent_pty_snapshot`]. +pub type ExperimentalPersistentPtySnapshotOutput = PersistentPtySnapshot; + +/// Input of [`Client::experimental_persistent_pty_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtyRemoveInput { + pub pty_id: PtyID, +} + +/// Input of [`Client::experimental_persistent_pty_connect_token`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalPersistentPtyConnectTokenInput { + pub pty_id: PtyID, + pub x_opencode_ticket: Option, +} + +/// Output of [`Client::experimental_persistent_pty_connect_token`]. +pub type ExperimentalPersistentPtyConnectTokenOutput = PtyTicketConnectToken; + +/// `MediaHash` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct MediaHash(pub String); + +impl MediaHash { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for MediaHash { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for MediaHash { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for MediaHash { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// Input of [`Client::experimental_media_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalMediaGetInput { + pub hash: MediaHash, +} + +/// `Schedule.Duration` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ScheduleDuration(pub String); + +impl ScheduleDuration { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ScheduleDuration { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ScheduleDuration { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ScheduleDuration { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenInputObject { + pub r#in: ScheduleDuration, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenInputObject2 { + pub at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenInputObject3 { + pub every: ScheduleDuration, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenInputObject4 { + pub cron: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +/// `Schedule.WhenInput` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ScheduleWhenInput { + Object(ScheduleWhenInputObject), + Object2(ScheduleWhenInputObject2), + Object3(ScheduleWhenInputObject3), + Object4(ScheduleWhenInputObject4), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleConditionInputObject { + pub run: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub matches: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub changes: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleConditionInputObject2 { + pub code: String, +} + +/// `Schedule.ConditionInput` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ScheduleConditionInput { + Object(ScheduleConditionInputObject), + Object2(ScheduleConditionInputObject2), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleEnds { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub after: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub times: Option, +} + +/// Input of [`Client::experimental_schedule_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalScheduleCreateInput { + pub session_id: SessionID, + pub name: Option, + pub when: Option, + pub r#if: Option, + pub until: Option, + pub ends: Option, + pub prompt: String, +} + +/// `Schedule.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ScheduleID(pub String); + +impl ScheduleID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ScheduleID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ScheduleID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ScheduleID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenIn { + pub r#type: String, + pub r#in: ScheduleDuration, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenAt { + pub r#type: String, + pub at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenEvery { + pub r#type: String, + pub every: ScheduleDuration, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleWhenCron { + pub r#type: String, + pub cron: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tz: Option, +} + +/// `Schedule.When`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ScheduleWhen { + In(ScheduleWhenIn), + At(ScheduleWhenAt), + Every(ScheduleWhenEvery), + Cron(ScheduleWhenCron), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ScheduleWhen { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("in") => crate::de::variant(value).map(Self::In), + Some("at") => crate::de::variant(value).map(Self::At), + Some("every") => crate::de::variant(value).map(Self::Every), + Some("cron") => crate::de::variant(value).map(Self::Cron), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleConditionShell { + pub r#type: String, + pub run: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub is: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub matches: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub changes: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleConditionCode { + pub r#type: String, + pub code: String, +} + +/// `Schedule.Condition`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ScheduleCondition { + Shell(ScheduleConditionShell), + Code(ScheduleConditionCode), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ScheduleCondition { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("shell") => crate::de::variant(value).map(Self::Shell), + Some("code") => crate::de::variant(value).map(Self::Code), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleActionPrompt { + pub r#type: String, + pub prompt: String, +} + +/// `Schedule.Status` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ScheduleStatus { + Active, + Paused, + Done, + Unknown(String), +} + +impl ScheduleStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Active => "active", + Self::Paused => "paused", + Self::Done => "done", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ScheduleStatus { + fn from(value: &str) -> Self { + match value { + "active" => Self::Active, + "paused" => Self::Paused, + "done" => Self::Done, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ScheduleStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ScheduleStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Schedule.Outcome` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ScheduleOutcome { + Fired, + Late, + Checked, + Expired, + Skipped, + Disabled, + Failed, + Unknown(String), +} + +impl ScheduleOutcome { + pub fn as_str(&self) -> &str { + match self { + Self::Fired => "fired", + Self::Late => "late", + Self::Checked => "checked", + Self::Expired => "expired", + Self::Skipped => "skipped", + Self::Disabled => "disabled", + Self::Failed => "failed", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ScheduleOutcome { + fn from(value: &str) -> Self { + match value { + "fired" => Self::Fired, + "late" => Self::Late, + "checked" => Self::Checked, + "expired" => Self::Expired, + "skipped" => Self::Skipped, + "disabled" => Self::Disabled, + "failed" => Self::Failed, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ScheduleOutcome { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ScheduleOutcome { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleInfoTime { + pub created: f64, + pub updated: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ScheduleInfo { + pub id: ScheduleID, + #[serde(rename = "sessionID", default, skip_serializing_if = "Option::is_none")] + pub session_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + pub when: ScheduleWhen, + pub tz: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub r#if: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub until: Option, + pub action: ScheduleActionPrompt, + pub status: ScheduleStatus, + #[serde(rename = "nextDueAt", default, skip_serializing_if = "Option::is_none")] + pub next_due_at: Option, + #[serde(rename = "endsAt", default, skip_serializing_if = "Option::is_none")] + pub ends_at: Option, + #[serde( + rename = "remainingRuns", + default, + skip_serializing_if = "Option::is_none" + )] + pub remaining_runs: Option, + #[serde(rename = "runCount")] + pub run_count: i64, + #[serde( + rename = "lastFiredAt", + default, + skip_serializing_if = "Option::is_none" + )] + pub last_fired_at: Option, + #[serde( + rename = "lastOutcome", + default, + skip_serializing_if = "Option::is_none" + )] + pub last_outcome: Option, + #[serde( + rename = "lastOutput", + default, + skip_serializing_if = "Option::is_none" + )] + pub last_output: Option, + pub time: ScheduleInfoTime, +} + +/// Output of [`Client::experimental_schedule_create`]. +pub type ExperimentalScheduleCreateOutput = ScheduleInfo; + +/// Input of [`Client::experimental_schedule_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalScheduleListInput { + pub session_id: SessionID, +} + +/// Output of [`Client::experimental_schedule_list`]. +pub type ExperimentalScheduleListOutput = Vec; + +/// Input of [`Client::experimental_schedule_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalScheduleGetInput { + pub schedule_id: ScheduleID, +} + +/// Output of [`Client::experimental_schedule_get`]. +pub type ExperimentalScheduleGetOutput = ScheduleInfo; + +/// Input of [`Client::experimental_schedule_pause`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalSchedulePauseInput { + pub schedule_id: ScheduleID, +} + +/// Output of [`Client::experimental_schedule_pause`]. +pub type ExperimentalSchedulePauseOutput = ScheduleInfo; + +/// Input of [`Client::experimental_schedule_resume`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalScheduleResumeInput { + pub schedule_id: ScheduleID, +} + +/// Output of [`Client::experimental_schedule_resume`]. +pub type ExperimentalScheduleResumeOutput = ScheduleInfo; + +/// Input of [`Client::experimental_schedule_delete`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalScheduleDeleteInput { + pub schedule_id: ScheduleID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsProvidersInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_artifacts_providers`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalArtifactsProvidersInput { + pub location: Option, +} + +/// `Artifact.Capability` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ArtifactCapability { + Static, + ServerCode, + Sqlite, + DurableObjects, + Unknown(String), +} + +impl ArtifactCapability { + pub fn as_str(&self) -> &str { + match self { + Self::Static => "static", + Self::ServerCode => "server-code", + Self::Sqlite => "sqlite", + Self::DurableObjects => "durable-objects", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ArtifactCapability { + fn from(value: &str) -> Self { + match value { + "static" => Self::Static, + "server-code" => Self::ServerCode, + "sqlite" => Self::Sqlite, + "durable-objects" => Self::DurableObjects, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ArtifactCapability { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ArtifactCapability { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ArtifactProvider { + pub id: String, + pub name: String, + pub capabilities: Vec, + pub default: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsProvidersOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// `Artifact.ProviderID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ArtifactProviderID(pub String); + +impl ArtifactProviderID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ArtifactProviderID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ArtifactProviderID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ArtifactProviderID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// Input of [`Client::experimental_artifacts_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalArtifactsListInput { + pub location: Option, + pub session_id: Option, + pub provider: Option, +} + +/// `Artifact.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ArtifactID(pub String); + +impl ArtifactID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ArtifactID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ArtifactID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ArtifactID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ArtifactTime { + pub created: f64, + pub updated: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ArtifactInfo { + pub id: ArtifactID, + pub provider: String, + #[serde(rename = "sessionID", default, skip_serializing_if = "Option::is_none")] + pub session_id: Option, + pub title: String, + pub entry: String, + pub url: String, + pub time: ArtifactTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsCreateInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_artifacts_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalArtifactsCreateInput { + pub location: Option, + pub title: String, + pub files: BTreeMap, + pub entry: Option, + pub provider: Option, + pub session_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsCreateOutput { + pub location: LocationPublicRef, + pub data: ArtifactInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_artifacts_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalArtifactsGetInput { + pub artifact_id: ArtifactID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ArtifactContent { + pub info: ArtifactInfo, + pub files: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsGetOutput { + pub location: LocationPublicRef, + pub data: ArtifactContent, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsUpdateInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_artifacts_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalArtifactsUpdateInput { + pub artifact_id: ArtifactID, + pub location: Option, + pub title: Option, + pub files: BTreeMap, + pub entry: Option, + pub session_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsUpdateOutput { + pub location: LocationPublicRef, + pub data: ArtifactInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsDeleteInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_artifacts_delete`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalArtifactsDeleteInput { + pub artifact_id: ArtifactID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalArtifactsViewInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_artifacts_view`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalArtifactsViewInput { + pub artifact_id: ArtifactID, + pub location: Option, + pub path: String, +} + +/// `Job.Kind` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum JobKind { + Shell, + Subagent, + Image, + Unknown(String), +} + +impl JobKind { + pub fn as_str(&self) -> &str { + match self { + Self::Shell => "shell", + Self::Subagent => "subagent", + Self::Image => "image", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for JobKind { + fn from(value: &str) -> Self { + match value { + "shell" => Self::Shell, + "subagent" => Self::Subagent, + "image" => Self::Image, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for JobKind { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for JobKind { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Job.Status` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum JobStatus { + Running, + Completed, + Error, + Cancelled, + Unknown(String), +} + +impl JobStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Running => "running", + Self::Completed => "completed", + Self::Error => "error", + Self::Cancelled => "cancelled", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for JobStatus { + fn from(value: &str) -> Self { + match value { + "running" => Self::Running, + "completed" => Self::Completed, + "error" => Self::Error, + "cancelled" => Self::Cancelled, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for JobStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for JobStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// Input of [`Client::experimental_job_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalJobListInput { + pub session_id: Option, + pub kind: Option, + pub status: Option, + pub descendants: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct JobTime { + pub started: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct JobShell { + pub kind: String, + pub id: String, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub status: JobStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + pub time: JobTime, + #[serde(rename = "shellID")] + pub shell_id: String, + pub command: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct JobSubagent { + pub kind: String, + pub id: String, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub status: JobStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + pub time: JobTime, + #[serde(rename = "childSessionID")] + pub child_session_id: SessionID, + pub agent: String, + pub description: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct JobImage { + pub kind: String, + pub id: String, + #[serde(rename = "sessionID")] + pub session_id: SessionID, + pub status: JobStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + pub time: JobTime, + pub path: String, + pub model: String, +} + +/// `Job.Info`, tagged by `kind`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum JobInfo { + Shell(JobShell), + Subagent(JobSubagent), + Image(JobImage), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for JobInfo { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("kind").and_then(serde_json::Value::as_str) { + Some("shell") => crate::de::variant(value).map(Self::Shell), + Some("subagent") => crate::de::variant(value).map(Self::Subagent), + Some("image") => crate::de::variant(value).map(Self::Image), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Output of [`Client::experimental_job_list`]. +pub type ExperimentalJobListOutput = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::shell_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ShellListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ShellInfo1Status { + Running, + Exited, + Timeout, + Killed, + Unknown(String), +} + +impl ShellInfo1Status { + pub fn as_str(&self) -> &str { + match self { + Self::Running => "running", + Self::Exited => "exited", + Self::Timeout => "timeout", + Self::Killed => "killed", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ShellInfo1Status { + fn from(value: &str) -> Self { + match value { + "running" => Self::Running, + "exited" => Self::Exited, + "timeout" => Self::Timeout, + "killed" => Self::Killed, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ShellInfo1Status { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ShellInfo1Status { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellInfo1Time { + pub started: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellInfo1 { + pub id: ShellID, + pub status: ShellInfo1Status, + pub command: String, + pub cwd: String, + pub shell: String, + pub file: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pid: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exit: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub signal: Option, + pub metadata: BTreeMap, + pub time: ShellInfo1Time, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellCreateInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::shell_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ShellCreateInput { + pub location: Option, + pub command: String, + pub cwd: Option, + pub timeout: Option, + pub metadata: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellCreateOutput { + pub location: LocationPublicRef, + pub data: ShellInfo1, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::shell_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ShellGetInput { + pub id: ShellID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShellGetOutput { + pub location: LocationPublicRef, + pub data: ShellInfo1, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellOutputInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::shell_output`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ShellOutputInput { + pub id: ShellID, + pub location: Option, + pub cursor: Option, + pub limit: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellOutputOutputData { + pub output: String, + pub cursor: i64, + pub size: i64, + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellOutputOutput { + pub location: LocationPublicRef, + pub data: ShellOutputOutputData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellRemoveInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::shell_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ShellRemoveInput { + pub id: ShellID, + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ReferenceListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::reference_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ReferenceListInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ReferenceLocalSource { + pub r#type: String, + pub path: AbsolutePath, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ReferenceGitSource { + pub r#type: String, + pub repository: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub branch: Option, +} + +/// `Reference.Source`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ReferenceSource { + Local(ReferenceLocalSource), + Git(ReferenceGitSource), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ReferenceSource { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("local") => crate::de::variant(value).map(Self::Local), + Some("git") => crate::de::variant(value).map(Self::Git), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ReferenceInfo { + pub name: String, + pub path: AbsolutePath, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hidden: Option, + pub source: ReferenceSource, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ReferenceListOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +/// Input of [`Client::worktree_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct WorktreeListInput { + pub project_id: ProjectID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeDirectory { + pub directory: AbsolutePath, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub strategy: Option, +} + +/// `Worktree.List` +pub type WorktreeList = Vec; + +/// Output of [`Client::worktree_list`]. +pub type WorktreeListOutput = WorktreeList; + +/// Input of [`Client::worktree_create`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct WorktreeCreateInput { + pub project_id: ProjectID, + pub from: Option, + pub branch: Option, + pub directory: Option, + pub name: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeInfo { + pub directory: AbsolutePath, +} + +/// Output of [`Client::worktree_create`]. +pub type WorktreeCreateOutput = WorktreeInfo; + +/// Input of [`Client::worktree_remove`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct WorktreeRemoveInput { + pub project_id: ProjectID, + pub directory: AbsolutePath, + pub force: bool, +} + +/// Input of [`Client::worktree_refresh`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct WorktreeRefreshInput { + pub project_id: ProjectID, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsInitInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::vcs_init`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct VcsInitInput { + pub location: Option, + pub provider: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::vcs_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct VcsGetInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsBranch { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub current: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsInfo { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider: Option, + pub branch: VcsBranch, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsGetOutput { + pub location: LocationPublicRef, + pub data: VcsInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsBaseInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::vcs_base`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct VcsBaseInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum VcsBaseSource { + Reflog, + Default, + Unknown(String), +} + +impl VcsBaseSource { + pub fn as_str(&self) -> &str { + match self { + Self::Reflog => "reflog", + Self::Default => "default", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for VcsBaseSource { + fn from(value: &str) -> Self { + match value { + "reflog" => Self::Reflog, + "default" => Self::Default, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for VcsBaseSource { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for VcsBaseSource { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct VcsBase { + pub name: String, + pub r#ref: String, + pub source: VcsBaseSource, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsBaseOutput { + pub location: LocationPublicRef, + #[serde(default)] + pub data: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsStatusInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::vcs_status`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct VcsStatusInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum VcsFileStatusStatus { + Added, + Deleted, + Modified, + Unknown(String), +} + +impl VcsFileStatusStatus { + pub fn as_str(&self) -> &str { + match self { + Self::Added => "added", + Self::Deleted => "deleted", + Self::Modified => "modified", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for VcsFileStatusStatus { + fn from(value: &str) -> Self { + match value { + "added" => Self::Added, + "deleted" => Self::Deleted, + "modified" => Self::Modified, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for VcsFileStatusStatus { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for VcsFileStatusStatus { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct VcsFileStatus { + pub file: String, + pub additions: i64, + pub deletions: i64, + pub status: VcsFileStatusStatus, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsStatusOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsBranchListInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::vcs_branch_list`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct VcsBranchListInput { + pub location: Option, + pub search: Option, + pub limit: Option, +} + +/// `Vcs.BranchList` +pub type VcsBranchList = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsBranchListOutput { + pub location: LocationPublicRef, + pub data: VcsBranchList, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsDiffInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// `Vcs.Mode` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum VcsMode { + Working, + Branch, + Committed, + Unknown(String), +} + +impl VcsMode { + pub fn as_str(&self) -> &str { + match self { + Self::Working => "working", + Self::Branch => "branch", + Self::Committed => "committed", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for VcsMode { + fn from(value: &str) -> Self { + match value { + "working" => Self::Working, + "branch" => Self::Branch, + "committed" => Self::Committed, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for VcsMode { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for VcsMode { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// `Vcs.Untracked` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum VcsUntracked { + Files, + Folders, + Unknown(String), +} + +impl VcsUntracked { + pub fn as_str(&self) -> &str { + match self { + Self::Files => "files", + Self::Folders => "folders", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for VcsUntracked { + fn from(value: &str) -> Self { + match value { + "files" => Self::Files, + "folders" => Self::Folders, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for VcsUntracked { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for VcsUntracked { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +/// Input of [`Client::vcs_diff`]. +#[derive(Debug, Clone, PartialEq)] +pub struct VcsDiffInput { + pub location: Option, + pub mode: VcsMode, + pub base: Option, + pub context: Option, + pub untracked: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsDiffOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +/// Input of [`Client::debug_heap_dump`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct DebugHeapDumpInput { + pub directory: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct DebugHeapDumpOutputMemory { + pub rss: f64, + #[serde(rename = "heapTotal")] + pub heap_total: f64, + #[serde(rename = "heapUsed")] + pub heap_used: f64, + pub external: f64, + #[serde(rename = "arrayBuffers")] + pub array_buffers: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct DebugHeapDumpOutput { + pub path: String, + pub pid: i64, + pub memory: DebugHeapDumpOutputMemory, +} + +/// Output of [`Client::debug_location_list`]. +pub type DebugLocationListOutput = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct DebugLocationEvictInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::debug_location_evict`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct DebugLocationEvictInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ExperimentalMigrationV1StatusOutput2Variant1Status { + Required, + Completed, + Unknown(String), +} + +impl ExperimentalMigrationV1StatusOutput2Variant1Status { + pub fn as_str(&self) -> &str { + match self { + Self::Required => "required", + Self::Completed => "completed", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ExperimentalMigrationV1StatusOutput2Variant1Status { + fn from(value: &str) -> Self { + match value { + "required" => Self::Required, + "completed" => Self::Completed, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ExperimentalMigrationV1StatusOutput2Variant1Status { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ExperimentalMigrationV1StatusOutput2Variant1Status { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ExperimentalMigrationV1StatusOutput2Variant1 { + pub status: ExperimentalMigrationV1StatusOutput2Variant1Status, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMigrationV1StatusOutput2RunningProgress { + pub label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub numerator: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub denominator: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMigrationV1StatusOutput2Running { + pub status: String, + pub progress: ExperimentalMigrationV1StatusOutput2RunningProgress, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalMigrationV1StatusOutput2Error { + pub status: String, + pub error: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ExperimentalMigrationV1StatusOutput2 { + Variant1(ExperimentalMigrationV1StatusOutput2Variant1), + Running(ExperimentalMigrationV1StatusOutput2Running), + Error(ExperimentalMigrationV1StatusOutput2Error), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ExperimentalMigrationV1StatusOutput2 { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("status").and_then(serde_json::Value::as_str) { + Some("required") | Some("completed") => crate::de::variant(value).map(Self::Variant1), + Some("running") => crate::de::variant(value).map(Self::Running), + Some("error") => crate::de::variant(value).map(Self::Error), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Output of [`Client::experimental_migration_v1_status`]. +pub type ExperimentalMigrationV1StatusOutput = ExperimentalMigrationV1StatusOutput2; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebsearchProvidersInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::websearch_providers`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct WebsearchProvidersInput { + pub location: Option, +} + +/// `WebSearch.ID` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct WebSearchID(pub String); + +impl WebSearchID { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for WebSearchID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for WebSearchID { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for WebSearchID { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebSearchProvider { + pub id: WebSearchID, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebsearchProvidersOutput { + pub location: LocationPublicRef, + pub data: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebsearchQueryInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::websearch_query`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct WebsearchQueryInput { + pub location: Option, + pub query: String, + pub provider_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebSearchResultTime { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub published: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebSearchResult { + pub url: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub content: Option, + pub time: WebSearchResultTime, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebsearchQueryOutputData { + #[serde(rename = "providerID")] + pub provider_id: WebSearchID, + pub results: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WebsearchQueryOutput { + pub location: LocationPublicRef, + pub data: WebsearchQueryOutputData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalUsageLimitsInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::experimental_usage_limits`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalUsageLimitsInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UsageLimitsInfoWorkspace { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "usageURL")] + pub usage_url: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UsageLimitsMeter { + pub percent: f64, + pub limited: bool, + #[serde(rename = "resetsAt")] + pub resets_at: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UsageLimitsGo { + pub rolling: UsageLimitsMeter, + pub weekly: UsageLimitsMeter, + pub monthly: UsageLimitsMeter, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum UsageLimitsBudgetScope { + Each, + Combined, + Unknown(String), +} + +impl UsageLimitsBudgetScope { + pub fn as_str(&self) -> &str { + match self { + Self::Each => "each", + Self::Combined => "combined", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for UsageLimitsBudgetScope { + fn from(value: &str) -> Self { + match value { + "each" => Self::Each, + "combined" => Self::Combined, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for UsageLimitsBudgetScope { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for UsageLimitsBudgetScope { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum UsageLimitsBudgetPer { + Set, + Model, + Unknown(String), +} + +impl UsageLimitsBudgetPer { + pub fn as_str(&self) -> &str { + match self { + Self::Set => "set", + Self::Model => "model", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for UsageLimitsBudgetPer { + fn from(value: &str) -> Self { + match value { + "set" => Self::Set, + "model" => Self::Model, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for UsageLimitsBudgetPer { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for UsageLimitsBudgetPer { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum UsageLimitsBudgetCoverage { + All, + Models, + Unknown(String), +} + +impl UsageLimitsBudgetCoverage { + pub fn as_str(&self) -> &str { + match self { + Self::All => "all", + Self::Models => "models", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for UsageLimitsBudgetCoverage { + fn from(value: &str) -> Self { + match value { + "all" => Self::All, + "models" => Self::Models, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for UsageLimitsBudgetCoverage { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for UsageLimitsBudgetCoverage { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UsageLimitsBudgetModel { + #[serde(rename = "providerID")] + pub provider_id: ProviderID, + #[serde(rename = "modelID")] + pub model_id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spent: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct UsageLimitsBudget { + pub id: String, + pub limit: MoneyUSD, + pub spent: MoneyUSD, + pub scope: UsageLimitsBudgetScope, + pub per: UsageLimitsBudgetPer, + pub coverage: UsageLimitsBudgetCoverage, + pub models: Vec, + pub vendors: Vec, + #[serde( + rename = "inputPriceAtLeast", + default, + skip_serializing_if = "Option::is_none" + )] + pub input_price_at_least: Option, + pub picked: bool, + pub shared: bool, + #[serde(rename = "resetsAt")] + pub resets_at: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UsageLimitsInfo { + pub workspace: UsageLimitsInfoWorkspace, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub go: Option, + pub budgets: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ExperimentalUsageLimitsOutput { + pub location: LocationPublicRef, + #[serde(default)] + pub data: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigGetInputLocation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub directory: Option, +} + +/// Input of [`Client::config_get`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ConfigGetInput { + pub location: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoModelObject { + #[serde(rename = "providerID")] + pub provider_id: String, + pub model: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoModel { + String(String), + Object(ConfigEntryDocumentInfoModelObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConfigEntryDocumentInfoUpdate { + Disable, + Notify, + Auto, + Unknown(String), +} + +impl ConfigEntryDocumentInfoUpdate { + pub fn as_str(&self) -> &str { + match self { + Self::Disable => "disable", + Self::Notify => "notify", + Self::Auto => "auto", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConfigEntryDocumentInfoUpdate { + fn from(value: &str) -> Self { + match value { + "disable" => Self::Disable, + "notify" => Self::Notify, + "auto" => Self::Auto, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConfigEntryDocumentInfoUpdate { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoUpdate { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConfigEntryDocumentInfoShare { + Manual, + Auto, + Disabled, + Unknown(String), +} + +impl ConfigEntryDocumentInfoShare { + pub fn as_str(&self) -> &str { + match self { + Self::Manual => "manual", + Self::Auto => "auto", + Self::Disabled => "disabled", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConfigEntryDocumentInfoShare { + fn from(value: &str) -> Self { + match value { + "manual" => Self::Manual, + "auto" => Self::Auto, + "disabled" => Self::Disabled, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConfigEntryDocumentInfoShare { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoShare { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoEnterprise { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConfigEntryDocumentInfoPoliciesItemAction { + ProviderUse, + ToolUse, + IntegrationConnect, + IntegrationUse, + McpUse, + SkillUse, + PluginUse, + WebsearchUse, + Unknown(String), +} + +impl ConfigEntryDocumentInfoPoliciesItemAction { + pub fn as_str(&self) -> &str { + match self { + Self::ProviderUse => "provider.use", + Self::ToolUse => "tool.use", + Self::IntegrationConnect => "integration.connect", + Self::IntegrationUse => "integration.use", + Self::McpUse => "mcp.use", + Self::SkillUse => "skill.use", + Self::PluginUse => "plugin.use", + Self::WebsearchUse => "websearch.use", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConfigEntryDocumentInfoPoliciesItemAction { + fn from(value: &str) -> Self { + match value { + "provider.use" => Self::ProviderUse, + "tool.use" => Self::ToolUse, + "integration.connect" => Self::IntegrationConnect, + "integration.use" => Self::IntegrationUse, + "mcp.use" => Self::McpUse, + "skill.use" => Self::SkillUse, + "plugin.use" => Self::PluginUse, + "websearch.use" => Self::WebsearchUse, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConfigEntryDocumentInfoPoliciesItemAction { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoPoliciesItemAction { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConfigEntryDocumentInfoPoliciesItemEffect { + Allow, + Deny, + Unknown(String), +} + +impl ConfigEntryDocumentInfoPoliciesItemEffect { + pub fn as_str(&self) -> &str { + match self { + Self::Allow => "allow", + Self::Deny => "deny", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConfigEntryDocumentInfoPoliciesItemEffect { + fn from(value: &str) -> Self { + match value { + "allow" => Self::Allow, + "deny" => Self::Deny, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConfigEntryDocumentInfoPoliciesItemEffect { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoPoliciesItemEffect { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ConfigEntryDocumentInfoPoliciesItem { + pub action: ConfigEntryDocumentInfoPoliciesItemAction, + pub resource: String, + pub effect: ConfigEntryDocumentInfoPoliciesItemEffect, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoAgentsValueModelObject { + #[serde(rename = "providerID")] + pub provider_id: String, + pub model: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoAgentsValueModel { + String(String), + Object(ConfigEntryDocumentInfoAgentsValueModelObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoAgentsValueRequest { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConfigEntryDocumentInfoAgentsValueMode { + Subagent, + Primary, + All, + Unknown(String), +} + +impl ConfigEntryDocumentInfoAgentsValueMode { + pub fn as_str(&self) -> &str { + match self { + Self::Subagent => "subagent", + Self::Primary => "primary", + Self::All => "all", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConfigEntryDocumentInfoAgentsValueMode { + fn from(value: &str) -> Self { + match value { + "subagent" => Self::Subagent, + "primary" => Self::Primary, + "all" => Self::All, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConfigEntryDocumentInfoAgentsValueMode { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoAgentsValueMode { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoAgentsValue { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub system: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hidden: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub steps: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub permissions: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoWatcher { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ignore: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoFormatterObjectValue { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub command: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub environment: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub extensions: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoFormatter { + Bool(bool), + Object(BTreeMap), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoLspObjectValueObject { + pub disabled: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoLspObjectValueObject2 { + pub command: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub extensions: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub env: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub initialization: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoLspObjectValue { + Object(ConfigEntryDocumentInfoLspObjectValueObject), + Object2(ConfigEntryDocumentInfoLspObjectValueObject2), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoLsp { + Bool(bool), + Object(BTreeMap), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMediaImage { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_resize: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_height: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_base64_bytes: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMedia { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub image: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoToolOutput { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_lines: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMcpTimeout { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub startup: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub catalog: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub execution: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMcpServersValueLocalTimeout { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub startup: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub catalog: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub execution: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMcpServersValueLocal { + pub r#type: String, + pub command: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub environment: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub codemode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub protocol: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMcpServersValueRemoteOauthObject { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scope: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub callback_port: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub redirect_uri: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth_server_metadata_url: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoMcpServersValueRemoteOauth { + Object(ConfigEntryDocumentInfoMcpServersValueRemoteOauthObject), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMcpServersValueRemoteTimeout { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub startup: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub catalog: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub execution: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMcpServersValueRemote { + pub r#type: String, + pub url: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub oauth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub codemode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub protocol: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoMcpServersValue { + Local(ConfigEntryDocumentInfoMcpServersValueLocal), + Remote(ConfigEntryDocumentInfoMcpServersValueRemote), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoMcpServersValue { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("local") => crate::de::variant(value).map(Self::Local), + Some("remote") => crate::de::variant(value).map(Self::Remote), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoMcp { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub servers: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoCompactionKeep { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +/// `Config.Compaction.Percent` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ConfigCompactionPercent(pub String); + +impl ConfigCompactionPercent { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for ConfigCompactionPercent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ConfigCompactionPercent { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ConfigCompactionPercent { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoCompactionBuffer { + String(ConfigCompactionPercent), + Number(i64), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoCompaction { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub keep: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub buffer: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoCommandsValueModelObject { + #[serde(rename = "providerID")] + pub provider_id: String, + pub model: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoCommandsValueModel { + String(String), + Object(ConfigEntryDocumentInfoCommandsValueModelObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoCommandsValue { + pub template: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subagent: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subtask: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoReferencesValueObject { + pub repository: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hidden: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoReferencesValueObject2 { + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hidden: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoReferencesValue { + String(String), + Object(ConfigEntryDocumentInfoReferencesValueObject), + Object2(ConfigEntryDocumentInfoReferencesValueObject2), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoWebsearchObject { + pub provider: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoWebsearch { + Bool(bool), + Object(ConfigEntryDocumentInfoWebsearchObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoPluginsItemObject { + pub package: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub options: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoPluginsItem { + String(String), + Object(ConfigEntryDocumentInfoPluginsItemObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigWorktree { + pub directory: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoWarmingObject { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub interval: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoWarming { + Bool(bool), + Object(ConfigEntryDocumentInfoWarmingObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigProviderSettingsTimeout { + Number(f64), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigProviderSettingsHeaderTimeout { + Number(f64), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigProviderSettingsChunkTimeout { + Number(f64), + Bool(bool), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigProviderSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde( + rename = "headerTimeout", + default, + skip_serializing_if = "Option::is_none" + )] + pub header_timeout: Option, + #[serde( + rename = "chunkTimeout", + default, + skip_serializing_if = "Option::is_none" + )] + pub chunk_timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encoding: Option, + #[serde(flatten)] + pub extra: BTreeMap>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigModelSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encoding: Option, + #[serde(flatten)] + pub extra: BTreeMap>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigModelReasoningFalse { + pub supported: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigModelReasoningTrueBudget { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigModelReasoningTrue { + pub supported: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub toggle: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effort: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub budget: Option, +} + +/// `Config.Model.Reasoning`, tagged by `supported`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ConfigModelReasoning { + False(ConfigModelReasoningFalse), + True(ConfigModelReasoningTrue), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ConfigModelReasoning { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("supported").and_then(serde_json::Value::as_bool) { + Some(false) => crate::de::variant(value).map(Self::False), + Some(true) => crate::de::variant(value).map(Self::True), + _ => Ok(Self::Unknown(value)), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigModelCapabilities { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tools: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub temperature: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigModelVariantSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encoding: Option, + #[serde(flatten)] + pub extra: BTreeMap>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueVariantsItem { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub settings: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueCostObjectTier { + pub r#type: String, + pub size: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueCostObjectCache { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub write: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueCostObject { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tier: Option, + pub input: MoneyUSDPerMillionTokens, + pub output: MoneyUSDPerMillionTokens, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueCostArrayItemTier { + pub r#type: String, + pub size: i64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueCostArrayItemCache { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub write: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueCostArrayItem { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tier: Option, + pub input: MoneyUSDPerMillionTokens, + pub output: MoneyUSDPerMillionTokens, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoProvidersValueModelsValueCost { + Object(ConfigEntryDocumentInfoProvidersValueModelsValueCostObject), + Array(Vec), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValueLimit { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValueModelsValue { + #[serde(rename = "modelID", default, skip_serializing_if = "Option::is_none")] + pub model_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub r#type: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub family: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde( + rename = "releaseDate", + default, + skip_serializing_if = "Option::is_none" + )] + pub release_date: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compatibility: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub package: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub settings: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub capabilities: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variants: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disabled: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoProvidersValue { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub canonical: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub env: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub package: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compatibility: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub settings: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub body: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub models: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoExperimentalImageGenerateObjectModelObject { + #[serde(rename = "providerID")] + pub provider_id: String, + pub model: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoExperimentalImageGenerateObjectModel { + String(String), + Object(ConfigEntryDocumentInfoExperimentalImageGenerateObjectModelObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoExperimentalImageGenerateObject { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ConfigEntryDocumentInfoExperimentalImageGenerate { + Bool(bool), + Object(ConfigEntryDocumentInfoExperimentalImageGenerateObject), + /// A shape this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConfigEntryDocumentInfoExperimentalPoliciesItemAction { + ProviderUse, + ToolUse, + IntegrationConnect, + IntegrationUse, + McpUse, + SkillUse, + PluginUse, + WebsearchUse, + Unknown(String), +} + +impl ConfigEntryDocumentInfoExperimentalPoliciesItemAction { + pub fn as_str(&self) -> &str { + match self { + Self::ProviderUse => "provider.use", + Self::ToolUse => "tool.use", + Self::IntegrationConnect => "integration.connect", + Self::IntegrationUse => "integration.use", + Self::McpUse => "mcp.use", + Self::SkillUse => "skill.use", + Self::PluginUse => "plugin.use", + Self::WebsearchUse => "websearch.use", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConfigEntryDocumentInfoExperimentalPoliciesItemAction { + fn from(value: &str) -> Self { + match value { + "provider.use" => Self::ProviderUse, + "tool.use" => Self::ToolUse, + "integration.connect" => Self::IntegrationConnect, + "integration.use" => Self::IntegrationUse, + "mcp.use" => Self::McpUse, + "skill.use" => Self::SkillUse, + "plugin.use" => Self::PluginUse, + "websearch.use" => Self::WebsearchUse, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConfigEntryDocumentInfoExperimentalPoliciesItemAction { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoExperimentalPoliciesItemAction { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ConfigEntryDocumentInfoExperimentalPoliciesItemEffect { + Allow, + Deny, + Unknown(String), +} + +impl ConfigEntryDocumentInfoExperimentalPoliciesItemEffect { + pub fn as_str(&self) -> &str { + match self { + Self::Allow => "allow", + Self::Deny => "deny", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ConfigEntryDocumentInfoExperimentalPoliciesItemEffect { + fn from(value: &str) -> Self { + match value { + "allow" => Self::Allow, + "deny" => Self::Deny, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ConfigEntryDocumentInfoExperimentalPoliciesItemEffect { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ConfigEntryDocumentInfoExperimentalPoliciesItemEffect { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ConfigEntryDocumentInfoExperimentalPoliciesItem { + pub action: ConfigEntryDocumentInfoExperimentalPoliciesItemAction, + pub resource: String, + pub effect: ConfigEntryDocumentInfoExperimentalPoliciesItemEffect, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfoExperimental { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub portable_shell_scanner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub todo: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background_compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub media_blob: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub image_generate: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub schedules: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub artifacts: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subagent_depth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location_idle_timeout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub policies: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocumentInfo { + #[serde(rename = "$schema", default, skip_serializing_if = "Option::is_none")] + pub schema: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub shell: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_agent: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub update: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub share: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enterprise: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub username: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timezone: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub permissions: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub policies: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agents: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshots: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub watcher: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub formatter: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lsp: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub media: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_output: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mcp: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skills: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub commands: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub references: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub websearch: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plugins: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub worktree: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub warming: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub providers: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub experimental: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDocument { + pub r#type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option, + pub info: ConfigEntryDocumentInfo, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigEntryDirectory { + pub r#type: String, + pub path: AbsolutePath, +} + +/// `Config.Entry`, tagged by `type`. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ConfigEntry { + Document(ConfigEntryDocument), + Directory(ConfigEntryDirectory), + /// A member this client does not know, kept as it arrived. + Unknown(serde_json::Value), +} + +impl<'de> Deserialize<'de> for ConfigEntry { + fn deserialize>(deserializer: D) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + match value.get("type").and_then(serde_json::Value::as_str) { + Some("document") => crate::de::variant(value).map(Self::Document), + Some("directory") => crate::de::variant(value).map(Self::Directory), + _ => Ok(Self::Unknown(value)), + } + } +} + +/// Output of [`Client::config_get`]. +pub type ConfigGetOutput = Vec; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConfigShellOption { + pub path: String, + pub name: String, + pub acceptable: bool, +} + +/// Output of [`Client::config_shells`]. +pub type ConfigShellsOutput = Vec; + +/// Input of [`Client::experimental_config_update`]. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ExperimentalConfigUpdateInput { + pub shell: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InvalidRequestError { + #[serde(rename = "_tag")] + pub tag: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub field: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UnauthorizedError { + #[serde(rename = "_tag")] + pub tag: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct LocationNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub location: LocationPublicRef, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ServiceUnavailableError { + #[serde(rename = "_tag")] + pub tag: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub service: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct AgentNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "agentID")] + pub agent_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PluginNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "pluginID")] + pub plugin_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InvalidCursorError { + #[serde(rename = "_tag")] + pub tag: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "sessionID")] + pub session_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct MessageNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "sessionID")] + pub session_id: String, + #[serde(rename = "messageID")] + pub message_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ConflictError { + #[serde(rename = "_tag")] + pub tag: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resource: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CommandNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub command: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct CommandExecutionError { + #[serde(rename = "_tag")] + pub tag: String, + pub command: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SessionBusyError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "sessionID")] + pub session_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UnknownError { + #[serde(rename = "_tag")] + pub tag: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub r#ref: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormInvalidAnswerError { + #[serde(rename = "_tag")] + pub tag: String, + pub id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FormAlreadySettledError { + #[serde(rename = "_tag")] + pub tag: String, + pub id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct SkillNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub skill: SkillID, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct InstructionEntryValueTooLargeError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "actualBytes")] + pub actual_bytes: i64, + #[serde(rename = "maxBytes")] + pub max_bytes: i64, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProviderNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "providerID")] + pub provider_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ModelNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "providerID")] + pub provider_id: String, + #[serde(rename = "modelID")] + pub model_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct UnsupportedModelError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "providerID")] + pub provider_id: String, + #[serde(rename = "modelID")] + pub model_id: String, + pub capability: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ProviderRequestErrorReason { + Authentication, + RateLimit, + ContentFilter, + InvalidRequest, + Overloaded, + Provider, + Unknown(String), +} + +impl ProviderRequestErrorReason { + pub fn as_str(&self) -> &str { + match self { + Self::Authentication => "authentication", + Self::RateLimit => "rate_limit", + Self::ContentFilter => "content_filter", + Self::InvalidRequest => "invalid_request", + Self::Overloaded => "overloaded", + Self::Provider => "provider", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for ProviderRequestErrorReason { + fn from(value: &str) -> Self { + match value { + "authentication" => Self::Authentication, + "rate_limit" => Self::RateLimit, + "content_filter" => Self::ContentFilter, + "invalid_request" => Self::InvalidRequest, + "overloaded" => Self::Overloaded, + "provider" => Self::Provider, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for ProviderRequestErrorReason { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for ProviderRequestErrorReason { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ProviderRequestError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "providerID")] + pub provider_id: String, + pub reason: ProviderRequestErrorReason, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, + #[serde( + rename = "retryAfterMs", + default, + skip_serializing_if = "Option::is_none" + )] + pub retry_after_ms: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "integrationID")] + pub integration_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationAttemptNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "integrationID")] + pub integration_id: String, + #[serde(rename = "attemptID")] + pub attempt_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct IntegrationMethodNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "integrationID")] + pub integration_id: String, + #[serde(rename = "methodID")] + pub method_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct McpServerNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub server: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ForbiddenError { + #[serde(rename = "_tag")] + pub tag: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ProjectNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "projectID")] + pub project_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionSavedNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PermissionNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "requestID")] + pub request_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct FileNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub path: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct RpcError { + #[serde(rename = "_tag")] + pub tag: String, + pub r#type: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum RpcInternalErrorType { + RpcInternal, + RpcInvalidOutput, + Unknown(String), +} + +impl RpcInternalErrorType { + pub fn as_str(&self) -> &str { + match self { + Self::RpcInternal => "rpc.internal", + Self::RpcInvalidOutput => "rpc.invalid_output", + Self::Unknown(value) => value, + } + } +} + +impl From<&str> for RpcInternalErrorType { + fn from(value: &str) -> Self { + match value { + "rpc.internal" => Self::RpcInternal, + "rpc.invalid_output" => Self::RpcInvalidOutput, + _ => Self::Unknown(value.to_owned()), + } + } +} + +impl Serialize for RpcInternalErrorType { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for RpcInternalErrorType { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Ok(Self::from(value.as_str())) + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct RpcInternalError { + #[serde(rename = "_tag")] + pub tag: String, + pub r#type: RpcInternalErrorType, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "ptyID")] + pub pty_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct PtyFeatureUnsupportedError { + #[serde(rename = "_tag")] + pub tag: String, + pub feature: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ScheduleNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "scheduleID")] + pub schedule_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ArtifactNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "artifactID")] + pub artifact_id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct ShellNotFoundError { + #[serde(rename = "_tag")] + pub tag: String, + pub id: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeErrorData { + pub message: String, + #[serde( + rename = "forceRequired", + default, + skip_serializing_if = "Option::is_none" + )] + pub force_required: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct WorktreeError { + #[serde(rename = "_tag")] + pub tag: String, + pub name: String, + pub data: WorktreeErrorData, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct VcsInitNotSupportedError { + #[serde(rename = "_tag")] + pub tag: String, + #[serde(rename = "providerID")] + pub provider_id: String, + pub message: String, +} diff --git a/packages/cli-rs/crates/api/src/lib.rs b/packages/cli-rs/crates/api/src/lib.rs index c66aeeeff85..1324f19c930 100644 --- a/packages/cli-rs/crates/api/src/lib.rs +++ b/packages/cli-rs/crates/api/src/lib.rs @@ -2,6 +2,7 @@ pub mod client; pub mod client_mcp; +pub mod de; pub mod error; pub mod events; pub mod generated; diff --git a/packages/cli-rs/crates/api/src/query.rs b/packages/cli-rs/crates/api/src/query.rs index 5c79af4ff50..20344702b0d 100644 --- a/packages/cli-rs/crates/api/src/query.rs +++ b/packages/cli-rs/crates/api/src/query.rs @@ -1 +1,106 @@ -//! Query string encoding, bracket-encoded like `appendQuery` (F.2). +//! Query string encoding, bracket-encoded like `appendQuery` +//! (`packages/client/src/promise/generated/client.ts:2795-2810`). + +use serde_json::Value; + +/// Appends `value` under `key`: `null` as `"null"`, arrays as repeated keys, objects as `key[child]`, +/// and scalars as JavaScript's `String(value)` would write them. +pub fn append(pairs: &mut Vec<(String, String)>, key: &str, value: &Value) { + match value { + Value::Array(items) => items.iter().for_each(|item| append(pairs, key, item)), + Value::Object(map) => map + .iter() + .for_each(|(child, item)| append(pairs, &format!("{key}[{child}]"), item)), + _ => pairs.push((key.to_owned(), js_string(value))), + } +} + +/// `String(value)` for a JSON value. Objects and arrays never reach here from [`append`]. +pub fn js_string(value: &Value) -> String { + match value { + Value::Null => "null".to_owned(), + Value::Bool(value) => value.to_string(), + Value::String(value) => value.clone(), + Value::Number(number) => match (number.as_i64(), number.as_u64(), number.as_f64()) { + (Some(value), _, _) => value.to_string(), + (_, Some(value), _) => value.to_string(), + (_, _, Some(value)) => js_number(value), + _ => number.to_string(), + }, + Value::Array(items) => items.iter().map(js_string).collect::>().join(","), + Value::Object(_) => "[object Object]".to_owned(), + } +} + +/// JavaScript's `Number.prototype.toString()`: shortest round-trip digits, with exponent notation +/// outside `[1e-6, 1e21)`. +fn js_number(value: f64) -> String { + if value == 0.0 { + return "0".to_owned(); + } + let magnitude = value.abs(); + if (1e-6..1e21).contains(&magnitude) { + return format!("{value}"); + } + // Rust writes `1e21` and `1e-7`; JavaScript writes `1e+21` and `1e-7`. + let text = format!("{value:e}"); + match text.split_once('e') { + Some((mantissa, exponent)) if !exponent.starts_with('-') => { + format!("{mantissa}e+{exponent}") + } + _ => text, + } +} + +/// The `application/x-www-form-urlencoded` form of `pairs`, as `URLSearchParams` serializes it. +pub fn encode(pairs: &[(String, String)]) -> String { + let mut serializer = url::form_urlencoded::Serializer::new(String::new()); + for (key, value) in pairs { + serializer.append_pair(key, value); + } + serializer.finish() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn query(key: &str, value: Value) -> String { + let mut pairs = Vec::new(); + append(&mut pairs, key, &value); + encode(&pairs) + } + + #[test] + fn nested_objects_use_brackets() { + assert_eq!( + query( + "location", + json!({ "directory": "/a b", "workspace": { "id": "w" } }) + ), + "location%5Bdirectory%5D=%2Fa+b&location%5Bworkspace%5D%5Bid%5D=w" + ); + } + + #[test] + fn arrays_repeat_and_null_is_written() { + assert_eq!(query("types", json!(["a", "b"])), "types=a&types=b"); + assert_eq!(query("cursor", Value::Null), "cursor=null"); + } + + #[test] + fn numbers_match_javascript() { + let cases = [ + (1.0, "1"), + (1.5, "1.5"), + (1e21, "1e+21"), + (1e-7, "1e-7"), + (0.000001, "0.000001"), + (-0.0, "0"), + ]; + for (value, text) in cases { + assert_eq!(js_string(&json!(value)), text, "{value}"); + } + } +} diff --git a/packages/cli-rs/crates/api/src/transport.rs b/packages/cli-rs/crates/api/src/transport.rs index 2e4f36f4a2e..4fb4988d289 100644 --- a/packages/cli-rs/crates/api/src/transport.rs +++ b/packages/cli-rs/crates/api/src/transport.rs @@ -1 +1,132 @@ -//! The transport trait and its `reqwest` implementation (F.2). +//! The transport trait and its `reqwest` implementation. + +use std::future::Future; +use std::marker::PhantomData; +use std::pin::Pin; + +use bytes::Bytes; +use futures_util::{Stream, StreamExt}; + +/// A future a transport returns. +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// A response body as a stream of chunks. +pub type BodyStream = Pin> + Send>>; + +/// One HTTP request, fully prepared by the client. +#[derive(Debug, Clone)] +pub struct Request { + pub method: &'static str, + pub url: url::Url, + /// Header names are lowercase; each name appears once. + pub headers: Vec<(String, String)>, + pub body: Option, +} + +/// One HTTP response. The body is read lazily, so server-sent events can stream. +pub struct Response { + pub status: u16, + /// Header names are lowercase. + pub headers: Vec<(String, String)>, + pub body: BodyStream, +} + +impl Response { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) + } + + /// Reads the whole body. + pub async fn bytes(mut self) -> Result { + let mut buffer = Vec::new(); + while let Some(chunk) = self.body.next().await { + buffer.extend_from_slice(&chunk?); + } + Ok(Bytes::from(buffer)) + } +} + +impl std::fmt::Debug for Response { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Response") + .field("status", &self.status) + .field("headers", &self.headers) + .finish_non_exhaustive() + } +} + +/// Sends requests. The `reqwest` implementation talks to a server; tests and P-APP use in-memory ones. +pub trait Transport: Send + Sync { + /// Sends `request`. An error is a transport failure (no response), described as text. + fn send(&self, request: Request) -> BoxFuture<'_, Result>; +} + +/// The checked response of a server-sent events endpoint: status and content type are verified, and +/// the body has not been read. F.3 parses it into events of type `T`. +pub struct SseResponse { + pub response: Response, + event: PhantomData T>, +} + +impl SseResponse { + pub fn new(response: Response) -> Self { + Self { + response, + event: PhantomData, + } + } +} + +impl std::fmt::Debug for SseResponse { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("SseResponse").field(&self.response).finish() + } +} + +/// The `reqwest` transport, with rustls. +#[derive(Debug, Clone, Default)] +pub struct Reqwest { + client: reqwest::Client, +} + +impl Reqwest { + pub fn new(client: reqwest::Client) -> Self { + Self { client } + } +} + +impl Transport for Reqwest { + fn send(&self, request: Request) -> BoxFuture<'_, Result> { + Box::pin(async move { + let method = reqwest::Method::from_bytes(request.method.as_bytes()) + .map_err(|error| error.to_string())?; + let mut builder = self.client.request(method, request.url); + for (name, value) in &request.headers { + builder = builder.header(name, value); + } + if let Some(body) = request.body { + builder = builder.body(body); + } + let response = builder.send().await.map_err(|error| error.to_string())?; + let headers = response + .headers() + .iter() + .filter_map(|(name, value)| { + Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned())) + }) + .collect(); + Ok(Response { + status: response.status().as_u16(), + headers, + body: Box::pin( + response + .bytes_stream() + .map(|chunk| chunk.map_err(|error| error.to_string())), + ), + }) + }) + } +} diff --git a/packages/cli-rs/script/gen/api.ts b/packages/cli-rs/script/gen/api.ts new file mode 100644 index 00000000000..3fcc769070b --- /dev/null +++ b/packages/cli-rs/script/gen/api.ts @@ -0,0 +1,177 @@ +// Generates crates/api/src/generated from ClientApi, with the options of the Promise client +// (packages/client/script/generate.ts). The type mapping is in docs/F.2.md. +import { compile, type Endpoint } from "@opencode/httpapi-codegen" +import { ClientApi, clientNamespace, groupNames, promiseOmitEndpoints } from "@opencode/protocol/client" +import { Schema, SchemaAST, SchemaRepresentation } from "effect" +import { HttpApiSchema } from "effect/http-api" +import { emitMethod, type Field, type Method } from "../rust/methods.ts" +import { pascal, Types } from "../rust/types.ts" + +const root = new URL("..", import.meta.url).pathname.replace(/script\/$/, "") +const directory = `${root}crates/api/src/generated` +const resolveEncoding = SchemaAST.resolveAt<{ readonly _tag: string }>("~httpApiEncoding") +const resolveStatus = SchemaAST.resolveAt("httpApiStatus") + +const contract = compile(ClientApi, { groupNames, omitEndpoints: promiseOmitEndpoints, namespace: clientNamespace }) + +type Root = { readonly ast: SchemaAST.AST } +const roots: Array = [] +const add = (ast: SchemaAST.AST) => { + const item = { ast } + roots.push(item) + return item +} + +const plans = contract.groups.flatMap((group) => + group.endpoints.map((endpoint) => { + const opaque = endpoint.payloads[0] !== undefined && !flattenable(endpoint.payloads[0]) + const binaryBody = endpoint.payloads[0] !== undefined && resolveEncoding(endpoint.payloads[0].ast)?._tag === "Uint8Array" + const sources = { params: endpoint.params, query: endpoint.query, headers: endpoint.headers, payload: endpoint.payloads[0] } + const fields = endpoint.input.map((field) => { + const schema = sources[field.source]! + if (opaque && field.source === "payload") return { ...field, root: binaryBody ? undefined : add(Schema.toEncoded(schema).ast) } + const ast = (field.source === "query" ? Schema.toType(schema) : Schema.toEncoded(schema)).ast + if (!SchemaAST.isObjects(ast)) throw new Error(`Input schema must be a struct: ${endpoint.operation.name}`) + const property = ast.propertySignatures.find((item) => item.name === field.name)! + return { ...field, root: add(property.type) } + }) + const wildcard = endpoint.endpoint.path.endsWith("*") + ? [{ name: endpoint.input.some((field) => field.name === "path") ? "wildcard" : "path", source: "wildcard" as const, optional: false, root: undefined }] + : [] + const success = endpoint.successes[0] + const kind = streamKind(success) + const output = (() => { + if (kind === "sse") return add(sseData(success)) + if (HttpApiSchema.isNoContent(success.ast) || resolveEncoding(success.ast)?._tag === "Uint8Array") return undefined + const ast = Schema.toEncoded(success).ast + if (!endpoint.unwrapData) return add(ast) + if (!SchemaAST.isObjects(ast)) throw new Error(`Invalid data envelope: ${endpoint.operation.name}`) + return add(ast.propertySignatures.find((item) => item.name === "data")!.type) + })() + for (const error of endpoint.errors) add(Schema.toEncoded(error.schema).ast) + const successKind: Method["success"] = + kind === "sse" + ? "sse" + : HttpApiSchema.isNoContent(success.ast) + ? "empty" + : resolveEncoding(success.ast)?._tag === "Uint8Array" + ? "binary" + : endpoint.unwrapData + ? "data" + : "json" + return { group, endpoint, opaque, binaryBody, fields: [...fields, ...wildcard], output, success: successKind } + }), +) + +const document = SchemaRepresentation.toRepresentations( + normalize(roots.map((item) => item.ast)) as [SchemaAST.AST, ...Array], +) +const representation = new Map(roots.map((item, index) => [item, document.representations[index]])) +const types = new Types(document.references) +for (const name of ["Client", "Call", "Error", "RequestOptions", "SseResponse"]) types.name(name) + +const methods = plans.map((plan) => + emitMethod(types, { + group: plan.group, + endpoint: plan.endpoint, + prefix: `${pascal(plan.group.identifier)}${plan.endpoint.clientPath.map(pascal).join("")}`, + opaque: plan.opaque, + binaryBody: plan.binaryBody, + fields: plan.fields.map( + (field): Field => ({ + name: field.name, + source: field.source, + optional: field.optional, + representation: field.root === undefined ? undefined : representation.get(field.root), + }), + ), + success: plan.success, + output: plan.output === undefined ? undefined : representation.get(plan.output), + successStatus: resolveStatus(plan.endpoint.successes[0].ast) ?? 200, + }), +) +// Declared error bodies get types too, for `DeclaredError::decode`. +for (const ref of Object.keys(document.references)) { + if (/Error$/.test(ref)) types.type({ _tag: "Reference", $ref: ref }, ref) +} + +const header = "// Generated by script/gen/api.ts from ClientApi. Do not edit.\n" +await Bun.write( + `${directory}/types.rs`, + `${header}#![allow(clippy::all, clippy::pedantic, non_camel_case_types)]\n\nuse std::collections::BTreeMap;\n\nuse serde::{Deserialize, Serialize};\n\n${types.items.join("\n\n")}\n`, +) +await Bun.write( + `${directory}/methods.rs`, + `${header}#![allow(clippy::all, clippy::pedantic)]\n\nuse super::types::*;\nuse crate::client::{Call, Client, RequestOptions};\nuse crate::error::Error;\nuse crate::transport::SseResponse;\n\nimpl Client {\n${methods.join("\n\n")}\n}\n`, +) +await Bun.write( + `${directory}/mod.rs`, + `${header}//! Types and methods generated from \`ClientApi\` by \`script/gen/api.ts\` (F.2).\n\nmod methods;\npub mod types;\n\npub use types::*;\n\n/// Endpoints in the generated client.\npub const ENDPOINTS: usize = ${plans.length};\n`, +) +const format = Bun.spawnSync(["rustfmt", "--edition", "2024", `${directory}/mod.rs`], { stdout: "inherit", stderr: "inherit" }) +if (format.exitCode !== 0) process.exit(format.exitCode ?? 1) +console.log(`api: ${plans.length} endpoints, ${types.items.length} items`) + +function flattenable(schema: Schema.Top) { + const ast = Schema.toType(schema).ast + return SchemaAST.isObjects(ast) && ast.indexSignatures.length === 0 +} + +function streamKind(schema: Schema.Top) { + if (!("_tag" in schema)) return undefined + if (schema._tag === "StreamSse") return "sse" + if (schema._tag === "StreamUint8Array") throw new Error("Byte streams are not supported") + return undefined +} + +// The encoded data schema of an SSE endpoint, as `streamEncodedDataSchema` in httpapi-codegen. +function sseData(schema: Endpoint["successes"][number]) { + const events = (schema as unknown as { readonly events: Schema.Top }).events.ast + if (!SchemaAST.isObjects(events)) throw new Error("Invalid SSE data schema") + const data = events.propertySignatures.find((field) => field.name === "data")!.type + // oxlint-disable-next-line no-restricted-globals -- Effect exposes this runtime helper without a public type. + const replaceEncoding = Reflect.get(SchemaAST, "replaceEncoding") as (ast: SchemaAST.AST, encoding: undefined) => SchemaAST.AST + return Schema.toEncoded(Schema.make(replaceEncoding(data, undefined))).ast +} + +// Declarations become their fields or JSON, as `codegenAsts` in httpapi-codegen, and equal named +// schemas share one reference. +function normalize(input: ReadonlyArray) { + const cache = new WeakMap() + const references = new Map() + const recur = (ast: SchemaAST.AST): SchemaAST.AST => { + const cached = cache.get(ast) + if (cached !== undefined) return cached + const identifier = SchemaAST.resolveIdentifier(ast) + const output = step(ast) + const key = + identifier === undefined + ? undefined + : `${identifier}\0${ast.context?.isOptional === true}\0${JSON.stringify(SchemaRepresentation.toJson(SchemaRepresentation.toRepresentation(output)))}` + const reference = key === undefined ? undefined : references.get(key) + if (reference !== undefined) { + cache.set(ast, reference) + return reference + } + cache.set(ast, output) + if (key !== undefined) references.set(key, output) + return output + } + const step = (ast: SchemaAST.AST): SchemaAST.AST => { + if (SchemaAST.isDeclaration(ast) && ast.annotations?.toCode === undefined) { + const representation = ast.annotations?.representation + if (typeof representation === "object" && representation !== null && "id" in representation && representation.id === "effect/schema/Json") { + return Schema.Json.ast + } + if (ast.annotations?.["~constructor"] !== undefined && ast.typeParameters[0] !== undefined) { + const identifier = SchemaAST.resolveIdentifier(ast) + const fields = recur(ast.typeParameters[0]) + if (identifier === undefined) return fields + return Schema.make(fields).annotate({ identifier }).ast + } + } + if (!("recur" in ast) || typeof ast.recur !== "function") return ast + return ast.recur(recur) + } + return input.map(recur) +} diff --git a/packages/cli-rs/script/rust/methods.ts b/packages/cli-rs/script/rust/methods.ts new file mode 100644 index 00000000000..eac8dd877d5 --- /dev/null +++ b/packages/cli-rs/script/rust/methods.ts @@ -0,0 +1,125 @@ +// Emits one `Client` method per endpoint, following docs/F.2.md. +import type { Endpoint, Group } from "@opencode/httpapi-codegen" +import type { SchemaRepresentation } from "effect" +import { pascal, snake, type Types } from "./types.ts" + +export type Field = { + readonly name: string + readonly source: "params" | "query" | "headers" | "payload" | "wildcard" + readonly optional: boolean + /** Undefined for the wildcard, which is always a string. */ + readonly representation: SchemaRepresentation.Representation | undefined +} + +export type Method = { + readonly group: Group + readonly endpoint: Endpoint + readonly prefix: string + readonly fields: ReadonlyArray + readonly opaque: boolean + readonly binaryBody: boolean + readonly success: "json" | "data" | "empty" | "binary" | "sse" + readonly output: SchemaRepresentation.Representation | undefined + readonly successStatus: number +} + +export function emitMethod(types: Types, method: Method) { + const name = snake([...method.group.path, ...method.endpoint.clientPath].map((part) => snake(part).replace(/^r#/, "")).join("_")) + const idents = new Map() + for (const field of method.fields) { + let ident = snake(field.name) + for (let i = 2; [...idents.values()].includes(ident); i++) ident = `${snake(field.name)}_${i}` + idents.set(field, ident) + } + const input = method.fields.length === 0 ? undefined : types.name(`${method.prefix}Input`) + if (input !== undefined) { + const lines = method.fields.map((field) => { + const hint = `${method.prefix}Input${pascal(field.name)}` + const type = + method.binaryBody && field.source === "payload" + ? "bytes::Bytes" + : field.representation === undefined + ? "String" + : (types.field(field.representation, field.optional, hint)?.type ?? "()") + return { line: ` pub ${idents.get(field)}: ${type},`, type } + }) + const defaults = lines.every((line) => types.isDefault(line.type) || line.type === "bytes::Bytes") + types.items.push( + `/// Input of [\`Client::${name.replace(/^r#/, "")}\`].\n#[derive(Debug, Clone, PartialEq${defaults ? ", Default" : ""})]\npub struct ${input} {\n${lines.map((line) => line.line).join("\n")}\n}`, + ) + } + const outputName = types.name(`${method.prefix}Output`) + const output = (() => { + if (method.success === "empty") return "()" + if (method.success === "binary") return "bytes::Bytes" + const representation = method.output! + if (representation._tag === "Objects" && representation.propertySignatures.length > 0) { + return types.objects(representation, outputName, outputName) + } + const type = types.type(representation, outputName) + types.items.push(`/// Output of [\`Client::${name.replace(/^r#/, "")}\`].\npub type ${outputName} = ${type};`) + return outputName + })() + + const path = pathTemplate(method, idents) + const access = (field: Field) => `input.${idents.get(field)}` + const statements = method.fields.flatMap((field) => { + const call = + field.source === "query" + ? `call.query(${JSON.stringify(field.name)}, VALUE)?;` + : field.source === "headers" + ? `call.header(${JSON.stringify(field.name)}, VALUE)?;` + : field.source === "payload" + ? method.binaryBody + ? `call.bytes(${access(field)}.clone());` + : method.opaque + ? "call.json(VALUE)?;" + : `call.field(${JSON.stringify(field.name)}, VALUE)?;` + : undefined + if (call === undefined) return [] + if (field.optional) return [`if let Some(value) = &${access(field)} {\n ${call.replace("VALUE", "value")}\n }`] + return [call.replace("VALUE", `&${access(field)}`)] + }) + if (method.endpoint.payloads.length > 0 && !method.binaryBody && !method.opaque) statements.unshift("call.object();") + const declared = [...new Set(method.endpoint.errors.map((error) => error.status))] + const send = + method.success === "sse" + ? "self.sse(call, options).await" + : method.success === "data" + ? "self.data(call, options).await" + : method.success === "empty" + ? "self.empty(call, options).await" + : method.success === "binary" + ? "self.binary(call, options).await" + : "self.json(call, options).await" + const returns = method.success === "sse" ? `SseResponse<${output}>` : output + const argument = input === undefined ? "" : `input: &${input}, ` + const mutable = statements.length === 0 ? "" : "mut " + return ` /// \`${method.endpoint.endpoint.method} ${method.endpoint.endpoint.path}\` (\`${method.endpoint.operation.name}\`) + pub async fn ${name}(&self, ${argument}options: &RequestOptions) -> Result<${returns}, Error> { + let ${mutable}call = Call::new(${JSON.stringify(method.endpoint.endpoint.method)}, ${path}, ${method.successStatus}, &[${declared.join(", ")}]); +${statements.map((statement) => ` ${statement}`).join("\n")} + ${send} + }` +} + +function pathTemplate(method: Method, idents: Map) { + const params = new Map(method.fields.filter((field) => field.source === "params").map((field) => [field.name, field])) + const wildcard = method.fields.find((field) => field.source === "wildcard") + const source = wildcard === undefined ? method.endpoint.endpoint.path : method.endpoint.endpoint.path.slice(0, -1) + const args: Array = [] + const template = source + .split(/(:[A-Za-z_][A-Za-z0-9_]*)/g) + .filter(Boolean) + .map((segment) => { + if (!segment.startsWith(":")) return segment.replaceAll("{", "{{").replaceAll("}", "}}") + const field = params.get(segment.slice(1)) + if (field === undefined) throw new Error(`Missing path parameter: ${segment}`) + args.push(`crate::client::path_param(&input.${idents.get(field)})?`) + return "{}" + }) + .join("") + if (wildcard !== undefined) args.push(`crate::client::path_wildcard(&input.${idents.get(wildcard)})`) + if (args.length === 0) return `${JSON.stringify(template)}.to_owned()` + return `format!(${JSON.stringify(template + (wildcard === undefined ? "" : "{}"))}, ${args.join(", ")})` +} diff --git a/packages/cli-rs/script/rust/types.ts b/packages/cli-rs/script/rust/types.ts new file mode 100644 index 00000000000..ff889380dbe --- /dev/null +++ b/packages/cli-rs/script/rust/types.ts @@ -0,0 +1,401 @@ +// Emits Rust types from Effect schema representations, following docs/F.2.md. +import type { SchemaRepresentation } from "effect" + +type R = SchemaRepresentation.Representation +type Objects = SchemaRepresentation.Objects + +const keywords = new Set( + "as async await break const continue crate dyn else enum extern false fn for gen if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while abstract become box do final macro override priv try typeof unsized virtual yield".split( + " ", + ), +) + +export function pascal(value: string) { + const name = value + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .map((part) => `${part[0].toUpperCase()}${part.slice(1)}`) + .join("") + return /^[A-Za-z]/.test(name) ? name : `V${name}` +} + +export function snake(value: string) { + const name = value + .replace(/([a-z0-9])([A-Z])/g, "$1_$2") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2") + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .join("_") + .toLowerCase() + const safe = /^[a-z_]/.test(name) ? name : `v${name}` + if (safe === "self" || safe === "super" || safe === "crate" || safe === "_") return `${safe}_` + return keywords.has(safe) ? `r#${safe}` : safe +} + +/** Turns representations into Rust items. `type(r, hint)` returns a Rust type expression and emits what it names. */ +export class Types { + readonly items: Array = [] + private readonly names = new Set() + private readonly referenced = new Map() + private readonly defaultable = new Set() + private readonly visiting = new Set() + + constructor(private readonly references: SchemaRepresentation.References) {} + + /** Reserves a unique type name based on `seed`. */ + name(seed: string) { + const base = pascal(seed) + let name = base + for (let index = 2; this.names.has(name); index++) name = `${base}${index}` + this.names.add(name) + return name + } + + deref(r: R): R { + if (r._tag === "Reference") return this.deref(this.references[r.$ref]) + if (r._tag === "Suspend") return this.deref(r.thunk) + return r + } + + isDefault(type: string) { + return ( + /^(Option|Vec|BTreeMap) { + if (resolved._tag === "Objects" && resolved.propertySignatures.length > 0) { + const name = this.name(ref) + this.referenced.set(ref, name) + return this.objects(resolved, name, name) + } + if (resolved._tag === "Union") { + const shape = this.union(resolved, ref, ref) + return shape + } + if (resolved._tag === "String" || resolved._tag === "TemplateLiteral") { + const name = this.name(ref) + this.defaultable.add(name) + this.items.push(newtype(name, ref)) + return name + } + const type = this.type(target, ref) + if (/^[A-Z][A-Za-z0-9]*$/.test(type) && !["String"].includes(type)) return type + const name = this.name(ref) + if (this.isDefault(type)) this.defaultable.add(name) + this.items.push(`/// \`${ref}\`\npub type ${name} = ${type};`) + return name + })() + this.visiting.delete(ref) + this.referenced.set(ref, result) + return result + } + + private arrays(r: SchemaRepresentation.Arrays, hint: string): string { + if (r.elements.length === 0 && r.rest.length === 1) return `Vec<${this.type(r.rest[0], `${hint}Item`)}>` + if (r.rest.length === 0 && r.elements.every((element) => !element.isOptional)) { + return `(${r.elements.map((element, index) => `${this.type(element.type, `${hint}${index}`)},`).join(" ")})` + } + return "Vec" + } + + /** A struct, or a map for an object with only index signatures. */ + objects(r: Objects, name: string, hint: string): string { + const index = r.indexSignatures[0] + const value = index === undefined ? undefined : this.type(index.type, `${hint}Value`) + if (r.propertySignatures.length === 0 && value !== undefined) { + this.names.delete(name) + return `BTreeMap` + } + const used = new Set() + const fields = r.propertySignatures.flatMap((property) => { + const key = String(property.name) + const field = this.field(property.type, property.isOptional, `${hint}${pascal(key)}`) + if (field === undefined) return [] + let ident = snake(key) + for (let i = 2; used.has(ident); i++) ident = `${snake(key)}_${i}` + used.add(ident) + const plain = ident.replace(/^r#/, "") + const attrs = [plain === key ? undefined : `rename = ${JSON.stringify(key)}`, ...field.attrs].filter(Boolean) + const doc = docOf(property.annotations) + return [ + `${doc}${attrs.length ? ` #[serde(${attrs.join(", ")})]\n` : ""} pub ${ident}: ${field.type},`, + field.type, + ] + }) + const lines = fields.filter((_, i) => i % 2 === 0) + const types = fields.filter((_, i) => i % 2 === 1) + if (value !== undefined) { + lines.push(` #[serde(flatten)]\n pub extra: BTreeMap,`) + types.push("BTreeMap") + } + const defaults = types.every((type) => this.isDefault(type) || type === "BTreeMap") + if (defaults) this.defaultable.add(name) + this.items.push( + `#[derive(Debug, Clone, PartialEq, Serialize, Deserialize${defaults ? ", Default" : ""})]\npub struct ${name} {\n${lines.join("\n")}\n}`, + ) + return name + } + + /** A field type with its serde attributes, or undefined for a field that can only be absent. */ + field(r: R, optional: boolean, hint: string) { + const members = r._tag === "Union" ? flatten(r.types) : [r] + const present = members.filter((member) => !["Undefined", "Never", "Void"].includes(this.deref(member)._tag)) + if (present.length === 0) return undefined + const nullable = present.some((member) => this.deref(member)._tag === "Null") + const rest = present.filter((member) => this.deref(member)._tag !== "Null") + const inner = + rest.length === 0 + ? "()" + : rest.length === 1 + ? this.type(rest[0], hint) + : this.union({ ...(r as SchemaRepresentation.Union), types: rest }, hint, undefined) + if (optional && nullable) { + return { + type: `Option>`, + attrs: ['default', 'deserialize_with = "crate::de::double_option"', 'skip_serializing_if = "Option::is_none"'], + } + } + if (optional) return { type: `Option<${inner}>`, attrs: ["default", 'skip_serializing_if = "Option::is_none"'] } + if (nullable) return { type: `Option<${inner}>`, attrs: ["default"] } + return { type: inner, attrs: [] as Array } + } + + /** A union. `ref` names the reference it defines, if any. */ + union(r: SchemaRepresentation.Union, hint: string, ref: string | undefined): string { + const members = flatten(r.types).filter((member) => !["Undefined", "Never", "Void"].includes(this.deref(member)._tag)) + const nullable = members.some((member) => this.deref(member)._tag === "Null") + const rest = members.filter((member) => this.deref(member)._tag !== "Null") + const wrap = (type: string) => (nullable ? `Option<${type}>` : type) + if (rest.length === 0) return "()" + if (rest.length === 1) return wrap(this.type(rest[0], hint)) + const resolved = rest.map((member) => this.deref(member)) + if (resolved.every((member) => member._tag === "Literal")) { + const values = resolved.map((member) => (member as SchemaRepresentation.Literal).literal) + if (values.every((value) => typeof value === "string")) { + return wrap(this.literals(values as Array, ref ?? hint, ref)) + } + if (values.every((value) => typeof value === "boolean")) return wrap("bool") + if (values.every((value) => typeof value === "number")) + return wrap(values.every(Number.isInteger) ? "i64" : "f64") + return wrap("serde_json::Value") + } + if (resolved.every((member) => member._tag === "Literal" || member._tag === "String")) return wrap("String") + if (resolved.every((member) => member._tag === "Objects")) { + const tagged = this.discriminator(resolved as Array) + if (tagged !== undefined) return wrap(this.tagged(rest, tagged, ref ?? hint, ref)) + } + return wrap(this.untagged(rest, ref ?? hint, ref)) + } + + private literals(values: Array, seed: string, ref: string | undefined) { + const name = this.name(seed) + const variants = uniqueVariants(values.map((value) => pascal(value))) + const doc = ref === undefined ? "" : `/// \`${ref}\`\n` + this.items.push( + `${doc}#[derive(Debug, Clone, PartialEq, Eq, Hash)]\npub enum ${name} {\n${variants.map((variant) => ` ${variant},`).join("\n")}\n Unknown(String),\n}\n\nimpl ${name} {\n pub fn as_str(&self) -> &str {\n match self {\n${variants.map((variant, i) => ` Self::${variant} => ${JSON.stringify(values[i])},`).join("\n")}\n Self::Unknown(value) => value,\n }\n }\n}\n\nimpl From<&str> for ${name} {\n fn from(value: &str) -> Self {\n match value {\n${variants.map((variant, i) => ` ${JSON.stringify(values[i])} => Self::${variant},`).join("\n")}\n _ => Self::Unknown(value.to_owned()),\n }\n }\n}\n\nimpl Serialize for ${name} {\n fn serialize(&self, serializer: S) -> Result {\n serializer.serialize_str(self.as_str())\n }\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize>(deserializer: D) -> Result {\n let value = String::deserialize(deserializer)?;\n Ok(Self::from(value.as_str()))\n }\n}`, + ) + return name + } + + /** The discriminator of an object union: a required field whose literal values tell every member apart. */ + private discriminator(members: Array) { + const tags = (member: Objects, key: string) => { + const property = member.propertySignatures.find((p) => p.name === key) + if (property === undefined || property.isOptional) return undefined + return this.tagValues(property.type) + } + const keys = members[0].propertySignatures.map((p) => String(p.name)) + const ordered = [...keys.filter((key) => key === "type" || key === "_tag"), ...keys.filter((key) => key !== "type" && key !== "_tag")] + for (const key of ordered) { + const values = members.map((member) => tags(member, key)) + if (values.some((value) => value === undefined)) continue + const exact = values.flatMap((value) => value!.exact.map((item) => JSON.stringify(item))) + if (new Set(exact).size !== exact.length) continue + const kinds = new Set(values.flatMap((value) => value!.exact.map((item) => typeof item))) + if (kinds.size > 1 || (kinds.size === 1 && !kinds.has("string") && !kinds.has("boolean"))) continue + if (kinds.has("boolean") && values.some((value) => value!.prefixes.length > 0)) continue + return { key, values: values as Array<{ exact: Array; prefixes: Array }> } + } + return undefined + } + + private tagValues(r: R): { exact: Array; prefixes: Array } | undefined { + const resolved = this.deref(r) + if (resolved._tag === "Literal") { + if (typeof resolved.literal !== "string" && typeof resolved.literal !== "boolean") return undefined + return { exact: [resolved.literal], prefixes: [] } + } + if (resolved._tag === "TemplateLiteral") { + const [head, ...tail] = resolved.parts + if (head?._tag !== "Literal" || typeof head.literal !== "string") return undefined + if (tail.length !== 1 || this.deref(tail[0])._tag !== "String") return undefined + return { exact: [], prefixes: [head.literal] } + } + if (resolved._tag === "Union") { + const parts = flatten(resolved.types).map((member) => this.tagValues(member)) + if (parts.some((part) => part === undefined)) return undefined + return { exact: parts.flatMap((part) => part!.exact), prefixes: parts.flatMap((part) => part!.prefixes) } + } + return undefined + } + + private tagged( + members: Array, + tag: { key: string; values: Array<{ exact: Array; prefixes: Array }> }, + seed: string, + ref: string | undefined, + ) { + const name = this.name(seed) + const variants = uniqueVariants( + tag.values.map((value, index) => { + if (value.exact.length === 1) return pascal(String(value.exact[0])) + if (value.prefixes.length > 0 && value.exact.length === 0) return pascal(value.prefixes[0]) + const member = members[index] + return member._tag === "Reference" ? pascal(member.$ref.split(".").at(-1)!) : `Variant${index + 1}` + }), + ) + const types = members.map((member, index) => { + const resolved = this.deref(member) + if (member._tag === "Reference") return this.type(member, `${name}${variants[index]}`) + return this.objects(resolved as Objects, this.name(`${name}${variants[index]}`), `${name}${variants[index]}`) + }) + const kind = typeof tag.values.find((value) => value.exact.length > 0)?.exact[0] + const access = kind === "boolean" ? "as_bool" : "as_str" + const arms = tag.values.flatMap((value, index) => [ + ...(value.exact.length === 0 + ? [] + : [` ${value.exact.map((item) => `Some(${JSON.stringify(item)})`).join(" | ")} => crate::de::variant(value).map(Self::${variants[index]}),`]), + ...value.prefixes.map( + (prefix) => + ` Some(tag) if tag.starts_with(${JSON.stringify(prefix)}) => crate::de::variant(value).map(Self::${variants[index]}),`, + ), + ]) + const ordered = [...arms.filter((arm) => !arm.includes("starts_with")), ...arms.filter((arm) => arm.includes("starts_with"))] + const doc = ref === undefined ? "" : `/// \`${ref}\`, tagged by \`${tag.key}\`.\n` + this.items.push( + `${doc}#[derive(Debug, Clone, PartialEq, Serialize)]\n#[serde(untagged)]\npub enum ${name} {\n${variants.map((variant, index) => ` ${variant}(${types[index]}),`).join("\n")}\n /// A member this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize>(deserializer: D) -> Result {\n let value = serde_json::Value::deserialize(deserializer)?;\n match value.get(${JSON.stringify(tag.key)}).and_then(serde_json::Value::${access}) {\n${ordered.join("\n")}\n _ => Ok(Self::Unknown(value)),\n }\n }\n}`, + ) + return name + } + + private untagged(members: Array, seed: string, ref: string | undefined) { + const name = this.name(seed) + const seen = new Map() + for (const member of members) { + const resolved = this.deref(member) + const variant = + member._tag === "Reference" && resolved._tag !== "String" + ? pascal(member.$ref.split(".").at(-1)!) + : resolved._tag === "Literal" + ? typeof resolved.literal === "string" + ? "String" + : typeof resolved.literal === "boolean" + ? "Bool" + : "Number" + : ({ String: "String", TemplateLiteral: "String", Boolean: "Bool", Number: "Number", Arrays: "Array", Objects: "Object" } as Record)[ + resolved._tag + ] ?? "Value" + const type = + resolved._tag === "Literal" + ? typeof resolved.literal === "string" + ? "String" + : typeof resolved.literal === "boolean" + ? "bool" + : "f64" + : this.type(member, `${name}${variant}`) + if ([...seen.values()].includes(type)) continue + let unique = variant + for (let index = 2; seen.has(unique); index++) unique = `${variant}${index}` + seen.set(unique, type) + } + const doc = ref === undefined ? "" : `/// \`${ref}\`\n` + this.items.push( + `${doc}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum ${name} {\n${[...seen].map(([variant, type]) => ` ${variant}(${type}),`).join("\n")}\n /// A shape this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}`, + ) + return name + } +} + +function flatten(types: ReadonlyArray): Array { + return types.flatMap((type) => (type._tag === "Union" ? flatten(type.types) : [type])) +} + +function integer(r: SchemaRepresentation.Number) { + const visit = (checks: ReadonlyArray): boolean => + checks.some((check) => + check._tag === "Filter" ? check.representation?.id === "effect/schema/isInt" : visit(check.checks), + ) + return visit(r.checks) +} + +function literalType(literal: unknown) { + if (typeof literal === "string") return "String" + if (typeof literal === "boolean") return "bool" + if (typeof literal === "number") return Number.isInteger(literal) ? "i64" : "f64" + return "serde_json::Value" +} + +function newtype(name: string, ref: string) { + return `/// \`${ref}\`\n#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)]\n#[serde(transparent)]\npub struct ${name}(pub String);\n\nimpl ${name} {\n pub fn as_str(&self) -> &str {\n &self.0\n }\n}\n\nimpl std::fmt::Display for ${name} {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.write_str(&self.0)\n }\n}\n\nimpl From for ${name} {\n fn from(value: String) -> Self {\n Self(value)\n }\n}\n\nimpl From<&str> for ${name} {\n fn from(value: &str) -> Self {\n Self(value.to_owned())\n }\n}` +} + +function uniqueVariants(names: Array) { + const seen = new Set(["Unknown"]) + return names.map((name) => { + let unique = name + for (let index = 2; seen.has(unique); index++) unique = `${name}${index}` + seen.add(unique) + return unique + }) +} + +function docOf(annotations: { readonly [key: string]: unknown } | undefined) { + const description = annotations?.description + if (typeof description !== "string" || description === "") return "" + return description + .split("\n") + .map((line) => ` /// ${line}`.trimEnd() + "\n") + .join("") +}