mod binary;
mod dirs;
mod hook_file;
pub mod self_paths;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result, bail};
use openmoat_hosts::Host;
pub use binary::{hook_binary, stale_hint};
pub use dirs::Recorded;
pub use hook_file::{HookState, Outcome, read_or_empty};
use crate::home::{Home, user_home};
pub const HOOK_BACKUP: &str = "moat-backup";
pub const SANDBOX_BACKUP: &str = "moat-sandbox-backup";
pub fn backup_path(path: &Path, suffix: &str) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(".");
name.push(suffix);
PathBuf::from(name)
}
pub fn back_up(home: &Home, path: &Path, suffix: &str) -> Result<()> {
let backup = backup_path(path, suffix);
if !path.exists() || fs::symlink_metadata(&backup).is_ok() {
return Ok(());
}
fs::copy(path, &backup).with_context(|| format!("backing up {}", path.display()))?;
let mut recorded = Recorded::load(home)?;
recorded.backups.push(backup);
recorded.save(home)
}
pub fn backups(path: &Path) -> Vec<PathBuf> {
[HOOK_BACKUP, SANDBOX_BACKUP]
.into_iter()
.map(|suffix| backup_path(path, suffix))
.filter(|p| p.is_file())
.collect()
}
#[derive(Debug, Clone, Copy)]
pub struct HookSpec {
pub event: &'static str,
pub matcher: &'static str,
pub timeout: u64,
}
const TOOL_HOOK_TIMEOUT_S: u64 = 600;
const CONFIG_HOOK_TIMEOUT_S: u64 = 60;
pub const GUARD_BUDGET_S: u64 = 10;
const _: () = assert!(GUARD_BUDGET_S < CONFIG_HOOK_TIMEOUT_S);
const _: () = assert!(GUARD_BUDGET_S < TOOL_HOOK_TIMEOUT_S);
const TOOL_MATCHER: &str = "Bash|Monitor|PowerShell|Edit|Write|MultiEdit|NotebookEdit|Read|Glob|Grep|LSP|SendFile|WebFetch|WebSearch|mcp__.*";
const CLAUDE_CODE_HOOKS: &[HookSpec] = &[
HookSpec {
event: "PreToolUse",
matcher: TOOL_MATCHER,
timeout: TOOL_HOOK_TIMEOUT_S,
},
HookSpec {
event: "ConfigChange",
matcher: "user_settings|project_settings|local_settings",
timeout: CONFIG_HOOK_TIMEOUT_S,
},
];
const CODEX_HOOKS: &[HookSpec] = &[HookSpec {
event: "PreToolUse",
matcher: "Bash|apply_patch|mcp__.*",
timeout: TOOL_HOOK_TIMEOUT_S,
}];
const CURSOR_HOOKS: &[HookSpec] = &[
HookSpec {
event: "beforeShellExecution",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
},
HookSpec {
event: "beforeMCPExecution",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
},
HookSpec {
event: "beforeReadFile",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
},
HookSpec {
event: "preToolUse",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
},
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookFormat {
Nested,
Cursor,
}
#[derive(Debug, Clone)]
pub struct HostConfig {
pub host: Host,
pub settings_path: PathBuf,
pub hooks: &'static [HookSpec],
pub format: HookFormat,
}
pub fn dir_variable(host: Host) -> Result<(&'static str, &'static str)> {
Ok(match host {
Host::ClaudeCode => ("CLAUDE_CONFIG_DIR", ".claude"),
Host::Codex => ("CODEX_HOME", ".codex"),
Host::Cursor => ("CURSOR_CONFIG_DIR", ".cursor"),
Host::Continue => {
bail!("the Continue CLI runs the Claude Code hook; it has none of its own")
}
})
}
pub fn env_config_dir(host: Host) -> Result<Option<PathBuf>> {
Ok(env_dir(dir_variable(host)?.0))
}
impl HostConfig {
pub fn for_host(home: &Home, host: Host) -> Result<Self> {
let recorded = Recorded::load(home)?;
Self::at(host, recorded.dir(host).or(env_config_dir(host)?))
}
pub fn for_init(home: &Home, host: Host) -> Result<Self> {
match env_config_dir(host)? {
Some(dir) => Self::at(host, Some(dir)),
None => Self::for_host(home, host),
}
}
fn at(host: Host, dir: Option<PathBuf>) -> Result<Self> {
let (_, default) = dir_variable(host)?;
let dir = match dir {
Some(dir) => dir,
None => user_home()?.join(default),
};
let (file, hooks, format) = match host {
Host::ClaudeCode => ("settings.json", CLAUDE_CODE_HOOKS, HookFormat::Nested),
Host::Codex => ("hooks.json", CODEX_HOOKS, HookFormat::Nested),
_ => ("hooks.json", CURSOR_HOOKS, HookFormat::Cursor),
};
Ok(Self {
host,
settings_path: dir.join(file),
hooks,
format,
})
}
pub fn dir(&self) -> &Path {
self.settings_path.parent().unwrap_or(&self.settings_path)
}
pub fn host_present(&self) -> bool {
self.settings_path
.parent()
.is_some_and(std::path::Path::is_dir)
}
pub fn install(&self, home: &Home, binary: &Path, dry_run: bool) -> Result<Outcome> {
hook_file::install(home, self, binary, dry_run)
}
pub fn state(&self, binary: &std::path::Path) -> HookState {
hook_file::state(self, binary)
}
pub fn set_up(&self, binary: &std::path::Path) -> bool {
self.state(binary) == HookState::Installed
}
pub fn remove(&self, root: &mut serde_json::Value) -> bool {
hook_file::remove(root, self)
}
}
pub const CONTINUE_CLI_WARNING: &str = "the released Continue CLI does not run hooks, so \
OpenMoat cannot check its tool calls; run it under `moat run`";
pub fn continue_cli() -> Result<Option<PathBuf>> {
let dir = match env_dir("CONTINUE_GLOBAL_DIR") {
Some(dir) => dir,
None => user_home()?.join(".continue"),
};
if dir.is_dir() {
return Ok(Some(dir));
}
let path: Vec<PathBuf> = std::env::var_os("PATH")
.map(|p| std::env::split_paths(&p).collect())
.unwrap_or_default();
Ok(crate::environment::find_in(&path, &[], "cn"))
}
fn env_dir(name: &str) -> Option<PathBuf> {
std::env::var_os(name)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
}