blyte 0.90.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use blyte_agent::approval::NoApprover;
use blyte_cli::conversation_store::ConversationStore;
use blyte_cli::http::{Request, Response};
use blyte_cli::mcp::McpManager;
use blyte_cli::repl::ReplConfig;
use blyte_cli::serve::{generate_token, route, OpenCodes, Surface, MESSAGE_HEADER, TOKEN_HEADER};
use blyte_cli::session::{
    build_redacted_shell_context, AgentRunner, EntryBody, PromptRunner, Session,
};
use blyte_cli::surface_registry::SurfaceState;
use blyte_cli::terminal_front::render_entry;
use blyte_provider::Message;
use serde_json::{json, Value};

struct CountingRunner {
    calls: Arc<AtomicUsize>,
    seen_prompts: Arc<Mutex<Vec<String>>>,
    gate_started: Option<mpsc::Sender<()>>,
    gate_release: Option<Arc<Mutex<mpsc::Receiver<()>>>>,
}

impl CountingRunner {
    fn new() -> (Self, Arc<AtomicUsize>, Arc<Mutex<Vec<String>>>) {
        let calls = Arc::new(AtomicUsize::new(0));
        let seen_prompts = Arc::new(Mutex::new(Vec::new()));
        (
            Self {
                calls: Arc::clone(&calls),
                seen_prompts: Arc::clone(&seen_prompts),
                gate_started: None,
                gate_release: None,
            },
            calls,
            seen_prompts,
        )
    }

    fn blocking() -> (Self, Arc<AtomicUsize>, mpsc::Receiver<()>, mpsc::Sender<()>) {
        let calls = Arc::new(AtomicUsize::new(0));
        let seen_prompts = Arc::new(Mutex::new(Vec::new()));
        let (start_tx, start_rx) = mpsc::channel();
        let (rel_tx, rel_rx) = mpsc::channel();
        (
            Self {
                calls: Arc::clone(&calls),
                seen_prompts,
                gate_started: Some(start_tx),
                gate_release: Some(Arc::new(Mutex::new(rel_rx))),
            },
            calls,
            start_rx,
            rel_tx,
        )
    }
}

impl PromptRunner for CountingRunner {
    fn run(
        &mut self,
        prompt: &str,
        _model: &str,
        emit: &(dyn Fn(EntryBody) + Sync),
    ) -> Result<(), String> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        self.seen_prompts.lock().unwrap().push(prompt.to_string());
        if let Some(ref tx) = self.gate_started {
            let _ = tx.send(());
        }
        if let Some(ref rx) = self.gate_release {
            let _ = rx.lock().unwrap().recv();
        }
        emit(EntryBody::Turn {
            n: 1,
            text: format!("model saw: {prompt}"),
            input_tokens: 1,
            output_tokens: 1,
            cost_usd: None,
            cached_tokens: None,
            thinking_tokens: None,
            first_event_ms: None,
            first_output_ms: None,
            total_ms: None,
            retries: None,
            retry_wait_ms: None,
        });
        Ok(())
    }
}

fn make_surface(root: PathBuf, session: Session, mcp: Arc<McpManager>) -> Surface {
    let repo = root
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("repo")
        .to_string();
    Surface {
        surface_id: "s00000000000000bb".to_string(),
        surface_name: repo.clone(),
        root,
        repo,
        session,
        session_id: "sess-shell-1".to_string(),
        started_at: 1_700_000_000,
        runtime: blyte_cli::surface_version::SurfaceRuntimeInfo::current().unwrap(),
        days: 14,
        token: generate_token().unwrap(),
        message_credential: generate_token().unwrap(),
        open_codes: OpenCodes::new(),
        requests: Arc::new(blyte_cli::requests::RequestsState::new()),
        publisher: Arc::new(blyte_cli::requests::RealPublisher),
        mcp,
        reconcile_lock: Mutex::new(()),
        reconcile_requested: AtomicBool::new(false),
    }
}

fn req(method: &str, path: &str, token: Option<&str>, body: Option<Value>) -> Request {
    let mut headers = Vec::new();
    if let Some(tok) = token {
        headers.push((TOKEN_HEADER.to_string(), tok.to_string()));
    }
    let body_bytes = match body {
        Some(v) => {
            headers.push(("content-type".to_string(), "application/json".to_string()));
            serde_json::to_vec(&v).unwrap()
        }
        None => Vec::new(),
    };
    Request {
        method: method.to_string(),
        path: path.to_string(),
        query: Vec::new(),
        headers,
        body: body_bytes,
    }
}

fn peer_req(cred: &str, body: Value) -> Request {
    Request {
        method: "POST".to_string(),
        path: "/api/peer/messages".to_string(),
        query: Vec::new(),
        headers: vec![
            (MESSAGE_HEADER.to_string(), cred.to_string()),
            ("content-type".to_string(), "application/json".to_string()),
        ],
        body: serde_json::to_vec(&body).unwrap(),
    }
}

fn parse_json(resp: &Response) -> Value {
    serde_json::from_slice(&resp.body).unwrap_or_else(|e| {
        panic!(
            "invalid JSON (status {}): {e}: {}",
            resp.status,
            String::from_utf8_lossy(&resp.body)
        )
    })
}

fn default_repl_config(repo: PathBuf) -> ReplConfig {
    ReplConfig {
        repo_root: repo,
        gate: None,
        context_strategy: "folded".to_string(),
        max_turns: 4,
        max_gates: 1,
        rollback: false,
        model: Some("gemini-4-neon".to_string()),
        container: None,
        converse: true,
        fold_budget: Some(100_000),
        dispatch_cmd: None,
        sandbox: "off".to_string(),
        network: Some("on".to_string()),
        allow_read: Vec::new(),
        pass_env: Vec::new(),
    }
}

fn make_mcp_with_secret(tmp: &Path, root: &Path, secret: &str) -> Arc<McpManager> {
    let cfg_dir = tmp.join("mcp-cfg");
    std::fs::create_dir_all(&cfg_dir).unwrap();
    let user_cfg = cfg_dir.join("mcp.json");
    let trust = cfg_dir.join("mcp-trust.json");
    let auth = cfg_dir.join("mcp-auth.json");
    let cfg_json = json!({
        "mcpServers": {
            "secret_srv": {
                "command": "true",
                "env": {
                    "MCP_SECRET_TOKEN": secret
                }
            }
        }
    });
    std::fs::write(&user_cfg, serde_json::to_string_pretty(&cfg_json).unwrap()).unwrap();
    Arc::new(McpManager::new(user_cfg, Some(root.to_path_buf()), trust, auth).unwrap())
}

#[test]
fn shell_endpoint_requires_token_and_rejects_blank_commands() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("repo");
    std::fs::create_dir_all(&root).unwrap();
    let (runner, calls, _) = CountingRunner::new();
    let session = Session::start(Box::new(runner), "gemini-4-neon".to_string());
    let mcp = Arc::new(McpManager::empty_in(&root));
    let surface = make_surface(root, session, mcp);

    let missing_tok = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            None,
            Some(json!({ "command": "echo hi" })),
        ),
        1_700_000_010,
    );
    assert_eq!(missing_tok.status, 403);

    let bad_tok = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some("wrong-token"),
            Some(json!({ "command": "echo hi" })),
        ),
        1_700_000_010,
    );
    assert_eq!(bad_tok.status, 403);

    let blank = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some(&surface.token),
            Some(json!({ "command": "   \t\n  " })),
        ),
        1_700_000_010,
    );
    assert_eq!(blank.status, 400);

    let missing_field = route(
        &surface,
        &req("POST", "/api/shell", Some(&surface.token), Some(json!({}))),
        1_700_000_010,
    );
    assert_eq!(missing_field.status, 400);

    let get_method = route(
        &surface,
        &req("GET", "/api/shell", Some(&surface.token), None),
        1_700_000_010,
    );
    assert_eq!(get_method.status, 405);
    assert_eq!(calls.load(Ordering::SeqCst), 0);
}

#[test]
fn shell_endpoint_returns_409_during_turn_concurrent_shell_or_reload() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("repo");
    std::fs::create_dir_all(&root).unwrap();
    let (runner, _calls, started_rx, release_tx) = CountingRunner::blocking();
    let session = Session::start(Box::new(runner), "gemini-4-neon".to_string());
    type StateTransition = (Option<String>, SurfaceState);
    let transitions: Arc<Mutex<Vec<StateTransition>>> = Arc::new(Mutex::new(Vec::new()));
    let transitions_hook = Arc::clone(&transitions);
    session.set_activity_hook(Box::new(move |doing, state| {
        transitions_hook
            .lock()
            .unwrap()
            .push((doing.map(str::to_string), state));
    }));
    let mcp = Arc::new(McpManager::empty_in(&root));
    let surface = Arc::new(make_surface(root, session, mcp));

    let msg_resp = route(
        &surface,
        &req(
            "POST",
            "/api/session/messages",
            Some(&surface.token),
            Some(json!({ "text": "hello" })),
        ),
        1_700_000_010,
    );
    assert_eq!(msg_resp.status, 200);
    started_rx
        .recv_timeout(Duration::from_secs(5))
        .expect("turn did not start");

    let during_turn = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some(&surface.token),
            Some(json!({ "command": "echo nope" })),
        ),
        1_700_000_011,
    );
    assert_eq!(during_turn.status, 409);

    release_tx.send(()).unwrap();
    let deadline = Instant::now() + Duration::from_secs(5);
    while surface.session.info().busy && Instant::now() < deadline {
        thread::sleep(Duration::from_millis(10));
    }
    assert!(!surface.session.info().busy);

    transitions.lock().unwrap().clear();

    let surface_bg = Arc::clone(&surface);
    let token = surface.token.clone();
    let slow_handle = thread::spawn(move || {
        route(
            &surface_bg,
            &req(
                "POST",
                "/api/shell",
                Some(&token),
                Some(json!({ "command": "sleep 0.35 && echo done" })),
            ),
            1_700_000_012,
        )
    });

    let wait_deadline = Instant::now() + Duration::from_secs(5);
    while !surface.session.info().busy && Instant::now() < wait_deadline {
        thread::sleep(Duration::from_millis(10));
    }
    assert!(surface.session.info().busy);
    assert_eq!(surface.session.info().state, SurfaceState::Working);

    let concurrent = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some(&surface.token),
            Some(json!({ "command": "echo second" })),
        ),
        1_700_000_013,
    );
    assert_eq!(concurrent.status, 409);

    let slow_resp = slow_handle.join().unwrap();
    assert_eq!(slow_resp.status, 200);
    assert!(!surface.session.info().busy);
    assert_eq!(surface.session.info().state, SurfaceState::Idle);

    let recorded = transitions.lock().unwrap();
    assert!(
        recorded.iter().any(|(doing, st)| {
            *st == SurfaceState::Working && doing.as_deref() == Some("! sleep 0.35 && echo done")
        }),
        "expected working transition with doing = '! sleep 0.35 && echo done', got {recorded:?}"
    );
    assert_eq!(
        recorded.last(),
        Some(&(None, SurfaceState::Idle)),
        "expected final transition to idle with no doing, got {recorded:?}"
    );

    assert!(surface.session.try_begin_reload().is_ok());
    let during_reload = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some(&surface.token),
            Some(json!({ "command": "echo blocked" })),
        ),
        1_700_000_014,
    );
    assert_eq!(during_reload.status, 409);
}

#[test]
fn shell_endpoint_executes_in_repo_root_persists_to_entries_and_never_invokes_model() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("repo");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(root.join("marker.txt"), "repo-root-ok\n").unwrap();
    let entries_path = tmp.path().join("entries.jsonl");

    let (runner, calls, _) = CountingRunner::new();
    let mut err_buf = Vec::new();
    let session = Session::start_with_log_io(
        "gemini-4-neon".to_string(),
        Some(entries_path.clone()),
        &mut err_buf,
        |_| Box::new(runner),
    )
    .unwrap();
    let mcp = Arc::new(McpManager::empty_in(&root));
    let surface = make_surface(root.clone(), session, mcp);

    let ok_resp = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some(&surface.token),
            Some(json!({ "command": "cat marker.txt && echo err-line >&2" })),
        ),
        1_700_000_010,
    );
    assert_eq!(ok_resp.status, 200);
    let ok_json = parse_json(&ok_resp);
    assert_eq!(ok_json["exit_code"], 0);
    assert_eq!(ok_json["truncated"], false);
    assert_eq!(ok_json["timed_out"], false);
    let ok_out = ok_json["output"].as_str().unwrap();
    assert!(ok_out.contains("repo-root-ok"), "output was: {ok_out}");
    assert!(ok_out.contains("err-line"), "output was: {ok_out}");

    let fail_resp = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some(&surface.token),
            Some(json!({ "command": "echo failing-now && exit 7" })),
        ),
        1_700_000_011,
    );
    assert_eq!(fail_resp.status, 200);
    let fail_json = parse_json(&fail_resp);
    assert_eq!(fail_json["exit_code"], 7);
    assert!(fail_json["output"]
        .as_str()
        .unwrap()
        .contains("failing-now"));

    assert_eq!(calls.load(Ordering::SeqCst), 0);
    assert_eq!(surface.session.info().state, SurfaceState::Idle);

    let raw_log = std::fs::read_to_string(&entries_path).unwrap();
    assert!(raw_log.contains("\"kind\":\"shell_command\""));
    assert!(raw_log.contains("\"exit_code\":0"));
    assert!(raw_log.contains("\"exit_code\":7"));

    let (runner2, _, _) = CountingRunner::new();
    let mut err_buf2 = Vec::new();
    let resumed = Session::start_with_log_io(
        "gemini-4-neon".to_string(),
        Some(entries_path),
        &mut err_buf2,
        |_| Box::new(runner2),
    )
    .unwrap();
    let entries = resumed.entries_after(0, Duration::ZERO);
    let shell_entries: Vec<_> = entries
        .iter()
        .filter(|e| matches!(e.body, EntryBody::ShellCommand { .. }))
        .collect();
    assert_eq!(shell_entries.len(), 2);

    let formatted_ok = render_entry(shell_entries[0]).unwrap();
    assert!(formatted_ok.contains("$ cat marker.txt"));
    assert!(formatted_ok.contains("[exit 0"));

    let formatted_fail = render_entry(shell_entries[1]).unwrap();
    assert!(formatted_fail.contains("[exit 7"));
}

#[test]
fn shell_context_injects_redacted_env_and_mcp_secrets_into_conversation_store_and_fails_closed() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("repo");
    std::fs::create_dir_all(&root).unwrap();

    let env_secret = "env-super-secret-value-99887766";
    let mcp_secret = "mcp-super-secret-value-11223344";
    std::fs::write(root.join(".env"), format!("APP_API_KEY={env_secret}\n")).unwrap();

    let mcp = make_mcp_with_secret(tmp.path(), &root, mcp_secret);
    let store_path = tmp.path().join("conversation.json");
    let store = ConversationStore::new_for_fresh(store_path.clone()).unwrap();

    let cfg = default_repl_config(root.clone());
    let mut runner =
        AgentRunner::try_new_with_conversation(&cfg, Arc::new(NoApprover), Some(store), None)
            .unwrap();
    runner.set_mcp_manager(Arc::clone(&mcp));

    let session = Session::start(Box::new(runner), "gemini-4-neon".to_string());
    let surface = make_surface(root.clone(), session, Arc::clone(&mcp));

    let cmd = format!("echo \"env={env_secret} mcp={mcp_secret}\"");
    let resp = route(
        &surface,
        &req(
            "POST",
            "/api/shell",
            Some(&surface.token),
            Some(json!({ "command": cmd })),
        ),
        1_700_000_010,
    );
    assert_eq!(resp.status, 200);

    let (_store2, loaded_opt) = ConversationStore::load(store_path).unwrap();
    let loaded = loaded_opt.expect("conversation must be saved");
    assert_eq!(loaded.messages.len(), 1);
    let injected_text = match &loaded.messages[0] {
        Message::User(text) => text.clone(),
        other => panic!("expected user message, got {other:?}"),
    };
    assert!(
        !injected_text.contains(env_secret),
        ".env secret leaked into conversation history: {injected_text}"
    );
    assert!(
        !injected_text.contains(mcp_secret),
        "MCP secret leaked into conversation history: {injected_text}"
    );
    assert!(injected_text.contains("exit code: 0"));
    assert!(injected_text.contains("[redacted"));

    let fail_dir = tmp.path().join("bad-root");
    std::fs::create_dir_all(fail_dir.join(".env")).unwrap();
    let fail_res = build_redacted_shell_context(
        &fail_dir,
        "echo secret",
        0,
        "secret-data",
        false,
        false,
        None,
        None,
    );
    assert!(
        fail_res.is_err(),
        "redactor failure must fail closed rather than leaking secrets"
    );
}

#[test]
fn peer_tell_messages_starting_with_bang_never_execute_shell() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("repo");
    std::fs::create_dir_all(&root).unwrap();
    let sentinel = root.join("must_not_be_created");

    let (runner, calls, seen_prompts) = CountingRunner::new();
    let session = Session::start(Box::new(runner), "gemini-4-neon".to_string());
    let mcp = Arc::new(McpManager::empty_in(&root));
    let surface = make_surface(root.clone(), session, mcp);

    let bang_text = format!("! touch {}", sentinel.display());
    let resp = route(
        &surface,
        &peer_req(
            &surface.message_credential,
            json!({
                "from_name": "other-surface",
                "from_repository": "other-repo",
                "text": bang_text,
            }),
        ),
        1_700_000_010,
    );
    assert_eq!(resp.status, 200);

    let deadline = Instant::now() + Duration::from_secs(5);
    while calls.load(Ordering::SeqCst) == 0 && Instant::now() < deadline {
        thread::sleep(Duration::from_millis(10));
    }
    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert!(
        !sentinel.exists(),
        "peer tell message must never execute shell commands"
    );

    let prompts = seen_prompts.lock().unwrap();
    assert!(prompts[0].contains(&bang_text));

    let entries = surface.session.entries_after(0, Duration::ZERO);
    assert!(
        entries
            .iter()
            .all(|e| !matches!(e.body, EntryBody::ShellCommand { .. })),
        "peer tell message must not produce shell_command entries"
    );
}