openlatch-client 0.6.5

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Cursor's binding — the IDE and the CLI (`cursor-agent`), which read one
//! user-level `~/.cursor/hooks.json`.
//!
//! Cursor's entry is **flat** (`{type, command, timeout}`) and its file root
//! carries `"version": 1`. Nothing else goes into Cursor's file: no `matcher`
//! (its regex flavour is undocumented) and no `_openlatch` marker (Cursor does
//! not document tolerating an unknown key, and a rejected one would stop the
//! whole file loading, the developer's own hooks included). Ownership is
//! therefore a [`MarkerPlacement::Sidecar`].

use std::path::{Path, PathBuf};

use serde_json::{json, Value};

use crate::core::hook_state::marker::OpenlatchMarker;

use crate::model_relay::wire_format::WireFormat;

use super::super::binding::{
    AgentBinding, BindingCapabilities, DaemonChannel, EndpointConvention, Enforces, EnvCommand,
    FailureMode, LivenessReport, MarkerPlacement, ModelRelayWiring, ProxyDelivery,
};
use crate::core::envelope::alias::{AliasTable, EventTool, McpKeyRule, MultiValueRule};

/// Cursor's alias table (D-I16-22).
///
/// `Shell` (`preToolUse`) and `beforeShellExecution` — an event that IS the
/// command and names no tool — are both `Bash`. `Read`, `Write`, `Grep` and
/// `Task` are already canonical. `Delete` is unmapped on purpose. An MCP call
/// names its server beside the tool (`mcp_server_name`), or arrives as
/// `MCP:<tool>` with none (`mcp__unknown__<tool>`), and its arguments are a
/// JSON string.
pub static ALIASES: AliasTable = AliasTable {
    agent: "cursor",
    binding: "cursor_hook",
    renders_binding: None,
    tools: &[
        ("Shell", "Bash"),
        ("Read", "Read"),
        ("Write", "Write"),
        ("Grep", "Grep"),
        ("Task", "Task"),
    ],
    event_tools: &[EventTool {
        event: "beforeShellExecution",
        canonical: "Bash",
        keys: &["command", "cwd", "sandbox"],
    }],
    keep: &[("Shell", &["command", "cwd"])],
    inputs: &[],
    creates: &[],
    mcp_rule: McpKeyRule {
        server_field: Some("mcp_server_name"),
        bare_prefix: Some("MCP:"),
        wrapper: None,
        joined: false,
        json_string_input: true,
    },
    multi: MultiValueRule::NONE,
};

/// The events this build installs: the four deciding ones first, then the
/// record-only ones.
///
/// The deciding events ([`DECIDING`]) arrive together with
/// `hook_output::cursor`, and never one without the other: without that arm
/// `hook_output::translate` ends in `_ => empty()`, and a deciding hook that
/// prints `{}` for every verdict is an allow.
const EVENT_TYPES: &[&str] = &[
    "preToolUse",
    "beforeShellExecution",
    "beforeMCPExecution",
    "beforeSubmitPrompt",
    "sessionStart",
    "sessionEnd",
    "postToolUse",
    "postToolUseFailure",
    "subagentStop",
    "preCompact",
    "stop",
];

/// Cursor's permission events — the ones whose answer can refuse the action.
///
/// Their entries carry the long timeout below; every other event records.
const DECIDING: &[&str] = &[
    "preToolUse",
    "beforeShellExecution",
    "beforeMCPExecution",
    "beforeSubmitPrompt",
];

/// The hosts Cursor's model traffic reaches, every one flagged HTTP/2 (I-2 D-06).
///
/// `api2.cursor.sh` is FIRST: the preflight proves trust against `intercept_hosts[0]`. Cursor
/// sends every model request to its own backend over Connect-RPC, so interception is its only
/// lane. Never listed, so tunnelled untouched: `api3.cursor.sh` (Tab), `repo42.cursor.sh`,
/// `metrics.cursor.sh`, `api.origin.cursor.com`, and the marketplace and auth hosts. No host here
/// is one of Cline's — a shared host attributes nothing (`WiringState::sole_interceptor_for`).
pub const CURSOR_INTERCEPT_HOSTS: &[&str] = &[
    "api2.cursor.sh",
    "api5.cursor.sh",
    "agent.api5.cursor.sh",
    "agentn.api5.cursor.sh",
    "agent.us.api5.cursor.sh",
    "agentn.us.api5.cursor.sh",
    "agent.global.api5.cursor.sh",
    "agentn.global.api5.cursor.sh",
];

/// Whether this build points the Cursor IDE at the relay (D-08). `true` only in a build where the
/// IDE proof passed (a VM machine install, never a developer's own machine); until then the IDE
/// request plane is `unsupported` (doctor reads that off the absent `SettingsKey` delivery) and only
/// the CLI is wired.
const CURSOR_IDE_DELIVERY: bool = false;

/// The CLI's commands. `agent` is a generic name, so its wrapper is defined only when it resolves
/// into Cursor's own install (D-07); `cursor-agent` needs no guard.
const CURSOR_COMMANDS: &[EnvCommand] = &[
    EnvCommand::plain("cursor-agent"),
    EnvCommand {
        name: "agent",
        resolve_guard: Some("cursor-agent"),
    },
];

const CURSOR_DELIVERY_CLI_ONLY: &[ProxyDelivery] = &[ProxyDelivery::EnvFile {
    commands: CURSOR_COMMANDS,
    defaults: &[],
}];

const CURSOR_DELIVERY_WITH_IDE: &[ProxyDelivery] = &[
    ProxyDelivery::EnvFile {
        commands: CURSOR_COMMANDS,
        defaults: &[],
    },
    ProxyDelivery::SettingsKey {
        file: crate::hooks::cursor::ide_user_settings,
        key: "http.proxy",
    },
];

/// Cursor's configuration root, and the one file its hooks are registered in.
pub struct CursorBinding {
    /// `$OPENLATCH_CURSOR_DIR`, else `~/.cursor` — resolved by `hooks::cursor`.
    pub root: PathBuf,
    /// `<root>/hooks.json`.
    pub hooks_path: PathBuf,
}

impl CursorBinding {
    /// Delegates to `hooks::cursor`, which owns resolution and detection for
    /// every caller.
    pub fn detect() -> Option<Self> {
        let root = crate::hooks::cursor::detect()?;
        Some(Self {
            hooks_path: crate::hooks::cursor::hooks_json_path(&root),
            root,
        })
    }
}

/// Cursor's camelCase event name → the OpenLatch wire event.
///
/// Its own table, never `pascal_to_snake`: that one answers `"unknown"` for a
/// camelCase name, and the install would write `--event unknown` without a
/// word. `"unknown"` here is a bug too, which is why a test walks every entry
/// of [`EVENT_TYPES`] and [`DECIDING`] against the known wire values.
fn cursor_wire_event(event: &str) -> &'static str {
    match event {
        "preToolUse" | "beforeShellExecution" | "beforeMCPExecution" => "pre_tool_use",
        "beforeSubmitPrompt" => "user_prompt_submit",
        "sessionStart" => "session_start",
        "sessionEnd" => "session_end",
        "postToolUse" => "post_tool_use",
        "postToolUseFailure" => "post_tool_use_failure",
        "subagentStop" => "subagent_stop",
        "preCompact" => "pre_compact",
        "stop" => "stop",
        _ => "unknown",
    }
}

impl AgentBinding for CursorBinding {
    fn agent_type(&self) -> &'static str {
        "cursor"
    }

    fn aliases(&self) -> &'static AliasTable {
        &ALIASES
    }

    fn display_name(&self) -> &'static str {
        "Cursor"
    }

    fn config_dir(&self) -> PathBuf {
        self.root.clone()
    }

    fn hook_config_path(&self) -> PathBuf {
        self.hooks_path.clone()
    }

    fn hook_event_types(&self) -> &'static [&'static str] {
        EVENT_TYPES
    }

    fn load_bearing_events(&self) -> &'static [&'static str] {
        // The events a refusal rides on. `beforeMCPExecution` is left out on
        // purpose: an MCP call takes the ordinary verdict path, and no rule
        // kind can deny one yet.
        &["preToolUse", "beforeShellExecution", "beforeSubmitPrompt"]
    }

    fn daemon_channel(&self) -> DaemonChannel {
        // Cursor's entry has no environment block to pin a token in, and an
        // undocumented key there is exactly what this binding refuses to write.
        // The hook is told where to look on its own command line, as Codex's is.
        DaemonChannel::OpenlatchDirArg
    }

    fn liveness(&self) -> LivenessReport {
        // Cursor has no trust gate: installed is armed. Proving it is live is
        // evidence-based and lands with the doctor attestation.
        LivenessReport {
            armed: None,
            detail: None,
            remedy: None,
            code: None,
            off: false,
            pending: false,
        }
    }

    fn build_hook_entry(
        &self,
        event: &str,
        binary: &Path,
        _port: u16,
        _marker: &OpenlatchMarker,
    ) -> Value {
        let wire = cursor_wire_event(event);
        let openlatch_dir = crate::config::openlatch_dir();
        // Both paths quoted, on every OS: Windows paths carry spaces, and the
        // documented Windows wrapper is `& "<command path>" <args>`.
        let command = format!(
            r#""{}" --agent cursor --event {wire} --openlatch-dir "{}""#,
            binary.display(),
            openlatch_dir.display()
        );
        // Seconds, and always explicit: Cursor's default is unpublished.
        let timeout = if DECIDING.contains(&event) { 900 } else { 10 };
        // The documented keys and nothing else — no marker, no matcher.
        json!({ "type": "command", "command": command, "timeout": timeout })
    }

    fn config_is_machine_global(&self) -> bool {
        crate::hooks::cursor::config_is_machine_global()
    }

    fn capabilities(&self) -> BindingCapabilities {
        BindingCapabilities {
            // `ask` is native on `beforeShellExecution` and
            // `beforeMCPExecution` only. On `preToolUse` and
            // `beforeSubmitPrompt` it degrades to an allow — never to a deny —
            // and the daemon stamps `olaskdegraded` on the record.
            expressible: &["allow", "ask", "deny"],
            can_mutate_arguments: false,
            native_failure_mode: FailureMode::FailOpen,
            admin_owned_settings: false,
            declares_session_in_request: true,
            notice: false,
            observes_execution: true,
            enforces: Enforces::All,
        }
    }

    fn model_relay_wiring(&self) -> Option<ModelRelayWiring> {
        // Intercepted (I-2 D-05), on HTTP/2 for every host: Cursor's agent stream is a Connect
        // bidi call, which stalls on a relay that speaks only HTTP/1.1. The format is not
        // captured in this build, so a turn is forwarded and recorded by nothing yet; it never
        // enters attribution either — a ProxyEnv agent records no format.
        Some(ModelRelayWiring {
            wire_format: WireFormat::CursorConnectRpc,
            endpoint: EndpointConvention::ProxyEnv {
                intercept_hosts: CURSOR_INTERCEPT_HOSTS,
                delivery: if CURSOR_IDE_DELIVERY {
                    CURSOR_DELIVERY_WITH_IDE
                } else {
                    CURSOR_DELIVERY_CLI_ONLY
                },
                h2_hosts: CURSOR_INTERCEPT_HOSTS,
            },
            install_id_header: "x-openlatch-install-id",
        })
    }

    fn marker_placement(&self) -> MarkerPlacement {
        MarkerPlacement::Sidecar
    }

    fn file_root_defaults(&self) -> &'static [(&'static str, i64)] {
        // Cursor requires it, and a created file must carry it.
        &[("version", 1)]
    }

    fn byte_identical_restore(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::envelope::known_types::KNOWN_HOOK_EVENT_TYPES;

    fn binding() -> CursorBinding {
        CursorBinding {
            root: PathBuf::from("/home/test/.cursor"),
            hooks_path: PathBuf::from("/home/test/.cursor/hooks.json"),
        }
    }

    #[test]
    fn every_event_maps_to_a_known_wire_value() {
        for event in EVENT_TYPES.iter().chain(DECIDING) {
            let wire = cursor_wire_event(event);
            assert_ne!(wire, "unknown", "{event} has no wire value");
            assert!(
                KNOWN_HOOK_EVENT_TYPES.contains(&wire),
                "{event} maps to {wire}, which is not a known hook event type"
            );
        }
    }

    /// Every deciding event is installed, and each has a translator row that
    /// never answers `{}` — the two land together or not at all.
    #[test]
    fn every_deciding_event_is_installed_with_its_translator() {
        use crate::hook_output::{translate, Verdict};
        for event in DECIDING {
            assert!(EVENT_TYPES.contains(event), "{event} is not installed");
            assert_ne!(
                translate("cursor", event, &Verdict::allow()),
                crate::hook_output::empty(),
                "{event} would answer {{}}, which Cursor reads as a refusal"
            );
        }
        assert!(binding()
            .load_bearing_events()
            .iter()
            .all(|e| DECIDING.contains(e)));
    }

    #[test]
    fn entry_is_flat_with_only_documented_keys() {
        let marker = OpenlatchMarker::new("id".into());
        for event in EVENT_TYPES.iter().chain(DECIDING) {
            let entry =
                binding().build_hook_entry(event, Path::new("/bin/openlatch-hook"), 7443, &marker);
            let keys: Vec<&String> = entry.as_object().expect("an object").keys().collect();
            assert!(
                keys.iter()
                    .all(|k| ["type", "command", "timeout"].contains(&k.as_str())),
                "{event}: undocumented key in {entry}"
            );
            assert_eq!(entry["type"], "command");
            let expected = if DECIDING.contains(event) { 900 } else { 10 };
            assert_eq!(entry["timeout"], expected, "{event}");
        }
    }

    #[test]
    fn command_quotes_both_paths() {
        // The command and the assertion both read `OPENLATCH_DIR`; a sibling
        // redirecting it between the two would fail this for the wrong reason.
        let _dir_lock = crate::config::OPENLATCH_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let marker = OpenlatchMarker::new("id".into());
        let bin = Path::new("/Applications/Open Latch/openlatch-hook");
        let entry = binding().build_hook_entry("stop", bin, 7443, &marker);
        let command = entry["command"].as_str().expect("a command");
        let dir = crate::config::openlatch_dir();
        assert_eq!(
            command,
            format!(
                r#""{}" --agent cursor --event stop --openlatch-dir "{}""#,
                bin.display(),
                dir.display()
            )
        );
        assert!(crate::hooks::entry_shape::is_sidecar_owned(
            command, "cursor"
        ));
    }

    fn proxy_env(
        b: &CursorBinding,
    ) -> (
        &'static [&'static str],
        &'static [ProxyDelivery],
        &'static [&'static str],
    ) {
        match b
            .model_relay_wiring()
            .expect("Cursor declares its lane")
            .endpoint
        {
            EndpointConvention::ProxyEnv {
                intercept_hosts,
                delivery,
                h2_hosts,
            } => (intercept_hosts, delivery, h2_hosts),
            other => panic!("expected ProxyEnv, got {other:?}"),
        }
    }

    /// Attribution stays unambiguous: a host both agents declare is attributed to nobody.
    #[test]
    fn cursor_hosts_do_not_overlap_cline() {
        let cline = crate::hooks::cline_providers::CLINE_INTERCEPT_HOSTS;
        assert!(!CURSOR_INTERCEPT_HOSTS.is_empty());
        for host in CURSOR_INTERCEPT_HOSTS {
            assert!(
                !cline.iter().any(|c| c.eq_ignore_ascii_case(host)),
                "{host} is declared by Cursor and Cline"
            );
        }
    }

    /// D-06: the preflight probes the first host, and every host speaks HTTP/2.
    #[test]
    fn cursor_first_host_is_the_probe_target() {
        let b = binding();
        let (hosts, _, h2) = proxy_env(&b);
        assert_eq!(hosts.first(), Some(&"api2.cursor.sh"));
        assert_eq!(h2, hosts, "every Cursor host is flagged h2");
        let w = b.model_relay_wiring().expect("wired");
        assert_eq!(w.wire_format, WireFormat::CursorConnectRpc);
        assert!(
            w.wire_format.is_captured() && w.wire_format.has_decoder(),
            "Cursor traffic is recorded from its mirror decoder (plan 03)"
        );
        for never in [
            "api3.cursor.sh",
            "repo42.cursor.sh",
            "metrics.cursor.sh",
            "api.origin.cursor.com",
        ] {
            assert!(!hosts.contains(&never), "{never} must tunnel untouched");
        }
    }

    /// D-08: without the IDE proof the IDE gets no delivery; the CLI always does, with `agent`
    /// guarded to Cursor's own install.
    #[test]
    fn cursor_ide_delivery_absent_when_flag_false() {
        let (_, delivery, _) = proxy_env(&binding());
        let has_ide = delivery.iter().any(|d| {
            matches!(
                d,
                ProxyDelivery::SettingsKey {
                    key: "http.proxy",
                    ..
                }
            )
        });
        assert_eq!(has_ide, CURSOR_IDE_DELIVERY);
        assert_eq!(
            delivery.len(),
            if CURSOR_IDE_DELIVERY { 2 } else { 1 },
            "the CLI wrapper, plus the IDE key only once its proof has passed"
        );
        match delivery[0] {
            ProxyDelivery::EnvFile { commands, defaults } => {
                assert_eq!(commands, CURSOR_COMMANDS);
                assert!(defaults.is_empty());
            }
            ref other => panic!("expected the CLI wrapper, got {other:?}"),
        }
        assert_eq!(
            CURSOR_COMMANDS
                .iter()
                .map(|c| (c.name, c.resolve_guard))
                .collect::<Vec<_>>(),
            vec![("cursor-agent", None), ("agent", Some("cursor-agent"))]
        );
        assert!(matches!(
            CURSOR_DELIVERY_WITH_IDE[1],
            ProxyDelivery::SettingsKey {
                key: "http.proxy",
                ..
            }
        ));
    }

    #[test]
    fn cursor_declares_the_sidecar_and_byte_identical_restore() {
        let b = binding();
        assert_eq!(b.marker_placement(), MarkerPlacement::Sidecar);
        assert_eq!(b.file_root_defaults(), &[("version", 1)]);
        assert!(b.byte_identical_restore());
        assert!(matches!(b.daemon_channel(), DaemonChannel::OpenlatchDirArg));
    }

    /// D-9, pinned: Cursor asks natively, has no non-blocking notice, observes
    /// execution and enforces everywhere.
    #[test]
    fn capabilities_are_the_pinned_values() {
        let c = binding().capabilities();
        assert!(c.ask(), "ask is derived from `expressible`, which holds it");
        assert!(!c.notice);
        assert!(c.observes_execution);
        assert_eq!(c.enforces, Enforces::All);
    }

    /// D-7 / AC-2, AC-3, AC-5, AC-6: the pinned Cursor rows.
    #[test]
    fn aliases_resolve_the_pinned_rows() {
        let shell = ALIASES.resolve(
            "Shell",
            Some(json!({"command": "ls", "cwd": "/w", "timeout": 5})),
            None,
        );
        assert_eq!((shell.name.as_str(), shell.mapped), ("Bash", true));
        assert_eq!(shell.input, Some(json!({"command": "ls", "cwd": "/w"})));
        assert_eq!(shell.native, "Shell");
        let event = ALIASES
            .resolve_event(
                "beforeShellExecution",
                &json!({"command": "ls", "cwd": "", "sandbox": false}),
            )
            .expect("an event that is the command");
        assert_eq!(event.name, "Bash");
        for tool in ["Read", "Write", "Grep", "Task"] {
            assert!(ALIASES.resolve(tool, None, None).mapped, "{tool}");
        }
        let delete = ALIASES.resolve("Delete", Some(json!({"path": "a"})), None);
        assert!(!delete.mapped, "Delete is unmapped on purpose");
        let wrapped = ALIASES.resolve(
            "create_issue",
            Some(json!("{\"title\":\"x\"}")),
            Some("github"),
        );
        assert_eq!(wrapped.name, "mcp__github__create_issue");
        assert_eq!(wrapped.input, Some(json!({"title": "x"})));
        let bare = ALIASES.resolve("MCP:create_issue", None, None);
        assert_eq!(bare.name, "mcp__unknown__create_issue");
        assert_eq!(ALIASES.binding_id(true), "cursor_hook");
    }
}