adk_rust_macros/lib.rs
1//! # adk-rust-macros
2//!
3//! Procedural macros for ADK-Rust.
4//!
5//! | Macro | Generates |
6//! |-------|-----------|
7//! | [`macro@tool`] | A zero-sized struct implementing `adk_core::Tool` from an async function |
8//! | [`macro@entrypoint`] | An `adk-graph` functional workflow agent struct |
9//! | [`macro@task`] | A checkpointed, optionally retried `adk-graph` task wrapper |
10//! | [`macro@Choice`] | An `adk_core::Choice` implementation for an enum of unit variants, for typed decisions |
11//!
12//! ## `#[tool]`
13//!
14//! Turns an async function into a `Tool` implementation. The generated code refers to
15//! `adk_tool`, `schemars`, and `serde_json`, so the calling crate depends on all three;
16//! `adk-tool` re-exports the macro as `adk_tool::tool`.
17//!
18//! ```rust
19//! use adk_rust_macros::tool;
20//! use adk_tool::{AdkError, Tool};
21//! use schemars::JsonSchema;
22//! use serde::Deserialize;
23//!
24//! #[derive(Deserialize, JsonSchema)]
25//! struct WeatherArgs {
26//! /// The city to look up
27//! city: String,
28//! }
29//!
30//! /// Get the current weather for a city.
31//! #[tool(read_only)]
32//! async fn get_weather(args: WeatherArgs) -> Result<serde_json::Value, AdkError> {
33//! Ok(serde_json::json!({ "temp": 72, "city": args.city }))
34//! }
35//!
36//! // Generates `pub struct GetWeather` implementing `adk_tool::Tool`.
37//! // Register it with `agent_builder.tool(Arc::new(GetWeather))`.
38//! assert_eq!(GetWeather.name(), "get_weather");
39//! assert!(GetWeather.is_read_only());
40//! ```
41//!
42//! The macro:
43//! - Uses the function's doc comment as the tool description
44//! - Derives the JSON schema from the argument type via `schemars::schema_for!`
45//! - Checks each call's arguments against that schema, rejecting keys it does not name,
46//! before the function runs
47//! - Names the tool after the function (snake_case)
48//! - Generates a zero-sized struct (PascalCase) implementing `Tool`
49
50use proc_macro::TokenStream;
51use quote::{format_ident, quote};
52use syn::{FnArg, ItemFn, Meta, Type, parse_macro_input};
53
54/// Attribute macro that generates a `Tool` implementation from an async function.
55///
56/// # Requirements
57///
58/// - The function must be `async`
59/// - It must take exactly one argument (the args struct) that implements
60/// `serde::de::DeserializeOwned` and `schemars::JsonSchema`
61/// - It must return `Result<serde_json::Value, adk_tool::AdkError>`
62/// - Doc comments become the tool description
63///
64/// # Attributes
65///
66/// Optional attributes can be passed to configure tool metadata:
67///
68/// - `read_only` — marks the tool as having no side effects (`is_read_only() → true`,
69/// `effect() → ToolEffect::ReadOnly`)
70/// - `idempotent` — marks the tool as safe to repeat (`effect() → ToolEffect::Idempotent`),
71/// so a retry budget may retry it after a retryable error. Ignored alongside `read_only`.
72/// - `concurrency_safe` — marks the tool as safe for concurrent execution (`is_concurrency_safe() → true`)
73/// - `long_running` — marks the tool as long-running (`is_long_running() → true`)
74/// - `lenient_args` — turns off argument validation; see below
75///
76/// # Argument validation
77///
78/// Before the function runs, the call's arguments are checked against the argument type's
79/// schema, with `additionalProperties: false` set on every object that declares all of its
80/// fields ([`close_object_schemas`]). A key the schema does not name, a value outside a
81/// `#[schemars(range(...))]`, `length(...)` or `pattern(...)` bound, or a missing required field
82/// fails the call with an `ErrorCategory::InvalidInput` error with code
83/// `TOOL_INVALID_ARGUMENTS_CODE`, which lists each violation by JSON pointer. An `LlmAgent`
84/// shows that message to the model so it can correct the call; the function does not run.
85/// `parameters_schema()` is not closed: Gemini's function declarations reject
86/// `additionalProperties`, and not every path to a provider runs a schema adapter.
87///
88/// A schema that differs from what the type deserializes from also rejects calls serde would
89/// accept: a `#[serde(alias = "...")]` key, or a field with a custom `deserialize_with` whose
90/// schema is narrower than its input. Keep such keys open with
91/// `#[schemars(extend("additionalProperties" = true))]` on the struct, or opt the tool out with
92/// `#[tool(lenient_args)]`, which deserializes with serde alone: unknown keys are dropped and
93/// schema bounds are advisory.
94///
95/// In both modes an integral float at an integer field, such as `3.0` for a `u32`, is read as
96/// the integer ([`coerce_integral_floats`]); some models write every number with a decimal
97/// point.
98///
99/// [`close_object_schemas`]: https://docs.rs/adk-tool/latest/adk_tool/fn.close_object_schemas.html
100/// [`coerce_integral_floats`]: https://docs.rs/adk-tool/latest/adk_tool/fn.coerce_integral_floats.html
101///
102/// # Examples
103///
104/// ```rust,ignore
105/// /// Search the knowledge base for documents matching a query.
106/// #[tool]
107/// async fn search_docs(args: SearchArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
108/// // ...
109/// }
110///
111/// /// Look up cached data (read-only, safe for parallel dispatch).
112/// #[tool(read_only, concurrency_safe)]
113/// async fn cache_lookup(args: LookupArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
114/// // ...
115/// }
116///
117/// /// Set a ticket's status; setting the same status twice changes nothing.
118/// #[tool(idempotent)]
119/// async fn set_ticket_status(args: StatusArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
120/// // ...
121/// }
122///
123/// /// Accept legacy argument names that only serde knows about.
124/// #[tool(lenient_args)]
125/// async fn legacy_lookup(args: LegacyArgs) -> Result<serde_json::Value, adk_tool::AdkError> {
126/// // ...
127/// }
128///
129/// // Generated: pub struct SearchDocs; implements Tool
130/// // Use: agent_builder.tool(Arc::new(SearchDocs))
131/// ```
132#[proc_macro_attribute]
133pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
134 let input_fn = parse_macro_input!(item as ItemFn);
135
136 // Parse optional attributes:
137 // #[tool(read_only, idempotent, concurrency_safe, long_running, lenient_args)]
138 let mut is_read_only = false;
139 let mut is_idempotent = false;
140 let mut is_concurrency_safe = false;
141 let mut is_long_running = false;
142 let mut is_lenient_args = false;
143
144 if !attr.is_empty() {
145 let meta = parse_macro_input!(attr as ToolAttrs);
146 is_read_only = meta.read_only;
147 is_idempotent = meta.idempotent;
148 is_concurrency_safe = meta.concurrency_safe;
149 is_long_running = meta.long_running;
150 is_lenient_args = meta.lenient_args;
151 }
152
153 let fn_name = &input_fn.sig.ident;
154 let fn_vis = &input_fn.vis;
155
156 // Extract doc comments for description
157 let doc_lines: Vec<String> = input_fn
158 .attrs
159 .iter()
160 .filter(|attr| attr.path().is_ident("doc"))
161 .filter_map(|attr| {
162 if let syn::Meta::NameValue(nv) = &attr.meta
163 && let syn::Expr::Lit(lit) = &nv.value
164 && let syn::Lit::Str(s) = &lit.lit
165 {
166 return Some(s.value().trim().to_string());
167 }
168 None
169 })
170 .collect();
171
172 let description = if doc_lines.is_empty() {
173 fn_name.to_string().replace('_', " ")
174 } else {
175 doc_lines.join(" ")
176 };
177
178 let tool_name_str = fn_name.to_string();
179
180 // Generate PascalCase struct name: get_weather → GetWeather
181 let struct_name = format_ident!(
182 "{}",
183 tool_name_str
184 .split('_')
185 .map(|seg| {
186 let mut chars = seg.chars();
187 match chars.next() {
188 None => String::new(),
189 Some(c) => c.to_uppercase().to_string() + chars.as_str(),
190 }
191 })
192 .collect::<String>()
193 );
194
195 // Extract the single argument type
196 let args_type = extract_args_type(&input_fn);
197
198 // The model is shown the generated schema as before; arguments are checked against the
199 // same schema with its objects closed. The closure stays out of `parameters_schema()`
200 // because some schemas reach providers without an adapter (a realtime session posts them
201 // as-is), and Gemini rejects `additionalProperties`. Validation keeps nullable types, so
202 // `null` stays accepted for an optional field the model-facing schema shows as non-null.
203 let schema_gen = match &args_type {
204 Some(args_ty) => quote! {
205 Some(adk_tool::model_facing_schema(
206 serde_json::to_value(schemars::schema_for!(#args_ty)).unwrap_or_default(),
207 ))
208 },
209 None => quote! { None },
210 };
211 let validate_args = match &args_type {
212 Some(args_ty) if !is_lenient_args => quote! {
213 static ARGUMENTS: std::sync::LazyLock<
214 std::result::Result<adk_tool::ToolArgumentValidator, String>,
215 > = std::sync::LazyLock::new(|| {
216 let mut schema = serde_json::to_value(schemars::schema_for!(#args_ty))
217 .unwrap_or_default();
218 adk_tool::close_object_schemas(&mut schema);
219 adk_tool::ToolArgumentValidator::new(&schema).map_err(|error| error.message)
220 });
221 match &*ARGUMENTS {
222 Ok(validator) => validator.validate(#tool_name_str, &args)?,
223 Err(message) => {
224 return Err(adk_tool::AdkError::new(
225 adk_tool::ErrorComponent::Tool,
226 adk_tool::ErrorCategory::Internal,
227 adk_tool::TOOL_INVALID_PARAMETERS_SCHEMA_CODE,
228 message.clone(),
229 ));
230 }
231 }
232 },
233 _ => quote! {},
234 };
235 // Applies with or without `lenient_args`: `3.0` for an integer field is a valid integer
236 // to the schema, but serde rejects it.
237 let coerce_args = args_type.as_ref().map(|args_ty| {
238 quote! {
239 static PARAMETERS: std::sync::LazyLock<serde_json::Value> =
240 std::sync::LazyLock::new(|| {
241 serde_json::to_value(schemars::schema_for!(#args_ty)).unwrap_or_default()
242 });
243 let mut args = args;
244 adk_tool::coerce_integral_floats(&PARAMETERS, &mut args);
245 }
246 });
247 let deserialize_args = args_type.as_ref().map(|args_ty| {
248 quote! {
249 let typed_args: #args_ty = serde_json::from_value(args)
250 .map_err(|e| adk_tool::AdkError::new(
251 adk_tool::ErrorComponent::Tool,
252 adk_tool::ErrorCategory::InvalidInput,
253 adk_tool::TOOL_INVALID_ARGUMENTS_CODE,
254 format!("invalid arguments for '{}': {e}", #tool_name_str),
255 ))?;
256 }
257 });
258
259 // Check if the function signature includes ctx: Arc<dyn ToolContext>
260 let has_ctx = has_tool_context_param(&input_fn);
261 let call = match (has_ctx, args_type.is_some()) {
262 (true, true) => quote! { #fn_name(ctx, typed_args).await },
263 (true, false) => quote! { let _ = args; #fn_name(ctx).await },
264 (false, true) => quote! { #fn_name(typed_args).await },
265 (false, false) => quote! { let _ = args; #fn_name().await },
266 };
267 let execute_body = quote! {
268 #coerce_args
269 #validate_args
270 #deserialize_args
271 #call
272 };
273
274 // Generate optional trait method overrides
275 let read_only_override = if is_read_only {
276 quote! {
277 fn is_read_only(&self) -> bool { true }
278 }
279 } else {
280 quote! {}
281 };
282
283 // `read_only` already yields `ToolEffect::ReadOnly` through the trait default.
284 let effect_override = if is_idempotent && !is_read_only {
285 quote! {
286 fn effect(&self) -> adk_tool::ToolEffect { adk_tool::ToolEffect::Idempotent }
287 }
288 } else {
289 quote! {}
290 };
291
292 let concurrency_safe_override = if is_concurrency_safe {
293 quote! {
294 fn is_concurrency_safe(&self) -> bool { true }
295 }
296 } else {
297 quote! {}
298 };
299
300 let long_running_override = if is_long_running {
301 quote! {
302 fn is_long_running(&self) -> bool { true }
303 }
304 } else {
305 quote! {}
306 };
307
308 let output = quote! {
309 // Keep the original function
310 #input_fn
311
312 /// Auto-generated tool struct for [`#fn_name`].
313 #fn_vis struct #struct_name;
314
315 #[adk_tool::async_trait]
316 impl adk_tool::Tool for #struct_name {
317 fn name(&self) -> &str {
318 #tool_name_str
319 }
320
321 fn description(&self) -> &str {
322 #description
323 }
324
325 fn parameters_schema(&self) -> Option<serde_json::Value> {
326 #schema_gen
327 }
328
329 #read_only_override
330 #effect_override
331 #concurrency_safe_override
332 #long_running_override
333
334 async fn execute(
335 &self,
336 ctx: std::sync::Arc<dyn adk_tool::ToolContext>,
337 args: serde_json::Value,
338 ) -> adk_tool::Result<serde_json::Value> {
339 #execute_body
340 }
341 }
342 };
343
344 output.into()
345}
346
347/// Extract the args type from the function signature.
348/// Skips any `Arc<dyn ToolContext>` parameter.
349fn extract_args_type(func: &ItemFn) -> Option<Type> {
350 for arg in &func.sig.inputs {
351 if let FnArg::Typed(pat_type) = arg {
352 // Skip context parameters (Arc<dyn ToolContext>)
353 let ty = &pat_type.ty;
354 let ty_str = quote!(#ty).to_string();
355 if ty_str.contains("ToolContext") {
356 continue;
357 }
358 return Some((*pat_type.ty).clone());
359 }
360 }
361 None
362}
363
364/// Check if the function has an Arc<dyn ToolContext> parameter.
365fn has_tool_context_param(func: &ItemFn) -> bool {
366 func.sig.inputs.iter().any(|arg| {
367 if let FnArg::Typed(pat_type) = arg {
368 let ty = &pat_type.ty;
369 let ty_str = quote!(#ty).to_string();
370 ty_str.contains("ToolContext")
371 } else {
372 false
373 }
374 })
375}
376
377/// Parsed attributes from
378/// `#[tool(read_only, idempotent, concurrency_safe, long_running, lenient_args)]`.
379struct ToolAttrs {
380 read_only: bool,
381 idempotent: bool,
382 concurrency_safe: bool,
383 long_running: bool,
384 lenient_args: bool,
385}
386
387impl syn::parse::Parse for ToolAttrs {
388 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
389 let mut attrs = ToolAttrs {
390 read_only: false,
391 idempotent: false,
392 concurrency_safe: false,
393 long_running: false,
394 lenient_args: false,
395 };
396
397 let punctuated =
398 syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated(input)?;
399
400 for meta in punctuated {
401 if let Meta::Path(path) = &meta {
402 if path.is_ident("read_only") {
403 attrs.read_only = true;
404 } else if path.is_ident("idempotent") {
405 attrs.idempotent = true;
406 } else if path.is_ident("concurrency_safe") {
407 attrs.concurrency_safe = true;
408 } else if path.is_ident("long_running") {
409 attrs.long_running = true;
410 } else if path.is_ident("lenient_args") {
411 attrs.lenient_args = true;
412 } else {
413 return Err(syn::Error::new_spanned(
414 path,
415 "unknown tool attribute; expected `read_only`, `idempotent`, `concurrency_safe`, `long_running`, or `lenient_args`",
416 ));
417 }
418 } else {
419 return Err(syn::Error::new_spanned(
420 meta,
421 "expected identifier (e.g., `read_only`), not key-value",
422 ));
423 }
424 }
425
426 Ok(attrs)
427 }
428}
429
430// ─── Functional API Macros ─────────────────────────────────────────────────────
431
432/// Attribute macro that generates a workflow agent struct from an async function.
433///
434/// The annotated function becomes the workflow body. The macro generates:
435/// - A PascalCase struct (e.g., `my_workflow` → `MyWorkflowAgent`)
436/// - A `new()` constructor accepting `Arc<dyn Checkpointer>`
437/// - An `invoke()` method that creates/restores `TaskContext`, validates state,
438/// creates checkpoints, calls the function, and persists the final checkpoint
439///
440/// # Requirements
441///
442/// - The function **must** be `async`
443/// - The function **must** accept `&mut TaskContext` as its sole parameter
444/// - The function **must** return `Result<Value>` (or equivalent)
445///
446/// # Example
447///
448/// ```rust,ignore
449/// use adk_graph::functional::TaskContext;
450/// use adk_graph::error::Result;
451/// use serde_json::Value;
452///
453/// #[entrypoint]
454/// async fn my_workflow(ctx: &mut TaskContext) -> Result<Value> {
455/// let data = step_a(ctx, "input").await?;
456/// let result = step_b(ctx, data).await?;
457/// Ok(result)
458/// }
459///
460/// // Generates: pub struct MyWorkflowAgent { ... }
461/// // with MyWorkflowAgent::new(checkpointer) and invoke(initial_state, config)
462/// ```
463#[proc_macro_attribute]
464pub fn entrypoint(_attr: TokenStream, item: TokenStream) -> TokenStream {
465 let input_fn = parse_macro_input!(item as ItemFn);
466
467 // Validate: must be async
468 if input_fn.sig.asyncness.is_none() {
469 return syn::Error::new_spanned(
470 input_fn.sig.fn_token,
471 "#[entrypoint] functions must be async",
472 )
473 .to_compile_error()
474 .into();
475 }
476
477 // Validate: must accept &mut TaskContext
478 let has_task_context = input_fn.sig.inputs.iter().any(|arg| {
479 if let FnArg::Typed(pat_type) = arg {
480 let full_str = quote!(#pat_type).to_string();
481 full_str.contains("TaskContext")
482 } else {
483 false
484 }
485 });
486
487 if !has_task_context {
488 return syn::Error::new_spanned(
489 &input_fn.sig,
490 "#[entrypoint] functions must accept `&mut TaskContext` as a parameter",
491 )
492 .to_compile_error()
493 .into();
494 }
495
496 let fn_name = &input_fn.sig.ident;
497 let fn_vis = &input_fn.vis;
498 let fn_name_str = fn_name.to_string();
499
500 // Generate PascalCase struct name: my_workflow → MyWorkflowAgent
501 let struct_name = format_ident!(
502 "{}Agent",
503 fn_name_str
504 .split('_')
505 .map(|seg| {
506 let mut chars = seg.chars();
507 match chars.next() {
508 None => String::new(),
509 Some(c) => c.to_uppercase().to_string() + chars.as_str(),
510 }
511 })
512 .collect::<String>()
513 );
514
515 let output = quote! {
516 // Preserve the original function for direct testing
517 #input_fn
518
519 /// Auto-generated workflow agent struct for [`#fn_name`].
520 ///
521 /// Created by the `#[entrypoint]` macro. Provides `new()` and `invoke()`
522 /// methods for executing the workflow with automatic checkpointing.
523 #fn_vis struct #struct_name {
524 checkpointer: std::sync::Arc<dyn adk_graph::checkpoint::Checkpointer>,
525 }
526
527 impl #struct_name {
528 /// Create a new workflow agent with the given checkpointer.
529 pub fn new(checkpointer: std::sync::Arc<dyn adk_graph::checkpoint::Checkpointer>) -> Self {
530 Self { checkpointer }
531 }
532
533 /// Invoke the workflow with an initial state and execution configuration.
534 ///
535 /// This method:
536 /// 1. Restores state and the execution log from the checkpoint
537 /// `execution_config.resume_from` names, or starts from
538 /// `initial_state` when it is unset
539 /// 2. Hands `execution_config.resume_values` to the `TaskContext`,
540 /// so an interrupt whose key is present returns its value
541 /// 3. Validates state against the configured schema
542 /// 4. Creates a checkpoint before execution, carrying the execution log
543 /// 5. Calls the annotated workflow function
544 /// 6. Persists the final checkpoint
545 /// 7. Returns the final workflow state
546 ///
547 /// Every checkpoint the run writes carries the execution log, so a
548 /// run resumed from any of them replays the tasks that completed
549 /// before it, however many times the workflow is resumed.
550 ///
551 /// # Errors
552 ///
553 /// Returns `GraphError::CheckpointError` when `resume_from` names a
554 /// checkpoint this thread does not have, `GraphError::Cancelled` when
555 /// `execution_config.cancellation_token` is cancelled, and the
556 /// workflow's own error when it fails or suspends at an interrupt.
557 pub async fn invoke(
558 &self,
559 initial_state: adk_graph::state::State,
560 execution_config: adk_graph::node::ExecutionConfig,
561 ) -> adk_graph::error::Result<adk_graph::state::State> {
562 use adk_graph::functional::ExecutionLog;
563 use adk_graph::state::Checkpoint;
564 use adk_graph::stream::StreamEvent;
565
566 let thread_id = execution_config.thread_id.clone();
567
568 let (state, execution_log) = adk_graph::functional::__private::load_resume_point(
569 self.checkpointer.as_ref(),
570 &execution_config,
571 )
572 .await?
573 .unwrap_or_else(|| (initial_state, ExecutionLog::new()));
574
575 // Create broadcast channel for stream events
576 let (event_tx, _) = tokio::sync::broadcast::channel::<StreamEvent>(256);
577 // The caller's token, so the caller can cancel the run.
578 let cancel_token =
579 execution_config.cancellation_token.clone().unwrap_or_default();
580 let pre_step = execution_log.current_step();
581 let pre_log = serde_json::to_value(&execution_log)?;
582 let execution_log = std::sync::Arc::new(tokio::sync::RwLock::new(execution_log));
583
584 // Create TaskContext
585 let mut ctx = adk_graph::functional::TaskContext::new(
586 thread_id.clone(),
587 state,
588 self.checkpointer.clone(),
589 event_tx.clone(),
590 execution_log.clone(),
591 cancel_token.clone(),
592 None,
593 )
594 .with_resume_values(execution_config.resume_values)
595 .with_resumed_from(execution_config.resume_from.clone());
596
597 // Validate initial state against schema (if configured)
598 ctx.validate_state().map_err(|e| adk_graph::error::GraphError::Other(e.to_string()))?;
599
600 // The pre-execution checkpoint becomes the thread's latest. Without
601 // the log, a crash before the next task completes would resume
602 // with an empty log and run every completed task again.
603 let pre_checkpoint = Checkpoint::new(
604 &thread_id,
605 ctx.state().clone(),
606 pre_step,
607 vec![],
608 )
609 .with_metadata("phase", serde_json::Value::String("pre_execution".to_string()))
610 .with_metadata("execution_log", pre_log);
611 ctx.save_checkpoint(pre_checkpoint).await?;
612
613 // Emit workflow start event
614 let _ = event_tx.send(StreamEvent::node_start(#fn_name_str, 0));
615
616 // Call the workflow function. A cancellation abandons it where it
617 // is: the task running then is not recorded, so it runs again when
618 // the thread resumes from its latest checkpoint.
619 let start = std::time::Instant::now();
620 let result = adk_graph::functional::__private::until_cancelled(
621 &cancel_token,
622 #fn_name(&mut ctx),
623 )
624 .await;
625
626 let duration = start.elapsed().as_millis() as u64;
627
628 match result {
629 Ok(_value) => {
630 // Persist final checkpoint
631 let step = execution_log.read().await.current_step();
632 let final_checkpoint = Checkpoint::new(
633 &thread_id,
634 ctx.state().clone(),
635 step,
636 vec![],
637 )
638 .with_metadata("phase", serde_json::Value::String("completed".to_string()))
639 .with_metadata(
640 "execution_log",
641 serde_json::to_value(&*execution_log.read().await)
642 .unwrap_or(serde_json::Value::Null),
643 );
644 ctx.save_checkpoint(final_checkpoint).await?;
645
646 // Emit workflow end event
647 let _ = event_tx.send(StreamEvent::node_end(#fn_name_str, step, duration));
648
649 Ok(ctx.state().clone())
650 }
651 // A cancelled run writes nothing more: the thread's latest
652 // checkpoint is the one the last completed task wrote.
653 Err(adk_graph::error::GraphError::Cancelled) => {
654 let _ = event_tx.send(StreamEvent::error("workflow cancelled", Some(#fn_name_str)));
655 Err(adk_graph::error::GraphError::Cancelled)
656 }
657 Err(e) => {
658 // Persist failure checkpoint
659 let step = execution_log.read().await.current_step();
660 let fail_checkpoint = Checkpoint::new(
661 &thread_id,
662 ctx.state().clone(),
663 step,
664 vec![],
665 )
666 .with_metadata("phase", serde_json::Value::String("failed".to_string()))
667 .with_metadata("error", serde_json::Value::String(e.to_string()))
668 .with_metadata(
669 "execution_log",
670 serde_json::to_value(&*execution_log.read().await)
671 .unwrap_or(serde_json::Value::Null),
672 );
673 let _ = ctx.save_checkpoint(fail_checkpoint).await;
674
675 // Emit error event
676 let _ = event_tx.send(StreamEvent::error(&e.to_string(), Some(#fn_name_str)));
677
678 Err(e)
679 }
680 }
681 }
682 }
683 };
684
685 output.into()
686}
687
688/// Attribute macro that generates a task wrapper with checkpointing, retry, and streaming.
689///
690/// The annotated function becomes the inner task body. The macro generates a wrapper
691/// function (prefixed with `__task_`) that:
692/// - Checks `ExecutionLog` for cached results (resume-skip path)
693/// - Emits `StreamEvent::node_start` and `StreamEvent::node_end` events
694/// - Implements retry logic when `retry(max_attempts, backoff)` is specified
695/// - Calls `record_completion()` on success
696/// - Calls `record_failure()` after all retries are exhausted
697///
698/// # Requirements
699///
700/// - The function **must** be `async`
701/// - The function **must** accept `&mut TaskContext` as its first argument
702/// - Every parameter **must** be a plain identifier (`mut` is allowed)
703///
704/// # Call identity
705///
706/// Each call is recorded in the `ExecutionLog` under its own key,
707/// `{task}#{ordinal}:{arg_hash}`: the ordinal counts this task's calls within
708/// the run, and the hash covers every argument that implements `Serialize`
709/// (`:{arg_hash}` is omitted when none does). A task called in a loop therefore
710/// records one result per call, and a resumed run replays each call's own
711/// result. A replayed call whose arguments differ from the recorded call at the
712/// same position runs again. See `adk_graph::functional::task_call_id`.
713///
714/// # Attributes
715///
716/// - `retry(max_attempts = N, backoff = "Xs")` — retry on failure, sleeping
717/// `backoff × attempt` between tries, so the delay grows linearly: `Xs`, `2Xs`,
718/// `3Xs`. For exponential growth, a cap, or jitter, attach an
719/// `adk_graph::retry::RetryPolicy` to a graph node instead. A suspension at an
720/// interrupt and a cancellation are not failures: they end the task at once,
721/// without a retry, and are not recorded as failures
722/// - `rerun_on_resume` — always re-execute on workflow resume, skip cached results
723/// - `rerun_on_resume = true` / `rerun_on_resume = false` — explicit boolean form
724///
725/// # Examples
726///
727/// ```rust,ignore
728/// use adk_graph::functional::TaskContext;
729/// use adk_graph::error::Result;
730/// use serde_json::Value;
731///
732/// #[task(retry(max_attempts = 3, backoff = "1s"))]
733/// async fn step_a(ctx: &mut TaskContext, input: &str) -> Result<Value> {
734/// Ok(serde_json::json!({"processed": input}))
735/// }
736///
737/// #[task(rerun_on_resume)]
738/// async fn step_b(ctx: &mut TaskContext) -> Result<Value> {
739/// // This task always re-executes on resume, never uses cached results
740/// Ok(serde_json::json!({"timestamp": chrono::Utc::now().to_rfc3339()}))
741/// }
742///
743/// #[task(rerun_on_resume, retry(max_attempts = 2, backoff = "2s"))]
744/// async fn step_c(ctx: &mut TaskContext) -> Result<Value> {
745/// // Combined: re-executes on resume with retry logic
746/// Ok(serde_json::json!({"status": "ok"}))
747/// }
748///
749/// // Generates: async fn __task_step_a(ctx: &mut TaskContext, input: &str) -> Result<Value>
750/// // which wraps step_a with checkpoint/retry/streaming logic.
751/// ```
752#[proc_macro_attribute]
753pub fn task(attr: TokenStream, item: TokenStream) -> TokenStream {
754 let input_fn = parse_macro_input!(item as ItemFn);
755
756 // Validate: must be async
757 if input_fn.sig.asyncness.is_none() {
758 return syn::Error::new_spanned(input_fn.sig.fn_token, "#[task] functions must be async")
759 .to_compile_error()
760 .into();
761 }
762
763 // Validate: first argument must be &mut TaskContext
764 let has_task_context_first = input_fn
765 .sig
766 .inputs
767 .first()
768 .map(|arg| {
769 if let FnArg::Typed(pat_type) = arg {
770 let full_str = quote!(#pat_type).to_string();
771 full_str.contains("TaskContext")
772 } else {
773 false
774 }
775 })
776 .unwrap_or(false);
777
778 if !has_task_context_first {
779 return syn::Error::new_spanned(
780 &input_fn.sig,
781 "#[task] functions must accept `&mut TaskContext` as the first argument",
782 )
783 .to_compile_error()
784 .into();
785 }
786
787 // Parse retry attributes from #[task(retry(max_attempts = N, backoff = "Xs"))]
788 let task_attrs = parse_task_attrs(attr);
789
790 let fn_name = &input_fn.sig.ident;
791 let fn_vis = &input_fn.vis;
792 let fn_name_str = fn_name.to_string();
793 let wrapper_name = format_ident!("__task_{}", fn_name);
794
795 // Collect function parameters (all of them for the wrapper signature)
796 let params = &input_fn.sig.inputs;
797 let return_type = &input_fn.sig.output;
798
799 // The wrapper refers to every parameter by name, so each must be a plain
800 // identifier; `mut` and `ref` are allowed since the name is what matters.
801 let mut param_idents = Vec::new();
802 for arg in &input_fn.sig.inputs {
803 match arg {
804 FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
805 syn::Pat::Ident(pat_ident) => param_idents.push(pat_ident.ident.clone()),
806 other => {
807 return syn::Error::new_spanned(
808 other,
809 "#[task] parameters must be plain identifiers, such as `item: Item`, so \
810 the generated wrapper can forward them",
811 )
812 .to_compile_error()
813 .into();
814 }
815 },
816 FnArg::Receiver(receiver) => {
817 return syn::Error::new_spanned(
818 receiver,
819 "#[task] functions must be free functions, not methods",
820 )
821 .to_compile_error()
822 .into();
823 }
824 }
825 }
826 let (ctx_ident, forward_args) = param_idents.split_first().expect("validated above");
827
828 // Build the call expression
829 let call_expr = if forward_args.is_empty() {
830 quote! { #fn_name(#ctx_ident).await }
831 } else {
832 quote! { #fn_name(#ctx_ident, #(#forward_args),*).await }
833 };
834
835 // The execution-log key: the task's call ordinal in this run plus a hash of
836 // every argument that implements `Serialize`; see `adk_graph::functional::task_call_id`.
837 let task_id_expr = if forward_args.is_empty() {
838 quote! { #ctx_ident.next_task_call_id(#fn_name_str, &[]) }
839 } else {
840 quote! {
841 {
842 #[allow(unused_imports)]
843 use adk_graph::functional::__private::{
844 OpaqueTaskArg as _, SerializableTaskArg as _,
845 };
846 let __adk_task_args = [
847 #((&adk_graph::functional::__private::TaskArg(&#forward_args)).task_arg_value()),*
848 ];
849 #ctx_ident.next_task_call_id(#fn_name_str, &__adk_task_args)
850 }
851 }
852 };
853
854 // A suspension or a cancellation stops the task without failing it: it is not
855 // retried, and the execution log does not record it as a failure, so the
856 // resumed run calls the task again.
857 let halts = quote! {
858 {
859 #[allow(unused_imports)]
860 use adk_graph::functional::__private::{
861 HaltingTaskError as _, OpaqueTaskError as _,
862 };
863 (&adk_graph::functional::__private::TaskError(&e)).halts_task()
864 }
865 };
866
867 // Generate retry logic or single-attempt logic
868 let execution_body = if let Some(retry_config) = &task_attrs.retry {
869 let max_attempts = retry_config.max_attempts;
870 let backoff_secs = retry_config.backoff_secs;
871 quote! {
872 let mut __adk_attempts: u32 = 0;
873 let __adk_max_attempts: u32 = #max_attempts;
874 let __adk_backoff = std::time::Duration::from_secs(#backoff_secs);
875
876 let __adk_result = loop {
877 __adk_attempts += 1;
878 match #call_expr {
879 Ok(value) => break Ok(value),
880 Err(e) if #halts => break Err(e),
881 Err(_) if __adk_attempts < __adk_max_attempts => {
882 tokio::time::sleep(__adk_backoff * __adk_attempts).await;
883 continue;
884 }
885 Err(e) => {
886 #ctx_ident.record_failure(__adk_task_id, &e.to_string()).await?;
887 #ctx_ident.emit(adk_graph::stream::StreamEvent::error(
888 &e.to_string(),
889 Some(__adk_task_id),
890 ));
891 break Err(e);
892 }
893 }
894 };
895 }
896 } else {
897 quote! {
898 let __adk_result = match #call_expr {
899 Ok(value) => Ok(value),
900 Err(e) if #halts => Err(e),
901 Err(e) => {
902 #ctx_ident.record_failure(__adk_task_id, &e.to_string()).await?;
903 #ctx_ident.emit(adk_graph::stream::StreamEvent::error(
904 &e.to_string(),
905 Some(__adk_task_id),
906 ));
907 Err(e)
908 }
909 };
910 }
911 };
912
913 // Generate cache-check code based on rerun_on_resume flag
914 let cache_check = if task_attrs.rerun_on_resume {
915 // rerun_on_resume = true: skip cache check, always execute
916 quote! {}
917 } else {
918 // Default: check ExecutionLog for cached results (resume-skip path)
919 quote! {
920 // Check if already completed (resume path)
921 if let Some(cached_result) = #ctx_ident.get_cached_result(__adk_task_id).await {
922 return Ok(cached_result);
923 }
924 }
925 };
926
927 let output = quote! {
928 // Preserve the original function for direct testing
929 #input_fn
930
931 /// Auto-generated task wrapper for [`#fn_name`].
932 ///
933 /// Wraps the original function with:
934 /// - Resume-skip logic (checks `ExecutionLog` for cached results)
935 /// - `StreamEvent::node_start` / `StreamEvent::node_end` emission
936 /// - Retry logic (if configured)
937 /// - `record_completion()` on success
938 /// - `record_failure()` after all retries exhausted
939 ///
940 /// Each call is logged under its own key, built from the call's ordinal
941 /// and its arguments; see `adk_graph::functional::task_call_id`.
942 #fn_vis async fn #wrapper_name(#params) #return_type {
943 let __adk_task_key: String = #task_id_expr;
944 let __adk_task_id: &str = &__adk_task_key;
945
946 #cache_check
947
948 // Emit task start event
949 let __adk_step = #ctx_ident.current_step().await;
950 #ctx_ident.emit(adk_graph::stream::StreamEvent::node_start(__adk_task_id, __adk_step));
951
952 let __adk_start = std::time::Instant::now();
953
954 #execution_body
955
956 if let Ok(ref value) = __adk_result {
957 // Record completion and checkpoint
958 #ctx_ident.record_completion(__adk_task_id, value).await?;
959 let duration = __adk_start.elapsed().as_millis() as u64;
960 let step = #ctx_ident.current_step().await;
961 #ctx_ident.emit(adk_graph::stream::StreamEvent::node_end(__adk_task_id, step, duration));
962 }
963
964 __adk_result
965 }
966 };
967
968 output.into()
969}
970
971// ─── Task Attribute Parsing ────────────────────────────────────────────────────
972
973/// Parsed retry configuration from `#[task(retry(max_attempts = N, backoff = "Xs"))]`.
974struct RetryConfig {
975 max_attempts: u32,
976 backoff_secs: u64,
977}
978
979/// Parsed attributes from `#[task(...)]`.
980struct TaskAttrs {
981 retry: Option<RetryConfig>,
982 rerun_on_resume: bool,
983}
984
985/// Parse task attributes from the attribute token stream.
986///
987/// Supports:
988/// - `#[task]` — no retry, no rerun
989/// - `#[task(retry(max_attempts = 3, backoff = "1s"))]` — with retry
990/// - `#[task(rerun_on_resume)]` — always re-execute on resume (skip cache)
991/// - `#[task(rerun_on_resume = true)]` — explicit boolean form
992/// - `#[task(rerun_on_resume, retry(max_attempts = 3, backoff = "1s"))]` — combined
993fn parse_task_attrs(attr: TokenStream) -> TaskAttrs {
994 if attr.is_empty() {
995 return TaskAttrs { retry: None, rerun_on_resume: false };
996 }
997
998 // Parse the attribute as a Meta list
999 let attr_meta: syn::Result<syn::Meta> = syn::parse(attr.clone());
1000 if let Ok(syn::Meta::List(meta_list)) = attr_meta
1001 && meta_list.path.is_ident("retry")
1002 && let Some(retry) = parse_retry_from_meta_list(&meta_list)
1003 {
1004 return TaskAttrs { retry: Some(retry), rerun_on_resume: false };
1005 }
1006
1007 // Try parsing as just the inner content of task(...)
1008 // e.g., the attr stream is: `retry(max_attempts = 3, backoff = "1s")`
1009 // or: `rerun_on_resume`
1010 // or: `rerun_on_resume, retry(max_attempts = 3, backoff = "1s")`
1011 let attr2: proc_macro2::TokenStream = attr.into();
1012 let parsed: syn::Result<TaskAttrContent> = syn::parse2(attr2);
1013 if let Ok(content) = parsed {
1014 return TaskAttrs { retry: content.retry, rerun_on_resume: content.rerun_on_resume };
1015 }
1016
1017 TaskAttrs { retry: None, rerun_on_resume: false }
1018}
1019
1020/// Inner content parsed from `#[task(retry(...), rerun_on_resume)]`.
1021struct TaskAttrContent {
1022 retry: Option<RetryConfig>,
1023 rerun_on_resume: bool,
1024}
1025
1026impl syn::parse::Parse for TaskAttrContent {
1027 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
1028 let mut retry = None;
1029 let mut rerun_on_resume = false;
1030
1031 // Parse comma-separated items: identifiers, name-value pairs, or calls like retry(...)
1032 while !input.is_empty() {
1033 let ident: syn::Ident = input.parse()?;
1034
1035 if ident == "retry" {
1036 let content;
1037 syn::parenthesized!(content in input);
1038
1039 let mut max_attempts: u32 = 3;
1040 let mut backoff_secs: u64 = 1;
1041
1042 let pairs = syn::punctuated::Punctuated::<syn::MetaNameValue, syn::Token![,]>::parse_terminated(&content)?;
1043
1044 for pair in pairs {
1045 if pair.path.is_ident("max_attempts")
1046 && let syn::Expr::Lit(expr_lit) = &pair.value
1047 && let syn::Lit::Int(lit_int) = &expr_lit.lit
1048 {
1049 max_attempts = lit_int.base10_parse().unwrap_or(3);
1050 } else if pair.path.is_ident("backoff")
1051 && let syn::Expr::Lit(expr_lit) = &pair.value
1052 && let syn::Lit::Str(lit_str) = &expr_lit.lit
1053 {
1054 backoff_secs = parse_duration_str(&lit_str.value());
1055 }
1056 }
1057
1058 retry = Some(RetryConfig { max_attempts, backoff_secs });
1059 } else if ident == "rerun_on_resume" {
1060 // Accept both `rerun_on_resume` (flag, implies true)
1061 // and `rerun_on_resume = true` / `rerun_on_resume = false`
1062 if input.peek(syn::Token![=]) {
1063 let _eq: syn::Token![=] = input.parse()?;
1064 let lit: syn::LitBool = input.parse()?;
1065 rerun_on_resume = lit.value;
1066 } else {
1067 rerun_on_resume = true;
1068 }
1069 } else {
1070 return Err(syn::Error::new_spanned(
1071 ident,
1072 "unknown task attribute; expected `retry(...)` or `rerun_on_resume`",
1073 ));
1074 }
1075
1076 // Consume optional trailing comma
1077 if input.peek(syn::Token![,]) {
1078 let _comma: syn::Token![,] = input.parse()?;
1079 }
1080 }
1081
1082 Ok(TaskAttrContent { retry, rerun_on_resume })
1083 }
1084}
1085
1086/// Parse retry config from a `Meta::List` (e.g., `retry(max_attempts = 3, backoff = "1s")`).
1087fn parse_retry_from_meta_list(meta_list: &syn::MetaList) -> Option<RetryConfig> {
1088 let mut max_attempts: u32 = 3;
1089 let mut backoff_secs: u64 = 1;
1090
1091 let pairs: syn::Result<syn::punctuated::Punctuated<syn::MetaNameValue, syn::Token![,]>> =
1092 meta_list.parse_args_with(syn::punctuated::Punctuated::parse_terminated);
1093
1094 if let Ok(pairs) = pairs {
1095 for pair in pairs {
1096 if pair.path.is_ident("max_attempts")
1097 && let syn::Expr::Lit(expr_lit) = &pair.value
1098 && let syn::Lit::Int(lit_int) = &expr_lit.lit
1099 {
1100 max_attempts = lit_int.base10_parse().unwrap_or(3);
1101 } else if pair.path.is_ident("backoff")
1102 && let syn::Expr::Lit(expr_lit) = &pair.value
1103 && let syn::Lit::Str(lit_str) = &expr_lit.lit
1104 {
1105 backoff_secs = parse_duration_str(&lit_str.value());
1106 }
1107 }
1108 Some(RetryConfig { max_attempts, backoff_secs })
1109 } else {
1110 None
1111 }
1112}
1113
1114/// Parse a duration string like "1s", "500ms", "2s" into seconds.
1115/// Defaults to 1 second if parsing fails.
1116fn parse_duration_str(s: &str) -> u64 {
1117 let s = s.trim();
1118 // Check "ms" suffix first (before "s" since "ms" ends with 's')
1119 if let Some(ms) = s.strip_suffix("ms") {
1120 return ms.parse::<u64>().ok().map(|v| v / 1000).unwrap_or(1);
1121 }
1122 if let Some(secs) = s.strip_suffix('s') {
1123 return secs.parse::<u64>().unwrap_or(1);
1124 }
1125 // Try parsing as plain number (assume seconds)
1126 s.parse::<u64>().unwrap_or(1)
1127}
1128
1129/// Derives `adk_core::Choice` for an enum of unit variants, so a model can decide one of them
1130/// with `adk_core::decide::<T>`.
1131///
1132/// Each variant is an option named in snake_case (`OutOfScope` → `out_of_scope`) unless
1133/// `#[choice(name = "...")]` names it, and described to the model by its doc comment. The
1134/// generated code refers to `adk_core`, so the calling crate depends on `adk-core` beside
1135/// `adk-rust-macros`.
1136///
1137/// # Example
1138///
1139/// ```rust
1140/// use adk_core::Choice;
1141/// use adk_rust_macros::Choice;
1142///
1143/// #[derive(Choice, Debug, PartialEq)]
1144/// enum Route {
1145/// /// Invoices, refunds and payment problems
1146/// Billing,
1147/// /// Errors, outages and how-to questions
1148/// Technical,
1149/// /// Anything the support team does not handle
1150/// #[choice(name = "elsewhere")]
1151/// OutOfScope,
1152/// }
1153///
1154/// let names: Vec<String> = Route::options().into_iter().map(|option| option.name).collect();
1155/// assert_eq!(names, ["billing", "technical", "elsewhere"]);
1156/// assert_eq!(Route::options()[0].description, "Invoices, refunds and payment problems");
1157/// assert_eq!(Route::from_option("elsewhere"), Some(Route::OutOfScope));
1158/// assert_eq!(Route::from_option("sales"), None);
1159/// ```
1160///
1161/// A struct, a union, a variant with fields, or two variants with the same option name fails
1162/// to compile.
1163#[proc_macro_derive(Choice, attributes(choice))]
1164pub fn derive_choice(input: TokenStream) -> TokenStream {
1165 let input = parse_macro_input!(input as syn::DeriveInput);
1166 match choice_impl(&input) {
1167 Ok(tokens) => tokens.into(),
1168 Err(error) => error.to_compile_error().into(),
1169 }
1170}
1171
1172fn choice_impl(input: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
1173 let syn::Data::Enum(data) = &input.data else {
1174 return Err(syn::Error::new_spanned(
1175 &input.ident,
1176 "#[derive(Choice)] needs an enum whose variants are the options",
1177 ));
1178 };
1179 let ident = &input.ident;
1180 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
1181 let mut names = Vec::new();
1182 let mut descriptions = Vec::new();
1183 let mut variants = Vec::new();
1184 for variant in &data.variants {
1185 if !matches!(variant.fields, syn::Fields::Unit) {
1186 return Err(syn::Error::new_spanned(
1187 variant,
1188 "#[derive(Choice)] options are unit variants; move the data elsewhere",
1189 ));
1190 }
1191 let mut name = None;
1192 for attr in variant.attrs.iter().filter(|attr| attr.path().is_ident("choice")) {
1193 attr.parse_nested_meta(|meta| {
1194 if meta.path.is_ident("name") {
1195 let value: syn::LitStr = meta.value()?.parse()?;
1196 name = Some(value.value());
1197 Ok(())
1198 } else {
1199 Err(meta.error("expected `name = \"...\"`"))
1200 }
1201 })?;
1202 }
1203 let name = name.unwrap_or_else(|| snake_case(&variant.ident.to_string()));
1204 if names.contains(&name) {
1205 return Err(syn::Error::new_spanned(
1206 variant,
1207 format!(
1208 "two variants are both the option `{name}`; give one a #[choice(name = ...)]"
1209 ),
1210 ));
1211 }
1212 let description = variant
1213 .attrs
1214 .iter()
1215 .filter_map(|attr| match &attr.meta {
1216 Meta::NameValue(pair) if pair.path.is_ident("doc") => match &pair.value {
1217 syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(text), .. }) => {
1218 Some(text.value().trim().to_string())
1219 }
1220 _ => None,
1221 },
1222 _ => None,
1223 })
1224 .filter(|line| !line.is_empty())
1225 .collect::<Vec<_>>()
1226 .join(" ");
1227 names.push(name);
1228 descriptions.push(description);
1229 variants.push(variant.ident.clone());
1230 }
1231 Ok(quote! {
1232 impl #impl_generics ::adk_core::Choice for #ident #ty_generics #where_clause {
1233 fn options() -> ::std::vec::Vec<::adk_core::ChoiceOption> {
1234 ::std::vec![#(::adk_core::ChoiceOption::new(#names, #descriptions)),*]
1235 }
1236
1237 fn from_option(name: &str) -> ::std::option::Option<Self> {
1238 match name {
1239 #(#names => ::std::option::Option::Some(Self::#variants),)*
1240 _ => ::std::option::Option::None,
1241 }
1242 }
1243 }
1244 })
1245}
1246
1247/// `OutOfScope` → `out_of_scope`.
1248fn snake_case(name: &str) -> String {
1249 let mut snake = String::new();
1250 for (index, ch) in name.chars().enumerate() {
1251 if ch.is_uppercase() {
1252 if index > 0 {
1253 snake.push('_');
1254 }
1255 snake.extend(ch.to_lowercase());
1256 } else {
1257 snake.push(ch);
1258 }
1259 }
1260 snake
1261}