cargo-adk 0.9.0

CLI scaffolding tool for ADK-Rust — generate agent projects from templates
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
//! Code generation engine for the composable scaffolding system.
//!
//! This module generates all project files from a [`CompositionManifest`]:
//! `main.rs`, `Cargo.toml`, `.env.example`, `README.md`, and `.gitignore`.
//!
//! The generated code uses `tracing` for logging, `anyhow` for error handling,
//! and follows ADK-Rust best practices.

use crate::composition::{CompositionManifest, GeneratedFile};
use crate::provider::get_provider_config;
use crate::registry::TemplateRegistry;

/// Current ADK-Rust version, read from this crate's own version at compile time.
const ADK_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Generate all project files from a composition manifest.
///
/// Returns a vector of [`GeneratedFile`] entries ready to be written to disk.
///
/// # Arguments
///
/// * `manifest` - The resolved composition manifest from the pipeline
/// * `project_name` - The project/crate name
///
/// # Example
///
/// ```rust,ignore
/// let files = generate_project(&manifest, "my-agent");
/// for file in &files {
///     println!("{}: {} bytes", file.path, file.content.len());
/// }
/// ```
pub fn generate_project(manifest: &CompositionManifest, project_name: &str) -> Vec<GeneratedFile> {
    vec![
        GeneratedFile {
            path: "Cargo.toml".to_string(),
            content: generate_cargo_toml(manifest, project_name),
        },
        GeneratedFile {
            path: "src/main.rs".to_string(),
            content: generate_main_rs(manifest, project_name),
        },
        GeneratedFile { path: ".env.example".to_string(), content: generate_env_example(manifest) },
        GeneratedFile {
            path: "README.md".to_string(),
            content: generate_readme(manifest, project_name),
        },
        GeneratedFile { path: ".gitignore".to_string(), content: generate_gitignore() },
    ]
}

/// Generate `Cargo.toml` with minimal dependencies from the composition manifest.
///
/// Uses edition 2024 and the current ADK_VERSION. Features are the union of
/// all template + addon + provider features.
pub fn generate_cargo_toml(manifest: &CompositionManifest, project_name: &str) -> String {
    let features: Vec<&str> = manifest.feature_set.iter().map(|s| s.as_str()).collect();
    let features_str = features.iter().map(|f| format!("\"{f}\"")).collect::<Vec<_>>().join(", ");

    let mut output = format!(
        r#"[package]
name = "{project_name}"
version = "0.1.0"
edition = "2024"

[dependencies]
adk-rust = {{ version = "{ADK_VERSION}", default-features = false, features = [{features_str}] }}
tokio = {{ version = "1", features = ["full"] }}
dotenvy = "0.15"
tracing = "0.1"
tracing-subscriber = {{ version = "0.3", features = ["env-filter"] }}
anyhow = "1"
"#
    );

    // Add additional dependencies from addons
    for dep in &manifest.dependencies {
        if dep.features.is_empty() {
            output.push_str(&format!("{} = \"{}\"\n", dep.crate_name, dep.version));
        } else {
            let dep_features =
                dep.features.iter().map(|f| format!("\"{f}\"")).collect::<Vec<_>>().join(", ");
            output.push_str(&format!(
                "{} = {{ version = \"{}\", features = [{dep_features}] }}\n",
                dep.crate_name, dep.version
            ));
        }
    }

    output
}

/// Generate `src/main.rs` with proper composition of template and addons.
///
/// The generated code merges:
/// - Provider model initialization
/// - Template agent construction
/// - Addon imports (sorted by priority)
/// - Addon initialization (sorted by priority)
/// - Addon builder calls
///
/// The server addon uses `std::env::var("PORT")` for port binding.
pub fn generate_main_rs(manifest: &CompositionManifest, project_name: &str) -> String {
    let registry = TemplateRegistry::builtin();

    // Resolve provider config for model init code
    let provider_config = get_provider_config(&manifest.provider).ok();

    // Collect addon code fragments sorted by priority
    let mut sorted_addons: Vec<_> = manifest
        .addons
        .iter()
        .filter_map(|addon_name| registry.capability_addons.iter().find(|a| a.name == *addon_name))
        .collect();
    sorted_addons.sort_by_key(|a| a.init_priority);

    // Resolve template for agent construction
    let template = registry.resolve_template(&manifest.template_name);

    // Build imports section
    let mut imports = Vec::new();
    imports.push("use adk_rust::prelude::*;".to_string());

    // Add template imports
    if let Some(tmpl) = template {
        for imp in &tmpl.code_fragments.imports {
            if !imp.is_empty() {
                imports.push(imp.to_string());
            }
        }
    }

    // Add addon imports (sorted by priority)
    for addon in &sorted_addons {
        for imp in &addon.code_fragments.imports {
            if !imp.is_empty() && !imports.contains(&imp.to_string()) {
                imports.push(imp.to_string());
            }
        }
    }

    let imports_section = imports.join("\n");

    // Build model initialization
    let model_init = if let Some(pc) = provider_config {
        format!("    let model = {};", pc.model_init_code)
    } else {
        "    let model = Gemini::from_env(\"gemini-2.5-flash\");".to_string()
    };

    // Build agent construction
    let agent_construction = if let Some(tmpl) = template {
        let code = tmpl.code_fragments.agent_construction;
        if code.is_empty() || code.starts_with("// TODO") {
            // Placeholder agent construction
            format!(
                r#"    let agent = LlmAgent::builder()
        .name("{project_name}")
        .model(model)
        .instruction("You are a helpful assistant.")
        .build();"#,
            )
        } else {
            // Replace {name} placeholder with actual project name
            let resolved = code.replace("{name}", project_name);
            format!("    {resolved}")
        }
    } else {
        format!(
            r#"    let agent = LlmAgent::builder()
        .name("{project_name}")
        .model(model)
        .instruction("You are a helpful assistant.")
        .build();"#,
        )
    };

    // Build addon initialization (sorted by priority)
    let mut addon_init_lines = Vec::new();
    for addon in &sorted_addons {
        let init = addon.code_fragments.initialization;
        if !init.is_empty() && !init.starts_with("// TODO") {
            addon_init_lines.push(format!("    {init}"));
        } else {
            // Generate placeholder initialization based on addon name
            addon_init_lines.push(format!(
                "    // {} initialization (priority {})",
                addon.name, addon.init_priority
            ));
            addon_init_lines.push(generate_placeholder_init(addon.name));
        }
    }

    // Build addon builder calls
    let mut builder_calls = Vec::new();
    for addon in &sorted_addons {
        let calls = addon.code_fragments.agent_builder_calls;
        if !calls.is_empty() {
            builder_calls.push(format!("    {calls}"));
        }
    }

    // Check if telemetry addon is present for tracing init
    let has_telemetry = manifest.addons.iter().any(|a| a == "telemetry");
    let has_server = manifest.addons.iter().any(|a| a == "server");

    // Build tracing subscriber init
    let tracing_init = if has_telemetry {
        r#"    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_target(true)
        .init();
    tracing::info!("telemetry initialized");"#
            .to_string()
    } else {
        r#"    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();"#
            .to_string()
    };

    // Build server binding (if server addon present)
    let server_section = if has_server {
        r#"
    // Server binding
    let port = std::env::var("PORT").unwrap_or_else(|_| "8080".to_string());
    let addr = format!("0.0.0.0:{port}");
    tracing::info!("starting server on {}", addr);"#
            .to_string()
    } else {
        String::new()
    };

    // Assemble the full main.rs
    let addon_init_section = if addon_init_lines.is_empty() {
        String::new()
    } else {
        format!(
            "\n    // Addon initialization (sorted by priority)\n{}\n",
            addon_init_lines.join("\n")
        )
    };

    let builder_calls_section = if builder_calls.is_empty() {
        String::new()
    } else {
        format!("\n    // Addon builder calls\n{}\n", builder_calls.join("\n"))
    };

    format!(
        r#"{imports_section}

#[tokio::main]
async fn main() -> anyhow::Result<()> {{
    dotenvy::dotenv().ok();

{tracing_init}

    // Provider model initialization
{model_init}

    // Agent construction
{agent_construction}
{addon_init_section}{builder_calls_section}{server_section}
    Ok(())
}}
"#
    )
}

/// Generate `.env.example` listing all required environment variables.
///
/// Collects env vars from the provider (if it requires an API key) and all addons.
pub fn generate_env_example(manifest: &CompositionManifest) -> String {
    let mut output = String::from("# Environment variables for this ADK-Rust agent project\n\n");

    if manifest.env_vars.is_empty() {
        output.push_str("# No environment variables required for this configuration.\n");
    } else {
        for (key, description) in &manifest.env_vars {
            output.push_str(&format!("# {description}\n"));
            output.push_str(&format!("{key}=\n\n"));
        }
    }

    // Always include RUST_LOG for tracing
    output.push_str("# Logging level (trace, debug, info, warn, error)\n");
    output.push_str("RUST_LOG=info\n");

    output
}

/// Generate `README.md` with template-specific documentation.
///
/// Includes project description, setup instructions, architecture overview,
/// and how to extend the agent.
pub fn generate_readme(manifest: &CompositionManifest, project_name: &str) -> String {
    let registry = TemplateRegistry::builtin();
    let template = registry.resolve_template(&manifest.template_name);

    let template_description = template.map(|t| t.description).unwrap_or("ADK-Rust agent project");

    let addons_section = if manifest.addons.is_empty() {
        String::new()
    } else {
        let addon_list: Vec<String> = manifest
            .addons
            .iter()
            .filter_map(|name| {
                registry
                    .capability_addons
                    .iter()
                    .find(|a| a.name == *name)
                    .map(|a| format!("- **{}**: {}", a.name, a.description))
            })
            .collect();
        format!("\n## Capabilities\n\n{}\n", addon_list.join("\n"))
    };

    let features_list: Vec<&str> = manifest.feature_set.iter().map(|s| s.as_str()).collect();

    let env_vars_section = if manifest.env_vars.is_empty() {
        String::new()
    } else {
        let vars: Vec<String> =
            manifest.env_vars.iter().map(|(key, desc)| format!("| `{key}` | {desc} |")).collect();
        format!(
            "\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n{}\n",
            vars.join("\n")
        )
    };

    format!(
        r#"# {project_name}

{template_description}

## Quick Start

```bash
# Install dependencies
cargo build

# Copy environment template
cp .env.example .env
# Edit .env with your API keys

# Run the agent
cargo run
```

## Architecture

- **Template**: `{template_name}` ({template_description})
- **Provider**: `{provider}`
- **Features**: `[{features}]`
{addons_section}{env_vars_section}
## Development

```bash
# Run with debug logging
RUST_LOG=debug cargo run

# Check for issues
cargo clippy -- -D warnings

# Format code
cargo fmt
```

## Extending

- Add tools by implementing the `Tool` trait
- Modify the agent instruction in `src/main.rs`
- Add new dependencies to `Cargo.toml`

## Resources

- [ADK-Rust Documentation](https://docs.rs/adk-rust)
- [ADK-Rust GitHub](https://github.com/zavora-ai/adk-rust)
"#,
        template_name = manifest.template_name,
        provider = manifest.provider,
        features = features_list.join(", "),
    )
}

/// Generate a standard Rust `.gitignore` file.
pub fn generate_gitignore() -> String {
    r#"/target
.env
*.swp
*.swo
*~
.DS_Store
"#
    .to_string()
}

/// Generate placeholder initialization code for an addon.
fn generate_placeholder_init(addon_name: &str) -> String {
    match addon_name {
        "telemetry" => "    tracing::info!(\"telemetry configured\");".to_string(),
        "auth" => "    tracing::info!(\"auth middleware configured\");".to_string(),
        "sessions" => "    tracing::info!(\"session service initialized\");".to_string(),
        "memory" => "    tracing::info!(\"memory service initialized\");".to_string(),
        "mcp" => "    tracing::info!(\"MCP tools connected\");".to_string(),
        "guardrails" => "    tracing::info!(\"guardrails configured\");".to_string(),
        "eval" => "    tracing::info!(\"eval harness ready\");".to_string(),
        "browser" => "    tracing::info!(\"browser tools initialized\");".to_string(),
        "server" => r#"    let port = std::env::var("PORT").unwrap_or_else(|_| "8080".to_string());
    tracing::info!("server will bind to port {}", port);"#
            .to_string(),
        _ => format!("    tracing::info!(\"{addon_name} initialized\");"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::composition::resolve_composition;
    use crate::registry::TemplateRegistry;

    fn registry() -> TemplateRegistry {
        TemplateRegistry::builtin()
    }

    #[test]
    fn test_generate_cargo_toml_basic() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "gemini").unwrap();
        let toml = generate_cargo_toml(&manifest, "my-agent");

        assert!(toml.contains("name = \"my-agent\""));
        assert!(toml.contains("edition = \"2024\""));
        assert!(toml.contains(&format!("version = \"{ADK_VERSION}\"")));
        assert!(toml.contains("\"minimal\""));
        assert!(toml.contains("\"gemini\""));
        assert!(toml.contains("tokio"));
        assert!(toml.contains("dotenvy"));
        assert!(toml.contains("tracing"));
        assert!(toml.contains("anyhow"));
    }

    #[test]
    fn test_generate_cargo_toml_with_addons() {
        let reg = registry();
        let manifest =
            resolve_composition(&reg, "llm", &["telemetry", "sessions"], "openai").unwrap();
        let toml = generate_cargo_toml(&manifest, "my-agent");

        assert!(toml.contains("\"minimal\""));
        assert!(toml.contains("\"openai\""));
        assert!(toml.contains("\"telemetry\""));
        assert!(toml.contains("\"sessions\""));
    }

    #[test]
    fn test_generate_main_rs_basic() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "gemini").unwrap();
        let main_rs = generate_main_rs(&manifest, "my-agent");

        assert!(main_rs.contains("use adk_rust::prelude::*;"));
        assert!(main_rs.contains("#[tokio::main]"));
        assert!(main_rs.contains("dotenvy::dotenv().ok();"));
        assert!(main_rs.contains("tracing_subscriber::fmt()"));
        assert!(main_rs.contains("Gemini::from_env(\"gemini-2.5-flash\")"));
        assert!(main_rs.contains("anyhow::Result<()>"));
    }

    #[test]
    fn test_generate_main_rs_with_server_addon_uses_port_env() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &["server"], "gemini").unwrap();
        let main_rs = generate_main_rs(&manifest, "my-agent");

        // Critical enterprise requirement: PORT env var
        assert!(
            main_rs.contains(r#"std::env::var("PORT").unwrap_or_else(|_| "8080".to_string())"#),
            "Server addon MUST use std::env::var(\"PORT\").unwrap_or_else(|_| \"8080\".to_string())"
        );
    }

    #[test]
    fn test_generate_main_rs_with_openai_provider() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "openai").unwrap();
        let main_rs = generate_main_rs(&manifest, "my-agent");

        assert!(main_rs.contains("OpenAI::from_env(\"gpt-5-mini\")"));
    }

    #[test]
    fn test_generate_main_rs_addon_ordering() {
        let reg = registry();
        // Pass addons in reverse priority order
        let manifest =
            resolve_composition(&reg, "llm", &["server", "telemetry", "auth"], "gemini").unwrap();
        let main_rs = generate_main_rs(&manifest, "my-agent");

        // Check initialization ordering within the addon initialization section.
        // Telemetry (10) should appear before auth (20) which should appear before server (90).
        // Use the initialization-specific markers to avoid matching import lines.
        let telemetry_init_pos = main_rs.find("telemetry initialized").or_else(|| {
            // Telemetry addon has empty initialization; codegen generates a placeholder comment
            main_rs.find("// telemetry initialization")
        });
        let auth_init_pos = main_rs.find("AUTH_API_KEY");
        let server_init_pos =
            main_rs.find(r#"std::env::var("PORT").unwrap_or_else(|_| "8080".to_string())"#);

        // Auth initialization must appear before server initialization
        if let (Some(auth_p), Some(server_p)) = (auth_init_pos, server_init_pos) {
            assert!(
                auth_p < server_p,
                "auth initialization should appear before server initialization"
            );
        }

        // If telemetry has a placeholder, it should appear before auth
        if let (Some(tel_p), Some(auth_p)) = (telemetry_init_pos, auth_init_pos) {
            assert!(
                tel_p < auth_p,
                "telemetry initialization should appear before auth initialization"
            );
        }
    }

    #[test]
    fn test_generate_env_example_with_provider() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "openai").unwrap();
        let env = generate_env_example(&manifest);

        assert!(env.contains("OPENAI_API_KEY"));
        assert!(env.contains("RUST_LOG"));
    }

    #[test]
    fn test_generate_env_example_ollama_no_key() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "ollama").unwrap();
        let env = generate_env_example(&manifest);

        // Ollama doesn't require an API key
        assert!(!env.contains("OLLAMA"));
        assert!(env.contains("RUST_LOG"));
    }

    #[test]
    fn test_generate_readme_basic() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "gemini").unwrap();
        let readme = generate_readme(&manifest, "my-agent");

        assert!(readme.contains("# my-agent"));
        assert!(readme.contains("gemini"));
        assert!(readme.contains("cargo run"));
        assert!(readme.contains("cargo build"));
    }

    #[test]
    fn test_generate_readme_with_addons() {
        let reg = registry();
        let manifest =
            resolve_composition(&reg, "llm", &["telemetry", "sessions"], "gemini").unwrap();
        let readme = generate_readme(&manifest, "my-agent");

        assert!(readme.contains("Capabilities"));
        assert!(readme.contains("telemetry"));
        assert!(readme.contains("sessions"));
    }

    #[test]
    fn test_generate_gitignore() {
        let gitignore = generate_gitignore();

        assert!(gitignore.contains("/target"));
        assert!(gitignore.contains(".env"));
    }

    #[test]
    fn test_generate_project_produces_all_files() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "gemini").unwrap();
        let files = generate_project(&manifest, "my-agent");

        let paths: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
        assert!(paths.contains(&"Cargo.toml"));
        assert!(paths.contains(&"src/main.rs"));
        assert!(paths.contains(&".env.example"));
        assert!(paths.contains(&"README.md"));
        assert!(paths.contains(&".gitignore"));
    }

    #[test]
    fn test_generate_cargo_toml_edition_2024() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "gemini").unwrap();
        let toml = generate_cargo_toml(&manifest, "test-project");

        assert!(toml.contains("edition = \"2024\""));
    }

    #[test]
    fn test_generate_cargo_toml_adk_version() {
        let reg = registry();
        let manifest = resolve_composition(&reg, "llm", &[], "gemini").unwrap();
        let toml = generate_cargo_toml(&manifest, "test-project");

        // Should contain the current ADK version
        assert!(toml.contains(ADK_VERSION), "Cargo.toml should contain ADK_VERSION: {ADK_VERSION}");
    }

    #[test]
    fn test_generate_main_rs_all_providers() {
        let reg = registry();
        let providers = [
            "gemini",
            "openai",
            "anthropic",
            "deepseek",
            "ollama",
            "groq",
            "openrouter",
            "bedrock",
            "azure-ai",
        ];

        for provider in providers {
            let manifest = resolve_composition(&reg, "llm", &[], provider).unwrap();
            let main_rs = generate_main_rs(&manifest, "test-project");

            // All should produce valid-looking code
            assert!(
                main_rs.contains("#[tokio::main]"),
                "Provider {provider} should produce tokio::main"
            );
            assert!(
                main_rs.contains("dotenvy::dotenv().ok()"),
                "Provider {provider} should include dotenvy"
            );
        }
    }

    #[test]
    fn test_generate_main_rs_with_multiple_addons() {
        let reg = registry();
        let manifest = resolve_composition(
            &reg,
            "llm",
            &["telemetry", "sessions", "memory", "server"],
            "gemini",
        )
        .unwrap();
        let main_rs = generate_main_rs(&manifest, "my-agent");

        // Should contain initialization for all addons
        assert!(main_rs.contains("telemetry"));
        assert!(main_rs.contains("session"));
        assert!(main_rs.contains("memory"));
        assert!(main_rs.contains("server"));
        // Server must use PORT env var
        assert!(main_rs.contains(r#"std::env::var("PORT")"#));
    }
}