aboutsummaryrefslogtreecommitdiff
path: root/modules/core/module-fs.js
blob: f93553af2988ba72780be885ff7940bcf33b3467 (plain)
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
class FileSystemModule {
    constructor() { this.commands = {}; this.commandsMeta = {
        'trash': { argType: 'file' }, 'ls-trash': { argType: 'file' },
        'upload': { argType: 'dir' }, 'vfs-export': { argType: 'file' },
        'vfs-import': { argType: 'file' }, 'download': { argType: 'file' },
    }; this.terminal = null; }
    getHelpInfo() {
        return {
            'ls': 'ls [path] [-la] — List files and directories',
            'cat': 'cat <file> — Display file contents',
            'put': 'put <file> <content> — Create or overwrite a file',
            'rm': 'rm <file> — Remove a file (moved to trash); use -r/-rf for directories',
            'trash': 'trash <file> — Move a file to trash',
            'trash-dir': 'trash-dir <dir> — Move a directory to trash',
            'ls-trash': 'ls-trash — List items in trash',
            'empty-trash': 'empty-trash — Permanently delete all trash items',
            'mkdir': 'mkdir <dir> [-p] — Create a directory; -p creates parent paths',
            'rmdir': 'rmdir <dir> — Remove a directory',
            'mv': 'mv <source> <dest> — Move file or directory',
            'cp': 'cp <source> <dest> — Copy file or directory',
            'cd': 'cd <path> — Change current directory; cd / to go to root',
            'pwd': 'pwd — Print current working directory',
            'find': 'find <pattern> — Search files by name pattern',
            'grep': 'grep <pattern> [file] — Search file content for pattern',
            'head': 'head <file> [lines] — Show first N lines (default: 10)',
            'tail': 'tail [-f] [-n N] <file> — Show last N lines; -f follows live changes (Ctrl+C/Esc to stop)',
            'sed': 'sed <expr> [file] — Stream editor; s/pat/rep/[g][i][p], /pat/d, Nd, $d; -i write in place; -n quiet mode',
            'sort': 'sort <file> — Sort lines of a file alphabetically',
            'wc': 'wc <file> — Count lines, words, and bytes',
            'touch': 'touch <file> — Create empty file or update timestamp',
            'tree': 'tree — Display directory structure as a tree',
            'du': 'du [path] — Estimate file/directory size',
            'upload': 'upload — Upload a file from your device',
            'download': 'download <file> — Download a file to your device',
            'vfs-export': 'vfs-export — Export the entire virtual filesystem as JSON',
            'vfs-import': 'vfs-import — Import a previously exported VFS JSON file',
            'session-save': 'session-save <name> — Save current session (path + terminal history)',
            'session-load': 'session-load <name> — Load a saved session',
            'session-list': 'session-list — List all saved sessions',
            'session-new': 'session-new — Start a fresh session (auto-saves current, clears AI context)',
            'session-delete': 'session-delete <name> — Delete a saved session',
        };
    }
    registerCommands() {
        const self = this;
        this.commands['ls'] = (args) => {
            const target = args && args.length > 0 && !args[0].startsWith('-') ? args[0] : undefined;
            const flags = (args || []).filter(a => a.startsWith('-'));
            const showLong = flags.some(f => f.includes('l'));
            const showHidden = flags.some(f => f.includes('a'));
            const files = this.terminal.fs.ls(target);
            if (!files || files.length === 0) { this.terminal.print('(empty)', 'info'); return; }
            const filtered = showHidden ? files : files.filter(f => !f.name.startsWith('.'));
            if (filtered.length === 0) { this.terminal.print('(no visible files, use ls -a)', 'info'); return; }
            const maxName = Math.max(...filtered.map(f => f.name.length), 8);
            if (showLong) {
                filtered.forEach(f => {
                    const type = f.type === 'dir' ? 'd' : '-';
                    const perms = f.type === 'dir' ? 'rwxr-xr-x' : 'rw-r--r--';
                    const size = String(f.size || 0).padStart(6);
                    this.terminal.print(type + perms + '  darkbot  ' + size + '  ' + f.name);
                });
                const total = filtered.reduce((s, f) => s + (f.size || 0), 0);
                this.terminal.print('total ' + filtered.length + ' (' + total + ' bytes)', 'text-muted');
            } else {
                // v4.6.57: printClickable() writes straight to the DOM, so anything that
                // captures output (the AI run_command tool, the diagnostics sweep) saw nothing
                // and reported "directory empty" (packet §1b). Always emit a text line.
                const names = filtered.map(f => f.name + (f.type === 'dir' ? '/' : '')).join('  ');
                this.terminal.print(names);
                const capturing = !!(this.terminal._printCaptureStack && this.terminal._printCaptureStack.length);
                if (!capturing && typeof this.terminal.printClickable === 'function') this.terminal.printClickable(filtered);
            }
        };
        this.commands['cat'] = (args) => {
            if(!args[0]) return this.terminal.print('Usage: cat <filename>', 'warning');
            const content = this.terminal.fs.readFile(args[0]);
            if(content !== null && content !== undefined) {
                if (content.length === 0) this.terminal.print('(empty file)', 'info');
                else this.terminal.print(content);
            } else this.terminal.print('cat: ' + args[0] + ': No such file', 'error');
        };
        this.commands['echo'] = (args) => {
            if (!args || args.length === 0) { this.terminal.print(''); return; }
            const ri = args.indexOf('>');
            if (ri >= 0) {
                const c = args.slice(0, ri).join(' '); const fn = args.slice(ri + 1).join(' ');
                if (fn) { this.terminal.fs.writeFile(fn, c); this.terminal.print('Wrote ' + c.length + ' bytes to ' + fn, 'success'); }
                return;
            }
            this.terminal.print(args.join(' '));
        };
        this.commands['put'] = (args) => {
            if(args.length < 2) return this.terminal.print('Usage: put <filename> <content>', 'warning');
            const name = args[0]; const content = args.slice(1).join(' ');
            this.terminal.fs.writeFile(name, content);
            this.terminal.print('Created/updated: ' + name + ' (' + content.length + ' bytes)', 'success');
        };
        this.commands['rm'] = (args) => {
            if(!args[0]) return this.terminal.print('Usage: rm <filename>', 'warning');
            if(args[0] === '-r' || args[0] === '-rf') {
                const t = args[1]; if (!t) return this.terminal.print('Usage: rm -r <dirname>', 'warning');
                // Use trash for recursive dir removal too
                if (this.terminal.fs.trashDir(t)) this.terminal.print('Moved to trash: ' + t, 'success');
                else this.terminal.print('rm: ' + t + ': No such file or directory', 'error');
                return;
            }
            if(this.terminal.fs.deleteFile(args[0])) this.terminal.print('Moved to trash: ' + args[0], 'success');
            else this.terminal.print('rm: ' + args[0] + ': No such file', 'error');
        };
        this.commands['trash'] = (args) => {
            const fs = this.terminal.fs;
            if(!args[0]) return this.terminal.print('Usage: trash <filename>', 'warning');
            const node = fs.readFile(args[0]) !== null ? { type: 'file' } : fs.readDir(args[0]);
            if (!node) return this.terminal.print('trash: ' + args[0] + ': No such file', 'error');
            if (node.type === 'dir') {
                if (fs.trashDir(args[0])) this.terminal.print('Moved to trash: ' + args[0], 'success');
                else this.terminal.print('trash: ' + args[0] + ': Failed', 'error');
            } else {
                const content = fs.readFile(args[0]);
                if (content !== null) {
                    fs.trashFile(args[0], { type: 'file', content, modified: new Date() });
                    this.terminal.print('Moved to trash: ' + args[0], 'success');
                } else {
                    this.terminal.print('trash: ' + args[0] + ': No such file', 'error');
                }
            }
        };
        this.commands['trash-dir'] = (args) => {
            if(!args[0]) return this.terminal.print('Usage: trash-dir <dirname>', 'warning');
            if (this.terminal.fs.trashDir(args[0])) this.terminal.print('Moved to trash: ' + args[0], 'success');
            else this.terminal.print('trash-dir: ' + args[0] + ': No such directory', 'error');
        };
        this.commands['ls-trash'] = () => {
            const fs = this.terminal.fs;
            const items = fs.listTrash ? fs.listTrash() : [];
            if (!items.length) return this.terminal.print('Trash is empty', 'info');
            this.terminal.print('Trash items:', 'info');
            items.forEach(it => {
                const date = new Date(it.ts).toLocaleString();
                this.terminal.print(`  ${it.name}  [${it.type}]  ${date}`);
            });
        };
        this.commands['empty-trash'] = () => {
            const fs = this.terminal.fs;
            const removed = fs.emptyTrash ? fs.emptyTrash(0) : 0;
            this.terminal.print(`Emptied trash: ${removed} item(s) permanently deleted`, removed > 0 ? 'warning' : 'info');
        };
        this.commands['mkdir'] = (args) => {
            if(!args[0]) return this.terminal.print('Usage: mkdir <dirname>', 'warning');
            if (args[0] === '-p') {
                if(!args[1]) return this.terminal.print('Usage: mkdir -p <path>', 'warning');
                if(this.terminal.fs.mkdirRecursive(args[1])) this.terminal.print('Created directories: ' + args[1], 'success');
                else this.terminal.print('mkdir: cannot create ' + args[1], 'error');
                return;
            }
            if(this.terminal.fs.mkdir(args[0])) this.terminal.print('Created directory: ' + args[0], 'success');
            else this.terminal.print('mkdir: cannot create ' + args[0] + ': File exists', 'error');
        };
        this.commands['rmdir'] = (args) => {
            if(!args[0]) return this.terminal.print('Usage: rmdir <dirname>', 'warning');
            if (this.terminal.fs.deleteDirRecursive(args[0])) this.terminal.print('Removed directory: ' + args[0], 'success');
            else this.terminal.print('rmdir: ' + args[0] + ': No such directory', 'error');
        };
        this.commands['mv'] = (args) => {
            if(!args[0] || !args[1]) return this.terminal.print('Usage: mv <source> <dest>', 'warning');
            if (this.terminal.fs.mv(args[0], args[1]))
                this.terminal.print('Moved: ' + args[0] + ' to ' + args[1], 'success');
            else
                this.terminal.print('mv: ' + args[0] + ': No such file or directory', 'error');
        };
        this.commands['cp'] = (args) => {
            if(!args[0] || !args[1]) return this.terminal.print('Usage: cp <source> <dest>', 'warning');
            if (this.terminal.fs.cp(args[0], args[1]))
                this.terminal.print('Copied: ' + args[0] + ' to ' + args[1], 'success');
            else
                this.terminal.print('cp: ' + args[0] + ': No such file or directory', 'error');
        };
        this.commands['cd'] = (args) => {
            if (!args[0] || args[0] === '/') {
                this.terminal.fs.currentPath = [];
                this.terminal.fs.saveToStorage();
                this.terminal.updatePrompt();
                return;
            }
            const segs = this.terminal.fs._toAbsoluteSegments(args[0]);
            if (segs === null) {
                this.terminal.print('cd: ' + args[0] + ': No such file or directory', 'error');
                return;
            }
            const dir = this.terminal.fs._resolveDir(args[0]);
            if (dir) {
                this.terminal.fs.currentPath = segs;
                this.terminal.fs.saveToStorage();
                this.terminal.updatePrompt();
            } else {
                this.terminal.print('cd: ' + args[0] + ': Not a directory', 'error');
            }
        };
        this.commands['pwd'] = () => { this.terminal.print('/' + this.terminal.fs.currentPath.join('/')); };
        this.commands['find'] = (args) => {
            if (!args[0]) return this.terminal.print('Usage: find <pattern>', 'warning');
            const results = this.terminal.fs.findFiles ? this.terminal.fs.findFiles(args[0].toLowerCase()) : [];
            if (results.length === 0) return this.terminal.print('No matches for ' + args[0], 'info');
            results.forEach(r => this.terminal.print('./' + r));
            this.terminal.print('Found ' + results.length + ' match(es)', 'info');
        };
        this.commands['grep'] = (args) => {
            // 2026-10-21: accept the common GNU flags instead of treating them as the pattern.
            // `grep -n "x" file` used to search for the literal "-n" inside a file named "x"
            // (6/6 syntax variants failed for the agent), while plain grep already prints
            // "line: text" for every hit.
            const opt = { count: false, invert: false, files: false, ignoreCase: true };
            let ai = 0;
            while (ai < args.length && /^-[a-zA-Z]+$/.test(args[ai])) {
                const f = args[ai].slice(1);
                if (f.indexOf('c') !== -1) opt.count = true;
                if (f.indexOf('v') !== -1) opt.invert = true;
                if (f.indexOf('l') !== -1) opt.files = true;
                if (f.indexOf('i') !== -1) opt.ignoreCase = true;
                ai++;
            }
            const pattern = args[ai]; const target = args[ai + 1];
            if (!pattern) return this.terminal.print('Usage: grep [-n] [-i] [-c] [-l] <pattern> [filename]', 'warning');
            const re = new RegExp(pattern, opt.ignoreCase ? 'i' : '');
            const hits = (line) => (opt.invert ? !re.test(line) : re.test(line));
            if (target) {
                const c = this.terminal.fs.readFile(target);
                if (c === null || c === undefined) return this.terminal.print('grep: ' + target + ': No such file', 'error');
                const lines = c.split('\n');
                let count = 0;
                lines.forEach((line, i) => {
                    if (!hits(line)) return;
                    count++;
                    if (!opt.count && !opt.files) this.terminal.print((i + 1) + ': ' + line);
                });
                if (opt.files && count) this.terminal.print(target);
                if (count === 0) this.terminal.print('(no matches)', 'info');
                else if (opt.count) this.terminal.print(String(count));
                else if (!opt.files) this.terminal.print(count + ' match(es)', 'text-muted');
            } else {
                const dir = this.terminal.fs.getCurrentDir();
                if (!dir) return this.terminal.print('grep: cannot search', 'error');
                let total = 0;
                Object.keys(dir.content).forEach(name => {
                    const node = dir.content[name];
                    if (node.type === 'file') {
                        (node.content || '').split('\n').forEach((line, i) => {
                            if (!hits(line)) return;
                            total++;
                            if (!opt.count && !opt.files) this.terminal.print(name + ':' + (i + 1) + ': ' + line);
                        });
                    }
                });
                if (opt.files && total) this.terminal.print(dir.name || '.');
                if (total === 0) this.terminal.print('(no matches)', 'info');
                else if (opt.count) this.terminal.print(String(total));
                else if (!opt.files) this.terminal.print(total + ' total match(es)', 'text-muted');
            }
        };
        this.commands['head'] = (args) => {
            // 2026-10-21: accept `head -40 f`, `head -n 40 f` and `head f 40`.
            let n = 10, file = null;
            for (let i = 0; i < (args || []).length; i++) {
                const a = args[i];
                if (/^-\d+$/.test(a)) n = parseInt(a.slice(1), 10);
                else if (a === '-n') { const v = parseInt(args[i + 1], 10); if (!isNaN(v)) n = v; i++; }
                else if (/^-[a-zA-Z]+$/.test(a)) { /* ignore other flags */ }
                else if (!file) file = a;
            }
            if (!file) return this.terminal.print('Usage: head [-n] <filename> [lines]', 'warning');
            const c = this.terminal.fs.readFile(file);
            if (c === null || c === undefined) return this.terminal.print('head: ' + file + ': No such file', 'error');
            this.terminal.print(c.split('\n').slice(0, Math.max(1, n)).join('\n'));
        };
        this.commands['tail'] = (args) => {
            const self = this;
            let follow = false, n = 10;
            const positional = [];
            for (let i = 0; i < (args || []).length; i++) {
                const a = args[i];
                if (a === '-f' || a === '--follow') follow = true;
                else if (a === '-n') {
                    const v = args[++i];
                    if (v === undefined || !/^\d+$/.test(v)) return this.terminal.print('tail: -n requires a number', 'error');
                    n = parseInt(v, 10);
                }
                else if (/^-\d+$/.test(a)) n = parseInt(a.slice(1), 10);
                else if (a === '-c' || a === '-q' || a === '-v' || a === '--pid') return this.terminal.print('tail: option ' + a + ' not supported', 'error');
                else if (a.startsWith('-')) return this.terminal.print('tail: invalid option: ' + a, 'error');
                else positional.push(a);
            }
            const file = positional[0];
            if (!file) return this.terminal.print('Usage: tail [-f] [-n N] <file> — last N lines; -f follows changes (Ctrl+C or Esc to stop)', 'warning');
            if (positional[1] && /^\d+$/.test(positional[1])) n = parseInt(positional[1], 10); // legacy back-compat: tail <file> <count>
            const c = this.terminal.fs.readFile(file);
            if (c === null || c === undefined) return this.terminal.print('tail: ' + file + ': No such file', 'error');
            // 2026-10-21: a trailing newline produced an empty last element, so `tail -n 1`
            // printed a blank line instead of the final line.
            const _all = c.split('\n');
            if (_all.length > 1 && _all[_all.length - 1] === '') _all.pop();
            this.terminal.print(_all.slice(-n).join('\n'));
            if (!follow) return;
            // AI tool calls cannot press Ctrl+C — auto-downgrade to a bounded read instead of a live timer
            if (this.terminal.security && this.terminal.security._aiToolDepth > 0) {
                return this.terminal.print('tail: follow mode (-f) is interactive-only; showing last lines instead (use tail -n ' + Math.max(n, 50) + ' for more)', 'warning');
            }
            // stop any previous follow before starting a new one
            if (this.terminal._activeFollow && this.terminal._activeFollow.interval) clearInterval(this.terminal._activeFollow.interval);
            this.terminal._activeFollow = null;
            let offset = c.length;
            const interval = setInterval(() => {
                const cur = self.terminal.fs.readFile(file);
                if (cur === null || cur === undefined) {
                    self.terminal.stopFollow('tail: ' + file + ': file removed — follow stopped');
                    return;
                }
                if (cur.length < offset) {
                    self.terminal.print('tail: ' + file + ': file truncated — following from start', 'warning');
                    self.terminal.print(cur);
                    offset = cur.length;
                    return;
                }
                if (cur.length > offset) {
                    self.terminal.print(cur.slice(offset));
                    offset = cur.length;
                }
            }, 1500);
            this.terminal._activeFollow = { interval, file };
            this.terminal.print('tail: following ' + file + ' (Ctrl+C or Esc to stop)', 'text-muted');
        };
        this.commands['sed'] = (args) => {
            if (!args || args.length === 0) {
                return this.terminal.print('Usage: sed <expr> [file] — expressions: s/pat/rep/[g][i][p], /pat/d, Nd, $d; flags: -i in place, -n quiet', 'warning');
            }
            let inPlace = false, quiet = false, expr = null, file = null;
            for (let i = 0; i < args.length; i++) {
                const a = args[i];
                if (a === '-i') inPlace = true;
                else if (a === '-n') quiet = true;
                else if (expr === null) expr = a;
                else if (file === null) file = a;
                else return this.terminal.print('sed: too many arguments: ' + a, 'error');
            }
            if (!expr) return this.terminal.print('sed: missing expression', 'error');
            let content;
            if (file) {
                content = this.terminal.fs.readFile(file);
                if (content === null || content === undefined) return this.terminal.print('sed: ' + file + ': No such file', 'error');
            } else if (this.terminal._pipeInput !== null && this.terminal._pipeInput !== undefined) {
                content = this.terminal._pipeInput; // piped input: cat x | sed s/a/b/
            } else {
                return this.terminal.print('sed: missing file operand (no piped input)', 'error');
            }
            let subst = null, delMatch = null, delLine = null;
            // 2026-10-21: `sed -n '10,40p' file` and `sed -n '7p' file` had no parser, so the
            // most common "show me lines N–M" idiom failed with an unsupported-expression error.
            const _range = /^(\d+)(?:,(\d+))?p$/.exec(expr);
            if (_range) {
                const _a = parseInt(_range[1], 10);
                const _b = _range[2] ? parseInt(_range[2], 10) : _a;
                const _lines = content.split('\n');
                this.terminal.print(_lines.slice(Math.max(0, _a - 1), Math.max(_a, _b)).join('\n'));
                return;
            }
            if (expr.startsWith('s/') && expr.length > 2) {
                const parts = []; let cur = '';
                for (let i = 2; i < expr.length; i++) {
                    const ch = expr[i];
                    if (ch === '\\' && expr[i + 1] === '/') { cur += '/'; i++; }
                    else if (ch === '/') { parts.push(cur); cur = ''; }
                    else cur += ch;
                }
                parts.push(cur);
                if (parts.length < 2 || parts.length > 3) return this.terminal.print('sed: malformed expression: ' + expr, 'error');
                const flags = parts[2] || '';
                if ([...flags].some(c => !'gip'.includes(c))) return this.terminal.print('sed: unsupported flags: ' + flags, 'error');
                subst = { pat: parts[0], rep: parts[1], flags };
            } else if (/^\/(.+)\/d$/.test(expr)) {
                delMatch = expr.slice(1, -2);
            } else if (/^(\d+|\$)d$/.test(expr)) {
                delLine = expr.slice(0, -1);
            } else {
                return this.terminal.print('sed: unsupported expression: ' + expr, 'error');
            }
            let lines = content.split('\n');
            let trailingNL = false;
            if (lines.length && lines[lines.length - 1] === '') { trailingNL = true; lines.pop(); }
            const outLines = [];
            let changed = 0;
            if (subst) {
                let re;
                try {
                    re = new RegExp(subst.pat, (subst.flags.includes('i') ? 'i' : '') + (subst.flags.includes('g') ? 'g' : ''));
                } catch (e) {
                    return this.terminal.print('sed: invalid regex: ' + e.message, 'error');
                }
                for (const line of lines) {
                    const after = line.replace(re, subst.rep);
                    if (after !== line) changed++;
                    if (quiet) {
                        if (subst.flags.includes('p') && after !== line) this.terminal.print(after);
                    } else {
                        outLines.push(after);
                    }
                }
            } else if (delMatch !== null) {
                let re;
                try { re = new RegExp(delMatch); } catch (e) { return this.terminal.print('sed: invalid regex: ' + e.message, 'error'); }
                for (const line of lines) {
                    if (re.test(line)) changed++;
                    else outLines.push(line);
                }
            } else {
                const idx = delLine === '$' ? lines.length - 1 : parseInt(delLine, 10) - 1;
                if (idx < 0 || idx >= lines.length) return this.terminal.print('sed: line number out of range: ' + delLine, 'error');
                for (let i = 0; i < lines.length; i++) {
                    if (i === idx) changed++;
                    else outLines.push(lines[i]);
                }
            }
            if (inPlace) {
                if (!file) return this.terminal.print('sed: -i requires a file operand', 'error');
                this.terminal.fs.writeFile(file, outLines.join('\n') + (trailingNL ? '\n' : ''));
                this.terminal.print('sed: updated ' + file + ' (' + changed + ' line' + (changed === 1 ? '' : 's') + ' changed)', 'success');
            } else if (quiet) {
                if (changed === 0) this.terminal.print('(no changes)', 'text-muted');
            } else {
                this.terminal.print(outLines.join('\n'));
            }
        };
        this.commands['sort'] = (args) => {
            if(!args[0]) return this.terminal.print('Usage: sort <filename>', 'warning');
            const c = this.terminal.fs.readFile(args[0]);
            if(c === null || c === undefined) return this.terminal.print('sort: ' + args[0] + ': No such file', 'error');
            c.split('\n').sort().forEach(l => this.terminal.print(l));
        };
        this.commands['wc'] = (args) => {
            // 2026-10-21: accept -l / -w / -c (previously ANY flag was read as a filename,
            // so `wc -l file` answered "wc: -l: No such file").
            // v4.6.58: multiple files. `wc -c a b` used to print only `a` and exit clean —
            // a silent false negative (packet §1).
            const want = { l: false, w: false, c: false };
            const files = [];
            (args || []).forEach(a => {
                if (/^-[lwc]+$/.test(a)) a.slice(1).split('').forEach(k => { want[k] = true; });
                else if (/^-[a-zA-Z]+$/.test(a)) { /* ignore other flags */ }
                else files.push(a);
            });
            if (!files.length) return this.terminal.print('Usage: wc [-l] [-w] [-c] <filename> [...]', 'warning');
            const anyFlag = want.l || want.w || want.c;
            const rows = [];
            let total = { l: 0, w: 0, c: 0 };
            files.forEach(file => {
                const content = this.terminal.fs.readFile(file);
                if (content === null || content === undefined) {
                    this.terminal.print('wc: ' + file + ': No such file', 'error');
                    return;
                }
                const r = {
                    file: file,
                    l: content.split('\n').length,
                    w: content.split(/\s+/).filter(w => w).length,
                    c: content.length
                };
                total.l += r.l; total.w += r.w; total.c += r.c;
                rows.push(r);
            });
            if (!rows.length) return;
            const multi = rows.length > 1;
            const fmt = (r, name) => {
                const out = [];
                if (want.l || !anyFlag) out.push(r.l);
                if (want.w || !anyFlag) out.push(r.w);
                if (want.c || !anyFlag) out.push(r.c);
                if (multi || (anyFlag && !(want.l && want.w && want.c))) out.push(name);
                return out.join(' ');
            };
            rows.forEach(r => this.terminal.print(fmt(r, r.file)));
            if (multi) this.terminal.print(fmt(total, 'total'));
        };
        this.commands['touch'] = (args) => {
            if(!args[0]) return this.terminal.print('Usage: touch <filename>', 'warning');
            const e = this.terminal.fs.readFile(args[0]);
            if (e === null || e === undefined) {
                const segs = this.terminal.fs._toAbsoluteSegments(args[0]);
                if (segs) {
                    const dirPath = segs.slice(0, -1).join('/') || '.';
                    const name = segs[segs.length - 1];
                    this.terminal.fs.mkdirRecursive(dirPath);
                }
                this.terminal.fs.writeFile(args[0], '');
                this.terminal.print('Created: ' + args[0], 'success');
            }
            else { this.terminal.print('Touched: ' + args[0], 'success'); }
        };
        this.commands['tree'] = () => {
            const dir = this.terminal.fs.getCurrentDir();
            if (!dir) return this.terminal.print('(no directory)', 'warning');
            const lines = []; this._printTree(dir, '', lines);
            lines.forEach(l => this.terminal.print(l));
        };
        this.commands['du'] = (args) => {
            const t = args && args[0] ? args[0] : '.';
            if (t === '.') {
                const dir = this.terminal.fs.getCurrentDir(); if (!dir) return;
                let total = 0; Object.keys(dir.content).forEach(k => { const node = dir.content[k]; total += node && typeof node.content === 'string' ? node.content.length : 0; });
                this.terminal.print(total + '\t' + t);
            } else {
                const c = this.terminal.fs.readFile(t);
                if (c === null || c === undefined) return;
                this.terminal.print(c.length + '\t' + t);
            }
        };
        this.commands['upload'] = () => { document.getElementById('file-upload-input').click(); };
        this.commands['download'] = async (args) => {
            if(!args[0]) return this.terminal.print('Usage: download <filename>', 'warning');
            const fname = args[0];
            const content = this.terminal.fs.readFile(fname);
            if(content === null || content === undefined) {
                return this.terminal.print('download: ' + fname + ': No such file', 'error');
            }
            // Push to WebDAV first — this is the only path to a real file download on Telegram WebView
            // because browser-based file downloads are blocked in WebViews
            let downloadUrl = null;
            if (this.terminal.moduleManager && this.terminal.moduleManager.modules.WebDAVModule) {
                const wdav = this.terminal.moduleManager.modules.WebDAVModule;
                if (wdav.config && wdav.config.url) {
                    try {
                        // Make sure /downloads/ dir exists
                        try { await wdav._ensureDir('/downloads'); } catch(e) {}
                        const resp = await wdav._webdavRequest('PUT', '/downloads/' + fname, {
                            body: content,
                            headers: { 'Content-Type': 'application/octet-stream' }
                        });
                        if (resp.ok || resp.status === 201 || resp.status === 204) {
                            // Build the public URL the user can tap
                            const baseUrl = wdav.config.url.replace(/\/+$/, '');
                            const hostMatch = baseUrl.match(/^(https?:\/\/[^\/]+)/);
                            const host = hostMatch ? hostMatch[1] : 'https://webx11.duckdns.org';
                            // Build the public URL the user can tap.
                            // The URL must use the space the PUT actually went to
                            // (config.url = the logged-in user's space). _spaceName is
                            // derived from the page path (/spaces/newos4/…) and is wrong
                            // for users downloading into their own space (2026-10-21).
                            const urlSpace = (typeof wdav._resolveSpaceName === 'function' && wdav._resolveSpaceName()) ||
                                             (wdav._extractSpaceNameFromUrl && wdav._extractSpaceNameFromUrl(wdav.config.url)) ||
                                             wdav._spaceName;
                            downloadUrl = host + '/spaces/' + urlSpace + '/downloads/' + encodeURIComponent(fname);
                            this.terminal.print('Uploaded to: ' + downloadUrl, 'success');
                        } else {
                            this.terminal.print('WebDAV push failed: HTTP ' + resp.status, 'warning');
                        }
                    } catch (e) {
                        this.terminal.print('WebDAV push error: ' + e.message, 'warning');
                    }
                } else {
                    this.terminal.print('WebDAV not configured. Run: webdav-config', 'warning');
                }
            }
            // Build a visible anchor link — tap = real user gesture = native browser download bar
            const size = content.length;
            const sizeStr = size > 1024 ? (size / 1024).toFixed(1) + ' KB' : size + ' B';
            const line = document.createElement('div');
            line.className = 'output-line';
            line.style.cssText = 'padding:8px 0;display:flex;align-items:center;gap:10px;flex-wrap:wrap;';
            if (downloadUrl) {
                line.innerHTML = '<span>⬇ ' + fname + ' (' + sizeStr + ') </span>' +
                    '<a href="' + downloadUrl + '" target="_blank" rel="noopener" ' +
                    'style="background:var(--success-color);color:#000;border:none;padding:8px 16px;' +
                    'border-radius:6px;cursor:pointer;font-size:0.9em;min-height:44px;' +
                    'display:inline-flex;align-items:center;text-decoration:none;font-weight:bold;">⬇ Tap to download</a>';
            } else {
                line.innerHTML = '<span>⬇ ' + fname + ' (' + sizeStr + ') — run <code>webdav-config</code> first to enable downloads</span>';
            }
            this.terminal.outputContainer.appendChild(line);
            this.terminal.scrollToBottom();
        };
        this.commands['vfs-export'] = () => {
            const data = this.terminal.fs.root;
            const json = JSON.stringify(data, null, 2);
            const blob = new Blob([json], {type: 'application/json'});
            const sizeMB = blob.size / (1024 * 1024);
            if (sizeMB > 5) {
                this.terminal.print('Warning: VFS size is ' + sizeMB.toFixed(1) + ' MB — large download may take time', 'warning');
            }
            const now = new Date();
            const dateStr = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + String(now.getDate()).padStart(2, '0');
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url; a.download = 'webx11-filesystem-' + dateStr + '.json';
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 2000);
            this.terminal.print('Exported VFS to webx11-filesystem-' + dateStr + '.json', 'success');
        };
        this.commands['vfs-size'] = () => {
            try {
                const json = JSON.stringify(this.terminal.fs.root);
                const totalSize = (json.length / 1024 / 1024).toFixed(2);
                const root = this.terminal.fs.root;
                const sizeMap = [];
                function walk(node, path) {
                    if (!node || !node.content) return;
                    for (const [name, child] of Object.entries(node.content)) {
                        const fullPath = path + '/' + name;
                        if (child.type === 'file') {
                            const size = (child.content ? child.content.length : 0);
                            sizeMap.push({ path: fullPath, size, sizeKB: (size / 1024).toFixed(1) });
                        } else if (child.type === 'dir') {
                            walk(child, fullPath);
                        }
                    }
                }
                walk(root, '');
                sizeMap.sort((a, b) => b.size - a.size);
                const totalFiles = sizeMap.length;
                const top5 = sizeMap.slice(0, 5);
                this.terminal.print('📊 VFS Size Report', 'text-muted');
                this.terminal.print('  Total: ' + totalSize + ' MB across ' + totalFiles + ' files');
                this.terminal.print('  Largest:');
                top5.forEach((f, i) => {
                    this.terminal.print('    ' + (i + 1) + '. ' + f.path + ' — ' + f.sizeKB + ' KB');
                });
                // Show system dir sizes
                const sysDirs = ['/_snapshots', '/_sessions', '/.trash'];
                for (const dir of sysDirs) {
                    const dirNode = this.terminal.fs.readDir(dir);
                    if (dirNode) {
                        const cnt = dirNode.length;
                        // estimate dir size
                        const dirSize = JSON.stringify(dirNode).length;
                        this.terminal.print('  ' + dir + ': ' + cnt + ' files, ~' + (dirSize / 1024).toFixed(1) + ' KB', dirSize > 102400 ? 'warning' : 'text-muted');
                    }
                }
            } catch (e) {
                this.terminal.print('vfs-size error: ' + e.message, 'error');
            }
        };
        
        // Session commands (save/load/export/import)
        this.commands['session-save'] = (args) => {
            if (!args[0]) return this.terminal.print('Usage: session-save <name>', 'warning');
            const name = args[0].replace(/[^a-zA-Z0-9_-]/g, '_');
            // v2: metadata-only — VFS is persisted independently in localStorage
            const manifest = {
                type: 'session',
                version: 2,
                savedAt: new Date().toISOString(),
                currentPath: this.terminal.fs.currentPath,
                terminalLines: this.terminal._historyBuffer ? this.terminal._historyBuffer.slice(-50) : []
            };
            const filePath = '_sessions/' + name + '.json';
            this.terminal.fs.mkdirRecursive('_sessions');
            this.terminal.fs.writeFile(filePath, JSON.stringify(manifest));
            this.terminal.print('Session saved: ' + name + ' (' + (manifest.terminalLines.length || 0) + ' history lines)', 'success');
        };
        this.commands['session-load'] = (args) => {
            if (!args[0]) return this.terminal.print('Usage: session-load <name>', 'warning');
            const filePath = '_sessions/' + args[0] + '.json';
            const content = this.terminal.fs.readFile(filePath);
            if (content === null) return this.terminal.print('Session not found: ' + args[0], 'error');
            try {
                const session = JSON.parse(content);
                if (!session || session.type !== 'session') {
                    return this.terminal.print('Invalid session file: ' + args[0], 'error');
                }
                if (session.version === 2) {
                    // v2: metadata-only restore — keep existing VFS, just restore path + terminal history
                    this.terminal.fs.currentPath = session.currentPath || [];
                    if (session.terminalLines && Array.isArray(session.terminalLines) && this.terminal._historyBuffer) {
                        this.terminal._historyBuffer = session.terminalLines.slice(-50);
                        // Re-render last few lines for context
                        this.terminal.outputContainer.innerHTML = '';
                        session.terminalLines.forEach(line => {
                            const text = typeof line === 'string' ? line : (line.l || '');
                            const type = typeof line === 'object' ? (line.t || '') : '';
                            this.terminal.print(text, type);
                        });
                    }
                } else {
                    // v1: full VFS restore (legacy)
                    if (!session.fsRoot) return this.terminal.print('Invalid session file', 'error');
                    this.terminal.fs.root = session.fsRoot;
                    this.terminal.fs.currentPath = session.currentPath || [];
                }
                this.terminal.fs.saveToStorage();
                this.terminal.updatePrompt();
                this.terminal.print('Session loaded: ' + args[0] + ' (' + new Date(session.savedAt).toLocaleString() + ')', 'success');
                this.terminal.executeCommand('ls');
            } catch (e) {
                this.terminal.print('Failed to load session: ' + e.message, 'error');
            }
        };
        this.commands['session-list'] = () => {
            this.terminal.fs.mkdirRecursive('_sessions');
            const files = this.terminal.fs.ls('_sessions');
            if (!files || files.length === 0) return this.terminal.print('No saved sessions', 'info');
            this.terminal.print('Saved sessions:', 'text-muted');
            files.forEach(f => {
                if (f.type === 'file' && f.name.endsWith('.json')) {
                    try {
                        const content = JSON.parse(this.terminal.fs.readFile('_sessions/' + f.name));
                        const label = f.name.replace('.json', '');
                        const date = content.savedAt ? new Date(content.savedAt).toLocaleString() : 'unknown';
                        if (content.version === 2) {
                            const lines = content.terminalLines ? content.terminalLines.length : 0;
                            this.terminal.print('  ' + label + '  (' + lines + ' history lines, ' + date + ')');
                        } else {
                            const fileCount = content.fsRoot ? Object.keys(content.fsRoot.content || {}).length : 0;
                            this.terminal.print('  ' + label + '  (' + fileCount + ' items, ' + date + ')');
                        }
                    } catch (e) {
                        this.terminal.print('  ' + f.name.replace('.json', '') + '  (corrupt)');
                    }
                }
            });
        };
        this.commands['session-delete'] = (args) => {
            if (!args[0]) return this.terminal.print('Usage: session-delete <name>', 'warning');
            const filePath = '_sessions/' + args[0] + '.json';
            if (this.terminal.fs.deleteFile(filePath)) {
                this.terminal.print('Session deleted: ' + args[0], 'success');
            } else {
                this.terminal.print('Session not found: ' + args[0], 'error');
            }
        };
        this.commands['session-new'] = () => {
            // Auto-save current session, clear AI context, fresh terminal
            this.terminal._autoSaveSession();
            try { localStorage.removeItem('webx11_ai_context'); } catch(e) {}
            // Clear terminal output
            if (this.terminal.outputContainer) this.terminal.outputContainer.innerHTML = '';
            if (this.terminal._historyBuffer) this.terminal._historyBuffer = [];
            // Clear AI conversation context
            const aiMod = this.terminal.moduleManager.modules['WebX11AIAssistantModule'];
            if (aiMod && aiMod.clearContext) aiMod.clearContext();
            this.terminal.print('✨ New session started — context cleared', 'success');
        };
        this.commands['session-export'] = (args) => {
            if (!args[0]) return this.terminal.print('Usage: session-export <name>', 'warning');
            const filePath = '_sessions/' + args[0] + '.json';
            const content = this.terminal.fs.readFile(filePath);
            if (content === null) return this.terminal.print('Session not found: ' + args[0], 'error');
            const blob = new Blob([content], {type: 'application/json'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'webx11-session-' + args[0] + '.json';
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 2000);
            this.terminal.print('Exported session: ' + args[0], 'success');
        };
        this.commands['session-import'] = () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            input.onchange = (e) => {
                const file = e.target.files[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = (evt) => {
                    try {
                        const session = JSON.parse(evt.target.result);
                        if (!session || session.type !== 'session') {
                            this.terminal.print('Invalid session file (not a valid session export)', 'error');
                            return;
                        }
                        if (session.version === 2) {
                            // v2: metadata-only — keep existing VFS, restore path
                            this.terminal.fs.currentPath = session.currentPath || [];
                            if (session.terminalLines && Array.isArray(session.terminalLines) && this.terminal._historyBuffer) {
                                this.terminal._historyBuffer = session.terminalLines.slice(-50);
                                this.terminal.outputContainer.innerHTML = '';
                                session.terminalLines.forEach(line => {
                                    const text = typeof line === 'string' ? line : (line.l || '');
                                    const type = typeof line === 'object' ? (line.t || '') : '';
                                    this.terminal.print(text, type);
                                });
                            }
                        } else {
                            if (!session.fsRoot) {
                                this.terminal.print('Invalid session file (not a valid session export)', 'error');
                                return;
                            }
                            this.terminal.fs.root = session.fsRoot;
                            this.terminal.fs.currentPath = session.currentPath || [];
                        }
                        this.terminal.fs.saveToStorage();
                        this.terminal.updatePrompt();
                        this.terminal.print('Session imported: ' + file.name + ' (' + (session.savedAt ? new Date(session.savedAt).toLocaleString() : 'unknown date') + ')', 'success');
                        this.terminal.executeCommand('ls');
                    } catch (err) {
                        this.terminal.print('Failed to import session: ' + err.message, 'error');
                    }
                };
                reader.readAsText(file);
            };
            input.click();
        };
        this.commands['vfs-import'] = () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            input.onchange = (e) => {
                const file = e.target.files[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = (evt) => {
                    try {
                        const data = JSON.parse(evt.target.result);
                        if (!data || !data.type) {
                            this.terminal.print('Invalid VFS file', 'error');
                            return;
                        }
                        if (this.terminal.fs.restoreFromExport(data)) {
                            this.terminal.updatePrompt();
                            this.terminal.print('VFS restored from: ' + file.name, 'success');
                            this.terminal.executeCommand('ls');
                        } else {
                            this.terminal.print('Failed to restore VFS', 'error');
                        }
                    } catch (err) {
                        this.terminal.print('Failed to import VFS: ' + err.message, 'error');
                    }
                };
                reader.readAsText(file);
            };
            input.click();
        };
    }
    _printTree(dir, prefix, lines) {
        const names = Object.keys(dir.content || {}).sort();
        names.forEach((name, i) => {
            const isLast = i === names.length - 1;
            const node = dir.content[name];
            const connector = isLast ? '\u2514\u2500\u2500 ' : '\u251c\u2500\u2500 ';
            const label = node.type === 'dir' ? name + '/' : name;
            lines.push(prefix + connector + label);
            if (node.type === 'dir') {
                this._printTree(node, prefix + (isLast ? '    ' : '\u2502   '), lines);
            }
        });
    }
}