hlx 1.2.5

Configuration language designed specifically for ml/ai/data systems
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
use std::path::PathBuf;
use crate::mds::templates::get_embedded_templates;

pub fn init_command(
    template: String,
    dir: Option<PathBuf>,
    name: Option<String>,
    force: bool,
    verbose: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let templates = get_embedded_templates();
    let template_content = templates
        .iter()
        .find(|(t, _)| t == &template)
        .map(|(_, content)| *content)
        .ok_or_else(|| {
            let available: Vec<&str> = templates
                .iter()
                .map(|(name, _)| *name)
                .collect();
            format!(
                "Unknown template '{}'. Available templates: {}", template, available
                .join(", ")
            )
        })?;
    let output_dir = dir
        .unwrap_or_else(|| {
            std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
        });
    let filename = name
        .unwrap_or_else(|| {
            match template.as_str() {
                "ai-dev" => "ai_development_team.hlx".to_string(),
                "data-pipeline" => "data_pipeline.hlx".to_string(),
                _ => format!("{}.hlx", template),
            }
        });
    let output_path = output_dir.join(&filename);
    if output_path.exists() && !force {
        return Err(
            anyhow::anyhow!(
                "File '{}' already exists. Use --force to overwrite.", output_path
                .display()
            )
                .into(),
        );
    }
    if verbose {
        println!("🚀 Initializing HELIX project:");
        println!("  Template: {}", template);
        println!("  Output: {}", output_path.display());
        println!("  Force: {}", force);
    }
    if let Some(parent) = output_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&output_path, template_content)?;
    println!("✅ HELIX project initialized successfully!");
    println!("  Created: {}", output_path.display());
    println!("  Template: {}", template);
    if verbose {
        let content_size = template_content.len();
        println!("  Size: {} bytes", content_size);
        let description = match template.as_str() {
            "minimal" => "Simple hlx configuration with basic agent and workflow",
            "ai-dev" => {
                "Complete AI development team with specialized agents for full-stack development"
            }
            "support" => {
                "Multi-tier customer support system with escalation and knowledge management"
            }
            "data-pipeline" => {
                "High-throughput data processing pipeline with ML integration"
            }
            "research" => {
                "AI-powered research assistant for literature review and paper writing"
            }
            _ => "HELIX configuration template",
        };
        println!("  Description: {}", description);
    }
    println!("\n📋 Next steps:");
    println!("  1. Review and customize the configuration");
    println!("  2. Set up your API keys and environment variables");
    println!("  3. Compile with: helix compile {}", filename);
    println!("  4. Run with your hlx runtime");
    Ok(())
}
fn install_command(
    local_only: bool,
    force: bool,
    verbose: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    if verbose {
        println!("🔧 Installing Helix compiler globally...");
    }
    let current_exe = std::env::current_exe()
        .map_err(|e| format!("Failed to get current executable path: {}", e))?;
    if verbose {
        println!("  Source: {}", current_exe.display());
    }
    let home_dir = std::env::var("HOME")
        .map_err(|e| format!("Failed to get HOME directory: {}", e))?;
    let baton_dir = PathBuf::from(&home_dir).join(".baton");
    let baton_bin_dir = baton_dir.join("bin");
    let target_binary = baton_bin_dir.join("hlx");
    if verbose {
        println!("  Target: {}", target_binary.display());
    }
    std::fs::create_dir_all(&baton_bin_dir)
        .map_err(|e| {
            format!("Failed to create directory {}: {}", baton_bin_dir.display(), e)
        })?;
    if verbose {
        println!("  ✅ Created directory: {}", baton_bin_dir.display());
    }
    if target_binary.exists() && !force {
        return Err(
            format!(
                "HELIX compiler already installed at {}. Use --force to overwrite.",
                target_binary.display()
            )
                .into(),
        );
    }
    std::fs::copy(&current_exe, &target_binary)
        .map_err(|e| {
            format!("Failed to copy binary to {}: {}", target_binary.display(), e)
        })?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&target_binary)?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&target_binary, perms)?;
    }
    if verbose {
        println!("  ✅ Copied binary to: {}", target_binary.display());
    }
    println!("✅ Helix compiler installed successfully!");
    println!("  Location: {}", target_binary.display());
    if local_only {
        println!("\n📋 Local installation complete!");
        println!("  Add {} to your PATH to use 'hlx' command", baton_bin_dir.display());
        println!("  Or run: export PATH=\"{}:$PATH\"", baton_bin_dir.display());
        return Ok(());
    }
    let global_bin_paths = vec![
        PathBuf::from("/usr/local/bin"), PathBuf::from("/usr/bin"),
        PathBuf::from("/opt/homebrew/bin"),
        PathBuf::from("/home/linuxbrew/.linuxbrew/bin"),
    ];
    let mut symlink_created = false;
    for global_bin in global_bin_paths {
        if global_bin.exists() && global_bin.is_dir() {
            let symlink_path = global_bin.join("hlx");
            if symlink_path.exists() && !force {
                if verbose {
                    println!(
                        "  ⚠️  Symlink already exists: {}", symlink_path.display()
                    );
                }
                continue;
            }
            if symlink_path.exists() {
                std::fs::remove_file(&symlink_path)
                    .map_err(|e| {
                        format!(
                            "Failed to remove existing symlink {}: {}", symlink_path
                            .display(), e
                        )
                    })?;
            }
            #[cfg(unix)]
            let symlink_result = std::os::unix::fs::symlink(
                &target_binary,
                &symlink_path,
            );
            #[cfg(windows)]
            let symlink_result = {
                std::fs::copy(&target_binary, &symlink_path)
                    .map(|_| ())
                    .or_else(|_| std::os::windows::fs::symlink_file(
                        &target_binary,
                        &symlink_path,
                    ))
            };
            #[cfg(not(any(unix, windows)))]
            let symlink_result = std::fs::copy(&target_binary, &symlink_path)
                .map(|_| ());
            match symlink_result {
                Ok(_) => {
                    println!("  ✅ Created global link: {}", symlink_path.display());
                    symlink_created = true;
                    break;
                }
                Err(e) => {
                    if verbose {
                        println!(
                            "  ⚠️  Failed to create link at {}: {}", symlink_path
                            .display(), e
                        );
                    }
                    continue;
                }
            }
        }
    }
    if symlink_created {
        println!("\n🎉 Global installation complete!");
        println!("  You can now use 'hlx' command from anywhere");
        println!("  Try: hlx --help");
    } else {
        println!("\n📋 Installation complete, but global symlink creation failed");
        println!("  This might be due to insufficient permissions");
        println!(
            "  You can still use hlx by adding {} to your PATH", baton_bin_dir.display()
        );
        println!("  Or run: export PATH=\"{}:$PATH\"", baton_bin_dir.display());
        if verbose {
            println!("\n💡 To create global symlink manually:");
            println!("  sudo ln -sf {} /usr/local/bin/hlx", target_binary.display());
        }
    }
    Ok(())
}

use std::fs;
use anyhow::{Result, Context};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProjectManifest {
    pub name: String,
    pub version: String,
    pub description: Option<String>,
    pub author: Option<String>,
    pub license: Option<String>,
    pub repository: Option<String>,
    pub created: Option<String>,
}
pub fn init_project(
    name: Option<String>,
    dir: Option<PathBuf>,
    template: Option<String>,
    force: bool,
    verbose: bool,
) -> Result<()> {
    let project_dir = dir
        .unwrap_or_else(|| {
            std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
        });
    let project_name = name
        .unwrap_or_else(|| {
            project_dir
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("hlx-project")
                .to_string()
        });
    if verbose {
        println!("🚀 Initializing HELIX project:");
        println!("  Name: {}", project_name);
        println!("  Directory: {}", project_dir.display());
        println!("  Template: {}", template.as_deref().unwrap_or("minimal"));
    }
    create_project_structure(&project_dir, &project_name, force)?;
    create_manifest(&project_dir, &project_name, template.as_deref())?;
    create_example_files(&project_dir, template.as_deref())?;
    register_project_globally(&project_name, &project_dir)?;
    println!("✅ HELIX project '{}' initialized successfully!", project_name);
    println!("  Location: {}", project_dir.display());
    if verbose {
        println!("\n📁 Project structure created:");
        println!("  project.hlx - Project manifest");
        println!("  src/ - Source files directory");
        println!("  target/ - Build artifacts");
        println!("  lib/ - Dependencies");
    }
    println!("\n📋 Next steps:");
    println!("  1. cd {}", project_dir.display());
    println!("  2. Edit src/main.hlx to customize your configuration");
    println!("  3. Add dependencies with: helix add <dependency>");
    println!("  4. Build with: helix build");
    println!("  5. Run with: helix run");
    Ok(())
}
fn create_project_structure(
    project_dir: &PathBuf,
    _project_name: &str,
    force: bool,
) -> Result<()> {
    if project_dir.exists() && !force {
        let entries: Vec<_> = fs::read_dir(project_dir)
            .context("Failed to read project directory")?
            .collect::<Result<Vec<_>, _>>()
            .context("Failed to read directory entries")?;
        if !entries.is_empty() {
            return Err(
                anyhow::anyhow!(
                    "Directory '{}' is not empty. Use --force to initialize anyway.",
                    project_dir.display()
                ),
            );
        }
    }
    let src_dir = project_dir.join("src");
    let target_dir = project_dir.join("target");
    let lib_dir = project_dir.join("lib");
    fs::create_dir_all(&src_dir).context("Failed to create src directory")?;
    fs::create_dir_all(&target_dir).context("Failed to create target directory")?;
    fs::create_dir_all(&lib_dir).context("Failed to create lib directory")?;
    Ok(())
}
fn create_manifest(
    project_dir: &PathBuf,
    project_name: &str,
    template: Option<&str>,
) -> Result<()> {
    let manifest_path = project_dir.join("project.hlx");
    let current_date = chrono::Utc::now().format("%Y-%m-%d").to_string();
    let helix_content = format!(
        r#"# {} Project Configuration
# Generated by HELIX Compiler

project "{}" {{
    version = "0.1.0"
    author = "HELIX Developer"
    description = "HELIX project: {}"
    created = "{}"
    license = "MIT"
}}

# Basic agent for the project
agent "main-agent" {{
    model = "gpt-4"
    role = "Main Agent"
    temperature = 0.7
    max_tokens = 50000
    
    capabilities [
        "general-purpose"
        "task-execution"
        "problem-solving"
    ]
}}

# Basic workflow
workflow "main-workflow" {{
    trigger = "manual"
    
    step "execute" {{
        agent = "main-agent"
        task = "Execute main task"
        timeout = 30m
    }}
}}

# Development context
context "development" {{
    environment = "dev"
    debug = true
    max_tokens = 50000
    
    variables {{
        log_level = "debug"
        timeout = 60s
        retry_count = 3
    }}
}}
"#,
        project_name, project_name, project_name, current_date
    );
    fs::write(&manifest_path, helix_content).context("Failed to write project.hlx")?;
    Ok(())
}
fn create_example_files(project_dir: &PathBuf, template: Option<&str>) -> Result<()> {
    let src_dir = project_dir.join("src");
    let main_content = match template {
        Some("ai-dev") => r#"# AI Development Team Configuration
project "ai-dev-team" {
    version = "1.0.0"
    description = "AI-powered development team"
}

agent "architect" {
    model = "gpt-4"
    role = "System Architect"
    temperature = 0.7
}

agent "developer" {
    model = "gpt-4"
    role = "Code Developer"
    temperature = 0.3
}
"#,
        Some("support") => r#"# Customer Support Configuration
project "support-team" {
    version = "1.0.0"
    description = "Customer support system"
}

agent "support-agent" {
    model = "gpt-4"
    role = "Customer Support Specialist"
    temperature = 0.8
}
"#,
        Some("data-pipeline") => r#"# Data Pipeline Configuration
project "data-pipeline" {
    version = "1.0.0"
    description = "Data processing pipeline"
}

agent "data-processor" {
    model = "gpt-4"
    role = "Data Processing Agent"
    temperature = 0.5
}
"#,
        Some("research") => r#"# Research Assistant Configuration
project "research-assistant" {
    version = "1.0.0"
    description = "AI research assistant"
}

agent "researcher" {
    model = "gpt-4"
    role = "Research Assistant"
    temperature = 0.6
}
"#,
        _ => r#"# Minimal HELIX Configuration
project "minimal-project" {
    version = "0.1.0"
    description = "A minimal HELIX project"
}

agent "basic-agent" {
    model = "gpt-4"
    role = "Basic Assistant"
    temperature = 0.7
    max_tokens = 50000
}

workflow "basic-workflow" {
    trigger = "manual"

    step "process" {
        agent = "basic-agent"
        task = "Process the request"
        timeout = 30m
    }
}
"#,
    };
    let main_path = src_dir.join("main.hlx");
    fs::write(&main_path, main_content).context("Failed to write main.hlx")?;
    let gitignore_content = r#"# hlx Build artifacts
target/
*.hlxb

# Dependencies
lib/

# IDE files
.vscode/
.idea/
*.swp
*.swo

# OS files
.DS_Store
Thumbs.db

# Logs
*.log
"#;
    let gitignore_path = project_dir.join(".gitignore");
    fs::write(&gitignore_path, gitignore_content).context("Failed to write .gitignore")?;
    Ok(())
}
fn register_project_globally(project_name: &str, project_dir: &PathBuf) -> Result<()> {
    let home_dir = dirs::home_dir()
        .ok_or_else(|| anyhow::anyhow!("Failed to get home directory"))?;
    let baton_dir = home_dir.join(".baton");
    let projects_dir = baton_dir.join("projects");
    fs::create_dir_all(&projects_dir)
        .context("Failed to create .baton/projects directory")?;
    let project_registry = projects_dir.join(format!("{}.hlx", project_name));
    let current_time = chrono::Utc::now().to_rfc3339();
    let registry_content = format!(
        r#"# Project Registry Entry: {}
# Generated by HELIX Compiler

project "{}" {{
    name = "{}"
    path = "{}"
    created_at = "{}"
    last_accessed = "{}"
    status = "active"
}}
"#,
        project_name, project_name, project_name, project_dir.to_string_lossy(),
        current_time, current_time
    );
    fs::write(&project_registry, registry_content)
        .context("Failed to write project registry entry")?;
    Ok(())
}