Skip to main content

aidaemon_tools/
cli_agent_flags.rs

1//! The terminal agents' (codex, claude, gemini, opencode) launch flags: their
2//! names, defaults kept in the settings store, and flags discovered from
3//! `--help`.
4
5use std::collections::{HashMap, HashSet};
6use std::process::Stdio;
7use std::time::Duration;
8
9use regex::Regex;
10use std::sync::LazyLock;
11use tokio::process::Command;
12
13use crate::services::SettingsStore;
14
15// ---------------------------------------------------------------------------
16// Constants
17// ---------------------------------------------------------------------------
18
19pub const AGENT_FLAGS_CACHE_TTL_SECS: i64 = 24 * 60 * 60;
20pub const MAX_DISCOVERED_AGENT_FLAGS: usize = 512;
21pub const MAX_DISCOVERED_AGENT_FLAG_CHARS: usize = 96;
22pub const MAX_DISCOVERED_AGENT_FLAG_DESC_CHARS: usize = 240;
23pub const AGENT_FLAGS_PAGE_SIZE: usize = 12;
24pub const SUPPORTED_TERMINAL_AGENTS: &[&str] = &["codex", "claude", "gemini", "opencode"];
25pub const MAX_TERMINAL_AGENT_ARGS: usize = 24;
26pub const MAX_TERMINAL_AGENT_ARG_CHARS: usize = 256;
27
28// ---------------------------------------------------------------------------
29// Structs
30// ---------------------------------------------------------------------------
31
32#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
33pub struct AgentFlagDoc {
34    pub flag: String,
35    #[serde(default)]
36    pub description: Option<String>,
37}
38
39#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
40pub struct AgentFlagsCacheEntry {
41    pub updated_at_unix: i64,
42    #[serde(default)]
43    pub flags: Vec<String>,
44    #[serde(default)]
45    pub docs: Vec<AgentFlagDoc>,
46}
47
48// ---------------------------------------------------------------------------
49// Normalization helpers
50// ---------------------------------------------------------------------------
51
52/// Normalize a terminal agent name, returning the canonical lowercase form.
53///
54/// Reuses the `normalize_terminal_agent_name` from `lib.rs` (which returns
55/// `Option<&'static str>`) and converts to `Option<String>`.
56/// The supported terminal agent `raw` names, case-insensitively.
57pub fn terminal_agent_name(raw: &str) -> Option<&'static str> {
58    let normalized = raw.trim().to_ascii_lowercase();
59    match normalized.as_str() {
60        "codex" => Some("codex"),
61        "claude" => Some("claude"),
62        "gemini" => Some("gemini"),
63        "opencode" => Some("opencode"),
64        _ => None,
65    }
66}
67
68pub fn normalize_terminal_agent_name(value: &str) -> Option<String> {
69    terminal_agent_name(value).map(String::from)
70}
71
72pub fn normalize_terminal_agent_args(values: Vec<String>) -> Vec<String> {
73    values
74        .into_iter()
75        .map(|v| v.trim().to_string())
76        .filter(|v| !v.is_empty() && !v.contains('\0'))
77        .map(|v| {
78            v.chars()
79                .take(MAX_TERMINAL_AGENT_ARG_CHARS)
80                .collect::<String>()
81        })
82        .take(MAX_TERMINAL_AGENT_ARGS)
83        .collect()
84}
85
86pub fn normalize_discovered_agent_flags(values: Vec<String>) -> Vec<String> {
87    let mut out = Vec::new();
88    let mut seen = HashSet::new();
89    for value in values {
90        let cleaned = value.trim().to_string();
91        if cleaned.is_empty() || !cleaned.starts_with("--") || cleaned.contains('\0') {
92            continue;
93        }
94        let clipped = cleaned
95            .chars()
96            .take(MAX_DISCOVERED_AGENT_FLAG_CHARS)
97            .collect::<String>();
98        if seen.insert(clipped.clone()) {
99            out.push(clipped);
100        }
101        if out.len() >= MAX_DISCOVERED_AGENT_FLAGS {
102            break;
103        }
104    }
105    out
106}
107
108pub fn normalize_agent_flag_docs(values: Vec<AgentFlagDoc>) -> Vec<AgentFlagDoc> {
109    let mut out: Vec<AgentFlagDoc> = Vec::new();
110    let mut seen: HashMap<String, usize> = HashMap::new();
111
112    for value in values {
113        let normalized_flags = normalize_discovered_agent_flags(vec![value.flag]);
114        let Some(flag) = normalized_flags.first().cloned() else {
115            continue;
116        };
117
118        let description = value
119            .description
120            .map(|d| d.split_whitespace().collect::<Vec<_>>().join(" "))
121            .map(|d| d.trim().to_string())
122            .filter(|d| !d.is_empty())
123            .map(|d| {
124                d.chars()
125                    .take(MAX_DISCOVERED_AGENT_FLAG_DESC_CHARS)
126                    .collect::<String>()
127            });
128
129        if let Some(idx) = seen.get(&flag).copied() {
130            let existing = out.get_mut(idx).expect("index from seen must exist");
131            let replace = match (&existing.description, &description) {
132                (None, Some(_)) => true,
133                (Some(old), Some(new)) => new.len() > old.len(),
134                _ => false,
135            };
136            if replace {
137                existing.description = description;
138            }
139        } else {
140            seen.insert(flag.clone(), out.len());
141            out.push(AgentFlagDoc { flag, description });
142            if out.len() >= MAX_DISCOVERED_AGENT_FLAGS {
143                break;
144            }
145        }
146    }
147
148    out
149}
150
151// ---------------------------------------------------------------------------
152// Formatting
153// ---------------------------------------------------------------------------
154
155pub fn format_agent_flag_docs(agent: &str, docs: &[AgentFlagDoc], cached: bool) -> Vec<String> {
156    if docs.is_empty() {
157        return vec![format!(
158            "### No flags found for `{}`{}\nTry `/agent flags {} refresh`.",
159            agent,
160            if cached { " (cached)" } else { "" },
161            agent
162        )];
163    }
164
165    let page_size = AGENT_FLAGS_PAGE_SIZE.max(1);
166    let total = docs.len();
167    let total_pages = total.div_ceil(page_size);
168    let mut pages = Vec::new();
169
170    for (idx, chunk) in docs.chunks(page_size).enumerate() {
171        let mut lines = Vec::new();
172        lines.push(format!(
173            "### Flags for `{}`{}",
174            agent,
175            if cached { " (cached)" } else { "" }
176        ));
177        lines.push(format!("**{} total**", total));
178        if total_pages > 1 {
179            let start = idx * page_size + 1;
180            let end = start + chunk.len() - 1;
181            lines.push(format!(
182                "**Showing {}-{} of {} (page {}/{})**",
183                start,
184                end,
185                total,
186                idx + 1,
187                total_pages
188            ));
189        }
190        lines.push(String::new());
191
192        for doc in chunk {
193            lines.push(format!("- `{}`", doc.flag));
194            if let Some(desc) = doc.description.as_deref() {
195                lines.push(format!("Description: {}", desc));
196            }
197            lines.push(String::new());
198        }
199
200        if idx + 1 == total_pages {
201            lines.push("Set defaults with `/agent defaults set <agent> [flags...]`.".to_string());
202            lines.push("Bypass once with `--no-default-flags`.".to_string());
203            lines.push("Refresh with `/agent flags <agent> refresh`.".to_string());
204        }
205
206        while lines.last().map(|line| line.is_empty()).unwrap_or(false) {
207            lines.pop();
208        }
209        pages.push(lines.join("\n"));
210    }
211
212    pages
213}
214
215pub fn strip_no_default_flag(agent_args: &mut Vec<String>) -> bool {
216    let before = agent_args.len();
217    agent_args.retain(|arg| arg != "--no-default-flags");
218    before != agent_args.len()
219}
220
221// ---------------------------------------------------------------------------
222// Help text parsing
223// ---------------------------------------------------------------------------
224
225pub fn extract_long_flags_from_help(help_text: &str) -> Vec<String> {
226    static LONG_FLAG_RE: LazyLock<Regex> = LazyLock::new(|| {
227        Regex::new(r"--[a-zA-Z0-9][a-zA-Z0-9\-]*").expect("valid long flag regex")
228    });
229    let mut out = Vec::new();
230    let mut seen = HashSet::new();
231    for cap in LONG_FLAG_RE.find_iter(help_text) {
232        let flag = cap.as_str().to_string();
233        if seen.insert(flag.clone()) {
234            out.push(flag);
235        }
236    }
237    out
238}
239
240pub fn extract_flag_docs_from_help(help_text: &str) -> Vec<AgentFlagDoc> {
241    static LONG_FLAG_RE: LazyLock<Regex> = LazyLock::new(|| {
242        Regex::new(r"--[a-zA-Z0-9][a-zA-Z0-9\-]*").expect("valid long flag regex")
243    });
244    let mut docs = Vec::new();
245    for raw_line in help_text.lines() {
246        let line = raw_line.trim();
247        if line.is_empty() {
248            continue;
249        }
250        let matches = LONG_FLAG_RE.find_iter(line).collect::<Vec<_>>();
251        if matches.is_empty() {
252            continue;
253        }
254        let first_end = matches[0].end();
255        let desc_raw = line
256            .get(first_end..)
257            .unwrap_or("")
258            .trim()
259            .trim_start_matches([':', ';', ',', '|', '-', ' ']);
260        let description = if desc_raw.is_empty() {
261            None
262        } else {
263            Some(desc_raw.to_string())
264        };
265        for m in matches {
266            docs.push(AgentFlagDoc {
267                flag: m.as_str().to_string(),
268                description: description.clone(),
269            });
270        }
271    }
272    normalize_agent_flag_docs(docs)
273}
274
275// ---------------------------------------------------------------------------
276// Discovery
277// ---------------------------------------------------------------------------
278
279pub async fn discover_agent_flags(agent: &str) -> anyhow::Result<Vec<AgentFlagDoc>> {
280    let run_help_cmd = |help_arg: &str| {
281        let mut cmd = Command::new(agent);
282        cmd.arg(help_arg);
283        cmd.stdin(Stdio::null());
284        cmd.stdout(Stdio::piped());
285        cmd.stderr(Stdio::piped());
286        cmd.kill_on_drop(true);
287        cmd.env_remove("CLAUDECODE");
288        cmd.env_remove("CLAUDE_CODE");
289        cmd
290    };
291
292    let output = match tokio::time::timeout(
293        Duration::from_secs(10),
294        run_help_cmd("--help").output(),
295    )
296    .await
297    {
298        Ok(Ok(v)) => v,
299        Ok(Err(err)) => {
300            if err.kind() == std::io::ErrorKind::NotFound {
301                anyhow::bail!(
302                    "`{}` is not installed or not in PATH on this machine.",
303                    agent
304                );
305            }
306            match tokio::time::timeout(Duration::from_secs(10), run_help_cmd("-h").output()).await {
307                Ok(Ok(v)) => v,
308                Ok(Err(second_err)) => {
309                    anyhow::bail!("Failed to run `{}` help: {}", agent, second_err)
310                }
311                Err(_) => return Err(help_timed_out(agent, "-h")),
312            }
313        }
314        Err(_) => return Err(help_timed_out(agent, "--help")),
315    };
316
317    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
318    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
319    let combined = if stdout.is_empty() {
320        stderr.clone()
321    } else if stderr.is_empty() {
322        stdout.clone()
323    } else {
324        format!("{}\n{}", stdout, stderr)
325    };
326
327    let flags = extract_long_flags_from_help(&combined);
328    if flags.is_empty() {
329        anyhow::bail!(
330            "No long-form flags were detected in `{}` help output. Try running `{}` manually.",
331            agent,
332            agent
333        );
334    }
335    let docs = extract_flag_docs_from_help(&combined);
336    if docs.is_empty() {
337        let fallback = normalize_discovered_agent_flags(flags)
338            .into_iter()
339            .map(|flag| AgentFlagDoc {
340                flag,
341                description: None,
342            })
343            .collect::<Vec<_>>();
344        return Ok(fallback);
345    }
346    Ok(docs)
347}
348
349// ---------------------------------------------------------------------------
350// Cache load/save
351// ---------------------------------------------------------------------------
352
353fn agent_flags_cache_key(namespace: &str, user_id: u64, agent: &str) -> String {
354    format!(
355        "telegram:agent_flags_cache:{}:{}:{}",
356        namespace,
357        user_id,
358        agent.to_ascii_lowercase()
359    )
360}
361
362fn terminal_agent_defaults_key(namespace: &str, user_id: u64, chat_id: i64) -> String {
363    format!(
364        "telegram:agent_defaults:{}:{}:{}",
365        namespace, user_id, chat_id
366    )
367}
368
369pub async fn load_agent_flags_cache(
370    state: &dyn SettingsStore,
371    namespace: &str,
372    user_id: u64,
373    agent: &str,
374) -> Option<AgentFlagsCacheEntry> {
375    let key = agent_flags_cache_key(namespace, user_id, agent);
376    let raw = state.get_setting(&key).await.ok().flatten()?;
377    let mut parsed: AgentFlagsCacheEntry = serde_json::from_str(&raw).ok()?;
378    let mut docs = normalize_agent_flag_docs(parsed.docs.clone());
379    if docs.is_empty() && !parsed.flags.is_empty() {
380        docs = normalize_discovered_agent_flags(parsed.flags.clone())
381            .into_iter()
382            .map(|flag| AgentFlagDoc {
383                flag,
384                description: None,
385            })
386            .collect();
387    }
388    if docs.is_empty() {
389        return None;
390    }
391    parsed.docs = docs.clone();
392    parsed.flags = docs.iter().map(|d| d.flag.clone()).collect();
393    Some(parsed)
394}
395
396pub async fn save_agent_flags_cache(
397    state: &dyn SettingsStore,
398    namespace: &str,
399    user_id: u64,
400    agent: &str,
401    docs: &[AgentFlagDoc],
402) -> anyhow::Result<()> {
403    let key = agent_flags_cache_key(namespace, user_id, agent);
404    let normalized_docs = normalize_agent_flag_docs(docs.to_vec());
405    let payload = AgentFlagsCacheEntry {
406        updated_at_unix: chrono::Utc::now().timestamp(),
407        flags: normalized_docs.iter().map(|d| d.flag.clone()).collect(),
408        docs: normalized_docs,
409    };
410    let serialized = serde_json::to_string(&payload)?;
411    state.set_setting(&key, &serialized).await
412}
413
414pub async fn load_terminal_agent_defaults(
415    state: &dyn SettingsStore,
416    namespace: &str,
417    chat_id: i64,
418    user_id: u64,
419) -> HashMap<String, Vec<String>> {
420    let key = terminal_agent_defaults_key(namespace, user_id, chat_id);
421    let raw = match state.get_setting(&key).await {
422        Ok(Some(v)) => v,
423        _ => return HashMap::new(),
424    };
425    let parsed: HashMap<String, Vec<String>> =
426        serde_json::from_str(&raw).unwrap_or_else(|_| HashMap::new());
427    let mut sanitized = HashMap::new();
428    for (agent, args) in parsed {
429        let Some(agent_name) = normalize_terminal_agent_name(&agent) else {
430            continue;
431        };
432        let cleaned = normalize_terminal_agent_args(args);
433        let (cleaned, _) = crate::permission_bypass::normalize_terminal_agent_permission_aliases(
434            Some(agent_name.as_str()),
435            cleaned,
436        );
437        if cleaned.is_empty() {
438            continue;
439        }
440        sanitized.insert(agent_name, cleaned);
441    }
442    sanitized
443}
444
445pub async fn save_terminal_agent_defaults(
446    state: &dyn SettingsStore,
447    namespace: &str,
448    chat_id: i64,
449    user_id: u64,
450    defaults: &HashMap<String, Vec<String>>,
451) -> anyhow::Result<()> {
452    let key = terminal_agent_defaults_key(namespace, user_id, chat_id);
453    let serialized = serde_json::to_string(defaults)?;
454    state.set_setting(&key, &serialized).await
455}
456
457// ---------------------------------------------------------------------------
458// Tests
459// ---------------------------------------------------------------------------
460
461/// A help fetch that ran out of time, raised as a typed
462/// [`crate::ToolTimedOut`] so it is retryable, not a failure.
463fn help_timed_out(agent: &str, flag: &str) -> anyhow::Error {
464    crate::ToolTimedOut(format!(
465        "`{agent} {flag}` timed out while fetching help output."
466    ))
467    .into()
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[test]
475    fn a_help_fetch_timeout_is_typed() {
476        let error = help_timed_out("synthetic-agent", "--help");
477        assert!(crate::timed_out(&error));
478        assert!(error.to_string().contains("synthetic-agent --help"));
479    }
480
481    #[test]
482    fn format_agent_flag_docs_paginates_and_keeps_footer_actions() {
483        let docs = (1..=13)
484            .map(|n| AgentFlagDoc {
485                flag: format!("--flag-{}", n),
486                description: Some(format!("Description {}", n)),
487            })
488            .collect::<Vec<_>>();
489
490        let pages = format_agent_flag_docs("claude", &docs, false);
491        assert_eq!(pages.len(), 2);
492        assert!(pages[0].contains("Showing 1-12 of 13 (page 1/2)"));
493        assert!(pages[1].contains("Showing 13-13 of 13 (page 2/2)"));
494        assert!(pages[1].contains("Set defaults with `/agent defaults set <agent> [flags...]`."));
495        assert!(pages[1].contains("Bypass once with `--no-default-flags`."));
496        assert!(pages[1].contains("Refresh with `/agent flags <agent> refresh`."));
497    }
498
499    #[test]
500    fn format_agent_flag_docs_includes_cached_badge() {
501        let docs = vec![AgentFlagDoc {
502            flag: "--print".to_string(),
503            description: Some("Output format.".to_string()),
504        }];
505        let pages = format_agent_flag_docs("claude", &docs, true);
506        assert_eq!(pages.len(), 1);
507        assert!(pages[0].contains("Flags for `claude` (cached)"));
508    }
509}