mod binary;
mod claude_version;
mod dirs;
mod hook_file;
pub mod openclaw;
pub mod self_paths;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context as _, Result, bail};
use openmoat_hosts::{Host, InstallSpec};
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,
pub block_on_failure: bool,
}
const TOOL_HOOK_TIMEOUT_S: u64 = 600;
const CONFIG_HOOK_TIMEOUT_S: u64 = 60;
pub const GUARD_BUDGET_S: u64 = 30;
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|ReadMcpResourceTool|EnterWorktree|Skill|mcp__.*";
const CLAUDE_CODE_HOOKS: &[HookSpec] = &[
HookSpec {
event: "PreToolUse",
matcher: TOOL_MATCHER,
timeout: TOOL_HOOK_TIMEOUT_S,
block_on_failure: true,
},
HookSpec {
event: "ConfigChange",
matcher: "user_settings|project_settings|local_settings",
timeout: CONFIG_HOOK_TIMEOUT_S,
block_on_failure: false,
},
];
const CODEX_HOOKS: &[HookSpec] = &[HookSpec {
event: "PreToolUse",
matcher: "Bash|apply_patch|mcp__.*",
timeout: TOOL_HOOK_TIMEOUT_S,
block_on_failure: false,
}];
const CURSOR_HOOKS: &[HookSpec] = &[
HookSpec {
event: "beforeShellExecution",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
block_on_failure: false,
},
HookSpec {
event: "beforeMCPExecution",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
block_on_failure: false,
},
HookSpec {
event: "beforeReadFile",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
block_on_failure: false,
},
HookSpec {
event: "preToolUse",
matcher: "",
timeout: TOOL_HOOK_TIMEOUT_S,
block_on_failure: false,
},
];
pub const OPENCLAW_HOOK_TIMEOUT_S: u64 = 60;
const _: () = assert!(GUARD_BUDGET_S < OPENCLAW_HOOK_TIMEOUT_S);
const OPENCLAW_HOOKS: &[HookSpec] = &[HookSpec {
event: "before_tool_call",
matcher: "",
timeout: OPENCLAW_HOOK_TIMEOUT_S,
block_on_failure: false,
}];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookFormat {
Nested,
Cursor,
OpenClaw,
}
#[derive(Debug, Clone)]
pub struct HostConfig {
pub host: Host,
pub settings_path: PathBuf,
pub dir: PathBuf,
pub hooks: &'static [HookSpec],
pub format: HookFormat,
pub blocks_on_failure: fn() -> bool,
}
pub fn dir_variable(host: Host) -> Result<(&'static str, &'static str)> {
let install = install_spec(host)?;
Ok((install.dir_variable, install.dir_name))
}
fn install_spec(host: Host) -> Result<&'static InstallSpec> {
match &host.spec().install {
Some(install) => Ok(install),
None => bail!(
"{} runs another agent's hook; it has none of its own",
host.display_name()
),
}
}
pub fn env_config_dir(host: Host) -> Result<Option<PathBuf>> {
if host == Host::OpenClaw {
return Ok(openclaw::Location::from_env()?.map(|l| l.state_dir));
}
Ok(env_dir(dir_variable(host)?.0))
}
impl HostConfig {
pub fn for_host(home: &Home, host: Host) -> Result<Self> {
let recorded = Recorded::load(home)?;
if host == Host::OpenClaw {
let location = match recorded.dir(host) {
Some(dir) => openclaw::Location::at(dir, recorded.file(host)),
None => match openclaw::Location::from_env()? {
Some(location) => location,
None => openclaw::Location::default_for(&user_home()?),
},
};
return Ok(Self::openclaw(location));
}
Self::at(host, recorded.dir(host).or(env_config_dir(host)?))
}
pub fn for_init(home: &Home, host: Host) -> Result<Self> {
if host == Host::OpenClaw
&& let Some(location) = openclaw::Location::from_env()?
{
return Ok(Self::openclaw(location));
}
match env_config_dir(host)? {
Some(dir) => Self::at(host, Some(dir)),
None => Self::for_host(home, host),
}
}
fn openclaw(location: openclaw::Location) -> Self {
Self {
host: Host::OpenClaw,
settings_path: location.config,
dir: location.state_dir,
hooks: OPENCLAW_HOOKS,
format: HookFormat::OpenClaw,
blocks_on_failure: || false,
}
}
pub fn openclaw_location(&self) -> Option<openclaw::Location> {
(self.host == Host::OpenClaw)
.then(|| openclaw::Location::at(self.dir.clone(), Some(self.settings_path.clone())))
}
fn at(host: Host, dir: Option<PathBuf>) -> Result<Self> {
let install = install_spec(host)?;
let dir = match dir {
Some(dir) => dir,
None => user_home()?.join(install.dir_name),
};
let (hooks, format) = match host {
Host::ClaudeCode => (CLAUDE_CODE_HOOKS, HookFormat::Nested),
Host::Codex => (CODEX_HOOKS, HookFormat::Nested),
Host::OpenClaw => (OPENCLAW_HOOKS, HookFormat::OpenClaw),
_ => (CURSOR_HOOKS, HookFormat::Cursor),
};
let blocks_on_failure: fn() -> bool = match host {
Host::ClaudeCode => claude_version::blocks_on_failure,
_ => || false,
};
Ok(Self {
host,
settings_path: dir.join(install.config_file),
dir,
hooks,
format,
blocks_on_failure,
})
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn host_present(&self) -> bool {
self.dir.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 render(&self, binary: &Path, current: &str) -> Result<Option<String>> {
hook_file::render(self, binary, current)
}
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 fn runs_calls_when_hook_fails(&self) -> bool {
hook_file::lacks_on_failure(self)
}
}
pub fn continue_cli_warning() -> &'static str {
Host::Continue.spec().gaps
}
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)
}