1use std::collections::{BTreeMap, HashMap};
9
10use serde_json::{json, Value};
11
12use super::model::{ModelFacts, ModelSource};
13use super::{block_of, facts_of, model_of, Agent, Ctx, LiveFacts, Select};
14use crate::backend::runtime_adapter::RuntimeKind;
15use crate::server::AppState;
16
17const DEFAULT_MAX_BYTES: usize = 60_000;
20
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct Filter {
24 pub state: Option<String>,
26 pub model: Option<String>,
28 pub provider: Option<String>,
29 pub runtime: Option<String>,
31 pub account: Option<String>,
33 pub seat: Option<String>,
35}
36
37#[derive(Debug, Clone)]
38pub struct Params {
39 pub select: Select,
40 pub filter: Filter,
41 pub limit: Option<usize>,
42 pub offset: usize,
43 pub group_by: Option<String>,
44 pub all_hosts: bool,
46}
47
48fn text(map: &HashMap<String, String>, key: &str) -> Option<String> {
49 map.get(key).map(|v| v.trim().to_string()).filter(|v| !v.is_empty())
50}
51
52impl Params {
53 pub fn from_map(map: &HashMap<String, String>, this_host: &str) -> Result<Self, String> {
56 let select = Select::parse(map.get("fields").map(String::as_str), map.get("detail").map(String::as_str))?;
57 let host = text(map, "host");
58 if let Some(host) = host.as_deref() {
59 if !host.eq_ignore_ascii_case("all") && !host.eq_ignore_ascii_case(this_host) {
60 return Err(format!("host {host:?} is not this machine ({this_host}): this route answers for this machine; another machine's agents are asked for with the tool's host argument"));
61 }
62 }
63 let number = |key: &str| -> Result<Option<usize>, String> {
64 text(map, key).map(|v| v.parse::<usize>().map_err(|_| format!("{key} must be a whole number, not {v:?}"))).transpose()
65 };
66 let group_by = text(map, "group_by");
67 if let Some(g) = group_by.as_deref().filter(|g| !["model", "state", "host", "account", "provider", "runtime"].contains(g)) {
68 return Err(format!("unknown group_by {g:?}: use model, state, host, account, provider or runtime"));
69 }
70 Ok(Self {
71 select,
72 filter: Filter {
73 state: text(map, "state"),
74 model: text(map, "model"),
75 provider: text(map, "provider"),
76 runtime: text(map, "runtime"),
77 account: text(map, "account"),
78 seat: text(map, "seat"),
79 },
80 limit: number("limit")?,
81 offset: number("offset")?.unwrap_or(0),
82 group_by,
83 all_hosts: host.as_deref().is_some_and(|h| h.eq_ignore_ascii_case("all")),
84 })
85 }
86}
87
88fn contains_ci(hay: &str, needle: &str) -> bool {
89 hay.to_ascii_lowercase().contains(&needle.to_ascii_lowercase())
90}
91
92fn names_model(model: &ModelFacts, wanted: &str) -> bool {
94 model.id.as_deref().is_some_and(|id| contains_ci(id, wanted)) || model.label.as_deref().is_some_and(|l| contains_ci(l, wanted))
95}
96
97pub struct Cheap<'a> {
99 pub state: &'a str,
100 pub model: &'a ModelFacts,
101 pub provider: &'a str,
102 pub container: bool,
103 pub account: Option<(&'a str, &'a str)>,
104 pub seat: &'a str,
105}
106
107pub fn wanted(f: &Filter, c: &Cheap) -> bool {
109 let model_ok = match f.model.as_deref() {
110 None => true,
111 Some(m) => match m.strip_prefix('!') {
112 Some(not) => c.model.source == ModelSource::Unknown || !names_model(c.model, not.trim()),
113 None => names_model(c.model, m),
114 },
115 };
116 model_ok
117 && f.state.as_deref().is_none_or(|s| c.state.eq_ignore_ascii_case(s))
118 && f.provider.as_deref().is_none_or(|p| c.provider.eq_ignore_ascii_case(p))
119 && f.runtime.as_deref().is_none_or(|r| r.eq_ignore_ascii_case(if c.container { "container" } else { "native" }))
120 && f.account.as_deref().is_none_or(|a| c.account.is_some_and(|(stable, label)| contains_ci(stable, a) || contains_ci(label, a)))
121 && f.seat.as_deref().is_none_or(|s| contains_ci(c.seat, s))
122}
123
124fn string_at<'a>(row: &'a Value, pointer: &str) -> &'a str {
125 row.pointer(pointer).and_then(Value::as_str).unwrap_or_default()
126}
127
128fn agent_of(row: &Value) -> Option<Agent<'_>> {
130 row.get("runtime").filter(|r| r.is_object())?;
131 Some(Agent {
132 uid: string_at(row, "/id"),
133 name: string_at(row, "/name"),
134 provider: string_at(row, "/runtime/provider"),
135 block_id: row.pointer("/runtime/block_id").and_then(Value::as_str),
136 state: string_at(row, "/runtime/state"),
137 container: row.pointer("/runtime/runtime").and_then(|v| serde_json::from_value::<RuntimeKind>(v.clone()).ok()) == Some(RuntimeKind::Container),
138 })
139}
140
141fn seat_words(seat: &Value) -> String {
144 ["/role", "/qualifier", "/lead/name", "/lead/id", "/area"].iter().filter_map(|p| seat.pointer(p).and_then(Value::as_str)).collect::<Vec<_>>().join(" ")
145}
146
147struct Kept {
149 row: Value,
150 model: Option<ModelFacts>,
151}
152
153fn filtered(ctx: &Ctx, rows: Vec<Value>, p: &Params) -> Vec<Kept> {
156 let narrowed = p.filter != Filter::default();
157 rows.into_iter()
158 .filter_map(|row| {
159 let Some(a) = agent_of(&row) else { return (!narrowed).then_some(Kept { row, model: None }) };
160 let block = block_of(ctx, &a);
161 let model = model_of(ctx, &a, block.as_ref());
162 let account = p.filter.account.as_ref().and_then(|_| super::account_of(ctx, block.as_ref()));
163 let seat = row.get("seat").map(seat_words).unwrap_or_default();
164 let cheap = Cheap {
165 state: a.state,
166 model: &model,
167 provider: a.provider,
168 container: a.container,
169 account: account.as_ref().map(|(f, _)| (f.stable_id.as_deref().unwrap_or_default(), f.label.as_str())),
170 seat: &seat,
171 };
172 wanted(&p.filter, &cheap).then_some(Kept { row, model: Some(model) })
173 })
174 .collect()
175}
176
177fn decorate_page(ctx: &Ctx, kept: Vec<Kept>, p: &Params) -> (Vec<Value>, Value) {
179 let total = kept.len();
180 let limit = p.limit.unwrap_or(usize::MAX);
181 let bounded = p.limit.is_some() || p.select.any();
182 let mut out: Vec<Value> = Vec::new();
183 let mut bytes = 0usize;
184 let mut truncated = false;
185 for k in kept.into_iter().skip(p.offset).take(limit) {
186 let Kept { mut row, model } = k;
187 if let (Some(model), Some(a)) = (model, agent_of(&row).map(|a| (a.uid.to_string(), a.name.to_string(), a.provider.to_string(), a.block_id.map(str::to_string), a.state.to_string(), a.container))) {
188 row["model_label"] = json!(model.label);
189 row["model_source"] = json!(model.source);
190 if p.select.any() {
191 let agent = Agent { uid: &a.0, name: &a.1, provider: &a.2, block_id: a.3.as_deref(), state: &a.4, container: a.5 };
192 row["facts"] = json!(facts_of(ctx, &p.select, &agent, model));
193 }
194 }
195 bytes += row.to_string().len();
196 if bounded && bytes > DEFAULT_MAX_BYTES && !out.is_empty() {
197 truncated = true;
198 break;
199 }
200 out.push(row);
201 }
202 let page = json!({ "total": total, "returned": out.len(), "offset": p.offset, "limit": p.limit, "truncated": truncated, "bytes": bytes });
203 (out, page)
204}
205
206pub fn apply(state: &AppState, rows: Vec<Value>, p: &Params, now_ms: u64) -> (Vec<Value>, Value) {
208 let ctx = Ctx::new(state, now_ms, &p.select, p.filter.account.is_some());
209 let kept = filtered(&ctx, rows, p);
210 decorate_page(&ctx, kept, p)
211}
212
213pub fn short_duration(ms: u64) -> String {
215 let s = ms / 1000;
216 match s {
217 0..=59 => format!("{s}s"),
218 60..=3599 => format!("{}m", s / 60),
219 _ => format!("{}h {}m", s / 3600, (s % 3600) / 60),
220 }
221}
222
223fn usage_short(u: &crate::backend::account_usage::AccountUsage) -> String {
225 let mut windows: Vec<(&String, &crate::backend::account_usage::UsageWindow)> = u.windows.iter().collect();
226 windows.sort_by_key(|(_, w)| w.resets_at_ms);
227 let name = |k: &str| match k {
228 "five_hour" => "5h".to_string(),
229 "seven_day" => "7d".to_string(),
230 other => other.replace('_', " "),
231 };
232 windows.iter().map(|(k, w)| format!("{} {}%", name(k), w.used_percent.round())).collect::<Vec<_>>().join(" ")
233}
234
235pub fn status_line(name: &str, state: &str, facts: &LiveFacts, model: &ModelFacts) -> String {
238 let mut parts: Vec<String> = vec![name.to_string()];
239 let turn = facts.turn.as_ref().filter(|t| t.active).and_then(|t| t.duration_ms).map(|d| format!(" (turn {})", short_duration(d))).unwrap_or_default();
240 let quiet = facts.quiet.as_ref().map(|q| format!(", quiet {}", short_duration(q.quiet_ms))).unwrap_or_default();
241 parts.push(format!("{state}{turn}{quiet}"));
242 let mut m = model.label.clone().or_else(|| model.id.clone()).unwrap_or_else(|| "model unknown".to_string());
243 if let Some(e) = &model.effort {
244 m = format!("{m} {e}");
245 }
246 if model.source == ModelSource::Requested || model.pending_switch {
247 m.push('?');
248 }
249 parts.push(m);
250 if let Some(p) = facts.context.as_ref().and_then(|c| c.percent) {
251 parts.push(format!("ctx {}%", p.round()));
252 }
253 if let Some(a) = &facts.account {
254 parts.push(a.label.clone());
255 }
256 if let Some(u) = facts.usage.as_ref().filter(|u| !u.windows.is_empty()) {
257 parts.push(usage_short(u));
258 }
259 if let Some(t) = &facts.task {
260 parts.push(format!("#{}", t.number));
261 }
262 parts.join(" | ")
263}
264
265fn key_of(group: &str, name_state: &str, model: &ModelFacts, a: &Agent, facts: &LiveFacts, host: &str) -> String {
267 match group {
268 "model" => model.label.clone().or_else(|| model.id.clone()).unwrap_or_else(|| "unknown".to_string()),
269 "state" => name_state.to_string(),
270 "host" => host.to_string(),
271 "account" => facts.account.as_ref().map_or_else(|| "none".to_string(), |x| x.label.clone()),
272 "provider" => a.provider.to_string(),
273 _ => if a.container { "container" } else { "native" }.to_string(),
274 }
275}
276
277pub fn status(state: &AppState, rows: Vec<Value>, p: &Params, now_ms: u64) -> Value {
279 let mut sel = p.select;
280 for group in ["model", "turn", "context", "account", "usage", "task", "quiet"] {
281 let _ = sel.set(group);
282 }
283 let p = Params { select: sel, ..p.clone() };
284 let ctx = Ctx::new(state, now_ms, &p.select, p.filter.account.is_some());
285 let kept = filtered(&ctx, rows, &p);
286 let total = kept.len();
287 let host = state.hostname.clone();
288 let (mut lines, mut by_state, mut by_model, mut groups): (Vec<String>, BTreeMap<String, usize>, BTreeMap<String, usize>, BTreeMap<String, Vec<String>>) =
289 (Vec::new(), BTreeMap::new(), BTreeMap::new(), BTreeMap::new());
290 for k in kept.into_iter().skip(p.offset).take(p.limit.unwrap_or(usize::MAX)) {
291 let Some(a) = agent_of(&k.row) else { continue };
292 let Some(model) = k.model else { continue };
293 let facts = facts_of(&ctx, &p.select, &a, model.clone());
294 lines.push(status_line(a.name, a.state, &facts, &model));
295 *by_state.entry(a.state.to_string()).or_default() += 1;
296 *by_model.entry(key_of("model", a.state, &model, &a, &facts, &host)).or_default() += 1;
297 if let Some(g) = p.group_by.as_deref() {
298 groups.entry(key_of(g, a.state, &model, &a, &facts, &host)).or_default().push(a.name.to_string());
299 }
300 }
301 let mut out = json!({
302 "host": host,
303 "total": total,
304 "returned": lines.len(),
305 "lines": lines,
306 "counts": { "by_state": by_state, "by_model": by_model, "by_host": { host.clone(): lines.len() } },
307 });
308 if let Some(g) = p.group_by.as_deref() {
309 out["group_by"] = json!(g);
310 out["groups"] = json!(groups.into_iter().map(|(k, v)| json!({ "key": k, "count": v.len(), "agents": v })).collect::<Vec<_>>());
311 }
312 out
313}
314
315#[cfg(test)]
316#[path = "query_tests.rs"]
317mod tests;