nepali-core 0.1.0

Nepali programming language core: lexer, parser, AST, interpreter
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
use crate::ast::{BinOp, Expr, Stmt};
use alloc::collections::BTreeMap;
use alloc::format;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::cell::RefCell;

pub type EvalResult<T> = Result<T, String>;

#[derive(Debug, Clone)]
pub enum Value {
    Number(f64),
    Str(String),
    Bool(bool),
    Null,
    Function(Rc<FunctionValue>),
    /// `Rc<RefCell<..>>`, not a plain `Vec` - arrays are reference types
    /// here (assigning `x[i] = v` must be visible through every other
    /// binding that refers to the same array, matching how every other
    /// language with mutable arrays behaves, and how `FunctionValue`'s
    /// closure already shares `Env` the same way).
    Array(Rc<RefCell<Vec<Value>>>),
}

#[derive(Debug)]
pub struct FunctionValue {
    pub name: String,
    pub params: Vec<String>,
    pub body: Vec<Stmt>,
    pub closure: Env,
}

impl Value {
    pub fn is_truthy(&self) -> bool {
        match self {
            Value::Bool(b) => *b,
            Value::Null => false,
            Value::Number(n) => *n != 0.0,
            Value::Str(s) => !s.is_empty(),
            Value::Function(_) => true,
            Value::Array(a) => !a.borrow().is_empty(),
        }
    }

    pub fn display(&self) -> String {
        match self {
            Value::Number(n) => {
                // core has no fract()/trunc() (libm, not in core); round-trip
                // through i64 instead to detect integer-valued floats.
                let as_int = *n as i64;
                if as_int as f64 == *n {
                    format!("{}", as_int)
                } else {
                    format!("{}", n)
                }
            }
            Value::Str(s) => s.clone(),
            Value::Bool(b) => {
                if *b {
                    "सहि".to_string()
                } else {
                    "गलत".to_string()
                }
            }
            Value::Null => "केहीछैन".to_string(),
            Value::Function(f) => format!("<function {}>", f.name),
            Value::Array(a) => {
                let items: Vec<String> = a.borrow().iter().map(Value::display).collect();
                format!("[{}]", items.join(", "))
            }
        }
    }
}

#[derive(Debug)]
pub struct Scope {
    vars: BTreeMap<String, Value>,
    parent: Option<Env>,
}

pub type Env = Rc<RefCell<Scope>>;

pub fn new_scope(parent: Option<Env>) -> Env {
    Rc::new(RefCell::new(Scope {
        vars: BTreeMap::new(),
        parent,
    }))
}

fn env_get(env: &Env, name: &str) -> Option<Value> {
    if let Some(v) = env.borrow().vars.get(name) {
        return Some(v.clone());
    }
    match &env.borrow().parent {
        Some(parent) => env_get(parent, name),
        None => None,
    }
}

fn env_define(env: &Env, name: String, value: Value) {
    env.borrow_mut().vars.insert(name, value);
}

fn env_assign(env: &Env, name: &str, value: Value) -> Result<(), String> {
    if env.borrow().vars.contains_key(name) {
        env.borrow_mut().vars.insert(name.into(), value);
        return Ok(());
    }
    let parent = env.borrow().parent.clone();
    match parent {
        Some(parent) => env_assign(&parent, name, value),
        None => Err(format!("undefined variable '{}'", name)),
    }
}

enum Signal {
    Normal,
    Return(Value),
}

/// A real filesystem `.nep` code can reach through
/// `ओएस_लेख्नुहोस्`/`ओएस_पढ्नुहोस्`/`ओएस_सूची` - not a simulated one.
/// `nepali-core` is `no_std` and has no filesystem of its own (and must
/// not depend on any particular host's - the kernel and the CLI have
/// completely different real ones), so this is dependency injection: the
/// host (`kernel/src/fs.rs`'s real FAT filesystem, or a `std::fs`-backed
/// one for the CLI) implements this trait and hands it to the
/// interpreter via `set_host_fs`; without one, these three builtins fail
/// with a clear "no host filesystem available" error instead of
/// pretending to succeed.
pub trait HostFs {
    fn read_file(&self, path: &str) -> Result<String, String>;
    fn write_file(&self, path: &str, contents: &str) -> Result<(), String>;
    /// Lists filenames only (not sizes/types) - deliberately the smallest
    /// useful contract, since what a "path" even means beyond a plain
    /// filename in the current directory is host-specific (see
    /// `kernel/src/fs.rs`'s lack of general path-splitting).
    fn list_dir(&self, path: &str) -> Result<Vec<String>, String>;
}

/// Real preemptible processes `.nep` code can reach through
/// `नयाँ_प्रक्रिया`/`प्रक्रिया_सूची` - not a simulated process table.
/// Same dependency-injection reasoning as `HostFs`: `nepali-core` has no
/// scheduler of its own, and the kernel's real one (`kernel/src/
/// process.rs`) is the only thing that could ever back this honestly.
pub trait HostProcess {
    /// Starts a real process, returning its index (a real, if simple,
    /// "PID"). The name is a label only - every process this kernel can
    /// spawn runs the same fixed program regardless of what it's called.
    fn spawn(&self, name: &str) -> Result<f64, String>;
    /// Real names of every currently running process, in spawn order.
    fn list(&self) -> Result<Vec<String>, String>;
}

/// Real, kernel-tracked FIFO message queues `.nep` code can reach through
/// `नयाँ_च्यानल`/`च्यानल_पठाउनुहोस्`/`च्यानल_पाउनुहोस्`. Same
/// dependency-injection reasoning as `HostFs`/`HostProcess`.
///
/// Honestly scoped, like `HostProcess`: this kernel's ring-3 processes
/// only ever run a fixed hand-written machine-code loop (see
/// `kernel/src/process.rs`) and have no way to call into `nepali-core` at
/// all, so a channel backed by this trait is real, persistent, kernel-side
/// FIFO state - not a fake in-interpreter simulation - but it is not yet
/// genuine inter-*process* communication, since no second execution
/// context exists that could be the other end of one. `recv` is
/// non-blocking (`Ok(None)` on empty) rather than parking the caller,
/// since there is also no real scheduler hook yet to wake a blocked
/// `nepali-core` script when a message arrives.
/// A real external command `.nep` code (and the agent loop below) can
/// run and get the *result* back from, through `आदेश_चलाउनुहोस्` - a
/// real gap this fills: `HostProcess` above is dead code for this OS
/// (never wired in the CLI - see `src/cli/main.rs` - a leftover from
/// the deleted from-scratch kernel, where "processes" only ever ran a
/// fixed hand-written machine-code loop, not real programs), and the
/// interactive shell's own external-command path
/// (`run_shell`/`run_external` in `src/cli/main.rs`) inherits stdio
/// straight through rather than capturing it, so nothing - not `.nep`
/// scripts, not an AI agent - could previously run a real command and
/// see what it printed or whether it succeeded. A real backend (the
/// CLI's `std::process::Command`-based implementation) is handed to the
/// interpreter via `set_host_command`.
pub trait HostCommand {
    /// Runs `program` with real `args`, waits for it to finish, and
    /// returns `(exit_code, stdout, stderr)` - all real, captured
    /// output, not fire-and-forget. Deliberately `Command::new(program)`
    /// with a real argument array, never a shell string handed to `sh
    /// -c` - shell metacharacters in `args` (`;`, `|`, `` ` ``, `$(...)`)
    /// are inert, passed through as literal argv entries, not
    /// interpreted. A real, meaningful security property for anything
    /// (especially an AI-driven agent) that runs commands built from
    /// text it didn't fully control.
    fn run(&self, program: &str, args: &[String]) -> Result<(i32, String, String), String>;
}

pub trait HostChannel {
    /// Creates a new, empty channel, returning its id.
    fn create(&self) -> Result<f64, String>;
    /// Pushes `msg` onto channel `id`'s queue.
    fn send(&self, id: f64, msg: &str) -> Result<(), String>;
    /// Pops the oldest message off channel `id`'s queue, or `None` if it's
    /// currently empty (never blocks).
    fn recv(&self, id: f64) -> Result<Option<String>, String>;
}

/// A real SQL database `.nep` code can reach through
/// `डाटाबेस_चलाउनुहोस्`/`डाटाबेस_सोध्नुहोस्` - not an in-memory toy. Same
/// dependency-injection reasoning as `HostFs`: `nepali-core` has no
/// database engine of its own and must not assume any particular host's,
/// so a real backend (e.g. the CLI's SQLite-backed implementation, via
/// the well-audited `rusqlite` crate rather than a hand-rolled one)
/// implements this trait and is handed to the interpreter via
/// `set_host_db`. Deliberately just these two operations - a full ORM-
/// style API belongs in a `.nep` standard-library module built on top of
/// these two primitives, not baked into the interpreter itself.
pub trait HostDb {
    /// Runs a statement with no result set (INSERT/UPDATE/DELETE/CREATE/
    /// ...), returning the number of rows affected.
    fn execute(&self, sql: &str) -> Result<f64, String>;
    /// Runs a SELECT, returning each row as a `Value::Array` of column
    /// values (SQLite's own dynamic typing maps directly onto this
    /// language's existing `Value` variants: `INTEGER`/`REAL` ->
    /// `Number`, `TEXT` -> `Str`, `NULL` -> `Null`; a `BLOB` column is a
    /// real, honest runtime error rather than silently mangled text).
    fn query(&self, sql: &str) -> Result<Vec<Value>, String>;
}

/// Real embedded Python `.nep` code can reach through
/// `पाइथन_चलाउनुहोस्` - the first of four planned real-interop bridges
/// (Python, then Rust plugins, then JS/TS, then Go - see CLAUDE.md), not
/// a simulated one. Same dependency-injection reasoning as the other
/// `Host*` traits: `nepali-core` stays `no_std` and has no Python runtime
/// of its own, so a real backend (the CLI's `pyo3`-based implementation,
/// embedding the real system CPython) implements this and is handed to
/// the interpreter via `set_host_python`.
pub trait HostPython {
    /// Runs `code` as real Python (multiple statements allowed, real
    /// `import`s work). Returns whatever the script assigns to the
    /// conventional variable `परिणाम` by the time it finishes, or
    /// `Value::Null` if it never does - Python statements don't have a
    /// single trailing "value" the way an expression-based language's
    /// blocks do, so a return value needs an explicit convention rather
    /// than an implicit "last expression" rule.
    fn eval(&self, code: &str) -> Result<Value, String>;
}

/// Real, separately-compiled native plugins `.nep` code can reach
/// through `रस्ट_चलाउनुहोस्`/`गो_चलाउनुहोस्` - the second (and, since Go
/// reuses the exact same mechanism, effectively also the fourth) of four
/// planned real interop bridges (Python (done), Rust + Go (this), JS/TS
/// - see CLAUDE.md). A plugin is any real shared library exporting
/// `nepali_plugin_call`/`nepali_plugin_free_string` with the exact
/// signatures `nepali-plugin-abi` defines - a real Rust `cdylib`
/// (`crates/nepali-example-plugin`) or a real `go build
/// -buildmode=c-shared` binary (`plugins/go-example`) both satisfy the
/// same C ABI, verified side by side against the identical loader.
/// `dlopen`ed at runtime by the host implementation (the CLI's
/// `libloading`-based `src/cli/host_rust.rs`), not linked at compile
/// time, so `.nep` code can load a plugin it didn't know about when
/// `nepali-core-cli` itself was built.
pub trait HostRust {
    /// Loads (or reuses an already-loaded) shared library at `lib_path`
    /// and calls its exported `fn_name` with `args`. Only
    /// `Number`/`Str`/`Bool`/`Null` values can cross this boundary -
    /// `Array`/`Function` arguments are a real, explicit error, the same
    /// honestly-scoped limit as `HostPython`'s conversion.
    fn call(&self, lib_path: &str, fn_name: &str, args: &[Value]) -> Result<Value, String>;
}

/// Real embedded JavaScript/TypeScript `.nep` code can reach through
/// `जेएस_चलाउनुहोस्`/`टिएस_चलाउनुहोस्` - the third of four planned real
/// interop bridges (Python, Rust (both done), JS/TS (this), Go - see
/// CLAUDE.md). Same dependency-injection reasoning as `HostPython`: a
/// real backend (the CLI's `rquickjs`-based implementation, a real
/// embedded QuickJS engine) implements this and is handed to the
/// interpreter via `set_host_js`. Unlike `HostPython`, no
/// `परिणाम`-variable convention is needed - a JS program's value is
/// genuinely the value of its last expression, so `eval` returns that
/// directly.
pub trait HostJs {
    fn eval(&self, code: &str) -> Result<Value, String>;
    /// Real TypeScript, not JS-with-types-that-happen-to-parse: type
    /// annotations, `interface`, `enum`, `as` casts, etc. are real
    /// syntax `eval` alone can't handle - a real implementation
    /// transpiles TS to JS first (via `swc`, a real, proven compiler,
    /// not a hand-rolled type-annotation stripper) and then runs the
    /// result through the exact same JS engine `eval` uses.
    fn eval_ts(&self, code: &str) -> Result<Value, String>;
}

/// A real cache server `.nep` code can reach through
/// `क्यास_राख्नुहोस्`/`क्यास_ल्याउनुहोस्`/`क्यास_हटाउनुहोस्` - second item
/// of the services roadmap (fileserver done first - see CLAUDE.md). Same
/// dependency-injection reasoning as `HostDb`: a real backend (the CLI's
/// implementation, a real `redis` crate client talking to a real
/// `redis-server` process over the network) implements this and is
/// handed to the interpreter via `set_host_cache` - not an in-process
/// `HashMap` pretending to be a cache server.
pub trait HostCache {
    /// Sets `key` to `value`. `ttl_seconds` of `0` means no expiry.
    fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> Result<(), String>;
    /// `Ok(None)` for a real cache miss (key absent or expired) - not an
    /// error, the same "empty means empty, not broken" reasoning as
    /// `HostChannel::recv`.
    fn get(&self, key: &str) -> Result<Option<String>, String>;
    fn delete(&self, key: &str) -> Result<(), String>;
}

/// A real, locally-running AI backend `.nep` code (and the interactive
/// shell) can reach through `एआई_सोध्नुहोस्`/`एआई_सुन्नुहोस्`/`एआई_बोल्नुहोस्`
/// - same dependency-injection reasoning as every other `Host*` trait:
/// `nepali-core` has no model runtime of its own, so a real backend (the
/// CLI's implementation, a real local LLM for text and a real local
/// speech model for voice - see CLAUDE.md for exactly which models and
/// their honest limitations) implements this and is handed to the
/// interpreter via `set_host_ai`. Deliberately three separate, narrow
/// operations rather than one do-everything call, matching how
/// `HostDb`/`HostCache` stay narrow too.
pub trait HostAi {
    /// Runs `prompt` through a real local language model and returns its
    /// real generated response (not a canned/templated string). A model
    /// too small or not fine-tuned for a language is a real, honest
    /// quality limitation of the underlying weights, not something this
    /// trait can paper over.
    fn ask(&self, prompt: &str) -> Result<String, String>;
    /// Real speech-to-text: `audio_path` names a real audio file on the
    /// host filesystem, transcribed by a real local speech model.
    fn listen(&self, audio_path: &str) -> Result<String, String>;
    /// Real text-to-speech: synthesizes `text` with a real local voice
    /// model and returns the path to the real audio file it wrote.
    fn speak(&self, text: &str) -> Result<String, String>;
}

pub struct Interpreter {
    pub output: Vec<String>,
    globals: Env,
    host_fs: Option<Rc<dyn HostFs>>,
    host_process: Option<Rc<dyn HostProcess>>,
    host_channel: Option<Rc<dyn HostChannel>>,
    host_db: Option<Rc<dyn HostDb>>,
    host_python: Option<Rc<dyn HostPython>>,
    host_rust: Option<Rc<dyn HostRust>>,
    host_js: Option<Rc<dyn HostJs>>,
    host_cache: Option<Rc<dyn HostCache>>,
    host_ai: Option<Rc<dyn HostAi>>,
    host_command: Option<Rc<dyn HostCommand>>,
}

impl Interpreter {
    pub fn new() -> Self {
        Interpreter {
            output: Vec::new(),
            globals: new_scope(None),
            host_fs: None,
            host_process: None,
            host_channel: None,
            host_db: None,
            host_python: None,
            host_rust: None,
            host_js: None,
            host_cache: None,
            host_ai: None,
            host_command: None,
        }
    }

    /// Gives this interpreter a real filesystem to reach through
    /// `ओएस_लेख्नुहोस्`/`ओएस_पढ्नुहोस्`/`ओएस_सूची`. Optional - an
    /// `Interpreter` with none still runs everything else normally, and
    /// those three builtins fail with a clear error instead of a panic
    /// or a silently-fake result.
    pub fn set_host_fs(&mut self, host_fs: Rc<dyn HostFs>) {
        self.host_fs = Some(host_fs);
    }

    /// Gives this interpreter a real process host to reach through
    /// `नयाँ_प्रक्रिया`/`प्रक्रिया_सूची`. Same optionality as `set_host_fs`.
    pub fn set_host_process(&mut self, host_process: Rc<dyn HostProcess>) {
        self.host_process = Some(host_process);
    }

    /// Gives this interpreter a real channel host to reach through
    /// `नयाँ_च्यानल`/`च्यानल_पठाउनुहोस्`/`च्यानल_पाउनुहोस्`. Same
    /// optionality as `set_host_fs`/`set_host_process`.
    pub fn set_host_channel(&mut self, host_channel: Rc<dyn HostChannel>) {
        self.host_channel = Some(host_channel);
    }

    /// Gives this interpreter a real database to reach through
    /// `डाटाबेस_चलाउनुहोस्`/`डाटाबेस_सोध्नुहोस्`. Same optionality as
    /// `set_host_fs`/`set_host_process`/`set_host_channel`.
    pub fn set_host_db(&mut self, host_db: Rc<dyn HostDb>) {
        self.host_db = Some(host_db);
    }

    /// Gives this interpreter a real embedded Python to reach through
    /// `पाइथन_चलाउनुहोस्`. Same optionality as every other `set_host_*`.
    pub fn set_host_python(&mut self, host_python: Rc<dyn HostPython>) {
        self.host_python = Some(host_python);
    }

    /// Gives this interpreter a real Rust-plugin loader to reach through
    /// `रस्ट_चलाउनुहोस्`. Same optionality as every other `set_host_*`.
    pub fn set_host_rust(&mut self, host_rust: Rc<dyn HostRust>) {
        self.host_rust = Some(host_rust);
    }

    /// Gives this interpreter a real embedded JS/TS engine to reach
    /// through `जेएस_चलाउनुहोस्`. Same optionality as every other
    /// `set_host_*`.
    pub fn set_host_js(&mut self, host_js: Rc<dyn HostJs>) {
        self.host_js = Some(host_js);
    }

    /// Gives this interpreter a real cache server to reach through
    /// `क्यास_राख्नुहोस्`/`क्यास_ल्याउनुहोस्`/`क्यास_हटाउनुहोस्`. Same
    /// optionality as every other `set_host_*`.
    pub fn set_host_cache(&mut self, host_cache: Rc<dyn HostCache>) {
        self.host_cache = Some(host_cache);
    }

    /// Gives this interpreter a real local AI backend to reach through
    /// `एआई_सोध्नुहोस्`/`एआई_सुन्नुहोस्`/`एआई_बोल्नुहोस्`. Same optionality as
    /// every other `set_host_*`.
    pub fn set_host_ai(&mut self, host_ai: Rc<dyn HostAi>) {
        self.host_ai = Some(host_ai);
    }

    /// Gives this interpreter a real command runner to reach through
    /// `आदेश_चलाउनुहोस्` (and the agent loop, `एजेन्ट_चलाउनुहोस्`, below).
    /// Same optionality as every other `set_host_*`.
    pub fn set_host_command(&mut self, host_command: Rc<dyn HostCommand>) {
        self.host_command = Some(host_command);
    }

    pub fn run(&mut self, program: &[Stmt]) -> EvalResult<()> {
        let env = self.globals.clone();
        match self.exec_block(program, &env)? {
            _ => Ok(()),
        }
    }

    fn exec_block(&mut self, stmts: &[Stmt], env: &Env) -> EvalResult<Signal> {
        for stmt in stmts {
            match self.exec_stmt(stmt, env)? {
                Signal::Normal => continue,
                ret @ Signal::Return(_) => return Ok(ret),
            }
        }
        Ok(Signal::Normal)
    }

    fn exec_stmt(&mut self, stmt: &Stmt, env: &Env) -> EvalResult<Signal> {
        match stmt {
            Stmt::Let(name, expr) => {
                let value = self.eval_expr(expr, env)?;
                env_define(env, name.clone(), value);
                Ok(Signal::Normal)
            }
            Stmt::Print(exprs) => {
                let mut parts = Vec::with_capacity(exprs.len());
                for expr in exprs {
                    parts.push(self.eval_expr(expr, env)?.display());
                }
                self.output.push(parts.join(" "));
                Ok(Signal::Normal)
            }
            Stmt::ExprStmt(expr) => {
                self.eval_expr(expr, env)?;
                Ok(Signal::Normal)
            }
            Stmt::If(cond, then_branch, else_branch) => {
                let cond_val = self.eval_expr(cond, env)?;
                if cond_val.is_truthy() {
                    let scope = new_scope(Some(env.clone()));
                    self.exec_block(then_branch, &scope)
                } else if let Some(else_branch) = else_branch {
                    let scope = new_scope(Some(env.clone()));
                    self.exec_block(else_branch, &scope)
                } else {
                    Ok(Signal::Normal)
                }
            }
            Stmt::While(cond, body) => {
                while self.eval_expr(cond, env)?.is_truthy() {
                    let scope = new_scope(Some(env.clone()));
                    match self.exec_block(body, &scope)? {
                        Signal::Normal => continue,
                        ret @ Signal::Return(_) => return Ok(ret),
                    }
                }
                Ok(Signal::Normal)
            }
            Stmt::FunctionDecl(name, params, body) => {
                let func = Value::Function(Rc::new(FunctionValue {
                    name: name.clone(),
                    params: params.clone(),
                    body: body.clone(),
                    closure: env.clone(),
                }));
                env_define(env, name.clone(), func);
                Ok(Signal::Normal)
            }
            Stmt::Return(expr) => {
                let value = match expr {
                    Some(e) => self.eval_expr(e, env)?,
                    None => Value::Null,
                };
                Ok(Signal::Return(value))
            }
            Stmt::Import(path) => Err(format!(
                "import \"{}\" reached the interpreter unresolved - imports must be \
                 resolved by a host loader (e.g. nepali-core-cli's loader module) before running",
                path
            )),
        }
    }

    fn eval_expr(&mut self, expr: &Expr, env: &Env) -> EvalResult<Value> {
        match expr {
            Expr::Number(n) => Ok(Value::Number(*n)),
            Expr::StringLit(s) => Ok(Value::Str(s.clone())),
            Expr::Bool(b) => Ok(Value::Bool(*b)),
            Expr::Null => Ok(Value::Null),
            Expr::Ident(name) => {
                env_get(env, name).ok_or_else(|| format!("undefined variable '{}'", name))
            }
            Expr::Neg(inner) => {
                let v = self.eval_expr(inner, env)?;
                match v {
                    Value::Number(n) => Ok(Value::Number(-n)),
                    other => Err(format!("cannot negate {}", other.display())),
                }
            }
            Expr::Not(inner) => {
                let v = self.eval_expr(inner, env)?;
                Ok(Value::Bool(!v.is_truthy()))
            }
            Expr::Assign(name, value_expr) => {
                let value = self.eval_expr(value_expr, env)?;
                env_assign(env, name, value.clone())?;
                Ok(value)
            }
            Expr::ArrayLit(elements) => {
                let mut values = Vec::with_capacity(elements.len());
                for e in elements {
                    values.push(self.eval_expr(e, env)?);
                }
                Ok(Value::Array(Rc::new(RefCell::new(values))))
            }
            Expr::Index(object, index) => {
                let obj = self.eval_expr(object, env)?;
                let idx = self.eval_expr(index, env)?;
                let arr = expect_array(&obj)?;
                let i = expect_index(&idx, arr.borrow().len())?;
                let value = arr.borrow()[i].clone();
                Ok(value)
            }
            Expr::IndexAssign(object, index, value_expr) => {
                let obj = self.eval_expr(object, env)?;
                let idx = self.eval_expr(index, env)?;
                let value = self.eval_expr(value_expr, env)?;
                let arr = expect_array(&obj)?;
                let i = expect_index(&idx, arr.borrow().len())?;
                arr.borrow_mut()[i] = value.clone();
                Ok(value)
            }
            // Short-circuit: the right operand is only evaluated when the
            // left doesn't already decide the result, so any side effect
            // in it (a call, an assignment) genuinely doesn't run - not
            // just "returns the right answer regardless," an observable
            // difference for real programs, not just an optimization.
            Expr::Binary(BinOp::And, left, right) => {
                let l = self.eval_expr(left, env)?;
                if !l.is_truthy() {
                    return Ok(Value::Bool(false));
                }
                let r = self.eval_expr(right, env)?;
                Ok(Value::Bool(r.is_truthy()))
            }
            Expr::Binary(BinOp::Or, left, right) => {
                let l = self.eval_expr(left, env)?;
                if l.is_truthy() {
                    return Ok(Value::Bool(true));
                }
                let r = self.eval_expr(right, env)?;
                Ok(Value::Bool(r.is_truthy()))
            }
            Expr::Binary(op, left, right) => {
                let l = self.eval_expr(left, env)?;
                let r = self.eval_expr(right, env)?;
                self.eval_binary(op, l, r)
            }
            Expr::Call(callee, arg_exprs) => {
                if let Expr::Ident(name) = callee.as_ref() {
                    if is_host_fs_builtin(name)
                        || is_host_process_builtin(name)
                        || is_host_channel_builtin(name)
                        || is_host_db_builtin(name)
                        || is_host_python_builtin(name)
                        || is_host_rust_builtin(name)
                        || is_host_js_builtin(name)
                        || is_host_cache_builtin(name)
                        || is_host_ai_builtin(name)
                        || is_host_command_builtin(name)
                        || is_agent_builtin(name)
                        || is_builtin(name)
                    {
                        let mut args = Vec::with_capacity(arg_exprs.len());
                        for a in arg_exprs {
                            args.push(self.eval_expr(a, env)?);
                        }
                        return self.dispatch_builtin(name, &args);
                    }
                }
                let callee_val = self.eval_expr(callee, env)?;
                let mut args = Vec::with_capacity(arg_exprs.len());
                for a in arg_exprs {
                    args.push(self.eval_expr(a, env)?);
                }
                self.call(callee_val, args)
            }
        }
    }

    /// Single dispatch point for every kind of builtin (real host
    /// filesystem, real host process manager, or the plain
    /// string/array ones with no host dependency) - one place, called
    /// once args are already evaluated, rather than three separate
    /// call sites each re-deciding which category `name` falls into.
    fn dispatch_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        if is_host_fs_builtin(name) {
            return self.call_host_fs_builtin(name, args);
        }
        if is_host_process_builtin(name) {
            return self.call_host_process_builtin(name, args);
        }
        if is_host_channel_builtin(name) {
            return self.call_host_channel_builtin(name, args);
        }
        if is_host_db_builtin(name) {
            return self.call_host_db_builtin(name, args);
        }
        if is_host_python_builtin(name) {
            return self.call_host_python_builtin(name, args);
        }
        if is_host_rust_builtin(name) {
            return self.call_host_rust_builtin(name, args);
        }
        if is_host_js_builtin(name) {
            return self.call_host_js_builtin(name, args);
        }
        if is_host_cache_builtin(name) {
            return self.call_host_cache_builtin(name, args);
        }
        if is_host_ai_builtin(name) {
            return self.call_host_ai_builtin(name, args);
        }
        if is_host_command_builtin(name) {
            return self.call_host_command_builtin(name, args);
        }
        if is_agent_builtin(name) {
            return self.call_agent_builtin(name, args);
        }
        call_builtin(name, args)
    }

    fn call_host_fs_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_fs.clone().ok_or_else(|| {
            format!(
                "'{}' needs a host filesystem, which isn't available here \
                 (no disk mounted, or running somewhere with no real filesystem at all)",
                name
            )
        })?;
        match name {
            "ओएस_लेख्नुहोस्" => {
                let path = expect_string(name, args, 0)?;
                let contents = expect_string(name, args, 1)?;
                host.write_file(&path, &contents)?;
                Ok(Value::Null)
            }
            "ओएस_पढ्नुहोस्" => {
                let path = expect_string(name, args, 0)?;
                let contents = host.read_file(&path)?;
                Ok(Value::Str(contents))
            }
            "ओएस_सूची" => {
                let path = expect_string(name, args, 0)?;
                let entries = host.list_dir(&path)?;
                let values: Vec<Value> = entries.into_iter().map(Value::Str).collect();
                Ok(Value::Array(Rc::new(RefCell::new(values))))
            }
            _ => unreachable!("is_host_fs_builtin only admits the three names handled above"),
        }
    }

    fn call_host_process_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_process.clone().ok_or_else(|| {
            format!(
                "'{}' needs a host process manager, which isn't available here \
                 (running somewhere with no real process scheduler at all)",
                name
            )
        })?;
        match name {
            "नयाँ_प्रक्रिया" => {
                let proc_name = expect_string(name, args, 0)?;
                let pid = host.spawn(&proc_name)?;
                Ok(Value::Number(pid))
            }
            "प्रक्रिया_सूची" => {
                let names = host.list()?;
                let values: Vec<Value> = names.into_iter().map(Value::Str).collect();
                Ok(Value::Array(Rc::new(RefCell::new(values))))
            }
            _ => unreachable!("is_host_process_builtin only admits the two names handled above"),
        }
    }

    fn call_host_channel_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_channel.clone().ok_or_else(|| {
            format!(
                "'{}' needs a host channel manager, which isn't available here \
                 (running somewhere with no real channel mechanism at all)",
                name
            )
        })?;
        match name {
            "नयाँ_च्यानल" => {
                let id = host.create()?;
                Ok(Value::Number(id))
            }
            "च्यानल_पठाउनुहोस्" => {
                let id = expect_number(name, args, 0)?;
                let msg = expect_string(name, args, 1)?;
                host.send(id, &msg)?;
                Ok(Value::Null)
            }
            "च्यानल_पाउनुहोस्" => {
                let id = expect_number(name, args, 0)?;
                match host.recv(id)? {
                    Some(msg) => Ok(Value::Str(msg)),
                    None => Ok(Value::Null),
                }
            }
            _ => unreachable!("is_host_channel_builtin only admits the three names handled above"),
        }
    }

    fn call_host_db_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_db.clone().ok_or_else(|| {
            format!(
                "'{}' needs a host database, which isn't available here \
                 (running somewhere with no real database connection at all)",
                name
            )
        })?;
        match name {
            "डाटाबेस_चलाउनुहोस्" => {
                let sql = expect_string(name, args, 0)?;
                let affected = host.execute(&sql)?;
                Ok(Value::Number(affected))
            }
            "डाटाबेस_सोध्नुहोस्" => {
                let sql = expect_string(name, args, 0)?;
                let rows = host.query(&sql)?;
                Ok(Value::Array(Rc::new(RefCell::new(rows))))
            }
            _ => unreachable!("is_host_db_builtin only admits the two names handled above"),
        }
    }

    fn call_host_python_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_python.clone().ok_or_else(|| {
            format!(
                "'{}' needs an embedded Python, which isn't available here \
                 (running somewhere with no real Python interpreter linked in)",
                name
            )
        })?;
        match name {
            "पाइथन_चलाउनुहोस्" => {
                let code = expect_string(name, args, 0)?;
                host.eval(&code)
            }
            _ => unreachable!("is_host_python_builtin only admits the one name handled above"),
        }
    }

    fn call_host_rust_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_rust.clone().ok_or_else(|| {
            format!(
                "'{}' needs a real native-plugin loader, which isn't available here",
                name
            )
        })?;
        match name {
            // Two names, one real mechanism: a `go build
            // -buildmode=c-shared` binary satisfying the exact same
            // nepali-plugin-abi contract as a real Rust cdylib loads and
            // runs through this same dlopen call - verified live with
            // `crates/nepali-example-plugin` (Rust) and
            // `plugins/go-example` (Go) side by side, see CLAUDE.md.
            // गो_चलाउनुहोस् exists for real Go-code UX, not as a second
            // implementation pretending to be separate.
            "रस्ट_चलाउनुहोस्" | "गो_चलाउनुहोस्" => {
                let lib_path = expect_string(name, args, 0)?;
                let fn_name = expect_string(name, args, 1)?;
                // Safe: expect_string above already errored out if
                // args.len() < 2, so this slice is always in bounds.
                host.call(&lib_path, &fn_name, &args[2..])
            }
            _ => unreachable!("is_host_rust_builtin only admits the two names handled above"),
        }
    }

    fn call_host_js_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_js.clone().ok_or_else(|| {
            format!(
                "'{}' needs an embedded JS/TS engine, which isn't available here",
                name
            )
        })?;
        match name {
            "जेएस_चलाउनुहोस्" => {
                let code = expect_string(name, args, 0)?;
                host.eval(&code)
            }
            "टिएस_चलाउनुहोस्" => {
                let code = expect_string(name, args, 0)?;
                host.eval_ts(&code)
            }
            _ => unreachable!("is_host_js_builtin only admits the two names handled above"),
        }
    }

    fn call_host_cache_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_cache.clone().ok_or_else(|| {
            format!(
                "'{}' needs a real cache server, which isn't available here \
                 (no redis-server connection)",
                name
            )
        })?;
        match name {
            "क्यास_राख्नुहोस्" => {
                let key = expect_string(name, args, 0)?;
                let value = expect_string(name, args, 1)?;
                let ttl = if args.len() > 2 { expect_number(name, args, 2)? } else { 0.0 };
                host.set(&key, &value, ttl.max(0.0) as u64)?;
                Ok(Value::Null)
            }
            "क्यास_ल्याउनुहोस्" => {
                let key = expect_string(name, args, 0)?;
                match host.get(&key)? {
                    Some(v) => Ok(Value::Str(v)),
                    None => Ok(Value::Null),
                }
            }
            "क्यास_हटाउनुहोस्" => {
                let key = expect_string(name, args, 0)?;
                host.delete(&key)?;
                Ok(Value::Null)
            }
            _ => unreachable!("is_host_cache_builtin only admits the three names handled above"),
        }
    }

    fn call_host_ai_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_ai.clone().ok_or_else(|| {
            format!(
                "'{}' needs a real local AI backend, which isn't available here \
                 (no model loaded)",
                name
            )
        })?;
        match name {
            "एआई_सोध्नुहोस्" => {
                let prompt = expect_string(name, args, 0)?;
                let response = host.ask(&prompt)?;
                Ok(Value::Str(response))
            }
            "एआई_सुन्नुहोस्" => {
                let audio_path = expect_string(name, args, 0)?;
                let text = host.listen(&audio_path)?;
                Ok(Value::Str(text))
            }
            "एआई_बोल्नुहोस्" => {
                let text = expect_string(name, args, 0)?;
                let out_path = host.speak(&text)?;
                Ok(Value::Str(out_path))
            }
            _ => unreachable!("is_host_ai_builtin only admits the three names handled above"),
        }
    }

    fn call_host_command_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        let host = self.host_command.clone().ok_or_else(|| {
            format!(
                "'{}' needs a real command runner, which isn't available here",
                name
            )
        })?;
        match name {
            "आदेश_चलाउनुहोस्" => {
                let program = expect_string(name, args, 0)?;
                let cmd_args = if args.len() > 1 {
                    let arr = expect_array(&args[1])?;
                    let arr = arr.borrow();
                    let mut out = Vec::with_capacity(arr.len());
                    for v in arr.iter() {
                        match v {
                            Value::Str(s) => out.push(s.clone()),
                            other => {
                                return Err(format!(
                                    "'{}' expects an array of strings as argument 2, got {}",
                                    name,
                                    other.display()
                                ))
                            }
                        }
                    }
                    out
                } else {
                    Vec::new()
                };
                let (exit_code, stdout, stderr) = host.run(&program, &cmd_args)?;
                let result = alloc::vec![
                    Value::Number(exit_code as f64),
                    Value::Str(stdout),
                    Value::Str(stderr),
                ];
                Ok(Value::Array(Rc::new(RefCell::new(result))))
            }
            _ => unreachable!("is_host_command_builtin only admits the one name handled above"),
        }
    }

    fn call_agent_builtin(&mut self, name: &str, args: &[Value]) -> EvalResult<Value> {
        match name {
            "एजेन्ट_चलाउनुहोस्" => {
                let goal = expect_string(name, args, 0)?;
                let max_steps = if args.len() > 1 {
                    expect_number(name, args, 1)?.max(1.0) as usize
                } else {
                    6
                };
                let answer = self.run_agent(&goal, max_steps)?;
                Ok(Value::Str(answer))
            }
            _ => unreachable!("is_agent_builtin only admits the one name handled above"),
        }
    }

    /// A real, if simple, tool-using agent loop for `एजेन्ट_चलाउनुहोस्`:
    /// the AI proposes one real action per turn from a small fixed
    /// toolset (read/write/list a file, run a real command), this
    /// interpreter actually executes it through the exact same `Host*`
    /// implementations every other builtin uses, and the real result is
    /// fed back for the next turn - not a simulated conversation, a real
    /// loop that really touches the filesystem and really runs
    /// commands. Deliberately a tiny, explicit line-based protocol
    /// (`कार्य: name(args)` / `अन्तिम: answer`) instead of JSON
    /// tool-calling: no JSON parser exists in this `no_std`+`alloc`
    /// crate, and a plain-text protocol is also more forgiving of a
    /// small model's imperfect formatting, which matters given how weak
    /// small open models' structured-output reliability still is (see
    /// CLAUDE.md's `एआई_सोध्नुहोस्` findings).
    fn run_agent(&mut self, goal: &str, max_steps: usize) -> EvalResult<String> {
        let host_ai = self.host_ai.clone().ok_or_else(|| {
            "एजेन्ट_चलाउनुहोस् needs a real local AI backend, which isn't available here"
                .to_string()
        })?;

        let mut transcript = format!(
            "You are an OS agent for Nepali OS. Respond with EXACTLY one line, one of:\n\
             कार्य: TOOL(args)\n\
             अन्तिम: your final answer\n\n\
             Available tools:\n\
             - फाइल_पढ्नुहोस्(path) - reads a real file\n\
             - फाइल_लेख्नुहोस्(path, contents) - writes a real file\n\
             - सूची(path) - lists a real directory\n\
             - आदेश(program, arg1, arg2, ...) - runs a real command, returns its exit code and output\n\n\
             Example:\n\
             Goal: read /tmp/x.txt and tell me what it says\n\
             कार्य: फाइल_पढ्नुहोस्(/tmp/x.txt)\n\
             नतिजा: hello world\n\
             अन्तिम: The file says \"hello world\".\n\n\
             Now the real task.\n\
             Goal: {goal}\n\n\
             Respond with exactly one line, starting with either कार्य: or अन्तिम: - nothing else.\n"
        );

        let mut last_action: Option<String> = None;

        for step in 0..max_steps {
            let response = host_ai.ask(&transcript)?;
            let line: String = response
                .lines()
                .find(|l| !l.trim().is_empty())
                .unwrap_or("")
                .trim()
                .to_string();

            if let Some(answer) = line.strip_prefix("अन्तिम:") {
                return Ok(answer.trim().to_string());
            }

            let Some(action) = line.strip_prefix("कार्य:") else {
                // The model's own malformed line is still appended below -
                // without it, the transcript loses the record of what the
                // assistant just said, and it loses track of turn
                // structure (a real bug found and fixed: an agent that
                // forgets its own last turn just re-completes the last
                // pattern it can see instead of moving forward).
                transcript.push_str(&format!(
                    "\n{line}\n\nत्रुटि: अपेक्षित 'कार्य:' वा 'अन्तिम:' बाट सुरु हुने लाइन। \
                     पुन: प्रयास गर्नुहोस्:\n"
                ));
                continue;
            };
            let action = action.trim();

            // A real, honest safeguard for a real, observed small-model
            // failure mode: a weak model can get stuck re-proposing the
            // identical action forever instead of ever switching to
            // अन्तिम: once it already has the answer (see CLAUDE.md -
            // reproduced live with the same small Qwen2.5-0.5B checkpoint
            // used to verify एआई_सोध्नुहोस्). Rather than burn the rest
            // of `max_steps` re-running (and re-asking about) a call
            // already known, stop with the real result already in hand -
            // graceful degradation, not a second AI call pretending to
            // "decide" this is the end.
            if last_action.as_deref() == Some(action) {
                let result = self.execute_agent_action(action);
                return Ok(format!(
                    "(दोहोरिएको कार्य पत्ता लाग्यो, यसैले रोकियो; अन्तिम नतिजा: {result})"
                ));
            }
            last_action = Some(action.to_string());

            let result = self.execute_agent_action(action);
            let is_last = step == max_steps - 1;
            if is_last {
                return Ok(format!(
                    "(अधिकतम चरण पुग्यो, अन्तिम जवाफ बिना; अन्तिम नतिजा: {result})"
                ));
            }
            transcript.push_str(&format!(
                "\n{line}\nनतिजा: {result}\n\nअर्को कार्य वा अन्तिम जवाफ दिनुहोस्:\n"
            ));
        }
        Ok("(कुनै जवाफ आएन)".to_string())
    }

    /// Parses `name(arg1, arg2, ...)` and dispatches to the one real
    /// tool it names, via the exact same `Host*` implementations every
    /// other builtin uses - not a second, separate implementation of
    /// file/command access. Never propagates an `Err` to its caller: any
    /// failure (unknown tool, bad syntax, a real filesystem/command
    /// error) becomes a real error *string* fed back into the
    /// transcript, so the model gets a chance to recover instead of the
    /// whole agent run aborting on one bad step.
    fn execute_agent_action(&mut self, action: &str) -> String {
        let Some(open) = action.find('(') else {
            return format!("त्रुटि: '{action}' मा '(' फेला परेन");
        };
        let Some(close) = action.rfind(')') else {
            return format!("त्रुटि: '{action}' मा ')' फेला परेन");
        };
        if close < open {
            return format!("त्रुटि: '{action}' मा कोष्ठक मिलेन");
        }
        let tool = action[..open].trim();
        let args_str = &action[open + 1..close];
        let raw_args: Vec<String> = if args_str.trim().is_empty() {
            Vec::new()
        } else {
            args_str
                .split(',')
                .map(|a| a.trim().trim_matches('"').trim_matches('\'').to_string())
                .collect()
        };

        match tool {
            "फाइल_पढ्नुहोस्" => {
                let Some(host) = self.host_fs.clone() else {
                    return "त्रुटि: कुनै वास्तविक फाइलसिस्टम उपलब्ध छैन".to_string();
                };
                let Some(path) = raw_args.first() else {
                    return "त्रुटि: फाइल_पढ्नुहोस् लाई path चाहिन्छ".to_string();
                };
                match host.read_file(path) {
                    Ok(contents) => contents,
                    Err(e) => format!("त्रुटि: {e}"),
                }
            }
            "फाइल_लेख्नुहोस्" => {
                let Some(host) = self.host_fs.clone() else {
                    return "त्रुटि: कुनै वास्तविक फाइलसिस्टम उपलब्ध छैन".to_string();
                };
                if raw_args.len() < 2 {
                    return "त्रुटि: फाइल_लेख्नुहोस् लाई path र contents चाहिन्छ".to_string();
                }
                match host.write_file(&raw_args[0], &raw_args[1]) {
                    Ok(()) => "ठिक छ".to_string(),
                    Err(e) => format!("त्रुटि: {e}"),
                }
            }
            "सूची" => {
                let Some(host) = self.host_fs.clone() else {
                    return "त्रुटि: कुनै वास्तविक फाइलसिस्टम उपलब्ध छैन".to_string();
                };
                let Some(path) = raw_args.first() else {
                    return "त्रुटि: सूची लाई path चाहिन्छ".to_string();
                };
                match host.list_dir(path) {
                    Ok(entries) => entries.join(", "),
                    Err(e) => format!("त्रुटि: {e}"),
                }
            }
            "आदेश" => {
                let Some(host) = self.host_command.clone() else {
                    return "त्रुटि: कुनै वास्तविक आदेश-चालक उपलब्ध छैन".to_string();
                };
                let Some(program) = raw_args.first() else {
                    return "त्रुटि: आदेश लाई program चाहिन्छ".to_string();
                };
                let cmd_args = raw_args[1..].to_vec();
                match host.run(program, &cmd_args) {
                    Ok((code, stdout, stderr)) => {
                        format!("exit={code}\nstdout: {stdout}\nstderr: {stderr}")
                    }
                    Err(e) => format!("त्रुटि: {e}"),
                }
            }
            other => format!("त्रुटि: अज्ञात औजार '{other}'"),
        }
    }

    fn call(&mut self, callee: Value, args: Vec<Value>) -> EvalResult<Value> {
        let func = match callee {
            Value::Function(f) => f,
            other => return Err(format!("'{}' is not callable", other.display())),
        };
        if args.len() != func.params.len() {
            return Err(format!(
                "function '{}' expects {} argument(s), got {}",
                func.name,
                func.params.len(),
                args.len()
            ));
        }
        let call_scope = new_scope(Some(func.closure.clone()));
        for (param, arg) in func.params.iter().zip(args.into_iter()) {
            env_define(&call_scope, param.clone(), arg);
        }
        match self.exec_block(&func.body, &call_scope)? {
            Signal::Return(v) => Ok(v),
            Signal::Normal => Ok(Value::Null),
        }
    }

    fn eval_binary(&self, op: &BinOp, l: Value, r: Value) -> EvalResult<Value> {
        use BinOp::*;
        match op {
            Add => match (&l, &r) {
                (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
                _ => Ok(Value::Str(format!("{}{}", l.display(), r.display()))),
            },
            Sub | Mul | Div | Mod => {
                let (a, b) = match (&l, &r) {
                    (Value::Number(a), Value::Number(b)) => (*a, *b),
                    _ => {
                        return Err(format!(
                            "arithmetic on non-numbers: {} and {}",
                            l.display(),
                            r.display()
                        ))
                    }
                };
                match op {
                    Sub => Ok(Value::Number(a - b)),
                    Mul => Ok(Value::Number(a * b)),
                    Div => Ok(Value::Number(a / b)),
                    Mod => Ok(Value::Number(a % b)),
                    _ => unreachable!(),
                }
            }
            Eq => Ok(Value::Bool(values_equal(&l, &r))),
            NotEq => Ok(Value::Bool(!values_equal(&l, &r))),
            Lt | Gt | Lte | Gte => {
                let (a, b) = match (&l, &r) {
                    (Value::Number(a), Value::Number(b)) => (*a, *b),
                    _ => {
                        return Err(format!(
                            "comparison on non-numbers: {} and {}",
                            l.display(),
                            r.display()
                        ))
                    }
                };
                let result = match op {
                    Lt => a < b,
                    Gt => a > b,
                    Lte => a <= b,
                    Gte => a >= b,
                    _ => unreachable!(),
                };
                Ok(Value::Bool(result))
            }
            And | Or => unreachable!(
                "Expr::Binary(And|Or, ..) is intercepted in eval_expr for short-circuiting \
                 before it ever reaches eval_binary"
            ),
        }
    }
}

impl Default for Interpreter {
    fn default() -> Self {
        Self::new()
    }
}

fn values_equal(l: &Value, r: &Value) -> bool {
    match (l, r) {
        (Value::Number(a), Value::Number(b)) => a == b,
        (Value::Str(a), Value::Str(b)) => a == b,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Null, Value::Null) => true,
        (Value::Array(a), Value::Array(b)) => {
            // Structural equality (same length, equal elements pairwise),
            // not reference identity - matches how Str/Number/Bool
            // equality already works here, and is the less surprising
            // default (`[1,2] == [1,2]` reads as true to anyone who
            // hasn't been told this language uses reference semantics for
            // arrays internally).
            let a = a.borrow();
            let b = b.borrow();
            a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| values_equal(x, y))
        }
        _ => false,
    }
}

fn expect_array(v: &Value) -> EvalResult<Rc<RefCell<Vec<Value>>>> {
    match v {
        Value::Array(a) => Ok(a.clone()),
        other => Err(format!("'{}' is not an array", other.display())),
    }
}

fn expect_index(v: &Value, len: usize) -> EvalResult<usize> {
    match v {
        Value::Number(n) => {
            let i = *n as i64;
            if i < 0 || i as usize >= len {
                Err(format!(
                    "array index {} out of bounds (length {})",
                    i, len
                ))
            } else {
                Ok(i as usize)
            }
        }
        other => Err(format!("array index must be a number, got {}", other.display())),
    }
}

/// A small set of native builtins - not user-declarable functions, and
/// deliberately not going through `env`/closures at all. These exist to
/// unblock real string/character inspection: without them, a `.nep`
/// program has no way to look at individual characters of a string, which
/// makes writing anything like a lexer *in* nepali (roadmap lang step 5,
/// self-hosting) impossible - there was nothing to index into text with.
/// Counted in Unicode scalar values (`char`s), not bytes, so indices work
/// correctly over multi-byte Devanagari text, not just ASCII.
pub const BUILTINS: &[&str] = &[
    "लम्बाइ",
    "अक्षर",
    "संकेत",
    "थप्नुहोस्",
    "ओएस_लेख्नुहोस्",
    "ओएस_पढ्नुहोस्",
    "ओएस_सूची",
    "नयाँ_प्रक्रिया",
    "प्रक्रिया_सूची",
    "नयाँ_च्यानल",
    "च्यानल_पठाउनुहोस्",
    "च्यानल_पाउनुहोस्",
    "डाटाबेस_चलाउनुहोस्",
    "डाटाबेस_सोध्नुहोस्",
    "पाइथन_चलाउनुहोस्",
    "रस्ट_चलाउनुहोस्",
    "गो_चलाउनुहोस्",
    "जेएस_चलाउनुहोस्",
    "टिएस_चलाउनुहोस्",
    "क्यास_राख्नुहोस्",
    "क्यास_ल्याउनुहोस्",
    "क्यास_हटाउनुहोस्",
    "एआई_सोध्नुहोस्",
    "एआई_सुन्नुहोस्",
    "एआई_बोल्नुहोस्",
    "आदेश_चलाउनुहोस्",
    "एजेन्ट_चलाउनुहोस्",
];

pub fn is_builtin(name: &str) -> bool {
    BUILTINS.contains(&name)
}

fn is_host_fs_builtin(name: &str) -> bool {
    matches!(name, "ओएस_लेख्नुहोस्" | "ओएस_पढ्नुहोस्" | "ओएस_सूची")
}

fn is_host_process_builtin(name: &str) -> bool {
    matches!(name, "नयाँ_प्रक्रिया" | "प्रक्रिया_सूची")
}

fn is_host_channel_builtin(name: &str) -> bool {
    matches!(
        name,
        "नयाँ_च्यानल" | "च्यानल_पठाउनुहोस्" | "च्यानल_पाउनुहोस्"
    )
}

fn is_host_db_builtin(name: &str) -> bool {
    matches!(name, "डाटाबेस_चलाउनुहोस्" | "डाटाबेस_सोध्नुहोस्")
}

fn is_host_python_builtin(name: &str) -> bool {
    matches!(name, "पाइथन_चलाउनुहोस्")
}

fn is_host_rust_builtin(name: &str) -> bool {
    matches!(name, "रस्ट_चलाउनुहोस्" | "गो_चलाउनुहोस्")
}

fn is_host_js_builtin(name: &str) -> bool {
    matches!(name, "जेएस_चलाउनुहोस्" | "टिएस_चलाउनुहोस्")
}

fn is_host_cache_builtin(name: &str) -> bool {
    matches!(name, "क्यास_राख्नुहोस्" | "क्यास_ल्याउनुहोस्" | "क्यास_हटाउनुहोस्")
}

fn is_host_ai_builtin(name: &str) -> bool {
    matches!(name, "एआई_सोध्नुहोस्" | "एआई_सुन्नुहोस्" | "एआई_बोल्नुहोस्")
}

fn is_host_command_builtin(name: &str) -> bool {
    matches!(name, "आदेश_चलाउनुहोस्")
}

fn is_agent_builtin(name: &str) -> bool {
    matches!(name, "एजेन्ट_चलाउनुहोस्")
}

pub fn call_builtin(name: &str, args: &[Value]) -> EvalResult<Value> {
    match name {
        "लम्बाइ" => match args.first() {
            Some(Value::Str(s)) => Ok(Value::Number(s.chars().count() as f64)),
            Some(Value::Array(a)) => Ok(Value::Number(a.borrow().len() as f64)),
            Some(other) => Err(format!(
                "'{}' expects a string or array, got {}",
                name,
                other.display()
            )),
            None => Err(format!("'{}' expects an argument at position 1", name)),
        },
        "थप्नुहोस्" => {
            let arr = match args.first() {
                Some(Value::Array(a)) => a.clone(),
                Some(other) => {
                    return Err(format!(
                        "'{}' expects an array at argument 1, got {}",
                        name,
                        other.display()
                    ))
                }
                None => return Err(format!("'{}' expects an argument at position 1", name)),
            };
            let value = args
                .get(1)
                .cloned()
                .ok_or_else(|| format!("'{}' expects an argument at position 2", name))?;
            arr.borrow_mut().push(value);
            Ok(Value::Null)
        }
        "अक्षर" => {
            let s = expect_string(name, args, 0)?;
            let i = expect_number(name, args, 1)? as i64;
            if i < 0 {
                return Ok(Value::Str(String::new()));
            }
            match s.chars().nth(i as usize) {
                Some(c) => Ok(Value::Str(c.to_string())),
                None => Ok(Value::Str(String::new())),
            }
        }
        "संकेत" => {
            let s = expect_string(name, args, 0)?;
            let mut chars = s.chars();
            match (chars.next(), chars.next()) {
                (Some(c), None) => Ok(Value::Number(c as u32 as f64)),
                _ => Err(format!(
                    "'{}' expects a single-character string, got \"{}\"",
                    name, s
                )),
            }
        }
        other => Err(format!("unknown builtin '{}'", other)),
    }
}

fn expect_string(fn_name: &str, args: &[Value], idx: usize) -> EvalResult<String> {
    match args.get(idx) {
        Some(Value::Str(s)) => Ok(s.clone()),
        Some(other) => Err(format!(
            "'{}' expects a string at argument {}, got {}",
            fn_name,
            idx + 1,
            other.display()
        )),
        None => Err(format!("'{}' expects an argument at position {}", fn_name, idx + 1)),
    }
}

fn expect_number(fn_name: &str, args: &[Value], idx: usize) -> EvalResult<f64> {
    match args.get(idx) {
        Some(Value::Number(n)) => Ok(*n),
        Some(other) => Err(format!(
            "'{}' expects a number at argument {}, got {}",
            fn_name,
            idx + 1,
            other.display()
        )),
        None => Err(format!("'{}' expects an argument at position {}", fn_name, idx + 1)),
    }
}