orch-cli 0.88.4

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
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
//! Integration tests that invoke real agent CLIs.
//!
//! These tests are `#[ignore]`d by default — they need real API keys,
//! installed CLIs, and cost money to run.
//!
//! Run all locally:
//! ```bash
//! cargo test --test integration_agents -- --ignored --nocapture
//! ```
//!
//! Run a single agent:
//! ```bash
//! cargo test --test integration_agents claude -- --ignored --nocapture
//! cargo test --test integration_agents codex -- --ignored --nocapture
//! cargo test --test integration_agents opencode -- --ignored --nocapture
//! cargo test --test integration_agents kimi -- --ignored --nocapture
//! cargo test --test integration_agents minimax -- --ignored --nocapture
//! cargo test --test integration_agents router -- --ignored --nocapture
//! ```

use std::process::Command;

/// Simple prompt that should produce a parseable JSON response.
const SIMPLE_PROMPT: &str = r#"Reply with ONLY this JSON, no markdown, no explanation:
{"status":"done","summary":"integration test","accomplished":["replied"],"remaining":[],"files":[]}"#;

fn is_available(binary: &str) -> bool {
    which::which(binary).is_ok()
}

/// Build a Command with CLAUDECODE unset so claude-based agents don't
/// refuse to run when tests are launched from inside a Claude Code session.
fn agent_cmd(binary: &str) -> Command {
    let mut cmd = Command::new(binary);
    cmd.env_remove("CLAUDECODE");
    cmd
}

/// Assert a Claude JSON envelope is valid and extract the inner result.
fn assert_claude_envelope(stdout: &str) -> String {
    let val: serde_json::Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("not valid JSON: {e}\nraw: {stdout}"));

    assert_eq!(
        val.get("type").and_then(|v| v.as_str()),
        Some("result"),
        "expected Claude envelope with type=result, got: {val}"
    );

    let is_error = val
        .get("is_error")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    assert!(!is_error, "Claude envelope has is_error=true: {val}");

    val.get("result")
        .and_then(|v| v.as_str())
        .expect("envelope missing 'result' field")
        .to_string()
}

/// Assert NDJSON stream has at least one valid line, return all parsed events.
fn assert_ndjson(stdout: &str) -> Vec<serde_json::Value> {
    let mut events = Vec::new();
    for line in stdout.lines() {
        if line.trim().is_empty() {
            continue;
        }
        match serde_json::from_str::<serde_json::Value>(line) {
            Ok(val) => {
                let event_type = val.get("type").and_then(|v| v.as_str()).unwrap_or("?");
                eprintln!("  event: {event_type}");
                events.push(val);
            }
            Err(e) => {
                eprintln!("  unparseable: {e}: {}", &line[..line.len().min(100)]);
            }
        }
    }
    assert!(!events.is_empty(), "no valid NDJSON lines in output");
    events
}

fn codex_completed_with_benign_shutdown_error(events: &[serde_json::Value]) -> bool {
    let has_agent_message = events.iter().any(|e| {
        e.get("type").and_then(|v| v.as_str()) == Some("item.completed")
            && e.get("item")
                .and_then(|i| i.get("type"))
                .and_then(|v| v.as_str())
                == Some("agent_message")
    });

    let has_turn_completed = events
        .iter()
        .any(|e| e.get("type").and_then(|v| v.as_str()) == Some("turn.completed"));

    let has_only_benign_error = events.iter().all(|e| {
        if e.get("type").and_then(|v| v.as_str()) != Some("error") {
            return true;
        }
        e.get("message").and_then(|v| v.as_str()) == Some("Failed to shutdown rollout recorder")
    });

    has_agent_message && has_turn_completed && has_only_benign_error
}

fn kimi_has_quota_error(stdout: &str) -> bool {
    let Ok(val) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {
        return false;
    };

    let is_error = val
        .get("is_error")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let result = val.get("result").and_then(|v| v.as_str()).unwrap_or("");

    is_error
        && (result.contains("\"type\":\"permission_error\"")
            || result.contains("usage limit")
            || result.contains("quota"))
}

// ── Claude ────────────────────────────────────────────────────────

#[test]
#[ignore]
fn claude_responds_with_json_envelope() {
    if !is_available("claude") {
        eprintln!("SKIP: claude not in PATH");
        return;
    }

    let output = agent_cmd("claude")
        .args([
            "--output-format",
            "json",
            "--print",
            "--model",
            "haiku",
            SIMPLE_PROMPT,
        ])
        .output()
        .expect("failed to execute claude");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes): {}",
        stdout.len(),
        &stdout[..stdout.len().min(500)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    assert!(output.status.success(), "claude failed: {stderr}");
    assert!(!stdout.is_empty(), "claude returned empty stdout");

    let result = assert_claude_envelope(&stdout);
    eprintln!("inner result: {result}");

    // Inner result should contain our JSON response
    assert!(
        result.contains("status") || result.contains("done"),
        "result doesn't look like expected JSON: {result}"
    );
}

#[test]
#[ignore]
fn claude_stdin_pipe_mode() {
    if !is_available("claude") {
        eprintln!("SKIP: claude not in PATH");
        return;
    }

    // Test -p with stdin redirect — matches real task agent invocation
    let output = agent_cmd("claude")
        .args(["-p", "--model", "haiku", "--output-format", "json"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            if let Some(ref mut stdin) = child.stdin {
                stdin.write_all(SIMPLE_PROMPT.as_bytes()).ok();
            }
            drop(child.stdin.take()); // close stdin
            child.wait_with_output()
        })
        .expect("failed to execute claude");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes): {}",
        stdout.len(),
        &stdout[..stdout.len().min(500)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    assert!(output.status.success(), "claude -p failed: {stderr}");
    assert!(!stdout.is_empty(), "claude -p returned empty stdout");

    let result = assert_claude_envelope(&stdout);
    eprintln!("inner result: {result}");
}

// ── Codex ─────────────────────────────────────────────────────────

#[test]
#[ignore]
fn codex_responds_with_ndjson() {
    if !is_available("codex") {
        eprintln!("SKIP: codex not in PATH");
        return;
    }

    let output = agent_cmd("codex")
        .args(["--full-auto", "exec", "--json", SIMPLE_PROMPT])
        .output()
        .expect("failed to execute codex");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes):\n{}",
        stdout.len(),
        &stdout[..stdout.len().min(1000)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    let events = assert_ndjson(&stdout);
    if !output.status.success() && codex_completed_with_benign_shutdown_error(&events) {
        eprintln!("SKIP: codex exited non-zero due benign rollout recorder shutdown error");
        return;
    }

    assert!(output.status.success(), "codex failed: {stderr}");
    assert!(!stdout.is_empty(), "codex returned empty stdout");

    // Check for error events
    let errors: Vec<_> = events
        .iter()
        .filter(|e| {
            let t = e.get("type").and_then(|v| v.as_str()).unwrap_or("");
            t == "error" || t == "turn.failed"
        })
        .collect();

    if !errors.is_empty() {
        for err in &errors {
            eprintln!("  ERROR EVENT: {err}");
        }
        panic!("codex returned error events");
    }

    // Should have an agent_message
    let has_message = events.iter().any(|e| {
        e.get("type").and_then(|v| v.as_str()) == Some("item.completed")
            && e.get("item")
                .and_then(|i| i.get("type"))
                .and_then(|v| v.as_str())
                == Some("agent_message")
    });
    assert!(has_message, "codex produced no agent_message events");
}

#[test]
#[ignore]
fn codex_stdin_pipe_mode() {
    if !is_available("codex") {
        eprintln!("SKIP: codex not in PATH");
        return;
    }

    // Test piped stdin — matches real task invocation: cat msg | codex ... exec --json -
    let output = agent_cmd("codex")
        .args(["--full-auto", "exec", "--json", "-"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            if let Some(ref mut stdin) = child.stdin {
                stdin.write_all(SIMPLE_PROMPT.as_bytes()).ok();
            }
            drop(child.stdin.take());
            child.wait_with_output()
        })
        .expect("failed to execute codex");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes):\n{}",
        stdout.len(),
        &stdout[..stdout.len().min(1000)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    let events = assert_ndjson(&stdout);
    if !output.status.success() && codex_completed_with_benign_shutdown_error(&events) {
        eprintln!("SKIP: codex stdin exited non-zero due benign rollout recorder shutdown error");
        return;
    }

    assert!(output.status.success(), "codex stdin failed: {stderr}");
    assert!(!stdout.is_empty(), "codex stdin returned empty stdout");

    // Parse again to keep parity with non-stdin test behavior.
    let errors: Vec<_> = events
        .iter()
        .filter(|e| {
            let t = e.get("type").and_then(|v| v.as_str()).unwrap_or("");
            t == "error" || t == "turn.failed"
        })
        .collect();
    if !errors.is_empty() {
        for err in &errors {
            eprintln!("  ERROR EVENT: {err}");
        }
        panic!("codex stdin returned error events");
    }
}

// ── OpenCode ──────────────────────────────────────────────────────

#[test]
#[ignore]
fn opencode_responds_with_ndjson() {
    if !is_available("opencode") {
        eprintln!("SKIP: opencode not in PATH");
        return;
    }

    let output = agent_cmd("opencode")
        .args(["run", "--format", "json", SIMPLE_PROMPT])
        .output()
        .expect("failed to execute opencode");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes):\n{}",
        stdout.len(),
        &stdout[..stdout.len().min(1000)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    if !output.status.success() && stderr.contains("attempt to write a readonly database") {
        eprintln!("SKIP: opencode database path is readonly in this environment");
        return;
    }

    assert!(output.status.success(), "opencode failed: {stderr}");
    assert!(!stdout.is_empty(), "opencode returned empty stdout");
    assert_ndjson(&stdout);
}

/// OpenCode with `.opencode/config.json` permission config — the same
/// prompt that fails with "user rejected permission" without the config
/// should succeed when permissions are pre-allowed (as orch's runner does).
#[test]
#[ignore]
fn opencode_with_permission_config_succeeds() {
    if !is_available("opencode") {
        eprintln!("SKIP: opencode not in PATH");
        return;
    }

    // Create a temp workdir with .opencode/config.json (same as build_command generates)
    let workdir = tempfile::tempdir().expect("failed to create tempdir");
    let config_dir = workdir.path().join(".opencode");
    std::fs::create_dir_all(&config_dir).expect("failed to create .opencode dir");
    std::fs::write(
        config_dir.join("config.json"),
        r#"{"permission":{"read":"allow","edit":"allow","glob":"allow","grep":"allow","bash":"allow","task":"allow","skill":"allow","webfetch":"allow","websearch":"allow","list":"allow","todowrite":"allow","todoread":"allow","question":"allow","codesearch":"allow"}}"#,
    )
    .expect("failed to write config.json");

    let output = agent_cmd("opencode")
        .current_dir(workdir.path())
        .args(["run", "--format", "json", SIMPLE_PROMPT])
        .output()
        .expect("failed to execute opencode");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes):\n{}",
        stdout.len(),
        &stdout[..stdout.len().min(1000)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    if !output.status.success() && stderr.contains("attempt to write a readonly database") {
        eprintln!("SKIP: opencode database path is readonly in this environment");
        return;
    }

    assert!(
        output.status.success(),
        "opencode with permission config failed: {stderr}"
    );
    assert!(
        !stdout.is_empty(),
        "opencode with permission config returned empty stdout"
    );

    let events = assert_ndjson(&stdout);

    // Should NOT have permission denial errors
    let has_permission_error = events.iter().any(|e| {
        let msg = e
            .get("error")
            .and_then(|err| err.get("name"))
            .and_then(|v| v.as_str())
            .unwrap_or("");
        msg.contains("Permission")
    });
    assert!(
        !has_permission_error,
        "opencode still denied permissions despite config"
    );
}

// ── Kimi ──────────────────────────────────────────────────────────

#[test]
#[ignore]
fn kimi_responds_like_claude() {
    if !is_available("kimi") {
        eprintln!("SKIP: kimi not in PATH");
        return;
    }

    let output = agent_cmd("kimi")
        .args([
            "-p",
            "--output-format",
            "json",
            "--model",
            "haiku",
            SIMPLE_PROMPT,
        ])
        .output()
        .expect("failed to execute kimi");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes): {}",
        stdout.len(),
        &stdout[..stdout.len().min(500)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    if !output.status.success() && kimi_has_quota_error(&stdout) {
        eprintln!("SKIP: kimi account quota/permission limit in this environment");
        return;
    }

    assert!(output.status.success(), "kimi failed: {stderr}");
    assert!(!stdout.is_empty(), "kimi returned empty stdout");

    let result = assert_claude_envelope(&stdout);
    eprintln!("inner result: {result}");
}

// ── MiniMax ───────────────────────────────────────────────────────

#[test]
#[ignore]
fn minimax_responds_like_claude() {
    if !is_available("minimax") {
        eprintln!("SKIP: minimax not in PATH");
        return;
    }

    let output = agent_cmd("minimax")
        .args([
            "-p",
            "--output-format",
            "json",
            "--model",
            "haiku",
            SIMPLE_PROMPT,
        ])
        .output()
        .expect("failed to execute minimax");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes): {}",
        stdout.len(),
        &stdout[..stdout.len().min(500)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    assert!(output.status.success(), "minimax failed: {stderr}");
    assert!(!stdout.is_empty(), "minimax returned empty stdout");

    let result = assert_claude_envelope(&stdout);
    eprintln!("inner result: {result}");
}

// ── Router LLM ───────────────────────────────────────────────────

#[test]
#[ignore]
fn router_claude_haiku_returns_valid_routing() {
    if !is_available("claude") {
        eprintln!("SKIP: claude not in PATH");
        return;
    }

    let router_prompt = r#"You are a task router. Given the task below, respond with ONLY a JSON object (no markdown, no explanation):

Task: "Fix typo in README.md"

Required JSON format:
{"executor":"claude","complexity":"simple","reason":"trivial text fix","profile":{"role":"editor","skills":[],"tools":[],"constraints":[]},"selected_skills":[]}"#;

    let output = agent_cmd("claude")
        .args([
            "--output-format",
            "json",
            "--print",
            "--model",
            "haiku",
            router_prompt,
        ])
        .output()
        .expect("failed to execute claude");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("exit: {}", output.status.code().unwrap_or(-1));
    eprintln!(
        "stdout ({} bytes): {}",
        stdout.len(),
        &stdout[..stdout.len().min(500)]
    );
    eprintln!(
        "stderr ({} bytes): {}",
        stderr.len(),
        &stderr[..stderr.len().min(500)]
    );

    assert!(output.status.success(), "router failed: {stderr}");
    assert!(!stdout.is_empty(), "router returned empty stdout");

    // Unwrap Claude envelope
    let result = assert_claude_envelope(&stdout);
    eprintln!("inner result: {result}");

    // The inner result should be parseable as JSON with an "executor" field
    // (might be in a code block or raw JSON)
    let text = result.trim();
    let json_str = if let Some(start) = text.find("```json") {
        let after = &text[start + 7..];
        &after[..after.find("```").unwrap_or(after.len())]
    } else if let Some(start) = text.find("```") {
        let after = &text[start + 3..];
        &after[..after.find("```").unwrap_or(after.len())]
    } else if let Some(start) = text.find('{') {
        &text[start..=text.rfind('}').unwrap_or(text.len() - 1)]
    } else {
        text
    };

    let route: serde_json::Value = serde_json::from_str(json_str.trim())
        .unwrap_or_else(|e| panic!("inner result is not valid JSON: {e}\nraw: {json_str}"));

    assert!(
        route.get("executor").is_some(),
        "route response missing 'executor' field: {route}"
    );

    eprintln!(
        "route: executor={}, complexity={}",
        route
            .get("executor")
            .and_then(|v| v.as_str())
            .unwrap_or("?"),
        route
            .get("complexity")
            .and_then(|v| v.as_str())
            .unwrap_or("?"),
    );
}