1use std::{
8 collections::BTreeMap,
9 ffi::OsString,
10 path::{Path, PathBuf},
11 sync::{
12 Mutex, OnceLock,
13 atomic::{AtomicU64, Ordering},
14 },
15 time::{Duration, Instant, SystemTime},
16};
17
18use serde::{Deserialize, Serialize};
19use sha2::{Digest, Sha256};
20use tokio_util::sync::CancellationToken;
21
22use crate::{
23 auth::storage::{Storage, Tokens},
24 llm::models::ListedModel,
25 platform, process,
26};
27
28use super::{
29 AgentId, ConfigOption, Problem,
30 trust::{self, LauncherFingerprint},
31 wire::{Connection, INITIALIZE_TIMEOUT},
32};
33
34const AGENTS_FILE: &str = "agents.json";
35const AGENTS_LOCK: &str = "agents";
36const SECRETS_FILE: &str = "secrets.json";
37const SECRETS_LOCK: &str = "secrets";
38const AGENTS_SCHEMA_VERSION: u32 = 1;
39pub const DEFAULT_REGISTRY_URL: &str =
41 "https://raw.githubusercontent.com/agentclientprotocol/registry/main/registry.json";
42const REGISTRY_URL_ENV: &str = "ARTIFACTIZE_ACP_REGISTRY_URL";
44pub const PROBE_CACHE_TTL: Duration = Duration::from_secs(2 * 60);
46pub const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
48const REGISTRY_FETCH_TIMEOUT: Duration = Duration::from_secs(30);
50const MAX_SECRET_VALUE_BYTES: usize = 16 * 1024;
52const MAX_REGISTRY_ARTIFACT_BYTES: usize = 256 * 1024 * 1024;
54pub const ANTIGRAVITY_MINIMUM: semver::Version = semver::Version::new(1, 5, 1);
56
57pub(crate) const ANTIGRAVITY_ALTERNATE_AUTH: &[&str] = &[
59 "GEMINI_API_KEY",
60 "GOOGLE_API_KEY",
61 "GOOGLE_APPLICATION_CREDENTIALS",
62 "GOOGLE_GENAI_USE_VERTEXAI",
63];
64
65static AUTH_GENERATION: AtomicU64 = AtomicU64::new(1);
66
67pub fn bump_auth_generation() -> u64 {
69 AUTH_GENERATION.fetch_add(1, Ordering::SeqCst) + 1
70}
71
72pub fn auth_generation() -> u64 {
73 AUTH_GENERATION.load(Ordering::SeqCst)
74}
75
76#[derive(Debug, Clone)]
78pub struct Preset {
79 pub id: &'static str,
80 pub display_name: &'static str,
81 pub program: &'static str,
82 pub args: &'static [&'static str],
83 pub version_args: &'static [&'static str],
84 pub minimum_version: Option<semver::Version>,
85 pub env_denylist: &'static [&'static str],
86 pub extra_env: &'static [(&'static str, &'static str)],
87 pub mcp_stdio: bool,
88 pub supports_same_child_load: bool,
89 pub can_disable_project_config: bool,
90 pub native_sandbox_note: &'static str,
91 pub hide_always_options: bool,
92 pub install_hint: &'static str,
93 pub login_action: &'static str,
94}
95
96pub const PRESETS: &[Preset] = &[
98 Preset {
99 id: "antigravity",
100 display_name: "Antigravity",
101 program: "agy",
102 args: &["acp"],
103 version_args: &["--version"],
104 minimum_version: Some(ANTIGRAVITY_MINIMUM),
105 env_denylist: ANTIGRAVITY_ALTERNATE_AUTH,
106 extra_env: &[("AGY_CLI_DISABLE_AUTO_UPDATE", "1")],
107 mcp_stdio: true,
108 supports_same_child_load: true,
109 can_disable_project_config: true,
110 native_sandbox_note: "Runs natively in the worktree via `agy acp`; ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
111 hide_always_options: false,
112 install_hint: "Install the Antigravity CLI (`agy`), then sign in via `artifactize login antigravity` or Settings → Chat Agents.",
113 login_action: "artifactize login antigravity",
114 },
115 Preset {
116 id: "claude-acp",
117 display_name: "Claude ACP",
118 program: "claude-agent-acp",
119 args: &[],
120 version_args: &["--version"],
121 minimum_version: None,
122 env_denylist: &[],
123 extra_env: &[],
124 mcp_stdio: true,
125 supports_same_child_load: true,
126 can_disable_project_config: false,
127 native_sandbox_note: "Runs Claude Code's native harness via ACP in the worktree; may read repository `.claude/` settings and hooks on startup. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
128 hide_always_options: false,
129 install_hint: "Install `claude-agent-acp` (or install from Settings → Chat Agents → Browse Registry) and sign in with `claude auth login`.",
130 login_action: "claude auth login",
131 },
132 Preset {
133 id: "codex-acp",
134 display_name: "Codex ACP",
135 program: "codex-acp",
136 args: &[],
137 version_args: &["--version"],
138 minimum_version: None,
139 env_denylist: &[],
140 extra_env: &[],
141 mcp_stdio: true,
142 supports_same_child_load: true,
143 can_disable_project_config: false,
144 native_sandbox_note: "Runs Codex's native harness via ACP in the worktree; native sandbox/approval modes are exposed via `configOptions`. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
145 hide_always_options: false,
146 install_hint: "Install `codex-acp` (or install from Settings → Chat Agents → Browse Registry) and sign in with Codex.",
147 login_action: "codex login",
148 },
149 Preset {
150 id: "gemini-cli",
151 display_name: "Gemini CLI",
152 program: "gemini",
153 args: &["--experimental-acp"],
154 version_args: &["--version"],
155 minimum_version: None,
156 env_denylist: &[],
157 extra_env: &[],
158 mcp_stdio: true,
159 supports_same_child_load: true,
160 can_disable_project_config: false,
161 native_sandbox_note: "Runs Gemini CLI natively via ACP in the worktree; may read `.gemini/settings.json` on startup. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
162 hide_always_options: false,
163 install_hint: "Install Gemini CLI (`gemini`) and complete its login in a terminal.",
164 login_action: "gemini",
165 },
166 Preset {
167 id: "opencode",
168 display_name: "OpenCode",
169 program: "opencode",
170 args: &["acp"],
171 version_args: &["--version"],
172 minimum_version: None,
173 env_denylist: &[],
174 extra_env: &[],
175 mcp_stdio: true,
176 supports_same_child_load: true,
177 can_disable_project_config: false,
178 native_sandbox_note: "Runs OpenCode natively via ACP in the worktree; may read `opencode.json` on startup. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
179 hide_always_options: false,
180 install_hint: "Install OpenCode (`opencode`) and configure its credentials.",
181 login_action: "opencode auth login",
182 },
183 Preset {
184 id: "copilot",
185 display_name: "GitHub Copilot",
186 program: "copilot",
187 args: &["--acp"],
188 version_args: &["--version"],
189 minimum_version: None,
190 env_denylist: &[],
191 extra_env: &[],
192 mcp_stdio: true,
193 supports_same_child_load: true,
194 can_disable_project_config: false,
195 native_sandbox_note: "Runs GitHub Copilot CLI natively via ACP in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
196 hide_always_options: true,
197 install_hint: "Install GitHub Copilot CLI (`copilot`) and sign in with GitHub.",
198 login_action: "copilot auth login",
199 },
200 Preset {
201 id: "cursor",
202 display_name: "Cursor Agent",
203 program: "cursor-agent",
204 args: &["acp"],
205 version_args: &["--version"],
206 minimum_version: None,
207 env_denylist: &[],
208 extra_env: &[],
209 mcp_stdio: true,
210 supports_same_child_load: true,
211 can_disable_project_config: false,
212 native_sandbox_note: "Runs Cursor Agent natively via ACP in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
213 hide_always_options: true,
214 install_hint: "Install Cursor Agent (`cursor-agent`) and sign in.",
215 login_action: "cursor-agent login",
216 },
217 Preset {
218 id: "goose",
219 display_name: "Goose",
220 program: "goose",
221 args: &["acp"],
222 version_args: &["--version"],
223 minimum_version: None,
224 env_denylist: &[],
225 extra_env: &[],
226 mcp_stdio: true,
227 supports_same_child_load: true,
228 can_disable_project_config: false,
229 native_sandbox_note: "Runs Goose natively via ACP in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
230 hide_always_options: true,
231 install_hint: "Install Goose (`goose`) and run `goose configure`.",
232 login_action: "goose configure",
233 },
234];
235
236pub fn preset_by_id(id: &str) -> Option<&'static Preset> {
237 PRESETS.iter().find(|preset| preset.id == id)
238}
239
240pub fn is_builtin_preset(id: &str) -> bool {
241 preset_by_id(id).is_some()
242}
243
244pub fn is_chat_agent(name: &str, state: Option<&Path>, repo: Option<&Path>) -> bool {
247 if is_builtin_preset(name) {
248 return true;
249 }
250 list_custom(state, repo)
251 .map(|agents| agents.iter().any(|agent| agent.id.as_str() == name))
252 .unwrap_or(false)
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub enum DistributionKind {
259 Binary,
260 Archive,
261 Npx,
262 Uvx,
263}
264
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "camelCase")]
268pub struct RegistryInstallSpec {
269 pub registry_id: AgentId,
270 pub display_name: String,
271 pub exact_version: String,
272 pub platform: String,
273 pub distribution_kind: DistributionKind,
274 pub package_or_url: String,
275 #[serde(default)]
276 pub args: Vec<String>,
277 #[serde(default)]
278 pub env_pairs: BTreeMap<String, String>,
279 #[serde(default)]
280 pub build_scripts_allowed: bool,
281 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub artifact_sha256: Option<String>,
283 #[serde(default)]
285 pub allow_unsigned_digest: bool,
286}
287
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290#[serde(rename_all = "camelCase")]
291pub struct RegistryEntry {
292 pub id: AgentId,
293 pub name: String,
294 pub version: String,
295 #[serde(default)]
296 pub description: String,
297 pub spec: RegistryInstallSpec,
298}
299
300#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(rename_all = "camelCase")]
303pub enum AgentTier {
304 Preset,
305 Registry,
306 Custom,
307}
308
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(rename_all = "camelCase")]
312pub struct CustomAgent {
313 pub id: AgentId,
314 pub name: String,
315 pub command: String,
316 #[serde(default)]
317 pub args: Vec<String>,
318 #[serde(default)]
319 pub env: BTreeMap<String, String>,
320 #[serde(default)]
322 pub secret_env_keys: Vec<String>,
323 #[serde(default = "default_true")]
324 pub mcp_stdio: bool,
325 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub registry: Option<RegistryInstallSpec>,
327 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub entrypoint_sha256: Option<String>,
329}
330
331fn default_true() -> bool {
332 true
333}
334
335#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(transparent)]
338pub struct SecretEnvValue(String);
339
340impl SecretEnvValue {
341 pub fn parse(raw: &str) -> Result<Self, String> {
342 if raw.is_empty() || raw.len() > MAX_SECRET_VALUE_BYTES {
343 return Err(format!(
344 "Secret environment value must be 1–{MAX_SECRET_VALUE_BYTES} bytes."
345 ));
346 }
347 if raw.bytes().any(|byte| byte == 0) {
348 return Err("Secret environment value cannot contain NUL bytes.".into());
349 }
350 Ok(Self(raw.to_owned()))
351 }
352
353 pub(crate) fn expose(&self) -> &str {
354 &self.0
355 }
356}
357
358impl std::fmt::Debug for SecretEnvValue {
359 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360 formatter.write_str("SecretEnvValue(…)")
361 }
362}
363
364#[derive(Debug, Clone)]
366pub struct AgentSpec {
367 pub id: AgentId,
368 pub name: String,
369 pub tier: AgentTier,
370 pub program: String,
371 pub args: Vec<String>,
372 pub version_args: Vec<String>,
373 pub minimum_version: Option<semver::Version>,
374 pub env_denylist: Vec<String>,
375 pub extra_env: BTreeMap<String, String>,
376 pub secret_env: BTreeMap<String, SecretEnvValue>,
377 pub mcp_stdio: bool,
378 pub supports_same_child_load: bool,
379 pub reject_worktree_executable: bool,
380 pub hide_always_options: bool,
381 pub native_sandbox_note: String,
382 pub can_disable_project_config: bool,
383 pub install_hint: String,
384 pub login_action: String,
385}
386
387impl AgentSpec {
388 pub fn from_preset(preset: &Preset) -> Self {
389 Self {
390 id: preset.id.parse().expect("built-in preset id is valid"),
391 name: preset.display_name.to_owned(),
392 tier: AgentTier::Preset,
393 program: preset.program.to_owned(),
394 args: preset.args.iter().map(|arg| (*arg).to_owned()).collect(),
395 version_args: preset
396 .version_args
397 .iter()
398 .map(|arg| (*arg).to_owned())
399 .collect(),
400 minimum_version: preset.minimum_version.clone(),
401 env_denylist: preset
402 .env_denylist
403 .iter()
404 .map(|name| (*name).to_owned())
405 .collect(),
406 extra_env: preset
407 .extra_env
408 .iter()
409 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
410 .collect(),
411 secret_env: BTreeMap::new(),
412 mcp_stdio: preset.mcp_stdio,
413 supports_same_child_load: preset.supports_same_child_load,
414 reject_worktree_executable: true,
415 hide_always_options: preset.hide_always_options,
416 native_sandbox_note: preset.native_sandbox_note.to_owned(),
417 can_disable_project_config: preset.can_disable_project_config,
418 install_hint: preset.install_hint.to_owned(),
419 login_action: preset.login_action.to_owned(),
420 }
421 }
422
423 pub fn build_env(&self, for_worktree: bool) -> BTreeMap<OsString, OsString> {
428 let mut env = platform::environment::for_command();
429 for (key, value) in &self.extra_env {
430 platform::environment::set(&mut env, key, value);
431 }
432 for (key, secret) in &self.secret_env {
433 platform::environment::set(&mut env, key, secret.expose());
434 }
435 if for_worktree {
436 platform::environment::strip_relative_path_entries(&mut env);
437 }
438 for name in &self.env_denylist {
439 platform::environment::remove(&mut env, name);
440 }
441 env
442 }
443
444 pub fn known_secrets(&self) -> Vec<String> {
446 self.secret_env
447 .values()
448 .map(|secret| secret.expose().to_owned())
449 .collect()
450 }
451}
452
453#[derive(Debug, Clone, Serialize, Deserialize)]
455#[serde(rename_all = "camelCase")]
456pub struct CatalogEntry {
457 pub id: AgentId,
458 pub name: String,
459 pub tier: AgentTier,
460 pub command: String,
461 pub args: Vec<String>,
462 pub env: BTreeMap<String, String>,
463 pub secret_env_keys: Vec<String>,
464 pub mcp_stdio: bool,
465 pub can_disable_project_config: bool,
466 pub native_sandbox_note: String,
467 pub login_action: String,
468 pub install_hint: String,
469 #[serde(default, skip_serializing_if = "Option::is_none")]
470 pub registry: Option<RegistryInstallSpec>,
471}
472
473#[derive(Debug, Clone, Serialize, Deserialize)]
475#[serde(
476 tag = "kind",
477 rename_all = "camelCase",
478 rename_all_fields = "camelCase"
479)]
480pub enum AgentAvailability {
481 Ready {
482 #[serde(with = "crate::platform::path_serde")]
483 executable: PathBuf,
484 version: Option<String>,
485 models: Vec<ListedModel>,
486 config_options: Vec<ConfigOption>,
487 },
488 NotSetUp {
489 #[serde(with = "crate::platform::path_serde::option")]
490 executable: Option<PathBuf>,
491 version: Option<String>,
492 reason: String,
493 login_action: String,
494 },
495 Missing {
496 reason: String,
497 },
498 TooOld {
499 #[serde(with = "crate::platform::path_serde")]
500 executable: PathBuf,
501 version: String,
502 required_version: String,
503 reason: String,
504 },
505 Failed {
506 #[serde(with = "crate::platform::path_serde::option")]
507 executable: Option<PathBuf>,
508 version: Option<String>,
509 error: String,
510 },
511}
512
513#[derive(Debug, Serialize, Deserialize)]
514#[serde(rename_all = "camelCase")]
515struct SavedAgents {
516 version: u32,
517 #[serde(default)]
518 agents: Vec<CustomAgent>,
519}
520
521impl Default for SavedAgents {
522 fn default() -> Self {
523 Self {
524 version: AGENTS_SCHEMA_VERSION,
525 agents: Vec::new(),
526 }
527 }
528}
529
530#[derive(Debug, Default, Serialize, Deserialize)]
531#[serde(rename_all = "camelCase")]
532struct SavedSecrets {
533 #[serde(default)]
534 by_agent: BTreeMap<String, BTreeMap<String, SecretEnvValue>>,
535}
536
537pub fn list_custom(state: Option<&Path>, repo: Option<&Path>) -> Result<Vec<CustomAgent>, String> {
539 let storage = Storage::inspect(state, repo, Tokens::ChatAgents)?;
540 Ok(storage
541 .read::<SavedAgents>(AGENTS_FILE)?
542 .unwrap_or_default()
543 .agents)
544}
545
546pub fn list_catalog(
548 state: Option<&Path>,
549 repo: Option<&Path>,
550) -> Result<Vec<CatalogEntry>, String> {
551 let mut entries: Vec<CatalogEntry> = PRESETS
552 .iter()
553 .map(|preset| CatalogEntry {
554 id: preset.id.parse().expect("preset id is valid"),
555 name: preset.display_name.to_owned(),
556 tier: AgentTier::Preset,
557 command: preset.program.to_owned(),
558 args: preset.args.iter().map(|arg| (*arg).to_owned()).collect(),
559 env: BTreeMap::new(),
560 secret_env_keys: Vec::new(),
561 mcp_stdio: preset.mcp_stdio,
562 can_disable_project_config: preset.can_disable_project_config,
563 native_sandbox_note: preset.native_sandbox_note.to_owned(),
564 login_action: preset.login_action.to_owned(),
565 install_hint: preset.install_hint.to_owned(),
566 registry: None,
567 })
568 .collect();
569 for custom in list_custom(state, repo)? {
570 let tier = if custom.registry.is_some() {
571 AgentTier::Registry
572 } else {
573 AgentTier::Custom
574 };
575 entries.push(CatalogEntry {
576 id: custom.id,
577 name: custom.name,
578 tier,
579 command: custom.command,
580 args: custom.args,
581 env: custom.env,
582 secret_env_keys: custom.secret_env_keys,
583 mcp_stdio: custom.mcp_stdio,
584 can_disable_project_config: false,
585 native_sandbox_note: "Custom ACP agent running natively in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).".into(),
586 login_action: String::new(),
587 install_hint: String::new(),
588 registry: custom.registry,
589 });
590 }
591 Ok(entries)
592}
593
594pub fn resolve_spec(
597 agent_id: &AgentId,
598 state: Option<&Path>,
599 repo: Option<&Path>,
600) -> Result<AgentSpec, String> {
601 if let Some(preset) = preset_by_id(agent_id.as_str()) {
602 return Ok(AgentSpec::from_preset(preset));
603 }
604 let custom = list_custom(state, repo)?
605 .into_iter()
606 .find(|agent| &agent.id == agent_id)
607 .ok_or_else(|| format!("No ACP Chat agent named {agent_id:?} is configured."))?;
608 let secret_storage = Storage::inspect(state, repo, Tokens::ChatSecrets)?;
609 let secret_env = secret_storage
610 .read::<SavedSecrets>(SECRETS_FILE)?
611 .unwrap_or_default()
612 .by_agent
613 .remove(agent_id.as_str())
614 .unwrap_or_default();
615 let tier = if custom.registry.is_some() {
616 AgentTier::Registry
617 } else {
618 AgentTier::Custom
619 };
620 Ok(AgentSpec {
621 id: custom.id,
622 name: custom.name,
623 tier,
624 program: custom.command,
625 args: custom.args,
626 version_args: vec!["--version".into()],
627 minimum_version: None,
628 env_denylist: Vec::new(),
629 extra_env: custom.env,
630 secret_env,
631 mcp_stdio: custom.mcp_stdio,
632 supports_same_child_load: true,
633 reject_worktree_executable: false,
634 hide_always_options: false,
635 native_sandbox_note: "Custom ACP agent running natively in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).".into(),
636 can_disable_project_config: false,
637 install_hint: String::new(),
638 login_action: String::new(),
639 })
640}
641
642pub async fn save_custom_agent(
644 state: Option<&Path>,
645 repo: Option<&Path>,
646 mut agent: CustomAgent,
647 set_secrets: BTreeMap<String, SecretEnvValue>,
648 remove_secret_keys: &[String],
649) -> Result<CustomAgent, String> {
650 if is_builtin_preset(agent.id.as_str()) {
651 return Err(format!(
652 "{} is a built-in ACP preset and cannot be shadowed by a custom agent.",
653 agent.id
654 ));
655 }
656 if agent.name.trim().is_empty() {
657 return Err("Custom ACP agent display name cannot be empty.".into());
658 }
659 if agent.command.trim().is_empty() {
660 return Err("Custom ACP agent command cannot be empty.".into());
661 }
662 let secrets_storage = Storage::new(state, repo, Tokens::ChatSecrets)?;
663 let _secrets_lock = secrets_storage.lock(SECRETS_LOCK).await?;
664 let mut secrets: SavedSecrets = secrets_storage.read(SECRETS_FILE)?.unwrap_or_default();
665 let agent_secrets = secrets
666 .by_agent
667 .entry(agent.id.as_str().to_owned())
668 .or_default();
669 for key in remove_secret_keys {
670 agent_secrets.remove(key);
671 }
672 for (key, value) in set_secrets {
673 agent_secrets.insert(key, value);
674 }
675 agent.secret_env_keys = agent_secrets.keys().cloned().collect();
676 secrets_storage.save(SECRETS_FILE, &secrets)?;
677
678 let agents_storage = Storage::new(state, repo, Tokens::ChatAgents)?;
679 let _agents_lock = agents_storage.lock(AGENTS_LOCK).await?;
680 let mut saved: SavedAgents = agents_storage.read(AGENTS_FILE)?.unwrap_or_default();
681 saved.agents.retain(|existing| existing.id != agent.id);
682 saved.agents.push(agent.clone());
683 agents_storage.save(AGENTS_FILE, &saved)?;
684 invalidate_probe_cache(&agent.id);
685 Ok(agent)
686}
687
688pub async fn remove_custom_agent(
690 state: Option<&Path>,
691 repo: Option<&Path>,
692 id: &AgentId,
693) -> Result<bool, String> {
694 if is_builtin_preset(id.as_str()) {
695 return Err(format!(
696 "{id} is a built-in ACP preset and cannot be removed."
697 ));
698 }
699 let agents_storage = Storage::new(state, repo, Tokens::ChatAgents)?;
700 let _agents_lock = agents_storage.lock(AGENTS_LOCK).await?;
701 let mut saved: SavedAgents = agents_storage.read(AGENTS_FILE)?.unwrap_or_default();
702 let before = saved.agents.len();
703 saved.agents.retain(|existing| &existing.id != id);
704 let removed = saved.agents.len() != before;
705 if removed {
706 agents_storage.save(AGENTS_FILE, &saved)?;
707 }
708
709 let secrets_storage = Storage::new(state, repo, Tokens::ChatSecrets)?;
710 let _secrets_lock = secrets_storage.lock(SECRETS_LOCK).await?;
711 let mut secrets: SavedSecrets = secrets_storage.read(SECRETS_FILE)?.unwrap_or_default();
712 if secrets.by_agent.remove(id.as_str()).is_some() {
713 secrets_storage.save(SECRETS_FILE, &secrets)?;
714 }
715 invalidate_probe_cache(id);
716 Ok(removed)
717}
718
719#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
720struct ProbeCacheKey {
721 agent_id: AgentId,
722 resolved_executable: PathBuf,
723 args_hash: String,
724 mtime_secs: Option<u64>,
725 auth_generation: u64,
726}
727
728struct CachedProbe {
729 recorded_at: Instant,
730 availability: AgentAvailability,
731}
732
733fn probe_cache() -> &'static Mutex<BTreeMap<ProbeCacheKey, CachedProbe>> {
734 static CACHE: OnceLock<Mutex<BTreeMap<ProbeCacheKey, CachedProbe>>> = OnceLock::new();
735 CACHE.get_or_init(Mutex::default)
736}
737
738pub fn invalidate_probe_cache(agent_id: &AgentId) {
739 if let Ok(mut cache) = probe_cache().lock() {
740 cache.retain(|key, _| &key.agent_id != agent_id);
741 }
742}
743
744pub async fn probe_agent(
747 agent_id: &AgentId,
748 state: Option<&Path>,
749 repo: Option<&Path>,
750 force_refresh: bool,
751) -> AgentAvailability {
752 let spec = match resolve_spec(agent_id, state, repo) {
753 Ok(spec) => spec,
754 Err(error) => {
755 return AgentAvailability::Failed {
756 executable: None,
757 version: None,
758 error,
759 };
760 }
761 };
762 probe_spec(&spec, force_refresh).await
763}
764
765pub async fn probe_spec(spec: &AgentSpec, force_refresh: bool) -> AgentAvailability {
766 let probe_dir = match platform::private_tempdir_in(
767 "artifactize-acp-probe-",
768 &platform::temporary_directory(),
769 ) {
770 Ok(dir) => dir,
771 Err(error) => {
772 return AgentAvailability::Failed {
773 executable: None,
774 version: None,
775 error: format!("Cannot create ACP probe directory: {error}."),
776 };
777 }
778 };
779 let program_path = match platform::program_path(&spec.program) {
780 Ok(path) => path,
781 Err(error) => {
782 return AgentAvailability::Failed {
783 executable: None,
784 version: None,
785 error: format!("Invalid ACP command {:?}: {error}.", spec.program),
786 };
787 }
788 };
789 let resolved = match platform::program::resolve(&program_path, probe_dir.path()) {
790 Ok(path) => platform::canonicalize(&path).unwrap_or(path),
791 Err(_) => {
792 return AgentAvailability::Missing {
793 reason: if spec.install_hint.is_empty() {
794 format!("Executable {:?} is not on PATH.", spec.program)
795 } else {
796 format!(
797 "{} (`{}`) is not on PATH. {}",
798 spec.name, spec.program, spec.install_hint
799 )
800 },
801 };
802 }
803 };
804 let mtime_secs = std::fs::metadata(&resolved)
805 .ok()
806 .and_then(|meta| meta.modified().ok())
807 .and_then(|modified| modified.duration_since(SystemTime::UNIX_EPOCH).ok())
808 .map(|duration| duration.as_secs());
809 let cache_key = ProbeCacheKey {
810 agent_id: spec.id.clone(),
811 resolved_executable: resolved.clone(),
812 args_hash: trust::hash_args(&spec.args),
813 mtime_secs,
814 auth_generation: auth_generation(),
815 };
816 if !force_refresh
817 && let Ok(cache) = probe_cache().lock()
818 && let Some(entry) = cache.get(&cache_key)
819 && entry.recorded_at.elapsed() < PROBE_CACHE_TTL
820 {
821 return entry.availability.clone();
822 }
823
824 let availability = run_live_probe(spec, &resolved, probe_dir.path()).await;
825 if let Ok(mut cache) = probe_cache().lock() {
826 cache.insert(
827 cache_key,
828 CachedProbe {
829 recorded_at: Instant::now(),
830 availability: availability.clone(),
831 },
832 );
833 }
834 availability
835}
836
837async fn run_live_probe(
838 spec: &AgentSpec,
839 executable: &Path,
840 probe_dir: &Path,
841) -> AgentAvailability {
842 let cancel = CancellationToken::new();
843 let deadline = tokio::time::Instant::now() + PROBE_TIMEOUT;
844
845 let detected_version = probe_version(spec, executable, probe_dir, deadline, &cancel).await;
846 if let Some(minimum) = &spec.minimum_version {
847 match &detected_version {
848 None => {
849 return AgentAvailability::Failed {
850 executable: Some(executable.to_path_buf()),
851 version: None,
852 error: format!(
853 "Cannot read the {} CLI version; requires {minimum} or newer.",
854 spec.name
855 ),
856 };
857 }
858 Some(found) if found < minimum => {
859 return AgentAvailability::TooOld {
860 executable: executable.to_path_buf(),
861 version: found.to_string(),
862 required_version: minimum.to_string(),
863 reason: format!(
864 "{} {found} is too old; update to {minimum} or newer.",
865 spec.name
866 ),
867 };
868 }
869 Some(_) => {}
870 }
871 }
872
873 let mut args: Vec<OsString> = spec.args.iter().map(OsString::from).collect();
874 if spec.id.as_str() == "antigravity" {
876 args.push("--sandbox".into());
877 args.push("--include-default-customizations=false".into());
878 }
879 let command = process::Command {
880 program: executable.as_os_str().to_owned(),
881 args,
882 cwd: probe_dir.to_path_buf(),
883 env: spec.build_env(false),
884 timeout: PROBE_TIMEOUT,
885 };
886 let process_cancel = CancellationToken::new();
887 let mut child = match process::spawn_supervised(&command, &process_cancel).await {
888 Ok(child) => child,
889 Err(error) => {
890 return AgentAvailability::Failed {
891 executable: Some(executable.to_path_buf()),
892 version: detected_version.map(|v| v.to_string()),
893 error: format!("Cannot start {}: {error}.", spec.name),
894 };
895 }
896 };
897 let stdout = child.stdout().take().expect("probe stdout piped");
898 let stdin = child.stdin().take().expect("probe stdin piped");
899 let mut stderr = child.stderr().take().expect("probe stderr piped");
900 let stderr_task = tokio::spawn(async move { read_bounded_stderr(&mut stderr).await });
901 let mut conn = Connection::new(
902 &spec.name,
903 &spec.install_hint,
904 stdout,
905 stdin,
906 spec.hide_always_options,
907 spec.known_secrets(),
908 );
909 let result = tokio::time::timeout(PROBE_TIMEOUT, conn.inspect_models(probe_dir))
910 .await
911 .unwrap_or_else(|_| {
912 Err(Problem::Failed(format!(
913 "{} did not answer the ACP probe in time.",
914 spec.name
915 )))
916 });
917 drop(conn);
918 let _ = process::terminate(&mut child).await;
919 let _ = child.cleanup().await;
920 let stderr_bytes = crate::task::joined(stderr_task.await).unwrap_or_default();
921 let stderr_text = platform::output_text(&stderr_bytes);
922
923 let version_str = detected_version.map(|v| v.to_string());
924 match result {
925 Ok((models, config_options)) => AgentAvailability::Ready {
926 executable: executable.to_path_buf(),
927 version: version_str,
928 models,
929 config_options,
930 },
931 Err(problem) => {
932 let classified = if stderr_text.contains(super::wire::AUTH_LINK_MARKER) {
933 Problem::SignedOut {
934 agent: spec.name.clone(),
935 hint: spec.install_hint.clone(),
936 }
937 } else if matches!(problem, Problem::Failed(_)) {
938 Problem::classify_text(&spec.name, &spec.install_hint, &stderr_text)
939 .unwrap_or(problem)
940 } else {
941 problem
942 };
943 match classified {
944 Problem::SignedOut { .. } => AgentAvailability::NotSetUp {
945 executable: Some(executable.to_path_buf()),
946 version: version_str,
947 reason: format!("Sign in to {}.", spec.name),
948 login_action: spec.login_action.clone(),
949 },
950 other => AgentAvailability::Failed {
951 executable: Some(executable.to_path_buf()),
952 version: version_str,
953 error: crate::agent::error::Failure::from(other).message,
954 },
955 }
956 }
957 }
958}
959
960const PROBE_STDERR_LIMIT: usize = 64 * 1024;
962const PROBE_STDERR_CHUNK: usize = 4 * 1024;
963
964pub(crate) async fn read_bounded_stderr(stderr: &mut tokio::process::ChildStderr) -> Vec<u8> {
965 use tokio::io::AsyncReadExt;
966 let mut kept = Vec::new();
967 let mut buf = [0u8; PROBE_STDERR_CHUNK];
968 while let Ok(count) = stderr.read(&mut buf).await {
969 if count == 0 {
970 break;
971 }
972 kept.extend_from_slice(&buf[..count]);
973 if kept.len() > PROBE_STDERR_LIMIT {
974 kept.drain(..kept.len() - PROBE_STDERR_LIMIT);
975 }
976 }
977 kept
978}
979
980async fn probe_version(
981 spec: &AgentSpec,
982 executable: &Path,
983 probe_dir: &Path,
984 deadline: tokio::time::Instant,
985 cancel: &CancellationToken,
986) -> Option<semver::Version> {
987 if spec.version_args.is_empty() {
988 return None;
989 }
990 let command = process::Command {
991 program: executable.as_os_str().to_owned(),
992 args: spec.version_args.iter().map(OsString::from).collect(),
993 cwd: probe_dir.to_path_buf(),
994 env: spec.build_env(false),
995 timeout: deadline
996 .saturating_duration_since(tokio::time::Instant::now())
997 .min(INITIALIZE_TIMEOUT),
998 };
999 let output = process::run(command, cancel.clone(), |_| async { Ok(()) })
1000 .await
1001 .ok()?;
1002 if !output.status.success() {
1003 return None;
1004 }
1005 let text = platform::output_text(&output.stdout);
1006 text.split_whitespace()
1007 .find_map(|word| semver::Version::parse(word.trim_start_matches('v')).ok())
1008}
1009
1010pub async fn discover_registry() -> Result<Vec<RegistryEntry>, String> {
1012 let url = platform::environment::var_text(REGISTRY_URL_ENV)
1013 .filter(|value| !value.trim().is_empty())
1014 .unwrap_or_else(|| DEFAULT_REGISTRY_URL.to_owned());
1015 let client = reqwest::Client::builder()
1016 .timeout(REGISTRY_FETCH_TIMEOUT)
1017 .redirect(reqwest::redirect::Policy::limited(5))
1018 .build()
1019 .map_err(|error| format!("Cannot build HTTP client for ACP Registry: {error}."))?;
1020 let response = client
1021 .get(&url)
1022 .send()
1023 .await
1024 .map_err(|error| format!("Cannot fetch ACP Registry from {url}: {error}."))?;
1025 if !response.status().is_success() {
1026 return Err(format!(
1027 "ACP Registry returned HTTP {} for {url}.",
1028 response.status()
1029 ));
1030 }
1031 let raw: RawRegistryFeed = response
1032 .json()
1033 .await
1034 .map_err(|error| format!("Cannot parse ACP Registry feed: {error}."))?;
1035 let platform_key = current_platform_key();
1036 let mut entries = Vec::new();
1037 for item in raw.agents {
1038 let Ok(id) = item.id.parse::<AgentId>() else {
1039 continue;
1040 };
1041 if let Some(spec) = resolve_registry_spec(&id, &item, platform_key) {
1042 entries.push(RegistryEntry {
1043 id,
1044 name: item.name,
1045 version: item.version,
1046 description: item.description.unwrap_or_default(),
1047 spec,
1048 });
1049 }
1050 }
1051 Ok(entries)
1052}
1053
1054pub async fn install_registry_agent(
1058 state: Option<&Path>,
1059 repo: Option<&Path>,
1060 spec: RegistryInstallSpec,
1061) -> Result<CustomAgent, String> {
1062 if is_builtin_preset(spec.registry_id.as_str()) {
1063 return Err(format!(
1064 "{} matches a built-in ACP preset and cannot shadow it.",
1065 spec.registry_id
1066 ));
1067 }
1068 if platform::install::is_msix() {
1069 return Err(
1070 "Microsoft Store (MSIX) installations restrict dynamic runtime execution under state directories; install the agent CLI onto PATH instead."
1071 .into(),
1072 );
1073 }
1074 if spec.exact_version.trim().is_empty()
1075 || spec.exact_version.eq_ignore_ascii_case("latest")
1076 || !spec
1077 .exact_version
1078 .bytes()
1079 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'+'))
1080 {
1081 return Err(format!(
1082 "Registry installs require an exact pinned version (got {:?}).",
1083 spec.exact_version
1084 ));
1085 }
1086 let chat_storage = Storage::new(state, repo, Tokens::ChatAgents)?;
1087 let runtimes_root = chat_storage.directory.join("runtimes");
1088 platform::create_private_dir_all(&runtimes_root).map_err(|e| e.to_string())?;
1089 let target_dir = runtimes_root
1090 .join(spec.registry_id.as_str())
1091 .join(&spec.exact_version);
1092 platform::create_private_dir_all(&target_dir).map_err(|e| e.to_string())?;
1093
1094 let entrypoint = match spec.distribution_kind {
1095 DistributionKind::Binary => install_pinned_binary(&spec, &target_dir).await?,
1096 DistributionKind::Archive => {
1097 return Err(
1098 "Archive extraction requires a verified binary or npm/uvx package entrypoint; unpack manually or choose a Binary/Npx/Uvx distribution."
1099 .into(),
1100 );
1101 }
1102 DistributionKind::Npx => install_pinned_npm(&spec, &target_dir).await?,
1103 DistributionKind::Uvx => install_pinned_uv(&spec, &target_dir).await?,
1104 };
1105
1106 verify_tree_no_links(&target_dir)?;
1108 let canonical_target = platform::canonicalize(&target_dir).map_err(|e| e.to_string())?;
1109 let canonical_entry = platform::canonicalize(&entrypoint).map_err(|e| e.to_string())?;
1110 if !platform::is_within(&canonical_entry, &canonical_target) {
1111 return Err(
1112 "Installed ACP runtime entrypoint escaped its pinned runtime directory.".into(),
1113 );
1114 }
1115 let entrypoint_sha256 = trust::hash_executable(&canonical_entry)?;
1116
1117 let agent = CustomAgent {
1118 id: spec.registry_id.clone(),
1119 name: spec.display_name.clone(),
1120 command: platform::path_text(&canonical_entry),
1121 args: spec.args.clone(),
1122 env: spec.env_pairs.clone(),
1123 secret_env_keys: Vec::new(),
1124 mcp_stdio: true,
1125 registry: Some(spec),
1126 entrypoint_sha256: Some(entrypoint_sha256),
1127 };
1128 save_custom_agent(state, repo, agent, BTreeMap::new(), &[]).await
1129}
1130
1131async fn install_pinned_binary(
1132 spec: &RegistryInstallSpec,
1133 target_dir: &Path,
1134) -> Result<PathBuf, String> {
1135 let url = url::Url::parse(&spec.package_or_url)
1136 .map_err(|_| format!("Invalid binary URL {:?}.", spec.package_or_url))?;
1137 if !matches!(url.scheme(), "https" | "http") {
1138 return Err("Registry binary downloads require an http(s) URL.".into());
1139 }
1140 let client = reqwest::Client::builder()
1141 .timeout(REGISTRY_FETCH_TIMEOUT)
1142 .build()
1143 .map_err(|error| format!("Cannot build HTTP client: {error}."))?;
1144 let response = client
1145 .get(url)
1146 .send()
1147 .await
1148 .map_err(|error| format!("Cannot download Registry binary: {error}."))?;
1149 if !response.status().is_success() {
1150 return Err(format!(
1151 "Registry binary download failed with HTTP {}.",
1152 response.status()
1153 ));
1154 }
1155 let bytes = response
1156 .bytes()
1157 .await
1158 .map_err(|error| format!("Cannot read Registry binary bytes: {error}."))?;
1159 if bytes.len() > MAX_REGISTRY_ARTIFACT_BYTES {
1160 return Err("Registry binary exceeds the 256 MiB safety limit.".into());
1161 }
1162 let computed = hex_sha256(&bytes);
1163 match &spec.artifact_sha256 {
1164 Some(expected) if expected.eq_ignore_ascii_case(&computed) => {}
1165 Some(expected) => {
1166 return Err(format!(
1167 "SHA-256 mismatch for {}: expected {expected}, got {computed}.",
1168 spec.registry_id
1169 ));
1170 }
1171 None if spec.allow_unsigned_digest => {}
1172 None => {
1173 return Err(format!(
1174 "Unsigned Registry binary blocked by default. Re-confirm install with computed SHA-256 {computed}."
1175 ));
1176 }
1177 }
1178 let final_path = platform::install_executable(target_dir, spec.registry_id.as_str(), &bytes)
1179 .map_err(|e| format!("Cannot install {}: {e}.", spec.registry_id))?;
1180 Ok(final_path)
1181}
1182
1183async fn install_pinned_npm(
1184 spec: &RegistryInstallSpec,
1185 target_dir: &Path,
1186) -> Result<PathBuf, String> {
1187 let empty_cwd = platform::private_tempdir_in("acp-npm-", &platform::temporary_directory())
1188 .map_err(|e| e.to_string())?;
1189 let mut args = vec![
1190 OsString::from("install"),
1191 OsString::from("--prefix"),
1192 target_dir.as_os_str().to_owned(),
1193 OsString::from("--no-audit"),
1194 OsString::from("--no-fund"),
1195 OsString::from("--save-exact"),
1196 ];
1197 if !spec.build_scripts_allowed {
1198 args.push(OsString::from("--ignore-scripts"));
1199 }
1200 args.push(OsString::from(format!(
1201 "{}@{}",
1202 spec.package_or_url, spec.exact_version
1203 )));
1204 let command = process::Command {
1205 program: OsString::from("npm"),
1206 args,
1207 cwd: empty_cwd.path().to_path_buf(),
1208 env: platform::environment::for_command(),
1209 timeout: Duration::from_secs(120),
1210 };
1211 let output = process::run(command, CancellationToken::new(), |_| async { Ok(()) })
1212 .await
1213 .map_err(|error| format!("Pinned npm install failed: {error}."))?;
1214 if !output.status.success() {
1215 return Err(format!(
1216 "Pinned npm install failed: {}",
1217 platform::output_text(&output.stderr).trim()
1218 ));
1219 }
1220 let bin_dir = target_dir.join("node_modules").join(".bin");
1221 if let Ok(resolved) =
1222 platform::program::resolve(&bin_dir.join(spec.registry_id.as_str()), &bin_dir)
1223 {
1224 Ok(resolved)
1225 } else {
1226 let handle = platform::open_directory(&bin_dir).map_err(|e| e.to_string())?;
1228 let entries = platform::read_dir(&handle).map_err(|e| e.to_string())?;
1229 let mut found = None;
1230 for entry in entries {
1231 let entry = entry.map_err(|e| e.to_string())?;
1232 if let Ok(resolved) =
1233 platform::program::resolve(&bin_dir.join(entry.file_name()), &bin_dir)
1234 {
1235 found = Some(resolved);
1236 break;
1237 }
1238 }
1239 found.ok_or_else(|| {
1240 "Pinned npm install produced no runnable binary in node_modules/.bin.".into()
1241 })
1242 }
1243}
1244
1245async fn install_pinned_uv(
1246 spec: &RegistryInstallSpec,
1247 target_dir: &Path,
1248) -> Result<PathBuf, String> {
1249 let empty_cwd = platform::private_tempdir_in("acp-uv-", &platform::temporary_directory())
1250 .map_err(|e| e.to_string())?;
1251 let venv_dir = target_dir.join("venv");
1252 let create = process::Command {
1253 program: OsString::from("uv"),
1254 args: vec![OsString::from("venv"), venv_dir.as_os_str().to_owned()],
1255 cwd: empty_cwd.path().to_path_buf(),
1256 env: platform::environment::for_command(),
1257 timeout: Duration::from_secs(60),
1258 };
1259 let created = process::run(create, CancellationToken::new(), |_| async { Ok(()) })
1260 .await
1261 .map_err(|error| format!("Cannot create pinned uv venv: {error}."))?;
1262 if !created.status.success() {
1263 return Err(format!(
1264 "uv venv failed: {}",
1265 platform::output_text(&created.stderr).trim()
1266 ));
1267 }
1268 let mut args = vec![
1269 OsString::from("pip"),
1270 OsString::from("install"),
1271 OsString::from("--python"),
1272 venv_dir.as_os_str().to_owned(),
1273 ];
1274 if !spec.build_scripts_allowed {
1275 args.push(OsString::from("--only-binary=:all:"));
1276 }
1277 args.push(OsString::from(format!(
1278 "{}=={}",
1279 spec.package_or_url, spec.exact_version
1280 )));
1281 let install = process::Command {
1282 program: OsString::from("uv"),
1283 args,
1284 cwd: empty_cwd.path().to_path_buf(),
1285 env: platform::environment::for_command(),
1286 timeout: Duration::from_secs(120),
1287 };
1288 let installed = process::run(install, CancellationToken::new(), |_| async { Ok(()) })
1289 .await
1290 .map_err(|error| format!("Pinned uv install failed: {error}."))?;
1291 if !installed.status.success() {
1292 return Err(format!(
1293 "Pinned uv install failed: {}",
1294 platform::output_text(&installed.stderr).trim()
1295 ));
1296 }
1297 let bin_dir = platform::venv_bin_dir(&venv_dir);
1298 platform::program::resolve(&bin_dir.join(spec.registry_id.as_str()), &bin_dir).map_err(|_| {
1299 "Pinned uv install produced no runnable entrypoint in the isolated venv.".into()
1300 })
1301}
1302
1303fn verify_tree_no_links(root: &Path) -> Result<(), String> {
1305 let mut stack = vec![root.to_path_buf()];
1306 while let Some(dir) = stack.pop() {
1307 let handle = platform::open_directory(&dir).map_err(|e| e.to_string())?;
1308 for entry in platform::read_dir(&handle).map_err(|e| e.to_string())? {
1309 let entry = entry.map_err(|e| e.to_string())?;
1310 let child = dir.join(entry.file_name());
1311 match entry.file_type().map_err(|e| e.to_string())? {
1312 platform::FileKind::Directory => stack.push(child),
1313 platform::FileKind::File => {}
1314 platform::FileKind::Symlink | platform::FileKind::Other => {
1315 return Err(format!(
1316 "Refusing symlink or special file {} inside pinned ACP runtime.",
1317 platform::path_text(&child)
1318 ));
1319 }
1320 }
1321 }
1322 }
1323 Ok(())
1324}
1325
1326fn hex_sha256(bytes: &[u8]) -> String {
1327 const HEX: &[u8; 16] = b"0123456789abcdef";
1328 let digest = Sha256::digest(bytes);
1329 let mut out = String::with_capacity(64);
1330 for &byte in digest.as_slice() {
1331 out.push(HEX[(byte >> 4) as usize] as char);
1332 out.push(HEX[(byte & 0x0f) as usize] as char);
1333 }
1334 out
1335}
1336
1337fn current_platform_key() -> &'static str {
1338 platform::registry_platform()
1339}
1340
1341#[derive(Deserialize)]
1342struct RawRegistryFeed {
1343 #[serde(default)]
1344 agents: Vec<RawRegistryAgent>,
1345}
1346
1347#[derive(Deserialize)]
1348struct RawRegistryAgent {
1349 id: String,
1350 name: String,
1351 version: String,
1352 #[serde(default)]
1353 description: Option<String>,
1354 #[serde(default)]
1355 distribution: RawDistribution,
1356}
1357
1358#[derive(Default, Deserialize)]
1359struct RawDistribution {
1360 #[serde(default)]
1361 binary: BTreeMap<String, RawBinaryTarget>,
1362 #[serde(default)]
1363 npx: Option<RawPackageTarget>,
1364 #[serde(default)]
1365 uvx: Option<RawPackageTarget>,
1366}
1367
1368#[derive(Deserialize)]
1369struct RawBinaryTarget {
1370 archive: String,
1371 #[serde(default)]
1372 args: Vec<String>,
1373 #[serde(default)]
1374 env: BTreeMap<String, String>,
1375 #[serde(default)]
1376 sha256: Option<String>,
1377}
1378
1379#[derive(Deserialize)]
1380struct RawPackageTarget {
1381 package: String,
1382 #[serde(default)]
1383 args: Vec<String>,
1384 #[serde(default)]
1385 env: BTreeMap<String, String>,
1386}
1387
1388fn resolve_registry_spec(
1389 id: &AgentId,
1390 item: &RawRegistryAgent,
1391 platform_key: &str,
1392) -> Option<RegistryInstallSpec> {
1393 if let Some(bin) = item.distribution.binary.get(platform_key) {
1394 return Some(RegistryInstallSpec {
1395 registry_id: id.clone(),
1396 display_name: item.name.clone(),
1397 exact_version: item.version.clone(),
1398 platform: platform_key.to_owned(),
1399 distribution_kind: if bin.archive.ends_with(".tar.gz")
1400 || bin.archive.ends_with(".zip")
1401 || bin.archive.ends_with(".tgz")
1402 {
1403 DistributionKind::Archive
1404 } else {
1405 DistributionKind::Binary
1406 },
1407 package_or_url: bin.archive.clone(),
1408 args: bin.args.clone(),
1409 env_pairs: bin.env.clone(),
1410 build_scripts_allowed: false,
1411 artifact_sha256: bin.sha256.clone(),
1412 allow_unsigned_digest: false,
1413 });
1414 }
1415 if let Some(npx) = &item.distribution.npx {
1416 return Some(RegistryInstallSpec {
1417 registry_id: id.clone(),
1418 display_name: item.name.clone(),
1419 exact_version: item.version.clone(),
1420 platform: platform_key.to_owned(),
1421 distribution_kind: DistributionKind::Npx,
1422 package_or_url: npx.package.clone(),
1423 args: npx.args.clone(),
1424 env_pairs: npx.env.clone(),
1425 build_scripts_allowed: false,
1426 artifact_sha256: None,
1427 allow_unsigned_digest: false,
1428 });
1429 }
1430 if let Some(uvx) = &item.distribution.uvx {
1431 return Some(RegistryInstallSpec {
1432 registry_id: id.clone(),
1433 display_name: item.name.clone(),
1434 exact_version: item.version.clone(),
1435 platform: platform_key.to_owned(),
1436 distribution_kind: DistributionKind::Uvx,
1437 package_or_url: uvx.package.clone(),
1438 args: uvx.args.clone(),
1439 env_pairs: uvx.env.clone(),
1440 build_scripts_allowed: false,
1441 artifact_sha256: None,
1442 allow_unsigned_digest: false,
1443 });
1444 }
1445 None
1446}
1447
1448pub fn compute_launcher_fingerprint(
1450 spec: &AgentSpec,
1451 worktree: &Path,
1452) -> Result<LauncherFingerprint, String> {
1453 let resolved = trust::resolve_executable(
1454 &spec.program,
1455 Some(worktree),
1456 spec.reject_worktree_executable,
1457 )?;
1458 LauncherFingerprint::compute(&resolved, &spec.args)
1459}
1460
1461#[cfg(test)]
1462mod tests {
1463 use super::*;
1464
1465 #[tokio::test]
1466 async fn custom_agent_roundtrip_stores_secrets_separately_and_blocks_preset_shadowing() {
1467 let root = crate::test_os::tempdir();
1468 let state = root.path().join("state");
1469 let worktree = root.path().join("work");
1470 std::fs::create_dir_all(&worktree).unwrap();
1471
1472 let shadow = CustomAgent {
1473 id: "antigravity".parse().unwrap(),
1474 name: "Shadow".into(),
1475 command: "fake".into(),
1476 args: Vec::new(),
1477 env: BTreeMap::new(),
1478 secret_env_keys: Vec::new(),
1479 mcp_stdio: true,
1480 registry: None,
1481 entrypoint_sha256: None,
1482 };
1483 assert!(
1484 save_custom_agent(Some(&state), Some(&worktree), shadow, BTreeMap::new(), &[])
1485 .await
1486 .is_err()
1487 );
1488
1489 let custom = CustomAgent {
1490 id: "my-acp".parse().unwrap(),
1491 name: "My ACP".into(),
1492 command: "my-acp-bin".into(),
1493 args: vec!["--stdio".into()],
1494 env: BTreeMap::from([("PLAIN_FLAG".into(), "1".into())]),
1495 secret_env_keys: Vec::new(),
1496 mcp_stdio: true,
1497 registry: None,
1498 entrypoint_sha256: None,
1499 };
1500 let mut secrets = BTreeMap::new();
1501 secrets.insert(
1502 "MY_SECRET".into(),
1503 SecretEnvValue::parse("top-secret-value-999").unwrap(),
1504 );
1505 let saved = save_custom_agent(Some(&state), Some(&worktree), custom, secrets, &[])
1506 .await
1507 .unwrap();
1508 assert_eq!(saved.secret_env_keys, vec!["MY_SECRET".to_owned()]);
1509
1510 let agents_json = std::fs::read_to_string(state.join("chat/agents.json")).unwrap();
1512 assert!(!agents_json.contains("top-secret-value-999"));
1513 assert!(agents_json.contains("MY_SECRET"));
1514
1515 let spec = resolve_spec(&saved.id, Some(&state), Some(&worktree)).unwrap();
1516 assert_eq!(
1517 spec.known_secrets(),
1518 vec!["top-secret-value-999".to_owned()]
1519 );
1520 assert!(is_chat_agent("my-acp", Some(&state), Some(&worktree)));
1521
1522 assert!(
1523 remove_custom_agent(Some(&state), Some(&worktree), &saved.id)
1524 .await
1525 .unwrap()
1526 );
1527 assert!(!is_chat_agent("my-acp", Some(&state), Some(&worktree)));
1528 }
1529}