agentkernel 0.18.1

Run AI coding agents in secure, isolated microVMs
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
//! HTTP hooks for proxy request/response interception (l8v).
//!
//! Hooks allow external systems to observe and react to proxied requests.
//! Supported targets:
//! - **Webhook**: POST event payload as JSON to a URL
//! - **File**: Append JSON event to a file (JSONL format)
//! - **Audit**: Log to the agentkernel audit log (always enabled)

use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// When a hook fires.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HookEvent {
    OnRequest,
    OnResponse,
}

/// Where a hook delivers its payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum HookTarget {
    Webhook { url: String },
    File { path: String },
    Audit,
}

/// A registered proxy hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProxyHook {
    pub name: String,
    pub event: HookEvent,
    pub target: HookTarget,
}

/// A proxy event emitted for each proxied request.
#[derive(Debug, Clone, Serialize)]
pub struct ProxyEvent {
    /// RFC3339 timestamp
    pub timestamp: String,
    /// Sandbox that originated the request
    pub sandbox: String,
    /// HTTP method
    pub method: String,
    /// Full request URL
    pub url: String,
    /// Destination host
    pub host: String,
    /// Response status (None for CONNECT tunnels or errors)
    pub status: Option<u16>,
    /// Whether a secret was injected into this request
    pub secret_injected: bool,
    /// Request latency in milliseconds (None if not measured)
    pub latency_ms: Option<u64>,
}

/// Thread-safe hook registry shared across proxy connections.
pub type HookRegistry = Arc<RwLock<HookRegistryInner>>;

/// Inner state for the hook registry.
pub struct HookRegistryInner {
    hooks: HashMap<String, ProxyHook>,
}

impl Default for HookRegistryInner {
    fn default() -> Self {
        Self::new()
    }
}

impl HookRegistryInner {
    pub fn new() -> Self {
        Self {
            hooks: HashMap::new(),
        }
    }

    pub fn register(&mut self, hook: ProxyHook) -> Result<()> {
        if hook.name.is_empty() {
            bail!("Hook name cannot be empty");
        }
        if let HookTarget::Webhook { ref url } = hook.target
            && !url.starts_with("http://")
            && !url.starts_with("https://")
        {
            bail!("Webhook URL must start with http:// or https://");
        }
        self.hooks.insert(hook.name.clone(), hook);
        Ok(())
    }

    pub fn remove(&mut self, name: &str) -> bool {
        self.hooks.remove(name).is_some()
    }

    pub fn list(&self) -> Vec<ProxyHook> {
        self.hooks.values().cloned().collect()
    }

    pub fn hooks_for_event(&self, event: &HookEvent) -> Vec<ProxyHook> {
        self.hooks
            .values()
            .filter(|h| h.event == *event)
            .cloned()
            .collect()
    }
}

/// Create a new hook registry, optionally seeded with initial hooks.
pub fn new_registry(initial: Vec<ProxyHook>) -> HookRegistry {
    let mut inner = HookRegistryInner::new();
    for hook in initial {
        let _ = inner.register(hook);
    }
    Arc::new(RwLock::new(inner))
}

/// Dispatch an event to all matching hooks.
///
/// Webhook delivery is best-effort (fire-and-forget). Failures are logged but
/// do not block the proxy.
pub async fn dispatch_hooks(event: &HookEvent, payload: &ProxyEvent, registry: &HookRegistry) {
    // Always log to stderr (audit)
    log_proxy_event(payload);

    let hooks = {
        let r = registry.read().await;
        r.hooks_for_event(event)
    };

    for hook in hooks {
        match &hook.target {
            HookTarget::Audit => {
                // Already logged above
            }
            HookTarget::File { path } => {
                if let Ok(json) = serde_json::to_string(payload) {
                    use std::io::Write;
                    if let Ok(mut f) = std::fs::OpenOptions::new()
                        .create(true)
                        .append(true)
                        .open(path)
                    {
                        let _ = writeln!(f, "{}", json);
                    } else {
                        eprintln!("[proxy:hook] Failed to open file: {}", path);
                    }
                }
            }
            HookTarget::Webhook { url } => {
                let url = url.clone();
                let json = match serde_json::to_string(payload) {
                    Ok(j) => j,
                    Err(_) => continue,
                };
                // Fire-and-forget: don't block the proxy
                tokio::spawn(async move {
                    deliver_webhook(&url, &json).await;
                });
            }
        }
    }
}

/// Dispatch an LLM event to all matching hooks.
///
/// LLM events piggyback on `OnResponse` hooks. Consumers can distinguish them
/// from regular `ProxyEvent` payloads by the presence of the `provider` field.
pub async fn dispatch_llm_hooks(event: &crate::llm_intercept::LlmEvent, registry: &HookRegistry) {
    eprintln!(
        "[proxy:llm] {} {} {} model={:?} tokens=({:?}/{:?}/{:?})",
        event.sandbox,
        event.provider,
        event.path,
        event.model,
        event.input_tokens,
        event.output_tokens,
        event.total_tokens,
    );

    let hooks = {
        let r = registry.read().await;
        r.hooks_for_event(&HookEvent::OnResponse)
    };

    for hook in hooks {
        match &hook.target {
            HookTarget::Audit => {
                // Already logged above
            }
            HookTarget::File { path } => {
                if let Ok(json) = serde_json::to_string(event) {
                    use std::io::Write;
                    if let Ok(mut f) = std::fs::OpenOptions::new()
                        .create(true)
                        .append(true)
                        .open(path)
                    {
                        let _ = writeln!(f, "{}", json);
                    } else {
                        eprintln!("[proxy:hook] Failed to open file: {}", path);
                    }
                }
            }
            HookTarget::Webhook { url } => {
                let url = url.clone();
                let json = match serde_json::to_string(event) {
                    Ok(j) => j,
                    Err(_) => continue,
                };
                tokio::spawn(async move {
                    deliver_webhook(&url, &json).await;
                });
            }
        }
    }
}

/// Log a proxy event to stderr (audit trail).
pub fn log_proxy_event(event: &ProxyEvent) {
    eprintln!(
        "[proxy:audit] {} {} {} -> {} (secret={}, status={:?})",
        event.sandbox, event.method, event.url, event.host, event.secret_injected, event.status,
    );
}

/// POST a JSON payload to a webhook URL. Best-effort, logs errors.
async fn deliver_webhook(url: &str, json: &str) {
    use hyper::body::Bytes;

    // Simple TCP-based HTTP POST (no TLS for webhook URLs starting with http://)
    // For production, this would use a proper HTTP client. For MVP, we use hyper directly.
    let uri: hyper::Uri = match url.parse() {
        Ok(u) => u,
        Err(e) => {
            eprintln!("[proxy:hook] Invalid webhook URL '{}': {}", url, e);
            return;
        }
    };

    let host = match uri.host() {
        Some(h) => h.to_string(),
        None => {
            eprintln!("[proxy:hook] No host in webhook URL: {}", url);
            return;
        }
    };
    let port = uri
        .port_u16()
        .unwrap_or(if uri.scheme_str() == Some("https") {
            443
        } else {
            80
        });
    let addr = format!("{}:{}", host, port);

    let stream = match tokio::net::TcpStream::connect(&addr).await {
        Ok(s) => s,
        Err(e) => {
            eprintln!("[proxy:hook] Failed to connect to {}: {}", addr, e);
            return;
        }
    };

    let io = hyper_util::rt::TokioIo::new(stream);
    let (mut sender, conn) = match hyper::client::conn::http1::handshake(io).await {
        Ok(pair) => pair,
        Err(e) => {
            eprintln!("[proxy:hook] HTTP handshake with {} failed: {}", addr, e);
            return;
        }
    };

    tokio::spawn(async move {
        if let Err(e) = conn.await {
            eprintln!("[proxy:hook] Connection error: {}", e);
        }
    });

    let body = http_body_util::Full::new(Bytes::from(json.to_string()));
    let req = match hyper::Request::builder()
        .method(hyper::Method::POST)
        .uri(uri)
        .header("content-type", "application/json")
        .header("host", &host)
        .header("user-agent", "agentkernel-proxy-hook/1.0")
        .body(body)
    {
        Ok(r) => r,
        Err(e) => {
            eprintln!("[proxy:hook] Failed to build request: {}", e);
            return;
        }
    };

    match sender.send_request(req).await {
        Ok(resp) => {
            if !resp.status().is_success() {
                eprintln!(
                    "[proxy:hook] Webhook {} returned status {}",
                    url,
                    resp.status()
                );
            }
        }
        Err(e) => {
            eprintln!("[proxy:hook] Webhook delivery to {} failed: {}", url, e);
        }
    }
}

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

    #[test]
    fn test_register_hook() {
        let mut registry = HookRegistryInner::new();
        let hook = ProxyHook {
            name: "my-hook".to_string(),
            event: HookEvent::OnRequest,
            target: HookTarget::Audit,
        };
        registry.register(hook).unwrap();
        assert_eq!(registry.list().len(), 1);
    }

    #[test]
    fn test_register_empty_name_fails() {
        let mut registry = HookRegistryInner::new();
        let hook = ProxyHook {
            name: String::new(),
            event: HookEvent::OnRequest,
            target: HookTarget::Audit,
        };
        assert!(registry.register(hook).is_err());
    }

    #[test]
    fn test_register_invalid_webhook_url() {
        let mut registry = HookRegistryInner::new();
        let hook = ProxyHook {
            name: "bad-url".to_string(),
            event: HookEvent::OnRequest,
            target: HookTarget::Webhook {
                url: "not-a-url".to_string(),
            },
        };
        assert!(registry.register(hook).is_err());
    }

    #[test]
    fn test_remove_hook() {
        let mut registry = HookRegistryInner::new();
        let hook = ProxyHook {
            name: "removable".to_string(),
            event: HookEvent::OnResponse,
            target: HookTarget::File {
                path: "/tmp/hook.jsonl".to_string(),
            },
        };
        registry.register(hook).unwrap();
        assert!(registry.remove("removable"));
        assert!(!registry.remove("removable")); // already removed
        assert_eq!(registry.list().len(), 0);
    }

    #[test]
    fn test_hooks_for_event() {
        let mut registry = HookRegistryInner::new();
        registry
            .register(ProxyHook {
                name: "on-req".to_string(),
                event: HookEvent::OnRequest,
                target: HookTarget::Audit,
            })
            .unwrap();
        registry
            .register(ProxyHook {
                name: "on-resp".to_string(),
                event: HookEvent::OnResponse,
                target: HookTarget::Audit,
            })
            .unwrap();

        let req_hooks = registry.hooks_for_event(&HookEvent::OnRequest);
        assert_eq!(req_hooks.len(), 1);
        assert_eq!(req_hooks[0].name, "on-req");

        let resp_hooks = registry.hooks_for_event(&HookEvent::OnResponse);
        assert_eq!(resp_hooks.len(), 1);
        assert_eq!(resp_hooks[0].name, "on-resp");
    }

    #[test]
    fn test_new_registry_with_initial() {
        let hooks = vec![
            ProxyHook {
                name: "h1".to_string(),
                event: HookEvent::OnRequest,
                target: HookTarget::Audit,
            },
            ProxyHook {
                name: "h2".to_string(),
                event: HookEvent::OnResponse,
                target: HookTarget::Audit,
            },
        ];
        let _registry = new_registry(hooks);
        // registry is Arc<RwLock<...>>, just verify it was created
    }

    #[test]
    fn test_hook_serde_roundtrip() {
        let hook = ProxyHook {
            name: "test-hook".to_string(),
            event: HookEvent::OnRequest,
            target: HookTarget::Webhook {
                url: "http://localhost:8080/hook".to_string(),
            },
        };
        let json = serde_json::to_string(&hook).unwrap();
        let deserialized: ProxyHook = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.name, "test-hook");
        assert_eq!(deserialized.event, HookEvent::OnRequest);
    }
}