agentbridge 0.3.1

Connect AI brains to local coding agents through MCP
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
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! OpenCode executor adapter.
//!
//! AgentBridge is not a coding agent. This module starts a local OpenCode CLI
//! process against the configured workspace, captures exit status, and returns
//! a compact result. Internal model reasoning is discarded.

use std::path::{Path, PathBuf};
use std::process::Stdio;

use tokio::io::AsyncReadExt;
use tokio::process::{Child, Command};

use crate::config::{ExecutorConfig, ExecutorMode, ALLOWED_EXECUTOR_TYPES};
use crate::protocol::C2cPlan;

const MAX_CAPTURE_BYTES: usize = 64 * 1024;
const MAX_SUMMARY_CHARS: usize = 2_000;

#[derive(Debug, thiserror::Error)]
pub enum ExecutorError {
    #[error(
        "OpenCode is not installed or not found on PATH (looked for `{0}`). \
         Install OpenCode and ensure the executable is available."
    )]
    NotInstalled(String),
    #[error("executor type `{0}` is not allowed (allowlist: opencode, codex, claude)")]
    TypeNotAllowed(String),
    #[error("executor type `{0}` is not implemented; V0.2 only supports OpenCode")]
    TypeNotImplemented(String),
    #[error("an executor task is already running (task_id={0})")]
    AlreadyRunning(String),
    #[error("no running executor task")]
    NotRunning,
    #[error("executor command is invalid: {0}")]
    InvalidCommand(String),
    #[error("executor workspace is invalid: {0}")]
    InvalidWorkspace(String),
    #[error("failed to start OpenCode: {0}")]
    Spawn(String),
    #[error("executor crashed: {0}")]
    Crashed(String),
    #[error("executor was cancelled")]
    Cancelled,
    #[error("{0}")]
    Other(String),
}

/// Local coding agent that may write files and run commands inside the workspace.
pub trait Executor: Send + Sync {
    fn name(&self) -> &'static str;
    fn detect(&self) -> Result<PathBuf, ExecutorError>;
    fn start_task(&self, plan: &C2cPlan, workspace: &Path) -> Result<SpawnedTask, ExecutorError>;
    fn status(&self, task_id: &str) -> Result<ExecutorSnapshot, ExecutorError>;
    fn result(&self, task_id: &str) -> Result<ExecutorSnapshot, ExecutorError>;
    fn cancel(&self, task_id: &str) -> Result<(), ExecutorError>;
}

/// Handle to a live OpenCode process. `status` / `result` / `cancel` are
/// implemented by [`crate::task::TaskRuntime`], which owns this handle.
pub struct SpawnedTask {
    pub child: Child,
    pub pid: u32,
    pub executable: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecutorSnapshot {
    pub task_id: String,
    pub status: String,
    pub summary: Option<String>,
    pub exit_code: Option<i32>,
    pub tests: Option<String>,
    pub changed_files: Vec<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecutorOutcome {
    pub exit_code: Option<i32>,
    pub summary: String,
    pub tests_excerpt: Option<String>,
    pub cancelled: bool,
    pub error: Option<String>,
}

#[derive(Debug, Clone)]
pub struct OpenCodeExecutor {
    command: String,
    mode: ExecutorMode,
}

impl OpenCodeExecutor {
    pub fn from_config(cfg: &ExecutorConfig) -> Result<Self, ExecutorError> {
        validate_executor_type(&cfg.kind)?;
        let command = cfg.command.trim();
        if command.is_empty() {
            return Err(ExecutorError::InvalidCommand(
                "command must not be empty".into(),
            ));
        }
        if command.contains('\0') {
            return Err(ExecutorError::InvalidCommand("command contains NUL".into()));
        }
        Ok(Self {
            command: command.to_string(),
            mode: cfg.mode,
        })
    }

    pub fn command(&self) -> &str {
        &self.command
    }

    pub fn mode(&self) -> ExecutorMode {
        self.mode
    }
}

impl Executor for OpenCodeExecutor {
    fn name(&self) -> &'static str {
        "opencode"
    }

    fn detect(&self) -> Result<PathBuf, ExecutorError> {
        find_executable(&self.command)
            .ok_or_else(|| ExecutorError::NotInstalled(self.command.clone()))
    }

    fn start_task(&self, plan: &C2cPlan, workspace: &Path) -> Result<SpawnedTask, ExecutorError> {
        plan.validate()
            .map_err(|e| ExecutorError::Other(e.to_string()))?;
        if !workspace.is_dir() {
            return Err(ExecutorError::InvalidWorkspace(
                workspace.display().to_string(),
            ));
        }
        let exe = self.detect()?;
        let prompt = executor_argv_prompt();
        let child = spawn_opencode(&exe, workspace, prompt)?;
        let pid = child
            .id()
            .ok_or_else(|| ExecutorError::Spawn("OpenCode process has no pid".into()))?;
        Ok(SpawnedTask {
            child,
            pid,
            executable: exe,
        })
    }

    fn status(&self, _task_id: &str) -> Result<ExecutorSnapshot, ExecutorError> {
        Err(ExecutorError::Other(
            "status is provided by TaskRuntime".into(),
        ))
    }

    fn result(&self, _task_id: &str) -> Result<ExecutorSnapshot, ExecutorError> {
        Err(ExecutorError::Other(
            "result is provided by TaskRuntime".into(),
        ))
    }

    fn cancel(&self, _task_id: &str) -> Result<(), ExecutorError> {
        Err(ExecutorError::Other(
            "cancel is provided by TaskRuntime".into(),
        ))
    }
}

pub fn validate_executor_type(kind: &str) -> Result<(), ExecutorError> {
    let kind = kind.trim().to_ascii_lowercase();
    if !ALLOWED_EXECUTOR_TYPES
        .iter()
        .any(|allowed| *allowed == kind)
    {
        return Err(ExecutorError::TypeNotAllowed(kind));
    }
    if kind != "opencode" {
        return Err(ExecutorError::TypeNotImplemented(kind));
    }
    Ok(())
}

/// Locate `command` on PATH (Windows-aware). Absolute paths from config are allowed.
pub fn find_executable(command: &str) -> Option<PathBuf> {
    let command = command.trim();
    if command.is_empty() || command.contains('\0') {
        return None;
    }
    let path = Path::new(command);
    if path.is_absolute() {
        return existing_file(path);
    }
    if command.contains("..") {
        return None;
    }
    if path.components().count() > 1 {
        return existing_file(path);
    }

    let path_var = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_var) {
        for candidate in candidates_in_dir(&dir, command) {
            if let Some(found) = existing_file(&candidate) {
                return Some(found);
            }
        }
    }
    None
}

fn existing_file(path: &Path) -> Option<PathBuf> {
    if path.is_file() {
        return Some(path.to_path_buf());
    }
    #[cfg(windows)]
    {
        for ext in pathext() {
            let with_ext = if has_extension(path) {
                path.to_path_buf()
            } else {
                let mut p = path.as_os_str().to_os_string();
                p.push(&ext);
                PathBuf::from(p)
            };
            if with_ext.is_file() {
                return Some(with_ext);
            }
        }
    }
    None
}

fn candidates_in_dir(dir: &Path, command: &str) -> Vec<PathBuf> {
    let base = dir.join(command);
    let mut out = vec![base.clone()];
    #[cfg(windows)]
    {
        if !has_extension(&base) {
            for ext in pathext() {
                let mut p = base.as_os_str().to_os_string();
                p.push(&ext);
                out.push(PathBuf::from(p));
            }
        }
    }
    out
}

#[cfg(windows)]
fn has_extension(path: &Path) -> bool {
    path.extension().is_some()
}

#[cfg(windows)]
fn pathext() -> Vec<String> {
    let raw = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
    raw.split(';')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

pub fn opencode_version(command: &str) -> Option<String> {
    let exe = find_executable(command)?;
    let output = std::process::Command::new(&exe)
        .arg("--version")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .ok()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let line = stdout
        .lines()
        .map(str::trim)
        .find(|l| !l.is_empty())
        .map(ToOwned::to_owned);
    if let Some(line) = line {
        return Some(line);
    }
    Some(exe.display().to_string())
}

/// Short argv payload. The full PLAN is in `.agentbridge/current.c2c` so Windows
/// `.cmd` wrappers are not given multiline arguments.
fn executor_argv_prompt() -> &'static str {
    "Read .agentbridge/current.c2c and implement that PLAN. Stay inside this working directory. Run the TESTS. Print a short summary of changed files and test results. Do not paste source or internal reasoning."
}

fn spawn_opencode(exe: &Path, workspace: &Path, prompt: &str) -> Result<Child, ExecutorError> {
    let mut cmd = Command::new(exe);
    cmd.arg("run")
        .arg("--auto")
        .arg(prompt)
        .current_dir(workspace)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .env_remove("AGENTBRIDGE_AUTH_TOKEN");

    #[cfg(windows)]
    {
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
        cmd.creation_flags(CREATE_NEW_PROCESS_GROUP);
    }

    cmd.spawn().map_err(|err| {
        if err.kind() == std::io::ErrorKind::NotFound {
            ExecutorError::NotInstalled(exe.display().to_string())
        } else {
            ExecutorError::Spawn(err.to_string())
        }
    })
}

/// Wait for OpenCode, honouring cancel. Returns a compact outcome (no reasoning).
pub async fn run_spawned(
    mut child: Child,
    cancel: tokio_util::sync::CancellationToken,
    mode: ExecutorMode,
) -> ExecutorOutcome {
    let stream_to_stdout = mode == ExecutorMode::Stream;
    let stdout = child.stdout.take();
    let stderr = child.stderr.take();
    let out_buf = tokio::spawn(read_limited(stdout, stream_to_stdout));
    let err_buf = tokio::spawn(read_limited(stderr, stream_to_stdout));

    enum Finish {
        Status(std::io::Result<std::process::ExitStatus>),
        Cancelled,
    }

    let finish = tokio::select! {
        _ = cancel.cancelled() => {
            if let Some(pid) = child.id() {
                let _ = kill_process_tree(pid);
            }
            let _ = child.kill().await;
            Finish::Cancelled
        }
        status = child.wait() => Finish::Status(status),
    };

    if matches!(finish, Finish::Cancelled) {
        let _ = child.wait().await;
    }

    let stdout_bytes = out_buf.await.unwrap_or_default();
    let stderr_bytes = err_buf.await.unwrap_or_default();
    let stdout = String::from_utf8_lossy(&stdout_bytes);
    let stderr = String::from_utf8_lossy(&stderr_bytes);
    let stdout = strip_reasoning(&stdout);
    let stderr = strip_reasoning(&stderr);

    match finish {
        Finish::Cancelled => ExecutorOutcome {
            exit_code: None,
            summary: "Executor was cancelled.".into(),
            tests_excerpt: extract_tests_excerpt(&stdout),
            cancelled: true,
            error: None,
        },
        Finish::Status(Ok(status)) => {
            let code = status.code();
            let crashed = code.is_none() && !status.success();
            let summary = sanitize_summary(&stdout, &stderr, code, crashed);
            let error = if crashed {
                Some("OpenCode process crashed (no exit code).".into())
            } else if code.unwrap_or(0) != 0 {
                Some(format!("OpenCode exited with code {}.", code.unwrap_or(-1)))
            } else {
                None
            };
            ExecutorOutcome {
                exit_code: code,
                summary,
                tests_excerpt: extract_tests_excerpt(&stdout),
                cancelled: false,
                error,
            }
        }
        Finish::Status(Err(err)) => ExecutorOutcome {
            exit_code: None,
            summary: format!("Executor crashed: {err}"),
            tests_excerpt: extract_tests_excerpt(&stdout),
            cancelled: false,
            error: Some(err.to_string()),
        },
    }
}

async fn read_limited<R: tokio::io::AsyncRead + Unpin + Send + 'static>(
    reader: Option<R>,
    stream_to_stdout: bool,
) -> Vec<u8> {
    let Some(mut reader) = reader else {
        return Vec::new();
    };
    let mut buf = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        match reader.read(&mut chunk).await {
            Ok(0) => break,
            Ok(n) => {
                if stream_to_stdout {
                    use std::io::Write;
                    let _ = std::io::stdout().write_all(&chunk[..n]);
                    let _ = std::io::stdout().flush();
                }
                if buf.len() < MAX_CAPTURE_BYTES {
                    let take = n.min(MAX_CAPTURE_BYTES - buf.len());
                    buf.extend_from_slice(&chunk[..take]);
                }
            }
            Err(_) => break,
        }
    }
    buf
}

pub fn kill_process_tree(pid: u32) -> Result<(), ExecutorError> {
    #[cfg(windows)]
    {
        let _ = std::process::Command::new("taskkill")
            .args(["/PID", &pid.to_string(), "/T", "/F"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        Ok(())
    }
    #[cfg(unix)]
    {
        let _ = std::process::Command::new("kill")
            .args(["-TERM", &format!("-{pid}")])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        let _ = std::process::Command::new("kill")
            .args(["-TERM", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        Ok(())
    }
}

pub fn process_is_alive(pid: u32) -> bool {
    if pid == 0 {
        return false;
    }
    #[cfg(windows)]
    {
        let output = std::process::Command::new("tasklist")
            .args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"])
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .output();
        match output {
            Ok(o) => {
                let s = String::from_utf8_lossy(&o.stdout);
                s.split(',')
                    .any(|col| col.trim_matches('"') == pid.to_string())
                    || s.contains(&pid.to_string())
            }
            Err(_) => false,
        }
    }
    #[cfg(unix)]
    {
        std::process::Command::new("kill")
            .args(["-0", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }
}

fn strip_reasoning(text: &str) -> String {
    let mut out = String::new();
    let mut in_think = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.contains("<think>") || trimmed.contains("<thinking>") {
            in_think = true;
        }
        if in_think {
            if trimmed.contains("</think>") || trimmed.contains("</thinking>") {
                in_think = false;
            }
            continue;
        }
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) {
            if is_reasoning_event(&value) {
                continue;
            }
            if let Some(text) = json_text(&value) {
                if !out.is_empty() {
                    out.push('\n');
                }
                out.push_str(&text);
                continue;
            }
        }
        if trimmed.eq_ignore_ascii_case("thinking")
            || trimmed.starts_with("thinking:")
            || trimmed.starts_with("Reasoning:")
        {
            continue;
        }
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(line);
    }
    out
}

fn is_reasoning_event(value: &serde_json::Value) -> bool {
    let ty = value
        .get("type")
        .or_else(|| value.get("kind"))
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    matches!(
        ty.as_str(),
        "thinking" | "reasoning" | "think" | "internal" | "thought"
    )
}

fn json_text(value: &serde_json::Value) -> Option<String> {
    if let Some(s) = value.get("text").and_then(|v| v.as_str()) {
        return Some(s.to_string());
    }
    if let Some(s) = value.get("response").and_then(|v| v.as_str()) {
        return Some(s.to_string());
    }
    if let Some(s) = value
        .get("part")
        .and_then(|v| v.get("text"))
        .and_then(|v| v.as_str())
    {
        return Some(s.to_string());
    }
    None
}

fn sanitize_summary(stdout: &str, stderr: &str, exit_code: Option<i32>, crashed: bool) -> String {
    if crashed {
        return truncate_chars(
            &format!(
                "OpenCode crashed. {}",
                stderr.trim().lines().next().unwrap_or("")
            ),
            MAX_SUMMARY_CHARS,
        );
    }
    let body = stdout.trim();
    if !body.is_empty() {
        return truncate_chars(body, MAX_SUMMARY_CHARS);
    }
    let err = stderr.trim();
    if !err.is_empty() {
        return truncate_chars(err, MAX_SUMMARY_CHARS);
    }
    match exit_code {
        Some(0) => "OpenCode finished successfully.".into(),
        Some(code) => format!("OpenCode exited with code {code}."),
        None => "OpenCode finished.".into(),
    }
}

fn extract_tests_excerpt(stdout: &str) -> Option<String> {
    let mut hits = Vec::new();
    for line in stdout.lines() {
        let l = line.trim();
        let lower = l.to_ascii_lowercase();
        if lower.contains("test result:")
            || lower.contains("passed")
            || lower.contains("failed")
            || lower.contains("cargo test")
            || lower.contains("npm test")
            || lower.contains("pytest")
        {
            hits.push(l.to_string());
        }
        if hits.len() >= 8 {
            break;
        }
    }
    if hits.is_empty() {
        None
    } else {
        Some(hits.join("\n"))
    }
}

fn truncate_chars(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
    out.push('…');
    out
}

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

    #[test]
    fn detects_missing_binary() {
        let cfg = ExecutorConfig {
            kind: "opencode".into(),
            command: "opencode-not-installed-agentbridge-xyz".into(),
            mode: ExecutorMode::Silent,
        };
        let exec = OpenCodeExecutor::from_config(&cfg).unwrap();
        let err = exec.detect().unwrap_err();
        assert!(matches!(err, ExecutorError::NotInstalled(_)));
        assert!(err.to_string().contains("not installed"));
    }

    #[test]
    fn rejects_unimplemented_types() {
        let err = validate_executor_type("codex").unwrap_err();
        assert!(matches!(err, ExecutorError::TypeNotImplemented(_)));
        let err = validate_executor_type("not-a-real-agent").unwrap_err();
        assert!(matches!(err, ExecutorError::TypeNotAllowed(_)));
        validate_executor_type("opencode").unwrap();
    }

    #[test]
    fn finds_git_on_path() {
        assert!(find_executable("git").is_some());
    }

    #[test]
    fn strip_reasoning_drops_think_blocks() {
        let raw = "<think>\nsecret chain of thought\n</think>\ncreated TEST.md\n";
        let out = strip_reasoning(raw);
        assert!(!out.contains("chain of thought"));
        assert!(out.contains("created TEST.md"));
    }
}