aethershell 0.3.1

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
use std::collections::BTreeMap;
use std::fmt;

use crate::ast::{BinOp, Expr, Stmt, UnOp};
use crate::types::Type;

pub type TypeEnv = BTreeMap<String, Type>;

/* =========================
Errors
========================= */

#[derive(Debug)]
pub enum TypeError {
    UnboundIdent(String),
    Mismatch { expected: Type, found: Type },
    BadBinary { op: BinOp, left: Type, right: Type },
    BadUnary { op: UnOp, inner: Type },
    NotCallable(Type),
    Other(String),
}

impl std::error::Error for TypeError {}

impl fmt::Display for TypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TypeError::UnboundIdent(name) => write!(f, "unbound identifier `{}`", name),
            TypeError::Mismatch { expected, found } => write!(
                f,
                "type mismatch: expected {:?}, found {:?}",
                expected, found
            ),
            TypeError::BadBinary { op, left, right } => write!(
                f,
                "invalid operand types for operator {:?}: {:?} and {:?}",
                op, left, right
            ),
            TypeError::BadUnary { op, inner } => write!(
                f,
                "invalid operand type for unary operator {:?}: {:?}",
                op, inner
            ),
            TypeError::NotCallable(t) => write!(f, "not a function: {:?}", t),
            TypeError::Other(msg) => write!(f, "{}", msg),
        }
    }
}

/* =========================
Public entry points
========================= */

pub fn typecheck(stmts: &[Stmt]) -> Result<TypeEnv, TypeError> {
    let mut env = TypeEnv::new();
    for s in stmts {
        type_of_stmt(s, &mut env)?;
    }
    Ok(env)
}

pub fn type_of_stmt(stmt: &Stmt, env: &mut TypeEnv) -> Result<(), TypeError> {
    match stmt {
        Stmt::Let { name, value, .. } => {
            let t = type_of_expr(value, env)?;
            env.insert(name.clone(), t);
            Ok(())
        }
        Stmt::Expr(e) => {
            let _ = type_of_expr(e, env)?;
            Ok(())
        }
        Stmt::Import { .. } => {
            // Import statements don't contribute to type checking in this pass
            // The imported module's types would be resolved at runtime
            Ok(())
        }
        Stmt::Export { .. } => {
            // Export statements don't add new types, they just mark existing items for export
            Ok(())
        }
        Stmt::Cfg { body, .. } => {
            // Type check the body statement - the condition is evaluated at runtime
            type_of_stmt(body, env)
        }
    }
}

pub fn type_of_expr(expr: &Expr, env: &mut TypeEnv) -> Result<Type, TypeError> {
    match expr {
        // --- literals ---
        Expr::LitInt(_) => Ok(Type::Int),
        Expr::LitFloat(_) => Ok(Type::Float),
        Expr::LitStr(s) => {
            if looks_like_uri(s) {
                Ok(Type::Uri)
            } else {
                Ok(Type::String)
            }
        }
        Expr::LitBool(_) => Ok(Type::Bool),
        Expr::Null => Ok(Type::Null),

        // --- variables ---
        Expr::Ident(name) => env
            .get(name)
            .cloned()
            .ok_or_else(|| TypeError::UnboundIdent(name.clone())),

        // --- collections ---
        Expr::Array(elems) => {
            if elems.is_empty() {
                Ok(Type::Array(Box::new(Type::Any)))
            } else {
                let mut acc = type_of_expr(&elems[0], env)?;
                for e in &elems[1..] {
                    let t = type_of_expr(e, env)?;
                    acc = promote_array_elem(acc, t);
                }
                Ok(Type::Array(Box::new(acc)))
            }
        }
        Expr::Record(fields) => {
            let mut map = BTreeMap::new();
            for (k, v) in fields {
                let t = type_of_expr(v, env)?;
                map.insert(k.clone(), t);
            }
            Ok(Type::Record(map))
        }

        // --- lambda ---
        Expr::Lambda { params, body } => {
            // Parameters default to `Any` in the checker.
            let mut local = env.clone();
            let param_types = vec![Type::Any; params.len()];
            for p in params {
                local.insert(p.clone(), Type::Any);
            }
            let ret = type_of_expr(body, &mut local)?;
            Ok(Type::Lambda(param_types, Box::new(ret)))
        }

        // --- call ---
        Expr::Call {
            callee,
            args,
            named,
        } => {
            // If `callee` is an identifier for a known builtin, handle it first.
            if let Expr::Ident(name) = &**callee {
                if is_builtin(name) {
                    let mut arg_tys = Vec::with_capacity(args.len());
                    for a in args {
                        arg_tys.push(type_of_expr(a, env)?);
                    }
                    let named_map = typed_named_args(named, env)?;
                    return type_builtin_call(name, &arg_tys, &named_map);
                }
                // otherwise fall through to treat it as a variable holding a lambda
            }

            // Otherwise, infer callee type and try function application.
            let callee_ty = type_of_expr(callee, env)?;
            let mut arg_tys = Vec::with_capacity(args.len());
            for a in args {
                arg_tys.push(type_of_expr(a, env)?);
            }
            let _named_map = typed_named_args(named, env)?;

            match callee_ty {
                Type::Lambda(params, ret) => {
                    // Be forgiving on arity: unify what we can, still return `ret`.
                    let upto = params.len().min(arg_tys.len());
                    for i in 0..upto {
                        let _ = unify(params[i].clone(), arg_tys[i].clone());
                    }
                    Ok(*ret)
                }
                Type::Any => Ok(Type::Any),
                other => Err(TypeError::NotCallable(other)),
            }
        }

        // --- pipeline ---
        Expr::Pipe { left, right } => {
            let left_t = type_of_expr(left, env)?;
            if let Expr::Call {
                callee,
                args,
                named,
            } = &**right
            {
                // compute args with LHS as the first (piped) arg
                let mut arg_tys = Vec::new();
                arg_tys.push(left_t.clone());
                for a in args {
                    arg_tys.push(type_of_expr(a, env)?);
                }
                let named_map = typed_named_args(named, env)?;
                if let Expr::Ident(name) = &**callee {
                    if is_builtin(name) {
                        // Builtins in pipelines: precise typing
                        return type_builtin_call(name, &arg_tys, &named_map);
                    }
                }
                // If it's a lambda application, prefer the lambda's return.
                let callee_ty = type_of_expr(callee, env)?;
                match callee_ty {
                    Type::Lambda(_params, ret) => Ok(*ret),
                    Type::Any => Ok(Type::Any),
                    _ => Ok(Type::Any),
                }
            } else {
                Ok(Type::Any)
            }
        }

        // --- unary ---
        Expr::Unary { op, expr } => {
            let t = type_of_expr(expr, env)?;
            match op {
                UnOp::Neg => match t {
                    Type::Int | Type::Float => Ok(t),
                    Type::Any => Ok(Type::Any),
                    other => Err(TypeError::BadUnary {
                        op: *op,
                        inner: other,
                    }),
                },
                UnOp::Not => match t {
                    Type::Bool | Type::Any => Ok(Type::Bool),
                    other => Err(TypeError::BadUnary {
                        op: *op,
                        inner: other,
                    }),
                },
            }
        }

        // --- binary ---
        Expr::Binary { left, op, right } => {
            let lt = type_of_expr(left, env)?;
            let rt = type_of_expr(right, env)?;
            type_binary(op, lt, rt)
        }

        // --- member access: record.field ---
        Expr::MemberAccess { object, field: _ } => {
            let obj_type = type_of_expr(object, env)?;
            // For now, if the object is a Record type, we return Any
            // since we don't track field types in our simple type system
            match obj_type {
                Type::Record(_) => Ok(Type::Any),
                Type::Any => Ok(Type::Any), // Allow access on Any type
                other => Err(TypeError::Other(format!(
                    "cannot access field on non-record type: {:?}",
                    other
                ))),
            }
        }

        // --- pattern matching ---
        Expr::Match { scrutinee, arms } => {
            // Type check the scrutinee
            let _scrutinee_type = type_of_expr(scrutinee, env)?;

            // For simplicity, check all arms and return the type of the first arm's body
            // In a more sophisticated system, we'd verify all arms return the same type
            if arms.is_empty() {
                return Err(TypeError::Other("match expression has no arms".to_string()));
            }

            // Type check each arm's body (we don't deeply validate patterns yet)
            let mut arm_type = None;
            for arm in arms {
                // Create a temporary environment for pattern bindings
                // (we don't track exact pattern types, so we just check the body)
                let body_type = type_of_expr(&arm.body, env)?;

                if let Some(ref expected) = arm_type {
                    // In a real system, we'd verify all arms have compatible types
                    // For now, just use the first arm's type
                    if body_type != *expected && body_type != Type::Any && *expected != Type::Any {
                        // Allow Any to match anything
                    }
                } else {
                    arm_type = Some(body_type);
                }
            }

            Ok(arm_type.unwrap_or(Type::Any))
        }

        // --- async lambda ---
        Expr::AsyncLambda { params, body } => {
            // Parameters default to `Any` in the checker.
            let mut local = env.clone();
            let param_types = vec![Type::Any; params.len()];
            for p in params {
                local.insert(p.clone(), Type::Any);
            }
            let _ret = type_of_expr(body, &mut local)?;
            // AsyncLambda returns a Future type (which we model as Any for now)
            Ok(Type::Lambda(param_types, Box::new(Type::Any)))
        }

        // --- await ---
        Expr::Await(inner) => {
            // Await unwraps a Future, but since we model futures as Any,
            // the result is also Any
            let _inner_type = type_of_expr(inner, env)?;
            Ok(Type::Any)
        }

        // --- try/catch ---
        Expr::TryCatch {
            try_expr,
            catch_var: _,
            catch_expr,
        } => {
            // Both branches should be typed, result is union (Any for simplicity)
            let _try_type = type_of_expr(try_expr, env)?;
            let _catch_type = type_of_expr(catch_expr, env)?;
            Ok(Type::Any)
        }

        // --- throw ---
        Expr::Throw(inner) => {
            // Throw returns an Error type, which we model as Any
            let _inner_type = type_of_expr(inner, env)?;
            Ok(Type::Any)
        }
    }
}

/* =========================
Helpers
========================= */

fn is_builtin(name: &str) -> bool {
    matches!(
        name,
        "map"
            | "reduce"
            | "where"
            | "select"
            | "group_by"
            | "agg"
            | "http_get"
            | "ls"
            | "list"
            | "pwd"
            | "cat"
            | "head"
            | "tail"
            | "find"
            | "sort"
            | "uniq"
            | "wc"
            | "grep"
            | "help"
            | "call"
            | "clear"
            | "echo"
            | "print"
            | "take"
            | "agent"
            | "swarm"
            // PowerShell-style cmdlets
            | "Get-Files" | "get-files"
            | "Get-Content" | "get-content"
            | "Select-Object" | "select-object"
            | "Where-Object" | "where-object"
            | "ForEach-Object" | "foreach-object" | "foreach"
            | "Sort-Object" | "sort-object"
            | "Group-Object" | "group-object" | "group"
            | "Measure-Object" | "measure-object" | "measure"
            // Nushell-style data commands
            | "from-json" | "from_json"
            | "to-json" | "to_json"
            | "from-csv" | "from_csv"
            | "to-csv" | "to_csv"
            | "from-yaml" | "from_yaml"
            | "to-yaml" | "to_yaml"
            | "columns"
            | "describe"
            // AI-enhanced commands
            | "ai-suggest" | "suggest"
            | "ai-explain" | "explain"
            | "ai-complete" | "complete"
            | "ai-fix" | "fix"
    )
}

fn typed_named_args(
    named: &[(String, Expr)],
    env: &mut TypeEnv,
) -> Result<BTreeMap<String, Type>, TypeError> {
    let mut m = BTreeMap::new();
    for (k, e) in named {
        m.insert(k.clone(), type_of_expr(e, env)?);
    }
    Ok(m)
}

fn promote_array_elem(a: Type, b: Type) -> Type {
    match (a, b) {
        (Type::Float, Type::Int) | (Type::Int, Type::Float) => Type::Float,
        (Type::Array(x), Type::Array(y)) => Type::Array(Box::new(unify(*x, *y))),
        (Type::Any, t) | (t, Type::Any) => t,
        (x, y) if x == y => x,
        (x, y) => unify(x, y),
    }
}

fn unify(a: Type, b: Type) -> Type {
    use Type::*;
    match (a, b) {
        (x, y) if x == y => x,
        (Any, t) | (t, Any) => t,
        (Int, Float) | (Float, Int) => Float,
        (Array(x), Array(y)) => Array(Box::new(unify(*x, *y))),
        (Record(mut rx), Record(ry)) => {
            let mut out = BTreeMap::new();
            for (k, vx) in rx.iter_mut() {
                if let Some(vy) = ry.get(k) {
                    out.insert(k.clone(), unify(vx.clone(), vy.clone()));
                } else {
                    out.insert(k.clone(), vx.clone());
                }
            }
            for (k, vy) in ry {
                out.entry(k).or_insert(vy);
            }
            Record(out)
        }
        (Table(mut sx), Table(sy)) => {
            let mut out = BTreeMap::new();
            for (k, vx) in sx.iter_mut() {
                if let Some(vy) = sy.get(k) {
                    out.insert(k.clone(), unify(vx.clone(), vy.clone()));
                } else {
                    out.insert(k.clone(), vx.clone());
                }
            }
            for (k, vy) in sy {
                out.entry(k).or_insert(vy);
            }
            Table(out)
        }
        _ => Any,
    }
}

fn type_binary(op: &BinOp, lt: Type, rt: Type) -> Result<Type, TypeError> {
    use BinOp::*;
    use Type::*;
    Ok(match op {
        Add | Sub | Mul | Div | Rem | BinOp::Pow => match (lt.clone(), rt.clone()) {
            (Int, Int) => Int,
            (Float, Int) | (Int, Float) | (Float, Float) => Float,
            (Any, t) | (t, Any) => t,
            _ => {
                return Err(TypeError::BadBinary {
                    op: *op,
                    left: lt,
                    right: rt,
                });
            }
        },
        Eq | Ne => Bool,
        Lt | Lte | Gt | Gte => match (lt.clone(), rt.clone()) {
            (Int, Int) | (Float, Float) | (Int, Float) | (Float, Int) | (String, String) => Bool,
            (Any, _) | (_, Any) => Bool,
            _ => {
                return Err(TypeError::BadBinary {
                    op: *op,
                    left: lt,
                    right: rt,
                });
            }
        },
        And | Or => match (lt.clone(), rt.clone()) {
            (Bool, Bool) | (Any, _) | (_, Any) => Bool,
            _ => {
                return Err(TypeError::BadBinary {
                    op: *op,
                    left: lt,
                    right: rt,
                });
            }
        },
    })
}

/* =========================
Builtin typing
========================= */

fn type_builtin_call(
    name: &str,
    args: &[Type],
    _named: &BTreeMap<String, Type>,
) -> Result<Type, TypeError> {
    match name {
        "map" => {
            // map(array<T>, fn(T)->U) -> array<U>
            if args.len() >= 2 {
                if let Type::Array(_elem) = &args[0] {
                    if let Type::Lambda(_params, ret) = &args[1] {
                        return Ok(Type::Array(ret.clone()));
                    }
                }
            }
            Ok(Type::Any)
        }
        "reduce" => {
            // reduce(array<T>, fn(Acc,T)->Acc, init:Acc) -> Acc
            if args.len() >= 3 {
                let acc_t = args[2].clone();
                return Ok(acc_t);
            }
            Ok(Type::Any)
        }
        "where" => {
            // where(array<T>, fn(T)->Bool) -> array<T>
            if let Some(Type::Array(t)) = args.get(0) {
                return Ok(Type::Array(t.clone()));
            }
            Ok(Type::Any)
        }
        "select" => {
            // select(table{S}, ...) -> table{S} (shape-preserving)
            if let Some(Type::Table(schema)) = args.get(0) {
                return Ok(Type::Table(schema.clone()));
            }
            Ok(Type::Any)
        }
        "group_by" => Ok(Type::Any),
        "agg" => Ok(Type::Any),
        "http_get" => {
            // http_get(url) -> { url:String, status:Int, headers:Record<String,String>, body:Any }
            let mut rec = BTreeMap::new();
            rec.insert("url".into(), Type::String);
            rec.insert("status".into(), Type::Int);
            let mut hdrs = BTreeMap::new();
            hdrs.insert("*".into(), Type::String); // schematic wildcard
            rec.insert("headers".into(), Type::Record(hdrs));
            rec.insert("body".into(), Type::Any);
            Ok(Type::Record(rec))
        }
        _ => Ok(Type::Any),
    }
}

/* =========================
URI detection
========================= */

fn looks_like_uri(s: &str) -> bool {
    if let Some(colon) = s.find(':') {
        if colon == 0 {
            return false;
        }
        let scheme = &s[..colon];
        let mut chars = scheme.chars();
        match chars.next() {
            Some(c) if c.is_ascii_alphabetic() => {}
            _ => return false,
        }
        for ch in chars {
            if !(ch.is_ascii_alphabetic()
                || ch.is_ascii_digit()
                || ch == '+'
                || ch == '-'
                || ch == '.')
            {
                return false;
            }
        }
        true
    } else {
        false
    }
}

/* =========================
Anyhow-friendly helpers
========================= */

/// Parse + typecheck a full source string; returns the type environment.
pub fn typecheck_program(src: &str) -> anyhow::Result<TypeEnv> {
    let stmts = crate::parser::parse_program(src)?;
    typecheck(&stmts).map_err(|e| anyhow::anyhow!(e.to_string()))
}

/// Parse a source string and return the **type of the last expression**.
pub fn infer_last_type(src: &str) -> anyhow::Result<Type> {
    let stmts = crate::parser::parse_program(src)?;
    let mut env = TypeEnv::new();
    let mut last_ty = Type::Null;
    for s in &stmts {
        match s {
            Stmt::Let { name, value, .. } => {
                let t =
                    type_of_expr(value, &mut env).map_err(|e| anyhow::anyhow!(e.to_string()))?;
                env.insert(name.clone(), t.clone());
                last_ty = t;
            }
            Stmt::Expr(e) => {
                last_ty = type_of_expr(e, &mut env).map_err(|e| anyhow::anyhow!(e.to_string()))?;
            }
            Stmt::Import { .. } | Stmt::Export { .. } => {
                // Import/Export statements don't affect the type of the last expression
                // Keep last_ty unchanged
            }
            Stmt::Cfg { body, .. } => {
                // Type check the cfg body recursively
                match body.as_ref() {
                    Stmt::Let { name, value, .. } => {
                        let t = type_of_expr(value, &mut env)
                            .map_err(|e| anyhow::anyhow!(e.to_string()))?;
                        env.insert(name.clone(), t.clone());
                        last_ty = t;
                    }
                    Stmt::Expr(e) => {
                        last_ty = type_of_expr(e, &mut env)
                            .map_err(|e| anyhow::anyhow!(e.to_string()))?;
                    }
                    _ => {
                        // Recursively handle other statement types
                    }
                }
            }
        }
    }
    Ok(last_ty)
}

/// If you already have an AST and want the env with anyhow errors.
pub fn typecheck_stmts_anyhow(stmts: &[crate::ast::Stmt]) -> anyhow::Result<TypeEnv> {
    typecheck(stmts).map_err(|e| anyhow::anyhow!(e.to_string()))
}