Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

mux: identify agents through interpreter argv, survive binary swaps

RoversX6583c0b0f959
diff --git a/mux/src/agent_status/identify.rs b/mux/src/agent_status/identify.rs
index 46382eef..416e2e6a 100644
--- a/mux/src/agent_status/identify.rs
+++ b/mux/src/agent_status/identify.rs
@@ -53,12 +53,23 @@ fn probe(pane: &dyn Pane) -> CachedIdent {
} else {
CachePolicy::FetchImmediate
};
- let leader_path = pane.get_foreground_process_name(policy);
+ let leader_path = pane
+ .get_foreground_process_name(policy)
+ .map(normalize_executable_path);
let resolved = CachedIdent {
at: now,
- agent: leader_path
- .as_deref()
- .and_then(identify_from_process_path),
+ agent: leader_path.as_deref().and_then(|path| {
+ // argv is fetched only if the leader turns out to be a generic
+ // interpreter, and always AllowStale: the name probe one step
+ // up just refreshed the leader cache, so this reuses that same
+ // pid. Re-probing here could race a foreground change and pair
+ // this argv with the other probe's path — and on Windows a
+ // FetchImmediate would repeat a full process-table walk.
+ let mut argv = || pane.get_foreground_process_argv(CachePolicy::AllowStale);
+ super::proc_match::identify(path, &mut argv, &|name| {
+ super::engine::manifest_id_for_alias(name)
+ })
+ }),
leader_path,
};
@@ -110,98 +121,34 @@ pub fn forget_pane(pane_id: crate::pane::PaneId) {
}
}
-/// Match a foreground executable path to a manifest id: by basename, and
-/// failing that by the last few directory components. Version-managed
-/// launchers exec a binary named after the version — e.g. Claude Code runs
-/// as `~/.local/share/claude/versions/2.1.239` — so the agent's name only
-/// appears as a parent directory.
-fn identify_from_process_path(path: &str) -> Option<String> {
- let name = basename(path).to_lowercase();
- if let Some(id) = super::engine::manifest_id_for_alias(&name) {
- return Some(id);
+/// On Linux, `/proc/<pid>/exe` reads as `/path/to/bin (deleted)` once the
+/// binary has been replaced on disk — routine for self-updating agents.
+/// Normalizing here, at the module's single entry point for the path,
+/// keeps both identification and the contract's leader-path equality
+/// working across an in-place update. macOS resolves via `proc_pidpath`,
+/// which never decorates the path, so this is a no-op there.
+fn normalize_executable_path(path: String) -> String {
+ match path.strip_suffix(" (deleted)") {
+ Some(stripped) => stripped.to_string(),
+ None => path,
}
- // Directory components only vouch for a *versioned launcher* layout
- // (`~/.local/share/claude/versions/2.1.239`). Without the version-like
- // basename gate, any executable under an alias-named directory would
- // be misidentified — e.g. everything in `/home/pi/.local/bin`.
- if !looks_like_version(&name) {
- return None;
- }
- path.rsplit(['/', '\\'])
- .skip(1)
- .take(2)
- .find_map(|component| super::engine::manifest_id_for_alias(&component.to_lowercase()))
-}
-
-/// A launcher-style version basename: starts with a digit, rest is
-/// digits/letters/dots/dashes ("2.1.239", "1.0.0-rc1").
-fn looks_like_version(name: &str) -> bool {
- let mut chars = name.chars();
- matches!(chars.next(), Some(c) if c.is_ascii_digit())
- && chars.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
-}
-
-fn basename(path: &str) -> &str {
- let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
- name.strip_suffix(".exe").unwrap_or(name)
}
#[cfg(test)]
mod tests {
- use super::basename;
-
- #[test]
- fn basenames() {
- assert_eq!(basename("/usr/local/bin/claude"), "claude");
- assert_eq!(basename("codex"), "codex");
- assert_eq!(basename("C:\\tools\\codex.exe"), "codex");
- }
-
- #[test]
- fn versioned_launcher_paths_identify_by_parent_directory() {
- assert_eq!(
- super::identify_from_process_path("/Users/x/.local/share/claude/versions/2.1.239")
- .as_deref(),
- Some("claude")
- );
- assert_eq!(
- super::identify_from_process_path("/usr/local/bin/claude").as_deref(),
- Some("claude")
- );
- assert_eq!(super::identify_from_process_path("/bin/zsh"), None);
- // The component match only looks at the trailing directories, so a
- // deep unrelated prefix cannot misidentify.
- assert_eq!(
- super::identify_from_process_path("/home/claude/projects/tool/bin/node"),
- None
- );
- }
+ // Matching-rule behavior is covered in `proc_match`'s own tests
+ // against a fake alias table; this module only owns the path
+ // normalization and the cache.
- /// Directory names vouch only for versioned launchers: an ordinary
- /// binary living under an alias-named directory (a user named `pi`,
- /// say) must not be misidentified.
#[test]
- fn alias_named_directories_do_not_claim_ordinary_binaries() {
- assert_eq!(
- super::identify_from_process_path("/home/pi/.local/bin/htop"),
- None
- );
- // Even a version-like basename doesn't help when the alias is a
- // grandparent past the two-component window — `pi` here is the
- // user's home, not a launcher directory.
- assert_eq!(
- super::identify_from_process_path("/home/pi/.local/bin/2.0.1"),
- None
- );
- // A real launcher layout for the same agent still identifies.
+ fn replaced_binaries_lose_their_deleted_decoration() {
assert_eq!(
- super::identify_from_process_path("/home/x/pi/versions/2.0.1").as_deref(),
- Some("pi")
+ super::normalize_executable_path("/usr/local/bin/claude (deleted)".to_string()),
+ "/usr/local/bin/claude"
);
- // The gate also bounds the walk to the last two directories.
assert_eq!(
- super::identify_from_process_path("/opt/claude/deep/nested/2.1.0"),
- None
+ super::normalize_executable_path("/usr/local/bin/claude".to_string()),
+ "/usr/local/bin/claude"
);
}
}
diff --git a/mux/src/agent_status/mod.rs b/mux/src/agent_status/mod.rs
index fd4cc008..0271aff7 100644
--- a/mux/src/agent_status/mod.rs
+++ b/mux/src/agent_status/mod.rs
@@ -24,6 +24,7 @@ pub mod contract;
pub mod engine;
mod hysteresis;
pub mod identify;
+mod proc_match;
use crate::pane::{Pane, PaneId};
use crate::{Mux, MuxNotification};
@@ -268,9 +269,11 @@ fn mark_dirty(pane_id: PaneId) {
/// since its last evaluation keeps serving a cached verdict (the
/// seqno-equality reuse), which was computed under the *old* rules and
/// would survive indefinitely. Safe to call from any thread; the caller
-/// may run it on a worker since loading reads manifest files.
-pub fn reload_rules() {
- engine::reload_manifests();
+/// may run it on a worker since loading reads manifest files. Returns how
+/// many manifest files were rejected, so the caller can report a partial
+/// reload instead of unconditional success.
+pub fn reload_rules() -> usize {
+ let rejected = engine::reload_manifests();
let panes: Vec<PaneId> = {
let mut registry = REGISTRY.write();
for record in registry.values_mut() {
@@ -281,6 +284,7 @@ pub fn reload_rules() {
for pane_id in panes {
mark_dirty(pane_id);
}
+ rejected
}
/// Drop a pane's state without telling anyone. Returns whether a published
@@ -771,6 +775,8 @@ mod tests {
user_vars: parking_lot::Mutex<HashMap<String, String>>,
seqno: AtomicUsize,
process: parking_lot::Mutex<Option<String>>,
+ argv: parking_lot::Mutex<Option<Vec<String>>>,
+ argv_probes: AtomicUsize,
probes: AtomicUsize,
remote_mirror: bool,
dead: AtomicBool,
@@ -790,6 +796,8 @@ mod tests {
user_vars: parking_lot::Mutex::new(HashMap::new()),
seqno: AtomicUsize::new(1),
process: parking_lot::Mutex::new(process.map(|p| p.to_string())),
+ argv: parking_lot::Mutex::new(None),
+ argv_probes: AtomicUsize::new(0),
probes: AtomicUsize::new(0),
remote_mirror: false,
dead: AtomicBool::new(false),
@@ -833,6 +841,12 @@ mod tests {
identify::forget_pane(self.id);
self.seqno.fetch_add(1, Ordering::SeqCst);
}
+
+ /// The leader's argv, as identification sees it when the leader
+ /// executable is a generic interpreter.
+ fn set_argv(&self, argv: &[&str]) {
+ *self.argv.lock() = Some(argv.iter().map(|a| a.to_string()).collect());
+ }
}
impl Pane for FakeAgentPane {
@@ -915,6 +929,10 @@ mod tests {
self.probes.fetch_add(1, Ordering::SeqCst);
self.process.lock().clone()
}
+ fn get_foreground_process_argv(&self, _policy: CachePolicy) -> Option<Vec<String>> {
+ self.argv_probes.fetch_add(1, Ordering::SeqCst);
+ self.argv.lock().clone()
+ }
fn send_paste(&self, _text: &str) -> anyhow::Result<()> {
unimplemented!();
}
@@ -994,6 +1012,79 @@ mod tests {
evict_pane(pane.pane_id());
}
+ /// An npm-installed agent runs as `node <shim>`: the leader executable
+ /// says only "node", and the agent's name rides in argv. This is the
+ /// installation style the basename-only identifier was blind to.
+ #[test]
+ fn interpreter_wrapped_agent_identifies_through_argv() {
+ let pane = FakeAgentPane::new(Some("/opt/homebrew/bin/node"));
+ pane.set_argv(&["node", "/opt/homebrew/bin/claude"]);
+ pane.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");
+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));
+ let status = status_for_pane(pane.pane_id()).expect("classified");
+ assert_eq!(status.agent_id, "claude");
+ assert_eq!(status.state, AgentState::Working);
+ assert_eq!(status.evidence, AgentEvidence::Screen);
+ evict_pane(pane.pane_id());
+
+ // A plain interpreter with no agent in its argv stays unidentified.
+ let plain = FakeAgentPane::new(Some("/opt/homebrew/bin/node"));
+ plain.set_argv(&["node", "/opt/tools/build.js"]);
+ plain.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");
+ assert!(!evaluate_pane(plain.as_ref() as &dyn Pane));
+ assert!(status_for_pane(plain.pane_id()).is_none());
+ evict_pane(plain.pane_id());
+
+ // A retitled interpreter (`process.title = "claude"` clobbered the
+ // argv block) identifies by the surviving argv[0].
+ let retitled = FakeAgentPane::new(Some("/opt/homebrew/Cellar/node/26.7.0/bin/node"));
+ retitled.set_argv(&["claude"]);
+ retitled.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");
+ assert!(evaluate_pane(retitled.as_ref() as &dyn Pane));
+ let status = status_for_pane(retitled.pane_id()).expect("classified");
+ assert_eq!(status.agent_id, "claude");
+ evict_pane(retitled.pane_id());
+ }
+
+ /// The argv read is lazy: a leader that names the agent directly must
+ /// never pay for it, and an interpreter leader pays exactly once per
+ /// identity-cache window, not once per evaluation.
+ #[test]
+ fn argv_is_fetched_only_for_interpreter_leaders() {
+ let direct = FakeAgentPane::new(Some("/usr/local/bin/claude"));
+ direct.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");
+ assert!(evaluate_pane(direct.as_ref() as &dyn Pane));
+ assert_eq!(direct.argv_probes.load(Ordering::SeqCst), 0);
+ evict_pane(direct.pane_id());
+
+ let wrapped = FakeAgentPane::new(Some("/usr/bin/node"));
+ wrapped.set_argv(&["node", "/opt/homebrew/bin/claude"]);
+ wrapped.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");
+ assert!(evaluate_pane(wrapped.as_ref() as &dyn Pane));
+ assert_eq!(wrapped.argv_probes.load(Ordering::SeqCst), 1);
+ // A second evaluation inside the identity TTL serves the cached
+ // identity without another argv read (the unchanged verdict means
+ // evaluate_pane reports no state change — irrelevant here).
+ wrapped.set_screen("more output\n⏵⏵ Cooking… (esc to interrupt · 13s)\n");
+ let _ = evaluate_pane(wrapped.as_ref() as &dyn Pane);
+ assert_eq!(wrapped.argv_probes.load(Ordering::SeqCst), 1);
+ evict_pane(wrapped.pane_id());
+ }
+
+ /// A self-updating agent replaces its own binary; Linux then reports
+ /// the leader as `/path/claude (deleted)`. Identification must survive
+ /// that, or detection silently dies right after every agent update.
+ #[test]
+ fn replaced_binary_still_identifies_as_its_agent() {
+ let pane = FakeAgentPane::new(Some("/usr/local/bin/claude (deleted)"));
+ pane.set_screen("some output\n⏵⏵ Cooking… (esc to interrupt · 12s)\n");
+ assert!(evaluate_pane(pane.as_ref() as &dyn Pane));
+ let status = status_for_pane(pane.pane_id()).expect("classified");
+ assert_eq!(status.agent_id, "claude");
+ assert_eq!(status.evidence, AgentEvidence::Screen);
+ evict_pane(pane.pane_id());
+ }
+
/// codex draws its trust prompt near the top of the screen and leaves
/// the rest blank; on a 40-row terminal the prompt must still reach
/// the `top_non_empty_lines` rules rather than falling outside the
diff --git a/mux/src/agent_status/proc_match.rs b/mux/src/agent_status/proc_match.rs
new file mode 100644
index 00000000..eb280cfa
--- /dev/null
+++ b/mux/src/agent_status/proc_match.rs
@@ -0,0 +1,572 @@
+//! Process-fact → agent matching rules, ported from herdr's
+//! identification layer (research/herdr/src/detect/mod.rs).
+//!
+//! Layering contract: this module performs no pane or process-table IO.
+//! The executable path and an argv thunk come in as arguments, the
+//! manifest alias table comes in as a lookup closure, and the only
+//! filesystem access is the final symlink-resolution tier. The usual
+//! maintenance edits — a new runtime, a new flag, a new package layout,
+//! a new process alias — are all table changes at the top of this file.
+
+/// Executables that are interpreters or shells: their own name says
+/// nothing about the agent, so only their argv can. Python is matched
+/// separately because of its versioned basenames (`python3.12`).
+const GENERIC_RUNTIMES: &[&str] = &[
+ "sh",
+ "bash",
+ "zsh",
+ "fish",
+ "tmux",
+ "node",
+ "bun",
+ "cmd",
+ "powershell",
+ "pwsh",
+];
+
+/// Stripped from a candidate name before the alias lookup, so `pi.js`
+/// and `codex.cmd` read as `pi` and `codex`. First match wins.
+const STRIP_SUFFIXES: &[&str] = &[".exe", ".cmd", ".bat", ".ps1", ".js"];
+
+/// Interpreter options that consume the next argv slot, so the argv scan
+/// does not mistake an option value for the script path
+/// (`node -r ./preload.js real-script.js`).
+const OPTIONS_TAKING_VALUE: &[&str] = &[
+ "-r",
+ "--require",
+ "--loader",
+ "--import",
+ "--experimental-loader",
+ "--inspect-port",
+ "-W",
+ "-X",
+ "-S",
+ "-L",
+ "-o",
+];
+
+/// Script paths whose basename is generic (`cli.js`, `index.js`) but
+/// whose package directory names the agent. Matched as a normalized
+/// path-component window; the last component is compared after suffix
+/// stripping. The id is re-checked against the manifest table so an
+/// entry without a manifest can never claim a pane.
+const KNOWN_PACKAGE_PATHS: &[(&[&str], &str)] = &[
+ (
+ &["node_modules", "@earendil-works", "pi-coding-agent", "dist", "cli"],
+ "pi",
+ ),
+ (
+ &[
+ "node_modules",
+ "@earendil-works",
+ "pi-coding-agent",
+ "dist",
+ "bundle",
+ "cli",
+ ],
+ "pi",
+ ),
+];
+
+/// Process names herdr recognizes in its code-side table that our
+/// manifest alias lists do not carry (the manifests assume herdr's own
+/// table exists). The id is re-checked against the manifests.
+const EXTRA_PROCESS_ALIASES: &[(&str, &str)] = &[
+ ("copilot", "github-copilot"),
+ ("opencode2", "opencode"),
+];
+
+/// Identify the agent behind a foreground process-group leader.
+///
+/// `leader_path` is the leader's executable path (already normalized of
+/// Linux's " (deleted)" decoration). `argv` is fetched only when the
+/// executable turns out to be a generic interpreter. `lookup` maps a
+/// normalized process name to a manifest id (id or alias).
+pub(crate) fn identify(
+ leader_path: &str,
+ argv: &mut dyn FnMut() -> Option<Vec<String>>,
+ lookup: &dyn Fn(&str) -> Option<String>,
+) -> Option<String> {
+ let name = normalized_lookup_name(basename(leader_path));
+ if is_generic_runtime(&name) {
+ // A runtime name can never identify by itself; unwrap or give up,
+ // so no manifest alias can ever claim every `node` on the box.
+ let argv = argv()?;
+ // Node's `process.title = "pi"` rewrites the argv block in place,
+ // and the OS reads the title back — often as the only surviving
+ // token, the original script path clobbered. That self-declared
+ // title is the strongest signal there is, so consult argv[0]
+ // before scanning for a script path. An unretitled interpreter
+ // has argv[0] = "node"/"bash"/…, which no manifest aliases.
+ if let Some(first) = argv.first() {
+ if let Some(id) = resolve_name(&normalized_lookup_name(basename(first)), lookup) {
+ return Some(id);
+ }
+ }
+ return wrapped_agent(&name, &argv, lookup);
+ }
+ if let Some(id) = resolve_name(&name, lookup) {
+ return Some(id);
+ }
+ versioned_launcher_agent(leader_path, &name, lookup)
+}
+
+/// One alias resolution: the manifest table first, then the code-side
+/// supplement (whose target must itself exist in the manifest table).
+fn resolve_name(name: &str, lookup: &dyn Fn(&str) -> Option<String>) -> Option<String> {
+ if let Some(id) = lookup(name) {
+ return Some(id);
+ }
+ EXTRA_PROCESS_ALIASES
+ .iter()
+ .find(|(alias, _)| *alias == name)
+ .and_then(|(_, id)| lookup(id))
+}
+
+/// The interpreter's argv decides. Eval payloads (`node -e …`,
+/// `python -c …`, `sh -c …`) are never mined for agent names — a token
+/// merely *looking* like an agent must not classify the pane.
+fn wrapped_agent(
+ runtime: &str,
+ argv: &[String],
+ lookup: &dyn Fn(&str) -> Option<String>,
+) -> Option<String> {
+ match runtime {
+ "node" => cursor_bundled_node_agent(argv, lookup)
+ .or_else(|| script_arg_agent(argv, &["-e", "--eval", "-p", "--print"], &[], lookup)),
+ "bun" => script_arg_agent(argv, &["-e", "--eval", "-p", "--print"], &[], lookup),
+ name if is_python_runtime(name) => script_arg_agent(argv, &["-c"], &["-m"], lookup),
+ "sh" | "bash" | "zsh" | "fish" => script_arg_agent(argv, &["-c"], &[], lookup),
+ // tmux wraps a server, not an agent. cmd/powershell text
+ // unwrapping belongs to the deferred Windows identification work.
+ _ => None,
+ }
+}
+
+/// Find the script path in an interpreter's argv: skip options (consuming
+/// values where the option takes one), bail out entirely on eval/module
+/// flags, honor `--` as "next token is the script".
+fn script_arg_agent(
+ argv: &[String],
+ eval_flags: &[&str],
+ module_flags: &[&str],
+ lookup: &dyn Fn(&str) -> Option<String>,
+) -> Option<String> {
+ let mut args = argv.iter().skip(1);
+ while let Some(arg) = args.next() {
+ if arg == "--" {
+ return args.next().and_then(|token| agent_from_path_token(token, lookup));
+ }
+ if flag_matches(arg, eval_flags) || flag_matches(arg, module_flags) {
+ return None;
+ }
+ if arg.starts_with('-') {
+ if OPTIONS_TAKING_VALUE.contains(&arg.as_str()) {
+ let _ = args.next();
+ }
+ continue;
+ }
+ return agent_from_path_token(arg, lookup);
+ }
+ None
+}
+
+/// `-e`, `-epayload`, `--eval`, and `--eval=payload` all count.
+fn flag_matches(arg: &str, flags: &[&str]) -> bool {
+ flags.iter().any(|flag| {
+ arg == *flag
+ || (!flag.starts_with("--") && arg.len() > flag.len() && arg.starts_with(flag))
+ || (flag.starts_with("--")
+ && arg.starts_with(flag)
+ && arg.as_bytes().get(flag.len()) == Some(&b'='))
+ })
+}
+
+/// Cursor ships its own node: `<pkg>/versions/<ver>/node[.exe]` running
+/// `<same directory>/index.js`. Neither basename names the agent, so the
+/// install layout has to — and only that exact layout: a system node
+/// running some unrelated `…/cursor-agent/versions/x/index.js` lives in a
+/// different parent directory and must not match.
+fn cursor_bundled_node_agent(
+ argv: &[String],
+ lookup: &dyn Fn(&str) -> Option<String>,
+) -> Option<String> {
+ let (runtime_parent, runtime_name) = path_parent_and_basename(argv.first()?)?;
+ let (script_parent, script_name) = path_parent_and_basename(argv.get(1)?)?;
+ if normalized_lookup_name(runtime_name) != "node"
+ || !script_name.eq_ignore_ascii_case("index.js")
+ || !runtime_parent.eq_ignore_ascii_case(script_parent)
+ {
+ return None;
+ }
+ let mut tail = runtime_parent
+ .rsplit(['/', '\\'])
+ .filter(|component| !component.is_empty());
+ let (Some(version), Some(versions), Some(package)) = (tail.next(), tail.next(), tail.next())
+ else {
+ return None;
+ };
+ (package.eq_ignore_ascii_case("cursor-agent")
+ && versions.eq_ignore_ascii_case("versions")
+ && !version.trim().is_empty())
+ .then(|| lookup("cursor-agent"))?
+}
+
+fn path_parent_and_basename(path: &str) -> Option<(&str, &str)> {
+ let index = path.rfind(['/', '\\'])?;
+ let parent = &path[..index];
+ let base = &path[index + 1..];
+ if parent.is_empty() || base.is_empty() {
+ return None;
+ }
+ Some((parent, base))
+}
+
+/// Map a script-path token to an agent, in three tiers: exact basename
+/// (after suffix stripping), known package-directory layout, and finally
+/// symlink resolution for shims whose link name is generic but whose
+/// target is not.
+fn agent_from_path_token(token: &str, lookup: &dyn Fn(&str) -> Option<String>) -> Option<String> {
+ let trimmed = token.trim_matches(|c| matches!(c, '"' | '\''));
+ if trimmed.is_empty() || trimmed.starts_with('-') {
+ return None;
+ }
+ resolve_name(&normalized_lookup_name(basename(trimmed)), lookup)
+ .or_else(|| known_package_agent(trimmed, lookup))
+ .or_else(|| symlink_target_agent(trimmed, lookup))
+}
+
+fn known_package_agent(path: &str, lookup: &dyn Fn(&str) -> Option<String>) -> Option<String> {
+ let components: Vec<String> = path
+ .split(['/', '\\'])
+ .filter(|component| !component.is_empty())
+ .map(normalized_lookup_name)
+ .collect();
+ for (window, id) in KNOWN_PACKAGE_PATHS {
+ // `windows(0)` panics; an empty table entry is a table-editing
+ // mistake, not a reason to take the process down.
+ if window.is_empty() {
+ continue;
+ }
+ if components
+ .windows(window.len())
+ .any(|candidate| candidate == *window)
+ {
+ return lookup(id);
+ }
+ }
+ None
+}
+
+/// The one filesystem touch in this module. Bare names never reach the
+/// filesystem — only multi-component paths can be shims worth resolving.
+fn symlink_target_agent(token: &str, lookup: &dyn Fn(&str) -> Option<String>) -> Option<String> {
+ let path = std::path::Path::new(token);
+ if path.components().count() < 2 {
+ return None;
+ }
+ let resolved = std::fs::canonicalize(path).ok()?;
+ let base = resolved.file_name()?.to_str()?;
+ resolve_name(&normalized_lookup_name(base), lookup)
+}
+
+/// Version-managed launchers exec a binary named after the version —
+/// e.g. Claude Code runs as `~/.local/share/claude/versions/2.1.239` —
+/// so the agent's name only appears as a parent directory. Directory
+/// components only vouch for that layout: without the version-like
+/// basename gate, any executable under an alias-named directory would be
+/// misidentified (everything in `/home/pi/.local/bin`, say).
+fn versioned_launcher_agent(
+ path: &str,
+ name: &str,
+ lookup: &dyn Fn(&str) -> Option<String>,
+) -> Option<String> {
+ if !looks_like_version(name) {
+ return None;
+ }
+ path.rsplit(['/', '\\'])
+ .skip(1)
+ .take(2)
+ .find_map(|component| resolve_name(&component.to_lowercase(), lookup))
+}
+
+/// A launcher-style version basename: starts with a digit, rest is
+/// digits/letters/dots/dashes ("2.1.239", "1.0.0-rc1").
+fn looks_like_version(name: &str) -> bool {
+ let mut chars = name.chars();
+ matches!(chars.next(), Some(c) if c.is_ascii_digit())
+ && chars.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
+}
+
+fn is_generic_runtime(name: &str) -> bool {
+ is_python_runtime(name) || GENERIC_RUNTIMES.contains(&name)
+}
+
+fn is_python_runtime(name: &str) -> bool {
+ name == "python"
+ || name.strip_prefix("python").is_some_and(|version| {
+ !version.is_empty()
+ && version
+ .split('.')
+ .all(|part| !part.is_empty() && part.chars().all(|ch| ch.is_ascii_digit()))
+ })
+}
+
+fn normalized_lookup_name(name: &str) -> String {
+ let mut name = name.trim().to_lowercase();
+ for suffix in STRIP_SUFFIXES {
+ if name.ends_with(suffix) {
+ name.truncate(name.len() - suffix.len());
+ break;
+ }
+ }
+ name
+}
+
+pub(crate) fn basename(path: &str) -> &str {
+ path.rsplit(['/', '\\']).next().unwrap_or(path)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A stand-in for the manifest id/alias table, so these tests are
+ /// independent of which manifests are bundled.
+ fn lookup(name: &str) -> Option<String> {
+ match name {
+ "claude" | "claude-code" => Some("claude".to_string()),
+ "codex" => Some("codex".to_string()),
+ "github-copilot" | "ghcs" => Some("github-copilot".to_string()),
+ "cursor" | "cursor-agent" => Some("cursor".to_string()),
+ "kimi" => Some("kimi".to_string()),
+ "opencode" => Some("opencode".to_string()),
+ "pi" => Some("pi".to_string()),
+ _ => None,
+ }
+ }
+
+ fn identify_with_argv(path: &str, argv: &[&str]) -> Option<String> {
+ let argv: Vec<String> = argv.iter().map(|s| s.to_string()).collect();
+ let mut fetch = || Some(argv.clone());
+ identify(path, &mut fetch, &lookup)
+ }
+
+ fn identify_no_argv(path: &str) -> Option<String> {
+ let mut fetch = || None;
+ identify(path, &mut fetch, &lookup)
+ }
+
+ #[test]
+ fn plain_agent_binaries_identify_directly() {
+ assert_eq!(identify_no_argv("/usr/local/bin/claude").as_deref(), Some("claude"));
+ assert_eq!(identify_no_argv("C:\\tools\\codex.exe").as_deref(), Some("codex"));
+ assert_eq!(identify_no_argv("/bin/zsh"), None);
+ assert_eq!(identify_no_argv("/tmp/my-codex-helper"), None);
+ }
+
+ #[test]
+ fn npm_shims_identify_through_the_interpreter_argv() {
+ // `pi` installed via npm: the leader is node, the shim path rides
+ // in argv[1]. This is the case the old basename-only identifier
+ // was blind to.
+ assert_eq!(
+ identify_with_argv(
+ "/opt/homebrew/bin/node",
+ &["node", "/opt/homebrew/bin/pi"]
+ )
+ .as_deref(),
+ Some("pi")
+ );
+ // Runtime options before the script are skipped; value-taking
+ // options consume their value.
+ assert_eq!(
+ identify_with_argv(
+ "/usr/bin/node",
+ &[
+ "node",
+ "--max-old-space-size=4096",
+ "-r",
+ "/x/preload.js",
+ "/usr/local/bin/codex"
+ ]
+ )
+ .as_deref(),
+ Some("codex")
+ );
+ // `--` means "next token is the script".
+ assert_eq!(
+ identify_with_argv("/usr/bin/node", &["node", "--", "/x/pi"]).as_deref(),
+ Some("pi")
+ );
+ // `.js` is stripped before the alias lookup.
+ assert_eq!(
+ identify_with_argv("/usr/bin/node", &["node", "/y/dist/pi.js"]).as_deref(),
+ Some("pi")
+ );
+ // A bare runtime with no script stays unidentified.
+ assert_eq!(identify_with_argv("/usr/bin/node", &["node"]), None);
+ assert_eq!(identify_no_argv("/usr/bin/node"), None);
+ }
+
+ #[test]
+ fn cursor_bundled_node_identifies_by_install_layout() {
+ // Unix layout.
+ assert_eq!(
+ identify_with_argv(
+ "/home/x/.local/share/cursor-agent/versions/2.0.1/node",
+ &[
+ "/home/x/.local/share/cursor-agent/versions/2.0.1/node",
+ "/home/x/.local/share/cursor-agent/versions/2.0.1/index.js"
+ ]
+ )
+ .as_deref(),
+ Some("cursor")
+ );
+ // Windows layout, backslashes and node.exe.
+ assert_eq!(
+ identify_with_argv(
+ "C:\\Users\\x\\cursor-agent\\versions\\2.0.1\\node.exe",
+ &[
+ "C:\\Users\\x\\cursor-agent\\versions\\2.0.1\\node.exe",
+ "C:\\Users\\x\\cursor-agent\\versions\\2.0.1\\index.js"
+ ]
+ )
+ .as_deref(),
+ Some("cursor")
+ );
+ // A system node running a lookalike path must not match: the
+ // runtime does not live in the cursor-agent directory.
+ assert_eq!(
+ identify_with_argv(
+ "/usr/bin/node",
+ &["/usr/bin/node", "/tmp/cursor-agent/versions/x/index.js"]
+ ),
+ None
+ );
+ }
+
+ /// Node's `process.title = "pi"` clobbers the argv block: the OS then
+ /// reports argv as just `["pi"]`, the script path gone. The rewritten
+ /// argv[0] is the agent's own self-declaration — trust it.
+ #[test]
+ fn retitled_interpreters_identify_by_their_new_title() {
+ assert_eq!(
+ identify_with_argv("/opt/homebrew/Cellar/node/26.7.0/bin/node", &["pi"]).as_deref(),
+ Some("pi")
+ );
+ // An unretitled interpreter's argv[0] is the runtime name and
+ // must not match anything.
+ assert_eq!(
+ identify_with_argv("/usr/bin/node", &["node", "/opt/tools/build.js"]),
+ None
+ );
+ }
+
+ #[test]
+ fn eval_payloads_are_never_mined_for_agent_names() {
+ assert_eq!(
+ identify_with_argv("/usr/bin/node", &["node", "-e", "codex"]),
+ None
+ );
+ assert_eq!(
+ identify_with_argv("/usr/bin/node", &["node", "--eval=codex"]),
+ None
+ );
+ assert_eq!(
+ identify_with_argv("/usr/bin/python3.12", &["python3.12", "-c", "codex"]),
+ None
+ );
+ assert_eq!(
+ identify_with_argv("/usr/bin/python3.12", &["python3.12", "-m", "codex"]),
+ None
+ );
+ assert_eq!(
+ identify_with_argv("/bin/bash", &["bash", "-c", "codex --help"]),
+ None
+ );
+ // But a shell running an agent script identifies.
+ assert_eq!(
+ identify_with_argv("/bin/bash", &["bash", "/opt/agents/claude"]).as_deref(),
+ Some("claude")
+ );
+ }
+
+ #[test]
+ fn known_package_layouts_identify_generic_entry_scripts() {
+ assert_eq!(
+ identify_with_argv(
+ "/usr/bin/node",
+ &[
+ "node",
+ "/opt/homebrew/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js"
+ ]
+ )
+ .as_deref(),
+ Some("pi")
+ );
+ // A random cli.js does not.
+ assert_eq!(
+ identify_with_argv("/usr/bin/node", &["node", "/some/tool/dist/cli.js"]),
+ None
+ );
+ }
+
+ #[test]
+ fn extra_process_aliases_cover_names_the_manifests_lack() {
+ // The npm binary is `copilot`; the manifest id is `github-copilot`
+ // and its alias list assumes herdr's code-side table.
+ assert_eq!(
+ identify_no_argv("/opt/homebrew/bin/copilot").as_deref(),
+ Some("github-copilot")
+ );
+ }
+
+ #[test]
+ fn versioned_launcher_paths_identify_by_parent_directory() {
+ assert_eq!(
+ identify_no_argv("/Users/x/.local/share/claude/versions/2.1.239").as_deref(),
+ Some("claude")
+ );
+ // An ordinary binary under an alias-named directory (a user named
+ // `pi`, say) must not be misidentified.
+ assert_eq!(identify_no_argv("/home/pi/.local/bin/htop"), None);
+ assert_eq!(identify_no_argv("/home/pi/.local/bin/2.0.1"), None);
+ assert_eq!(
+ identify_no_argv("/home/x/pi/versions/2.0.1").as_deref(),
+ Some("pi")
+ );
+ assert_eq!(identify_no_argv("/opt/claude/deep/nested/2.1.0"), None);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlinked_shims_identify_by_their_target() {
+ let dir = std::env::temp_dir().join(format!(
+ "thinkterm-proc-match-{}",
+ std::process::id()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let target = dir.join("claude");
+ std::fs::write(&target, b"#!/bin/sh\n").unwrap();
+ let link = dir.join("agent-shim");
+ let _ = std::fs::remove_file(&link);
+ std::os::unix::fs::symlink(&target, &link).unwrap();
+
+ assert_eq!(
+ identify_with_argv(
+ "/usr/bin/node",
+ &["node", link.to_str().unwrap()]
+ )
+ .as_deref(),
+ Some("claude")
+ );
+
+ // Bare names never touch the filesystem.
+ assert_eq!(
+ identify_with_argv("/usr/bin/node", &["node", "agent-shim"]),
+ None
+ );
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs
index 81ff7234..b3fe4466 100644
--- a/mux/src/localpane.rs
+++ b/mux/src/localpane.rs
@@ -586,6 +586,27 @@ impl Pane for LocalPane {
None
}
+ fn get_foreground_process_argv(&self, policy: CachePolicy) -> Option<Vec<String>> {
+ #[cfg(unix)]
+ {
+ let leader = self.get_leader(policy);
+ if leader.pid > 0 {
+ return LocalProcessInfo::argv_for_pid(leader.pid);
+ }
+ return None;
+ }
+
+ #[cfg(windows)]
+ if let Some(fg) = self.divine_foreground_process(policy) {
+ if !fg.argv.is_empty() {
+ return Some(fg.argv);
+ }
+ }
+
+ #[allow(unreachable_code)]
+ None
+ }
+
fn can_close_without_prompting(&self, _reason: CloseReason) -> bool {
if let Some(info) = self.divine_process_list(CachePolicy::FetchImmediate) {
log::trace!(
diff --git a/mux/src/pane.rs b/mux/src/pane.rs
index 292c094a..3f1425eb 100644
--- a/mux/src/pane.rs
+++ b/mux/src/pane.rs
@@ -381,6 +381,14 @@ pub trait Pane: Downcast + Send + Sync {
fn get_foreground_process_name(&self, _policy: CachePolicy) -> Option<String> {
None
}
+ /// The argument vector of the foreground process-group leader, when
+ /// the platform can read it. Agent identification asks for this only
+ /// when the leader executable is a generic interpreter (node, python,
+ /// a shell), so implementations may fetch it on demand rather than
+ /// caching it alongside the leader path.
+ fn get_foreground_process_argv(&self, _policy: CachePolicy) -> Option<Vec<String>> {
+ None
+ }
fn get_foreground_process_info(
&self,
_policy: CachePolicy,