zoi-plugins 1.25.2

Advanced Package Manager & Environment Orchestrator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
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
//! Plugin management system for Zoi.
//!
//! This crate provides the `PluginManager` which handles loading and executing
//! Lua plugins that extend Zoi's functionality. It also includes support for
//! extensions that can modify registry configurations.

/// Registry extension management.
pub mod extension;

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Result, anyhow};
use colored::Colorize;
use comfy_table::Table as ComfyTable;
use comfy_table::presets::UTF8_FULL;
use dialoguer::theme::ColorfulTheme;
use dialoguer::{Confirm, Select};
use mlua::{Function, Lua, LuaSerdeExt, Table, Value};
use sha2::{Digest, Sha256};
use zoi_core::{types, utils};
use zoi_project as project;
use zoi_resolver::{local, resolve};

/// Key used in the Lua globals to store environment variable overrides.
const PLUGIN_ENV_OVERRIDES_KEY: &str = "__ZOI_ENV_OVERRIDES";

/// Orchestrates Zoi's extensibility via global Lua plugins.
///
/// Plugins allow users to customize Zoi's behavior by:
/// - Registering new subcommands (`zoi.register_command`).
/// - Intercepting lifecycle events (`zoi.on_post_install`, etc.).
/// - Overriding tool versions at runtime (shim resolution).
///
/// Plugins are stored in `~/.zoi/plugins/` and are verified against
/// a `trusted_hashes.json` database to prevent unauthorized execution.
pub struct PluginManager {
    /// The initialized mlua Lua Virtual Machine.
    pub lua: Lua
}

impl PluginManager {
    /// Initializes a new `PluginManager` and sets up the global Lua API.
    ///
    /// This injects the entire `zoi.*` API surface into the Lua environment,
    /// enabling plugins to interact with the filesystem, HTTP, archives,
    /// the UI, and the hook registry.
    ///
    /// # Errors
    ///
    /// Returns an error if the Lua VM cannot be initialized or if the `zoi` API
    /// fails to be injected.
    pub fn new() -> Result<Self> {
        let lua = Lua::new();
        let manager = Self { lua };
        manager.setup_api()?;
        Ok(manager)
    }

    /// Sets up the global `zoi` API in the Lua environment.
    fn setup_api(&self) -> Result<()> {
        let zoi = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;

        self.lua
            .globals()
            .set(
                "__ZOI_COMMANDS",
                self.lua
                    .create_table()
                    .map_err(|e| anyhow!(e.to_string()))?
            )
            .map_err(|e| anyhow!(e.to_string()))?;
        self.lua
            .globals()
            .set(
                "__ZOI_COMMAND_HELP",
                self.lua
                    .create_table()
                    .map_err(|e| anyhow!(e.to_string()))?
            )
            .map_err(|e| anyhow!(e.to_string()))?;

        let register_command = self
            .lua
            .create_function(|lua, arg: Value| {
                let registry: Table = lua.globals().get("__ZOI_COMMANDS")?;
                let help_registry: Table =
                    lua.globals().get("__ZOI_COMMAND_HELP")?;
                match arg {
                    Value::Table(t) => {
                        let name: String = t.get("name")?;
                        let desc: String = t
                            .get("description")
                            .unwrap_or_else(|_| String::new());
                        let callback: Function = t.get("callback")?;
                        registry.set(name.clone(), callback)?;
                        help_registry.set(name, desc)?;
                    }
                    _ => {
                        return Err(mlua::Error::RuntimeError(
                            "Invalid argument to register_command. Expected a \
                             table {name, description, callback}"
                                .to_string()
                        ));
                    }
                }
                Ok(())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("register_command", register_command)
            .map_err(|e| anyhow!(e.to_string()))?;

        let register_command_simple = self
            .lua
            .create_function(|lua, (name, callback): (String, Function)| {
                let registry: Table = lua.globals().get("__ZOI_COMMANDS")?;
                registry.set(name, callback)?;
                Ok(())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("register_command_simple", register_command_simple)
            .map_err(|e| anyhow!(e.to_string()))?;

        self.lua
            .globals()
            .set(
                "__ZOI_HOOKS",
                self.lua
                    .create_table()
                    .map_err(|e| anyhow!(e.to_string()))?
            )
            .map_err(|e| anyhow!(e.to_string()))?;
        self.lua
            .globals()
            .set(
                PLUGIN_ENV_OVERRIDES_KEY,
                self.lua
                    .create_table()
                    .map_err(|e| anyhow!(e.to_string()))?
            )
            .map_err(|e| anyhow!(e.to_string()))?;
        let hooks = [
            "on_pre_install",
            "on_post_install",
            "on_pre_uninstall",
            "on_post_uninstall",
            "on_pre_sync",
            "on_post_sync",
            "on_rollback",
            "on_pre_create",
            "on_post_create",
            "on_pre_extension_add",
            "on_post_extension_add",
            "on_pre_extension_remove",
            "on_post_extension_remove",
            "on_resolve_shim_version",
            "on_project_install"
        ];
        for hook in hooks {
            let hook_name = hook.to_string();
            let register_hook = self
                .lua
                .create_function(move |lua, callback: Function| {
                    let registry: Table = lua.globals().get("__ZOI_HOOKS")?;
                    let hook_list: Table =
                        if let Ok(t) = registry.get(hook_name.as_str()) {
                            t
                        } else {
                            let t = lua.create_table()?;
                            registry.set(hook_name.as_str(), t.clone())?;
                            t
                        };
                    hook_list.push(callback)?;
                    Ok(())
                })
                .map_err(|e| anyhow!(e.to_string()))?;
            zoi.set(hook, register_hook)
                .map_err(|e| anyhow!(e.to_string()))?;
        }

        let set_data = self
            .lua
            .create_function(|_, (key, value): (String, Value)| {
                let mut state = read_plugin_state().unwrap_or_default();
                let json_val: serde_json::Value = match value {
                    Value::String(s) => {
                        serde_json::Value::String(s.to_str()?.to_string())
                    }
                    Value::Integer(i) => serde_json::Value::Number(i.into()),
                    Value::Number(n) => {
                        let Some(num) = serde_json::Number::from_f64(n) else {
                            return Err(mlua::Error::RuntimeError(
                                "Non-finite numbers are not supported for \
                                 set_data"
                                    .to_string()
                            ));
                        };
                        serde_json::Value::Number(num)
                    }
                    Value::Boolean(b) => serde_json::Value::Bool(b),
                    _ => {
                        return Err(mlua::Error::RuntimeError(
                            "Unsupported value type for set_data".to_string()
                        ));
                    }
                };
                state.insert(key, json_val);
                write_plugin_state(&state)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                Ok(())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("set_data", set_data)
            .map_err(|e| anyhow!(e.to_string()))?;

        let get_data = self
            .lua
            .create_function(|lua, key: String| {
                let state = read_plugin_state().unwrap_or_default();
                if let Some(val) = state.get(&key) {
                    lua.to_value(val)
                } else {
                    Ok(Value::Nil)
                }
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("get_data", get_data)
            .map_err(|e| anyhow!(e.to_string()))?;

        let list_installed = self
            .lua
            .create_function(|lua, ()| {
                let installed = local::get_installed_packages()
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                lua.to_value(&installed)
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("list_installed", list_installed)
            .map_err(|e| anyhow!(e.to_string()))?;

        let get_package = self
            .lua
            .create_function(|lua, name: String| {
                let (pkg, _, _, _, _, _, _) =
                    resolve::resolve_package_and_version(
                        &name, None, true, false
                    )
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                lua.to_value(&pkg)
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("get_package", get_package)
            .map_err(|e| anyhow!(e.to_string()))?;

        if let Ok(config) = project::config::load() {
            let project_table = self
                .lua
                .create_table()
                .map_err(|e| anyhow!(e.to_string()))?;
            project_table
                .set("name", config.name)
                .map_err(|e| anyhow!(e.to_string()))?;
            project_table
                .set("packages", config.pkgs)
                .map_err(|e| anyhow!(e.to_string()))?;
            zoi.set("project", project_table)
                .map_err(|e| anyhow!(e.to_string()))?;
        }

        let ui = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;
        let ui_print = self
            .lua
            .create_function(|_, (text, color): (String, Option<String>)| {
                let colored_text = match color.as_deref() {
                    Some("red") => text.red(),
                    Some("green") => text.green(),
                    Some("yellow") => text.yellow(),
                    Some("blue") => text.blue(),
                    Some("cyan") => text.cyan(),
                    Some("magenta") => text.magenta(),
                    _ => text.normal()
                };
                println!("{colored_text}");
                Ok(())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        ui.set("print", ui_print)
            .map_err(|e| anyhow!(e.to_string()))?;

        let ui_confirm = self
            .lua
            .create_function(|_, prompt: String| {
                Ok(Confirm::with_theme(&ColorfulTheme::default())
                    .with_prompt(prompt)
                    .interact()
                    .unwrap_or(false))
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        ui.set("confirm", ui_confirm)
            .map_err(|e| anyhow!(e.to_string()))?;

        let ui_select = self
            .lua
            .create_function(|_, (prompt, options): (String, Vec<String>)| {
                let selection = Select::with_theme(&ColorfulTheme::default())
                    .with_prompt(prompt)
                    .items(&options)
                    .default(0)
                    .interact_opt()
                    .unwrap_or(None);
                Ok(selection.map(|s| s + 1))
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        ui.set("select", ui_select)
            .map_err(|e| anyhow!(e.to_string()))?;

        let ui_table = self
            .lua
            .create_function(
                |_, (headers, rows): (Vec<String>, Vec<Vec<String>>)| {
                    let mut table = ComfyTable::new();
                    table.load_style(UTF8_FULL).set_header(headers);
                    for row in rows {
                        table.add_row(row);
                    }
                    println!("{table}");
                    Ok(())
                }
            )
            .map_err(|e| anyhow!(e.to_string()))?;
        ui.set("table", ui_table)
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("ui", ui).map_err(|e| anyhow!(e.to_string()))?;

        let system = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;
        let platform = utils::get_platform()
            .unwrap_or_else(|_| "unknown-unknown".to_string());
        let parts: Vec<&str> = platform.split('-').collect();
        system
            .set("os", parts.first().unwrap_or(&"unknown").to_string())
            .map_err(|e| anyhow!(e.to_string()))?;
        system
            .set("arch", parts.get(1).unwrap_or(&"unknown").to_string())
            .map_err(|e| anyhow!(e.to_string()))?;
        if let Some(distro) = utils::get_linux_distribution() {
            system
                .set("distro", distro)
                .map_err(|e| anyhow!(e.to_string()))?;
        }
        if let Some(dv) = utils::get_distro_version() {
            system
                .set("distro_ver", dv)
                .map_err(|e| anyhow!(e.to_string()))?;
        }

        zoi.set("system", system)
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("version", env!("CARGO_PKG_VERSION"))
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("scope", "user") // Default
            .map_err(|e| anyhow!(e.to_string()))?;

        let shell = self
            .lua
            .create_function(|lua, cmd: String| {
                let env_overrides: Table = lua
                    .globals()
                    .get(PLUGIN_ENV_OVERRIDES_KEY)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;

                let mut command = if cfg!(target_os = "windows") {
                    let mut c = std::process::Command::new("pwsh");
                    c.arg("-Command").arg(&cmd);
                    c
                } else {
                    let mut c = std::process::Command::new("bash");
                    c.arg("-c").arg(&cmd);
                    c
                };

                for pair in env_overrides.pairs::<String, String>() {
                    let (key, value) = pair.map_err(|e| {
                        mlua::Error::RuntimeError(e.to_string())
                    })?;
                    command.env(key, value);
                }

                if let Ok(zoi_table) = lua.globals().get::<Table>("zoi")
                    && let Ok(scope_str) = zoi_table.get::<String>("scope")
                {
                    command.env("ZOI_SCOPE", scope_str);
                }

                let status = command.status();
                match status {
                    Ok(s) => Ok(s.code().unwrap_or(i32::from(!s.success()))),
                    Err(e) => Err(mlua::Error::RuntimeError(e.to_string()))
                }
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("sh", shell).map_err(|e| anyhow!(e.to_string()))?;

        let fs_table = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;
        let fs_read = self
            .lua
            .create_function(
                |_, path: String| Ok(fs::read_to_string(path).ok())
            )
            .map_err(|e| anyhow!(e.to_string()))?;
        fs_table
            .set("read", fs_read)
            .map_err(|e| anyhow!(e.to_string()))?;

        let fs_write = self
            .lua
            .create_function(|_, (path, content): (String, String)| {
                Ok(fs::write(path, content).is_ok())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        fs_table
            .set("write", fs_write)
            .map_err(|e| anyhow!(e.to_string()))?;

        let fs_exists = self
            .lua
            .create_function(|_, path: String| Ok(PathBuf::from(path).exists()))
            .map_err(|e| anyhow!(e.to_string()))?;
        fs_table
            .set("exists", fs_exists)
            .map_err(|e| anyhow!(e.to_string()))?;

        let fs_list = self
            .lua
            .create_function(|lua, path: String| {
                let mut entries = Vec::new();
                if let Ok(read_dir) = fs::read_dir(path) {
                    for entry in read_dir.flatten() {
                        entries.push(
                            entry.file_name().to_string_lossy().to_string()
                        );
                    }
                }
                lua.to_value(&entries)
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        fs_table
            .set("list", fs_list)
            .map_err(|e| anyhow!(e.to_string()))?;

        let fs_delete = self
            .lua
            .create_function(|_, path: String| {
                let p = PathBuf::from(path);
                if p.is_dir() {
                    Ok(fs::remove_dir_all(p).is_ok())
                } else {
                    Ok(fs::remove_file(p).is_ok())
                }
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        fs_table
            .set("delete", fs_delete)
            .map_err(|e| anyhow!(e.to_string()))?;

        let fs_symlink = self
            .lua
            .create_function(
                |_, (target, link, is_dir): (String, String, bool)| {
                    let target_path = PathBuf::from(target);
                    let link_path = PathBuf::from(link);
                    if is_dir {
                        Ok(utils::symlink_dir(&target_path, &link_path).is_ok())
                    } else {
                        Ok(utils::symlink_file(&target_path, &link_path)
                            .is_ok())
                    }
                }
            )
            .map_err(|e| anyhow!(e.to_string()))?;
        fs_table
            .set("symlink", fs_symlink)
            .map_err(|e| anyhow!(e.to_string()))?;

        let fs_copy = self
            .lua
            .create_function(|_, (src, dest): (String, String)| {
                let src_path = Path::new(&src);
                let dest_path = Path::new(&dest);
                if src_path.is_dir() {
                    Ok(utils::copy_dir_all(src_path, dest_path).is_ok())
                } else {
                    Ok(fs::copy(src_path, dest_path).is_ok())
                }
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        fs_table
            .set("copy", fs_copy)
            .map_err(|e| anyhow!(e.to_string()))?;

        zoi.set("fs", fs_table)
            .map_err(|e| anyhow!(e.to_string()))?;

        let archive_table = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;
        let archive_extract = self
            .lua
            .create_function(
                |_, (source, dest, strip): (String, String, Option<usize>)| {
                    fn safe_stripped_relative_path(
                        path: &Path,
                        strip: usize
                    ) -> Result<Option<PathBuf>, std::io::Error>
                    {
                        let mut sanitized = PathBuf::new();
                        let mut has_component = false;
                        for component in path.components().skip(strip) {
                            match component {
                                std::path::Component::Normal(part) => {
                                    sanitized.push(part);
                                    has_component = true;
                                }
                                std::path::Component::CurDir => {}
                                _ => {
                                    return Err(std::io::Error::new(
                                        std::io::ErrorKind::InvalidInput,
                                        format!(
                                            "Archive entry escapes \
                                             destination: {}",
                                            path.display()
                                        )
                                    ));
                                }
                            }
                        }
                        if has_component {
                            Ok(Some(sanitized))
                        } else {
                            Ok(None)
                        }
                    }

                    fn unpack_with_strip<R: std::io::Read>(
                        mut archive: tar::Archive<R>,
                        dest: &Path,
                        strip: usize
                    ) -> Result<(), std::io::Error> {
                        for entry in archive.entries()? {
                            let mut entry = entry?;
                            let path = entry.path()?.to_path_buf();
                            let Some(stripped_path) =
                                safe_stripped_relative_path(&path, strip)?
                            else {
                                continue;
                            };
                            entry.unpack(dest.join(stripped_path))?;
                        }
                        Ok(())
                    }

                    let src_path = Path::new(&source);
                    let dest_path = Path::new(&dest);

                    if !dest_path.exists() {
                        let _ = fs::create_dir_all(dest_path);
                    }

                    let file = fs::File::open(src_path).map_err(|e| {
                        mlua::Error::RuntimeError(e.to_string())
                    })?;
                    let archive_path_str = source.to_lowercase();

                    let strip_val = strip.unwrap_or(0);

                    if std::path::Path::new(&archive_path_str)
                        .extension()
                        .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
                    {
                        let mut archive =
                            zip::ZipArchive::new(file).map_err(|e| {
                                mlua::Error::RuntimeError(e.to_string())
                            })?;
                        if strip_val > 0 {
                            for i in 0..archive.len() {
                                let mut file =
                                    archive.by_index(i).map_err(|e| {
                                        mlua::Error::RuntimeError(e.to_string())
                                    })?;
                                let path = PathBuf::from(file.name());
                                let Some(stripped_path) =
                                    safe_stripped_relative_path(
                                        &path, strip_val
                                    )
                                    .map_err(|e| {
                                        mlua::Error::RuntimeError(e.to_string())
                                    })?
                                else {
                                    continue;
                                };
                                let out_path = dest_path.join(stripped_path);
                                if file.is_dir() {
                                    fs::create_dir_all(&out_path).map_err(
                                        |e| {
                                            mlua::Error::RuntimeError(
                                                e.to_string()
                                            )
                                        }
                                    )?;
                                } else {
                                    if let Some(p) = out_path.parent() {
                                        fs::create_dir_all(p).map_err(|e| {
                                            mlua::Error::RuntimeError(
                                                e.to_string()
                                            )
                                        })?;
                                    }
                                    let mut outfile = fs::File::create(
                                        &out_path
                                    )
                                    .map_err(|e| {
                                        mlua::Error::RuntimeError(e.to_string())
                                    })?;
                                    std::io::copy(&mut file, &mut outfile)
                                        .map_err(|e| {
                                            mlua::Error::RuntimeError(
                                                e.to_string()
                                            )
                                        })?;
                                }
                            }
                        } else {
                            archive.extract(dest_path).map_err(|e| {
                                mlua::Error::RuntimeError(e.to_string())
                            })?;
                        }
                    } else if archive_path_str.ends_with(".tar.gz")
                        || std::path::Path::new(&archive_path_str)
                            .extension()
                            .is_some_and(|ext| ext.eq_ignore_ascii_case("tgz"))
                    {
                        let tar_gz = flate2::read::GzDecoder::new(file);
                        let archive = tar::Archive::new(tar_gz);
                        if strip_val > 0 {
                            unpack_with_strip(archive, dest_path, strip_val)
                                .map_err(|e| {
                                    mlua::Error::RuntimeError(e.to_string())
                                })?;
                        } else {
                            let mut archive = archive;
                            archive.unpack(dest_path).map_err(|e| {
                                mlua::Error::RuntimeError(e.to_string())
                            })?;
                        }
                    } else if archive_path_str.ends_with(".tar.zst") {
                        let tar_zst = zstd::stream::read::Decoder::new(file)
                            .map_err(|e| {
                                mlua::Error::RuntimeError(e.to_string())
                            })?;
                        let archive = tar::Archive::new(tar_zst);
                        if strip_val > 0 {
                            unpack_with_strip(archive, dest_path, strip_val)
                                .map_err(|e| {
                                    mlua::Error::RuntimeError(e.to_string())
                                })?;
                        } else {
                            let mut archive = archive;
                            archive.unpack(dest_path).map_err(|e| {
                                mlua::Error::RuntimeError(e.to_string())
                            })?;
                        }
                    } else if archive_path_str.ends_with(".tar.xz") {
                        let tar_xz = xz2::read::XzDecoder::new(file);
                        let archive = tar::Archive::new(tar_xz);
                        if strip_val > 0 {
                            unpack_with_strip(archive, dest_path, strip_val)
                                .map_err(|e| {
                                    mlua::Error::RuntimeError(e.to_string())
                                })?;
                        } else {
                            let mut archive = archive;
                            archive.unpack(dest_path).map_err(|e| {
                                mlua::Error::RuntimeError(e.to_string())
                            })?;
                        }
                    } else {
                        return Err(mlua::Error::RuntimeError(format!(
                            "Unsupported archive format: {source}"
                        )));
                    }
                    Ok(true)
                }
            )
            .map_err(|e| anyhow!(e.to_string()))?;
        archive_table
            .set("extract", archive_extract)
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("archive", archive_table)
            .map_err(|e| anyhow!(e.to_string()))?;

        let http_table = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;
        let http_get = self
            .lua
            .create_function(|_, url: String| {
                let client = reqwest::blocking::Client::builder()
                    .user_agent("zoi-plugin")
                    .build()
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                match client.get(&url).send() {
                    Ok(resp) => Ok(resp.text().ok()),
                    Err(_) => Ok(None)
                }
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        http_table
            .set("get", http_get)
            .map_err(|e| anyhow!(e.to_string()))?;

        let http_download = self
            .lua
            .create_function(|_, (url, dest): (String, String)| {
                let mut response = reqwest::blocking::get(&url)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                if !response.status().is_success() {
                    return Ok(false);
                }
                let mut dest_file = fs::File::create(dest)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                std::io::copy(&mut response, &mut dest_file)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                Ok(true)
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        http_table
            .set("download", http_download)
            .map_err(|e| anyhow!(e.to_string()))?;

        let http_post = self
            .lua
            .create_function(|_, (url, body): (String, String)| {
                let client = reqwest::blocking::Client::builder()
                    .user_agent("zoi-plugin")
                    .build()
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                match client.post(&url).body(body).send() {
                    Ok(resp) => Ok(resp.text().ok()),
                    Err(_) => Ok(None)
                }
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        http_table
            .set("post", http_post)
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("http", http_table)
            .map_err(|e| anyhow!(e.to_string()))?;

        let json_table = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;
        let json_parse = self
            .lua
            .create_function(|lua, json_str: String| {
                let parsed: serde_json::Value = serde_json::from_str(&json_str)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                lua.to_value(&parsed)
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        json_table
            .set("parse", json_parse)
            .map_err(|e| anyhow!(e.to_string()))?;

        let json_stringify = self
            .lua
            .create_function(|lua, value: Value| {
                let json_val: serde_json::Value = lua
                    .from_value(value)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                Ok(serde_json::to_string(&json_val).unwrap_or_default())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        json_table
            .set("stringify", json_stringify)
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("json", json_table)
            .map_err(|e| anyhow!(e.to_string()))?;

        let env_table = self
            .lua
            .create_table()
            .map_err(|e| anyhow!(e.to_string()))?;
        let env_get = self
            .lua
            .create_function(|lua, name: String| {
                let env_overrides: Table = lua
                    .globals()
                    .get(PLUGIN_ENV_OVERRIDES_KEY)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;

                if let Some(value) = env_overrides
                    .get::<Option<String>>(name.as_str())
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?
                {
                    return Ok(Some(value));
                }

                Ok(std::env::var(name).ok())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        env_table
            .set("get", env_get)
            .map_err(|e| anyhow!(e.to_string()))?;

        let env_set = self
            .lua
            .create_function(|lua, (name, value): (String, String)| {
                let env_overrides: Table = lua
                    .globals()
                    .get(PLUGIN_ENV_OVERRIDES_KEY)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                env_overrides
                    .set(name, value)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                Ok(())
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        env_table
            .set("set", env_set)
            .map_err(|e| anyhow!(e.to_string()))?;
        zoi.set("env", env_table)
            .map_err(|e| anyhow!(e.to_string()))?;

        self.lua
            .globals()
            .set("zoi", zoi)
            .map_err(|e| anyhow!(e.to_string()))?;

        let plugin_dir = get_plugin_dir()?;
        let import_fn = self
            .lua
            .create_function(move |lua, file_name: String| {
                let path = plugin_dir.join(&file_name);
                if !path.exists() {
                    return Err(mlua::Error::RuntimeError(format!(
                        "File not found: {}",
                        path.display()
                    )));
                }
                let content = fs::read_to_string(&path)
                    .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
                if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
                    match ext {
                        "json" => {
                            let val: serde_json::Value = serde_json::from_str(
                                &content
                            )
                            .map_err(|e| {
                                mlua::Error::RuntimeError(e.to_string())
                            })?;
                            return lua.to_value(&val);
                        }
                        _ => return lua.to_value(&content)
                    }
                }
                lua.to_value(&content)
            })
            .map_err(|e| anyhow!(e.to_string()))?;
        self.lua
            .globals()
            .set("IMPORT", import_fn)
            .map_err(|e| anyhow!(e.to_string()))?;

        Ok(())
    }

    /// Sets the operational scope for plugins.
    ///
    /// # Errors
    ///
    /// Returns an error if the `zoi` global table cannot be accessed or if the
    /// scope cannot be set.
    pub fn set_context(&self, scope: types::Scope) -> Result<()> {
        let zoi: Table = self
            .lua
            .globals()
            .get("zoi")
            .map_err(|e| anyhow!(e.to_string()))?;
        let scope_str = format!("{scope:?}").to_lowercase();
        zoi.set("scope", scope_str)
            .map_err(|e| anyhow!(e.to_string()))?;
        Ok(())
    }

    /// Loads and executes all trusted Lua plugins from the plugin directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the plugin directory cannot be read, if a plugin
    /// script cannot be loaded, or if a plugin execution fails.
    pub fn load_all(&self, yes: bool) -> Result<()> {
        let plugin_dir = get_plugin_dir()?;
        if !plugin_dir.exists() {
            return Ok(());
        }
        let mut plugin_paths = Vec::new();
        for entry in fs::read_dir(plugin_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("lua") {
                plugin_paths.push(path);
            }
        }
        plugin_paths.sort();

        let trusted_path = get_plugin_dir()?.join("trusted_hashes.json");
        let mut trusted: HashMap<String, String> = if trusted_path.exists() {
            let content = fs::read_to_string(&trusted_path)?;
            serde_json::from_str(&content).unwrap_or_default()
        } else {
            HashMap::new()
        };
        let mut trusted_changed = false;

        for path in plugin_paths {
            let script = fs::read_to_string(&path)?;

            let mut hasher = Sha256::new();
            hasher.update(script.as_bytes());
            let hash = hex::encode(hasher.finalize());

            let plugin_name = path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string();

            let is_trusted = trusted
                .get(&plugin_name)
                .is_some_and(|known_hash| known_hash == &hash);

            if !is_trusted {
                if yes {
                    println!(
                        "\n{}: Skipping untrusted plugin: {}. Run Zoi \
                         interactively to trust it.",
                        "Warning".yellow().bold(),
                        plugin_name.cyan()
                    );

                    continue;
                }

                println!(
                    "\n{}: Untrusted plugin detected: {}",
                    "SECURITY WARNING".yellow().bold(),
                    plugin_name.cyan()
                );
                println!(
                    "Plugins can execute arbitrary commands and modify your \
                     system."
                );
                if utils::ask_for_confirmation(
                    "Do you trust this plugin and want to execute it?",
                    false
                ) {
                    trusted.insert(plugin_name.clone(), hash);
                    trusted_changed = true;
                } else {
                    println!("Skipping untrusted plugin: {plugin_name}");
                    continue;
                }
            }

            let script_wrapper = format!(
                "local old_reg = zoi.register_command; zoi.register_command = \
                 function(a, b) if type(a) == 'string' then \
                 zoi.register_command_simple(a, b) else old_reg(a) end end; \
                 {script}"
            );
            self.lua.load(&script_wrapper).exec().map_err(|e| {
                anyhow!("Plugin error in {}: {}", path.display(), e)
            })?;
        }

        if trusted_changed {
            let content = serde_json::to_string_pretty(&trusted)?;
            fs::write(trusted_path, content)?;
        }

        Ok(())
    }

    /// Triggers a lifecycle hook, executing all registered callbacks.
    ///
    /// # Errors
    ///
    /// Returns an error if the hook registry cannot be accessed or if any
    /// callback execution fails.
    pub fn trigger_hook(
        &self,
        hook_name: &str,
        arg: Option<&Value>
    ) -> Result<()> {
        let registry: Table = self
            .lua
            .globals()
            .get("__ZOI_HOOKS")
            .map_err(|e| anyhow!(e.to_string()))?;
        if let Ok(hook_list) = registry.get::<Table>(hook_name) {
            for callback in hook_list.sequence_values::<Function>() {
                let callback = callback.map_err(|e| anyhow!(e.to_string()))?;
                if let Some(a) = arg {
                    callback
                        .call::<()>(a.clone())
                        .map_err(|e| anyhow!(e.to_string()))?;
                } else {
                    callback
                        .call::<()>(())
                        .map_err(|e| anyhow!(e.to_string()))?;
                }
            }
        }
        Ok(())
    }

    /// Triggers a lifecycle hook but ignores errors, printing a warning
    /// instead.
    pub fn trigger_hook_nonfatal(&self, hook_name: &str, arg: Option<&Value>) {
        if let Err(error) = self.trigger_hook(hook_name, arg) {
            eprintln!(
                "Warning: hook '{hook_name}' failed after the operation \
                 completed: {error}"
            );
        }
    }

    /// Triggers the shim version resolution hook.
    ///
    /// # Errors
    ///
    /// Returns an error if the hook registry cannot be accessed or if any
    /// callback execution fails.
    pub fn trigger_resolve_shim_version(
        &self,
        bin_name: &str
    ) -> Result<Option<String>> {
        let registry: Table = self
            .lua
            .globals()
            .get("__ZOI_HOOKS")
            .map_err(|e| anyhow!(e.to_string()))?;

        if let Ok(hook_list) = registry.get::<Table>("on_resolve_shim_version")
        {
            for callback in hook_list.sequence_values::<Function>() {
                let callback = callback.map_err(|e| anyhow!(e.to_string()))?;
                let result: Option<String> = callback
                    .call(bin_name)
                    .map_err(|e| anyhow!(e.to_string()))?;
                if result.is_some() {
                    return Ok(result);
                }
            }
        }
        Ok(None)
    }

    /// Triggers the project installation hook.
    ///
    /// # Errors
    ///
    /// Returns an error if the hook registry cannot be accessed or if any
    /// callback execution fails.
    pub fn trigger_project_install_hook(&self) -> Result<bool> {
        let registry: Table = self
            .lua
            .globals()
            .get("__ZOI_HOOKS")
            .map_err(|e| anyhow!(e.to_string()))?;

        if let Ok(hook_list) = registry.get::<Table>("on_project_install") {
            for callback in hook_list.sequence_values::<Function>() {
                let callback = callback.map_err(|e| anyhow!(e.to_string()))?;
                let handled: bool =
                    callback.call(()).map_err(|e| anyhow!(e.to_string()))?;
                if handled {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    /// Executes a custom command registered by a plugin.
    ///
    /// # Errors
    ///
    /// Returns an error if the command registry cannot be accessed or if the
    /// command execution fails.
    pub fn run_command(&self, name: &str, args: Vec<String>) -> Result<bool> {
        let registry: Table = self
            .lua
            .globals()
            .get("__ZOI_COMMANDS")
            .map_err(|e| anyhow!(e.to_string()))?;
        let callback: Value =
            registry.get(name).map_err(|e| anyhow!(e.to_string()))?;
        if let Value::Function(func) = callback {
            func.call::<()>(args).map_err(|e| anyhow!(e.to_string()))?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Lists all custom commands registered by plugins.
    ///
    /// # Errors
    ///
    /// Returns an error if the command registry cannot be accessed.
    pub fn list_commands(&self) -> Result<Vec<(String, String)>> {
        let registry: Table = self
            .lua
            .globals()
            .get("__ZOI_COMMANDS")
            .map_err(|e| anyhow!(e.to_string()))?;
        let help_registry: Table = self
            .lua
            .globals()
            .get("__ZOI_COMMAND_HELP")
            .map_err(|e| anyhow!(e.to_string()))?;
        let mut commands = Vec::new();
        for pair in registry.pairs::<String, Value>() {
            let (name, _) = pair.map_err(|e| anyhow!(e.to_string()))?;
            let desc: String = help_registry
                .get(name.clone())
                .unwrap_or_else(|_| String::new());
            commands.push((name, desc));
        }
        Ok(commands)
    }
}

/// Returns the path to the Zoi plugin directory.
///
/// # Errors
///
/// Returns an error if the user home directory cannot be found or if the
/// plugin directory cannot be created.
pub fn get_plugin_dir() -> Result<PathBuf> {
    let home_dir = utils::get_user_home()
        .ok_or_else(|| anyhow!("Could not find home directory."))?;
    let plugin_dir = home_dir.join(".zoi").join("plugins");
    if !plugin_dir.exists() {
        fs::create_dir_all(&plugin_dir)?;
    }
    Ok(plugin_dir)
}

/// Reads the persistent state for plugins from state.json.
fn read_plugin_state() -> Result<HashMap<String, serde_json::Value>> {
    let path = get_plugin_dir()?.join("state.json");
    if !path.exists() {
        return Ok(HashMap::new());
    }
    let content = fs::read_to_string(path)?;
    Ok(serde_json::from_str(&content).unwrap_or_default())
}

/// Writes the persistent state for plugins to state.json.
fn write_plugin_state(
    state: &HashMap<String, serde_json::Value>
) -> Result<()> {
    let path = get_plugin_dir()?.join("state.json");
    let content = serde_json::to_string_pretty(state)?;
    fs::write(path, content)?;
    Ok(())
}