Repository navigation
Expand file tree
/
Copy pathwrapper.ts
More file actions
2243 lines (2067 loc) · 65.8 KB
/
Copy pathwrapper.ts
File metadata and controls
2243 lines (2067 loc) · 65.8 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,
NetworkOptions,
NetworkCredential,
NetworkCredentialPlaceholder,
CredentialHeader,
ShellState,
ScriptAnalysis,
AnalyzedCommand,
AnalyzedRedirect,
ExecutionProfileName as NativeExecutionProfileName,
} from "./index.cjs";
export type { ScriptAnalysis, AnalyzedCommand, AnalyzedRedirect };
/** Closed typed execution-policy selectors. */
export const ExecutionProfile = Object.freeze({
Hardened: "Hardened",
Standard: "Standard",
Interactive: "Interactive",
} as const);
export type ExecutionProfileName =
(typeof ExecutionProfile)[keyof typeof ExecutionProfile];
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;
const nativeCreateFileSystem: () => any = native.__createFileSystem;
const nativeRealFileSystem: (
hostPath: string,
writable?: boolean,
allowedMountPaths?: string[],
) => any = native.__realFileSystem;
const nativeImportFileSystem: (external: unknown) => any =
native.__importFileSystem;
const nativeFileSystemToExternal: (fs: any) => unknown =
native.__fileSystemToExternal;
const nativeFileSystemReadFile: (fs: any, path: string) => string =
native.__fileSystemReadFile;
const nativeFileSystemWriteFile: (
fs: any,
path: string,
content: string,
) => void = native.__fileSystemWriteFile;
const nativeFileSystemAppendFile: (
fs: any,
path: string,
content: string,
) => void = native.__fileSystemAppendFile;
const nativeFileSystemMkdir: (
fs: any,
path: string,
recursive?: boolean,
) => void = native.__fileSystemMkdir;
const nativeFileSystemRemove: (
fs: any,
path: string,
recursive?: boolean,
) => void = native.__fileSystemRemove;
const nativeFileSystemStat: (
fs: any,
path: string,
) => {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
} = native.__fileSystemStat;
const nativeFileSystemExists: (fs: any, path: string) => boolean =
native.__fileSystemExists;
const nativeFileSystemReadDir: (
fs: any,
path: string,
) => Array<{
name: string;
metadata: {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
};
}> = native.__fileSystemReadDir;
const nativeFileSystemSymlink: (fs: any, target: string, link: string) => void =
native.__fileSystemSymlink;
const nativeFileSystemReadLink: (fs: any, path: string) => string =
native.__fileSystemReadLink;
const nativeFileSystemChmod: (fs: any, path: string, mode: number) => void =
native.__fileSystemChmod;
const nativeFileSystemRename: (
fs: any,
fromPath: string,
toPath: string,
) => void = native.__fileSystemRename;
const nativeFileSystemCopy: (
fs: any,
fromPath: string,
toPath: string,
) => void = native.__fileSystemCopy;
export type {
ExecResult,
NetworkOptions,
NetworkCredential,
NetworkCredentialPlaceholder,
CredentialHeader,
ShellState,
};
/**
* 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;
/**
* Execution context passed to a custom builtin registered via
* `customBuiltins` or `addBuiltin`.
*
* `name`, `argv`, `stdin`, `env`, and `cwd` are snapshots of the shell
* state at invocation time; `fs` is a live handle to the interpreter's
* virtual filesystem.
*/
export interface BuiltinContext {
/** The command name as invoked. */
readonly name: string;
/** Arguments (not including the command name). */
readonly argv: string[];
/** Piped input, or `null` if there is no pipe. */
readonly stdin: string | null;
/** Environment variables visible at the call site. */
readonly env: Record<string, string>;
/** Current working directory. */
readonly cwd: string;
/**
* Live handle to the interpreter's virtual filesystem — the same VFS the
* executing script sees. Reads observe earlier script writes and writes
* are visible to subsequent commands. Inherits mounts and read-only
* configuration.
*/
readonly fs: FileSystem;
}
/**
* Callback signature for custom builtins. Return the stdout to emit.
* Both sync (`string`) and async (`Promise<string>`) returns are supported.
* Exceptions / rejections surface as stderr with exit code 1.
*/
export type BuiltinCallback = (ctx: BuiltinContext) => string | Promise<string>;
/**
* Options for creating a Bash or BashTool instance.
*/
export interface BashOptions {
/** Named resource-policy baseline. Individual limit options override it. */
profile?: ExecutionProfileName;
username?: string;
hostname?: string;
/**
* Initial working directory for the shell.
*
* Sets the starting `cwd` directly instead of running a leading
* `cd "${cwd}"` command, avoiding the parse/exec overhead.
*
* @example
* ```typescript
* const bash = new Bash({ cwd: "/home/user" });
* ```
*/
cwd?: string;
/**
* Initial environment variables, applied before execution.
*
* Scripts see these immediately without an `export` prelude. Keys are
* variable names, values are their string values.
*
* @example
* ```typescript
* const bash = new Bash({ env: { HOME: "/home/user", LANG: "en_US.UTF-8" } });
* ```
*/
env?: Record<string, string>;
maxCommands?: number;
maxLoopIterations?: number;
maxTotalLoopIterations?: number;
/**
* Maximum script input size in UTF-8 bytes.
*
* Async execute validates this before entering the per-instance queue so
* oversized calls cannot wait while retaining large command strings.
*/
maxInputBytes?: 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 }>;
/**
* Allowlist of host path prefixes permitted for real filesystem mounts.
*
* Required for `mounts` and runtime `mount()` APIs. Mount targets must
* resolve under one of these prefixes; otherwise the call is rejected.
*/
allowedMountPaths?: string[];
/**
* 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;
/**
* Enable the embedded SQLite builtin (`sqlite`/`sqlite3`).
*
* Backed by Turso. When `true`, the binding both registers the builtin
* and injects `BASHKIT_ALLOW_INPROCESS_SQLITE=1` so the runtime gate is
* satisfied. Defaults to `false`. Default `SqliteLimits` apply: 4 MiB
* script cap, 256 MiB DB cap, 30 s wall-clock budget,
* resource-affecting PRAGMAs and `ATTACH`/`DETACH` rejected.
*/
sqlite?: boolean;
/**
* Outbound network configuration. When set, enables `curl`/`wget`
* restricted to the configured allowlist, with optional transparent
* credential injection. Omitted = network disabled (no `curl`/`wget`).
*
* Must specify either `allow` (list of URL patterns) or `allowAll: true`,
* not both. `blockPrivateIps` defaults to `true`.
*
* @example
* ```typescript
* const bash = new Bash({
* network: {
* allow: ["https://api.example.com/**"],
* credentials: [
* { pattern: "https://api.example.com/**", kind: "bearer", token: secret },
* ],
* },
* });
* ```
*/
network?: NetworkOptions;
/**
* 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[];
/**
* Custom JS callbacks registered as bash builtins.
*
* Each entry becomes a bash command that shares the instance's VFS — files
* created by the callback persist across `execute()` calls. Callbacks can be
* sync (`string` return) or async (`Promise<string>`); exceptions surface as
* stderr with exit code 1.
*
* Equivalent to calling `addBuiltin(name, cb)` for each entry. Survives
* `reset()`; not preserved through `snapshot()`/`restoreSnapshot()` — pass
* the option again after restoring.
*
* Override precedence: shell function > POSIX special builtin > custom
* builtin > baked-in builtin > PATH.
*
* @example
* ```typescript
* const bash = new Bash({
* customBuiltins: {
* "get-order": (ctx) =>
* JSON.stringify({ id: ctx.argv[0], status: "shipped" }) + "\n",
* },
* });
* await bash.execute("mkdir -p /scratch");
* await bash.execute("get-order 42 > /scratch/order.json");
* console.log((await bash.execute("cat /scratch/order.json")).stdout);
* ```
*/
customBuiltins?: Record<string, BuiltinCallback>;
}
export interface SnapshotOptions {
excludeFilesystem?: boolean;
excludeFunctions?: boolean;
/**
* Secret key used to authenticate snapshot bytes with HMAC-SHA256.
* Required for BashTool snapshots because tool snapshots may cross tenant
* or network trust boundaries. Recommended for any snapshot accepted from
* users, shared storage, or remote callers.
*/
hmacKey?: Uint8Array;
}
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 DEFAULT_MAX_INPUT_BYTES = 10_000_000;
const MAX_PENDING_ASYNC_EXECUTIONS = 8;
const ASYNC_EXECUTE_QUEUE_FULL_ERROR =
"too many pending async execute calls for this instance";
interface AsyncExecuteQueueState {
tail: Promise<void>;
pending: number;
}
const asyncExecuteQueues = new WeakMap<object, AsyncExecuteQueueState>();
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 errorExecResult(error: string): ExecResult {
return {
stdout: "",
stdoutBytes: [],
stderr: error,
stderrBytes: Array.from(Buffer.from(error, "utf8")),
exitCode: 1,
error,
stdoutTruncated: false,
stderrTruncated: false,
finalEnv: undefined,
success: false,
};
}
function cancelledExecResult(): ExecResult {
// Preserve prior behavior: cancellation does not populate stderr.
return {
stdout: "",
stdoutBytes: [],
stderr: "",
stderrBytes: [],
exitCode: 1,
error: "execution cancelled",
stdoutTruncated: false,
stderrTruncated: false,
finalEnv: undefined,
success: false,
};
}
function inputTooLargeExecResult(
commands: string,
maxInputBytes: number,
): ExecResult | undefined {
const inputBytes = Buffer.byteLength(commands, "utf8");
if (inputBytes <= maxInputBytes) {
return undefined;
}
return errorExecResult(
`input too large: ${inputBytes} bytes exceeds maxInputBytes ${maxInputBytes}`,
);
}
// Decision: serialize async execute() per instance in JS so queued AbortSignal
// listeners only attach once a call reaches the front of the line. Also bound
// the backlog before retaining large command strings in queued closures.
function queueAsyncExecute<T>(
owner: object,
run: () => Promise<T>,
): Promise<T> {
let state = asyncExecuteQueues.get(owner);
if (!state) {
state = { tail: Promise.resolve(), pending: 0 };
asyncExecuteQueues.set(owner, state);
}
if (state.pending >= MAX_PENDING_ASYNC_EXECUTIONS) {
return Promise.reject(new Error(ASYNC_EXECUTE_QUEUE_FULL_ERROR));
}
state.pending += 1;
const previous = state.tail;
const completion = previous.then(
() => run(),
() => run(),
);
state.tail = completion.then(
() => undefined,
() => undefined,
);
state.tail.finally(() => {
state.pending -= 1;
if (state.pending === 0 && asyncExecuteQueues.get(owner) === state) {
asyncExecuteQueues.delete(owner);
}
});
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) {
// THREAT[TM-INF-028]: never propagate error.stack — it contains host file
// paths and function names. Use error.message only, and strip path-like
// patterns so attacker-controlled output cannot smuggle them.
const raw =
error instanceof Error
? (error.message ?? error.toString())
: String(error);
// Remove absolute-path and file:// URL segments from the message.
// Use a negative lookbehind so paths after punctuation (e.g. "at(/home/…")
// are also stripped, not just paths preceded by whitespace.
const sanitized = raw
.replace(/file:\/\/[^\s]*/g, "<path>")
.replace(/(?<!\w)\/[^\s]*/g, "<path>");
return sanitized.slice(0, 256) || "output callback failed";
}
};
}
/**
* 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,
profile: options?.profile as NativeExecutionProfileName | undefined,
hostname: options?.hostname,
cwd: options?.cwd,
env: options?.env,
maxCommands: options?.maxCommands,
maxLoopIterations: options?.maxLoopIterations,
maxTotalLoopIterations: options?.maxTotalLoopIterations,
maxMemory: options?.maxMemory,
maxInputBytes: options?.maxInputBytes,
timeoutMs: options?.timeoutMs,
files: resolvedFiles,
mounts: options?.mounts?.map((m) => ({
hostPath: m.root,
vfsPath: m.path,
writable: m.writable,
})),
allowedMountPaths: options?.allowedMountPaths,
python: options?.python,
externalFunctions: options?.externalFunctions,
sqlite: options?.sqlite,
network: options?.network,
};
}
function toNativeSnapshotOptions(
options?: SnapshotOptions,
): NativeSnapshotOptions | undefined {
if (!options) return undefined;
return {
excludeFilesystem: options.excludeFilesystem,
excludeFunctions: options.excludeFunctions,
hmacKey: options.hmacKey ? Buffer.from(options.hmacKey) : undefined,
};
}
function requireSnapshotHmacKey(options?: SnapshotOptions): void {
if (!options?.hmacKey || options.hmacKey.byteLength === 0) {
throw new Error(
"BashTool snapshots require SnapshotOptions.hmacKey for HMAC authentication",
);
}
}
function isFileSystemLike(value: unknown): value is { toExternal(): unknown } {
return (
typeof (value as { toExternal?: unknown } | null)?.toExternal === "function"
);
}
/**
* 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}`;
}
}
/**
* Standalone filesystem handle for direct VFS operations and native addon interop.
*/
export interface FileSystemRealOptions {
writable?: boolean;
allowedMountPaths: string[];
}
export class FileSystem {
private native: any;
private external?: unknown;
constructor() {
this.native = nativeCreateFileSystem();
}
static fromNative(nativeFs: any): FileSystem {
const fs = Object.create(FileSystem.prototype) as FileSystem;
fs.native = nativeFs;
fs.external = undefined;
return fs;
}
static real(hostPath: string, options: FileSystemRealOptions): FileSystem {
if (!options || !Array.isArray(options.allowedMountPaths)) {
throw new TypeError("FileSystem.real requires options.allowedMountPaths");
}
return FileSystem.fromNative(
nativeRealFileSystem(
hostPath,
options.writable,
options.allowedMountPaths,
),
);
}
static fromExternal(external: unknown): FileSystem {
const fs = FileSystem.fromNative(nativeImportFileSystem(external));
fs.external = external;
return fs;
}
toExternal(): unknown {
this.external ??= nativeFileSystemToExternal(this.native);
return this.external;
}
readFile(path: string): string {
return nativeFileSystemReadFile(this.native, path);
}
writeFile(path: string, content: string): void {
nativeFileSystemWriteFile(this.native, path, content);
}
appendFile(path: string, content: string): void {
nativeFileSystemAppendFile(this.native, path, content);
}
mkdir(path: string, recursive?: boolean): void {
nativeFileSystemMkdir(this.native, path, recursive);
}
remove(path: string, recursive?: boolean): void {
nativeFileSystemRemove(this.native, path, recursive);
}
stat(path: string): {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
} {
return nativeFileSystemStat(this.native, path);
}
exists(path: string): boolean {
return nativeFileSystemExists(this.native, path);
}
readDir(path: string): Array<{
name: string;
metadata: {
fileType: string;
size: number;
mode: number;
modified: number;
created: number;
};
}> {
return nativeFileSystemReadDir(this.native, path);
}
symlink(target: string, link: string): void {
nativeFileSystemSymlink(this.native, target, link);
}
readLink(path: string): string {
return nativeFileSystemReadLink(this.native, path);
}
chmod(path: string, mode: number): void {
nativeFileSystemChmod(this.native, path, mode);
}
rename(fromPath: string, toPath: string): void {
nativeFileSystemRename(this.native, fromPath, toPath);
}
copy(fromPath: string, toPath: string): void {
nativeFileSystemCopy(this.native, fromPath, toPath);
}
}
/**
* Wrap a {@link BuiltinCallback} for the native `addBuiltin` ABI.
*
* The native side passes the JSON-serialized context plus an opaque VFS
* handle. Like the output callback, the napi TSFN delivers the
* `(String, External)` args as one `[payload, fsHandle]` tuple; this
* wrapper adapts that odd FFI shape into a single {@link BuiltinContext}
* object with a live `fs` accessor.
*
* The Rust side expects a uniform `Promise<string>` return, so we always
* route the callback result through `Promise.resolve` — sync `string`
* returns get wrapped, native `Promise<string>` returns pass through, and
* synchronous throws become rejected promises. Either way, the Rust adapter
* sees one shape: a Promise it can `.await`.
*/
function makeBuiltinDispatcher(
callback: BuiltinCallback,
): (requestPair: [string, unknown]) => Promise<string> {
return (requestPair: [string, unknown]) => {
try {
const [payload, fsHandle] = requestPair;
const parsed = JSON.parse(payload) as Omit<BuiltinContext, "fs">;
const ctx: BuiltinContext = {
...parsed,
fs: FileSystem.fromNative(fsHandle),
};
return Promise.resolve(callback(ctx));
} catch (e) {
return Promise.reject(e);
}
};
}
/**
* Register each entry of `builtins` on `native` via `addBuiltin`.
* Idempotent for empty/undefined input.
*/
function registerCustomBuiltins(
native: {
addBuiltin(
name: string,
dispatch: (requestPair: [string, unknown]) => Promise<string>,
): void;
},
builtins: Record<string, BuiltinCallback> | undefined,
): void {
if (!builtins) return;
for (const [name, cb] of Object.entries(builtins)) {
native.addBuiltin(name, makeBuiltinDispatcher(cb));
}
}
/**
* 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;
private maxInputBytes: number;
constructor(options?: BashOptions) {
const resolved = resolveFilesSync(options?.files);
this.native = new NativeBash(toNativeOptions(options, resolved));
this.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES;
registerCustomBuiltins(this.native, options?.customBuiltins);
}
/**
* 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));
instance.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES;
registerCustomBuiltins(instance.native, options?.customBuiltins);
return instance;
}
/**
* Register a JS callback as a custom bash builtin.
*
* The callback receives a {@link BuiltinContext} and returns the stdout to
* emit. Sync (`string`) and async (`Promise<string>`) returns are both
* supported. Exceptions become stderr + exit code 1.
*
* Safe to call at any time — the new builtin is visible to the next
* `execute*()` invocation with no interpreter rebuild or VFS disturbance.
* Survives `reset()`.
*/
addBuiltin(name: string, callback: BuiltinCallback): void {
this.native.addBuiltin(name, makeBuiltinDispatcher(callback));
}
/** Remove a previously registered custom builtin. */
removeBuiltin(name: string): void {
this.native.removeBuiltin(name);
}
/**
* Set an exported environment variable on the live interpreter.
*
* The env counterpart to runtime {@link Bash.mount} — usable after
* construction, so a reusable setup bundle (mount + env + builtins) can be
* applied to an existing instance instead of only through
* {@link BashOptions}. Scripts see it as `$NAME`; child contexts see it in
* `env`. A later script assignment wins.
*
* Survives `reset()`, like `customBuiltins` and unlike env a *script*
* exported: only host-set values are replayed on rebuild.
*
* @example
* ```typescript
* const bash = new Bash();
* bash.mount("/skills/my-skill", skillFs);
* bash.setEnv("SKILL_PATH", "/skills/my-skill");
* await bash.execute('cat "$SKILL_PATH/SKILL.md"');
* ```
*/
setEnv(key: string, value: string): void {
this.native.setEnv(key, value);
}
/**
* 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 inputLimitResult = inputTooLargeExecResult(
commands,
this.maxInputBytes,
);
if (inputLimitResult) {
return inputLimitResult;
}
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();
}
const inputLimitResult = inputTooLargeExecResult(
commands,
this.maxInputBytes,
);
if (inputLimitResult) {
return inputLimitResult;
}
return queueAsyncExecute(this, async () => {
if (signal?.aborted) {
return cancelledExecResult();
}
if (signal) {
let signalTriggered = false;