diaryx_extism 1.3.2

Extism-based third-party plugin runtime for Diaryx
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
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
//! Host functions exposed to guest WASM plugins.
//!
//! These functions give guest plugins controlled, sandboxed access to the
//! Diaryx environment. They are registered with the Extism plugin via
//! [`PluginBuilder`](extism::PluginBuilder).

use std::path::{Path, PathBuf};
use std::sync::Arc;

use chrono::{Local, SecondsFormat};
use diaryx_core::fs::AsyncFileSystem;
use diaryx_core::plugin::permissions::PermissionType;
use extism::{CurrentPlugin, Error as ExtismError, UserData, Val, ValType};

use crate::permission_checker::DenyAllPermissionChecker;

/// Trait for persisting plugin state (CRDT snapshots, config, etc.).
///
/// Implementations might use SQLite on native or IndexedDB on web.
pub trait PluginStorage: Send + Sync {
    /// Load a value by key.
    fn get(&self, key: &str) -> Option<Vec<u8>>;
    /// Store a value by key.
    fn set(&self, key: &str, data: &[u8]);
    /// Delete a value by key.
    fn delete(&self, key: &str);
}

/// Trait for persisting plugin secrets separately from normal plugin state.
pub trait PluginSecretStore: Send + Sync {
    /// Load a secret by key.
    fn get(&self, key: &str) -> Option<String>;
    /// Store a secret by key.
    fn set(&self, key: &str, value: &str);
    /// Delete a secret by key.
    fn delete(&self, key: &str);
}

/// Trait for emitting events from plugins to the host application.
pub trait EventEmitter: Send + Sync {
    /// Emit an event (JSON payload) to the host.
    fn emit(&self, event_json: &str);
}

/// Trait for handling plugin-initiated websocket transport requests.
pub trait WebSocketBridge: Send + Sync {
    /// Handle a serialized websocket request and return a serialized response.
    fn request(&self, request_json: &str) -> Result<String, String>;
}

/// Trait for plugin-to-plugin command dispatch mediated by the host.
pub trait PluginCommandBridge: Send + Sync {
    /// Execute a command on another plugin and return the plugin's raw JSON data.
    fn call(
        &self,
        caller_plugin_id: &str,
        plugin_id: &str,
        command: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value, String>;
}

/// Trait for exposing generic host runtime context to plugins.
pub trait RuntimeContextProvider: Send + Sync {
    /// Return runtime context for the caller plugin.
    fn get_context(&self, plugin_id: &str) -> serde_json::Value;
}

/// No-op implementation of [`PluginStorage`] for plugins that don't need persistence.
pub struct NoopStorage;

impl PluginStorage for NoopStorage {
    fn get(&self, _key: &str) -> Option<Vec<u8>> {
        None
    }
    fn set(&self, _key: &str, _data: &[u8]) {}
    fn delete(&self, _key: &str) {}
}

/// No-op implementation of [`PluginSecretStore`] for hosts without secure storage.
pub struct NoopSecretStore;

impl PluginSecretStore for NoopSecretStore {
    fn get(&self, _key: &str) -> Option<String> {
        None
    }

    fn set(&self, _key: &str, _value: &str) {}

    fn delete(&self, _key: &str) {}
}

fn sanitize_storage_key(key: &str) -> String {
    key.chars()
        .map(|c| {
            if c == '/' || c == '\\' || c == ':' {
                '_'
            } else {
                c
            }
        })
        .collect()
}

/// File-backed [`PluginStorage`] implementation for native hosts.
pub struct FilePluginStorage {
    base_dir: PathBuf,
}

impl FilePluginStorage {
    pub fn new(base_dir: PathBuf) -> Self {
        let _ = std::fs::create_dir_all(&base_dir);
        Self { base_dir }
    }

    fn key_to_path(&self, key: &str) -> PathBuf {
        self.base_dir
            .join(format!("{}.bin", sanitize_storage_key(key)))
    }
}

impl PluginStorage for FilePluginStorage {
    fn get(&self, key: &str) -> Option<Vec<u8>> {
        std::fs::read(self.key_to_path(key)).ok()
    }

    fn set(&self, key: &str, data: &[u8]) {
        let path = self.key_to_path(key);
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let _ = std::fs::write(path, data);
    }

    fn delete(&self, key: &str) {
        let _ = std::fs::remove_file(self.key_to_path(key));
    }
}

/// File-backed [`PluginSecretStore`] implementation for native hosts.
pub struct FilePluginSecretStore {
    base_dir: PathBuf,
}

impl FilePluginSecretStore {
    pub fn new(base_dir: PathBuf) -> Self {
        let _ = std::fs::create_dir_all(&base_dir);
        Self { base_dir }
    }

    fn key_to_path(&self, key: &str) -> PathBuf {
        self.base_dir
            .join(format!("{}.secret", sanitize_storage_key(key)))
    }
}

impl PluginSecretStore for FilePluginSecretStore {
    fn get(&self, key: &str) -> Option<String> {
        std::fs::read_to_string(self.key_to_path(key)).ok()
    }

    fn set(&self, key: &str, value: &str) {
        let path = self.key_to_path(key);
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let _ = std::fs::write(path, value);
    }

    fn delete(&self, key: &str) {
        let _ = std::fs::remove_file(self.key_to_path(key));
    }
}

/// Trait for providing user-selected files to plugins.
///
/// On CLI, files come from command-line arguments (paths read into memory).
/// On browser, files come from File input elements or drag-and-drop.
/// Plugins request files by key name (e.g. "source_file", "dayone_export").
pub trait FileProvider: Send + Sync {
    /// Get file bytes by key name. Returns `None` if no file is available for that key.
    fn get_file(&self, key: &str) -> Option<Vec<u8>>;
}

/// No-op implementation of [`FileProvider`] — always returns `None`.
pub struct NoopFileProvider;

impl FileProvider for NoopFileProvider {
    fn get_file(&self, _key: &str) -> Option<Vec<u8>> {
        None
    }
}

/// [`FileProvider`] backed by a pre-populated map.
///
/// Used by the CLI to pass files read from command-line arguments.
pub struct MapFileProvider {
    files: std::collections::HashMap<String, Vec<u8>>,
}

impl MapFileProvider {
    pub fn new(files: std::collections::HashMap<String, Vec<u8>>) -> Self {
        Self { files }
    }
}

impl FileProvider for MapFileProvider {
    fn get_file(&self, key: &str) -> Option<Vec<u8>> {
        self.files.get(key).cloned()
    }
}

/// No-op implementation of [`EventEmitter`] for plugins that don't emit events.
pub struct NoopEventEmitter;

impl EventEmitter for NoopEventEmitter {
    fn emit(&self, _event_json: &str) {}
}

/// No-op websocket bridge for hosts that don't support plugin-managed transport.
pub struct NoopWebSocketBridge;

impl WebSocketBridge for NoopWebSocketBridge {
    fn request(&self, _request_json: &str) -> Result<String, String> {
        Ok(String::new())
    }
}

/// No-op plugin command bridge for hosts that do not support plugin-to-plugin calls.
pub struct NoopPluginCommandBridge;

impl PluginCommandBridge for NoopPluginCommandBridge {
    fn call(
        &self,
        _caller_plugin_id: &str,
        _plugin_id: &str,
        _command: &str,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value, String> {
        Err("Plugin command bridge is not available".to_string())
    }
}

/// No-op runtime context provider for hosts without runtime context wiring.
pub struct NoopRuntimeContextProvider;

impl RuntimeContextProvider for NoopRuntimeContextProvider {
    fn get_context(&self, _plugin_id: &str) -> serde_json::Value {
        serde_json::json!({})
    }
}

/// Trait for checking plugin permissions before allowing host function calls.
///
/// Implementations may check static config, prompt the user, or consult
/// a session-level cache.
pub trait PermissionChecker: Send + Sync {
    /// Check if a plugin has permission for an action.
    ///
    /// Returns `Ok(())` if allowed, `Err(message)` if denied.
    /// The `target` is context-dependent: file path, URL, command name, etc.
    fn check_permission(
        &self,
        plugin_id: &str,
        permission_type: PermissionType,
        target: &str,
    ) -> Result<(), String>;
}

/// Context shared with host functions via Extism's `UserData` mechanism.
///
/// Provides guest plugins with controlled access to the workspace filesystem,
/// persistent storage, and event dispatch.
pub struct HostContext {
    /// Type-erased async filesystem for workspace file access.
    pub fs: Arc<dyn AsyncFileSystem>,
    /// Persistent storage for plugin state (CRDT snapshots, etc.).
    pub storage: Arc<dyn PluginStorage>,
    /// Persistent storage for plugin secrets (tokens, API keys).
    pub secret_store: Arc<dyn PluginSecretStore>,
    /// Event emitter for sync events.
    pub event_emitter: Arc<dyn EventEmitter>,
    /// Which plugin this context belongs to.
    pub plugin_id: String,
    /// Permission checker (None = deny all).
    pub permission_checker: Option<Arc<dyn PermissionChecker>>,
    /// Provider of user-selected files (e.g. from CLI args or browser file picker).
    pub file_provider: Arc<dyn FileProvider>,
    /// WebSocket bridge for plugin-managed sync transport.
    pub ws_bridge: Arc<dyn WebSocketBridge>,
    /// Host-mediated plugin-to-plugin command bridge.
    pub plugin_command_bridge: Arc<dyn PluginCommandBridge>,
    /// Provider of generic runtime context for the caller plugin.
    pub runtime_context_provider: Arc<dyn RuntimeContextProvider>,
}

impl HostContext {
    /// Create a context with just a filesystem (backwards compatible).
    pub fn with_fs(fs: Arc<dyn AsyncFileSystem>) -> Self {
        Self {
            fs,
            storage: Arc::new(NoopStorage),
            secret_store: Arc::new(NoopSecretStore),
            event_emitter: Arc::new(NoopEventEmitter),
            plugin_id: String::new(),
            permission_checker: Some(Arc::new(DenyAllPermissionChecker)),
            file_provider: Arc::new(NoopFileProvider),
            ws_bridge: Arc::new(NoopWebSocketBridge),
            plugin_command_bridge: Arc::new(NoopPluginCommandBridge),
            runtime_context_provider: Arc::new(NoopRuntimeContextProvider),
        }
    }

    /// Check a permission, returning an Extism error if denied.
    fn check_perm(&self, perm: PermissionType, target: &str) -> Result<(), ExtismError> {
        if let Some(checker) = &self.permission_checker {
            checker
                .check_permission(&self.plugin_id, perm, target)
                .map_err(|msg| ExtismError::msg(msg))
        } else {
            Err(ExtismError::msg(
                "Permission checker is not configured for this plugin host context",
            ))
        }
    }

    fn storage_key(&self, key: &str) -> String {
        if self.plugin_id.is_empty() {
            key.to_string()
        } else {
            format!("{}:{}", self.plugin_id, key)
        }
    }

    fn secret_key(&self, key: &str) -> String {
        self.storage_key(key)
    }
}

// SAFETY: HostContext only contains Arc<dyn Trait> values which require
// Send + Sync on native targets.
unsafe impl Send for HostContext {}
unsafe impl Sync for HostContext {}

/// Register all host functions on an Extism `PluginBuilder`.
///
/// The builder is consumed and returned with host functions attached.
pub fn register_host_functions(
    builder: extism::PluginBuilder<'_>,
    user_data: UserData<HostContext>,
) -> extism::PluginBuilder<'_> {
    builder
        .with_function(
            "host_log",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_log,
        )
        .with_function(
            "host_read_file",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_read_file,
        )
        .with_function(
            "host_read_binary",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_read_binary,
        )
        .with_function(
            "host_list_files",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_list_files,
        )
        .with_function(
            "host_file_exists",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_file_exists,
        )
        .with_function(
            "host_write_file",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_write_file,
        )
        .with_function(
            "host_delete_file",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_delete_file,
        )
        .with_function(
            "host_write_binary",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_write_binary,
        )
        .with_function(
            "host_emit_event",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_emit_event,
        )
        .with_function(
            "host_storage_get",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_storage_get,
        )
        .with_function(
            "host_storage_set",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_storage_set,
        )
        .with_function(
            "host_secret_get",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_secret_get,
        )
        .with_function(
            "host_secret_set",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_secret_set,
        )
        .with_function(
            "host_secret_delete",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_secret_delete,
        )
        .with_function(
            "host_get_timestamp",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_get_timestamp,
        )
        .with_function(
            "host_get_now",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_get_now,
        )
        .with_function(
            "host_http_request",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_http_request,
        )
        .with_function(
            "host_run_wasi_module",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_run_wasi_module,
        )
        .with_function(
            "host_request_file",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_request_file,
        )
        .with_function(
            "host_plugin_command",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_plugin_command,
        )
        .with_function(
            "host_get_runtime_context",
            [ValType::I64],
            [ValType::I64],
            user_data.clone(),
            host_get_runtime_context,
        )
        .with_function(
            "host_ws_request",
            [ValType::I64],
            [ValType::I64],
            user_data,
            host_ws_request,
        )
}

/// Host function: `host_log(input: {level, message}) -> ""`
///
/// Logs a message via the `log` crate at the specified level.
fn host_log(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    _user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct LogInput {
        level: String,
        message: String,
    }

    let parsed: LogInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_log: invalid input: {e}")))?;

    match parsed.level.as_str() {
        "error" => log::error!("[extism-plugin] {}", parsed.message),
        "warn" => log::warn!("[extism-plugin] {}", parsed.message),
        "info" => log::info!("[extism-plugin] {}", parsed.message),
        "debug" => log::debug!("[extism-plugin] {}", parsed.message),
        _ => log::trace!("[extism-plugin] {}", parsed.message),
    }

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_read_file(input: {path}) -> file content string`
///
/// Reads a workspace file and returns its content.
fn host_read_file(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct ReadInput {
        path: String,
    }

    let parsed: ReadInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_read_file: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::ReadFiles, &parsed.path)?;
    let content = futures_lite::future::block_on(ctx.fs.read_to_string(Path::new(&parsed.path)))
        .map_err(|e| ExtismError::msg(format!("host_read_file: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], content.as_str())?;
    Ok(())
}

/// Host function: `host_read_binary(input: {path}) -> {data: base64}`
///
/// Reads a workspace file as raw bytes.
fn host_read_binary(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    use base64::Engine;

    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct ReadInput {
        path: String,
    }

    let parsed: ReadInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_read_binary: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::ReadFiles, &parsed.path)?;
    let bytes = futures_lite::future::block_on(ctx.fs.read_binary(Path::new(&parsed.path)))
        .map_err(|e| ExtismError::msg(format!("host_read_binary: {e}")))?;
    let json = serde_json::json!({
        "data": base64::engine::general_purpose::STANDARD.encode(&bytes)
    })
    .to_string();

    plugin.memory_set_val(&mut outputs[0], json.as_str())?;
    Ok(())
}

/// Host function: `host_list_files(input: {prefix}) -> string[] JSON`
///
/// Lists files under a given prefix in the workspace.
fn host_list_files(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct ListInput {
        prefix: String,
    }

    let parsed: ListInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_list_files: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::ReadFiles, &parsed.prefix)?;
    let files =
        futures_lite::future::block_on(ctx.fs.list_all_files_recursive(Path::new(&parsed.prefix)))
            .map_err(|e| ExtismError::msg(format!("host_list_files: {e}")))?;

    let file_strings: Vec<String> = files
        .iter()
        .map(|p| p.to_string_lossy().to_string())
        .collect();
    let json = serde_json::to_string(&file_strings)
        .map_err(|e| ExtismError::msg(format!("host_list_files: serialize: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], json.as_str())?;
    Ok(())
}

/// Host function: `host_file_exists(input: {path}) -> bool JSON`
///
/// Checks if a file exists in the workspace.
fn host_file_exists(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct ExistsInput {
        path: String,
    }

    let parsed: ExistsInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_file_exists: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::ReadFiles, &parsed.path)?;
    // exists() returns bool directly (not Result<bool>)
    let exists = futures_lite::future::block_on(ctx.fs.exists(Path::new(&parsed.path)));

    let json = serde_json::to_string(&exists)
        .map_err(|e| ExtismError::msg(format!("host_file_exists: serialize: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], json.as_str())?;
    Ok(())
}

/// Host function: `host_write_file(input: {path, content}) -> ""`
///
/// Writes a text file to the workspace.
fn host_write_file(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct WriteInput {
        path: String,
        content: String,
    }

    let parsed: WriteInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_write_file: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    // Check edit or create based on whether the file exists
    let exists = futures_lite::future::block_on(ctx.fs.exists(Path::new(&parsed.path)));
    let perm = if exists {
        PermissionType::EditFiles
    } else {
        PermissionType::CreateFiles
    };
    ctx.check_perm(perm, &parsed.path)?;
    futures_lite::future::block_on(ctx.fs.write_file(Path::new(&parsed.path), &parsed.content))
        .map_err(|e| ExtismError::msg(format!("host_write_file: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_delete_file(input: {path}) -> ""`
///
/// Deletes a file from the workspace.
fn host_delete_file(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct DeleteInput {
        path: String,
    }

    let parsed: DeleteInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_delete_file: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::DeleteFiles, &parsed.path)?;
    futures_lite::future::block_on(ctx.fs.delete_file(Path::new(&parsed.path)))
        .map_err(|e| ExtismError::msg(format!("host_delete_file: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_write_binary(input: {path, content}) -> ""`
///
/// Writes binary content (base64-encoded) to a file.
fn host_write_binary(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    use base64::Engine;

    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct WriteBinaryInput {
        path: String,
        content: String, // base64-encoded
    }

    let parsed: WriteBinaryInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_write_binary: invalid input: {e}")))?;

    let bytes = base64::engine::general_purpose::STANDARD
        .decode(&parsed.content)
        .map_err(|e| ExtismError::msg(format!("host_write_binary: base64 decode: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    let exists = futures_lite::future::block_on(ctx.fs.exists(Path::new(&parsed.path)));
    let perm = if exists {
        PermissionType::EditFiles
    } else {
        PermissionType::CreateFiles
    };
    ctx.check_perm(perm, &parsed.path)?;
    futures_lite::future::block_on(ctx.fs.write_binary(Path::new(&parsed.path), &bytes))
        .map_err(|e| ExtismError::msg(format!("host_write_binary: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_emit_event(input: event_json) -> ""`
///
/// Emits a sync event to the host application.
fn host_emit_event(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let event_json: String = plugin.memory_get_val(&inputs[0])?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.event_emitter.emit(&event_json);

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_storage_get(input: {key}) -> {data: base64} or ""`
///
/// Loads persisted state by key.
fn host_storage_get(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    use base64::Engine;

    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct StorageGetInput {
        key: String,
    }

    let parsed: StorageGetInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_storage_get: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::PluginStorage, &parsed.key)?;
    let storage_key = ctx.storage_key(&parsed.key);

    let result = match ctx.storage.get(&storage_key) {
        Some(data) => {
            let encoded = base64::engine::general_purpose::STANDARD.encode(&data);
            serde_json::json!({ "data": encoded }).to_string()
        }
        None => String::new(),
    };

    plugin.memory_set_val(&mut outputs[0], result.as_str())?;
    Ok(())
}

/// Host function: `host_storage_set(input: {key, data}) -> ""`
///
/// Persists state by key (data is base64-encoded).
fn host_storage_set(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    use base64::Engine;

    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct StorageSetInput {
        key: String,
        data: String, // base64-encoded
    }

    let parsed: StorageSetInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_storage_set: invalid input: {e}")))?;

    let bytes = base64::engine::general_purpose::STANDARD
        .decode(&parsed.data)
        .map_err(|e| ExtismError::msg(format!("host_storage_set: base64 decode: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::PluginStorage, &parsed.key)?;
    let storage_key = ctx.storage_key(&parsed.key);
    ctx.storage.set(&storage_key, &bytes);

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_secret_get(input: {key}) -> {value: string} or ""`
///
/// Loads a secret value by key.
fn host_secret_get(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct SecretGetInput {
        key: String,
    }

    let parsed: SecretGetInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_secret_get: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::PluginStorage, &parsed.key)?;
    let secret_key = ctx.secret_key(&parsed.key);

    let result = match ctx.secret_store.get(&secret_key) {
        Some(value) => serde_json::json!({ "value": value }).to_string(),
        None => String::new(),
    };

    plugin.memory_set_val(&mut outputs[0], result.as_str())?;
    Ok(())
}

/// Host function: `host_secret_set(input: {key, value}) -> ""`
///
/// Persists a secret value by key.
fn host_secret_set(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct SecretSetInput {
        key: String,
        value: String,
    }

    let parsed: SecretSetInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_secret_set: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::PluginStorage, &parsed.key)?;
    let secret_key = ctx.secret_key(&parsed.key);
    ctx.secret_store.set(&secret_key, &parsed.value);

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_secret_delete(input: {key}) -> ""`
///
/// Deletes a secret value by key.
fn host_secret_delete(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct SecretDeleteInput {
        key: String,
    }

    let parsed: SecretDeleteInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_secret_delete: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::PluginStorage, &parsed.key)?;
    let secret_key = ctx.secret_key(&parsed.key);
    ctx.secret_store.delete(&secret_key);

    plugin.memory_set_val(&mut outputs[0], "")?;
    Ok(())
}

/// Host function: `host_run_wasi_module(input: WasiRunRequest) -> WasiRunResult`
///
/// Runs a WASI module stored in plugin storage. The guest provides a storage
/// key, CLI arguments, optional stdin, virtual filesystem files, and a list
/// of output files to capture. Only available when the `wasi-runner` feature
/// is enabled.
#[cfg(feature = "wasi-runner")]
fn host_run_wasi_module(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    use base64::Engine;

    let input: String = plugin.memory_get_val(&inputs[0])?;
    let request: crate::wasi_runner::WasiRunRequest = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_run_wasi_module: invalid input: {e}")))?;

    // Load the WASM module bytes from plugin storage
    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    ctx.check_perm(PermissionType::PluginStorage, &request.module_key)?;
    let storage_key = ctx.storage_key(&request.module_key);
    let wasm_bytes = ctx.storage.get(&storage_key).ok_or_else(|| {
        ExtismError::msg(format!(
            "host_run_wasi_module: module not found in storage: {}",
            request.module_key
        ))
    })?;
    drop(ctx);

    // Decode input files from base64
    let decoded_files = if let Some(ref files) = request.files {
        let mut map = std::collections::HashMap::new();
        for (path, b64) in files {
            let data = base64::engine::general_purpose::STANDARD
                .decode(b64)
                .map_err(|e| {
                    ExtismError::msg(format!(
                        "host_run_wasi_module: base64 decode for {path}: {e}"
                    ))
                })?;
            map.insert(path.clone(), data);
        }
        Some(map)
    } else {
        None
    };

    // Decode stdin from base64
    let stdin_bytes = if let Some(ref b64) = request.stdin {
        Some(
            base64::engine::general_purpose::STANDARD
                .decode(b64)
                .map_err(|e| {
                    ExtismError::msg(format!("host_run_wasi_module: stdin base64 decode: {e}"))
                })?,
        )
    } else {
        None
    };

    // Run the module
    let result = crate::wasi_runner::run_wasi_module(
        &wasm_bytes,
        &request.args,
        stdin_bytes.as_deref(),
        decoded_files.as_ref(),
        request.output_files.as_deref(),
    )
    .map_err(|e| ExtismError::msg(format!("host_run_wasi_module: {e}")))?;

    let json = serde_json::to_string(&result)
        .map_err(|e| ExtismError::msg(format!("host_run_wasi_module: serialize: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], json.as_str())?;
    Ok(())
}

/// Stub for `host_run_wasi_module` when the `wasi-runner` feature is not enabled.
#[cfg(not(feature = "wasi-runner"))]
fn host_run_wasi_module(
    plugin: &mut CurrentPlugin,
    _inputs: &[Val],
    outputs: &mut [Val],
    _user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let error = serde_json::json!({
        "exit_code": -1,
        "stdout": "",
        "stderr": "host_run_wasi_module: wasi-runner feature not enabled"
    });
    plugin.memory_set_val(&mut outputs[0], error.to_string().as_str())?;
    Ok(())
}

/// Host function: `host_get_timestamp(input: "") -> timestamp_ms string`
///
/// Returns the current timestamp in milliseconds since epoch.
fn host_get_timestamp(
    plugin: &mut CurrentPlugin,
    _inputs: &[Val],
    outputs: &mut [Val],
    _user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);

    plugin.memory_set_val(&mut outputs[0], now.to_string().as_str())?;
    Ok(())
}

/// Host function: `host_get_now(input: "") -> local RFC 3339 timestamp string`
fn host_get_now(
    plugin: &mut CurrentPlugin,
    _inputs: &[Val],
    outputs: &mut [Val],
    _user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let now = Local::now().to_rfc3339_opts(SecondsFormat::Secs, false);
    plugin.memory_set_val(&mut outputs[0], now.as_str())?;
    Ok(())
}

/// Host function: `host_request_file(input: {key}) -> raw bytes or empty`
///
/// Requests a user-provided file by key name. The host decides where the
/// file comes from (CLI: read from path in command args; browser: File picker).
/// Returns the raw file bytes, or an empty result if unavailable.
fn host_request_file(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct RequestFileInput {
        key: String,
    }

    let parsed: RequestFileInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_request_file: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();

    let result = ctx.file_provider.get_file(&parsed.key).unwrap_or_default();

    plugin.memory_set_val(&mut outputs[0], result.as_slice())?;
    Ok(())
}

/// Host function: `host_plugin_command(input: {plugin_id, command, params}) -> {success, data?, error?}`
///
/// Executes a command on another loaded plugin through the host bridge.
fn host_plugin_command(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    #[derive(serde::Deserialize)]
    struct PluginCommandInput {
        plugin_id: String,
        command: String,
        #[serde(default)]
        params: serde_json::Value,
    }

    let input: String = plugin.memory_get_val(&inputs[0])?;
    let parsed: PluginCommandInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_plugin_command: invalid input: {e}")))?;

    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();

    let response = if parsed.plugin_id.trim().is_empty() || parsed.command.trim().is_empty() {
        serde_json::json!({
            "success": false,
            "error": "plugin_id and command are required",
        })
    } else if parsed.plugin_id == ctx.plugin_id {
        serde_json::json!({
            "success": false,
            "error": "Plugins cannot call their own commands via host_plugin_command",
        })
    } else {
        let permission_target = format!("{}:{}", parsed.plugin_id, parsed.command);
        match ctx.check_perm(PermissionType::ExecuteCommands, &permission_target) {
            Ok(()) => match ctx.plugin_command_bridge.call(
                &ctx.plugin_id,
                &parsed.plugin_id,
                &parsed.command,
                parsed.params,
            ) {
                Ok(data) => serde_json::json!({
                    "success": true,
                    "data": data,
                }),
                Err(error) => serde_json::json!({
                    "success": false,
                    "error": error,
                }),
            },
            Err(error) => serde_json::json!({
                "success": false,
                "error": error.to_string(),
            }),
        }
    };

    let json = serde_json::to_string(&response)
        .map_err(|e| ExtismError::msg(format!("host_plugin_command: serialize: {e}")))?;
    plugin.memory_set_val(&mut outputs[0], json.as_str())?;
    Ok(())
}

/// Host function: `host_get_runtime_context(input: "") -> json`
///
/// Returns generic host runtime context for the caller plugin.
fn host_get_runtime_context(
    plugin: &mut CurrentPlugin,
    _inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    let json = serde_json::to_string(&ctx.runtime_context_provider.get_context(&ctx.plugin_id))
        .map_err(|e| ExtismError::msg(format!("host_get_runtime_context: serialize: {e}")))?;
    plugin.memory_set_val(&mut outputs[0], json.as_str())?;
    Ok(())
}

/// Host function: `host_ws_request(input: json) -> string`
///
/// Forward-compatible bridge for plugin-managed websocket ownership.
/// The concrete host bridge owns the socket lifecycle and maps these
/// requests to runtime-specific websocket operations.
fn host_ws_request(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let input: String = plugin.memory_get_val(&inputs[0])?;
    let ctx = user_data.get()?;
    let ctx = ctx.lock().unwrap();
    let result = ctx.ws_bridge.request(&input).map_err(ExtismError::msg)?;
    plugin.memory_set_val(&mut outputs[0], result.as_str())?;
    Ok(())
}

/// Host function: `host_http_request(input: {url, method, headers, body?, timeout_ms?}) -> {status, headers, body}`
///
/// Performs an HTTP request and returns the response. Only available when
/// the `http` feature is enabled (native builds). On WASM the browser
/// host functions provide the equivalent via `fetch()`.
#[cfg(feature = "http")]
fn host_http_request(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    use base64::Engine as _;
    use ureq::http::Request;

    let input: String = plugin.memory_get_val(&inputs[0])?;

    #[derive(serde::Deserialize)]
    struct HttpInput {
        url: String,
        method: String,
        headers: std::collections::HashMap<String, String>,
        body: Option<String>,
        /// Base64-encoded binary body. Takes priority over `body` when present.
        body_base64: Option<String>,
        /// Optional request timeout in milliseconds.
        timeout_ms: Option<u64>,
    }

    #[derive(serde::Serialize)]
    struct HttpOutput {
        status: u16,
        headers: std::collections::HashMap<String, String>,
        body: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        body_base64: Option<String>,
    }

    let parsed: HttpInput = serde_json::from_str(&input)
        .map_err(|e| ExtismError::msg(format!("host_http_request: invalid input: {e}")))?;

    {
        let ctx = user_data.get()?;
        let ctx = ctx.lock().unwrap();
        ctx.check_perm(PermissionType::HttpRequests, &parsed.url)?;
    }

    const MIN_HTTP_TIMEOUT_MS: u64 = 1_000;
    const MAX_HTTP_TIMEOUT_MS: u64 = 300_000;

    let timeout = parsed
        .timeout_ms
        .map(|value| value.clamp(MIN_HTTP_TIMEOUT_MS, MAX_HTTP_TIMEOUT_MS))
        .map(std::time::Duration::from_millis);
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .timeout_global(timeout)
        .build()
        .into();

    let mut request_builder = Request::builder()
        .method(parsed.method.as_str())
        .uri(parsed.url.as_str());
    for (key, value) in &parsed.headers {
        request_builder = request_builder.header(key, value);
    }

    let response = if let Some(b64) = &parsed.body_base64 {
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .map_err(|e| ExtismError::msg(format!("host_http_request: base64 decode: {e}")))?;
        let request = request_builder
            .body(bytes)
            .map_err(|e| ExtismError::msg(format!("host_http_request: invalid request: {e}")))?;
        agent
            .run(request)
            .map_err(|e| ExtismError::msg(format!("host_http_request: {e}")))?
    } else if let Some(body) = &parsed.body {
        let request = request_builder
            .body(body.clone())
            .map_err(|e| ExtismError::msg(format!("host_http_request: invalid request: {e}")))?;
        agent
            .run(request)
            .map_err(|e| ExtismError::msg(format!("host_http_request: {e}")))?
    } else {
        let request = request_builder
            .body(())
            .map_err(|e| ExtismError::msg(format!("host_http_request: invalid request: {e}")))?;
        agent
            .run(request)
            .map_err(|e| ExtismError::msg(format!("host_http_request: {e}")))?
    };

    let status = response.status().as_u16();
    let mut resp_headers = std::collections::HashMap::new();
    for (name, value) in response.headers() {
        if let Ok(value) = value.to_str() {
            resp_headers.insert(name.to_string(), value.to_string());
        }
    }
    let mut response = response;
    let body_bytes = response
        .body_mut()
        .read_to_vec()
        .map_err(|e| ExtismError::msg(format!("host_http_request: read body: {e}")))?;
    let body = String::from_utf8_lossy(&body_bytes).to_string();
    let body_base64 = Some(base64::engine::general_purpose::STANDARD.encode(&body_bytes));

    let output = HttpOutput {
        status,
        headers: resp_headers,
        body,
        body_base64,
    };

    let json = serde_json::to_string(&output)
        .map_err(|e| ExtismError::msg(format!("host_http_request: serialize: {e}")))?;

    plugin.memory_set_val(&mut outputs[0], json.as_str())?;
    Ok(())
}

/// Stub for `host_http_request` when the `http` feature is not enabled.
#[cfg(not(feature = "http"))]
fn host_http_request(
    plugin: &mut CurrentPlugin,
    _inputs: &[Val],
    outputs: &mut [Val],
    _user_data: UserData<HostContext>,
) -> Result<(), ExtismError> {
    let error = serde_json::json!({
        "status": 0,
        "headers": {},
        "body": "host_http_request: http feature not enabled"
    });
    plugin.memory_set_val(&mut outputs[0], error.to_string().as_str())?;
    Ok(())
}