-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathwrapper.ts
More file actions
1240 lines (1127 loc) · 34.1 KB
/
wrapper.ts
File metadata and controls
1240 lines (1127 loc) · 34.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
import { AsyncResource } from "node:async_hooks";
import { createRequire } from "node:module";
import type {
Bash as NativeBashType,
BashTool as NativeBashToolType,
ScriptedTool as NativeScriptedToolType,
ExecResult,
BashOptions as NativeBashOptions,
SnapshotOptions as NativeSnapshotOptions,
} from "./index.cjs";
const require = createRequire(import.meta.url);
const native = require("./index.cjs");
const NativeBash: typeof NativeBashType = native.Bash;
const NativeBashTool: typeof NativeBashToolType = native.BashTool;
const NativeScriptedTool: typeof NativeScriptedToolType = native.ScriptedTool;
const nativeGetVersion: () => string = native.getVersion;
export type { ExecResult };
/**
* A file value: either a string, a sync function returning a string,
* or an async function returning a Promise<string>.
*
* Function values are resolved lazily on first read and cached.
*/
export type FileValue = string | (() => string) | (() => Promise<string>);
const MAX_JSON_NESTING_DEPTH = 64;
/**
* Options for creating a Bash or BashTool instance.
*/
export interface BashOptions {
username?: string;
hostname?: string;
maxCommands?: number;
maxLoopIterations?: number;
/**
* Maximum interpreter memory in bytes (variables, arrays, functions).
*
* Caps the total byte budget for variable storage and function bodies.
* Prevents OOM from untrusted input such as exponential string doubling.
*
* @example
* ```typescript
* const bash = new Bash({ maxMemory: 10 * 1024 * 1024 }); // 10 MB
* ```
*/
maxMemory?: number;
/**
* Execution timeout in milliseconds.
*
* When set, commands that exceed this duration are aborted with
* exit code 124 (matching the bash `timeout` convention).
*
* @example
* ```typescript
* const bash = new Bash({ timeoutMs: 30000 }); // 30 seconds
* ```
*/
timeoutMs?: number;
/**
* Files to mount in the virtual filesystem.
* Keys are absolute paths, values are content strings or lazy providers.
*
* String values are mounted immediately. Function values are called on
* first read and the result is cached.
*
* @example
* ```typescript
* const bash = await Bash.create({
* files: {
* "/data/config.json": '{"key": "value"}',
* "/data/large.json": () => fetchData(),
* "/data/remote.txt": async () => await fetch(url).then(r => r.text()),
* }
* });
* ```
*/
files?: Record<string, FileValue>;
/**
* Real filesystem mounts. Each mount maps a host directory into the VFS.
*
* @example
* ```typescript
* const bash = new Bash({
* mounts: [
* { path: "/docs", root: "/real/path/to/docs" },
* ],
* });
* ```
*/
mounts?: Array<{ path: string; root: string; writable?: boolean }>;
/**
* Enable embedded Python execution (`python`/`python3` builtins).
*
* When true, bash scripts can use `python -c '...'` or `python3 script.py`
* to run Python code within the sandbox.
*/
python?: boolean;
/**
* Names of external functions callable from embedded Python code.
*
* These function names become available as Python builtins within
* the embedded interpreter. When called, they invoke the external handler.
*/
externalFunctions?: string[];
}
export interface SnapshotOptions {
excludeFilesystem?: boolean;
excludeFunctions?: boolean;
}
export interface OutputChunk {
stdout: string;
stderr: string;
}
export type OnOutput = (chunk: OutputChunk) => void;
export interface ExecuteOptions {
signal?: AbortSignal;
/**
* Live chunk callback. Must be synchronous.
*
* Limitation: do not call back into the same `Bash` / `BashTool` instance
* from this handler (`execute*`, `readFile`, `fs()`, etc.). The current
* binding rejects same-instance re-entry to avoid deadlocks and runtime
* panics.
*/
onOutput?: OnOutput;
}
type NativeOnOutput = (chunkPair: [string, string]) => string | undefined;
const ASYNC_ON_OUTPUT_ERROR =
"onOutput must be synchronous and must not return a Promise";
const asyncExecuteQueues = new WeakMap<object, Promise<void>>();
function isAsyncFunction(fn: Function): boolean {
return Object.prototype.toString.call(fn) === "[object AsyncFunction]";
}
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
return (
value !== null &&
(typeof value === "object" || typeof value === "function") &&
typeof (value as { then?: unknown }).then === "function"
);
}
function cancelledExecResult(): ExecResult {
return {
stdout: "",
stderr: "",
exitCode: 1,
error: "execution cancelled",
stdoutTruncated: false,
stderrTruncated: false,
finalEnv: undefined,
success: false,
};
}
// Decision: serialize async execute() per instance in JS so queued AbortSignal
// listeners only attach once a call reaches the front of the line.
function queueAsyncExecute<T>(
owner: object,
run: () => Promise<T>,
): Promise<T> {
const previous = asyncExecuteQueues.get(owner) ?? Promise.resolve();
const completion = previous.then(
() => run(),
() => run(),
);
asyncExecuteQueues.set(
owner,
completion.then(
() => undefined,
() => undefined,
),
);
return completion;
}
function bindOnOutputToCurrentAsyncContext(onOutput: OnOutput): OnOutput {
return AsyncResource.bind(onOutput) as OnOutput;
}
function toNativeOnOutput(onOutput?: OnOutput): NativeOnOutput | undefined {
if (!onOutput) return undefined;
if (isAsyncFunction(onOutput)) {
throw new TypeError(ASYNC_ON_OUTPUT_ERROR);
}
const onOutputWithContext = bindOnOutputToCurrentAsyncContext(onOutput);
// The native binding passes one tuple payload `[stdoutChunk, stderrChunk]`.
// Adapt that odd FFI shape here so the public wrapper API stays future-proof.
return ([stdoutChunk, stderrChunk]) => {
try {
const result = onOutputWithContext({
stdout: stdoutChunk,
stderr: stderrChunk,
});
if (isPromiseLike(result)) {
void Promise.resolve(result).catch(() => {});
return ASYNC_ON_OUTPUT_ERROR;
}
return undefined;
} catch (error) {
if (error instanceof Error) {
return error.stack ?? error.message ?? error.toString();
}
return String(error);
}
};
}
/**
* Resolve file values: sync functions are called immediately,
* async functions are awaited. Returns a plain string map.
*/
async function resolveFiles(
files?: Record<string, FileValue>,
): Promise<Record<string, string> | undefined> {
if (!files) return undefined;
const resolved: Record<string, string> = {};
for (const [path, value] of Object.entries(files)) {
if (typeof value === "string") {
resolved[path] = value;
} else if (typeof value === "function") {
const result = value();
resolved[path] =
result instanceof Promise ? await result : (result as string);
}
}
return resolved;
}
function validateJsonNestingDepth(value: unknown, depth = 0): void {
if (depth > MAX_JSON_NESTING_DEPTH) {
throw new RangeError(
`JSON nesting depth exceeds maximum of ${MAX_JSON_NESTING_DEPTH}`,
);
}
if (Array.isArray(value)) {
for (const item of value) {
validateJsonNestingDepth(item, depth + 1);
}
return;
}
if (value && typeof value === "object") {
for (const item of Object.values(value as Record<string, unknown>)) {
validateJsonNestingDepth(item, depth + 1);
}
}
}
/**
* Resolve file values synchronously. Throws if any value is async.
*/
function resolveFilesSync(
files?: Record<string, FileValue>,
): Record<string, string> | undefined {
if (!files) return undefined;
const resolved: Record<string, string> = {};
for (const [path, value] of Object.entries(files)) {
if (typeof value === "string") {
resolved[path] = value;
} else if (typeof value === "function") {
const result = value();
if (result instanceof Promise) {
throw new Error(
`File "${path}" has an async provider. Use Bash.create() instead of new Bash() for async file values.`,
);
}
resolved[path] = result as string;
}
}
return resolved;
}
function toNativeOptions(
options?: BashOptions,
resolvedFiles?: Record<string, string>,
): NativeBashOptions | undefined {
if (!options && !resolvedFiles) return undefined;
return {
username: options?.username,
hostname: options?.hostname,
maxCommands: options?.maxCommands,
maxLoopIterations: options?.maxLoopIterations,
maxMemory: options?.maxMemory,
timeoutMs: options?.timeoutMs,
files: resolvedFiles,
mounts: options?.mounts?.map((m) => ({
hostPath: m.root,
vfsPath: m.path,
writable: m.writable,
})),
python: options?.python,
externalFunctions: options?.externalFunctions,
};
}
function toNativeSnapshotOptions(
options?: SnapshotOptions,
): NativeSnapshotOptions | undefined {
if (!options) return undefined;
return {
excludeFilesystem: options.excludeFilesystem,
excludeFunctions: options.excludeFunctions,
};
}
/**
* Error thrown when a bash command execution fails.
*/
export class BashError extends Error {
readonly exitCode: number;
readonly stderr: string;
constructor(result: ExecResult) {
const message =
result.error ?? result.stderr ?? `Exit code ${result.exitCode}`;
super(message);
this.name = "BashError";
this.exitCode = result.exitCode;
this.stderr = result.stderr;
}
display(): string {
return `BashError(exit_code=${this.exitCode}): ${this.message}`;
}
}
/**
* Core bash interpreter with virtual filesystem.
*
* State persists between calls — files created in one `execute()` are
* available in subsequent calls.
*
* @example
* ```typescript
* import { Bash } from '@everruns/bashkit';
*
* const bash = new Bash();
* const result = bash.executeSync('echo "Hello, World!"');
* console.log(result.stdout); // Hello, World!\n
* ```
*/
export class Bash {
private native: NativeBashType;
constructor(options?: BashOptions) {
const resolved = resolveFilesSync(options?.files);
this.native = new NativeBash(toNativeOptions(options, resolved));
}
/**
* Create a Bash instance with support for async file providers.
*
* Use this instead of `new Bash()` when file values are async functions.
*
* @example
* ```typescript
* const bash = await Bash.create({
* files: {
* "/data/remote.json": async () => await fetchData(),
* }
* });
* ```
*/
static async create(options?: BashOptions): Promise<Bash> {
const resolved = await resolveFiles(options?.files);
const instance = Object.create(Bash.prototype) as Bash;
instance.native = new NativeBash(toNativeOptions(options, resolved));
return instance;
}
/**
* Execute bash commands synchronously and return the result.
*
* If `signal` is provided, the execution will be cancelled when the signal
* is aborted. If `onOutput` is provided, it receives chunk objects with
* `{ stdout, stderr }` during execution. Chunks are not line-aligned. The callback must be
* synchronous; Promise-returning handlers are rejected. Do not re-enter the
* same instance from `onOutput` via `execute*`, `readFile`, `fs()`, etc.
*/
executeSync(commands: string, options?: ExecuteOptions): ExecResult {
const nativeOnOutput = toNativeOnOutput(options?.onOutput);
if (options?.signal) {
const signal = options.signal;
if (signal.aborted) {
return cancelledExecResult();
}
const onAbort = () => this.native.cancel();
signal.addEventListener("abort", onAbort, { once: true });
try {
return this.native.executeSync(commands, nativeOnOutput);
} finally {
signal.removeEventListener("abort", onAbort);
if (signal.aborted) {
this.native.clearCancel();
}
}
}
return this.native.executeSync(commands, nativeOnOutput);
}
/**
* Execute bash commands asynchronously, returning a Promise.
*
* Non-blocking for the Node.js event loop.
* If `onOutput` is provided, it receives chunk objects with `{ stdout, stderr }`
* during execution. Chunks are not line-aligned. The callback must be
* synchronous; Promise-returning handlers are rejected. Do not re-enter the
* same instance from `onOutput` via `execute*`, `readFile`, `fs()`, etc.
*
* @example
* ```typescript
* const result = await bash.execute('echo hello');
* console.log(result.stdout); // hello\n
* ```
*/
async execute(
commands: string,
options?: ExecuteOptions,
): Promise<ExecResult> {
const nativeOnOutput = toNativeOnOutput(options?.onOutput);
const signal = options?.signal;
if (signal?.aborted) {
return cancelledExecResult();
}
return queueAsyncExecute(this, async () => {
if (signal?.aborted) {
return cancelledExecResult();
}
if (signal) {
let signalTriggered = false;
const onAbort = () => {
signalTriggered = true;
this.native.cancel();
};
signal.addEventListener("abort", onAbort, { once: true });
try {
if (nativeOnOutput) {
return await this.native.executeWithOutput(
commands,
nativeOnOutput,
);
}
return await this.native.execute(commands);
} finally {
signal.removeEventListener("abort", onAbort);
if (signalTriggered) {
this.native.clearCancel();
}
}
}
if (nativeOnOutput) {
return this.native.executeWithOutput(commands, nativeOnOutput);
}
return this.native.execute(commands);
});
}
/**
* Execute bash commands synchronously. Throws `BashError` on non-zero exit.
*/
executeSyncOrThrow(commands: string, options?: ExecuteOptions): ExecResult {
const result = this.executeSync(commands, options);
if (result.exitCode !== 0) {
throw new BashError(result);
}
return result;
}
/**
* Execute bash commands asynchronously. Throws `BashError` on non-zero exit.
*/
async executeOrThrow(
commands: string,
options?: ExecuteOptions,
): Promise<ExecResult> {
const result = await this.execute(commands, options);
if (result.exitCode !== 0) {
throw new BashError(result);
}
return result;
}
/**
* Cancel the currently running execution.
*/
cancel(): void {
this.native.cancel();
}
/**
* Clear the cancellation flag so subsequent executions proceed normally.
*
* Call this after `cancel()` once the in-flight execution has finished and
* you want to reuse the same instance without discarding shell or VFS state.
*/
clearCancel(): void {
this.native.clearCancel();
}
/**
* Reset interpreter to fresh state, preserving configuration.
*/
reset(): void {
this.native.reset();
}
// Snapshot / Resume
/**
* Serialize interpreter state (variables, VFS, counters) to a Uint8Array.
*
* The snapshot can be persisted to disk, sent over the network, and later
* used with `Bash.fromSnapshot()` to restore the session.
*
* @example
* ```typescript
* const bash = new Bash();
* await bash.execute("x=42");
* const snapshot = bash.snapshot();
* // persist snapshot...
* const bash2 = Bash.fromSnapshot(snapshot);
* const r = await bash2.execute("echo $x"); // "42\n"
* ```
*/
snapshot(options?: SnapshotOptions): Uint8Array {
return this.native.snapshot(toNativeSnapshotOptions(options));
}
/**
* Restore interpreter state from a previously captured snapshot.
* Preserves current configuration (limits, builtins) but replaces
* shell state and VFS contents.
*/
restoreSnapshot(data: Uint8Array): void {
this.native.restoreSnapshot(Buffer.from(data));
}
/**
* Create a new Bash instance from a snapshot.
*
* @example
* ```typescript
* const snapshot = existingBash.snapshot();
* const restored = Bash.fromSnapshot(snapshot);
* ```
*/
static fromSnapshot(data: Uint8Array): Bash {
const instance = new Bash();
instance.native = NativeBash.fromSnapshot(Buffer.from(data));
return instance;
}
// VFS — direct filesystem access
/** Read a file from the virtual filesystem as a UTF-8 string. */
readFile(path: string): string {
return this.native.readFile(path);
}
/** Write a string to a file in the virtual filesystem. */
writeFile(path: string, content: string): void {
this.native.writeFile(path, content);
}
/** Create a directory. If recursive is true, creates parents as needed. */
mkdir(path: string, recursive?: boolean): void {
this.native.mkdir(path, recursive);
}
/** Check if a path exists in the virtual filesystem. */
exists(path: string): boolean {
return this.native.exists(path);
}
/** Remove a file or directory. If recursive is true, removes contents. */
remove(path: string, recursive?: boolean): void {
this.native.remove(path, recursive);
}
/** Get metadata for a path (fileType, size, mode, timestamps). */
stat(path: string): {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
} {
return this.native.stat(path);
}
/** Append content to a file. */
appendFile(path: string, content: string): void {
this.native.appendFile(path, content);
}
/** Change file permissions (octal mode, e.g. 0o755). */
chmod(path: string, mode: number): void {
this.native.chmod(path, mode);
}
/** Create a symbolic link pointing to target. */
symlink(target: string, link: string): void {
this.native.symlink(target, link);
}
/** Read the target of a symbolic link. */
readLink(path: string): string {
return this.native.readLink(path);
}
/** List directory entries with metadata. */
readDir(path: string): Array<{
name: string;
metadata: {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
};
}> {
return this.native.readDir(path);
}
/** Get a JsFileSystem handle for direct VFS operations. */
fs(): any {
return this.native.fs();
}
/** Mount a host directory into the VFS. Read-only by default; pass writable: true to enable writes. */
mount(hostPath: string, vfsPath: string, writable?: boolean): void {
this.native.mount(hostPath, vfsPath, writable);
}
/** Unmount a previously mounted filesystem. */
unmount(vfsPath: string): void {
this.native.unmount(vfsPath);
}
/**
* List entry names in a directory. Returns empty array if directory does not exist.
*/
ls(path?: string): string[] {
const target = path ?? ".";
try {
return this.native.readDir(target).map((e: { name: string }) => e.name);
} catch {
return [];
}
}
/**
* Find files matching a name pattern. Returns absolute paths.
*/
glob(pattern: string): string[] {
// Reject patterns containing shell metacharacters to prevent injection.
// Allow only safe glob characters: alphanumeric, *, ?, [], ., -, _, /
if (/[^a-zA-Z0-9*?\[\]._ /-]/.test(pattern)) {
return [];
}
const result = this.executeSync(
`find / -name '${pattern}' -type f 2>/dev/null`,
);
if (result.exitCode !== 0) return [];
return result.stdout
.split("\n")
.map((s) => s.trim())
.filter((s) => s.length > 0);
}
}
/**
* Bash interpreter with tool-contract metadata.
*
* Use this when integrating with AI frameworks that need tool definitions.
*
* @example
* ```typescript
* import { BashTool } from '@everruns/bashkit';
*
* const tool = new BashTool();
* console.log(tool.name); // "bashkit"
* console.log(tool.inputSchema()); // JSON schema string
* console.log(tool.help()); // Markdown help document
*
* const result = tool.executeSync('echo hello');
* console.log(result.stdout); // hello\n
* ```
*/
export class BashTool {
private native: NativeBashToolType;
constructor(options?: BashOptions) {
const resolved = resolveFilesSync(options?.files);
this.native = new NativeBashTool(toNativeOptions(options, resolved));
}
/**
* Create a BashTool instance with support for async file providers.
*/
static async create(options?: BashOptions): Promise<BashTool> {
const resolved = await resolveFiles(options?.files);
const instance = Object.create(BashTool.prototype) as BashTool;
instance.native = new NativeBashTool(toNativeOptions(options, resolved));
return instance;
}
/**
* Execute bash commands synchronously and return the result.
*
* If `onOutput` is provided, it must be synchronous; Promise-returning
* handlers are rejected. Do not re-enter the same instance from `onOutput`
* via `execute*`, `readFile`, `fs()`, etc.
*/
executeSync(commands: string, options?: ExecuteOptions): ExecResult {
const nativeOnOutput = toNativeOnOutput(options?.onOutput);
if (options?.signal) {
const signal = options.signal;
if (signal.aborted) {
return cancelledExecResult();
}
const onAbort = () => this.native.cancel();
signal.addEventListener("abort", onAbort, { once: true });
try {
return this.native.executeSync(commands, nativeOnOutput);
} finally {
signal.removeEventListener("abort", onAbort);
if (signal.aborted) {
this.native.clearCancel();
}
}
}
return this.native.executeSync(commands, nativeOnOutput);
}
/**
* Execute bash commands asynchronously, returning a Promise.
*
* If `onOutput` is provided, it must be synchronous; Promise-returning
* handlers are rejected. Do not re-enter the same instance from `onOutput`
* via `execute*`, `readFile`, `fs()`, etc.
*/
async execute(
commands: string,
options?: ExecuteOptions,
): Promise<ExecResult> {
const nativeOnOutput = toNativeOnOutput(options?.onOutput);
const signal = options?.signal;
if (signal?.aborted) {
return cancelledExecResult();
}
return queueAsyncExecute(this, async () => {
if (signal?.aborted) {
return cancelledExecResult();
}
if (signal) {
let signalTriggered = false;
const onAbort = () => {
signalTriggered = true;
this.native.cancel();
};
signal.addEventListener("abort", onAbort, { once: true });
try {
if (nativeOnOutput) {
return await this.native.executeWithOutput(
commands,
nativeOnOutput,
);
}
return await this.native.execute(commands);
} finally {
signal.removeEventListener("abort", onAbort);
if (signalTriggered) {
this.native.clearCancel();
}
}
}
if (nativeOnOutput) {
return this.native.executeWithOutput(commands, nativeOnOutput);
}
return this.native.execute(commands);
});
}
/**
* Execute bash commands synchronously. Throws `BashError` on non-zero exit.
*/
executeSyncOrThrow(commands: string, options?: ExecuteOptions): ExecResult {
const result = this.executeSync(commands, options);
if (result.exitCode !== 0) {
throw new BashError(result);
}
return result;
}
/**
* Execute bash commands asynchronously. Throws `BashError` on non-zero exit.
*/
async executeOrThrow(
commands: string,
options?: ExecuteOptions,
): Promise<ExecResult> {
const result = await this.execute(commands, options);
if (result.exitCode !== 0) {
throw new BashError(result);
}
return result;
}
/**
* Cancel the currently running execution.
*/
cancel(): void {
this.native.cancel();
}
/**
* Clear the cancellation flag so subsequent executions proceed normally.
*
* Call this after `cancel()` once the in-flight execution has finished and
* you want to reuse the same instance without discarding shell or VFS state.
*/
clearCancel(): void {
this.native.clearCancel();
}
/**
* Reset interpreter to fresh state, preserving configuration.
*/
reset(): void {
this.native.reset();
}
/**
* Serialize interpreter state (variables, VFS, counters) to a Uint8Array.
*/
snapshot(options?: SnapshotOptions): Uint8Array {
return this.native.snapshot(toNativeSnapshotOptions(options));
}
/**
* Restore interpreter state from a previously captured snapshot.
* Preserves current configuration (limits, identity) but replaces
* shell state and VFS contents.
*/
restoreSnapshot(data: Uint8Array): void {
this.native.restoreSnapshot(Buffer.from(data));
}
/**
* Create a new BashTool instance from a snapshot.
*
* Any provided options are applied before restoring the snapshot so limits
* and identity settings survive round-trips.
*/
static fromSnapshot(data: Uint8Array, options?: BashOptions): BashTool {
const resolved = resolveFilesSync(options?.files);
const instance = Object.create(BashTool.prototype) as BashTool;
instance.native = NativeBashTool.fromSnapshot(
Buffer.from(data),
toNativeOptions(options, resolved),
);
return instance;
}
// ==========================================================================
// VFS file helpers
// ==========================================================================
/**
* Check whether a path exists in the virtual filesystem.
*/
exists(path: string): boolean {
try {
return this.native.exists(path);
} catch {
return false;
}
}
/**
* Read file contents from the virtual filesystem.
* Throws `BashError` if the file does not exist.
*/
readFile(path: string): string {
return this.native.readFile(path);
}
/**
* Write content to a file in the virtual filesystem.
* Creates parent directories as needed.
*/
writeFile(path: string, content: string): void {
// Ensure parent directory exists (matches prior shell-based behavior)
const lastSlash = path.lastIndexOf("/");
if (lastSlash > 0) {
const parent = path.slice(0, lastSlash);
try {
this.native.mkdir(parent, true);
} catch {
// parent may already exist — ignore
}
}
this.native.writeFile(path, content);
}
/** Get metadata for a path (fileType, size, mode, timestamps). */
stat(path: string): {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
} {
return this.native.stat(path);
}
/** Append content to a file. */
appendFile(path: string, content: string): void {
this.native.appendFile(path, content);
}
/** Change file permissions (octal mode, e.g. 0o755). */
chmod(path: string, mode: number): void {
this.native.chmod(path, mode);
}
/** Create a symbolic link pointing to target. */
symlink(target: string, link: string): void {
this.native.symlink(target, link);
}
/** Read the target of a symbolic link. */
readLink(path: string): string {
return this.native.readLink(path);
}
/** List directory entries with metadata. */
readDir(path: string): Array<{
name: string;
metadata: {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
};
}> {
return this.native.readDir(path);
}
/** Get a JsFileSystem handle for direct VFS operations. */
fs(): any {
return this.native.fs();
}
/** Mount a host directory into the VFS. Read-only by default; pass writable: true to enable writes. */
mount(hostPath: string, vfsPath: string, writable?: boolean): void {
this.native.mount(hostPath, vfsPath, writable);
}
/** Unmount a previously mounted filesystem. */
unmount(vfsPath: string): void {
this.native.unmount(vfsPath);
}
/**
* List entry names in a directory. Returns empty array if directory does not exist.
*/
ls(path?: string): string[] {
const target = path ?? ".";
try {
return this.native.readDir(target).map((e: { name: string }) => e.name);
} catch {
return [];
}
}
/**
* Find files matching a name pattern. Returns absolute paths.
*/
glob(pattern: string): string[] {
// Reject patterns containing shell metacharacters to prevent injection.
// Allow only safe glob characters: alphanumeric, *, ?, [], ., -, _, /
if (/[^a-zA-Z0-9*?\[\]._ /-]/.test(pattern)) {
return [];
}
const result = this.executeSync(