agentmux_srv/server/agent_handlers/identity/
named_agents.rs1use 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
18struct 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 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
57pub(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 match mstore.shared_agent_registry() {
85 Some(reg) => registry_rows(mstore, ®, &cmd, limit, &lookups),
86 None => instance_rows(mstore, &cmd, limit, &lookups),
87 }
88}
89
90fn 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 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 let sqlite_rows: Vec<AgentInstance> = mstore
128 .instance_list_named(records.len().max(1), cmd.definition_id.as_deref(), None, 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 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 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
175fn 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(), None, 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
205pub(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}