symbi 1.13.0

AI-native agent framework for building autonomous, policy-aware agents that can safely collaborate with humans, other agents, and large language models
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
use clap::ArgMatches;
use std::fs;
use std::path::Path;

const TEMPLATES: &[(&str, &str)] = &[
    (
        "webhook-min",
        "Minimal webhook handler with bearer token auth + JSON echo",
    ),
    (
        "webscraper-agent",
        "Web scraper tool + guard policy + sample prompt",
    ),
    ("slm-first", "Router + SLM allow-list + confidence fallback"),
    ("rag-lite", "Qdrant + ingestion scripts + search agent"),
];

pub async fn run(matches: &ArgMatches) {
    if matches.get_flag("list") {
        list_templates();
        return;
    }

    let template = matches.get_one::<String>("template").unwrap();
    let project_name = matches
        .get_one::<String>("name")
        .map(|s| s.as_str())
        .unwrap_or(template);

    if !is_valid_template(template) {
        eprintln!("✗ Unknown template: {}", template);
        eprintln!("\nAvailable templates:");
        list_templates();
        std::process::exit(1);
    }

    println!(
        "🔧 Creating project '{}' from template '{}'...",
        project_name, template
    );

    // Create project directory
    if Path::new(project_name).exists() {
        eprintln!("✗ Directory '{}' already exists", project_name);
        std::process::exit(1);
    }

    fs::create_dir(project_name).expect("Failed to create project directory");

    // Generate template based on type
    match template.as_str() {
        "webhook-min" => create_webhook_min_template(project_name),
        "webscraper-agent" => create_webscraper_agent_template(project_name),
        "slm-first" => create_slm_first_template(project_name),
        "rag-lite" => create_rag_lite_template(project_name),
        _ => unreachable!(),
    }

    println!("\n✅ Project created successfully!");
    println!("\n📝 Next steps:");
    println!("  cd {}", project_name);
    println!("  symbi up");
    println!("  # Follow instructions in README.md");
}

fn list_templates() {
    for (name, description) in TEMPLATES {
        println!("  {} - {}", name, description);
    }
}

fn is_valid_template(template: &str) -> bool {
    TEMPLATES.iter().any(|(name, _)| *name == template)
}

fn create_webhook_min_template(project_name: &str) {
    let base = Path::new(project_name);

    // Create directory structure
    fs::create_dir_all(base.join("agents")).unwrap();
    fs::create_dir_all(base.join("policies")).unwrap();
    fs::create_dir_all(base.join("tests")).unwrap();

    // Create agent
    fs::write(
        base.join("agents/webhook_handler.symbi"),
        r#"agent webhook_handler {
    name: "Webhook Handler"
    description: "Handles incoming webhook requests"

    on_http_post {
        validate: bearer_token
        parse: json

        response {
            status: 200
            body: {
                "received": true,
                "echo": request.body
            }
        }
    }
}
"#,
    )
    .unwrap();

    // Create policy
    fs::write(
        base.join("policies/webhook_policy.dsl"),
        r#"policy webhook_policy {
    name: "Webhook Security Policy"

    allow http_post {
        where: has_bearer_token()
        where: content_type == "application/json"
    }

    deny {
        where: request_size > 1MB
        message: "Request body too large"
    }

    rate_limit {
        requests: 100
        per: "1 minute"
    }
}
"#,
    )
    .unwrap();

    // Create test script
    fs::write(
        base.join("tests/webhook_test.sh"),
        r#"#!/bin/bash
# Test webhook handler

echo "Testing webhook..."
curl -X POST \
  -H "Authorization: Bearer dev" \
  -H "Content-Type: application/json" \
  -d '{"ping":"pong"}' \
  http://localhost:8081/webhook

echo -e "\n\nTest complete!"
"#,
    )
    .unwrap();

    // Make test script executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(base.join("tests/webhook_test.sh"))
            .unwrap()
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(base.join("tests/webhook_test.sh"), perms).unwrap();
    }

    // Create config
    fs::write(
        base.join("symbi.toml"),
        r#"[runtime]
mode = "dev"
hot_reload = true

[http]
enabled = true
port = 8081
dev_token = "dev"

[logging]
level = "info"
format = "pretty"
"#,
    )
    .unwrap();

    // Create README
    fs::write(
        base.join("README.md"),
        format!(
            r#"# {}

Minimal webhook handler with bearer token authentication and JSON echo.

## Getting Started

1. Start the runtime:
   ```bash
   symbi up
   ```

2. Test the webhook:
   ```bash
   ./tests/webhook_test.sh
   ```

   Or manually:
   ```bash
   curl -X POST \
     -H "Authorization: Bearer dev" \
     -H "Content-Type: application/json" \
     -d '{{"test":"data"}}' \
     http://localhost:8081/webhook
   ```

## Project Structure

- `agents/webhook_handler.symbi` - Webhook agent definition
- `policies/webhook_policy.dsl` - Security policy
- `tests/webhook_test.sh` - Integration test
- `symbi.toml` - Runtime configuration

## Next Steps

- Modify the agent to add custom logic
- Adjust the policy for your security requirements
- Change the dev token for production use

## Documentation

See https://docs.symbi.sh for full documentation.
"#,
            project_name
        ),
    )
    .unwrap();
}

fn create_webscraper_agent_template(project_name: &str) {
    let base = Path::new(project_name);

    fs::create_dir_all(base.join("agents")).unwrap();
    fs::create_dir_all(base.join("policies")).unwrap();
    fs::create_dir_all(base.join("tests")).unwrap();

    fs::write(
        base.join("agents/scraper.symbi"),
        r#"agent webscraper {
    name: "Web Scraper"
    description: "Scrapes and extracts content from URLs"

    tools: [http.fetch]

    on_http_post {
        validate: bearer_token
        parse: json

        action {
            url = request.body.url
            content = http.fetch(url)

            prompt: |
                Extract the main content from this webpage and summarize it in 3 bullet points:

                {{ content }}

            response {
                status: 200
                body: {
                    "url": url,
                    "summary": ai_response
                }
            }
        }
    }
}
"#,
    )
    .unwrap();

    fs::write(
        base.join("policies/scraper_policy.dsl"),
        r#"policy scraper_policy {
    name: "Web Scraper Security Policy"

    allow http.fetch {
        where: url.starts_with("https://")
        where: !url.contains("localhost")
        where: !is_private_ip(url)
    }

    rate_limit {
        requests: 20
        per: "1 minute"
    }
}
"#,
    )
    .unwrap();

    fs::write(
        base.join("README.md"),
        format!(
            r#"# {}

Web scraper agent with URL validation and content extraction.

## Features

- HTTP fetch tool with rate limiting
- URL validation policy (HTTPS only, no private IPs)
- AI-powered content summarization

## Getting Started

```bash
symbi up

curl -X POST \
  -H "Authorization: Bearer dev" \
  -H "Content-Type: application/json" \
  -d '{{"url":"https://example.com"}}' \
  http://localhost:8081/webhook
```

## Documentation

See https://docs.symbi.sh for full documentation.
"#,
            project_name
        ),
    )
    .unwrap();

    fs::write(
        base.join("symbi.toml"),
        r#"[runtime]
mode = "dev"
"#,
    )
    .unwrap();
}

fn create_slm_first_template(project_name: &str) {
    let base = Path::new(project_name);

    fs::create_dir_all(base.join("agents")).unwrap();
    fs::create_dir_all(base.join("routing")).unwrap();

    fs::write(
        base.join("agents/code_helper.symbi"),
        r#"agent code_helper {
    name: "Code Helper"
    description: "SLM-first coding assistant with LLM fallback"

    router {
        slm: "llama-3.2-3b"
        llm: "gpt-4"
        strategy: "confidence"
    }

    on_prompt {
        if confidence < 0.7 {
            use: llm
        } else {
            use: slm
        }

        response {
            body: {
                "model_used": model_name,
                "confidence": confidence_score,
                "response": ai_response
            }
        }
    }
}
"#,
    )
    .unwrap();

    fs::write(
        base.join("routing/config.toml"),
        r#"[router]
strategy = "confidence"

[slm]
model = "llama-3.2-3b"
confidence_threshold = 0.7
tasks = ["classify", "summarize", "extract", "simple_code"]

[llm]
model = "gpt-4o-mini"
fallback_on_low_confidence = true
tasks = ["complex_reasoning", "refactoring"]
"#,
    )
    .unwrap();

    fs::write(
        base.join("README.md"),
        format!(
            r#"# {}

SLM-first coding assistant with intelligent routing and LLM fallback.

## Features

- Uses Llama 3.2 3B for simple tasks (fast, cost-effective)
- Falls back to GPT-4 for complex reasoning
- Confidence-based routing
- Cost tracking and metrics

## Getting Started

```bash
symbi up

curl -X POST \
  -H "Authorization: Bearer dev" \
  -H "Content-Type: application/json" \
  -d '{{"prompt":"Write a function to check if a number is prime"}}' \
  http://localhost:8081/webhook
```

## Documentation

See https://docs.symbi.sh for full documentation.
"#,
            project_name
        ),
    )
    .unwrap();

    fs::write(
        base.join("symbi.toml"),
        r#"[runtime]
mode = "dev"
"#,
    )
    .unwrap();
}

fn create_rag_lite_template(project_name: &str) {
    let base = Path::new(project_name);

    fs::create_dir_all(base.join("agents")).unwrap();
    fs::create_dir_all(base.join("scripts")).unwrap();
    fs::create_dir_all(base.join("docs")).unwrap();

    fs::write(
        base.join("agents/doc_search.symbi"),
        r#"agent doc_search {
    name: "Document Search"
    description: "RAG agent for searching documentation"

    vector_db: "qdrant"
    collection: "docs"

    on_query {
        embed: query
        search: {
            collection: "docs",
            top_k: 5,
            score_threshold: 0.7
        }

        prompt: |
            Answer the question using these documents:

            {{ search_results }}

            Question: {{ query }}

        response {
            body: {
                "answer": ai_response,
                "sources": search_results.sources
            }
        }
    }
}
"#,
    )
    .unwrap();

    fs::write(
        base.join("scripts/ingest_docs.sh"),
        r#"#!/bin/bash
# Ingest documentation into Qdrant

echo "Ingesting documents..."

# Check if Qdrant is running
if ! curl -s http://localhost:6333/health >/dev/null 2>&1; then
    echo "❌ Qdrant is not running. Please start it first:"
    echo "   docker run -p 6333:6333 qdrant/qdrant"
    exit 1
fi

echo "✅ Qdrant is running"

# Create collection if it doesn't exist
curl -X PUT 'http://localhost:6333/collections/docs' \
    -H 'Content-Type: application/json' \
    -d '{
        "vectors": {
            "size": 384,
            "distance": "Cosine"
        }
    }' 2>/dev/null

echo "📚 Processing documents..."

# Ingest each markdown file
for file in docs/*.md; do
    if [ -f "$file" ]; then
        echo "Processing $file..."
        
        # Extract filename without path and extension
        filename=$(basename "$file" .md)
        
        # Read file content and prepare for embedding
        content=$(cat "$file")
        
        # Simple chunking: split on double newlines
        echo "$content" | awk 'BEGIN{RS="\n\n"; chunk=1} {
            if(length($0) > 10) {
                gsub(/\"/,"\\\""); # Escape quotes
                gsub(/\n/," ");    # Replace newlines with spaces
                
                # Create vector point for Qdrant
                printf "{\"id\": %d, \"vector\": ", chunk
                
                # Generate simple hash-based vector (384 dimensions)
                for(i=1; i<=384; i++) {
                    printf "%.6f", (sin(i + length($0)) + 1) / 2
                    if(i < 384) printf ","
                }
                
                printf "], \"payload\": {\"text\": \"%s\", \"source\": \"%s\", \"chunk\": %d}}\n", $0, "'$filename'", chunk
                chunk++
            }
        }' > "/tmp/${filename}_vectors.json"
        
        # Upload to Qdrant
        if [ -s "/tmp/${filename}_vectors.json" ]; then
            while IFS= read -r line; do
                curl -X PUT "http://localhost:6333/collections/docs/points" \
                    -H 'Content-Type: application/json' \
                    -d "[$line]" >/dev/null 2>&1
            done < "/tmp/${filename}_vectors.json"
            
            rm "/tmp/${filename}_vectors.json"
        fi
        
        echo "   ✅ Processed $file"
    fi
done

echo "🎉 Ingestion complete!"
echo "📊 Collection stats:"
curl -s 'http://localhost:6333/collections/docs' | jq '.result.vectors_count // "unknown"' | xargs echo "   Documents indexed:"
"#,
    ).unwrap();

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(base.join("scripts/ingest_docs.sh"))
            .unwrap()
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(base.join("scripts/ingest_docs.sh"), perms).unwrap();
    }

    fs::write(
        base.join("docs/sample.md"),
        r#"# Sample Documentation

This is a sample document for testing RAG functionality.

## Features

- Vector similarity search
- Hybrid search capabilities
- Automatic relevance scoring

## Usage

Query the documentation by sending POST requests to the webhook endpoint.
"#,
    )
    .unwrap();

    fs::write(
        base.join("README.md"),
        format!(
            r#"# {}

RAG (Retrieval-Augmented Generation) agent for searching documentation.

## Features

- Qdrant vector database integration
- Document ingestion scripts
- Hybrid search with relevance scoring
- Sample documents included

## Getting Started

1. Start Qdrant:
   ```bash
   docker run -p 6333:6333 qdrant/qdrant
   ```

2. Ingest documents:
   ```bash
   ./scripts/ingest_docs.sh
   ```

3. Start Symbiont:
   ```bash
   symbi up
   ```

4. Query the documentation:
   ```bash
   curl -X POST \
     -H "Authorization: Bearer dev" \
     -H "Content-Type: application/json" \
     -d '{{"query":"What are the features?"}}' \
     http://localhost:8081/webhook
   ```

## Documentation

See https://docs.symbi.sh for full documentation.
"#,
            project_name
        ),
    )
    .unwrap();

    fs::write(
        base.join("symbi.toml"),
        r#"[runtime]
mode = "dev"

[vector]
provider = "qdrant"
host = "localhost"
port = 6333
collection_name = "docs"
"#,
    )
    .unwrap();
}