Skip to main content

mecha_core/
lib.rs

1//! `mecha-core` — an agent harness for local models.
2//!
3//! The library knows nothing about any particular CLI, UI, or project. It gives
4//! you four things and lets you wire them together:
5//!
6//!   * [`provider`] — talk to a model (Anthropic, or anything OpenAI-shaped)
7//!   * [`tool`] — things the agent can do, native or [`mcp`]-backed
8//!   * [`agent`] — the loop that puts those together
9//!   * [`session`] / [`batch`] — persistence and fan-out around the loop
10//!
11//! ```no_run
12//! # async fn example() -> anyhow::Result<()> {
13//! use mecha_core::{agent::Agent, agent::Conversation, config::Config};
14//! use mecha_core::sandbox::Sandbox;
15//! use mecha_core::tool::{ModeApprover, Registry, ToolCtx};
16//! use std::sync::Arc;
17//!
18//! let cfg = Config::load(&std::env::current_dir()?)?;
19//! let (_, provider_cfg) = cfg.provider(None)?;
20//!
21//! // How `shell` is confined. It decides that tool's declared capabilities,
22//! // so it is built before the registry rather than consulted at call time.
23//! let sandbox = Arc::new(Sandbox::new(cfg.sandbox.clone()));
24//!
25//! let agent = Agent::new(
26//!     mecha_core::provider::build(provider_cfg)?,
27//!     Registry::new().with_builtins(&cfg.tools, sandbox),
28//!     Arc::new(ModeApprover { mode: cfg.tools.permission_mode }),
29//!     ToolCtx {
30//!         workspace: std::env::current_dir()?,
31//!         shell_timeout: std::time::Duration::from_secs(cfg.tools.shell_timeout_secs),
32//!         security: cfg.security.clone(),
33//!         ..ToolCtx::default()
34//!     },
35//!     cfg.agent.clone(),
36//!     None,
37//! )?;
38//!
39//! // A conversation carries its own taint, so keeping it across turns keeps
40//! // the trifecta interlock honest — see `agent::Conversation`.
41//! let mut convo = Conversation::user("What changed in this repo today?");
42//! let outcome = agent.run(&mut convo, None).await?;
43//! println!("{}", outcome.text);
44//! # Ok(())
45//! # }
46//! ```
47
48pub mod agent;
49pub mod batch;
50pub mod cache_lens;
51pub mod candidate;
52pub mod compact;
53pub mod config;
54pub mod counterfactual;
55pub mod cron;
56pub mod diagnose;
57pub mod distill;
58pub mod doctor;
59pub mod eval;
60pub mod frontdoor;
61pub mod gossip;
62pub mod hooks;
63pub mod learning;
64pub mod mail_triage;
65pub mod mailbox;
66pub mod mcp;
67pub mod message;
68pub mod outbox;
69pub mod provider;
70pub mod replay;
71pub mod replay_run;
72pub mod runlog;
73pub mod sandbox;
74pub mod search;
75pub mod session;
76pub mod subagent;
77pub mod tool;
78pub mod trigger;
79pub mod work;
80
81pub use agent::{Agent, AgentEvent, RunOutcome};
82pub use config::Config;
83pub use message::{Block, Effort, Message, Role, StopReason, Usage};
84
85pub const VERSION: &str = env!("CARGO_PKG_VERSION");
86
87/// Create a directory (and its parents) and make the leaf owner-only.
88///
89/// Transcripts, staged outbox drafts, the learning store and spilled tool
90/// output all carry the user's private data — mail bodies included, now that
91/// mail is wired — so their directories get the rule the mail token files
92/// already enforce on themselves (0600). The leaf only, on purpose: parents
93/// like `~/.mecha` also hold things the user may deliberately share, and the
94/// sensitive data lives below the leaf. Idempotent, and tightens a
95/// pre-existing directory too.
96/// Is this pid still around? `kill(pid, 0)` checks without delivering
97/// anything; `EPERM` means it exists and is not ours, which still counts.
98///
99/// The range check is not defensive padding — it is the whole correctness of
100/// the function. `kill(2)` gives non-positive pids entirely different
101/// meanings: `0` is "every process in my group", `-1` is "every process I may
102/// signal" (which succeeds, always), and any other negative is a process
103/// group. A corrupt marker holding one of those would report a long-dead run
104/// as alive and leave whatever owns the marker looking permanently busy in
105/// every UI that asks. Found by a test using `u32::MAX`, which sign-flips to exactly the
106/// `-1` case.
107pub fn process_alive(pid: u32) -> bool {
108    let Ok(pid) = libc::pid_t::try_from(pid) else {
109        return false;
110    };
111    if pid <= 0 {
112        return false;
113    }
114    // SAFETY: signal 0 delivers nothing and only probes for the process.
115    let rc = unsafe { libc::kill(pid, 0) };
116    rc == 0 || std::io::Error::last_os_error().kind() == std::io::ErrorKind::PermissionDenied
117}
118
119pub fn create_private_dir(dir: &std::path::Path) -> std::io::Result<()> {
120    std::fs::create_dir_all(dir)?;
121    #[cfg(unix)]
122    {
123        use std::os::unix::fs::PermissionsExt;
124        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
125    }
126    Ok(())
127}
128
129#[cfg(test)]
130mod process_alive_tests {
131    /// The case that found the bug, kept beside the function now that more
132    /// than one subsystem depends on it: `u32::MAX` sign-flips to `-1`, which
133    /// `kill(2)` reads as "every process I may signal" and answers yes to.
134    #[test]
135    fn a_pid_that_is_not_a_pid_is_never_alive() {
136        assert!(!super::process_alive(u32::MAX));
137        assert!(!super::process_alive(0), "0 means my whole process group");
138        assert!(
139            !super::process_alive(i32::MAX as u32),
140            "real-looking and far above any pid_max"
141        );
142        assert!(
143            super::process_alive(std::process::id()),
144            "and the negative is not vacuous: we are alive"
145        );
146    }
147}