-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathlib.rs
More file actions
1952 lines (1805 loc) · 68.1 KB
/
lib.rs
File metadata and controls
1952 lines (1805 loc) · 68.1 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
//! Bashkit Python package
//!
//! Primary interface: `Bash` — the core interpreter with virtual filesystem.
//! Convenience wrapper: `BashTool` — adds contract metadata (`description`,
//! `help`, `system_prompt`, JSON schemas) on top of the core interpreter.
//! Orchestration: `ScriptedTool` — composes Python callbacks as bash builtins.
use bashkit::tool::VERSION;
use bashkit::{
Bash, BashTool as RustBashTool, DirEntry as FsDirEntry, ExcType, ExecutionLimits,
ExtFunctionResult, FileSystem, FileType as FsFileType, InMemoryFs, Metadata as FsMetadata,
MontyException, MontyObject, PosixFs, PythonExternalFnHandler, PythonLimits, RealFs,
RealFsMode, ScriptedTool as RustScriptedTool, Tool, ToolArgs, ToolDef, ToolRequest,
};
use pyo3::exceptions::{PyRuntimeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PySet, PyTuple};
use pyo3_async_runtimes::tokio::future_into_py;
use std::future::Future;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::runtime::Runtime;
use tokio::sync::Mutex;
// ============================================================================
// JSON <-> Python helpers
// ============================================================================
/// Convert serde_json::Value → Py<PyAny>
const MAX_NESTING_DEPTH: usize = 64;
fn json_to_py(py: Python<'_>, val: &serde_json::Value) -> PyResult<Py<PyAny>> {
json_to_py_inner(py, val, 0)
}
fn json_to_py_inner(py: Python<'_>, val: &serde_json::Value, depth: usize) -> PyResult<Py<PyAny>> {
if depth > MAX_NESTING_DEPTH {
return Err(pyo3::exceptions::PyValueError::new_err(
"JSON nesting depth exceeds maximum of 64",
));
}
match val {
serde_json::Value::Null => Ok(py.None()),
serde_json::Value::Bool(b) => Ok(b.into_pyobject(py)?.to_owned().into_any().unbind()),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
Ok(i.into_pyobject(py)?.into_any().unbind())
} else if let Some(f) = n.as_f64() {
Ok(f.into_pyobject(py)?.into_any().unbind())
} else {
Ok(py.None())
}
}
serde_json::Value::String(s) => Ok(s.into_pyobject(py)?.into_any().unbind()),
serde_json::Value::Array(arr) => {
let items: Vec<Py<PyAny>> = arr
.iter()
.map(|v| json_to_py_inner(py, v, depth + 1))
.collect::<PyResult<_>>()?;
Ok(PyList::new(py, &items)?.into_any().unbind())
}
serde_json::Value::Object(map) => {
let dict = PyDict::new(py);
for (k, v) in map {
dict.set_item(k, json_to_py_inner(py, v, depth + 1)?)?;
}
Ok(dict.into_any().unbind())
}
}
}
/// Convert Py<PyAny> → serde_json::Value (for schema dicts)
fn py_to_json(py: Python<'_>, obj: &Bound<'_, pyo3::PyAny>) -> PyResult<serde_json::Value> {
py_to_json_inner(py, obj, 0)
}
#[allow(clippy::only_used_in_recursion)]
fn py_to_json_inner(
py: Python<'_>,
obj: &Bound<'_, pyo3::PyAny>,
depth: usize,
) -> PyResult<serde_json::Value> {
if depth > MAX_NESTING_DEPTH {
return Err(pyo3::exceptions::PyValueError::new_err(
"Python object nesting depth exceeds maximum of 64",
));
}
if obj.is_none() {
return Ok(serde_json::Value::Null);
}
if let Ok(b) = obj.extract::<bool>() {
return Ok(serde_json::Value::Bool(b));
}
if let Ok(i) = obj.extract::<i64>() {
return Ok(serde_json::json!(i));
}
if let Ok(f) = obj.extract::<f64>() {
return Ok(serde_json::json!(f));
}
if let Ok(s) = obj.extract::<String>() {
return Ok(serde_json::Value::String(s));
}
if let Ok(list) = obj.cast::<PyList>() {
let arr: Vec<serde_json::Value> = list
.iter()
.map(|item| py_to_json_inner(py, &item, depth + 1))
.collect::<PyResult<_>>()?;
return Ok(serde_json::Value::Array(arr));
}
if let Ok(dict) = obj.cast::<PyDict>() {
let mut map = serde_json::Map::new();
for (k, v) in dict.iter() {
let key: String = k.extract()?;
map.insert(key, py_to_json_inner(py, &v, depth + 1)?);
}
return Ok(serde_json::Value::Object(map));
}
// Fallback: str()
let s = obj.str()?.extract::<String>()?;
Ok(serde_json::Value::String(s))
}
#[derive(Clone)]
struct MountedTextConfig {
path: String,
content: String,
readonly: bool,
}
#[derive(Clone)]
struct RealMountConfig {
host_path: String,
vfs_mount: Option<String>,
readwrite: bool,
}
fn make_runtime() -> PyResult<Arc<Runtime>> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map(Arc::new)
.map_err(|e| PyRuntimeError::new_err(format!("Failed to create runtime: {e}")))
}
/// Parse the six mount kwargs into internal config structs.
/// Shared by both `PyBash::new()` and `BashTool::new()`.
fn parse_mount_configs(
mount_text: Option<Vec<(String, String)>>,
mount_readonly_text: Option<Vec<(String, String)>>,
mount_real_readonly: Option<Vec<String>>,
mount_real_readonly_at: Option<Vec<(String, String)>>,
mount_real_readwrite: Option<Vec<String>>,
mount_real_readwrite_at: Option<Vec<(String, String)>>,
) -> (Vec<MountedTextConfig>, Vec<RealMountConfig>) {
let mounted_text_files = mount_text
.unwrap_or_default()
.into_iter()
.map(|(path, content)| MountedTextConfig {
path,
content,
readonly: false,
})
.chain(
mount_readonly_text
.unwrap_or_default()
.into_iter()
.map(|(path, content)| MountedTextConfig {
path,
content,
readonly: true,
}),
)
.collect::<Vec<_>>();
let real_mounts = mount_real_readonly
.unwrap_or_default()
.into_iter()
.map(|host_path| RealMountConfig {
host_path,
vfs_mount: None,
readwrite: false,
})
.chain(mount_real_readonly_at.unwrap_or_default().into_iter().map(
|(host_path, vfs_mount)| RealMountConfig {
host_path,
vfs_mount: Some(vfs_mount),
readwrite: false,
},
))
.chain(
mount_real_readwrite
.unwrap_or_default()
.into_iter()
.map(|host_path| RealMountConfig {
host_path,
vfs_mount: None,
readwrite: true,
}),
)
.chain(mount_real_readwrite_at.unwrap_or_default().into_iter().map(
|(host_path, vfs_mount)| RealMountConfig {
host_path,
vfs_mount: Some(vfs_mount),
readwrite: true,
},
))
.collect::<Vec<_>>();
(mounted_text_files, real_mounts)
}
fn apply_fs_config(
mut builder: bashkit::BashBuilder,
mounted_text_files: &[MountedTextConfig],
real_mounts: &[RealMountConfig],
) -> bashkit::BashBuilder {
for mount in mounted_text_files {
builder = if mount.readonly {
builder.mount_readonly_text(&mount.path, mount.content.clone())
} else {
builder.mount_text(&mount.path, mount.content.clone())
};
}
for mount in real_mounts {
builder = match (mount.readwrite, &mount.vfs_mount) {
(false, None) => builder.mount_real_readonly(&mount.host_path),
(false, Some(vfs_mount)) => builder.mount_real_readonly_at(&mount.host_path, vfs_mount),
(true, None) => builder.mount_real_readwrite(&mount.host_path),
(true, Some(vfs_mount)) => builder.mount_real_readwrite_at(&mount.host_path, vfs_mount),
};
}
builder
}
fn system_time_to_unix_seconds(time: SystemTime) -> f64 {
time.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs_f64())
.unwrap_or(0.0)
}
fn file_type_name(file_type: FsFileType) -> &'static str {
match file_type {
FsFileType::File => "file",
FsFileType::Directory => "directory",
FsFileType::Symlink => "symlink",
FsFileType::Fifo => "fifo",
}
}
fn metadata_to_pydict(py: Python<'_>, metadata: &FsMetadata) -> PyResult<Py<PyAny>> {
let dict = PyDict::new(py);
dict.set_item("file_type", file_type_name(metadata.file_type))?;
dict.set_item("size", metadata.size)?;
dict.set_item("mode", metadata.mode)?;
dict.set_item("modified", system_time_to_unix_seconds(metadata.modified))?;
dict.set_item("created", system_time_to_unix_seconds(metadata.created))?;
Ok(dict.into_any().unbind())
}
fn dir_entry_to_pydict(py: Python<'_>, entry: &FsDirEntry) -> PyResult<Py<PyAny>> {
let dict = PyDict::new(py);
dict.set_item("name", &entry.name)?;
dict.set_item("metadata", metadata_to_pydict(py, &entry.metadata)?)?;
Ok(dict.into_any().unbind())
}
#[derive(Clone)]
enum FileSystemHandle {
Static(Arc<dyn FileSystem>),
Live(Arc<Mutex<Bash>>),
}
impl FileSystemHandle {
async fn resolve(&self) -> Arc<dyn FileSystem> {
match self {
Self::Static(fs) => Arc::clone(fs),
Self::Live(inner) => {
let bash = inner.lock().await;
bash.fs()
}
}
}
}
#[pyclass(name = "FileSystem")]
struct PyFileSystem {
inner: FileSystemHandle,
rt: Arc<Runtime>,
}
impl PyFileSystem {
fn from_static(inner: Arc<dyn FileSystem>, rt: Arc<Runtime>) -> Self {
Self {
inner: FileSystemHandle::Static(inner),
rt,
}
}
fn from_live(inner: Arc<Mutex<Bash>>, rt: Arc<Runtime>) -> Self {
Self {
inner: FileSystemHandle::Live(inner),
rt,
}
}
fn with_fs<T, F, Fut>(&self, f: F) -> PyResult<T>
where
F: FnOnce(Arc<dyn FileSystem>) -> Fut,
Fut: Future<Output = PyResult<T>>,
{
let inner = self.inner.clone();
self.rt.block_on(async move {
let fs = inner.resolve().await;
f(fs).await
})
}
}
#[pymethods]
impl PyFileSystem {
#[new]
fn new() -> PyResult<Self> {
let rt = make_runtime()?;
Ok(Self::from_static(Arc::new(InMemoryFs::new()), rt))
}
#[staticmethod]
#[pyo3(signature = (host_path, readwrite=false))]
fn real(host_path: String, readwrite: bool) -> PyResult<Self> {
let rt = make_runtime()?;
let mode = if readwrite {
RealFsMode::ReadWrite
} else {
RealFsMode::ReadOnly
};
let backend =
RealFs::new(&host_path, mode).map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
let fs: Arc<dyn FileSystem> = PosixFs::new(backend).into();
Ok(Self::from_static(fs, rt))
}
fn read_file<'py>(&self, py: Python<'py>, path: String) -> PyResult<Bound<'py, PyBytes>> {
let data = py.detach(|| {
self.with_fs(|fs| async move {
fs.read_file(Path::new(&path))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})?;
Ok(PyBytes::new(py, &data))
}
fn write_file(&self, py: Python<'_>, path: String, content: Vec<u8>) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.write_file(Path::new(&path), &content)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
fn append_file(&self, py: Python<'_>, path: String, content: Vec<u8>) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.append_file(Path::new(&path), &content)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
#[pyo3(signature = (path, recursive=false))]
fn mkdir(&self, py: Python<'_>, path: String, recursive: bool) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.mkdir(Path::new(&path), recursive)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
#[pyo3(signature = (path, recursive=false))]
fn remove(&self, py: Python<'_>, path: String, recursive: bool) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.remove(Path::new(&path), recursive)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
fn stat(&self, py: Python<'_>, path: String) -> PyResult<Py<PyAny>> {
let metadata = py.detach(|| {
self.with_fs(|fs| async move {
fs.stat(Path::new(&path))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})?;
metadata_to_pydict(py, &metadata)
}
fn read_dir(&self, py: Python<'_>, path: String) -> PyResult<Py<PyAny>> {
let entries = py.detach(|| {
self.with_fs(|fs| async move {
fs.read_dir(Path::new(&path))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})?;
let items: Vec<Py<PyAny>> = entries
.iter()
.map(|entry| dir_entry_to_pydict(py, entry))
.collect::<PyResult<_>>()?;
Ok(PyList::new(py, &items)?.into_any().unbind())
}
fn exists(&self, py: Python<'_>, path: String) -> PyResult<bool> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.exists(Path::new(&path))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
fn rename(&self, py: Python<'_>, from_path: String, to_path: String) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.rename(Path::new(&from_path), Path::new(&to_path))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
fn copy(&self, py: Python<'_>, from_path: String, to_path: String) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.copy(Path::new(&from_path), Path::new(&to_path))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
fn symlink(&self, py: Python<'_>, target: String, link: String) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.symlink(Path::new(&target), Path::new(&link))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
fn chmod(&self, py: Python<'_>, path: String, mode: u32) -> PyResult<()> {
py.detach(|| {
self.with_fs(|fs| async move {
fs.chmod(Path::new(&path), mode)
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})
}
fn read_link(&self, py: Python<'_>, path: String) -> PyResult<String> {
let target = py.detach(|| {
self.with_fs(|fs| async move {
fs.read_link(Path::new(&path))
.await
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})
})?;
Ok(target.display().to_string())
}
}
// ============================================================================
// ExecResult
// ============================================================================
/// Result from executing bash commands
#[pyclass(from_py_object)]
#[derive(Clone)]
pub struct ExecResult {
#[pyo3(get)]
pub stdout: String,
#[pyo3(get)]
pub stderr: String,
#[pyo3(get)]
pub exit_code: i32,
#[pyo3(get)]
pub error: Option<String>,
#[pyo3(get)]
pub stdout_truncated: bool,
#[pyo3(get)]
pub stderr_truncated: bool,
#[pyo3(get)]
pub final_env: Option<std::collections::HashMap<String, String>>,
}
#[pymethods]
impl ExecResult {
fn __repr__(&self) -> String {
format!(
"ExecResult(stdout={:?}, stderr={:?}, exit_code={}, error={:?}, stdout_truncated={}, stderr_truncated={}, final_env={:?})",
self.stdout,
self.stderr,
self.exit_code,
self.error,
self.stdout_truncated,
self.stderr_truncated,
self.final_env
)
}
fn __str__(&self) -> String {
if self.exit_code == 0 {
self.stdout.clone()
} else {
format!("Error ({}): {}", self.exit_code, self.stderr)
}
}
/// Check if command succeeded
#[getter]
fn success(&self) -> bool {
self.exit_code == 0
}
/// Return output as dict
fn to_dict(&self) -> pyo3::PyResult<pyo3::Py<PyDict>> {
Python::attach(|py| {
let dict = PyDict::new(py);
dict.set_item("stdout", &self.stdout)?;
dict.set_item("stderr", &self.stderr)?;
dict.set_item("exit_code", self.exit_code)?;
dict.set_item("error", &self.error)?;
dict.set_item("stdout_truncated", self.stdout_truncated)?;
dict.set_item("stderr_truncated", self.stderr_truncated)?;
dict.set_item("final_env", &self.final_env)?;
Ok(dict.into())
})
}
}
// ============================================================================
// Bash — core interpreter
// ============================================================================
/// Build a `PythonExternalFnHandler` from a Python async callable.
///
/// The handler converts MontyObject args/kwargs to Python objects, calls the
/// async handler coroutine, awaits it, and converts the result back.
fn make_external_handler(py_handler: Py<PyAny>) -> PythonExternalFnHandler {
Arc::new(move |fn_name, args, kwargs| {
let py_handler = Python::attach(|py| py_handler.clone_ref(py));
Box::pin(async move {
let fut = Python::attach(|py| {
let py_args = args
.iter()
.map(|o| monty_to_py(py, o))
.collect::<PyResult<Vec<_>>>()?;
let py_args_list = PyList::new(py, &py_args)?;
let py_kwargs = PyDict::new(py);
for (k, v) in &kwargs {
py_kwargs.set_item(monty_to_py(py, k)?, monty_to_py(py, v)?)?;
}
let coro = py_handler.call1(py, (fn_name, py_args_list, py_kwargs))?;
pyo3_async_runtimes::tokio::into_future(coro.into_bound(py))
});
match fut {
Err(e) => ExtFunctionResult::Error(MontyException::new(
ExcType::RuntimeError,
Some(e.to_string()),
)),
Ok(awaitable) => match awaitable.await {
Err(e) => ExtFunctionResult::Error(MontyException::new(
ExcType::RuntimeError,
Some(e.to_string()),
)),
Ok(py_result) => {
Python::attach(|py| match py_to_monty(py, py_result.bind(py)) {
Ok(v) => ExtFunctionResult::Return(v),
Err(e) => ExtFunctionResult::Error(MontyException::new(
ExcType::RuntimeError,
Some(e.to_string()),
)),
})
}
},
}
})
})
}
/// Apply python/external_handler configuration to a `BashBuilder`.
///
/// Centralises the logic shared between `new()` and `reset()`.
fn apply_python_config(
mut builder: bashkit::BashBuilder,
python: bool,
fn_names: Vec<String>,
handler: Option<Py<PyAny>>,
) -> bashkit::BashBuilder {
// By construction, handler.is_some() implies python=true (validated in new()).
match (python, handler) {
(true, Some(h)) => {
builder = builder.python_with_external_handler(
PythonLimits::default(),
fn_names,
make_external_handler(h),
);
}
(true, None) => {
builder = builder.python();
}
(false, _) => {}
}
builder
}
/// Core bash interpreter with virtual filesystem.
///
/// State persists between calls — files created in one `execute()` are
/// available in subsequent calls. This is the primary interface.
///
/// Example:
/// ```python
/// from bashkit import Bash
///
/// bash = Bash()
/// result = await bash.execute("echo 'Hello, World!'")
/// print(result.stdout) # Hello, World!
/// ```
#[pyclass(name = "Bash")]
#[allow(dead_code)]
pub struct PyBash {
inner: Arc<Mutex<Bash>>,
/// Shared tokio runtime — reused across all sync calls to avoid
/// per-call OS thread/fd exhaustion (issue #414).
rt: Arc<Runtime>,
/// Cancellation token. Wrapped in RwLock so reset() can swap it to
/// the new interpreter's token without requiring &mut self.
cancelled: Arc<RwLock<Arc<AtomicBool>>>,
username: Option<String>,
hostname: Option<String>,
/// Whether Monty Python execution is enabled (`python`/`python3` builtins).
python: bool,
/// External function names callable from Monty code via the handler.
external_functions: Vec<String>,
/// Async Python callable invoked when Monty calls an external function.
external_handler: Option<Py<PyAny>>,
mounted_text_files: Vec<MountedTextConfig>,
real_mounts: Vec<RealMountConfig>,
max_commands: Option<u64>,
max_loop_iterations: Option<u64>,
}
#[pymethods]
impl PyBash {
#[new]
#[pyo3(signature = (
username=None,
hostname=None,
max_commands=None,
max_loop_iterations=None,
python=false,
external_functions=None,
external_handler=None,
mount_text=None,
mount_readonly_text=None,
mount_real_readonly=None,
mount_real_readonly_at=None,
mount_real_readwrite=None,
mount_real_readwrite_at=None,
))]
#[allow(clippy::too_many_arguments)]
fn new(
py: Python<'_>,
username: Option<String>,
hostname: Option<String>,
max_commands: Option<u64>,
max_loop_iterations: Option<u64>,
python: bool,
external_functions: Option<Vec<String>>,
external_handler: Option<Py<PyAny>>,
mount_text: Option<Vec<(String, String)>>,
mount_readonly_text: Option<Vec<(String, String)>>,
mount_real_readonly: Option<Vec<String>>,
mount_real_readonly_at: Option<Vec<(String, String)>>,
mount_real_readwrite: Option<Vec<String>>,
mount_real_readwrite_at: Option<Vec<(String, String)>>,
) -> PyResult<Self> {
let mut builder = Bash::builder();
if let Some(ref u) = username {
builder = builder.username(u);
}
if let Some(ref h) = hostname {
builder = builder.hostname(h);
}
let mut limits = ExecutionLimits::new();
if let Some(mc) = max_commands {
limits = limits.max_commands(usize::try_from(mc).unwrap_or(usize::MAX));
}
if let Some(mli) = max_loop_iterations {
limits = limits.max_loop_iterations(usize::try_from(mli).unwrap_or(usize::MAX));
}
builder = builder.limits(limits);
let (mounted_text_files, real_mounts) = parse_mount_configs(
mount_text,
mount_readonly_text,
mount_real_readonly,
mount_real_readonly_at,
mount_real_readwrite,
mount_real_readwrite_at,
);
let fn_names = external_functions.clone().unwrap_or_default();
if !fn_names.is_empty() && external_handler.is_none() {
return Err(PyValueError::new_err(
"external_functions requires external_handler — the list has no effect without a handler",
));
}
if external_handler.is_some() && !python {
return Err(PyValueError::new_err(
"external_handler requires python=True",
));
}
if external_handler
.as_ref()
.is_some_and(|h| !h.bind(py).is_callable())
{
return Err(PyValueError::new_err("external_handler must be callable"));
}
if let Some(ref handler) = external_handler {
// Check both the object itself and its __call__ method to support
// objects with `async def __call__` (matching the ExternalHandler Protocol),
// decorated coroutines, and similar async callables that return False
// from iscoroutinefunction(obj) but True for iscoroutinefunction(obj.__call__).
let inspect = py.import("inspect")?;
let is_coro_fn = inspect.getattr("iscoroutinefunction")?;
let bound = handler.bind(py);
let is_coro = is_coro_fn.call1((bound,))?.extract::<bool>()?
|| bound
.getattr("__call__")
.ok()
.and_then(|c| is_coro_fn.call1((c,)).ok())
.and_then(|r| r.extract::<bool>().ok())
.unwrap_or(false);
if !is_coro {
return Err(PyValueError::new_err(
"external_handler must be an async callable (coroutine function)",
));
}
}
let handler_for_build = external_handler.as_ref().map(|h| h.clone_ref(py));
builder = apply_python_config(builder, python, fn_names, handler_for_build);
builder = apply_fs_config(builder, &mounted_text_files, &real_mounts);
let bash = builder.build();
let cancelled = Arc::new(RwLock::new(bash.cancellation_token()));
let rt = make_runtime()?;
Ok(Self {
inner: Arc::new(Mutex::new(bash)),
rt,
cancelled,
username,
hostname,
python,
external_functions: external_functions.unwrap_or_default(),
external_handler,
mounted_text_files,
real_mounts,
max_commands,
max_loop_iterations,
})
}
/// Cancel the currently running execution.
///
/// Safe to call from any thread. Execution will abort at the next
/// command boundary.
fn cancel(&self) {
if let Ok(token) = self.cancelled.read() {
token.store(true, Ordering::Relaxed);
}
}
/// Execute commands asynchronously.
fn execute<'py>(&self, py: Python<'py>, commands: String) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
future_into_py(py, async move {
let mut bash = inner.lock().await;
match bash.exec(&commands).await {
Ok(result) => Ok(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,
}),
Err(e) => {
let msg = e.to_string();
Ok(ExecResult {
stdout: String::new(),
stderr: msg.clone(),
exit_code: 1,
error: Some(msg),
stdout_truncated: false,
stderr_truncated: false,
final_env: None,
})
}
}
})
}
/// Execute commands synchronously (blocking).
///
/// Not supported when `external_handler` is configured: the handler is an async
/// Python coroutine that requires a running event loop, which is unavailable in
/// sync context. Use `execute()` (async) instead.
///
/// Releases GIL before blocking on tokio to prevent deadlock with callbacks.
fn execute_sync(&self, py: Python<'_>, commands: String) -> PyResult<ExecResult> {
if self.external_handler.is_some() {
return Err(PyRuntimeError::new_err(
"execute_sync is not supported when external_handler is configured — use execute() (async) instead, e.g. asyncio.run(bash.execute(...))",
));
}
let inner = self.inner.clone();
py.detach(|| {
self.rt.block_on(async move {
let mut bash = inner.lock().await;
match bash.exec(&commands).await {
Ok(result) => Ok(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,
}),
Err(e) => {
let msg = e.to_string();
Ok(ExecResult {
stdout: String::new(),
stderr: msg.clone(),
exit_code: 1,
error: Some(msg),
stdout_truncated: false,
stderr_truncated: false,
final_env: None,
})
}
}
})
})
}
/// Execute commands synchronously. Raises `BashError` on non-zero exit.
///
/// Not supported when `external_handler` is configured.
fn execute_sync_or_throw(&self, py: Python<'_>, commands: String) -> PyResult<ExecResult> {
let result = self.execute_sync(py, commands)?;
if result.exit_code != 0 {
return Err(raise_bash_error(&result));
}
Ok(result)
}
/// Execute commands asynchronously. Raises `BashError` on non-zero exit.
fn execute_or_throw<'py>(
&self,
py: Python<'py>,
commands: String,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
future_into_py(py, async move {
let mut bash = inner.lock().await;
let result = match bash.exec(&commands).await {
Ok(r) => ExecResult {
stdout: r.stdout,
stderr: r.stderr,
exit_code: r.exit_code,
error: None,
stdout_truncated: r.stdout_truncated,
stderr_truncated: r.stderr_truncated,
final_env: r.final_env,
},
Err(e) => {
let msg = e.to_string();
ExecResult {
stdout: String::new(),
stderr: msg.clone(),
exit_code: 1,
error: Some(msg),
stdout_truncated: false,
stderr_truncated: false,
final_env: None,
}
}
};
if result.exit_code != 0 {
return Err(raise_bash_error(&result));
}
Ok(result)
})
}
/// Reset interpreter to fresh state, preserving all configuration including
/// python mode and external function handler.
/// Releases GIL before blocking on tokio to prevent deadlock.
fn reset(&self, py: Python<'_>) -> PyResult<()> {
let inner = self.inner.clone();
// THREAT[TM-PY-026]: Rebuild with same config to preserve DoS protections.
let username = self.username.clone();
let hostname = self.hostname.clone();
let max_commands = self.max_commands;
let max_loop_iterations = self.max_loop_iterations;
let python = self.python;
let external_functions = self.external_functions.clone();
let mounted_text_files = self.mounted_text_files.clone();
let real_mounts = self.real_mounts.clone();
// Clone handler ref while still holding the GIL (before py.detach).
let handler_clone = self.external_handler.as_ref().map(|h| h.clone_ref(py));
let cancelled = self.cancelled.clone();
py.detach(|| {
self.rt.block_on(async move {
let mut bash = inner.lock().await;
let mut builder = Bash::builder();
if let Some(ref u) = username {
builder = builder.username(u);
}
if let Some(ref h) = hostname {
builder = builder.hostname(h);
}
let mut limits = ExecutionLimits::new();
if let Some(mc) = max_commands {
limits = limits.max_commands(usize::try_from(mc).unwrap_or(usize::MAX));
}
if let Some(mli) = max_loop_iterations {
limits = limits.max_loop_iterations(usize::try_from(mli).unwrap_or(usize::MAX));
}
builder = builder.limits(limits);
builder = apply_python_config(builder, python, external_functions, handler_clone);
builder = apply_fs_config(builder, &mounted_text_files, &real_mounts);
*bash = builder.build();
// Swap the cancellation token to the new interpreter's token so
// cancel() targets the current (not stale) interpreter.
if let Ok(mut token) = cancelled.write() {
*token = bash.cancellation_token();
}
Ok(())
})
})
}
/// Return a live filesystem handle backed by the current interpreter.
///
/// Each operation on the returned handle acquires the interpreter lock,
/// so it always reflects the latest state (including post-reset). For
/// batch reads where consistency isn't needed, prefer reading files via
/// `execute_sync("cat ...")`.
fn fs(&self, py: Python<'_>) -> PyResult<Py<PyFileSystem>> {
Py::new(
py,
PyFileSystem::from_live(self.inner.clone(), self.rt.clone()),
)
}
/// Mount a filesystem at `vfs_path` without rebuilding the interpreter.
fn mount(&self, py: Python<'_>, vfs_path: String, fs: PyRef<'_, PyFileSystem>) -> PyResult<()> {
let inner = self.inner.clone();
let source = fs.inner.clone();
py.detach(|| {
self.rt.block_on(async move {
let mounted_fs = source.resolve().await;
let bash = inner.lock().await;
bash.mount(Path::new(&vfs_path), mounted_fs)
.map_err(|e| PyRuntimeError::new_err(e.to_string()))
})