openlatch-client 0.6.6

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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Alias tables — how one binding's native tool vocabulary becomes OpenLatch's
//! canonical one (D-I16-22).
//!
//! The evaluator reads **canonical** names only (`Bash`, `Read`, `Write`,
//! `Edit`, `Grep`, `Glob`, `WebFetch`, `mcp__<server>__<tool>`, …). They belong
//! to no agent. Everything an agent adds to that — its own tool ids, its own
//! argument keys, how it spells an MCP call — is **data in its binding**: a
//! static [`AliasTable`] under `src/hooks/bindings/`. This module holds the
//! table's shape and the one function that applies it, so a new agent is a new
//! table and no shared code changes.
//!
//! Applying a table does three things, once, before evaluation:
//!
//! 1. the native tool name becomes the canonical one (or an `mcp__` name);
//! 2. the native argument keys become the canonical ones the evaluator reads
//!    (`file_path`, `url`, `command`), and a native input carrying several
//!    targets keeps **all** of them (a path or URL key may hold an array);
//! 3. a tool the table does not map is reported as **unmapped**, so the caller
//!    can key it `<olbinding>:<native name>` and the evaluator treats it as
//!    unknown (D-8).
//!
//! A leaf module: it imports `serde_json` and nothing else of this crate.

use serde_json::{Map, Value};

/// One binding's native-to-canonical mapping.
#[derive(Debug)]
pub struct AliasTable {
    /// The agent's wire name (`source`), which is how a payload finds its table.
    pub agent: &'static str,
    /// The `olbinding` id this agent's hook lane decides through.
    pub binding: &'static str,
    /// The id of the lane that is not a hook, when the agent has one — the
    /// binding is part of the tool key because two lanes of one agent are
    /// distinct bindings.
    pub renders_binding: Option<&'static str>,
    /// Native tool name → canonical name. A native name that is already the
    /// canonical one is listed too (identity row): **a tool absent from this
    /// list is unmapped on purpose** and is learned as unknown.
    pub tools: &'static [(&'static str, &'static str)],
    /// Events that ARE a tool call and carry no tool name.
    pub event_tools: &'static [EventTool],
    /// Native tool → the only argument keys it keeps (the rest is evidence the
    /// agent already holds, never a target).
    pub keep: &'static [(&'static str, &'static [&'static str])],
    /// Argument-key renames: `(tool or "*", native key, canonical key)`.
    pub inputs: &'static [(&'static str, &'static str, &'static str)],
    /// A native tool that is its canonical alternative when the keys named are
    /// absent (an editor that writes a file instead of editing it).
    pub creates: &'static [Creates],
    /// How an MCP invocation becomes `mcp__<server>__<tool>`.
    pub mcp_rule: McpKeyRule,
    /// How an input carrying several targets is kept.
    pub multi: MultiValueRule,
}

/// A hook event that is itself a tool call.
#[derive(Debug)]
pub struct EventTool {
    /// The native event name (`hook_event_name`).
    pub event: &'static str,
    /// The canonical tool it is.
    pub canonical: &'static str,
    /// The payload's own keys that form the tool input. The **first** must be
    /// a string — it is the action itself — or the event is not a tool call.
    pub keys: &'static [&'static str],
}

/// A tool that is a different canonical tool when some keys are absent.
#[derive(Debug)]
pub struct Creates {
    /// The native tool.
    pub tool: &'static str,
    /// The canonical tool it is in that case.
    pub canonical: &'static str,
    /// Keys that must all be absent (or null) for it to apply.
    pub when_absent: &'static [&'static str],
    /// Renames applied in that case, in place of the ordinary ones for them.
    pub renames: &'static [(&'static str, &'static str)],
}

/// How a binding spells an MCP call.
///
/// A name that already starts `mcp__` is canonical for every binding and needs
/// no rule. Each part below is optional: a binding declares the ones its agent
/// uses.
#[derive(Debug)]
pub struct McpKeyRule {
    /// The payload field that names the server beside the tool.
    pub server_field: Option<&'static str>,
    /// A prefix on the tool name when no server is named; the call is then
    /// `mcp__unknown__<tool>`.
    pub bare_prefix: Option<&'static str>,
    /// A native tool that wraps the call, naming server, tool and arguments in
    /// its own input.
    pub wrapper: Option<McpWrapper>,
    /// The agent joins server and tool as `<server>__<tool>`.
    pub joined: bool,
    /// The arguments arrive as a JSON string.
    pub json_string_input: bool,
}

impl McpKeyRule {
    /// No MCP spelling beyond the canonical one.
    pub const NATIVE: McpKeyRule = McpKeyRule {
        server_field: None,
        bare_prefix: None,
        wrapper: None,
        joined: false,
        json_string_input: false,
    };
}

/// An MCP call wrapped in a native tool's own input.
#[derive(Debug)]
pub struct McpWrapper {
    pub tool: &'static str,
    pub server_key: &'static str,
    pub tool_key: &'static str,
    pub arguments_key: &'static str,
}

/// The rules that keep a multi-target input whole.
#[derive(Debug)]
pub struct MultiValueRule {
    pub rules: &'static [MultiRule],
}

impl MultiValueRule {
    /// No input of this binding carries several targets.
    pub const NONE: MultiValueRule = MultiValueRule { rules: &[] };
}

/// One multi-target input.
#[derive(Debug)]
pub struct MultiRule {
    /// Native tools it applies to; empty means every tool.
    pub tools: &'static [&'static str],
    /// The native keys that may hold the values, first present one wins.
    pub from: &'static [&'static str],
    /// When an entry is an object, the key holding its value.
    pub element_key: Option<&'static str>,
    /// The canonical key the values land under.
    pub to: &'static str,
    /// How the values are combined.
    pub join: Join,
}

/// How several values become one canonical input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Join {
    /// Every value kept: a string for one, an array for several. A path or
    /// URL key may hold an array and every element is classified.
    Array,
    /// Separate command lines, joined with newlines so each runs as its own
    /// command. The source key is removed.
    Lines,
    /// One argv array, each element POSIX-quoted and joined with spaces.
    Argv,
    /// The first value only.
    First,
}

/// A native tool call resolved against a table.
#[derive(Debug, Clone, PartialEq)]
pub struct Resolved {
    /// The canonical name, or the native one when nothing maps it.
    pub name: String,
    /// The input in the canonical shape.
    pub input: Option<Value>,
    /// The name the agent used.
    pub native: String,
    /// `false` when the table has no row for it: the tool is unknown.
    pub mapped: bool,
}

impl Resolved {
    /// The tool key the evaluator, the decision event and the platform all
    /// use: the canonical name, or `<binding>:<native name>` for a tool the
    /// table does not map (D-8) — one string, never derived anywhere else.
    pub fn key(&self, binding: &str) -> String {
        if self.mapped {
            self.name.clone()
        } else {
            format!("{binding}:{}", self.native)
        }
    }
}

impl AliasTable {
    /// A table that maps nothing: every tool of the agent is unmapped.
    pub const fn empty(agent: &'static str, binding: &'static str) -> AliasTable {
        AliasTable {
            agent,
            binding,
            renders_binding: None,
            tools: &[],
            event_tools: &[],
            keep: &[],
            inputs: &[],
            creates: &[],
            mcp_rule: McpKeyRule::NATIVE,
            multi: MultiValueRule::NONE,
        }
    }

    /// The `olbinding` id of a lane of this agent.
    pub fn binding_id(&self, renders: bool) -> &'static str {
        match (renders, self.renders_binding) {
            (true, Some(plugin)) => plugin,
            _ => self.binding,
        }
    }

    /// Resolve a tool named by the payload.
    ///
    /// `server` is the value of [`McpKeyRule::server_field`] in the payload,
    /// when it carries one.
    pub fn resolve(&self, native: &str, input: Option<Value>, server: Option<&str>) -> Resolved {
        let mapped = |name: String, input: Option<Value>| Resolved {
            name,
            input,
            native: native.to_string(),
            mapped: true,
        };
        if native.starts_with("mcp__") {
            return mapped(native.to_string(), input);
        }
        let rule = &self.mcp_rule;
        if let Some(server) = server {
            let tool = rule
                .bare_prefix
                .and_then(|prefix| native.strip_prefix(prefix))
                .unwrap_or(native);
            let input = match input {
                Some(Value::String(raw)) if rule.json_string_input => {
                    // A string that does not parse is kept: it is what the model sent.
                    Some(serde_json::from_str(&raw).unwrap_or(Value::String(raw)))
                }
                other => other,
            };
            return mapped(format!("mcp__{server}__{tool}"), input);
        }
        if let Some(tool) = rule.bare_prefix.and_then(|p| native.strip_prefix(p)) {
            return mapped(format!("mcp__unknown__{tool}"), input);
        }
        if let Some(wrapper) = rule.wrapper.as_ref().filter(|w| w.tool == native) {
            if let Some(resolved) = unwrap_mcp(wrapper, native, &input) {
                return resolved;
            }
        }
        if let Some((_, canonical)) = self.tools.iter().find(|(name, _)| *name == native) {
            return self.map_tool(native, canonical, input);
        }
        if rule.joined && native.contains("__") {
            return mapped(format!("mcp__{native}"), input);
        }
        Resolved {
            name: native.to_string(),
            input,
            native: native.to_string(),
            mapped: false,
        }
    }

    /// Resolve an event that is itself a tool call, from the payload's own keys.
    pub fn resolve_event(&self, event: &str, payload: &Value) -> Option<Resolved> {
        let row = self.event_tools.iter().find(|row| row.event == event)?;
        payload.get(row.keys.first()?)?.as_str()?;
        let input: Map<String, Value> = row
            .keys
            .iter()
            .filter_map(|key| Some((key.to_string(), payload.get(key)?.clone())))
            .collect();
        Some(Resolved {
            name: row.canonical.to_string(),
            input: Some(Value::Object(input)),
            native: event.to_string(),
            mapped: true,
        })
    }

    fn map_tool(&self, native: &str, canonical: &str, input: Option<Value>) -> Resolved {
        let mut canonical = canonical;
        let Some(Value::Object(mut args)) = input else {
            return Resolved {
                name: canonical.to_string(),
                input,
                native: native.to_string(),
                mapped: true,
            };
        };
        if let Some((_, keys)) = self.keep.iter().find(|(tool, _)| *tool == native) {
            args.retain(|key, _| keys.contains(&key.as_str()));
        }
        let mut renames: Vec<(&str, &str)> = Vec::new();
        let creating = self.creates.iter().find(|row| {
            row.tool == native
                && row
                    .when_absent
                    .iter()
                    .all(|key| args.get(*key).is_none_or(Value::is_null))
        });
        if let Some(row) = creating {
            canonical = row.canonical;
            for key in row.when_absent {
                args.remove(*key);
            }
            renames.extend(row.renames);
        }
        renames.extend(
            self.inputs
                .iter()
                .filter(|(tool, _, _)| *tool == "*" || *tool == native)
                .map(|(_, from, to)| (*from, *to)),
        );
        for (from, to) in renames {
            if let Some(value) = args.remove(from) {
                args.entry(to.to_string()).or_insert(value);
            }
        }
        for rule in self
            .multi
            .rules
            .iter()
            .filter(|rule| rule.tools.is_empty() || rule.tools.contains(&native))
        {
            apply_multi(rule, &mut args);
        }
        Resolved {
            name: canonical.to_string(),
            input: Some(Value::Object(args)),
            native: native.to_string(),
            mapped: true,
        }
    }
}

/// `server`, `tool` and `arguments` out of a wrapper tool's own input.
fn unwrap_mcp(wrapper: &McpWrapper, native: &str, input: &Option<Value>) -> Option<Resolved> {
    let args = input.as_ref()?.as_object()?;
    let server = args.get(wrapper.server_key)?.as_str()?;
    let tool = args.get(wrapper.tool_key)?.as_str()?;
    let arguments = match args.get(wrapper.arguments_key) {
        Some(Value::String(raw)) => serde_json::from_str(raw)
            .ok()
            .filter(Value::is_object)
            .unwrap_or_else(|| Value::String(raw.clone())),
        Some(other) => other.clone(),
        None => Value::Object(Map::new()),
    };
    Some(Resolved {
        name: format!("mcp__{server}__{tool}"),
        input: Some(arguments),
        native: native.to_string(),
        mapped: true,
    })
}

/// The string values a multi-target key holds, in order.
fn values_of(value: &Value, element_key: Option<&str>, out: &mut Vec<Value>) {
    let entry = |item: &Value, out: &mut Vec<Value>| {
        let text = item
            .as_str()
            .or_else(|| element_key.and_then(|key| item.get(key)?.as_str()));
        if let Some(text) = text {
            out.push(Value::String(text.to_string()));
        }
    };
    match value {
        Value::Array(items) => items.iter().for_each(|item| entry(item, out)),
        other => entry(other, out),
    }
}

fn apply_multi(rule: &MultiRule, args: &mut Map<String, Value>) {
    let Some((source, values)) = rule.from.iter().find_map(|key| {
        let mut values = Vec::new();
        values_of(args.get(*key)?, rule.element_key, &mut values);
        (!values.is_empty()).then_some((*key, values))
    }) else {
        return;
    };
    match rule.join {
        Join::Array => {
            let kept = if values.len() == 1 {
                values.into_iter().next().unwrap_or(Value::Null)
            } else {
                Value::Array(values)
            };
            args.entry(rule.to.to_string()).or_insert(kept);
        }
        Join::First => {
            if let Some(first) = values.into_iter().next() {
                args.entry(rule.to.to_string()).or_insert(first);
            }
        }
        Join::Lines => {
            let joined = values
                .iter()
                .filter_map(Value::as_str)
                .collect::<Vec<_>>()
                .join("\n");
            args.remove(source);
            args.entry(rule.to.to_string())
                .or_insert(Value::String(joined));
        }
        Join::Argv => {
            // Only an array is an argv; a string command is already a line.
            if !args.get(source).is_some_and(Value::is_array) {
                return;
            }
            let joined = values
                .iter()
                .filter_map(Value::as_str)
                .map(posix_quote)
                .collect::<Vec<_>>()
                .join(" ");
            args.insert(rule.to.to_string(), Value::String(joined));
        }
    }
}

/// One argv element as a POSIX shell word.
fn posix_quote(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', "'\\''"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    static TABLE: AliasTable = AliasTable {
        agent: "fixture",
        binding: "fixture_hook",
        renders_binding: Some("fixture_plugin"),
        tools: &[
            ("Sh", "Bash"),
            ("Open", "Read"),
            ("Ed", "Edit"),
            ("Cmds", "Bash"),
        ],
        event_tools: &[EventTool {
            event: "beforeShell",
            canonical: "Bash",
            keys: &["command", "cwd"],
        }],
        keep: &[("Sh", &["command"])],
        inputs: &[("Open", "path", "file_path"), ("*", "q", "query")],
        creates: &[Creates {
            tool: "Ed",
            canonical: "Write",
            when_absent: &["old"],
            renames: &[("new", "content")],
        }],
        mcp_rule: McpKeyRule {
            server_field: Some("server"),
            bare_prefix: Some("MCP:"),
            wrapper: Some(McpWrapper {
                tool: "call_mcp",
                server_key: "s",
                tool_key: "t",
                arguments_key: "a",
            }),
            joined: true,
            json_string_input: true,
        },
        multi: MultiValueRule {
            rules: &[
                MultiRule {
                    tools: &["Open"],
                    from: &["files"],
                    element_key: Some("path"),
                    to: "file_path",
                    join: Join::Array,
                },
                MultiRule {
                    tools: &["Cmds"],
                    from: &["commands"],
                    element_key: Some("command"),
                    to: "command",
                    join: Join::Lines,
                },
                MultiRule {
                    tools: &["Sh"],
                    from: &["command"],
                    element_key: None,
                    to: "command",
                    join: Join::Argv,
                },
            ],
        },
    };

    #[test]
    fn a_listed_tool_is_mapped_and_an_unlisted_one_is_not() {
        let sh = TABLE.resolve("Sh", Some(json!({"command": "ls", "x": 1})), None);
        assert_eq!(sh.name, "Bash");
        assert!(sh.mapped);
        assert_eq!(sh.input, Some(json!({"command": "ls"})), "keep drops x");
        let other = TABLE.resolve("Mystery", Some(json!({"a": 1})), None);
        assert_eq!((other.name.as_str(), other.mapped), ("Mystery", false));
        assert_eq!(other.native, "Mystery");
        assert_eq!(other.input, Some(json!({"a": 1})));
    }

    #[test]
    fn inputs_are_renamed_per_tool_and_globally() {
        let open = TABLE.resolve("Open", Some(json!({"path": "a", "q": "x"})), None);
        assert_eq!(open.input, Some(json!({"file_path": "a", "query": "x"})));
    }

    #[test]
    fn several_targets_are_all_kept() {
        let open = TABLE.resolve(
            "Open",
            Some(json!({"files": [{"path": "a"}, {"path": "b"}]})),
            None,
        );
        assert_eq!(open.input.unwrap()["file_path"], json!(["a", "b"]));
        let one = TABLE.resolve("Open", Some(json!({"files": [{"path": "a"}]})), None);
        assert_eq!(one.input.unwrap()["file_path"], json!("a"));
        let lines = TABLE.resolve(
            "Cmds",
            Some(json!({"commands": ["ls", {"command": "pwd"}]})),
            None,
        );
        assert_eq!(lines.input, Some(json!({"command": "ls\npwd"})));
    }

    #[test]
    fn an_argv_array_is_posix_quoted_and_joined() {
        let sh = TABLE.resolve(
            "Sh",
            Some(json!({"command": ["rm", "-rf", "my dir", "it's"]})),
            None,
        );
        assert_eq!(
            sh.input,
            Some(json!({"command": "rm -rf 'my dir' 'it'\\''s'"}))
        );
        let line = TABLE.resolve("Sh", Some(json!({"command": "rm -rf x"})), None);
        assert_eq!(line.input, Some(json!({"command": "rm -rf x"})));
    }

    #[test]
    fn a_tool_is_its_alternative_when_the_keys_are_absent() {
        let write = TABLE.resolve("Ed", Some(json!({"new": "body"})), None);
        assert_eq!(write.name, "Write");
        assert_eq!(write.input, Some(json!({"content": "body"})));
        let edit = TABLE.resolve("Ed", Some(json!({"old": "a", "new": "b"})), None);
        assert_eq!(edit.name, "Edit");
        assert_eq!(edit.input, Some(json!({"old": "a", "new": "b"})));
    }

    #[test]
    fn mcp_calls_become_the_canonical_name() {
        let canonical = TABLE.resolve("mcp__s__t", None, None);
        assert_eq!(
            (canonical.name.as_str(), canonical.mapped),
            ("mcp__s__t", true)
        );
        let beside = TABLE.resolve("create", Some(json!("{\"a\":1}")), Some("gh"));
        assert_eq!(beside.name, "mcp__gh__create");
        assert_eq!(beside.input, Some(json!({"a": 1})));
        let bare = TABLE.resolve("MCP:create", Some(json!({"a": 1})), None);
        assert_eq!(bare.name, "mcp__unknown__create");
        let wrapped = TABLE.resolve(
            "call_mcp",
            Some(json!({"s": "gh", "t": "create", "a": "{\"x\":1}"})),
            None,
        );
        assert_eq!(wrapped.name, "mcp__gh__create");
        assert_eq!(wrapped.input, Some(json!({"x": 1})));
        assert_eq!(wrapped.native, "call_mcp");
        let joined = TABLE.resolve("gh__create", Some(json!({"a": 1})), None);
        assert_eq!(joined.name, "mcp__gh__create");
        assert!(joined.mapped);
        let broken = TABLE.resolve("call_mcp", Some(json!({"s": "gh"})), None);
        assert!(!broken.mapped, "a wrapper naming no tool is not a call");
    }

    #[test]
    fn an_event_that_is_a_tool_call_needs_its_action() {
        let payload = json!({"command": "ls", "cwd": "/w", "other": 1});
        let call = TABLE
            .resolve_event("beforeShell", &payload)
            .expect("a call");
        assert_eq!(call.name, "Bash");
        assert_eq!(call.input, Some(json!({"command": "ls", "cwd": "/w"})));
        assert_eq!(call.native, "beforeShell");
        assert!(TABLE
            .resolve_event("beforeShell", &json!({"cwd": "/w"}))
            .is_none());
        assert!(TABLE.resolve_event("sessionStart", &payload).is_none());
    }

    #[test]
    fn a_lane_that_is_not_a_hook_has_its_own_binding() {
        assert_eq!(TABLE.binding_id(false), "fixture_hook");
        assert_eq!(TABLE.binding_id(true), "fixture_plugin");
    }
}