iron-shell 14.0.3

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
use anyhow::{Context, Result};
use std::env;
use std::fs;
use std::io::{self, Read};

use clap::{Parser, Subcommand};
use iron_shell::{env::Env, modules, transpile};

/// Create an environment with all builtin modules pre-registered
fn create_env_with_modules() -> Env {
    modules::env_with_modules()
}

/// Counts live heap bytes so the evaluator can enforce the memory budget.
#[global_allocator]
static ALLOCATOR: iron_shell::memory::CountingAlloc = iron_shell::memory::CountingAlloc;

#[derive(Parser)]
#[command(name = "ish")]
#[command(about = "IronShell Shell - A typed functional shell with multi-modal AI")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(args_conflicts_with_subcommands = true)]
#[command(
    after_help = "Builtins: help(\"name\") or ontology_describe(\"name\") gives one builtin's signature, effect and examples; ontology_manifest() lists the categories."
)]
struct Cli {
    #[command(subcommand)]
    subcommand: Option<Commands>,

    /// Bash compatibility mode
    #[arg(long, short = 'b')]
    bash: bool,

    /// Zsh compatibility mode
    #[arg(long, short = 'z')]
    zsh: bool,

    /// PowerShell compatibility mode
    #[arg(long, short = 'p')]
    pwsh: bool,

    /// Agentic syntax mode (token-minimized for AI agents)
    #[arg(long, short = 'a')]
    agentic: bool,

    /// Execute a command string
    #[arg(long, short = 'c', allow_hyphen_values = true)]
    command: Option<String>,

    /// Token budget for output: results over N estimated tokens are paged/truncated
    #[arg(long, value_name = "N")]
    budget: Option<usize>,

    /// Stop the evaluation after SECONDS (E_BUDGET_EXCEEDED); env IRONSHELL_TIMEOUT.
    /// No limit by default.
    #[arg(long, value_name = "SECONDS")]
    timeout: Option<u64>,

    /// Memory budget in MB (E_BUDGET_EXCEEDED past it, 0 for none); env
    /// IRONSHELL_MEMORY_LIMIT_MB. Default: the smaller of 2048 and half of memory
    #[arg(long, value_name = "MB")]
    memory_limit: Option<usize>,

    /// Agent mode: default-deny dangerous effect classes (gate behind approval)
    #[arg(long)]
    agent: bool,

    /// Workspace root that confines destructive/write operations (the jail)
    #[arg(long, value_name = "DIR")]
    workspace: Option<String>,

    /// Safety policy: "strict" (default) or "permissive" (allow-all in agent mode)
    #[arg(long, value_name = "POLICY", value_parser = ["strict", "permissive"], ignore_case = true)]
    policy: Option<String>,

    /// Report what a program would do -- every call, its effect class and the
    /// agent-mode decision -- without running it. Use with -c or a file.
    #[arg(long)]
    explain: bool,

    /// Deterministic output: render results as canonical, byte-stable JSON
    /// (sorted keys, stable floats) for snapshot tests, caching, and diffs
    #[arg(long)]
    deterministic: bool,

    /// Script file to execute, then the arguments the script receives (read
    /// with `args()`). Everything after the file is passed on, flags included.
    #[arg(value_name = "FILE", trailing_var_arg = true)]
    file_and_args: Vec<String>,
}

#[derive(Subcommand)]
enum Commands {
    /// Start terminal GUI (TUI) mode
    Tui,

    /// AI model management (list, download, serve API, etc.)
    #[command(alias = "model")]
    Ai {
        #[command(subcommand)]
        command: AiCommands,
    },

    /// Start MCP (Model Context Protocol) server mode
    #[command(visible_alias = "mcp-server")]
    Mcp {
        #[command(subcommand)]
        command: McpCommands,
    },

    /// Agent API mode - AI-callable interface for ChatGPT, Claude, Gemini
    #[command(visible_alias = "agent-api")]
    Agent {
        #[command(subcommand)]
        command: AgentApiCommands,
    },

    /// AI assistant - natural language to IronShell transpilation
    #[command(visible_alias = "ai-assist")]
    Assist {
        /// Natural language query (reads from stdin if not provided)
        query: Option<String>,

        /// Execute the generated code immediately (default: show only)
        #[arg(long, short = 'x')]
        execute: bool,

        /// Interactive mode - continuous assistant session
        #[arg(long, short = 'i')]
        interactive: bool,

        /// Context-aware mode - include system info in prompts
        #[arg(long, short = 'c')]
        context: bool,

        /// Suggest useful commands based on current directory
        #[arg(long, short = 's')]
        suggest: bool,
    },
}
#[derive(Subcommand)]
enum AiCommands {
    /// Start the AI model API server
    Serve {
        /// Server host
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
        /// Server port
        #[arg(long, default_value = "8080")]
        port: u16,
        /// Enable CORS
        #[arg(long)]
        cors: bool,
    },
    /// List available AI models
    #[command(alias = "ls")]
    List {
        /// Filter by provider
        #[arg(long)]
        provider: Option<String>,
        /// Show only local models
        #[arg(long)]
        local: bool,
    },
    /// Download a model
    Download {
        /// Model identifier or URL
        model: String,
    },
    /// Show AI model configuration
    Config,
    /// Manage API keys securely
    #[command(alias = "key")]
    Keys {
        #[command(subcommand)]
        action: KeysAction,
    },
}

#[derive(Subcommand)]
enum KeysAction {
    /// Store an API key securely
    Store {
        /// Provider name (openai, anthropic, google, etc.)
        provider: String,
        /// API key (reads from stdin if not provided)
        #[arg(long)]
        key: Option<String>,
    },
    /// Get an API key
    Get {
        /// Provider name
        provider: String,
    },
    /// Delete an API key
    Delete {
        /// Provider name
        provider: String,
    },
    /// List stored API key providers
    List,
}

#[derive(Subcommand)]
enum McpCommands {
    /// Start the MCP server
    Serve {
        /// Server host
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
        /// Server port
        #[arg(long, default_value = "3001")]
        port: u16,
        /// Enable CORS for browser access
        #[arg(long)]
        cors: bool,
        /// Safety level (safe, caution, dangerous, critical)
        #[arg(long, default_value = "caution")]
        safety: String,
        /// Allow admin tools
        #[arg(long)]
        admin: bool,
    },
    /// List available MCP tools
    Tools {
        /// Filter by category
        #[arg(long)]
        category: Option<String>,
    },
    /// Serve over stdio as a strict JSON-RPC 2.0 MCP server (the canonical MCP
    /// transport). Every builtin is callable, through three advertised tools
    /// rather than as several hundred schemas: `ontology_manifest` indexes the
    /// categories, `ontology_describe` expands one, and `ironshell` invokes a
    /// builtin by name. Every call is routed through the safety model, in
    /// agent mode unless `IRONSHELL_MODE` says otherwise.
    Stdio,
}

#[derive(Subcommand)]
enum AgentApiCommands {
    /// Start the Agent API HTTP server (for AI integrations)
    Serve {
        /// Server host
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
        /// Server port
        #[arg(long, default_value = "3002")]
        port: u16,
        /// Enable CORS for browser/API access
        #[arg(long)]
        cors: bool,
        /// Bearer token required by every endpoint except /health. Omit to have
        /// one generated and printed at startup. Prefer IRONSHELL_API_TOKEN over
        /// this flag, so the token stays out of the process list.
        #[arg(long)]
        token: Option<String>,
        /// Seconds a single request/response route may run before it is
        /// cancelled with 408. Does not apply to the SSE stream or WebSocket
        /// routes, which are long-lived by design. 0 disables the deadline,
        /// which lets one caller hold a worker indefinitely.
        #[arg(long, default_value = "300")]
        request_timeout: u64,
    },
    /// Execute a JSON request (read from stdin or argument)
    #[command(alias = "exec")]
    Execute {
        /// JSON request (reads from stdin if not provided)
        request: Option<String>,
    },
    /// Get the language schema for AI agents. The full schema is large: pass
    /// --module <name> for one module's builtins (`ish agent schema --module file`).
    Schema {
        // The same list the error for an unknown format prints.
        #[arg(
            long,
            short = 'f',
            default_value = "compact",
            help = format!("Output format: {}", iron_shell::agent_api::SCHEMA_FORMATS_HINT)
        )]
        format: String,
        /// Output to file
        #[arg(long, short = 'o')]
        output: Option<String>,
        /// Only the builtins in this module (for example `file`)
        #[arg(long)]
        module: Option<String>,
        /// Only the builtins whose name or description contains this text
        #[arg(long, short = 'q')]
        q: Option<String>,
    },
    /// List all available builtins
    #[command(alias = "ls")]
    Builtins {
        /// Filter by category
        #[arg(long, short = 'c')]
        category: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Interactive agent mode (process requests from stdin continuously)
    Interactive,
}

fn main() -> Result<()> {
    iron_shell::tls::install_provider();
    // Everything runs on a thread with a large stack (finding 13). The
    // interpreter recurses through `eval_expr` for nested calls, and on the
    // default main-thread stack — 1 MB on Windows — that overflowed and aborted
    // the process at roughly 35 frames. The stack is reserved address space,
    // not committed memory, so this costs nothing until it is used, and it is
    // what makes `safety::MAX_CALL_DEPTH` able to fire first.
    //
    // Parsing argv here rather than inside the closure keeps `--help` and
    // argument errors on the real main thread, so their exit codes and output
    // are unchanged.
    let cli = parse_cli();
    iron_shell::safety::with_eval_stack(move || run(cli))
}

impl Cli {
    /// The global flags that came before the subcommand, applied to it.
    fn with_leading_globals(mut self, leading: Cli) -> Cli {
        self.bash |= leading.bash;
        self.zsh |= leading.zsh;
        self.pwsh |= leading.pwsh;
        self.agentic |= leading.agentic;
        self.agent |= leading.agent;
        self.explain |= leading.explain;
        self.deterministic |= leading.deterministic;
        self.budget = leading.budget.or(self.budget);
        self.timeout = leading.timeout.or(self.timeout);
        self.memory_limit = leading.memory_limit.or(self.memory_limit);
        self.workspace = leading.workspace.or(self.workspace);
        self.policy = leading.policy.or(self.policy);
        self.command = leading.command.or(self.command);
        self
    }
}

/// Global flags that take no value.
const GLOBAL_SWITCHES: &[&str] = &[
    "-b",
    "--bash",
    "-z",
    "--zsh",
    "-p",
    "--pwsh",
    "-a",
    "--agentic",
    "--agent",
    "--explain",
    "--deterministic",
];

/// Global flags that take a value, as `--flag VALUE` or `--flag=VALUE`.
const GLOBAL_VALUED: &[&str] = &[
    "--budget",
    "--workspace",
    "--policy",
    "--timeout",
    "--memory-limit",
];

/// The subcommand names and aliases `Commands` declares.
const SUBCOMMANDS: &[&str] = &[
    "tui",
    "ai",
    "model",
    "mcp",
    "mcp-server",
    "agent",
    "agent-api",
    "assist",
    "ai-assist",
];

/// Parse the command line. Clap takes a word as a subcommand only when no
/// argument before it is a value, so `ish --agent agent execute` would read
/// `agent` as a script path. The global flags that come before a subcommand
/// are split off and parsed beside the subcommand, and applied to it.
fn parse_cli() -> Cli {
    let argv: Vec<std::ffi::OsString> = env::args_os().collect();
    match split_leading_globals(&argv) {
        None => Cli::parse(),
        Some((leading, rest)) => {
            let leading = Cli::parse_from(leading);
            Cli::parse_from(rest).with_leading_globals(leading)
        }
    }
}

/// Split `argv` into the global flags before its first subcommand, and the
/// command line from the subcommand on (with the program name in front). None
/// unless a global flag comes before a subcommand: a command string (`-c`), a
/// script, or any other word leaves the command line to clap as it was.
fn split_leading_globals(
    argv: &[std::ffi::OsString],
) -> Option<(Vec<std::ffi::OsString>, Vec<std::ffi::OsString>)> {
    let program = argv.first()?;
    let mut leading = vec![program.clone()];
    let mut i = 1;
    while i < argv.len() {
        let word = argv[i].to_str()?;
        if SUBCOMMANDS.contains(&word) {
            if i == 1 {
                return None;
            }
            let mut rest = vec![program.clone()];
            rest.extend(argv[i..].iter().cloned());
            return Some((leading, rest));
        }
        if GLOBAL_SWITCHES.contains(&word) {
            leading.push(argv[i].clone());
            i += 1;
        } else if GLOBAL_VALUED.contains(&word) {
            let value = argv.get(i + 1)?;
            leading.push(argv[i].clone());
            leading.push(value.clone());
            i += 2;
        } else if GLOBAL_VALUED
            .iter()
            .any(|flag| word.starts_with(&format!("{flag}=")))
        {
            leading.push(argv[i].clone());
            i += 1;
        } else {
            return None;
        }
    }
    None
}

/// Whether this invocation exists to serve an AI agent rather than a person.
///
/// The subcommands whose only caller is an agent qualify: the two HTTP
/// servers, the MCP stdio transport (what an MCP client such as a desktop
/// assistant launches), and the agent API's `execute` and `interactive`, which
/// read agent requests as JSON. `ish mcp stdio` was left out when the servers
/// were covered, so the canonical MCP transport kept the permissive profile.
///
/// A one-shot `ish -c` may well be run *by* an agent, but it is equally the way
/// a person and every shell script invoke the shell, so it keeps the human
/// profile and `--agent` stays the way to ask for the other one.
fn serves_an_agent(cmd: &Option<Commands>) -> bool {
    matches!(
        cmd,
        Some(Commands::Agent {
            command: AgentApiCommands::Serve { .. }
                | AgentApiCommands::Execute { .. }
                | AgentApiCommands::Interactive
        }) | Some(Commands::Mcp {
            command: McpCommands::Serve { .. } | McpCommands::Stdio
        })
    )
}

fn run(mut cli: Cli) -> Result<()> {
    // The memory budget: `--memory-limit`, else IRONSHELL_MEMORY_LIMIT_MB, else
    // the default. The allocator that counts is installed below.
    if let Some(mb) = cli.memory_limit {
        std::env::set_var("IRONSHELL_MEMORY_LIMIT_MB", mb.to_string());
    }
    iron_shell::memory::init_from_env();
    // The evaluation deadline: `--timeout`, else IRONSHELL_TIMEOUT (seconds).
    // None by default. The guard bounds this thread until `run` returns.
    let timeout = match cli.timeout {
        Some(n) => Some(n),
        None => match env::var("IRONSHELL_TIMEOUT") {
            Ok(v) => match v.trim().parse::<u64>() {
                Ok(n) => Some(n),
                Err(_) => {
                    eprintln!(
                        "ish: IRONSHELL_TIMEOUT must be a whole number of seconds, not {v:?}"
                    );
                    std::process::exit(2);
                }
            },
            Err(_) => None,
        },
    };
    let _deadline = timeout
        .filter(|n| *n > 0)
        .map(iron_shell::safety::enter_cli_deadline);
    // An output token budget applies to all eval/print paths via the REPL.
    if let Some(n) = cli.budget {
        std::env::set_var("IRONSHELL_TOKEN_BUDGET", n.to_string());
    }
    // Safety flags set the env vars the safety layer reads (see src/safety.rs).
    if cli.agent {
        std::env::set_var("IRONSHELL_MODE", "agent");
    }
    if let Some(ws) = &cli.workspace {
        // A workspace that does not exist is refused before anything runs. It
        // used to be created, with an audit log inside, so a mistyped path
        // quietly made a new jail. A UNC path is not probed: `is_dir` on it
        // opens an SMB session (see `names_a_remote_share`).
        let given = std::path::Path::new(ws);
        if !iron_shell::safety::names_a_remote_share(ws) && !given.is_dir() {
            eprintln!("ish: --workspace {ws} does not exist");
            eprintln!("hint: create the directory first (for example: mkdir {ws}), then run again");
            std::process::exit(2);
        }
        // Fixed as an absolute path now, so a later `cd` does not move the jail
        // and a child `ish` inherits the same root.
        let ws = given;
        let ws = std::path::absolute(ws).unwrap_or_else(|_| ws.to_path_buf());
        std::env::set_var("IRONSHELL_WORKSPACE", &ws);
        // Run from outside the workspace (`ish --workspace proj -c ...` from
        // proj's parent), a write's relative path was the workspace's while a
        // read's was the working directory's, so `file_write("x")` and
        // `open("x")` named different files. Start in the workspace instead,
        // with the script file, if any, made absolute first. Run from inside
        // it, as with `--workspace .`, nothing changes.
        let inside = match (std::env::current_dir(), ws.canonicalize()) {
            (Ok(cwd), Ok(root)) => cwd.canonicalize().is_ok_and(|c| c.starts_with(&root)),
            _ => true,
        };
        if !inside && cli.subcommand.is_none() {
            if let Some(file) = cli.file_and_args.first_mut().filter(|f| f.as_str() != "-") {
                if let Ok(abs) = std::path::absolute(&*file) {
                    *file = abs.to_string_lossy().into_owned();
                }
            }
            if let Err(e) = std::env::set_current_dir(&ws) {
                eprintln!("ish: cannot enter the workspace {ws:?}: {e}");
                std::process::exit(2);
            }
        }
    }
    // `ish agent serve` and `ish mcp serve` exist for one purpose: to let an AI
    // agent drive this shell. They ran with the *human* safety profile unless
    // the operator also remembered `--agent`, which meant the default posture
    // of the two agent-facing surfaces was the permissive one.
    //
    // That was masked for as long as `POST /api/v1/eval` could not resolve a
    // module namespace at all (see `modules::env_with_modules`): a probe that
    // tried to write outside the server's directory came back "contained",
    // because the call had never run. With the namespaces bound, the same probe
    // writes the file. Containment that depends on a second bug is not
    // containment.
    //
    // So serving an agent now implies agent mode — default-deny on dangerous
    // effect classes, and the workspace jail rooted at the server's working
    // directory. This changes nothing for `ish -c`, `ish script.ish` or the REPL;
    // a human shell that refused to write outside its cwd would not be a shell.
    // An operator who wants the old posture sets `IRONSHELL_MODE` explicitly,
    // which is honoured here and announced at startup either way.
    if serves_an_agent(&cli.subcommand) && std::env::var_os("IRONSHELL_MODE").is_none() {
        std::env::set_var("IRONSHELL_MODE", "agent");
    }
    // The mode is now final for every route below (`--agent`, IRONSHELL_MODE,
    // the serving subcommands, `-b`, `-c`, the REPL). Fix the workspace root
    // before anything reads it: `cd` must not move the jail or the audit log.
    iron_shell::safety::pin_workspace_root();
    if let Some(p) = &cli.policy {
        std::env::set_var("IRONSHELL_POLICY", p);
    }
    if cli.deterministic {
        std::env::set_var("IRONSHELL_DETERMINISTIC", "1");
    }
    // Load the RBAC manager + acting principal from config at startup, if
    // configured (IRONSHELL_RBAC_CONFIG / <workspace>/.ironshell/rbac.toml / IRONSHELL_PRINCIPAL).
    iron_shell::safety::init_rbac_from_env();

    // `ish script.ish a b`: the first word is the script and the rest are its
    // arguments. Under -c there is no script, so the words after -c are not
    // arguments, and the REPL has none either.
    let mut file_and_args = cli.file_and_args;
    // Under -c the words are the command's positional parameters for `-b`
    // (`ish -b -c 'echo $1' a` prints a), so keep a copy before the first word
    // is taken as the file.
    let c_args = file_and_args.clone();
    let file = (!file_and_args.is_empty()).then(|| file_and_args.remove(0));
    let script_args = if cli.command.is_some() {
        Vec::new()
    } else {
        file_and_args
    };
    iron_shell::builtins::set_script_args(script_args);
    if cli.command.is_some() {
        iron_shell::builtins::set_run_under_c();
        // Under -b the words are positional parameters; under plain -c nothing
        // reads them, so say so instead of dropping them without a word.
        if !cli.bash && !c_args.is_empty() {
            eprintln!(
                "ish: arguments after -c are ignored (args() is empty under -c); use a script file"
            );
        }
    }

    // Handle subcommands
    if let Some(cmd) = cli.subcommand {
        return match cmd {
            Commands::Tui => {
                iron_shell::tui::run()?;
                Ok(())
            }
            Commands::Ai { command } => iron_shell::serve::run_then_release(
                tokio::runtime::Runtime::new()?,
                handle_ai_command(command),
            ),
            Commands::Mcp { command } => iron_shell::serve::run_then_release(
                tokio::runtime::Runtime::new()?,
                handle_mcp_command(command),
            ),
            Commands::Agent { command } => handle_agent_api_command(command),
            Commands::Assist {
                query,
                execute,
                interactive,
                context,
                suggest,
            } => handle_assist(query, execute, interactive, context, suggest),
        };
    }

    // Handle bash mode with stdin
    if cli.bash && file.is_none() && cli.command.is_none() {
        let mut buf = String::new();
        io::stdin().read_to_string(&mut buf)?;
        run_posix_or_fall_back(&buf, None, &[]);
        let code = transpile::bash::transpile_bash_to_ae(&buf)?;
        return run_code(&code);
    }
    // Handle zsh mode with stdin
    if cli.zsh && file.is_none() && cli.command.is_none() {
        let mut buf = String::new();
        io::stdin().read_to_string(&mut buf)?;
        run_zsh_or_fall_back(&buf, None, &[]);
        let code = transpile_zsh_checked(&buf)?;
        return run_code(&code);
    }
    // Handle pwsh mode with stdin
    if cli.pwsh && file.is_none() && cli.command.is_none() {
        let mut buf = String::new();
        io::stdin().read_to_string(&mut buf)?;
        let code = transpile_pwsh_checked(&buf)?;
        return run_code(&code);
    }
    // Handle agentic mode with stdin
    if cli.agentic && file.is_none() && cli.command.is_none() {
        let mut buf = String::new();
        io::stdin().read_to_string(&mut buf)?;
        let code = transpile::agentic::transpile_agentic_to_ae(&buf)?;
        return run_code(&code);
    }

    // `--explain`: the static effect set, instead of running anything.
    if cli.explain {
        let code = match (&cli.command, &file) {
            (Some(c), _) => c.clone(),
            (None, Some(f)) => {
                fs::read_to_string(f).with_context(|| format!("failed to read {f}"))?
            }
            (None, None) => {
                let mut buf = String::new();
                io::stdin().read_to_string(&mut buf)?;
                buf
            }
        };
        // `-b` runs the source as the POSIX subset does, not as IronShell, so it
        // is explained as the subset runs it: a program is an exec, and the
        // decision is the one the run gets.
        if cli.bash {
            let report = iron_shell::explain::explain_posix(&code)?;
            println!("{}", serde_json::to_string_pretty(&report.to_json())?);
            return Ok(());
        }
        // A file that does not parse is reported as a run reports it: the
        // parser's own `E_PARSE` JSON on stderr and exit status 2. Going through
        // `explain`, which wraps the message as a builtin argument error, nested
        // that JSON inside a string and exited 1.
        if let Err(e) = iron_shell::parser::parse_program(&code) {
            eprintln!("{e}");
            std::process::exit(iron_shell::repl::exit_status_for(&e));
        }
        // A file's imports are read relative to the file, as a run reads them.
        let _entry = match (&cli.command, &file) {
            (None, Some(f)) => Some(iron_shell::module_loader::enter_entry_file(
                std::path::Path::new(f),
            )),
            _ => None,
        };
        let report = iron_shell::explain::explain(&code)?;
        println!("{}", serde_json::to_string_pretty(&report.to_json())?);
        return Ok(());
    }

    // Handle -c/--command flag
    if let Some(cmd) = cli.command {
        let code = if cli.bash {
            run_posix_or_fall_back(&cmd, None, &c_args);
            transpile::bash::transpile_bash_to_ae(&cmd)?
        } else if cli.zsh {
            run_zsh_or_fall_back(&cmd, None, &c_args);
            transpile_zsh_checked(&cmd)?
        } else if cli.pwsh {
            transpile_pwsh_checked(&cmd)?
        } else if cli.agentic {
            transpile::agentic::transpile_agentic_to_ae(&cmd)?
        } else {
            cmd
        };
        return run_code(&code);
    }

    // Determine transpile mode from flags
    let transpile_mode = if cli.bash {
        Some(TranspileMode::Bash)
    } else if cli.zsh {
        Some(TranspileMode::Zsh)
    } else if cli.pwsh {
        Some(TranspileMode::PowerShell)
    } else if cli.agentic {
        Some(TranspileMode::Agentic)
    } else {
        None
    };

    // Handle file execution or REPL
    match file {
        Some(file) => run_file(&file, transpile_mode)?,
        None => repl()?,
    }

    Ok(())
}

async fn handle_ai_command(command: AiCommands) -> Result<()> {
    use iron_shell::ai_api::*;

    match command {
        AiCommands::Serve { host, port, cors } => {
            let config_manager = ConfigManager::new()?;
            let mut config = config_manager.load_config()?;
            config.server.host = host.clone();
            config.server.port = port;
            config.server.enable_cors = cors;

            println!("Starting AI Model API server on {}:{}", host, port);
            println!(
                "OpenAPI docs: http://{}:{}{}",
                host, port, config.server.openapi_path
            );

            start_server(config).await
        }
        AiCommands::List { provider, local } => {
            let config_manager = ConfigManager::new()?;
            let config = config_manager.load_config()?;
            let api = AIModelAPI::new(config)?;
            let mut models = api.list_models().await?;

            if let Some(p) = provider {
                models.retain(|m| m.provider == p);
            }
            if local {
                models.retain(|m| m.local_path.is_some());
            }

            println!("{:<30} {:<15} {:<10}", "Model ID", "Provider", "Format");
            println!("{}", "-".repeat(55));
            for model in models {
                println!(
                    "{:<30} {:<15} {:<10}",
                    model.id,
                    model.provider,
                    format!("{:?}", model.format)
                );
            }
            Ok(())
        }
        AiCommands::Download { model } => {
            let config_manager = ConfigManager::new()?;
            let config = config_manager.load_config()?;
            let storage = ModelStorage::new(&config.storage)?;
            let mut downloader = ModelDownloader::new(storage)?;

            println!("Downloading model: {}", model);

            let request = DownloadRequest {
                model_id: model.clone(),
                source: ModelSource {
                    origin: "huggingface".to_string(),
                    url: None,
                    repository: Some(model.clone()),
                    commit: None,
                    license: None,
                },
                format_preference: None,
                quantization: None,
                validate_checksum: true,
            };

            let metadata = downloader.download_model(request).await?;
            println!("✓ Download complete: {}", metadata.file_path);
            Ok(())
        }
        AiCommands::Config => {
            let config_manager = ConfigManager::new()?;
            let config = config_manager.load_config()?;
            println!("{}", serde_json::to_string_pretty(&config)?);
            Ok(())
        }
        AiCommands::Keys { action } => handle_keys_action(action).await,
    }
}

async fn handle_keys_action(action: KeysAction) -> Result<()> {
    use iron_shell::secure_config::SecureApiConfig;
    use std::io::Write;

    match action {
        KeysAction::Store { provider, key } => {
            let api_key = if let Some(k) = key {
                k
            } else {
                print!("Enter API key for '{}': ", provider);
                io::stdout().flush()?;
                let mut buffer = String::new();
                io::stdin().read_line(&mut buffer)?;
                buffer.trim().to_string()
            };

            SecureApiConfig::store_in_keyring(&provider, &api_key)?;
            println!("✓ API key for '{}' stored securely", provider);
            Ok(())
        }
        KeysAction::Get { provider } => {
            let _config = SecureApiConfig::from_keyring(
                &provider,
                String::new(),
                String::new(),
                provider.clone(),
            )?;
            println!("API key for '{}': {}", provider, "*".repeat(20));
            println!("(Key is stored securely in OS credential store)");
            Ok(())
        }
        KeysAction::Delete { provider } => {
            SecureApiConfig::delete_from_keyring(&provider)?;
            println!("✓ API key for '{}' deleted", provider);
            Ok(())
        }
        KeysAction::List => {
            println!("Stored API key providers:");
            println!("(Use 'ae ai keys get <provider>' to verify a key exists)");
            println!("  - openai");
            println!("  - anthropic");
            println!("  - google");
            Ok(())
        }
    }
}

async fn handle_mcp_command(command: McpCommands) -> Result<()> {
    use iron_shell::mcp::{server::*, McpServer};
    use iron_shell::os_tools::SafetyLevel;

    match command {
        McpCommands::Serve {
            host,
            port,
            cors,
            safety,
            admin,
        } => {
            let safety_level = match safety.to_lowercase().as_str() {
                "safe" => SafetyLevel::Safe,
                "caution" => SafetyLevel::Caution,
                "dangerous" => SafetyLevel::Dangerous,
                "critical" => SafetyLevel::Critical,
                _ => {
                    eprintln!("Invalid safety level: {}. Using 'caution'", safety);
                    SafetyLevel::Caution
                }
            };

            let config = McpServerConfig {
                host,
                port,
                enable_cors: cors,
                // Same source as the agent API's token, so one env var covers
                // both servers; `None` mints one and prints it at startup.
                auth_token: std::env::var("IRONSHELL_API_TOKEN")
                    .ok()
                    .filter(|t| !t.trim().is_empty()),
                safety_level,
                allow_admin: admin,
            };

            start_mcp_server(config).await
        }
        McpCommands::Tools { category } => {
            let server = McpServer::new();
            let tools = server.list_tools();

            let filtered_tools: Vec<_> = if let Some(cat) = category {
                tools
                    .into_iter()
                    .filter(|t| t.name.contains(&cat) || t.description.contains(&cat))
                    .collect()
            } else {
                tools
            };

            println!("{:<25} Description", "Tool Name");
            println!("{}", "-".repeat(80));
            for tool in filtered_tools {
                let desc = if tool.description.len() > 50 {
                    format!("{}...", &tool.description[..50])
                } else {
                    tool.description.clone()
                };
                println!("{:<25} {}", tool.name, desc);
            }
            Ok(())
        }
        McpCommands::Stdio => {
            let server = McpServer::new();
            server.serve_stdio()?;
            Ok(())
        }
    }
}

fn handle_agent_api_command(command: AgentApiCommands) -> Result<()> {
    use iron_shell::agent_api::{self, AgentRequest};
    use std::io::{BufRead, Write};

    match command {
        AgentApiCommands::Serve {
            host,
            port,
            cors,
            token,
            request_timeout,
        } => {
            #[cfg(feature = "native")]
            {
                // The flag wins, but IRONSHELL_API_TOKEN is the documented path:
                // an argv token is visible to every other process on the box.
                let auth_token = token.or_else(|| {
                    std::env::var("IRONSHELL_API_TOKEN")
                        .ok()
                        .filter(|t| !t.trim().is_empty())
                });

                let config = agent_api::server::AgentApiConfig {
                    host,
                    port,
                    enable_cors: cors,
                    auth_token,
                    request_timeout_secs: request_timeout,
                };

                // `with_eval_stack` in `main` covers this thread, but tokio
                // spawns its own workers — and evaluation happens on those, via
                // `spawn_blocking`. Without this they would get the default
                // stack and overflow at a few dozen frames, long before
                // `safety::MAX_CALL_DEPTH` could refuse the call. This is the
                // path that matters for finding 13: it is the one an
                // unauthenticated-adjacent caller can reach.
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .enable_all()
                    .thread_stack_size(iron_shell::safety::EVAL_STACK_SIZE)
                    .build()?;
                iron_shell::serve::run_then_release(
                    rt,
                    agent_api::server::start_agent_api_server(config),
                )
            }

            #[cfg(not(feature = "native"))]
            {
                Err(anyhow::anyhow!("Agent API server requires native feature"))
            }
        }
        AgentApiCommands::Execute { request } => {
            let json_str = if let Some(req) = request {
                req
            } else {
                // Read from stdin
                let mut buffer = String::new();
                io::stdin().read_to_string(&mut buffer)?;
                buffer
            };

            // Every input gets one JSON response on stdout. Input that is not a
            // request is answered with its failure, and the exit status is 1.
            match agent_api::parse_request(&json_str) {
                Ok(parsed) => {
                    let response = agent_api::process_request(&parsed);
                    println!("{}", serde_json::to_string_pretty(&response)?);
                    // A failed call exits with the status the CLI gives the same
                    // error code (75 needs approval, 127 unknown builtin, ...),
                    // so a shell `&&` or a caller's exit check sees the failure.
                    // A malformed request below still exits 1.
                    if !response.success {
                        io::stdout().flush()?;
                        let status = response
                            .code
                            .as_deref()
                            .map_or(1, iron_shell::safety::ErrorCode::exit_code_for_wire);
                        std::process::exit(status);
                    }
                    Ok(())
                }
                Err(response) => {
                    println!("{}", serde_json::to_string_pretty(&response)?);
                    io::stdout().flush()?;
                    std::process::exit(1);
                }
            }
        }
        AgentApiCommands::Schema {
            format,
            output,
            module,
            q,
        } => {
            let schema =
                agent_api::generate_schema_filtered(&format, module.as_deref(), q.as_deref())?;

            if let Some(path) = output {
                fs::write(&path, &schema)?;
                println!("✓ Schema written to {}", path);
            } else {
                println!("{}", schema);
            }
            Ok(())
        }
        AgentApiCommands::Builtins {
            category,
            json: json_output,
        } => {
            let request = AgentRequest::ListBuiltins { category };
            let response = agent_api::process_request(&request);

            if json_output {
                println!("{}", serde_json::to_string_pretty(&response)?);
            } else if response.success {
                if let Some(result) = &response.result {
                    if let Some(builtins) = result.get("builtins") {
                        if let Some(arr) = builtins.as_array() {
                            println!("{:<20} {:<12} Description", "Name", "Category");
                            println!("{}", "-".repeat(80));
                            for b in arr {
                                let name = b.get("name").and_then(|v| v.as_str()).unwrap_or("");
                                let cat = b.get("category").and_then(|v| v.as_str()).unwrap_or("");
                                let desc =
                                    b.get("description").and_then(|v| v.as_str()).unwrap_or("");
                                let desc_short = if desc.len() > 45 {
                                    format!("{}...", &desc[..45])
                                } else {
                                    desc.to_string()
                                };
                                println!("{:<20} {:<12} {}", name, cat, desc_short);
                            }
                        }
                    }
                }
            } else {
                eprintln!("Error: {}", response.error.unwrap_or_default());
            }
            Ok(())
        }
        AgentApiCommands::Interactive => {
            // The banner goes to stderr, so stdout carries only responses: one
            // compact JSON line per request line.
            eprintln!("🤖 IronShell Agent API - Interactive Mode");
            eprintln!("Send JSON requests (one per line), receive JSON responses");
            eprintln!("Press Ctrl+D to exit\n");

            let stdin = io::stdin();
            let mut stdout = io::stdout();

            for line in stdin.lock().lines() {
                match line {
                    Ok(json_str) if !json_str.trim().is_empty() => {
                        let response = agent_api::process_json_response(&json_str);
                        println!("{}", serde_json::to_string(&response)?);
                        stdout.flush()?;
                    }
                    Ok(_) => {} // Empty line, skip
                    Err(e) => {
                        eprintln!("Read error: {}", e);
                        break;
                    }
                }
            }
            Ok(())
        }
    }
}
fn handle_assist(
    query: Option<String>,
    execute: bool,
    interactive: bool,
    context: bool,
    suggest: bool,
) -> Result<()> {
    use std::io::{BufRead, Write};

    let system_prompt = build_assist_prompt();
    let ctx = if context {
        gather_system_context()
    } else {
        String::new()
    };

    // Suggest mode: analyze cwd and suggest useful commands
    if suggest {
        let suggest_prompt = format!(
            "{}\n\n{}\n\nBased on the context above, suggest 3-5 useful IronShell commands \
             the user could run in this directory. Format each as a one-line comment explaining \
             what it does, followed by the code on the next line. Separate suggestions with blank lines.",
            system_prompt, ctx
        );
        let suggestions = iron_shell::ai::complete_sync_router(&suggest_prompt)
            .context("AI completion failed — is IRONSHELL_AI configured?")?;
        println!("{}", clean_ai_output(&suggestions));
        return Ok(());
    }

    if interactive {
        println!("Æther Assist — natural language → IronShell");
        println!("Type your request, press Enter. Type 'exit' or Ctrl-D to quit.");
        if context {
            println!("Context-aware mode: system info included in prompts.");
        }
        println!();

        let stdin = io::stdin();
        let mut stdout = io::stdout();
        let mut history: Vec<String> = Vec::new();

        loop {
            print!("assist> ");
            stdout.flush().ok();

            let mut line = String::new();
            if stdin.lock().read_line(&mut line)? == 0 {
                println!();
                break;
            }

            let input = line.trim();
            if input.is_empty() {
                continue;
            }
            if input == "exit" || input == "quit" {
                break;
            }

            // Build context-aware prompt with conversation history
            let history_context = if !history.is_empty() {
                let recent: Vec<String> = history
                    .iter()
                    .rev()
                    .take(5)
                    .cloned()
                    .collect::<Vec<_>>()
                    .into_iter()
                    .rev()
                    .collect();
                format!("\nRecent conversation:\n{}\n", recent.join("\n"))
            } else {
                String::new()
            };

            match assist_once(&system_prompt, &ctx, &history_context, input, execute) {
                Ok(code) => {
                    history.push(format!("User: {}", input));
                    history.push(format!("Assistant: {}", code));
                }
                Err(e) => eprintln!("error: {e}"),
            }
            println!();
        }
        return Ok(());
    }

    // Single query mode
    let input = if let Some(q) = query {
        q
    } else {
        let mut buf = String::new();
        io::stdin().read_to_string(&mut buf)?;
        buf
    };

    assist_once(&system_prompt, &ctx, "", input.trim(), execute)?;
    Ok(())
}
/// Build the comprehensive system prompt for NL -> IronShell transpilation
fn build_assist_prompt() -> String {
    "You are an IronShell assistant. Convert natural language into IronShell code.\n\n\
IronShell is a typed functional shell where data flows as structured values through pipelines.\n\n\
## Core Syntax\n\
- Variables: x = 42, name = \"hello\", items = [1,2,3], config = {key: \"val\"}\n\
- Lambdas: fn(x) => x * 2, fn(a, b) => a + b\n\
- Pipelines: data | where(fn(x) => x > 0) | map(fn(x) => x * 2) | take(5)\n\
- Pattern matching: match val { 1 => \"one\", 2 => \"two\", _ => \"other\" }\n\
- Error handling: try { risky() } catch e { fallback }\n\
- String interpolation: \"Hello ${name}, you have ${count} items\"\n\
- Async: await http.get(url)\n\n\
## Module System (38 modules, 215+ builtins)\n\
### File & System\n\
- file.read(path), file.write(path, data), file.exists(path), file.copy(src, dst)\n\
- file.replace(path, old, new), file.patch(path, line_start, line_end, content)\n\
- file.insert(path, {after: pattern}, content), file.backup(path)\n\
- ls(path), cd(path), pwd(), cat(path), mkdir(path), rm(path)\n\
- sys.hostname(), sys.uptime(), sys.cpu_info(), sys.mem_info()\n\
- proc.list(), proc.kill(pid)\n\
- platform.os(), platform.arch(), platform.gpus(), platform.hardware_summary()\n\n\
### Data & Text\n\
- str.upper(s), str.lower(s), str.split(s, delim), str.trim(s), str.replace(s, old, new)\n\
- arr.range(n), arr.flatten(a), arr.unique(a), arr.sort(a), arr.reverse(a)\n\
- json.parse(s), json.stringify(v)\n\
- math.sqrt(x), math.pow(a, b), math.abs(x), math.ceil(x), math.floor(x)\n\n\
### Pipeline Operations\n\
- map(fn), where(fn), reduce(fn, init), sort(fn), reverse()\n\
- take(n), skip(n), head(n), tail(n), flatten(), unique()\n\
- select(field1, field2), get(key), keys(), values()\n\
- length(), enumerate(), zip(other)\n\n\
### Network & HTTP\n\
- net.ping(host), net.dns_lookup(host), net.interfaces()\n\
- http.get(url), http.post(url, body), http.put(url, body), http.delete(url)\n\n\
### Crypto & Database\n\
- crypto.uuid(), crypto.hash(algo, data), crypto.jwt_decode(token)\n\
- db.sqlite_open(path), db.sqlite_query(conn, sql)\n\n\
### AI & Agents\n\
- ai(prompt), ai(prompt, {context: data}), ai(prompt, {images: [path]})\n\
- agent(goal, tools), agent(goal, tools, {model: \"openai:gpt-4o\", max_steps: 10})\n\
- swarm({coordinator: goal, agents: [...], tools: [...]})\n\n\
### Protocols\n\
- mcp.tools(), mcp.call(tool, args)\n\
- a2a.send(agent, msg)\n\
- a2ui.notify(msg, level), a2ui.progress(label, fraction)\n\n\
### Enterprise\n\
- rbac.create(role, perms), rbac.grant(user, role)\n\
- audit.log(action, target, meta)\n\
- sso.init(provider, config)\n\n\
### Other Modules\n\
- shell.exec(cmd), env(key), which(cmd)\n\
- clip.read(), clip.write(text)\n\
- archive.compress(path, format), archive.extract(path)\n\
- cron.schedule(expr, cmd), svc.list(), pkg.list()\n\n\
## AI Model URIs\n\
- openai:gpt-4o, openai:gpt-4o-mini\n\
- ollama:llama3, ollama:codellama\n\
- anthropic:claude-3-opus\n\n\
RULES:\n\
1. Output ONLY valid IronShell code — no markdown fences, no explanations.\n\
2. Use pipelines for data transformation chains.\n\
3. Prefer module builtins (file.read, sys.hostname) over raw shell commands.\n\
4. One complete program per response.\n\
5. Use the most appropriate module for each task."
        .to_string()
}
/// Gather system context for context-aware suggestions
fn gather_system_context() -> String {
    let mut ctx = String::from("## System Context\n");

    // Working directory
    if let Ok(cwd) = std::env::current_dir() {
        ctx.push_str(&format!("- Working directory: {}\n", cwd.display()));

        // List files in cwd (first 20)
        if let Ok(entries) = std::fs::read_dir(&cwd) {
            let mut files: Vec<String> = Vec::new();
            for entry in entries.flatten().take(20) {
                let name = entry.file_name().to_string_lossy().to_string();
                let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
                if is_dir {
                    files.push(format!("{}/", name));
                } else {
                    files.push(name);
                }
            }
            ctx.push_str(&format!("- Directory contents: {}\n", files.join(", ")));
        }
    }

    // OS and platform
    ctx.push_str(&format!("- OS: {}\n", std::env::consts::OS));
    ctx.push_str(&format!("- Arch: {}\n", std::env::consts::ARCH));

    // Detect project type from files
    let project_indicators = [
        ("Cargo.toml", "Rust project"),
        ("package.json", "Node.js project"),
        ("pyproject.toml", "Python project"),
        ("go.mod", "Go project"),
        ("pom.xml", "Java/Maven project"),
        ("build.gradle", "Java/Gradle project"),
        ("Makefile", "Make-based project"),
        ("Dockerfile", "Docker containerized"),
        (".git", "Git repository"),
        ("docker-compose.yml", "Docker Compose setup"),
    ];

    let mut detected: Vec<&str> = Vec::new();
    for (file, label) in &project_indicators {
        if std::path::Path::new(file).exists() {
            detected.push(label);
        }
    }
    if !detected.is_empty() {
        ctx.push_str(&format!("- Project type: {}\n", detected.join(", ")));
    }

    // Relevant env vars (without values for security)
    let relevant_vars = [
        "IRONSHELL_AI",
        "OPENAI_API_KEY",
        "ANTHROPIC_API_KEY",
        "OLLAMA_HOST",
        "EDITOR",
        "SHELL",
        "TERM",
    ];
    let set_vars: Vec<&str> = relevant_vars
        .iter()
        .filter(|v| std::env::var(v).is_ok())
        .copied()
        .collect();
    if !set_vars.is_empty() {
        ctx.push_str(&format!("- Available env vars: {}\n", set_vars.join(", ")));
    }

    ctx
}
/// Clean AI output: strip markdown fences and whitespace
fn clean_ai_output(raw: &str) -> String {
    let cleaned = raw.trim();
    let cleaned = cleaned
        .strip_prefix("```ironshell")
        .or_else(|| cleaned.strip_prefix("```ish"))
        .or_else(|| cleaned.strip_prefix("```"))
        .unwrap_or(cleaned);
    let cleaned = cleaned.strip_suffix("```").unwrap_or(cleaned).trim();
    cleaned.to_string()
}

fn assist_once(
    system_prompt: &str,
    system_context: &str,
    history: &str,
    query: &str,
    execute: bool,
) -> Result<String> {
    use iron_shell::ai;

    let prompt = format!(
        "{}\n\n{}{}\nUser request: {}",
        system_prompt, system_context, history, query
    );
    let code = ai::complete_sync_router(&prompt)
        .context("AI completion failed — is IRONSHELL_AI configured?")?;

    let cleaned = clean_ai_output(&code);

    if execute {
        println!("# Generated code:");
        for line in cleaned.lines() {
            println!("  {}", line);
        }
        println!("# Running...\n");
        run_code(&cleaned)?;
    } else {
        println!("{}", cleaned);
    }
    Ok(cleaned.to_string())
}
fn repl() -> Result<()> {
    // Delegates to `repl.rs`, which owns prompt rendering (fish / powerline /
    // pure styles), fish-style line editing, and history persistence.
    //
    // This used to be a second, inline REPL that printed a hard-coded `ae> `
    // and `{:?}`-formatted values — added "to avoid extra wires" — which meant
    // the real REPL was never reached interactively and none of the prompt or
    // history configuration had any effect.
    let mut env = create_env_with_modules();
    iron_shell::repl::run(&mut env)
}

/// Transpilation mode for legacy shell compatibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TranspileMode {
    Bash,
    Zsh,
    PowerShell,
    Agentic,
}

/// Detect transpile mode from file extension (when no explicit flag is given).
fn detect_transpile_mode(path: &str) -> Option<TranspileMode> {
    let lower = path.to_lowercase();
    if lower.ends_with(".sh") || lower.ends_with(".bash") {
        Some(TranspileMode::Bash)
    } else if lower.ends_with(".zsh") {
        Some(TranspileMode::Zsh)
    } else if lower.ends_with(".ps1") || lower.ends_with(".psm1") || lower.ends_with(".psd1") {
        Some(TranspileMode::PowerShell)
    } else if lower.ends_with(".ishg") {
        Some(TranspileMode::Agentic)
    } else {
        None
    }
}

fn run_file(path: &str, explicit_mode: Option<TranspileMode>) -> Result<()> {
    let mut code = match fs::read_to_string(path) {
        Ok(code) => code,
        // A script that does not exist is E_NOT_FOUND (exit 66), as a missing
        // file is anywhere else in the language; under --agent it is the JSON
        // error shape.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            let err = iron_shell::safety::not_found("run", "file", path);
            iron_shell::repl::report_error(&err);
            std::process::exit(iron_shell::repl::exit_status_for(&err));
        }
        Err(e) => return Err(e).with_context(|| format!("failed to read {}", path)),
    };

    // Explicit flag takes priority; otherwise auto-detect from extension
    let mode = explicit_mode.or_else(|| detect_transpile_mode(path));

    if let Some(m) = mode {
        code = match m {
            TranspileMode::Bash => {
                run_posix_or_fall_back(&code, Some(path), iron_shell::builtins::script_args());
                transpile::bash::transpile_bash_to_ae(&code).with_context(|| {
                    format!("bash\u{2192}ironshell transpile failed for {}", path)
                })?
            }
            TranspileMode::Zsh => {
                run_zsh_or_fall_back(&code, Some(path), iron_shell::builtins::script_args());
                transpile_zsh_checked(&code).with_context(|| {
                    format!("zsh\u{2192}ironshell transpile failed for {}", path)
                })?
            }
            TranspileMode::PowerShell => transpile_pwsh_checked(&code).with_context(|| {
                format!("powershell\u{2192}ironshell transpile failed for {}", path)
            })?,
            TranspileMode::Agentic => transpile::agentic::transpile_agentic_to_ae(&code)
                .with_context(|| {
                    format!("agentic\u{2192}ironshell transpile failed for {}", path)
                })?,
        };
    }

    // `import` paths in this file resolve against its own directory.
    let _entry = iron_shell::module_loader::enter_entry_file(std::path::Path::new(path));
    run_code_as(&code, iron_shell::record::Surface::File)
}

/// Run shell source natively when it is inside the POSIX subset
/// (`src/posix.rs`), exiting with its status. Returns only when the source is
/// outside the subset, before anything has run, so the caller falls back to
/// the transpiler exactly as it did before the subset existed. `args` are the
/// script's arguments, which become its positional parameters `$1`..`$9`.
/// Run `src` in the POSIX subset. `script` is the file's path, which is `$0`;
/// `None` (stdin, `-c`) makes `$0` `ish`.
fn run_posix_or_fall_back(src: &str, script: Option<&str>, args: &[String]) {
    let started = std::time::Instant::now();
    let ran = match script {
        Some(path) => iron_shell::posix::run_script(src, path, args),
        None => iron_shell::posix::run_with_args(src, args),
    };
    if let Some(status) = ran {
        iron_shell::record::note_status(
            iron_shell::record::Surface::Sh,
            src,
            iron_shell::posix::heads,
            status,
            started.elapsed(),
        );
        std::process::exit(status);
    }
    // Outside the subset, and nothing has run. The transpiler below turns the
    // unsupported parts into `sh(...)` calls: with IRONSHELL_ALLOW_SH they run
    // through `bash -lc`, and without it each refuses at run time, after the
    // lines before it have already run. Without the opt-in, refuse here, naming
    // the construct and where it starts.
    if let Some(r) = iron_shell::posix::refusal(src) {
        // A syntax error is wrong in every shell, so it is reported as one
        // (E_PARSE, exit 2) whether or not the transpiler fallback is allowed.
        if r.syntax {
            let e = anyhow::Error::new(iron_shell::parser::ParseError::with_hint(
                format!("{} at line {}, column {}", r.construct, r.line, r.column),
                r.hint,
            ));
            iron_shell::repl::report_error(&e);
            std::process::exit(iron_shell::repl::exit_status_for(&e));
        }
        if iron_shell::security::validate_sh_allowed().is_err() {
            let e = iron_shell::safety::policy_deny(
                "posix",
                format!(
                    "{} at line {}, column {} is not in the in-process POSIX subset, so nothing in this script was run",
                    r.construct, r.line, r.column
                ),
                r.hint,
            );
            iron_shell::repl::report_error(&e);
            std::process::exit(iron_shell::repl::exit_status_for(&e));
        }
    }
}

fn run_code(code: &str) -> Result<()> {
    run_code_as(code, iron_shell::record::Surface::C)
}

fn run_code_as(code: &str, surface: iron_shell::record::Surface) -> Result<()> {
    let mut env = create_env_with_modules();
    let exit_code = iron_shell::repl::run_one_as(&mut env, code, surface)?;
    // The process ends here, and freeing the environment -- ~120 module
    // records, a few thousand small allocations -- was 14% of the
    // instructions `ish -c 1` executes. Neither `Env` nor `Value` has a `Drop`
    // with side effects; output has already been written by `run_one`.
    std::mem::forget(env);
    if exit_code != 0 {
        std::process::exit(exit_code);
    }
    Ok(())
}

/// Run zsh source natively when it is plain POSIX once zsh's own words are
/// rewritten (`src/transpile/zsh.rs`), exiting with its status. Returns only
/// for source that is not run that way (a lone `**` command, or source outside
/// the POSIX subset when `IRONSHELL_ALLOW_SH` lets the transpiler take it);
/// otherwise a refusal names the construct and line, and nothing has run.
fn run_zsh_or_fall_back(src: &str, script: Option<&str>, args: &[String]) {
    match transpile::zsh::route(src) {
        Ok(transpile::zsh::Route::Posix(posix)) => run_posix_or_fall_back(&posix, script, args),
        Ok(transpile::zsh::Route::Transpile) => {}
        Err(r) => {
            let e = iron_shell::safety::policy_deny(
                "zsh",
                format!(
                    "{} at line {} is not translated, so nothing in this script was run",
                    r.construct, r.line
                ),
                r.hint,
            );
            iron_shell::repl::report_error(&e);
            std::process::exit(iron_shell::repl::exit_status_for(&e));
        }
    }
}

/// Transpile zsh for the evaluator. A construct handed to `sh(...)` is refused
/// here, by name and line and before anything runs, unless `sh` is allowed.
fn transpile_zsh_checked(src: &str) -> Result<String> {
    let (code, fallbacks) = transpile::zsh::transpile_zsh_with_report(src)?;
    refuse_sh_fallbacks("zsh", &fallbacks);
    Ok(code)
}

/// [`transpile_zsh_checked`] for PowerShell.
fn transpile_pwsh_checked(src: &str) -> Result<String> {
    let (code, fallbacks) = match transpile::powershell::transpile_powershell_with_report(src) {
        Ok(r) => r,
        // Every transpile-time refusal has one shape: E_POLICY_DENY, exit 77,
        // with a hint, as a construct handed to `sh` is refused below.
        Err(why) => {
            let e = iron_shell::safety::policy_deny(
                "powershell",
                why.to_string(),
                "rewrite it with commands and expressions the powershell transpiler translates, or write it in ish",
            );
            iron_shell::repl::report_error(&e);
            std::process::exit(iron_shell::repl::exit_status_for(&e));
        }
    };
    refuse_sh_fallbacks("powershell", &fallbacks);
    // The translation has no line map: a runtime error would name its line, not
    // the PowerShell source's.
    iron_shell::repl::set_source_lines_unknown();
    Ok(code)
}

fn refuse_sh_fallbacks(shell: &str, fallbacks: &[transpile::Fallback]) {
    let Some(f) = fallbacks.first() else {
        return;
    };
    if iron_shell::security::validate_sh_allowed().is_ok() {
        return;
    }
    let agent = iron_shell::safety::current_mode() == iron_shell::safety::Mode::Agent;
    let hint = if agent {
        format!("rewrite it with commands this {shell} transpiler maps, or write it in ish")
    } else {
        format!("rewrite it with commands this {shell} transpiler maps, write it in ish, or set IRONSHELL_ALLOW_SH=true to run the untranslated parts through {shell}, outside the effect gate")
    };
    // An unmapped command is named as one: it is not an operator or expression.
    let reason = if f.construct.starts_with("command `") {
        "has no IronShell mapping"
    } else {
        "is not translated to IronShell"
    };
    let e = iron_shell::safety::policy_deny(
        shell,
        format!(
            "{} at line {} {reason}, so nothing in this script was run",
            f.construct, f.line
        ),
        hint,
    );
    iron_shell::repl::report_error(&e);
    std::process::exit(iron_shell::repl::exit_status_for(&e));
}