oi-kit-agent 0.1.0-alpha.16

oi-kit's Agent Loop
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use anyhow::Result;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, Mutex, OwnedMutexGuard, RwLock};
use tokio::time::timeout;
use tracing::warn;
use uuid::Uuid;

use oi_kit_provider_types::conversation::message::{Message, MessageContent};

const ACTION_REQUIRED_STREAM_CAPACITY: usize = 8;

#[derive(Debug, Clone, PartialEq)]
pub enum ElicitationOutcome {
    Accept(Value),
    Decline,
    Cancel,
}

struct PendingRequest {
    session_id: String,
    response_tx: Option<tokio::sync::oneshot::Sender<ElicitationOutcome>>,
}

pub struct PendingResponseClaim {
    request_id: String,
    pending: OwnedMutexGuard<PendingRequest>,
}

impl PendingResponseClaim {
    pub fn submit(mut self, response: ElicitationOutcome) -> Result<()> {
        let tx = self
            .pending
            .response_tx
            .take()
            .ok_or_else(|| anyhow::anyhow!("Request already completed: {}", self.request_id))?;
        drop(self.pending);

        if tx.send(response).is_err() {
            return Err(anyhow::anyhow!("Response channel closed"));
        }

        Ok(())
    }
}

struct ForwardedRequest {
    parent_id: String,
    subagent_id: String,
    request_id: String,
}

pub struct ActionRequiredManager {
    pending: Arc<RwLock<HashMap<String, Arc<Mutex<PendingRequest>>>>>,
    action_required_senders: Mutex<HashMap<(String, String), mpsc::Sender<Message>>>,
    forwarded: std::sync::Mutex<HashMap<String, ForwardedRequest>>,
}

impl Default for ActionRequiredManager {
    fn default() -> Self {
        Self::new()
    }
}

impl ActionRequiredManager {
    pub fn new() -> Self {
        Self {
            pending: Arc::new(RwLock::new(HashMap::new())),
            action_required_senders: Mutex::new(HashMap::new()),
            forwarded: std::sync::Mutex::new(HashMap::new()),
        }
    }

    pub fn forward(&self, parent_id: &str, subagent_id: &str, request_id: &str) -> String {
        let id = Uuid::new_v4().to_string();
        self.forwarded
            .lock()
            .expect("forwarded requests unavailable")
            .insert(
                id.clone(),
                ForwardedRequest {
                    parent_id: parent_id.to_string(),
                    subagent_id: subagent_id.to_string(),
                    request_id: request_id.to_string(),
                },
            );
        id
    }

    pub fn is_forwarded(&self, id: &str) -> bool {
        self.forwarded
            .lock()
            .expect("forwarded requests unavailable")
            .contains_key(id)
    }

    pub fn answered_request(&self, session_id: &str, request_id: &str) -> Result<(String, String)> {
        let forwarded = self
            .forwarded
            .lock()
            .expect("forwarded requests unavailable");
        match forwarded.get(request_id) {
            None => Ok((session_id.to_string(), request_id.to_string())),
            Some(request) if request.parent_id == session_id => {
                Ok((request.subagent_id.clone(), request.request_id.clone()))
            }
            Some(_) => Err(anyhow::anyhow!(
                "Request {request_id} was not forwarded to session {session_id}"
            )),
        }
    }

    pub fn forget_forwarded_from(&self, subagent_id: &str) {
        self.forwarded
            .lock()
            .expect("forwarded requests unavailable")
            .retain(|_, request| request.subagent_id != subagent_id);
    }

    pub async fn request_and_wait(
        &self,
        session_id: String,
        tool_call_request_id: String,
        message: String,
        schema: Value,
        timeout_duration: Duration,
    ) -> Result<ElicitationOutcome> {
        let sender = self
            .action_required_senders
            .lock()
            .await
            .get(&(session_id.clone(), tool_call_request_id.clone()))
            .cloned();

        let Some(sender) = sender else {
            return Err(anyhow::anyhow!(
                "Tool call request not found for elicitation: {}",
                tool_call_request_id
            ));
        };

        let id = Uuid::new_v4().to_string();
        let (tx, rx) = tokio::sync::oneshot::channel();
        let pending_request = PendingRequest {
            session_id: session_id.clone(),
            response_tx: Some(tx),
        };
        let pending_request = Arc::new(Mutex::new(pending_request));

        self.pending
            .write()
            .await
            .insert(id.clone(), Arc::clone(&pending_request));

        let action_required_message = Message::assistant().with_content(
            MessageContent::action_required_elicitation(id.clone(), message, schema),
        );
        if let Err(error) = sender.try_send(action_required_message) {
            self.pending.write().await.remove(&id);
            let message = match error {
                mpsc::error::TrySendError::Full(_) => "stream is full",
                mpsc::error::TrySendError::Closed(_) => "stream closed",
            };
            return Err(anyhow::anyhow!(
                "Tool call action-required {message}: {tool_call_request_id}"
            ));
        }

        let result = self
            .wait_for_response(&id, pending_request, rx, timeout_duration)
            .await;

        self.pending.write().await.remove(&id);

        result
    }

    pub async fn claim_response(
        &self,
        session_id: &str,
        request_id: &str,
    ) -> Result<PendingResponseClaim> {
        let pending_arc = self.pending_request(request_id).await?;
        let mut pending = pending_arc.lock_owned().await;

        if pending.session_id != session_id {
            return Err(anyhow::anyhow!(
                "Request {} belongs to session {}, not {}",
                request_id,
                pending.session_id,
                session_id
            ));
        }

        let tx = pending
            .response_tx
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Request already completed: {}", request_id))?;
        if tx.is_closed() {
            pending.response_tx.take();
            return Err(anyhow::anyhow!("Response channel closed"));
        }

        Ok(PendingResponseClaim {
            request_id: request_id.to_string(),
            pending,
        })
    }

    async fn pending_request(&self, request_id: &str) -> Result<Arc<Mutex<PendingRequest>>> {
        let pending = self.pending.read().await;
        pending
            .get(request_id)
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("Request not found: {}", request_id))
    }

    async fn wait_for_response(
        &self,
        request_id: &str,
        pending_request: Arc<Mutex<PendingRequest>>,
        mut rx: tokio::sync::oneshot::Receiver<ElicitationOutcome>,
        timeout_duration: Duration,
    ) -> Result<ElicitationOutcome> {
        match timeout(timeout_duration, &mut rx).await {
            Ok(response) => Self::finish_waiting(request_id, response),
            Err(_) => {
                let mut pending = pending_request.lock().await;
                if pending.response_tx.is_some() {
                    pending.response_tx.take();
                    warn!("Timeout waiting for response: {}", request_id);
                    return Err(anyhow::anyhow!("Timeout waiting for user response"));
                }
                drop(pending);

                Self::finish_waiting(request_id, rx.await)
            }
        }
    }

    fn finish_waiting(
        request_id: &str,
        response: Result<ElicitationOutcome, tokio::sync::oneshot::error::RecvError>,
    ) -> Result<ElicitationOutcome> {
        match response {
            Ok(user_data) => Ok(user_data),
            Err(_) => {
                warn!("Response channel closed for request: {}", request_id);
                Err(anyhow::anyhow!("Response channel closed"))
            }
        }
    }

    pub async fn register_action_required_stream(
        &self,
        session_id: String,
        tool_call_request_id: String,
    ) -> mpsc::Receiver<Message> {
        let (tx, rx) = mpsc::channel(ACTION_REQUIRED_STREAM_CAPACITY);
        self.action_required_senders
            .lock()
            .await
            .insert((session_id, tool_call_request_id), tx);
        rx
    }

    pub async fn has_action_required_stream(
        &self,
        session_id: &str,
        tool_call_request_id: &str,
    ) -> bool {
        self.action_required_senders
            .lock()
            .await
            .contains_key(&(session_id.to_string(), tool_call_request_id.to_string()))
    }

    pub async fn unregister_action_required_stream(
        &self,
        session_id: &str,
        tool_call_request_id: &str,
    ) {
        self.action_required_senders
            .lock()
            .await
            .remove(&(session_id.to_string(), tool_call_request_id.to_string()));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oi_kit_provider_types::conversation::message::ActionRequiredData;
    use serde_json::json;

    fn elicitation_id(message: &Message) -> String {
        match &message.content[0] {
            MessageContent::ActionRequired(action_required) => match &action_required.data {
                ActionRequiredData::Elicitation { id, .. } => id.clone(),
                _ => panic!("expected elicitation action-required message"),
            },
            _ => panic!("expected action-required message"),
        }
    }

    async fn recv_elicitation_message(rx: &mut mpsc::Receiver<Message>) -> Message {
        tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("timed out waiting for elicitation message")
            .expect("action-required stream closed")
    }

    #[tokio::test]
    async fn wrong_session_does_not_consume_pending_response() {
        let manager = Arc::new(ActionRequiredManager::new());
        let mut action_required_rx = manager
            .register_action_required_stream("session-a".to_string(), "tool-call-a".to_string())
            .await;
        let waiter = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-a".to_string(),
                        "tool-call-a".to_string(),
                        "Need input".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };

        let message = recv_elicitation_message(&mut action_required_rx).await;
        let request_id = elicitation_id(&message);

        let err = match manager.claim_response("session-b", &request_id).await {
            Ok(_) => panic!("wrong session should not claim pending response"),
            Err(error) => error,
        };
        assert!(err.to_string().contains("belongs to session session-a"));

        manager
            .claim_response("session-a", &request_id)
            .await
            .unwrap()
            .submit(ElicitationOutcome::Accept(json!({ "answer": "right" })))
            .unwrap();

        let response = waiter.await.unwrap().unwrap();
        assert_eq!(
            response,
            ElicitationOutcome::Accept(json!({ "answer": "right" }))
        );
    }

    #[tokio::test]
    async fn streams_only_requested_tool_call() {
        let manager = Arc::new(ActionRequiredManager::new());
        let mut stream_a = manager
            .register_action_required_stream("session-a".to_string(), "tool-call-a".to_string())
            .await;
        let mut stream_b = manager
            .register_action_required_stream("session-b".to_string(), "tool-call-b".to_string())
            .await;
        let waiter_a = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-a".to_string(),
                        "tool-call-a".to_string(),
                        "Need input A".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };
        let waiter_b = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-b".to_string(),
                        "tool-call-b".to_string(),
                        "Need input B".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };

        let message_a = recv_elicitation_message(&mut stream_a).await;
        let request_id_a = elicitation_id(&message_a);
        assert!(stream_a.try_recv().is_err());

        let message_b = recv_elicitation_message(&mut stream_b).await;
        let request_id_b = elicitation_id(&message_b);

        manager
            .claim_response("session-a", &request_id_a)
            .await
            .unwrap()
            .submit(ElicitationOutcome::Accept(json!({ "answer": "a" })))
            .unwrap();
        manager
            .claim_response("session-b", &request_id_b)
            .await
            .unwrap()
            .submit(ElicitationOutcome::Accept(json!({ "answer": "b" })))
            .unwrap();

        assert_eq!(
            waiter_a.await.unwrap().unwrap(),
            ElicitationOutcome::Accept(json!({ "answer": "a" }))
        );
        assert_eq!(
            waiter_b.await.unwrap().unwrap(),
            ElicitationOutcome::Accept(json!({ "answer": "b" }))
        );
    }

    #[tokio::test]
    async fn streams_are_namespaced_by_session() {
        let manager = Arc::new(ActionRequiredManager::new());
        let mut stream_a = manager
            .register_action_required_stream("session-a".to_string(), "tool-call-a".to_string())
            .await;
        let mut stream_b = manager
            .register_action_required_stream("session-b".to_string(), "tool-call-a".to_string())
            .await;
        let waiter_a = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-a".to_string(),
                        "tool-call-a".to_string(),
                        "Need input A".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };
        let waiter_b = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-b".to_string(),
                        "tool-call-a".to_string(),
                        "Need input B".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };

        let message_a = recv_elicitation_message(&mut stream_a).await;
        let request_id_a = elicitation_id(&message_a);
        let message_b = recv_elicitation_message(&mut stream_b).await;
        let request_id_b = elicitation_id(&message_b);

        manager
            .claim_response("session-a", &request_id_a)
            .await
            .unwrap()
            .submit(ElicitationOutcome::Accept(json!({ "answer": "a" })))
            .unwrap();
        manager
            .claim_response("session-b", &request_id_b)
            .await
            .unwrap()
            .submit(ElicitationOutcome::Accept(json!({ "answer": "b" })))
            .unwrap();

        assert_eq!(
            waiter_a.await.unwrap().unwrap(),
            ElicitationOutcome::Accept(json!({ "answer": "a" }))
        );
        assert_eq!(
            waiter_b.await.unwrap().unwrap(),
            ElicitationOutcome::Accept(json!({ "answer": "b" }))
        );
    }

    #[tokio::test]
    async fn claimed_response_can_complete_after_timeout_deadline() {
        let manager = Arc::new(ActionRequiredManager::new());
        let mut action_required_rx = manager
            .register_action_required_stream("session-a".to_string(), "tool-call-a".to_string())
            .await;
        let waiter = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-a".to_string(),
                        "tool-call-a".to_string(),
                        "Need input".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_millis(25),
                    )
                    .await
            })
        };

        let message = recv_elicitation_message(&mut action_required_rx).await;
        let request_id = elicitation_id(&message);

        let claim = manager
            .claim_response("session-a", &request_id)
            .await
            .unwrap();

        tokio::time::sleep(Duration::from_millis(50)).await;

        claim
            .submit(ElicitationOutcome::Accept(json!({ "answer": "late" })))
            .unwrap();

        assert_eq!(
            waiter.await.unwrap().unwrap(),
            ElicitationOutcome::Accept(json!({ "answer": "late" }))
        );
    }

    #[tokio::test]
    async fn request_and_wait_returns_decline_and_cancel_actions() {
        let manager = Arc::new(ActionRequiredManager::new());
        let mut decline_rx = manager
            .register_action_required_stream("session-a".to_string(), "tool-call-a".to_string())
            .await;
        let mut cancel_rx = manager
            .register_action_required_stream("session-b".to_string(), "tool-call-b".to_string())
            .await;
        let decline_waiter = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-a".to_string(),
                        "tool-call-a".to_string(),
                        "Need input A".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };
        let cancel_waiter = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-b".to_string(),
                        "tool-call-b".to_string(),
                        "Need input B".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };

        let decline_message = recv_elicitation_message(&mut decline_rx).await;
        let decline_request_id = elicitation_id(&decline_message);
        let cancel_message = recv_elicitation_message(&mut cancel_rx).await;
        let cancel_request_id = elicitation_id(&cancel_message);

        manager
            .claim_response("session-a", &decline_request_id)
            .await
            .unwrap()
            .submit(ElicitationOutcome::Decline)
            .unwrap();
        manager
            .claim_response("session-b", &cancel_request_id)
            .await
            .unwrap()
            .submit(ElicitationOutcome::Cancel)
            .unwrap();

        assert_eq!(
            decline_waiter.await.unwrap().unwrap(),
            ElicitationOutcome::Decline
        );
        assert_eq!(
            cancel_waiter.await.unwrap().unwrap(),
            ElicitationOutcome::Cancel
        );
    }

    #[tokio::test]
    async fn missing_tool_call_stream_errors() {
        let manager = Arc::new(ActionRequiredManager::new());

        let result = manager
            .request_and_wait(
                "session-a".to_string(),
                "missing-tool-call".to_string(),
                "Need input".to_string(),
                json!({ "type": "object" }),
                Duration::from_secs(5),
            )
            .await;

        let err = result.expect_err("request should fail without a registered stream");
        assert!(err
            .to_string()
            .contains("Tool call request not found for elicitation"));
    }

    #[tokio::test]
    async fn closed_tool_call_stream_errors() {
        let manager = Arc::new(ActionRequiredManager::new());
        let rx = manager
            .register_action_required_stream("session-a".to_string(), "tool-call-a".to_string())
            .await;
        drop(rx);

        let result = manager
            .request_and_wait(
                "session-a".to_string(),
                "tool-call-a".to_string(),
                "Need input".to_string(),
                json!({ "type": "object" }),
                Duration::from_secs(5),
            )
            .await;

        let err = result.expect_err("request should fail when stream is closed");
        assert!(err
            .to_string()
            .contains("Tool call action-required stream closed"));
    }

    #[tokio::test]
    async fn full_tool_call_stream_rejects_without_pending_state() {
        let manager = Arc::new(ActionRequiredManager::new());
        let mut action_required_rx = manager
            .register_action_required_stream("session-a".to_string(), "tool-call-a".to_string())
            .await;

        for index in 0..ACTION_REQUIRED_STREAM_CAPACITY {
            let result = manager
                .request_and_wait(
                    "session-a".to_string(),
                    "tool-call-a".to_string(),
                    format!("Fill queue {index}"),
                    json!({ "type": "object" }),
                    Duration::ZERO,
                )
                .await;
            assert!(result.is_err());
        }

        assert!(manager.pending.read().await.is_empty());

        let result = tokio::time::timeout(
            Duration::from_millis(100),
            manager.request_and_wait(
                "session-a".to_string(),
                "tool-call-a".to_string(),
                "Rejected while queue is full".to_string(),
                json!({ "type": "object" }),
                Duration::from_secs(5),
            ),
        )
        .await
        .expect("full-stream rejection must not wait for response timeout");

        assert!(result
            .expect_err("full stream should reject another elicitation")
            .to_string()
            .contains("Tool call action-required stream is full"));
        assert!(manager.pending.read().await.is_empty());

        recv_elicitation_message(&mut action_required_rx).await;
        let waiter = {
            let manager = manager.clone();
            tokio::spawn(async move {
                manager
                    .request_and_wait(
                        "session-a".to_string(),
                        "tool-call-a".to_string(),
                        "Admitted after capacity is available".to_string(),
                        json!({ "type": "object" }),
                        Duration::from_secs(5),
                    )
                    .await
            })
        };

        for _ in 1..ACTION_REQUIRED_STREAM_CAPACITY {
            recv_elicitation_message(&mut action_required_rx).await;
        }
        let admitted = recv_elicitation_message(&mut action_required_rx).await;
        manager
            .claim_response("session-a", &elicitation_id(&admitted))
            .await
            .unwrap()
            .submit(ElicitationOutcome::Accept(json!({ "answer": "accepted" })))
            .unwrap();

        assert_eq!(
            waiter.await.unwrap().unwrap(),
            ElicitationOutcome::Accept(json!({ "answer": "accepted" }))
        );
    }
}