gadk-engine 0.5.4

The gadk runtime: LLM agent and flow, workflow agents and graphs, and the runner
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The `Flow` struct and processor types, and the step loop (`run`, `run_one_step`, the model
//! call and `generate_content`).

use std::{
    collections::{BTreeMap, HashMap},
    fmt,
    sync::Arc,
};

use futures::{StreamExt, future::BoxFuture, stream::BoxStream};
use gadk_agent::{
    AfterModelCallback, AfterToolCallback, Agent, AgentError, BeforeModelCallback,
    BeforeToolCallback, CancelCause, Context, ContextDelta, EventStream, InvocationContext,
    OnModelErrorCallback, OnToolErrorCallback, StreamingMode, Tool, tool_from_request,
};
use gadk_genai::Content;
use gadk_model::{Llm, LlmRequest, LlmResponse, ModelError};
use gadk_session::{Event, EventActions};
use serde_json::{Map, Value};

use crate::{
    llm::{
        functions::{
            generate_auth_event, generate_request_confirmation_event, handle_function_calls,
        },
        live::reconnect::LiveReconnectPolicy,
        processors::{
            output_schema::{
                create_final_model_response_event, retrieve_structured_model_response,
            },
            tools::{tool_preprocess, toolset_preprocess},
        },
        transfer::transfer_target_agents,
    },
    telemetry::{attrs::GenerateContentParams, instrumentation::instrument_generate_content},
    tool::utils::{function_calls, function_responses, populate_client_function_call_id},
    workflow::route::go_quote,
};

/// A request processor. Returns the events the processor emits; the flow yields them in order.
pub(crate) type RequestProcessor = for<'a> fn(
    &'a InvocationContext,
    &'a mut LlmRequest,
    &'a Flow,
) -> BoxFuture<'a, Result<Vec<Event>, AgentError>>;

/// A response processor: edits the model response in place.
pub(crate) type ResponseProcessor = for<'a> fn(
    &'a InvocationContext,
    &'a LlmRequest,
    &'a mut LlmResponse,
) -> Result<(), AgentError>;

/// The LLM flow: model, tools, processors and callbacks.
#[derive(Default)]
pub(crate) struct Flow {
    pub(crate) model: Option<Arc<dyn Llm>>,
    /// The tools of the current step. The tools processor (slot 2) rewrites it on every step,
    /// and the request-confirmation processor and `tool_preprocess` read it. Interior
    /// mutability is needed because processors get `&Flow`. Never hold the guard across an
    /// `.await`. There is no `toolsets` field: the processors read toolsets through
    /// `reveal(ctx.agent())`.
    pub(crate) tools: parking_lot::RwLock<Vec<Arc<dyn Tool>>>,
    pub(crate) request_processors: Vec<RequestProcessor>,
    pub(crate) response_processors: Vec<ResponseProcessor>,
    pub(crate) before_model_callbacks: Vec<BeforeModelCallback>,
    pub(crate) after_model_callbacks: Vec<AfterModelCallback>,
    pub(crate) on_model_error_callbacks: Vec<OnModelErrorCallback>,
    pub(crate) before_tool_callbacks: Vec<BeforeToolCallback>,
    pub(crate) after_tool_callbacks: Vec<AfterToolCallback>,
    pub(crate) on_tool_error_callbacks: Vec<OnToolErrorCallback>,
    /// Bounds `run_live`'s reconnect attempts. `None` means the defaults;
    /// only tests set it, to shrink the delays.
    pub(crate) live_reconnect: Option<LiveReconnectPolicy>,
}

/// A safety net against a model that only
/// ever "thinks"; deliberately not configurable.
pub(crate) const MAX_CONSECUTIVE_THOUGHT_ONLY_TURNS: usize = 10;

/// Error text when the flow has no model.
pub(crate) const ERR_MODEL_NOT_CONFIGURED: &str =
    "model not configured; ensure LlmAgentConfig::model is set";

/// The step's callback actions: shared by the model callbacks and stamped on every model-response
/// event of the step (the state-delta and artifact-delta maps).
type SharedActions = Arc<parking_lot::Mutex<EventActions>>;

impl Flow {
    /// Runs steps until a final response, a partial last
    /// event, or too many consecutive thought-only turns.
    pub(crate) fn run(self: Arc<Self>, ctx: InvocationContext) -> EventStream {
        Box::pin(async_stream::try_stream! {
            let mut thought_only_turns = 0usize;
            loop {
                let mut last_event: Option<Event> = None;
                let mut step = self.clone().run_one_step(ctx.clone());
                while let Some(item) = step.next().await {
                    let ev = item?;
                    last_event = Some(ev.clone());
                    // Forward the event first.
                    yield ev;
                }
                let Some(last) = last_event else { break };
                if last.is_final_response() {
                    // A thought-only turn reports as final but has no answer: call the model
                    // again, up to the bound.
                    if !is_thought_only_turn(Some(&last)) {
                        break;
                    }
                    thought_only_turns += 1;
                    if thought_only_turns >= MAX_CONSECUTIVE_THOUGHT_ONLY_TURNS {
                        let model = self.model.as_ref().map(|m| m.name().to_owned()).unwrap_or_default();
                        tracing::warn!(
                            target: "adk",
                            "adk: model {} produced {} consecutive thought-only turns without an answer (limit {}) for agent {} (invocation {}); giving up and returning the last thinking event",
                            go_quote(&model),
                            thought_only_turns,
                            MAX_CONSECUTIVE_THOUGHT_ONLY_TURNS,
                            go_quote(ctx.agent().name()),
                            go_quote(ctx.invocation_id())
                        );
                        break;
                    }
                } else {
                    thought_only_turns = 0;
                }
                if last.response.partial {
                    // A producer ended its stream without a terminal aggregate: the turn was
                    // truncated, so stop instead of looping again.
                    tracing::warn!(
                        target: "adk",
                        "adk: agent {} (invocation {}): step ended on a partial event from {}; the producer did not close its stream with an aggregated final event, so the turn will not appear in session history",
                        go_quote(ctx.agent().name()),
                        go_quote(ctx.invocation_id()),
                        go_quote(&last.author)
                    );
                    break;
                }
            }
        })
    }

    /// Runs one step: preprocess, the model call (with its
    /// callbacks), function calls, the confirmation and structured-output events, and the
    /// `transfer_to_agent` dispatch.
    pub(crate) fn run_one_step(self: Arc<Self>, ctx: InvocationContext) -> EventStream {
        Box::pin(async_stream::try_stream! {
            'step: {
                let model = self.model.clone().ok_or_else(|| {
                    AgentError::Config(format!(
                        "agent {}: {}",
                        go_quote(ctx.agent().name()),
                        ERR_MODEL_NOT_CONFIGURED
                    ))
                })?;

                let mut req = LlmRequest {
                    model: model.name().to_owned(),
                    ..Default::default()
                };
                let mut preprocess_yielded_final_response = false;
                {
                    // Each processor's events are yielded as they are produced, so they are in
                    // the session before a later processor (contents) reads it (the resumed
                    // tool's response comes from the confirmation processor and must reach the
                    // same step's request).
                    let mut pre = self.preprocess(&ctx, &mut req);
                    while let Some(ev) = pre.next().await {
                        let ev = ev?;
                        if !function_responses(ev.response.content.as_ref()).is_empty()
                            && ev.is_final_response()
                        {
                            preprocess_yielded_final_response = true;
                        }
                        yield ev;
                    }
                }
                // A preprocessor can run a tool itself, such as a call resumed after
                // confirmation. When that tool's response is final, because the tool set
                // skip_summarization, the turn ends there, as it does when the tool runs after a
                // model call.
                if ctx.ended() || preprocess_yielded_final_response {
                    break 'step;
                }

                let actions: SharedActions = Arc::new(parking_lot::Mutex::new(EventActions {
                    state_delta: Some(Map::new()),
                    artifact_delta: Some(BTreeMap::new()),
                    ..Default::default()
                }));

                // Before-model callbacks, plugins first. `Some`
                // response short-circuits the model call (and the after-model callbacks).
                let mut short_circuit: Option<LlmResponse> = None;
                if let Some(pm) = ctx.plugin_manager() {
                    let (r, res) = pm
                        .run_before_model(callback_ctx(&ctx, &actions), std::mem::take(&mut req))
                        .await;
                    req = r;
                    match res {
                        Ok(r) => short_circuit = r,
                        Err(e) => {
                            // A UUID is consumed before the error.
                            let _ = ctx.platform().new_uuid();
                            Err::<(), AgentError>(e)?;
                        }
                    }
                }
                if short_circuit.is_none() {
                    for cb in &self.before_model_callbacks {
                        let (r, res) = cb(callback_ctx(&ctx, &actions), std::mem::take(&mut req)).await;
                        req = r;
                        match res {
                            Ok(Some(resp)) => {
                                short_circuit = Some(resp);
                                break;
                            }
                            Ok(None) => {}
                            Err(e) => {
                                let _ = ctx.platform().new_uuid();
                                Err::<(), AgentError>(e)?;
                            }
                        }
                    }
                }
                let mut responses: BoxStream<'static, Result<(LlmResponse, String), AgentError>> =
                    match short_circuit {
                        Some(resp) => {
                            let id = ctx.platform().new_uuid();
                            futures::stream::once(futures::future::ready(Ok((resp, id)))).boxed()
                        }
                        // The CURRENT request (with callback edits) is what the model sees.
                        None => self
                            .clone()
                            .call_model(ctx.clone(), model.clone(), req.clone(), actions.clone()),
                    };

                while let Some(item) = responses.next().await {
                    let (mut resp, event_id) = item?;
                    self.postprocess(&ctx, &req, &mut resp)?;
                    // Skip a response with no content, error code, interruption or grounding
                    // metadata (the code executor relies on this to trigger another loop).
                    if resp.content.is_none()
                        && resp.error_code.is_empty()
                        && !resp.interrupted
                        && resp.grounding_metadata.is_none()
                    {
                        continue;
                    }
                    let tools = tools_from_request(&req)?;
                    let model_ev = finalize_model_response_event(&ctx, resp, event_id, &tools, &actions);
                    yield model_ev.clone();
                    if model_ev.response.partial {
                        continue;
                    }
                    let Some(fr_ev) = handle_function_calls(&ctx, &self, &tools, &model_ev, None).await? else {
                        continue;
                    };
                    let confirmation_ev = generate_request_confirmation_event(&ctx, &model_ev, &fr_ev);
                    // Function responses before confirmation and credential requests, so consumers
                    // that pause for the user still persist completed tool results. Asking the
                    // user to sign in ends the invocation.
                    let auth_ev = generate_auth_event(&ctx, &fr_ev);
                    yield fr_ev.clone();
                    if let Some(a) = auth_ev {
                        ctx.end_invocation();
                        yield a;
                    }
                    if let Some(c) = confirmation_ev {
                        yield c;
                    }
                    let structured = retrieve_structured_model_response(Some(&fr_ev))?;
                    if !structured.is_empty() {
                        yield create_final_model_response_event(&ctx, &structured);
                    }
                    if fr_ev.actions.transfer_to_agent.is_empty() {
                        break 'step;
                    }
                    let next = self
                        .agent_to_run(&ctx, &fr_ev.actions.transfer_to_agent)
                        .ok_or_else(|| {
                            AgentError::other(format!(
                                "failed to find agent: {}",
                                fr_ev.actions.transfer_to_agent
                            ))
                        })?;
                    // An LlmAgent target runs through the node
                    // wrapper with a promoted context and a null node input; any other agent runs
                    // directly.
                    let mut s = if crate::llm::state::reveal(&*next).is_some() {
                        crate::llm::node_wrapper::run_llm_agent_as_node(
                            ctx.clone().into_context(),
                            next,
                            Value::Null,
                        )
                    } else {
                        next.run(ctx.clone())
                    };
                    // Forward, stopping on the first error.
                    while let Some(item) = s.next().await {
                        yield item?;
                    }
                }
            }
        })
    }

    /// Runs the request processors, then
    /// `tool_preprocess` over `Flow.tools` and `toolset_preprocess`. Each processor's events are
    /// yielded before the next processor runs, so the caller can append
    /// them to the session first. The events of a failing processor are dropped (those of
    /// earlier processors were yielded).
    pub(crate) fn preprocess<'a>(
        &'a self,
        ctx: &'a InvocationContext,
        req: &'a mut LlmRequest,
    ) -> BoxStream<'a, Result<Event, AgentError>> {
        Box::pin(async_stream::try_stream! {
            for p in &self.request_processors {
                for ev in p(ctx, &mut *req, self).await? {
                    yield ev;
                }
            }
            // Never hold the guard across an .await.
            let tools = self.tools.read().clone();
            tool_preprocess(ctx, &mut *req, &tools).await?;
            toolset_preprocess(ctx, &mut *req).await?;
        })
    }

    /// The model half of a step:
    /// streaming flag, the LLM-call limit, the model call, the on-model-error and after-model
    /// callbacks. Each item carries the event ID reserved for its response.
    pub(crate) fn call_model(
        self: Arc<Self>,
        ctx: InvocationContext,
        model: Arc<dyn Llm>,
        req: LlmRequest,
        actions: SharedActions,
    ) -> BoxStream<'static, Result<(LlmResponse, String), AgentError>> {
        Box::pin(async_stream::try_stream! {
            // Streaming mode comes from the invocation context's RunConfig.
            let use_stream = ctx.run_config().streaming_mode == StreamingMode::Sse;
            // Count this call before making it; no limiter means no limit.
            if let Some(l) = ctx.llm_call_limiter() {
                l.increment_and_enforce()?;
            }
            let token = ctx.cancellation_token().clone();
            // An already-ended context skips the model call (and its span); the cancellation
            // is then handled as one that ends the call below. Rust
            // models do not observe the context, so the model is not called with it.
            let mut inner = (!token.is_cancelled())
                .then(|| generate_content(&ctx, model, req.clone(), use_stream));
            loop {
                let next = match inner.as_mut() {
                    None => None,
                    // Model first: an already-ready response wins over the cancellation;
                    // the cancellation ends the call only while the model is pending.
                    Some(inner) => tokio::select! {
                        biased;
                        n = inner.next() => Some(n),
                        _ = token.cancelled() => None,
                    },
                };
                // A cancelled call yields the context's error, which runs the on-model-error
                // callbacks. Rust models do not see the context, so the flow ends the call and
                // yields that error for it.
                let (item, event_id, cancelled) = match next {
                    None => (
                        Err(ModelError::Other(Box::new(context_err(&ctx)))),
                        ctx.platform().new_uuid(),
                        true,
                    ),
                    Some(None) => break,
                    Some(Some((item, event_id))) => (item, event_id, false),
                };
                let mut resp = match item {
                    Ok(r) => r,
                    Err(model_err) => {
                        let err = Arc::new(model_err);
                        match self.run_on_model_error_callbacks(&ctx, &req, &actions, err.clone()).await {
                            Err(cb_err) => {
                                Err::<(), AgentError>(cb_err)?;
                                break;
                            }
                            // The model's error is yielded as is: for a cancelled call that is
                            // the context's error, `AgentError::Cancelled` / `DeadlineExceeded`.
                            Ok(None) if cancelled => {
                                Err::<(), AgentError>(context_err(&ctx))?;
                                break;
                            }
                            Ok(None) => {
                                Err::<(), AgentError>(model_error_into_agent(err))?;
                                break;
                            }
                            Ok(Some(r)) => r,
                        }
                    }
                };
                // Function call IDs are optional in genai; set them for the after-model callbacks.
                populate_client_function_call_id(ctx.platform(), resp.content.as_mut());
                // The model error argument is always None here. The
                // callbacks hand the (possibly edited) response back; it is yielded when no
                // callback replaces it.
                let (resp, res) = self.run_after_model_callbacks(&ctx, resp, &actions).await;
                match res? {
                    Some(r) => yield (inherit_model_fields(&resp, r), event_id),
                    None => yield (resp, event_id),
                }
                // A cancelled call ends after yielding: a callback's reply ends the call.
                if cancelled {
                    break;
                }
            }
        })
    }

    /// Runs the after-model callbacks: plugins first; the first `Some`/`Err`
    /// wins. The response is threaded through every callback (plugins, then the agent's) and
    /// handed back, so an edit made by one callback reaches the next and the flow.
    async fn run_after_model_callbacks(
        &self,
        ctx: &InvocationContext,
        mut resp: LlmResponse,
        actions: &SharedActions,
    ) -> (LlmResponse, Result<Option<LlmResponse>, AgentError>) {
        if let Some(pm) = ctx.plugin_manager() {
            let (r, res) = pm
                .run_after_model(callback_ctx(ctx, actions), resp, None)
                .await;
            resp = r;
            match res {
                Ok(None) => {}
                other => return (resp, other),
            }
        }
        for cb in &self.after_model_callbacks {
            let (r, res) = cb(callback_ctx(ctx, actions), resp, None).await;
            resp = r;
            match res {
                Ok(None) => {}
                other => return (resp, other),
            }
        }
        (resp, Ok(None))
    }

    /// Runs the on-model-error callbacks: plugins first; the first `Some`/`Err`
    /// wins.
    async fn run_on_model_error_callbacks(
        &self,
        ctx: &InvocationContext,
        req: &LlmRequest,
        actions: &SharedActions,
        err: Arc<ModelError>,
    ) -> Result<Option<LlmResponse>, AgentError> {
        if let Some(pm) = ctx.plugin_manager()
            && let Some(r) = pm
                .run_on_model_error(callback_ctx(ctx, actions), req.clone(), err.clone())
                .await?
        {
            return Ok(Some(r));
        }
        for cb in &self.on_model_error_callbacks {
            if let Some(r) = cb(callback_ctx(ctx, actions), req.clone(), err.clone()).await? {
                return Ok(Some(r));
            }
        }
        Ok(None)
    }

    /// Runs the response processors in order.
    fn postprocess(
        &self,
        ctx: &InvocationContext,
        req: &LlmRequest,
        resp: &mut LlmResponse,
    ) -> Result<(), AgentError> {
        for p in &self.response_processors {
            p(ctx, req, resp)?;
        }
        Ok(())
    }

    /// The transfer target named `name`, searched among the
    /// current agent's transfer targets (not the whole tree, unlike adk-python).
    fn agent_to_run(&self, ctx: &InvocationContext, name: &str) -> Option<Arc<dyn Agent>> {
        transfer_target_agents(ctx, &ctx.agent())
            .into_iter()
            .find(|a| a.name() == name)
    }
}

/// Carries the fields that describe the
/// model call, rather than the response content, from a response onto the after-model
/// callback's replacement for it. A partial original keeps its replacement partial, a response
/// that ended the turn keeps its replacement ending it, and the original's usage metadata fills
/// a replacement that has none.
fn inherit_model_fields(original: &LlmResponse, mut replacement: LlmResponse) -> LlmResponse {
    if original.partial {
        replacement.partial = true;
    }
    if original.turn_complete {
        replacement.turn_complete = true;
    }
    if replacement.usage_metadata.is_none() {
        replacement.usage_metadata = original.usage_metadata.clone();
    }
    replacement
}

/// A callback context recording into `actions`.
fn callback_ctx(ctx: &InvocationContext, actions: &SharedActions) -> Context {
    ctx.clone().into_context().with_delta(ContextDelta {
        actions: Some(actions.clone()),
        ..Default::default()
    })
}

/// A model error still shared by a callback that kept a clone of its `Arc`.
#[derive(Debug)]
struct SharedModelError(Arc<ModelError>);

impl fmt::Display for SharedModelError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&*self.0, f)
    }
}

impl std::error::Error for SharedModelError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&*self.0)
    }
}

/// The error for an ended context: `AgentError::DeadlineExceeded` when its deadline passed,
/// else `AgentError::Cancelled` (whatever the cancellation cause). Shared by
/// the LLM flow (the model yields the context's error) and the parallel worker.
pub(crate) fn context_err(ctx: &InvocationContext) -> AgentError {
    match ctx.cause() {
        Some(CancelCause::DeadlineExceeded) => AgentError::DeadlineExceeded,
        _ => AgentError::Cancelled,
    }
}

/// The model error as an `AgentError::Model`, or `AgentError::Other` (same text) when a callback
/// still holds the `Arc`. Shared with the `function_call_modifier` plugin's after-model callback.
pub(crate) fn model_error_into_agent(err: Arc<ModelError>) -> AgentError {
    match Arc::try_unwrap(err) {
        Ok(e) => AgentError::Model(e),
        Err(shared) => AgentError::Other(Box::new(SharedModelError(shared))),
    }
}

/// The tools map of a step: every packed request tool as an `Arc<dyn Tool>`.
fn tools_from_request(req: &LlmRequest) -> Result<HashMap<String, Arc<dyn Tool>>, AgentError> {
    let mut tools = HashMap::with_capacity(req.tools.len());
    for k in req.tools.keys() {
        let Some(t) = tool_from_request(req, k) else {
            return Err(AgentError::other(format!(
                "unexpected tool type for tool {k}"
            )));
        };
        tools.insert(k.clone(), t);
    }
    Ok(tools)
}

/// Builds the event for a model response: the reserved `event_id`, the agent's name and branch,
/// the step's state and artifact deltas, and the long-running tool call IDs.
fn finalize_model_response_event(
    ctx: &InvocationContext,
    mut resp: LlmResponse,
    event_id: String,
    tools: &HashMap<String, Arc<dyn Tool>>,
    actions: &SharedActions,
) -> Event {
    // Matching function calls and responses needs non-empty call IDs.
    populate_client_function_call_id(ctx.platform(), resp.content.as_mut());
    // `Event::new` consumes a UUID even though the ID is then replaced.
    let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
    ev.id = event_id;
    ev.author = ctx.agent().name().to_owned();
    ev.branch = ctx.branch();
    {
        let a = actions.lock();
        ev.actions.state_delta = a.state_delta.clone();
        ev.actions.artifact_delta = a.artifact_delta.clone();
    }
    ev.long_running_tool_ids = find_long_running_function_call_ids(resp.content.as_ref(), tools);
    ev.response = resp;
    ev
}

/// IDs of calls (non-empty ID) to
/// long-running tools, deduplicated, in call order.
pub(crate) fn find_long_running_function_call_ids(
    c: Option<&Content>,
    tools: &HashMap<String, Arc<dyn Tool>>,
) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for fc in function_calls(c) {
        if !fc.id.is_empty()
            && tools.get(&fc.name).is_some_and(|t| t.is_long_running())
            && !out.contains(&fc.id)
        {
            out.push(fc.id.clone());
        }
    }
    out
}

/// Whether the event is a
/// thoughts.
pub(crate) fn is_thought_only_turn(ev: Option<&Event>) -> bool {
    let Some(ev) = ev.filter(|e| !e.response.partial) else {
        return false;
    };
    let Some(c) = ev.response.content.as_ref().filter(|c| !c.parts.is_empty()) else {
        return false;
    };
    c.parts.iter().all(|p| p.thought)
}

/// The model call inside
/// a `generate_content` span, which covers only the model
/// call (callbacks and plugins stay outside it). Each item carries an event ID:
/// the partial chunks of a streamed response share one ID with the response that completes
/// them. A complete response ends the ID, and so does an error, because an on-model-error
/// callback may turn it into a saved event. A new ID is drawn when the next item arrives, never
/// ahead of one.
pub(crate) fn generate_content(
    ctx: &InvocationContext,
    model: Arc<dyn Llm>,
    req: LlmRequest,
    stream: bool,
) -> BoxStream<'static, (Result<LlmResponse, ModelError>, String)> {
    let params = GenerateContentParams {
        model_name: model.name().to_owned(),
        invocation_id: ctx.invocation_id().to_owned(),
        backend: gadk_model::google_variant(model.as_ref()),
        stream,
    };
    let platform = ctx.platform().clone();
    instrument_generate_content(params, req, move |req| {
        let mut event_id = String::new();
        model
            .generate_content(req, stream)
            .map(move |item| {
                if event_id.is_empty() {
                    event_id = platform.new_uuid();
                }
                let id = match &item {
                    Ok(r) if r.partial => event_id.clone(),
                    _ => std::mem::take(&mut event_id),
                };
                (item, id)
            })
            .boxed()
    })
}

#[cfg(test)]
mod tests {
    use std::{any::Any, sync::Arc};

    use async_trait::async_trait;
    use futures::StreamExt;
    use gadk_agent::{
        AgentConfig, AgentError, BeforeModelCallback, Context, InvocationContext,
        OnModelErrorCallback, ParentMap, RunnableTool, Tool, ToolError, agent,
        run_limits::LlmCallLimiter,
    };
    use gadk_genai::{Content, FunctionCall, FunctionDeclaration, Part};
    use gadk_model::{LlmResponse, ModelError};
    use gadk_session::Event;
    use pretty_assertions::assert_eq;
    use serde_json::{Map, Value, json};

    use super::*;
    use crate::{
        llm::{
            config::LlmAgentConfig,
            processors::{default_request_processors, test_llm_agent},
        },
        testutil::MockModel,
    };

    fn named_agent(name: &str) -> Arc<dyn Agent> {
        agent::new(AgentConfig {
            name: name.into(),
            ..Default::default()
        })
        .unwrap()
    }

    fn ctx_for(name: &str) -> InvocationContext {
        InvocationContext::builder()
            .agent(named_agent(name))
            .build_invocation()
    }

    fn text_resp(t: &str) -> LlmResponse {
        LlmResponse {
            content: Some(Content {
                role: "model".into(),
                parts: vec![Part {
                    text: t.into(),
                    ..Default::default()
                }],
            }),
            ..Default::default()
        }
    }

    fn call_resp(id: &str, name: &str, args: Value) -> LlmResponse {
        LlmResponse {
            content: Some(Content {
                role: "model".into(),
                parts: vec![Part {
                    function_call: Some(FunctionCall {
                        id: id.into(),
                        name: name.into(),
                        args: args.as_object().cloned().unwrap_or_default(),
                        ..Default::default()
                    }),
                    ..Default::default()
                }],
            }),
            ..Default::default()
        }
    }

    fn texts(events: &[Event]) -> Vec<String> {
        events
            .iter()
            .filter_map(|e| e.response.content.as_ref())
            .flat_map(|c| {
                c.parts
                    .iter()
                    .filter(|p| !p.text.is_empty())
                    .map(|p| p.text.clone())
            })
            .collect()
    }

    async fn run_all(flow: Flow, ctx: InvocationContext) -> Vec<Result<Event, AgentError>> {
        Arc::new(flow).run(ctx).collect().await
    }

    /// A no-op tool, optionally long-running. It has a declaration, as every callable Go tool
    /// does: Go tools pack themselves in ProcessRequest, and the Rust flow packs only declared
    /// tools, so a declaration-less tool would never reach `req.tools`.
    struct Noop {
        name: &'static str,
        long_running: bool,
    }

    impl Tool for Noop {
        fn name(&self) -> &str {
            self.name
        }
        fn description(&self) -> &str {
            "noop"
        }
        fn is_long_running(&self) -> bool {
            self.long_running
        }
        fn declaration(&self) -> Option<FunctionDeclaration> {
            Some(FunctionDeclaration {
                name: self.name.into(),
                ..Default::default()
            })
        }
        fn as_runnable(&self) -> Option<&dyn RunnableTool> {
            Some(self)
        }
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[async_trait]
    impl RunnableTool for Noop {
        async fn run(&self, _: Context, _: Value) -> Result<Map<String, Value>, ToolError> {
            Ok(Map::new())
        }
    }

    #[tokio::test]
    async fn model_not_configured_error_text() {
        let items = run_all(Flow::default(), ctx_for("a")).await;
        assert_eq!(items.len(), 1);
        let err = items.into_iter().next().unwrap().unwrap_err();
        assert_eq!(
            err.to_string(),
            "agent \"a\": model not configured; ensure LlmAgentConfig::model is set"
        );
    }

    #[tokio::test]
    async fn before_model_callback_short_circuits() {
        let model = MockModel::new(vec![Ok(text_resp("model"))]);
        let cb: BeforeModelCallback =
            Arc::new(|_, req| Box::pin(async move { (req, Ok(Some(text_resp("cb")))) }));
        let flow = Flow {
            model: Some(model.clone()),
            before_model_callbacks: vec![cb],
            ..Default::default()
        };
        let events: Vec<Event> = run_all(flow, ctx_for("a"))
            .await
            .into_iter()
            .map(Result::unwrap)
            .collect();
        assert_eq!(texts(&events), ["cb"]);
        assert_eq!(events.len(), 1);
        assert!(model.requests().is_empty(), "model must not be called");
    }

    #[tokio::test]
    async fn before_model_callback_request_edits_reach_model() {
        let model = MockModel::new(vec![Ok(text_resp("ok"))]);
        let cb: BeforeModelCallback = Arc::new(|_, mut req| {
            Box::pin(async move {
                req.model = "x".into();
                (req, Ok(None))
            })
        });
        let flow = Flow {
            model: Some(model.clone()),
            before_model_callbacks: vec![cb],
            ..Default::default()
        };
        let items = run_all(flow, ctx_for("a")).await;
        assert!(items.iter().all(Result::is_ok));
        let reqs = model.requests();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].model, "x");
    }

    #[tokio::test]
    async fn on_model_error_callback_recovers() {
        let model = MockModel::new(vec![Err(ModelError::Other("boom".into()))]);
        let cb: OnModelErrorCallback = Arc::new(|_, _, err| {
            assert_eq!(err.to_string(), "boom");
            Box::pin(async move { Ok(Some(text_resp("recovered"))) })
        });
        let flow = Flow {
            model: Some(model),
            on_model_error_callbacks: vec![cb],
            ..Default::default()
        };
        let events: Vec<Event> = run_all(flow, ctx_for("a"))
            .await
            .into_iter()
            .map(Result::unwrap)
            .collect();
        assert_eq!(texts(&events), ["recovered"]);
    }

    #[tokio::test]
    async fn model_error_without_callback_is_returned() {
        let model = MockModel::new(vec![Err(ModelError::Other("boom".into()))]);
        let flow = Flow {
            model: Some(model),
            ..Default::default()
        };
        let items = run_all(flow, ctx_for("a")).await;
        assert_eq!(items.len(), 1);
        let err = items.into_iter().next().unwrap().unwrap_err();
        assert!(matches!(err, AgentError::Model(_)), "{err:?}");
        assert_eq!(err.to_string(), "boom");
    }

    #[tokio::test]
    async fn long_running_tool_without_result_emits_no_response() {
        let lr: Arc<dyn Tool> = Arc::new(Noop {
            name: "lr",
            long_running: true,
        });
        let flow = Flow {
            model: Some(MockModel::new(vec![Ok(call_resp("fc1", "lr", json!({})))])),
            tools: parking_lot::RwLock::new(vec![lr.clone()]),
            ..Default::default()
        };
        let events: Vec<Event> = run_all(flow, ctx_for("a"))
            .await
            .into_iter()
            .map(Result::unwrap)
            .collect();
        // Only the model event: the long-running call has no response, and the event is final.
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].long_running_tool_ids, ["fc1"]);

        let tools = HashMap::from([("lr".to_owned(), lr)]);
        let got = handle_function_calls(&ctx_for("a"), &Flow::default(), &tools, &events[0], None)
            .await
            .unwrap();
        assert!(got.is_none());
    }

    #[tokio::test]
    async fn transfer_runs_target_agent() {
        let c = agent::new(AgentConfig {
            name: "c".into(),
            description: "child".into(),
            run: Some(Arc::new(|ctx: InvocationContext| {
                Box::pin(futures::stream::once(async move {
                    let mut ev = Event::new(ctx.platform(), ctx.invocation_id());
                    ev.author = "c".into();
                    ev.response = text_resp("from c");
                    Ok(ev)
                }))
            })),
            ..Default::default()
        })
        .unwrap();
        let model = MockModel::new(vec![Ok(call_resp(
            "fc1",
            "transfer_to_agent",
            json!({"agent_name": "c"}),
        ))]);
        let root = test_llm_agent(LlmAgentConfig {
            name: "root".into(),
            model: Some(model.clone()),
            sub_agents: vec![c],
            ..Default::default()
        });
        let pm = Arc::new(ParentMap::new(&root).unwrap());
        let ctx = InvocationContext::builder()
            .agent(root)
            .parent_map(pm)
            .build_invocation();
        let flow = Flow {
            model: Some(model),
            request_processors: default_request_processors(),
            ..Default::default()
        };
        let events: Vec<Event> = run_all(flow, ctx)
            .await
            .into_iter()
            .map(Result::unwrap)
            .collect();
        assert_eq!(events.len(), 3, "{events:#?}");
        let call = &events[0].response.content.as_ref().unwrap().parts[0];
        assert_eq!(
            call.function_call.as_ref().unwrap().name,
            "transfer_to_agent"
        );
        let resp = &events[1].response.content.as_ref().unwrap().parts[0];
        assert_eq!(resp.function_response.as_ref().unwrap().id, "fc1");
        assert_eq!(events[1].actions.transfer_to_agent, "c");
        assert_eq!(events[2].author, "c");
        assert_eq!(texts(&events[2..]), ["from c"]);
    }

    #[tokio::test]
    async fn llm_call_limit_exceeded() {
        let noop: Arc<dyn Tool> = Arc::new(Noop {
            name: "noop",
            long_running: false,
        });
        let model = MockModel::new(vec![
            Ok(call_resp("", "noop", json!({}))),
            Ok(call_resp("", "noop", json!({}))),
        ]);
        let flow = Flow {
            model: Some(model.clone()),
            tools: parking_lot::RwLock::new(vec![noop]),
            ..Default::default()
        };
        let ctx = InvocationContext::builder()
            .agent(named_agent("a"))
            .llm_call_limiter(Arc::new(LlmCallLimiter::new(1)))
            .build_invocation();
        let items = run_all(flow, ctx).await;
        // Step 1: the call and its response; step 2 fails before calling the model.
        assert_eq!(items.len(), 3);
        assert!(items[..2].iter().all(Result::is_ok));
        let err = items.into_iter().nth(2).unwrap().unwrap_err();
        assert!(
            matches!(err, AgentError::LlmCallsLimitExceeded { limit: 1 }),
            "{err:?}"
        );
        assert_eq!(
            err.to_string(),
            "max number of llm calls exceeded: limit is 1"
        );
        assert_eq!(model.requests().len(), 1);
    }

    #[derive(serde::Deserialize, schemars::JsonSchema)]
    struct NoArgs {}

    #[tokio::test]
    async fn confirmation_required_error_carries_go_tool_prefix() {
        use gadk_agent::AfterToolCallback;

        use crate::tool::{FunctionTool, FunctionToolConfig};

        let secure = FunctionTool::new(
            FunctionToolConfig {
                require_confirmation: true,
                ..FunctionToolConfig::new("secure_action", "needs approval")
            },
            |_ctx: Context, _: NoArgs| async move { Ok::<_, ToolError>(json!({"done": true})) },
        )
        .unwrap();
        let seen: Arc<parking_lot::Mutex<Option<(String, bool)>>> = Arc::default();
        let seen_cb = seen.clone();
        let after: AfterToolCallback = Arc::new(move |_, _, _, _, err| {
            let err = err.expect("after callback sees the tool error");
            // The sentinel stays reachable through source() (Go errors.Is).
            let mut src: Option<&(dyn std::error::Error + 'static)> = Some(&*err);
            let mut is_required = false;
            while let Some(e) = src {
                is_required |= matches!(
                    e.downcast_ref::<ToolError>(),
                    Some(ToolError::ConfirmationRequired)
                );
                src = e.source();
            }
            *seen_cb.lock() = Some((err.to_string(), is_required));
            Box::pin(async { Ok(None) })
        });
        let flow = Flow {
            model: Some(MockModel::new(vec![Ok(call_resp(
                "fc1",
                "secure_action",
                json!({}),
            ))])),
            tools: parking_lot::RwLock::new(vec![secure]),
            after_tool_callbacks: vec![after],
            ..Default::default()
        };
        let events: Vec<Event> = run_all(flow, ctx_for("a"))
            .await
            .into_iter()
            .map(Result::unwrap)
            .collect();
        let want = "error tool \"secure_action\" requires confirmation, please approve or reject";
        let fr = events[1].response.content.as_ref().unwrap().parts[0]
            .function_response
            .clone()
            .unwrap();
        assert_eq!(
            fr.response,
            json!({"error": want}).as_object().unwrap().clone()
        );
        assert_eq!(*seen.lock(), Some((want.to_owned(), true)));
        // The confirmation request follows the response event.
        let req = events[2].response.content.as_ref().unwrap().parts[0]
            .function_call
            .clone()
            .unwrap();
        assert_eq!(
            req.name,
            gadk_agent::REQUEST_CONFIRMATION_FUNCTION_CALL_NAME
        );
    }

    #[tokio::test]
    async fn cancelled_token_stops_model_call() {
        let model = MockModel::new(vec![Ok(text_resp("never"))]);
        let token = tokio_util::sync::CancellationToken::new();
        token.cancel();
        let ctx = InvocationContext::builder()
            .agent(named_agent("a"))
            .cancellation_token(token)
            .build_invocation();
        let flow = Flow {
            model: Some(model.clone()),
            ..Default::default()
        };
        let items = run_all(flow, ctx).await;
        assert_eq!(items.len(), 1);
        assert!(matches!(items[0], Err(AgentError::Cancelled)));
        assert!(model.requests().is_empty());
    }

    /// A model that streams one partial chunk, then never yields again (Go
    /// streamThenWaitLLM's `<-ctx.Done()`: the flow's cancellation ends the wait).
    struct PartialThenWait;

    impl Llm for PartialThenWait {
        fn name(&self) -> &str {
            "partial-then-wait"
        }
        fn generate_content(
            &self,
            _req: LlmRequest,
            _stream: bool,
        ) -> BoxStream<'static, Result<LlmResponse, ModelError>> {
            let partial = LlmResponse {
                partial: true,
                ..text_resp("streaming...")
            };
            futures::stream::iter([Ok(partial)])
                .chain(futures::stream::pending())
                .boxed()
        }
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    /// The (text, context-error kind) pairs an on-model-error callback saw.
    type SeenErrors = Arc<parking_lot::Mutex<Vec<(String, Option<String>)>>>;

    /// An on-model-error callback recording the error text and whether the error is Go's
    /// context error (`ModelError::Other(AgentError::Cancelled | DeadlineExceeded)`).
    fn recording_on_model_error(
        seen: SeenErrors,
        reply: Option<LlmResponse>,
    ) -> OnModelErrorCallback {
        Arc::new(move |_, _, err| {
            let ctx_err = match &*err {
                ModelError::Other(b) => b.downcast_ref::<AgentError>().map(|a| match a {
                    AgentError::Cancelled => "Cancelled".to_owned(),
                    AgentError::DeadlineExceeded => "DeadlineExceeded".to_owned(),
                    other => format!("other: {other}"),
                }),
                _ => None,
            };
            seen.lock().push((err.to_string(), ctx_err));
            let reply = reply.clone();
            Box::pin(async move { Ok(reply) })
        })
    }

    /// Go base_flow.go:1031-1041: a model call that its context's cancellation ends after a
    /// partial chunk yields `ctx.Err()`, so the on-model-error callbacks run with
    /// `context.Canceled` and, returning nothing, the flow yields that error.
    #[tokio::test]
    async fn cancel_after_partial_runs_on_model_error_with_context_canceled() {
        let seen = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let ctx = ctx_for("a");
        let flow = Flow {
            model: Some(Arc::new(PartialThenWait)),
            on_model_error_callbacks: vec![recording_on_model_error(seen.clone(), None)],
            ..Default::default()
        };
        let mut s = Arc::new(flow).run(ctx.clone());
        let first = s.next().await.unwrap().unwrap();
        assert!(first.response.partial);
        ctx.cancel_with_cause(gadk_agent::CancelCause::Canceled);
        let rest: Vec<_> = s.collect().await;
        assert_eq!(rest.len(), 1);
        assert!(matches!(rest[0], Err(AgentError::Cancelled)));
        assert_eq!(
            *seen.lock(),
            [("context canceled".to_owned(), Some("Cancelled".to_owned()))]
        );
    }

    /// Go `ctx.Err()` is `context.DeadlineExceeded` for a context whose deadline passed; the
    /// model is not called on an already-ended context.
    #[tokio::test]
    async fn deadline_cancel_runs_on_model_error_with_deadline_exceeded() {
        let seen = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let model = MockModel::new(vec![Ok(text_resp("never"))]);
        let ctx = ctx_for("a");
        ctx.cancel_with_cause(gadk_agent::CancelCause::DeadlineExceeded);
        let flow = Flow {
            model: Some(model.clone()),
            on_model_error_callbacks: vec![recording_on_model_error(seen.clone(), None)],
            ..Default::default()
        };
        let items = run_all(flow, ctx).await;
        assert_eq!(items.len(), 1);
        assert!(matches!(items[0], Err(AgentError::DeadlineExceeded)));
        assert!(model.requests().is_empty());
        assert_eq!(
            *seen.lock(),
            [(
                "context deadline exceeded".to_owned(),
                Some("DeadlineExceeded".to_owned())
            )]
        );
    }

    /// Go `ctx.Err()` of a `WithCancelCause` context is `context.Canceled` whatever the
    /// cause: the callbacks see `context canceled`, not the cause's text.
    #[tokio::test]
    async fn error_cause_runs_on_model_error_with_context_canceled() {
        let seen = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let ctx = ctx_for("a");
        let flow = Flow {
            model: Some(Arc::new(PartialThenWait)),
            on_model_error_callbacks: vec![recording_on_model_error(seen.clone(), None)],
            ..Default::default()
        };
        let mut s = Arc::new(flow).run(ctx.clone());
        s.next().await.unwrap().unwrap();
        let cause: Arc<dyn std::error::Error + Send + Sync> =
            Arc::new(std::io::Error::other("sibling failed"));
        ctx.cancel_with_cause(gadk_agent::CancelCause::Error(cause));
        let rest: Vec<_> = s.collect().await;
        assert_eq!(rest.len(), 1);
        assert!(matches!(rest[0], Err(AgentError::Cancelled)));
        assert_eq!(
            *seen.lock(),
            [("context canceled".to_owned(), Some("Cancelled".to_owned()))]
        );
    }

    /// Go base_flow.go:1042-1046: an on-model-error callback's response replaces the
    /// cancelled call's error; the after-model callbacks see it and it is yielded, and the
    /// model call then ends (Go's model returns after yielding `ctx.Err()`).
    #[tokio::test]
    async fn on_model_error_reply_on_cancel_is_yielded_and_ends_the_call() {
        let seen = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let after_seen = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let after_seen2 = after_seen.clone();
        let after: gadk_agent::AfterModelCallback = Arc::new(move |_, resp: LlmResponse, _| {
            after_seen2.lock().push(texts_of(&resp));
            Box::pin(async move { (resp, Ok(None)) })
        });
        let flow = Arc::new(Flow {
            on_model_error_callbacks: vec![recording_on_model_error(
                seen.clone(),
                Some(text_resp("recovered")),
            )],
            after_model_callbacks: vec![after],
            ..Default::default()
        });
        let ctx = ctx_for("a");
        let actions = SharedActions::default();
        let mut s = flow.call_model(
            ctx.clone(),
            Arc::new(PartialThenWait),
            LlmRequest::default(),
            actions,
        );
        let (first, _) = s.next().await.unwrap().unwrap();
        assert!(first.partial);
        ctx.cancel_with_cause(gadk_agent::CancelCause::Canceled);
        let rest: Vec<_> = s.collect().await;
        assert_eq!(rest.len(), 1);
        let (resp, _) = rest[0].as_ref().unwrap();
        assert_eq!(texts_of(resp), "recovered");
        assert_eq!(*after_seen.lock(), ["streaming...", "recovered"]);
        assert_eq!(seen.lock().len(), 1);
    }

    /// A model that streams two chunks at once, then never yields again.
    struct TwoThenWait;

    impl Llm for TwoThenWait {
        fn name(&self) -> &str {
            "two-then-wait"
        }
        fn generate_content(
            &self,
            _req: LlmRequest,
            _stream: bool,
        ) -> BoxStream<'static, Result<LlmResponse, ModelError>> {
            let partial = LlmResponse {
                partial: true,
                ..text_resp("streaming...")
            };
            futures::stream::iter([Ok(partial), Ok(text_resp("ready"))])
                .chain(futures::stream::pending())
                .boxed()
        }
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    /// Go's flow ranges over the model's responses without checking its context between
    /// them: a response the model has ready when the cancellation lands is still processed;
    /// the cancellation is noticed while the model is pending (Go's model yields `ctx.Err()`).
    #[tokio::test]
    async fn ready_model_item_wins_over_cancellation() {
        let seen = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let flow = Arc::new(Flow {
            on_model_error_callbacks: vec![recording_on_model_error(seen.clone(), None)],
            ..Default::default()
        });
        let ctx = ctx_for("a");
        let mut s = flow.call_model(
            ctx.clone(),
            Arc::new(TwoThenWait),
            LlmRequest::default(),
            SharedActions::default(),
        );
        let (first, _) = s.next().await.unwrap().unwrap();
        assert!(first.partial);
        ctx.cancel_with_cause(gadk_agent::CancelCause::Canceled);
        let rest: Vec<_> = s.collect().await;
        assert_eq!(rest.len(), 2, "{rest:?}");
        let (ready, _) = rest[0].as_ref().unwrap();
        assert_eq!(texts_of(ready), "ready");
        assert!(matches!(rest[1], Err(AgentError::Cancelled)));
        assert_eq!(
            *seen.lock(),
            [("context canceled".to_owned(), Some("Cancelled".to_owned()))]
        );
    }

    fn texts_of(resp: &LlmResponse) -> String {
        resp.content
            .as_ref()
            .map(|c| c.parts.iter().map(|p| p.text.as_str()).collect())
            .unwrap_or_default()
    }
}

/// Test-only `tracing` span recorder for the span parity tests.
#[cfg(test)]
pub(crate) mod span_capture {
    use std::{
        cell::RefCell, collections::BTreeMap, collections::HashMap, future::Future, sync::Arc,
    };

    use tracing::{
        field::{Field, Visit},
        span::{Attributes, Id, Record},
    };
    use tracing_subscriber::{
        Layer,
        layer::{Context as LayerContext, SubscriberExt},
        registry::LookupSpan,
    };

    /// One recorded span: its name, `otel.name`, the fields recorded on it or on events inside it,
    /// whether it has closed, and its parent's name.
    #[derive(Clone, Debug, Default)]
    pub(crate) struct CapturedSpan {
        pub(crate) name: String,
        pub(crate) otel_name: String,
        pub(crate) fields: BTreeMap<String, String>,
        pub(crate) closed: bool,
        /// The static name of the span's parent, `None` for a root span.
        pub(crate) parent: Option<String>,
    }

    impl CapturedSpan {
        /// The rendered value of field `k`, if recorded.
        pub(crate) fn field(&self, k: &str) -> Option<String> {
            self.fields.get(k).cloned()
        }
    }

    thread_local! {
        static CLOSED: RefCell<HashMap<String, usize>> = RefCell::new(HashMap::new());
    }

    /// How many spans named `name` have closed on this thread since `capture_spans` started.
    pub(crate) fn closed_count(name: &str) -> usize {
        CLOSED.with(|c| c.borrow().get(name).copied().unwrap_or(0))
    }

    pub(crate) use crate::telemetry::span_digest::pin_tracing_interest;

    /// Runs `fut` with a recording subscriber as the thread default and the default (empty)
    /// telemetry environment; use only on a current-thread runtime.
    pub(crate) async fn capture_spans<F: Future>(fut: F) -> (F::Output, Vec<CapturedSpan>) {
        let _env = crate::telemetry::env::test_env(&[]);
        capture_spans_in_env(fut).await
    }

    /// [`capture_spans`] for a test that installed its own telemetry environment.
    pub(crate) async fn capture_spans_in_env<F: Future>(fut: F) -> (F::Output, Vec<CapturedSpan>) {
        pin_tracing_interest();
        CLOSED.with(|c| c.borrow_mut().clear());
        let spans: Arc<parking_lot::Mutex<Vec<CapturedSpan>>> = Arc::default();
        let sub = tracing_subscriber::registry().with(CaptureLayer(spans.clone()));
        let out = {
            let _g = tracing::subscriber::set_default(sub);
            fut.await
        };
        let spans = spans.lock().clone();
        (out, spans)
    }

    struct CaptureLayer(Arc<parking_lot::Mutex<Vec<CapturedSpan>>>);

    /// The index of a span in the captured list (stored in the span's extensions).
    struct Idx(usize);

    struct Fields<'a>(&'a mut BTreeMap<String, String>);

    impl Visit for Fields<'_> {
        fn record_str(&mut self, f: &Field, v: &str) {
            self.0.insert(f.name().to_owned(), v.to_owned());
        }
        fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
            self.0.insert(f.name().to_owned(), format!("{v:?}"));
        }
        /// A structured attribute's JSON text (Go's `Value.Emit` of a string slice).
        fn record_bytes(&mut self, f: &Field, v: &[u8]) {
            self.0
                .insert(f.name().to_owned(), String::from_utf8_lossy(v).into_owned());
        }
    }

    impl CaptureLayer {
        fn with_span<S>(
            &self,
            id: &Id,
            ctx: &LayerContext<'_, S>,
            f: impl FnOnce(&mut CapturedSpan),
        ) where
            S: tracing::Subscriber + for<'a> LookupSpan<'a>,
        {
            let Some(span) = ctx.span(id) else { return };
            let Some(i) = span.extensions().get::<Idx>().map(|i| i.0) else {
                return;
            };
            if let Some(s) = self.0.lock().get_mut(i) {
                f(s);
            }
        }
    }

    impl<S> Layer<S> for CaptureLayer
    where
        S: tracing::Subscriber + for<'a> LookupSpan<'a>,
    {
        fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: LayerContext<'_, S>) {
            let mut fields = BTreeMap::new();
            attrs.record(&mut Fields(&mut fields));
            let parent = ctx
                .span(id)
                .and_then(|s| s.parent())
                .map(|p| p.name().to_owned());
            let captured = CapturedSpan {
                name: attrs.metadata().name().to_owned(),
                otel_name: fields.get("otel.name").cloned().unwrap_or_default(),
                fields,
                closed: false,
                parent,
            };
            let i = {
                let mut v = self.0.lock();
                v.push(captured);
                v.len() - 1
            };
            if let Some(span) = ctx.span(id) {
                span.extensions_mut().insert(Idx(i));
            }
        }

        fn on_record(&self, id: &Id, values: &Record<'_>, ctx: LayerContext<'_, S>) {
            self.with_span(id, &ctx, |s| values.record(&mut Fields(&mut s.fields)));
        }

        fn on_event(&self, event: &tracing::Event<'_>, ctx: LayerContext<'_, S>) {
            let Some(parent) = ctx.event_span(event) else {
                return;
            };
            let id = parent.id();
            self.with_span(&id, &ctx, |s| event.record(&mut Fields(&mut s.fields)));
        }

        fn on_close(&self, id: Id, ctx: LayerContext<'_, S>) {
            let mut name = None;
            self.with_span(&id, &ctx, |s| {
                s.closed = true;
                name = Some(s.name.clone());
            });
            if let Some(n) = name {
                CLOSED.with(|c| *c.borrow_mut().entry(n).or_insert(0) += 1);
            }
        }
    }
}