Skip to main content

mecha_core/
lib.rs

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