batty-cli 0.11.63

Supervised agent execution for software teams
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
//! Integration tests for the Kiro ACP shim runtime.
//!
//! These tests spawn mock subprocesses that simulate the Kiro ACP JSON-RPC
//! protocol, exercising the runtime's initialization handshake, message
//! delivery, streaming updates, and permission auto-approval.
//!
//! Gated behind `shim-integration` feature flag.
//! Run with: cargo test --features shim-integration tests_kiro

use std::path::PathBuf;
use std::time::Duration;

use crate::shim::protocol::{self, Channel, Command, Event, ShimState};
use crate::shim::runtime::ShimArgs;

/// Check if an error is a read timeout (WouldBlock/TimedOut).
fn is_timeout_error(e: &anyhow::Error) -> bool {
    if let Some(io_err) = e.downcast_ref::<std::io::Error>() {
        matches!(
            io_err.kind(),
            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
        )
    } else {
        false
    }
}

/// Wait for a specific event type, skipping others, with a timeout.
fn wait_for_event<F>(ch: &mut Channel, timeout: Duration, predicate: F) -> Option<Event>
where
    F: Fn(&Event) -> bool,
{
    let deadline = std::time::Instant::now() + timeout;
    loop {
        if std::time::Instant::now() > deadline {
            return None;
        }
        match ch.recv::<Event>() {
            Ok(Some(evt)) if predicate(&evt) => return Some(evt),
            Ok(Some(_)) => continue,
            Ok(None) => return None,
            Err(e) if is_timeout_error(&e) => continue,
            Err(_) => return None,
        }
    }
}

/// Spawn a Kiro ACP shim with a bash command that acts as a mock kiro-cli acp.
fn spawn_kiro_mock(mock_cmd: &str) -> Channel {
    let (parent_sock, child_sock) = protocol::socketpair().unwrap();
    let channel = Channel::new(child_sock);

    let args = ShimArgs {
        id: "kiro-test".into(),
        agent_type: crate::shim::classifier::AgentType::Kiro,
        cmd: mock_cmd.to_string(),
        cwd: PathBuf::from("/tmp"),
        rows: 24,
        cols: 80,
        pty_log_path: None,
        graceful_shutdown_timeout_secs: 5,
        auto_commit_on_restart: true,
    };

    std::thread::spawn(move || {
        crate::shim::runtime_kiro::run_kiro_acp(args, channel).ok();
    });

    let mut ch = Channel::new(parent_sock);
    ch.set_read_timeout(Some(Duration::from_millis(500)))
        .unwrap();
    ch
}

/// Write a mock ACP script to a temp file and return the command to execute it.
///
/// Avoids all bash quoting issues by writing the script to disk.
/// The handshake extracts JSON-RPC request IDs dynamically so tests work
/// regardless of the global AtomicU64 counter value.
fn write_mock_script(prompt_handler: &str) -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static MOCK_COUNTER: AtomicU64 = AtomicU64::new(0);
    let unique = format!(
        "{}-{}",
        std::process::id(),
        MOCK_COUNTER.fetch_add(1, Ordering::Relaxed),
    );
    let script_path = std::env::temp_dir().join(format!("batty-kiro-mock-{unique}.sh"));

    let script = format!(
        r#"#!/bin/bash
# Helper to extract JSON-RPC id from a request line
extract_id() {{
    echo "$1" | grep -o '"id":[0-9]*' | head -1 | grep -o '[0-9]*'
}}

# --- ACP initialization handshake ---

# Read initialize request
read line
init_id=$(extract_id "$line")
echo '{{"jsonrpc":"2.0","id":'$init_id',"result":{{"protocolVersion":1,"agentCapabilities":{{}},"agentInfo":{{"name":"mock-kiro","version":"1.0.0"}}}}}}'

# Read session/new request
read line
sess_id=$(extract_id "$line")
echo '{{"jsonrpc":"2.0","id":'$sess_id',"result":{{"sessionId":"sess-mock-123"}}}}'

# --- prompt handling ---
{prompt_handler}
"#
    );

    std::fs::write(&script_path, &script).expect("failed to write mock script");

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).ok();
    }

    format!("exec bash {}", script_path.display())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Kiro ACP mode completes the handshake and emits Ready.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_emits_ready_after_handshake() {
    let mock = write_mock_script("sleep 30");
    let mut ch = spawn_kiro_mock(&mock);

    let evt = wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    });
    assert!(evt.is_some(), "expected Ready event after ACP handshake");

    ch.send(&Command::Shutdown {
        timeout_secs: 2,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .ok();
}

/// Kiro ACP mode responds to Ping with Pong.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_ping_pong() {
    let mock = write_mock_script("sleep 30");
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    ch.send(&Command::Ping).unwrap();
    let evt = wait_for_event(&mut ch, Duration::from_secs(2), |e| {
        matches!(e, Event::Pong)
    });
    assert!(evt.is_some(), "expected Pong");

    ch.send(&Command::Shutdown {
        timeout_secs: 2,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .ok();
}

/// Kiro ACP mode reports state as Idle after Ready.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_get_state_idle() {
    let mock = write_mock_script("sleep 30");
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    ch.send(&Command::GetState).unwrap();
    let evt = wait_for_event(&mut ch, Duration::from_secs(2), |e| {
        matches!(e, Event::State { .. })
    });
    match evt {
        Some(Event::State { state, .. }) => assert_eq!(state, ShimState::Idle),
        _ => panic!("expected State event"),
    }

    ch.send(&Command::Shutdown {
        timeout_secs: 2,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .ok();
}

/// Sending a prompt produces a Completion with streamed text.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_prompt_produces_completion() {
    let mock = write_mock_script(
        r#"
read line
prompt_id=$(extract_id "$line")
echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-mock-123","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello from mock Kiro"}}}}'
sleep 0.1
echo '{"jsonrpc":"2.0","id":'$prompt_id',"result":{"stopReason":"end_turn"}}'
sleep 30
"#,
    );
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    ch.send(&Command::SendMessage {
        from: "user".into(),
        body: "Hello".into(),
        message_id: Some("msg-1".into()),
    })
    .unwrap();

    // Should get Working state
    let evt = wait_for_event(&mut ch, Duration::from_secs(5), |e| {
        matches!(
            e,
            Event::StateChanged {
                to: ShimState::Working,
                ..
            }
        )
    });
    assert!(evt.is_some(), "expected Working state change");

    // Wait for Completion
    let mut got_completion = false;
    let mut got_idle = false;
    let mut response_text = String::new();
    let mut completion_msg_id = None;
    let deadline = std::time::Instant::now() + Duration::from_secs(10);
    while !(got_completion && got_idle) && std::time::Instant::now() < deadline {
        match ch.recv::<Event>() {
            Ok(Some(Event::Completion {
                response,
                message_id,
                ..
            })) => {
                response_text = response;
                completion_msg_id = message_id;
                got_completion = true;
            }
            Ok(Some(Event::StateChanged {
                to: ShimState::Idle,
                ..
            })) => {
                got_idle = true;
            }
            Ok(Some(_)) => continue,
            Ok(None) => break,
            Err(e) if is_timeout_error(&e) => continue,
            Err(_) => break,
        }
    }
    assert!(got_completion, "expected Completion event");
    assert!(got_idle, "expected Idle state after completion");
    assert!(
        response_text.contains("Hello from mock Kiro"),
        "response should contain mock text, got: {response_text}"
    );
    assert_eq!(completion_msg_id.as_deref(), Some("msg-1"));

    ch.send(&Command::Shutdown {
        timeout_secs: 2,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .ok();
}

/// Permission requests are auto-approved.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_auto_approves_permissions() {
    let mock = write_mock_script(
        r#"
read line
prompt_id=$(extract_id "$line")
echo '{"jsonrpc":"2.0","id":100,"method":"session/request_permission","params":{"sessionId":"sess-mock-123","toolCall":{"toolCallId":"c1","title":"Running: ls","kind":"execute"},"options":[{"optionId":"allow_once","name":"Yes"},{"optionId":"deny","name":"No"}]}}'
read approval
if echo "$approval" | grep -q "allow_once"; then
  echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-mock-123","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"permission approved"}}}}'
  sleep 0.1
  echo '{"jsonrpc":"2.0","id":'$prompt_id',"result":{"stopReason":"end_turn"}}'
else
  echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-mock-123","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"permission denied"}}}}'
  sleep 0.1
  echo '{"jsonrpc":"2.0","id":'$prompt_id',"result":{"stopReason":"end_turn"}}'
fi
sleep 30
"#,
    );
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    ch.send(&Command::SendMessage {
        from: "user".into(),
        body: "run a command".into(),
        message_id: None,
    })
    .unwrap();

    let evt = wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Completion { .. })
    });
    match evt {
        Some(Event::Completion { response, .. }) => {
            assert!(
                response.contains("permission approved"),
                "expected auto-approval, got: {response}"
            );
        }
        _ => panic!("expected Completion"),
    }

    ch.send(&Command::Shutdown {
        timeout_secs: 2,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .ok();
}

/// When the mock subprocess exits, Died is emitted.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_subprocess_exit_emits_died() {
    let mock = write_mock_script("sleep 0.5; exit 0");
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    let evt = wait_for_event(&mut ch, Duration::from_secs(5), |e| {
        matches!(e, Event::Died { .. })
    });
    assert!(evt.is_some(), "expected Died event after subprocess exit");
}

/// Messages sent while Working are queued and delivered on Idle.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_message_queued_while_working() {
    let mock = write_mock_script(
        r#"
while read line; do
  req_id=$(extract_id "$line")
  echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-mock-123","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"response"}}}}'
  sleep 0.1
  echo '{"jsonrpc":"2.0","id":'$req_id',"result":{"stopReason":"end_turn"}}'
done
"#,
    );
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    // Send first message
    ch.send(&Command::SendMessage {
        from: "user".into(),
        body: "first".into(),
        message_id: Some("m1".into()),
    })
    .unwrap();

    // Wait for Working state
    wait_for_event(&mut ch, Duration::from_secs(5), |e| {
        matches!(
            e,
            Event::StateChanged {
                to: ShimState::Working,
                ..
            }
        )
    })
    .expect("Working after first message");

    // Send second message while working
    ch.send(&Command::SendMessage {
        from: "user".into(),
        body: "second".into(),
        message_id: Some("m2".into()),
    })
    .unwrap();

    // Should get Warning
    let evt = wait_for_event(&mut ch, Duration::from_secs(3), |e| {
        matches!(e, Event::Warning { .. })
    });
    assert!(evt.is_some(), "expected Warning about queued message");

    // Wait for first Completion
    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Completion { .. })
    })
    .expect("first Completion");

    // Queued message should produce second Completion
    let evt = wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Completion { .. })
    });
    assert!(
        evt.is_some(),
        "expected second Completion from queued message"
    );

    ch.send(&Command::Shutdown {
        timeout_secs: 2,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .ok();
}

/// Context exhaustion detected from high usage metadata notification.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_context_exhaustion_from_metadata() {
    let mock = write_mock_script(
        r#"
read line
echo '{"jsonrpc":"2.0","method":"_kiro.dev/metadata","params":{"sessionId":"sess-mock-123","credits":1.0,"contextUsagePercentage":99.5}}'
sleep 30
"#,
    );
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    ch.send(&Command::SendMessage {
        from: "user".into(),
        body: "test".into(),
        message_id: None,
    })
    .unwrap();

    let evt = wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::ContextExhausted { .. })
    });
    assert!(evt.is_some(), "expected ContextExhausted from high usage");

    ch.send(&Command::Kill).ok();
}

/// CaptureScreen returns accumulated response text.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_capture_screen() {
    let mock = write_mock_script("sleep 30");
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    ch.send(&Command::CaptureScreen {
        last_n_lines: Some(10),
    })
    .unwrap();

    let evt = wait_for_event(&mut ch, Duration::from_secs(2), |e| {
        matches!(e, Event::ScreenCapture { .. })
    });
    match evt {
        Some(Event::ScreenCapture { content, .. }) => {
            assert!(content.is_empty(), "expected empty screen before messages");
        }
        _ => panic!("expected ScreenCapture"),
    }

    ch.send(&Command::Shutdown {
        timeout_secs: 2,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .ok();
}

/// Shutdown terminates cleanly.
///
/// After shutdown the channel may close (shim exited) or we may receive
/// Died/Dead events — either outcome means the shutdown was clean.
#[test]
#[cfg_attr(not(feature = "shim-integration"), ignore)]
fn kiro_acp_shutdown_terminates_cleanly() {
    // Use `cat` instead of `sleep` — cat exits when stdin closes
    let mock = write_mock_script("cat > /dev/null");
    let mut ch = spawn_kiro_mock(&mock);

    wait_for_event(&mut ch, Duration::from_secs(10), |e| {
        matches!(e, Event::Ready)
    })
    .expect("Ready");

    ch.send(&Command::Shutdown {
        timeout_secs: 3,
        reason: crate::shim::protocol::ShutdownReason::Requested,
    })
    .unwrap();

    // The shim may emit Died/Dead or just close the channel — both are fine.
    let deadline = std::time::Instant::now() + Duration::from_secs(10);
    let mut shutdown_clean = false;
    while std::time::Instant::now() < deadline {
        match ch.recv::<Event>() {
            Ok(Some(Event::Died { .. }))
            | Ok(Some(Event::StateChanged {
                to: ShimState::Dead,
                ..
            })) => {
                shutdown_clean = true;
                break;
            }
            Ok(None) => {
                // Channel closed — shim exited cleanly
                shutdown_clean = true;
                break;
            }
            Err(e) if is_timeout_error(&e) => continue,
            Err(_) => {
                // Channel error — shim exited
                shutdown_clean = true;
                break;
            }
            Ok(Some(_)) => continue,
        }
    }
    assert!(shutdown_clean, "expected clean shutdown");
}