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 harness;
63pub mod hooks;
64pub mod image;
65pub mod learning;
66pub mod mail_triage;
67pub mod mailbox;
68pub mod mcp;
69pub mod message;
70pub mod onboarding;
71pub mod outbox;
72pub mod outbox_source;
73pub mod provider;
74pub mod replay;
75pub mod replay_run;
76pub mod runlog;
77pub mod sandbox;
78pub mod search;
79pub mod session;
80pub mod skill;
81pub mod subagent;
82pub mod tool;
83pub mod trigger;
84pub mod work;
85
86pub use agent::{Agent, AgentEvent, RunOutcome};
87pub use config::Config;
88pub use message::{Block, Effort, Message, Role, StopReason, Usage};
89
90pub const VERSION: &str = env!("CARGO_PKG_VERSION");
91
92/// Create a directory (and its parents) and make the leaf owner-only.
93///
94/// Transcripts, staged outbox drafts, the learning store and spilled tool
95/// output all carry the user's private data — mail bodies included, now that
96/// mail is wired — so their directories get the rule the mail token files
97/// already enforce on themselves (0600). The leaf only, on purpose: parents
98/// like `~/.mecha` also hold things the user may deliberately share, and the
99/// sensitive data lives below the leaf. Idempotent, and tightens a
100/// pre-existing directory too.
101/// Is this pid still around? `kill(pid, 0)` checks without delivering
102/// anything; `EPERM` means it exists and is not ours, which still counts.
103///
104/// The range check is not defensive padding — it is the whole correctness of
105/// the function. `kill(2)` gives non-positive pids entirely different
106/// meanings: `0` is "every process in my group", `-1` is "every process I may
107/// signal" (which succeeds, always), and any other negative is a process
108/// group. A corrupt marker holding one of those would report a long-dead run
109/// as alive and leave whatever owns the marker looking permanently busy in
110/// every UI that asks. Found by a test using `u32::MAX`, which sign-flips to exactly the
111/// `-1` case.
112pub fn process_alive(pid: u32) -> bool {
113    let Ok(pid) = libc::pid_t::try_from(pid) else {
114        return false;
115    };
116    if pid <= 0 {
117        return false;
118    }
119    // SAFETY: signal 0 delivers nothing and only probes for the process.
120    let rc = unsafe { libc::kill(pid, 0) };
121    rc == 0 || std::io::Error::last_os_error().kind() == std::io::ErrorKind::PermissionDenied
122}
123
124pub fn create_private_dir(dir: &std::path::Path) -> std::io::Result<()> {
125    std::fs::create_dir_all(dir)?;
126    #[cfg(unix)]
127    {
128        use std::os::unix::fs::PermissionsExt;
129        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
130    }
131    Ok(())
132}
133
134#[cfg(test)]
135mod process_alive_tests {
136    /// The case that found the bug, kept beside the function now that more
137    /// than one subsystem depends on it: `u32::MAX` sign-flips to `-1`, which
138    /// `kill(2)` reads as "every process I may signal" and answers yes to.
139    #[test]
140    fn a_pid_that_is_not_a_pid_is_never_alive() {
141        assert!(!super::process_alive(u32::MAX));
142        assert!(!super::process_alive(0), "0 means my whole process group");
143        assert!(
144            !super::process_alive(i32::MAX as u32),
145            "real-looking and far above any pid_max"
146        );
147        assert!(
148            super::process_alive(std::process::id()),
149            "and the negative is not vacuous: we are alive"
150        );
151    }
152}