openbutler-protocol 0.0.2

The wire contract between the OpenButler daemon and its clients: frame encoding, action envelopes, and the shared state types.
Documentation
//! The Node sidecar door: commands (host → sidecar) and events
//! (sidecar → host) over newline-delimited JSON on stdin/stdout.
//!
//! The Rust side owns the agent loop, retries, queueing and cancellation;
//! the sidecar is a stateless model transport — one process, many calls,
//! no conversation state. Unknown event types are ignored and logged by
//! the decoder (forward compatibility); a line that is not JSON, or that
//! exceeds the line cap, is a protocol violation and kills the process.
//! Source decision record: `docs/sidecar-door.md`.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// The door's own protocol version, negotiated at the handshake.
pub const SIDECAR_PROTOCOL_VERSION: u32 = 1;

/// One provider entry in a call. `key` must be on the sidecar's embedded
/// allowlist — an unknown key is refused, never used as a package name.
/// `api_key` travels only over stdin and is never logged or persisted.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SidecarProvider {
    pub key: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
}

/// A tool handed to the SDK as a schema only: there is no `execute`
/// channel in the contract, so the SDK cannot run its own loop — the
/// host receives the call and decides.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SidecarTool {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub parameters: Value,
}

/// What the host asked for. `Call` is an ordinary chat step; `Review` is one
/// schema-constrained decision (the auto-review judge).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SidecarCallKind {
    /// One chat step: text, reasoning, tool calls.
    #[default]
    Call,
    /// One structured decision: the answer arrives as an `object` event.
    Review,
}

impl SidecarCallKind {
    /// Absence on the wire means `call`, so the key is skipped for it.
    fn is_call(&self) -> bool {
        matches!(self, Self::Call)
    }
}

/// One model call. `messages` is the AI SDK message array kept as opaque
/// JSON: the typed extraction lands with the agent-loop slice, and the
/// door's job is a lossless pass-through (providerOptions, reasoning
/// parts and cache marks included).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SidecarCall {
    pub id: String,
    pub provider: SidecarProvider,
    pub model: String,
    pub messages: Value,
    /// The assembled system prompt. Absent on calls that carry none —
    /// the key never appears on the wire then.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,
    #[serde(default)]
    pub tools: Vec<SidecarTool>,
    /// Output ceiling for this request (the compaction engine's summary
    /// budget). Absent on ordinary chat calls.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_output_tokens: Option<u64>,
    /// Request-level provider options (reasoning effort, cache metadata)
    /// the source passes with side requests like compaction. Absent on
    /// ordinary chat calls.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_options: Option<Value>,
    /// The call's flavour. Absent means `call`; the key never appears on that
    /// wire, so an older sidecar keeps reading the same command.
    #[serde(default, skip_serializing_if = "SidecarCallKind::is_call")]
    pub kind: SidecarCallKind,
    /// The JSON Schema a `review` answer must satisfy (the decision shape).
    /// Absent on ordinary calls.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<Value>,
}

/// Host → sidecar commands.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SidecarCommand {
    #[serde(rename = "call")]
    Call(Box<SidecarCall>),
    #[serde(rename = "cancel")]
    Cancel { id: String },
}

/// The sidecar's startup announcement. The host refuses to send calls
/// until this arrives and validates: protocol version match, and the
/// requested provider keys present in the allowlist report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SidecarReady {
    pub protocol_version: u32,
    pub ai_sdk_version: String,
    pub providers: Vec<String>,
}

/// Error classes the host makes policy decisions from. `Other` catches
/// unknown kinds so a newer sidecar never breaks the door.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SidecarErrorKind {
    Auth,
    RateLimit,
    ContextOverflow,
    Network,
    Aborted,
    InvalidRequest,
    #[serde(other)]
    Other,
}

/// Sidecar → host events. Field names are camelCase on the wire; each
/// carries the call id it belongs to.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all_fields = "camelCase")]
pub enum SidecarEvent {
    #[serde(rename = "ready")]
    Ready(SidecarReady),
    #[serde(rename = "text-delta")]
    TextDelta { id: String, delta: String },
    #[serde(rename = "reasoning-delta")]
    ReasoningDelta {
        id: String,
        delta: String,
        /// The provider's thinking signature when it arrives on this part
        /// (Anthropic signature, OpenAI encrypted reasoning) — forwarded
        /// untouched so multi-step turns can echo it back.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        signature: Option<String>,
    },
    #[serde(rename = "tool-call")]
    ToolCall {
        id: String,
        name: String,
        arguments: Value,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        call_id: Option<String>,
    },
    /// The one structured answer a `review` call produces. `finish`
    /// follows it, exactly like a chat step.
    #[serde(rename = "object")]
    Object { id: String, object: Value },
    #[serde(rename = "usage")]
    Usage {
        id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        prompt_tokens: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        completion_tokens: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reasoning_tokens: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        total_tokens: Option<u64>,
        /// The input-token split the accounting row stores (`usage.inputTokenDetails`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        no_cache_tokens: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache_read_tokens: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache_write_tokens: Option<u64>,
        /// The output-text split (`usage.outputTokenDetails.textTokens`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        text_tokens: Option<u64>,
        /// Raw provider usage, where an inline cost may sit
        /// (`usage.raw`, forwarded untouched).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        raw: Option<Value>,
    },
    #[serde(rename = "finish")]
    Finish {
        id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        finish_reason: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        provider_metadata: Option<Value>,
        /// The provider's own response id (`finish-step.response.id`) →
        /// the usage row's `generation_id`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        response_id: Option<String>,
    },
    #[serde(rename = "error")]
    Error {
        id: String,
        kind: SidecarErrorKind,
        retryable: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        status: Option<u16>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        retry_after_ms: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message: Option<String>,
    },
}