-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlib.rs
More file actions
2945 lines (2693 loc) · 102 KB
/
Copy pathlib.rs
File metadata and controls
2945 lines (2693 loc) · 102 KB
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
// napi macros generate code that triggers some clippy lints
#![allow(clippy::needless_pass_by_value, clippy::trivially_copy_pass_by_ref)]
//! Node.js/TypeScript bindings for the Bashkit sandboxed bash interpreter.
//!
//! Exposes `Bash` (core interpreter), `BashTool` (interpreter + LLM metadata),
//! and `ExecResult` via napi-rs for use from JavaScript/TypeScript.
//!
//! # Safety: `Arc<SharedState>` pattern
//!
//! Both `Bash` and `BashTool` wrap all mutable state in `Arc<SharedState>`.
//! Every `#[napi]` method clones the `Arc` *before* doing any blocking or async
//! work. This prevents CodeQL `rust/access-invalid-pointer` alerts caused by
//! holding a raw-pointer-derived `&self` across `block_on` or `.await` points.
use bashkit::interop::fs::{
BashkitFsAbiHandleV1, BashkitFsAbiOwnedHandleV1, export_filesystem, import_filesystem,
};
use bashkit::tool::VERSION;
use bashkit::{
Bash as RustBash, BashTool as RustBashTool, Builtin, BuiltinContext, BuiltinRegistry,
ExecResult as RustExecResult, ExecutionLimits, ExtFunctionResult, FileSystem as BashFileSystem,
FileType, InMemoryFs, Metadata, MontyObject, OutputCallback, PosixFs, PythonExternalFnHandler,
PythonLimits, RealFs, RealFsMode, ScriptedTool as RustScriptedTool,
SnapshotOptions as RustSnapshotOptions, Tool, ToolArgs, ToolDef, ToolRequest, async_trait,
};
use napi::bindgen_prelude::External;
use napi::{Env, JsValue, Unknown, ValueType, sys};
use napi_derive::napi;
use std::collections::HashMap;
use std::ffi::c_void;
use std::mem::{MaybeUninit, size_of};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::ptr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex as StdMutex};
use tokio::sync::Mutex;
// ---------------------------------------------------------------------------
// Shared tokio runtime + concurrency limiter for JS tool callbacks (issue #982).
// A single multi-thread runtime is created lazily and reused for every callback
// invocation, replacing the previous pattern of spawning an unbounded number of
// OS threads each with its own single-threaded runtime. A semaphore caps the
// maximum number of concurrent in-flight callbacks to prevent DoS.
// ---------------------------------------------------------------------------
const MAX_CONCURRENT_TOOL_CALLBACKS: usize = 10;
fn callback_runtime() -> &'static tokio::runtime::Runtime {
use std::sync::OnceLock;
static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
RT.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.expect("failed to create shared callback runtime")
})
}
fn callback_semaphore() -> &'static tokio::sync::Semaphore {
use std::sync::OnceLock;
static SEM: OnceLock<tokio::sync::Semaphore> = OnceLock::new();
SEM.get_or_init(|| tokio::sync::Semaphore::new(MAX_CONCURRENT_TOOL_CALLBACKS))
}
// Decision: reject same-instance onOutput re-entry at the binding boundary so
// sync paths fail with a JS error instead of deadlocking or panicking.
const ON_OUTPUT_REENTRY_ERROR: &str = "onOutput cannot re-enter the same Bash instance; use collected output or another Bash instance for live access";
// Decision: surface the executeSync+custom-builtin deadlock as a normal script
// error instead of a silent hang. executeSync blocks the JS event loop via
// block_on, but a JsCustomBuiltinAdapter dispatches its callback over a
// threadsafe function that requires the loop to be free — the call would never
// resolve. Detect that case and fail the builtin with exit 1 + a clear message
// so the user sees a real error and can migrate to async execute().
const SYNC_BUILTIN_DEADLOCK_ERROR: &str = "custom builtins require execute() (async). executeSync() would deadlock because the JS event loop is blocked while the synchronous call is in flight";
struct OnOutputReentryScope {
depth: Arc<AtomicUsize>,
}
impl OnOutputReentryScope {
fn enter(depth: Arc<AtomicUsize>) -> Self {
depth.fetch_add(1, Ordering::SeqCst);
Self { depth }
}
}
impl Drop for OnOutputReentryScope {
fn drop(&mut self) {
self.depth.fetch_sub(1, Ordering::SeqCst);
}
}
fn reject_on_output_reentry(state: &Arc<SharedState>) -> napi::Result<()> {
if state.on_output_reentry_depth.load(Ordering::SeqCst) > 0 {
return Err(napi::Error::from_reason(ON_OUTPUT_REENTRY_ERROR));
}
Ok(())
}
struct SyncExecuteScope {
depth: Arc<AtomicUsize>,
}
impl SyncExecuteScope {
fn enter(depth: Arc<AtomicUsize>) -> Self {
depth.fetch_add(1, Ordering::SeqCst);
Self { depth }
}
}
impl Drop for SyncExecuteScope {
fn drop(&mut self) {
self.depth.fetch_sub(1, Ordering::SeqCst);
}
}
// ============================================================================
// MontyObject <-> JSON conversion
// ============================================================================
#[allow(dead_code)]
fn monty_to_json(obj: &MontyObject) -> serde_json::Value {
match obj {
MontyObject::None => serde_json::Value::Null,
MontyObject::Bool(b) => serde_json::Value::Bool(*b),
MontyObject::Int(i) => serde_json::json!(*i),
MontyObject::BigInt(b) => serde_json::Value::String(b.to_string()),
MontyObject::Float(f) => serde_json::json!(*f),
MontyObject::String(s) | MontyObject::Path(s) => serde_json::Value::String(s.clone()),
MontyObject::Bytes(b) => serde_json::Value::String(base64_encode(b)),
MontyObject::Tuple(items) | MontyObject::List(items) => {
serde_json::Value::Array(items.iter().map(monty_to_json).collect())
}
MontyObject::Set(items) | MontyObject::FrozenSet(items) => {
serde_json::Value::Array(items.iter().map(monty_to_json).collect())
}
MontyObject::Dict(pairs) => {
let mut map = serde_json::Map::new();
for (k, v) in pairs.clone() {
let key = match &k {
MontyObject::String(s) => s.clone(),
other => format!("{}", monty_to_json(other)),
};
map.insert(key, monty_to_json(&v));
}
serde_json::Value::Object(map)
}
MontyObject::NamedTuple {
field_names,
values,
..
} => {
let mut map = serde_json::Map::new();
for (name, value) in field_names.iter().zip(values.iter()) {
map.insert(name.clone(), monty_to_json(value));
}
serde_json::Value::Object(map)
}
other => serde_json::Value::String(other.py_repr()),
}
}
#[allow(dead_code)]
fn json_to_monty(val: &serde_json::Value) -> MontyObject {
match val {
serde_json::Value::Null => MontyObject::None,
serde_json::Value::Bool(b) => MontyObject::Bool(*b),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
MontyObject::Int(i)
} else if let Some(f) = n.as_f64() {
MontyObject::Float(f)
} else {
MontyObject::None
}
}
serde_json::Value::String(s) => MontyObject::String(s.clone()),
serde_json::Value::Array(arr) => MontyObject::List(arr.iter().map(json_to_monty).collect()),
serde_json::Value::Object(map) => {
let pairs: Vec<(MontyObject, MontyObject)> = map
.iter()
.map(|(k, v)| (MontyObject::String(k.clone()), json_to_monty(v)))
.collect();
MontyObject::dict(pairs)
}
}
}
#[allow(dead_code)]
fn base64_encode(data: &[u8]) -> String {
const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut result = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let n = (b0 << 16) | (b1 << 8) | b2;
result.push(CHARS[(n >> 18 & 63) as usize] as char);
result.push(CHARS[(n >> 12 & 63) as usize] as char);
if chunk.len() > 1 {
result.push(CHARS[(n >> 6 & 63) as usize] as char);
} else {
result.push('=');
}
if chunk.len() > 2 {
result.push(CHARS[(n & 63) as usize] as char);
} else {
result.push('=');
}
}
result
}
// ============================================================================
// FileMetadata + JsDirEntry + JsFileSystem
// ============================================================================
/// Metadata for a VFS entry, returned by `stat()` and `readDir()`.
#[napi(object)]
pub struct FileMetadata {
pub file_type: String,
pub size: f64,
pub mode: u32,
pub modified: f64,
pub created: f64,
}
/// Directory entry with name and metadata.
#[napi(object)]
pub struct JsDirEntry {
pub name: String,
pub metadata: FileMetadata,
}
fn metadata_to_js(meta: &Metadata) -> FileMetadata {
let file_type = match meta.file_type {
FileType::File => "file",
FileType::Directory => "directory",
FileType::Symlink => "symlink",
FileType::Fifo => "fifo",
}
.to_string();
FileMetadata {
file_type,
size: meta.size as f64,
mode: meta.mode,
modified: meta
.modified
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0),
created: meta
.created
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0),
}
}
/// Direct VFS accessor — bypasses shell command parsing for file operations.
///
/// Obtained via `bash.fs()` or `bashTool.fs()`. All methods are synchronous
/// and block until the underlying async VFS operation completes.
#[derive(Clone)]
enum FileSystemHandle {
Static(Arc<dyn BashFileSystem>),
Live(Arc<SharedState>),
}
// Decision: keep filesystem handles opaque in Node. `FileSystem.toExternal()`
// returns a native N-API External carrying `BashkitFsAbiOwnedHandleV1`; JS never
// receives mutable handle bytes or function pointers.
pub struct NativeFileSystemState {
inner: FileSystemHandle,
}
impl NativeFileSystemState {
fn new() -> Self {
Self::from_static(Arc::new(InMemoryFs::new()))
}
fn from_static(fs: Arc<dyn BashFileSystem>) -> Self {
Self {
inner: FileSystemHandle::Static(fs),
}
}
fn from_live(state: Arc<SharedState>) -> Self {
Self {
inner: FileSystemHandle::Live(state),
}
}
fn with_fs<T, Fut>(&self, f: impl FnOnce(Arc<dyn BashFileSystem>) -> Fut) -> napi::Result<T>
where
Fut: std::future::Future<Output = napi::Result<T>>,
{
match &self.inner {
FileSystemHandle::Static(fs) => callback_runtime().block_on(f(fs.clone())),
FileSystemHandle::Live(state) => block_on_with(state, |s| async move {
let bash = s.inner.lock().await;
f(bash.fs()).await
}),
}
}
fn export_fs(&self) -> napi::Result<Arc<dyn BashFileSystem>> {
self.with_fs(|fs| async move { Ok(fs) })
}
}
unsafe extern "C" fn finalize_owned_file_system_handle(
_env: sys::napi_env,
data: *mut c_void,
_hint: *mut c_void,
) {
if !data.is_null() {
unsafe {
drop(Box::from_raw(data.cast::<BashkitFsAbiOwnedHandleV1>()));
}
}
}
fn napi_status_result(status: sys::napi_status, action: &str) -> napi::Result<()> {
if status == sys::Status::napi_ok {
return Ok(());
}
Err(napi::Error::from_reason(format!(
"{action} failed with napi status {status}"
)))
}
fn create_file_system_external(
env: &Env,
handle: BashkitFsAbiOwnedHandleV1,
) -> napi::Result<Unknown<'static>> {
let raw_handle = Box::into_raw(Box::new(handle));
let mut raw_external = ptr::null_mut();
let status = unsafe {
sys::napi_create_external(
env.raw(),
raw_handle.cast::<c_void>(),
Some(finalize_owned_file_system_handle),
ptr::null_mut(),
&mut raw_external,
)
};
if let Err(err) = napi_status_result(status, "create filesystem external") {
unsafe {
drop(Box::from_raw(raw_handle));
}
return Err(err);
}
Ok(unsafe { Unknown::from_raw_unchecked(env.raw(), raw_external) })
}
fn file_system_external_handle(external: Unknown<'_>) -> napi::Result<BashkitFsAbiHandleV1> {
if external.get_type()? != ValueType::External {
return Err(napi::Error::from_reason(
"filesystem external must be a native External token",
));
}
let value = external.value();
let mut raw_external = ptr::null_mut();
let status = unsafe { sys::napi_get_value_external(value.env, value.value, &mut raw_external) };
napi_status_result(status, "read filesystem external")?;
if raw_external.is_null() {
return Err(napi::Error::from_reason(
"filesystem external must not be null",
));
}
let mut handle = MaybeUninit::<BashkitFsAbiHandleV1>::uninit();
unsafe {
ptr::copy_nonoverlapping(
raw_external.cast::<u8>(),
handle.as_mut_ptr().cast::<u8>(),
size_of::<BashkitFsAbiHandleV1>(),
);
Ok(handle.assume_init())
}
}
fn import_external_file_system(external: Unknown<'_>) -> napi::Result<Arc<dyn BashFileSystem>> {
let handle = file_system_external_handle(external)?;
// SAFETY: `external` was created by export_external_file_system; the
// ABI handle inside it is valid as long as the external value lives.
unsafe { import_filesystem(&handle) }.map_err(|e| napi::Error::from_reason(e.to_string()))
}
impl NativeFileSystemState {
fn real(
host_path: String,
writable: Option<bool>,
allowed_mount_paths: Option<Vec<String>>,
) -> napi::Result<Self> {
let is_writable = writable.unwrap_or(false);
if is_writable {
eprintln!(
"bashkit: warning: writable mount at {} — scripts can modify host files",
host_path
);
}
enforce_mount_policy(
allowed_mount_paths.as_deref(),
&host_path,
"FileSystem.real",
)?;
let mode = if is_writable {
RealFsMode::ReadWrite
} else {
RealFsMode::ReadOnly
};
let backend =
RealFs::new(&host_path, mode).map_err(|e| napi::Error::from_reason(e.to_string()))?;
let fs: Arc<dyn BashFileSystem> = Arc::new(PosixFs::new(backend));
Ok(Self::from_static(fs))
}
fn import_external(external: Unknown<'_>) -> napi::Result<Self> {
let fs = import_external_file_system(external)?;
Ok(Self::from_static(fs))
}
fn to_external(&self, env: Env) -> napi::Result<Unknown<'static>> {
let fs = self.export_fs()?;
let handle = export_filesystem(fs).map_err(|e| napi::Error::from_reason(e.to_string()))?;
create_file_system_external(&env, handle)
}
fn read_file(&self, path: String) -> napi::Result<String> {
self.with_fs(|fs| async move {
let bytes = fs
.read_file(Path::new(&path))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
String::from_utf8(bytes)
.map_err(|e| napi::Error::from_reason(format!("Invalid UTF-8: {e}")))
})
}
fn write_file(&self, path: String, content: String) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.write_file(Path::new(&path), content.as_bytes())
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn append_file(&self, path: String, content: String) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.append_file(Path::new(&path), content.as_bytes())
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn mkdir(&self, path: String, recursive: Option<bool>) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.mkdir(Path::new(&path), recursive.unwrap_or(false))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn remove(&self, path: String, recursive: Option<bool>) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.remove(Path::new(&path), recursive.unwrap_or(false))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn stat(&self, path: String) -> napi::Result<FileMetadata> {
self.with_fs(|fs| async move {
let meta = fs
.stat(Path::new(&path))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
Ok(metadata_to_js(&meta))
})
}
fn exists(&self, path: String) -> napi::Result<bool> {
self.with_fs(|fs| async move {
fs.exists(Path::new(&path))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn read_dir(&self, path: String) -> napi::Result<Vec<JsDirEntry>> {
self.with_fs(|fs| async move {
let entries = fs
.read_dir(Path::new(&path))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
Ok(entries
.iter()
.map(|e| JsDirEntry {
name: e.name.clone(),
metadata: metadata_to_js(&e.metadata),
})
.collect())
})
}
fn symlink(&self, target: String, link: String) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.symlink(Path::new(&target), Path::new(&link))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn read_link(&self, path: String) -> napi::Result<String> {
self.with_fs(|fs| async move {
let target = fs
.read_link(Path::new(&path))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))?;
Ok(target.to_string_lossy().to_string())
})
}
fn chmod(&self, path: String, mode: u32) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.chmod(Path::new(&path), mode)
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn rename(&self, from_path: String, to_path: String) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.rename(Path::new(&from_path), Path::new(&to_path))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
fn copy(&self, from_path: String, to_path: String) -> napi::Result<()> {
self.with_fs(|fs| async move {
fs.copy(Path::new(&from_path), Path::new(&to_path))
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
})
}
}
impl Default for NativeFileSystemState {
fn default() -> Self {
Self::new()
}
}
#[napi(js_name = "__createFileSystem")]
pub fn create_file_system() -> External<NativeFileSystemState> {
External::new(NativeFileSystemState::new())
}
#[napi(js_name = "__realFileSystem")]
pub fn real_file_system(
host_path: String,
writable: Option<bool>,
allowed_mount_paths: Option<Vec<String>>,
) -> napi::Result<External<NativeFileSystemState>> {
Ok(External::new(NativeFileSystemState::real(
host_path,
writable,
allowed_mount_paths,
)?))
}
#[napi(js_name = "__importFileSystem")]
pub fn import_file_system(external: Unknown<'_>) -> napi::Result<External<NativeFileSystemState>> {
Ok(External::new(NativeFileSystemState::import_external(
external,
)?))
}
#[napi(js_name = "__fileSystemToExternal")]
pub fn file_system_to_external(
fs: &External<NativeFileSystemState>,
env: Env,
) -> napi::Result<Unknown<'static>> {
fs.to_external(env)
}
#[napi(js_name = "__fileSystemReadFile")]
pub fn file_system_read_file(
fs: &External<NativeFileSystemState>,
path: String,
) -> napi::Result<String> {
fs.read_file(path)
}
#[napi(js_name = "__fileSystemWriteFile")]
pub fn file_system_write_file(
fs: &External<NativeFileSystemState>,
path: String,
content: String,
) -> napi::Result<()> {
fs.write_file(path, content)
}
#[napi(js_name = "__fileSystemAppendFile")]
pub fn file_system_append_file(
fs: &External<NativeFileSystemState>,
path: String,
content: String,
) -> napi::Result<()> {
fs.append_file(path, content)
}
#[napi(js_name = "__fileSystemMkdir")]
pub fn file_system_mkdir(
fs: &External<NativeFileSystemState>,
path: String,
recursive: Option<bool>,
) -> napi::Result<()> {
fs.mkdir(path, recursive)
}
#[napi(js_name = "__fileSystemRemove")]
pub fn file_system_remove(
fs: &External<NativeFileSystemState>,
path: String,
recursive: Option<bool>,
) -> napi::Result<()> {
fs.remove(path, recursive)
}
#[napi(js_name = "__fileSystemStat")]
pub fn file_system_stat(
fs: &External<NativeFileSystemState>,
path: String,
) -> napi::Result<FileMetadata> {
fs.stat(path)
}
#[napi(js_name = "__fileSystemExists")]
pub fn file_system_exists(
fs: &External<NativeFileSystemState>,
path: String,
) -> napi::Result<bool> {
fs.exists(path)
}
#[napi(js_name = "__fileSystemReadDir")]
pub fn file_system_read_dir(
fs: &External<NativeFileSystemState>,
path: String,
) -> napi::Result<Vec<JsDirEntry>> {
fs.read_dir(path)
}
#[napi(js_name = "__fileSystemSymlink")]
pub fn file_system_symlink(
fs: &External<NativeFileSystemState>,
target: String,
link: String,
) -> napi::Result<()> {
fs.symlink(target, link)
}
#[napi(js_name = "__fileSystemReadLink")]
pub fn file_system_read_link(
fs: &External<NativeFileSystemState>,
path: String,
) -> napi::Result<String> {
fs.read_link(path)
}
#[napi(js_name = "__fileSystemChmod")]
pub fn file_system_chmod(
fs: &External<NativeFileSystemState>,
path: String,
mode: u32,
) -> napi::Result<()> {
fs.chmod(path, mode)
}
#[napi(js_name = "__fileSystemRename")]
pub fn file_system_rename(
fs: &External<NativeFileSystemState>,
from_path: String,
to_path: String,
) -> napi::Result<()> {
fs.rename(from_path, to_path)
}
#[napi(js_name = "__fileSystemCopy")]
pub fn file_system_copy(
fs: &External<NativeFileSystemState>,
from_path: String,
to_path: String,
) -> napi::Result<()> {
fs.copy(from_path, to_path)
}
// ============================================================================
// ExecResult
// ============================================================================
/// Result from executing bash commands.
#[napi(object)]
#[derive(Clone)]
pub struct ExecResult {
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
pub error: Option<String>,
pub stdout_truncated: bool,
pub stderr_truncated: bool,
pub final_env: Option<HashMap<String, String>>,
/// True if exit_code is 0.
pub success: bool,
}
// The native JS callback arrives as one `[stdout, stderr]` tuple payload even
// though napi-rs models the args as `(String, String)`. Keep the public TS
// wrapper responsible for adapting that odd FFI shape into its
// object-shaped `{ stdout, stderr }` callback API.
type SyncOutputFn = napi::bindgen_prelude::FunctionRef<(String, String), Option<String>>;
type OutputTsfn = napi::threadsafe_function::ThreadsafeFunction<
(String, String),
Option<String>,
(String, String),
napi::Status,
false,
true,
>;
fn js_exec_result_from_rust(result: RustExecResult) -> ExecResult {
ExecResult {
stdout: result.stdout,
stderr: result.stderr,
exit_code: result.exit_code,
error: None,
stdout_truncated: result.stdout_truncated,
stderr_truncated: result.stderr_truncated,
final_env: result.final_env,
success: result.exit_code == 0,
}
}
fn js_exec_result_from_error(err: impl ToString) -> ExecResult {
let msg = err.to_string();
ExecResult {
stdout: String::new(),
stderr: msg.clone(),
exit_code: 1,
error: Some(msg),
stdout_truncated: false,
stderr_truncated: false,
final_env: None,
success: false,
}
}
fn js_exec_result_from_bash_result(result: bashkit::Result<RustExecResult>) -> ExecResult {
match result {
Ok(result) => js_exec_result_from_rust(result),
Err(err) => js_exec_result_from_error(err),
}
}
fn callback_error_reason(err: impl ToString) -> String {
format!("onOutput callback failed: {}", err.to_string())
}
fn record_callback_error(
callback_error: &StdMutex<Option<String>>,
cancelled: &Arc<AtomicBool>,
callback_requested_cancel: &Arc<AtomicBool>,
message: String,
) {
if let Ok(mut callback_error) = callback_error.lock()
&& callback_error.is_none()
{
*callback_error = Some(message);
}
if !cancelled.swap(true, Ordering::SeqCst) {
callback_requested_cancel.store(true, Ordering::SeqCst);
}
}
fn take_callback_error(callback_error: &StdMutex<Option<String>>) -> Option<napi::Error> {
callback_error
.lock()
.ok()
.and_then(|mut callback_error| callback_error.take())
.map(napi::Error::from_reason)
}
fn build_sync_output_callback(
env_raw: usize,
on_output: SyncOutputFn,
cancelled: Arc<AtomicBool>,
callback_requested_cancel: Arc<AtomicBool>,
callback_error: Arc<StdMutex<Option<String>>>,
on_output_reentry_depth: Arc<AtomicUsize>,
) -> OutputCallback {
Box::new(move |stdout_chunk, stderr_chunk| {
let has_error = callback_error
.lock()
.map(|callback_error| callback_error.is_some())
.unwrap_or(false);
if has_error {
return;
}
let env = napi::Env::from_raw(env_raw as napi::sys::napi_env);
let callback = match on_output.borrow_back(&env) {
Ok(callback) => callback,
Err(err) => {
record_callback_error(
&callback_error,
&cancelled,
&callback_requested_cancel,
callback_error_reason(err),
);
return;
}
};
let _reentry_scope = OnOutputReentryScope::enter(on_output_reentry_depth.clone());
match callback.call((stdout_chunk.to_string(), stderr_chunk.to_string())) {
Ok(Some(err)) => {
record_callback_error(
&callback_error,
&cancelled,
&callback_requested_cancel,
callback_error_reason(err),
);
}
Ok(None) => {}
Err(err) => {
record_callback_error(
&callback_error,
&cancelled,
&callback_requested_cancel,
callback_error_reason(err),
);
}
}
})
}
fn build_async_output_callback(
tsfn: Arc<OutputTsfn>,
cancelled: Arc<AtomicBool>,
callback_requested_cancel: Arc<AtomicBool>,
on_output_reentry_depth: Arc<AtomicUsize>,
) -> (OutputCallback, Arc<StdMutex<Option<String>>>) {
let callback_error = Arc::new(StdMutex::new(None));
let callback_error_output = callback_error.clone();
let cancelled_output = cancelled.clone();
let callback_requested_cancel_output = callback_requested_cancel.clone();
let output_callback: OutputCallback = Box::new(move |stdout_chunk, stderr_chunk| {
let has_error = callback_error_output
.lock()
.map(|callback_error| callback_error.is_some())
.unwrap_or(false);
if has_error {
return;
}
let stdout = stdout_chunk.to_string();
let stderr = stderr_chunk.to_string();
let tsfn = tsfn.clone();
let on_output_reentry_depth = on_output_reentry_depth.clone();
let (tx, rx) = std::sync::mpsc::channel();
// OutputCallback in core bashkit is synchronous. Dispatch onto the
// shared callback runtime, then block until JS finishes so callback
// errors abort execution immediately and chunk ordering stays stable.
callback_runtime().spawn(async move {
let result: Result<Option<String>, String> = {
let _reentry_scope = OnOutputReentryScope::enter(on_output_reentry_depth);
tsfn.call_async((stdout, stderr))
.await
.map_err(callback_error_reason)
};
let _ = tx.send(result);
});
match rx.recv() {
Ok(Ok(Some(err))) => {
record_callback_error(
&callback_error_output,
&cancelled_output,
&callback_requested_cancel_output,
callback_error_reason(err),
);
}
Ok(Ok(None)) => {}
Ok(Err(err)) => {
record_callback_error(
&callback_error_output,
&cancelled_output,
&callback_requested_cancel_output,
err,
);
}
Err(_) => {
record_callback_error(
&callback_error_output,
&cancelled_output,
&callback_requested_cancel_output,
"onOutput callback failed: callback channel closed".to_string(),
);
}
}
});
(output_callback, callback_error)
}
fn create_output_tsfn(
on_output: napi::bindgen_prelude::Function<'_, (String, String), Option<String>>,
) -> napi::Result<Arc<OutputTsfn>> {
let tsfn = on_output
.build_threadsafe_function::<(String, String)>()
.weak::<true>()
.build()?;
Ok(Arc::new(tsfn))
}
async fn execute_rust_bash(
bash: &mut RustBash,
commands: &str,
output_callback: Option<OutputCallback>,
callback_error: Option<&Arc<StdMutex<Option<String>>>>,
cancelled: Option<&Arc<AtomicBool>>,
callback_requested_cancel: Option<&Arc<AtomicBool>>,
) -> napi::Result<ExecResult> {
let result = if let Some(output_callback) = output_callback {
bash.exec_streaming(commands, output_callback).await
} else {
bash.exec(commands).await
};
if let Some(callback_error) = callback_error
&& let Some(err) = take_callback_error(callback_error)
{
if let Some((cancelled, callback_requested_cancel)) =
cancelled.zip(callback_requested_cancel)
&& callback_requested_cancel.load(Ordering::SeqCst)
{
cancelled.store(false, Ordering::SeqCst);
}
return Err(err);
}
Ok(js_exec_result_from_bash_result(result))
}
// ============================================================================
// MountConfig + BashOptions
// ============================================================================
/// Configuration for a real filesystem mount.
#[napi(object)]
#[derive(Clone)]
pub struct MountConfig {
/// Host filesystem path to mount.
pub host_path: String,
/// VFS path where mount appears (defaults to host_path).
pub vfs_path: Option<String>,
/// If true, mount is read-write (default: false → read-only).
pub writable: Option<bool>,
}
/// Options for creating a Bash or BashTool instance.
#[napi(object)]
pub struct BashOptions {
pub username: Option<String>,
pub hostname: Option<String>,
pub max_commands: Option<u32>,
pub max_loop_iterations: Option<u32>,
pub max_total_loop_iterations: Option<u32>,
pub max_function_depth: Option<u32>,
/// Execution timeout in milliseconds.
pub timeout_ms: Option<u32>,
/// Parser timeout in milliseconds.
pub parser_timeout_ms: Option<u32>,
pub max_input_bytes: Option<u32>,
pub max_ast_depth: Option<u32>,
pub max_parser_operations: Option<u32>,
pub max_stdout_bytes: Option<u32>,
pub max_stderr_bytes: Option<u32>,
/// Maximum interpreter memory in bytes (variables, arrays, functions).
///
/// Caps `max_total_variable_bytes` and clamps `max_function_body_bytes`.
/// Prevents OOM from untrusted input such as exponential string doubling.