gate4agent-types 0.5.18

Pure data contracts for gate4agent backends and shells
Documentation
use crate::{normalize_executable_name, AdapterBinding, AgentId, AgentReadinessSpec};
use serde::{Deserialize, Serialize};

/// Runtime in which an executable is detected or launched.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RuntimePlatform {
    Windows,
    MacOs,
    Linux,
    Wsl,
}

impl RuntimePlatform {
    pub fn current() -> Self {
        if cfg!(target_os = "windows") {
            Self::Windows
        } else if cfg!(target_os = "macos") {
            Self::MacOs
        } else {
            Self::Linux
        }
    }
}

/// CPU architecture used to pick an arch-specific launch row.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HostArch {
    X86_64,
    Aarch64,
}

impl HostArch {
    /// Compile-target CPU, when this crate knows how to launch on it.
    pub fn current() -> Option<Self> {
        if cfg!(target_arch = "x86_64") {
            Some(Self::X86_64)
        } else if cfg!(target_arch = "aarch64") {
            Some(Self::Aarch64)
        } else {
            None
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DetectionSpec {
    pub command: String,
    #[serde(default)]
    pub aliases: Vec<String>,
    #[serde(default)]
    pub required_commands: Vec<String>,
    #[serde(default)]
    pub unsupported_platforms: Vec<RuntimePlatform>,
}

/// One platform's program and fixed args, used instead of the unmapped command.
///
/// `arch` is `None` when every CPU of that OS shares the command. Remote
/// Linux does not consult this row.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PlatformLaunch {
    pub platform: RuntimePlatform,
    #[serde(default)]
    pub arch: Option<HostArch>,
    pub program: String,
    pub fixed_args: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct LaunchSpec {
    /// Executable name or absolute path. It is never a shell command string.
    pub program: String,
    #[serde(default)]
    pub fixed_args: Vec<String>,
    /// Platform rows. Empty means every host uses `program` and `fixed_args`.
    /// An arch-specific row wins over an arch-neutral row for the same OS.
    /// Remote Linux keeps that unmapped pair and ignores this list.
    #[serde(default)]
    pub by_platform: Vec<PlatformLaunch>,
}

impl LaunchSpec {
    /// Program and fixed args for this host.
    ///
    /// Remote Linux keeps the unmapped command. Otherwise an arch-specific
    /// row for `platform` wins, then an arch-neutral row, then the unmapped
    /// command.
    pub fn resolve(
        &self,
        platform: RuntimePlatform,
        arch: Option<HostArch>,
        remote: bool,
    ) -> (&str, &[String]) {
        if remote && platform == RuntimePlatform::Linux {
            return (self.program.as_str(), self.fixed_args.as_slice());
        }
        if let Some(arch) = arch {
            if let Some(row) = self
                .by_platform
                .iter()
                .find(|row| row.platform == platform && row.arch == Some(arch))
            {
                return (row.program.as_str(), row.fixed_args.as_slice());
            }
        }
        if let Some(row) = self
            .by_platform
            .iter()
            .find(|row| row.platform == platform && row.arch.is_none())
        {
            return (row.program.as_str(), row.fixed_args.as_slice());
        }
        (self.program.as_str(), self.fixed_args.as_slice())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ProcessMatcher {
    Exact { name: String },
    Prefix { prefix: String },
}

impl ProcessMatcher {
    pub fn matches(&self, process_or_path: &str, platform: RuntimePlatform) -> bool {
        let process = normalize_executable_name(process_or_path, platform);
        match self {
            Self::Exact { name } => {
                let expected = normalize_executable_name(name, platform);
                process == expected
            }
            Self::Prefix { prefix } => {
                let expected = if platform == RuntimePlatform::Windows {
                    prefix.to_ascii_lowercase()
                } else {
                    prefix.clone()
                };
                process.starts_with(&expected)
            }
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum InitialPromptMode {
    None,
    Positional { option_terminator: bool },
    Flag { flag: String },
    InteractiveFlag { flag: String },
    AgentNativeQuery,
    AfterReady,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum NativeDraftMode {
    Flag { flag: String },
}

/// How a modified Enter is named.
///
/// `CsiU` Shift+Enter is `\x1b[13;2u` and Ctrl+Enter is `\x1b[13;5u`.
/// `prepare_agent_prompt` does not append either chord. A Windows
/// input-record newline of `csi-u` writes the Shift+Enter sequence once
/// per newline.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ModifiedEnterEncoding {
    CsiU,
}

/// How a Windows input-record paste names a newline.
///
/// On Windows, `prepare_agent_prompt` turns each CR, LF, and CRLF into one
/// sequence and does not bracket the body. `AltEnter` is `\x1b\r`. `CsiU`
/// is `\x1b[13;2u`. Other platforms keep the bracketed paste.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WindowsPasteNewline {
    AltEnter,
    CsiU,
}

/// Per-agent PTY submit policy. The shared byte writer reads the flags; it
/// does not branch on agent id.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct PtySubmitContract {
    #[serde(default)]
    pub submit_joins_paste_frame: bool,
    #[serde(default)]
    pub paste_needs_typed_request: bool,
    #[serde(default)]
    pub submit_line_settle_ms_per_line: u64,
    #[serde(default)]
    pub submit_retry_delay_ms: Option<u64>,
    #[serde(default)]
    pub submit_retry_budget_ms: Option<u64>,
    #[serde(default)]
    pub draft_paste_ready_timeout_ms: Option<u64>,
    /// Shift+Enter name. The chord gate is `encode_pty_shortcut`.
    /// `shift_enter_sequence` is the raw literal: `AltEnter` is `\x1b\r`
    /// and `CsiU` is `\x1b[13;2u`, the same bytes as a `csi-u` Windows
    /// paste newline. `prepare_agent_prompt` does not append this chord.
    #[serde(default)]
    pub windows_shift_enter: Option<ModifiedEnterEncoding>,
    /// Ctrl+Enter name. The chord gate is `encode_pty_shortcut`.
    /// `ctrl_enter_sequence` is the raw literal `\x1b[13;5u`.
    /// `prepare_agent_prompt` does not send this chord.
    #[serde(default)]
    pub ctrl_enter: Option<ModifiedEnterEncoding>,
    /// Windows input-record newline. On Windows the paste writer emits it
    /// and does not wrap bracketed paste. Other platforms stay bracketed.
    #[serde(default)]
    pub windows_paste_newline: Option<WindowsPasteNewline>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PromptSpec {
    pub initial: InitialPromptMode,
    #[serde(default)]
    pub native_draft: Option<NativeDraftMode>,
    #[serde(default)]
    pub pty_submit: PtySubmitContract,
    #[serde(default)]
    pub prefill_env: Option<String>,
    #[serde(default)]
    pub vendor_draft_signal: Option<String>,
    #[serde(default)]
    pub vendor_submit_signal: Option<String>,
}

impl Default for PromptSpec {
    fn default() -> Self {
        Self {
            initial: InitialPromptMode::None,
            native_draft: None,
            pty_submit: PtySubmitContract::default(),
            prefill_env: None,
            vendor_draft_signal: None,
            vendor_submit_signal: None,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AgentCommandMode {
    SlashLine,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentCapabilities {
    #[serde(default)]
    pub agent_commands: Option<AgentCommandMode>,
    #[serde(default)]
    pub transports: AgentTransportCapabilities,
    #[serde(default)]
    pub adapters: AgentAdapterCapabilities,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentAdapterCapabilities {
    /// Structured observation emitted beside an interactive PTY. This is an
    /// adapter binding only and does not declare Pipe as a launch transport.
    #[serde(default)]
    pub pty_sidecar: Option<AdapterBinding>,
    #[serde(default)]
    pub hook: Option<AdapterBinding>,
    /// Explicit host-level install/status/remove support for provider Hook
    /// configuration. This authority is separate from raw Hook normalization.
    #[serde(default)]
    pub managed_hook: Option<AdapterBinding>,
    /// Pure provider-owned non-interactive invocation planning. Native process
    /// ownership remains in a dedicated shell even when delivered as Pipe.
    #[serde(default)]
    pub one_shot: Option<AdapterBinding>,
    #[serde(default)]
    pub history: Option<AdapterBinding>,
    #[serde(default)]
    pub resume: Option<AdapterBinding>,
    #[serde(default)]
    pub session_options: Option<AdapterBinding>,
    #[serde(default)]
    pub capability_probe: Option<AdapterBinding>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PipePromptDelivery {
    None,
    StdinClose,
    Positional,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PipeProtocol {
    #[default]
    SemanticNdjson,
    /// Provider-owned structured JSONL emitted by a headless CLI invocation.
    /// Unlike `SemanticNdjson`, this path may expose a provider session
    /// identity and be resumed by a later child process.
    StructuredJsonl,
    OneShotText,
}

/// Optional catalog override used by controlled fixtures and providers whose
/// headless executable differs from their interactive PTY executable.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PipeTransportSpec {
    pub adapter: AdapterBinding,
    #[serde(default)]
    pub protocol: PipeProtocol,
    #[serde(default)]
    pub launch_override: Option<LaunchSpec>,
    #[serde(default = "default_pipe_prompt_delivery")]
    pub prompt_delivery: PipePromptDelivery,
}

fn default_pipe_prompt_delivery() -> PipePromptDelivery {
    PipePromptDelivery::None
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AcpTransportSpec {
    pub adapter: AdapterBinding,
    #[serde(default)]
    pub launch_override: Option<LaunchSpec>,
    #[serde(default)]
    pub env: Vec<(String, String)>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentTransportCapabilities {
    #[serde(default = "default_true")]
    pub pty: bool,
    #[serde(default)]
    pub pty_adapter: Option<AdapterBinding>,
    #[serde(default)]
    pub pipe: Option<PipeTransportSpec>,
    #[serde(default)]
    pub acp: Option<AcpTransportSpec>,
}

impl Default for AgentTransportCapabilities {
    fn default() -> Self {
        Self {
            pty: true,
            pty_adapter: None,
            pipe: None,
            acp: None,
        }
    }
}

fn default_true() -> bool {
    true
}

/// Provenance state for a built-in launch specification.
///
/// `Reference` means the shape still requires verification against a pinned
/// vendor CLI before a product presents it as fully supported.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SpecVerification {
    Gate4AgentVerified,
    Reference,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AgentSpec {
    pub id: AgentId,
    /// Revision of the launch/detection contract, not the installed CLI version.
    pub revision: String,
    pub display_name: String,
    pub detection: DetectionSpec,
    pub launch: LaunchSpec,
    pub expected_processes: Vec<ProcessMatcher>,
    pub prompt: PromptSpec,
    pub readiness: AgentReadinessSpec,
    #[serde(default)]
    pub capabilities: AgentCapabilities,
    pub verification: SpecVerification,
}

impl AgentSpec {
    pub fn supports_platform(&self, platform: RuntimePlatform) -> bool {
        !self.detection.unsupported_platforms.contains(&platform)
    }
}