adk-rust-macros 3.0.0

Procedural macros for ADK-Rust: #[tool] tool definitions and #[entrypoint]/#[task] graph workflows
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
//! # adk-rust-macros
//!
//! Procedural macros for ADK-Rust.
//!
//! | Macro | Generates |
//! |-------|-----------|
//! | [`macro@tool`] | A zero-sized struct implementing `adk_core::Tool` from an async function |
//! | [`macro@entrypoint`] | An `adk-graph` functional workflow agent struct |
//! | [`macro@task`] | A checkpointed, optionally retried `adk-graph` task wrapper |
//! | [`macro@Choice`] | An `adk_core::Choice` implementation for an enum of unit variants, for typed decisions |
//!
//! ## `#[tool]`
//!
//! Turns an async function into a `Tool` implementation. The generated code refers to
//! `adk_tool`, `schemars`, and `serde_json`, so the calling crate depends on all three;
//! `adk-tool` re-exports the macro as `adk_tool::tool`.
//!
//! ```rust
//! use adk_rust_macros::tool;
//! use adk_tool::{AdkError, Tool};
//! use schemars::JsonSchema;
//! use serde::Deserialize;
//!
//! #[derive(Deserialize, JsonSchema)]
//! struct WeatherArgs {
//!     /// The city to look up
//!     city: String,
//! }
//!
//! /// Get the current weather for a city.
//! #[tool(read_only)]
//! async fn get_weather(args: WeatherArgs) -> Result<serde_json::Value, AdkError> {
//!     Ok(serde_json::json!({ "temp": 72, "city": args.city }))
//! }
//!
//! // Generates `pub struct GetWeather` implementing `adk_tool::Tool`.
//! // Register it with `agent_builder.tool(Arc::new(GetWeather))`.
//! assert_eq!(GetWeather.name(), "get_weather");
//! assert!(GetWeather.is_read_only());
//! ```
//!
//! The macro:
//! - Uses the function's doc comment as the tool description
//! - Derives the JSON schema from the argument type via `schemars::schema_for!`
//! - Checks each call's arguments against that schema, rejecting keys it does not name,
//!   before the function runs
//! - Names the tool after the function (snake_case)
//! - Generates a zero-sized struct (PascalCase) implementing `Tool`

use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{FnArg, ItemFn, Meta, Type, parse_macro_input};

/// Attribute macro that generates a `Tool` implementation from an async function.
///
/// # Requirements
///
/// - The function must be `async`
/// - It must take exactly one argument (the args struct) that implements
///   `serde::de::DeserializeOwned` and `schemars::JsonSchema`
/// - It must return `Result<serde_json::Value, adk_tool::AdkError>`
/// - Doc comments become the tool description
///
/// # Attributes
///
/// Optional attributes can be passed to configure tool metadata:
///
/// - `read_only` — marks the tool as having no side effects (`is_read_only() → true`,
///   `effect() → ToolEffect::ReadOnly`)
/// - `idempotent` — marks the tool as safe to repeat (`effect() → ToolEffect::Idempotent`),
///   so a retry budget may retry it after a retryable error. Ignored alongside `read_only`.
/// - `concurrency_safe` — marks the tool as safe for concurrent execution (`is_concurrency_safe() → true`)
/// - `long_running` — marks the tool as long-running (`is_long_running() → true`)
/// - `lenient_args` — turns off argument validation; see below
///
/// # Argument validation
///
/// Before the function runs, the call's arguments are checked against the argument type's
/// schema, with `additionalProperties: false` set on every object that declares all of its
/// fields ([`close_object_schemas`]). A key the schema does not name, a value outside a
/// `#[schemars(range(...))]`, `length(...)` or `pattern(...)` bound, or a missing required field
/// fails the call with an `ErrorCategory::InvalidInput` error with code
/// `TOOL_INVALID_ARGUMENTS_CODE`, which lists each violation by JSON pointer. An `LlmAgent`
/// shows that message to the model so it can correct the call; the function does not run.
/// `parameters_schema()` is not closed: Gemini's function declarations reject
/// `additionalProperties`, and not every path to a provider runs a schema adapter.
///
/// A schema that differs from what the type deserializes from also rejects calls serde would
/// accept: a `#[serde(alias = "...")]` key, or a field with a custom `deserialize_with` whose
/// schema is narrower than its input. Keep such keys open with
/// `#[schemars(extend("additionalProperties" = true))]` on the struct, or opt the tool out with
/// `#[tool(lenient_args)]`, which deserializes with serde alone: unknown keys are dropped and
/// schema bounds are advisory.
///
/// In both modes an integral float at an integer field, such as `3.0` for a `u32`, is read as
/// the integer ([`coerce_integral_floats`]); some models write every number with a decimal
/// point.
///
/// [`close_object_schemas`]: https://docs.rs/adk-tool/latest/adk_tool/fn.close_object_schemas.html
/// [`coerce_integral_floats`]: https://docs.rs/adk-tool/latest/adk_tool/fn.coerce_integral_floats.html
///
/// # Examples
///
/// ```rust,ignore
/// /// Search the knowledge base for documents matching a query.
/// #[tool]
/// async fn search_docs(args: SearchArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
///     // ...
/// }
///
/// /// Look up cached data (read-only, safe for parallel dispatch).
/// #[tool(read_only, concurrency_safe)]
/// async fn cache_lookup(args: LookupArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
///     // ...
/// }
///
/// /// Set a ticket's status; setting the same status twice changes nothing.
/// #[tool(idempotent)]
/// async fn set_ticket_status(args: StatusArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
///     // ...
/// }
///
/// /// Accept legacy argument names that only serde knows about.
/// #[tool(lenient_args)]
/// async fn legacy_lookup(args: LegacyArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
///     // ...
/// }
///
/// // Generated: pub struct SearchDocs; implements Tool
/// // Use: agent_builder.tool(Arc::new(SearchDocs))
/// ```
#[proc_macro_attribute]
pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as ItemFn);

    // Parse optional attributes:
    // #[tool(read_only, idempotent, concurrency_safe, long_running, lenient_args)]
    let mut is_read_only = false;
    let mut is_idempotent = false;
    let mut is_concurrency_safe = false;
    let mut is_long_running = false;
    let mut is_lenient_args = false;

    if !attr.is_empty() {
        let meta = parse_macro_input!(attr as ToolAttrs);
        is_read_only = meta.read_only;
        is_idempotent = meta.idempotent;
        is_concurrency_safe = meta.concurrency_safe;
        is_long_running = meta.long_running;
        is_lenient_args = meta.lenient_args;
    }

    let fn_name = &input_fn.sig.ident;
    let fn_vis = &input_fn.vis;

    // Extract doc comments for description
    let doc_lines: Vec<String> = input_fn
        .attrs
        .iter()
        .filter(|attr| attr.path().is_ident("doc"))
        .filter_map(|attr| {
            if let syn::Meta::NameValue(nv) = &attr.meta
                && let syn::Expr::Lit(lit) = &nv.value
                && let syn::Lit::Str(s) = &lit.lit
            {
                return Some(s.value().trim().to_string());
            }
            None
        })
        .collect();

    let description = if doc_lines.is_empty() {
        fn_name.to_string().replace('_', " ")
    } else {
        doc_lines.join(" ")
    };

    let tool_name_str = fn_name.to_string();

    // Generate PascalCase struct name: get_weather → GetWeather
    let struct_name = format_ident!(
        "{}",
        tool_name_str
            .split('_')
            .map(|seg| {
                let mut chars = seg.chars();
                match chars.next() {
                    None => String::new(),
                    Some(c) => c.to_uppercase().to_string() + chars.as_str(),
                }
            })
            .collect::<String>()
    );

    // Extract the single argument type
    let args_type = extract_args_type(&input_fn);

    // The model is shown the generated schema as before; arguments are checked against the
    // same schema with its objects closed. The closure stays out of `parameters_schema()`
    // because some schemas reach providers without an adapter (a realtime session posts them
    // as-is), and Gemini rejects `additionalProperties`. Validation keeps nullable types, so
    // `null` stays accepted for an optional field the model-facing schema shows as non-null.
    let schema_gen = match &args_type {
        Some(args_ty) => quote! {
            Some(adk_tool::model_facing_schema(
                serde_json::to_value(schemars::schema_for!(#args_ty)).unwrap_or_default(),
            ))
        },
        None => quote! { None },
    };
    let validate_args = match &args_type {
        Some(args_ty) if !is_lenient_args => quote! {
            static ARGUMENTS: std::sync::LazyLock<
                std::result::Result<adk_tool::ToolArgumentValidator, String>,
            > = std::sync::LazyLock::new(|| {
                let mut schema = serde_json::to_value(schemars::schema_for!(#args_ty))
                    .unwrap_or_default();
                adk_tool::close_object_schemas(&mut schema);
                adk_tool::ToolArgumentValidator::new(&schema).map_err(|error| error.message)
            });
            match &*ARGUMENTS {
                Ok(validator) => validator.validate(#tool_name_str, &args)?,
                Err(message) => {
                    return Err(adk_tool::AdkError::new(
                        adk_tool::ErrorComponent::Tool,
                        adk_tool::ErrorCategory::Internal,
                        adk_tool::TOOL_INVALID_PARAMETERS_SCHEMA_CODE,
                        message.clone(),
                    ));
                }
            }
        },
        _ => quote! {},
    };
    // Applies with or without `lenient_args`: `3.0` for an integer field is a valid integer
    // to the schema, but serde rejects it.
    let coerce_args = args_type.as_ref().map(|args_ty| {
        quote! {
            static PARAMETERS: std::sync::LazyLock<serde_json::Value> =
                std::sync::LazyLock::new(|| {
                    serde_json::to_value(schemars::schema_for!(#args_ty)).unwrap_or_default()
                });
            let mut args = args;
            adk_tool::coerce_integral_floats(&PARAMETERS, &mut args);
        }
    });
    let deserialize_args = args_type.as_ref().map(|args_ty| {
        quote! {
            let typed_args: #args_ty = serde_json::from_value(args)
                .map_err(|e| adk_tool::AdkError::new(
                    adk_tool::ErrorComponent::Tool,
                    adk_tool::ErrorCategory::InvalidInput,
                    adk_tool::TOOL_INVALID_ARGUMENTS_CODE,
                    format!("invalid arguments for '{}': {e}", #tool_name_str),
                ))?;
        }
    });

    // Check if the function signature includes ctx: Arc<dyn ToolContext>
    let has_ctx = has_tool_context_param(&input_fn);
    let call = match (has_ctx, args_type.is_some()) {
        (true, true) => quote! { #fn_name(ctx, typed_args).await },
        (true, false) => quote! { let _ = args; #fn_name(ctx).await },
        (false, true) => quote! { #fn_name(typed_args).await },
        (false, false) => quote! { let _ = args; #fn_name().await },
    };
    let execute_body = quote! {
        #coerce_args
        #validate_args
        #deserialize_args
        #call
    };

    // Generate optional trait method overrides
    let read_only_override = if is_read_only {
        quote! {
            fn is_read_only(&self) -> bool { true }
        }
    } else {
        quote! {}
    };

    // `read_only` already yields `ToolEffect::ReadOnly` through the trait default.
    let effect_override = if is_idempotent && !is_read_only {
        quote! {
            fn effect(&self) -> adk_tool::ToolEffect { adk_tool::ToolEffect::Idempotent }
        }
    } else {
        quote! {}
    };

    let concurrency_safe_override = if is_concurrency_safe {
        quote! {
            fn is_concurrency_safe(&self) -> bool { true }
        }
    } else {
        quote! {}
    };

    let long_running_override = if is_long_running {
        quote! {
            fn is_long_running(&self) -> bool { true }
        }
    } else {
        quote! {}
    };

    let output = quote! {
        // Keep the original function
        #input_fn

        /// Auto-generated tool struct for [`#fn_name`].
        #fn_vis struct #struct_name;

        #[adk_tool::async_trait]
        impl adk_tool::Tool for #struct_name {
            fn name(&self) -> &str {
                #tool_name_str
            }

            fn description(&self) -> &str {
                #description
            }

            fn parameters_schema(&self) -> Option<serde_json::Value> {
                #schema_gen
            }

            #read_only_override
            #effect_override
            #concurrency_safe_override
            #long_running_override

            async fn execute(
                &self,
                ctx: std::sync::Arc<dyn adk_tool::ToolContext>,
                args: serde_json::Value,
            ) -> adk_tool::Result<serde_json::Value> {
                #execute_body
            }
        }
    };

    output.into()
}

/// Extract the args type from the function signature.
/// Skips any `Arc<dyn ToolContext>` parameter.
fn extract_args_type(func: &ItemFn) -> Option<Type> {
    for arg in &func.sig.inputs {
        if let FnArg::Typed(pat_type) = arg {
            // Skip context parameters (Arc<dyn ToolContext>)
            let ty = &pat_type.ty;
            let ty_str = quote!(#ty).to_string();
            if ty_str.contains("ToolContext") {
                continue;
            }
            return Some((*pat_type.ty).clone());
        }
    }
    None
}

/// Check if the function has an Arc<dyn ToolContext> parameter.
fn has_tool_context_param(func: &ItemFn) -> bool {
    func.sig.inputs.iter().any(|arg| {
        if let FnArg::Typed(pat_type) = arg {
            let ty = &pat_type.ty;
            let ty_str = quote!(#ty).to_string();
            ty_str.contains("ToolContext")
        } else {
            false
        }
    })
}

/// Parsed attributes from
/// `#[tool(read_only, idempotent, concurrency_safe, long_running, lenient_args)]`.
struct ToolAttrs {
    read_only: bool,
    idempotent: bool,
    concurrency_safe: bool,
    long_running: bool,
    lenient_args: bool,
}

impl syn::parse::Parse for ToolAttrs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut attrs = ToolAttrs {
            read_only: false,
            idempotent: false,
            concurrency_safe: false,
            long_running: false,
            lenient_args: false,
        };

        let punctuated =
            syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated(input)?;

        for meta in punctuated {
            if let Meta::Path(path) = &meta {
                if path.is_ident("read_only") {
                    attrs.read_only = true;
                } else if path.is_ident("idempotent") {
                    attrs.idempotent = true;
                } else if path.is_ident("concurrency_safe") {
                    attrs.concurrency_safe = true;
                } else if path.is_ident("long_running") {
                    attrs.long_running = true;
                } else if path.is_ident("lenient_args") {
                    attrs.lenient_args = true;
                } else {
                    return Err(syn::Error::new_spanned(
                        path,
                        "unknown tool attribute; expected `read_only`, `idempotent`, `concurrency_safe`, `long_running`, or `lenient_args`",
                    ));
                }
            } else {
                return Err(syn::Error::new_spanned(
                    meta,
                    "expected identifier (e.g., `read_only`), not key-value",
                ));
            }
        }

        Ok(attrs)
    }
}

// ─── Functional API Macros ─────────────────────────────────────────────────────

/// Attribute macro that generates a workflow agent struct from an async function.
///
/// The annotated function becomes the workflow body. The macro generates:
/// - A PascalCase struct (e.g., `my_workflow` → `MyWorkflowAgent`)
/// - A `new()` constructor accepting `Arc<dyn Checkpointer>`
/// - An `invoke()` method that creates/restores `TaskContext`, validates state,
///   creates checkpoints, calls the function, and persists the final checkpoint
///
/// # Requirements
///
/// - The function **must** be `async`
/// - The function **must** accept `&mut TaskContext` as its sole parameter
/// - The function **must** return `Result<Value>` (or equivalent)
///
/// # Example
///
/// ```rust,ignore
/// use adk_graph::functional::TaskContext;
/// use adk_graph::error::Result;
/// use serde_json::Value;
///
/// #[entrypoint]
/// async fn my_workflow(ctx: &mut TaskContext) -> Result<Value> {
///     let data = step_a(ctx, "input").await?;
///     let result = step_b(ctx, data).await?;
///     Ok(result)
/// }
///
/// // Generates: pub struct MyWorkflowAgent { ... }
/// // with MyWorkflowAgent::new(checkpointer) and invoke(initial_state, config)
/// ```
#[proc_macro_attribute]
pub fn entrypoint(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as ItemFn);

    // Validate: must be async
    if input_fn.sig.asyncness.is_none() {
        return syn::Error::new_spanned(
            input_fn.sig.fn_token,
            "#[entrypoint] functions must be async",
        )
        .to_compile_error()
        .into();
    }

    // Validate: must accept &mut TaskContext
    let has_task_context = input_fn.sig.inputs.iter().any(|arg| {
        if let FnArg::Typed(pat_type) = arg {
            let full_str = quote!(#pat_type).to_string();
            full_str.contains("TaskContext")
        } else {
            false
        }
    });

    if !has_task_context {
        return syn::Error::new_spanned(
            &input_fn.sig,
            "#[entrypoint] functions must accept `&mut TaskContext` as a parameter",
        )
        .to_compile_error()
        .into();
    }

    let fn_name = &input_fn.sig.ident;
    let fn_vis = &input_fn.vis;
    let fn_name_str = fn_name.to_string();

    // Generate PascalCase struct name: my_workflow → MyWorkflowAgent
    let struct_name = format_ident!(
        "{}Agent",
        fn_name_str
            .split('_')
            .map(|seg| {
                let mut chars = seg.chars();
                match chars.next() {
                    None => String::new(),
                    Some(c) => c.to_uppercase().to_string() + chars.as_str(),
                }
            })
            .collect::<String>()
    );

    let output = quote! {
        // Preserve the original function for direct testing
        #input_fn

        /// Auto-generated workflow agent struct for [`#fn_name`].
        ///
        /// Created by the `#[entrypoint]` macro. Provides `new()` and `invoke()`
        /// methods for executing the workflow with automatic checkpointing.
        #fn_vis struct #struct_name {
            checkpointer: std::sync::Arc<dyn adk_graph::checkpoint::Checkpointer>,
        }

        impl #struct_name {
            /// Create a new workflow agent with the given checkpointer.
            pub fn new(checkpointer: std::sync::Arc<dyn adk_graph::checkpoint::Checkpointer>) -> Self {
                Self { checkpointer }
            }

            /// Invoke the workflow with an initial state and execution configuration.
            ///
            /// This method:
            /// 1. Restores state and the execution log from the checkpoint
            ///    `execution_config.resume_from` names, or starts from
            ///    `initial_state` when it is unset
            /// 2. Hands `execution_config.resume_values` to the `TaskContext`,
            ///    so an interrupt whose key is present returns its value
            /// 3. Validates state against the configured schema
            /// 4. Creates a checkpoint before execution, carrying the execution log
            /// 5. Calls the annotated workflow function
            /// 6. Persists the final checkpoint
            /// 7. Returns the final workflow state
            ///
            /// Every checkpoint the run writes carries the execution log, so a
            /// run resumed from any of them replays the tasks that completed
            /// before it, however many times the workflow is resumed.
            ///
            /// # Errors
            ///
            /// Returns `GraphError::CheckpointError` when `resume_from` names a
            /// checkpoint this thread does not have, `GraphError::Cancelled` when
            /// `execution_config.cancellation_token` is cancelled, and the
            /// workflow's own error when it fails or suspends at an interrupt.
            pub async fn invoke(
                &self,
                initial_state: adk_graph::state::State,
                execution_config: adk_graph::node::ExecutionConfig,
            ) -> adk_graph::error::Result<adk_graph::state::State> {
                use adk_graph::functional::ExecutionLog;
                use adk_graph::state::Checkpoint;
                use adk_graph::stream::StreamEvent;

                let thread_id = execution_config.thread_id.clone();

                let (state, execution_log) = adk_graph::functional::__private::load_resume_point(
                    self.checkpointer.as_ref(),
                    &execution_config,
                )
                .await?
                .unwrap_or_else(|| (initial_state, ExecutionLog::new()));

                // Create broadcast channel for stream events
                let (event_tx, _) = tokio::sync::broadcast::channel::<StreamEvent>(256);
                // The caller's token, so the caller can cancel the run.
                let cancel_token =
                    execution_config.cancellation_token.clone().unwrap_or_default();
                let pre_step = execution_log.current_step();
                let pre_log = serde_json::to_value(&execution_log)?;
                let execution_log = std::sync::Arc::new(tokio::sync::RwLock::new(execution_log));

                // Create TaskContext
                let mut ctx = adk_graph::functional::TaskContext::new(
                    thread_id.clone(),
                    state,
                    self.checkpointer.clone(),
                    event_tx.clone(),
                    execution_log.clone(),
                    cancel_token.clone(),
                    None,
                )
                .with_resume_values(execution_config.resume_values)
                .with_resumed_from(execution_config.resume_from.clone());

                // Validate initial state against schema (if configured)
                ctx.validate_state().map_err(|e| adk_graph::error::GraphError::Other(e.to_string()))?;

                // The pre-execution checkpoint becomes the thread's latest. Without
                // the log, a crash before the next task completes would resume
                // with an empty log and run every completed task again.
                let pre_checkpoint = Checkpoint::new(
                    &thread_id,
                    ctx.state().clone(),
                    pre_step,
                    vec![],
                )
                .with_metadata("phase", serde_json::Value::String("pre_execution".to_string()))
                .with_metadata("execution_log", pre_log);
                ctx.save_checkpoint(pre_checkpoint).await?;

                // Emit workflow start event
                let _ = event_tx.send(StreamEvent::node_start(#fn_name_str, 0));

                // Call the workflow function. A cancellation abandons it where it
                // is: the task running then is not recorded, so it runs again when
                // the thread resumes from its latest checkpoint.
                let start = std::time::Instant::now();
                let result = adk_graph::functional::__private::until_cancelled(
                    &cancel_token,
                    #fn_name(&mut ctx),
                )
                .await;

                let duration = start.elapsed().as_millis() as u64;

                match result {
                    Ok(_value) => {
                        // Persist final checkpoint
                        let step = execution_log.read().await.current_step();
                        let final_checkpoint = Checkpoint::new(
                            &thread_id,
                            ctx.state().clone(),
                            step,
                            vec![],
                        )
                        .with_metadata("phase", serde_json::Value::String("completed".to_string()))
                        .with_metadata(
                            "execution_log",
                            serde_json::to_value(&*execution_log.read().await)
                                .unwrap_or(serde_json::Value::Null),
                        );
                        ctx.save_checkpoint(final_checkpoint).await?;

                        // Emit workflow end event
                        let _ = event_tx.send(StreamEvent::node_end(#fn_name_str, step, duration));

                        Ok(ctx.state().clone())
                    }
                    // A cancelled run writes nothing more: the thread's latest
                    // checkpoint is the one the last completed task wrote.
                    Err(adk_graph::error::GraphError::Cancelled) => {
                        let _ = event_tx.send(StreamEvent::error("workflow cancelled", Some(#fn_name_str)));
                        Err(adk_graph::error::GraphError::Cancelled)
                    }
                    Err(e) => {
                        // Persist failure checkpoint
                        let step = execution_log.read().await.current_step();
                        let fail_checkpoint = Checkpoint::new(
                            &thread_id,
                            ctx.state().clone(),
                            step,
                            vec![],
                        )
                        .with_metadata("phase", serde_json::Value::String("failed".to_string()))
                        .with_metadata("error", serde_json::Value::String(e.to_string()))
                        .with_metadata(
                            "execution_log",
                            serde_json::to_value(&*execution_log.read().await)
                                .unwrap_or(serde_json::Value::Null),
                        );
                        let _ = ctx.save_checkpoint(fail_checkpoint).await;

                        // Emit error event
                        let _ = event_tx.send(StreamEvent::error(&e.to_string(), Some(#fn_name_str)));

                        Err(e)
                    }
                }
            }
        }
    };

    output.into()
}

/// Attribute macro that generates a task wrapper with checkpointing, retry, and streaming.
///
/// The annotated function becomes the inner task body. The macro generates a wrapper
/// function (prefixed with `__task_`) that:
/// - Checks `ExecutionLog` for cached results (resume-skip path)
/// - Emits `StreamEvent::node_start` and `StreamEvent::node_end` events
/// - Implements retry logic when `retry(max_attempts, backoff)` is specified
/// - Calls `record_completion()` on success
/// - Calls `record_failure()` after all retries are exhausted
///
/// # Requirements
///
/// - The function **must** be `async`
/// - The function **must** accept `&mut TaskContext` as its first argument
/// - Every parameter **must** be a plain identifier (`mut` is allowed)
///
/// # Call identity
///
/// Each call is recorded in the `ExecutionLog` under its own key,
/// `{task}#{ordinal}:{arg_hash}`: the ordinal counts this task's calls within
/// the run, and the hash covers every argument that implements `Serialize`
/// (`:{arg_hash}` is omitted when none does). A task called in a loop therefore
/// records one result per call, and a resumed run replays each call's own
/// result. A replayed call whose arguments differ from the recorded call at the
/// same position runs again. See `adk_graph::functional::task_call_id`.
///
/// # Attributes
///
/// - `retry(max_attempts = N, backoff = "Xs")` — retry on failure, sleeping
///   `backoff × attempt` between tries, so the delay grows linearly: `Xs`, `2Xs`,
///   `3Xs`. For exponential growth, a cap, or jitter, attach an
///   `adk_graph::retry::RetryPolicy` to a graph node instead. A suspension at an
///   interrupt and a cancellation are not failures: they end the task at once,
///   without a retry, and are not recorded as failures
/// - `rerun_on_resume` — always re-execute on workflow resume, skip cached results
/// - `rerun_on_resume = true` / `rerun_on_resume = false` — explicit boolean form
///
/// # Examples
///
/// ```rust,ignore
/// use adk_graph::functional::TaskContext;
/// use adk_graph::error::Result;
/// use serde_json::Value;
///
/// #[task(retry(max_attempts = 3, backoff = "1s"))]
/// async fn step_a(ctx: &mut TaskContext, input: &str) -> Result<Value> {
///     Ok(serde_json::json!({"processed": input}))
/// }
///
/// #[task(rerun_on_resume)]
/// async fn step_b(ctx: &mut TaskContext) -> Result<Value> {
///     // This task always re-executes on resume, never uses cached results
///     Ok(serde_json::json!({"timestamp": chrono::Utc::now().to_rfc3339()}))
/// }
///
/// #[task(rerun_on_resume, retry(max_attempts = 2, backoff = "2s"))]
/// async fn step_c(ctx: &mut TaskContext) -> Result<Value> {
///     // Combined: re-executes on resume with retry logic
///     Ok(serde_json::json!({"status": "ok"}))
/// }
///
/// // Generates: async fn __task_step_a(ctx: &mut TaskContext, input: &str) -> Result<Value>
/// // which wraps step_a with checkpoint/retry/streaming logic.
/// ```
#[proc_macro_attribute]
pub fn task(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as ItemFn);

    // Validate: must be async
    if input_fn.sig.asyncness.is_none() {
        return syn::Error::new_spanned(input_fn.sig.fn_token, "#[task] functions must be async")
            .to_compile_error()
            .into();
    }

    // Validate: first argument must be &mut TaskContext
    let has_task_context_first = input_fn
        .sig
        .inputs
        .first()
        .map(|arg| {
            if let FnArg::Typed(pat_type) = arg {
                let full_str = quote!(#pat_type).to_string();
                full_str.contains("TaskContext")
            } else {
                false
            }
        })
        .unwrap_or(false);

    if !has_task_context_first {
        return syn::Error::new_spanned(
            &input_fn.sig,
            "#[task] functions must accept `&mut TaskContext` as the first argument",
        )
        .to_compile_error()
        .into();
    }

    // Parse retry attributes from #[task(retry(max_attempts = N, backoff = "Xs"))]
    let task_attrs = parse_task_attrs(attr);

    let fn_name = &input_fn.sig.ident;
    let fn_vis = &input_fn.vis;
    let fn_name_str = fn_name.to_string();
    let wrapper_name = format_ident!("__task_{}", fn_name);

    // Collect function parameters (all of them for the wrapper signature)
    let params = &input_fn.sig.inputs;
    let return_type = &input_fn.sig.output;

    // The wrapper refers to every parameter by name, so each must be a plain
    // identifier; `mut` and `ref` are allowed since the name is what matters.
    let mut param_idents = Vec::new();
    for arg in &input_fn.sig.inputs {
        match arg {
            FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
                syn::Pat::Ident(pat_ident) => param_idents.push(pat_ident.ident.clone()),
                other => {
                    return syn::Error::new_spanned(
                        other,
                        "#[task] parameters must be plain identifiers, such as `item: Item`, so \
                         the generated wrapper can forward them",
                    )
                    .to_compile_error()
                    .into();
                }
            },
            FnArg::Receiver(receiver) => {
                return syn::Error::new_spanned(
                    receiver,
                    "#[task] functions must be free functions, not methods",
                )
                .to_compile_error()
                .into();
            }
        }
    }
    let (ctx_ident, forward_args) = param_idents.split_first().expect("validated above");

    // Build the call expression
    let call_expr = if forward_args.is_empty() {
        quote! { #fn_name(#ctx_ident).await }
    } else {
        quote! { #fn_name(#ctx_ident, #(#forward_args),*).await }
    };

    // The execution-log key: the task's call ordinal in this run plus a hash of
    // every argument that implements `Serialize`; see `adk_graph::functional::task_call_id`.
    let task_id_expr = if forward_args.is_empty() {
        quote! { #ctx_ident.next_task_call_id(#fn_name_str, &[]) }
    } else {
        quote! {
            {
                #[allow(unused_imports)]
                use adk_graph::functional::__private::{
                    OpaqueTaskArg as _, SerializableTaskArg as _,
                };
                let __adk_task_args = [
                    #((&adk_graph::functional::__private::TaskArg(&#forward_args)).task_arg_value()),*
                ];
                #ctx_ident.next_task_call_id(#fn_name_str, &__adk_task_args)
            }
        }
    };

    // A suspension or a cancellation stops the task without failing it: it is not
    // retried, and the execution log does not record it as a failure, so the
    // resumed run calls the task again.
    let halts = quote! {
        {
            #[allow(unused_imports)]
            use adk_graph::functional::__private::{
                HaltingTaskError as _, OpaqueTaskError as _,
            };
            (&adk_graph::functional::__private::TaskError(&e)).halts_task()
        }
    };

    // Generate retry logic or single-attempt logic
    let execution_body = if let Some(retry_config) = &task_attrs.retry {
        let max_attempts = retry_config.max_attempts;
        let backoff_secs = retry_config.backoff_secs;
        quote! {
            let mut __adk_attempts: u32 = 0;
            let __adk_max_attempts: u32 = #max_attempts;
            let __adk_backoff = std::time::Duration::from_secs(#backoff_secs);

            let __adk_result = loop {
                __adk_attempts += 1;
                match #call_expr {
                    Ok(value) => break Ok(value),
                    Err(e) if #halts => break Err(e),
                    Err(_) if __adk_attempts < __adk_max_attempts => {
                        tokio::time::sleep(__adk_backoff * __adk_attempts).await;
                        continue;
                    }
                    Err(e) => {
                        #ctx_ident.record_failure(__adk_task_id, &e.to_string()).await?;
                        #ctx_ident.emit(adk_graph::stream::StreamEvent::error(
                            &e.to_string(),
                            Some(__adk_task_id),
                        ));
                        break Err(e);
                    }
                }
            };
        }
    } else {
        quote! {
            let __adk_result = match #call_expr {
                Ok(value) => Ok(value),
                Err(e) if #halts => Err(e),
                Err(e) => {
                    #ctx_ident.record_failure(__adk_task_id, &e.to_string()).await?;
                    #ctx_ident.emit(adk_graph::stream::StreamEvent::error(
                        &e.to_string(),
                        Some(__adk_task_id),
                    ));
                    Err(e)
                }
            };
        }
    };

    // Generate cache-check code based on rerun_on_resume flag
    let cache_check = if task_attrs.rerun_on_resume {
        // rerun_on_resume = true: skip cache check, always execute
        quote! {}
    } else {
        // Default: check ExecutionLog for cached results (resume-skip path)
        quote! {
            // Check if already completed (resume path)
            if let Some(cached_result) = #ctx_ident.get_cached_result(__adk_task_id).await {
                return Ok(cached_result);
            }
        }
    };

    let output = quote! {
        // Preserve the original function for direct testing
        #input_fn

        /// Auto-generated task wrapper for [`#fn_name`].
        ///
        /// Wraps the original function with:
        /// - Resume-skip logic (checks `ExecutionLog` for cached results)
        /// - `StreamEvent::node_start` / `StreamEvent::node_end` emission
        /// - Retry logic (if configured)
        /// - `record_completion()` on success
        /// - `record_failure()` after all retries exhausted
        ///
        /// Each call is logged under its own key, built from the call's ordinal
        /// and its arguments; see `adk_graph::functional::task_call_id`.
        #fn_vis async fn #wrapper_name(#params) #return_type {
            let __adk_task_key: String = #task_id_expr;
            let __adk_task_id: &str = &__adk_task_key;

            #cache_check

            // Emit task start event
            let __adk_step = #ctx_ident.current_step().await;
            #ctx_ident.emit(adk_graph::stream::StreamEvent::node_start(__adk_task_id, __adk_step));

            let __adk_start = std::time::Instant::now();

            #execution_body

            if let Ok(ref value) = __adk_result {
                // Record completion and checkpoint
                #ctx_ident.record_completion(__adk_task_id, value).await?;
                let duration = __adk_start.elapsed().as_millis() as u64;
                let step = #ctx_ident.current_step().await;
                #ctx_ident.emit(adk_graph::stream::StreamEvent::node_end(__adk_task_id, step, duration));
            }

            __adk_result
        }
    };

    output.into()
}

// ─── Task Attribute Parsing ────────────────────────────────────────────────────

/// Parsed retry configuration from `#[task(retry(max_attempts = N, backoff = "Xs"))]`.
struct RetryConfig {
    max_attempts: u32,
    backoff_secs: u64,
}

/// Parsed attributes from `#[task(...)]`.
struct TaskAttrs {
    retry: Option<RetryConfig>,
    rerun_on_resume: bool,
}

/// Parse task attributes from the attribute token stream.
///
/// Supports:
/// - `#[task]` — no retry, no rerun
/// - `#[task(retry(max_attempts = 3, backoff = "1s"))]` — with retry
/// - `#[task(rerun_on_resume)]` — always re-execute on resume (skip cache)
/// - `#[task(rerun_on_resume = true)]` — explicit boolean form
/// - `#[task(rerun_on_resume, retry(max_attempts = 3, backoff = "1s"))]` — combined
fn parse_task_attrs(attr: TokenStream) -> TaskAttrs {
    if attr.is_empty() {
        return TaskAttrs { retry: None, rerun_on_resume: false };
    }

    // Parse the attribute as a Meta list
    let attr_meta: syn::Result<syn::Meta> = syn::parse(attr.clone());
    if let Ok(syn::Meta::List(meta_list)) = attr_meta
        && meta_list.path.is_ident("retry")
        && let Some(retry) = parse_retry_from_meta_list(&meta_list)
    {
        return TaskAttrs { retry: Some(retry), rerun_on_resume: false };
    }

    // Try parsing as just the inner content of task(...)
    // e.g., the attr stream is: `retry(max_attempts = 3, backoff = "1s")`
    // or: `rerun_on_resume`
    // or: `rerun_on_resume, retry(max_attempts = 3, backoff = "1s")`
    let attr2: proc_macro2::TokenStream = attr.into();
    let parsed: syn::Result<TaskAttrContent> = syn::parse2(attr2);
    if let Ok(content) = parsed {
        return TaskAttrs { retry: content.retry, rerun_on_resume: content.rerun_on_resume };
    }

    TaskAttrs { retry: None, rerun_on_resume: false }
}

/// Inner content parsed from `#[task(retry(...), rerun_on_resume)]`.
struct TaskAttrContent {
    retry: Option<RetryConfig>,
    rerun_on_resume: bool,
}

impl syn::parse::Parse for TaskAttrContent {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut retry = None;
        let mut rerun_on_resume = false;

        // Parse comma-separated items: identifiers, name-value pairs, or calls like retry(...)
        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;

            if ident == "retry" {
                let content;
                syn::parenthesized!(content in input);

                let mut max_attempts: u32 = 3;
                let mut backoff_secs: u64 = 1;

                let pairs = syn::punctuated::Punctuated::<syn::MetaNameValue, syn::Token![,]>::parse_terminated(&content)?;

                for pair in pairs {
                    if pair.path.is_ident("max_attempts")
                        && let syn::Expr::Lit(expr_lit) = &pair.value
                        && let syn::Lit::Int(lit_int) = &expr_lit.lit
                    {
                        max_attempts = lit_int.base10_parse().unwrap_or(3);
                    } else if pair.path.is_ident("backoff")
                        && let syn::Expr::Lit(expr_lit) = &pair.value
                        && let syn::Lit::Str(lit_str) = &expr_lit.lit
                    {
                        backoff_secs = parse_duration_str(&lit_str.value());
                    }
                }

                retry = Some(RetryConfig { max_attempts, backoff_secs });
            } else if ident == "rerun_on_resume" {
                // Accept both `rerun_on_resume` (flag, implies true)
                // and `rerun_on_resume = true` / `rerun_on_resume = false`
                if input.peek(syn::Token![=]) {
                    let _eq: syn::Token![=] = input.parse()?;
                    let lit: syn::LitBool = input.parse()?;
                    rerun_on_resume = lit.value;
                } else {
                    rerun_on_resume = true;
                }
            } else {
                return Err(syn::Error::new_spanned(
                    ident,
                    "unknown task attribute; expected `retry(...)` or `rerun_on_resume`",
                ));
            }

            // Consume optional trailing comma
            if input.peek(syn::Token![,]) {
                let _comma: syn::Token![,] = input.parse()?;
            }
        }

        Ok(TaskAttrContent { retry, rerun_on_resume })
    }
}

/// Parse retry config from a `Meta::List` (e.g., `retry(max_attempts = 3, backoff = "1s")`).
fn parse_retry_from_meta_list(meta_list: &syn::MetaList) -> Option<RetryConfig> {
    let mut max_attempts: u32 = 3;
    let mut backoff_secs: u64 = 1;

    let pairs: syn::Result<syn::punctuated::Punctuated<syn::MetaNameValue, syn::Token![,]>> =
        meta_list.parse_args_with(syn::punctuated::Punctuated::parse_terminated);

    if let Ok(pairs) = pairs {
        for pair in pairs {
            if pair.path.is_ident("max_attempts")
                && let syn::Expr::Lit(expr_lit) = &pair.value
                && let syn::Lit::Int(lit_int) = &expr_lit.lit
            {
                max_attempts = lit_int.base10_parse().unwrap_or(3);
            } else if pair.path.is_ident("backoff")
                && let syn::Expr::Lit(expr_lit) = &pair.value
                && let syn::Lit::Str(lit_str) = &expr_lit.lit
            {
                backoff_secs = parse_duration_str(&lit_str.value());
            }
        }
        Some(RetryConfig { max_attempts, backoff_secs })
    } else {
        None
    }
}

/// Parse a duration string like "1s", "500ms", "2s" into seconds.
/// Defaults to 1 second if parsing fails.
fn parse_duration_str(s: &str) -> u64 {
    let s = s.trim();
    // Check "ms" suffix first (before "s" since "ms" ends with 's')
    if let Some(ms) = s.strip_suffix("ms") {
        return ms.parse::<u64>().ok().map(|v| v / 1000).unwrap_or(1);
    }
    if let Some(secs) = s.strip_suffix('s') {
        return secs.parse::<u64>().unwrap_or(1);
    }
    // Try parsing as plain number (assume seconds)
    s.parse::<u64>().unwrap_or(1)
}

/// Derives `adk_core::Choice` for an enum of unit variants, so a model can decide one of them
/// with `adk_core::decide::<T>`.
///
/// Each variant is an option named in snake_case (`OutOfScope` → `out_of_scope`) unless
/// `#[choice(name = "...")]` names it, and described to the model by its doc comment. The
/// generated code refers to `adk_core`, so the calling crate depends on `adk-core` beside
/// `adk-rust-macros`.
///
/// # Example
///
/// ```rust
/// use adk_core::Choice;
/// use adk_rust_macros::Choice;
///
/// #[derive(Choice, Debug, PartialEq)]
/// enum Route {
///     /// Invoices, refunds and payment problems
///     Billing,
///     /// Errors, outages and how-to questions
///     Technical,
///     /// Anything the support team does not handle
///     #[choice(name = "elsewhere")]
///     OutOfScope,
/// }
///
/// let names: Vec<String> = Route::options().into_iter().map(|option| option.name).collect();
/// assert_eq!(names, ["billing", "technical", "elsewhere"]);
/// assert_eq!(Route::options()[0].description, "Invoices, refunds and payment problems");
/// assert_eq!(Route::from_option("elsewhere"), Some(Route::OutOfScope));
/// assert_eq!(Route::from_option("sales"), None);
/// ```
///
/// A struct, a union, a variant with fields, or two variants with the same option name fails
/// to compile.
#[proc_macro_derive(Choice, attributes(choice))]
pub fn derive_choice(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as syn::DeriveInput);
    match choice_impl(&input) {
        Ok(tokens) => tokens.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

fn choice_impl(input: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let syn::Data::Enum(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            &input.ident,
            "#[derive(Choice)] needs an enum whose variants are the options",
        ));
    };
    let ident = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
    let mut names = Vec::new();
    let mut descriptions = Vec::new();
    let mut variants = Vec::new();
    for variant in &data.variants {
        if !matches!(variant.fields, syn::Fields::Unit) {
            return Err(syn::Error::new_spanned(
                variant,
                "#[derive(Choice)] options are unit variants; move the data elsewhere",
            ));
        }
        let mut name = None;
        for attr in variant.attrs.iter().filter(|attr| attr.path().is_ident("choice")) {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("name") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    name = Some(value.value());
                    Ok(())
                } else {
                    Err(meta.error("expected `name = \"...\"`"))
                }
            })?;
        }
        let name = name.unwrap_or_else(|| snake_case(&variant.ident.to_string()));
        if names.contains(&name) {
            return Err(syn::Error::new_spanned(
                variant,
                format!(
                    "two variants are both the option `{name}`; give one a #[choice(name = ...)]"
                ),
            ));
        }
        let description = variant
            .attrs
            .iter()
            .filter_map(|attr| match &attr.meta {
                Meta::NameValue(pair) if pair.path.is_ident("doc") => match &pair.value {
                    syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(text), .. }) => {
                        Some(text.value().trim().to_string())
                    }
                    _ => None,
                },
                _ => None,
            })
            .filter(|line| !line.is_empty())
            .collect::<Vec<_>>()
            .join(" ");
        names.push(name);
        descriptions.push(description);
        variants.push(variant.ident.clone());
    }
    Ok(quote! {
        impl #impl_generics ::adk_core::Choice for #ident #ty_generics #where_clause {
            fn options() -> ::std::vec::Vec<::adk_core::ChoiceOption> {
                ::std::vec![#(::adk_core::ChoiceOption::new(#names, #descriptions)),*]
            }

            fn from_option(name: &str) -> ::std::option::Option<Self> {
                match name {
                    #(#names => ::std::option::Option::Some(Self::#variants),)*
                    _ => ::std::option::Option::None,
                }
            }
        }
    })
}

/// `OutOfScope` → `out_of_scope`.
fn snake_case(name: &str) -> String {
    let mut snake = String::new();
    for (index, ch) in name.chars().enumerate() {
        if ch.is_uppercase() {
            if index > 0 {
                snake.push('_');
            }
            snake.extend(ch.to_lowercase());
        } else {
            snake.push(ch);
        }
    }
    snake
}