Skip to main content

agentmux_srv_core/backend/
cli_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pane notices about an agent's CLI
5//! (SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_STARTUP_FILES_2026_09_30.md §6.3,
6//! phase LC4):
7//!
8//! - **Install:** while `ResolveCli` npm-installs the pinned CLI for a pane,
9//!   an `agentmux_cli_install` frame says so — `installing`, then
10//!   `installed` or `failed`, under one `install_id` so the row updates in
11//!   place. A pane restored at startup used to install silently.
12//! - **Version change:** each agent's last-run CLI version is kept in
13//!   [`RECORD_FILE`], in the channel directory ([`record_dir`]). When the agent's CLI next starts on a different
14//!   version, an `agentmux_cli_version_changed` frame tells the user
15//!   (`from`, `to`, and the version AgentMux pins).
16//!
17//! Both are `system` frames appended to the pane's output, so they replay
18//! with the transcript, and the digest never reads them (it only reads
19//! assistant/user/result lines). They are for the user; the agent's context
20//! is unchanged.
21
22use 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";
30/// Subtype of the frames that say how a container agent's container is coming up.
31pub 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";
36/// Subtype of the frame that names the MCP servers a host agent is not given from its folder's own file.
37pub const MCP_LEFT_OUT_SUBTYPE: &str = "agentmux_mcp_left_out";
38/// Subtype of the frame that says a container agent is ready and waiting for its first message.
39pub const AGENT_READY_SUBTYPE: &str = "agentmux_agent_ready";
40
41/// Per-agent last-run CLI versions, in [`record_dir`] (no schema change: a
42/// new column would lock older builds out of a shared store.db).
43pub const RECORD_FILE: &str = "agent-cli-versions.json";
44
45/// Where [`RECORD_FILE`] lives: the channel directory
46/// (`~/.agentmux/channels/<channel>/`, or a dev build's own root), next to
47/// the shared store that holds the agents it is keyed by. Not `data_dir`:
48/// an installed build's data dir is per AgentMux version
49/// (`channels/<ch>/versions/<v>/data/`), so after an upgrade every agent
50/// would read as a first run and the upgrade this exists to report would
51/// go unnoticed (ReAgent P1 on #4128).
52pub fn record_dir(paths: &agentmux_common::DataPaths) -> &Path {
53    &paths.instance_dir
54}
55
56/// Where an install stands.
57#[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
74/// The version number in a CLI's `--version` output, e.g. `"2.1.285"` from
75/// `"2.1.285 (Claude Code)"` or `"codex-cli 0.154.0"`. `None` if there is
76/// none (`"unknown"`, an empty string).
77pub 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
84/// An `agentmux_cli_install` frame. `install_id` is the same for every frame
85/// of one install, so the pane updates one row.
86pub 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/// Where a container agent's start-up is.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum ContainerStartState {
115    /// The image is being downloaded.
116    Pulling,
117    /// The image is here; the container is being created.
118    Starting,
119    /// The container is up.
120    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
135/// An `agentmux_container_start` frame. `start_id` is the same for every frame
136/// of one start-up, so the pane updates one row. `percent` is how much of the
137/// image has arrived, once the daemon has said.
138pub 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
168/// An `agentmux_agent_ready` frame: a container agent's container and CLI are up and nothing is on
169/// its way to it, so the pane waits for the user's first message. `seconds` is the whole start-up.
170pub 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
181/// An `agentmux_container_image` frame: the container runs an older agent image than this
182/// AgentMux (`state` `outdated`), has just been removed on request so the next message starts it from
183/// the current one (`updated`), or was moved to the current one by AgentMux itself while the agent was idle
184/// (`auto_updated`).
185pub 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/// An `agentmux_container_limit` frame: a container's CPU or memory limit changed (`state` `changed`, by `by`),
199/// something in the container was stopped for going over its memory limit (`oom`), or the daemon refused a limit
200/// (`failed`, with `error`). `agent` is the agent's id and name, for the row's button. `memory_mb` and `cpus` are
201/// the limits in force; each frame is its own row.
202#[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
239/// An `agentmux_container_caches` frame: the cache volumes of a container agent (a developer agent's cargo registry and
240/// build output) hold `bytes`, more than the warning level. `agent` is the agent's id and name, for the row's button.
241pub 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
255/// An `agentmux_mcp_left_out` frame: a container agent can write the folder of the host agent on `block_id`, so
256/// the agent takes nothing of the folder's own configuration (`mcp_folder_rule`, `host_agent_files`). `names`
257/// are the servers its folder's own `.mcp.json` lists besides the agent's, `folder` is what else of the folder
258/// is not loaded, by kind and count, and `no_path` are the agent's own servers left out because their command
259/// has no path outside the folder.
260pub 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
274/// An `agentmux_cli_version_changed` frame. `pinned` is the version this
275/// AgentMux build installs, so the pane can say when `to` isn't it (a
276/// self-update, or a stale install).
277pub 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
289/// Append `frame` to `block_id`'s output (and the agent's global transcript
290/// zone), as the memory-delivery notice does.
291pub 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
301/// [`append_to_pane`] for a frame already serialized to its one line (no
302/// trailing newline).
303pub 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
329/// Serializes read-modify-write of [`RECORD_FILE`] within this srv.
330static RECORD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
331
332/// Record that `agent_key`'s CLI just started on `version`, and return the
333/// version it last ran if that was a different one of the same provider.
334/// A first run, or a switch to another provider, records and returns `None`.
335/// A record that can't be read or written is logged and treated as empty:
336/// at worst a notice is missed, never a launch.
337pub 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
363/// The key an agent's record is kept under: the block's `agentId` (the
364/// agent's UID, or a provider key for a quick-launch pane). `None` for a
365/// block with no agent.
366pub 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
372/// Observe `version` for an agent and, if it changed, append the notice to
373/// `block_id`'s pane. The agent is `agent_id` when the caller knows it (a
374/// new pane resolves its CLI before its `agentId` meta is written), else
375/// the pane's `agentId`. The one entry point both sources use: Claude's own
376/// `system/init` frame, and `ResolveCli` for the other providers.
377pub 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    /// The pane (`frontend/app/view/agent/cli-notice.ts`) reads these field names.
431    #[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}