1#![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
35const UNMEASURED_OPTIONS: &str =
37 "the Antigravity CLI's `agy acp` describe is not measured, so its options are not listed";
38
39#[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#[derive(Debug, Clone, ToValue, FromValue, Schema)]
89#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
90pub struct AntigravityConfig {
91 #[map(default = String::from("agy"))]
93 pub executable: String,
94 #[map(default = 64 * 1024 * 1024)]
97 pub json_line_bytes: u64,
98 #[map(default = 64)]
100 pub csi_bytes: u64,
101 #[map(default = 8)]
103 pub tail_lines: u64,
104 #[map(default = 512)]
106 pub tail_line_bytes: u64,
107 #[map(default = 2_000)]
109 pub close_wait_ms: u64,
110 #[map(default = 1_000)]
112 pub exit_wait_ms: u64,
113 #[map(default = 1024 * 1024)]
116 pub context_file_bytes: u64,
117 #[map(default = 60)]
120 pub gate_timeout_secs: u64,
121 #[map(default = 0)]
124 pub mcp_timeout_secs: i64,
125 #[map(default = 20_000)]
129 pub usage_wait_ms: u64,
130 #[schema(section = "agent")]
134 #[map(default)]
135 pub allowed_tools: Vec<String>,
136 #[schema(section = "agent")]
139 #[map(default)]
140 pub denied_tools: Vec<String>,
141 #[schema(section = "agent")]
144 #[map(with = ::ai6::guatiao_serde::adapt::object, default)]
145 pub settings: AgySettingsExtras,
146 #[schema(section = "agent")]
149 #[map(default)]
150 pub auto_update: bool,
151 #[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#[derive(Debug, Clone)]
182struct AntigravitySettings {
183 allowed_tools: Vec<String>,
187 denied_tools: Vec<String>,
190 settings: AgySettingsExtras,
193 auto_update: bool,
196 limit_phrases: Vec<String>,
198}
199
200const RESERVED_SETTINGS: [&str; 5] = [
203 "permissions",
204 "toolPermission",
205 "agentMode",
206 "trustedWorkspaces",
207 "allowNonWorkspaceAccess",
208];
209
210fn 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
249fn 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
263const COMMAND_TOOL: &str = "run_command";
265const COMMAND_ACTION: &str = "command";
266
267const READ_TOOLS: [&str; 4] = ["read_file", "grep_search", "find_by_name", "list_dir"];
270
271const EDIT_TOOLS: [&str; 2] = ["write_file", "edit_file"];
273
274const PROTECTED_DIRECTORIES: [&str; 3] = [".git", ".agents", ".agent"];
278
279const 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#[derive(Debug, Default)]
296struct Plan {
297 tools: Vec<String>,
298 inherit_mcp: bool,
299 allow: Vec<String>,
300 deny: Vec<String>,
301 servers: Vec<(String, String)>,
303 endpoints: BTreeMap<String, String>,
305 restriction: Option<Restriction>,
306 gate: bool,
307}
308
309struct 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#[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
358pub const RECORD_FORMAT: &str = "antigravity-jsonl";
360
361fn 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 fn assistant_network(&self) -> Result<Option<String>, ProviderError> {
384 Ok(None)
385 }
386
387 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 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 fn loadout_support(&self) -> Result<LoadoutSupport, ProviderError> {
410 Ok(loadout_support())
411 }
412
413 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 fn usage_support(&self) -> Result<UsageSupport, ProviderError> {
427 Ok(UsageSupport::new(vec![UsageSource::Reported], true))
428 }
429
430 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 fn run_record(&self, query: RunRecordQuery) -> Result<Option<RunRecordFile>, ProviderError> {
452 Ok(antigravity_record(&query))
453 }
454
455 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 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 if let Some(message) = request.message {
608 operation.hold(message)?;
609 }
610 Ok(operation.into_object())
611 }
612}
613
614impl AntigravityHandler {
615 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 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 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 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 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 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 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 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 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
946const AUTO_UPDATE_OFF_ENV: &str = "AGY_CLI_DISABLE_AUTO_UPDATE";
948
949const RESTRICTED_DENIED: [&str; 4] = [
951 "write_file(*)",
952 "command(*)",
953 "read_url(*)",
954 "execute_url(*)",
955];
956
957const ASSISTANT_TOOLS: [&str; 5] = [
960 "read_file",
961 "call_mcp_tool",
962 "list_resources",
963 "read_resource",
964 "manage_task",
965];
966
967fn 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
987fn rule_runs_commands(rule: &str) -> bool {
989 rule == COMMAND_TOOL || rule.starts_with("command(")
990}
991
992fn 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
1021fn 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
1038fn 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
1052fn shell_quote(word: &str) -> String {
1054 format!("'{}'", word.replace('\'', "'\\''"))
1055}
1056
1057fn 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
1092fn 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}