Skip to main content

ai6_agent_antigravity/
lib.rs

1//! The Antigravity CLI's stream-json implementation of AI6's AgentHandler contract.
2
3#![doc = include_str!("../README.md")]
4#![forbid(unsafe_code)]
5
6ai6::guatiao::providers!(AntigravityHandler);
7
8mod files;
9mod run;
10mod usage;
11
12use std::collections::BTreeMap;
13use std::path::Path;
14
15use ai6::AgentSession;
16use ai6::HarnessStdio;
17use ai6::directorates::q::terminal::{AgentTerminal, STREAM_COLS, Spec, TerminalRun};
18use ai6::directorates::section_00::agent::{
19    AgentHandler, AgentResume, AgentStart, AssistantMode, RunOverlays, RunRecordFile,
20    RunRecordQuery, StartOptions, clearance_runs_commands,
21};
22use ai6::directorates::section_00::gate::{CABLE_TOKEN_ENV, CABLE_URL_ENV, GATE_PROGRAM_ENV};
23use ai6::directorates::section_00::ledger_seed::{ANTIGRAVITY, SeedRequest, Seeding, seed};
24use ai6::directorates::section_00::loadout::{LoadoutSupport, RunLoadout};
25use ai6::directorates::section_00::records;
26use ai6::guatiao::library::{Object, ProviderError};
27use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
28use ai6::wire::OpaqueJson;
29use ai6::{UsageReport, UsageSource, UsageSupport};
30use serde::{Deserialize, Serialize};
31
32use files::{Ordered, RunFiles};
33use run::{AntigravityRun, Respawn, Restriction};
34
35/// Why the Antigravity CLI's options are not listed.
36const UNMEASURED_OPTIONS: &str =
37    "the Antigravity CLI's `agy acp` describe is not measured, so its options are not listed";
38
39/// Operator-supplied keys of agy's own settings document. AI6 forwards their values as given.
40#[derive(Debug, Clone, Default, Serialize, Deserialize)]
41#[serde(transparent)]
42pub struct AgySettingsExtras(Ordered<OpaqueJson>);
43
44impl AgySettingsExtras {
45    fn contains_key(&self, key: &str) -> bool {
46        self.0.0.iter().any(|(name, _)| name == key)
47    }
48}
49
50#[derive(Serialize)]
51struct RunSettings<'a> {
52    #[serde(flatten)]
53    extras: &'a AgySettingsExtras,
54    permissions: Permissions<'a>,
55}
56
57#[derive(Serialize)]
58struct Permissions<'a> {
59    allow: &'a [String],
60    deny: Vec<String>,
61}
62
63#[derive(Serialize)]
64struct GateHookFile {
65    #[serde(rename = "ai6-green-ink")]
66    green_ink: GateHookGroup,
67}
68
69#[derive(Serialize)]
70struct GateHookGroup {
71    #[serde(rename = "PreToolUse")]
72    pre_tool_use: [GateHookMatch; 1],
73}
74
75#[derive(Serialize)]
76struct GateHookMatch {
77    matcher: String,
78    hooks: [GateCommand; 1],
79}
80
81#[derive(Serialize)]
82#[serde(tag = "type", rename_all = "snake_case")]
83enum GateCommand {
84    Command { command: String, timeout: u64 },
85}
86
87/// Antigravity CLI AgentHandler configuration.
88#[derive(Debug, Clone, ToValue, FromValue, Schema)]
89#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
90pub struct AntigravityConfig {
91    /// Executable visible to the AI6-owned terminal environment.
92    #[map(default = String::from("agy"))]
93    pub executable: String,
94    /// Bytes of one line of agy's output the Run holds before handing over what it has.
95    /// Default 67108864 (64 MiB).
96    #[map(default = 64 * 1024 * 1024)]
97    pub json_line_bytes: u64,
98    /// Bytes of one terminal control sequence before it is dropped. Default 64.
99    #[map(default = 64)]
100    pub csi_bytes: u64,
101    /// How many of the last non-JSON lines a failed Run quotes. Default 8.
102    #[map(default = 8)]
103    pub tail_lines: u64,
104    /// Bytes of each of those lines a failed Run quotes. Default 512.
105    #[map(default = 512)]
106    pub tail_line_bytes: u64,
107    /// Milliseconds a closing Run waits for agy to have exited. Default 2000.
108    #[map(default = 2_000)]
109    pub close_wait_ms: u64,
110    /// Milliseconds the end of the output waits for agy's exit status. Default 1000.
111    #[map(default = 1_000)]
112    pub exit_wait_ms: u64,
113    /// Bytes of an assistant's context file read into the Run's system prompt; a larger file
114    /// is refused. Default 1048576.
115    #[map(default = 1024 * 1024)]
116    pub context_file_bytes: u64,
117    /// Seconds agy gives the green ink hook on each command; a hook past it holds the command.
118    /// Default 60.
119    #[map(default = 60)]
120    pub gate_timeout_secs: u64,
121    /// agy's `timeoutSeconds` for AI6's MCP servers: positive replaces its limits, negative turns
122    /// them off, and 0 leaves its own, 300 s to connect and 180 s for a call. Default 0.
123    #[map(default = 0)]
124    pub mcp_timeout_secs: i64,
125    /// Milliseconds a read of the account's quota with no Run running may take, counting the
126    /// private `agy acp` it starts: agy serves the quota a few seconds after a run opens.
127    /// Default 20000.
128    #[map(default = 20_000)]
129    pub usage_wait_ms: u64,
130    /// agy permission rules (`command(git)`, `read_url(*)`) added to the allow list, or the names
131    /// of tools added to what a Mission's Run is offered (`search_web`). Answer-only and
132    /// assistant Runs ignore them.
133    #[schema(section = "agent")]
134    #[map(default)]
135    pub allowed_tools: Vec<String>,
136    /// agy permission rules added to the deny list, or the names of tools taken out of what a
137    /// Mission's Run is offered; a deny rule beats an allow rule.
138    #[schema(section = "agent")]
139    #[map(default)]
140    pub denied_tools: Vec<String>,
141    /// Further `settings.json` keys for this Run's `--settings` (`modelProvider`), never those
142    /// that decide what a Run may do.
143    #[schema(section = "agent")]
144    #[map(with = ::ai6::guatiao_serde::adapt::object, default)]
145    pub settings: AgySettingsExtras,
146    /// Lets agy update itself while a Run starts; off by default, so that a Run runs the
147    /// CLI its fixtures were recorded from until an operator updates it.
148    #[schema(section = "agent")]
149    #[map(default)]
150    pub auto_update: bool,
151    /// What marks a failed turn as a quota limit, found in its error without regard to case.
152    #[schema(section = "agent")]
153    #[map(default = limit_phrases())]
154    pub limit_phrases: Vec<String>,
155}
156
157impl Default for AntigravityConfig {
158    fn default() -> Self {
159        Self {
160            executable: String::from("agy"),
161            json_line_bytes: 64 * 1024 * 1024,
162            csi_bytes: 64,
163            tail_lines: 8,
164            tail_line_bytes: 512,
165            close_wait_ms: 2_000,
166            exit_wait_ms: 1_000,
167            usage_wait_ms: 20_000,
168            context_file_bytes: 1024 * 1024,
169            gate_timeout_secs: 60,
170            mcp_timeout_secs: 0,
171            allowed_tools: Vec::new(),
172            denied_tools: Vec::new(),
173            settings: AgySettingsExtras::default(),
174            auto_update: false,
175            limit_phrases: limit_phrases(),
176        }
177    }
178}
179
180/// What an Agent's `handler_settings` change. Unknown keys are refused.
181#[derive(Debug, Clone)]
182struct AntigravitySettings {
183    /// agy permission rules (`command(git)`, `read_url(*)`) added to the allow list, or the names
184    /// of tools added to what a Mission's Run is offered (`search_web`). Answer-only and
185    /// assistant Runs ignore them.
186    allowed_tools: Vec<String>,
187    /// agy permission rules added to the deny list, or the names of tools taken out of what a
188    /// Mission's Run is offered; a deny rule beats an allow rule.
189    denied_tools: Vec<String>,
190    /// Further `settings.json` keys for this Run's `--settings` (`modelProvider`), never those
191    /// that decide what a Run may do ([`RESERVED_SETTINGS`]).
192    settings: AgySettingsExtras,
193    /// Lets agy update itself while a Run starts; off by default, so that a Run runs the
194    /// CLI its fixtures were recorded from until an operator updates it.
195    auto_update: bool,
196    /// What marks a failed turn as a quota limit, found in its error without regard to case.
197    limit_phrases: Vec<String>,
198}
199
200/// `settings.json` keys `handler_settings` may not set: they decide what a Run may do, which
201/// `allowed_tools` and `denied_tools` say and report as weakenings.
202const RESERVED_SETTINGS: [&str; 5] = [
203    "permissions",
204    "toolPermission",
205    "agentMode",
206    "trustedWorkspaces",
207    "allowNonWorkspaceAccess",
208];
209
210/// The words every handler reads a limit by. They cover agy 1.4.12's wording (`RESOURCE_EXHAUSTED`
211/// and `Error 429` in a turn's `result`; `QUOTA_EXHAUSTED`, the reason Google's error details
212/// carry) and leave out its 503 `No capacity available`, which is a shortage and no quota.
213fn limit_phrases() -> Vec<String> {
214    ai6::DEFAULT_LIMIT_PHRASES
215        .iter()
216        .copied()
217        .map(str::to_owned)
218        .collect()
219}
220
221impl AntigravitySettings {
222    fn of(config: &AntigravityConfig) -> Result<Self, String> {
223        let settings = Self {
224            allowed_tools: config.allowed_tools.clone(),
225            denied_tools: config.denied_tools.clone(),
226            settings: config.settings.clone(),
227            auto_update: config.auto_update,
228            limit_phrases: config.limit_phrases.clone(),
229        };
230        for rule in settings.allowed_tools.iter().chain(&settings.denied_tools) {
231            if !valid_rule(rule) {
232                return Err(format!(
233                    "{rule:?} is not an agy permission rule (`action(target)`) or a tool name"
234                ));
235            }
236        }
237        if let Some(key) = RESERVED_SETTINGS
238            .iter()
239            .find(|key| settings.settings.contains_key(key))
240        {
241            return Err(format!(
242                "settings may not set {key}: allowed_tools and denied_tools say what a Run may do"
243            ));
244        }
245        Ok(settings)
246    }
247}
248
249/// A tool name or an `action(target)` rule. The action is checked because a tool name goes into
250/// the agent file's YAML as it is.
251fn valid_rule(rule: &str) -> bool {
252    let (name, target) = match rule.split_once('(') {
253        Some((name, target)) => (name, Some(target)),
254        None => (rule, None),
255    };
256    !name.is_empty()
257        && name
258            .chars()
259            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
260        && target.is_none_or(|target| target.ends_with(')'))
261}
262
263/// The tool a Run runs commands with, and the permission action that governs it.
264const COMMAND_TOOL: &str = "run_command";
265const COMMAND_ACTION: &str = "command";
266
267/// The tools that read: `read_file` is also how a model learns an MCP tool's arguments, from
268/// `<app data>/mcp/<server>/<tool>.json`, which agy lets it read without a rule.
269const READ_TOOLS: [&str; 4] = ["read_file", "grep_search", "find_by_name", "list_dir"];
270
271/// The tools that edit, which an allow rule rooted at the working directory lets run.
272const EDIT_TOOLS: [&str; 2] = ["write_file", "edit_file"];
273
274/// Paths under the working directory no file tool may write, whatever else is allowed: agy loads a
275/// working directory's `.agents` and `.agent` hooks at its next start, and a planted `.git` hook
276/// runs under whatever next runs git there.
277const PROTECTED_DIRECTORIES: [&str; 3] = [".git", ".agents", ".agent"];
278
279/// Files a working directory carries that run commands or connect servers in any Run started
280/// there, trusted or not (agy 1.4.12: both hook files ran with the directory outside
281/// `trustedWorkspaces`, and `.agents/mcp_config.json` connected). The plugin directories are from
282/// agy's documentation.
283const PROJECT_HOOKS: [&str; 4] = [
284    ".agents/hooks.json",
285    ".agent/hooks.json",
286    ".agents/plugins",
287    ".agent/plugins",
288];
289const PROJECT_MCP: [&str; 2] = [".agents/mcp_config.json", ".agent/mcp_config.json"];
290
291/// What one launch of agy is told: the agent's tools, its permission rules and how the stream is
292/// watched. Agents, and so tools, are fixed by the conversation's first launch (agy 1.4.12 kept a
293/// conversation's tools and system prompt under another `--agent`), while `--settings` is read at
294/// each launch, so what a later clearance takes away is denied by rule.
295#[derive(Debug, Default)]
296struct Plan {
297    tools: Vec<String>,
298    inherit_mcp: bool,
299    allow: Vec<String>,
300    deny: Vec<String>,
301    /// Each MCP server's name and the prefix of its two variables.
302    servers: Vec<(String, String)>,
303    /// The Run's environment, where those variables are.
304    endpoints: BTreeMap<String, String>,
305    restriction: Option<Restriction>,
306    gate: bool,
307}
308
309/// What a request says about its Run, on a start or a resume.
310struct Launch<'a> {
311    working_directory: &'a str,
312    clearance: &'a str,
313    environment: &'a BTreeMap<String, String>,
314    model: Option<&'a str>,
315    effort: Option<&'a str>,
316    project_settings: bool,
317    project_mcp: bool,
318    answer_only: bool,
319    assistant: Option<&'a AssistantMode>,
320    overlays: &'a RunOverlays,
321    loadout: &'a RunLoadout,
322}
323
324/// Starts and resumes Antigravity CLI streams for AI6 Agent Runs.
325#[derive(Provider)]
326#[provider(
327    AgentHandler,
328    id = "antigravity",
329    name = "Antigravity CLI",
330    crate = ::ai6::guatiao,
331    config = AntigravityConfig
332)]
333pub struct AntigravityHandler {
334    config: AntigravityConfig,
335    settings: AntigravitySettings,
336}
337
338impl TryFrom<AntigravityConfig> for AntigravityHandler {
339    type Error = ProviderError;
340
341    fn try_from(config: AntigravityConfig) -> Result<Self, Self::Error> {
342        if config.executable.trim().is_empty() {
343            return Err(refuse(
344                Status::GUATIAO_ERR_BAD_VALUE,
345                "the agy executable is empty",
346            ));
347        }
348        let settings = AntigravitySettings::of(&config).map_err(|reason| {
349            refuse(
350                Status::GUATIAO_ERR_BAD_VALUE,
351                format!("handler_settings: {reason}"),
352            )
353        })?;
354        Ok(Self { config, settings })
355    }
356}
357
358/// The format of the Antigravity CLI's conversation transcript.
359pub const RECORD_FORMAT: &str = "antigravity-jsonl";
360
361/// The Antigravity CLI's transcript of the conversation `query` names, when it is on this
362/// host: `~/.gemini/antigravity-cli/brain/<conversation>/transcript.jsonl`, the path its hooks
363/// are given as `transcriptPath` (1.4.12).
364fn antigravity_record(query: &RunRecordQuery) -> Option<RunRecordFile> {
365    if !records::file_safe(&query.run_id) {
366        return None;
367    }
368    let path = records::home(&query.environment)?
369        .join(".gemini")
370        .join("antigravity-cli")
371        .join("brain")
372        .join(&query.run_id)
373        .join("transcript.jsonl");
374    path.is_file().then(|| RunRecordFile {
375        path: path.to_string_lossy().into_owned(),
376        format: RECORD_FORMAT.to_owned(),
377    })
378}
379
380impl AgentHandler for AntigravityHandler {
381    /// An assistant on this handler gets reading and its MCP servers only: any network but
382    /// nothing is refused at start.
383    fn assistant_network(&self) -> Result<Option<String>, ProviderError> {
384        Ok(None)
385    }
386
387    /// agy runs `/compact` as a turn in the live conversation. It refuses `/clear` in this mode, so
388    /// a clear is a new agy on a new conversation of the same Run.
389    fn session_commands(&self) -> Result<ai6::SessionCommands, ProviderError> {
390        Ok(ai6::SessionCommands {
391            compact: true,
392            clear: true,
393            unsupported_because: None,
394        })
395    }
396
397    /// agy with `--input-format stream-json` reads JSON lines from standard input.
398    fn stdio(&self) -> Result<HarnessStdio, ProviderError> {
399        Ok(HarnessStdio::Json)
400    }
401
402    fn program(&self) -> Result<Option<String>, ProviderError> {
403        Ok(Some(self.config.executable.clone()))
404    }
405
406    /// agy applies none of a loadout: only URL servers are measured (its `mcp_config.json`), the only
407    /// sandbox it has (`--sandbox`) is not, and no rule denies one of a server's tools by anything but
408    /// `mcp(<server>/<tool>)`, which has not been tried for a stdio server.
409    fn loadout_support(&self) -> Result<LoadoutSupport, ProviderError> {
410        Ok(loadout_support())
411    }
412
413    /// Every part is unknown, each with the same reason: `agy acp` is the one command that might
414    /// describe what a Run can start with, and what it answers before a session has not been
415    /// measured, so nothing is said and nothing is declared not supported.
416    fn start_options(
417        &self,
418        environment: BTreeMap<String, String>,
419    ) -> Result<StartOptions, ProviderError> {
420        let _ = environment;
421        Ok(StartOptions::unknown(UNMEASURED_OPTIONS))
422    }
423
424    /// agy reports the account's quota as figures it serves itself, with no turn. A turn's own
425    /// events carry the run's tokens.
426    fn usage_support(&self) -> Result<UsageSupport, ProviderError> {
427        Ok(UsageSupport::new(vec![UsageSource::Reported], true))
428    }
429
430    /// The quota of the account behind `environment`: from the agy of a running Run under the
431    /// same home when it serves it, else from a private `agy acp` with an empty run, started
432    /// under that home and ended after the read. No model turn is spent. A signed-out agy, or one
433    /// that serves no quota within `usage_wait_ms`, is an error.
434    fn usage(&self, environment: BTreeMap<String, String>) -> Result<UsageReport, ProviderError> {
435        let home = usage::home_of(&environment);
436        let wait = std::time::Duration::from_millis(self.config.usage_wait_ms);
437        let started = std::time::Instant::now();
438        if let Some(buckets) = usage::through_run(&home, wait) {
439            return Ok(usage::report_of(buckets));
440        }
441        usage::through_private_agent(
442            &self.config.executable,
443            &environment,
444            wait.saturating_sub(started.elapsed()),
445        )
446        .map(usage::report_of)
447        .map_err(|reason| refuse(Status::GUATIAO_ERR_INTERNAL, &reason))
448    }
449
450    /// agy keeps each conversation's transcript under its home directory.
451    fn run_record(&self, query: RunRecordQuery) -> Result<Option<RunRecordFile>, ProviderError> {
452        Ok(antigravity_record(&query))
453    }
454
455    /// Each rule of `allowed_tools` no default list holds. A rule the settings deny as well allows
456    /// nothing, so it is not one. A rule for a command is one however the Agent is configured,
457    /// since any Agent can come to work at `desk`.
458    fn weakenings(&self) -> Result<Vec<String>, ProviderError> {
459        let denied = &self.settings.denied_tools;
460        Ok(self
461            .settings
462            .allowed_tools
463            .iter()
464            .filter(|rule| !denied.contains(rule))
465            .filter_map(|rule| {
466                if rule_runs_commands(rule) {
467                    Some(format!(
468                        "allowed_tools adds {rule} to what its desk Runs may call"
469                    ))
470                } else if READ_TOOLS.contains(&rule.as_str()) || EDIT_TOOLS.contains(&rule.as_str())
471                {
472                    None
473                } else {
474                    Some(format!(
475                        "allowed_tools adds {rule} to what its field Runs may call"
476                    ))
477                }
478            })
479            .collect())
480    }
481
482    fn start(
483        &self,
484        request: AgentStart,
485        terminal: Object<dyn AgentTerminal>,
486    ) -> Result<Object<dyn AgentSession>, ProviderError> {
487        if let Some(ledger) = &request.ledger {
488            let document = &ledger.document;
489            let seeded = seed(
490                document,
491                &SeedRequest::new(ANTIGRAVITY, &request.working_directory, ""),
492            )
493            .map_err(|why| refuse(Status::GUATIAO_ERR_BAD_VALUE, why))?;
494            let reason = match seeded.seeding {
495                Seeding::Refused { reason } => reason,
496                _ => "the Antigravity CLI cannot start from a ledger".to_owned(),
497            };
498            return Err(refuse(Status::GUATIAO_ERR_UNSUPPORTED, reason));
499        }
500        let launch = Launch {
501            working_directory: &request.working_directory,
502            clearance: &request.clearance,
503            environment: &request.environment,
504            model: request.model.as_deref(),
505            effort: request.effort.as_deref(),
506            project_settings: request.project_settings,
507            project_mcp: request.project_mcp,
508            answer_only: request.answer_only,
509            assistant: request.assistant.as_ref(),
510            overlays: &request.overlays,
511            loadout: &request.loadout,
512        };
513        let plan = self.plan(&launch)?;
514        let context = self.context(
515            &request
516                .overlays
517                .with_routing(&request.initial_context, true),
518            request.assistant.as_ref(),
519        )?;
520        let files = RunFiles::create(
521            &request.working_directory,
522            &plan,
523            self.config.mcp_timeout_secs,
524            self.gate_hook(&launch, &plan).as_ref(),
525            &context,
526            &request.overlays,
527        )?;
528        let argv = self.argv(&launch, &plan, &files, Some(files.agent_name()), None);
529        let environment = self.environment(&request.environment);
530        let run = spawn(
531            &terminal,
532            argv.clone(),
533            &request.working_directory,
534            &environment,
535        )?;
536        let operation = AntigravityRun::new(
537            run,
538            None,
539            plan.restriction,
540            &self.config,
541            self.settings.limit_phrases.clone(),
542            files,
543            Respawn {
544                terminal,
545                argv,
546                working_directory: request.working_directory.clone(),
547                environment,
548            },
549        );
550        operation.send(&request.prompt)?;
551        Ok(operation.into_object())
552    }
553
554    fn resume(
555        &self,
556        request: AgentResume,
557        terminal: Object<dyn AgentTerminal>,
558    ) -> Result<Object<dyn AgentSession>, ProviderError> {
559        let launch = Launch {
560            working_directory: &request.working_directory,
561            clearance: &request.clearance,
562            environment: &request.environment,
563            model: request.model.as_deref(),
564            effort: request.effort.as_deref(),
565            project_settings: request.project_settings,
566            project_mcp: request.project_mcp,
567            answer_only: request.answer_only,
568            assistant: request.assistant.as_ref(),
569            overlays: &request.overlays,
570            loadout: &request.loadout,
571        };
572        let plan = self.plan(&launch)?;
573        // The agent and its system prompt stay as the conversation's first launch had them, so
574        // this launch needs no agent file; its MCP servers, hooks and skills are this launch's.
575        let files = RunFiles::create(
576            &request.working_directory,
577            &plan,
578            self.config.mcp_timeout_secs,
579            self.gate_hook(&launch, &plan).as_ref(),
580            "",
581            &request.overlays,
582        )?;
583        let argv = self.argv(&launch, &plan, &files, None, Some(request.run_id.as_str()));
584        let environment = self.environment(&request.environment);
585        let run = spawn(
586            &terminal,
587            argv.clone(),
588            &request.working_directory,
589            &environment,
590        )?;
591        let operation = AntigravityRun::new(
592            run,
593            Some(request.run_id.clone()),
594            plan.restriction,
595            &self.config,
596            self.settings.limit_phrases.clone(),
597            files,
598            Respawn {
599                terminal,
600                argv,
601                working_directory: request.working_directory.clone(),
602                environment,
603            },
604        );
605        // agy starts a new conversation for an ID it does not have and says so only on standard
606        // error, so the message waits for the `init` line that names the conversation.
607        if let Some(message) = request.message {
608            operation.hold(message)?;
609        }
610        Ok(operation.into_object())
611    }
612}
613
614impl AntigravityHandler {
615    /// Decides what this launch may do, refusing what the handler cannot hold it to.
616    fn plan(&self, launch: &Launch<'_>) -> Result<Plan, ProviderError> {
617        if !launch.loadout.is_empty() {
618            if launch.assistant.is_some() || launch.answer_only {
619                return Err(refuse(
620                    Status::GUATIAO_ERR_UNSUPPORTED,
621                    "a Run that reads and answers takes no loadout",
622                ));
623            }
624            let weakened = launch
625                .loadout
626                .check(
627                    &loadout_support(),
628                    has_endpoint(launch.environment, "AI6_THEATER_MCP"),
629                )
630                .map_err(|reason| refuse(Status::GUATIAO_ERR_UNSUPPORTED, reason))?;
631            for line in weakened {
632                eprintln!("ai6: warning: Antigravity CLI loadout: {line}");
633            }
634        }
635        check_project_files(
636            Path::new(launch.working_directory),
637            launch.project_settings,
638            launch.project_mcp,
639        )?;
640        let mut plan = if let Some(mode) = launch.assistant {
641            self.assistant_plan(launch, mode)?
642        } else if launch.answer_only {
643            answer_only_plan()
644        } else {
645            self.mission_plan(launch)?
646        };
647        plan.endpoints.clone_from(launch.environment);
648        Ok(plan)
649    }
650
651    /// A Mission's Run at its clearance. At `field` and `00`: reading, editing inside the
652    /// working directory, commands and AI6's MCP servers. At `desk` and any other clearance: the
653    /// same with no command tool, and commands denied by rule, since a resumed conversation keeps
654    /// the tools of its first launch. In remote-hands mode only the Theater's tools.
655    fn mission_plan(&self, launch: &Launch<'_>) -> Result<Plan, ProviderError> {
656        let environment = launch.environment;
657        let commands = clearance_runs_commands(launch.clearance);
658        let remote_hands = has_endpoint(environment, "AI6_THEATER_MCP");
659        let settings = &self.settings;
660        let bare_denied = |tool: &str| settings.denied_tools.iter().any(|rule| rule == tool);
661        let mut plan = Plan {
662            inherit_mcp: true,
663            gate: true,
664            ..Plan::default()
665        };
666        if has_endpoint(environment, "AI6_CABLE_MCP") {
667            plan.servers
668                .push(("ai6-cables".to_owned(), "AI6_CABLE_MCP".to_owned()));
669        }
670        if remote_hands {
671            plan.servers
672                .push(("ai6-theater".to_owned(), "AI6_THEATER_MCP".to_owned()));
673        }
674        plan.allow.extend(
675            plan.servers
676                .iter()
677                .map(|(name, _)| format!("mcp({name}/*)")),
678        );
679        let lifted = settings
680            .allowed_tools
681            .iter()
682            .any(|rule| rule_runs_commands(rule));
683        if remote_hands {
684            // Nothing the harness does may land on the Station.
685            plan.deny
686                .extend(["read_file(*)", "write_file(*)", "command(*)"].map(str::to_owned));
687            if !commands && !lifted {
688                plan.deny.extend(
689                    [
690                        "mcp(ai6-theater/exec)",
691                        "mcp(ai6-theater/fs_write)",
692                        "mcp(ai6-theater/edit)",
693                        "mcp(ai6-theater/apply_patch)",
694                    ]
695                    .map(str::to_owned),
696                );
697            }
698        } else {
699            let root = Path::new(launch.working_directory);
700            plan.tools.extend(
701                READ_TOOLS
702                    .iter()
703                    .chain(EDIT_TOOLS.iter())
704                    .filter(|tool| !bare_denied(tool))
705                    .map(|tool| (*tool).to_owned()),
706            );
707            plan.allow.push(format!("write_file({})", display(root)));
708            // agy 1.4.12 ended the turn on a read outside its workspaces under no rule.
709            plan.allow.extend(
710                launch
711                    .overlays
712                    .roots
713                    .iter()
714                    .map(|root| format!("read_file({root})")),
715            );
716            plan.deny.extend(
717                PROTECTED_DIRECTORIES
718                    .iter()
719                    .map(|name| format!("write_file({})", display(&root.join(name)))),
720            );
721            if commands || lifted {
722                if !bare_denied(COMMAND_TOOL) {
723                    plan.tools.push(COMMAND_TOOL.to_owned());
724                }
725                if commands {
726                    plan.allow.push(format!("{COMMAND_ACTION}(*)"));
727                }
728            } else {
729                plan.deny.push(format!("{COMMAND_ACTION}(*)"));
730            }
731            for rule in &settings.allowed_tools {
732                if !rule.contains('(') && !plan.tools.contains(rule) && !bare_denied(rule) {
733                    plan.tools.push(rule.clone());
734                }
735            }
736        }
737        for rule in &settings.allowed_tools {
738            if rule.contains('(') {
739                plan.allow.push(rule.clone());
740            } else if rule == COMMAND_TOOL && !remote_hands && !commands {
741                plan.allow.push(format!("{COMMAND_ACTION}(*)"));
742            }
743        }
744        plan.deny.extend(
745            settings
746                .denied_tools
747                .iter()
748                .filter(|rule| rule.contains('('))
749                .cloned(),
750        );
751        Ok(plan)
752    }
753
754    /// Moneypenny's Run: reading and the mode's MCP servers, or a refusal naming what is asked
755    /// for beyond them. agy has no `Bash(<interpreter> *)` rule, and its only sandbox is
756    /// `--sandbox`, which AI6 has not measured, so it runs no interpreter; it cannot keep a
757    /// `write_file` rule from a name starting with `.`, so it takes no `files`; `search_web` takes
758    /// no host list, so it has no network.
759    fn assistant_plan(
760        &self,
761        launch: &Launch<'_>,
762        mode: &AssistantMode,
763    ) -> Result<Plan, ProviderError> {
764        mode.validate()
765            .map_err(|reason| refuse(Status::GUATIAO_ERR_BAD_VALUE, reason))?;
766        let refused = if !mode.interpreters.is_empty() {
767            Some("the interpreters it names")
768        } else if !mode.files.is_empty() {
769            Some("the directories it names to write")
770        } else if !mode.skills.is_empty() {
771            Some("the skills it names")
772        } else if !mode.network.reaches_nothing() {
773            Some("a network besides its MCP servers")
774        } else {
775            None
776        };
777        if let Some(what) = refused {
778            return Err(refuse(
779                Status::GUATIAO_ERR_UNSUPPORTED,
780                format!(
781                    "the Antigravity CLI handler runs an assistant with reading and its MCP \
782                     servers only, so it cannot give this one {what}"
783                ),
784            ));
785        }
786        let mut servers = Vec::new();
787        for server in &mode.mcp_servers {
788            if !has_endpoint(launch.environment, &server.env_prefix) {
789                return Err(refuse(
790                    Status::GUATIAO_ERR_BAD_VALUE,
791                    format!(
792                        "the environment carries no URL and token for MCP server {:?}",
793                        server.name
794                    ),
795                ));
796            }
797            servers.push((server.name.clone(), server.env_prefix.clone()));
798        }
799        let allow = servers
800            .iter()
801            .map(|(name, _)| format!("mcp({name}/*)"))
802            .collect();
803        let names = servers.iter().map(|(name, _)| name.clone()).collect();
804        Ok(Plan {
805            tools: vec!["read_file".to_owned()],
806            inherit_mcp: true,
807            allow,
808            deny: RESTRICTED_DENIED.map(str::to_owned).to_vec(),
809            servers,
810            endpoints: BTreeMap::new(),
811            restriction: Some(Restriction {
812                servers: names,
813                tools: ASSISTANT_TOOLS.to_vec(),
814            }),
815            gate: false,
816        })
817    }
818
819    /// The hook that holds a command green ink does not cover, for a Run with a Station to
820    /// ask. It runs under `sh -c`, so each part is quoted; the token stays in the environment.
821    fn gate_hook(&self, launch: &Launch<'_>, plan: &Plan) -> Option<GateHookFile> {
822        if !plan.gate || !plan.tools.iter().any(|tool| tool == COMMAND_TOOL) {
823            return None;
824        }
825        let environment = launch.environment;
826        let cable_url = environment
827            .get(CABLE_URL_ENV)
828            .filter(|_| environment.contains_key(CABLE_TOKEN_ENV))?;
829        let program = hook_program(environment)?;
830        Some(GateHookFile {
831            green_ink: GateHookGroup {
832                pre_tool_use: [GateHookMatch {
833                    matcher: format!("^{COMMAND_TOOL}$"),
834                    hooks: [GateCommand::Command {
835                        command: format!(
836                            "{} green-ink gate --cable-url {}",
837                            shell_quote(&program),
838                            shell_quote(cable_url)
839                        ),
840                        timeout: self.config.gate_timeout_secs,
841                    }],
842                }],
843            },
844        })
845    }
846
847    /// The Run's system prompt: the standing context and an assistant's context file.
848    fn context(
849        &self,
850        context: &[String],
851        assistant: Option<&AssistantMode>,
852    ) -> Result<String, ProviderError> {
853        let mut parts: Vec<String> = context.to_vec();
854        if let Some(file) = assistant.and_then(|mode| mode.context_file.as_ref()) {
855            let size = std::fs::metadata(file)
856                .map_err(|error| {
857                    refuse(
858                        Status::GUATIAO_ERR_BAD_VALUE,
859                        format!("the assistant's context file {file}: {error}"),
860                    )
861                })?
862                .len();
863            if size > self.config.context_file_bytes {
864                return Err(refuse(
865                    Status::GUATIAO_ERR_BAD_VALUE,
866                    format!(
867                        "the assistant's context file {file} holds {size} bytes, over \
868                         context_file_bytes ({})",
869                        self.config.context_file_bytes
870                    ),
871                ));
872            }
873            parts.push(std::fs::read_to_string(file).map_err(|error| {
874                refuse(
875                    Status::GUATIAO_ERR_BAD_VALUE,
876                    format!("the assistant's context file {file}: {error}"),
877                )
878            })?);
879        }
880        Ok(parts.join("\n\n"))
881    }
882
883    fn argv(
884        &self,
885        launch: &Launch<'_>,
886        plan: &Plan,
887        files: &RunFiles,
888        agent: Option<&str>,
889        conversation: Option<&str>,
890    ) -> Vec<String> {
891        let mut argv = vec![
892            self.config.executable.clone(),
893            "--input-format".to_owned(),
894            "stream-json".to_owned(),
895            "--output-format".to_owned(),
896            "stream-json".to_owned(),
897            "--print-timeout=0s".to_owned(),
898            "--add-dir".to_owned(),
899            files.path_text(),
900        ];
901        if let Some(skills) = files.skills_text() {
902            argv.extend(["--add-dir".to_owned(), skills]);
903        }
904        if let Some(agent) = agent {
905            argv.push(format!("--agent={agent}"));
906        }
907        if let Some(conversation) = conversation {
908            argv.push(format!("--conversation={conversation}"));
909        }
910        add_model(&mut argv, launch.model, launch.effort);
911        argv.extend([
912            "--settings".to_owned(),
913            serde_json::to_string(&self.run_settings(plan, files))
914                .expect("agy's settings document serializes"),
915        ]);
916        argv
917    }
918
919    /// The `--settings` value: never saved by agy, so nothing here reaches the user's own file. It
920    /// names no secret; the Run's own directory is denied to the file tools, since it holds
921    /// the MCP servers' tokens.
922    fn run_settings<'a>(&'a self, plan: &'a Plan, files: &RunFiles) -> RunSettings<'a> {
923        let mut deny = plan.deny.clone();
924        deny.push(format!("read_file({})", files.path_text()));
925        deny.push(format!("write_file({})", files.path_text()));
926        RunSettings {
927            extras: &self.settings.settings,
928            permissions: Permissions {
929                allow: &plan.allow,
930                deny,
931            },
932        }
933    }
934
935    /// The harness's environment: the Run's, with agy's updater off unless the Agent lets it
936    /// run. Only the value `true` turns it off (agy 1.4.12 went on updating with `1`).
937    fn environment(&self, environment: &BTreeMap<String, String>) -> BTreeMap<String, String> {
938        let mut environment = environment.clone();
939        if !self.settings.auto_update {
940            environment.insert(AUTO_UPDATE_OFF_ENV.to_owned(), "true".to_owned());
941        }
942        environment
943    }
944}
945
946/// The variable that keeps agy from starting its updater.
947const AUTO_UPDATE_OFF_ENV: &str = "AGY_CLI_DISABLE_AUTO_UPDATE";
948
949/// The tools a restricted Run is not to reach by rule, should its offer ever widen.
950const RESTRICTED_DENIED: [&str; 4] = [
951    "write_file(*)",
952    "command(*)",
953    "read_url(*)",
954    "execute_url(*)",
955];
956
957/// The tools an assistant Run may call: reading, the MCP tools (checked by server), and
958/// `manage_task`, which agy offers every agent and which has no background task to act on here.
959const ASSISTANT_TOOLS: [&str; 5] = [
960    "read_file",
961    "call_mcp_tool",
962    "list_resources",
963    "read_resource",
964    "manage_task",
965];
966
967/// A Run that only reads its prompt and answers. agy offers `list_resources`, `read_resource`
968/// and `manage_task` to any agent; the rules and the tripwire keep the first two away.
969fn answer_only_plan() -> Plan {
970    let mut deny: Vec<String> = RESTRICTED_DENIED.map(str::to_owned).to_vec();
971    deny.extend(["read_file(*)", "mcp(*)"].map(str::to_owned));
972    Plan {
973        tools: Vec::new(),
974        inherit_mcp: false,
975        allow: Vec::new(),
976        deny,
977        servers: Vec::new(),
978        endpoints: BTreeMap::new(),
979        restriction: Some(Restriction {
980            servers: Vec::new(),
981            tools: vec!["manage_task"],
982        }),
983        gate: false,
984    }
985}
986
987/// Whether a rule lets a Run run commands.
988fn rule_runs_commands(rule: &str) -> bool {
989    rule == COMMAND_TOOL || rule.starts_with("command(")
990}
991
992/// Refuses a working directory whose own files agy would load though AI6 did not allow them.
993fn check_project_files(root: &Path, settings: bool, mcp: bool) -> Result<(), ProviderError> {
994    let found =
995        |names: &[&'static str]| names.iter().find(|name| root.join(name).exists()).copied();
996    let carried = if settings {
997        None
998    } else {
999        found(&PROJECT_HOOKS)
1000    };
1001    let carried = carried.or_else(|| {
1002        if settings && mcp {
1003            None
1004        } else {
1005            found(&PROJECT_MCP)
1006        }
1007    });
1008    match carried {
1009        Some(name) => Err(refuse(
1010            Status::GUATIAO_ERR_UNSUPPORTED,
1011            format!(
1012                "the working directory carries {name}, which the Antigravity CLI loads in every \
1013                 Run started there and no flag keeps out, and the Operation does not allow \
1014                 its project settings: remove it, or allow them with harness.project_settings"
1015            ),
1016        )),
1017        None => Ok(()),
1018    }
1019}
1020
1021/// Adds the model and effort, each as one `--flag=VALUE` argument: a value that starts with `-` is
1022/// then never read as another option. A model name that ends in an effort (`gemini-3.8-flash-low`)
1023/// already says one, and agy refuses `--effort` beside it when they differ, so the name wins.
1024fn add_model(argv: &mut Vec<String>, model: Option<&str>, effort: Option<&str>) {
1025    if let Some(model) = model {
1026        argv.push(format!("--model={model}"));
1027    }
1028    let named = model.is_some_and(|model| {
1029        ["low", "medium", "high", "xhigh", "max"]
1030            .iter()
1031            .any(|effort| model.ends_with(&format!("-{effort}")))
1032    });
1033    if let Some(effort) = effort.filter(|_| !named) {
1034        argv.push(format!("--effort={effort}"));
1035    }
1036}
1037
1038/// The program a hook runs as AI6's gate: `AI6_GREEN_INK_GATE` from the Run environment when
1039/// not blank, else the executable hosting this handler.
1040fn hook_program(environment: &BTreeMap<String, String>) -> Option<String> {
1041    environment
1042        .get(GATE_PROGRAM_ENV)
1043        .filter(|program| !program.trim().is_empty())
1044        .cloned()
1045        .or_else(|| {
1046            std::env::current_exe()
1047                .ok()
1048                .map(|path| path.to_string_lossy().into_owned())
1049        })
1050}
1051
1052/// One word for `sh`.
1053fn shell_quote(word: &str) -> String {
1054    format!("'{}'", word.replace('\'', "'\\''"))
1055}
1056
1057/// Whether `environment` carries an MCP endpoint's URL and token under `prefix`.
1058fn has_endpoint(environment: &BTreeMap<String, String>, prefix: &str) -> bool {
1059    environment.contains_key(&format!("{prefix}_URL"))
1060        && environment.contains_key(&format!("{prefix}_TOKEN"))
1061}
1062
1063fn display(path: &Path) -> String {
1064    path.to_string_lossy().into_owned()
1065}
1066
1067fn spawn(
1068    terminal: &Object<dyn AgentTerminal>,
1069    argv: Vec<String>,
1070    cwd: &str,
1071    environment: &BTreeMap<String, String>,
1072) -> Result<Object<dyn TerminalRun>, ProviderError> {
1073    let spec = Spec {
1074        argv,
1075        cwd: Some(cwd.to_owned()),
1076        env: Some(environment.clone()),
1077        rows: 24,
1078        cols: STREAM_COLS,
1079    };
1080    let value = spec.to_value().map_err(internal)?;
1081    terminal.spawn(&value)
1082}
1083
1084fn internal(error: impl std::fmt::Display) -> ProviderError {
1085    refuse(Status::GUATIAO_ERR_INTERNAL, error)
1086}
1087
1088fn refuse(status: Status, error: impl std::fmt::Display) -> ProviderError {
1089    ProviderError::new(status, &error.to_string())
1090}
1091
1092/// What this handler applies of a loadout: none of it, and why.
1093fn loadout_support() -> LoadoutSupport {
1094    LoadoutSupport::none(
1095        "agy's stdio MCP servers and its `--sandbox` are not measured against agy 1.4.12: only the \
1096         URL servers of its `mcp_config.json` are, so AI6 hands it none of a loadout",
1097    )
1098}
1099
1100#[cfg(test)]
1101mod record_tests {
1102    use super::*;
1103
1104    #[test]
1105    fn every_part_of_the_options_is_unknown_with_the_reason_and_none_is_declared_unsupported() {
1106        let options = AntigravityHandler::try_from(AntigravityConfig::default())
1107            .unwrap()
1108            .start_options(BTreeMap::new())
1109            .unwrap();
1110        assert_eq!(options, StartOptions::unknown(UNMEASURED_OPTIONS));
1111        assert!(!options.any_known());
1112    }
1113
1114    #[test]
1115    fn a_conversations_transcript_is_found_under_its_home() {
1116        let home = tempfile::tempdir().unwrap();
1117        let brain = home
1118            .path()
1119            .join(".gemini")
1120            .join("antigravity-cli")
1121            .join("brain")
1122            .join("c-1");
1123        std::fs::create_dir_all(&brain).unwrap();
1124        std::fs::write(brain.join("transcript.jsonl"), "{}\n").unwrap();
1125        let query = |conversation: &str| RunRecordQuery {
1126            run_id: conversation.to_owned(),
1127            working_directory: "/work".to_owned(),
1128            environment: BTreeMap::from([(
1129                "HOME".to_owned(),
1130                home.path().to_string_lossy().into_owned(),
1131            )]),
1132        };
1133        let found = antigravity_record(&query("c-1")).unwrap();
1134        assert_eq!(
1135            std::path::PathBuf::from(found.path),
1136            brain.join("transcript.jsonl")
1137        );
1138        assert_eq!(found.format, RECORD_FORMAT);
1139        assert!(antigravity_record(&query("c-2")).is_none());
1140        assert!(antigravity_record(&query("..")).is_none());
1141    }
1142}