Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,195 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
/// Marker trait for protocol types that can signal experimental usage.
pub trait ExperimentalApi {
/// Returns a short reason identifier when an experimental method or field is
/// used, or `None` when the value is entirely stable.
fn experimental_reason(&self) -> Option<&'static str>;
}
/// Describes an experimental field on a specific type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExperimentalField {
pub type_name: &'static str,
pub field_name: &'static str,
/// Stable identifier returned when this field is used.
/// Convention: `<method>` for method-level gates or `<method>.<field>` for
/// field-level gates.
pub reason: &'static str,
}
inventory::collect!(ExperimentalField);
/// Returns all experimental fields registered across the protocol types.
pub fn experimental_fields() -> Vec<&'static ExperimentalField> {
inventory::iter::<ExperimentalField>.into_iter().collect()
}
/// Constructs a consistent error message for experimental gating.
pub fn experimental_required_message(reason: &str) -> String {
format!("{reason} requires experimentalApi capability")
}
impl<T: ExperimentalApi> ExperimentalApi for Option<T> {
fn experimental_reason(&self) -> Option<&'static str> {
self.as_ref().and_then(ExperimentalApi::experimental_reason)
}
}
impl<T: ExperimentalApi> ExperimentalApi for Vec<T> {
fn experimental_reason(&self) -> Option<&'static str> {
self.iter().find_map(ExperimentalApi::experimental_reason)
}
}
impl<K, V: ExperimentalApi, S> ExperimentalApi for HashMap<K, V, S> {
fn experimental_reason(&self) -> Option<&'static str> {
self.values().find_map(ExperimentalApi::experimental_reason)
}
}
impl<K: Ord, V: ExperimentalApi> ExperimentalApi for BTreeMap<K, V> {
fn experimental_reason(&self) -> Option<&'static str> {
self.values().find_map(ExperimentalApi::experimental_reason)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::ExperimentalApi as ExperimentalApiTrait;
use akode_experimental_api_macros::ExperimentalApi;
use pretty_assertions::assert_eq;
#[allow(dead_code)]
#[derive(ExperimentalApi)]
enum EnumVariantShapes {
#[experimental("enum/unit")]
Unit,
#[experimental("enum/tuple")]
Tuple(u8),
#[experimental("enum/named")]
Named {
value: u8,
},
StableTuple(u8),
}
#[allow(dead_code)]
#[derive(ExperimentalApi)]
struct NestedFieldShape {
#[experimental(nested)]
inner: Option<EnumVariantShapes>,
}
#[allow(dead_code)]
#[derive(ExperimentalApi)]
struct NestedCollectionShape {
#[experimental(nested)]
inners: Vec<EnumVariantShapes>,
}
#[allow(dead_code)]
#[derive(ExperimentalApi)]
struct NestedMapShape {
#[experimental(nested)]
inners: HashMap<String, EnumVariantShapes>,
}
#[allow(dead_code)]
#[derive(ExperimentalApi)]
struct ExperimentalFieldShape {
#[experimental("field/optionalCollection")]
optional_collection: Option<Vec<EnumVariantShapes>>,
}
#[test]
fn derive_supports_all_enum_variant_shapes() {
assert_eq!(
ExperimentalApiTrait::experimental_reason(&EnumVariantShapes::Unit),
Some("enum/unit")
);
assert_eq!(
ExperimentalApiTrait::experimental_reason(&EnumVariantShapes::Tuple(1)),
Some("enum/tuple")
);
assert_eq!(
ExperimentalApiTrait::experimental_reason(&EnumVariantShapes::Named { value: 1 }),
Some("enum/named")
);
assert_eq!(
ExperimentalApiTrait::experimental_reason(&EnumVariantShapes::StableTuple(1)),
None
);
}
#[test]
fn derive_supports_nested_experimental_fields() {
assert_eq!(
ExperimentalApiTrait::experimental_reason(&NestedFieldShape {
inner: Some(EnumVariantShapes::Named { value: 1 }),
}),
Some("enum/named")
);
assert_eq!(
ExperimentalApiTrait::experimental_reason(&NestedFieldShape { inner: None }),
None
);
}
#[test]
fn derive_supports_nested_collections() {
assert_eq!(
ExperimentalApiTrait::experimental_reason(&NestedCollectionShape {
inners: vec![
EnumVariantShapes::StableTuple(1),
EnumVariantShapes::Tuple(2)
],
}),
Some("enum/tuple")
);
assert_eq!(
ExperimentalApiTrait::experimental_reason(&NestedCollectionShape {
inners: Vec::new()
}),
None
);
}
#[test]
fn derive_supports_nested_maps() {
assert_eq!(
ExperimentalApiTrait::experimental_reason(&NestedMapShape {
inners: HashMap::from([(
"default".to_string(),
EnumVariantShapes::Named { value: 1 },
)]),
}),
Some("enum/named")
);
assert_eq!(
ExperimentalApiTrait::experimental_reason(&NestedMapShape {
inners: HashMap::new(),
}),
None
);
}
#[test]
fn derive_marks_optional_experimental_fields_when_some() {
assert_eq!(
ExperimentalApiTrait::experimental_reason(&ExperimentalFieldShape {
optional_collection: Some(Vec::new()),
}),
Some("field/optionalCollection")
);
assert_eq!(
ExperimentalApiTrait::experimental_reason(&ExperimentalFieldShape {
optional_collection: None,
}),
None
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
//! Removes the opt-in verification mode from the flattened stable elicitation union.
//!
//! `ExperimentalApi` enum annotations currently drive runtime checks only. Keep this new mode
//! out of stable exports without changing the export behavior of existing gated enum variants.
use super::extract_discriminator_from_arm;
use super::split_top_level;
use super::split_type_alias;
use serde_json::Value;
const MODE: &str = "openai/userVerification";
pub(super) fn filter_ts(content: &str) -> String {
let Some((prefix, body, suffix)) = split_type_alias(content) else {
return content.to_string();
};
let parts = split_top_level(&body, '&')
.into_iter()
.map(|part| {
let Some(union) = part
.strip_prefix('(')
.and_then(|part| part.strip_suffix(')'))
else {
return part;
};
let arms = split_top_level(union, '|')
.into_iter()
.filter(|arm| extract_discriminator_from_arm(arm, "mode").as_deref() != Some(MODE))
.collect::<Vec<_>>();
format!("({})", arms.join(" | "))
})
.collect::<Vec<_>>();
format!("{prefix} {}{suffix}", parts.join(" & "))
}
pub(super) fn filter_json(value: &mut Value) {
match value {
Value::Array(items) => {
items.retain(|item| {
item.pointer("/properties/mode/enum") != Some(&serde_json::json!([MODE]))
});
for item in items {
filter_json(item);
}
}
Value::Object(map) => {
for entry in map.values_mut() {
filter_json(entry);
}
}
Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
}
}
#[cfg(test)]
#[path = "export_user_verification_tests.rs"]
mod tests;

View File

@@ -0,0 +1,39 @@
//! Checks that filtering the new mode preserves the stable elicitation contracts.
use super::*;
use crate::McpServerElicitationRequestParams;
use crate::TS;
use anyhow::Result;
use pretty_assertions::assert_eq;
#[test]
fn verification_mode_is_removed_from_flattened_typescript_only_for_stable_exports() -> Result<()> {
let generated = McpServerElicitationRequestParams::export_to_string()?;
assert!(generated.contains(MODE));
let filtered = filter_ts(&generated);
assert!(!filtered.contains(MODE));
assert_eq!(filter_ts(&filtered), filtered);
for mode in ["form", "openai/form", "openaiForm", "url"] {
assert!(filtered.contains(&format!("\"mode\": \"{mode}\"")));
}
assert!(filtered.contains("threadId: string"));
assert!(filtered.contains("requestedSchema: McpElicitationSchema"));
Ok(())
}
#[test]
fn verification_mode_is_removed_from_inline_json_without_changing_other_modes() -> Result<()> {
let generated = serde_json::to_value(schemars::schema_for!(McpServerElicitationRequestParams))?;
assert!(generated.to_string().contains(MODE));
let mut expected = generated.clone();
let modes = expected["oneOf"].as_array_mut().expect("flattened modes");
let verification = modes.remove(0);
assert_eq!(
verification["properties"]["mode"]["enum"],
serde_json::json!([MODE])
);
let mut filtered = generated;
filter_json(&mut filtered);
assert_eq!(filtered, expected);
Ok(())
}

View File

@@ -0,0 +1,72 @@
mod experimental_api;
mod precomputed_exports;
mod protocol;
pub mod rpc;
pub use experimental_api::*;
pub use precomputed_exports::GenerateTsOptions;
pub use precomputed_exports::generate_internal_json_schema;
pub use precomputed_exports::generate_json;
pub use precomputed_exports::generate_json_with_experimental;
pub use precomputed_exports::generate_ts;
pub use precomputed_exports::generate_ts_with_options;
pub use precomputed_exports::generate_types;
pub use protocol::common::*;
pub use protocol::event_mapping::*;
pub use protocol::item_builders::*;
pub use protocol::thread_history::*;
pub use protocol::thread_history_projection::*;
pub use protocol::v1::ApplyPatchApprovalParams;
pub use protocol::v1::ApplyPatchApprovalResponse;
pub use protocol::v1::ClientInfo;
pub use protocol::v1::ConversationGitInfo;
pub use protocol::v1::ConversationSummary;
pub use protocol::v1::ExecCommandApprovalParams;
pub use protocol::v1::ExecCommandApprovalResponse;
pub use protocol::v1::GetAuthStatusParams;
pub use protocol::v1::GetAuthStatusResponse;
pub use protocol::v1::GetConversationSummaryParams;
pub use protocol::v1::GetConversationSummaryResponse;
pub use protocol::v1::GitDiffToRemoteParams;
pub use protocol::v1::GitDiffToRemoteResponse;
pub use protocol::v1::GitSha;
pub use protocol::v1::InitializeCapabilities;
pub use protocol::v1::InitializeParams;
pub use protocol::v1::InitializeResponse;
pub use protocol::v1::InterruptConversationResponse;
pub use protocol::v1::LoginApiKeyParams;
pub use protocol::v1::SandboxSettings;
pub use protocol::v1::Tools;
pub use protocol::v1::UserSavedConfig;
pub use protocol::v2::*;
pub use rpc::*;
#[cfg(test)]
pub use schema_fixtures::SchemaFixtureOptions;
#[cfg(test)]
pub use schema_fixtures::read_schema_fixture_subtree;
#[cfg(test)]
pub use schema_fixtures::read_schema_fixture_tree;
#[cfg(test)]
pub use schema_fixtures::write_schema_fixtures;
#[cfg(test)]
pub use schema_fixtures::write_schema_fixtures_with_options;
#[cfg(not(test))]
pub(crate) use akode_app_server_protocol_noop_macros::JsonSchema;
#[cfg(not(test))]
pub(crate) use akode_app_server_protocol_noop_macros::TS;
#[cfg(test)]
pub(crate) use schemars::JsonSchema;
#[cfg(test)]
pub(crate) use ts_rs::TS;
#[cfg(test)]
#[path = "lib_tests.rs"]
mod tests;
// Release tooling selects this module's schema writer by its exact test name.
#[cfg(test)]
mod schema_fixtures_tests;
#[cfg(test)]
use tests::export;
#[cfg(test)]
use tests::schema_fixtures;

View File

@@ -0,0 +1,8 @@
#![cfg(test)]
#[path = "export.rs"]
pub(crate) mod export;
#[path = "precomputed_exports_tests.rs"]
mod precomputed_exports_tests;
#[path = "schema_fixtures.rs"]
pub(crate) mod schema_fixtures;

View File

@@ -0,0 +1,214 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::fs;
use std::io::Cursor;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
pub(crate) const GENERATED_TS_HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n";
const STABLE_EXPORTS: &[u8] =
include_bytes!("../schema/precomputed/app-server-exports-stable.json.zst");
const EXPERIMENTAL_EXPORTS: &[u8] =
include_bytes!("../schema/precomputed/app-server-exports-experimental.json.zst");
#[derive(Clone, Copy, Debug)]
pub struct GenerateTsOptions {
pub generate_indices: bool,
pub ensure_headers: bool,
pub run_prettier: bool,
pub experimental_api: bool,
}
impl Default for GenerateTsOptions {
fn default() -> Self {
Self {
generate_indices: true,
ensure_headers: true,
run_prettier: true,
experimental_api: false,
}
}
}
#[derive(Deserialize)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq, serde::Serialize))]
pub(crate) struct PrecomputedExports {
pub(crate) typescript: BTreeMap<String, String>,
pub(crate) json_schema: BTreeMap<String, String>,
pub(crate) internal_json_schema: BTreeMap<String, String>,
}
#[derive(Clone, Copy)]
enum ExportSet {
Stable,
Experimental,
}
pub fn generate_types(out_dir: &Path, prettier: Option<&Path>) -> Result<()> {
generate_ts(out_dir, prettier)?;
generate_json(out_dir)
}
pub fn generate_ts(out_dir: &Path, prettier: Option<&Path>) -> Result<()> {
generate_ts_with_options(out_dir, prettier, GenerateTsOptions::default())
}
pub fn generate_ts_with_options(
out_dir: &Path,
prettier: Option<&Path>,
options: GenerateTsOptions,
) -> Result<()> {
let export_set = if options.experimental_api {
ExportSet::Experimental
} else {
ExportSet::Stable
};
let exports = load_exports(export_set)?;
let ts_files = write_typescript_exports(out_dir, &exports.typescript, options)?;
if options.run_prettier
&& let Some(prettier_bin) = prettier
&& !ts_files.is_empty()
{
let status = Command::new(prettier_bin)
.arg("--write")
.arg("--log-level")
.arg("warn")
.args(ts_files.iter().map(PathBuf::as_path))
.status()
.with_context(|| format!("Failed to invoke Prettier at {}", prettier_bin.display()))?;
if !status.success() {
bail!("Prettier failed with status {status}");
}
}
trim_trailing_whitespace_in_ts_files(&ts_files)
}
pub fn generate_json(out_dir: &Path) -> Result<()> {
generate_json_with_experimental(out_dir, /*experimental_api*/ false)
}
pub fn generate_json_with_experimental(out_dir: &Path, experimental_api: bool) -> Result<()> {
let export_set = if experimental_api {
ExportSet::Experimental
} else {
ExportSet::Stable
};
let exports = load_exports(export_set)?;
write_exports(out_dir, &exports.json_schema)?;
Ok(())
}
pub fn generate_internal_json_schema(out_dir: &Path) -> Result<()> {
let exports = load_exports(ExportSet::Stable)?;
write_exports(out_dir, &exports.internal_json_schema)?;
Ok(())
}
fn load_exports(export_set: ExportSet) -> Result<PrecomputedExports> {
let compressed = match export_set {
ExportSet::Stable => STABLE_EXPORTS,
ExportSet::Experimental => EXPERIMENTAL_EXPORTS,
};
let bytes = zstd::stream::decode_all(Cursor::new(compressed))
.context("decompress precomputed app-server protocol exports")?;
serde_json::from_slice(&bytes).context("decode precomputed app-server protocol exports")
}
fn write_typescript_exports(
out_dir: &Path,
exports: &BTreeMap<String, String>,
options: GenerateTsOptions,
) -> Result<Vec<PathBuf>> {
let mut written = Vec::new();
for (relative_path, archived_contents) in exports {
let is_index = Path::new(relative_path).file_name() == Some(OsStr::new("index.ts"));
if is_index && !options.generate_indices {
continue;
}
let contents = if options.ensure_headers || is_index {
archived_contents.as_str()
} else {
archived_contents
.strip_prefix(GENERATED_TS_HEADER)
.unwrap_or(archived_contents)
};
written.push(write_export(out_dir, relative_path, contents)?);
}
Ok(written)
}
fn write_exports(out_dir: &Path, exports: &BTreeMap<String, String>) -> Result<Vec<PathBuf>> {
exports
.iter()
.map(|(relative_path, contents)| write_export(out_dir, relative_path, contents))
.collect()
}
fn write_export(out_dir: &Path, relative_path: &str, contents: &str) -> Result<PathBuf> {
let relative_path = validated_relative_path(relative_path)?;
let output_path = out_dir.join(relative_path);
let parent = output_path
.parent()
.context("precomputed export path should have a parent")?;
fs::create_dir_all(parent).with_context(|| format!("Failed to create {}", parent.display()))?;
fs::write(&output_path, contents)
.with_context(|| format!("Failed to write {}", output_path.display()))?;
Ok(output_path)
}
fn validated_relative_path(path: &str) -> Result<&Path> {
let path = Path::new(path);
if path.as_os_str().is_empty()
|| path
.components()
.any(|component| !matches!(component, Component::Normal(_)))
{
bail!("invalid precomputed export path: {}", path.display());
}
Ok(path)
}
fn trim_trailing_whitespace_in_ts_files(paths: &[PathBuf]) -> Result<()> {
for path in paths {
let content = fs::read_to_string(path)
.with_context(|| format!("Failed to read {}", path.display()))?;
let trimmed = trim_trailing_line_whitespace(&content);
if trimmed != content {
fs::write(path, trimmed)
.with_context(|| format!("Failed to write {}", path.display()))?;
}
}
Ok(())
}
fn trim_trailing_line_whitespace(content: &str) -> String {
let mut trimmed = String::with_capacity(content.len());
for line in content.split_inclusive('\n') {
if let Some(line_without_newline) = line.strip_suffix('\n') {
trimmed.push_str(line_without_newline.trim_end_matches([' ', '\t']));
trimmed.push('\n');
} else {
trimmed.push_str(line.trim_end_matches([' ', '\t']));
}
}
trimmed
}
#[cfg(test)]
pub(crate) fn decode_precomputed_exports(experimental_api: bool) -> Result<PrecomputedExports> {
let export_set = if experimental_api {
ExportSet::Experimental
} else {
ExportSet::Stable
};
load_exports(export_set)
}

View File

@@ -0,0 +1,69 @@
use crate::GenerateTsOptions;
use crate::generate_internal_json_schema;
use crate::generate_json_with_experimental;
use crate::generate_ts_with_options;
use crate::precomputed_exports::GENERATED_TS_HEADER;
use crate::precomputed_exports::decode_precomputed_exports;
use crate::schema_fixtures::collect_export_files_recursive;
use anyhow::Context;
use anyhow::Result;
use pretty_assertions::assert_eq;
use std::path::Path;
#[test]
fn precomputed_exports_are_written_to_disk() -> Result<()> {
let output_dir = tempfile::tempdir().context("create export temp dir")?;
let typescript_dir = output_dir.path().join("typescript");
let json_dir = output_dir.path().join("json");
let internal_json_dir = output_dir.path().join("internal-json");
generate_ts_with_options(
&typescript_dir,
/*prettier*/ None,
GenerateTsOptions::default(),
)?;
generate_json_with_experimental(&json_dir, /*experimental_api*/ false)?;
generate_internal_json_schema(&internal_json_dir)?;
let exports = decode_precomputed_exports(/*experimental_api*/ false)?;
assert_eq!(
collect_export_files_recursive(&typescript_dir)?,
exports.typescript
);
assert_eq!(
collect_export_files_recursive(&json_dir)?,
exports.json_schema
);
assert_eq!(
collect_export_files_recursive(&internal_json_dir)?,
exports.internal_json_schema
);
Ok(())
}
#[test]
fn typescript_export_options_preserve_generator_behavior() -> Result<()> {
let output_dir = tempfile::tempdir().context("create TypeScript export temp dir")?;
generate_ts_with_options(
output_dir.path(),
/*prettier*/ None,
GenerateTsOptions {
generate_indices: false,
ensure_headers: false,
..GenerateTsOptions::default()
},
)?;
let files = collect_export_files_recursive(output_dir.path())?;
assert!(!files.keys().any(|path| {
Path::new(path)
.file_name()
.is_some_and(|name| name == "index.ts")
}));
assert!(
files
.values()
.all(|contents| !contents.starts_with(GENERATED_TS_HEADER))
);
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,141 @@
use super::*;
use anyhow::Result;
use akode_protocol::protocol::TurnAbortReason;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn client_response_payload_serializes_without_an_intermediate_json_value() -> Result<()> {
let payload = ClientResponsePayload::ThreadArchive(v2::ThreadArchiveResponse {});
assert_eq!(serde_json::to_string(&payload)?, "{}");
let Some(ClientResponse::ThreadArchive {
request_id,
response: _,
}) = payload.into_client_response(RequestId::Integer(7))
else {
panic!("expected thread/archive client response");
};
assert_eq!(request_id, RequestId::Integer(7));
Ok(())
}
#[test]
fn interrupt_conversation_payload_stays_jsonrpc_only() -> Result<()> {
let payload = ClientResponsePayload::InterruptConversation(v1::InterruptConversationResponse {
abort_reason: TurnAbortReason::Interrupted,
});
assert_eq!(
serde_json::to_value(&payload)?,
json!({
"abortReason": "interrupted",
})
);
assert!(
payload
.into_client_response(RequestId::Integer(8))
.is_none()
);
Ok(())
}
#[test]
fn client_response_jsonrpc_parts_preserve_payloads_and_request_ids() -> Result<()> {
let payloads = [
(
ClientResponsePayload::GetAuthStatus(v1::GetAuthStatusResponse {
auth_method: Some(AuthMode::ApiKey),
auth_token: None,
requires_openai_auth: Some(true),
}),
json!({
"authMethod": "apikey",
"authToken": null,
"requiresOpenaiAuth": true,
}),
),
(
ClientResponsePayload::GetAccount(v2::GetAccountResponse {
account: Some(v2::Account::ApiKey {}),
requires_openai_auth: false,
}),
json!({
"account": { "type": "apiKey" },
"requiresOpenaiAuth": false,
}),
),
];
for (payload, expected_result) in payloads {
for request_id in [RequestId::Integer(7), RequestId::String("request-7".into())] {
let expected = (request_id.clone(), expected_result.clone());
let response = payload
.clone()
.into_client_response(request_id.clone())
.expect("request-backed payload has a typed response");
assert_eq!(response.into_jsonrpc_parts()?, expected);
assert_eq!(payload.to_jsonrpc_parts(request_id.clone())?, expected);
assert_eq!(payload.clone().into_jsonrpc_parts(request_id)?, expected);
}
}
Ok(())
}
#[test]
fn client_response_jsonrpc_parts_preserve_legacy_interrupt() -> Result<()> {
let request_id = RequestId::String("interrupt-7".into());
let payload = ClientResponsePayload::InterruptConversation(v1::InterruptConversationResponse {
abort_reason: TurnAbortReason::Interrupted,
});
let expected = (request_id.clone(), json!({ "abortReason": "interrupted" }));
assert!(
payload
.clone()
.into_client_response(request_id.clone())
.is_none()
);
assert_eq!(payload.to_jsonrpc_parts(request_id.clone())?, expected);
assert_eq!(payload.into_jsonrpc_parts(request_id)?, expected);
Ok(())
}
#[cfg(unix)]
#[test]
fn client_response_jsonrpc_parts_preserve_serialization_errors() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let request_id = RequestId::Integer(7);
let response = v1::GetConversationSummaryResponse {
summary: v1::ConversationSummary {
conversation_id: akode_protocol::ThreadId::from_u128(/*value*/ 7),
path: PathBuf::from(OsString::from_vec(vec![0xff])),
preview: String::new(),
timestamp: None,
updated_at: None,
model_provider: String::new(),
cwd: PathBuf::new(),
cli_version: String::new(),
source: akode_protocol::protocol::SessionSource::Exec,
git_info: None,
},
};
let describe = |error: serde_json::Error| (error.classify(), error.to_string());
let expected = describe(serde_json::to_value(&response).unwrap_err());
let payload = ClientResponsePayload::GetConversationSummary(response.clone());
let typed = ClientResponse::GetConversationSummary {
request_id: request_id.clone(),
response,
};
assert_eq!(describe(typed.into_jsonrpc_parts().unwrap_err()), expected);
assert_eq!(
describe(payload.to_jsonrpc_parts(request_id.clone()).unwrap_err()),
expected
);
assert_eq!(
describe(payload.into_jsonrpc_parts(request_id).unwrap_err()),
expected
);
}

View File

@@ -0,0 +1,679 @@
use crate::protocol::common::ServerNotification;
use crate::protocol::item_builders::build_command_execution_begin_item;
use crate::protocol::item_builders::build_command_execution_end_item;
use crate::protocol::item_builders::convert_patch_changes;
use crate::protocol::v2::AgentMessageDeltaNotification;
use crate::protocol::v2::CollabAgentState;
use crate::protocol::v2::CollabAgentTool;
use crate::protocol::v2::CollabAgentToolCallStatus;
use crate::protocol::v2::CommandExecutionOutputDeltaNotification;
use crate::protocol::v2::DynamicToolCallOutputContentItem;
use crate::protocol::v2::DynamicToolCallStatus;
use crate::protocol::v2::FileChangePatchUpdatedNotification;
use crate::protocol::v2::ItemCompletedNotification;
use crate::protocol::v2::ItemStartedNotification;
use crate::protocol::v2::PlanDeltaNotification;
use crate::protocol::v2::ReasoningSummaryPartAddedNotification;
use crate::protocol::v2::ReasoningSummaryTextDeltaNotification;
use crate::protocol::v2::ReasoningTextDeltaNotification;
use crate::protocol::v2::TerminalInteractionNotification;
use crate::protocol::v2::ThreadItemPayload;
use akode_protocol::dynamic_tools::DynamicToolCallOutputContentItem as CoreDynamicToolCallOutputContentItem;
use akode_protocol::protocol::EventMsg;
use std::collections::HashMap;
/// Build the v2 app-server notification that directly corresponds to a single core event.
///
/// This only covers the stateless event-to-notification projections that have a one-to-one
/// mapping. Callers remain responsible for any surrounding state checks or side effects before
/// invoking this helper.
pub fn item_event_to_server_notification(
msg: EventMsg,
thread_id: &str,
turn_id: &str,
) -> ServerNotification {
let thread_id = thread_id.to_string();
let turn_id = turn_id.to_string();
match msg {
EventMsg::DynamicToolCallResponse(response) => {
let status = if response.success {
DynamicToolCallStatus::Completed
} else {
DynamicToolCallStatus::Failed
};
let duration_ms = i64::try_from(response.duration.as_millis()).ok();
let item = ThreadItemPayload::DynamicToolCall {
id: response.call_id,
namespace: response.namespace,
tool: response.tool,
arguments: response.arguments,
status,
content_items: Some(
response
.content_items
.into_iter()
.map(|item| match item {
CoreDynamicToolCallOutputContentItem::InputText { text } => {
DynamicToolCallOutputContentItem::InputText { text }
}
CoreDynamicToolCallOutputContentItem::InputImage { image_url } => {
DynamicToolCallOutputContentItem::InputImage { image_url }
}
CoreDynamicToolCallOutputContentItem::InputAudio { audio_url } => {
DynamicToolCallOutputContentItem::InputAudio { audio_url }
}
})
.collect(),
),
success: Some(response.success),
duration_ms,
};
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
response.turn_id,
item,
/*started_at_ms*/ None,
response.completed_at_ms,
))
}
EventMsg::CollabAgentSpawnBegin(begin_event) => {
let item = ThreadItemPayload::CollabAgentToolCall {
id: begin_event.call_id,
tool: CollabAgentTool::SpawnAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: begin_event.sender_thread_id.to_string(),
receiver_thread_ids: Vec::new(),
prompt: Some(begin_event.prompt),
model: Some(begin_event.model),
reasoning_effort: Some(begin_event.reasoning_effort),
agents_states: HashMap::new(),
};
ServerNotification::ItemStarted(ItemStartedNotification::new(
thread_id,
turn_id,
item,
begin_event.started_at_ms,
))
}
EventMsg::CollabAgentSpawnEnd(end_event) => {
let has_receiver = end_event.new_thread_id.is_some();
let status = match &end_event.status {
akode_protocol::protocol::AgentStatus::Errored(_)
| akode_protocol::protocol::AgentStatus::NotFound => {
CollabAgentToolCallStatus::Failed
}
_ if has_receiver => CollabAgentToolCallStatus::Completed,
_ => CollabAgentToolCallStatus::Failed,
};
let (receiver_thread_ids, agents_states) = match end_event.new_thread_id {
Some(id) => {
let receiver_id = id.to_string();
let received_status = CollabAgentState::from(end_event.status.clone());
(
vec![receiver_id.clone()],
[(receiver_id, received_status)].into_iter().collect(),
)
}
None => (Vec::new(), HashMap::new()),
};
let item = ThreadItemPayload::CollabAgentToolCall {
id: end_event.call_id,
tool: CollabAgentTool::SpawnAgent,
status,
sender_thread_id: end_event.sender_thread_id.to_string(),
receiver_thread_ids,
prompt: Some(end_event.prompt),
model: Some(end_event.model),
reasoning_effort: Some(end_event.reasoning_effort),
agents_states,
};
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
turn_id,
item,
/*started_at_ms*/ None,
end_event.completed_at_ms,
))
}
EventMsg::CollabAgentInteractionBegin(begin_event) => {
let receiver_thread_ids = vec![begin_event.receiver_thread_id.to_string()];
let item = ThreadItemPayload::CollabAgentToolCall {
id: begin_event.call_id,
tool: CollabAgentTool::SendInput,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: begin_event.sender_thread_id.to_string(),
receiver_thread_ids,
prompt: Some(begin_event.prompt),
model: None,
reasoning_effort: None,
agents_states: HashMap::new(),
};
ServerNotification::ItemStarted(ItemStartedNotification::new(
thread_id,
turn_id,
item,
begin_event.started_at_ms,
))
}
EventMsg::CollabAgentInteractionEnd(end_event) => {
let status = match &end_event.status {
akode_protocol::protocol::AgentStatus::Errored(_)
| akode_protocol::protocol::AgentStatus::NotFound => {
CollabAgentToolCallStatus::Failed
}
_ => CollabAgentToolCallStatus::Completed,
};
let receiver_id = end_event.receiver_thread_id.to_string();
let received_status = CollabAgentState::from(end_event.status);
let item = ThreadItemPayload::CollabAgentToolCall {
id: end_event.call_id,
tool: CollabAgentTool::SendInput,
status,
sender_thread_id: end_event.sender_thread_id.to_string(),
receiver_thread_ids: vec![receiver_id.clone()],
prompt: Some(end_event.prompt),
model: None,
reasoning_effort: None,
agents_states: [(receiver_id, received_status)].into_iter().collect(),
};
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
turn_id,
item,
/*started_at_ms*/ None,
end_event.completed_at_ms,
))
}
EventMsg::SubAgentActivity(activity) => {
let item = ThreadItemPayload::SubAgentActivity {
model: activity.model,
reasoning_effort: activity.reasoning_effort,
id: activity.event_id,
kind: activity.kind.into(),
agent_thread_id: activity.agent_thread_id.to_string(),
agent_path: String::from(activity.agent_path),
};
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
turn_id,
item,
/*started_at_ms*/ None,
activity.occurred_at_ms,
))
}
EventMsg::CollabWaitingBegin(begin_event) => {
let receiver_thread_ids = begin_event
.receiver_thread_ids
.iter()
.map(ToString::to_string)
.collect();
let item = ThreadItemPayload::CollabAgentToolCall {
id: begin_event.call_id,
tool: CollabAgentTool::Wait,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: begin_event.sender_thread_id.to_string(),
receiver_thread_ids,
prompt: None,
model: None,
reasoning_effort: None,
agents_states: HashMap::new(),
};
ServerNotification::ItemStarted(ItemStartedNotification::new(
thread_id,
turn_id,
item,
begin_event.started_at_ms,
))
}
EventMsg::CollabWaitingEnd(end_event) => {
let status = if end_event.statuses.values().any(|status| {
matches!(
status,
akode_protocol::protocol::AgentStatus::Errored(_)
| akode_protocol::protocol::AgentStatus::NotFound
)
}) {
CollabAgentToolCallStatus::Failed
} else {
CollabAgentToolCallStatus::Completed
};
let receiver_thread_ids = end_event.statuses.keys().map(ToString::to_string).collect();
let agents_states = end_event
.statuses
.iter()
.map(|(id, status)| (id.to_string(), CollabAgentState::from(status.clone())))
.collect();
let item = ThreadItemPayload::CollabAgentToolCall {
id: end_event.call_id,
tool: CollabAgentTool::Wait,
status,
sender_thread_id: end_event.sender_thread_id.to_string(),
receiver_thread_ids,
prompt: None,
model: None,
reasoning_effort: None,
agents_states,
};
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
turn_id,
item,
/*started_at_ms*/ None,
end_event.completed_at_ms,
))
}
EventMsg::CollabCloseBegin(begin_event) => {
let item = ThreadItemPayload::CollabAgentToolCall {
id: begin_event.call_id,
tool: CollabAgentTool::CloseAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: begin_event.sender_thread_id.to_string(),
receiver_thread_ids: vec![begin_event.receiver_thread_id.to_string()],
prompt: None,
model: None,
reasoning_effort: None,
agents_states: HashMap::new(),
};
ServerNotification::ItemStarted(ItemStartedNotification::new(
thread_id,
turn_id,
item,
begin_event.started_at_ms,
))
}
EventMsg::CollabCloseEnd(end_event) => {
let status = match &end_event.status {
akode_protocol::protocol::AgentStatus::Errored(_)
| akode_protocol::protocol::AgentStatus::NotFound => {
CollabAgentToolCallStatus::Failed
}
_ => CollabAgentToolCallStatus::Completed,
};
let receiver_id = end_event.receiver_thread_id.to_string();
let agents_states = [(
receiver_id.clone(),
CollabAgentState::from(end_event.status),
)]
.into_iter()
.collect();
let item = ThreadItemPayload::CollabAgentToolCall {
id: end_event.call_id,
tool: CollabAgentTool::CloseAgent,
status,
sender_thread_id: end_event.sender_thread_id.to_string(),
receiver_thread_ids: vec![receiver_id],
prompt: None,
model: None,
reasoning_effort: None,
agents_states,
};
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
turn_id,
item,
/*started_at_ms*/ None,
end_event.completed_at_ms,
))
}
EventMsg::CollabResumeBegin(begin_event) => {
let item = ThreadItemPayload::CollabAgentToolCall {
id: begin_event.call_id,
tool: CollabAgentTool::ResumeAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: begin_event.sender_thread_id.to_string(),
receiver_thread_ids: vec![begin_event.receiver_thread_id.to_string()],
prompt: None,
model: None,
reasoning_effort: None,
agents_states: HashMap::new(),
};
ServerNotification::ItemStarted(ItemStartedNotification::new(
thread_id,
turn_id,
item,
begin_event.started_at_ms,
))
}
EventMsg::CollabResumeEnd(end_event) => {
let status = match &end_event.status {
akode_protocol::protocol::AgentStatus::Errored(_)
| akode_protocol::protocol::AgentStatus::NotFound => {
CollabAgentToolCallStatus::Failed
}
_ => CollabAgentToolCallStatus::Completed,
};
let receiver_id = end_event.receiver_thread_id.to_string();
let agents_states = [(
receiver_id.clone(),
CollabAgentState::from(end_event.status),
)]
.into_iter()
.collect();
let item = ThreadItemPayload::CollabAgentToolCall {
id: end_event.call_id,
tool: CollabAgentTool::ResumeAgent,
status,
sender_thread_id: end_event.sender_thread_id.to_string(),
receiver_thread_ids: vec![receiver_id],
prompt: None,
model: None,
reasoning_effort: None,
agents_states,
};
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
turn_id,
item,
/*started_at_ms*/ None,
end_event.completed_at_ms,
))
}
EventMsg::AgentMessageContentDelta(event) => {
let akode_protocol::protocol::AgentMessageContentDeltaEvent { item_id, delta, .. } =
event;
ServerNotification::AgentMessageDelta(AgentMessageDeltaNotification {
thread_id,
turn_id,
item_id,
delta,
})
}
EventMsg::PlanDelta(event) => ServerNotification::PlanDelta(PlanDeltaNotification {
thread_id,
turn_id,
item_id: event.item_id,
delta: event.delta,
}),
EventMsg::ReasoningContentDelta(event) => {
ServerNotification::ReasoningSummaryTextDelta(ReasoningSummaryTextDeltaNotification {
thread_id,
turn_id,
item_id: event.item_id,
delta: event.delta,
summary_index: event.summary_index,
})
}
EventMsg::ReasoningRawContentDelta(event) => {
ServerNotification::ReasoningTextDelta(ReasoningTextDeltaNotification {
thread_id,
turn_id,
item_id: event.item_id,
delta: event.delta,
content_index: event.content_index,
})
}
EventMsg::AgentReasoningSectionBreak(event) => {
ServerNotification::ReasoningSummaryPartAdded(ReasoningSummaryPartAddedNotification {
thread_id,
turn_id,
item_id: event.item_id,
summary_index: event.summary_index,
})
}
EventMsg::ItemStarted(item_started_event) => {
ServerNotification::ItemStarted(ItemStartedNotification::new(
thread_id,
turn_id,
ThreadItemPayload::from(item_started_event.item),
item_started_event.started_at_ms,
))
}
EventMsg::ItemCompleted(item_completed_event) => {
let mut notification = ItemCompletedNotification::new(
thread_id,
turn_id,
ThreadItemPayload::from(item_completed_event.item),
item_completed_event.started_at_ms,
item_completed_event.completed_at_ms,
);
notification.content_token_count = item_completed_event.content_token_count;
ServerNotification::ItemCompleted(notification)
}
EventMsg::PatchApplyUpdated(event) => {
ServerNotification::FileChangePatchUpdated(FileChangePatchUpdatedNotification {
thread_id,
turn_id,
item_id: event.call_id,
changes: convert_patch_changes(&event.changes),
})
}
EventMsg::ExecCommandBegin(exec_command_begin_event) => {
ServerNotification::ItemStarted(ItemStartedNotification::new(
thread_id,
turn_id,
build_command_execution_begin_item(&exec_command_begin_event),
exec_command_begin_event.started_at_ms,
))
}
EventMsg::ExecCommandOutputDelta(exec_command_output_delta_event) => {
let item_id = exec_command_output_delta_event.call_id;
let delta = String::from_utf8_lossy(&exec_command_output_delta_event.chunk).to_string();
ServerNotification::CommandExecutionOutputDelta(
CommandExecutionOutputDeltaNotification {
thread_id,
turn_id,
item_id,
delta,
},
)
}
EventMsg::TerminalInteraction(terminal_event) => {
ServerNotification::TerminalInteraction(TerminalInteractionNotification {
thread_id,
turn_id,
item_id: terminal_event.call_id,
process_id: terminal_event.process_id,
stdin: terminal_event.stdin,
})
}
EventMsg::ExecCommandEnd(exec_command_end_event) => {
ServerNotification::ItemCompleted(ItemCompletedNotification::new(
thread_id,
turn_id,
build_command_execution_end_item(&exec_command_end_event),
/*started_at_ms*/ None,
exec_command_end_event.completed_at_ms,
))
}
_ => unreachable!("unsupported item event"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use akode_protocol::ThreadId;
use akode_protocol::protocol::CollabResumeBeginEvent;
use akode_protocol::protocol::CollabResumeEndEvent;
use akode_protocol::protocol::ExecCommandOutputDeltaEvent;
use akode_protocol::protocol::ExecOutputStream;
use pretty_assertions::assert_eq;
#[test]
fn assistant_completion_count_is_optional_envelope_metadata() {
let item = akode_protocol::items::TurnItem::AgentMessage(
akode_protocol::items::AgentMessageItem {
moderation: None,
id: "answer".into(),
content: vec![akode_protocol::items::AgentMessageContent::Text {
text: "Answer".into(),
}],
phase: None,
memory_citation: None,
delivery: None,
questions: None,
},
);
let payload = ThreadItemPayload::from(item.clone());
for count in [None, Some(0), Some(23)] {
let event = akode_protocol::protocol::ItemCompletedEvent {
thread_id: ThreadId::new(),
turn_id: "turn".into(),
item: item.clone(),
content_token_count: count,
started_at_ms: Some(1),
completed_at_ms: 2,
};
let mut expected = ItemCompletedNotification::new(
"thread".into(),
"turn".into(),
payload.clone(),
/*started_at_ms*/ Some(1),
/*completed_at_ms*/ 2,
);
expected.content_token_count = count;
assert_item_completed_server_notification(
item_event_to_server_notification(EventMsg::ItemCompleted(event), "thread", "turn"),
expected.clone(),
);
let mut wire = serde_json::to_value(&expected).unwrap();
assert_eq!(
wire.get("contentTokenCount"),
Some(&serde_json::json!(count))
);
wire.as_object_mut().unwrap().remove("contentTokenCount");
expected.content_token_count = None;
assert_eq!(
serde_json::from_value::<ItemCompletedNotification>(wire).unwrap(),
expected,
);
}
}
fn assert_item_started_server_notification(
notification: ServerNotification,
expected: ItemStartedNotification,
) {
match notification {
ServerNotification::ItemStarted(payload) => assert_eq!(payload, expected),
other => panic!("expected item started notification, got {other:?}"),
}
}
fn assert_item_completed_server_notification(
notification: ServerNotification,
expected: ItemCompletedNotification,
) {
match notification {
ServerNotification::ItemCompleted(payload) => assert_eq!(payload, expected),
other => panic!("expected item completed notification, got {other:?}"),
}
}
fn assert_command_execution_output_delta_server_notification(
notification: ServerNotification,
expected: CommandExecutionOutputDeltaNotification,
) {
match notification {
ServerNotification::CommandExecutionOutputDelta(payload) => {
assert_eq!(payload, expected)
}
other => panic!("expected command execution output delta, got {other:?}"),
}
}
#[test]
fn collab_resume_begin_maps_to_item_started_resume_agent() {
let event = CollabResumeBeginEvent {
call_id: "call-1".to_string(),
started_at_ms: 123,
sender_thread_id: ThreadId::new(),
receiver_thread_id: ThreadId::new(),
receiver_agent_nickname: None,
receiver_agent_role: None,
};
let notification = item_event_to_server_notification(
EventMsg::CollabResumeBegin(event.clone()),
"thread-1",
"turn-1",
);
assert_item_started_server_notification(
notification,
ItemStartedNotification::new(
"thread-1".to_string(),
"turn-1".to_string(),
ThreadItemPayload::CollabAgentToolCall {
id: event.call_id,
tool: CollabAgentTool::ResumeAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: event.sender_thread_id.to_string(),
receiver_thread_ids: vec![event.receiver_thread_id.to_string()],
prompt: None,
model: None,
reasoning_effort: None,
agents_states: HashMap::new(),
},
event.started_at_ms,
),
);
}
#[test]
fn collab_resume_end_maps_to_item_completed_resume_agent() {
let event = CollabResumeEndEvent {
call_id: "call-2".to_string(),
completed_at_ms: 456,
sender_thread_id: ThreadId::new(),
receiver_thread_id: ThreadId::new(),
receiver_agent_nickname: None,
receiver_agent_role: None,
status: akode_protocol::protocol::AgentStatus::NotFound,
};
let receiver_id = event.receiver_thread_id.to_string();
let notification = item_event_to_server_notification(
EventMsg::CollabResumeEnd(event.clone()),
"thread-2",
"turn-2",
);
assert_item_completed_server_notification(
notification,
ItemCompletedNotification::new(
"thread-2".to_string(),
"turn-2".to_string(),
ThreadItemPayload::CollabAgentToolCall {
id: event.call_id,
tool: CollabAgentTool::ResumeAgent,
status: CollabAgentToolCallStatus::Failed,
sender_thread_id: event.sender_thread_id.to_string(),
receiver_thread_ids: vec![receiver_id.clone()],
prompt: None,
model: None,
reasoning_effort: None,
agents_states: [(
receiver_id,
CollabAgentState::from(akode_protocol::protocol::AgentStatus::NotFound),
)]
.into_iter()
.collect(),
},
/*started_at_ms*/ None,
event.completed_at_ms,
),
);
}
#[test]
fn exec_command_output_delta_maps_to_command_execution_output_delta() {
let notification = item_event_to_server_notification(
EventMsg::ExecCommandOutputDelta(ExecCommandOutputDeltaEvent {
call_id: "call-1".to_string(),
stream: ExecOutputStream::Stdout,
chunk: b"hello".to_vec(),
}),
"thread-1",
"turn-1",
);
assert_command_execution_output_delta_server_notification(
notification,
CommandExecutionOutputDeltaNotification {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
item_id: "call-1".to_string(),
delta: "hello".to_string(),
},
);
}
}

View File

@@ -0,0 +1,384 @@
//! Shared builders for app-server [`ThreadItem`] values derived from compatibility events.
//!
//! Most live tool items now come from first-class core `ItemStarted` / `ItemCompleted` events.
//! These builders remain for approval flows, rebuilt legacy history, and other pre-execution
//! paths where the underlying tool has not started or never starts at all.
//!
//! Keeping these builders in one place is useful for two reasons:
//! - Live notifications and rebuilt `thread/read` history both need to construct the same
//! synthetic items, so sharing the logic avoids drift between those paths.
//! - The projection is presentation-specific. Core protocol events stay generic, while the
//! app-server protocol decides how to surface those events as `ThreadItem`s for clients.
use crate::protocol::common::ServerNotification;
use crate::protocol::v2::AutoReviewDecisionSource;
use crate::protocol::v2::CommandAction;
use crate::protocol::v2::CommandExecutionSource;
use crate::protocol::v2::CommandExecutionStatus;
use crate::protocol::v2::FileUpdateChange;
use crate::protocol::v2::GuardianApprovalReview;
use crate::protocol::v2::GuardianApprovalReviewStatus;
use crate::protocol::v2::ItemGuardianApprovalReviewCompletedNotification;
use crate::protocol::v2::ItemGuardianApprovalReviewStartedNotification;
use crate::protocol::v2::PatchApplyStatus;
use crate::protocol::v2::PatchChangeKind;
use crate::protocol::v2::ThreadItemPayload;
use akode_protocol::ThreadId;
use akode_protocol::parse_command::ParsedCommand;
use akode_protocol::protocol::ApplyPatchApprovalRequestEvent;
use akode_protocol::protocol::ExecCommandBeginEvent;
use akode_protocol::protocol::ExecCommandEndEvent;
use akode_protocol::protocol::FileChange;
use akode_protocol::protocol::GuardianAssessmentAction;
use akode_protocol::protocol::GuardianAssessmentEvent;
use akode_protocol::protocol::PatchApplyBeginEvent;
use akode_protocol::protocol::PatchApplyEndEvent;
use akode_protocol::protocol::ReviewOutputEvent;
use akode_protocol::review_format::REVIEW_FALLBACK_MESSAGE;
use akode_protocol::review_format::render_review_output_text;
use akode_secrets::redact_secrets;
use akode_shell_command::parse_command::parse_command;
use akode_shell_command::parse_command::shlex_join;
use akode_utils_path_uri::PathUri;
use std::collections::HashMap;
use std::path::PathBuf;
use tracing::warn;
/// Client-facing command and parsed actions projected from a raw command.
pub struct CommandExecutionPresentation {
/// Shell-formatted command with recognizable secrets redacted.
pub command: String,
/// Parsed command actions with recognizable secrets redacted.
pub command_actions: Vec<CommandAction>,
}
impl CommandExecutionPresentation {
/// Projects a raw command into its client-facing representation.
pub fn from_raw(command: &[String], parsed_cmd: &[ParsedCommand], cwd: &PathUri) -> Self {
Self {
command: redact_secrets(shlex_join(command)),
command_actions: command_actions_for_path_uri(parsed_cmd, cwd),
}
}
}
pub(crate) fn review_output_text(output: Option<&ReviewOutputEvent>) -> String {
output
.map(render_review_output_text)
.unwrap_or_else(|| REVIEW_FALLBACK_MESSAGE.to_string())
}
pub fn build_file_change_approval_request_item(
payload: &ApplyPatchApprovalRequestEvent,
) -> ThreadItemPayload {
ThreadItemPayload::FileChange {
id: payload.call_id.clone(),
changes: convert_patch_changes(&payload.changes),
status: PatchApplyStatus::InProgress,
}
}
pub fn build_file_change_begin_item(payload: &PatchApplyBeginEvent) -> ThreadItemPayload {
ThreadItemPayload::FileChange {
id: payload.call_id.clone(),
changes: convert_patch_changes(&payload.changes),
status: PatchApplyStatus::InProgress,
}
}
pub fn build_file_change_end_item(payload: &PatchApplyEndEvent) -> ThreadItemPayload {
ThreadItemPayload::FileChange {
id: payload.call_id.clone(),
changes: convert_patch_changes(&payload.changes),
status: (&payload.status).into(),
}
}
pub fn build_command_execution_begin_item(payload: &ExecCommandBeginEvent) -> ThreadItemPayload {
let presentation =
CommandExecutionPresentation::from_raw(&payload.command, &payload.parsed_cmd, &payload.cwd);
ThreadItemPayload::CommandExecution {
model_context: None,
sandbox_type: None,
id: payload.call_id.clone(),
plugin_id: payload.plugin_id.clone(),
script_path: payload.script_path.clone(),
command: presentation.command,
cwd: payload.cwd.clone().into(),
process_id: payload.process_id.clone(),
source: payload.source.into(),
status: CommandExecutionStatus::InProgress,
command_actions: presentation.command_actions,
aggregated_output: None,
exit_code: None,
duration_ms: None,
}
}
pub fn build_command_execution_end_item(payload: &ExecCommandEndEvent) -> ThreadItemPayload {
let aggregated_output = if payload.aggregated_output.is_empty() {
None
} else {
Some(payload.aggregated_output.clone())
};
let duration_ms = i64::try_from(payload.duration.as_millis()).unwrap_or(i64::MAX);
let presentation =
CommandExecutionPresentation::from_raw(&payload.command, &payload.parsed_cmd, &payload.cwd);
ThreadItemPayload::CommandExecution {
model_context: None,
sandbox_type: None,
id: payload.call_id.clone(),
plugin_id: payload.plugin_id.clone(),
script_path: payload.script_path.clone(),
command: presentation.command,
cwd: payload.cwd.clone().into(),
process_id: payload.process_id.clone(),
source: payload.source.into(),
status: (&payload.status).into(),
command_actions: presentation.command_actions,
aggregated_output,
exit_code: Some(payload.exit_code),
duration_ms: Some(duration_ms),
}
}
fn command_actions_for_path_uri(parsed_cmd: &[ParsedCommand], cwd: &PathUri) -> Vec<CommandAction> {
parsed_cmd
.iter()
.cloned()
.filter_map(|parsed| match parsed {
ParsedCommand::Read { cmd, name, path } => {
// Resolve against the executor's URI, not the app-server's filesystem. POSIX
// non-UTF-8 paths are percent-encoded, not opaque. Expanding `~` or resolving a
// genuinely opaque cwd would require executor-native state unavailable here.
match cwd.join(path.to_string_lossy().as_ref()) {
Ok(path) => Some(CommandAction::Read {
command: redact_secrets(cmd),
name,
path: path.into(),
}),
Err(error) => {
warn!(
command = cmd,
%cwd,
file_path = %path.display(),
%error,
"omitting read action: invalid file path or cwd"
);
None
}
}
}
ParsedCommand::ListFiles { cmd, path } => Some(CommandAction::ListFiles {
command: redact_secrets(cmd),
path,
}),
ParsedCommand::Search { cmd, query, path } => Some(CommandAction::Search {
command: redact_secrets(cmd),
query: query.map(redact_secrets),
path,
}),
ParsedCommand::Unknown { cmd } => Some(CommandAction::Unknown {
command: redact_secrets(cmd),
}),
})
.collect()
}
/// Build a guardian-derived [`ThreadItem`].
///
/// Currently this only synthesizes [`ThreadItem::CommandExecution`] for
/// [`GuardianAssessmentAction::Command`] and [`GuardianAssessmentAction::Execve`].
/// Stdin reviews are child approvals and must not change the parent item lifecycle.
pub fn build_item_from_guardian_event(
assessment: &GuardianAssessmentEvent,
status: CommandExecutionStatus,
) -> Option<ThreadItemPayload> {
match &assessment.action {
GuardianAssessmentAction::Command { command, cwd, .. } => {
let id = assessment.target_item_id.as_ref()?;
let command = command.clone();
let command_actions = vec![CommandAction::Unknown {
command: command.clone(),
}];
Some(ThreadItemPayload::CommandExecution {
id: id.clone(),
model_context: assessment.model_context.clone(),
sandbox_type: None,
plugin_id: assessment.plugin_id.clone(),
script_path: assessment.script_path.clone(),
command,
cwd: cwd.clone(),
process_id: None,
source: CommandExecutionSource::Agent,
status,
command_actions,
aggregated_output: None,
exit_code: None,
duration_ms: None,
})
}
GuardianAssessmentAction::Execve {
program, argv, cwd, ..
} => {
let id = assessment.target_item_id.as_ref()?;
let argv = if argv.is_empty() {
vec![program.clone()]
} else {
std::iter::once(program.clone())
.chain(argv.iter().skip(1).cloned())
.collect::<Vec<_>>()
};
let command = shlex_join(&argv);
let parsed_cmd = parse_command(&argv);
let command_actions = if parsed_cmd.is_empty() {
vec![CommandAction::Unknown {
command: command.clone(),
}]
} else {
parsed_cmd
.into_iter()
.map(|parsed| CommandAction::from_core_with_cwd(parsed, cwd))
.collect()
};
Some(ThreadItemPayload::CommandExecution {
id: id.clone(),
model_context: assessment.model_context.clone(),
sandbox_type: None,
plugin_id: assessment.plugin_id.clone(),
script_path: assessment.script_path.clone(),
command,
cwd: cwd.clone().into(),
process_id: None,
source: CommandExecutionSource::Agent,
status,
command_actions,
aggregated_output: None,
exit_code: None,
duration_ms: None,
})
}
GuardianAssessmentAction::WriteStdin { .. }
| GuardianAssessmentAction::ApplyPatch { .. }
| GuardianAssessmentAction::NetworkAccess { .. }
| GuardianAssessmentAction::McpToolCall { .. }
| GuardianAssessmentAction::RequestPermissions { .. } => None,
}
}
pub fn guardian_auto_approval_review_notification(
conversation_id: &ThreadId,
event_turn_id: &str,
assessment: &GuardianAssessmentEvent,
) -> ServerNotification {
let turn_id = if assessment.turn_id.is_empty() {
event_turn_id.to_string()
} else {
assessment.turn_id.clone()
};
let review = GuardianApprovalReview {
status: match assessment.status {
akode_protocol::protocol::GuardianAssessmentStatus::InProgress => {
GuardianApprovalReviewStatus::InProgress
}
akode_protocol::protocol::GuardianAssessmentStatus::Approved => {
GuardianApprovalReviewStatus::Approved
}
akode_protocol::protocol::GuardianAssessmentStatus::Denied => {
GuardianApprovalReviewStatus::Denied
}
akode_protocol::protocol::GuardianAssessmentStatus::TimedOut => {
GuardianApprovalReviewStatus::TimedOut
}
akode_protocol::protocol::GuardianAssessmentStatus::Aborted => {
GuardianApprovalReviewStatus::Aborted
}
},
risk_level: assessment.risk_level.map(Into::into),
user_authorization: assessment.user_authorization.map(Into::into),
rationale: assessment.rationale.clone(),
};
let action = assessment.action.clone().into();
match assessment.status {
akode_protocol::protocol::GuardianAssessmentStatus::InProgress => {
ServerNotification::ItemGuardianApprovalReviewStarted(
ItemGuardianApprovalReviewStartedNotification {
thread_id: conversation_id.to_string(),
turn_id,
review_id: assessment.id.clone(),
started_at_ms: assessment.started_at_ms,
target_item_id: assessment.target_item_id.clone(),
review,
action,
},
)
}
akode_protocol::protocol::GuardianAssessmentStatus::Approved
| akode_protocol::protocol::GuardianAssessmentStatus::Denied
| akode_protocol::protocol::GuardianAssessmentStatus::TimedOut
| akode_protocol::protocol::GuardianAssessmentStatus::Aborted => {
ServerNotification::ItemGuardianApprovalReviewCompleted(
ItemGuardianApprovalReviewCompletedNotification {
thread_id: conversation_id.to_string(),
turn_id,
review_id: assessment.id.clone(),
started_at_ms: assessment.started_at_ms,
completed_at_ms: assessment
.completed_at_ms
.unwrap_or(assessment.started_at_ms),
target_item_id: assessment.target_item_id.clone(),
decision_source: assessment
.decision_source
.map(AutoReviewDecisionSource::from)
.unwrap_or(AutoReviewDecisionSource::Agent),
review,
action,
},
)
}
}
}
pub fn convert_patch_changes(changes: &HashMap<PathBuf, FileChange>) -> Vec<FileUpdateChange> {
let mut converted: Vec<FileUpdateChange> = changes
.iter()
.map(|(path, change)| FileUpdateChange {
path: path.to_string_lossy().into_owned(),
kind: map_patch_change_kind(change),
diff: format_file_change_diff(change),
})
.collect();
converted.sort_by(|a, b| a.path.cmp(&b.path));
converted
}
fn map_patch_change_kind(change: &FileChange) -> PatchChangeKind {
match change {
FileChange::Add { .. } => PatchChangeKind::Add,
FileChange::Delete { .. } => PatchChangeKind::Delete,
FileChange::Update { move_path, .. } => PatchChangeKind::Update {
move_path: move_path.clone(),
},
}
}
fn format_file_change_diff(change: &FileChange) -> String {
match change {
FileChange::Add { content } => content.clone(),
FileChange::Delete { content } => content.clone(),
FileChange::Update {
unified_diff,
move_path,
} => {
if let Some(path) = move_path {
format!("{unified_diff}\n\nMoved to: {}", path.display())
} else {
unified_diff.clone()
}
}
}
}
#[cfg(test)]
#[path = "item_builders_tests.rs"]
mod tests;

View File

@@ -0,0 +1,185 @@
use super::*;
use crate::protocol::thread_history::build_turns_from_rollout_items;
use crate::protocol::v2::ThreadItem;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ExecCommandSource;
use akode_protocol::protocol::GuardianAssessmentStatus;
use akode_protocol::protocol::TurnStartedEvent;
use akode_rollout::RolloutItem;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn read_command_actions_preserve_native_and_foreign_paths() {
let api_key = "sk-abcdefghijklmnopqrstuvwxyz123456";
for (cwd_uri, relative_path, expected_path) in [
(
"file:///home/alice/repo",
"src/main.rs",
"/home/alice/repo/src/main.rs",
),
(
"file:///C:/Users/Alice%20Smith/repo",
r"src\main.rs",
r"C:\Users\Alice Smith\repo\src\main.rs",
),
(
"file:///C:/Users/Alice%20Smith/repo",
r"C:src\main.rs",
r"C:\Users\Alice Smith\repo\src\main.rs",
),
(
"file://server/share/repo",
r"src\main.rs",
r"\\server\share\repo\src\main.rs",
),
] {
let cwd = PathUri::parse(cwd_uri).expect("valid cross-platform cwd");
let command = format!("cat {relative_path}");
let parsed_cmd = vec![
ParsedCommand::Read {
cmd: command.clone(),
name: "main.rs".to_string(),
path: PathBuf::from(relative_path),
},
ParsedCommand::ListFiles {
cmd: "ls".to_string(),
path: Some("subdir".to_string()),
},
ParsedCommand::Search {
cmd: format!("rg {api_key}"),
query: Some(api_key.to_string()),
path: Some("src".to_string()),
},
ParsedCommand::Search {
cmd: "rg needle".to_string(),
query: Some("needle".to_string()),
path: Some("src".to_string()),
},
];
assert_eq!(
serde_json::to_value(command_actions_for_path_uri(&parsed_cmd, &cwd))
.expect("command actions should serialize"),
json!([
{
"type": "read",
"command": command,
"name": "main.rs",
"path": expected_path,
},
{
"type": "listFiles",
"command": "ls",
"path": "subdir",
},
{
"type": "search",
"command": "rg [REDACTED_SECRET]",
"query": "[REDACTED_SECRET]",
"path": "src",
},
{
"type": "search",
"command": "rg needle",
"query": "needle",
"path": "src",
},
]),
"resolving command actions against {cwd_uri}",
);
}
}
#[test]
fn guardian_stdin_reviews_preserve_parent_command_history() {
let cwd = PathUri::parse("file:///home/alice/repo").expect("valid cwd URI");
let begin = ExecCommandBeginEvent {
call_id: "terminal-command".into(),
plugin_id: None,
script_path: None,
process_id: Some("42".into()),
turn_id: "turn-1".into(),
started_at_ms: 1_000,
command: vec!["cat".into()],
cwd: cwd.clone(),
parsed_cmd: vec![ParsedCommand::Unknown { cmd: "cat".into() }],
source: ExecCommandSource::UnifiedExecStartup,
interaction_input: None,
};
let start_turn = |turn_id: &str| {
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_attribution: None,
turn_id: turn_id.into(),
root_turn_id: None,
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
}))
};
let mut items = vec![
start_turn("turn-1"),
RolloutItem::EventMsg(EventMsg::ExecCommandBegin(begin.clone())),
start_turn("turn-2"),
];
let expected = build_turns_from_rollout_items(&items);
assert_eq!(expected.len(), 2);
assert_eq!(
expected[0].items,
[ThreadItem {
payload: build_command_execution_begin_item(&begin),
started_at_ms: Some(begin.started_at_ms),
completed_at_ms: None,
}],
);
assert!(expected[1].items.is_empty());
let assessment = GuardianAssessmentEvent {
review_reason: None,
model_context: None,
id: "review-stdin".into(),
target_item_id: Some("terminal-command".into()),
plugin_id: None,
script_path: None,
turn_id: "turn-2".into(),
started_at_ms: 2_000,
completed_at_ms: None,
status: GuardianAssessmentStatus::InProgress,
risk_level: None,
user_authorization: None,
rationale: None,
decision_source: None,
action: GuardianAssessmentAction::WriteStdin {
approval_id: "stdin-approval".into(),
process_id: "42".into(),
stdin: "yes\n".into(),
cwd,
},
};
for turn_id in ["turn-1", "turn-2"] {
for status in [
GuardianAssessmentStatus::InProgress,
GuardianAssessmentStatus::Approved,
GuardianAssessmentStatus::Denied,
GuardianAssessmentStatus::TimedOut,
GuardianAssessmentStatus::Aborted,
] {
items.push(RolloutItem::EventMsg(EventMsg::GuardianAssessment(
GuardianAssessmentEvent {
review_reason: None,
turn_id: turn_id.into(),
status,
..assessment.clone()
},
)));
assert_eq!(
build_turns_from_rollout_items(&items),
expected,
"stdin review {status:?} in {turn_id} must preserve command history",
);
items.pop();
}
}
}

View File

@@ -0,0 +1,24 @@
use crate::protocol::v1;
use crate::protocol::v2;
impl From<v1::ExecOneOffCommandParams> for v2::CommandExecParams {
fn from(value: v1::ExecOneOffCommandParams) -> Self {
Self {
command: value.command,
process_id: None,
tty: false,
stream_stdin: false,
stream_stdout_stderr: false,
output_bytes_cap: None,
disable_output_cap: false,
disable_timeout: false,
timeout_ms: value
.timeout_ms
.map(|timeout| i64::try_from(timeout).unwrap_or(60_000)),
cwd: value.cwd,
env: None,
size: None,
sandbox_policy: value.sandbox_policy.map(std::convert::Into::into),
permission_profile: None,
}
}
}

View File

@@ -0,0 +1,13 @@
// Module declarations for the app-server protocol namespace.
// Exposes protocol pieces used by `lib.rs` via `pub use protocol::common::*;`.
pub mod common;
pub mod event_mapping;
pub mod item_builders;
mod mappers;
mod serde_helpers;
pub mod thread_history;
pub mod thread_history_projection;
mod turn_items_view;
pub mod v1;
pub mod v2;

View File

@@ -0,0 +1,40 @@
use std::path::PathBuf;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
#[cfg(test)]
pub(crate) fn nullable_string_schema(
generator: &mut schemars::r#gen::SchemaGenerator,
) -> schemars::schema::Schema {
generator.subschema_for::<Option<String>>()
}
pub fn deserialize_empty_path_as_none<'de, D>(deserializer: D) -> Result<Option<PathBuf>, D::Error>
where
D: Deserializer<'de>,
{
let path = Option::<PathBuf>::deserialize(deserializer)?;
Ok(path.filter(|path| !path.as_os_str().is_empty()))
}
pub fn deserialize_double_option<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
where
T: Deserialize<'de>,
D: Deserializer<'de>,
{
serde_with::rust::double_option::deserialize(deserializer)
}
pub fn serialize_double_option<T, S>(
value: &Option<Option<T>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
T: Serialize,
S: Serializer,
{
serde_with::rust::double_option::serialize(value, serializer)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
//! Stateless projection from canonical paginated rollout records to thread-history changes.
//!
//! This module is only for the new paginated rollout format that persists canonical
//! `ItemCompleted(TurnItem)` records, not legacy event-only rollouts.
use akode_protocol::protocol::EventMsg;
use akode_rollout::RolloutItem;
use akode_rollout::RolloutLine;
use crate::protocol::thread_history::ThreadHistoryChangeSet;
use crate::protocol::thread_history::ThreadHistoryItemChange;
use crate::protocol::thread_history::ThreadHistoryTurnMetadata;
use crate::protocol::v2::ThreadItem;
use crate::protocol::v2::TurnError;
use crate::protocol::v2::TurnStatus;
/// Project one durable rollout line without reconstructing earlier history.
///
/// Callers that replay a JSONL suffix should invoke it once per line, in ordinal order, so storage
/// can preserve the first and latest timestamps for repeated item snapshots independently.
pub fn project_rollout_line(line: &RolloutLine) -> ThreadHistoryChangeSet {
match &line.item {
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => ThreadHistoryChangeSet {
changed_turns: vec![ThreadHistoryTurnMetadata {
turn_id: event.turn_id.clone(),
root_turn_id: event.root_turn_id.clone(),
status: TurnStatus::InProgress,
error: None,
started_at: event.started_at,
completed_at: None,
duration_ms: None,
}],
..Default::default()
},
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => ThreadHistoryChangeSet {
changed_turns: vec![ThreadHistoryTurnMetadata {
turn_id: event.turn_id.clone(),
root_turn_id: event.root_turn_id.clone(),
status: if event.error.is_some() {
TurnStatus::Failed
} else {
TurnStatus::Completed
},
error: event.error.as_ref().map(|error| TurnError {
misalignment: error.misalignment.clone().map(Into::into),
message: error.message.clone(),
codex_error_info: error.codex_error_info.clone().map(Into::into),
additional_details: None,
}),
started_at: event.started_at,
completed_at: event.completed_at,
duration_ms: event.duration_ms,
}],
..Default::default()
},
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => {
let Some(turn_id) = event.turn_id.as_ref() else {
return ThreadHistoryChangeSet::default();
};
ThreadHistoryChangeSet {
changed_turns: vec![ThreadHistoryTurnMetadata {
turn_id: turn_id.clone(),
root_turn_id: event.root_turn_id.clone(),
status: TurnStatus::Interrupted,
error: event.error.as_ref().map(|error| TurnError {
message: error.message.clone(),
codex_error_info: error.codex_error_info.clone().map(Into::into),
misalignment: error.misalignment.clone().map(Into::into),
additional_details: None,
}),
started_at: event.started_at,
completed_at: event.completed_at,
duration_ms: event.duration_ms,
}],
..Default::default()
}
}
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => ThreadHistoryChangeSet {
changed_items: vec![ThreadHistoryItemChange {
turn_id: event.turn_id.clone(),
item: ThreadItem::from(event),
}],
..Default::default()
},
RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SessionMeta(_)
| RolloutItem::ResponseItem(_)
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::Compacted(_)
| RolloutItem::TurnContext(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::WorldState(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::EventMsg(_) => ThreadHistoryChangeSet::default(),
}
}
#[cfg(test)]
#[path = "thread_history_projection_tests.rs"]
mod tests;

View File

@@ -0,0 +1,296 @@
use akode_protocol::ThreadId;
use akode_protocol::items::AgentMessageContent;
use akode_protocol::items::AgentMessageItem;
use akode_protocol::items::TurnItem;
use akode_protocol::items::UserMessageItem;
use akode_protocol::protocol::ErrorEvent;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ItemCompletedEvent;
use akode_protocol::protocol::TurnAbortReason;
use akode_protocol::protocol::TurnAbortedEvent;
use akode_protocol::protocol::TurnCompleteEvent;
use akode_protocol::protocol::TurnStartedEvent;
use akode_protocol::security_risk::SecurityRiskScore;
use akode_protocol::user_input::UserInput;
use akode_rollout::CompactedItem;
use akode_rollout::RolloutItem;
use akode_rollout::RolloutLine;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use super::*;
use crate::protocol::v2::ThreadItemPayload;
use crate::protocol::v2::TurnError;
#[test]
fn projects_turn_lifecycle_without_prior_builder_state() {
let started = project(RolloutItem::EventMsg(EventMsg::TurnStarted(
TurnStartedEvent {
turn_attribution: None,
turn_id: "turn-1".to_string(),
root_turn_id: Some("root-turn".into()),
trace_id: None,
started_at: Some(10),
model_context_window: None,
collaboration_mode_kind: Default::default(),
},
)));
let completed = project(RolloutItem::EventMsg(EventMsg::TurnComplete(
TurnCompleteEvent {
root_turn_id: Some("root-turn".into()),
turn_id: "turn-1".to_string(),
last_agent_message: None,
error: None,
started_at: Some(10),
completed_at: Some(20),
duration_ms: Some(10_000),
time_to_first_token_ms: None,
},
)));
assert_eq!(started.changed_turns.len(), 1);
assert_eq!(started.changed_turns[0].turn_id, "turn-1");
assert_eq!(started.changed_turns[0].status, TurnStatus::InProgress);
assert_eq!(started.changed_turns[0].started_at, Some(10));
assert_eq!(
started.changed_turns[0].root_turn_id.as_deref(),
Some("root-turn")
);
assert_eq!(
completed,
ThreadHistoryChangeSet {
changed_turns: vec![ThreadHistoryTurnMetadata {
turn_id: "turn-1".to_string(),
root_turn_id: Some("root-turn".into()),
status: TurnStatus::Completed,
error: None,
started_at: Some(10),
completed_at: Some(20),
duration_ms: Some(10_000),
}],
..Default::default()
}
);
}
#[test]
fn projects_failed_turn_completion_as_snapshot() {
let error = ErrorEvent {
misalignment: None,
message: "request failed".to_string(),
codex_error_info: None,
rejected_audio_file_ids: Vec::new(),
};
let changes = project(RolloutItem::EventMsg(EventMsg::TurnComplete(
TurnCompleteEvent {
root_turn_id: None,
turn_id: "turn-1".to_string(),
last_agent_message: None,
error: Some(error),
started_at: Some(10),
completed_at: Some(20),
duration_ms: Some(10_000),
time_to_first_token_ms: None,
},
)));
assert_eq!(
changes,
ThreadHistoryChangeSet {
changed_turns: vec![ThreadHistoryTurnMetadata {
turn_id: "turn-1".to_string(),
root_turn_id: None,
status: TurnStatus::Failed,
error: Some(TurnError {
misalignment: None,
message: "request failed".to_string(),
codex_error_info: None,
additional_details: None,
}),
started_at: Some(10),
completed_at: Some(20),
duration_ms: Some(10_000),
}],
..Default::default()
}
);
}
#[test]
fn projects_completed_canonical_turn_items() {
let thread_id = ThreadId::default();
let user_item = TurnItem::UserMessage(UserMessageItem {
id: "user-1".to_string(),
client_id: None,
content: vec![UserInput::Text {
text: "hello".to_string(),
text_elements: Vec::new(),
}],
});
let agent_item = TurnItem::AgentMessage(AgentMessageItem {
moderation: None,
id: "agent-1".to_string(),
content: vec![AgentMessageContent::Text {
text: "done".to_string(),
}],
phase: None,
memory_citation: None,
delivery: None,
questions: None,
});
let user_changes = project(item_completed(thread_id, "turn-1", user_item.clone()));
let agent_changes = project(item_completed(thread_id, "turn-1", agent_item.clone()));
assert_eq!(
user_changes.changed_items,
vec![ThreadHistoryItemChange {
turn_id: "turn-1".to_string(),
item: ThreadItem {
payload: ThreadItemPayload::from(user_item),
started_at_ms: Some(100),
completed_at_ms: Some(123)
}
}]
);
assert_eq!(
agent_changes.changed_items,
vec![ThreadHistoryItemChange {
turn_id: "turn-1".to_string(),
item: ThreadItem {
payload: ThreadItemPayload::from(agent_item),
started_at_ms: Some(100),
completed_at_ms: Some(123)
}
}]
);
}
#[test]
fn projects_optional_completed_item_lifecycle_timestamps() {
let item = TurnItem::UserMessage(UserMessageItem {
id: "user-1".to_string(),
client_id: None,
content: Vec::new(),
});
for (started_at_ms, completed_at_ms, expected_completed_at_ms) in
[(None, 123, Some(123)), (Some(100), 0, None)]
{
let changes = project(RolloutItem::EventMsg(EventMsg::ItemCompleted(
ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::default(),
turn_id: "turn-1".to_string(),
item: item.clone(),
started_at_ms,
completed_at_ms,
},
)));
assert_eq!(
changes,
ThreadHistoryChangeSet {
changed_items: vec![ThreadHistoryItemChange {
turn_id: "turn-1".to_string(),
item: ThreadItem {
payload: ThreadItemPayload::from(item.clone()),
started_at_ms,
completed_at_ms: expected_completed_at_ms
}
}],
..Default::default()
}
);
}
}
#[test]
fn ignores_legacy_abort_without_turn_id_and_context_only_records() {
let aborted = project(RolloutItem::EventMsg(EventMsg::TurnAborted(
TurnAbortedEvent {
root_turn_id: None,
turn_id: None,
reason: TurnAbortReason::Interrupted,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
},
)));
let compacted = project(RolloutItem::Compacted(Box::new(CompactedItem {
message: String::new(),
replacement_history: None,
retained_context: None,
guardian_history: None,
mcp_resource_origins: None,
window_number: None,
first_window_id: None,
previous_window_id: None,
window_id: None,
compaction_response_id: None,
latest_token_usage_record: None,
resume_metadata: None,
})));
let security_risk = project(RolloutItem::SecurityRiskScore(SecurityRiskScore {
scores: BTreeMap::from([("action_risk".to_string(), 0.92)]),
call_id: None,
action: None,
sampled_at: None,
}));
assert!(aborted.is_empty());
assert!(compacted.is_empty());
assert!(security_risk.is_empty());
}
#[test]
fn projects_identified_turn_aborts() {
let changes = project(RolloutItem::EventMsg(EventMsg::TurnAborted(
TurnAbortedEvent {
root_turn_id: Some("root-turn".into()),
turn_id: Some("turn-1".to_string()),
reason: TurnAbortReason::Interrupted,
error: None,
started_at: Some(10),
completed_at: Some(20),
duration_ms: Some(10_000),
},
)));
assert_eq!(
changes,
ThreadHistoryChangeSet {
changed_turns: vec![ThreadHistoryTurnMetadata {
turn_id: "turn-1".to_string(),
root_turn_id: Some("root-turn".into()),
status: TurnStatus::Interrupted,
error: None,
started_at: Some(10),
completed_at: Some(20),
duration_ms: Some(10_000),
}],
..Default::default()
}
);
}
fn project(item: RolloutItem) -> ThreadHistoryChangeSet {
project_rollout_line(&RolloutLine {
timestamp: "2026-07-09T00:00:00.000Z".to_string(),
ordinal: Some(7),
item,
})
}
fn item_completed(thread_id: ThreadId, turn_id: &str, item: TurnItem) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id,
turn_id: turn_id.to_string(),
item,
started_at_ms: Some(100),
completed_at_ms: 123,
}))
}

View File

@@ -0,0 +1,33 @@
//! Projects a turn's items without copying payloads excluded by the requested view.
use super::v2::ThreadItemPayload;
use super::v2::TurnItemsView;
use std::borrow::Borrow;
impl TurnItemsView {
/// Copies only the items included in this view, preserving summary selection order.
pub fn project_items<T: Borrow<ThreadItemPayload> + Clone>(self, items: &[T]) -> Vec<T> {
match self {
Self::NotLoaded => Vec::new(),
Self::Full => items.to_vec(),
Self::Summary => {
let first_user_message = items
.iter()
.find(|item| matches!((*item).borrow(), ThreadItemPayload::UserMessage { .. }));
let final_agent_message = items.iter().rev().find(|item| {
matches!((*item).borrow(), ThreadItemPayload::AgentMessage { .. })
});
match (first_user_message, final_agent_message) {
(Some(user_message), Some(agent_message))
if user_message.borrow().id() != agent_message.borrow().id() =>
{
vec![user_message.clone(), agent_message.clone()]
}
(Some(user_message), _) => vec![user_message.clone()],
(None, Some(agent_message)) => vec![agent_message.clone()],
(None, None) => Vec::new(),
}
}
}
}
}

View File

@@ -0,0 +1,248 @@
use std::collections::HashMap;
use std::path::PathBuf;
use crate::JsonSchema;
use crate::TS;
use akode_protocol::ThreadId;
use akode_protocol::config_types::ForcedLoginMethod;
use akode_protocol::config_types::ReasoningSummary;
use akode_protocol::config_types::SandboxMode;
use akode_protocol::config_types::Verbosity;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::parse_command::ParsedCommand;
use akode_protocol::protocol::AskForApproval;
use akode_protocol::protocol::FileChange;
pub use akode_protocol::protocol::GitSha;
use akode_protocol::protocol::ReviewDecision;
use akode_protocol::protocol::SandboxPolicy;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::TurnAbortReason;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
use crate::protocol::common::AuthMode;
use crate::protocol::v2::ForcedChatgptWorkspaceIds;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct InitializeParams {
pub client_info: ClientInfo,
#[serde(skip_serializing_if = "Option::is_none")]
pub capabilities: Option<InitializeCapabilities>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct ClientInfo {
pub name: String,
pub title: Option<String>,
pub version: String,
}
/// Client-declared capabilities negotiated during initialize.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct InitializeCapabilities {
/// Present `humanCommand` approvals to a person and return only a one-time decision.
/// Requires `experimentalApi`. Pending requests can be replayed to compatible clients.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub required_human_approval: bool,
/// Use explicit gateway OAuth login instead of automatic browser authorization.
/// Applies to this app-server's gateway runtime; later connections cannot undo it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub explicit_gateway_oauth: bool,
/// Opt into receiving experimental API methods and fields.
#[serde(default)]
pub experimental_api: bool,
/// Legacy opt-in for the `openai/form` MCP extension.
///
/// New clients should declare `openai/form` in [`Self::extensions`].
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub mcp_server_openai_form_elicitation: bool,
/// Exact notification method names that should be suppressed for this
/// connection (for example `thread/started`).
#[ts(optional = nullable)]
pub opt_out_notification_methods: Option<Vec<String>>,
/// MCP extension settings declared by the app-server client.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub extensions: Option<HashMap<String, serde_json::Value>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResponse {
pub user_agent: String,
/// Absolute path to the server's $AKODE_HOME directory.
pub codex_home: AbsolutePathBuf,
/// Platform family for the running app-server target, for example
/// `"unix"` or `"windows"`.
pub platform_family: String,
/// Operating system for the running app-server target, for example
/// `"macos"`, `"linux"`, or `"windows"`.
pub platform_os: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(untagged)]
pub enum GetConversationSummaryParams {
RolloutPath {
#[serde(rename = "rolloutPath")]
rollout_path: PathBuf,
},
ThreadId {
#[serde(rename = "conversationId")]
conversation_id: ThreadId,
},
}
#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct GetConversationSummaryResponse {
pub summary: ConversationSummary,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct ConversationSummary {
pub conversation_id: ThreadId,
pub path: PathBuf,
pub preview: String,
pub timestamp: Option<String>,
pub updated_at: Option<String>,
pub model_provider: String,
pub cwd: PathBuf,
pub cli_version: String,
pub source: SessionSource,
pub git_info: Option<ConversationGitInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub struct ConversationGitInfo {
pub sha: Option<String>,
pub branch: Option<String>,
pub origin_url: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct LoginApiKeyParams {
pub api_key: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct GitDiffToRemoteResponse {
pub sha: GitSha,
pub diff: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct ApplyPatchApprovalParams {
pub conversation_id: ThreadId,
/// Use to correlate this with [akode_protocol::protocol::PatchApplyBeginEvent]
/// and [akode_protocol::protocol::PatchApplyEndEvent].
pub call_id: String,
pub file_changes: HashMap<PathBuf, FileChange>,
/// Optional explanatory reason (e.g. request for extra write access).
pub reason: Option<String>,
/// When set, the agent is asking the user to allow writes under this root
/// for the remainder of the session (unclear if this is honored today).
pub grant_root: Option<PathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct ApplyPatchApprovalResponse {
pub decision: ReviewDecision,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct ExecCommandApprovalParams {
pub conversation_id: ThreadId,
/// Use to correlate this with [akode_protocol::protocol::ExecCommandBeginEvent]
/// and [akode_protocol::protocol::ExecCommandEndEvent].
pub call_id: String,
/// Identifier for this specific approval callback.
pub approval_id: Option<String>,
pub command: Vec<String>,
pub cwd: PathBuf,
pub reason: Option<String>,
pub parsed_cmd: Vec<ParsedCommand>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
pub struct ExecCommandApprovalResponse {
pub decision: ReviewDecision,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct GitDiffToRemoteParams {
pub cwd: PathBuf,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct GetAuthStatusParams {
pub include_token: Option<bool>,
pub refresh_token: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct ExecOneOffCommandParams {
pub command: Vec<String>,
pub timeout_ms: Option<u64>,
pub cwd: Option<PathBuf>,
pub sandbox_policy: Option<SandboxPolicy>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct GetAuthStatusResponse {
pub auth_method: Option<AuthMode>,
pub auth_token: Option<String>,
pub requires_openai_auth: Option<bool>,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Serialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct UserSavedConfig {
pub approval_policy: Option<AskForApproval>,
pub sandbox_mode: Option<SandboxMode>,
pub sandbox_settings: Option<SandboxSettings>,
pub forced_chatgpt_workspace_id: Option<ForcedChatgptWorkspaceIds>,
pub forced_login_method: Option<ForcedLoginMethod>,
pub model: Option<String>,
pub model_reasoning_effort: Option<ReasoningEffort>,
pub model_reasoning_summary: Option<ReasoningSummary>,
pub model_verbosity: Option<Verbosity>,
pub tools: Option<Tools>,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Serialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct Tools {
pub web_search: Option<bool>,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Serialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct SandboxSettings {
#[serde(default)]
pub writable_roots: Vec<AbsolutePathBuf>,
pub network_access: Option<bool>,
pub exclude_tmpdir_env_var: Option<bool>,
pub exclude_slash_tmp: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct InterruptConversationResponse {
pub abort_reason: TurnAbortReason,
}

View File

@@ -0,0 +1,616 @@
use super::ThreadUsage;
use crate::JsonSchema;
use crate::TS;
use crate::protocol::common::AuthMode;
use akode_experimental_api_macros::ExperimentalApi;
use akode_protocol::account::PlanType;
use akode_protocol::account::ProviderAccount;
use akode_protocol::protocol::CreditsSnapshot as CoreCreditsSnapshot;
use akode_protocol::protocol::RateLimitReachedType as CoreRateLimitReachedType;
use akode_protocol::protocol::RateLimitSnapshot as CoreRateLimitSnapshot;
use akode_protocol::protocol::RateLimitWindow as CoreRateLimitWindow;
use akode_protocol::protocol::SpendControlLimitSnapshot as CoreSpendControlLimitSnapshot;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum Account {
#[serde(rename = "apiKey", rename_all = "camelCase")]
#[ts(rename = "apiKey", rename_all = "camelCase")]
ApiKey {},
}
impl From<ProviderAccount> for Account {
fn from(account: ProviderAccount) -> Self {
match account {
ProviderAccount::ApiKey => Self::ApiKey {},
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(tag = "type")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum LoginAccountParams {
#[serde(rename = "apiKey", rename_all = "camelCase")]
#[ts(rename = "apiKey", rename_all = "camelCase")]
ApiKey {
#[serde(rename = "apiKey")]
#[ts(rename = "apiKey")]
api_key: String,
},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum LoginAccountResponse {
#[serde(rename = "apiKey", rename_all = "camelCase")]
#[ts(rename = "apiKey", rename_all = "camelCase")]
ApiKey {},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CancelLoginAccountParams {
pub login_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum CancelLoginAccountStatus {
Canceled,
NotFound,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CancelLoginAccountResponse {
pub status: CancelLoginAccountStatus,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct LogoutAccountResponse {}
/// Usage-read capabilities of the requesting client, never inferred from its experiment arm.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetAccountRateLimitsParams {
/// The client supports automatic Luna Reserve fallback. For eligible ChatGPT CLI users,
/// allow the backend to record experiment exposure after ordinary usage is blocked.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub supports_luna_reserve: bool,
/// Skip the separate reset-credit detail lookup for background usage polls. The usage
/// response still includes the available count; omitted/false preserves detailed reads.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub exclude_reset_credit_details: bool,
}
pub type NullableGetAccountRateLimitsParams = Option<GetAccountRateLimitsParams>;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetAccountRateLimitsResponse {
/// Backend permission for ordinary included usage, validated against the active account.
/// Null means unavailable; clients must not infer recovery from percentages or reset times.
pub ordinary_usage_allowed: Option<bool>,
/// Backward-compatible single-bucket view; mirrors the historical payload.
pub rate_limits: RateLimitSnapshot,
/// Multi-bucket view keyed by metered `limit_id` (for example, `codex`).
pub rate_limits_by_limit_id: Option<HashMap<String, RateLimitSnapshot>>,
pub rate_limit_reset_credits: Option<RateLimitResetCreditsSummary>,
/// Account associated with this usage snapshot, when supplied by the backend.
pub account_id: Option<String>,
/// Optional backend-owned banner from the same usage read. Its nested keys retain the
/// backend's snake_case contract; an absent banner leaves the client's existing UI unchanged.
pub rate_limit_upsell: Option<serde_json::Value>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RateLimitResetCreditsSummary {
pub available_count: i64,
/// Detail rows for available reset credits, when the backend provides them.
///
/// `null` means only `availableCount` is known, while an empty array means details were fetched
/// and no available credits were returned. The backend may cap this list, so its length can be
/// less than `availableCount`.
pub credits: Option<Vec<RateLimitResetCredit>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RateLimitResetCredit {
/// Opaque backend identifier for this reset credit.
pub id: String,
pub reset_type: RateLimitResetType,
pub status: RateLimitResetCreditStatus,
/// Unix timestamp in seconds when the credit was granted.
#[ts(type = "number")]
pub granted_at: i64,
/// Unix timestamp in seconds when the credit expires, or `null` if it does not expire.
#[ts(type = "number | null")]
pub expires_at: Option<i64>,
/// Backend-provided display title for this credit, or `null` when unavailable.
pub title: Option<String>,
/// Backend-provided display description for this credit, or `null` when unavailable.
pub description: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/", rename_all = "camelCase")]
pub enum RateLimitResetType {
CodexRateLimits,
#[serde(other)]
Unknown,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/", rename_all = "camelCase")]
pub enum RateLimitResetCreditStatus {
Available,
Redeeming,
Redeemed,
#[serde(other)]
Unknown,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ConsumeAccountRateLimitResetCreditParams {
/// Identifies one logical reset attempt. A UUID is recommended; reuse the same value when
/// retrying that attempt.
pub idempotency_key: String,
/// Opaque reset-credit identifier to redeem. When omitted, the backend selects the next
/// available credit.
#[ts(optional = nullable)]
pub credit_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ConsumeAccountRateLimitResetCreditResponse {
pub outcome: ConsumeAccountRateLimitResetCreditOutcome,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/", rename_all = "camelCase")]
pub enum ConsumeAccountRateLimitResetCreditOutcome {
/// A reset credit was consumed and the eligible rate-limit windows were reset.
Reset,
/// No current rate-limit window is eligible for a reset.
NothingToReset,
/// The account has no earned reset credits available.
NoCredit,
/// The same idempotency key already completed a reset successfully.
AlreadyRedeemed,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetAccountTokenUsageParams {
/// When present, read estimated usage for this thread instead of account-wide token activity.
#[ts(optional = nullable)]
pub thread_id: Option<String>,
}
pub type NullableGetAccountTokenUsageParams = Option<GetAccountTokenUsageParams>;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetAccountTokenUsageResponse {
pub summary: AccountTokenUsageSummary,
pub daily_usage_buckets: Option<Vec<AccountTokenUsageDailyBucket>>,
/// Estimated usage when a thread was requested and its billing route is available.
#[serde(default)]
#[ts(optional, as = "Option<Option<ThreadUsage>>")]
pub thread_usage: Option<ThreadUsage>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetWorkspaceMessagesResponse {
/// Whether the workspace-message backend route is available for this client.
pub feature_enabled: bool,
/// Active workspace messages returned by the backend.
pub messages: Vec<WorkspaceMessage>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct WorkspaceMessage {
pub message_id: String,
pub message_type: WorkspaceMessageType,
pub message_body: String,
/// Unix timestamp (in seconds) when the message was created.
#[ts(type = "number | null")]
pub created_at: Option<i64>,
/// Unix timestamp (in seconds) when the message was archived.
#[ts(type = "number | null")]
pub archived_at: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/", rename_all = "snake_case")]
pub enum WorkspaceMessageType {
Headline,
Announcement,
#[serde(other)]
Unknown,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AccountTokenUsageSummary {
pub lifetime_tokens: Option<i64>,
pub peak_daily_tokens: Option<i64>,
pub longest_running_turn_sec: Option<i64>,
pub current_streak_days: Option<i64>,
pub longest_streak_days: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AccountTokenUsageDailyBucket {
pub start_date: String,
pub tokens: i64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SendAddCreditsNudgeEmailParams {
pub credit_type: AddCreditsNudgeCreditType,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/", rename_all = "snake_case")]
pub enum AddCreditsNudgeCreditType {
Credits,
UsageLimit,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SendAddCreditsNudgeEmailResponse {
pub status: AddCreditsNudgeEmailStatus,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/", rename_all = "snake_case")]
pub enum AddCreditsNudgeEmailStatus {
Sent,
CooldownActive,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetAccountParams {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetAccountResponse {
pub account: Option<Account>,
pub requires_openai_auth: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AccountUpdatedNotification {
pub auth_mode: Option<AuthMode>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/", rename_all = "camelCase")]
pub enum GatewayOAuthStatus {
NotReady,
Started,
Succeeded,
Failed,
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GatewayOAuthChangedNotification {
/// Authorization handoff, sent only to the connection that started login.
pub auth_url: Option<String>,
pub provider_id: String,
pub status: GatewayOAuthStatus,
pub error: Option<String>,
}
impl std::fmt::Debug for GatewayOAuthChangedNotification {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GatewayOAuthChangedNotification")
.field("auth_url", &self.auth_url.as_ref().map(|_| "[REDACTED]"))
.field("provider_id", &self.provider_id)
.field("status", &self.status)
.field("error", &self.error)
.finish()
}
}
/// Read credential readiness for a configured provider without starting browser login.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GatewayOAuthReadParams {
/// Defaults to the current provider when omitted.
#[ts(optional = nullable)]
pub model_provider: Option<String>,
}
pub type NullableGatewayOAuthReadParams = Option<GatewayOAuthReadParams>;
/// Authorize a configured provider without changing the default or any thread's provider.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GatewayOAuthLoginParams {
/// Defaults to the current provider when omitted.
#[ts(optional = nullable)]
pub model_provider: Option<String>,
}
pub type NullableGatewayOAuthLoginParams = Option<GatewayOAuthLoginParams>;
/// Current effective gateway policy and credential readiness; never contains credentials.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GatewayOAuthReadResponse {
pub provider_id: String,
pub provider_name: String,
/// Whether the selected provider uses gateway OAuth, even when already signed in.
pub required: bool,
/// Null when the effective provider does not use gateway OAuth.
pub status: Option<GatewayOAuthStatus>,
pub error: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GatewayOAuthLoginResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GatewayOAuthCancelResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
/// Sparse rolling rate-limit update.
///
/// Clients should merge available values into the most recent `account/rateLimits/read` response
/// or refetch that snapshot. Nullable account metadata may be unavailable in a rolling update and
/// does not clear a previously observed value.
pub struct AccountRateLimitsUpdatedNotification {
pub rate_limits: RateLimitSnapshot,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RateLimitSnapshot {
pub limit_id: Option<String>,
pub limit_name: Option<String>,
/// Normal model whose display name and reasoning options describe this quota alias.
pub normal_model_slug: Option<String>,
pub primary: Option<RateLimitWindow>,
pub secondary: Option<RateLimitWindow>,
pub credits: Option<CreditsSnapshot>,
pub individual_limit: Option<SpendControlLimitSnapshot>,
/// Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.
pub spend_control_reached: Option<bool>,
pub plan_type: Option<PlanType>,
pub rate_limit_reached_type: Option<RateLimitReachedType>,
}
impl From<CoreRateLimitSnapshot> for RateLimitSnapshot {
fn from(value: CoreRateLimitSnapshot) -> Self {
Self {
limit_id: value.limit_id,
limit_name: value.limit_name,
normal_model_slug: value.normal_model_slug,
primary: value.primary.map(RateLimitWindow::from),
secondary: value.secondary.map(RateLimitWindow::from),
credits: value.credits.map(CreditsSnapshot::from),
individual_limit: value.individual_limit.map(SpendControlLimitSnapshot::from),
spend_control_reached: value.spend_control_reached,
plan_type: value.plan_type,
rate_limit_reached_type: value
.rate_limit_reached_type
.map(RateLimitReachedType::from),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/", rename_all = "snake_case")]
pub enum RateLimitReachedType {
RateLimitReached,
WorkspaceOwnerCreditsDepleted,
WorkspaceMemberCreditsDepleted,
WorkspaceOwnerUsageLimitReached,
WorkspaceMemberUsageLimitReached,
}
impl From<CoreRateLimitReachedType> for RateLimitReachedType {
fn from(value: CoreRateLimitReachedType) -> Self {
match value {
CoreRateLimitReachedType::RateLimitReached => Self::RateLimitReached,
CoreRateLimitReachedType::WorkspaceOwnerCreditsDepleted => {
Self::WorkspaceOwnerCreditsDepleted
}
CoreRateLimitReachedType::WorkspaceMemberCreditsDepleted => {
Self::WorkspaceMemberCreditsDepleted
}
CoreRateLimitReachedType::WorkspaceOwnerUsageLimitReached => {
Self::WorkspaceOwnerUsageLimitReached
}
CoreRateLimitReachedType::WorkspaceMemberUsageLimitReached => {
Self::WorkspaceMemberUsageLimitReached
}
}
}
}
impl From<RateLimitReachedType> for CoreRateLimitReachedType {
fn from(value: RateLimitReachedType) -> Self {
match value {
RateLimitReachedType::RateLimitReached => Self::RateLimitReached,
RateLimitReachedType::WorkspaceOwnerCreditsDepleted => {
Self::WorkspaceOwnerCreditsDepleted
}
RateLimitReachedType::WorkspaceMemberCreditsDepleted => {
Self::WorkspaceMemberCreditsDepleted
}
RateLimitReachedType::WorkspaceOwnerUsageLimitReached => {
Self::WorkspaceOwnerUsageLimitReached
}
RateLimitReachedType::WorkspaceMemberUsageLimitReached => {
Self::WorkspaceMemberUsageLimitReached
}
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RateLimitWindow {
pub used_percent: i32,
#[ts(type = "number | null")]
pub window_duration_mins: Option<i64>,
#[ts(type = "number | null")]
pub resets_at: Option<i64>,
}
impl From<CoreRateLimitWindow> for RateLimitWindow {
fn from(value: CoreRateLimitWindow) -> Self {
Self {
used_percent: value.used_percent.round() as i32,
window_duration_mins: value.window_minutes,
resets_at: value.resets_at,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CreditsSnapshot {
pub has_credits: bool,
pub unlimited: bool,
pub balance: Option<String>,
}
impl From<CoreCreditsSnapshot> for CreditsSnapshot {
fn from(value: CoreCreditsSnapshot) -> Self {
Self {
has_credits: value.has_credits,
unlimited: value.unlimited,
balance: value.balance,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SpendControlLimitSnapshot {
pub limit: String,
pub used: String,
pub remaining_percent: i32,
#[ts(type = "number")]
pub resets_at: i64,
}
impl From<CoreSpendControlLimitSnapshot> for SpendControlLimitSnapshot {
fn from(value: CoreSpendControlLimitSnapshot) -> Self {
Self {
limit: value.limit,
used: value.used,
remaining_percent: value.remaining_percent,
resets_at: value.resets_at,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AccountLoginCompletedNotification {
// Use plain String for identifiers to avoid TS/JSON Schema quirks around uuid-specific types.
// Convert to/from UUIDs at the application layer as needed.
pub login_id: Option<String>,
pub success: bool,
pub error: Option<String>,
}
/// Optional security reminder bound to the account that fetched it. Unavailable or
/// ineligible accounts return no notice; this read never changes account security.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GetAccountSecuritySetupResponse {
pub notice: Option<AccountSecuritySetupNotice>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AccountSecuritySetupNotice {
pub account_id: String,
pub user_id: String,
pub title: String,
pub description: String,
pub action: AccountSecuritySetupAction,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AccountSecuritySetupAction {
pub label: String,
pub url: String,
}

View File

@@ -0,0 +1,35 @@
//! Managed application network and storage requirements, separate from agent permissions.
use super::NetworkDomainPermission;
use crate::JsonSchema;
use crate::TS;
use akode_utils_path_uri::LegacyAppPathString;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ApplicationRequirements {
pub network: Option<ApplicationNetworkRequirements>,
pub storage: Option<ApplicationStorageRequirements>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ApplicationNetworkRequirements {
/// When enabled, only explicitly allowed exact domains may be contacted.
pub enabled: bool,
pub domains: BTreeMap<String, NetworkDomainPermission>,
}
/// Managed storage settings for new Desktop workspaces, not filesystem access restrictions.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ApplicationStorageRequirements {
pub default_project_parent: Option<LegacyAppPathString>,
pub projectless_workspace_root: Option<LegacyAppPathString>,
}

View File

@@ -0,0 +1,17 @@
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
/// EXPERIMENTAL - app metadata summary for plugin responses. ChatGPT apps are never
/// available in aKode, so plugin responses always carry empty lists of this type.
pub struct AppSummary {
pub id: String,
pub name: String,
pub description: Option<String>,
pub install_url: Option<String>,
pub category: Option<String>,
}

View File

@@ -0,0 +1,25 @@
use super::AllowDenyRequirement;
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub struct BrowserUseConfig {
pub allow_history_access: Option<bool>,
pub default_origin_policy: Option<BrowserUseOriginPolicyConfig>,
pub origins: Option<BTreeMap<String, BrowserUseOriginPolicyConfig>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub struct BrowserUseOriginPolicyConfig {
pub access: Option<AllowDenyRequirement>,
pub downloads: Option<AllowDenyRequirement>,
pub uploads: Option<AllowDenyRequirement>,
pub full_cdp_access: Option<AllowDenyRequirement>,
}

View File

@@ -0,0 +1,45 @@
use crate::JsonSchema;
use crate::TS;
use akode_protocol::config_types::CollaborationModeMask as CoreCollaborationModeMask;
use akode_protocol::config_types::ModeKind;
use akode_protocol::openai_models::ReasoningEffort;
use serde::Deserialize;
use serde::Serialize;
/// EXPERIMENTAL - list collaboration mode presets.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CollaborationModeListParams {}
/// EXPERIMENTAL - collaboration mode preset metadata for clients.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CollaborationModeMask {
pub name: String,
pub mode: Option<ModeKind>,
pub model: Option<String>,
#[serde(rename = "reasoning_effort")]
#[ts(rename = "reasoning_effort")]
pub reasoning_effort: Option<Option<ReasoningEffort>>,
}
impl From<CoreCollaborationModeMask> for CollaborationModeMask {
fn from(value: CoreCollaborationModeMask) -> Self {
Self {
name: value.name,
mode: value.mode,
model: value.model,
reasoning_effort: value.reasoning_effort,
}
}
}
/// EXPERIMENTAL - collaboration mode presets response.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CollaborationModeListResponse {
pub data: Vec<CollaborationModeMask>,
}

View File

@@ -0,0 +1,213 @@
use super::SandboxPolicy;
use crate::JsonSchema;
use crate::TS;
use akode_experimental_api_macros::ExperimentalApi;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::path::PathBuf;
/// PTY size in character cells for `command/exec` PTY sessions.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecTerminalSize {
/// Terminal height in character cells.
pub rows: u16,
/// Terminal width in character cells.
pub cols: u16,
}
/// Run a standalone command (argv vector) in the server sandbox without
/// creating a thread or turn.
///
/// The final `command/exec` response is deferred until the process exits and is
/// sent only after all `command/exec/outputDelta` notifications for that
/// connection have been emitted.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecParams {
/// Command argv vector. Empty arrays are rejected.
pub command: Vec<String>,
/// Optional client-supplied, connection-scoped process id.
///
/// Required for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up
/// `command/exec/write`, `command/exec/resize`, and
/// `command/exec/terminate` calls. When omitted, buffered execution gets an
/// internal id that is not exposed to the client.
#[ts(optional = nullable)]
pub process_id: Option<String>,
/// Enable PTY mode.
///
/// This implies `streamStdin` and `streamStdoutStderr`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub tty: bool,
/// Allow follow-up `command/exec/write` requests to write stdin bytes.
///
/// Requires a client-supplied `processId`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub stream_stdin: bool,
/// Stream stdout/stderr via `command/exec/outputDelta` notifications.
///
/// Streamed bytes are not duplicated into the final response and require a
/// client-supplied `processId`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub stream_stdout_stderr: bool,
/// Optional per-stream stdout/stderr capture cap in bytes.
///
/// When omitted, the server default applies. Cannot be combined with
/// `disableOutputCap`.
#[ts(type = "number | null")]
#[ts(optional = nullable)]
pub output_bytes_cap: Option<usize>,
/// Disable stdout/stderr capture truncation for this request.
///
/// Cannot be combined with `outputBytesCap`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub disable_output_cap: bool,
/// Disable the timeout entirely for this request.
///
/// Cannot be combined with `timeoutMs`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub disable_timeout: bool,
/// Optional timeout in milliseconds.
///
/// When omitted, the server default applies. Cannot be combined with
/// `disableTimeout`.
#[ts(type = "number | null")]
#[ts(optional = nullable)]
pub timeout_ms: Option<i64>,
/// Optional working directory. Defaults to the server cwd.
#[ts(optional = nullable)]
pub cwd: Option<PathBuf>,
/// Optional environment overrides merged into the server-computed
/// environment.
///
/// Matching names override inherited values. Set a key to `null` to unset
/// an inherited variable.
#[ts(optional = nullable)]
pub env: Option<HashMap<String, Option<String>>>,
/// Optional initial PTY size in character cells. Only valid when `tty` is
/// true.
#[ts(optional = nullable)]
pub size: Option<CommandExecTerminalSize>,
/// Optional sandbox policy for this command.
///
/// Uses the same shape as thread/turn execution sandbox configuration and
/// defaults to the user's configured policy when omitted. Cannot be
/// combined with `permissionProfile`.
#[ts(optional = nullable)]
pub sandbox_policy: Option<SandboxPolicy>,
/// Optional active permissions profile id for this command.
///
/// Defaults to the user's configured permissions when omitted. Cannot be
/// combined with `sandboxPolicy`.
#[experimental("command/exec.permissionProfile")]
#[ts(optional = nullable)]
pub permission_profile: Option<String>,
}
/// Final buffered result for `command/exec`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecResponse {
/// Process exit code.
pub exit_code: i32,
/// Buffered stdout capture.
///
/// Empty when stdout was streamed via `command/exec/outputDelta`.
pub stdout: String,
/// Buffered stderr capture.
///
/// Empty when stderr was streamed via `command/exec/outputDelta`.
pub stderr: String,
}
/// Write stdin bytes to a running `command/exec` session, close stdin, or
/// both.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecWriteParams {
/// Client-supplied, connection-scoped `processId` from the original
/// `command/exec` request.
pub process_id: String,
/// Optional base64-encoded stdin bytes to write.
#[ts(optional = nullable)]
pub delta_base64: Option<String>,
/// Close stdin after writing `deltaBase64`, if present.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub close_stdin: bool,
}
/// Empty success response for `command/exec/write`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecWriteResponse {}
/// Terminate a running `command/exec` session.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecTerminateParams {
/// Client-supplied, connection-scoped `processId` from the original
/// `command/exec` request.
pub process_id: String,
}
/// Empty success response for `command/exec/terminate`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecTerminateResponse {}
/// Resize a running PTY-backed `command/exec` session.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecResizeParams {
/// Client-supplied, connection-scoped `processId` from the original
/// `command/exec` request.
pub process_id: String,
/// New PTY size in character cells.
pub size: CommandExecTerminalSize,
}
/// Empty success response for `command/exec/resize`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecResizeResponse {}
/// Stream label for `command/exec/outputDelta` notifications.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum CommandExecOutputStream {
/// stdout stream. PTY mode multiplexes terminal output here.
Stdout,
/// stderr stream.
Stderr,
}
/// Base64-encoded output chunk emitted for a streaming `command/exec` request.
///
/// These notifications are connection-scoped. If the originating connection
/// closes, the server terminates the process.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CommandExecOutputDeltaNotification {
/// Client-supplied, connection-scoped `processId` from the original
/// `command/exec` request.
pub process_id: String,
/// Output stream for this chunk.
pub stream: CommandExecOutputStream,
/// Base64-encoded output bytes.
pub delta_base64: String,
/// `true` on the final streamed chunk for a stream when `outputBytesCap`
/// truncated later output on that stream.
pub cap_reached: bool,
}

View File

@@ -0,0 +1,40 @@
use super::AllowDenyRequirement;
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub struct ComputerUseConfig {
pub default_app_access: Option<AllowDenyRequirement>,
pub macos: Option<ComputerUseMacosConfig>,
pub windows: Option<ComputerUseWindowsConfig>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub struct ComputerUseMacosConfig {
pub bundle_ids: Option<BTreeMap<String, AllowDenyRequirement>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub struct ComputerUseWindowsConfig {
pub aumids: Option<BTreeMap<String, AllowDenyRequirement>>,
pub exes: Option<Vec<ComputerUseWindowsExeConfig>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub struct ComputerUseWindowsExeConfig {
pub publisher_name: String,
pub product_name: String,
pub binary_name: Option<String>,
pub access: AllowDenyRequirement,
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
use super::BrowserUseRequirements;
use super::RequestHeader;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn request_header_debug_redacts_values_without_changing_serialization() {
let wire = json!({ "name": "x-company-token", "value": "private-header-token" });
let header: RequestHeader = serde_json::from_value(wire.clone()).unwrap();
assert_eq!(serde_json::to_value(&header).unwrap(), wire);
assert_eq!(
format!("{header:?}"),
r#"RequestHeader { name: "x-company-token", value: "[REDACTED]" }"#
);
let requirements: BrowserUseRequirements = serde_json::from_value(json!({
"extension": { "requestHeaders": [wire] }
}))
.unwrap();
for debug in [format!("{requirements:?}"), format!("{requirements:#?}")] {
assert!(!debug.contains("private-header-token"));
assert!(debug.contains("x-company-token"));
assert!(debug.contains("[REDACTED]"));
}
assert_eq!(
serde_json::to_value(&requirements).unwrap()["extension"]["requestHeaders"],
json!([wire])
);
}

View File

@@ -0,0 +1,20 @@
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CurrentTimeReadParams {
pub thread_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CurrentTimeReadResponse {
/// Current time as whole Unix seconds.
#[ts(type = "number")]
pub current_time_at: i64,
}

View File

@@ -0,0 +1,37 @@
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ServerDiagnosticsParams {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ServerDiagnosticsResponse {
pub process: ServerDiagnosticsProcess,
pub gauges: Vec<ServerDiagnosticsGauge>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ServerDiagnosticsProcess {
pub id: u32,
#[ts(type = "number | null")]
pub resident_memory_bytes: Option<u64>,
#[ts(type = "number | null")]
pub physical_footprint_bytes: Option<u64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ServerDiagnosticsGauge {
pub name: String,
#[ts(type = "number")]
pub value: u64,
}

View File

@@ -0,0 +1,150 @@
use crate::JsonSchema;
use crate::TS;
use akode_protocol::protocol::TurnEnvironmentSelection;
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathUri;
use akode_utils_redacted_string::RedactedString;
use serde::Deserialize;
use serde::Serialize;
/// An environment selected by a loaded thread, independent of connection status.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEnvironment {
pub environment_id: String,
pub cwd: LegacyAppPathString,
pub runtime_workspace_roots: Vec<LegacyAppPathString>,
}
impl From<&TurnEnvironmentSelection> for ThreadEnvironment {
fn from(selection: &TurnEnvironmentSelection) -> Self {
Self {
environment_id: selection.environment_id.clone(),
cwd: selection.cwd.clone().into(),
runtime_workspace_roots: selection
.workspace_roots
.iter()
.cloned()
.map(Into::into)
.collect(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentAddParams {
pub environment_id: String,
pub exec_server_url: String,
/// Optional raw bearer token for executor authentication, including reconnects.
/// Requires a secure transport or a loopback destination.
#[ts(type = "string | null")]
#[ts(optional = nullable)]
pub auth_bearer_token: Option<RedactedString>,
/// Optional X-Request-ID for the direct WebSocket upgrade, including reconnects.
/// Requires a secure transport or a loopback destination.
#[ts(optional = nullable)]
pub websocket_request_id: Option<String>,
/// Optional WebSocket connection timeout. The server default applies when omitted.
#[ts(type = "number | null")]
#[ts(optional = nullable)]
pub connect_timeout_ms: Option<u64>,
/// Required skills supplied by this environment, checked before model inference.
#[ts(optional = nullable)]
pub skills: Option<EnvironmentSkillsParams>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentAddResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentSkillsParams {
/// Exact catalog names that must be available from this environment.
#[ts(optional = nullable)]
pub required: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub struct EnvironmentConnectionNotification {
pub thread_id: String,
pub environment_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentInfoParams {
pub environment_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentInfoResponse {
pub shell: EnvironmentShellInfo,
/// Default working directory reported by the environment, as a canonical file URI.
pub cwd: Option<PathUri>,
}
/// Parameters for reading the current status of one configured environment.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentStatusParams {
/// Environment id to inspect.
pub environment_id: String,
}
/// Current status for the requested environment.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentStatusResponse {
/// Current status observed without starting or recovering the environment.
pub status: EnvironmentStatusKind,
/// Human-readable detail for `disconnected` and `unknown`; omitted for other statuses.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub error: Option<String>,
}
/// Current status observed by app-server without starting or recovering an environment.
///
/// For a currently ready remote environment, app-server asks the existing
/// exec-server connection for `environment/status` without allowing recovery.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum EnvironmentStatusKind {
/// The environment is local, or an already-connected remote exec-server answered
/// `environment/status` over its existing initialized connection.
Ready,
/// The configured environment has no ready connection and no observed connection failure.
/// This includes lazy environments that have never been started and initial startup that has
/// not finished.
Pending,
/// A connection attempt, prior connection, or fail-fast `environment/status` probe observed
/// a failure. This does not promise the failure is terminal: later normal environment use may
/// recover it. This call does not trigger recovery; `error` contains the observed reason.
Disconnected,
/// The requested environment id is not configured in app-server.
Unknown,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct EnvironmentShellInfo {
/// Stable shell name, for example `zsh`, `bash`, `powershell`, `sh`, or `cmd`.
pub name: String,
/// Target-native shell executable path or command name.
pub path: String,
}

View File

@@ -0,0 +1,90 @@
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ExperimentalFeatureListParams {
/// Opaque pagination cursor returned by a previous call.
#[ts(optional = nullable)]
pub cursor: Option<String>,
/// Optional page size; defaults to a reasonable server-side value.
#[ts(optional = nullable)]
pub limit: Option<u32>,
/// Optional loaded thread id. Pass this when showing feature state for an
/// existing thread so enablement is computed from that thread's refreshed
/// config, including project-local config for the thread's cwd.
#[ts(optional = nullable)]
pub thread_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ExperimentalFeatureStage {
/// Feature is available for user testing and feedback.
Beta,
/// Feature is still being built and not ready for broad use.
UnderDevelopment,
/// Feature is production-ready.
Stable,
/// Feature is deprecated and should be avoided.
Deprecated,
/// Feature flag is retained only for backwards compatibility.
Removed,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ExperimentalFeature {
/// Stable key used in config.toml and CLI flag toggles.
pub name: String,
/// Lifecycle stage of this feature flag.
pub stage: ExperimentalFeatureStage,
/// User-facing display name shown in the experimental features UI.
/// Null when this feature is not in beta.
pub display_name: Option<String>,
/// Short summary describing what the feature does.
/// Null when this feature is not in beta.
pub description: Option<String>,
/// Announcement copy shown to users when the feature is introduced.
/// Null when this feature is not in beta.
pub announcement: Option<String>,
/// Whether this feature is currently enabled in the loaded config.
pub enabled: bool,
/// Whether this feature is enabled by default.
pub default_enabled: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ExperimentalFeatureListResponse {
pub data: Vec<ExperimentalFeature>,
/// Opaque cursor to pass to the next call to continue after the last item.
/// If None, there are no more items to return.
pub next_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ExperimentalFeatureEnablementSetParams {
/// Process-wide runtime feature enablement keyed by canonical feature name.
///
/// Only named features are updated. Omitted features are left unchanged.
/// Send an empty map for a no-op.
pub enablement: BTreeMap<String, bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ExperimentalFeatureEnablementSetResponse {
/// Feature enablement entries updated by this request.
pub enablement: BTreeMap<String, bool>,
}

View File

@@ -0,0 +1,48 @@
use crate::JsonSchema;
use crate::TS;
use akode_utils_path_uri::LegacyAppPathString;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
/// Report contents for `feedback/save`. Feedback is only ever saved locally.
pub struct FeedbackReportParams {
pub classification: String,
#[ts(optional = nullable)]
pub reason: Option<String>,
#[ts(optional = nullable)]
pub thread_id: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub include_logs: bool,
#[ts(optional = nullable)]
pub extra_log_files: Option<Vec<PathBuf>>,
#[ts(optional = nullable)]
pub tags: Option<BTreeMap<String, String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FeedbackSaveParams {
#[serde(flatten)]
pub feedback: FeedbackReportParams,
/// Absolute, previously unused ZIP path on the app-server host.
/// The caller owns this file, including after a disconnected RPC.
pub save_path: LegacyAppPathString,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FeedbackSaveResponse {
pub saved_path: LegacyAppPathString,
pub thread_id: String,
/// Whitespace-normalized SHA-256 of the session base instructions, matching the
/// saved `prompt_hash` tag. Does not include later developer messages.
/// Null when the reported rollout has no prompt metadata.
pub prompt_hash: Option<String>,
}

View File

@@ -0,0 +1,204 @@
use crate::JsonSchema;
use crate::TS;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
/// Read a file from the host filesystem.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsReadFileParams {
/// Absolute path to read.
pub path: AbsolutePathBuf,
}
/// Base64-encoded file contents returned by `fs/readFile`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsReadFileResponse {
/// File contents encoded as base64.
pub data_base64: String,
}
/// Write a file on the host filesystem.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsWriteFileParams {
/// Absolute path to write.
pub path: AbsolutePathBuf,
/// File contents encoded as base64.
pub data_base64: String,
}
/// Successful response for `fs/writeFile`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsWriteFileResponse {}
/// Create a directory on the host filesystem.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsCreateDirectoryParams {
/// Absolute directory path to create.
pub path: AbsolutePathBuf,
/// Whether parent directories should also be created. Defaults to `true`.
#[ts(optional = nullable)]
pub recursive: Option<bool>,
}
/// Successful response for `fs/createDirectory`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsCreateDirectoryResponse {}
/// Request metadata for an absolute path.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsGetMetadataParams {
/// Absolute path to inspect.
pub path: AbsolutePathBuf,
}
/// Metadata returned by `fs/getMetadata`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsGetMetadataResponse {
/// Whether the path resolves to a directory.
pub is_directory: bool,
/// Whether the path resolves to a regular file.
pub is_file: bool,
/// Whether the path itself is a symbolic link.
pub is_symlink: bool,
/// File creation time in Unix milliseconds when available, otherwise `0`.
#[ts(type = "number")]
pub created_at_ms: i64,
/// File modification time in Unix milliseconds when available, otherwise `0`.
#[ts(type = "number")]
pub modified_at_ms: i64,
}
/// List direct child names for a directory.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsReadDirectoryParams {
/// Absolute directory path to read.
pub path: AbsolutePathBuf,
}
/// A directory entry returned by `fs/readDirectory`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsReadDirectoryEntry {
/// Direct child entry name only, not an absolute or relative path.
pub file_name: String,
/// Whether this entry resolves to a directory.
pub is_directory: bool,
/// Whether this entry resolves to a regular file.
pub is_file: bool,
}
/// Directory entries returned by `fs/readDirectory`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsReadDirectoryResponse {
/// Direct child entries in the requested directory.
pub entries: Vec<FsReadDirectoryEntry>,
}
/// Remove a file or directory tree from the host filesystem.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsRemoveParams {
/// Absolute path to remove.
pub path: AbsolutePathBuf,
/// Whether directory removal should recurse. Defaults to `true`.
#[ts(optional = nullable)]
pub recursive: Option<bool>,
/// Whether missing paths should be ignored. Defaults to `true`.
#[ts(optional = nullable)]
pub force: Option<bool>,
}
/// Successful response for `fs/remove`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsRemoveResponse {}
/// Copy a file or directory tree on the host filesystem.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsCopyParams {
/// Absolute source path.
pub source_path: AbsolutePathBuf,
/// Absolute destination path.
pub destination_path: AbsolutePathBuf,
/// Required for directory copies; ignored for file copies.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub recursive: bool,
}
/// Successful response for `fs/copy`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsCopyResponse {}
/// Start filesystem watch notifications for an absolute path.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsWatchParams {
/// Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.
pub watch_id: String,
/// Absolute file or directory path to watch.
pub path: AbsolutePathBuf,
}
/// Successful response for `fs/watch`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsWatchResponse {
/// Canonicalized path associated with the watch.
pub path: AbsolutePathBuf,
}
/// Stop filesystem watch notifications for a prior `fs/watch`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsUnwatchParams {
/// Watch identifier previously provided to `fs/watch`.
pub watch_id: String,
}
/// Successful response for `fs/unwatch`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsUnwatchResponse {}
/// Filesystem watch notification emitted for `fs/watch` subscribers.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FsChangedNotification {
/// Watch identifier previously provided to `fs/watch`.
pub watch_id: String,
/// File or directory paths associated with this event.
pub changed_paths: Vec<AbsolutePathBuf>,
}

View File

@@ -0,0 +1,156 @@
use super::shared::v2_enum_from_core;
use crate::JsonSchema;
use crate::TS;
use akode_protocol::protocol::HookEventName as CoreHookEventName;
use akode_protocol::protocol::HookExecutionMode as CoreHookExecutionMode;
use akode_protocol::protocol::HookHandlerType as CoreHookHandlerType;
use akode_protocol::protocol::HookOutputEntry as CoreHookOutputEntry;
use akode_protocol::protocol::HookOutputEntryKind as CoreHookOutputEntryKind;
use akode_protocol::protocol::HookRunStatus as CoreHookRunStatus;
use akode_protocol::protocol::HookRunSummary as CoreHookRunSummary;
use akode_protocol::protocol::HookScope as CoreHookScope;
use akode_protocol::protocol::HookSource as CoreHookSource;
use akode_protocol::protocol::HookTrustStatus as CoreHookTrustStatus;
use akode_utils_path_uri::LegacyAppPathString;
use serde::Deserialize;
use serde::Serialize;
v2_enum_from_core!(
pub enum HookEventName from CoreHookEventName {
PreModelRequest, PostModelRequest, PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, SessionEnd, UserPromptSubmit, SubagentStart, SubagentStop, Stop, Interrupt
}
);
v2_enum_from_core!(
pub enum HookHandlerType from CoreHookHandlerType {
Command, McpTool, Prompt, Agent
}
);
v2_enum_from_core!(
#[derive(Default)]
pub enum HookExecutionMode from CoreHookExecutionMode {
#[default]
Sync,
Async
}
);
v2_enum_from_core!(
pub enum HookScope from CoreHookScope {
Thread, Turn
}
);
v2_enum_from_core!(
pub enum HookSource from CoreHookSource {
System,
User,
Project,
Mdm,
SessionFlags,
Plugin,
LegacyManagedConfigFile,
LegacyManagedConfigMdm,
Unknown,
}
);
v2_enum_from_core!(
pub enum HookTrustStatus from CoreHookTrustStatus {
Managed, Untrusted, Trusted, Modified
}
);
fn default_hook_source() -> HookSource {
HookSource::Unknown
}
v2_enum_from_core!(
pub enum HookRunStatus from CoreHookRunStatus {
Running, Completed, Failed, Blocked, Stopped
}
);
v2_enum_from_core!(
pub enum HookOutputEntryKind from CoreHookOutputEntryKind {
Warning, Stop, Feedback, Context, Error
}
);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookOutputEntry {
pub kind: HookOutputEntryKind,
pub text: String,
}
impl From<CoreHookOutputEntry> for HookOutputEntry {
fn from(value: CoreHookOutputEntry) -> Self {
Self {
kind: value.kind.into(),
text: value.text,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookRunSummary {
pub id: String,
pub event_name: HookEventName,
pub handler_type: HookHandlerType,
pub execution_mode: HookExecutionMode,
pub scope: HookScope,
pub source_path: LegacyAppPathString,
#[serde(default = "default_hook_source")]
pub source: HookSource,
pub display_order: i64,
pub status: HookRunStatus,
pub status_message: Option<String>,
pub started_at: i64,
pub completed_at: Option<i64>,
pub duration_ms: Option<i64>,
pub entries: Vec<HookOutputEntry>,
}
impl From<CoreHookRunSummary> for HookRunSummary {
fn from(value: CoreHookRunSummary) -> Self {
Self {
id: value.id,
event_name: value.event_name.into(),
handler_type: value.handler_type.into(),
execution_mode: value.execution_mode.into(),
scope: value.scope.into(),
source_path: value.source_path,
source: value.source.into(),
display_order: value.display_order,
status: value.status.into(),
status_message: value.status_message,
started_at: value.started_at,
completed_at: value.completed_at,
duration_ms: value.duration_ms,
entries: value.entries.into_iter().map(Into::into).collect(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookStartedNotification {
pub thread_id: String,
pub turn_id: Option<String>,
pub run: HookRunSummary,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookCompletedNotification {
pub thread_id: String,
pub turn_id: Option<String>,
pub run: HookRunSummary,
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,863 @@
use super::shared::v2_enum_from_core;
use crate::JsonSchema;
use crate::TS;
use akode_experimental_api_macros::ExperimentalApi;
use akode_protocol::approvals::ElicitationRequest as CoreElicitationRequest;
use akode_protocol::items::McpToolCallError as CoreMcpToolCallError;
use akode_protocol::mcp::CallToolResult as CoreMcpCallToolResult;
use akode_protocol::mcp::McpServerInfo;
use akode_protocol::mcp::Resource as McpResource;
pub use akode_protocol::mcp::ResourceContent as McpResourceContent;
use akode_protocol::mcp::ResourceTemplate as McpResourceTemplate;
use akode_protocol::mcp::Tool as McpTool;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
v2_enum_from_core!(
pub enum McpAuthStatus from akode_protocol::protocol::McpAuthStatus {
Unknown,
Unsupported,
NotLoggedIn,
BearerToken,
OAuth
}
);
v2_enum_from_core!(
pub enum McpServerStartupFailureReason from akode_protocol::protocol::McpStartupFailureReason {
ReauthenticationRequired
}
);
v2_enum_from_core!(
#[ts(rename_all = "camelCase")]
pub enum McpServerConnectionStatus from akode_protocol::mcp::McpServerConnectionStatus {
NotStarted,
Starting,
Connected,
AuthenticationRequired,
Failed,
Cancelled,
Disabled
}
);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ListMcpServerStatusParams {
/// Opaque pagination cursor returned by a previous call.
#[ts(optional = nullable)]
pub cursor: Option<String>,
/// Optional page size; defaults to a server-defined value.
#[ts(optional = nullable)]
pub limit: Option<u32>,
/// Controls how much MCP inventory data to fetch for each server.
/// Defaults to `Full` when omitted.
#[ts(optional = nullable)]
pub detail: Option<McpServerStatusDetail>,
#[ts(optional = nullable)]
pub thread_id: Option<String>,
/// Limit discovery to one server. With a thread ID, reuse that thread's MCP connection.
#[ts(optional = nullable)]
pub server_name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum McpServerStatusDetail {
Full,
ToolsAndAuthOnly,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerStatus {
pub name: String,
/// Current thread-runtime connection state; null when unavailable or the configuration changed.
pub runtime_status: Option<McpServerConnectionStatus>,
pub plugin_id: Option<String>,
/// HTTP origin of the effective configured endpoint, including plugin servers.
/// Excludes credentials, path, query, and fragment; null for non-HTTP transports.
pub http_origin: Option<String>,
pub server_info: Option<McpServerInfo>,
/// Capabilities advertised by the initialized MCP server; null when unavailable.
pub server_capabilities: Option<serde_json::Value>,
/// Opaque `_meta` from the first page of the corresponding MCP tool catalog. Null when unavailable.
pub tool_list_meta: Option<serde_json::Value>,
pub tools: std::collections::HashMap<String, McpTool>,
/// Tool discovery failed and no catalog was returned.
/// Null when a catalog is returned, including cached or empty catalogs.
pub tools_error: Option<String>,
pub resources: Vec<McpResource>,
pub resource_templates: Vec<McpResourceTemplate>,
pub auth_status: McpAuthStatus,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ListMcpServerStatusResponse {
pub data: Vec<McpServerStatus>,
/// Opaque cursor to pass to the next call to continue after the last item.
/// If None, there are no more items to return.
pub next_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpResourceReadParams {
/// Additional MCP request metadata. Account and turn routing keys are reserved.
#[serde(rename = "_meta")]
#[ts(rename = "_meta", optional = nullable)]
pub meta: Option<serde_json::Map<String, JsonValue>>,
#[ts(optional = nullable)]
pub thread_id: Option<String>,
pub server: String,
pub uri: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpResourceReadResponse {
pub contents: Vec<McpResourceContent>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerToolCallParams {
pub thread_id: String,
pub server: String,
pub tool: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub arguments: Option<JsonValue>,
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub meta: Option<JsonValue>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerToolCallResponse {
pub content: Vec<JsonValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub structured_content: Option<JsonValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub is_error: Option<bool>,
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub meta: Option<JsonValue>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpToolCallResult {
// NOTE: `rmcp::model::Content` (and its `RawContent` variants) would be a more precise Rust
// representation of MCP content blocks. We intentionally use `serde_json::Value` here because
// this crate exports JSON schema + TS types (`schemars`/`ts-rs`), and the rmcp model types
// aren't set up to be schema/TS friendly (and would introduce heavier coupling to rmcp's Rust
// representations). Using `JsonValue` keeps the payload wire-shaped and easy to export.
pub content: Vec<JsonValue>,
pub structured_content: Option<JsonValue>,
#[serde(rename = "_meta")]
#[ts(rename = "_meta")]
pub meta: Option<JsonValue>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpToolCallError {
pub message: String,
}
impl From<CoreMcpCallToolResult> for McpServerToolCallResponse {
fn from(result: CoreMcpCallToolResult) -> Self {
Self {
content: result.content,
structured_content: result.structured_content,
is_error: result.is_error,
meta: result.meta,
}
}
}
impl From<CoreMcpCallToolResult> for McpToolCallResult {
fn from(result: CoreMcpCallToolResult) -> Self {
Self {
content: result.content,
structured_content: result.structured_content,
meta: result.meta,
}
}
}
impl From<CoreMcpToolCallError> for McpToolCallError {
fn from(error: CoreMcpToolCallError) -> Self {
Self {
message: error.message,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerRefreshParams {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerRefreshResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerOauthLoginParams {
pub name: String,
#[ts(optional = nullable)]
pub thread_id: Option<String>,
/// Registration strategy for this login only; omission selects automatic discovery.
#[ts(optional = nullable)]
pub client_registration: Option<McpServerOauthClientRegistration>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub scopes: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub timeout_secs: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum McpServerOauthClientRegistration {
#[default]
Auto,
Cimd,
Dcr,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerOauthLoginResponse {
pub authorization_url: String,
/// Identifies this login attempt across the response and completion notification.
/// Older servers omit this field; current servers always return it.
#[serde(default)]
#[ts(optional)]
pub login_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpToolCallProgressNotification {
pub thread_id: String,
pub turn_id: String,
pub item_id: String,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerOauthLoginCompletedNotification {
pub name: String,
pub thread_id: Option<String>,
/// Identifies the explicit login attempt. Older servers omit this field.
#[ts(optional, as = "Option<Option<String>>")]
pub login_id: Option<String>,
pub success: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub error: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum McpServerStartupState {
Starting,
Ready,
Failed,
Cancelled,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerStatusUpdatedNotification {
pub thread_id: Option<String>,
pub name: String,
pub status: McpServerStartupState,
pub error: Option<String>,
pub failure_reason: Option<McpServerStartupFailureReason>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum McpServerElicitationAction {
Accept,
Decline,
Cancel,
}
impl McpServerElicitationAction {
pub fn to_core(self) -> akode_protocol::approvals::ElicitationAction {
match self {
Self::Accept => akode_protocol::approvals::ElicitationAction::Accept,
Self::Decline => akode_protocol::approvals::ElicitationAction::Decline,
Self::Cancel => akode_protocol::approvals::ElicitationAction::Cancel,
}
}
}
impl From<McpServerElicitationAction> for rmcp::model::ElicitationAction {
fn from(value: McpServerElicitationAction) -> Self {
match value {
McpServerElicitationAction::Accept => Self::Accept,
McpServerElicitationAction::Decline => Self::Decline,
McpServerElicitationAction::Cancel => Self::Cancel,
}
}
}
impl From<rmcp::model::ElicitationAction> for McpServerElicitationAction {
fn from(value: rmcp::model::ElicitationAction) -> Self {
match value {
rmcp::model::ElicitationAction::Accept => Self::Accept,
rmcp::model::ElicitationAction::Decline => Self::Decline,
rmcp::model::ElicitationAction::Cancel => Self::Cancel,
_ => Self::Cancel,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerElicitationRequestParams {
pub thread_id: String,
/// Active Codex turn when this elicitation was observed, if app-server could correlate one.
///
/// This is nullable because MCP models elicitation as a standalone server-to-client request
/// identified by the MCP server request id. It may be triggered during a turn, but turn
/// context is app-server correlation rather than part of the protocol identity of the
/// elicitation itself.
pub turn_id: Option<String>,
pub server_name: String,
#[serde(flatten)]
#[experimental(nested)]
pub request: McpServerElicitationRequest,
// TODO: When core can correlate an elicitation with an MCP tool call, expose the associated
// McpToolCall item id here as an optional field. The current core event does not carry that
// association.
}
/// Typed form schema for MCP `elicitation/create` requests.
///
/// This matches the `requestedSchema` shape from the MCP 2025-11-25
/// `ElicitRequestFormParams` schema.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationSchema {
#[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
#[ts(optional, rename = "$schema")]
pub schema_uri: Option<String>,
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationObjectType,
pub properties: BTreeMap<String, McpElicitationPrimitiveSchema>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub required: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export_to = "v2/")]
pub enum McpElicitationObjectType {
Object,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(untagged)]
#[ts(export_to = "v2/")]
pub enum McpElicitationPrimitiveSchema {
Enum(McpElicitationEnumSchema),
String(McpElicitationStringSchema),
#[serde(serialize_with = "serialize_mcp_elicitation_number_schema")]
Number(McpElicitationNumberSchema),
Boolean(McpElicitationBooleanSchema),
}
fn serialize_mcp_elicitation_number_schema<S>(
schema: &McpElicitationNumberSchema,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if schema.type_ != McpElicitationNumberType::Integer {
return schema.serialize(serializer);
}
let mut value = serde_json::to_value(schema).map_err(serde::ser::Error::custom)?;
if let Some(object) = value.as_object_mut() {
for key in ["minimum", "maximum", "default"] {
if let Some(value) = object.get_mut(key)
&& let Some(number) = value.as_f64()
&& number.fract() == 0.0
&& number >= i64::MIN as f64
&& number < -(i64::MIN as f64)
{
*value = serde_json::Value::from(number as i64);
}
}
}
value.serialize(serializer)
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationStringSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationStringType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub min_length: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub max_length: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub format: Option<McpElicitationStringFormat>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export_to = "v2/")]
pub enum McpElicitationStringType {
String,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "kebab-case")]
#[ts(rename_all = "kebab-case", export_to = "v2/")]
pub enum McpElicitationStringFormat {
Email,
Uri,
Date,
DateTime,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationNumberSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationNumberType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub minimum: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub maximum: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<f64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export_to = "v2/")]
pub enum McpElicitationNumberType {
Number,
Integer,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationBooleanSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationBooleanType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export_to = "v2/")]
pub enum McpElicitationBooleanType {
Boolean,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(untagged)]
#[ts(export_to = "v2/")]
pub enum McpElicitationEnumSchema {
SingleSelect(McpElicitationSingleSelectEnumSchema),
MultiSelect(McpElicitationMultiSelectEnumSchema),
Legacy(McpElicitationLegacyTitledEnumSchema),
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationLegacyTitledEnumSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationStringType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(rename = "enum")]
#[ts(rename = "enum")]
pub enum_: Vec<String>,
#[serde(rename = "enumNames", skip_serializing_if = "Option::is_none")]
#[ts(optional, rename = "enumNames")]
pub enum_names: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(untagged)]
#[ts(export_to = "v2/")]
pub enum McpElicitationSingleSelectEnumSchema {
Untitled(McpElicitationUntitledSingleSelectEnumSchema),
Titled(McpElicitationTitledSingleSelectEnumSchema),
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationUntitledSingleSelectEnumSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationStringType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(rename = "enum")]
#[ts(rename = "enum")]
pub enum_: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationTitledSingleSelectEnumSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationStringType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(rename = "oneOf")]
#[ts(rename = "oneOf")]
pub one_of: Vec<McpElicitationConstOption>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(untagged)]
#[ts(export_to = "v2/")]
pub enum McpElicitationMultiSelectEnumSchema {
Untitled(McpElicitationUntitledMultiSelectEnumSchema),
Titled(McpElicitationTitledMultiSelectEnumSchema),
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationUntitledMultiSelectEnumSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationArrayType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub min_items: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub max_items: Option<u64>,
pub items: McpElicitationUntitledEnumItems,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationTitledMultiSelectEnumSchema {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationArrayType,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub min_items: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub max_items: Option<u64>,
pub items: McpElicitationTitledEnumItems,
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub default: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export_to = "v2/")]
pub enum McpElicitationArrayType {
Array,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationUntitledEnumItems {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub type_: McpElicitationStringType,
#[serde(rename = "enum")]
#[ts(rename = "enum")]
pub enum_: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationTitledEnumItems {
#[serde(rename = "anyOf", alias = "oneOf")]
#[ts(rename = "anyOf")]
pub any_of: Vec<McpElicitationConstOption>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct McpElicitationConstOption {
#[serde(rename = "const")]
#[ts(rename = "const")]
pub const_: String,
pub title: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(tag = "mode", rename_all = "camelCase")]
#[ts(tag = "mode")]
#[ts(export_to = "v2/")]
pub enum McpServerElicitationRequest {
/// A device-authenticated approval; accepted responses contain the proof in `content`.
#[experimental("mcpServer/elicitation/request.userVerification")]
#[serde(rename = "openai/userVerification", rename_all = "camelCase")]
#[ts(rename = "openai/userVerification", rename_all = "camelCase")]
UserVerification {
#[serde(rename = "_meta")]
#[ts(rename = "_meta")]
meta: Option<JsonValue>,
title: String,
description: String,
challenge: String,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Form {
#[serde(rename = "_meta")]
#[ts(rename = "_meta")]
meta: Option<JsonValue>,
message: String,
requested_schema: McpElicitationSchema,
},
// TODO(victor): Deprecate once migrated to `openai/elicitation/create`.
#[serde(rename = "openai/form", rename_all = "camelCase")]
#[ts(rename = "openai/form", rename_all = "camelCase")]
OpenAiForm {
#[serde(rename = "_meta")]
#[ts(rename = "_meta")]
meta: Option<JsonValue>,
message: String,
requested_schema: JsonValue,
},
#[serde(rename = "openaiForm", rename_all = "camelCase")]
#[ts(rename = "openaiForm", rename_all = "camelCase")]
OpenAiElicitationForm {
#[serde(rename = "_meta")]
#[ts(rename = "_meta")]
meta: Option<JsonValue>,
message: String,
requested_schema: JsonValue,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Url {
#[serde(rename = "_meta")]
#[ts(rename = "_meta")]
meta: Option<JsonValue>,
message: String,
url: String,
elicitation_id: String,
},
}
impl TryFrom<CoreElicitationRequest> for McpServerElicitationRequest {
type Error = serde_json::Error;
fn try_from(value: CoreElicitationRequest) -> Result<Self, Self::Error> {
match value {
CoreElicitationRequest::UserVerification {
meta,
title,
description,
challenge,
} => Ok(Self::UserVerification {
meta,
title,
description,
challenge,
}),
CoreElicitationRequest::Form {
meta,
message,
requested_schema,
} => Ok(Self::Form {
meta,
message,
requested_schema: serde_json::from_value(requested_schema)?,
}),
CoreElicitationRequest::OpenAiForm {
meta,
message,
requested_schema,
} => Ok(Self::OpenAiForm {
meta,
message,
requested_schema,
}),
CoreElicitationRequest::OpenAiElicitationForm {
meta,
message,
requested_schema,
} => Ok(Self::OpenAiElicitationForm {
meta,
message,
requested_schema,
}),
CoreElicitationRequest::Url {
meta,
message,
url,
elicitation_id,
} => Ok(Self::Url {
meta,
message,
url,
elicitation_id,
}),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpServerElicitationRequestResponse {
pub action: McpServerElicitationAction,
/// Structured user input for accepted elicitations, mirroring RMCP `CreateElicitationResult`.
///
/// This is nullable because decline/cancel responses have no content.
pub content: Option<JsonValue>,
/// Optional client metadata for form-mode action handling.
#[serde(rename = "_meta")]
#[ts(rename = "_meta")]
pub meta: Option<JsonValue>,
}
impl From<McpServerElicitationRequestResponse> for rmcp::model::ElicitResult {
fn from(value: McpServerElicitationRequestResponse) -> Self {
let mut result = Self::new(value.action.into());
result.content = value.content;
result
}
}
impl From<rmcp::model::ElicitResult> for McpServerElicitationRequestResponse {
fn from(value: rmcp::model::ElicitResult) -> Self {
Self {
action: value.action.into(),
content: value.content,
meta: None,
}
}
}

View File

@@ -0,0 +1,40 @@
//! Memory readiness and summary reads using a loaded thread's selected pipeline.
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadMemoryReadParams {
/// The thread must already be started or resumed.
pub thread_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadMemoryReadResponse {
/// Summary from the thread's selected memory version. Null when memory use is
/// disabled or the selected summary is missing, unreadable, or blank.
pub summary: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MemoryStatusParams {
/// Required distinct consolidated threads. Defaults to 20; supported range is 1..=4096.
#[ts(optional = nullable)]
pub min_consolidated_threads: Option<u32>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MemoryStatusResponse {
pub v2_consolidated_threads: u32,
pub v2_ready: bool,
}

View File

@@ -0,0 +1,87 @@
mod shared;
mod account;
mod application;
mod apps;
mod browser_use_config;
mod collaboration_mode;
mod command_exec;
mod computer_use_config;
mod config;
mod current_time;
mod diagnostics;
mod environment;
mod experimental_feature;
mod feedback;
mod fs;
mod hook;
mod item;
mod mcp;
mod memory;
mod model;
mod model_provider;
mod model_provider_error;
mod notification;
mod permissions;
mod plugin;
mod plugin_search;
mod process;
mod project;
mod realtime;
mod remote_control;
mod review;
mod rollout;
mod thread;
mod thread_attachment;
mod thread_data;
mod thread_prediction;
mod thread_sample;
mod thread_usage;
mod turn;
mod user_verification;
mod windows_sandbox;
pub use account::*;
pub use application::*;
pub use apps::*;
pub use browser_use_config::*;
pub use collaboration_mode::*;
pub use command_exec::*;
pub use computer_use_config::*;
pub use config::*;
pub use current_time::*;
pub use diagnostics::*;
pub use environment::*;
pub use experimental_feature::*;
pub use feedback::*;
pub use fs::*;
pub use hook::*;
pub use item::*;
pub use mcp::*;
pub use memory::*;
pub use model::*;
pub use model_provider::*;
pub use model_provider_error::*;
pub use notification::*;
pub use permissions::*;
pub use plugin::*;
pub use plugin_search::*;
pub use process::*;
pub use project::*;
pub use realtime::*;
pub use remote_control::*;
pub use review::*;
pub use rollout::*;
pub use shared::*;
pub use thread::*;
pub use thread_attachment::*;
pub use thread_data::*;
pub use thread_prediction::*;
pub use thread_sample::*;
pub use thread_usage::*;
pub use turn::*;
pub use user_verification::*;
pub use windows_sandbox::*;
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,162 @@
use super::shared::v2_enum_from_core;
use crate::JsonSchema;
use crate::TS;
use akode_protocol::openai_models::InputModality;
use akode_protocol::openai_models::ModelAvailabilityNux as CoreModelAvailabilityNux;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::openai_models::default_input_modalities;
use akode_protocol::protocol::MultiAgentVersion as CoreMultiAgentVersion;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
v2_enum_from_core!(
/// Multi-agent runtime supported by a model.
pub enum MultiAgentVersion from CoreMultiAgentVersion {
Disabled,
V1,
V2
}
);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelProviderCapabilitiesReadParams {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelProviderCapabilitiesReadResponse {
pub web_search: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelListParams {
/// List models for this configured provider instead of the app-server default.
#[ts(optional = nullable)]
pub model_provider: Option<String>,
/// Opaque pagination cursor returned by a previous call.
#[ts(optional = nullable)]
pub cursor: Option<String>,
/// Optional page size; defaults to a reasonable server-side value.
#[ts(optional = nullable)]
pub limit: Option<u32>,
/// When true, include models that are hidden from the default picker list.
#[ts(optional = nullable)]
pub include_hidden: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelAvailabilityNux {
pub message: String,
}
impl From<CoreModelAvailabilityNux> for ModelAvailabilityNux {
fn from(value: CoreModelAvailabilityNux) -> Self {
Self {
message: value.message,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelServiceTier {
pub id: String,
pub name: String,
pub description: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct Model {
pub id: String,
pub model: String,
pub upgrade: Option<String>,
pub upgrade_info: Option<ModelUpgradeInfo>,
pub availability_nux: Option<ModelAvailabilityNux>,
pub display_name: String,
pub description: String,
#[serde(default)]
pub model_specialty: Option<String>,
pub hidden: bool,
pub supported_reasoning_efforts: Vec<ReasoningEffortOption>,
pub default_reasoning_effort: ReasoningEffort,
#[serde(default = "default_input_modalities")]
pub input_modalities: Vec<InputModality>,
/// @deprecated Always false; models no longer support personality selection.
#[serde(default)]
pub supports_personality: bool,
/// Multi-agent runtime declared by this model, when available.
pub multi_agent_version: Option<MultiAgentVersion>,
/// Deprecated: use `serviceTiers` instead.
#[serde(default)]
pub additional_speed_tiers: Vec<String>,
#[serde(default)]
pub service_tiers: Vec<ModelServiceTier>,
/// Catalog default service tier id for this model, when one is configured.
#[serde(default)]
pub default_service_tier: Option<String>,
// Only one model should be marked as default.
pub is_default: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelUpgradeInfo {
pub model: String,
pub upgrade_copy: Option<String>,
pub model_link: Option<String>,
pub migration_markdown: Option<String>,
/// Informational Unix timestamp for this upgrade's scheduled retirement, if known.
#[ts(type = "number | null")]
pub retirement_at: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ReasoningEffortOption {
pub reasoning_effort: ReasoningEffort,
pub description: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelListResponse {
pub data: Vec<Model>,
/// Opaque cursor to pass to the next call to continue after the last item.
/// If None, there are no more items to return.
pub next_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnModerationMetadataNotification {
pub thread_id: String,
pub turn_id: String,
pub metadata: JsonValue,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelSafetyBufferingUpdatedNotification {
pub thread_id: String,
pub turn_id: String,
pub model: String,
pub use_cases: Vec<String>,
pub reasons: Vec<String>,
pub show_buffering_ui: bool,
pub faster_model: Option<String>,
}

View File

@@ -0,0 +1,148 @@
//! Safe provider discovery and field patches for custom provider configuration.
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelProviderListParams {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelProviderListResponse {
pub data: Vec<ModelProviderSummary>,
pub default_provider_id: String,
pub can_change_default: bool,
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelProviderSummary {
pub id: String,
pub name: String,
/// Whether a supported configuration field can be edited in the active user layer.
pub can_edit: bool,
/// Null when the endpoint is absent or cannot be safely displayed.
pub base_url: Option<String>,
pub settings: ProviderSettings,
}
impl std::fmt::Debug for ModelProviderSummary {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ModelProviderSummary")
.field("id", &self.id)
.field("name", &self.name)
.field("can_edit", &self.can_edit)
.field("base_url", &"[REDACTED]")
.field("settings", &self.settings)
.finish()
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type", rename_all = "camelCase", export_to = "v2/")]
pub enum ProviderSettings {
CustomGateway { auth: GatewayAuth },
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "mode", rename_all = "camelCase")]
#[ts(tag = "mode", rename_all = "camelCase", export_to = "v2/")]
pub enum GatewayAuth {
None,
EnvironmentVariable {
#[serde(rename = "envKey")]
#[ts(rename = "envKey")]
env_key: String,
},
/// Authentication is configured outside the gateway form. Preserve it on edits.
ExternallyConfigured {
#[serde(rename = "envKey")]
#[ts(rename = "envKey")]
env_key: Option<String>,
},
}
/// Omitted patch fields preserve their values. Explicit null clears a nullable field.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
#[ts(tag = "type", rename_all = "camelCase", export_to = "v2/")]
pub enum ProviderSettingsPatch {
CustomGateway(CustomGatewaySettingsParams),
}
#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct CustomGatewaySettingsParams {
/// Omit or pass null to allocate a new custom provider ID.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub provider_id: Option<String>,
#[serde(
default,
deserialize_with = "deserialize_patch_name",
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "String", skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub name: Option<String>,
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
serialize_with = "crate::protocol::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "Option<String>", skip_serializing_if = "Option::is_none")]
#[ts(type = "string | null")]
#[ts(optional = nullable)]
pub base_url: Option<Option<String>>,
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
serialize_with = "crate::protocol::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "Option<String>", skip_serializing_if = "Option::is_none")]
#[ts(type = "string | null")]
#[ts(optional = nullable)]
pub env_key: Option<Option<String>>,
}
// A missing name preserves it, but an explicitly supplied name must be a string.
fn deserialize_patch_name<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Option<String>, D::Error> {
String::deserialize(deserializer).map(Some)
}
impl std::fmt::Debug for CustomGatewaySettingsParams {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomGatewaySettingsParams")
.field("name", &self.name)
.field("base_url", &"[REDACTED]")
.field("env_key", &self.env_key)
.field("provider_id", &self.provider_id)
.finish()
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct ModelProviderConfigWriteParams {
pub settings: ProviderSettingsPatch,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ModelProviderConfigWriteResponse {
pub provider: ModelProviderSummary,
}

View File

@@ -0,0 +1,70 @@
//! Recoverable provider failures shared by resume and inference admission.
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
/// Structured JSON-RPC error data. Unknown errors must retain the client's normal fallback.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
#[ts(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase",
export_to = "v2/"
)]
pub enum ModelProviderError {
ModelProviderMismatch {
#[schemars(rename = "modelProvider")]
model_provider: String,
#[schemars(rename = "currentModelProvider")]
current_model_provider: String,
},
ModelProviderNotConfigured {
#[schemars(rename = "modelProvider")]
model_provider: String,
},
ModelProviderPolicyConflict {
#[schemars(rename = "modelProvider")]
model_provider: String,
#[schemars(rename = "requiredModelProvider")]
required_model_provider: String,
},
}
impl ModelProviderError {
pub fn title(&self) -> &'static str {
match self {
Self::ModelProviderMismatch { .. } => "Model provider mismatch",
Self::ModelProviderNotConfigured { .. } => "Model provider unavailable",
Self::ModelProviderPolicyConflict { .. } => "Model provider blocked by policy",
}
}
}
impl std::fmt::Display for ModelProviderError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ModelProviderMismatch { model_provider, current_model_provider } => write!(f,
"This chat uses {model_provider}, but your current provider is {current_model_provider}. Switch to {model_provider} to continue."),
Self::ModelProviderNotConfigured { model_provider } => write!(f,
"This chat uses model provider “{model_provider}”, which is no longer configured. Restore this provider’s configuration to continue."),
Self::ModelProviderPolicyConflict { model_provider, required_model_provider }
if model_provider != required_model_provider => write!(f,
"This chat uses model provider “{model_provider}”, but your organization requires “{required_model_provider}”. Contact your administrator or start a new chat using the required provider."),
Self::ModelProviderPolicyConflict { .. } => f.write_str(
"This chat’s model provider settings no longer match your organization’s requirements. Contact your administrator or start a new chat using the current provider settings."),
}
}
}
impl std::error::Error for ModelProviderError {}
#[cfg(test)]
#[path = "model_provider_error_tests.rs"]
mod tests;

View File

@@ -0,0 +1,53 @@
//! Checks that generated provider-error schemas describe the serialized wire payloads.
use super::ModelProviderError;
use pretty_assertions::assert_eq;
use std::collections::BTreeSet;
#[test]
fn provider_error_schema_matches_wire_fields() -> anyhow::Result<()> {
let schema = serde_json::to_value(schemars::schema_for!(ModelProviderError))?;
for error in [
ModelProviderError::ModelProviderMismatch {
model_provider: "old-provider".to_string(),
current_model_provider: "current-provider".to_string(),
},
ModelProviderError::ModelProviderNotConfigured {
model_provider: "old-provider".to_string(),
},
ModelProviderError::ModelProviderPolicyConflict {
model_provider: "old-provider".to_string(),
required_model_provider: "required-provider".to_string(),
},
] {
let wire = serde_json::to_value(&error)?;
let variant = schema["oneOf"]
.as_array()
.expect("tagged variants")
.iter()
.find(|variant| variant["properties"]["type"]["enum"][0] == wire["type"])
.expect("schema variant for wire discriminator");
let wire_fields: BTreeSet<_> = wire
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
let schema_fields: BTreeSet<_> = variant["properties"]
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
let required_fields: BTreeSet<_> = variant["required"]
.as_array()
.unwrap()
.iter()
.map(|value| value.as_str().unwrap())
.collect();
assert_eq!(schema_fields, wire_fields);
assert_eq!(required_fields, wire_fields);
assert_eq!(serde_json::from_value::<ModelProviderError>(wire)?, error);
}
Ok(())
}

View File

@@ -0,0 +1,77 @@
use super::TurnError;
use crate::JsonSchema;
use crate::RequestId;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AuthRecoveryNotification {
pub thread_id: String,
pub turn_id: String,
pub provider: String,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct DeprecationNoticeNotification {
/// Concise summary of what is deprecated.
pub summary: String,
/// Optional extra guidance, such as migration steps or rationale.
pub details: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct WarningNotification {
/// Optional thread target when the warning applies to a specific thread.
pub thread_id: Option<String>,
/// Concise warning message for the user.
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GuardianWarningNotification {
/// Thread target for the guardian warning.
pub thread_id: String,
/// Concise guardian warning message for the user.
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct StrictReviewRequiredNotification {
pub thread_id: String,
pub turn_id: String,
/// Unix timestamp (in milliseconds) when this review started.
#[ts(type = "number")]
pub started_at_ms: i64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ErrorNotification {
pub error: TurnError,
// Set to true if the error is transient and the app-server process will automatically retry.
// If true, this will not interrupt a turn.
pub will_retry: bool,
pub thread_id: String,
pub turn_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ServerRequestResolvedNotification {
pub thread_id: String,
pub request_id: RequestId,
}

View File

@@ -0,0 +1,807 @@
use super::shared::v2_enum_from_core;
use crate::JsonSchema;
use crate::TS;
use akode_protocol::approvals::ExecPolicyAmendment as CoreExecPolicyAmendment;
use akode_protocol::approvals::NetworkApprovalContext as CoreNetworkApprovalContext;
use akode_protocol::approvals::NetworkApprovalProtocol as CoreNetworkApprovalProtocol;
use akode_protocol::approvals::NetworkPolicyAmendment as CoreNetworkPolicyAmendment;
use akode_protocol::approvals::NetworkPolicyRuleAction as CoreNetworkPolicyRuleAction;
use akode_protocol::models::ActivePermissionProfile as CoreActivePermissionProfile;
use akode_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile;
use akode_protocol::models::FileSystemPermissions as CoreFileSystemPermissions;
use akode_protocol::models::LegacyReadWriteRoots;
use akode_protocol::models::NetworkPermissions as CoreNetworkPermissions;
use akode_protocol::permissions::FileSystemAccessMode as CoreFileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath as CoreFileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry as CoreFileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSpecialPath as CoreFileSystemSpecialPath;
use akode_protocol::protocol::NetworkAccess as CoreNetworkAccess;
use akode_protocol::request_permissions::PermissionGrantScope as CorePermissionGrantScope;
use akode_protocol::request_permissions::RequestPermissionProfile as CoreRequestPermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathUri;
use serde::Deserialize;
use serde::Serialize;
use std::io;
use std::num::NonZeroUsize;
use std::path::Path;
v2_enum_from_core! {
pub enum NetworkApprovalProtocol from CoreNetworkApprovalProtocol {
Http,
Https,
Socks5Tcp,
Socks5Udp,
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct NetworkApprovalContext {
pub host: String,
pub protocol: NetworkApprovalProtocol,
}
impl From<CoreNetworkApprovalContext> for NetworkApprovalContext {
fn from(value: CoreNetworkApprovalContext) -> Self {
Self {
host: value.host,
protocol: value.protocol.into(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AdditionalFileSystemPermissions {
/// This will be removed in favor of `entries`.
pub read: Option<Vec<LegacyAppPathString>>,
/// This will be removed in favor of `entries`.
pub write: Option<Vec<LegacyAppPathString>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub glob_scan_max_depth: Option<NonZeroUsize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub entries: Option<Vec<FileSystemSandboxEntry>>,
}
fn permission_path_uri(path: LegacyAppPathString) -> io::Result<PathUri> {
if let Ok(path) = AbsolutePathBuf::try_from(path.clone()) {
return Ok(path.into());
}
PathUri::try_from(path).map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
}
// TODO(anp): Remove this conversion once core permission paths use PathUri.
impl From<CoreFileSystemPermissions> for AdditionalFileSystemPermissions {
fn from(value: CoreFileSystemPermissions) -> Self {
if let Some(LegacyReadWriteRoots { read, write }) = value.legacy_read_write_roots() {
let mut entries = Vec::with_capacity(
read.as_ref().map_or(0, Vec::len) + write.as_ref().map_or(0, Vec::len),
);
if let Some(paths) = read.as_ref() {
entries.extend(paths.iter().map(|path| FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: LegacyAppPathString::from_abs_path(path),
},
access: FileSystemAccessMode::Read,
}));
}
if let Some(paths) = write.as_ref() {
entries.extend(paths.iter().map(|path| FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: LegacyAppPathString::from_abs_path(path),
},
access: FileSystemAccessMode::Write,
}));
}
Self {
read: read.map(|paths| {
paths
.iter()
.map(LegacyAppPathString::from_abs_path)
.collect()
}),
write: write.map(|paths| {
paths
.iter()
.map(LegacyAppPathString::from_abs_path)
.collect()
}),
glob_scan_max_depth: None,
entries: Some(entries),
}
} else {
let mut read = Vec::new();
let mut write = Vec::new();
let legacy_compatible = value.glob_scan_max_depth.is_none()
&& value.entries.iter().all(|entry| {
let CoreFileSystemPath::Path { path } = &entry.path else {
return false;
};
let legacy_path = LegacyAppPathString::from(path.clone());
if legacy_path.to_inferred_path_uri().as_ref() != Some(path) {
return false;
}
match entry.access {
CoreFileSystemAccessMode::Read => read.push(legacy_path),
CoreFileSystemAccessMode::Write => write.push(legacy_path),
CoreFileSystemAccessMode::Deny => return false,
}
true
});
Self {
read: (legacy_compatible && !read.is_empty()).then_some(read),
write: (legacy_compatible && !write.is_empty()).then_some(write),
glob_scan_max_depth: value.glob_scan_max_depth,
entries: Some(
value
.entries
.into_iter()
.map(FileSystemSandboxEntry::from)
.collect(),
),
}
}
}
}
// TODO(anp): Remove this conversion once core permission paths use PathUri.
impl TryFrom<AdditionalFileSystemPermissions> for CoreFileSystemPermissions {
type Error = io::Error;
fn try_from(value: AdditionalFileSystemPermissions) -> Result<Self, Self::Error> {
let mut permissions = if let Some(entries) = value.entries {
Self {
entries: entries
.into_iter()
.map(CoreFileSystemSandboxEntry::try_from)
.collect::<io::Result<_>>()?,
glob_scan_max_depth: None,
}
} else {
let read = value
.read
.map(|paths| {
paths
.into_iter()
.map(permission_path_uri)
.collect::<io::Result<Vec<_>>>()
})
.transpose()?;
let write = value
.write
.map(|paths| {
paths
.into_iter()
.map(permission_path_uri)
.collect::<io::Result<Vec<_>>>()
})
.transpose()?;
CoreFileSystemPermissions::from_read_write_path_uris(read, write)
};
permissions.glob_scan_max_depth = value.glob_scan_max_depth;
Ok(permissions)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AdditionalNetworkPermissions {
pub enabled: Option<bool>,
}
impl From<CoreNetworkPermissions> for AdditionalNetworkPermissions {
fn from(value: CoreNetworkPermissions) -> Self {
Self {
enabled: value.enabled,
}
}
}
impl From<AdditionalNetworkPermissions> for CoreNetworkPermissions {
fn from(value: AdditionalNetworkPermissions) -> Self {
Self {
enabled: value.enabled,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct RequestPermissionProfile {
pub network: Option<AdditionalNetworkPermissions>,
pub file_system: Option<AdditionalFileSystemPermissions>,
}
// TODO(anp): Remove this conversion once core permission paths use PathUri.
impl From<CoreRequestPermissionProfile> for RequestPermissionProfile {
fn from(value: CoreRequestPermissionProfile) -> Self {
Self {
network: value.network.map(AdditionalNetworkPermissions::from),
file_system: value.file_system.map(AdditionalFileSystemPermissions::from),
}
}
}
impl TryFrom<RequestPermissionProfile> for CoreRequestPermissionProfile {
type Error = io::Error;
fn try_from(value: RequestPermissionProfile) -> Result<Self, Self::Error> {
Ok(Self {
network: value.network.map(CoreNetworkPermissions::from),
file_system: value
.file_system
.map(CoreFileSystemPermissions::try_from)
.transpose()?,
})
}
}
v2_enum_from_core!(
pub enum FileSystemAccessMode from CoreFileSystemAccessMode {
Read,
Write,
Deny
}
);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[ts(tag = "kind")]
#[ts(export_to = "v2/")]
pub enum FileSystemSpecialPath {
Root,
Minimal,
#[serde(alias = "current_working_directory")]
ProjectRoots {
subpath: Option<LegacyAppPathString>,
},
Tmpdir,
SlashTmp,
Unknown {
path: String,
subpath: Option<LegacyAppPathString>,
},
}
impl From<CoreFileSystemSpecialPath> for FileSystemSpecialPath {
fn from(value: CoreFileSystemSpecialPath) -> Self {
match value {
CoreFileSystemSpecialPath::Root => Self::Root,
CoreFileSystemSpecialPath::Minimal => Self::Minimal,
CoreFileSystemSpecialPath::ProjectRoots { subpath } => Self::ProjectRoots {
subpath: subpath
.as_deref()
.map(Path::new)
.map(LegacyAppPathString::from_path),
},
CoreFileSystemSpecialPath::Tmpdir => Self::Tmpdir,
CoreFileSystemSpecialPath::SlashTmp => Self::SlashTmp,
CoreFileSystemSpecialPath::Unknown { path, subpath } => Self::Unknown {
path,
subpath: subpath
.as_deref()
.map(Path::new)
.map(LegacyAppPathString::from_path),
},
}
}
}
impl From<FileSystemSpecialPath> for CoreFileSystemSpecialPath {
fn from(value: FileSystemSpecialPath) -> Self {
match value {
FileSystemSpecialPath::Root => Self::Root,
FileSystemSpecialPath::Minimal => Self::Minimal,
FileSystemSpecialPath::ProjectRoots { subpath } => Self::ProjectRoots {
subpath: subpath.map(LegacyAppPathString::into_string),
},
FileSystemSpecialPath::Tmpdir => Self::Tmpdir,
FileSystemSpecialPath::SlashTmp => Self::SlashTmp,
FileSystemSpecialPath::Unknown { path, subpath } => Self::Unknown {
path,
subpath: subpath.map(LegacyAppPathString::into_string),
},
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
// TODO(anp): Rename this type to distinguish it from the protocol FileSystemPath.
pub enum FileSystemPath {
Path { path: LegacyAppPathString },
GlobPattern { pattern: String },
Special { value: FileSystemSpecialPath },
}
// TODO(anp): Remove this conversion once core permission paths use PathUri.
impl From<CoreFileSystemPath> for FileSystemPath {
fn from(value: CoreFileSystemPath) -> Self {
match value {
CoreFileSystemPath::Path { path } => Self::Path { path: path.into() },
CoreFileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern },
CoreFileSystemPath::Special { value } => Self::Special {
value: value.into(),
},
}
}
}
// TODO(anp): Remove this conversion once core permission paths use PathUri.
impl TryFrom<FileSystemPath> for CoreFileSystemPath {
type Error = io::Error;
fn try_from(value: FileSystemPath) -> Result<Self, Self::Error> {
Ok(match value {
FileSystemPath::Path { path } => Self::Path {
path: permission_path_uri(path)?,
},
FileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern },
FileSystemPath::Special { value } => Self::Special {
value: value.into(),
},
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FileSystemSandboxEntry {
pub path: FileSystemPath,
pub access: FileSystemAccessMode,
}
// TODO(anp): Remove this conversion once core permission paths use PathUri.
impl From<CoreFileSystemSandboxEntry> for FileSystemSandboxEntry {
fn from(value: CoreFileSystemSandboxEntry) -> Self {
Self {
path: value.path.into(),
access: value.access.into(),
}
}
}
impl TryFrom<FileSystemSandboxEntry> for CoreFileSystemSandboxEntry {
type Error = io::Error;
fn try_from(value: FileSystemSandboxEntry) -> Result<Self, Self::Error> {
Ok(Self {
path: value.path.try_into()?,
access: value.access.to_core(),
missing_path_behavior: None,
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PermissionProfileListParams {
/// Opaque pagination cursor returned by a previous call.
#[ts(optional = nullable)]
pub cursor: Option<String>,
/// Optional page size; defaults to the full result set.
#[ts(optional = nullable)]
pub limit: Option<u32>,
/// Optional working directory to resolve project config layers.
#[ts(optional = nullable)]
pub cwd: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PermissionProfileSummary {
/// Available permission profile identifier.
pub id: String,
/// Optional user-facing description for display in clients.
pub description: Option<String>,
/// Whether the effective requirements allow selecting this profile.
pub allowed: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PermissionProfileListResponse {
pub data: Vec<PermissionProfileSummary>,
/// Opaque cursor to pass to the next call to continue after the last item.
/// If None, there are no more items to return.
pub next_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ActivePermissionProfile {
/// Identifier from `default_permissions` or the implicit built-in default,
/// such as `:workspace` or a user-defined `[permissions.<id>]` profile.
pub id: String,
/// Parent profile identifier from the selected permissions profile's
/// `extends` setting, when present.
#[serde(default)]
pub extends: Option<String>,
}
impl ActivePermissionProfile {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
extends: None,
}
}
pub fn read_only() -> Self {
CoreActivePermissionProfile::read_only().into()
}
}
impl From<CoreActivePermissionProfile> for ActivePermissionProfile {
fn from(value: CoreActivePermissionProfile) -> Self {
Self {
id: value.id,
extends: value.extends,
}
}
}
impl From<ActivePermissionProfile> for CoreActivePermissionProfile {
fn from(value: ActivePermissionProfile) -> Self {
Self {
id: value.id,
extends: value.extends,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AdditionalPermissionProfile {
/// Partial overlay used for per-command permission requests.
pub network: Option<AdditionalNetworkPermissions>,
pub file_system: Option<AdditionalFileSystemPermissions>,
}
// TODO(anp): Remove this conversion once core permission paths use PathUri.
impl From<CoreAdditionalPermissionProfile> for AdditionalPermissionProfile {
fn from(value: CoreAdditionalPermissionProfile) -> Self {
Self {
network: value.network.map(AdditionalNetworkPermissions::from),
file_system: value.file_system.map(AdditionalFileSystemPermissions::from),
}
}
}
impl TryFrom<AdditionalPermissionProfile> for CoreAdditionalPermissionProfile {
type Error = io::Error;
fn try_from(value: AdditionalPermissionProfile) -> Result<Self, Self::Error> {
Ok(Self {
network: value.network.map(CoreNetworkPermissions::from),
file_system: value
.file_system
.map(CoreFileSystemPermissions::try_from)
.transpose()?,
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GrantedPermissionProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub network: Option<AdditionalNetworkPermissions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub file_system: Option<AdditionalFileSystemPermissions>,
}
impl TryFrom<GrantedPermissionProfile> for CoreAdditionalPermissionProfile {
type Error = io::Error;
fn try_from(value: GrantedPermissionProfile) -> Result<Self, Self::Error> {
Ok(Self {
network: value.network.map(CoreNetworkPermissions::from),
file_system: value
.file_system
.map(CoreFileSystemPermissions::try_from)
.transpose()?,
})
}
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum NetworkAccess {
#[default]
Restricted,
Enabled,
}
#[derive(Serialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum SandboxPolicy {
DangerFullAccess,
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
ReadOnly {
#[serde(default)]
network_access: bool,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
ExternalSandbox {
#[serde(default)]
network_access: NetworkAccess,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
WorkspaceWrite {
#[serde(default)]
writable_roots: Vec<AbsolutePathBuf>,
#[serde(default)]
network_access: bool,
#[serde(default)]
exclude_tmpdir_env_var: bool,
#[serde(default)]
exclude_slash_tmp: bool,
},
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
enum SandboxPolicyDeserialize {
DangerFullAccess,
#[serde(rename_all = "camelCase")]
ReadOnly {
#[serde(default)]
network_access: bool,
#[serde(default)]
access: Option<LegacyReadOnlyAccess>,
},
#[serde(rename_all = "camelCase")]
ExternalSandbox {
#[serde(default)]
network_access: NetworkAccess,
},
#[serde(rename_all = "camelCase")]
WorkspaceWrite {
#[serde(default)]
writable_roots: Vec<AbsolutePathBuf>,
#[serde(default)]
read_only_access: Option<LegacyReadOnlyAccess>,
#[serde(default)]
network_access: bool,
#[serde(default)]
exclude_tmpdir_env_var: bool,
#[serde(default)]
exclude_slash_tmp: bool,
},
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
enum LegacyReadOnlyAccess {
FullAccess,
Restricted,
}
impl<'de> Deserialize<'de> for SandboxPolicy {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
match SandboxPolicyDeserialize::deserialize(deserializer)? {
SandboxPolicyDeserialize::DangerFullAccess => Ok(SandboxPolicy::DangerFullAccess),
SandboxPolicyDeserialize::ReadOnly {
network_access,
access,
} => {
if matches!(access, Some(LegacyReadOnlyAccess::Restricted)) {
return Err(serde::de::Error::custom(
"readOnly.access is no longer supported; use permissionProfile for restricted reads",
));
}
Ok(SandboxPolicy::ReadOnly { network_access })
}
SandboxPolicyDeserialize::ExternalSandbox { network_access } => {
Ok(SandboxPolicy::ExternalSandbox { network_access })
}
SandboxPolicyDeserialize::WorkspaceWrite {
writable_roots,
read_only_access,
network_access,
exclude_tmpdir_env_var,
exclude_slash_tmp,
} => {
if matches!(read_only_access, Some(LegacyReadOnlyAccess::Restricted)) {
return Err(serde::de::Error::custom(
"workspaceWrite.readOnlyAccess is no longer supported; use permissionProfile for restricted reads",
));
}
Ok(SandboxPolicy::WorkspaceWrite {
writable_roots,
network_access,
exclude_tmpdir_env_var,
exclude_slash_tmp,
})
}
}
}
}
impl SandboxPolicy {
pub fn to_core(&self) -> akode_protocol::protocol::SandboxPolicy {
match self {
SandboxPolicy::DangerFullAccess => {
akode_protocol::protocol::SandboxPolicy::DangerFullAccess
}
SandboxPolicy::ReadOnly { network_access } => {
akode_protocol::protocol::SandboxPolicy::ReadOnly {
network_access: *network_access,
}
}
SandboxPolicy::ExternalSandbox { network_access } => {
akode_protocol::protocol::SandboxPolicy::ExternalSandbox {
network_access: match network_access {
NetworkAccess::Restricted => CoreNetworkAccess::Restricted,
NetworkAccess::Enabled => CoreNetworkAccess::Enabled,
},
}
}
SandboxPolicy::WorkspaceWrite {
writable_roots,
network_access,
exclude_tmpdir_env_var,
exclude_slash_tmp,
} => akode_protocol::protocol::SandboxPolicy::WorkspaceWrite {
writable_roots: writable_roots.clone(),
network_access: *network_access,
exclude_tmpdir_env_var: *exclude_tmpdir_env_var,
exclude_slash_tmp: *exclude_slash_tmp,
},
}
}
}
impl From<akode_protocol::protocol::SandboxPolicy> for SandboxPolicy {
fn from(value: akode_protocol::protocol::SandboxPolicy) -> Self {
match value {
akode_protocol::protocol::SandboxPolicy::DangerFullAccess => {
SandboxPolicy::DangerFullAccess
}
akode_protocol::protocol::SandboxPolicy::ReadOnly { network_access } => {
SandboxPolicy::ReadOnly { network_access }
}
akode_protocol::protocol::SandboxPolicy::ExternalSandbox { network_access } => {
SandboxPolicy::ExternalSandbox {
network_access: match network_access {
CoreNetworkAccess::Restricted => NetworkAccess::Restricted,
CoreNetworkAccess::Enabled => NetworkAccess::Enabled,
},
}
}
akode_protocol::protocol::SandboxPolicy::WorkspaceWrite {
writable_roots,
network_access,
exclude_tmpdir_env_var,
exclude_slash_tmp,
} => SandboxPolicy::WorkspaceWrite {
writable_roots,
network_access,
exclude_tmpdir_env_var,
exclude_slash_tmp,
},
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(transparent)]
#[ts(type = "Array<string>", export_to = "v2/")]
pub struct ExecPolicyAmendment {
pub command: Vec<String>,
}
impl ExecPolicyAmendment {
pub fn into_core(self) -> CoreExecPolicyAmendment {
CoreExecPolicyAmendment::new(self.command)
}
}
impl From<CoreExecPolicyAmendment> for ExecPolicyAmendment {
fn from(value: CoreExecPolicyAmendment) -> Self {
Self {
command: value.command().to_vec(),
}
}
}
v2_enum_from_core!(
pub enum NetworkPolicyRuleAction from CoreNetworkPolicyRuleAction {
Allow, Deny
}
);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct NetworkPolicyAmendment {
pub host: String,
pub action: NetworkPolicyRuleAction,
}
impl NetworkPolicyAmendment {
pub fn into_core(self) -> CoreNetworkPolicyAmendment {
CoreNetworkPolicyAmendment {
host: self.host,
action: self.action.to_core(),
}
}
}
impl From<CoreNetworkPolicyAmendment> for NetworkPolicyAmendment {
fn from(value: CoreNetworkPolicyAmendment) -> Self {
Self {
host: value.host,
action: NetworkPolicyRuleAction::from(value.action),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PermissionsRequestApprovalParams {
pub thread_id: String,
pub turn_id: String,
pub item_id: String,
#[serde(default)]
pub environment_id: Option<String>,
/// Unix timestamp (in milliseconds) when this approval request started.
#[ts(type = "number")]
pub started_at_ms: i64,
pub cwd: LegacyAppPathString,
pub reason: Option<String>,
pub permissions: RequestPermissionProfile,
}
v2_enum_from_core!(
#[derive(Default)]
pub enum PermissionGrantScope from CorePermissionGrantScope {
#[default]
Turn,
Session
}
);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PermissionsRequestApprovalResponse {
pub permissions: GrantedPermissionProfile,
#[serde(default)]
pub scope: PermissionGrantScope,
/// Review every subsequent command in this turn before normal sandboxed execution.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub strict_auto_review: Option<bool>,
}

View File

@@ -0,0 +1,630 @@
use super::AppSummary;
use super::HookEventName;
use super::HookSource;
use super::HookTrustStatus;
use crate::JsonSchema;
use crate::TS;
use akode_protocol::protocol::SkillDependencies as CoreSkillDependencies;
use akode_protocol::protocol::SkillInterface as CoreSkillInterface;
use akode_protocol::protocol::SkillMetadata as CoreSkillMetadata;
use akode_protocol::protocol::SkillScope as CoreSkillScope;
use akode_protocol::protocol::SkillToolDependency as CoreSkillToolDependency;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::LegacyAppPathString;
use serde::Deserialize;
use serde::Serialize;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillsListParams {
/// When empty, defaults to the current session working directory.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cwds: Vec<PathBuf>,
/// When true, bypass the skills cache and re-scan skills from disk.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub force_reload: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillsListResponse {
pub data: Vec<SkillsListEntry>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillsExtraRootsSetParams {
pub extra_roots: Vec<AbsolutePathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillsExtraRootsSetResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HooksListParams {
/// Working directories to inspect when no thread is specified. An empty list uses the session cwd.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cwds: Vec<PathBuf>,
/// List a loaded thread's hooks, including its selected environments. Omit `cwds` in this mode.
#[ts(optional = nullable)]
pub thread_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HooksListResponse {
pub data: Vec<HooksListEntry>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceAddParams {
pub source: String,
#[ts(optional = nullable)]
pub ref_name: Option<String>,
#[ts(optional = nullable)]
pub sparse_paths: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceAddResponse {
pub marketplace_name: String,
pub installed_root: AbsolutePathBuf,
pub already_added: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceRemoveParams {
pub marketplace_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceRemoveResponse {
pub marketplace_name: String,
pub installed_root: Option<AbsolutePathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceUpgradeParams {
#[ts(optional = nullable)]
pub marketplace_name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceUpgradeResponse {
pub selected_marketplaces: Vec<String>,
pub upgraded_roots: Vec<AbsolutePathBuf>,
pub errors: Vec<MarketplaceUpgradeErrorInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceUpgradeErrorInfo {
pub marketplace_name: String,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginListParams {
/// Optional working directories used to discover repo marketplaces. When omitted,
/// only home-scoped marketplaces and the official curated marketplace are considered.
#[ts(optional = nullable)]
pub cwds: Option<Vec<AbsolutePathBuf>>,
/// Whether the client requests a fresh refresh of configured (git/npm) marketplace plugin
/// caches before listing.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub force_refetch: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginInstalledParams {
/// Optional working directories used to discover repo marketplaces.
#[ts(optional = nullable)]
pub cwds: Option<Vec<AbsolutePathBuf>>,
/// Additional uninstalled plugin names that should be returned when present locally.
/// This is used by mention surfaces that intentionally expose install entrypoints.
#[ts(optional = nullable)]
pub install_suggestion_plugin_names: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginListResponse {
pub marketplaces: Vec<PluginMarketplaceEntry>,
#[serde(default)]
pub marketplace_load_errors: Vec<MarketplaceLoadErrorInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginInstalledResponse {
pub marketplaces: Vec<PluginMarketplaceEntry>,
#[serde(default)]
pub marketplace_load_errors: Vec<MarketplaceLoadErrorInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceLoadErrorInfo {
pub marketplace_path: AbsolutePathBuf,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginReadParams {
#[ts(optional = nullable)]
pub marketplace_path: Option<AbsolutePathBuf>,
pub plugin_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginReadResponse {
pub plugin: PluginDetail,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub enum SkillScope {
User,
Repo,
System,
Admin,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillMetadata {
pub name: String,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
/// Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.
pub short_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub interface: Option<SkillInterface>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub dependencies: Option<SkillDependencies>,
pub path: LegacyAppPathString,
pub scope: SkillScope,
pub enabled: bool,
/// Owning plugin ID, matching `PluginSummary.id`, when known.
pub plugin_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillInterface {
#[ts(optional)]
pub display_name: Option<String>,
#[ts(optional)]
pub short_description: Option<String>,
#[ts(optional)]
pub icon_small: Option<AbsolutePathBuf>,
#[ts(optional)]
pub icon_large: Option<AbsolutePathBuf>,
#[ts(optional)]
pub brand_color: Option<String>,
#[ts(optional)]
pub default_prompt: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillDependencies {
pub tools: Vec<SkillToolDependency>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillToolDependency {
#[serde(rename = "type")]
#[ts(rename = "type")]
pub r#type: String,
pub value: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub transport: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub command: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub url: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillErrorInfo {
pub path: PathBuf,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillsListEntry {
pub cwd: PathBuf,
pub skills: Vec<SkillMetadata>,
pub errors: Vec<SkillErrorInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HooksListEntry {
pub cwd: PathBuf,
pub hooks: Vec<HookMetadata>,
pub warnings: Vec<String>,
pub errors: Vec<HookErrorInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "handlerType", rename_all = "camelCase")]
#[ts(tag = "handlerType", export_to = "v2/")]
pub enum HookHandlerMetadata {
Command {
command: String,
#[serde(default)]
r#async: bool,
},
McpTool {
server: String,
tool: String,
},
Prompt {},
Agent {},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookMetadata {
pub key: String,
pub event_name: HookEventName,
#[serde(flatten)]
pub handler: HookHandlerMetadata,
pub matcher: Option<String>,
pub timeout_sec: u64,
pub status_message: Option<String>,
/// Configured `additionalContext` spill threshold.
/// `null` uses 2,500 tokens; `0` disables spilling.
pub additional_context_limit: Option<usize>,
pub source_path: AbsolutePathBuf,
pub source: HookSource,
pub plugin_id: Option<String>,
/// The owning execution environment, if this hook came from its requirements.
pub environment_id: Option<String>,
pub display_order: i64,
pub enabled: bool,
pub is_managed: bool,
pub current_hash: String,
pub trust_status: HookTrustStatus,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct HookErrorInfo {
pub path: PathBuf,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginMarketplaceEntry {
pub name: String,
/// Local marketplace file path when the marketplace is backed by a local file.
pub path: Option<AbsolutePathBuf>,
pub interface: Option<MarketplaceInterface>,
pub plugins: Vec<PluginSummary>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceInterface {
pub display_name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[ts(export_to = "v2/")]
pub enum PluginInstallPolicy {
#[serde(rename = "NOT_AVAILABLE")]
#[ts(rename = "NOT_AVAILABLE")]
NotAvailable,
#[serde(rename = "AVAILABLE")]
#[ts(rename = "AVAILABLE")]
Available,
#[serde(rename = "INSTALLED_BY_DEFAULT")]
#[ts(rename = "INSTALLED_BY_DEFAULT")]
InstalledByDefault,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[ts(export_to = "v2/")]
pub enum PluginAuthPolicy {
#[serde(rename = "ON_INSTALL")]
#[ts(rename = "ON_INSTALL")]
OnInstall,
#[serde(rename = "ON_USE")]
#[ts(rename = "ON_USE")]
OnUse,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginSummary {
pub id: String,
/// Version of the locally materialized plugin package when available.
#[serde(default)]
pub local_version: Option<String>,
pub name: String,
pub source: PluginSource,
pub installed: bool,
pub enabled: bool,
pub install_policy: PluginInstallPolicy,
pub auth_policy: PluginAuthPolicy,
pub interface: Option<PluginInterface>,
#[serde(default)]
pub keywords: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginDetail {
pub marketplace_name: String,
pub marketplace_path: Option<AbsolutePathBuf>,
pub summary: PluginSummary,
pub description: Option<String>,
pub skills: Vec<SkillSummary>,
/// The declared onboarding skill, when the plugin and visible skill are enabled.
#[serde(default)]
pub onboarding_skill: Option<SkillSummary>,
pub hooks: Vec<PluginHookSummary>,
pub apps: Vec<AppSummary>,
pub mcp_servers: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginHookSummary {
pub key: String,
pub event_name: HookEventName,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillSummary {
pub name: String,
pub description: String,
pub short_description: Option<String>,
pub interface: Option<SkillInterface>,
pub path: Option<LegacyAppPathString>,
pub enabled: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginInterface {
pub display_name: Option<String>,
pub short_description: Option<String>,
pub long_description: Option<String>,
pub developer_name: Option<String>,
pub category: Option<String>,
pub capabilities: Vec<String>,
pub website_url: Option<String>,
pub privacy_policy_url: Option<String>,
pub terms_of_service_url: Option<String>,
/// Starter prompts for the plugin. Capped at 3 entries with a maximum of
/// 512 characters per entry.
pub default_prompt: Option<Vec<String>>,
pub brand_color: Option<String>,
/// Local composer icon path, resolved from the installed plugin package.
pub composer_icon: Option<AbsolutePathBuf>,
/// Local logo path, resolved from the installed plugin package.
pub logo: Option<AbsolutePathBuf>,
/// Local dark-mode logo path, resolved from the installed plugin package.
pub logo_dark: Option<AbsolutePathBuf>,
/// Local screenshot paths, resolved from the installed plugin package.
pub screenshots: Vec<AbsolutePathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum PluginSource {
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Local { path: AbsolutePathBuf },
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Git {
url: String,
path: Option<String>,
ref_name: Option<String>,
sha: Option<String>,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Npm {
package: String,
/// Optional npm version or version range.
version: Option<String>,
/// Optional HTTPS registry URL. Authentication stays in the user's npm config.
registry: Option<String>,
},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillsConfigWriteParams {
/// Path-based selector.
#[ts(optional = nullable)]
pub path: Option<AbsolutePathBuf>,
/// Name-based selector.
#[ts(optional = nullable)]
pub name: Option<String>,
pub enabled: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SkillsConfigWriteResponse {
pub effective_enabled: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginInstallParams {
#[ts(optional = nullable)]
pub marketplace_path: Option<AbsolutePathBuf>,
pub plugin_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginInstallResponse {
pub auth_policy: PluginAuthPolicy,
pub apps_needing_auth: Vec<AppSummary>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginUninstallParams {
pub plugin_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginUninstallResponse {}
impl From<CoreSkillMetadata> for SkillMetadata {
fn from(value: CoreSkillMetadata) -> Self {
Self {
name: value.name,
description: value.description,
short_description: value.short_description,
interface: value.interface.map(SkillInterface::from),
dependencies: value.dependencies.map(SkillDependencies::from),
path: value.path.into(),
scope: value.scope.into(),
enabled: true,
plugin_id: None,
}
}
}
impl From<CoreSkillInterface> for SkillInterface {
fn from(value: CoreSkillInterface) -> Self {
Self {
display_name: value.display_name,
short_description: value.short_description,
brand_color: value.brand_color,
default_prompt: value.default_prompt,
icon_small: value.icon_small,
icon_large: value.icon_large,
}
}
}
impl From<CoreSkillDependencies> for SkillDependencies {
fn from(value: CoreSkillDependencies) -> Self {
Self {
tools: value
.tools
.into_iter()
.map(SkillToolDependency::from)
.collect(),
}
}
}
impl From<CoreSkillToolDependency> for SkillToolDependency {
fn from(value: CoreSkillToolDependency) -> Self {
Self {
r#type: value.r#type,
value: value.value,
description: value.description,
transport: value.transport,
command: value.command,
url: value.url,
}
}
}
impl From<CoreSkillScope> for SkillScope {
fn from(value: CoreSkillScope) -> Self {
match value {
CoreSkillScope::User => Self::User,
CoreSkillScope::Repo => Self::Repo,
CoreSkillScope::System => Self::System,
CoreSkillScope::Admin => Self::Admin,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
/// Notification emitted when watched local skill files change.
///
/// Treat this as an invalidation signal and re-run `skills/list` with the
/// client's current parameters when refreshed skill metadata is needed.
pub struct SkillsChangedNotification {}

View File

@@ -0,0 +1,47 @@
use super::PluginSummary;
use crate::JsonSchema;
use crate::TS;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginSearchParams {
pub search_term: String,
#[ts(optional = nullable)]
pub scope: Option<PluginSearchScope>,
#[ts(optional = nullable)]
pub cwds: Option<Vec<AbsolutePathBuf>>,
#[ts(optional = nullable)]
pub cursor: Option<String>,
#[ts(optional = nullable)]
pub limit: Option<u32>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum PluginSearchScope {
Global,
Workspace,
Personal,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginSearchResult {
pub plugin: PluginSummary,
pub marketplace_name: String,
pub marketplace_path: Option<AbsolutePathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct PluginSearchResponse {
pub data: Vec<PluginSearchResult>,
pub next_cursor: Option<String>,
}

View File

@@ -0,0 +1,208 @@
use crate::JsonSchema;
use crate::TS;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
/// PTY size in character cells for `process/spawn` PTY sessions.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessTerminalSize {
/// Terminal height in character cells.
pub rows: u16,
/// Terminal width in character cells.
pub cols: u16,
}
/// Spawn a standalone process (argv vector) without a Codex sandbox on the host
/// where the app server is running.
///
/// `process/spawn` returns after the process has started and the connection-scoped
/// `processHandle` has been registered. Process output and exit are reported via
/// `process/outputDelta` and `process/exited` notifications.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessSpawnParams {
/// Command argv vector. Empty arrays are rejected.
pub command: Vec<String>,
/// Client-supplied, connection-scoped process handle.
///
/// Duplicate active handles are rejected on the same connection. The same
/// handle can be reused after the prior process exits.
pub process_handle: String,
/// Absolute working directory for the process.
pub cwd: AbsolutePathBuf,
/// Enable PTY mode.
///
/// This implies `streamStdin` and `streamStdoutStderr`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub tty: bool,
/// Allow follow-up `process/writeStdin` requests to write stdin bytes.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub stream_stdin: bool,
/// Stream stdout/stderr via `process/outputDelta` notifications.
///
/// Streamed bytes are not duplicated into the `process/exited` notification.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub stream_stdout_stderr: bool,
/// Optional per-stream stdout/stderr capture cap in bytes.
///
/// When omitted, the server default applies. Set to `null` to disable the
/// cap.
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
serialize_with = "crate::protocol::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[ts(type = "number | null")]
#[ts(optional = nullable)]
pub output_bytes_cap: Option<Option<usize>>,
/// Optional timeout in milliseconds.
///
/// When omitted, the server default applies. Set to `null` to disable the
/// timeout.
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
serialize_with = "crate::protocol::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[ts(type = "number | null")]
#[ts(optional = nullable)]
pub timeout_ms: Option<Option<i64>>,
/// Optional environment overrides merged into the app-server process
/// environment.
///
/// Matching names override inherited values. Set a key to `null` to unset
/// an inherited variable.
#[ts(optional = nullable)]
pub env: Option<HashMap<String, Option<String>>>,
/// Optional initial PTY size in character cells. Only valid when `tty` is
/// true.
#[ts(optional = nullable)]
pub size: Option<ProcessTerminalSize>,
}
/// Successful response for `process/spawn`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessSpawnResponse {}
/// Write stdin bytes to a running `process/spawn` session, close stdin, or
/// both.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessWriteStdinParams {
/// Client-supplied, connection-scoped `processHandle` from `process/spawn`.
pub process_handle: String,
/// Optional base64-encoded stdin bytes to write.
#[ts(optional = nullable)]
pub delta_base64: Option<String>,
/// Close stdin after writing `deltaBase64`, if present.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub close_stdin: bool,
}
/// Empty success response for `process/writeStdin`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessWriteStdinResponse {}
/// Terminate a running `process/spawn` session.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessKillParams {
/// Client-supplied, connection-scoped `processHandle` from `process/spawn`.
pub process_handle: String,
}
/// Empty success response for `process/kill`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessKillResponse {}
/// Resize a running PTY-backed `process/spawn` session.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessResizePtyParams {
/// Client-supplied, connection-scoped `processHandle` from `process/spawn`.
pub process_handle: String,
/// New PTY size in character cells.
pub size: ProcessTerminalSize,
}
/// Empty success response for `process/resizePty`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessResizePtyResponse {}
/// Stream label for `process/outputDelta` notifications.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ProcessOutputStream {
/// stdout stream. PTY mode multiplexes terminal output here.
Stdout,
/// stderr stream.
Stderr,
}
/// Base64-encoded output chunk emitted for a streaming `process/spawn` request.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessOutputDeltaNotification {
/// Client-supplied, connection-scoped `processHandle` from `process/spawn`.
pub process_handle: String,
/// Output stream this chunk belongs to.
pub stream: ProcessOutputStream,
/// Base64-encoded output bytes.
pub delta_base64: String,
/// True on the final streamed chunk for this stream when output was
/// truncated by `outputBytesCap`.
pub cap_reached: bool,
}
/// Final process exit notification for `process/spawn`.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProcessExitedNotification {
/// Client-supplied, connection-scoped `processHandle` from `process/spawn`.
pub process_handle: String,
/// Process exit code.
pub exit_code: i32,
/// Whether output collection hit its post-exit deadline before seeing EOF or reaching the
/// requested byte cap on either stream. Older servers omit this field.
#[ts(optional, as = "Option<Option<bool>>")]
pub output_drain_timed_out: Option<bool>,
/// Buffered stdout capture.
///
/// Empty when stdout was streamed via `process/outputDelta`.
pub stdout: String,
/// Whether stdout reached `outputBytesCap`.
///
/// In streaming mode, stdout is empty and cap state is also reported on the
/// final stdout `process/outputDelta` notification.
pub stdout_cap_reached: bool,
/// Buffered stderr capture.
///
/// Empty when stderr was streamed via `process/outputDelta`.
pub stderr: String,
/// Whether stderr reached `outputBytesCap`.
///
/// In streaming mode, stderr is empty and cap state is also reported on the
/// final stderr `process/outputDelta` notification.
pub stderr_cap_reached: bool,
}

View File

@@ -0,0 +1,195 @@
use std::collections::BTreeMap;
use crate::JsonSchema;
use crate::TS;
use akode_experimental_api_macros::ExperimentalApi;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
use super::SortDirection;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectRoot {
pub path: AbsolutePathBuf,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct Project {
pub id: String,
pub name: String,
pub roots: Vec<ProjectRoot>,
pub metadata: BTreeMap<String, String>,
#[ts(type = "number")]
pub position: i64,
#[ts(type = "number")]
pub created_at: i64,
#[ts(type = "number")]
pub updated_at: i64,
/// Newest non-archived member thread's recency, in Unix seconds; null when none exist.
#[ts(type = "number | null")]
pub recency_at: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum ProjectSortKey {
Position,
RecencyAt,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectListParams {
#[ts(optional = nullable)]
pub cursor: Option<String>,
#[ts(optional = nullable)]
pub limit: Option<u32>,
/// Defaults to position. Recency sorting always places empty projects last.
#[ts(optional = nullable)]
pub sort_key: Option<ProjectSortKey>,
/// Requires sortKey. Defaults to asc for position and desc for recencyAt.
#[ts(optional = nullable)]
pub sort_direction: Option<SortDirection>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectListResponse {
pub data: Vec<Project>,
pub next_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectReadParams {
pub project_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectReadResponse {
pub project: Project,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectCreateParams {
pub name: String,
pub roots: Vec<ProjectRoot>,
#[ts(optional = nullable)]
pub metadata: Option<BTreeMap<String, String>>,
pub idempotency_key: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectCreateResponse {
pub project: Project,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectImportParams {
pub name: String,
pub roots: Vec<ProjectRoot>,
#[ts(optional = nullable)]
pub metadata: Option<BTreeMap<String, String>>,
#[ts(optional = nullable)]
pub threads: Option<Vec<String>>,
pub idempotency_key: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectImportResponse {
pub project: Project,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectUpdateParams {
pub project_id: String,
#[ts(optional = nullable)]
pub name: Option<String>,
#[ts(optional = nullable)]
pub roots: Option<Vec<ProjectRoot>>,
#[ts(optional = nullable)]
pub metadata: Option<BTreeMap<String, String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectUpdateResponse {
pub project: Project,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectMoveParams {
pub project_id: String,
#[ts(optional = nullable)]
pub before_project_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectMoveResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectDeleteParams {
pub project_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectDeleteResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ProjectChangeType {
Created,
Updated,
Deleted,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ProjectChangedNotification {
pub project_id: String,
pub change_type: ProjectChangeType,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadProjectUpdatedNotification {
pub thread_id: String,
#[schemars(
required,
schema_with = "crate::protocol::serde_helpers::nullable_string_schema"
)]
pub project_id: Option<String>,
}

View File

@@ -0,0 +1,487 @@
use crate::JsonSchema;
use crate::TS;
use akode_protocol::protocol::CodexResponseHandoffMode;
use akode_protocol::protocol::ConversationTextRole;
use akode_protocol::protocol::RealtimeAudioFrame as CoreRealtimeAudioFrame;
use akode_protocol::protocol::RealtimeConversationVersion;
use akode_protocol::protocol::RealtimeOutputModality;
use akode_protocol::protocol::RealtimeVoice;
use akode_protocol::protocol::RealtimeVoicesList;
use akode_protocol::realtime::BemItemPresentation as CoreBemItemPresentation;
use akode_protocol::realtime::RealtimeItem as CoreRealtimeItem;
use akode_protocol::realtime::RealtimeItemContent as CoreRealtimeItemContent;
use akode_protocol::realtime::RealtimeSessionOutcome as CoreRealtimeSessionOutcome;
use akode_protocol::realtime::RealtimeTranscriptRole as CoreRealtimeTranscriptRole;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
/// EXPERIMENTAL - a thread-scoped realtime item in the canonical timeline.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeItem {
pub id: String,
pub realtime_session_id: String,
#[serde(flatten)]
pub content: ThreadRealtimeItemContent,
}
/// EXPERIMENTAL - durable facts describing realtime speech and promoted work.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
#[ts(tag = "type", rename_all = "camelCase", export_to = "v2/")]
pub enum ThreadRealtimeItemContent {
RealtimeSessionStarted,
TranscriptSegment {
role: ThreadRealtimeTranscriptRole,
text: String,
},
BemItemPromoted {
turn_id: String,
item_id: String,
presentation: ThreadRealtimeBemItemPresentation,
},
RealtimeSessionClosed {
outcome: ThreadRealtimeSessionOutcome,
},
}
/// EXPERIMENTAL - how an existing agent item appears in a realtime conversation.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
#[ts(tag = "type", rename_all = "camelCase", export_to = "v2/")]
pub enum ThreadRealtimeBemItemPresentation {
WholeItem,
InlineMarkdown,
InlineVisualization { index: u32 },
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum ThreadRealtimeTranscriptRole {
User,
Assistant,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum ThreadRealtimeSessionOutcome {
Ended,
Failed,
}
impl From<CoreRealtimeItem> for ThreadRealtimeItem {
fn from(item: CoreRealtimeItem) -> Self {
let CoreRealtimeItem {
id,
realtime_session_id,
content,
} = item;
let content = match content {
CoreRealtimeItemContent::RealtimeSessionStarted => {
ThreadRealtimeItemContent::RealtimeSessionStarted
}
CoreRealtimeItemContent::TranscriptSegment { role, text } => {
ThreadRealtimeItemContent::TranscriptSegment {
role: match role {
CoreRealtimeTranscriptRole::User => ThreadRealtimeTranscriptRole::User,
CoreRealtimeTranscriptRole::Assistant => {
ThreadRealtimeTranscriptRole::Assistant
}
},
text,
}
}
CoreRealtimeItemContent::BemItemPromoted {
turn_id,
item_id,
presentation,
} => ThreadRealtimeItemContent::BemItemPromoted {
turn_id,
item_id,
presentation: match presentation {
CoreBemItemPresentation::WholeItem => {
ThreadRealtimeBemItemPresentation::WholeItem
}
CoreBemItemPresentation::InlineMarkdown => {
ThreadRealtimeBemItemPresentation::InlineMarkdown
}
CoreBemItemPresentation::InlineVisualization { index } => {
ThreadRealtimeBemItemPresentation::InlineVisualization { index }
}
},
},
CoreRealtimeItemContent::RealtimeSessionClosed { outcome } => {
ThreadRealtimeItemContent::RealtimeSessionClosed {
outcome: match outcome {
CoreRealtimeSessionOutcome::Ended => ThreadRealtimeSessionOutcome::Ended,
CoreRealtimeSessionOutcome::Failed => ThreadRealtimeSessionOutcome::Failed,
},
}
}
};
Self {
id,
realtime_session_id,
content,
}
}
}
/// EXPERIMENTAL - thread realtime audio chunk.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeAudioChunk {
pub data: String,
pub sample_rate: u32,
pub num_channels: u16,
pub samples_per_channel: Option<u32>,
pub item_id: Option<String>,
}
impl From<CoreRealtimeAudioFrame> for ThreadRealtimeAudioChunk {
fn from(value: CoreRealtimeAudioFrame) -> Self {
let CoreRealtimeAudioFrame {
data,
sample_rate,
num_channels,
samples_per_channel,
item_id,
} = value;
Self {
data,
sample_rate,
num_channels,
samples_per_channel,
item_id,
}
}
}
impl From<ThreadRealtimeAudioChunk> for CoreRealtimeAudioFrame {
fn from(value: ThreadRealtimeAudioChunk) -> Self {
let ThreadRealtimeAudioChunk {
data,
sample_rate,
num_channels,
samples_per_channel,
item_id,
} = value;
Self {
data,
sample_rate,
num_channels,
samples_per_channel,
item_id,
}
}
}
/// EXPERIMENTAL - start a thread-scoped realtime session.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeStartParams {
pub thread_id: String,
/// Leaves Codex response handoffs to the client's explicit append calls instead of forwarding
/// them automatically. Defaults to false.
#[ts(optional = nullable)]
pub client_managed_handoffs: Option<bool>,
/// Controls whether a realtime V3 delegation produces an acknowledgement filler.
/// Omitted values preserve the Realtime API's default behavior.
#[ts(optional = nullable)]
pub delegation_ack_filler: Option<bool>,
/// Routes any transcript tail remaining at session end through Codex. Defaults to false.
/// TODO: Remove this rollout knob once transcript-tail flushing is always enabled.
#[ts(optional = nullable)]
pub flush_transcript_tail_on_session_end: Option<bool>,
// TODO: Remove this experiment-only delivery path after response-item testing is complete.
/// Sends automatic Codex responses as realtime conversation items instead of handoff appends.
#[ts(optional = nullable)]
pub codex_responses_as_items: Option<bool>,
// TODO: Remove this experiment-only prefix with `codex_responses_as_items`.
/// Optional prefix added to automatic Codex response items when `codexResponsesAsItems` is true.
#[ts(optional = nullable)]
pub codex_response_item_prefix: Option<String>,
/// Selects how automatic Codex responses are routed in Frameless Bidi sessions. Omitted values
/// default to `thinking`. Realtime V1 and V2 ignore this setting.
#[ts(optional = nullable)]
pub codex_response_handoff_mode: Option<CodexResponseHandoffMode>,
/// Relays public reasoning summaries as quiet context for realtime V3 delegations. Defaults to false.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub backend_reasoning_status: bool,
/// Overrides BEM channel prefixes by `analysis`, `commentary`, or `final`.
/// Omitted channels retain their default uppercase bracketed prefixes.
#[ts(optional = nullable)]
pub codex_response_handoff_channel_prefixes: Option<BTreeMap<String, Vec<String>>>,
/// Overrides the configured realtime model for this session only.
#[ts(optional = nullable)]
pub model: Option<String>,
/// Selects text or audio output for the realtime session. Transport and voice stay
/// independent so clients can choose how they connect separately from what the model emits.
pub output_modality: RealtimeOutputModality,
/// Set to false to start without Codex's startup context. Omitted or null includes it.
#[ts(optional = nullable)]
pub include_startup_context: Option<bool>,
/// Adds complete role-bearing text items to the initial Frameless Bidi session history.
/// This is only supported by realtime V3 and is sent during session startup. Requests are
/// limited to 128 items and 8,192 estimated text tokens in total.
#[ts(optional = nullable)]
pub initial_items: Option<Vec<ThreadRealtimeInitialItem>>,
/// Developer instructions given to the backing Codex model when this realtime session starts.
#[ts(optional = nullable)]
pub realtime_start_instructions: Option<String>,
/// Developer instructions given to the backing Codex model when this realtime session ends.
#[ts(optional = nullable)]
pub realtime_end_instructions: Option<String>,
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
serialize_with = "crate::protocol::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional = nullable)]
pub prompt: Option<Option<String>>,
#[ts(optional = nullable)]
pub realtime_session_id: Option<String>,
/// Client-generated identifier for the product voice session. This is distinct from
/// `realtimeSessionId`.
#[ts(optional = nullable)]
pub voice_session_id: Option<String>,
#[ts(optional = nullable)]
pub transport: Option<ThreadRealtimeStartTransport>,
/// Overrides the configured realtime protocol version for this session only.
#[ts(optional = nullable)]
pub version: Option<RealtimeConversationVersion>,
#[ts(optional = nullable)]
pub voice: Option<RealtimeVoice>,
}
/// EXPERIMENTAL - role-bearing text item included when a realtime V3 session starts.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeInitialItem {
pub role: ConversationTextRole,
pub text: String,
}
/// EXPERIMENTAL - transport used by thread realtime.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(export_to = "v2/", tag = "type")]
pub enum ThreadRealtimeStartTransport {
Websocket,
Webrtc {
/// SDP offer generated by a WebRTC RTCPeerConnection after configuring audio and the
/// realtime events data channel.
sdp: String,
},
ExistingCall {
/// Identifier of a realtime call already created and negotiated by the client.
#[serde(rename = "callId")]
#[ts(rename = "callId")]
call_id: String,
},
}
/// EXPERIMENTAL - response for starting thread realtime.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeStartResponse {}
/// EXPERIMENTAL - append audio input to thread realtime.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeAppendAudioParams {
pub thread_id: String,
pub audio: ThreadRealtimeAudioChunk,
}
/// EXPERIMENTAL - response for appending realtime audio input.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeAppendAudioResponse {}
/// EXPERIMENTAL - append text input to thread realtime.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeAppendTextParams {
pub thread_id: String,
pub text: String,
#[serde(default)]
pub role: ConversationTextRole,
}
/// EXPERIMENTAL - response for appending realtime text input.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeAppendTextResponse {}
/// EXPERIMENTAL - append speakable text to thread realtime.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeAppendSpeechParams {
pub thread_id: String,
pub text: String,
}
/// EXPERIMENTAL - response for appending realtime speech.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeAppendSpeechResponse {}
/// EXPERIMENTAL - stop thread realtime.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeStopParams {
pub thread_id: String,
}
/// EXPERIMENTAL - response for stopping thread realtime.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeStopResponse {}
/// EXPERIMENTAL - list voices supported by thread realtime.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeListVoicesParams {}
/// EXPERIMENTAL - response for listing supported realtime voices.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeListVoicesResponse {
pub voices: RealtimeVoicesList,
}
/// EXPERIMENTAL - emitted when thread realtime startup is accepted.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeStartedNotification {
pub thread_id: String,
pub realtime_session_id: Option<String>,
pub version: RealtimeConversationVersion,
}
/// EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeItemAddedNotification {
pub thread_id: String,
pub item: JsonValue,
}
/// EXPERIMENTAL - a realtime timeline item started before its content streams.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeItemStartedNotification {
pub thread_id: String,
pub item: ThreadRealtimeItem,
}
/// EXPERIMENTAL - text appended to an active realtime transcript item.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeItemTranscriptDeltaNotification {
pub thread_id: String,
pub item_id: String,
pub delta: String,
}
/// EXPERIMENTAL - a realtime timeline item published after canonical commit.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeItemCompletedNotification {
pub thread_id: String,
pub item: ThreadRealtimeItem,
}
/// EXPERIMENTAL - flat transcript delta emitted whenever realtime
/// transcript text changes.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeTranscriptDeltaNotification {
pub thread_id: String,
pub role: String,
/// Live transcript delta from the realtime event.
pub delta: String,
}
/// EXPERIMENTAL - final transcript text emitted when realtime completes
/// a transcript part.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeTranscriptDoneNotification {
pub thread_id: String,
pub role: String,
/// Final complete text for the transcript part.
pub text: String,
}
/// EXPERIMENTAL - streamed output audio emitted by thread realtime.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeOutputAudioDeltaNotification {
pub thread_id: String,
pub audio: ThreadRealtimeAudioChunk,
}
/// EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeSdpNotification {
pub thread_id: String,
pub sdp: String,
}
/// EXPERIMENTAL - emitted when thread realtime encounters an error.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeErrorNotification {
pub thread_id: String,
pub message: String,
}
/// EXPERIMENTAL - emitted when thread realtime transport closes.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadRealtimeClosedNotification {
pub thread_id: String,
pub reason: Option<String>,
}

View File

@@ -0,0 +1,204 @@
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlEnableParams {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub ephemeral: bool,
}
pub type NullableRemoteControlEnableParams = Option<RemoteControlEnableParams>;
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlDisableParams {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub ephemeral: bool,
}
pub type NullableRemoteControlDisableParams = Option<RemoteControlDisableParams>;
/// Current remote-control connection status and remote identity exposed to clients.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlStatusChangedNotification {
pub status: RemoteControlConnectionStatus,
pub server_name: String,
pub installation_id: String,
pub environment_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlEnableResponse {
pub status: RemoteControlConnectionStatus,
pub server_name: String,
pub installation_id: String,
pub environment_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlDisableResponse {
pub status: RemoteControlConnectionStatus,
pub server_name: String,
pub installation_id: String,
pub environment_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlStatusReadResponse {
pub status: RemoteControlConnectionStatus,
pub server_name: String,
pub installation_id: String,
pub environment_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlPairingStartParams {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub manual_code: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlPairingStartResponse {
pub pairing_code: String,
pub manual_pairing_code: Option<String>,
pub environment_id: String,
pub expires_at: i64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlPairingStatusParams {
#[ts(optional = nullable)]
pub pairing_code: Option<String>,
#[ts(optional = nullable)]
pub manual_pairing_code: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlPairingStatusResponse {
pub claimed: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlClientsListParams {
pub environment_id: String,
#[ts(optional = nullable)]
pub cursor: Option<String>,
#[ts(optional = nullable)]
pub limit: Option<u32>,
#[ts(optional = nullable)]
pub order: Option<RemoteControlClientsListOrder>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum RemoteControlClientsListOrder {
Asc,
Desc,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlClientsListResponse {
pub data: Vec<RemoteControlClient>,
pub next_cursor: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlClient {
pub client_id: String,
pub display_name: Option<String>,
pub device_type: Option<String>,
pub platform: Option<String>,
pub os_version: Option<String>,
pub device_model: Option<String>,
pub app_version: Option<String>,
pub last_seen_at: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlClientsRevokeParams {
pub environment_id: String,
pub client_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RemoteControlClientsRevokeResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum RemoteControlConnectionStatus {
Disabled,
Connecting,
Connected,
Errored,
}
impl From<RemoteControlStatusChangedNotification> for RemoteControlEnableResponse {
fn from(notification: RemoteControlStatusChangedNotification) -> Self {
let RemoteControlStatusChangedNotification {
status,
server_name,
installation_id,
environment_id,
} = notification;
Self {
status,
server_name,
installation_id,
environment_id,
}
}
}
impl From<RemoteControlStatusChangedNotification> for RemoteControlDisableResponse {
fn from(notification: RemoteControlStatusChangedNotification) -> Self {
let RemoteControlStatusChangedNotification {
status,
server_name,
installation_id,
environment_id,
} = notification;
Self {
status,
server_name,
installation_id,
environment_id,
}
}
}
#[cfg(test)]
#[path = "remote_control_tests.rs"]
mod tests;

View File

@@ -0,0 +1,50 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn remote_control_clients_list_params_serialize_nullable_optional_fields() {
assert_eq!(
serde_json::to_value(RemoteControlClientsListParams {
environment_id: "env-123".to_string(),
cursor: None,
limit: None,
order: None,
})
.expect("params should serialize"),
json!({
"environmentId": "env-123",
"cursor": null,
"limit": null,
"order": null,
})
);
}
#[test]
fn remote_control_clients_list_params_deserialize_camel_case_fields() {
assert_eq!(
serde_json::from_value::<RemoteControlClientsListParams>(json!({
"environmentId": "env-123",
"cursor": "cursor-123",
"limit": 10,
"order": "asc",
}))
.expect("params should deserialize"),
RemoteControlClientsListParams {
environment_id: "env-123".to_string(),
cursor: Some("cursor-123".to_string()),
limit: Some(10),
order: Some(RemoteControlClientsListOrder::Asc),
}
);
}
#[test]
fn remote_control_clients_revoke_response_serializes_as_empty_object() {
assert_eq!(
serde_json::to_value(RemoteControlClientsRevokeResponse {})
.expect("response should serialize"),
json!({})
);
}

View File

@@ -0,0 +1,62 @@
use super::Turn;
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ReviewDelivery {
Inline,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ReviewStartParams {
pub thread_id: String,
pub target: ReviewTarget,
/// Reviews run inline on the supplied thread. Omit this field or pass `inline`.
/// To review on a separate thread, start a thread first and use its id.
#[serde(default)]
#[ts(optional = nullable)]
pub delivery: Option<ReviewDelivery>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ReviewStartResponse {
pub turn: Turn,
/// The thread id supplied to `review/start`.
pub review_thread_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type", export_to = "v2/")]
pub enum ReviewTarget {
/// Review the working tree: staged, unstaged, and untracked files.
UncommittedChanges,
/// Review changes between the current branch and the given base branch.
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
BaseBranch { branch: String },
/// Review the changes introduced by a specific commit.
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Commit {
sha: String,
/// Optional human-readable label (e.g., commit subject) for UIs.
title: Option<String>,
},
/// Arbitrary instructions, equivalent to the old free-form prompt.
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Custom { instructions: String },
}

View File

@@ -0,0 +1,13 @@
//! Fire-and-forget maintenance requests for local rollout storage.
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
/// Acknowledges the compression trigger, not completion. Existing maintenance
/// locks and cooldowns can cause the background pass to skip without doing work.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct RolloutCompressResponse {}

View File

@@ -0,0 +1,366 @@
use crate::JsonSchema;
use crate::TS;
use akode_experimental_api_macros::ExperimentalApi;
use akode_protocol::config_types::ApprovalsReviewer as CoreApprovalsReviewer;
use akode_protocol::config_types::SandboxMode as CoreSandboxMode;
use akode_protocol::protocol::AskForApproval as CoreAskForApproval;
use akode_protocol::protocol::CodexErrorInfo as CoreCodexErrorInfo;
use akode_protocol::protocol::GranularApprovalConfig as CoreGranularApprovalConfig;
use akode_protocol::protocol::NonSteerableTurnKind as CoreNonSteerableTurnKind;
#[cfg(test)]
use schemars::r#gen::SchemaGenerator;
#[cfg(test)]
use schemars::schema::InstanceType;
#[cfg(test)]
use schemars::schema::Metadata;
#[cfg(test)]
use schemars::schema::Schema;
#[cfg(test)]
use schemars::schema::SchemaObject;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
// Macro to declare a camelCased API v2 enum mirroring a core enum which
// tends to use either snake_case or kebab-case.
macro_rules! v2_enum_from_core {
(
$(#[$enum_meta:meta])*
pub enum $Name:ident from $Src:path {
$( $(#[$variant_meta:meta])* $Variant:ident ),+ $(,)?
}
) => {
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
$(#[$enum_meta])*
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum $Name {
$( $(#[$variant_meta])* $Variant ),+
}
impl $Name {
pub fn to_core(self) -> $Src {
match self { $( $Name::$Variant => <$Src>::$Variant ),+ }
}
}
impl From<$Src> for $Name {
fn from(value: $Src) -> Self {
match value { $( <$Src>::$Variant => $Name::$Variant ),+ }
}
}
};
}
pub(super) use v2_enum_from_core;
pub(super) const fn default_enabled() -> bool {
true
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum NonSteerableTurnKind {
Review,
Compact,
}
/// This translation layer make sure that we expose codex error code in camel case.
///
/// When an upstream HTTP status is available (for example, from the Responses API or a provider),
/// it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum CodexErrorInfo {
ContextWindowExceeded,
SessionBudgetExceeded,
UsageLimitExceeded,
RateLimitExceeded,
FlexUnavailable,
ServerOverloaded,
ModelNotFound,
// Capacity is unavailable on a route restricted by server policy.
PolicyCapacityUnavailable,
CyberPolicy,
MisalignmentPolicyViolation,
TooManyDenials,
HttpConnectionFailed {
#[serde(rename = "httpStatusCode")]
#[ts(rename = "httpStatusCode")]
http_status_code: Option<u16>,
},
/// Failed to connect to the response SSE stream.
ResponseStreamConnectionFailed {
#[serde(rename = "httpStatusCode")]
#[ts(rename = "httpStatusCode")]
http_status_code: Option<u16>,
},
InternalServerError,
Unauthorized,
BadRequest,
ThreadRollbackFailed,
SandboxError,
/// The response SSE stream disconnected in the middle of a turn before completion.
ResponseStreamDisconnected {
#[serde(rename = "httpStatusCode")]
#[ts(rename = "httpStatusCode")]
http_status_code: Option<u16>,
},
/// Reached the retry limit for responses.
ResponseTooManyFailedAttempts {
#[serde(rename = "httpStatusCode")]
#[ts(rename = "httpStatusCode")]
http_status_code: Option<u16>,
},
/// Returned when `turn/start` or `turn/steer` is submitted while the current active turn
/// cannot accept same-turn steering, for example `/review` or manual `/compact`.
ActiveTurnNotSteerable {
#[serde(rename = "turnKind")]
#[ts(rename = "turnKind")]
turn_kind: NonSteerableTurnKind,
},
#[serde(
untagged,
serialize_with = "serialize_other_codex_error_info",
deserialize_with = "deserialize_other_codex_error_info"
)]
#[ts(type = "\"other\" | string | { [key: string]: unknown }")]
Other,
}
fn serialize_other_codex_error_info<S>(serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str("other")
}
fn deserialize_other_codex_error_info<'de, D>(deserializer: D) -> Result<(), D::Error>
where
D: serde::Deserializer<'de>,
{
match JsonValue::deserialize(deserializer)? {
JsonValue::String(_) | JsonValue::Object(_) => Ok(()),
_ => Err(serde::de::Error::custom(
"expected an error string or object",
)),
}
}
impl From<CoreCodexErrorInfo> for CodexErrorInfo {
fn from(value: CoreCodexErrorInfo) -> Self {
match value {
CoreCodexErrorInfo::ContextWindowExceeded => CodexErrorInfo::ContextWindowExceeded,
CoreCodexErrorInfo::SessionBudgetExceeded => CodexErrorInfo::SessionBudgetExceeded,
CoreCodexErrorInfo::UsageLimitExceeded => CodexErrorInfo::UsageLimitExceeded,
CoreCodexErrorInfo::RateLimitExceeded => CodexErrorInfo::RateLimitExceeded,
CoreCodexErrorInfo::FlexUnavailable => CodexErrorInfo::FlexUnavailable,
CoreCodexErrorInfo::ServerOverloaded => CodexErrorInfo::ServerOverloaded,
CoreCodexErrorInfo::ModelNotFound => CodexErrorInfo::ModelNotFound,
CoreCodexErrorInfo::PolicyCapacityUnavailable => {
CodexErrorInfo::PolicyCapacityUnavailable
}
CoreCodexErrorInfo::CyberPolicy => CodexErrorInfo::CyberPolicy,
CoreCodexErrorInfo::BioPolicy => CodexErrorInfo::Other,
CoreCodexErrorInfo::MisalignmentPolicyViolation => {
CodexErrorInfo::MisalignmentPolicyViolation
}
CoreCodexErrorInfo::TooManyDenials => CodexErrorInfo::TooManyDenials,
CoreCodexErrorInfo::HttpConnectionFailed { http_status_code } => {
CodexErrorInfo::HttpConnectionFailed { http_status_code }
}
CoreCodexErrorInfo::ResponseStreamConnectionFailed { http_status_code } => {
CodexErrorInfo::ResponseStreamConnectionFailed { http_status_code }
}
CoreCodexErrorInfo::InternalServerError => CodexErrorInfo::InternalServerError,
CoreCodexErrorInfo::Unauthorized => CodexErrorInfo::Unauthorized,
CoreCodexErrorInfo::BadRequest => CodexErrorInfo::BadRequest,
CoreCodexErrorInfo::InvalidPrompt => CodexErrorInfo::Other,
CoreCodexErrorInfo::ThreadRollbackFailed => CodexErrorInfo::ThreadRollbackFailed,
CoreCodexErrorInfo::SandboxError => CodexErrorInfo::SandboxError,
CoreCodexErrorInfo::ResponseStreamDisconnected { http_status_code } => {
CodexErrorInfo::ResponseStreamDisconnected { http_status_code }
}
CoreCodexErrorInfo::ResponseTooManyFailedAttempts { http_status_code } => {
CodexErrorInfo::ResponseTooManyFailedAttempts { http_status_code }
}
CoreCodexErrorInfo::ActiveTurnNotSteerable { turn_kind } => {
CodexErrorInfo::ActiveTurnNotSteerable {
turn_kind: turn_kind.into(),
}
}
CoreCodexErrorInfo::Other => CodexErrorInfo::Other,
}
}
}
impl From<CoreNonSteerableTurnKind> for NonSteerableTurnKind {
fn from(value: CoreNonSteerableTurnKind) -> Self {
match value {
CoreNonSteerableTurnKind::Review => Self::Review,
CoreNonSteerableTurnKind::Compact => Self::Compact,
}
}
}
#[derive(
Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS, ExperimentalApi,
)]
#[serde(rename_all = "kebab-case")]
#[ts(rename_all = "kebab-case", export_to = "v2/")]
pub enum AskForApproval {
#[serde(rename = "untrusted")]
#[ts(rename = "untrusted")]
UnlessTrusted,
OnRequest,
#[experimental("askForApproval.granular")]
Granular {
sandbox_approval: bool,
rules: bool,
#[serde(default)]
skill_approval: bool,
#[serde(default)]
request_permissions: bool,
mcp_elicitations: bool,
},
Never,
}
impl AskForApproval {
pub fn to_core(self) -> CoreAskForApproval {
match self {
AskForApproval::UnlessTrusted => CoreAskForApproval::UnlessTrusted,
AskForApproval::OnRequest => CoreAskForApproval::OnRequest,
AskForApproval::Granular {
sandbox_approval,
rules,
skill_approval,
request_permissions,
mcp_elicitations,
} => CoreAskForApproval::Granular(CoreGranularApprovalConfig {
sandbox_approval,
rules,
skill_approval,
request_permissions,
mcp_elicitations,
}),
AskForApproval::Never => CoreAskForApproval::Never,
}
}
}
impl From<CoreAskForApproval> for AskForApproval {
fn from(value: CoreAskForApproval) -> Self {
match value {
CoreAskForApproval::UnlessTrusted => AskForApproval::UnlessTrusted,
CoreAskForApproval::OnRequest => AskForApproval::OnRequest,
CoreAskForApproval::Granular(granular_config) => AskForApproval::Granular {
sandbox_approval: granular_config.sandbox_approval,
rules: granular_config.rules,
skill_approval: granular_config.skill_approval,
request_permissions: granular_config.request_permissions,
mcp_elicitations: granular_config.mcp_elicitations,
},
CoreAskForApproval::Never => AskForApproval::Never,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, TS)]
#[ts(
type = r#""user" | "auto_review" | "guardian_subagent""#,
export_to = "v2/"
)]
/// Configures who approval requests are routed to for review. Examples
/// include sandbox escapes, blocked network access, MCP approval prompts, and
/// ARC escalations. Defaults to `user`. `auto_review` uses a carefully
/// prompted subagent to gather relevant context and apply a risk-based
/// decision framework before approving or denying the request.
pub enum ApprovalsReviewer {
#[serde(rename = "user")]
User,
#[serde(rename = "auto_review", alias = "guardian_subagent")]
AutoReview,
}
#[cfg(test)]
impl JsonSchema for ApprovalsReviewer {
fn schema_name() -> String {
"ApprovalsReviewer".to_string()
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
string_enum_schema_with_description(
&["user", "auto_review", "guardian_subagent"],
"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.",
)
}
}
#[cfg(test)]
fn string_enum_schema_with_description(values: &[&str], description: &str) -> Schema {
let mut schema = SchemaObject {
instance_type: Some(InstanceType::String.into()),
metadata: Some(Box::new(Metadata {
description: Some(description.to_string()),
..Default::default()
})),
..Default::default()
};
schema.enum_values = Some(
values
.iter()
.map(|value| JsonValue::String((*value).to_string()))
.collect(),
);
Schema::Object(schema)
}
impl ApprovalsReviewer {
pub fn to_core(self) -> CoreApprovalsReviewer {
match self {
ApprovalsReviewer::User => CoreApprovalsReviewer::User,
ApprovalsReviewer::AutoReview => CoreApprovalsReviewer::AutoReview,
}
}
}
impl From<CoreApprovalsReviewer> for ApprovalsReviewer {
fn from(value: CoreApprovalsReviewer) -> Self {
match value {
CoreApprovalsReviewer::User => ApprovalsReviewer::User,
CoreApprovalsReviewer::AutoReview => ApprovalsReviewer::AutoReview,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "kebab-case")]
#[ts(rename_all = "kebab-case", export_to = "v2/")]
pub enum SandboxMode {
ReadOnly,
WorkspaceWrite,
DangerFullAccess,
}
impl SandboxMode {
pub fn to_core(self) -> CoreSandboxMode {
match self {
SandboxMode::ReadOnly => CoreSandboxMode::ReadOnly,
SandboxMode::WorkspaceWrite => CoreSandboxMode::WorkspaceWrite,
SandboxMode::DangerFullAccess => CoreSandboxMode::DangerFullAccess,
}
}
}
impl From<CoreSandboxMode> for SandboxMode {
fn from(value: CoreSandboxMode) -> Self {
match value {
CoreSandboxMode::ReadOnly => SandboxMode::ReadOnly,
CoreSandboxMode::WorkspaceWrite => SandboxMode::WorkspaceWrite,
CoreSandboxMode::DangerFullAccess => SandboxMode::DangerFullAccess,
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,142 @@
//! Wire contracts for managing the current set of attachments on a thread.
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
/// An independently persisted attachment associated with a thread.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachment {
pub id: String,
pub attachment_type: String,
pub identity_key: String,
pub payload: JsonValue,
#[ts(type = "number")]
pub created_at: i64,
}
/// Parameters for creating or locating an attachment on its owning thread.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentAddParams {
pub thread_id: String,
pub attachment_type: String,
pub identity_key: String,
pub payload: JsonValue,
}
/// Result of attempting to associate an attachment with a thread.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum ThreadAttachmentAddOutcome {
Created,
Existing,
}
/// The created or existing attachment.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentAddResponse {
pub outcome: ThreadAttachmentAddOutcome,
pub attachment: ThreadAttachment,
}
/// Parameters for listing attachments from one thread.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentListParams {
pub thread_id: String,
#[ts(optional = nullable)]
pub cursor: Option<String>,
#[ts(optional = nullable)]
pub limit: Option<u32>,
}
/// One page of attachments associated with the requested thread.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentListResponse {
pub data: Vec<ThreadAttachment>,
pub next_cursor: Option<String>,
}
/// Parameters for deleting an attachment by its stable thread-local identity.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentRemoveParams {
pub thread_id: String,
pub attachment_type: String,
pub identity_key: String,
}
/// Successful deletion does not return additional attachment data.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentRemoveResponse {}
/// The persisted attachment change represented by a notification.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum ThreadAttachmentOperation {
Created,
Deleted,
}
/// Notification published after a thread attachment is created or deleted.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentUpdatedNotification {
pub thread_id: String,
pub attachment_type: String,
pub identity_key: String,
pub attachment_id: String,
pub operation: ThreadAttachmentOperation,
}
/// Parameters for reverse lookup by attachment identity within this server's store.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentOwnerListParams {
pub attachment_type: String,
pub identity_key: String,
/// Omitted or null returns all matches; false returns non-archived threads only.
#[ts(optional = nullable)]
pub archived: Option<bool>,
#[ts(optional = nullable)]
pub cursor: Option<String>,
#[ts(optional = nullable)]
pub limit: Option<u32>,
}
/// A thread that currently owns an attachment with the requested identity.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentOwner {
pub thread_id: String,
/// Whether the owning thread is archived, not whether it is currently executing a turn.
pub archived: bool,
}
/// One page of matching owners, including threads without their own user messages.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadAttachmentOwnerListResponse {
pub data: Vec<ThreadAttachmentOwner>,
pub next_cursor: Option<String>,
}

View File

@@ -0,0 +1,507 @@
use super::CodexErrorInfo;
use super::ThreadEnvironment;
use super::ThreadItem;
use super::ThreadItemPayload;
use super::ThreadStatus;
use super::TurnStatus;
use crate::JsonSchema;
use crate::TS;
use akode_experimental_api_macros::ExperimentalApi;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::protocol::MisalignmentErrorDetails as CoreMisalignmentErrorDetails;
use akode_protocol::protocol::MisalignmentSteer as CoreMisalignmentSteer;
use akode_protocol::protocol::SessionSource as CoreSessionSource;
use akode_protocol::protocol::SubAgentSource as CoreSubAgentSource;
use akode_protocol::protocol::ThreadHistoryMode as CoreThreadHistoryMode;
use akode_protocol::protocol::ThreadSource as CoreThreadSource;
use akode_utils_absolute_path::AbsolutePathBuf;
#[cfg(test)]
use schemars::r#gen::SchemaGenerator;
#[cfg(test)]
use schemars::schema::Schema;
use serde::Deserialize;
use serde::Serialize;
use std::fmt;
use std::path::PathBuf;
use thiserror::Error;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
#[derive(Default)]
pub enum SessionSource {
Cli,
#[serde(rename = "vscode")]
#[ts(rename = "vscode")]
#[default]
VsCode,
Exec,
AppServer,
Custom(String),
SubAgent(CoreSubAgentSource),
#[serde(other)]
Unknown,
}
impl From<CoreSessionSource> for SessionSource {
fn from(value: CoreSessionSource) -> Self {
match value {
CoreSessionSource::Cli => SessionSource::Cli,
CoreSessionSource::VSCode => SessionSource::VsCode,
CoreSessionSource::Exec => SessionSource::Exec,
CoreSessionSource::Mcp => SessionSource::AppServer,
CoreSessionSource::Custom(source) => SessionSource::Custom(source),
// We do not want to render those at the app-server level.
CoreSessionSource::Internal(_) => SessionSource::Unknown,
CoreSessionSource::SubAgent(sub) => SessionSource::SubAgent(sub),
CoreSessionSource::Unknown => SessionSource::Unknown,
}
}
}
impl From<SessionSource> for CoreSessionSource {
fn from(value: SessionSource) -> Self {
match value {
SessionSource::Cli => CoreSessionSource::Cli,
SessionSource::VsCode => CoreSessionSource::VSCode,
SessionSource::Exec => CoreSessionSource::Exec,
SessionSource::AppServer => CoreSessionSource::Mcp,
SessionSource::Custom(source) => CoreSessionSource::Custom(source),
SessionSource::SubAgent(sub) => CoreSessionSource::SubAgent(sub),
SessionSource::Unknown => CoreSessionSource::Unknown,
}
}
}
#[derive(Default, Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename_all = "lowercase", export_to = "v2/")]
pub enum ThreadHistoryMode {
#[default]
Legacy,
Paginated,
}
impl From<CoreThreadHistoryMode> for ThreadHistoryMode {
fn from(value: CoreThreadHistoryMode) -> Self {
match value {
CoreThreadHistoryMode::Legacy => Self::Legacy,
CoreThreadHistoryMode::Paginated => Self::Paginated,
}
}
}
impl From<ThreadHistoryMode> for CoreThreadHistoryMode {
fn from(value: ThreadHistoryMode) -> Self {
match value {
ThreadHistoryMode::Legacy => Self::Legacy,
ThreadHistoryMode::Paginated => Self::Paginated,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, TS)]
#[serde(try_from = "String", into = "String")]
#[ts(type = "string")]
#[ts(export_to = "v2/")]
pub enum ThreadSource {
User,
Subagent,
GuardianReview,
Feature(String),
MemoryConsolidation,
}
#[cfg(test)]
impl JsonSchema for ThreadSource {
fn schema_name() -> String {
"ThreadSource".to_string()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
String::json_schema(generator)
}
}
impl TryFrom<String> for ThreadSource {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
value.parse::<CoreThreadSource>().map(Into::into)
}
}
impl From<ThreadSource> for String {
fn from(value: ThreadSource) -> Self {
CoreThreadSource::from(value).into()
}
}
impl From<CoreThreadSource> for ThreadSource {
fn from(value: CoreThreadSource) -> Self {
match value {
CoreThreadSource::User => ThreadSource::User,
CoreThreadSource::Subagent => ThreadSource::Subagent,
CoreThreadSource::GuardianReview => ThreadSource::GuardianReview,
CoreThreadSource::Feature(feature) => ThreadSource::Feature(feature),
CoreThreadSource::MemoryConsolidation => ThreadSource::MemoryConsolidation,
}
}
}
impl From<ThreadSource> for CoreThreadSource {
fn from(value: ThreadSource) -> Self {
match value {
ThreadSource::User => CoreThreadSource::User,
ThreadSource::Subagent => CoreThreadSource::Subagent,
ThreadSource::GuardianReview => CoreThreadSource::GuardianReview,
ThreadSource::Feature(feature) => CoreThreadSource::Feature(feature),
ThreadSource::MemoryConsolidation => CoreThreadSource::MemoryConsolidation,
}
}
}
/// Extra app-server data for a thread.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub struct ThreadExtra {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct GitInfo {
pub sha: Option<String>,
pub branch: Option<String>,
pub origin_url: Option<String>,
}
/// An independently persisted, user-visible thread section.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadSection {
/// Opaque UUIDv7 identity that remains stable when the section is renamed.
pub id: String,
/// The current user-visible section name.
pub name: String,
/// Optional appearance synchronized across clients.
#[serde(default)]
pub appearance: Option<ThreadSectionAppearance>,
}
/// Extensible visual presentation for a custom thread section.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadSectionAppearance {
pub icon: Option<String>,
pub color: Option<String>,
}
#[derive(Serialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct Thread {
/// Identifier for this thread. Codex-generated thread IDs are UUIDv7.
pub id: String,
/// Current environments for a loaded thread, in priority order, primary first.
/// `null` means the thread is not loaded or the server does not expose its selection.
/// An empty list means no environments are selected. This does not report connection status.
#[experimental("thread.environments")]
#[serde(default)]
pub environments: Option<Vec<ThreadEnvironment>>,
/// Optional implementation-specific thread data.
#[experimental("thread.extra")]
pub extra: Option<ThreadExtra>,
/// Session id shared by threads that belong to the same session tree.
pub session_id: String,
/// Source thread id when this thread was created by forking another thread.
pub forked_from_id: Option<String>,
/// The ID of the parent thread. This will only be set if this thread is a subagent.
pub parent_thread_id: Option<String>,
/// Usually the first user message in the thread, if available.
pub preview: String,
/// Whether the thread is ephemeral and should not be materialized on disk.
pub ephemeral: bool,
/// The independently persisted section selected for this thread, if any.
#[serde(default)]
pub section: Option<ThreadSection>,
/// Unix timestamp in seconds when the thread entered its current section.
#[serde(default)]
#[ts(type = "number | null")]
pub section_entered_at: Option<i64>,
/// Canonical project assignment owned by app-server, if any.
#[schemars(
required,
schema_with = "crate::protocol::serde_helpers::nullable_string_schema"
)]
pub project_id: Option<String>,
/// Persisted thread history contract selected when this thread was created.
#[serde(default)]
pub history_mode: ThreadHistoryMode,
/// Model provider used for this thread (for example, 'openai').
pub model_provider: String,
/// Current configured model when loaded, otherwise the latest persisted model.
/// Null when unavailable. This is not per-turn execution telemetry.
pub model: Option<String>,
/// Current configured reasoning effort when loaded, otherwise the latest persisted effort.
/// Null when unset or unavailable. This is not per-turn execution telemetry.
pub reasoning_effort: Option<ReasoningEffort>,
/// Unix timestamp (in seconds) when the thread was created.
#[ts(type = "number")]
pub created_at: i64,
/// Unix timestamp (in seconds) when the thread was last updated.
#[ts(type = "number")]
pub updated_at: i64,
/// Unix timestamp (in seconds) used for thread recency ordering.
#[ts(type = "number | null")]
pub recency_at: Option<i64>,
/// Current runtime status for the thread.
pub status: ThreadStatus,
/// [UNSTABLE] Path to the thread on disk.
pub path: Option<PathBuf>,
/// Working directory captured for the thread.
pub cwd: AbsolutePathBuf,
/// Version of the CLI that created the thread.
pub cli_version: String,
/// Originator recorded when the thread was created, independent of its current client or executor.
/// Null when the recorded originator is unavailable.
pub originator: Option<String>,
/// Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).
pub source: SessionSource,
/// Whether the app server accepts direct turn input for this loaded thread.
/// `None` means the capability is unavailable, such as for an unloaded stored thread.
#[experimental("thread.canAcceptDirectInput")]
pub can_accept_direct_input: Option<bool>,
/// Optional source classification for this thread.
pub thread_source: Option<ThreadSource>,
/// Optional random unique nickname assigned to an AgentControl-spawned sub-agent.
pub agent_nickname: Option<String>,
/// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.
pub agent_role: Option<String>,
/// Optional Git metadata captured when the thread was created.
pub git_info: Option<GitInfo>,
/// Optional user-facing thread title.
pub name: Option<String>,
/// Only populated on `thread/resume`, `thread/fork`, and `thread/read`
/// (when `includeTurns` is true) responses.
/// For all other responses and notifications returning a Thread,
/// the turns field will be an empty list.
pub turns: Vec<Turn>,
}
// TODO: Remove this compatibility decoder after app-server versions that omitted
// `projectId` have aged out of the supported TUI -> remote app-server version-skew window.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ThreadCompatibility {
id: String,
#[serde(default)]
environments: Option<Vec<ThreadEnvironment>>,
extra: Option<ThreadExtra>,
session_id: String,
forked_from_id: Option<String>,
parent_thread_id: Option<String>,
preview: String,
ephemeral: bool,
#[serde(default)]
section: Option<ThreadSection>,
#[serde(default)]
section_entered_at: Option<i64>,
#[serde(default)]
project_id: Option<String>,
#[serde(default)]
history_mode: ThreadHistoryMode,
model_provider: String,
model: Option<String>,
reasoning_effort: Option<ReasoningEffort>,
created_at: i64,
updated_at: i64,
recency_at: Option<i64>,
status: ThreadStatus,
path: Option<PathBuf>,
cwd: AbsolutePathBuf,
cli_version: String,
originator: Option<String>,
source: SessionSource,
can_accept_direct_input: Option<bool>,
thread_source: Option<ThreadSource>,
agent_nickname: Option<String>,
agent_role: Option<String>,
git_info: Option<GitInfo>,
name: Option<String>,
turns: Vec<Turn>,
}
impl<'de> Deserialize<'de> for Thread {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let thread = ThreadCompatibility::deserialize(deserializer)?;
Ok(Self {
id: thread.id,
environments: thread.environments,
extra: thread.extra,
session_id: thread.session_id,
forked_from_id: thread.forked_from_id,
parent_thread_id: thread.parent_thread_id,
preview: thread.preview,
ephemeral: thread.ephemeral,
section: thread.section,
section_entered_at: thread.section_entered_at,
project_id: thread.project_id,
history_mode: thread.history_mode,
model_provider: thread.model_provider,
model: thread.model,
reasoning_effort: thread.reasoning_effort,
created_at: thread.created_at,
updated_at: thread.updated_at,
recency_at: thread.recency_at,
status: thread.status,
path: thread.path,
cwd: thread.cwd,
cli_version: thread.cli_version,
originator: thread.originator,
source: thread.source,
can_accept_direct_input: thread.can_accept_direct_input,
thread_source: thread.thread_source,
agent_nickname: thread.agent_nickname,
agent_role: thread.agent_role,
git_info: thread.git_info,
name: thread.name,
turns: thread.turns,
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct Turn {
/// Identifier for this turn. Codex-generated turn IDs are UUIDv7.
pub id: String,
/// ID of the first turn in the chain of work that led to this turn.
/// Pass this as `rootTurnId` when starting work on behalf of this turn.
/// May be null in older history or a `review/start` response.
pub root_turn_id: Option<String>,
/// Thread items currently included in this turn payload.
pub items: Vec<ThreadItem>,
/// Describes how much of `items` has been loaded for this turn.
#[serde(default)]
pub items_view: TurnItemsView,
pub status: TurnStatus,
/// Error associated with a failed or interrupted turn.
pub error: Option<TurnError>,
/// Unix timestamp (in seconds) when the turn started.
#[ts(type = "number | null")]
pub started_at: Option<i64>,
/// Unix timestamp (in seconds) when the turn completed.
#[ts(type = "number | null")]
pub completed_at: Option<i64>,
/// Duration between turn start and completion in milliseconds, if known.
#[ts(type = "number | null")]
pub duration_ms: Option<i64>,
}
impl Turn {
/// Iterates over the item payloads in this turn.
pub fn item_payloads(
&self,
) -> impl DoubleEndedIterator<Item = &ThreadItemPayload> + ExactSizeIterator {
self.items.iter().map(|item| &item.payload)
}
}
#[derive(Default, Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum TurnItemsView {
/// `items` was not loaded for this turn. The field is intentionally empty.
NotLoaded,
/// `items` contains only a display summary for this turn.
Summary,
/// `items` contains every ThreadItem available from persisted app-server history for this turn.
#[default]
Full,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, Error)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
#[error("{message}")]
pub struct TurnError {
pub message: String,
pub codex_error_info: Option<CodexErrorInfo>,
#[serde(default)]
pub additional_details: Option<String>,
/// Optional public explanation and continuation instruction for a misalignment block.
#[serde(default)]
pub misalignment: Option<MisalignmentErrorDetails>,
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MisalignmentErrorDetails {
/// Open-ended classification; clients must accept categories added by Responses.
pub error_type: Option<String>,
/// A substantive localized explanation is required before offering continuation.
pub detailed_explanation: Option<String>,
/// Instruction to submit as the next turn's user input if continuation is confirmed.
pub steer: Option<MisalignmentSteer>,
/// Opaque server-issued block target. Presence alone does not enable target-based continuation.
#[ts(optional = nullable)]
pub review_target: Option<String>,
}
impl fmt::Debug for MisalignmentErrorDetails {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MisalignmentErrorDetails")
.field("error_type", &self.error_type)
.field(
"has_detailed_explanation",
&self.detailed_explanation.is_some(),
)
.field("has_steer", &self.steer.is_some())
.field("has_review_target", &self.review_target.is_some())
.finish()
}
}
impl From<CoreMisalignmentErrorDetails> for MisalignmentErrorDetails {
fn from(value: CoreMisalignmentErrorDetails) -> Self {
Self {
error_type: value.error_type,
detailed_explanation: value.detailed_explanation,
steer: value.steer.map(Into::into),
review_target: value.review_target,
}
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MisalignmentSteer {
pub message: String,
}
impl fmt::Debug for MisalignmentSteer {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MisalignmentSteer")
.field("message", &"[REDACTED]")
.finish()
}
}
impl From<CoreMisalignmentSteer> for MisalignmentSteer {
fn from(value: CoreMisalignmentSteer) -> Self {
Self {
message: value.message,
}
}
}

View File

@@ -0,0 +1,35 @@
//! App-server API types for predictions.
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadPredictionRequestParams {
pub thread_id: String,
pub source_turn_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[ts(export_to = "v2/")]
pub struct ThreadPredictionRequestResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadPredictionUpdatedNotification {
pub thread_id: String,
pub source_turn_id: String,
pub result: ThreadPredictionResult,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type", rename_all = "camelCase", export_to = "v2/")]
pub enum ThreadPredictionResult {
Completed { text: Option<String> },
Failed,
}

View File

@@ -0,0 +1,62 @@
//! One model response on an ephemeral fork that inherits the source's configuration and context.
use super::ThreadSource;
use crate::JsonSchema;
use crate::RequestId;
use crate::TS;
use akode_protocol::openai_models::ReasoningEffort;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadSampleParams {
pub thread_id: String,
/// The loaded source's latest completed, failed, or interrupted turn.
/// Stale or active sources are rejected.
pub expected_turn_id: String,
pub prompt: String,
/// Applied only when the provider and model support cache-preserving reasoning-effort updates.
#[ts(optional = nullable)]
pub effort: Option<ReasoningEffort>,
#[ts(optional = nullable)]
pub thread_source: Option<ThreadSource>,
#[ts(optional = nullable)]
pub turn_trigger: Option<String>,
/// Optional metadata to enrich Codex's ResponsesAPI turn metadata.
#[ts(optional = nullable)]
pub responsesapi_client_metadata: Option<HashMap<String, String>>,
/// Disable MCP servers when the inherited window uses incremental tools on Responses Lite.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub disable_mcp: bool,
/// Override upstream interruption on cancellation for this sample; otherwise inherit the parent.
#[ts(optional = nullable)]
pub interrupt_on_cancel: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadSampleResponse {
pub source_turn_id: String,
pub response_id: String,
/// Assistant text from the response, or null if it attempted a tool call or completed without text.
pub text: Option<String>,
pub input_tokens: Option<i64>,
pub cached_input_tokens: Option<i64>,
pub output_tokens: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct ThreadSampleCancelParams {
pub request_id: RequestId,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadSampleCancelResponse {}

View File

@@ -0,0 +1,34 @@
//! Thread billing amounts, keeping native dollars separate from credit estimates.
use crate::JsonSchema;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadUsage {
pub thread_id: String,
pub estimated_usage_credits_micros: i64,
pub estimated_usage_usd_micros: Option<i64>,
/// Native dollar usage, independent of credit estimates. None means unknown, not zero.
#[ts(optional, as = "Option<Option<i64>>")]
pub native_usage_usd_micros: Option<i64>,
pub groups: Vec<ThreadUsageBreakdownGroup>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadUsageBreakdownGroup {
pub model: Option<String>,
pub reasoning_effort: Option<String>,
pub speed: Option<String>,
pub estimated_usage_credits_micros: i64,
pub net_new_input_tokens: Option<i64>,
pub cached_input_tokens: Option<i64>,
pub input_tokens: Option<i64>,
pub output_tokens: Option<i64>,
pub total_tokens: Option<i64>,
}

View File

@@ -0,0 +1,632 @@
use super::ApprovalsReviewer;
use super::AskForApproval;
use super::SandboxPolicy;
use super::Turn;
use crate::JsonSchema;
use crate::TS;
use akode_experimental_api_macros::ExperimentalApi;
use akode_protocol::config_types::CollaborationMode;
use akode_protocol::config_types::MultiAgentMode;
use akode_protocol::config_types::Personality;
use akode_protocol::config_types::ReasoningSummary;
use akode_protocol::models::AudioReference as CoreAudioReference;
use akode_protocol::models::FunctionCallOutputBody;
use akode_protocol::models::ImageDetail;
use akode_protocol::models::ImageReference as CoreImageReference;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::plan_tool::PlanItemArg as CorePlanItemArg;
use akode_protocol::plan_tool::StepStatus as CorePlanStepStatus;
use akode_protocol::user_input::ByteRange as CoreByteRange;
use akode_protocol::user_input::TextElement as CoreTextElement;
use akode_protocol::user_input::UserInput as CoreUserInput;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::LegacyAppPathString;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum TurnStatus {
Completed,
Interrupted,
Failed,
InProgress,
}
// Turn APIs
/// Experimental settings changes for one running turn, not future turns.
/// Unsupported fields are rejected rather than silently ignored.
/// Any live task kind may accept publication. Child sessions and consumers of
/// frozen initial settings are unchanged.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct TurnSettingsUpdateParams {
pub thread_id: String,
pub turn_id: String,
/// Changes the active turn's reviewer without changing future thread settings.
/// Already captured steps and pending approvals retain their original reviewer.
#[ts(optional = nullable)]
pub approvals_reviewer: Option<ApprovalsReviewer>,
/// Omission or `null` leaves the model unchanged.
#[ts(optional = nullable)]
pub model: Option<String>,
/// Omission or `null` leaves the effort unchanged.
#[ts(optional = nullable)]
pub effort: Option<ReasoningEffort>,
/// Omission or `null` leaves the summary preference unchanged.
#[ts(optional = nullable)]
pub summary: Option<ReasoningSummary>,
/// `null` clears the requested tier; omission leaves it unchanged.
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
serialize_with = "crate::protocol::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional = nullable)]
pub service_tier: Option<Option<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnSettingsUpdateResponse {
pub status: TurnSettingsUpdateStatus,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum TurnSettingsUpdateStatus {
/// Published for subsequent captures, even if the values were unchanged.
/// Already captured steps are unchanged; a later inference is not guaranteed.
Applied,
/// No matching live task remained available for publication.
TargetUnavailable,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnEnvironmentParams {
pub environment_id: String,
pub cwd: LegacyAppPathString,
/// Environment-native runtime workspace roots. Omitted defaults to `cwd`.
#[ts(optional = nullable)]
pub runtime_workspace_roots: Option<Vec<LegacyAppPathString>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename_all = "lowercase")]
#[ts(export_to = "v2/")]
pub enum AdditionalContextKind {
Untrusted,
Application,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AdditionalContextEntry {
pub value: String,
pub kind: AdditionalContextKind,
/// Optional name for untrusted context, used to label its tool output.
#[ts(optional = nullable)]
pub name: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnToolOutput {
pub name: String,
pub namespace: Option<String>,
pub output: FunctionCallOutputBody,
/// Requests retention of this output in the thread's model history.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub retain: bool,
}
#[derive(
Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS, ExperimentalApi,
)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnStartParams {
pub thread_id: String,
/// Replace this thread's disabled plugin IDs.
/// Omitted/null preserves the list; [] clears it.
#[ts(optional = nullable)]
pub disabled_plugin_ids: Option<Vec<String>>,
#[ts(optional = nullable)]
pub client_user_message_id: Option<String>,
pub input: Vec<UserInput>,
/// Optional source classification for the caller that starts this turn.
/// Ignored when this request steers an already-active turn.
#[ts(optional = nullable)]
pub turn_trigger: Option<String>,
/// ID of the turn that caused this new turn to start.
///
/// Set this when starting work on behalf of another turn, such as delegated
/// work in a different thread. Leave unset for work started directly by the
/// user. Ignored when this request adds input to an active turn.
#[ts(optional = nullable)]
pub parent_turn_id: Option<String>,
/// ID of the first turn in the chain of work that led to this new turn.
///
/// When setting `parentTurnId`, set this to the parent turn's `rootTurnId`
/// when known. This keeps descendant work attributed to the original turn.
/// If omitted, the new turn becomes its own root. Ignored when this request
/// adds input to an active turn.
#[ts(optional = nullable)]
pub root_turn_id: Option<String>,
#[ts(optional = nullable)]
pub tool_output: Option<Box<TurnToolOutput>>,
/// Optional metadata to enrich Codex's ResponsesAPI turn metadata.
/// Replaces unprotected client-provided entries when supplied; an empty map clears them.
///
/// Entries are flattened into the JSON string sent as
/// `client_metadata["x-codex-turn-metadata"]` on ResponsesAPI HTTP and websocket requests.
///
/// They are not sent as top-level ResponsesAPI `client_metadata` keys, and reserved keys
/// such as `session_id`, `thread_id`, `turn_id`, and `window_id` cannot be overridden.
#[experimental("turn/start.responsesapiClientMetadata")]
#[ts(optional = nullable)]
pub responsesapi_client_metadata: Option<HashMap<String, String>>,
/// Merge entries into the ResponsesAPI turn metadata without removing existing entries.
/// Applied after `responsesapiClientMetadata` if both are provided; reserved keys remain protected.
#[experimental("turn/start.responsesapiClientMetadataPatch")]
#[ts(optional = nullable)]
pub responsesapi_client_metadata_patch: Option<HashMap<String, String>>,
/// Optional client-provided context fragments keyed by an opaque source identifier.
#[experimental("turn/start.additionalContext")]
#[ts(optional = nullable)]
pub additional_context: Option<HashMap<String, AdditionalContextEntry>>,
/// Optional environments for this turn and subsequent turns.
///
/// Omitted uses the thread sticky environments. Empty disables
/// environment access for this turn. Non-empty selects the first
/// environment as the current turn environment for this turn.
#[experimental("turn/start.environments")]
#[ts(optional = nullable)]
pub environments: Option<Vec<TurnEnvironmentParams>>,
/// Override the working directory for this turn and subsequent turns.
#[ts(optional = nullable)]
pub cwd: Option<PathBuf>,
/// Replace the thread's runtime workspace roots for this turn and
/// subsequent turns. Paths must be absolute.
#[experimental("turn/start.runtimeWorkspaceRoots")]
#[ts(optional = nullable)]
pub runtime_workspace_roots: Option<Vec<AbsolutePathBuf>>,
/// Override the approval policy for this turn and subsequent turns.
#[experimental(nested)]
#[ts(optional = nullable)]
pub approval_policy: Option<AskForApproval>,
/// Override where approval requests are routed for review on this turn and
/// subsequent turns.
#[ts(optional = nullable)]
pub approvals_reviewer: Option<ApprovalsReviewer>,
/// Override the sandbox policy for this turn and subsequent turns.
#[ts(optional = nullable)]
pub sandbox_policy: Option<SandboxPolicy>,
/// Select a named permissions profile id for this turn and subsequent
/// turns. Cannot be combined with `sandboxPolicy`.
#[experimental("turn/start.permissions")]
#[ts(optional = nullable)]
pub permissions: Option<String>,
/// Override the model for this turn and subsequent turns.
#[ts(optional = nullable)]
pub model: Option<String>,
/// Override the service tier for this turn and subsequent turns.
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
serialize_with = "crate::protocol::serde_helpers::serialize_double_option",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional = nullable)]
pub service_tier: Option<Option<String>>,
/// Override the service tier only when this request starts a new turn.
/// Use "default" for standard speed. Omitted or null inherits the thread's tier.
/// Does not change the thread's tier or a turn being steered.
#[ts(optional = nullable)]
pub service_tier_for_turn: Option<String>,
/// Override the reasoning effort for this turn and subsequent turns.
#[ts(optional = nullable)]
pub effort: Option<ReasoningEffort>,
/// Override the reasoning summary for this turn and subsequent turns.
#[ts(optional = nullable)]
pub summary: Option<ReasoningSummary>,
/// @deprecated `friendly` and `pragmatic` no longer select a style.
/// Changing this does not rewrite the thread's existing instructions.
#[ts(optional = nullable)]
pub personality: Option<Personality>,
/// Optional JSON Schema used to constrain the final assistant message for
/// this turn.
#[ts(optional = nullable)]
pub output_schema: Option<JsonValue>,
/// EXPERIMENTAL - Set a pre-set collaboration mode.
/// Takes precedence over model, reasoning_effort, and developer instructions if set.
///
/// For `collaboration_mode.settings.developer_instructions`, `null` means
/// "use the built-in instructions for the selected mode".
#[experimental("turn/start.collaborationMode")]
#[ts(optional = nullable)]
pub collaboration_mode: Option<CollaborationMode>,
/// @deprecated Ignored. Use `effort: "ultra"` for proactive multi-agent behavior.
#[experimental("turn/start.multiAgentMode")]
#[ts(optional = nullable)]
pub multi_agent_mode: Option<MultiAgentMode>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnStartResponse {
pub turn: Turn,
}
#[derive(
Serialize, Deserialize, Debug, Default, Clone, PartialEq, JsonSchema, TS, ExperimentalApi,
)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnSteerParams {
pub thread_id: String,
#[ts(optional = nullable)]
pub client_user_message_id: Option<String>,
pub input: Vec<UserInput>,
/// Optional metadata to enrich Codex's ResponsesAPI turn metadata.
/// Replaces unprotected client-provided entries when supplied; an empty map clears them.
///
/// Entries are flattened into the JSON string sent as
/// `client_metadata["x-codex-turn-metadata"]` on ResponsesAPI HTTP and websocket requests.
///
/// They are not sent as top-level ResponsesAPI `client_metadata` keys, and reserved keys
/// such as `session_id`, `thread_id`, `turn_id`, and `window_id` cannot be overridden.
#[experimental("turn/steer.responsesapiClientMetadata")]
#[ts(optional = nullable)]
pub responsesapi_client_metadata: Option<HashMap<String, String>>,
/// Merge entries into the ResponsesAPI turn metadata without removing existing entries.
/// Applied after `responsesapiClientMetadata` if both are provided; reserved keys remain protected.
#[experimental("turn/steer.responsesapiClientMetadataPatch")]
#[ts(optional = nullable)]
pub responsesapi_client_metadata_patch: Option<HashMap<String, String>>,
/// Optional client-provided context fragments keyed by an opaque source identifier.
#[experimental("turn/steer.additionalContext")]
#[ts(optional = nullable)]
pub additional_context: Option<HashMap<String, AdditionalContextEntry>>,
/// Required active turn id precondition. The request fails when it does not
/// match the currently active turn.
pub expected_turn_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnSteerResponse {
pub turn_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnInterruptParams {
pub thread_id: String,
pub turn_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnInterruptResponse {}
// User input types
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ByteRange {
pub start: usize,
pub end: usize,
}
impl From<CoreByteRange> for ByteRange {
fn from(value: CoreByteRange) -> Self {
Self {
start: value.start,
end: value.end,
}
}
}
impl From<ByteRange> for CoreByteRange {
fn from(value: ByteRange) -> Self {
Self {
start: value.start,
end: value.end,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TextElement {
/// Byte range in the parent `text` buffer that this element occupies.
pub byte_range: ByteRange,
/// Optional human-readable placeholder for the element, displayed in the UI.
placeholder: Option<String>,
}
impl TextElement {
pub fn new(byte_range: ByteRange, placeholder: Option<String>) -> Self {
Self {
byte_range,
placeholder,
}
}
pub fn set_placeholder(&mut self, placeholder: Option<String>) {
self.placeholder = placeholder;
}
pub fn placeholder(&self) -> Option<&str> {
self.placeholder.as_deref()
}
}
impl From<CoreTextElement> for TextElement {
fn from(value: CoreTextElement) -> Self {
Self::new(
value.byte_range.into(),
value._placeholder_for_conversion_only().map(str::to_string),
)
}
}
impl From<TextElement> for CoreTextElement {
fn from(value: TextElement) -> Self {
Self::new(value.byte_range.into(), value.placeholder)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(untagged)]
#[ts(untagged)]
#[ts(export_to = "v2/")]
pub enum ImageReference {
Inline {
url: String,
},
File {
#[serde(rename = "fileId")]
#[ts(rename = "fileId")]
file_id: String,
},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(untagged)]
#[ts(untagged)]
#[ts(export_to = "v2/")]
pub enum AudioReference {
Inline {
url: String,
},
File {
#[serde(rename = "fileId")]
#[ts(rename = "fileId")]
file_id: String,
},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum UserInput {
Text {
text: String,
/// UI-defined spans within `text` used to render or persist special elements.
#[serde(default)]
text_elements: Vec<TextElement>,
},
Image {
#[serde(flatten)]
image: ImageReference,
#[serde(default)]
#[ts(optional)]
detail: Option<ImageDetail>,
},
LocalImage {
#[serde(default)]
#[ts(optional)]
detail: Option<ImageDetail>,
path: PathBuf,
},
Audio {
#[serde(flatten)]
audio: AudioReference,
},
LocalAudio {
path: PathBuf,
},
Skill {
name: String,
path: PathBuf,
},
Mention {
name: String,
path: String,
},
}
impl UserInput {
pub fn into_core(self) -> CoreUserInput {
match self {
UserInput::Text {
text,
text_elements,
} => CoreUserInput::Text {
text,
text_elements: text_elements.into_iter().map(Into::into).collect(),
},
UserInput::Image { image, detail } => CoreUserInput::Image {
image: match image {
ImageReference::Inline { url } => CoreImageReference::Inline { image_url: url },
ImageReference::File { file_id } => CoreImageReference::File { file_id },
},
detail,
},
UserInput::LocalImage { path, detail } => CoreUserInput::LocalImage { path, detail },
UserInput::Audio { audio } => CoreUserInput::Audio {
audio: match audio {
AudioReference::Inline { url } => CoreAudioReference::Inline { audio_url: url },
AudioReference::File { file_id } => CoreAudioReference::File { file_id },
},
},
UserInput::LocalAudio { path } => CoreUserInput::LocalAudio { path },
UserInput::Skill { name, path } => CoreUserInput::Skill { name, path },
UserInput::Mention { name, path } => CoreUserInput::Mention { name, path },
}
}
}
impl From<CoreUserInput> for UserInput {
fn from(value: CoreUserInput) -> Self {
match value {
CoreUserInput::Text {
text,
text_elements,
} => UserInput::Text {
text,
text_elements: text_elements.into_iter().map(Into::into).collect(),
},
CoreUserInput::Image { image, detail } => UserInput::Image {
image: match image {
CoreImageReference::Inline { image_url } => {
ImageReference::Inline { url: image_url }
}
CoreImageReference::File { file_id } => ImageReference::File { file_id },
},
detail,
},
CoreUserInput::LocalImage { path, detail } => UserInput::LocalImage { path, detail },
CoreUserInput::Audio { audio } => UserInput::Audio {
audio: match audio {
CoreAudioReference::Inline { audio_url } => {
AudioReference::Inline { url: audio_url }
}
CoreAudioReference::File { file_id } => AudioReference::File { file_id },
},
},
CoreUserInput::LocalAudio { path } => UserInput::LocalAudio { path },
CoreUserInput::Skill { name, path } => UserInput::Skill { name, path },
CoreUserInput::Mention { name, path } => UserInput::Mention { name, path },
_ => unreachable!("unsupported user input variant"),
}
}
}
impl UserInput {
pub fn text_char_count(&self) -> usize {
match self {
UserInput::Text { text, .. } => text.chars().count(),
UserInput::Image { .. }
| UserInput::LocalImage { .. }
| UserInput::Audio { .. }
| UserInput::LocalAudio { .. }
| UserInput::Skill { .. }
| UserInput::Mention { .. } => 0,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnStartedNotification {
pub thread_id: String,
pub turn: Turn,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct Usage {
pub input_tokens: i32,
pub cached_input_tokens: i32,
pub output_tokens: i32,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnCompletedNotification {
pub thread_id: String,
pub turn: Turn,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
/// Notification that the turn-level unified diff has changed.
/// Contains the latest aggregated diff across all file changes in the turn.
pub struct TurnDiffUpdatedNotification {
pub thread_id: String,
pub turn_id: String,
pub diff: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnPlanUpdatedNotification {
pub thread_id: String,
pub turn_id: String,
pub explanation: Option<String>,
pub plan: Vec<TurnPlanStep>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct TurnPlanStep {
pub step: String,
pub status: TurnPlanStepStatus,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum TurnPlanStepStatus {
Pending,
InProgress,
Completed,
}
impl From<CorePlanItemArg> for TurnPlanStep {
fn from(value: CorePlanItemArg) -> Self {
Self {
step: value.step,
status: value.status.into(),
}
}
}
impl From<CorePlanStepStatus> for TurnPlanStepStatus {
fn from(value: CorePlanStepStatus) -> Self {
match value {
CorePlanStepStatus::Pending => Self::Pending,
CorePlanStepStatus::InProgress => Self::InProgress,
CorePlanStepStatus::Completed => Self::Completed,
}
}
}

View File

@@ -0,0 +1,175 @@
//! Experimental user-verification APIs for trusted UI clients.
//! Native implementation and registration transport are independent of these contracts.
use crate::JsonSchema;
use crate::RequestId;
use crate::TS;
use serde::Deserialize;
use serde::Serialize;
/// A signature over the exact decoded challenge. The verifier validates and consumes it.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct UserVerificationProof {
pub credential_id: String,
/// Unpadded base64url DER ECDSA signature using P-256 and SHA-256.
pub signature: String,
}
impl std::fmt::Debug for UserVerificationProof {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("UserVerificationProof")
.finish_non_exhaustive()
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum UserVerificationUnavailableReason {
CredentialMissing,
BiometricsUnavailable,
ProviderUnavailable,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum UserVerificationCancellationReason {
UserCancelled,
Interrupted,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum UserVerificationFailureReason {
AuthenticationFailed,
Timeout,
ProviderError,
ServiceError,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum UserVerificationInvalidRequestReason {
InvalidParams,
}
/// Closed error categories; native diagnostic payloads must not cross this boundary.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
#[ts(tag = "type", rename_all = "camelCase", export_to = "v2/")]
pub enum UserVerificationErrorDetails {
InvalidRequest {
reason: UserVerificationInvalidRequestReason,
},
Unavailable {
reason: UserVerificationUnavailableReason,
},
Cancelled {
reason: UserVerificationCancellationReason,
},
Failed {
reason: UserVerificationFailureReason,
},
}
/// The error object inside the normal JSON-RPC envelope.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct UserVerificationRpcError {
#[ts(type = "number")]
pub code: i64,
pub message: String,
pub data: UserVerificationErrorDetails,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct UserVerificationStatusParams {}
/// Local readiness only; this neither prompts nor queries server registration.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct UserVerificationStatusResponse {
pub credential_id: Option<String>,
pub unavailable_reason: Option<UserVerificationUnavailableReason>,
pub unavailable_message: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct UserVerificationEnrollParams {}
/// Public metadata for a created or reused local credential. The caller completes
/// backend registration; this response does not establish server enrollment.
/// Older app-servers omit the metadata fields; callers must check both before registration.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct UserVerificationEnrollResponse {
pub credential_id: String,
// TODO: Make both metadata fields required after the experimental/alpha rollout
// guarantees them on the oldest supported app-server version.
pub algorithm: Option<String>,
/// Unpadded base64url of the SubjectPublicKeyInfo DER encoding.
pub public_key: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct UserVerificationDeleteParams {}
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct UserVerificationDeleteResponse {}
/// Local signing primitive, independent of any pending elicitation.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct UserVerificationVerifyParams {
/// Unpadded base64url encoding of 1–4096 challenge bytes.
pub challenge: String,
/// Display context already approved by the UI; 1–256 UTF-8 bytes.
pub title: String,
/// Additional display context; at most 4096 UTF-8 bytes.
pub description: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct UserVerificationVerifyResponse {
pub proof: UserVerificationProof,
}
/// Cancels a native verification RPC issued on this connection, not an elicitation.
/// Use a fresh request ID for each operation and a distinct ID for this cancellation RPC.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct UserVerificationCancelParams {
pub request_id: RequestId,
}
/// Acknowledges the cancellation signal; native work may still be finishing.
/// Unknown or finished requests are a no-op, and completed effects are not rolled back.
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct UserVerificationCancelResponse {}
#[cfg(test)]
#[path = "user_verification_tests.rs"]
mod tests;

View File

@@ -0,0 +1,73 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn enrollment_response_accepts_older_servers_without_public_metadata() {
for response in [
json!({"credentialId": "credential"}),
json!({"credentialId": "credential", "algorithm": null, "publicKey": null}),
] {
assert_eq!(
serde_json::from_value::<UserVerificationEnrollResponse>(response).unwrap(),
UserVerificationEnrollResponse {
credential_id: "credential".into(),
algorithm: None,
public_key: None,
}
);
}
let response = UserVerificationEnrollResponse {
credential_id: "credential".into(),
algorithm: Some("ecdsaP256Sha256X962".into()),
public_key: Some("public-key".into()),
};
assert_eq!(
serde_json::from_value::<UserVerificationEnrollResponse>(
serde_json::to_value(&response).unwrap()
)
.unwrap(),
response
);
}
#[test]
fn local_readiness_retains_credential_during_biometric_unavailability() {
let status = UserVerificationStatusResponse {
credential_id: Some("credential".into()),
unavailable_reason: Some(UserVerificationUnavailableReason::BiometricsUnavailable),
unavailable_message: Some("Unlock biometrics to continue.".into()),
};
assert_eq!(
serde_json::to_value(&status).unwrap(),
json!({
"credentialId": "credential",
"unavailableReason": "biometricsUnavailable",
"unavailableMessage": "Unlock biometrics to continue."
})
);
assert_eq!(
serde_json::from_value::<UserVerificationStatusResponse>(
serde_json::to_value(&status).unwrap()
)
.unwrap(),
status
);
}
#[test]
fn error_details_reject_cross_category_reasons_and_native_payloads() {
let details = UserVerificationErrorDetails::Cancelled {
reason: UserVerificationCancellationReason::UserCancelled,
};
assert_eq!(
serde_json::to_value(details).unwrap(),
json!({"type": "cancelled", "reason": "userCancelled"})
);
for invalid in [
json!({"type": "failed", "reason": "userCancelled"}),
json!({"type": "unavailable", "reason": "providerUnavailable", "nativeError": {"code": 1}}),
] {
assert!(serde_json::from_value::<UserVerificationErrorDetails>(invalid).is_err());
}
}

View File

@@ -0,0 +1,72 @@
use crate::JsonSchema;
use crate::TS;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct WindowsWorldWritableWarningNotification {
pub sample_paths: Vec<String>,
pub extra_count: usize,
pub failed_scan: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum WindowsSandboxSetupMode {
Elevated,
Unelevated,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub enum WindowsSandboxImplementation {
Elevated,
Unelevated,
Mxc,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum WindowsSandboxReadiness {
Ready,
NotConfigured,
UpdateRequired,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct WindowsSandboxSetupStartParams {
pub mode: WindowsSandboxSetupMode,
#[ts(optional = nullable)]
pub cwd: Option<AbsolutePathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct WindowsSandboxSetupStartResponse {
pub started: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct WindowsSandboxReadinessResponse {
pub status: WindowsSandboxReadiness,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct WindowsSandboxSetupCompletedNotification {
pub mode: WindowsSandboxSetupMode,
pub success: bool,
pub error: Option<String>,
}

View File

@@ -0,0 +1,88 @@
//! We do not do true JSON-RPC 2.0, as we neither send nor expect the
//! "jsonrpc": "2.0" field.
use crate::JsonSchema;
use crate::TS;
use akode_protocol::protocol::W3cTraceContext;
use serde::Deserialize;
use serde::Serialize;
use std::fmt;
pub const JSONRPC_VERSION: &str = "2.0";
#[derive(
Debug, Clone, PartialEq, PartialOrd, Ord, Deserialize, Serialize, Hash, Eq, JsonSchema, TS,
)]
#[serde(untagged)]
pub enum RequestId {
String(String),
#[ts(type = "number")]
Integer(i64),
}
impl fmt::Display for RequestId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::String(value) => f.write_str(value),
Self::Integer(value) => write!(f, "{value}"),
}
}
}
pub type Result = serde_json::Value;
/// Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
#[serde(untagged)]
pub enum JSONRPCMessage {
Request(JSONRPCRequest),
Notification(JSONRPCNotification),
Response(JSONRPCResponse),
Error(JSONRPCError),
}
/// A request that expects a response.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
pub struct JSONRPCRequest {
pub id: RequestId,
pub method: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub params: Option<serde_json::Value>,
/// Optional W3C Trace Context for distributed tracing.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub trace: Option<W3cTraceContext>,
}
/// A notification which does not expect a response.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
pub struct JSONRPCNotification {
pub method: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub params: Option<serde_json::Value>,
}
/// A successful (non-error) response to a request.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
pub struct JSONRPCResponse {
pub id: RequestId,
pub result: Result,
}
/// A response to a request that indicates an error occurred.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
pub struct JSONRPCError {
pub error: JSONRPCErrorError,
pub id: RequestId,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
pub struct JSONRPCErrorError {
pub code: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub data: Option<serde_json::Value>,
pub message: String,
}

View File

@@ -0,0 +1,464 @@
use crate::ClientNotification;
use crate::ClientRequest;
use crate::ServerNotification;
use crate::ServerNotificationEnvelope;
use crate::ServerRequest;
use crate::TS;
use crate::export::GENERATED_TS_HEADER;
use crate::export::filter_experimental_ts_tree;
use crate::export::generate_index_ts_tree;
use crate::export::trim_trailing_line_whitespace;
use crate::precomputed_exports::PrecomputedExports;
use crate::protocol::common::visit_client_response_types;
use crate::protocol::common::visit_server_response_types;
use anyhow::Context;
use anyhow::Result;
use serde_json::Map;
use serde_json::Value;
use std::any::TypeId;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::io::Cursor;
use std::path::Path;
use std::path::PathBuf;
use ts_rs::TypeVisitor;
#[derive(Clone, Copy, Debug, Default)]
pub struct SchemaFixtureOptions {
pub experimental_api: bool,
}
pub(crate) fn write_schema_fixtures_from_env() -> Result<()> {
let schema_root = std::env::var_os("AKODE_APP_SERVER_SCHEMA_ROOT")
.map(PathBuf::from)
.context("AKODE_APP_SERVER_SCHEMA_ROOT must be set")?;
let prettier = std::env::var_os("AKODE_APP_SERVER_SCHEMA_PRETTIER").map(PathBuf::from);
let experimental = std::env::var("AKODE_APP_SERVER_SCHEMA_EXPERIMENTAL")
.context("AKODE_APP_SERVER_SCHEMA_EXPERIMENTAL must be set")?;
let experimental_api = match experimental.as_str() {
"0" => false,
"1" => true,
value => {
anyhow::bail!("AKODE_APP_SERVER_SCHEMA_EXPERIMENTAL must be 0 or 1, got {value:?}")
}
};
write_schema_fixtures_with_options(
&schema_root,
prettier.as_deref(),
SchemaFixtureOptions { experimental_api },
)
}
pub fn read_schema_fixture_tree(schema_root: &Path) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
let typescript_root = schema_root.join("typescript");
let json_root = schema_root.join("json");
let mut all = BTreeMap::new();
for (rel, bytes) in collect_files_recursive(&typescript_root)? {
all.insert(PathBuf::from("typescript").join(rel), bytes);
}
for (rel, bytes) in collect_files_recursive(&json_root)? {
all.insert(PathBuf::from("json").join(rel), bytes);
}
Ok(all)
}
pub fn read_schema_fixture_subtree(
schema_root: &Path,
label: &str,
) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
let subtree_root = schema_root.join(label);
collect_files_recursive(&subtree_root)
.with_context(|| format!("read schema fixture subtree {}", subtree_root.display()))
}
#[doc(hidden)]
pub fn generate_typescript_schema_fixture_subtree_for_tests() -> Result<BTreeMap<PathBuf, Vec<u8>>>
{
let mut files = BTreeMap::new();
let mut seen = HashSet::new();
collect_typescript_fixture_file::<ClientRequest>(&mut files, &mut seen)?;
visit_typescript_fixture_dependencies(&mut files, &mut seen, |visitor| {
visit_client_response_types(visitor);
})?;
collect_typescript_fixture_file::<ClientNotification>(&mut files, &mut seen)?;
collect_typescript_fixture_file::<crate::ModelProviderError>(&mut files, &mut seen)?;
collect_typescript_fixture_file::<ServerRequest>(&mut files, &mut seen)?;
visit_typescript_fixture_dependencies(&mut files, &mut seen, |visitor| {
visit_server_response_types(visitor);
})?;
collect_typescript_fixture_file::<ServerNotification>(&mut files, &mut seen)?;
collect_typescript_fixture_file::<ServerNotificationEnvelope>(&mut files, &mut seen)?;
filter_experimental_ts_tree(&mut files)?;
generate_index_ts_tree(&mut files);
for content in files.values_mut() {
*content = trim_trailing_line_whitespace(content);
}
Ok(files
.into_iter()
.map(|(path, content)| (path, content.into_bytes()))
.collect())
}
/// Regenerates `schema/typescript/`, `schema/json/`, and the stable embedded exports.
///
/// This is intended to be used by tooling (e.g., `just write-app-server-schema`).
/// It deletes any previously generated files so stale artifacts are removed.
pub fn write_schema_fixtures(schema_root: &Path, prettier: Option<&Path>) -> Result<()> {
write_schema_fixtures_with_options(schema_root, prettier, SchemaFixtureOptions::default())
}
/// Regenerates schema fixtures with configurable options.
pub fn write_schema_fixtures_with_options(
schema_root: &Path,
prettier: Option<&Path>,
options: SchemaFixtureOptions,
) -> Result<()> {
if options.experimental_api {
return write_experimental_precomputed_exports(schema_root, prettier);
}
let typescript_out_dir = schema_root.join("typescript");
let json_out_dir = schema_root.join("json");
ensure_empty_dir(&typescript_out_dir)?;
ensure_empty_dir(&json_out_dir)?;
crate::export::generate_ts_with_options(
&typescript_out_dir,
prettier,
crate::export::GenerateTsOptions::default(),
)?;
crate::export::generate_json(&json_out_dir)?;
let internal_dir = tempfile::tempdir().context("create internal schema temp dir")?;
crate::export::generate_internal_json_schema(internal_dir.path())?;
let exports = PrecomputedExports {
typescript: collect_export_files_recursive(&typescript_out_dir)?,
json_schema: collect_export_files_recursive(&json_out_dir)?,
internal_json_schema: collect_export_files_recursive(internal_dir.path())?,
};
write_precomputed_exports(schema_root, "stable", &exports)?;
Ok(())
}
fn write_experimental_precomputed_exports(
schema_root: &Path,
prettier: Option<&Path>,
) -> Result<()> {
let temp_dir = tempfile::tempdir().context("create experimental schema temp dir")?;
let typescript_out_dir = temp_dir.path().join("typescript");
let json_out_dir = temp_dir.path().join("json");
crate::export::generate_ts_with_options(
&typescript_out_dir,
prettier,
crate::export::GenerateTsOptions {
experimental_api: true,
..crate::export::GenerateTsOptions::default()
},
)?;
crate::export::generate_json_with_experimental(&json_out_dir, /*experimental_api*/ true)?;
let exports = PrecomputedExports {
typescript: collect_export_files_recursive(&typescript_out_dir)?,
json_schema: collect_export_files_recursive(&json_out_dir)?,
internal_json_schema: BTreeMap::new(),
};
write_precomputed_exports(schema_root, "experimental", &exports)
}
fn write_precomputed_exports(
schema_root: &Path,
name: &str,
exports: &PrecomputedExports,
) -> Result<()> {
let output_dir = schema_root.join("precomputed");
std::fs::create_dir_all(&output_dir)
.with_context(|| format!("create {}", output_dir.display()))?;
let output_path = output_dir.join(format!("app-server-exports-{name}.json.zst"));
let json = serde_json::to_vec(exports).context("serialize precomputed protocol exports")?;
let compressed = zstd::stream::encode_all(Cursor::new(json), 19)
.context("compress precomputed protocol exports")?;
std::fs::write(&output_path, compressed)
.with_context(|| format!("write {}", output_path.display()))
}
fn ensure_empty_dir(dir: &Path) -> Result<()> {
if dir.exists() {
std::fs::remove_dir_all(dir)
.with_context(|| format!("failed to remove {}", dir.display()))?;
}
std::fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?;
Ok(())
}
fn read_file_bytes(path: &Path) -> Result<Vec<u8>> {
let bytes =
std::fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
if path.extension().is_some_and(|ext| ext == "json") {
let value: Value = serde_json::from_slice(&bytes)
.with_context(|| format!("failed to parse JSON in {}", path.display()))?;
let value = canonicalize_json(&value);
let normalized = serde_json::to_vec_pretty(&value)
.with_context(|| format!("failed to reserialize JSON in {}", path.display()))?;
return Ok(normalized);
}
if path.extension().is_some_and(|ext| ext == "ts") {
// Windows checkouts (and some generators) may produce CRLF; normalize so the
// fixture test is platform-independent.
let text = String::from_utf8(bytes)
.with_context(|| format!("expected UTF-8 TypeScript in {}", path.display()))?;
let text = text.replace("\r\n", "\n").replace('\r', "\n");
// Fixture comparisons care about schema content, not whether the generator
// re-prepended the standard banner to every TypeScript file.
let text = text
.strip_prefix(GENERATED_TS_HEADER)
.unwrap_or(&text)
.to_string();
return Ok(text.into_bytes());
}
Ok(bytes)
}
fn canonicalize_json(value: &Value) -> Value {
match value {
Value::Array(items) => {
// NOTE: We sort some JSON arrays to make schema fixture comparisons stable across
// platforms.
//
// In general, JSON array ordering is significant. However, this code path is used
// only by `schema_fixtures_match_generated` to compare our *vendored* JSON schema
// files against freshly generated output. Some parts of schema generation end up
// with non-deterministic ordering across platforms (often due to map iteration order
// upstream), which can cause Windows CI failures even when the generated schema is
// semantically equivalent.
//
// JSON Schema itself also contains a number of array-valued keywords whose ordering
// does not affect validation semantics (e.g. `required`, `type`, `enum`, `anyOf`,
// `oneOf`, `allOf`). That makes it reasonable to treat many schema-emitted arrays as
// order-insensitive for the purpose of fixture diffs.
//
// To avoid accidentally changing the meaning of arrays where order *could* matter
// (e.g. tuple validation / `prefixItems`-style arrays), we only sort arrays when we
// can derive a stable sort key for *every* element. If we cannot, we preserve the
// original ordering.
let items = items.iter().map(canonicalize_json).collect::<Vec<_>>();
let mut sortable = Vec::with_capacity(items.len());
for item in &items {
let Some(key) = schema_array_item_sort_key(item) else {
return Value::Array(items);
};
let stable = serde_json::to_string(item).unwrap_or_default();
sortable.push((key, stable));
}
let mut items = items.into_iter().zip(sortable).collect::<Vec<_>>();
items.sort_by(
|(_, (key_left, stable_left)), (_, (key_right, stable_right))| match key_left
.cmp(key_right)
{
Ordering::Equal => stable_left.cmp(stable_right),
other => other,
},
);
Value::Array(items.into_iter().map(|(item, _)| item).collect())
}
Value::Object(map) => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_by_key(|(key, _)| *key);
let mut sorted = Map::with_capacity(map.len());
for (key, child) in entries {
sorted.insert(key.clone(), canonicalize_json(child));
}
Value::Object(sorted)
}
_ => value.clone(),
}
}
fn schema_array_item_sort_key(item: &Value) -> Option<String> {
match item {
Value::Null => Some("null".to_string()),
Value::Bool(b) => Some(format!("b:{b}")),
Value::Number(n) => Some(format!("n:{n}")),
Value::String(s) => Some(format!("s:{s}")),
Value::Object(map) => {
if let Some(Value::String(reference)) = map.get("$ref") {
Some(format!("ref:{reference}"))
} else if let Some(Value::String(title)) = map.get("title") {
Some(format!("title:{title}"))
} else {
None
}
}
Value::Array(_) => None,
}
}
fn collect_files_recursive(root: &Path) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
files_recursive(root)?
.into_iter()
.map(|(relative_path, path)| Ok((relative_path, read_file_bytes(&path)?)))
.collect()
}
pub(crate) fn collect_export_files_recursive(root: &Path) -> Result<BTreeMap<String, String>> {
files_recursive(root)?
.into_iter()
.map(|(relative_path, path)| {
let relative_path = relative_path
.components()
.map(|component| component.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
let contents = std::fs::read_to_string(&path)
.with_context(|| format!("read UTF-8 export {}", path.display()))?
.replace("\r\n", "\n");
Ok((relative_path, contents))
})
.collect()
}
fn files_recursive(root: &Path) -> Result<Vec<(PathBuf, PathBuf)>> {
let mut files = Vec::new();
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(&dir)
.with_context(|| format!("failed to read dir {}", dir.display()))?
{
let entry =
entry.with_context(|| format!("failed to read dir entry in {}", dir.display()))?;
let path = entry.path();
// On some platforms, Bazel runfiles are symlinks. `DirEntry::file_type()` does not
// follow symlinks, so use `metadata()` here to treat symlinks as the files/dirs they
// point to.
let metadata = std::fs::metadata(&path)
.with_context(|| format!("failed to stat {}", path.display()))?;
if metadata.is_dir() {
stack.push(path);
continue;
} else if !metadata.is_file() {
continue;
}
let rel = path
.strip_prefix(root)
.with_context(|| {
format!(
"failed to strip prefix {} from {}",
root.display(),
path.display()
)
})?
.to_path_buf();
files.push((rel, path));
}
}
files.sort_by(|(left, _), (right, _)| left.cmp(right));
Ok(files)
}
fn collect_typescript_fixture_file<T: TS + 'static + ?Sized>(
files: &mut BTreeMap<PathBuf, String>,
seen: &mut HashSet<TypeId>,
) -> Result<()> {
let Some(output_path) = T::output_path() else {
return Ok(());
};
if !seen.insert(TypeId::of::<T>()) {
return Ok(());
}
let contents = T::export_to_string().context("export TypeScript fixture content")?;
let output_path = normalize_relative_fixture_path(&output_path);
files.insert(
output_path,
contents.replace("\r\n", "\n").replace('\r', "\n"),
);
let mut visitor = TypeScriptFixtureCollector {
files,
seen,
error: None,
};
T::visit_dependencies(&mut visitor);
if let Some(error) = visitor.error {
return Err(error);
}
Ok(())
}
fn normalize_relative_fixture_path(path: &Path) -> PathBuf {
path.components().collect()
}
fn visit_typescript_fixture_dependencies(
files: &mut BTreeMap<PathBuf, String>,
seen: &mut HashSet<TypeId>,
visit: impl FnOnce(&mut TypeScriptFixtureCollector<'_>),
) -> Result<()> {
let mut visitor = TypeScriptFixtureCollector {
files,
seen,
error: None,
};
visit(&mut visitor);
if let Some(error) = visitor.error {
return Err(error);
}
Ok(())
}
struct TypeScriptFixtureCollector<'a> {
files: &'a mut BTreeMap<PathBuf, String>,
seen: &'a mut HashSet<TypeId>,
error: Option<anyhow::Error>,
}
impl TypeVisitor for TypeScriptFixtureCollector<'_> {
fn visit<T: TS + 'static + ?Sized>(&mut self) {
if self.error.is_some() {
return;
}
self.error = collect_typescript_fixture_file::<T>(self.files, self.seen).err();
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn canonicalize_json_sorts_string_arrays() {
let value = serde_json::json!(["b", "a"]);
let expected = serde_json::json!(["a", "b"]);
assert_eq!(canonicalize_json(&value), expected);
}
#[test]
fn canonicalize_json_sorts_schema_ref_arrays() {
let value = serde_json::json!([
{"$ref": "#/definitions/B"},
{"$ref": "#/definitions/A"}
]);
let expected = serde_json::json!([
{"$ref": "#/definitions/A"},
{"$ref": "#/definitions/B"}
]);
assert_eq!(canonicalize_json(&value), expected);
}
}

View File

@@ -0,0 +1,225 @@
use crate::export::GenerateTsOptions;
use crate::export::generate_internal_json_schema;
use crate::export::generate_json_with_experimental;
use crate::export::generate_ts_with_options;
use crate::precomputed_exports::decode_precomputed_exports;
use crate::schema_fixtures::collect_export_files_recursive;
use crate::schema_fixtures::generate_typescript_schema_fixture_subtree_for_tests;
use crate::schema_fixtures::read_schema_fixture_subtree;
use anyhow::Context;
use anyhow::Result;
use pretty_assertions::assert_eq;
use similar::TextDiff;
use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
#[test]
fn typescript_schema_fixtures_match_generated() -> Result<()> {
let schema_root = schema_root()?;
let fixture_tree = read_tree(&schema_root, "typescript")?;
let generated_tree = generate_typescript_schema_fixture_subtree_for_tests()
.context("generate in-memory typescript schema fixtures")?;
assert_schema_trees_match("typescript", &fixture_tree, &generated_tree)?;
let config_requirements = generated_tree
.get(Path::new("v2/ConfigRequirements.ts"))
.context("generated ConfigRequirements.ts should exist")?;
anyhow::ensure!(
!String::from_utf8_lossy(config_requirements).contains("../PathUri")
|| generated_tree.contains_key(Path::new("PathUri.ts")),
"stable ConfigRequirements.ts imports PathUri but PathUri.ts was not generated"
);
Ok(())
}
#[test]
fn json_schema_fixtures_match_generated() -> Result<()> {
assert_schema_fixtures_match_generated("json", |output_dir| {
generate_json_with_experimental(output_dir, /*experimental_api*/ false)
})
}
#[test]
fn stable_precomputed_exports_match_schema_fixtures() -> Result<()> {
let schema_root = schema_root()?;
let exports = decode_precomputed_exports(/*experimental_api*/ false)?;
assert_eq!(
exports.typescript,
collect_export_files_recursive(&schema_root.join("typescript"))?
);
assert_eq!(
exports.json_schema,
collect_export_files_recursive(&schema_root.join("json"))?
);
let internal_dir = tempfile::tempdir().context("create internal schema temp dir")?;
generate_internal_json_schema(internal_dir.path())?;
assert_json_export_trees_match(
&exports.internal_json_schema,
&collect_export_files_recursive(internal_dir.path())?,
)?;
Ok(())
}
#[test]
fn experimental_precomputed_exports_match_generated() -> Result<()> {
let output_dir = tempfile::tempdir().context("create experimental schema temp dir")?;
let typescript_dir = output_dir.path().join("typescript");
let json_dir = output_dir.path().join("json");
generate_ts_with_options(
&typescript_dir,
/*prettier*/ None,
GenerateTsOptions {
experimental_api: true,
..GenerateTsOptions::default()
},
)?;
generate_json_with_experimental(&json_dir, /*experimental_api*/ true)?;
let exports = decode_precomputed_exports(/*experimental_api*/ true)?;
assert_eq!(
exports.typescript,
collect_export_files_recursive(&typescript_dir)?
);
assert_json_export_trees_match(
&exports.json_schema,
&collect_export_files_recursive(&json_dir)?,
)?;
assert_eq!(exports.internal_json_schema, BTreeMap::new());
Ok(())
}
#[test]
#[ignore = "invoked by `just write-app-server-schema`"]
fn write_schema_fixtures_from_env() -> Result<()> {
crate::schema_fixtures::write_schema_fixtures_from_env()
}
fn assert_schema_fixtures_match_generated(
label: &'static str,
generate: impl FnOnce(&Path) -> Result<()>,
) -> Result<()> {
let schema_root = schema_root()?;
let fixture_tree = read_tree(&schema_root, label)?;
let temp_dir = tempfile::tempdir().context("create temp dir")?;
let generated_root = temp_dir.path().join(label);
generate(&generated_root).with_context(|| {
format!(
"generate {label} schema fixtures into {}",
generated_root.display()
)
})?;
let generated_tree = read_tree(temp_dir.path(), label)?;
assert_schema_trees_match(label, &fixture_tree, &generated_tree)
}
fn assert_json_export_trees_match(
expected: &BTreeMap<String, String>,
actual: &BTreeMap<String, String>,
) -> Result<()> {
assert_eq!(
expected.keys().collect::<Vec<_>>(),
actual.keys().collect::<Vec<_>>()
);
for (path, expected) in expected {
let expected: serde_json::Value = serde_json::from_str(expected)
.with_context(|| format!("parse precomputed JSON export {path}"))?;
let actual: serde_json::Value = serde_json::from_str(&actual[path])
.with_context(|| format!("parse freshly generated JSON export {path}"))?;
assert_eq!(expected, actual, "JSON export differs: {path}");
}
Ok(())
}
fn assert_schema_trees_match(
label: &str,
fixture_tree: &BTreeMap<PathBuf, Vec<u8>>,
generated_tree: &BTreeMap<PathBuf, Vec<u8>>,
) -> Result<()> {
let fixture_paths = fixture_tree
.keys()
.map(|p| p.display().to_string())
.collect::<Vec<_>>();
let generated_paths = generated_tree
.keys()
.map(|p| p.display().to_string())
.collect::<Vec<_>>();
if fixture_paths != generated_paths {
let expected = fixture_paths.join("\n");
let actual = generated_paths.join("\n");
let diff = TextDiff::from_lines(&expected, &actual)
.unified_diff()
.header("fixture", "generated")
.to_string();
panic!(
"Vendored {label} app-server schema fixture file set doesn't match freshly generated output. \
Run `just write-app-server-schema` to overwrite with your changes.\n\n{diff}"
);
}
for (path, expected) in fixture_tree {
let actual = generated_tree
.get(path)
.ok_or_else(|| anyhow::anyhow!("missing generated file: {}", path.display()))?;
if expected == actual {
continue;
}
let expected_str = String::from_utf8_lossy(expected);
let actual_str = String::from_utf8_lossy(actual);
let diff = TextDiff::from_lines(&expected_str, &actual_str)
.unified_diff()
.header("fixture", "generated")
.to_string();
panic!(
"Vendored {label} app-server schema fixture {} differs from generated output. \
Run `just write-app-server-schema` to overwrite with your changes.\n\n{diff}",
path.display()
);
}
Ok(())
}
fn schema_root() -> Result<PathBuf> {
let typescript_index = akode_utils_cargo_bin::find_resource!("schema/typescript/index.ts")
.context("resolve TypeScript schema index.ts")?;
let schema_root = typescript_index
.parent()
.and_then(|p| p.parent())
.context("derive schema root from schema/typescript/index.ts")?
.to_path_buf();
let json_bundle =
akode_utils_cargo_bin::find_resource!("schema/json/akode_app_server_protocol.schemas.json")
.context("resolve JSON schema bundle")?;
let json_root = json_bundle
.parent()
.and_then(|p| p.parent())
.context("derive schema root from schema/json/akode_app_server_protocol.schemas.json")?;
anyhow::ensure!(
schema_root == json_root,
"schema roots disagree: typescript={} json={}",
schema_root.display(),
json_root.display()
);
Ok(schema_root)
}
fn read_tree(root: &Path, label: &str) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
read_schema_fixture_subtree(root, label).with_context(|| {
format!(
"read {label} schema fixture subtree from {}",
root.display()
)
})
}