Skip to main content

gate4agent_types/
spec.rs

1use crate::{normalize_executable_name, AdapterBinding, AgentId, AgentReadinessSpec};
2use serde::{Deserialize, Serialize};
3
4/// Runtime in which an executable is detected or launched.
5#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
6#[serde(rename_all = "kebab-case")]
7pub enum RuntimePlatform {
8    Windows,
9    MacOs,
10    Linux,
11    Wsl,
12}
13
14impl RuntimePlatform {
15    pub fn current() -> Self {
16        if cfg!(target_os = "windows") {
17            Self::Windows
18        } else if cfg!(target_os = "macos") {
19            Self::MacOs
20        } else {
21            Self::Linux
22        }
23    }
24}
25
26/// CPU architecture used to pick an arch-specific launch row.
27#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
28#[serde(rename_all = "kebab-case")]
29pub enum HostArch {
30    X86_64,
31    Aarch64,
32}
33
34impl HostArch {
35    /// Compile-target CPU, when this crate knows how to launch on it.
36    pub fn current() -> Option<Self> {
37        if cfg!(target_arch = "x86_64") {
38            Some(Self::X86_64)
39        } else if cfg!(target_arch = "aarch64") {
40            Some(Self::Aarch64)
41        } else {
42            None
43        }
44    }
45}
46
47#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
48pub struct DetectionSpec {
49    pub command: String,
50    #[serde(default)]
51    pub aliases: Vec<String>,
52    #[serde(default)]
53    pub required_commands: Vec<String>,
54    #[serde(default)]
55    pub unsupported_platforms: Vec<RuntimePlatform>,
56}
57
58/// One platform's program and fixed args, used instead of the unmapped command.
59///
60/// `arch` is `None` when every CPU of that OS shares the command. Remote
61/// Linux does not consult this row.
62#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
63pub struct PlatformLaunch {
64    pub platform: RuntimePlatform,
65    #[serde(default)]
66    pub arch: Option<HostArch>,
67    pub program: String,
68    pub fixed_args: Vec<String>,
69}
70
71#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
72pub struct LaunchSpec {
73    /// Executable name or absolute path. It is never a shell command string.
74    pub program: String,
75    #[serde(default)]
76    pub fixed_args: Vec<String>,
77    /// Platform rows. Empty means every host uses `program` and `fixed_args`.
78    /// An arch-specific row wins over an arch-neutral row for the same OS.
79    /// Remote Linux keeps that unmapped pair and ignores this list.
80    #[serde(default)]
81    pub by_platform: Vec<PlatformLaunch>,
82}
83
84impl LaunchSpec {
85    /// Program and fixed args for this host.
86    ///
87    /// Remote Linux keeps the unmapped command. Otherwise an arch-specific
88    /// row for `platform` wins, then an arch-neutral row, then the unmapped
89    /// command.
90    pub fn resolve(
91        &self,
92        platform: RuntimePlatform,
93        arch: Option<HostArch>,
94        remote: bool,
95    ) -> (&str, &[String]) {
96        if remote && platform == RuntimePlatform::Linux {
97            return (self.program.as_str(), self.fixed_args.as_slice());
98        }
99        if let Some(arch) = arch {
100            if let Some(row) = self
101                .by_platform
102                .iter()
103                .find(|row| row.platform == platform && row.arch == Some(arch))
104            {
105                return (row.program.as_str(), row.fixed_args.as_slice());
106            }
107        }
108        if let Some(row) = self
109            .by_platform
110            .iter()
111            .find(|row| row.platform == platform && row.arch.is_none())
112        {
113            return (row.program.as_str(), row.fixed_args.as_slice());
114        }
115        (self.program.as_str(), self.fixed_args.as_slice())
116    }
117}
118
119#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
120#[serde(tag = "kind", rename_all = "kebab-case")]
121pub enum ProcessMatcher {
122    Exact { name: String },
123    Prefix { prefix: String },
124}
125
126impl ProcessMatcher {
127    pub fn matches(&self, process_or_path: &str, platform: RuntimePlatform) -> bool {
128        let process = normalize_executable_name(process_or_path, platform);
129        match self {
130            Self::Exact { name } => {
131                let expected = normalize_executable_name(name, platform);
132                process == expected
133            }
134            Self::Prefix { prefix } => {
135                let expected = if platform == RuntimePlatform::Windows {
136                    prefix.to_ascii_lowercase()
137                } else {
138                    prefix.clone()
139                };
140                process.starts_with(&expected)
141            }
142        }
143    }
144}
145
146#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
147#[serde(tag = "kind", rename_all = "kebab-case")]
148pub enum InitialPromptMode {
149    None,
150    Positional { option_terminator: bool },
151    Flag { flag: String },
152    InteractiveFlag { flag: String },
153    AgentNativeQuery,
154    AfterReady,
155}
156
157#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
158#[serde(tag = "kind", rename_all = "kebab-case")]
159pub enum NativeDraftMode {
160    Flag { flag: String },
161}
162
163/// How a modified Enter is named.
164///
165/// `CsiU` Shift+Enter is `\x1b[13;2u` and Ctrl+Enter is `\x1b[13;5u`.
166/// `prepare_agent_prompt` does not append either chord. A Windows
167/// input-record newline of `csi-u` writes the Shift+Enter sequence once
168/// per newline.
169#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
170#[serde(rename_all = "kebab-case")]
171pub enum ModifiedEnterEncoding {
172    CsiU,
173}
174
175/// How a Windows input-record paste names a newline.
176///
177/// On Windows, `prepare_agent_prompt` turns each CR, LF, and CRLF into one
178/// sequence and does not bracket the body. `AltEnter` is `\x1b\r`. `CsiU`
179/// is `\x1b[13;2u`. Other platforms keep the bracketed paste.
180#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
181#[serde(rename_all = "kebab-case")]
182pub enum WindowsPasteNewline {
183    AltEnter,
184    CsiU,
185}
186
187/// Per-agent PTY submit policy. The shared byte writer reads the flags; it
188/// does not branch on agent id.
189#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
190pub struct PtySubmitContract {
191    #[serde(default)]
192    pub submit_joins_paste_frame: bool,
193    #[serde(default)]
194    pub paste_needs_typed_request: bool,
195    #[serde(default)]
196    pub submit_line_settle_ms_per_line: u64,
197    #[serde(default)]
198    pub submit_retry_delay_ms: Option<u64>,
199    #[serde(default)]
200    pub submit_retry_budget_ms: Option<u64>,
201    #[serde(default)]
202    pub draft_paste_ready_timeout_ms: Option<u64>,
203    /// Shift+Enter name. The chord gate is `encode_pty_shortcut`.
204    /// `shift_enter_sequence` is the raw literal: `AltEnter` is `\x1b\r`
205    /// and `CsiU` is `\x1b[13;2u`, the same bytes as a `csi-u` Windows
206    /// paste newline. `prepare_agent_prompt` does not append this chord.
207    #[serde(default)]
208    pub windows_shift_enter: Option<ModifiedEnterEncoding>,
209    /// Ctrl+Enter name. The chord gate is `encode_pty_shortcut`.
210    /// `ctrl_enter_sequence` is the raw literal `\x1b[13;5u`.
211    /// `prepare_agent_prompt` does not send this chord.
212    #[serde(default)]
213    pub ctrl_enter: Option<ModifiedEnterEncoding>,
214    /// Windows input-record newline. On Windows the paste writer emits it
215    /// and does not wrap bracketed paste. Other platforms stay bracketed.
216    #[serde(default)]
217    pub windows_paste_newline: Option<WindowsPasteNewline>,
218}
219
220#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
221pub struct PromptSpec {
222    pub initial: InitialPromptMode,
223    #[serde(default)]
224    pub native_draft: Option<NativeDraftMode>,
225    #[serde(default)]
226    pub pty_submit: PtySubmitContract,
227    #[serde(default)]
228    pub prefill_env: Option<String>,
229    #[serde(default)]
230    pub vendor_draft_signal: Option<String>,
231    #[serde(default)]
232    pub vendor_submit_signal: Option<String>,
233}
234
235impl Default for PromptSpec {
236    fn default() -> Self {
237        Self {
238            initial: InitialPromptMode::None,
239            native_draft: None,
240            pty_submit: PtySubmitContract::default(),
241            prefill_env: None,
242            vendor_draft_signal: None,
243            vendor_submit_signal: None,
244        }
245    }
246}
247
248#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
249#[serde(rename_all = "kebab-case")]
250pub enum AgentCommandMode {
251    SlashLine,
252}
253
254#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
255pub struct AgentCapabilities {
256    #[serde(default)]
257    pub agent_commands: Option<AgentCommandMode>,
258    #[serde(default)]
259    pub transports: AgentTransportCapabilities,
260    #[serde(default)]
261    pub adapters: AgentAdapterCapabilities,
262}
263
264#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
265pub struct AgentAdapterCapabilities {
266    /// Structured observation emitted beside an interactive PTY. This is an
267    /// adapter binding only and does not declare Pipe as a launch transport.
268    #[serde(default)]
269    pub pty_sidecar: Option<AdapterBinding>,
270    #[serde(default)]
271    pub hook: Option<AdapterBinding>,
272    /// Explicit host-level install/status/remove support for provider Hook
273    /// configuration. This authority is separate from raw Hook normalization.
274    #[serde(default)]
275    pub managed_hook: Option<AdapterBinding>,
276    /// Pure provider-owned non-interactive invocation planning. Native process
277    /// ownership remains in a dedicated shell even when delivered as Pipe.
278    #[serde(default)]
279    pub one_shot: Option<AdapterBinding>,
280    #[serde(default)]
281    pub history: Option<AdapterBinding>,
282    #[serde(default)]
283    pub resume: Option<AdapterBinding>,
284    #[serde(default)]
285    pub session_options: Option<AdapterBinding>,
286    #[serde(default)]
287    pub capability_probe: Option<AdapterBinding>,
288}
289
290#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
291#[serde(rename_all = "kebab-case")]
292pub enum PipePromptDelivery {
293    None,
294    StdinClose,
295    Positional,
296}
297
298#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
299#[serde(rename_all = "kebab-case")]
300pub enum PipeProtocol {
301    #[default]
302    SemanticNdjson,
303    /// Provider-owned structured JSONL emitted by a headless CLI invocation.
304    /// Unlike `SemanticNdjson`, this path may expose a provider session
305    /// identity and be resumed by a later child process.
306    StructuredJsonl,
307    OneShotText,
308}
309
310/// Optional catalog override used by controlled fixtures and providers whose
311/// headless executable differs from their interactive PTY executable.
312#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
313pub struct PipeTransportSpec {
314    pub adapter: AdapterBinding,
315    #[serde(default)]
316    pub protocol: PipeProtocol,
317    #[serde(default)]
318    pub launch_override: Option<LaunchSpec>,
319    #[serde(default = "default_pipe_prompt_delivery")]
320    pub prompt_delivery: PipePromptDelivery,
321}
322
323fn default_pipe_prompt_delivery() -> PipePromptDelivery {
324    PipePromptDelivery::None
325}
326
327#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
328pub struct AcpTransportSpec {
329    pub adapter: AdapterBinding,
330    #[serde(default)]
331    pub launch_override: Option<LaunchSpec>,
332    #[serde(default)]
333    pub env: Vec<(String, String)>,
334}
335
336#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
337pub struct AgentTransportCapabilities {
338    #[serde(default = "default_true")]
339    pub pty: bool,
340    #[serde(default)]
341    pub pty_adapter: Option<AdapterBinding>,
342    #[serde(default)]
343    pub pipe: Option<PipeTransportSpec>,
344    #[serde(default)]
345    pub acp: Option<AcpTransportSpec>,
346}
347
348impl Default for AgentTransportCapabilities {
349    fn default() -> Self {
350        Self {
351            pty: true,
352            pty_adapter: None,
353            pipe: None,
354            acp: None,
355        }
356    }
357}
358
359fn default_true() -> bool {
360    true
361}
362
363/// Provenance state for a built-in launch specification.
364///
365/// `Reference` means the shape still requires verification against a pinned
366/// vendor CLI before a product presents it as fully supported.
367#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
368#[serde(rename_all = "kebab-case")]
369pub enum SpecVerification {
370    Gate4AgentVerified,
371    Reference,
372}
373
374#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
375pub struct AgentSpec {
376    pub id: AgentId,
377    /// Revision of the launch/detection contract, not the installed CLI version.
378    pub revision: String,
379    pub display_name: String,
380    pub detection: DetectionSpec,
381    pub launch: LaunchSpec,
382    pub expected_processes: Vec<ProcessMatcher>,
383    pub prompt: PromptSpec,
384    pub readiness: AgentReadinessSpec,
385    #[serde(default)]
386    pub capabilities: AgentCapabilities,
387    pub verification: SpecVerification,
388}
389
390impl AgentSpec {
391    pub fn supports_platform(&self, platform: RuntimePlatform) -> bool {
392        !self.detection.unsupported_platforms.contains(&platform)
393    }
394}