openmoat 0.25.0

Policy checks for AI coding agents: decides allow, defer, review or deny for each tool call the hook of Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot CLI and seven more agents reports, configures Claude Code's, Codex's and Cursor's own OS sandboxes from the same policy, and keeps a local audit log.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! `openmoat approvals`: answering reviews from another device (ADR-078).
//! Every command but `status` is a person's, as `openmoat allow` is: it
//! refuses without a terminal and with an agent among its parents, so an
//! agent can neither connect a channel, add an approver nor answer.
//!
//! No command names a channel: each takes it from the registry
//! ([`crate::remote::REGISTRY`]) and the settings. `listen` also runs as the
//! user service `install` writes ([`service`], ADR-094).

mod listen;
mod service;

use std::io::Write as _;

use anyhow::{Context as _, Result, bail};

use crate::cli::{ApprovalsStatusArgs, ApproverArgs, ConnectArgs, Format, WaitArgs};
use crate::exit::Code;
use crate::home::Home;
use crate::proxy_session::Key;
use crate::remote::{
    Credential, DEFAULT_EXPIRY_S, MAX_EXPIRY_S, MIN_EXPIRY_S, Options, REGISTRY, Secrets, Settings,
    Spec, Store,
};
use crate::render::Deferred;

pub use listen::listen;
pub use service::{install, lines as service_lines, uninstall};

fn person(command: &str) -> Result<()> {
    crate::terminal::refuse_agent(command)?;
    if !crate::terminal::interactive() {
        bail!("`{command}` must be run by a person in a terminal, not from a hook or script");
    }
    Ok(())
}

fn store() -> Result<(Home, Store)> {
    let home = Home::locate()?;
    home.require_exists()?;
    let store = Store::of(&home);
    Ok((home, store))
}

/// How to connect one, for messages: the registry's names.
fn how_to_connect() -> String {
    format!(
        "`openmoat approvals connect <{}>` sets one up",
        REGISTRY.names().join("|")
    )
}

/// The key and settings of a connected channel.
fn connected(store: &Store) -> Result<(Key, Settings)> {
    if !store.connected() {
        bail!("no channel is connected; {}", how_to_connect());
    }
    let key = Key::load(&store.key_path())?;
    let settings = Settings::load(&store.settings_path(), &key)?;
    Ok((key, settings))
}

/// A line the person types at the terminal, after `ask`.
fn ask(ask: &str) -> Result<String> {
    eprint!("{ask}");
    std::io::stderr().flush()?;
    Ok(crate::terminal::read_answer()?.trim().to_owned())
}

/// `spec`'s fields: settings from `--set`, the one secret from
/// `--credential-file`, and every other one asked at the terminal. A secret
/// is never taken from the command line, which other programs can read.
fn fields(spec: &Spec, args: &ConnectArgs) -> Result<(Secrets, Options)> {
    let mut secrets = Secrets::new();
    let mut options = Options::new();
    for pair in &args.options {
        let (key, value) = pair
            .split_once('=')
            .with_context(|| format!("--set {pair} is not KEY=VALUE"))?;
        let key = key.trim();
        if spec.fields.iter().any(|f| f.secret && f.key == key) {
            bail!(
                "`{key}` is a secret: it is asked at the terminal or read with \
                 --credential-file, never given on the command line"
            );
        }
        options.insert(key.to_owned(), value.trim().to_owned());
    }
    if let Some(path) = &args.credential_file {
        let mut secret = spec.fields.iter().filter(|f| f.secret);
        let (Some(only), None) = (secret.next(), secret.next()) else {
            bail!(
                "--credential-file reads one secret; {} takes another number, asked at \
                 the terminal",
                spec.title
            );
        };
        let text = Credential::new(
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?,
        );
        secrets.insert(only.key.to_owned(), Credential::new(text.trim().to_owned()));
    }
    for field in spec.fields {
        let have = if field.secret {
            secrets.contains_key(field.key)
        } else {
            options.contains_key(field.key)
        };
        if have {
            continue;
        }
        if field.secret {
            // Echo off, never printed back, and never from piped input.
            let secret = crate::terminal::read_secret(field.ask).with_context(|| {
                format!(
                    "reading {}'s {} (--credential-file FILE reads it from a file)",
                    spec.title, field.key
                )
            })?;
            secrets.insert(field.key.to_owned(), secret);
        } else {
            options.insert(field.key.to_owned(), ask(field.ask)?);
        }
    }
    Ok((secrets, options))
}

/// `openmoat approvals connect <channel>`.
pub fn connect(args: &ConnectArgs) -> Result<Code> {
    person("openmoat approvals connect")?;
    let spec = REGISTRY.find(&args.channel)?;
    let expiry_s = match &args.expires {
        None => DEFAULT_EXPIRY_S,
        Some(text) => crate::time::parse_span(text)
            .map(|ms| u64::try_from(ms / 1000).unwrap_or(0))
            .filter(|s| (MIN_EXPIRY_S..=MAX_EXPIRY_S).contains(s))
            .with_context(|| {
                format!("--expires {text} is not a span of 1 to 60 minutes, such as `5m`")
            })?,
    };
    let (_home, store) = store()?;
    let (secrets, options) = fields(spec, args)?;
    let account = crate::remote::connect(&store, spec, &secrets, options, expiry_s)?;
    let mut out = Deferred::default();
    writeln!(
        out,
        "connected {} as {account}; its credential is in {} (owner-only)",
        spec.title,
        store.channel(spec).credential_path().display()
    )?;
    if let Some(path) = &args.credential_file {
        writeln!(out, "you can delete {} now", path.display())?;
    }
    writeln!(
        out,
        "next:\n{}\nrequests wait {} minute(s) for an answer",
        (spec.next_steps)(&account),
        expiry_s / 60
    )?;
    out.finish()?;
    Ok(Code::Ok)
}

/// `openmoat approvals allow <id>`.
pub fn allow(args: &ApproverArgs) -> Result<Code> {
    person("openmoat approvals allow")?;
    let (_home, store) = store()?;
    let (key, mut settings) = connected(&store)?;
    let spec = REGISTRY.find(&settings.channel)?;
    let id = REGISTRY.approver(spec, &args.user_id)?;
    let mut out = Deferred::default();
    if settings.approver(&id) {
        writeln!(out, "{id} can already approve")?;
    } else {
        settings.approvers.push(id.clone());
        settings.save(&store.settings_path(), &key)?;
        writeln!(
            out,
            "{id} can now approve calls held for review on this machine; `openmoat approvals \
             remove {id}` takes that back"
        )?;
    }
    out.finish()?;
    Ok(Code::Ok)
}

/// `openmoat approvals remove <id>`.
pub fn remove(args: &ApproverArgs) -> Result<Code> {
    person("openmoat approvals remove")?;
    let (_home, store) = store()?;
    let (key, mut settings) = connected(&store)?;
    let spec = REGISTRY.find(&settings.channel)?;
    let id = REGISTRY.approver(spec, &args.user_id)?;
    if !settings.approver(&id) {
        bail!("{id} is not an approver");
    }
    settings.approvers.retain(|a| a != &id);
    settings.save(&store.settings_path(), &key)?;
    let mut out = Deferred::default();
    writeln!(
        out,
        "{id} can no longer approve; answers it gave that are not used yet no longer count"
    )?;
    out.finish()?;
    Ok(Code::Ok)
}

/// The service's lines as `status --format json` gives them: `null` when it
/// is not installed.
fn service_json(lines: &[(bool, String)]) -> serde_json::Value {
    if lines.is_empty() {
        return serde_json::Value::Null;
    }
    serde_json::json!({
        "ok": lines.iter().all(|(ok, _)| *ok),
        "lines": lines.iter().map(|(_, line)| line).collect::<Vec<_>>(),
    })
}

/// What `status` reports of a connected channel.
struct State {
    settings: Settings,
    account: Option<String>,
    waiting: usize,
    /// Whether a listener's beat is fresh ([`crate::remote::live`]).
    listening: bool,
    problem: Option<String>,
}

fn state(store: &Store) -> Result<State> {
    let (key, settings) = connected(store)?;
    let now = crate::time::now_ms();
    let waiting = store
        .requests()
        .unwrap_or_default()
        .into_iter()
        .flatten()
        .filter(|r| r.verified(&key) && !r.expired(now))
        .count();
    let listening = crate::remote::live::live(store, &key, &settings.channel, now);
    let (account, problem) = match REGISTRY.find(&settings.channel) {
        Ok(spec) => (
            crate::remote::account(store, &REGISTRY, &key, &settings),
            crate::remote::credential_problem(store, spec),
        ),
        Err(error) => (None, Some(format!("{error:#}"))),
    };
    Ok(State {
        settings,
        account,
        waiting,
        listening,
        problem,
    })
}

/// `openmoat approvals status`: read-only, so no terminal is needed.
pub fn status(args: &ApprovalsStatusArgs) -> Result<Code> {
    let (home, store) = store()?;
    let service = service::lines(&home);
    let state = if store.connected() {
        state(&store)
    } else {
        Err(anyhow::Error::msg("no channel connected"))
    };
    if args.format == Format::Json {
        let value = match &state {
            Ok(s) => serde_json::json!({
                "connected": true,
                "channel": s.settings.channel,
                "account": s.account,
                "approvers": s.settings.approvers,
                "expiry_s": s.settings.expiry_s,
                "wait_s": s.settings.wait().as_secs(),
                "listening": s.listening,
                "waiting": s.waiting,
                "problem": s.problem,
                "service": service_json(&service),
            }),
            Err(error) => serde_json::json!({
                "connected": false,
                "problem": store.connected().then(|| format!("{error:#}")),
                "service": service_json(&service),
            }),
        };
        crate::render::json(&value)?;
        return Ok(Code::Ok);
    }
    let mut out = Deferred::default();
    match state {
        Ok(s) => {
            match &s.account {
                Some(account) => writeln!(out, "channel: {} ({account})", s.settings.channel)?,
                None => writeln!(out, "channel: {}", s.settings.channel)?,
            }
            if s.settings.approvers.is_empty() {
                writeln!(
                    out,
                    "approvers: none yet; `openmoat approvals allow <user id>` adds one"
                )?;
            } else {
                writeln!(out, "approvers: {}", s.settings.approvers.join(", "))?;
            }
            writeln!(out, "requests wait: {} minute(s)", s.settings.expiry_s / 60)?;
            match s.settings.wait().as_secs() {
                0 => writeln!(
                    out,
                    "the hook waits: no (`openmoat approvals wait <seconds>`)"
                )?,
                wait => writeln!(
                    out,
                    "the hook waits: up to {wait} s while the listener runs ({})",
                    if s.listening {
                        "running now"
                    } else {
                        "not running now"
                    }
                )?,
            }
            writeln!(out, "waiting now: {}", s.waiting)?;
            if let Some(problem) = s.problem {
                writeln!(out, "problem: {problem}")?;
            }
            if service.is_empty() {
                writeln!(
                    out,
                    "answers arrive only while `openmoat approvals listen` runs; `openmoat \
                     approvals install` keeps it running"
                )?;
            }
        }
        Err(_) if !store.connected() => writeln!(
            out,
            "no channel connected: reviews are answered where the agent runs; {}",
            how_to_connect()
        )?,
        Err(error) => writeln!(
            out,
            "channel settings unusable, so no remote answer is accepted: {error:#}"
        )?,
    }
    for (ok, line) in &service {
        writeln!(out, "{} {line}", if *ok { "✔" } else { "✗" })?;
    }
    out.finish()?;
    Ok(Code::Ok)
}

/// `openmoat approvals test`.
pub fn test() -> Result<Code> {
    person("openmoat approvals test")?;
    let (_home, store) = store()?;
    let (key, settings) = connected(&store)?;
    if settings.approvers.is_empty() {
        bail!("no approver yet; `openmoat approvals allow <user id>` adds one");
    }
    let (spec, mut channel) = crate::remote::open(&store, &REGISTRY, &key, &settings)?;
    let mut out = Deferred::default();
    let mut failed = false;
    for approver in &settings.approvers {
        let Some(local) = crate::remote::channel::local_id(spec.name, approver) else {
            continue;
        };
        match channel.notify(
            local,
            "OpenMoat: a test message. Calls held for review on this machine will come here \
             while `openmoat approvals listen` runs.",
        ) {
            Ok(()) => writeln!(out, "sent to {approver}")?,
            Err(error) => {
                failed = true;
                writeln!(out, "could not reach {approver}: {error:#}")?;
            }
        }
    }
    out.finish()?;
    Ok(if failed { Code::Failed } else { Code::Ok })
}

/// `openmoat approvals wait <seconds>`: how long the hook waits for an answer
/// while `listen` runs (ADR-093); `0` never waits.
pub fn wait(args: &WaitArgs) -> Result<Code> {
    person("openmoat approvals wait")?;
    let (_home, store) = store()?;
    let (key, mut settings) = connected(&store)?;
    settings.set_wait(args.seconds)?;
    settings.save(&store.settings_path(), &key)?;
    let mut out = Deferred::default();
    if args.seconds == 0 {
        writeln!(
            out,
            "the hook no longer waits: an approval from {} runs the call on its next try",
            settings.channel
        )?;
    } else {
        writeln!(
            out,
            "while `openmoat approvals listen` runs, the hook waits up to {} s for an answer \
             (less where the agent's hook time limit or the guard's own budget leaves less)",
            args.seconds
        )?;
    }
    out.finish()?;
    Ok(Code::Ok)
}

/// `openmoat approvals disconnect`.
pub fn disconnect() -> Result<Code> {
    person("openmoat approvals disconnect")?;
    let (home, store) = store()?;
    let (was, removed) = crate::remote::disconnect(&store, &REGISTRY)?;
    let mut out = Deferred::default();
    if removed {
        write!(
            out,
            "disconnected: reviews are answered only where the agent runs"
        )?;
        match was {
            Some(spec) => writeln!(out, "; {}", spec.revoke)?,
            None => writeln!(out)?,
        }
    } else {
        writeln!(out, "no channel was connected")?;
    }
    if !service::lines(&home).is_empty() {
        writeln!(
            out,
            "the listener's service keeps running and waits for a channel; `openmoat \
             approvals uninstall` removes it"
        )?;
    }
    out.finish()?;
    Ok(Code::Ok)
}