arqen 0.4.0

Backend infrastructure for agent-ready applications
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
use clap::{Parser, Subcommand};
use std::fs;
use std::net::SocketAddr;
use std::path::Path;

#[derive(Parser)]
#[command(name = "arqen")]
#[command(about = "Arqen CLI for generating and running applications")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Generate a new Arqen application
    New {
        /// Project name
        name: String,
    },
    /// Generate code scaffolding
    Generate {
        #[command(subcommand)]
        kind: GenerateKind,
    },
    /// Run the application in development mode
    Dev {
        /// Host to bind to
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
        /// Port to bind to
        #[arg(short, long, default_value = "8888")]
        port: u16,
        /// Log level
        #[arg(short, long, default_value = "info")]
        log: String,
        /// Storage mode
        #[arg(short, long, default_value = "memory")]
        storage: String,
    },
    /// Run the application
    Start {
        /// Host to bind to
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
        /// Port to bind to
        #[arg(short, long, default_value = "8888")]
        port: u16,
        /// Log level
        #[arg(short, long, default_value = "info")]
        log: String,
        /// Storage mode
        #[arg(short, long, default_value = "memory")]
        storage: String,
    },
    /// Run and supervise local dev services defined in arqen.toml
    Up {
        /// Names of services to start (defaults to all)
        #[arg(value_name = "SERVICE")]
        services: Vec<String>,
        /// Config file to read dev services from
        #[arg(long, default_value = "arqen.toml")]
        file: std::path::PathBuf,
        /// Print the services that would be started without running them
        #[arg(long)]
        dry_run: bool,
    },
    /// Run checks
    Check,
    /// Diagnose Rust, thingd, Docker, and environment setup
    Doctor,
}

#[derive(Subcommand)]
enum GenerateKind {
    /// Generate a new module
    Module {
        /// Module name
        name: String,
    },
    /// Generate a new tool
    Tool {
        /// Tool name
        name: String,
    },
    /// Generate a new job handler
    Job {
        /// Job name
        name: String,
    },
}

fn generate_project(name: &str) -> anyhow::Result<()> {
    let project_dir = Path::new(name);
    if project_dir.exists() {
        anyhow::bail!("Directory '{}' already exists", name);
    }

    // Create directory structure
    fs::create_dir_all(project_dir.join("src").join("app"))?;
    fs::create_dir_all(project_dir.join("src").join("routes"))?;

    // Cargo.toml
    let cargo_toml = format!(
        r#"[package]
name = "{}"
version = "0.1.0"
edition = "2024"
rust-version = "1.96"

[dependencies]
arqen = {{ version = "0.3", features = ["logging", "http-server"] }}
tokio = {{ version = "1", features = ["full"] }}
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
async-trait = "0.1"
"#,
        name
    );
    fs::write(project_dir.join("Cargo.toml"), cargo_toml)?;

    // src/main.rs
    let main_rs = format!(
        r#"use arqen::app::ArqenApp;
use arqen::module::Module;

mod app;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {{
    arqen::logging::init_logging("info", "pretty");

    ArqenApp::builder()
        .name("{name}")
        .module(app::AppModule)
        .build()?
        .start()
        .await
}}
"#
    );
    fs::write(project_dir.join("src").join("main.rs"), main_rs)?;

    // src/app/mod.rs
    let app_mod = r#"use arqen::module::{Module, ModuleHealth};

pub struct AppModule;

#[async_trait::async_trait]
impl Module for AppModule {
    fn name(&self) -> &str {
        "app"
    }

    async fn health_check(&self) -> ModuleHealth {
        ModuleHealth::Healthy
    }
}
"#;
    fs::write(project_dir.join("src").join("app").join("mod.rs"), app_mod)?;

    // src/routes/mod.rs
    let routes_mod = r#"pub mod health;
"#;
    fs::write(
        project_dir.join("src").join("routes").join("mod.rs"),
        routes_mod,
    )?;

    // src/routes/health.rs
    let health_route = r#"use axum::Json;
use serde_json::{json, Value};

pub async fn health() -> Json<Value> {
    Json(json!({"status": "ok"}))
}
"#;
    fs::write(
        project_dir.join("src").join("routes").join("health.rs"),
        health_route,
    )?;

    // README.md
    let readme = format!(
        r#"# {name}

An Arqen application.

## Getting started

```bash
cargo run
```

The server starts on http://127.0.0.1:8888 with in-memory storage.

## Endpoints

- GET /health - Liveness check
- GET /ready - Readiness check
- GET /agent - Agent description
- GET /agent/manifest - Agent manifest
- GET /docs - API documentation

## Adding modules

```bash
arqen generate module users
```

This creates `src/users/mod.rs` with a module stub. Register it in `src/app/mod.rs`:

```rust
mod users;

// In AppModule::dependencies():
fn dependencies(&self) -> Vec<&str> {{
    vec!["users"]
}}
```

## Adding tools

```bash
arqen generate tool get_user
```

This creates `src/tools/get_user.rs` with a tool definition. Register it in your module's `register()` method.

## Adding jobs

```bash
arqen generate job send_email
```

This creates `src/jobs/send_email.rs` with a job handler.
"#
    );
    fs::write(project_dir.join("README.md"), readme)?;

    println!("Created project '{}'", name);
    println!();
    println!("Next steps:");
    println!("  cd {}", name);
    println!("  cargo run");
    Ok(())
}

fn generate_module(name: &str) -> anyhow::Result<()> {
    let src_dir = Path::new("src");
    if !src_dir.exists() {
        anyhow::bail!("No src/ directory found. Run this from an Arqen project root.");
    }

    let module_dir = src_dir.join(name);
    if module_dir.exists() {
        anyhow::bail!("Module '{}' already exists", name);
    }

    fs::create_dir_all(&module_dir)?;

    let module_rs = format!(
        r#"use arqen::module::{{Module, ModuleContext, ModuleHealth}};
use arqen::core::AppError;

pub struct {module_name}Module;

#[async_trait::async_trait]
impl Module for {module_name}Module {{
    fn name(&self) -> &str {{
        "{name}"
    }}

    fn register(&self, _ctx: &mut ModuleContext<'_>) -> Result<(), AppError> {{
        // Register tools: ctx.tools.register_tool(...)
        Ok(())
    }}

    async fn health_check(&self) -> ModuleHealth {{
        ModuleHealth::Healthy
    }}
}}
"#,
        module_name = to_pascal_case(name),
        name = name,
    );
    fs::write(module_dir.join("mod.rs"), module_rs)?;

    println!("Created module '{name}' at src/{name}/mod.rs");
    println!();
    println!("Register in src/app/mod.rs:");
    println!("  pub mod {name};");
    println!();
    println!("Add to AppModule::dependencies():");
    println!("  fn dependencies(&self) -> Vec<&str> {{ vec![\"{name}\"] }}");
    Ok(())
}

fn generate_tool(name: &str) -> anyhow::Result<()> {
    let src_dir = Path::new("src");
    if !src_dir.exists() {
        anyhow::bail!("No src/ directory found. Run this from an Arqen project root.");
    }

    let tools_dir = src_dir.join("tools");
    fs::create_dir_all(&tools_dir)?;

    let tool_file = tools_dir.join(format!("{}.rs", name));
    if tool_file.exists() {
        anyhow::bail!("Tool '{}' already exists", name);
    }

    let tool_rs = format!(
        r#"use arqen::agent::{{ToolEffect, ToolMetadata}};
use arqen::core::AppError;
use arqen::module::ModuleContext;

pub fn tool_metadata() -> ToolMetadata {{
    ToolMetadata {{
        name: "{name}".to_string(),
        description: "TODO: describe what this tool does".to_string(),
        input: serde_json::json!({{
            "type": "object",
            "properties": {{}},
            "required": []
        }}),
        output: serde_json::json!({{
            "type": "object"
        }}),
        scopes: vec![],
        effect: ToolEffect::Read,
        idempotent: true,
        enqueues_job: None,
        timeout: None,
    }}
}}

pub fn register(ctx: &mut ModuleContext<'_>) -> Result<(), AppError> {{
    ctx.tools.register_tool(tool_metadata());
    Ok(())
}}
"#
    );
    fs::write(&tool_file, tool_rs)?;

    println!("Created tool '{name}' at src/tools/{name}.rs");
    println!();
    println!("Register in your module's register() method:");
    println!("  crate::tools::{name}::register(ctx)?;");
    Ok(())
}

fn generate_job(name: &str) -> anyhow::Result<()> {
    let src_dir = Path::new("src");
    if !src_dir.exists() {
        anyhow::bail!("No src/ directory found. Run this from an Arqen project root.");
    }

    let jobs_dir = src_dir.join("jobs");
    fs::create_dir_all(&jobs_dir)?;

    let job_file = jobs_dir.join(format!("{}.rs", name));
    if job_file.exists() {
        anyhow::bail!("Job '{}' already exists", name);
    }

    let job_rs = format!(
        r#"use arqen::core::AppError;
use arqen::jobs::JobHandler;

pub struct {handler_name}Handler;

#[async_trait::async_trait]
impl JobHandler for {handler_name}Handler {{
    async fn handle(&self, payload: serde_json::Value) -> Result<(), AppError> {{
        // TODO: implement job processing
        tracing::info!(payload = %payload, "Processing job");
        Ok(())
    }}
}}
"#,
        handler_name = to_pascal_case(name),
    );
    fs::write(&job_file, job_rs)?;

    println!("Created job handler '{name}' at src/jobs/{name}.rs");
    println!();
    println!("Next steps:");
    println!("  1. Add `pub mod {name};` to src/jobs/mod.rs.");
    println!("  2. Register the job metadata with your application's ToolRegistry.");
    println!("  3. Configure a worker for the job queue and start it from your app.");
    Ok(())
}

fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(c) => c.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
            }
        })
        .collect()
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::New { name } => {
            generate_project(&name)?;
        }
        Commands::Generate { kind } => match kind {
            GenerateKind::Module { name } => generate_module(&name)?,
            GenerateKind::Tool { name } => generate_tool(&name)?,
            GenerateKind::Job { name } => generate_job(&name)?,
        },
        Commands::Dev {
            host,
            port,
            log,
            storage,
        } => {
            println!("Starting Arqen in development mode...");
            arqen::logging::init_logging(&log, "pretty");

            let addr: SocketAddr = format!("{}:{}", host, port).parse()?;
            let state = arqen::AppState::builder()
                .with_storage_mode(&storage)
                .with_tool_registry(arqen::ToolRegistry::new(
                    "arqen-app",
                    env!("CARGO_PKG_VERSION"),
                    "An Arqen application",
                    &storage,
                ))
                .build()?;
            let router = arqen::http::create_router_with_state(state);

            println!("Arqen v{}", env!("CARGO_PKG_VERSION"));
            println!("API:    http://{}", addr);
            println!("Health: http://{}/health", addr);
            println!("Docs:   http://{}/docs", addr);
            println!("Agent:  http://{}/agent", addr);
            println!("Storage: {}", storage);

            arqen::http::start_server(addr, router)
                .await
                .map_err(|e| anyhow::anyhow!(e))?;
        }
        Commands::Start {
            host,
            port,
            log,
            storage,
        } => {
            println!("Starting Arqen...");
            arqen::logging::init_logging(&log, "json");

            let addr: SocketAddr = format!("{}:{}", host, port).parse()?;
            let state = arqen::AppState::builder()
                .with_storage_mode(&storage)
                .with_tool_registry(arqen::ToolRegistry::new(
                    "arqen-app",
                    env!("CARGO_PKG_VERSION"),
                    "An Arqen application",
                    &storage,
                ))
                .build()?;
            let router = arqen::http::create_router_with_state(state);

            println!("Arqen listening on {}", addr);

            arqen::http::start_server(addr, router)
                .await
                .map_err(|e| anyhow::anyhow!(e))?;
        }
        Commands::Up {
            services,
            file,
            dry_run,
        } => {
            arqen::dev::run_up(&file, &services, dry_run).await?;
        }
        Commands::Check => {
            println!("Running checks...");
            println!("Checks passed");
        }
        Commands::Doctor => {
            println!("Arqen Doctor - Diagnosing environment...\n");

            println!("1. Checking Rust installation...");
            match std::process::Command::new("rustc")
                .arg("--version")
                .output()
            {
                Ok(output) => {
                    let version = String::from_utf8_lossy(&output.stdout);
                    println!("   Rust installed: {}", version.trim());
                }
                Err(e) => println!("   Rust not found: {}", e),
            }

            println!("2. Checking Cargo installation...");
            match std::process::Command::new("cargo")
                .arg("--version")
                .output()
            {
                Ok(output) => {
                    let version = String::from_utf8_lossy(&output.stdout);
                    println!("   Cargo installed: {}", version.trim());
                }
                Err(e) => println!("   Cargo not found: {}", e),
            }

            println!("3. Checking Docker installation...");
            match std::process::Command::new("docker")
                .arg("--version")
                .output()
            {
                Ok(output) => {
                    let version = String::from_utf8_lossy(&output.stdout);
                    println!("   Docker installed: {}", version.trim());
                }
                Err(e) => println!("   Docker not found: {}", e),
            }

            println!("4. Checking Docker Compose...");
            match std::process::Command::new("docker")
                .arg("compose")
                .arg("version")
                .output()
            {
                Ok(output) => {
                    let version = String::from_utf8_lossy(&output.stdout);
                    println!("   Docker Compose installed: {}", version.trim());
                }
                Err(_) => match std::process::Command::new("docker-compose")
                    .arg("--version")
                    .output()
                {
                    Ok(output) => {
                        let version = String::from_utf8_lossy(&output.stdout);
                        println!("   Docker Compose installed: {}", version.trim());
                    }
                    Err(e) => println!("   Docker Compose not found: {}", e),
                },
            }

            println!("5. Checking thingd connectivity...");
            if let Ok(thingd_url) = std::env::var("ARQEN_THINGD_URL") {
                println!("   thingd URL: {}", thingd_url);
                println!("   Connectivity check not implemented");
            } else {
                println!("   ARQEN_THINGD_URL not set");
            }

            println!("6. Checking environment variables...");
            let env_vars = [
                "ARQEN_HOST",
                "ARQEN_PORT",
                "ARQEN_LOG",
                "ARQEN_STORAGE_MODE",
            ];
            for var in env_vars {
                match std::env::var(var) {
                    Ok(value) => println!("   {} = {}", var, value),
                    Err(_) => println!("   {} not set (using default)", var),
                }
            }

            println!("\nDoctor complete.");
        }
    }

    Ok(())
}