embacle 0.35.0

LLM runner library — 12 AI CLI tools, ACP, and HTTP APIs (Anthropic, Gemini, Cohere, Groq, OpenRouter, OpenAI-compatible) as pluggable LLM providers with fallback chains, agent loop, guardrails, and cost tracking
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
// ABOUTME: Drives each CLI runner twice against a shell stand-in that records its argv, proving
// ABOUTME: no call ever resumes the session a previous call on the same runner instance opened
//
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 dravr.ai

//! One runner instance serves every caller in a process, and each request
//! carries its whole conversation. A runner that remembered the session id a
//! CLI returned and passed it back on the next call (`--resume`, `--session`,
//! `--taskId`, `--conversation`) spliced the previous caller's conversation
//! into the next caller's turn: measured on 2026-09-30, athlete B's Claude Code
//! call quoted athlete A's resting heart rate.
//!
//! Every stand-in here reports a session id the way its real CLI does, and
//! every test runs two calls with the same model on one runner. The second
//! call's argv must carry no resume flag and must never name the id the first
//! call was handed back.

#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::fmt::Write as _;
use std::fs;
use std::mem;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use embacle::config::RunnerConfig;
use embacle::types::{ChatMessage, ChatRequest, LlmProvider};
use embacle::{
    ClaudeCodeRunner, ClineCliRunner, ContinueCliRunner, CursorAgentRunner, GeminiCliRunner,
    GooseCliRunner, KiloCliRunner, KiroCliRunner, OpenCodeRunner, WarpCliRunner,
};
use tokio_stream::StreamExt;

// Each test execs a script it just wrote; see `support` for the ETXTBSY race
// that makes every call here retry its spawn.
mod support;
use support::retry_text_file_busy;

/// The id every stand-in reports as the session it opened.
const SESSION_ID: &str = "sess-alice-7f3a";

/// Written after each invocation's arguments in the argv log.
const CALL_END: &str = "--END-OF-CALL--";

/// Flags any of the wrapped CLIs uses to continue an earlier session.
const RESUME_FLAGS: &[&str] = &[
    "--resume",
    "-r",
    "--continue",
    "-c",
    "--session",
    "--session-id",
    "--taskId",
    "--conversation",
    "--fork-session",
];

/// Environment variables the stand-in records beside its argv, as
/// `env:NAME=value` lines.
const RECORDED_ENV: &[&str] = &[
    "CLAUDE_CODE_DISABLE_AUTO_MEMORY",
    "CLAUDE_CODE_DISABLE_CLAUDE_MDS",
];

/// A CLI stand-in that appends its argv, one argument per line, and the
/// [`RECORDED_ENV`] values it was started with to `argv.log` beside it, then
/// prints `stdout`.
fn fake_cli(dir: &Path, stdout: &str) -> PathBuf {
    let path = dir.join("fake-cli");
    let log = dir.join("argv.log");
    let mut env_lines = String::new();
    for name in RECORDED_ENV {
        write!(env_lines, " printf 'env:{name}=%s\\n' \"${name}\";").unwrap();
    }
    let script = format!(
        "#!/bin/sh\n{{ for a in \"$@\"; do printf '%s\\n' \"$a\"; done;{env_lines} printf '%s\\n' '{CALL_END}'; }} >> '{}'\ncat <<'FAKE_EOF'\n{stdout}\nFAKE_EOF\n",
        log.display()
    );
    fs::write(&path, script).unwrap();
    fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
    path
}

/// The argv of every recorded invocation, in call order.
fn recorded_calls(dir: &Path) -> Vec<Vec<String>> {
    let log = fs::read_to_string(dir.join("argv.log")).unwrap();
    let mut calls = Vec::new();
    let mut current = Vec::new();
    for line in log.lines() {
        if line == CALL_END {
            calls.push(mem::take(&mut current));
        } else {
            current.push(line.to_owned());
        }
    }
    calls
}

/// Two turns from two different athletes, on the same model.
fn requests() -> [ChatRequest; 2] {
    [
        ChatRequest::new(vec![ChatMessage::user("I am Alice, resting HR 47")]).with_model("m"),
        ChatRequest::new(vec![ChatMessage::user("I am Bob, what did Alice say?")]).with_model("m"),
    ]
}

/// Both calls ran, and neither carries a resume flag or the reported id.
fn assert_never_resumed(dir: &Path) -> Vec<Vec<String>> {
    let calls = assert_no_resume_args(dir);
    assert!(
        calls[1].iter().any(|a| a.contains("Bob")),
        "the second call carries its own prompt: {:?}",
        calls[1]
    );
    calls
}

/// [`assert_never_resumed`] for a CLI that reads its prompt from a file or
/// stdin rather than from argv.
fn assert_no_resume_args(dir: &Path) -> Vec<Vec<String>> {
    let calls = recorded_calls(dir);
    assert_eq!(calls.len(), 2, "expected two invocations, got {calls:?}");
    for (i, argv) in calls.iter().enumerate() {
        for flag in RESUME_FLAGS {
            assert!(
                !argv.iter().any(|a| a == flag),
                "call {i} passed {flag}: {argv:?}"
            );
        }
        assert!(
            !argv.iter().any(|a| a.contains(SESSION_ID)),
            "call {i} named the session a previous call opened: {argv:?}"
        );
    }
    calls
}

/// A Claude Code call that neither saves its session nor reads or writes the
/// per-directory memory, `CLAUDE.md` and settings every caller shares.
fn assert_claude_isolated(argv: &[String]) {
    assert!(
        argv.iter().any(|a| a == "--no-session-persistence"),
        "every call is an unsaved session: {argv:?}"
    );
    let sources = argv
        .iter()
        .position(|a| a == "--setting-sources")
        .and_then(|i| argv.get(i + 1));
    assert_eq!(
        sources.map(String::as_str),
        Some("user"),
        "project and local settings from the shared cwd are never loaded: {argv:?}"
    );
    for line in [
        "env:CLAUDE_CODE_DISABLE_AUTO_MEMORY=1",
        "env:CLAUDE_CODE_DISABLE_CLAUDE_MDS=1",
    ] {
        assert!(argv.iter().any(|a| a == line), "missing {line}: {argv:?}");
    }
}

/// Run `complete()` for both requests and return the two answers.
async fn complete_twice(runner: &dyn LlmProvider) -> Vec<String> {
    let mut answers = Vec::new();
    for request in &requests() {
        let response = retry_text_file_busy(|| runner.complete(request)).await;
        answers.push(response.unwrap().content);
    }
    answers
}

/// Run `complete_stream()` for both requests, draining each stream, and
/// return the text each one streamed.
async fn stream_twice(runner: &dyn LlmProvider) -> Vec<String> {
    let mut answers = Vec::new();
    for request in &requests() {
        let mut stream = retry_text_file_busy(|| runner.complete_stream(request))
            .await
            .unwrap();
        let mut text = String::new();
        while let Some(chunk) = stream.next().await {
            if let Ok(chunk) = chunk {
                text.push_str(&chunk.delta);
            }
        }
        answers.push(text);
    }
    answers
}

#[tokio::test]
async fn claude_code_complete_never_resumes_and_shares_no_cwd_state() {
    let dir = tempfile::tempdir().unwrap();
    let doc = format!(r#"{{"result":"pong","is_error":false,"session_id":"{SESSION_ID}"}}"#);
    let runner = ClaudeCodeRunner::new(RunnerConfig::new(fake_cli(dir.path(), &doc)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);

    for argv in assert_never_resumed(dir.path()) {
        assert_claude_isolated(&argv);
    }
}

#[tokio::test]
async fn claude_code_stream_never_resumes_and_shares_no_cwd_state() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"{SESSION_ID}\"}}\n\
         {{\"type\":\"assistant\",\"message\":{{\"content\":[{{\"type\":\"text\",\"text\":\"pong\"}}]}},\"session_id\":\"{SESSION_ID}\"}}\n\
         {{\"type\":\"result\",\"is_error\":false,\"result\":\"pong\",\"session_id\":\"{SESSION_ID}\"}}"
    );
    let runner = ClaudeCodeRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    assert_eq!(stream_twice(&runner).await, ["pong", "pong"]);

    for argv in assert_never_resumed(dir.path()) {
        assert_claude_isolated(&argv);
    }
}

#[tokio::test]
async fn claude_code_complete_then_stream_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let doc = format!(
        r#"{{"type":"result","result":"pong","is_error":false,"session_id":"{SESSION_ID}"}}"#
    );
    let runner = ClaudeCodeRunner::new(RunnerConfig::new(fake_cli(dir.path(), &doc)));
    let [alice, bob] = requests();

    let answer = retry_text_file_busy(|| runner.complete(&alice)).await;
    assert_eq!(answer.unwrap().content, "pong");
    let mut stream = retry_text_file_busy(|| runner.complete_stream(&bob))
        .await
        .unwrap();
    while stream.next().await.is_some() {}

    for argv in assert_never_resumed(dir.path()) {
        assert_claude_isolated(&argv);
    }
}

#[tokio::test]
async fn cursor_agent_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let doc = format!(r#"{{"result":"pong","is_error":false,"session_id":"{SESSION_ID}"}}"#);
    let runner = CursorAgentRunner::new(RunnerConfig::new(fake_cli(dir.path(), &doc)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn cursor_agent_stream_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let doc = format!(
        r#"{{"type":"result","result":"pong","is_error":false,"session_id":"{SESSION_ID}"}}"#
    );
    let runner = CursorAgentRunner::new(RunnerConfig::new(fake_cli(dir.path(), &doc)));

    stream_twice(&runner).await;
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn gemini_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let doc = format!(r#"{{"session_id":"{SESSION_ID}","response":"pong"}}"#);
    let runner = GeminiCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), &doc)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn gemini_stream_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"init\",\"session_id\":\"{SESSION_ID}\"}}\n\
         {{\"type\":\"message\",\"role\":\"assistant\",\"content\":\"pong\",\"delta\":true}}\n\
         {{\"type\":\"result\",\"status\":\"success\"}}"
    );
    let runner = GeminiCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    stream_twice(&runner).await;
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn goose_never_resumes_and_runs_without_a_session() {
    let dir = tempfile::tempdir().unwrap();
    let doc = r#"{"messages":[{"role":"assistant","content":[{"type":"text","text":"pong"}]}]}"#;
    let runner = GooseCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), doc)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    for argv in assert_no_resume_args(dir.path()) {
        assert!(argv.iter().any(|a| a == "--no-session"), "{argv:?}");
    }
}

#[tokio::test]
async fn goose_stream_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let doc = r#"{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"pong"}]}}"#;
    let runner = GooseCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), doc)));

    stream_twice(&runner).await;
    for argv in assert_no_resume_args(dir.path()) {
        assert!(argv.iter().any(|a| a == "--no-session"), "{argv:?}");
    }
}

#[tokio::test]
async fn cline_never_resumes_a_task() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"task_started\",\"taskId\":\"{SESSION_ID}\"}}\n\
         {{\"type\":\"say\",\"say\":\"completion_result\",\"text\":\"pong\"}}"
    );
    let runner = ClineCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn cline_stream_never_resumes_a_task() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"task_started\",\"taskId\":\"{SESSION_ID}\"}}\n\
         {{\"type\":\"say\",\"say\":\"completion_result\",\"text\":\"pong\"}}"
    );
    let runner = ClineCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    stream_twice(&runner).await;
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn continue_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let runner = ContinueCliRunner::new(RunnerConfig::new(fake_cli(
        dir.path(),
        r#"{"response":"pong"}"#,
    )));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn continue_stream_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let runner = ContinueCliRunner::new(RunnerConfig::new(fake_cli(
        dir.path(),
        r#"{"response":"pong"}"#,
    )));

    assert_eq!(stream_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn kiro_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let runner = KiroCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), "pong")));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn kiro_stream_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let runner = KiroCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), "pong")));

    assert_eq!(stream_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn kilo_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"text\",\"sessionID\":\"{SESSION_ID}\",\"part\":{{\"type\":\"text\",\"text\":\"pong\"}}}}\n\
         {{\"type\":\"step_finish\",\"sessionID\":\"{SESSION_ID}\",\"part\":{{\"type\":\"step-finish\",\"reason\":\"stop\"}}}}"
    );
    let runner = KiloCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn kilo_stream_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"text\",\"sessionID\":\"{SESSION_ID}\",\"part\":{{\"type\":\"text\",\"text\":\"pong\"}}}}\n\
         {{\"type\":\"step_finish\",\"sessionID\":\"{SESSION_ID}\",\"part\":{{\"type\":\"step-finish\",\"reason\":\"stop\"}}}}"
    );
    let runner = KiloCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    stream_twice(&runner).await;
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn opencode_never_resumes() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"text\",\"sessionID\":\"{SESSION_ID}\",\"part\":{{\"type\":\"text\",\"text\":\"pong\"}}}}\n\
         {{\"type\":\"step_finish\",\"sessionID\":\"{SESSION_ID}\",\"part\":{{\"type\":\"step-finish\",\"reason\":\"stop\"}}}}"
    );
    let runner = OpenCodeRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}

#[tokio::test]
async fn warp_never_resumes_a_conversation() {
    let dir = tempfile::tempdir().unwrap();
    let lines = format!(
        "{{\"type\":\"system\",\"event_type\":\"conversation_started\",\"conversation_id\":\"{SESSION_ID}\"}}\n\
         {{\"type\":\"agent\",\"text\":\"pong\"}}"
    );
    let runner = WarpCliRunner::new(RunnerConfig::new(fake_cli(dir.path(), &lines)));

    assert_eq!(complete_twice(&runner).await, ["pong", "pong"]);
    assert_never_resumed(dir.path());
}