agy-bridge 0.1.0

Rust bridge for the Google Antigravity SDK (Python) via PyO3
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
/// Async operation handlers: cancel, wait-for-idle, clear-history, send,
/// signal-idle, and wait-for-wakeup.
use std::time::Duration;

use pyo3::prelude::*;
use tokio::{sync::oneshot, time::timeout};

use super::super::{
    AgentId,
    command_loop::{
        AgentRegistry, CANCEL_FN, CANCEL_FN_NAME, CLEAR_HISTORY_FN, CLEAR_HISTORY_FN_NAME,
        DELETE_FN, DELETE_FN_NAME, DISCONNECT_FN, DISCONNECT_FN_NAME, HANDLER_TIMEOUT, SEND_FN,
        SEND_FN_NAME, SIGNAL_IDLE_FN, SIGNAL_IDLE_FN_NAME, WAIT_FOR_IDLE_FN, WAIT_FOR_IDLE_FN_NAME,
        WAIT_FOR_WAKEUP_FN, WAIT_FOR_WAKEUP_FN_NAME, get_or_compile_py_helper,
    },
    py_scripts::{
        PYTHON_CANCEL_SCRIPT, PYTHON_CLEAR_HISTORY_SCRIPT, PYTHON_DELETE_SCRIPT,
        PYTHON_DISCONNECT_SCRIPT, PYTHON_SEND_SCRIPT, PYTHON_SIGNAL_IDLE_SCRIPT,
        PYTHON_WAIT_FOR_IDLE_SCRIPT, PYTHON_WAIT_FOR_WAKEUP_SCRIPT,
    },
};
use crate::error::Error;

/// Lock the agent registry, recovering from mutex poisoning.
fn lock_registry(
    registry: &AgentRegistry,
) -> std::sync::MutexGuard<
    '_,
    std::collections::HashMap<super::super::AgentId, (pyo3::PyObject, pyo3::PyObject)>,
> {
    registry.lock().unwrap_or_else(|e| {
        tracing::error!("Agent registry mutex was poisoned, recovering: {e}");
        e.into_inner()
    })
}

pub(in crate::runtime) async fn handle_cancel(
    registry: AgentRegistry,
    agent_id: AgentId,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "Cancel reply receiver dropped (agent not found)");
        }
        return;
    };

    let cancel_helper = get_or_compile_py_helper(&CANCEL_FN, PYTHON_CANCEL_SCRIPT, CANCEL_FN_NAME);
    let cancel_fut = cancel_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound,))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let cancel_fut = match cancel_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Cancel reply receiver dropped (cancel coro error)");
            }
            return;
        }
    };

    let cancel_result = match timeout(HANDLER_TIMEOUT, cancel_fut).await {
        Ok(result) => result,
        Err(_elapsed) => {
            let err_msg = format!(
                "handle_cancel timed out after {}s for agent {agent_id}",
                HANDLER_TIMEOUT.as_secs()
            );
            tracing::error!(agent_id = ?agent_id, "{err_msg}");
            if let Err(e) = reply.send(Err(Error::Timeout {
                duration: HANDLER_TIMEOUT,
                operation: format!("cancel(agent={agent_id})"),
            })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Cancel reply receiver dropped (timeout)");
            }
            return;
        }
    };
    match cancel_result {
        Ok(_) => {
            if let Err(e) = reply.send(Ok(())) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Cancel reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Cancel reply receiver dropped (cancel error)");
            }
        }
    }
}

pub(in crate::runtime) async fn handle_wait_for_idle(
    registry: AgentRegistry,
    agent_id: AgentId,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForIdle reply receiver dropped (agent not found)");
        }
        return;
    };

    let idle_helper = get_or_compile_py_helper(
        &WAIT_FOR_IDLE_FN,
        PYTHON_WAIT_FOR_IDLE_SCRIPT,
        WAIT_FOR_IDLE_FN_NAME,
    );
    let wait_fut = idle_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound,))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let wait_fut = match wait_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForIdle reply receiver dropped (coro error)");
            }
            return;
        }
    };

    let wait_result = match timeout(HANDLER_TIMEOUT, wait_fut).await {
        Ok(result) => result,
        Err(_elapsed) => {
            let err_msg = format!(
                "handle_wait_for_idle timed out after {}s for agent {agent_id}",
                HANDLER_TIMEOUT.as_secs()
            );
            tracing::error!(agent_id = ?agent_id, "{err_msg}");
            if let Err(e) = reply.send(Err(Error::Timeout {
                duration: HANDLER_TIMEOUT,
                operation: format!("wait_for_idle(agent={agent_id})"),
            })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForIdle reply receiver dropped (timeout)");
            }
            return;
        }
    };
    match wait_result {
        Ok(_) => {
            if let Err(e) = reply.send(Ok(())) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForIdle reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForIdle reply receiver dropped (error)");
            }
        }
    }
}

/// Clear the conversation history via the async Python API.
pub(in crate::runtime) async fn handle_clear_history(
    registry: AgentRegistry,
    agent_id: AgentId,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "ClearHistory reply receiver dropped (not found)");
        }
        return;
    };

    let clear_helper = get_or_compile_py_helper(
        &CLEAR_HISTORY_FN,
        PYTHON_CLEAR_HISTORY_SCRIPT,
        CLEAR_HISTORY_FN_NAME,
    );
    let clear_fut = clear_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound,))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let clear_fut = match clear_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "ClearHistory reply receiver dropped (coro error)");
            }
            return;
        }
    };

    match clear_fut.await {
        Ok(_) => {
            if let Err(e) = reply.send(Ok(())) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "ClearHistory reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "ClearHistory reply receiver dropped (error)");
            }
        }
    }
}

pub(in crate::runtime) async fn handle_send(
    registry: AgentRegistry,
    agent_id: AgentId,
    prompt: String,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "Send reply receiver dropped (agent not found)");
        }
        return;
    };

    let send_helper = get_or_compile_py_helper(&SEND_FN, &PYTHON_SEND_SCRIPT, SEND_FN_NAME);
    let send_fut = send_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound, &prompt))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let send_fut = match send_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Send reply receiver dropped (coro error)");
            }
            return;
        }
    };

    let send_result = match timeout(HANDLER_TIMEOUT, send_fut).await {
        Ok(result) => result,
        Err(_elapsed) => {
            let err_msg = format!(
                "handle_send timed out after {}s for agent {agent_id}",
                HANDLER_TIMEOUT.as_secs()
            );
            tracing::error!(agent_id = ?agent_id, "{err_msg}");
            if let Err(e) = reply.send(Err(Error::Timeout {
                duration: HANDLER_TIMEOUT,
                operation: format!("send(agent={agent_id})"),
            })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Send reply receiver dropped (timeout)");
            }
            return;
        }
    };
    match send_result {
        Ok(_) => {
            if let Err(e) = reply.send(Ok(())) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Send reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Send reply receiver dropped (error)");
            }
        }
    }
}

pub(in crate::runtime) async fn handle_signal_idle(
    registry: AgentRegistry,
    agent_id: AgentId,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "SignalIdle reply receiver dropped (agent not found)");
        }
        return;
    };

    let idle_helper = get_or_compile_py_helper(
        &SIGNAL_IDLE_FN,
        PYTHON_SIGNAL_IDLE_SCRIPT,
        SIGNAL_IDLE_FN_NAME,
    );
    let idle_fut = idle_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound,))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let idle_fut = match idle_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "SignalIdle reply receiver dropped (coro error)");
            }
            return;
        }
    };

    let idle_result = match timeout(HANDLER_TIMEOUT, idle_fut).await {
        Ok(result) => result,
        Err(_elapsed) => {
            let err_msg = format!(
                "handle_signal_idle timed out after {}s for agent {agent_id}",
                HANDLER_TIMEOUT.as_secs()
            );
            tracing::error!(agent_id = ?agent_id, "{err_msg}");
            if let Err(e) = reply.send(Err(Error::Timeout {
                duration: HANDLER_TIMEOUT,
                operation: format!("signal_idle(agent={agent_id})"),
            })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "SignalIdle reply receiver dropped (timeout)");
            }
            return;
        }
    };
    match idle_result {
        Ok(_) => {
            if let Err(e) = reply.send(Ok(())) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "SignalIdle reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "SignalIdle reply receiver dropped (error)");
            }
        }
    }
}

pub(in crate::runtime) async fn handle_wait_for_wakeup(
    registry: AgentRegistry,
    agent_id: AgentId,
    timeout_secs: f64,
    reply: oneshot::Sender<Result<bool, Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForWakeup reply receiver dropped (agent not found)");
        }
        return;
    };

    let wakeup_helper = get_or_compile_py_helper(
        &WAIT_FOR_WAKEUP_FN,
        PYTHON_WAIT_FOR_WAKEUP_SCRIPT,
        WAIT_FOR_WAKEUP_FN_NAME,
    );
    let wakeup_fut = wakeup_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound, timeout_secs))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let wakeup_fut = match wakeup_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForWakeup reply receiver dropped (coro error)");
            }
            return;
        }
    };

    // Use Python's own timeout plus 5s headroom so the Rust side doesn't fire first.
    let wakeup_timeout = Duration::from_secs_f64(timeout_secs + 5.0);
    let wakeup_result = match timeout(wakeup_timeout, wakeup_fut).await {
        Ok(result) => result,
        Err(_elapsed) => {
            let err_msg = format!(
                "handle_wait_for_wakeup timed out after {:.1}s for agent {agent_id}",
                wakeup_timeout.as_secs_f64()
            );
            tracing::error!(agent_id = ?agent_id, "{err_msg}");
            if let Err(e) = reply.send(Err(Error::Timeout {
                duration: wakeup_timeout,
                operation: format!("wait_for_wakeup(agent={agent_id})"),
            })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForWakeup reply receiver dropped (timeout)");
            }
            return;
        }
    };
    match wakeup_result {
        Ok(result) => {
            let woken = Python::with_gil(|py| {
                result.bind(py).extract::<bool>().unwrap_or_else(|e| {
                    tracing::warn!("Extraction failed: {}", e);
                    false
                })
            });
            if let Err(e) = reply.send(Ok(woken)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForWakeup reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "WaitForWakeup reply receiver dropped (error)");
            }
        }
    }
}

/// Delete the conversation and all associated state via the async Python API.
pub(in crate::runtime) async fn handle_delete(
    registry: AgentRegistry,
    agent_id: AgentId,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "Delete reply receiver dropped (not found)");
        }
        return;
    };

    let delete_helper = get_or_compile_py_helper(&DELETE_FN, PYTHON_DELETE_SCRIPT, DELETE_FN_NAME);
    let delete_fut = delete_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound,))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let delete_fut = match delete_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Delete reply receiver dropped (coro error)");
            }
            return;
        }
    };

    let delete_result = match timeout(HANDLER_TIMEOUT, delete_fut).await {
        Ok(result) => result,
        Err(_elapsed) => {
            let err_msg = format!(
                "handle_delete timed out after {}s for agent {agent_id}",
                HANDLER_TIMEOUT.as_secs()
            );
            tracing::error!(agent_id = ?agent_id, "{err_msg}");
            if let Err(e) = reply.send(Err(Error::Timeout {
                duration: HANDLER_TIMEOUT,
                operation: format!("delete(agent={agent_id})"),
            })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Delete reply receiver dropped (timeout)");
            }
            return;
        }
    };
    match delete_result {
        Ok(_) => {
            if let Err(e) = reply.send(Ok(())) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Delete reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Delete reply receiver dropped (error)");
            }
        }
    }
}

/// Disconnect from the agent without deleting state via the async Python API.
pub(in crate::runtime) async fn handle_disconnect(
    registry: AgentRegistry,
    agent_id: AgentId,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let instance_opt = {
        {
            let lock = lock_registry(&registry);
            if let Some((c, a)) = lock.get(&agent_id) {
                Some(Python::with_gil(|py| (c.clone_ref(py), a.clone_ref(py))))
            } else {
                None
            }
        }
    };
    let Some((_ctx, agent_instance)) = instance_opt else {
        if let Err(e) = reply.send(Err(Error::BackendError {
            message: format!("Agent ID {agent_id} not found in registry"),
        })) {
            tracing::warn!(agent_id = ?agent_id, error = ?e, "Disconnect reply receiver dropped (not found)");
        }
        return;
    };

    let disconnect_helper =
        get_or_compile_py_helper(&DISCONNECT_FN, PYTHON_DISCONNECT_SCRIPT, DISCONNECT_FN_NAME);
    let disconnect_fut = disconnect_helper.and_then(|helper_fn| {
        Python::with_gil(|py| {
            let helper_bound = helper_fn.bind(py);
            let agent_bound = agent_instance.bind(py);
            let coro = helper_bound
                .call1((agent_bound,))
                .map_err(|e| format!("{e}"))?;
            pyo3_async_runtimes::tokio::into_future(coro).map_err(|e| format!("{e}"))
        })
    });

    let disconnect_fut = match disconnect_fut {
        Ok(fut) => fut,
        Err(err_msg) => {
            if let Err(e) = reply.send(Err(Error::BackendError { message: err_msg })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Disconnect reply receiver dropped (coro error)");
            }
            return;
        }
    };

    let disconnect_result = match timeout(HANDLER_TIMEOUT, disconnect_fut).await {
        Ok(result) => result,
        Err(_elapsed) => {
            let err_msg = format!(
                "handle_disconnect timed out after {}s for agent {agent_id}",
                HANDLER_TIMEOUT.as_secs()
            );
            tracing::error!(agent_id = ?agent_id, "{err_msg}");
            if let Err(e) = reply.send(Err(Error::Timeout {
                duration: HANDLER_TIMEOUT,
                operation: format!("disconnect(agent={agent_id})"),
            })) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Disconnect reply receiver dropped (timeout)");
            }
            return;
        }
    };
    match disconnect_result {
        Ok(_) => {
            if let Err(e) = reply.send(Ok(())) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Disconnect reply receiver dropped");
            }
        }
        Err(e) => {
            let err: Error = e.into();
            if let Err(e) = reply.send(Err(err)) {
                tracing::warn!(agent_id = ?agent_id, error = ?e, "Disconnect reply receiver dropped (error)");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Verify that `lock_registry` recovers from a poisoned mutex instead of
    /// panicking, and that the guard still provides access to the inner data.
    #[test]
    fn lock_registry_recovers_from_poisoned_mutex() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));

        // Poison the mutex by panicking inside a lock scope.
        let registry_clone = registry.clone();
        drop(
            std::thread::spawn(move || {
                let _guard = registry_clone.lock().unwrap();
                panic!("intentional panic to poison mutex");
            })
            .join(),
        );

        // The mutex should be poisoned now.
        assert!(registry.lock().is_err(), "Mutex should be poisoned");

        // lock_registry should recover gracefully.
        let guard = lock_registry(&registry);
        assert!(guard.is_empty());
    }

    /// Confirm that `handle_cancel` returns a `BackendError` when the agent is
    /// missing from the registry rather than panicking.
    #[tokio::test]
    async fn handle_cancel_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(9999);

        handle_cancel(registry, agent_id, tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("9999")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }

    /// Confirm that `handle_wait_for_idle` returns a `BackendError` when the
    /// agent is missing from the registry.
    #[tokio::test]
    async fn handle_wait_for_idle_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(42);

        handle_wait_for_idle(registry, agent_id, tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("42")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }

    /// Confirm that `handle_clear_history` returns a `BackendError` when the
    /// agent is missing from the registry.
    #[tokio::test]
    async fn handle_clear_history_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(77);

        handle_clear_history(registry, agent_id, tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("77")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }

    /// Confirm that `handle_send` returns a `BackendError` when the agent is
    /// missing from the registry.
    #[tokio::test]
    async fn handle_send_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(100);

        handle_send(registry, agent_id, "hello".to_owned(), tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("100")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }

    /// Confirm that `handle_signal_idle` returns a `BackendError` when the
    /// agent is missing from the registry.
    #[tokio::test]
    async fn handle_signal_idle_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(55);

        handle_signal_idle(registry, agent_id, tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("55")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }

    /// Confirm that `handle_wait_for_wakeup` returns a `BackendError` when the
    /// agent is missing from the registry.
    #[tokio::test]
    async fn handle_wait_for_wakeup_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(88);

        handle_wait_for_wakeup(registry, agent_id, 1.0, tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("88")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }

    /// `lock_registry` on a non-poisoned mutex works normally.
    #[test]
    fn lock_registry_normal_operation() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));

        let guard = lock_registry(&registry);
        assert!(guard.is_empty());
        drop(guard);

        // Can lock again after dropping.
        let guard2 = lock_registry(&registry);
        assert!(guard2.is_empty());
    }

    /// Confirm that `handle_delete` returns a `BackendError` when the agent is
    /// missing from the registry.
    #[tokio::test]
    async fn handle_delete_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(200);

        handle_delete(registry, agent_id, tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("200")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }

    /// Confirm that `handle_disconnect` returns a `BackendError` when the
    /// agent is missing from the registry.
    #[tokio::test]
    async fn handle_disconnect_missing_agent_returns_error() {
        let registry: AgentRegistry =
            std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let (tx, rx) = oneshot::channel();
        let agent_id = AgentId(300);

        handle_disconnect(registry, agent_id, tx).await;

        let result = rx.await.expect("reply channel should not be dropped");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::BackendError { ref message } if message.contains("300")),
            "Expected BackendError mentioning the agent ID, got: {err:?}"
        );
    }
}