Skip to main content

agentmux_srv/server/agent_handlers/identity/
named_agents.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The named-agent RPCs (`listnamedagents`, `hidenamedagent`), moved out of `identity::register` unchanged as
5//! named functions. They power the picker's My Agents and the Files pane, joining instance rows with the
6//! definition, account and bundle names so the frontend renders without follow-ups.
7
8use std::collections::HashMap;
9
10use super::super::account_label::{account_line, names_by_id, Degraded};
11use crate::backend::rpc_types::{CommandListNamedAgentsData, HideNamedAgentResult, NamedAgentRow};
12use crate::backend::storage::store::{AgentIdentityLink, AgentInstance, Bundle, IdentityAccount, Store};
13use crate::backend::storage::AgentDefinition;
14
15const DEFAULT_LIMIT: usize = 200;
16const MAX_LIMIT: usize = 1000;
17
18/// Everything a row's names are looked up in, fetched once per response: with at most 200 rows and account
19/// and bundle counts in the low dozens, a linear lookup on cached lists beats per-row round-trips.
20struct Lookups<'a> {
21    defs: &'a [AgentDefinition],
22    memories: &'a [Bundle],
23    links_by_agent: HashMap<&'a str, Vec<&'a AgentIdentityLink>>,
24    account_names: HashMap<&'a str, &'a str>,
25    mirror_failed: bool,
26}
27
28impl Lookups<'_> {
29    /// The identity name resolves off the direct agent↔account links, grouped by definition id
30    /// (SPEC_ARMORY_PHASE4_STORAGE_RENAME_COMPLETION_2026_07_12.md §4 item 2).
31    fn identity_name(&self, definition_id: &str) -> String {
32        account_line(
33            self.links_by_agent.get(definition_id).map(|v| v.as_slice()),
34            &self.account_names,
35            Degraded { links: false, accounts: self.mirror_failed },
36        )
37        .text
38    }
39
40    fn memory_name(&self, memory_id: &str) -> String {
41        if memory_id.is_empty() {
42            "(vanilla CLI)".to_string()
43        } else {
44            self.memories
45                .iter()
46                .find(|m| m.id == memory_id)
47                .map(|m| m.name.clone())
48                .unwrap_or_else(|| "(missing memory)".to_string())
49        }
50    }
51
52    fn definition(&self, definition_id: &str) -> Option<&AgentDefinition> {
53        self.defs.iter().find(|d| d.id == definition_id)
54    }
55}
56
57/// `data` is a `Value`: a malformed request means the defaults.
58pub(super) fn list_named_agents(
59    mstore: &Store,
60    id_store: &Store,
61    identity_store: &Store,
62    data: serde_json::Value,
63) -> Result<Vec<NamedAgentRow>, String> {
64    let cmd: CommandListNamedAgentsData = serde_json::from_value(data).unwrap_or_default();
65    let limit = if cmd.limit == 0 { DEFAULT_LIMIT } else { cmd.limit.min(MAX_LIMIT) };
66    let defs = mstore.agent_def_list().map_err(|e| format!("listnamedagents: agent_def_list: {e}"))?;
67    let memories = id_store.bundle_list().map_err(|e| format!("listnamedagents: bundle_list: {e}"))?;
68    let links = identity_store.agent_identity_list_all().map_err(|e| format!("listnamedagents: agent_identity_links: {e}"))?;
69    let accounts = id_store.identity_list(None).map_err(|e| format!("listnamedagents: accounts: {e}"))?;
70    let (mirror_accounts, mirror_failed) = mirror_accounts_for(&links, &accounts, identity_store);
71    let mut links_by_agent: HashMap<&str, Vec<&AgentIdentityLink>> = HashMap::new();
72    for link in &links {
73        links_by_agent.entry(link.agent_id.as_str()).or_default().push(link);
74    }
75    let lookups = Lookups {
76        defs: &defs,
77        memories: &memories,
78        links_by_agent,
79        account_names: names_by_id(&accounts, &mirror_accounts),
80        mirror_failed,
81    };
82    // Read from the cross-version registry when it's available; SQLite is the fallback when it couldn't be
83    // resolved at startup (CI, odd environments). SQLite stays authoritative while the parallel write is on.
84    match mstore.shared_agent_registry() {
85        Some(reg) => registry_rows(mstore, &reg, &cmd, limit, &lookups),
86        None => instance_rows(mstore, &cmd, limit, &lookups),
87    }
88}
89
90/// The global account mirror, read only when a link names an account this channel's store doesn't hold. The
91/// flag is set when that read fails, so a link that resolves to nothing is left empty, not "No auth".
92fn mirror_accounts_for(links: &[AgentIdentityLink], own: &[IdentityAccount], identity_store: &Store) -> (Vec<IdentityAccount>, bool) {
93    let own_ids: std::collections::HashSet<&str> = own.iter().map(|a| a.id.as_str()).collect();
94    if !links.iter().any(|l| !own_ids.contains(l.account_id.as_str())) {
95        return (Vec::new(), false);
96    }
97    match identity_store.identity_list(None) {
98        Ok(accounts) => (accounts, false),
99        Err(e) => {
100            tracing::warn!(error = %e, "listnamedagents: the global account mirror could not be read");
101            (Vec::new(), true)
102        }
103    }
104}
105
106fn registry_rows(
107    mstore: &Store,
108    reg: &crate::registry::Registry,
109    cmd: &CommandListNamedAgentsData,
110    limit: usize,
111    lookups: &Lookups,
112) -> Result<Vec<NamedAgentRow>, String> {
113    // Re-join a relative working_dir against the CURRENT channel's agents dir (symmetric with the write
114    // mirror), not the registry's own parent: P0.3 re-roots the registry out of channels/<ch>/agents/.
115    let agents_root = mstore.registry_agents_base();
116    let mut records = reg.list_active().map_err(|e| format!("listnamedagents: registry: {e}"))?;
117    if let Some(def_filter) = cmd.definition_id.as_deref() {
118        records.retain(|r| r.data.definition_id == def_filter);
119    }
120    records.sort_by(|a, b| b.data.last_launched_at_ms.cmp(&a.data.last_launched_at_ms));
121    records.truncate(limit);
122    // Pre-fetch the candidate same-version rows ONCE so enrichment doesn't issue N+1 queries, indexed by
123    // instance_id; rows that aren't in current SQLite fall through to sentinels. Head-of-chain only: the
124    // registry mirror excludes continuations (see `registry_upsert_if_named`), so the SQLite side must match,
125    // else continuation rows displace registry-head rows under the `limit` and the merge-by-id enrichment
126    // misses, silently downgrading running-state badges and block_id_hints to "available" / empty.
127    let sqlite_rows: Vec<AgentInstance> = mstore
128        .instance_list_named(records.len().max(1), cmd.definition_id.as_deref(), /* identity_id */ None, /* include_continuations */ false)
129        .unwrap_or_default();
130    let sqlite_by_id: HashMap<&str, &AgentInstance> = sqlite_rows.iter().map(|i| (i.id.as_str(), i)).collect();
131    Ok(records
132        .into_iter()
133        .map(|rec| {
134            let d = rec.data;
135            let def = lookups.definition(&d.definition_id);
136            let memory_id = d.memory_id.clone().unwrap_or_default();
137            // v3 records carry their SOURCE channel agents dir, so a row from another channel resolves to its
138            // real workspace; legacy (v1/v2) records fall back to the current channel base (the pre-P0.4
139            // behaviour, correct for the same-channel rows v1/v2 could represent).
140            let working_directory = if let Some(src) = d.source_agents_base.as_deref() {
141                std::path::Path::new(src).join(&d.working_dir).to_string_lossy().to_string()
142            } else {
143                match agents_root.as_ref() {
144                    Some(root) => root.join(&d.working_dir).to_string_lossy().to_string(),
145                    None => d.working_dir.clone(),
146                }
147            };
148            // Same-version enrichment: a row that is also in current SQLite carries runtime state (block_id for
149            // focus-existing-pane, status, ended_at) the registry intentionally doesn't track. Cross-version
150            // rows fall through with the "available" status and an empty block_id_hint.
151            let (block_id_hint, status, ended_at) = match sqlite_by_id.get(d.instance_id.as_str()) {
152                Some(inst) => (inst.block_id.clone(), inst.status.clone(), inst.ended_at),
153                None => (String::new(), "available".to_string(), 0),
154            };
155            NamedAgentRow {
156                instance_id: d.instance_id,
157                instance_name: d.instance_name,
158                definition_id: d.definition_id.clone(),
159                definition_name: def.map(|x| x.name.clone()).unwrap_or_else(|| "(missing definition)".to_string()),
160                provider: def.map(|x| x.provider.clone()).unwrap_or_default(),
161                working_directory,
162                identity_id: d.identity_id.clone().unwrap_or_default(),
163                identity_name: lookups.identity_name(&d.definition_id),
164                memory_name: lookups.memory_name(&memory_id),
165                memory_id,
166                started_at: d.last_launched_at_ms,
167                ended_at,
168                status,
169                block_id_hint,
170            }
171        })
172        .collect())
173}
174
175/// No-registry fallback: drives the launch modal's "Continue agent" dropdown directly. One entry per chain
176/// root, mirroring the registry path's semantics.
177fn instance_rows(mstore: &Store, cmd: &CommandListNamedAgentsData, limit: usize, lookups: &Lookups) -> Result<Vec<NamedAgentRow>, String> {
178    let instances = mstore
179        .instance_list_named(limit, cmd.definition_id.as_deref(), /* identity_id */ None, /* include_continuations */ false)
180        .map_err(|e| format!("listnamedagents: {e}"))?;
181    Ok(instances
182        .into_iter()
183        .map(|inst| {
184            let def = lookups.definition(&inst.definition_id);
185            NamedAgentRow {
186                definition_name: def.map(|d| d.name.clone()).unwrap_or_else(|| "(missing definition)".to_string()),
187                provider: def.map(|d| d.provider.clone()).unwrap_or_default(),
188                identity_name: lookups.identity_name(&inst.definition_id),
189                memory_name: lookups.memory_name(&inst.memory_id),
190                instance_id: inst.id,
191                instance_name: inst.instance_name,
192                definition_id: inst.definition_id,
193                working_directory: inst.working_directory,
194                identity_id: inst.identity_id,
195                memory_id: inst.memory_id,
196                started_at: inst.started_at,
197                ended_at: inst.ended_at,
198                status: inst.status,
199                block_id_hint: inst.block_id,
200            }
201        })
202        .collect())
203}
204
205/// Soft-delete (`display_hidden = 1`) so the row disappears from the dropdown. The working dir stays on disk.
206pub(super) fn hide_named_agent(
207    mstore: &Store,
208    broker: &crate::backend::mps::Broker,
209    id: &str,
210) -> Result<HideNamedAgentResult, String> {
211    let hidden = mstore.instance_set_hidden(id, true).map_err(|e| format!("hidenamedagent: {e}"))?;
212    if hidden {
213        broker.publish_event::<crate::backend::mps_events::NamedAgentsChanged>(&(), vec![], 0);
214    }
215    Ok(HideNamedAgentResult { hidden })
216}