1use crate::harness;
8use serde::Serialize;
9use std::ffi::OsString;
10use std::fs;
11use std::io::Read;
12use std::path::{Path, PathBuf};
13use std::process::{Command, Stdio};
14use std::sync::mpsc::{self, Receiver, Sender};
15use std::thread::{self, JoinHandle};
16use std::time::{Duration, Instant};
17
18pub const DEFAULT_TIMEOUT_SECS: u64 = 600;
19const MIN_TIMEOUT: Duration = Duration::from_secs(1);
20const MAX_PROMPT_BYTES: usize = 64 * 1024;
21const MAX_STDOUT_BYTES: usize = 256 * 1024;
22const MAX_STDERR_BYTES: usize = 64 * 1024;
23const MAX_TIMEOUT: Duration = Duration::from_secs(60 * 60);
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ExternalHarness {
27 Codex,
28 Claude,
29 OpenCode,
30}
31
32impl ExternalHarness {
33 pub fn parse(name: &str) -> Result<Self, String> {
34 match name.trim().to_ascii_lowercase().as_str() {
35 "codex" | "codex-cli" => Ok(Self::Codex),
36 "claude" | "claude-code" => Ok(Self::Claude),
37 "opencode" | "open-code" => Ok(Self::OpenCode),
38 _ => Err(format!(
39 "unsupported temporary agent `{name}`; choose codex, claude, or opencode"
40 )),
41 }
42 }
43
44 pub const fn id(self) -> &'static str {
45 match self {
46 Self::Codex => "codex",
47 Self::Claude => "claude",
48 Self::OpenCode => "opencode",
49 }
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
54#[serde(rename_all = "kebab-case")]
55pub enum ExternalSandbox {
56 ReadOnly,
57 WorkspaceWrite,
58}
59
60impl ExternalSandbox {
61 pub fn parse(value: &str) -> Result<Self, String> {
62 match value.trim().to_ascii_lowercase().as_str() {
63 "read-only" | "readonly" | "read_only" => Ok(Self::ReadOnly),
64 "workspace-write" | "workspacewrite" | "workspace_write" => Ok(Self::WorkspaceWrite),
65 _ => Err(format!(
66 "unsupported temporary-agent sandbox `{value}`; choose read-only or workspace-write"
67 )),
68 }
69 }
70
71 pub const fn id(self) -> &'static str {
72 match self {
73 Self::ReadOnly => "read-only",
74 Self::WorkspaceWrite => "workspace-write",
75 }
76 }
77}
78
79#[derive(Debug, Clone)]
80pub struct ExternalAgentRequest {
81 pub harness: String,
82 pub root: PathBuf,
83 pub prompt: String,
84 pub sandbox: ExternalSandbox,
85 pub timeout: Duration,
86 pub allow_mutation: bool,
87}
88
89#[derive(Debug, Clone, Serialize)]
90#[serde(rename_all = "camelCase")]
91pub struct ExternalAgentResult {
92 pub harness: String,
93 pub transport: String,
94 pub sandbox: ExternalSandbox,
95 pub success: bool,
96 pub status: Option<i32>,
97 pub timed_out: bool,
98 pub duration_ms: u64,
99 pub output: String,
100 pub stderr: String,
101 pub output_truncated: bool,
102 pub stderr_truncated: bool,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub(crate) struct ExternalInvocation {
107 pub program: PathBuf,
108 pub args: Vec<OsString>,
109 pub transport: &'static str,
110}
111
112pub fn delegate(request: ExternalAgentRequest) -> Result<ExternalAgentResult, String> {
114 validate_request(&request)?;
115 let root = fs::canonicalize(&request.root).map_err(|error| {
116 format!(
117 "could not resolve delegation root {}: {error}",
118 request.root.display()
119 )
120 })?;
121 if !root.is_dir() {
122 return Err(format!(
123 "delegation root is not a directory: {}",
124 root.display()
125 ));
126 }
127
128 let harness = ExternalHarness::parse(&request.harness)?;
129 let resolved = harness::resolve(harness.id())?;
130 let invocation = build_invocation(
131 harness,
132 resolved.path,
133 &root,
134 &request.prompt,
135 request.sandbox,
136 );
137
138 let mut command = Command::new(&invocation.program);
139 command
140 .args(&invocation.args)
141 .current_dir(&root)
142 .stdin(Stdio::null())
143 .stdout(Stdio::piped())
144 .stderr(Stdio::piped());
145 let started = Instant::now();
146 let mut child = command
147 .spawn()
148 .map_err(|error| format!("could not start {}: {error}", harness.id()))?;
149 let stdout = match child.stdout.take() {
150 Some(stdout) => stdout,
151 None => {
152 let _ = child.kill();
153 let _ = child.wait();
154 return Err(format!("{} did not expose stdout", harness.id()));
155 }
156 };
157 let stderr = match child.stderr.take() {
158 Some(stderr) => stderr,
159 None => {
160 let _ = child.kill();
161 let _ = child.wait();
162 return Err(format!("{} did not expose stderr", harness.id()));
163 }
164 };
165 let (sender, receiver) = mpsc::channel();
166 let stdout_thread = spawn_reader(stdout, StreamKind::Stdout, sender.clone(), MAX_STDOUT_BYTES);
167
168 let stderr_thread = spawn_reader(stderr, StreamKind::Stderr, sender.clone(), MAX_STDERR_BYTES);
169 drop(sender);
170
171 let mut stdout_bytes = Vec::new();
172 let mut stderr_bytes = Vec::new();
173 let mut stdout_truncated = false;
174 let mut stderr_truncated = false;
175 let mut timed_out = false;
176 let status = loop {
177 drain_chunks(
178 &receiver,
179 &mut stdout_bytes,
180 &mut stderr_bytes,
181 &mut stdout_truncated,
182 &mut stderr_truncated,
183 );
184 if let Some(status) = child
185 .try_wait()
186 .map_err(|error| format!("could not poll {}: {error}", harness.id()))?
187 {
188 break Some(status);
189 }
190 if started.elapsed() >= request.timeout {
191 timed_out = true;
192 let _ = child.kill();
193 break child.wait().ok();
194 }
195 match receiver.recv_timeout(Duration::from_millis(20)) {
196 Ok((kind, chunk)) => append_chunk(
197 kind,
198 &chunk,
199 &mut stdout_bytes,
200 &mut stderr_bytes,
201 &mut stdout_truncated,
202 &mut stderr_truncated,
203 ),
204 Err(mpsc::RecvTimeoutError::Timeout) => {}
205 Err(mpsc::RecvTimeoutError::Disconnected) => {
206 }
209 }
210 };
211
212 let _ = stdout_thread.join();
213 let _ = stderr_thread.join();
214 drain_chunks(
215 &receiver,
216 &mut stdout_bytes,
217 &mut stderr_bytes,
218 &mut stdout_truncated,
219 &mut stderr_truncated,
220 );
221
222 Ok(ExternalAgentResult {
223 harness: harness.id().into(),
224 transport: invocation.transport.into(),
225 sandbox: request.sandbox,
226 success: !timed_out && status.is_some_and(|status| status.success()),
227 status: status.and_then(|status| status.code()),
228 timed_out,
229 duration_ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
230 output: String::from_utf8_lossy(&stdout_bytes).into_owned(),
231 stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
232 output_truncated: stdout_truncated,
233 stderr_truncated,
234 })
235}
236
237fn validate_request(request: &ExternalAgentRequest) -> Result<(), String> {
238 if request.prompt.trim().is_empty() {
239 return Err("temporary-agent prompt must not be empty".into());
240 }
241 if request.prompt.contains('\0') {
242 return Err("temporary-agent prompt contains a NUL byte".into());
243 }
244 if request.prompt.len() > MAX_PROMPT_BYTES {
245 return Err(format!(
246 "temporary-agent prompt exceeds the {MAX_PROMPT_BYTES}-byte limit"
247 ));
248 }
249 if request.timeout < MIN_TIMEOUT || request.timeout > MAX_TIMEOUT {
250 return Err("temporary-agent timeout must be between 1 second and 1 hour".into());
251 }
252 if request.sandbox == ExternalSandbox::WorkspaceWrite && !request.allow_mutation {
253 return Err(
254 "workspace-write delegation requires explicit mutation authority and confirmation"
255 .into(),
256 );
257 }
258 Ok(())
259}
260
261pub(crate) fn build_invocation(
262 harness: ExternalHarness,
263 executable: PathBuf,
264 root: &Path,
265 prompt: &str,
266 sandbox: ExternalSandbox,
267) -> ExternalInvocation {
268 let root = root.as_os_str().to_os_string();
269 let prompt = OsString::from(prompt);
270 let (args, transport) = match harness {
271 ExternalHarness::Codex => (
272 vec![
273 "exec".into(),
274 "--json".into(),
275 "--ephemeral".into(),
276 "--color".into(),
277 "never".into(),
278 "--sandbox".into(),
279 sandbox.id().into(),
280 "--cd".into(),
281 root,
282 prompt,
283 ],
284 "codex-jsonl",
285 ),
286 ExternalHarness::Claude => (
287 vec![
288 "--print".into(),
289 "--output-format".into(),
290 "stream-json".into(),
291 "--no-session-persistence".into(),
292 "--permission-mode".into(),
293 match sandbox {
294 ExternalSandbox::ReadOnly => "plan".into(),
295 ExternalSandbox::WorkspaceWrite => "acceptEdits".into(),
296 },
297 prompt,
298 "--add-dir".into(),
299 root,
300 ],
301 "claude-stream-json",
302 ),
303 ExternalHarness::OpenCode => {
304 let mut args = vec![
305 "run".into(),
306 "--format".into(),
307 "json".into(),
308 "--pure".into(),
309 ];
310 if sandbox == ExternalSandbox::ReadOnly {
311 args.extend(["--agent".into(), "plan".into()]);
312 }
313 args.extend(["--dir".into(), root, prompt]);
314 (args, "opencode-json")
315 }
316 };
317 ExternalInvocation {
318 program: executable,
319 args,
320 transport,
321 }
322}
323
324#[derive(Debug, Clone, Copy)]
325enum StreamKind {
326 Stdout,
327 Stderr,
328}
329
330fn spawn_reader<R: Read + Send + 'static>(
331 mut reader: R,
332 kind: StreamKind,
333 sender: Sender<(StreamKind, Vec<u8>)>,
334 limit: usize,
335) -> JoinHandle<()> {
336 thread::spawn(move || {
337 let mut buffer = [0_u8; 8192];
338 let mut read = 0;
339 loop {
340 if read >= limit {
341 break;
342 }
343 let read_limit = (limit - read).min(buffer.len());
344 let length = match reader.read(&mut buffer[..read_limit]) {
345 Ok(0) => break,
346 Ok(length) => length,
347 Err(_) => break,
348 };
349 read += length;
350 if sender.send((kind, buffer[..length].to_vec())).is_err() {
351 break;
352 }
353 }
354 })
355}
356
357fn drain_chunks(
358 receiver: &Receiver<(StreamKind, Vec<u8>)>,
359 stdout: &mut Vec<u8>,
360 stderr: &mut Vec<u8>,
361 stdout_truncated: &mut bool,
362 stderr_truncated: &mut bool,
363) {
364 while let Ok((kind, chunk)) = receiver.try_recv() {
365 append_chunk(
366 kind,
367 &chunk,
368 stdout,
369 stderr,
370 stdout_truncated,
371 stderr_truncated,
372 );
373 }
374}
375
376fn append_chunk(
377 kind: StreamKind,
378 chunk: &[u8],
379 stdout: &mut Vec<u8>,
380 stderr: &mut Vec<u8>,
381 stdout_truncated: &mut bool,
382 stderr_truncated: &mut bool,
383) {
384 let (target, truncated, limit) = match kind {
385 StreamKind::Stdout => (stdout, stdout_truncated, MAX_STDOUT_BYTES),
386 StreamKind::Stderr => (stderr, stderr_truncated, MAX_STDERR_BYTES),
387 };
388 if target.len() >= limit {
389 *truncated = true;
390 return;
391 }
392 let remaining = limit - target.len();
393 if chunk.len() > remaining {
394 target.extend_from_slice(&chunk[..remaining]);
395 *truncated = true;
396 } else {
397 target.extend_from_slice(chunk);
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 #[test]
406 fn parses_only_supported_temporary_harnesses() {
407 assert!(ExternalHarness::parse("Codex CLI").is_err());
408 assert_eq!(ExternalHarness::parse("codex-cli").unwrap().id(), "codex");
409 assert_eq!(
410 ExternalHarness::parse("claude-code").unwrap().id(),
411 "claude"
412 );
413 assert_eq!(
414 ExternalHarness::parse("open-code").unwrap().id(),
415 "opencode"
416 );
417 assert!(ExternalHarness::parse("aider").is_err());
418 }
419
420 #[test]
421 fn invocation_keeps_prompt_and_root_as_single_arguments() {
422 let invocation = build_invocation(
423 ExternalHarness::Codex,
424 PathBuf::from("/bin/codex"),
425 Path::new("/tmp/project with spaces"),
426 "inspect && do not mutate",
427 ExternalSandbox::ReadOnly,
428 );
429 assert_eq!(invocation.program, PathBuf::from("/bin/codex"));
430 assert_eq!(invocation.transport, "codex-jsonl");
431 assert!(
432 invocation
433 .args
434 .windows(2)
435 .any(|pair| pair[0] == "--cd" && pair[1] == "/tmp/project with spaces")
436 );
437 assert_eq!(
438 invocation.args.last(),
439 Some(&OsString::from("inspect && do not mutate"))
440 );
441 }
442
443 #[test]
444 fn claude_prompt_precedes_greedy_add_dir_arguments() {
445 let invocation = build_invocation(
446 ExternalHarness::Claude,
447 PathBuf::from("/bin/claude"),
448 Path::new("/tmp/project with spaces"),
449 "inspect && do not mutate",
450 ExternalSandbox::ReadOnly,
451 );
452 assert!(
453 invocation
454 .args
455 .windows(2)
456 .any(|pair| pair[0] == "inspect && do not mutate" && pair[1] == "--add-dir")
457 );
458 assert_eq!(
459 invocation.args.last(),
460 Some(&OsString::from("/tmp/project with spaces"))
461 );
462 }
463
464 #[test]
465 fn readonly_opencode_uses_plan_agent() {
466 let read_only = build_invocation(
467 ExternalHarness::OpenCode,
468 PathBuf::from("/bin/opencode"),
469 Path::new("/tmp/project"),
470 "inspect the project",
471 ExternalSandbox::ReadOnly,
472 );
473 assert!(
474 read_only
475 .args
476 .windows(2)
477 .any(|pair| pair[0] == "--agent" && pair[1] == "plan")
478 );
479
480 let workspace_write = build_invocation(
481 ExternalHarness::OpenCode,
482 PathBuf::from("/bin/opencode"),
483 Path::new("/tmp/project"),
484 "update the project",
485 ExternalSandbox::WorkspaceWrite,
486 );
487 assert!(
488 !workspace_write
489 .args
490 .windows(2)
491 .any(|pair| pair[0] == "--agent" && pair[1] == "plan")
492 );
493 }
494
495 #[test]
496 fn reader_stops_at_stream_limit() {
497 let (sender, receiver) = mpsc::channel();
498 let reader = spawn_reader(
499 std::io::Cursor::new(vec![0_u8; MAX_STDOUT_BYTES + 1]),
500 StreamKind::Stdout,
501 sender,
502 MAX_STDOUT_BYTES,
503 );
504
505 reader.join().expect("reader thread should finish");
506 let received = receiver
507 .into_iter()
508 .map(|(_, chunk)| chunk.len())
509 .sum::<usize>();
510 assert_eq!(received, MAX_STDOUT_BYTES);
511 }
512 #[test]
513 fn timeout_must_be_at_least_one_second() {
514 let request = ExternalAgentRequest {
515 harness: "codex".into(),
516 root: PathBuf::from("."),
517 prompt: "inspect the project".into(),
518 sandbox: ExternalSandbox::ReadOnly,
519 timeout: Duration::from_millis(999),
520 allow_mutation: false,
521 };
522 assert!(
523 validate_request(&request)
524 .expect_err("subsecond timeouts must fail")
525 .contains("between 1 second and 1 hour")
526 );
527 }
528
529 #[test]
530 fn workspace_write_requires_authority() {
531 let request = ExternalAgentRequest {
532 harness: "codex".into(),
533 root: PathBuf::from("."),
534 prompt: "edit the failing test".into(),
535 sandbox: ExternalSandbox::WorkspaceWrite,
536 timeout: Duration::from_secs(30),
537 allow_mutation: false,
538 };
539 assert!(
540 validate_request(&request)
541 .expect_err("workspace writes without authority must fail")
542 .contains("explicit mutation authority")
543 );
544 }
545}