1use std::collections::BTreeMap;
23use std::path::Path;
24use std::sync::Arc;
25
26use serde::{Deserialize, Serialize};
27use serde_json::{json, Value};
28
29pub const INSTALL_SUBTYPE: &str = "agentmux_cli_install";
30pub const CONTAINER_START_SUBTYPE: &str = "agentmux_container_start";
32pub const VERSION_CHANGED_SUBTYPE: &str = "agentmux_cli_version_changed";
33pub const CONTAINER_IMAGE_SUBTYPE: &str = "agentmux_container_image";
34pub const CONTAINER_LIMIT_SUBTYPE: &str = "agentmux_container_limit";
35pub const CONTAINER_CACHES_SUBTYPE: &str = "agentmux_container_caches";
36pub const MCP_LEFT_OUT_SUBTYPE: &str = "agentmux_mcp_left_out";
38pub const AGENT_READY_SUBTYPE: &str = "agentmux_agent_ready";
40
41pub const RECORD_FILE: &str = "agent-cli-versions.json";
44
45pub fn record_dir(paths: &agentmux_common::DataPaths) -> &Path {
53 &paths.instance_dir
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum InstallState {
59 Installing,
60 Installed,
61 Failed,
62}
63
64impl InstallState {
65 fn as_str(self) -> &'static str {
66 match self {
67 Self::Installing => "installing",
68 Self::Installed => "installed",
69 Self::Failed => "failed",
70 }
71 }
72}
73
74pub fn version_token(raw: &str) -> Option<String> {
78 raw.split(|c: char| c.is_whitespace() || c == ',' || c == '(' || c == ')')
79 .map(|t| t.trim_start_matches('v'))
80 .find(|t| t.contains('.') && t.chars().next().is_some_and(|c| c.is_ascii_digit()))
81 .map(str::to_string)
82}
83
84pub fn install_frame(
87 install_id: &str,
88 provider: &str,
89 version: &str,
90 state: InstallState,
91 seconds: Option<f64>,
92 error: Option<&str>,
93) -> Value {
94 let mut frame = json!({
95 "type": "system",
96 "subtype": INSTALL_SUBTYPE,
97 "install_id": install_id,
98 "provider": provider,
99 "version": version,
100 "state": state.as_str(),
101 "timestamp": chrono::Utc::now().to_rfc3339(),
102 });
103 if let Some(s) = seconds {
104 frame["seconds"] = json!((s * 10.0).round() / 10.0);
105 }
106 if let Some(e) = error {
107 frame["error"] = json!(e);
108 }
109 frame
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum ContainerStartState {
115 Pulling,
117 Starting,
119 Ready,
121 Failed,
122}
123
124impl ContainerStartState {
125 pub fn as_str(self) -> &'static str {
126 match self {
127 Self::Pulling => "pulling",
128 Self::Starting => "starting",
129 Self::Ready => "ready",
130 Self::Failed => "failed",
131 }
132 }
133}
134
135pub fn container_start_frame(
139 start_id: &str,
140 provider: &str,
141 image: &str,
142 state: ContainerStartState,
143 percent: Option<u8>,
144 seconds: Option<f64>,
145 error: Option<&str>,
146) -> Value {
147 let mut frame = json!({
148 "type": "system",
149 "subtype": CONTAINER_START_SUBTYPE,
150 "start_id": start_id,
151 "provider": provider,
152 "image": image,
153 "state": state.as_str(),
154 "timestamp": chrono::Utc::now().to_rfc3339(),
155 });
156 if let Some(p) = percent {
157 frame["percent"] = json!(p.min(100));
158 }
159 if let Some(s) = seconds {
160 frame["seconds"] = json!((s * 10.0).round() / 10.0);
161 }
162 if let Some(e) = error {
163 frame["error"] = json!(e);
164 }
165 frame
166}
167
168pub fn agent_ready_frame(ready_id: &str, provider: &str, seconds: f64) -> Value {
171 json!({
172 "type": "system",
173 "subtype": AGENT_READY_SUBTYPE,
174 "ready_id": ready_id,
175 "provider": provider,
176 "seconds": (seconds * 10.0).round() / 10.0,
177 "timestamp": chrono::Utc::now().to_rfc3339(),
178 })
179}
180
181pub fn container_image_frame(provider: &str, block_id: &str, state: &str, running: &str, current: &str) -> Value {
186 json!({
187 "type": "system",
188 "subtype": CONTAINER_IMAGE_SUBTYPE,
189 "provider": provider,
190 "block_id": block_id,
191 "state": state,
192 "running": running,
193 "current": current,
194 "timestamp": chrono::Utc::now().to_rfc3339(),
195 })
196}
197
198#[allow(clippy::too_many_arguments)]
203pub fn container_limit_frame(
204 provider: &str,
205 block_id: &str,
206 agent: (&str, &str),
207 state: &str,
208 memory_mb: Option<u64>,
209 cpus: Option<f64>,
210 by: Option<&str>,
211 error: Option<&str>,
212) -> Value {
213 let mut frame = json!({
214 "type": "system",
215 "subtype": CONTAINER_LIMIT_SUBTYPE,
216 "provider": provider,
217 "block_id": block_id,
218 "agent_id": agent.0,
219 "agent_name": agent.1,
220 "event_id": uuid::Uuid::new_v4().to_string(),
221 "state": state,
222 "timestamp": chrono::Utc::now().to_rfc3339(),
223 });
224 if let Some(mb) = memory_mb {
225 frame["memory_mb"] = json!(mb);
226 }
227 if let Some(cpus) = cpus {
228 frame["cpus"] = json!((cpus * 100.0).round() / 100.0);
229 }
230 if let Some(by) = by {
231 frame["by"] = json!(by);
232 }
233 if let Some(error) = error {
234 frame["error"] = json!(error);
235 }
236 frame
237}
238
239pub fn container_caches_frame(provider: &str, block_id: &str, agent: (&str, &str), bytes: u64) -> Value {
242 json!({
243 "type": "system",
244 "subtype": CONTAINER_CACHES_SUBTYPE,
245 "provider": provider,
246 "block_id": block_id,
247 "agent_id": agent.0,
248 "agent_name": agent.1,
249 "event_id": uuid::Uuid::new_v4().to_string(),
250 "bytes": bytes,
251 "timestamp": chrono::Utc::now().to_rfc3339(),
252 })
253}
254
255pub fn mcp_left_out_frame(provider: &str, block_id: &str, names: &[String], folder: &crate::backend::host_agent_files::LeftOut, no_path: &[String]) -> Value {
261 json!({
262 "type": "system",
263 "subtype": MCP_LEFT_OUT_SUBTYPE,
264 "provider": provider,
265 "block_id": block_id,
266 "event_id": uuid::Uuid::new_v4().to_string(),
267 "names": names,
268 "folder": folder,
269 "no_path": no_path,
270 "timestamp": chrono::Utc::now().to_rfc3339(),
271 })
272}
273
274pub fn version_changed_frame(provider: &str, from: &str, to: &str, pinned: Option<&str>) -> Value {
278 json!({
279 "type": "system",
280 "subtype": VERSION_CHANGED_SUBTYPE,
281 "provider": provider,
282 "from": from,
283 "to": to,
284 "pinned": pinned,
285 "timestamp": chrono::Utc::now().to_rfc3339(),
286 })
287}
288
289pub fn append_to_pane(
292 broker: &Arc<crate::backend::mps::Broker>,
293 filestore: &Arc<crate::backend::storage::filestore::FileStore>,
294 mstore: &Arc<crate::backend::storage::store::Store>,
295 block_id: &str,
296 frame: &Value,
297) {
298 append_line_to_pane(broker, filestore, mstore, block_id, &frame.to_string());
299}
300
301pub fn append_line_to_pane(
304 broker: &Arc<crate::backend::mps::Broker>,
305 filestore: &Arc<crate::backend::storage::filestore::FileStore>,
306 mstore: &Arc<crate::backend::storage::store::Store>,
307 block_id: &str,
308 line: &str,
309) {
310 let line = format!("{line}\n");
311 let zone = crate::backend::transcript::append::resolve_global_output_zone(&Some(mstore.clone()), block_id);
312 crate::backend::blockcontroller::shell::handle_append_block_file(
313 broker,
314 block_id,
315 crate::backend::blockcontroller::persistent::PERSISTENT_OUTPUT_SUBJECT,
316 line.as_bytes(),
317 Some(filestore),
318 zone.as_deref(),
319 );
320}
321
322#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
323struct LastCli {
324 provider: String,
325 version: String,
326 at: i64,
327}
328
329static RECORD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
331
332pub fn observe_version(dir: &Path, agent_key: &str, provider: &str, version: &str) -> Option<String> {
338 let _guard = RECORD_LOCK.lock().unwrap_or_else(|p| p.into_inner());
339 let path = dir.join(RECORD_FILE);
340 let mut records: BTreeMap<String, LastCli> = std::fs::read(&path)
341 .ok()
342 .and_then(|bytes| serde_json::from_slice(&bytes).ok())
343 .unwrap_or_default();
344 let previous = records.get(agent_key).cloned();
345 if previous.as_ref().is_some_and(|p| p.provider == provider && p.version == version) {
346 return None;
347 }
348 records.insert(
349 agent_key.to_string(),
350 LastCli { provider: provider.to_string(), version: version.to_string(), at: agentmux_common::time::now_ms() },
351 );
352 let tmp = path.with_extension("json.tmp");
353 let written = serde_json::to_vec_pretty(&records)
354 .map_err(|e| e.to_string())
355 .and_then(|bytes| std::fs::write(&tmp, bytes).map_err(|e| e.to_string()))
356 .and_then(|()| std::fs::rename(&tmp, &path).map_err(|e| e.to_string()));
357 if let Err(e) = written {
358 tracing::warn!(path = %path.display(), error = %e, "cli notice: could not save the last-run CLI version");
359 }
360 previous.filter(|p| p.provider == provider).map(|p| p.version)
361}
362
363pub fn agent_key_of_block(mstore: &crate::backend::storage::store::Store, block_id: &str) -> Option<String> {
367 let block = mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
368 let id = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
369 (!id.trim().is_empty()).then_some(id)
370}
371
372pub fn observe_and_notify(
378 broker: &Arc<crate::backend::mps::Broker>,
379 filestore: &Arc<crate::backend::storage::filestore::FileStore>,
380 mstore: &Arc<crate::backend::storage::store::Store>,
381 block_id: &str,
382 agent_id: Option<&str>,
383 provider: &str,
384 version: &str,
385) {
386 let Some(agent_key) = agent_id.map(str::to_string).or_else(|| agent_key_of_block(mstore, block_id)) else {
387 return;
388 };
389 let Some(paths) = agentmux_common::DataPaths::from_env() else { return };
390 if let Some(from) = observe_version(record_dir(&paths), &agent_key, provider, version) {
391 let pinned = crate::backend::providers::get_provider(provider).map(|p| p.pinned_version);
392 tracing::info!(block_id, provider, from = %from, to = version, "cli notice: agent's CLI version changed");
393 append_to_pane(broker, filestore, mstore, block_id, &version_changed_frame(provider, &from, version, pinned));
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400
401 #[test]
402 fn the_container_image_frame_names_its_pane_and_both_versions() {
403 let f = container_image_frame("claude", "blk-1", "outdated", "0.59.41", "0.60.2");
404 assert_eq!(f["subtype"], CONTAINER_IMAGE_SUBTYPE);
405 assert_eq!((f["block_id"].as_str(), f["state"].as_str()), (Some("blk-1"), Some("outdated")));
406 assert_eq!((f["running"].as_str(), f["current"].as_str()), (Some("0.59.41"), Some("0.60.2")));
407 }
408
409 #[test]
410 fn the_container_limit_frame_carries_the_limits_in_force_and_who_changed_them() {
411 let f = container_limit_frame("claude", "blk-1", ("a-1", "Aria"), "changed", Some(8192), Some(6.004), Some("Agent1"), None);
412 assert_eq!(f["subtype"], CONTAINER_LIMIT_SUBTYPE);
413 assert_eq!((f["state"].as_str(), f["block_id"].as_str(), f["by"].as_str()), (Some("changed"), Some("blk-1"), Some("Agent1")));
414 assert_eq!((f["memory_mb"].as_u64(), f["cpus"].as_f64()), (Some(8192), Some(6.0)));
415 assert!(f["event_id"].as_str().is_some_and(|id| !id.is_empty()), "each event is its own row");
416 assert_eq!((f["agent_id"].as_str(), f["agent_name"].as_str()), (Some("a-1"), Some("Aria")));
417 let oom = container_limit_frame("claude", "blk-1", ("a-1", "Aria"), "oom", Some(256), None, None, None);
418 assert!(oom.get("by").is_none() && oom.get("cpus").is_none() && oom.get("error").is_none());
419 }
420
421 #[test]
422 fn the_container_caches_frame_carries_the_size_and_whose_container_it_is() {
423 let f = container_caches_frame("claude", "blk-1", ("a-1", "Aria"), 25_769_803_776);
424 assert_eq!(f["subtype"], CONTAINER_CACHES_SUBTYPE);
425 assert_eq!((f["bytes"].as_u64(), f["block_id"].as_str()), (Some(25_769_803_776), Some("blk-1")));
426 assert_eq!((f["agent_id"].as_str(), f["agent_name"].as_str()), (Some("a-1"), Some("Aria")));
427 assert!(f["event_id"].as_str().is_some_and(|id| !id.is_empty()));
428 }
429
430 #[test]
432 fn a_container_start_frame_carries_what_the_pane_reads() {
433 let f = container_start_frame("s1", "claude", "img:1", ContainerStartState::Pulling, Some(150), None, None);
434 assert_eq!(f["type"], "system");
435 assert_eq!(f["subtype"], "agentmux_container_start");
436 assert_eq!(f["start_id"], "s1");
437 assert_eq!(f["provider"], "claude");
438 assert_eq!(f["image"], "img:1");
439 assert_eq!(f["state"], "pulling");
440 assert_eq!(f["percent"], 100, "a percentage never reads above 100");
441 assert!(f.get("seconds").is_none() && f.get("error").is_none());
442 let failed = container_start_frame("s1", "claude", "img:1", ContainerStartState::Failed, None, None, Some("why"));
443 assert_eq!((failed["state"].as_str(), failed["error"].as_str()), (Some("failed"), Some("why")));
444 }
445
446 #[test]
447 fn version_token_finds_the_number() {
448 assert_eq!(version_token("2.1.285 (Claude Code)").as_deref(), Some("2.1.285"));
449 assert_eq!(version_token("codex-cli 0.154.0").as_deref(), Some("0.154.0"));
450 assert_eq!(version_token("v0.60.0").as_deref(), Some("0.60.0"));
451 assert_eq!(version_token("unknown"), None);
452 assert_eq!(version_token(""), None);
453 }
454
455 #[test]
456 fn first_run_records_without_a_notice_then_a_change_returns_the_old_version() {
457 let dir = tempfile::tempdir().unwrap();
458 assert_eq!(observe_version(dir.path(), "uid-1", "claude", "2.1.218"), None);
459 assert_eq!(observe_version(dir.path(), "uid-1", "claude", "2.1.218"), None, "same version");
460 assert_eq!(observe_version(dir.path(), "uid-1", "claude", "2.1.285").as_deref(), Some("2.1.218"));
461 assert_eq!(observe_version(dir.path(), "uid-1", "claude", "2.1.285"), None, "recorded the new one");
462 }
463
464 #[test]
465 fn agents_are_independent_and_a_provider_switch_is_not_an_upgrade() {
466 let dir = tempfile::tempdir().unwrap();
467 observe_version(dir.path(), "uid-1", "claude", "2.1.218");
468 assert_eq!(observe_version(dir.path(), "uid-2", "claude", "2.1.285"), None, "other agent's first run");
469 assert_eq!(observe_version(dir.path(), "uid-1", "codex", "0.154.0"), None, "switched provider");
470 assert_eq!(observe_version(dir.path(), "uid-1", "codex", "0.155.0").as_deref(), Some("0.154.0"));
471 }
472
473 #[test]
474 fn an_unreadable_record_is_treated_as_empty() {
475 let dir = tempfile::tempdir().unwrap();
476 std::fs::write(dir.path().join(RECORD_FILE), b"not json").unwrap();
477 assert_eq!(observe_version(dir.path(), "uid-1", "claude", "2.1.285"), None);
478 assert_eq!(observe_version(dir.path(), "uid-1", "claude", "2.1.286").as_deref(), Some("2.1.285"));
479 }
480
481 #[test]
482 fn frames_carry_what_the_pane_shows() {
483 let f = install_frame("claude-2.1.285-1", "claude", "2.1.285", InstallState::Installed, Some(14.04), None);
484 assert_eq!(f["subtype"], INSTALL_SUBTYPE);
485 assert_eq!(f["state"], "installed");
486 assert_eq!(f["seconds"], 14.0);
487 assert!(f.get("error").is_none());
488 let failed = install_frame("i", "claude", "2.1.285", InstallState::Failed, None, Some("exit 1"));
489 assert_eq!(failed["error"], "exit 1");
490
491 let ready = agent_ready_frame("r1", "claude", 18.04);
492 assert_eq!((ready["subtype"].as_str(), ready["ready_id"].as_str(), ready["seconds"].as_f64()), (Some(AGENT_READY_SUBTYPE), Some("r1"), Some(18.0)));
493
494 let v = version_changed_frame("claude", "2.1.218", "2.1.285", Some("2.1.285"));
495 assert_eq!(v["subtype"], VERSION_CHANGED_SUBTYPE);
496 assert_eq!((v["from"].as_str(), v["to"].as_str(), v["pinned"].as_str()), (Some("2.1.218"), Some("2.1.285"), Some("2.1.285")));
497 }
498}