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 "--".into(),
283 prompt,
284 ],
285 "codex-jsonl",
286 ),
287 ExternalHarness::Claude => (
288 vec![
289 "--print".into(),
290 "--output-format".into(),
291 "stream-json".into(),
292 "--no-session-persistence".into(),
293 "--permission-mode".into(),
294 match sandbox {
295 ExternalSandbox::ReadOnly => "plan".into(),
296 ExternalSandbox::WorkspaceWrite => "acceptEdits".into(),
297 },
298 "--add-dir".into(),
299 root,
300 "--".into(),
301 prompt,
302 ],
303 "claude-stream-json",
304 ),
305 ExternalHarness::OpenCode => {
306 let mut args = vec![
307 "run".into(),
308 "--format".into(),
309 "json".into(),
310 "--pure".into(),
311 ];
312 if sandbox == ExternalSandbox::ReadOnly {
313 args.extend(["--agent".into(), "plan".into()]);
314 }
315 args.extend(["--dir".into(), root, "--".into(), prompt]);
316 (args, "opencode-json")
317 }
318 };
319 ExternalInvocation {
320 program: executable,
321 args,
322 transport,
323 }
324}
325
326#[derive(Debug, Clone, Copy)]
327enum StreamKind {
328 Stdout,
329 Stderr,
330}
331
332fn spawn_reader<R: Read + Send + 'static>(
333 mut reader: R,
334 kind: StreamKind,
335 sender: Sender<(StreamKind, Vec<u8>)>,
336 limit: usize,
337) -> JoinHandle<()> {
338 thread::spawn(move || {
339 let mut buffer = [0_u8; 8192];
340 let mut read = 0;
341 loop {
342 if read >= limit {
343 break;
344 }
345 let read_limit = (limit - read).min(buffer.len());
346 let length = match reader.read(&mut buffer[..read_limit]) {
347 Ok(0) => break,
348 Ok(length) => length,
349 Err(_) => break,
350 };
351 read += length;
352 if sender.send((kind, buffer[..length].to_vec())).is_err() {
353 break;
354 }
355 }
356 })
357}
358
359fn drain_chunks(
360 receiver: &Receiver<(StreamKind, Vec<u8>)>,
361 stdout: &mut Vec<u8>,
362 stderr: &mut Vec<u8>,
363 stdout_truncated: &mut bool,
364 stderr_truncated: &mut bool,
365) {
366 while let Ok((kind, chunk)) = receiver.try_recv() {
367 append_chunk(
368 kind,
369 &chunk,
370 stdout,
371 stderr,
372 stdout_truncated,
373 stderr_truncated,
374 );
375 }
376}
377
378fn append_chunk(
379 kind: StreamKind,
380 chunk: &[u8],
381 stdout: &mut Vec<u8>,
382 stderr: &mut Vec<u8>,
383 stdout_truncated: &mut bool,
384 stderr_truncated: &mut bool,
385) {
386 let (target, truncated, limit) = match kind {
387 StreamKind::Stdout => (stdout, stdout_truncated, MAX_STDOUT_BYTES),
388 StreamKind::Stderr => (stderr, stderr_truncated, MAX_STDERR_BYTES),
389 };
390 if target.len() >= limit {
391 *truncated = true;
392 return;
393 }
394 let remaining = limit - target.len();
395 if chunk.len() > remaining {
396 target.extend_from_slice(&chunk[..remaining]);
397 *truncated = true;
398 } else {
399 target.extend_from_slice(chunk);
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 #[test]
408 fn parses_only_supported_temporary_harnesses() {
409 assert!(ExternalHarness::parse("Codex CLI").is_err());
410 assert_eq!(ExternalHarness::parse("codex-cli").unwrap().id(), "codex");
411 assert_eq!(
412 ExternalHarness::parse("claude-code").unwrap().id(),
413 "claude"
414 );
415 assert_eq!(
416 ExternalHarness::parse("open-code").unwrap().id(),
417 "opencode"
418 );
419 assert!(ExternalHarness::parse("aider").is_err());
420 }
421
422 #[test]
423 fn invocation_keeps_prompt_and_root_as_single_arguments() {
424 let invocation = build_invocation(
425 ExternalHarness::Codex,
426 PathBuf::from("/bin/codex"),
427 Path::new("/tmp/project with spaces"),
428 "inspect && do not mutate",
429 ExternalSandbox::ReadOnly,
430 );
431 assert_eq!(invocation.program, PathBuf::from("/bin/codex"));
432 assert_eq!(invocation.transport, "codex-jsonl");
433 assert!(
434 invocation
435 .args
436 .windows(2)
437 .any(|pair| pair[0] == "--cd" && pair[1] == "/tmp/project with spaces")
438 );
439 assert_eq!(
440 invocation.args.last(),
441 Some(&OsString::from("inspect && do not mutate"))
442 );
443 assert!(
444 invocation
445 .args
446 .windows(2)
447 .any(|pair| pair[0] == "--" && pair[1] == "inspect && do not mutate")
448 );
449 }
450
451 #[test]
452 fn claude_prompt_is_positional_after_end_of_options() {
453 let invocation = build_invocation(
454 ExternalHarness::Claude,
455 PathBuf::from("/bin/claude"),
456 Path::new("/tmp/project with spaces"),
457 "--dangerously-skip-permissions",
458 ExternalSandbox::ReadOnly,
459 );
460 assert!(
461 invocation
462 .args
463 .windows(2)
464 .any(|pair| pair[0] == "--add-dir" && pair[1] == "/tmp/project with spaces")
465 );
466 assert!(
467 invocation
468 .args
469 .windows(2)
470 .any(|pair| pair[0] == "--" && pair[1] == "--dangerously-skip-permissions")
471 );
472 assert_eq!(
473 invocation.args.last(),
474 Some(&OsString::from("--dangerously-skip-permissions"))
475 );
476 }
477
478 #[test]
479 fn readonly_opencode_uses_plan_agent() {
480 let read_only = build_invocation(
481 ExternalHarness::OpenCode,
482 PathBuf::from("/bin/opencode"),
483 Path::new("/tmp/project"),
484 "inspect the project",
485 ExternalSandbox::ReadOnly,
486 );
487 assert!(
488 read_only
489 .args
490 .windows(2)
491 .any(|pair| pair[0] == "--agent" && pair[1] == "plan")
492 );
493
494 let workspace_write = build_invocation(
495 ExternalHarness::OpenCode,
496 PathBuf::from("/bin/opencode"),
497 Path::new("/tmp/project"),
498 "update the project",
499 ExternalSandbox::WorkspaceWrite,
500 );
501 assert!(
502 !workspace_write
503 .args
504 .windows(2)
505 .any(|pair| pair[0] == "--agent" && pair[1] == "plan")
506 );
507 }
508
509 #[test]
510 fn reader_stops_at_stream_limit() {
511 let (sender, receiver) = mpsc::channel();
512 let reader = spawn_reader(
513 std::io::Cursor::new(vec![0_u8; MAX_STDOUT_BYTES + 1]),
514 StreamKind::Stdout,
515 sender,
516 MAX_STDOUT_BYTES,
517 );
518
519 reader.join().expect("reader thread should finish");
520 let received = receiver
521 .into_iter()
522 .map(|(_, chunk)| chunk.len())
523 .sum::<usize>();
524 assert_eq!(received, MAX_STDOUT_BYTES);
525 }
526 #[test]
527 fn timeout_must_be_at_least_one_second() {
528 let request = ExternalAgentRequest {
529 harness: "codex".into(),
530 root: PathBuf::from("."),
531 prompt: "inspect the project".into(),
532 sandbox: ExternalSandbox::ReadOnly,
533 timeout: Duration::from_millis(999),
534 allow_mutation: false,
535 };
536 assert!(
537 validate_request(&request)
538 .expect_err("subsecond timeouts must fail")
539 .contains("between 1 second and 1 hour")
540 );
541 }
542
543 #[test]
544 fn workspace_write_requires_authority() {
545 let request = ExternalAgentRequest {
546 harness: "codex".into(),
547 root: PathBuf::from("."),
548 prompt: "edit the failing test".into(),
549 sandbox: ExternalSandbox::WorkspaceWrite,
550 timeout: Duration::from_secs(30),
551 allow_mutation: false,
552 };
553 assert!(
554 validate_request(&request)
555 .expect_err("workspace writes without authority must fail")
556 .contains("explicit mutation authority")
557 );
558 }
559}