gate4agent 0.2.37

Universal transport library for CLI AI agents (Claude Code, Codex, Gemini, OpenCode). Pipe, PTY, ACP (Agent Client Protocol), and Daemon transports.
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
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
//! ACP host-side handler trait and bridge adapter.
//!
//! Rather than forcing callers to implement the low-level [`HostHandler`] with
//! raw string/JSON matching, this module provides a typed trait
//! [`AcpHostHandler`] with safe defaults. Internally [`AcpHostAdapter`]
//! bridges from [`HostHandler`] → [`AcpHostHandler`], so the reader loop can
//! use the existing RPC infrastructure unchanged.

use std::collections::HashMap;
use std::sync::Arc;

use serde_json::{json, Value};

use crate::rpc::handler::HostHandler;
use crate::rpc::message::RpcError;

use super::protocol::{FsReadParams, PermissionRequestParams, TerminalCreateParams, TerminalWriteParams};

// ---------------------------------------------------------------------------
// AcpHostHandler — typed trait
// ---------------------------------------------------------------------------

/// Typed handler for agent → host ACP requests.
///
/// All methods have default implementations that return safe denials, so
/// callers only need to override the operations they actually support.
///
/// Implementations must be `Send + Sync` because the handler is called from
/// the reader loop's blocking thread.
pub trait AcpHostHandler: Send + Sync {
    /// Agent wants to read a file from the host filesystem.
    ///
    /// Return `Ok(content)` or `Err(human-readable message)`.
    fn fs_read_text_file(&self, path: &str) -> Result<String, String> {
        Err(format!("fs/read_text_file not supported: {}", path))
    }

    /// Agent wants to create a terminal session on the host.
    ///
    /// Return `Ok(terminal_id)` or `Err(human-readable message)`.
    fn terminal_create(
        &self,
        _cwd: Option<&str>,
        _env: Option<&HashMap<String, String>>,
    ) -> Result<String, String> {
        Err("terminal/create not supported".to_string())
    }

    /// Agent wants to write input to an existing terminal session.
    ///
    /// Return `Ok(output)` or `Err(human-readable message)`.
    fn terminal_write(&self, terminal_id: &str, input: &str) -> Result<String, String> {
        let _ = (terminal_id, input);
        Err("terminal/write not supported".to_string())
    }

    /// Agent is requesting permission to run a tool.
    ///
    /// Return `Ok(true)` to allow, `Ok(false)` to deny, `Err` for error.
    /// Default: deny all requests (safe default).
    fn request_permission(
        &self,
        _tool_name: &str,
        _description: &str,
        _session_id: &str,
    ) -> Result<bool, String> {
        Ok(false)
    }
}

// ---------------------------------------------------------------------------
// DefaultAcpHandler
// ---------------------------------------------------------------------------

/// Default handler that denies all requests with safe defaults.
///
/// - `fs/read_text_file` → `Err("not supported")`
/// - `terminal/create` → `Err("not supported")`
/// - `terminal/write` → `Err("not supported")`
/// - `session/request_permission` → `Ok(false)` (deny)
pub struct DefaultAcpHandler;

impl AcpHostHandler for DefaultAcpHandler {}

// ---------------------------------------------------------------------------
// FilesystemAcpHandler
// ---------------------------------------------------------------------------

/// ACP host handler that serves real filesystem reads and auto-allows
/// permissions. Matches Pipe transport's `--dangerously-skip-permissions`
/// behavior.
pub struct FilesystemAcpHandler {
    /// Optional path prefix whitelist. `None` = allow all absolute paths.
    pub allowed_roots: Option<Vec<std::path::PathBuf>>,
}

impl FilesystemAcpHandler {
    /// Check that `path` is within the whitelist (if any), then read it.
    fn checked_read(&self, path: &str) -> Result<String, String> {
        if let Some(ref roots) = self.allowed_roots {
            let file_path = std::path::Path::new(path);
            let canonical = file_path.canonicalize().map_err(|e| e.to_string())?;
            let allowed = roots.iter().any(|root| {
                root.canonicalize()
                    .map(|r| canonical.starts_with(&r))
                    .unwrap_or(false)
            });
            if !allowed {
                return Err(format!("path outside allowed roots: {}", path));
            }
        }
        std::fs::read_to_string(path).map_err(|e| e.to_string())
    }
}

impl AcpHostHandler for FilesystemAcpHandler {
    fn fs_read_text_file(&self, path: &str) -> Result<String, String> {
        self.checked_read(path)
    }

    fn request_permission(
        &self,
        _tool_name: &str,
        _description: &str,
        _session_id: &str,
    ) -> Result<bool, String> {
        Ok(true) // auto-allow, like --dangerously-skip-permissions
    }
}

// ---------------------------------------------------------------------------
// TerminalAcpHandler
// ---------------------------------------------------------------------------

struct TerminalSession {
    cwd: std::path::PathBuf,
    env: HashMap<String, String>,
}

/// ACP host handler with real filesystem reads and terminal execution.
///
/// WARNING: No sandboxing. Use only with trusted agents.
pub struct TerminalAcpHandler {
    /// Optional path prefix whitelist. `None` = allow all absolute paths.
    pub allowed_roots: Option<Vec<std::path::PathBuf>>,
    sessions: std::sync::Mutex<HashMap<String, TerminalSession>>,
}

impl TerminalAcpHandler {
    /// Create a new handler. Pass `None` for `allowed_roots` to allow all paths.
    pub fn new(allowed_roots: Option<Vec<std::path::PathBuf>>) -> Self {
        Self {
            allowed_roots,
            sessions: std::sync::Mutex::new(HashMap::new()),
        }
    }

    fn checked_read(&self, path: &str) -> Result<String, String> {
        if let Some(ref roots) = self.allowed_roots {
            let file_path = std::path::Path::new(path);
            let canonical = file_path.canonicalize().map_err(|e| e.to_string())?;
            let allowed = roots.iter().any(|root| {
                root.canonicalize()
                    .map(|r| canonical.starts_with(&r))
                    .unwrap_or(false)
            });
            if !allowed {
                return Err(format!("path outside allowed roots: {}", path));
            }
        }
        std::fs::read_to_string(path).map_err(|e| e.to_string())
    }
}

impl AcpHostHandler for TerminalAcpHandler {
    fn fs_read_text_file(&self, path: &str) -> Result<String, String> {
        self.checked_read(path)
    }

    fn terminal_create(
        &self,
        cwd: Option<&str>,
        env: Option<&HashMap<String, String>>,
    ) -> Result<String, String> {
        let id = {
            let nanos = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos();
            format!("term-{:x}", nanos)
        };

        let session = TerminalSession {
            cwd: cwd
                .map(std::path::PathBuf::from)
                .unwrap_or_else(|| std::env::current_dir().unwrap_or_default()),
            env: env.cloned().unwrap_or_default(),
        };

        self.sessions
            .lock()
            .map_err(|e| e.to_string())?
            .insert(id.clone(), session);

        Ok(id)
    }

    fn terminal_write(&self, terminal_id: &str, input: &str) -> Result<String, String> {
        let sessions = self.sessions.lock().map_err(|e| e.to_string())?;
        let session = sessions
            .get(terminal_id)
            .ok_or_else(|| format!("unknown terminal: {}", terminal_id))?;

        let output = {
            #[cfg(windows)]
            {
                std::process::Command::new("cmd")
                    .args(["/C", input])
                    .current_dir(&session.cwd)
                    .envs(&session.env)
                    .output()
                    .map_err(|e| e.to_string())?
            }
            #[cfg(not(windows))]
            {
                std::process::Command::new("sh")
                    .args(["-c", input])
                    .current_dir(&session.cwd)
                    .envs(&session.env)
                    .output()
                    .map_err(|e| e.to_string())?
            }
        };

        let combined = format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        Ok(combined)
    }

    fn request_permission(
        &self,
        _tool_name: &str,
        _description: &str,
        _session_id: &str,
    ) -> Result<bool, String> {
        Ok(true) // auto-allow, like --dangerously-skip-permissions
    }
}

// ---------------------------------------------------------------------------
// AcpHostAdapter — bridges AcpHostHandler → HostHandler
// ---------------------------------------------------------------------------

/// Bridges [`AcpHostHandler`] → [`HostHandler`] for use in the reader loop.
///
/// Wraps `Arc<dyn AcpHostHandler>` so it can be cloned cheaply without
/// requiring `'static + Clone` bounds on the trait.
pub(crate) struct AcpHostAdapter(pub Arc<dyn AcpHostHandler>);

impl HostHandler for AcpHostAdapter {
    fn handle(&self, method: &str, params: Option<Value>) -> Result<Value, RpcError> {
        match method {
            "fs/read_text_file" => {
                let p: FsReadParams = parse_params(params)?;
                self.0
                    .fs_read_text_file(&p.path)
                    .map(|content| json!({ "content": content }))
                    .map_err(|msg| RpcError {
                        code: RpcError::PERMISSION_DENIED,
                        message: msg,
                        data: None,
                    })
            }

            "terminal/create" => {
                let p: TerminalCreateParams = parse_params(params)?;
                self.0
                    .terminal_create(p.cwd.as_deref(), p.env.as_ref())
                    .map(|terminal_id| json!({ "terminalId": terminal_id }))
                    .map_err(|msg| RpcError {
                        code: RpcError::UNSUPPORTED,
                        message: msg,
                        data: None,
                    })
            }

            "terminal/write" => {
                let p: TerminalWriteParams = parse_params(params)?;
                self.0
                    .terminal_write(&p.terminal_id, &p.input)
                    .map(|output| json!({ "output": output }))
                    .map_err(|msg| RpcError {
                        code: RpcError::UNSUPPORTED,
                        message: msg,
                        data: None,
                    })
            }

            "session/request_permission" => {
                let p: PermissionRequestParams = parse_params(params)?;
                self.0
                    .request_permission(&p.tool_name, &p.description, &p.session_id)
                    .map(|allowed| json!({ "allowed": allowed }))
                    .map_err(|msg| RpcError {
                        code: RpcError::INTERNAL_ERROR,
                        message: msg,
                        data: None,
                    })
            }

            other => Err(RpcError::method_not_found(other)),
        }
    }
}

// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------

fn parse_params<T: serde::de::DeserializeOwned>(params: Option<Value>) -> Result<T, RpcError> {
    let v = params.unwrap_or(Value::Null);
    serde_json::from_value(v).map_err(|e| RpcError {
        code: RpcError::INVALID_PARAMS,
        message: format!("Invalid params: {}", e),
        data: None,
    })
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    // -----------------------------------------------------------------------
    // DefaultAcpHandler tests (kept from original)
    // -----------------------------------------------------------------------

    fn default_adapter() -> AcpHostAdapter {
        AcpHostAdapter(Arc::new(DefaultAcpHandler))
    }

    #[test]
    fn default_handler_denies_fs_read() {
        let h = DefaultAcpHandler;
        let result = h.fs_read_text_file("/etc/passwd");
        assert!(result.is_err());
    }

    #[test]
    fn default_handler_denies_terminal() {
        let h = DefaultAcpHandler;
        let result = h.terminal_create(None, None);
        assert!(result.is_err());
    }

    #[test]
    fn default_handler_denies_permission() {
        let h = DefaultAcpHandler;
        let result = h.request_permission("bash", "run command", "s1");
        assert_eq!(result, Ok(false));
    }

    #[test]
    fn adapter_dispatches_fs_read_returns_permission_denied() {
        let adapter = default_adapter();
        let result = adapter.handle(
            "fs/read_text_file",
            Some(json!({"path": "/etc/passwd"})),
        );
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code, RpcError::PERMISSION_DENIED);
    }

    #[test]
    fn adapter_dispatches_permission_request_returns_denied() {
        let adapter = default_adapter();
        let result = adapter.handle(
            "session/request_permission",
            Some(json!({
                "toolName": "bash",
                "description": "run shell command",
                "sessionId": "s1"
            })),
        );
        // DefaultAcpHandler returns Ok(false) → adapter returns Ok({"allowed": false})
        assert!(result.is_ok());
        assert_eq!(result.unwrap()["allowed"], false);
    }

    #[test]
    fn adapter_unknown_method_returns_method_not_found() {
        let adapter = default_adapter();
        let result = adapter.handle("unknown/method", None);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code, RpcError::METHOD_NOT_FOUND);
    }

    #[test]
    fn adapter_invalid_params_returns_invalid_params_error() {
        let adapter = default_adapter();
        // fs/read_text_file requires a "path" field
        let result = adapter.handle("fs/read_text_file", Some(json!({"wrong_key": 42})));
        // DefaultAcpHandler denies, but parse should succeed with default missing fields
        // (FsReadParams.path will be empty string via default deserialization if it has #[serde(default)])
        // Actually FsReadParams.path is required so this should fail parse.
        // It may either fail with INVALID_PARAMS or succeed with empty path then PERMISSION_DENIED.
        // Either way it must be Err.
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // FilesystemAcpHandler tests
    // -----------------------------------------------------------------------

    #[test]
    fn filesystem_handler_allows_permission() {
        let h = FilesystemAcpHandler { allowed_roots: None };
        let result = h.request_permission("bash", "run command", "s1");
        assert_eq!(result, Ok(true));
    }

    #[test]
    fn filesystem_handler_reads_existing_file() {
        let dir = std::env::temp_dir();
        let path = dir.join("gate4agent_test_read.txt");
        std::fs::write(&path, "hello from test").unwrap();

        let h = FilesystemAcpHandler { allowed_roots: None };
        let result = h.fs_read_text_file(path.to_str().unwrap());
        assert!(result.is_ok(), "expected Ok, got {:?}", result);
        assert_eq!(result.unwrap(), "hello from test");

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn filesystem_handler_errors_on_missing_file() {
        let h = FilesystemAcpHandler { allowed_roots: None };
        let result = h.fs_read_text_file("/nonexistent/path/that/does/not/exist.txt");
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // TerminalAcpHandler tests
    // -----------------------------------------------------------------------

    #[test]
    fn terminal_handler_create_returns_id() {
        let h = TerminalAcpHandler::new(None);
        let result = h.terminal_create(None, None);
        assert!(result.is_ok(), "expected Ok, got {:?}", result);
        let id = result.unwrap();
        assert!(!id.is_empty(), "terminal id must not be empty");
        assert!(id.starts_with("term-"), "id should start with 'term-'");
    }

    #[test]
    fn terminal_handler_write_runs_echo() {
        let h = TerminalAcpHandler::new(None);
        let id = h.terminal_create(None, None).expect("create should succeed");

        #[cfg(windows)]
        let cmd = "echo hello";
        #[cfg(not(windows))]
        let cmd = "echo hello";

        let result = h.terminal_write(&id, cmd);
        assert!(result.is_ok(), "expected Ok, got {:?}", result);
        let output = result.unwrap();
        assert!(
            output.contains("hello"),
            "output should contain 'hello', got: {:?}",
            output
        );
    }

    #[test]
    fn terminal_handler_write_unknown_terminal_errors() {
        let h = TerminalAcpHandler::new(None);
        let result = h.terminal_write("nonexistent-id", "echo hi");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("unknown terminal"));
    }

    // -----------------------------------------------------------------------
    // Adapter dispatch tests for terminal/write
    // -----------------------------------------------------------------------

    #[test]
    fn adapter_dispatches_terminal_write() {
        let h = TerminalAcpHandler::new(None);
        let id = h.terminal_create(None, None).expect("create should succeed");

        let adapter = AcpHostAdapter(Arc::new(h));
        let result = adapter.handle(
            "terminal/write",
            Some(json!({ "terminalId": id, "input": "echo adapter_test" })),
        );
        assert!(result.is_ok(), "expected Ok from adapter, got {:?}", result);
        let val = result.unwrap();
        let output = val["output"].as_str().unwrap_or("");
        assert!(
            output.contains("adapter_test"),
            "output should contain 'adapter_test', got: {:?}",
            output
        );
    }

    #[test]
    fn adapter_terminal_write_unknown_id_returns_unsupported_error() {
        let h = TerminalAcpHandler::new(None);
        let adapter = AcpHostAdapter(Arc::new(h));
        let result = adapter.handle(
            "terminal/write",
            Some(json!({ "terminalId": "bad-id", "input": "echo hi" })),
        );
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code, RpcError::UNSUPPORTED);
    }

    #[test]
    fn default_handler_denies_terminal_write() {
        let h = DefaultAcpHandler;
        let result = h.terminal_write("term-123", "echo hi");
        assert!(result.is_err());
    }
}