Skip to main content

ai6_agent_acp/
lib.rs

1//! The `acp` AgentHandler: any Agent Client Protocol agent runs as an Agent's handler, with
2//! AI6's environment, accounts and green-ink gate.
3
4#![doc = include_str!("../README.md")]
5#![forbid(unsafe_code)]
6
7ai6::guatiao::providers!(AcpHandler);
8
9use agent_client_protocol::schema::v1::{
10    HttpHeader, McpServer, McpServerHttp, McpServerStdio, SessionConfigKind, SessionConfigOption,
11    SessionConfigOptionCategory, SessionConfigSelectOption, SessionConfigSelectOptions,
12    SessionModeState,
13};
14use std::collections::BTreeMap;
15use std::process::{Command, Stdio};
16use std::sync::Arc;
17use std::time::Duration;
18
19use ai6::directorates::q::terminal::{AgentTerminal, ExitInfo, STREAM_COLS, Spec, TerminalRun};
20use ai6::directorates::section_00::acp::{
21    AcpOptions, AcpRun, DEFAULT_MAX_TOOL_KINDS, DEFAULT_TEXT_FLUSH_BYTES, Elicitor, Exchange,
22    GateDecider, GateElicitor, THEATER_SERVED_ENV, TerminalIo, UNBOUNDED_LINE_BYTES, UNBOUNDED_MS,
23};
24use ai6::directorates::section_00::agent::{
25    AgentHandler, AgentResume, AgentStart, AssistantMode, clearance_runs_commands,
26};
27use ai6::directorates::section_00::gate::{CABLE_TOKEN_ENV, CABLE_URL_ENV};
28use ai6::directorates::section_00::ledger_seed::{SeedRequest, Seeding, new_session_id, seed};
29use ai6::directorates::section_00::loadout::{LoadoutSupport, RunLoadout};
30use ai6::guatiao::library::{Object, ProviderError};
31use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
32use ai6::{
33    AgentSession, Answer, ChoiceInfo, ConfigInfo, HarnessStdio, ModelInfo, SessionInfo,
34    SessionList, StartOptions,
35};
36use coqui_acp::DescribeLimits;
37use coqui_acp::lines::{Diagnostics, over_io};
38use serde_json::{Map, Value};
39
40/// What an `acp` handler is configured with, in the `station` record's `[providers.acp]` and
41/// an Agent's `handler_settings`. Unknown keys are refused.
42#[derive(Debug, Clone, ToValue, FromValue, Schema)]
43#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
44pub struct AcpSettings {
45    /// The program that speaks ACP on its standard input and output; an Agent sets it, and
46    /// without one the handler starts no Run.
47    #[schema(section = "agent")]
48    pub command: Option<String>,
49    /// Its arguments.
50    #[schema(section = "agent")]
51    #[map(default)]
52    pub args: Vec<String>,
53    /// Environment added under the Run's own (the Run wins).
54    #[schema(section = "agent")]
55    #[map(default)]
56    pub env: BTreeMap<String, String>,
57    /// A table passed beside AI6's launch data as `session/new._meta` (an adapter's options).
58    #[schema(section = "agent")]
59    #[map(with = ::ai6::guatiao_serde::adapt::object, default)]
60    // typed-boundary: free-form an adapter's own `session/new._meta` keys, sent on unchanged
61    pub meta: Map<String, Value>,
62    /// The config option id for the model; default: the option of category `model`, else `model`.
63    #[schema(section = "agent")]
64    pub model_option: Option<String>,
65    /// The config option id for the effort; default: the option of category `thought_level`,
66    /// else `effort`.
67    #[schema(section = "agent")]
68    pub effort_option: Option<String>,
69    /// The ACP version spoken; only `v1`.
70    #[schema(section = "agent")]
71    #[map(default = String::from("v1"))]
72    pub protocol: String,
73    /// How long `initialize` may take, in milliseconds.
74    #[schema(section = "agent")]
75    #[map(default = 20_000)]
76    pub initialize_timeout_ms: u64,
77    /// How long a request other than a prompt may take.
78    #[schema(section = "agent")]
79    #[map(default = 30_000)]
80    pub request_timeout_ms: u64,
81    /// How long the first prompt of a façade may take to start.
82    #[schema(section = "agent")]
83    #[map(default = 60_000)]
84    pub start_timeout_ms: u64,
85    /// How long close waits for the agent before its process is ended.
86    #[schema(section = "agent")]
87    #[map(default = 2_000)]
88    pub close_grace_ms: u64,
89    /// How long, in milliseconds, ending a Run that was not closed waits for the agent to take its
90    /// `session/cancel` before its process is ended.
91    #[schema(section = "agent")]
92    #[map(default = 5_000)]
93    pub abort_wait_ms: u64,
94    /// How many of the agent's last non-protocol output lines are kept to explain its death.
95    #[schema(section = "agent")]
96    #[map(default = 20)]
97    pub diagnostic_lines: usize,
98    /// How long, in milliseconds, the report of a lost agent waits for its exit status.
99    #[schema(section = "agent")]
100    #[map(default = 1_000)]
101    pub exit_wait_ms: i64,
102    /// How often, in milliseconds, a silent agent's output is checked for a stop request.
103    #[schema(section = "agent")]
104    #[map(default = 200)]
105    pub poll_ms: i64,
106    /// Starts a `desk` Run with whatever tools the agent has: AI6 does not choose an ACP
107    /// agent's tools, so it cannot keep commands from one, and without this the Run is
108    /// refused. Reported as a weakening.
109    #[schema(section = "agent")]
110    #[map(default)]
111    pub unconfined_desk: bool,
112    /// Says the agent does its file and shell work through the client's `fs/*` and `terminal/*`
113    /// requests when the client offers them, and never itself. On a remote Theater the Station
114    /// answers those requests from the Theater, so a Run there starts only with this set: AI6 cannot
115    /// tell such an agent from one that works on the Station's own machine, and without this the
116    /// Run is refused. Reported as a weakening.
117    #[schema(section = "agent")]
118    #[map(default)]
119    pub client_tools: bool,
120    /// What marks a failed turn as a provider's usage or rate limit, found in its error without
121    /// regard to case: such a Run stops as limited rather than failed, so its route or account
122    /// is passed over until the limit is likely over.
123    #[schema(section = "agent")]
124    #[map(default = limit_phrases())]
125    pub limit_phrases: Vec<String>,
126    /// UTF-8 bytes of agent text gathered before they are delivered mid-message.
127    #[schema(section = "agent")]
128    #[map(default = DEFAULT_TEXT_FLUSH_BYTES)]
129    pub text_flush_bytes: usize,
130    /// The tool calls whose kind is kept, by which a later message about one that does not say
131    /// its kind is judged; past it the oldest is forgotten, and such a message is of unknown kind.
132    #[schema(section = "agent")]
133    #[map(default = DEFAULT_MAX_TOOL_KINDS)]
134    pub max_tool_kinds: usize,
135    /// What asking the agent what a Run can start with keeps of its answer: options.
136    #[schema(section = "agent")]
137    #[map(default = DescribeLimits::new().options)]
138    pub describe_options: usize,
139    /// Values kept of each option.
140    #[schema(section = "agent")]
141    #[map(default = DescribeLimits::new().values)]
142    pub describe_values: usize,
143    /// Modes kept.
144    #[schema(section = "agent")]
145    #[map(default = DescribeLimits::new().modes)]
146    pub describe_modes: usize,
147    /// Runs kept of the agent's list, across its pages.
148    #[schema(section = "agent")]
149    #[map(default = DescribeLimits::new().sessions)]
150    pub describe_runs: usize,
151    /// UTF-8 bytes past which an identifier is dropped and other text cut.
152    #[schema(section = "agent")]
153    #[map(default = DescribeLimits::new().text)]
154    pub describe_text_bytes: usize,
155    /// Pages of the agent's run list asked for.
156    #[schema(section = "agent")]
157    #[map(default = DescribeLimits::new().pages)]
158    pub describe_pages: usize,
159}
160
161impl AcpSettings {
162    /// The program to run; empty until an Agent sets one.
163    fn command(&self) -> &str {
164        self.command.as_deref().unwrap_or_default()
165    }
166}
167
168/// The words every handler reads a limit by, with the Grok CLI's own for running out of credits
169/// (`402 Payment Required` with `personal-team-blocked:spending-limit`) and its free quota
170/// (`subscription:free-usage-exhausted`).
171fn limit_phrases() -> Vec<String> {
172    ai6::DEFAULT_LIMIT_PHRASES
173        .iter()
174        .copied()
175        .chain([
176            "usage-exhausted",
177            "spending-limit",
178            "run out of credits",
179            "402 payment required",
180        ])
181        .map(str::to_owned)
182        .collect()
183}
184
185/// Runs an ACP agent for each Run.
186#[derive(Provider)]
187#[provider(
188    AgentHandler,
189    id = "acp",
190    name = "Agent Client Protocol agent",
191    crate = ::ai6::guatiao,
192    config = AcpSettings
193)]
194pub struct AcpHandler {
195    settings: Option<AcpSettings>,
196}
197
198fn refuse(message: impl std::fmt::Display) -> ProviderError {
199    ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, &message.to_string())
200}
201
202impl TryFrom<AcpSettings> for AcpHandler {
203    type Error = ProviderError;
204
205    fn try_from(settings: AcpSettings) -> Result<Self, Self::Error> {
206        let Some(command) = &settings.command else {
207            if !settings.args.is_empty()
208                || !settings.env.is_empty()
209                || !settings.meta.is_empty()
210                || settings.unconfined_desk
211                || settings.client_tools
212            {
213                return Err(refuse("acp handler settings: `command` is required"));
214            }
215            return Ok(Self { settings: None });
216        };
217        if command.trim().is_empty() {
218            return Err(refuse("acp handler settings: `command` is empty"));
219        }
220        if settings.protocol != "v1" {
221            return Err(refuse(format!(
222                "acp handler settings: protocol {:?} is not supported; only \"v1\"",
223                settings.protocol
224            )));
225        }
226        Ok(Self {
227            settings: Some(settings),
228        })
229    }
230}
231
232impl AcpHandler {
233    fn settings(&self) -> Result<&AcpSettings, ProviderError> {
234        self.settings.as_ref().ok_or_else(|| {
235            refuse("the acp handler needs `handler_settings` with a `command` on its Agent")
236        })
237    }
238}
239
240/// The lines the agent wrote outside the protocol, kept to explain its death.
241fn last_words(diagnostics: &Diagnostics) -> String {
242    diagnostics
243        .lock()
244        .map(|lines| lines.iter().cloned().collect::<Vec<_>>().join(" | "))
245        .unwrap_or_default()
246}
247
248/// What became of an agent whose connection ended: how its process ended and what it last wrote.
249fn lost_agent(
250    process: &Object<dyn TerminalRun>,
251    diagnostics: &Diagnostics,
252    exit_wait_ms: i64,
253) -> Option<String> {
254    let how = process
255        .exit_status(exit_wait_ms)
256        .ok()
257        .and_then(|status| ExitInfo::from_value(&status).ok())
258        .filter(|exit| !exit.running)
259        .map(|exit| match (exit.code, exit.signal) {
260            (Some(code), _) => format!("it exited with code {code}"),
261            (None, Some(signal)) => format!("it was ended by signal {signal}"),
262            (None, None) => "it exited".to_owned(),
263        });
264    let said = last_words(diagnostics);
265    match (how, said.is_empty()) {
266        (None, true) => None,
267        (Some(how), true) => Some(how),
268        (None, false) => Some(format!("it last wrote: {said}")),
269        (Some(how), false) => Some(format!("{how}; it last wrote: {said}")),
270    }
271}
272
273/// One HTTP MCP server entry in ACP's form.
274fn http_server(name: &str, url: &str, token: &str) -> McpServer {
275    McpServer::Http(McpServerHttp::new(name, url).headers(vec![HttpHeader::new(
276        "Authorization",
277        format!("Bearer {token}"),
278    )]))
279}
280
281/// The MCP servers a Run's environment names: the Cable tools and an assistant's own.
282fn mcp_servers(
283    environment: &BTreeMap<String, String>,
284    assistant: Option<&AssistantMode>,
285    loadout: &RunLoadout,
286    working_directory: &str,
287) -> Result<Vec<McpServer>, ProviderError> {
288    if environment.contains_key("AI6_THEATER_MCP_URL") {
289        return Err(refuse(
290            "a Theater's tools replace the agent's own shell and file tools, which an ACP agent cannot be made to do: \
291             it works there through the client's fs and terminal requests (`client_tools`)",
292        ));
293    }
294    let mut servers = Vec::new();
295    if let (Some(url), Some(token)) = (
296        environment.get(CABLE_URL_ENV),
297        environment.get(CABLE_TOKEN_ENV),
298    ) {
299        servers.push(http_server("ai6-cables", url, token));
300    }
301    for server in assistant.iter().flat_map(|mode| &mode.mcp_servers) {
302        if let (Some(url), Some(token)) = (
303            environment.get(&format!("{}_URL", server.env_prefix)),
304            environment.get(&format!("{}_TOKEN", server.env_prefix)),
305        ) {
306            servers.push(http_server(&server.name, url, token));
307        }
308    }
309    for server in &loadout.mcp_servers {
310        let command = server.command_in(working_directory);
311        servers.push(McpServer::Stdio(
312            McpServerStdio::new(server.name.clone(), &command[0]).args(command[1..].to_vec()),
313        ));
314    }
315    Ok(servers)
316}
317
318/// The text before the first prompt: ACP v1 has no system prompt, so the Agent's context and
319/// the limits of a restricted Run go in front of the task.
320fn briefing(context: &[String], restricted: bool, prompt: &str) -> String {
321    let mut parts: Vec<String> = context.to_vec();
322    if restricted {
323        parts.push(
324            "This is a read-only Run: answer from what you are given. Do not edit, delete or move files, and do not run commands."
325                .to_owned(),
326        );
327    }
328    parts.push(prompt.to_owned());
329    parts.retain(|part| !part.trim().is_empty());
330    parts.join("\n\n")
331}
332
333struct Launch<'a> {
334    environment: &'a BTreeMap<String, String>,
335    working_directory: &'a str,
336    model: Option<&'a String>,
337    effort: Option<&'a String>,
338    restricted: bool,
339    assistant: Option<&'a AssistantMode>,
340    /// The Run is a Mission's at a clearance that may not run commands.
341    desk: bool,
342    /// What the Mission's loadout hands the agent.
343    loadout: &'a RunLoadout,
344    prompt: Option<String>,
345    resume: Option<String>,
346}
347
348impl AcpHandler {
349    fn run(
350        &self,
351        launch: Launch<'_>,
352        terminal: Object<dyn AgentTerminal>,
353    ) -> Result<Object<dyn AgentSession>, ProviderError> {
354        let settings = self.settings()?;
355        if !launch.loadout.is_empty() {
356            if launch.restricted || launch.desk {
357                return Err(ProviderError::new(
358                    Status::GUATIAO_ERR_UNSUPPORTED,
359                    "a Run that reads and answers, or works at desk, takes no loadout: its MCP servers \
360                     are applied at field clearance",
361                ));
362            }
363            let theater = launch.environment.contains_key(THEATER_SERVED_ENV)
364                || launch.environment.contains_key("AI6_THEATER_MCP_URL");
365            let weakened = launch
366                .loadout
367                .check(&loadout_support(), theater)
368                .map_err(|reason| ProviderError::new(Status::GUATIAO_ERR_UNSUPPORTED, &reason))?;
369            for line in weakened {
370                eprintln!("ai6: warning: ACP loadout: {line}");
371            }
372        }
373        if launch.environment.contains_key(THEATER_SERVED_ENV) && !settings.client_tools {
374            return Err(ProviderError::new(
375                Status::GUATIAO_ERR_UNSUPPORTED,
376                "this Run works on a remote Theater, and AI6 cannot tell whether this ACP agent \
377                 does its file and shell work through the client's fs and terminal requests, which \
378                 the Station answers from the Theater, or itself, on the Station's own machine: the \
379                 Run was not started. Set client_tools = true in the Agent's handler_settings when \
380                 the agent uses the client's tools",
381            ));
382        }
383        if launch.desk && !settings.unconfined_desk {
384            return Err(ProviderError::new(
385                Status::GUATIAO_ERR_UNSUPPORTED,
386                "this Agent works at desk clearance, which allows no command tool, and AI6 does \
387                 not choose an ACP agent's tools, so the Run was not started: give the Agent \
388                 field clearance, or set unconfined_desk = true in its handler_settings to start \
389                 it with whatever tools the agent has",
390            ));
391        }
392        let mut environment = settings.env.clone();
393        environment.extend(launch.environment.clone());
394        let mut argv = vec![settings.command.clone().unwrap_or_default()];
395        argv.extend(settings.args.clone());
396        let spec = Spec {
397            argv,
398            cwd: Some(launch.working_directory.to_owned()),
399            env: Some(environment),
400            rows: 24,
401            cols: STREAM_COLS,
402        };
403        let process: Arc<Object<dyn TerminalRun>> =
404            Arc::new(terminal.spawn(&spec.to_value().map_err(refuse)?)?);
405        let io = TerminalIo::new(process.clone(), settings.poll_ms);
406        let (lines, diagnostics) = over_io(
407            io.clone(),
408            io.clone(),
409            settings.diagnostic_lines,
410            UNBOUNDED_LINE_BYTES,
411        )
412        .map_err(|error| ProviderError::new(Status::GUATIAO_ERR_INTERNAL, &error.to_string()))?;
413        let options = AcpOptions {
414            cwd: launch.working_directory.to_owned(),
415            mcp_servers: mcp_servers(
416                launch.environment,
417                launch.assistant,
418                launch.loadout,
419                launch.working_directory,
420            )?,
421            // typed-boundary: free-form the same `_meta` table, handed to the protocol's own type
422            meta: serde::Deserialize::deserialize(serde_json::Value::Object(settings.meta.clone()))
423                .map_err(|error| refuse(format!("invalid ACP metadata: {error}")))?,
424            model: launch.model.cloned(),
425            effort: launch.effort.cloned(),
426            model_option: settings.model_option.clone(),
427            effort_option: settings.effort_option.clone(),
428            prompt: launch.prompt,
429            resume: launch.resume,
430            reattach: None,
431            restricted: launch.restricted,
432            authenticate: None,
433            initialize_timeout_ms: settings.initialize_timeout_ms,
434            request_timeout_ms: settings.request_timeout_ms,
435            start_timeout_ms: settings.start_timeout_ms,
436            close_grace_ms: settings.close_grace_ms,
437            abort_wait_ms: settings.abort_wait_ms,
438            decider: Arc::new(GateDecider::from_environment(
439                launch.environment,
440                launch.working_directory,
441            )),
442            elicitor: GateElicitor::from_environment(launch.environment)
443                .map(|elicitor| Arc::new(elicitor) as Arc<dyn Elicitor>),
444            close_on_drop: true,
445            fail_on_disconnect: true,
446            limit_phrases: settings.limit_phrases.clone(),
447            disconnect_detail: Some({
448                let (process, diagnostics) = (process.clone(), diagnostics.clone());
449                let exit_wait_ms = settings.exit_wait_ms;
450                Box::new(move || lost_agent(&process, &diagnostics, exit_wait_ms))
451            }),
452            text_flush_bytes: settings.text_flush_bytes,
453            max_tool_kinds: settings.max_tool_kinds,
454            extensions: None,
455            ..AcpOptions::default()
456        };
457        let ended = process.clone();
458        let stopper = io.clone();
459        let on_close: Box<dyn FnOnce() + Send> = Box::new(move || {
460            let _ = ended.kill();
461            stopper.stop();
462        });
463        AcpRun::connect(lines, options, Some(on_close))
464            .map(AcpRun::into_handle)
465            .map_err(|error| {
466                let said = last_words(&diagnostics);
467                if said.is_empty() {
468                    error
469                } else {
470                    ProviderError::new(
471                        Status::GUATIAO_ERR_INTERNAL,
472                        &format!("{error}; the agent last wrote: {said}"),
473                    )
474                }
475            })
476    }
477}
478
479/// A wait in milliseconds as `coqui_acp` takes it: [`UNBOUNDED_MS`] is none.
480fn wait_of(ms: u64) -> Option<Duration> {
481    (ms != UNBOUNDED_MS).then(|| Duration::from_millis(ms))
482}
483
484/// One value of a select option.
485fn choice_of(entry: &SessionConfigSelectOption) -> ChoiceInfo {
486    ChoiceInfo {
487        id: entry.value.0.to_string(),
488        name: Some(entry.name.clone()),
489        description: entry.description.clone(),
490    }
491}
492
493/// The values of a select option, from its values or its groups'.
494fn values_of(option: &SessionConfigOption) -> Vec<ChoiceInfo> {
495    let SessionConfigKind::Select(select) = &option.kind else {
496        return Vec::new();
497    };
498    match &select.options {
499        SessionConfigSelectOptions::Ungrouped(entries) => entries.iter().map(choice_of).collect(),
500        SessionConfigSelectOptions::Grouped(groups) => groups
501            .iter()
502            .flat_map(|group| group.options.iter().map(choice_of))
503            .collect(),
504        _ => Vec::new(),
505    }
506}
507
508/// Whether `option` is a select of `category`.
509fn selects(option: &SessionConfigOption, category: &SessionConfigOptionCategory) -> bool {
510    matches!(option.kind, SessionConfigKind::Select(_))
511        && option.category.as_ref() == Some(category)
512}
513
514/// The select option of `category`, the first the agent lists.
515fn option_of<'a>(
516    options: &'a [SessionConfigOption],
517    category: &SessionConfigOptionCategory,
518) -> Option<&'a SessionConfigOption> {
519    options.iter().find(|option| selects(option, category))
520}
521
522/// A category as the handler names it.
523fn category_name(category: &SessionConfigOptionCategory) -> Option<String> {
524    match category {
525        SessionConfigOptionCategory::Mode => Some("mode".to_owned()),
526        SessionConfigOptionCategory::Model => Some("model".to_owned()),
527        SessionConfigOptionCategory::ModelConfig => Some("model_config".to_owned()),
528        SessionConfigOptionCategory::ThoughtLevel => Some("thought_level".to_owned()),
529        SessionConfigOptionCategory::Other(name) => Some(name.clone()),
530        _ => None,
531    }
532}
533
534/// Models, efforts and other options, as [`options_of`] reads them.
535type OptionParts = (
536    Answer<Vec<ModelInfo>>,
537    Answer<Vec<ChoiceInfo>>,
538    Answer<Vec<ConfigInfo>>,
539);
540
541/// The models, efforts and other options among the options an agent listed. An agent that lists
542/// its options and has none of a category leaves that part unknown, with a reason: only the
543/// agent's own `NotSupported` is passed on as not supported.
544fn options_of(options: &[SessionConfigOption]) -> OptionParts {
545    let models = match option_of(options, &SessionConfigOptionCategory::Model) {
546        Some(option) => Answer::known(
547            values_of(option)
548                .into_iter()
549                .map(|choice| ModelInfo {
550                    id: choice.id,
551                    name: choice.name,
552                    description: choice.description,
553                    efforts: Vec::new(),
554                })
555                .collect(),
556        ),
557        None => Answer::unknown("the agent offers no model to choose before a Run"),
558    };
559    let efforts = match option_of(options, &SessionConfigOptionCategory::ThoughtLevel) {
560        Some(option) => Answer::known(values_of(option)),
561        None => Answer::unknown("the agent offers no effort to choose before a Run"),
562    };
563    let config = options
564        .iter()
565        .filter(|option| {
566            !(selects(option, &SessionConfigOptionCategory::Model)
567                || selects(option, &SessionConfigOptionCategory::ThoughtLevel))
568        })
569        .map(|option| ConfigInfo {
570            id: option.id.0.to_string(),
571            name: option.name.clone(),
572            description: option.description.clone(),
573            category: option.category.as_ref().and_then(category_name),
574            current: match &option.kind {
575                SessionConfigKind::Select(select) => Some(select.current_value.0.to_string()),
576                SessionConfigKind::Boolean(flag) => Some(flag.current_value.to_string()),
577                _ => None,
578            },
579            values: values_of(option),
580        })
581        .collect();
582    (models, efforts, Answer::known(config))
583}
584
585/// A part of the agent's answer as the handler gives it: its own three outcomes, passed on.
586fn passed<T, U>(answer: coqui_acp::Answer<T>, known: impl FnOnce(T) -> U) -> Answer<U> {
587    match answer {
588        coqui_acp::Answer::Known(value) => Answer::known(known(value)),
589        coqui_acp::Answer::Unknown(reason) => Answer::unknown(reason),
590        coqui_acp::Answer::NotSupported => Answer::NotSupported,
591    }
592}
593
594/// The modes of the agent's `SessionModeState`.
595fn modes_of(state: &SessionModeState) -> Vec<ChoiceInfo> {
596    state
597        .available_modes
598        .iter()
599        .map(|mode| ChoiceInfo {
600            id: mode.id.0.to_string(),
601            name: Some(mode.name.clone()),
602            description: mode.description.clone(),
603        })
604        .collect()
605}
606
607/// The sessions of the agent's `session/list`.
608fn sessions_of(list: &coqui_acp::SessionList) -> SessionList {
609    SessionList {
610        sessions: list
611            .sessions
612            .iter()
613            .filter_map(|session| {
614                Some(SessionInfo {
615                    id: session.session_id.0.to_string(),
616                    title: session.title.clone(),
617                    directory: Some(session.cwd.to_str()?.to_owned()),
618                    updated_at: session.updated_at.clone(),
619                })
620            })
621            .collect(),
622        incomplete: list.incomplete.clone(),
623    }
624}
625
626/// What the agent said, as the handler gives it: each part keeps the outcome the agent gave.
627fn start_options_of(described: coqui_acp::Description) -> StartOptions {
628    let (models, efforts, config) = match described.options {
629        coqui_acp::Answer::Known(options) => options_of(&options),
630        coqui_acp::Answer::Unknown(reason) => (
631            Answer::unknown(reason.clone()),
632            Answer::unknown(reason.clone()),
633            Answer::unknown(reason),
634        ),
635        coqui_acp::Answer::NotSupported => (
636            Answer::NotSupported,
637            Answer::NotSupported,
638            Answer::NotSupported,
639        ),
640    };
641    StartOptions {
642        models,
643        efforts,
644        modes: passed(described.modes, |state| modes_of(&state)),
645        config,
646        sessions: passed(described.sessions, |list| sessions_of(&list)),
647    }
648}
649
650impl AcpHandler {
651    /// Starts the agent with exactly `environment` over the settings' own, as a Run would
652    /// be, and asks what it offers before any Run; the agent is ended once it has answered.
653    fn describe(&self, environment: BTreeMap<String, String>) -> Result<StartOptions, String> {
654        let settings = self.settings().map_err(|error| error.to_string())?;
655        let mut merged = settings.env.clone();
656        merged.extend(environment);
657        let mut child = Command::new(settings.command())
658            .args(&settings.args)
659            .env_clear()
660            .envs(&merged)
661            .current_dir(std::env::temp_dir())
662            .stdin(Stdio::piped())
663            .stdout(Stdio::piped())
664            .stderr(Stdio::null())
665            .spawn()
666            .map_err(|error| format!("{} could not be started: {error}", settings.command()))?;
667        let (Some(stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else {
668            let _ = child.kill();
669            let _ = child.wait();
670            return Err(format!(
671                "{} has no standard input or output",
672                settings.command()
673            ));
674        };
675        let described = over_io(stdout, stdin, 0, UNBOUNDED_LINE_BYTES)
676            .map_err(|error| error.to_string())
677            .and_then(|(lines, _)| {
678                Exchange::new()
679                    .client_info("ai6", env!("CARGO_PKG_VERSION"))
680                    .initialize_timeout(wait_of(settings.initialize_timeout_ms))
681                    .request_timeout(wait_of(settings.request_timeout_ms))
682                    .describe_limits(
683                        DescribeLimits::new()
684                            .options(settings.describe_options)
685                            .values(settings.describe_values)
686                            .modes(settings.describe_modes)
687                            .sessions(settings.describe_runs)
688                            .text(settings.describe_text_bytes)
689                            .pages(settings.describe_pages),
690                    )
691                    .describe(lines)
692                    .map_err(|error| format!("the agent could not be asked: {error}"))
693            });
694        let _ = child.kill();
695        let _ = child.wait();
696        Ok(start_options_of(described?))
697    }
698}
699
700impl AgentHandler for AcpHandler {
701    /// What an ACP agent carries out is what it advertises (`compact`) and what ACP gives every
702    /// client (`session/new` on the connection), which only a session knows: this says what the
703    /// handler may do, and a session refuses a command its agent cannot carry out.
704    fn session_commands(&self) -> Result<ai6::SessionCommands, ProviderError> {
705        Ok(ai6::SessionCommands {
706            compact: true,
707            clear: true,
708            unsupported_because: None,
709        })
710    }
711
712    /// An ACP agent's usage is what its failed turns say: a refusal read as a limit is the only
713    /// figure, and nothing reads it between turns.
714    fn usage_support(&self) -> Result<ai6::UsageSupport, ProviderError> {
715        Ok(ai6::UsageSupport::new(vec![ai6::UsageSource::Inferred], false).needs_turn(true))
716    }
717
718    /// An ACP agent speaks JSON-RPC on plain pipes.
719    fn stdio(&self) -> Result<HarnessStdio, ProviderError> {
720        Ok(HarnessStdio::Json)
721    }
722
723    /// The `command` of its settings; without settings there is none to name.
724    fn program(&self) -> Result<Option<String>, ProviderError> {
725        Ok(self
726            .settings
727            .as_ref()
728            .map(|settings| settings.command().to_owned()))
729    }
730
731    /// What the agent offers before any Run, asked of it: its model, effort and other options,
732    /// its modes and its sessions, each with the outcome the agent gave (it said, it could not
733    /// tell and why, or it does not offer the question). An agent that cannot be started is
734    /// unknown in every part, with the reason.
735    fn start_options(
736        &self,
737        environment: BTreeMap<String, String>,
738    ) -> Result<StartOptions, ProviderError> {
739        Ok(self
740            .describe(environment)
741            .unwrap_or_else(StartOptions::unknown))
742    }
743
744    /// AI6 does not choose an ACP agent's tools, so it cannot keep commands from a `desk` Run.
745    fn clearance_refusal(&self, clearance: String) -> Result<Option<String>, ProviderError> {
746        let settings = self.settings()?;
747        Ok(
748            (!clearance_runs_commands(&clearance) && !settings.unconfined_desk).then(|| {
749                "AI6 does not choose an ACP agent's tools, so it cannot keep commands from a Run \
750             at this clearance, and the route's unconfined_desk is not set"
751                    .to_owned()
752            }),
753        )
754    }
755
756    /// An ACP agent starts the stdio MCP servers `session/new` hands it; ACP has no way to deny one
757    /// of a server's tools or to ask for a sandbox, which the agent applies, or not, itself.
758    fn loadout_support(&self) -> Result<LoadoutSupport, ProviderError> {
759        Ok(loadout_support())
760    }
761
762    /// `unconfined_desk`: a `desk` Run runs with the agent's own tools. `client_tools`: a Run on a
763    /// remote Theater trusts the agent to work only through the client.
764    fn weakenings(&self) -> Result<Vec<String>, ProviderError> {
765        let Some(settings) = &self.settings else {
766            return Ok(Vec::new());
767        };
768        let mut weakenings = Vec::new();
769        if settings.unconfined_desk {
770            weakenings.push(
771                "unconfined_desk starts its desk Runs with whatever tools the ACP agent has, \
772                 commands among them"
773                    .to_owned(),
774            );
775        }
776        if settings.client_tools {
777            weakenings.push(
778                "client_tools starts the ACP agent's Runs on a remote Theater on the word that it \
779                 does its file and shell work only through the client's fs and terminal requests; \
780                 one that does its own acts on the Station's machine"
781                    .to_owned(),
782            );
783        }
784        Ok(weakenings)
785    }
786
787    fn start(
788        &self,
789        request: AgentStart,
790        terminal: Object<dyn AgentTerminal>,
791    ) -> Result<Object<dyn AgentSession>, ProviderError> {
792        let restricted = request.answer_only || request.assistant.is_some();
793        let mut context = request
794            .overlays
795            .with_routing(&request.initial_context, false);
796        if let Some(ledger) = &request.ledger {
797            let session = ledger.session.clone().unwrap_or_else(new_session_id);
798            let document = &ledger.document;
799            let seeded = seed(
800                document,
801                &SeedRequest::new("acp", &request.working_directory, &session),
802            )
803            .map_err(refuse)?;
804            match &seeded.seeding {
805                Seeding::Context { text } => {
806                    context.push(text.clone());
807                    context.push(seeded.replay_note());
808                }
809                Seeding::Refused { reason } => {
810                    return Err(ProviderError::new(Status::GUATIAO_ERR_UNSUPPORTED, reason));
811                }
812                _ => {}
813            }
814        }
815        self.run(
816            Launch {
817                environment: &request.environment,
818                working_directory: &request.working_directory,
819                model: request.model.as_ref(),
820                effort: request.effort.as_ref(),
821                restricted,
822                assistant: request.assistant.as_ref(),
823                desk: !restricted && !clearance_runs_commands(&request.clearance),
824                loadout: &request.loadout,
825                prompt: Some(briefing(&context, restricted, &request.prompt)),
826                resume: None,
827            },
828            terminal,
829        )
830    }
831
832    fn resume(
833        &self,
834        request: AgentResume,
835        terminal: Object<dyn AgentTerminal>,
836    ) -> Result<Object<dyn AgentSession>, ProviderError> {
837        let restricted = request.answer_only || request.assistant.is_some();
838        self.run(
839            Launch {
840                environment: &request.environment,
841                working_directory: &request.working_directory,
842                model: request.model.as_ref(),
843                effort: request.effort.as_ref(),
844                restricted,
845                assistant: request.assistant.as_ref(),
846                desk: !restricted && !clearance_runs_commands(&request.clearance),
847                loadout: &request.loadout,
848                prompt: request.message.clone(),
849                resume: Some(request.run_id.to_string()),
850            },
851            terminal,
852        )
853    }
854}
855
856/// What this handler applies of a loadout: the servers, nothing of their tools or a sandbox.
857fn loadout_support() -> LoadoutSupport {
858    let sandbox = "ACP has no sandbox the Station can ask an agent for: the agent applies its own, \
859                   or none";
860    LoadoutSupport {
861        mcp: None,
862        mcp_deny: Some("ACP has no way to deny an MCP server's tools to an agent".to_owned()),
863        sandbox_write: Some(sandbox.to_owned()),
864        sandbox_no_network: Some(sandbox.to_owned()),
865        sandbox_hosts: Some(sandbox.to_owned()),
866    }
867}
868
869#[cfg(test)]
870mod route_tests {
871    use super::*;
872
873    fn handler(settings: &str) -> AcpHandler {
874        let table: toml::Table = toml::from_str(settings).unwrap();
875        let value = ai6::provider_settings::table_value(&table).unwrap();
876        AcpHandler::try_from(AcpSettings::from_value(&value).unwrap()).unwrap()
877    }
878
879    #[test]
880    fn an_acp_agents_usage_is_what_its_failed_turns_say() {
881        let support = handler("command = \"x\"\n").usage_support().unwrap();
882        assert_eq!(support.sources, [ai6::UsageSource::Inferred]);
883        assert!(support.needs_turn, "a Station never asks it to read one");
884    }
885
886    #[test]
887    fn it_cannot_hold_a_run_to_a_plan_however_it_is_set() {
888        for settings in [
889            "command = \"grok\"
890",
891            "command = \"grok\"
892unconfined_desk = true
893",
894        ] {
895            let refused = handler(settings).read_only_refusal().unwrap();
896            assert!(refused.is_some(), "{settings}");
897        }
898    }
899
900    #[test]
901    fn it_refuses_desk_unless_unconfined_and_keeps_its_limit_words() {
902        let confined = handler("command = \"grok\"\n");
903        assert!(
904            confined
905                .clearance_refusal("desk".to_owned())
906                .unwrap()
907                .is_some()
908        );
909        assert_eq!(
910            confined.clearance_refusal("field".to_owned()).unwrap(),
911            None
912        );
913        let unconfined = handler("command = \"grok\"\nunconfined_desk = true\n");
914        assert_eq!(
915            unconfined.clearance_refusal("desk".to_owned()).unwrap(),
916            None
917        );
918        assert!(
919            confined
920                .settings()
921                .unwrap()
922                .limit_phrases
923                .iter()
924                .any(|phrase| phrase == "usage-exhausted"),
925            "the Grok CLI's words count by default"
926        );
927        let run = |text: &str| {
928            let settings = confined.settings().unwrap();
929            let phrases: Vec<&str> = settings.limit_phrases.iter().map(String::as_str).collect();
930            ai6::infer_limit(text, &phrases).is_some()
931        };
932        assert!(
933            run("Rate limited: try again later"),
934            "the shared words count by default"
935        );
936        assert!(
937            !run("503 No capacity available"),
938            "a shortage of capacity is no quota"
939        );
940        assert!(
941            run("Internal error: API error (status 402 Payment Required): \
942                 personal-team-blocked:spending-limit: You have run out of credits"),
943            "Grok out of credits is a limit"
944        );
945        let own = handler("command = \"x\"\nlimit_phrases = [\"out of credits\"]\n");
946        assert_eq!(
947            own.settings().unwrap().limit_phrases,
948            ["out of credits"],
949            "a setting replaces them"
950        );
951    }
952}
953
954#[cfg(test)]
955mod option_tests {
956    use agent_client_protocol::schema::v1::{SessionConfigOption, SessionModeState};
957    use serde_json::json;
958
959    use super::*;
960
961    /// What an agent lists, in the wire form the protocol writes it.
962    fn listed() -> Vec<SessionConfigOption> {
963        serde_json::from_value(json!([
964            {"id": "model", "name": "Model", "category": "model", "type": "select",
965             "currentValue": "fast", "options": [
966                {"value": "fast", "name": "Fast", "description": "quick"},
967                {"value": "deep", "name": "Deep"}]},
968            {"id": "tier", "name": "Tier", "category": "model", "type": "select",
969             "currentValue": "a", "options": [
970                {"group": "g1", "name": "One", "options": [
971                    {"value": "a", "name": "A"}, {"value": "b", "name": "B", "description": "bee"}]},
972                {"group": "g2", "name": "Two", "options": [{"value": "c", "name": "C"}]}]},
973            {"id": "effort", "name": "Effort", "category": "thought_level", "type": "select",
974             "currentValue": "low", "options": [
975                {"value": "low", "name": "Low"}, {"value": "high", "name": "High", "description": "more"}]},
976            {"id": "mode", "name": "Mode", "description": "how it works", "category": "mode",
977             "type": "select", "currentValue": "plan", "options": [{"value": "plan", "name": "Plan"}]},
978            {"id": "verbose", "name": "Verbose", "type": "boolean", "currentValue": true},
979            {"id": "quiet", "name": "Quiet", "category": "model", "type": "boolean", "currentValue": false},
980            {"id": "custom", "name": "Custom", "category": "x_custom", "type": "select",
981             "currentValue": "z", "options": [{"value": "z", "name": "Z"}]},
982            {"id": "bare", "name": "Bare", "type": "select", "currentValue": "q", "options": []}
983        ]))
984        .unwrap()
985    }
986
987    #[test]
988    fn options_and_modes_are_read_as_recorded() {
989        let (models, efforts, config) = super::options_of(&listed());
990        let modes: SessionModeState = serde_json::from_value(json!({
991            "currentModeId": "ask",
992            "availableModes": [
993                {"id": "ask", "name": "Ask", "description": "asks first"},
994                {"id": "code", "name": "Code"}]
995        }))
996        .unwrap();
997        let text = format!(
998            "models: {models:#?}\nefforts: {efforts:#?}\nconfig: {config:#?}\nmodes: {:#?}\n",
999            modes_of(&modes)
1000        );
1001        let path =
1002            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/options.txt");
1003        if std::env::var_os("AI6_BLESS").is_some() {
1004            std::fs::write(&path, &text).unwrap();
1005        }
1006        assert_eq!(std::fs::read_to_string(path).unwrap(), text);
1007    }
1008}