koda-core 0.2.16

Core engine for the Koda AI coding agent (macOS and Linux only)
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
//! Approval flow and user interaction during tool execution.
//!
//! Extracted from `tool_dispatch.rs` — handles the async request/response
//! dance for tool approvals and the `AskUser` tool. Both functions emit
//! an event via [`EngineSink`] and `select!` on the command channel,
//! respecting cancellation tokens for graceful shutdown.

use crate::engine::{ApprovalDecision, EngineCommand, EngineEvent};

use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

/// Emit an `AskUserRequest` and wait for the user's typed response.
///
/// Returns `None` if the session was interrupted or cancelled.
pub(crate) async fn handle_ask_user(
    sink: &dyn crate::engine::EngineSink,
    cmd_rx: &mut mpsc::Receiver<EngineCommand>,
    cancel: &CancellationToken,
    args: &serde_json::Value,
) -> Option<String> {
    let question = args["question"].as_str().unwrap_or("").to_string();
    let options: Vec<String> = args["options"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default();

    let request_id = uuid::Uuid::new_v4().to_string();
    sink.emit(EngineEvent::AskUserRequest {
        id: request_id.clone(),
        question,
        options,
    });

    loop {
        tokio::select! {
            cmd = cmd_rx.recv() => match cmd {
                Some(EngineCommand::AskUserResponse { id, answer }) if id == request_id => {
                    return Some(answer);
                }
                Some(EngineCommand::Interrupt) => {
                    cancel.cancel();
                    return None;
                }
                None => return None,
                _ => continue,
            },
            _ = cancel.cancelled() => return None,
        }
    }
}

/// Emit an `ApprovalRequest` and wait for the user's decision.
///
/// Returns `None` if the session was interrupted or cancelled.
pub(crate) async fn request_approval(
    sink: &dyn crate::engine::EngineSink,
    cmd_rx: &mut mpsc::Receiver<EngineCommand>,
    cancel: &CancellationToken,
    tool_name: &str,
    detail: &str,
    preview: Option<crate::preview::DiffPreview>,
    effect: crate::tools::ToolEffect,
) -> Option<ApprovalDecision> {
    let approval_id = uuid::Uuid::new_v4().to_string();
    sink.emit(EngineEvent::ApprovalRequest {
        id: approval_id.clone(),
        tool_name: tool_name.to_string(),
        detail: detail.to_string(),
        preview,
        effect,
    });

    loop {
        tokio::select! {
            cmd = cmd_rx.recv() => match cmd {
                Some(EngineCommand::ApprovalResponse { id, decision }) if id == approval_id => {
                    return Some(decision);
                }
                Some(EngineCommand::Interrupt) => {
                    cancel.cancel();
                    return None;
                }
                None => return None,  // channel closed
                _ => continue,        // ignore unrelated commands
            },
            _ = cancel.cancelled() => return None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::sink::TestSink;
    use crate::tools::ToolEffect;
    use std::sync::Arc;
    use std::time::Duration;

    // ── handle_ask_user ────────────────────────────────────────────────────

    #[tokio::test]
    async fn ask_user_returns_answer() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();
        let args = serde_json::json!({"question": "Pick one?", "options": ["a", "b"]});

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            handle_ask_user(&*sink2, &mut rx, &cancel2, &args).await
        });

        // Wait for AskUserRequest to be emitted, then reply with matching id.
        tokio::time::sleep(Duration::from_millis(20)).await;
        let id = sink
            .events()
            .into_iter()
            .find_map(|e| {
                if let EngineEvent::AskUserRequest { id, .. } = e {
                    Some(id)
                } else {
                    None
                }
            })
            .expect("AskUserRequest not emitted");

        cmd_tx
            .send(EngineCommand::AskUserResponse {
                id,
                answer: "b".into(),
            })
            .await
            .unwrap();

        assert_eq!(task.await.unwrap(), Some("b".to_string()));
    }

    #[tokio::test]
    async fn ask_user_emits_request_event_with_question_and_options() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();
        let args = serde_json::json!({
            "question": "Continue?",
            "options": ["yes", "no"]
        });

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let _task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            handle_ask_user(&*sink2, &mut rx, &cancel2, &args).await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        let events = sink.events();
        let req = events.iter().find_map(|e| {
            if let EngineEvent::AskUserRequest {
                question, options, ..
            } = e
            {
                Some((question.clone(), options.clone()))
            } else {
                None
            }
        });
        let (q, opts) = req.expect("no AskUserRequest emitted");
        assert_eq!(q, "Continue?");
        assert_eq!(opts, vec!["yes", "no"]);

        drop(cmd_tx);
    }

    #[tokio::test]
    async fn ask_user_ignores_response_with_wrong_id() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();
        let args = serde_json::json!({"question": "Q?", "options": []});

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            handle_ask_user(&*sink2, &mut rx, &cancel2, &args).await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        let id = sink
            .events()
            .into_iter()
            .find_map(|e| {
                if let EngineEvent::AskUserRequest { id, .. } = e {
                    Some(id)
                } else {
                    None
                }
            })
            .unwrap();

        // Wrong id first — should be ignored.
        cmd_tx
            .send(EngineCommand::AskUserResponse {
                id: "wrong-id".into(),
                answer: "nope".into(),
            })
            .await
            .unwrap();

        // Correct id — should be accepted.
        cmd_tx
            .send(EngineCommand::AskUserResponse {
                id,
                answer: "correct".into(),
            })
            .await
            .unwrap();

        assert_eq!(task.await.unwrap(), Some("correct".to_string()));
    }

    #[tokio::test]
    async fn ask_user_returns_none_on_interrupt() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();
        let args = serde_json::json!({"question": "Q?", "options": []});

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            handle_ask_user(&*sink2, &mut rx, &cancel2, &args).await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        cmd_tx.send(EngineCommand::Interrupt).await.unwrap();
        assert_eq!(task.await.unwrap(), None);
        assert!(cancel.is_cancelled(), "interrupt should cancel the token");
    }

    #[tokio::test]
    async fn ask_user_returns_none_when_channel_closes() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();
        let args = serde_json::json!({"question": "Q?", "options": []});

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            handle_ask_user(&*sink2, &mut rx, &cancel2, &args).await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        drop(cmd_tx);
        assert_eq!(task.await.unwrap(), None);
    }

    #[tokio::test]
    async fn ask_user_returns_none_on_cancellation() {
        let sink = Arc::new(TestSink::new());
        let (_cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();
        let args = serde_json::json!({"question": "Q?", "options": []});

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            handle_ask_user(&*sink2, &mut rx, &cancel2, &args).await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        cancel.cancel();
        assert_eq!(task.await.unwrap(), None);
    }

    // ── request_approval ───────────────────────────────────────────────────

    #[tokio::test]
    async fn request_approval_returns_approve() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            request_approval(
                &*sink2,
                &mut rx,
                &cancel2,
                "Write",
                "overwrite main.rs",
                None,
                ToolEffect::LocalMutation,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        let id = sink
            .events()
            .into_iter()
            .find_map(|e| {
                if let EngineEvent::ApprovalRequest { id, .. } = e {
                    Some(id)
                } else {
                    None
                }
            })
            .expect("ApprovalRequest not emitted");

        cmd_tx
            .send(EngineCommand::ApprovalResponse {
                id,
                decision: ApprovalDecision::Approve,
            })
            .await
            .unwrap();

        assert_eq!(task.await.unwrap(), Some(ApprovalDecision::Approve));
    }

    #[tokio::test]
    async fn request_approval_returns_reject() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            request_approval(
                &*sink2,
                &mut rx,
                &cancel2,
                "Bash",
                "rm -rf .",
                None,
                ToolEffect::Destructive,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        let id = sink
            .events()
            .into_iter()
            .find_map(|e| {
                if let EngineEvent::ApprovalRequest { id, .. } = e {
                    Some(id)
                } else {
                    None
                }
            })
            .unwrap();

        cmd_tx
            .send(EngineCommand::ApprovalResponse {
                id,
                decision: ApprovalDecision::Reject,
            })
            .await
            .unwrap();

        assert_eq!(task.await.unwrap(), Some(ApprovalDecision::Reject));
    }

    #[tokio::test]
    async fn request_approval_emits_event_with_tool_name_and_detail() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let _task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            request_approval(
                &*sink2,
                &mut rx,
                &cancel2,
                "Edit",
                "replace line 42",
                None,
                ToolEffect::LocalMutation,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        let events = sink.events();
        let req = events.iter().find_map(|e| {
            if let EngineEvent::ApprovalRequest {
                tool_name, detail, ..
            } = e
            {
                Some((tool_name.clone(), detail.clone()))
            } else {
                None
            }
        });
        let (tool, detail) = req.expect("no ApprovalRequest emitted");
        assert_eq!(tool, "Edit");
        assert_eq!(detail, "replace line 42");

        drop(cmd_tx);
    }

    #[tokio::test]
    async fn request_approval_ignores_response_with_wrong_id() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            request_approval(
                &*sink2,
                &mut rx,
                &cancel2,
                "Write",
                "detail",
                None,
                ToolEffect::LocalMutation,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        let id = sink
            .events()
            .into_iter()
            .find_map(|e| {
                if let EngineEvent::ApprovalRequest { id, .. } = e {
                    Some(id)
                } else {
                    None
                }
            })
            .unwrap();

        // Wrong id ignored.
        cmd_tx
            .send(EngineCommand::ApprovalResponse {
                id: "wrong".into(),
                decision: ApprovalDecision::Reject,
            })
            .await
            .unwrap();

        // Correct id accepted.
        cmd_tx
            .send(EngineCommand::ApprovalResponse {
                id,
                decision: ApprovalDecision::Approve,
            })
            .await
            .unwrap();

        assert_eq!(task.await.unwrap(), Some(ApprovalDecision::Approve));
    }

    #[tokio::test]
    async fn request_approval_returns_none_on_interrupt() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            request_approval(
                &*sink2,
                &mut rx,
                &cancel2,
                "Bash",
                "detail",
                None,
                ToolEffect::Destructive,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        cmd_tx.send(EngineCommand::Interrupt).await.unwrap();
        assert_eq!(task.await.unwrap(), None);
        assert!(cancel.is_cancelled());
    }

    #[tokio::test]
    async fn request_approval_returns_none_when_channel_closes() {
        let sink = Arc::new(TestSink::new());
        let (cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            request_approval(
                &*sink2,
                &mut rx,
                &cancel2,
                "Write",
                "detail",
                None,
                ToolEffect::LocalMutation,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        drop(cmd_tx);
        assert_eq!(task.await.unwrap(), None);
    }

    #[tokio::test]
    async fn request_approval_returns_none_on_cancellation() {
        let sink = Arc::new(TestSink::new());
        let (_cmd_tx, cmd_rx) = mpsc::channel::<EngineCommand>(8);
        let cancel = CancellationToken::new();

        let sink2 = Arc::clone(&sink);
        let cancel2 = cancel.clone();
        let task = tokio::spawn(async move {
            let mut rx = cmd_rx;
            request_approval(
                &*sink2,
                &mut rx,
                &cancel2,
                "Write",
                "detail",
                None,
                ToolEffect::LocalMutation,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(20)).await;
        cancel.cancel();
        assert_eq!(task.await.unwrap(), None);
    }
}