acp-ws-bridge 0.3.3

WebSocket bridge between GitHub Copilot CLI (ACP) and remote clients
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
//! Copilot CLI child-process manager.

use std::process::Stdio;
use tokio::process::{Child, Command};
use tokio::time::{sleep, Duration};

#[derive(Clone, Debug, PartialEq, Eq)]
struct CopilotSpawnCommand {
    program: String,
    args: Vec<String>,
    display: String,
}

impl CopilotSpawnCommand {
    fn default_tcp(copilot_path: &str, port: u16, extra_args: &[String]) -> Self {
        let mut args = vec![
            "--acp".to_string(),
            "--port".to_string(),
            port.to_string(),
            "--resume".to_string(),
        ];
        args.extend(extra_args.iter().cloned());

        let mut display = format!("{copilot_path} --acp --port {port} --resume");
        if !extra_args.is_empty() {
            display.push(' ');
            display.push_str(&extra_args.join(" "));
        }

        Self {
            program: copilot_path.to_string(),
            args,
            display,
        }
    }

    fn default_stdio(copilot_path: &str, extra_args: &[String]) -> Self {
        let mut args = vec![
            "--acp".to_string(),
            "--stdio".to_string(),
            "--resume".to_string(),
        ];
        args.extend(extra_args.iter().cloned());

        let mut display = format!("{copilot_path} --acp --stdio --resume");
        if !extra_args.is_empty() {
            display.push(' ');
            display.push_str(&extra_args.join(" "));
        }

        Self {
            program: copilot_path.to_string(),
            args,
            display,
        }
    }

    fn exact_override(raw: &str) -> anyhow::Result<Self> {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            anyhow::bail!("Custom ACP command cannot be empty")
        }

        let tokens = shlex::split(trimmed)
            .ok_or_else(|| anyhow::anyhow!("Custom ACP command has invalid shell-style quoting"))?;
        let (program, args) = tokens
            .split_first()
            .ok_or_else(|| anyhow::anyhow!("Custom ACP command cannot be empty"))?;

        Ok(Self {
            program: program.clone(),
            args: args.to_vec(),
            display: "custom ACP command override".to_string(),
        })
    }

    fn into_command(self) -> Command {
        let mut cmd = Command::new(self.program);
        cmd.args(self.args);
        cmd
    }
}

pub fn validate_command_override(command: &str) -> anyhow::Result<()> {
    CopilotSpawnCommand::exact_override(command).map(|_| ())
}

pub fn validate_command_override_for_mode(
    command: &str,
    mode: &str,
    tcp_port: u16,
) -> anyhow::Result<()> {
    let parsed = CopilotSpawnCommand::exact_override(command)?;
    if !parsed.args.iter().any(|arg| arg == "--acp") {
        anyhow::bail!("Custom ACP command must include --acp")
    }

    match mode {
        "stdio" => {
            if !parsed.args.iter().any(|arg| arg == "--stdio") {
                anyhow::bail!(
                    "Custom ACP command must include --stdio when --copilot-mode is stdio"
                );
            }
            if tcp_port_arg(&parsed.args).is_some() {
                anyhow::bail!(
                    "Custom ACP command cannot include --port when --copilot-mode is stdio"
                );
            }
        }
        "tcp" => {
            if parsed.args.iter().any(|arg| arg == "--stdio") {
                anyhow::bail!(
                    "Custom ACP command cannot include --stdio when --copilot-mode is tcp"
                );
            }
            match tcp_port_arg(&parsed.args) {
                Some(port) if port == tcp_port => {}
                Some(port) => {
                    anyhow::bail!(
                        "Custom ACP command uses --port {}, but --copilot-port is configured as {}",
                        port,
                        tcp_port
                    );
                }
                None => {
                    anyhow::bail!(
                        "Custom ACP command must include --port {} when --copilot-mode is tcp",
                        tcp_port
                    );
                }
            }
        }
        _ => {}
    }

    Ok(())
}

pub fn effective_command_program(copilot_path: &str, custom_command: Option<&str>) -> String {
    custom_command
        .and_then(|command| CopilotSpawnCommand::exact_override(command).ok())
        .map(|command| command.program)
        .unwrap_or_else(|| copilot_path.to_string())
}

fn tcp_port_arg(args: &[String]) -> Option<u16> {
    let mut args_iter = args.iter();
    while let Some(arg) = args_iter.next() {
        if arg == "--port" {
            return args_iter.next()?.parse().ok();
        }
        if let Some(value) = arg.strip_prefix("--port=") {
            return value.parse().ok();
        }
    }
    None
}

fn version_probe_command(
    copilot_path: &str,
    custom_command: Option<&str>,
) -> anyhow::Result<CopilotSpawnCommand> {
    if let Some(command) = custom_command {
        let parsed = CopilotSpawnCommand::exact_override(command)?;
        let acp_index = parsed
            .args
            .iter()
            .position(|arg| arg == "--acp")
            .unwrap_or(parsed.args.len());

        let mut args = parsed.args.into_iter().take(acp_index).collect::<Vec<_>>();
        args.push("--version".to_string());

        return Ok(CopilotSpawnCommand {
            program: parsed.program,
            args,
            display: "custom ACP version probe".to_string(),
        });
    }

    Ok(CopilotSpawnCommand {
        program: copilot_path.to_string(),
        args: vec!["--version".to_string()],
        display: format!("{copilot_path} --version"),
    })
}

/// Describes how the bridge communicates with the Copilot CLI process.
#[allow(dead_code)]
pub enum CopilotTransport {
    /// TCP mode — Copilot CLI listens on a port, we connect to it.
    Tcp { port: u16 },
    /// Stdio mode — we own the child's stdin/stdout pipes directly.
    Stdio {
        stdin: tokio::process::ChildStdin,
        stdout: tokio::io::BufReader<tokio::process::ChildStdout>,
    },
}

/// Manages the Copilot CLI child process.
pub struct CopilotProcess {
    child: Child,
    port: u16,
}

impl CopilotProcess {
    /// Spawn `copilot --acp --port <port>` (TCP mode) and wait until it's ready.
    pub async fn spawn_tcp(
        copilot_path: &str,
        copilot_host: &str,
        port: u16,
        extra_args: &[String],
        custom_command: Option<&str>,
    ) -> anyhow::Result<(Self, CopilotTransport)> {
        let spawn_command = match custom_command {
            Some(command) => CopilotSpawnCommand::exact_override(command)?,
            None => CopilotSpawnCommand::default_tcp(copilot_path, port, extra_args),
        };
        tracing::info!("Spawning Copilot CLI (TCP): {}", spawn_command.display);

        let mut cmd = spawn_command.into_command();
        cmd.env("COPILOT_CLI", "1") // Let git hooks detect Copilot CLI subprocesses
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::null());

        let child = cmd.spawn().map_err(|e| {
            anyhow::anyhow!(
                "Failed to spawn '{}': {}. Make sure Copilot CLI is installed and authenticated.",
                copilot_path,
                e
            )
        })?;

        tracing::info!("Copilot CLI spawned (PID: {:?})", child.id());

        // Wait for the TCP port to become available
        let ready = wait_for_port(copilot_host, port, Duration::from_secs(30)).await;
        if !ready {
            tracing::warn!(
                "Copilot CLI may not be ready yet ({}:{} not reachable after 30s), proceeding anyway",
                copilot_host,
                port
            );
        } else {
            tracing::info!("Copilot CLI ready on {}:{}", copilot_host, port);
        }

        Ok((Self { child, port }, CopilotTransport::Tcp { port }))
    }

    /// Spawn `copilot --acp --stdio` and return piped stdin/stdout.
    pub async fn spawn_stdio(
        copilot_path: &str,
        extra_args: &[String],
        custom_command: Option<&str>,
    ) -> anyhow::Result<(Self, CopilotTransport)> {
        let spawn_command = match custom_command {
            Some(command) => CopilotSpawnCommand::exact_override(command)?,
            None => CopilotSpawnCommand::default_stdio(copilot_path, extra_args),
        };
        tracing::info!("Spawning Copilot CLI (stdio): {}", spawn_command.display);

        let mut cmd = spawn_command.into_command();
        cmd.env("COPILOT_CLI", "1") // Let git hooks detect Copilot CLI subprocesses
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null());

        let mut child = cmd.spawn().map_err(|e| {
            anyhow::anyhow!(
                "Failed to spawn '{}': {}. Make sure Copilot CLI is installed and authenticated.",
                copilot_path,
                e
            )
        })?;

        let stdin = child.stdin.take().ok_or_else(|| {
            anyhow::anyhow!("Failed to capture stdin pipe from Copilot CLI process")
        })?;
        let stdout = child.stdout.take().ok_or_else(|| {
            anyhow::anyhow!("Failed to capture stdout pipe from Copilot CLI process")
        })?;

        tracing::info!("Copilot CLI spawned in stdio mode (PID: {:?})", child.id());

        Ok((
            Self { child, port: 0 },
            CopilotTransport::Stdio {
                stdin,
                stdout: tokio::io::BufReader::new(stdout),
            },
        ))
    }

    pub fn port(&self) -> u16 {
        self.port
    }
}

impl Drop for CopilotProcess {
    fn drop(&mut self) {
        tracing::info!("Shutting down Copilot CLI");
        let _ = self.child.start_kill();
    }
}

/// Wait for a TCP port to become available.
async fn wait_for_port(host: &str, port: u16, timeout: Duration) -> bool {
    let addr = format!("{}:{}", host, port);
    let start = std::time::Instant::now();

    while start.elapsed() < timeout {
        match tokio::net::TcpStream::connect(&addr).await {
            Ok(_) => return true,
            Err(_) => {
                sleep(Duration::from_millis(500)).await;
            }
        }
    }

    false
}

/// Detect the installed Copilot CLI version by running `copilot --version`.
pub async fn detect_version(copilot_path: &str, custom_command: Option<&str>) -> Option<String> {
    let probe = version_probe_command(copilot_path, custom_command).ok()?;
    let mut cmd = probe.into_command();
    match cmd
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .await
    {
        Ok(output) if output.status.success() => {
            let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if raw.is_empty() {
                None
            } else {
                Some(raw)
            }
        }
        Ok(_) => None,
        Err(e) => {
            tracing::debug!("Could not detect Copilot CLI version: {}", e);
            None
        }
    }
}

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

    #[test]
    fn test_custom_command_parses_with_quotes() {
        let command = CopilotSpawnCommand::exact_override(
            r#"copilot --acp --stdio --profile "allow all tools""#,
        )
        .unwrap();

        assert_eq!(command.program, "copilot");
        assert_eq!(
            command.args,
            vec![
                "--acp".to_string(),
                "--stdio".to_string(),
                "--profile".to_string(),
                "allow all tools".to_string()
            ]
        );
    }

    #[test]
    fn test_custom_command_rejects_empty_string() {
        assert!(validate_command_override("   ").is_err());
    }

    #[test]
    fn test_validate_command_override_for_stdio_mode() {
        assert!(
            validate_command_override_for_mode("copilot --acp --stdio --yolo", "stdio", 3000)
                .is_ok()
        );
        assert!(
            validate_command_override_for_mode("copilot --acp --port 3000", "stdio", 3000).is_err()
        );
    }

    #[test]
    fn test_validate_command_override_for_tcp_mode() {
        assert!(
            validate_command_override_for_mode("copilot --acp --port 3000", "tcp", 3000).is_ok()
        );
        assert!(
            validate_command_override_for_mode("copilot --acp --port=4000", "tcp", 3000).is_err()
        );
        assert!(validate_command_override_for_mode(
            "copilot --acp --stdio --port 3000",
            "tcp",
            3000
        )
        .is_err());
    }

    #[test]
    fn test_default_stdio_command_includes_resume_and_extra_args() {
        let command =
            CopilotSpawnCommand::default_stdio("copilot", &["--allow-all-tools".to_string()]);

        assert_eq!(command.program, "copilot");
        assert_eq!(
            command.args,
            vec![
                "--acp".to_string(),
                "--stdio".to_string(),
                "--resume".to_string(),
                "--allow-all-tools".to_string()
            ]
        );
    }

    #[test]
    fn test_version_probe_strips_acp_flags_from_custom_command() {
        let command =
            version_probe_command("copilot", Some("node /tmp/copilot.js --acp --stdio --yolo"))
                .unwrap();

        assert_eq!(command.program, "node");
        assert_eq!(
            command.args,
            vec!["/tmp/copilot.js".to_string(), "--version".to_string()]
        );
    }

    #[test]
    fn test_effective_command_program_prefers_override_program() {
        assert_eq!(
            effective_command_program("copilot", Some("node /tmp/copilot.js --acp --stdio")),
            "node"
        );
    }
}