Skip to main content

hatchery_node/
m4a_accounts.rs

1//! Per-session m4a accounts assigned by the node at spawn (owner model: session = nick = one key
2//! = one role). Every PTY spawn gets its own account when the node can find `m4a-agent` (env
3//! `HATCHERY_M4A_AGENT_BIN`, else next to this binary, PATH, or `~/.cargo/bin`) and an accounts
4//! root (env `HATCHERY_M4A_ACCOUNTS_ROOT`, else `<enroll-state>/m4a-accounts`). Product URL comes
5//! from env or the enrollment reply (`m4a_product_url`). The node runs `m4a-agent account provision`
6//! (registry and vaults
7//! stay under the node's accounts root, outside the session sandbox), reads the fresh capability
8//! from a one-shot 0600 file it removes at once, and injects ONLY `M4A_NICK` and
9//! `M4A_SESSION_CAP` into that session's child environment. The capability is never logged.
10
11use std::ffi::OsString;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15use gate4agent_catalog::EnvMutation;
16
17/// g4a provider id -> the provider name `m4a-agent` accepts. g4a's built-in catalog is
18/// `claude`, `codex`, `grok`, `kimi`; anything else (custom agents) gets no account.
19pub fn m4a_provider(g4a_agent_id: &str) -> Option<&'static str> {
20    match g4a_agent_id {
21        "claude" => Some("claude-code"),
22        "codex" => Some("codex"),
23        "grok" => Some("grok"),
24        "kimi" => Some("kimi-code"),
25        _ => None,
26    }
27}
28
29/// Provider-specific process environment the node adds to its own sessions so the node's
30/// project-level m4a MCP entry is honoured without an interactive prompt.
31pub fn provider_session_env(g4a_agent_id: &str) -> Vec<EnvMutation> {
32    match g4a_agent_id {
33        // kimi-code: project `.kimi-code/mcp.json` stays disabled in an untrusted folder.
34        "kimi" => vec![EnvMutation { key: OsString::from("KIMI_CODE_TRUST_WORKSPACE"), value: Some(OsString::from("1")) }],
35        _ => Vec::new(),
36    }
37}
38
39/// Name of the node's m4a MCP server entry for a provider. A session's project entry under the
40/// same name as the user's own entry replaces it (kimi-code, grok and codex merge by name), so
41/// no duplicate m4a server runs. `HATCHERY_M4A_MCP_NAME_<PROVIDER>` (e.g. `..._KIMI`) or
42/// `HATCHERY_M4A_MCP_NAME`; default `m4a`.
43pub fn mcp_server_name(g4a_agent_id: &str) -> String {
44    let from_arg = MCP_NAME_ARGS.lock().unwrap_or_else(|p| p.into_inner()).iter().rev()
45        .find(|(p, _)| p.as_deref().map_or(true, |p| p == g4a_agent_id)).map(|(_, n)| n.clone());
46    if let Some(name) = from_arg {
47        return name;
48    }
49    let key = format!("HATCHERY_M4A_MCP_NAME_{}", g4a_agent_id.to_ascii_uppercase());
50    let ok = |v: &String| !v.is_empty() && v.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
51    std::env::var(&key)
52        .ok()
53        .filter(ok)
54        .or_else(|| std::env::var("HATCHERY_M4A_MCP_NAME").ok().filter(ok))
55        .unwrap_or_else(|| "m4a".into())
56}
57
58static MCP_NAME_ARGS: std::sync::Mutex<Vec<(Option<String>, String)>> = std::sync::Mutex::new(Vec::new());
59
60/// `--m4a-mcp-name [provider=]name` (repeatable): the node's m4a MCP entry name, taking
61/// precedence over the env. Returns false for a malformed value.
62pub fn set_mcp_name_arg(value: &str) -> bool {
63    let (provider, name) = match value.split_once('=') {
64        Some((p, n)) => (Some(p.trim().to_owned()), n.trim().to_owned()),
65        None => (None, value.trim().to_owned()),
66    };
67    if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
68        return false;
69    }
70    let mut args = MCP_NAME_ARGS.lock().unwrap_or_else(|p| p.into_inner());
71    // Provider-specific entries win over a plain one regardless of order.
72    if provider.is_some() { args.push((provider, name)) } else { args.insert(0, (None, name)) }
73    true
74}
75
76pub const AGENT_BIN_ENV: &str = "HATCHERY_M4A_AGENT_BIN";
77/// Messenger product base URL; with it (and an enrolled node) the node registers its sessions'
78/// accounts on the messenger itself, signed with the node key.
79pub const PRODUCT_URL_ENV: &str = "HATCHERY_M4A_PRODUCT_URL";
80/// The product's audience name the node signs for (default `m4a-product`).
81pub const PRODUCT_AUDIENCE_ENV: &str = "HATCHERY_M4A_PRODUCT_AUDIENCE";
82
83static NODE_SIGNER: std::sync::OnceLock<(String, std::sync::Arc<hatchery_enroll::NodeIdentity>)> = std::sync::OnceLock::new();
84
85/// Installs this node's identity (enrolled, trusted) as the signer of account registrations.
86/// An unenrolled node never has one, so it registers nothing.
87pub fn set_node_signer(node_id: String, identity: std::sync::Arc<hatchery_enroll::NodeIdentity>) {
88    let _ = NODE_SIGNER.set((node_id, identity));
89}
90
91/// Exact bytes the messenger product verifies (`m4a-node-account-v1`).
92pub fn node_account_message(audience: &str, node_id: &str, nick: Option<&str>, ts_ms: i64, nonce: &str) -> Vec<u8> {
93    format!("m4a-node-account-v1\n{audience}\n{node_id}\n{}\n{ts_ms}\n{nonce}\n", nick.unwrap_or("")).into_bytes()
94}
95pub const ACCOUNTS_ROOT_ENV: &str = "HATCHERY_M4A_ACCOUNTS_ROOT";
96/// Owner nick for session auto-nicks `<provider>-<N>.<node_id>.<owner>`.
97pub const OWNER_ENV: &str = "HATCHERY_M4A_OWNER";
98
99#[derive(Debug, Clone)]
100pub struct M4aSessionAccounts {
101    bin: PathBuf,
102    base: PathBuf,
103}
104
105/// One session's account as handed to its child: nick and capability only.
106pub struct SessionAccount {
107    pub nick: String,
108    /// The provider session key the account is bound to (also given to the session as
109    /// `M4A_SESSION_ID`, so its own inbox commands address the right account).
110    pub session_id: String,
111    /// The account's own store root (`M4A_STORE_ROOT`), when m4a-agent reported it.
112    pub store_root: Option<String>,
113    /// Messenger product URL the session's client uses (`M4A_PRODUCT_URL`), from the node env.
114    pub product_url: Option<String>,
115    cap: String,
116}
117
118impl Drop for SessionAccount {
119    fn drop(&mut self) {
120        // Best effort wipe of the capability copy held by the node.
121        let bytes = unsafe { self.cap.as_bytes_mut() };
122        bytes.iter_mut().for_each(|b| *b = 0);
123    }
124}
125
126impl std::fmt::Debug for SessionAccount {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        f.debug_struct("SessionAccount").field("nick", &self.nick).finish_non_exhaustive()
129    }
130}
131
132impl SessionAccount {
133    /// The only variables the session gets from the node for m4a.
134    /// The one-time `/m4a/attach` reply (the capability travels only in this body).
135    pub fn attach_reply(&self) -> serde_json::Value {
136        serde_json::json!({"nick": self.nick, "session_id": self.session_id, "cap": self.cap, "store_root": self.store_root, "product_url": self.product_url})
137    }
138
139    pub fn env_mutations(&self) -> Vec<EnvMutation> {
140        vec![
141            EnvMutation { key: OsString::from("M4A_NICK"), value: Some(OsString::from(&self.nick)) },
142            EnvMutation { key: OsString::from("M4A_SESSION_CAP"), value: Some(OsString::from(&self.cap)) },
143            EnvMutation { key: OsString::from("M4A_SESSION_ID"), value: Some(OsString::from(&self.session_id)) },
144            EnvMutation { key: OsString::from("M4A_BOT_NAME"), value: Some(OsString::from(&self.nick)) },
145        ]
146        .into_iter()
147        .chain(self.store_root.iter().map(|r| EnvMutation { key: OsString::from("M4A_STORE_ROOT"), value: Some(OsString::from(r)) }))
148        .chain(self.product_url.iter().map(|u| EnvMutation { key: OsString::from("M4A_PRODUCT_URL"), value: Some(OsString::from(u)) }))
149        .collect()
150    }
151}
152
153impl M4aSessionAccounts {
154    /// The `m4a-agent` binary the node runs (also the command of the node's MCP entry).
155    pub fn bin(&self) -> &Path {
156        &self.bin
157    }
158
159    /// Fallback identity channel: `<root>/sessions/<nick>.session` (owner-only), the same three
160    /// keys as [`SessionAccount::env_mutations`], for a provider whose tools run in a process
161    /// that did not inherit the session environment (`m4a-agent --session-file <path> ...`).
162    pub fn session_file_path(&self, nick: &str) -> Option<PathBuf> {
163        // Node auto-nicks carry dots (`claude-3.box.owner`); never a leading dot or `..`.
164        let ok = !nick.is_empty() && !nick.starts_with('.') && !nick.contains("..") && nick.len() <= 64
165            && nick.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.');
166        ok.then(|| self.base.join("sessions").join(format!("{nick}.session")))
167    }
168
169    pub fn write_session_file(&self, account: &SessionAccount) -> Result<PathBuf, String> {
170        let path = self.session_file_path(&account.nick).ok_or("invalid nick")?;
171        let dir = path.parent().ok_or("no dir")?;
172        std::fs::create_dir_all(dir).map_err(|e| format!("sessions dir: {}", e.kind()))?;
173        let mut body = String::new();
174        for m in account.env_mutations() {
175            if let Some(v) = m.value {
176                body.push_str(&format!("{}={}\n", m.key.to_string_lossy(), v.to_string_lossy()));
177            }
178        }
179        let mut opts = std::fs::OpenOptions::new();
180        opts.write(true).create(true).truncate(true);
181        #[cfg(unix)]
182        {
183            use std::os::unix::fs::OpenOptionsExt;
184            opts.mode(0o600);
185        }
186        use std::io::Write;
187        opts.open(&path)
188            .and_then(|mut f| f.write_all(body.as_bytes()))
189            .map_err(|e| format!("session file: {}", e.kind()))?;
190        body.zeroize_best_effort();
191        Ok(path)
192    }
193
194    /// Provider flags that give one spawned session its own m4a MCP server (`m4a-agent
195    /// --session-file <file> mcp`), without touching any user config. Empty for providers with
196    /// no verified per-session MCP flag (grok TUI, kimi PTY): those use attach (`/m4a/attach`).
197    pub fn mcp_launch_args(&self, g4a_provider: &str, nick: &str) -> Result<Vec<OsString>, String> {
198        let session_file = self.session_file_path(nick).ok_or("invalid nick")?;
199        let bin = self.bin.to_string_lossy().into_owned();
200        let sf = session_file.to_string_lossy().into_owned();
201        let provider = g4a_provider.to_owned();
202        match g4a_provider {
203            "claude" => {
204                let config = serde_json::json!({"mcpServers": {"m4a": {
205                    "type": "stdio",
206                    "command": bin,
207                    "args": ["--session-file", sf, "mcp", "--provider", provider],
208                }}});
209                let path = self.base.join("sessions").join(format!("{nick}.mcp.json"));
210                std::fs::create_dir_all(self.base.join("sessions")).map_err(|e| format!("sessions dir: {}", e.kind()))?;
211                std::fs::write(&path, config.to_string()).map_err(|e| format!("mcp config: {}", e.kind()))?;
212                Ok(vec![OsString::from("--mcp-config"), path.into_os_string()])
213            }
214            "codex" => {
215                // TOML literal strings: no escapes, no double quotes. On Windows codex runs through
216                // a `cmd /C <codex.cmd>` wrapper: an argument with whitespace gets quoted, and more
217                // than two quotes make cmd strip the wrapper's own quotes (spawn fails). So the
218                // values must be whitespace-free; a binary in a spaced directory is named by its
219                // file name (found on PATH), otherwise the session falls back to attach.
220                let name = mcp_server_name("codex");
221                let bin = codex_safe_command(&self.bin).ok_or("m4a-agent path has whitespace and is not on PATH")?;
222                if !codex_safe_value(&sf) {
223                    return Err("session file path is not safe for codex -c".into());
224                }
225                Ok(vec![
226                    OsString::from("-c"),
227                    OsString::from(format!("mcp_servers.{name}.command='{bin}'")),
228                    OsString::from("-c"),
229                    OsString::from(format!("mcp_servers.{name}.args=['--session-file','{sf}','mcp','--provider','codex']")),
230                ])
231            }
232            _ => Ok(Vec::new()),
233        }
234    }
235
236    /// Per-session working folder `<workspace>/.hatchery-sessions/<nick>` with the node's m4a
237    /// MCP in the provider's own project config (kimi-code `.kimi-code/mcp.json`, grok
238    /// `.grok/config.toml`). Returns the folder, or `None` when the provider has no project
239    /// config the node writes (the session then runs in the workspace root).
240    pub fn session_workdir(&self, workspace_root: &Path, g4a_provider: &str, nick: &str) -> Result<Option<PathBuf>, String> {
241        let session_file = self.session_file_path(nick).ok_or("invalid nick")?;
242        let dir = workspace_root.join(".hatchery-sessions").join(nick);
243        let name = mcp_server_name(g4a_provider);
244        let bin = self.bin.to_string_lossy().into_owned();
245        let sf = session_file.to_string_lossy().into_owned();
246        let write = |rel: &str, text: String| -> Result<(), String> {
247            let path = dir.join(rel);
248            if let Some(parent) = path.parent() {
249                std::fs::create_dir_all(parent).map_err(|e| format!("session dir: {}", e.kind()))?;
250            }
251            std::fs::write(&path, text).map_err(|e| format!("project mcp: {}", e.kind()))
252        };
253        match g4a_provider {
254            "kimi" => {
255                let provider = m4a_provider(g4a_provider).unwrap_or(g4a_provider);
256                let config = serde_json::json!({"mcpServers": {name: {
257                    "command": bin,
258                    "args": ["--session-file", sf, "mcp", "--provider", provider],
259                }}});
260                write(".kimi-code/mcp.json", serde_json::to_string_pretty(&config).unwrap_or_default())?;
261            }
262            "grok" => {
263                // TOML basic strings: the paths are escaped by serde_json's string form.
264                let q = |v: &str| serde_json::to_string(v).unwrap_or_default();
265                let text = format!(
266                    "[mcp_servers.{name}]\ncommand = {}\nargs = [{}, {}, \"mcp\", \"--provider\", \"grok\"]\n",
267                    q(&bin), q("--session-file"), q(&sf)
268                );
269                write(".grok/config.toml", text)?;
270            }
271            _ => return Ok(None),
272        }
273        Ok(Some(dir))
274    }
275
276    /// Registers the session under the node auto-nick `<provider>-<N>.<node_id>.<owner>` (unique
277    /// across boxes and humans: the server only accepts this node's own suffix and no human nick
278    /// has that shape). A taken nick moves to the next free `N`. Without an owner
279    /// (`HATCHERY_M4A_OWNER`) the local nick is registered as is.
280    fn register_auto_nick(&self, account: &mut SessionAccount, provider: &str, session_key: &str) {
281        // Env, else `<enroll-state>/m4a-owner` (one line), so a running supervisor need not restart.
282        let owner = std::env::var(OWNER_ENV).ok().filter(|o| !o.is_empty()).or_else(|| {
283            let t = std::fs::read_to_string(enroll_dir_hint()?.join("m4a-owner")).ok()?;
284            Some(t.trim().to_owned()).filter(|o| !o.is_empty())
285        });
286        let node_id = NODE_SIGNER.get().map(|(id, _)| id.clone());
287        let (Some(owner), Some(node_id)) = (owner, node_id) else {
288            if let Err(error) = self.node_enroll(account) {
289                tracing::warn!(nick = %account.nick, %error, "m4a account not registered on the messenger (stays local)");
290            }
291            return;
292        };
293        let suffix = format!(".{node_id}.{owner}");
294        let head = account.nick.strip_suffix(&suffix).unwrap_or(&account.nick).to_string();
295        let start: u64 = head.rsplit_once('-').and_then(|(_, n)| n.parse().ok()).unwrap_or(1);
296        // `claude-code` -> `claude`, `kimi-code` -> `kimi`: the nick names the agent, not the CLI.
297        let stem = provider.strip_suffix("-code").unwrap_or(provider);
298        let mut last = String::new();
299        for n in start..start + 32 {
300            let want = format!("{stem}-{n}{suffix}");
301            if want != account.nick {
302                if let Err(e) = self.renick(provider, session_key, &want) {
303                    last = e;
304                    continue;
305                }
306                account.nick = want.clone();
307            }
308            match self.node_enroll(account) {
309                Ok(()) => return,
310                Err(e) if e.contains("409") || e.contains("taken") => last = e,
311                Err(e) => {
312                    tracing::warn!(nick = %account.nick, error = %e, "m4a account not registered on the messenger (stays local)");
313                    return;
314                }
315            }
316        }
317        tracing::warn!(nick = %account.nick, error = %last, "m4a auto-nick: no free nick found");
318    }
319
320    fn renick(&self, provider: &str, session_key: &str, nick: &str) -> Result<(), String> {
321        let mut cmd = Command::new(&self.bin);
322        cmd.args(["account", "renick", "--provider", provider, "--session", session_key, "--nick", nick])
323            .env("M4A_ACCOUNTS_ROOT", &self.base)
324            .env_remove("M4A_SESSION_CAP")
325            .env_remove("M4A_PRODUCT_INVITE");
326        crate::windows_process::hide_console(&mut cmd);
327        let out = cmd.output().map_err(|e| format!("m4a-agent: {}", e.kind()))?;
328        if out.status.success() {
329            Ok(())
330        } else {
331            Err(String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("renick refused").chars().take(200).collect())
332        }
333    }
334
335    /// Registers the account on the messenger with this node's key, then the account's own client
336    /// enrolls its own key (`m4a-agent account node-enroll`). The invite never reaches the node.
337    fn node_enroll(&self, account: &SessionAccount) -> Result<(), String> {
338        let url = account.product_url.as_deref().ok_or("no messenger product url (HATCHERY_M4A_PRODUCT_URL)")?;
339        let store_root = account.store_root.as_deref().ok_or("m4a-agent reported no store root")?;
340        let (node_id, identity) = NODE_SIGNER.get().ok_or("this node is not enrolled: it registers no accounts")?;
341        let audience = std::env::var(PRODUCT_AUDIENCE_ENV).ok().filter(|a| !a.is_empty()).unwrap_or_else(|| "m4a-product".into());
342        let ts_ms = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0);
343        let mut raw = [0u8; 16];
344        getrandom(&mut raw)?;
345        let nonce: String = raw.iter().map(|b| format!("{b:02x}")).collect();
346        let signature = identity.sign_bytes(&node_account_message(&audience, node_id, Some(&account.nick), ts_ms, &nonce));
347        let mut cmd = Command::new(&self.bin);
348        cmd.args(["account", "node-enroll", "--node-id", node_id, "--ts", &ts_ms.to_string(), "--nonce", &nonce, "--signature", &signature, "--nick", &account.nick])
349            .env("M4A_PRODUCT_URL", url)
350            .env("M4A_SESSION_ID", &account.session_id)
351            .env("M4A_STORE_ROOT", store_root)
352            .env("M4A_BOT_NAME", &account.nick)
353            .env("M4A_ACCOUNTS_ROOT", &self.base)
354            .env_remove("M4A_SESSION_CAP")
355            .env_remove("M4A_PRODUCT_INVITE");
356        crate::windows_process::hide_console(&mut cmd);
357        let out = cmd.output().map_err(|e| format!("m4a-agent: {}", e.kind()))?;
358        if !out.status.success() {
359            let why = String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("").chars().take(200).collect::<String>();
360            return Err(format!("node-enroll failed: {why}"));
361        }
362        tracing::info!(nick = %account.nick, node_id = %node_id, "m4a account registered on the messenger by this node");
363        Ok(())
364    }
365
366    pub fn remove_session_file(&self, nick: &str) {
367        if let Some(path) = self.session_file_path(nick) {
368            let _ = std::fs::remove_file(path);
369        }
370        let _ = std::fs::remove_file(self.base.join("sessions").join(format!("{nick}.mcp.json")));
371    }
372
373    pub fn new(bin: impl Into<PathBuf>, base: impl Into<PathBuf>) -> Self {
374        Self { bin: bin.into(), base: base.into() }
375    }
376
377    /// The node's letter-wake token (`<root>/.node-wake-token`, 0600), created on first use.
378    pub fn wake_token(&self) -> Result<String, String> {
379        let path = self.base.join(".node-wake-token");
380        if let Ok(t) = std::fs::read_to_string(&path) {
381            if t.trim().len() >= 32 {
382                return Ok(t.trim().to_owned());
383            }
384        }
385        std::fs::create_dir_all(&self.base).map_err(|e| format!("accounts root: {}", e.kind()))?;
386        let mut raw = [0u8; 24];
387        getrandom(&mut raw)?;
388        let token: String = raw.iter().map(|b| format!("{b:02x}")).collect();
389        let mut opts = std::fs::OpenOptions::new();
390        opts.write(true).create(true).truncate(true);
391        #[cfg(unix)]
392        {
393            use std::os::unix::fs::OpenOptionsExt;
394            opts.mode(0o600);
395        }
396        use std::io::Write;
397        opts.open(&path).and_then(|mut f| f.write_all(token.as_bytes())).map_err(|e| format!("wake token: {}", e.kind()))?;
398        Ok(token)
399    }
400
401    /// Resolve `m4a-agent`: env override, then next to this binary, then PATH, then `~/.cargo/bin`.
402    pub fn find_agent_bin() -> Option<PathBuf> {
403        if let Some(p) = std::env::var_os(AGENT_BIN_ENV).filter(|v| !v.is_empty()).map(PathBuf::from) {
404            return Some(p);
405        }
406        if let Ok(exe) = std::env::current_exe() {
407            if let Some(dir) = exe.parent() {
408                for name in ["m4a-agent", "m4a-agent.exe"] {
409                    let p = dir.join(name);
410                    if p.is_file() {
411                        return Some(p);
412                    }
413                }
414            }
415        }
416        which("m4a-agent").or_else(|| which("m4a-agent.exe")).or_else(|| {
417            let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
418            let p = PathBuf::from(home).join(".cargo").join("bin").join(if cfg!(windows) { "m4a-agent.exe" } else { "m4a-agent" });
419            p.is_file().then_some(p)
420        })
421    }
422
423    /// Accounts root: env, else `<enroll_dir>/m4a-accounts`.
424    pub fn default_accounts_root(enroll_dir: Option<&Path>) -> Option<PathBuf> {
425        if let Some(p) = std::env::var_os(ACCOUNTS_ROOT_ENV).filter(|v| !v.is_empty()).map(PathBuf::from) {
426            return Some(p);
427        }
428        enroll_dir.map(|d| d.join("m4a-accounts"))
429    }
430
431    /// Product URL: env override, else what C2 answered on connect ([`set_c2_product_url`]), else
432    /// `m4a_product_url` from enrollment.json under enroll_dir.
433    pub fn resolve_product_url(enroll_dir: Option<&Path>) -> Option<String> {
434        if let Some(u) = std::env::var(PRODUCT_URL_ENV).ok().filter(|u| !u.is_empty()) {
435            return Some(u);
436        }
437        if let Some(u) = c2_product_url() {
438            return Some(u);
439        }
440        let dir = enroll_dir?;
441        let text = std::fs::read_to_string(dir.join("enrollment.json")).ok()?;
442        let v: serde_json::Value = serde_json::from_str(&text).ok()?;
443        v.get("response")
444            .and_then(|r| r.get("m4a_product_url"))
445            .or_else(|| v.get("m4a_product_url"))
446            .and_then(|u| u.as_str())
447            .filter(|u| !u.is_empty())
448            .map(str::to_owned)
449    }
450
451    /// Open from env and defaults. Logs clearly when m4a cannot start.
452    pub fn from_env() -> Option<Self> {
453        Self::from_enroll_dir(enroll_dir_hint().as_deref())
454    }
455
456    pub fn from_enroll_dir(enroll_dir: Option<&Path>) -> Option<Self> {
457        let bin = match Self::find_agent_bin() {
458            Some(p) => p,
459            None => {
460                tracing::warn!(
461                    "m4a-agent not found (set HATCHERY_M4A_AGENT_BIN, put it next to gate4agent-node, on PATH, or in ~/.cargo/bin); m4a off"
462                );
463                return None;
464            }
465        };
466        let base = match Self::default_accounts_root(enroll_dir) {
467            Some(p) => p,
468            None => {
469                tracing::warn!("m4a accounts root unknown (set HATCHERY_M4A_ACCOUNTS_ROOT or pass --enroll-state); m4a off");
470                return None;
471            }
472        };
473        if let Err(e) = std::fs::create_dir_all(&base) {
474            tracing::warn!(error = %e.kind(), path = %base.display(), "m4a accounts root not writable; m4a off");
475            return None;
476        }
477        let product = Self::resolve_product_url(enroll_dir);
478        if product.is_none() {
479            tracing::info!("m4a product url unset (env / C2 connect / enrollment); accounts stay local until set");
480        }
481        tracing::info!(bin = %bin.display(), accounts = %base.display(), product = product.as_deref().unwrap_or("-"), "m4a accounts ready");
482        Some(Self::new(bin, base))
483    }
484
485    pub fn base(&self) -> &Path {
486        &self.base
487    }
488
489    /// The account of `(provider, session_key)`, created if missing, with a fresh capability
490    /// (a respawn of the same session invalidates the previous process's key).
491    pub fn provision(&self, provider: &str, session_key: &str) -> Result<SessionAccount, String> {
492        std::fs::create_dir_all(&self.base).map_err(|e| format!("accounts root: {}", e.kind()))?;
493        let mut rand = [0u8; 12];
494        getrandom(&mut rand)?;
495        let tag: String = rand.iter().map(|b| format!("{b:02x}")).collect();
496        let cap_file = self.base.join(format!(".spawn-{tag}.cap"));
497        let mut cmd = Command::new(&self.bin);
498        cmd.args(["account", "provision", "--provider", provider, "--session", session_key, "--rotate", "--cap-out"])
499            .arg(&cap_file)
500            .env("M4A_ACCOUNTS_ROOT", &self.base)
501            .env_remove("M4A_SESSION_CAP")
502            .env_remove("M4A_PRODUCT_INVITE");
503        crate::windows_process::hide_console(&mut cmd);
504        let out = cmd.output().map_err(|e| format!("m4a-agent: {}", e.kind()))?;
505        let cap = std::fs::read_to_string(&cap_file);
506        let _ = std::fs::remove_file(&cap_file);
507        if !out.status.success() {
508            return Err(format!("m4a-agent account provision failed ({})", out.status.code().unwrap_or(-1)));
509        }
510        let v: serde_json::Value = serde_json::from_slice(&out.stdout).map_err(|_| "m4a-agent answer is not json".to_string())?;
511        let nick = v["nick"].as_str().ok_or("m4a-agent answer has no nick")?.to_string();
512        let cap = cap.map_err(|_| "no capability issued".to_string())?;
513        if cap.trim().is_empty() || cap.contains('\n') {
514            return Err("capability is malformed".into());
515        }
516        // mail4agent's own session env (`Provisioned::session_env`): the login session id is the
517        // account ref and the account has its own store root.
518        let session_id = v["account_ref"].as_str().filter(|r| !r.is_empty()).unwrap_or(session_key).to_owned();
519        let store_root = v["store_root"].as_str().filter(|r| !r.is_empty()).map(str::to_owned);
520        let product_url = Self::resolve_product_url(enroll_dir_hint().as_deref());
521        let mut account = SessionAccount { nick, session_id, store_root, product_url, cap };
522        if !v["enrolled"].as_bool().unwrap_or(false) {
523            self.register_auto_nick(&mut account, provider, session_key);
524        }
525        Ok(account)
526    }
527}
528
529fn which(name: &str) -> Option<PathBuf> {
530    let path = std::env::var_os("PATH")?;
531    for dir in std::env::split_paths(&path) {
532        let p = dir.join(name);
533        if p.is_file() {
534            return Some(p);
535        }
536    }
537    None
538}
539
540static C2_PRODUCT_URL: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
541
542/// What C2 answered for `m4a_product_url` on the latest connect (`None` clears).
543pub fn set_c2_product_url(url: Option<String>) {
544    *C2_PRODUCT_URL.write().unwrap_or_else(|e| e.into_inner()) = url.filter(|u| !u.is_empty());
545}
546
547pub fn c2_product_url() -> Option<String> {
548    C2_PRODUCT_URL.read().unwrap_or_else(|e| e.into_inner()).clone()
549}
550
551pub(crate) fn enroll_dir_hint() -> Option<PathBuf> {
552    std::env::var_os("HATCHERY_ENROLL_STATE")
553        .filter(|v| !v.is_empty())
554        .map(PathBuf::from)
555        .or_else(|| {
556            // Soft hint used when main has not set HATCHERY_ENROLL_STATE yet: none.
557            None
558        })
559}
560
561fn getrandom(buf: &mut [u8]) -> Result<(), String> {
562    use std::io::Read;
563    std::fs::File::open("/dev/urandom")
564        .and_then(|mut f| f.read_exact(buf))
565        .or_else(|_| {
566            // Non-unix fallback: time + address entropy is enough for a unique temp name.
567            let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
568            for (i, b) in buf.iter_mut().enumerate() {
569                *b = (t >> ((i % 16) * 8)) as u8 ^ (i as u8);
570            }
571            Ok::<(), std::io::Error>(())
572        })
573        .map_err(|e| e.to_string())
574}
575
576#[cfg(all(test, unix))]
577mod tests {
578    use super::*;
579
580    fn fake_agent(dir: &Path) -> PathBuf {
581        // Stands in for m4a-agent: one nick per --session, the cap written to --cap-out.
582        let p = dir.join("fake-m4a-agent");
583        std::fs::write(
584            &p,
585            "#!/bin/sh\nwhile [ $# -gt 0 ]; do case \"$1\" in --session) s=$2; shift;; --cap-out) o=$2; shift;; esac; shift; done\n\
586             umask 077; printf 'cap-%s-%s' \"$s\" \"$$\" > \"$o\"; printf '{\"nick\":\"codex-%s\",\"account_ref\":\"ref-%s\",\"store_root\":\"/s/%s\",\"enrolled\":true,\"cap_issued\":true}\\n' \"$s\" \"$s\" \"$s\"\n",
587        )
588        .unwrap();
589        use std::os::unix::fs::PermissionsExt;
590        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
591        p
592    }
593
594    #[test]
595    fn defaults_find_agent_and_accounts_root_and_product_from_enrollment() {
596        let dir = std::env::temp_dir().join(format!("m4a-defaults-{}", std::process::id()));
597        let _ = std::fs::remove_dir_all(&dir);
598        std::fs::create_dir_all(&dir).unwrap();
599        let agent = fake_agent(&dir);
600        std::env::set_var(AGENT_BIN_ENV, &agent);
601        std::env::remove_var(ACCOUNTS_ROOT_ENV);
602        std::env::remove_var(PRODUCT_URL_ENV);
603        let root = M4aSessionAccounts::default_accounts_root(Some(dir.as_path())).unwrap();
604        assert_eq!(root, dir.join("m4a-accounts"));
605        assert_eq!(M4aSessionAccounts::find_agent_bin().as_deref(), Some(agent.as_path()));
606        std::fs::write(
607            dir.join("enrollment.json"),
608            r#"{"node_id":"n","response":{"node_id":"n","status":"approved","m4a_product_url":"https://example.invalid"}}"#,
609        )
610        .unwrap();
611        assert_eq!(
612            M4aSessionAccounts::resolve_product_url(Some(dir.as_path())).as_deref(),
613            Some("https://example.invalid")
614        );
615        let got = M4aSessionAccounts::from_enroll_dir(Some(dir.as_path())).unwrap();
616        assert_eq!(got.base(), root.as_path());
617        std::env::remove_var(AGENT_BIN_ENV);
618        std::env::remove_var(PRODUCT_URL_ENV);
619        std::fs::remove_dir_all(&dir).unwrap();
620    }
621
622    #[test]
623    fn product_url_order_env_then_c2_then_enrollment() {
624        let dir = std::env::temp_dir().join(format!("m4a-purl-{}", std::process::id()));
625        let _ = std::fs::remove_dir_all(&dir);
626        std::fs::create_dir_all(&dir).unwrap();
627        std::fs::write(dir.join("enrollment.json"), r#"{"response":{"m4a_product_url":"https://enroll.invalid"}}"#).unwrap();
628        std::env::remove_var(PRODUCT_URL_ENV);
629        set_c2_product_url(None);
630        assert_eq!(M4aSessionAccounts::resolve_product_url(Some(&dir)).as_deref(), Some("https://enroll.invalid"));
631        set_c2_product_url(Some("https://c2.invalid".into()));
632        assert_eq!(M4aSessionAccounts::resolve_product_url(Some(&dir)).as_deref(), Some("https://c2.invalid"));
633        std::env::set_var(PRODUCT_URL_ENV, "https://env.invalid");
634        assert_eq!(M4aSessionAccounts::resolve_product_url(Some(&dir)).as_deref(), Some("https://env.invalid"));
635        std::env::remove_var(PRODUCT_URL_ENV);
636        set_c2_product_url(None);
637        std::fs::remove_dir_all(&dir).unwrap();
638    }
639
640    #[test]
641    fn each_spawn_gets_its_own_account_and_its_own_session_env() {
642        let dir = std::env::temp_dir().join(format!("hatch-m4a-{}", std::process::id()));
643        let _ = std::fs::remove_dir_all(&dir);
644        std::fs::create_dir_all(&dir).unwrap();
645        let acc = M4aSessionAccounts::new(fake_agent(&dir), dir.join("accounts"));
646        let a = acc.provision("codex", "inc-1").unwrap();
647        let b = acc.provision("codex", "inc-2").unwrap();
648        assert_ne!(a.nick, b.nick);
649        let env = a.env_mutations();
650        let keys: Vec<_> = env.iter().map(|m| m.key.to_string_lossy().into_owned()).collect();
651        assert_eq!(&keys[..5], ["M4A_NICK", "M4A_SESSION_CAP", "M4A_SESSION_ID", "M4A_BOT_NAME", "M4A_STORE_ROOT"]);
652        assert_eq!(env[2].value.as_deref(), Some(std::ffi::OsStr::new("ref-inc-1")));
653        assert_eq!(env[4].value.as_deref(), Some(std::ffi::OsStr::new("/s/inc-1")));
654        assert_ne!(env[1].value, b.env_mutations()[1].value);
655        // The one-shot cap file is gone and the cap is not in Debug output.
656        let left: Vec<_> = std::fs::read_dir(acc.base()).unwrap().filter_map(Result::ok).filter(|e| e.file_name().to_string_lossy().ends_with(".cap")).collect();
657        assert!(left.is_empty());
658        assert!(!format!("{a:?}").contains("cap-"));
659    }
660
661    #[test]
662    fn every_builtin_g4a_provider_maps_to_an_m4a_provider() {
663        for spec in gate4agent_catalog::builtin_specs() {
664            let id = spec.id.as_str().to_string();
665            assert!(m4a_provider(&id).is_some(), "g4a provider {id} has no m4a mapping");
666        }
667        assert_eq!(m4a_provider("custom"), None);
668    }
669
670    #[cfg(unix)]
671    #[test]
672    fn wake_token_is_private_stable_and_long() {
673        use std::os::unix::fs::PermissionsExt;
674        let dir = std::env::temp_dir().join(format!("node-wake-token-{}", std::process::id()));
675        let a = M4aSessionAccounts::new("/bin/false", &dir);
676        let t1 = a.wake_token().unwrap();
677        assert_eq!(t1.len(), 48);
678        assert_eq!(a.wake_token().unwrap(), t1);
679        let mode = std::fs::metadata(dir.join(".node-wake-token")).unwrap().permissions().mode() & 0o777;
680        assert_eq!(mode, 0o600);
681        let _ = std::fs::remove_dir_all(&dir);
682    }
683
684    #[test]
685    fn a_failing_agent_injects_nothing() {
686        let acc = M4aSessionAccounts::new("/nonexistent/m4a-agent", std::env::temp_dir().join("hatch-m4a-none"));
687        assert!(acc.provision("codex", "x").is_err());
688    }
689}
690
691fn codex_safe_value(v: &str) -> bool {
692    !v.is_empty() && !v.chars().any(|c| c.is_whitespace() || matches!(c, '\'' | '"' | '%' | '!' | '^' | '&' | '|' | '<' | '>' | '(' | ')'))
693}
694
695/// The `command` value for codex: the full path when it is safe, else the bare file name when
696/// the PATH lookup resolves to this same binary.
697fn codex_safe_command(bin: &Path) -> Option<String> {
698    let full = bin.to_string_lossy().into_owned();
699    if codex_safe_value(&full) {
700        return Some(full);
701    }
702    let name = bin.file_name()?.to_string_lossy().into_owned();
703    if !codex_safe_value(&name) {
704        return None;
705    }
706    let path = std::env::var_os("PATH")?;
707    let dir = bin.parent()?;
708    std::env::split_paths(&path)
709        .any(|p| p == dir)
710        .then(|| name.strip_suffix(".exe").map(str::to_owned).unwrap_or(name))
711}
712
713trait ZeroizeBestEffort {
714    fn zeroize_best_effort(&mut self);
715}
716
717impl ZeroizeBestEffort for String {
718    fn zeroize_best_effort(&mut self) {
719        // SAFETY: zero bytes keep the buffer valid UTF-8.
720        unsafe { self.as_bytes_mut() }.iter_mut().for_each(|b| *b = 0);
721    }
722}
723
724#[cfg(test)]
725mod session_file_tests {
726    use super::*;
727
728    #[test]
729    fn mcp_args_are_session_scoped_and_carry_no_capability() {
730        let root = std::env::temp_dir().join(format!("m4a-mcp-args-{}", std::process::id()));
731        let a = M4aSessionAccounts::new("m4a-agent", &root);
732        let c = a.mcp_launch_args("claude", "claude-1").unwrap();
733        assert_eq!(c[0], OsString::from("--mcp-config"));
734        let cfg = std::fs::read_to_string(&c[1]).unwrap();
735        assert!(cfg.contains("--session-file") && cfg.contains("claude-1.session"));
736        let x = a.mcp_launch_args("codex", "codex-1").unwrap();
737        assert_eq!(x.len(), 4);
738        assert!(x.iter().all(|v| !v.to_string_lossy().contains('"')));
739        assert!(a.mcp_launch_args("grok", "grok-1").unwrap().is_empty());
740        a.remove_session_file("claude-1");
741        assert!(!std::path::Path::new(&c[1]).exists());
742        let _ = std::fs::remove_dir_all(root);
743    }
744
745    #[test]
746    fn codex_values_never_carry_whitespace_or_quotes() {
747        assert!(codex_safe_value("/opt/m4a/bin/m4a-agent"));
748        assert!(!codex_safe_value("/home/a b/m4a-agent"));
749        assert!(!codex_safe_value("x'y"));
750        assert_eq!(codex_safe_command(Path::new("/opt/m4a/m4a-agent")).as_deref(), Some("/opt/m4a/m4a-agent"));
751        assert_eq!(codex_safe_command(Path::new("/no such dir/m4a-agent")), None);
752    }
753
754    #[test]
755    fn session_file_path_refuses_path_like_nicks() {
756        let a = M4aSessionAccounts::new("bin", std::env::temp_dir().join("m4a-sf-test"));
757        assert!(a.session_file_path("grok-1").unwrap().ends_with("sessions/grok-1.session"));
758        assert!(a.session_file_path("../x").is_none());
759        assert!(a.session_file_path("claude-3.hatchery-box.zeng3ld").is_some());
760        assert!(a.session_file_path("..x").is_none());
761        assert!(a.session_file_path(".x").is_none());
762        assert!(a.session_file_path("").is_none());
763    }
764}
765
766#[cfg(test)]
767mod node_account_message_tests {
768    #[test]
769    fn signed_bytes_follow_the_product_contract() {
770        let m = super::node_account_message("aud", "node-1", Some("nick-a"), 7, "n0");
771        assert_eq!(m, b"m4a-node-account-v1\naud\nnode-1\nnick-a\n7\nn0\n".to_vec());
772        assert_eq!(super::node_account_message("aud", "node-1", None, 7, "n0"), b"m4a-node-account-v1\naud\nnode-1\n\n7\nn0\n".to_vec());
773    }
774}