openlatch-client 0.0.0

The open-source security layer for AI agents — client forwarder
Documentation
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
//! Envelope module — core data types for event wrapping, agent identification, and verdict responses.
//!
//! This is a leaf module with zero internal dependencies. Every event flowing through the daemon
//! gets wrapped in an [`EventEnvelope`]. The types here are consumed by daemon handlers, the
//! privacy filter, and the logging module.

use serde::{Deserialize, Serialize};

/// Closed enumeration of supported agent platforms.
///
/// This enum is non-negotiable per the envelope format spec. Unknown agent types must be rejected
/// at deserialization. Adding a new agent requires updating this enum and bumping the minor version.
///
/// Serializes to kebab-case (e.g. `ClaudeCode` → `"claude-code"`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum AgentType {
    ClaudeCode,
    Cursor,
    Windsurf,
    GithubCopilot,
    CodexCli,
    GeminiCli,
    Cline,
    // SECURITY: Closed enum — unknown agent types are rejected at deserialization (OL-1001).
    // Manual rename needed: kebab-case would produce "open-claw" but the spec requires "openclaw".
    #[serde(rename = "openclaw")]
    OpenClaw,
}

/// Hook event type — identifies which agent lifecycle event triggered this envelope.
///
/// Serializes to snake_case (e.g. `PreToolUse` → `"pre_tool_use"`).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum HookEventType {
    PreToolUse,
    UserPromptSubmit,
    Stop,
}

/// Verdict returned to the agent hook.
///
/// In M1, only `Allow` and `Approve` are used. `Deny` is defined for schema completeness
/// but is never returned by M1 handlers.
///
/// Serializes to lowercase (e.g. `Allow` → `"allow"`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Verdict {
    Allow,
    Approve,
    /// Defined for schema completeness — not used in M1.
    Deny,
}

/// Complete event envelope wrapping a raw agent hook event with cross-cutting metadata.
///
/// All fields correspond to EVNT-02 requirements. Optional fields are omitted from JSON
/// when `None` to keep payloads compact.
///
/// # Examples
///
/// ```rust
/// use openlatch_client::envelope::{EventEnvelope, AgentType, HookEventType, Verdict,
///     new_event_id, current_timestamp, os_string, arch_string};
///
/// let envelope = EventEnvelope {
///     schema_version: "1.0".to_string(),
///     id: new_event_id(),
///     timestamp: current_timestamp(),
///     event_type: HookEventType::PreToolUse,
///     session_id: "session-abc".to_string(),
///     tool_name: Some("bash".to_string()),
///     tool_input: None,
///     user_prompt: None,
///     reason: None,
///     verdict: Verdict::Allow,
///     latency_ms: 3,
///     agent_platform: AgentType::ClaudeCode,
///     agent_version: None,
///     os: os_string().to_string(),
///     arch: arch_string().to_string(),
///     client_version: env!("CARGO_PKG_VERSION").to_string(),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct EventEnvelope {
    pub schema_version: String,
    pub id: String,
    pub timestamp: String,
    pub event_type: HookEventType,
    pub session_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_input: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_prompt: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub verdict: Verdict,
    pub latency_ms: u64,
    pub agent_platform: AgentType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_version: Option<String>,
    pub os: String,
    pub arch: String,
    pub client_version: String,
}

/// Verdict response returned to the agent hook after processing.
///
/// Mirrors the cloud response schema. Optional fields are omitted when `None`.
/// Use the [`VerdictResponse::allow`] and [`VerdictResponse::approve`] constructors for M1.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct VerdictResponse {
    pub schema_version: String,
    pub verdict: Verdict,
    pub event_id: String,
    pub latency_ms: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threat_category: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details_url: Option<String>,
}

impl VerdictResponse {
    /// Constructs an `allow` verdict response for PreToolUse and UserPromptSubmit events.
    pub fn allow(event_id: String, latency_ms: f64) -> Self {
        Self {
            schema_version: "1.0".to_string(),
            verdict: Verdict::Allow,
            event_id,
            latency_ms,
            reason: None,
            severity: None,
            threat_category: None,
            rule_id: None,
            details_url: None,
        }
    }

    /// Constructs an `approve` verdict response for Stop events.
    pub fn approve(event_id: String, latency_ms: f64) -> Self {
        Self {
            schema_version: "1.0".to_string(),
            verdict: Verdict::Approve,
            event_id,
            latency_ms,
            reason: None,
            severity: None,
            threat_category: None,
            rule_id: None,
            details_url: None,
        }
    }
}

/// Generates a new UUIDv7 event ID.
///
/// UUIDv7 IDs encode a millisecond-precision Unix timestamp in the most significant bits,
/// making them monotonically ordered when compared lexicographically. This satisfies EVNT-01.
pub fn new_event_id() -> String {
    format!("evt_{}", uuid::Uuid::now_v7())
}

/// Returns the current UTC timestamp as an RFC 3339 string with Z suffix.
///
/// Example output: `"2026-04-07T12:00:00Z"`
///
/// # PERFORMANCE: Pure in-memory — no I/O, no allocation beyond the returned String.
pub fn current_timestamp() -> String {
    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

/// Returns the current OS name as reported by the Rust standard library.
///
/// Examples: `"linux"`, `"macos"`, `"windows"`
pub fn os_string() -> &'static str {
    std::env::consts::OS
}

/// Returns the current CPU architecture as reported by the Rust standard library.
///
/// Examples: `"x86_64"`, `"aarch64"`
pub fn arch_string() -> &'static str {
    std::env::consts::ARCH
}

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

    fn make_test_envelope() -> EventEnvelope {
        EventEnvelope {
            schema_version: "1.0".to_string(),
            id: new_event_id(),
            timestamp: current_timestamp(),
            event_type: HookEventType::PreToolUse,
            session_id: "test-session-123".to_string(),
            tool_name: Some("bash".to_string()),
            tool_input: Some(serde_json::json!({"command": "ls -la"})),
            user_prompt: None,
            reason: None,
            verdict: Verdict::Allow,
            latency_ms: 3,
            agent_platform: AgentType::ClaudeCode,
            agent_version: None,
            os: os_string().to_string(),
            arch: arch_string().to_string(),
            client_version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }

    #[test]
    fn test_event_envelope_serializes_all_required_fields() {
        let envelope = make_test_envelope();
        let json = serde_json::to_value(&envelope).expect("serialization must succeed");

        // All required fields must be present
        assert!(
            json.get("schema_version").is_some(),
            "missing schema_version"
        );
        assert!(json.get("id").is_some(), "missing id");
        assert!(json.get("timestamp").is_some(), "missing timestamp");
        assert!(json.get("event_type").is_some(), "missing event_type");
        assert!(json.get("session_id").is_some(), "missing session_id");
        assert!(json.get("verdict").is_some(), "missing verdict");
        assert!(json.get("latency_ms").is_some(), "missing latency_ms");
        assert!(
            json.get("agent_platform").is_some(),
            "missing agent_platform"
        );
        assert!(json.get("os").is_some(), "missing os");
        assert!(json.get("arch").is_some(), "missing arch");
        assert!(
            json.get("client_version").is_some(),
            "missing client_version"
        );
    }

    #[test]
    fn test_agent_type_claude_code_serializes_to_kebab_case() {
        let agent_type = AgentType::ClaudeCode;
        let json = serde_json::to_string(&agent_type).expect("serialization must succeed");
        assert_eq!(json, "\"claude-code\"");
    }

    #[test]
    fn test_all_8_agent_types_serialize_correctly() {
        let cases = [
            (AgentType::ClaudeCode, "claude-code"),
            (AgentType::Cursor, "cursor"),
            (AgentType::Windsurf, "windsurf"),
            (AgentType::GithubCopilot, "github-copilot"),
            (AgentType::CodexCli, "codex-cli"),
            (AgentType::GeminiCli, "gemini-cli"),
            (AgentType::Cline, "cline"),
            (AgentType::OpenClaw, "openclaw"),
        ];

        for (agent, expected) in cases {
            let json = serde_json::to_string(&agent).expect("serialization must succeed");
            assert_eq!(
                json,
                format!("\"{}\"", expected),
                "wrong serialization for {:?}",
                agent
            );
        }
    }

    #[test]
    fn test_event_envelope_id_has_evt_prefix_and_valid_uuid_v7() {
        let id = new_event_id();
        assert!(
            id.starts_with("evt_"),
            "ID must start with evt_ prefix: {}",
            id
        );
        let uuid_part = id.strip_prefix("evt_").unwrap();
        let parsed = uuid::Uuid::parse_str(uuid_part).expect("ID must contain a valid UUID");
        // UUIDv7 has version nibble = 7 in the 7th byte (bits 12-15)
        assert_eq!(parsed.get_version_num(), 7, "UUID version must be 7");
    }

    #[test]
    fn test_consecutive_event_ids_are_monotonically_ordered() {
        let id1 = new_event_id();
        // Small sleep not needed — UUIDv7 uses sub-millisecond monotonic counter
        let id2 = new_event_id();
        assert!(
            id1 <= id2,
            "UUIDv7 IDs must be monotonically ordered: {} <= {}",
            id1,
            id2
        );
    }

    #[test]
    fn test_timestamp_ends_with_z_suffix() {
        let ts = current_timestamp();
        assert!(
            ts.ends_with('Z'),
            "Timestamp must end with 'Z' for UTC: {}",
            ts
        );
    }

    #[test]
    fn test_verdict_response_serializes_optional_fields_omitted_when_none() {
        let resp = VerdictResponse::allow("evt-001".to_string(), 5.0);
        let json = serde_json::to_value(&resp).expect("serialization must succeed");

        // Optional fields must NOT appear when None
        assert!(
            json.get("reason").is_none(),
            "reason should be omitted when None"
        );
        assert!(
            json.get("severity").is_none(),
            "severity should be omitted when None"
        );
        assert!(
            json.get("threat_category").is_none(),
            "threat_category should be omitted when None"
        );
        assert!(
            json.get("rule_id").is_none(),
            "rule_id should be omitted when None"
        );
        assert!(
            json.get("details_url").is_none(),
            "details_url should be omitted when None"
        );

        // Required fields must still be present
        assert_eq!(json["schema_version"], "1.0");
        assert_eq!(json["event_id"], "evt-001");
        assert_eq!(json["latency_ms"], 5.0);
    }

    #[test]
    fn test_verdict_allow_serializes_to_allow() {
        let verdict = Verdict::Allow;
        let json = serde_json::to_string(&verdict).expect("serialization must succeed");
        assert_eq!(json, "\"allow\"");
    }

    #[test]
    fn test_verdict_approve_serializes_to_approve() {
        let verdict = Verdict::Approve;
        let json = serde_json::to_string(&verdict).expect("serialization must succeed");
        assert_eq!(json, "\"approve\"");
    }

    #[test]
    fn test_hook_event_type_pre_tool_use_serializes_to_snake_case() {
        let event_type = HookEventType::PreToolUse;
        let json = serde_json::to_string(&event_type).expect("serialization must succeed");
        assert_eq!(json, "\"pre_tool_use\"");
    }

    #[test]
    fn test_event_envelope_round_trips_through_serde_json() {
        let original = make_test_envelope();
        let serialized = serde_json::to_string(&original).expect("serialization must succeed");
        let deserialized: EventEnvelope =
            serde_json::from_str(&serialized).expect("deserialization must succeed");
        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_client_version_matches_cargo_pkg_version() {
        let envelope = make_test_envelope();
        assert_eq!(envelope.client_version, env!("CARGO_PKG_VERSION"));
    }

    #[test]
    fn test_user_prompt_serialized_when_present_omitted_when_none() {
        let mut envelope = make_test_envelope();

        // When None, field should be absent from JSON
        let json = serde_json::to_value(&envelope).unwrap();
        assert!(
            json.get("user_prompt").is_none(),
            "user_prompt should be omitted when None"
        );

        // When Some, field should be present
        envelope.user_prompt = Some("tell me about Rust".to_string());
        let json = serde_json::to_value(&envelope).unwrap();
        assert_eq!(json["user_prompt"], "tell me about Rust");
    }

    #[test]
    fn test_reason_serialized_when_present_omitted_when_none() {
        let mut envelope = make_test_envelope();

        // When None, field should be absent from JSON
        let json = serde_json::to_value(&envelope).unwrap();
        assert!(
            json.get("reason").is_none(),
            "reason should be omitted when None"
        );

        // When Some, field should be present
        envelope.reason = Some("end_turn".to_string());
        let json = serde_json::to_value(&envelope).unwrap();
        assert_eq!(json["reason"], "end_turn");
    }

    #[test]
    fn test_schema_version_serializes_as_string() {
        let envelope = make_test_envelope();
        let json = serde_json::to_value(&envelope).unwrap();
        assert_eq!(
            json["schema_version"], "1.0",
            "schema_version must be string \"1.0\""
        );
    }
}