@strands-agents/shell 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,218 @@
1
+ // @strands-agents/shell — customer-facing JS API.
2
+ //
3
+ // Wraps the napi-generated native loader (`native.js`) with:
4
+ // * a config-driven `Shell.create(config)` factory (the native layer exposes
5
+ // a fluent builder, which we keep internal), and
6
+ // * a typed `ShellError` hierarchy. The native file ops reject with an Error
7
+ // whose message is a tab-delimited "{code}\t{path}\t{message}" envelope
8
+ // (set in src/js.rs::file_error); we parse it and re-throw the matching
9
+ // subclass with `.code` / `.path` / `.message` properties.
10
+
11
+ const native = require('./native.js')
12
+
13
+ // --- Error hierarchy ------------------------------------------------------
14
+
15
+ class ShellError extends Error {
16
+ constructor(message, { path = '', code = 'EOTHER' } = {}) {
17
+ super(message)
18
+ this.name = new.target.name
19
+ this.path = path
20
+ this.code = code
21
+ }
22
+ }
23
+
24
+ class NotFoundError extends ShellError {}
25
+ class PermissionDeniedError extends ShellError {}
26
+ class FileTooLargeError extends ShellError {}
27
+
28
+ const ERROR_BY_CODE = {
29
+ ENOENT: NotFoundError,
30
+ EACCES: PermissionDeniedError,
31
+ EFBIG: FileTooLargeError,
32
+ EOTHER: ShellError,
33
+ }
34
+
35
+ // Parse the tab-delimited envelope from native and build a typed error.
36
+ // Falls back to a generic ShellError if the message isn't in envelope form
37
+ // (e.g. a bug-level rejection from deeper in napi).
38
+ function toTypedError(err) {
39
+ const raw = err && typeof err.message === 'string' ? err.message : String(err)
40
+ const firstTab = raw.indexOf('\t')
41
+ const secondTab = firstTab === -1 ? -1 : raw.indexOf('\t', firstTab + 1)
42
+ if (firstTab === -1 || secondTab === -1) {
43
+ return new ShellError(raw)
44
+ }
45
+ const code = raw.slice(0, firstTab)
46
+ const path = raw.slice(firstTab + 1, secondTab)
47
+ const message = raw.slice(secondTab + 1)
48
+ const Cls = ERROR_BY_CODE[code] || ShellError
49
+ return new Cls(message, { path, code: ERROR_BY_CODE[code] ? code : 'EOTHER' })
50
+ }
51
+
52
+ // Wrap a native file-op promise so its rejection is re-thrown as a typed error.
53
+ async function mapErrors(promise) {
54
+ try {
55
+ return await promise
56
+ } catch (err) {
57
+ throw toTypedError(err)
58
+ }
59
+ }
60
+
61
+ // --- Shell ----------------------------------------------------------------
62
+
63
+ class Shell {
64
+ // Private — constructed via Shell.create(). Holds the native shell.
65
+ constructor(inner) {
66
+ this._inner = inner
67
+ }
68
+
69
+ /**
70
+ * Create a sandboxed shell from a config object. Async because the native
71
+ * worker thread is spawned and mounts are materialized during build.
72
+ */
73
+ static async create(config = {}) {
74
+ const {
75
+ binds = [],
76
+ credentials = [],
77
+ allowedUrls = [],
78
+ env = {},
79
+ umask,
80
+ timeout,
81
+ limits,
82
+ configFile,
83
+ } = config
84
+
85
+ const b = new native.ShellBuilder()
86
+
87
+ // configFile merges in first; explicit options below win over it. Each
88
+ // behavioral/limit setting is applied only when the caller actually passed
89
+ // it (`undefined` means "unset"), so omitting an option never silently
90
+ // clobbers a value the TOML set. The Rust core supplies the real defaults
91
+ // when nothing is configured here or in the file.
92
+ if (configFile !== undefined) {
93
+ b.configFile(configFile)
94
+ }
95
+
96
+ for (const bind of binds) {
97
+ const { source, destination, mode = 'direct', readonly = false } = bind
98
+ if (mode === 'direct' && readonly) {
99
+ b.bindDirectReadonly(source, destination)
100
+ } else if (mode === 'direct') {
101
+ b.bindDirect(source, destination)
102
+ } else if (readonly) {
103
+ b.bindReadonly(source, destination)
104
+ } else {
105
+ b.bind(source, destination)
106
+ }
107
+ }
108
+
109
+ for (const cred of credentials) {
110
+ const hasToken = cred.token !== undefined && cred.token !== null
111
+ const hasEnv = cred.envVar !== undefined && cred.envVar !== null
112
+ if (hasToken === hasEnv) {
113
+ throw new Error('CredConfig requires exactly one of `token` or `envVar`')
114
+ }
115
+ if (hasToken) {
116
+ b.credential(cred.url, cred.token)
117
+ } else {
118
+ b.credentialFromEnv(cred.url, cred.envVar)
119
+ }
120
+ }
121
+
122
+ for (const prefix of allowedUrls) {
123
+ b.allowUrl(prefix)
124
+ }
125
+
126
+ for (const [key, value] of Object.entries(env)) {
127
+ b.env(key, value)
128
+ }
129
+
130
+ if (umask !== undefined) {
131
+ b.umask(umask)
132
+ }
133
+ if (timeout !== undefined) {
134
+ // Reject non-positive / non-finite up front: zero would expire every
135
+ // command immediately (there is no "unlimited" sentinel — omit timeout
136
+ // instead), and a negative/NaN/Infinity value would panic the native
137
+ // Duration::from_secs_f64 across the FFI boundary.
138
+ if (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout <= 0) {
139
+ throw new Error(
140
+ 'timeout must be a positive, finite number of seconds (omit it for no timeout)',
141
+ )
142
+ }
143
+ b.timeout(timeout)
144
+ }
145
+
146
+ // Limits — namespaced. Apply only when a bundle is passed; within it, each
147
+ // field falls back to the documented default so a partial { maxOutput }
148
+ // still pins the others to their defaults rather than to whatever the
149
+ // config file set. (Passing no `limits` at all leaves the file/core in
150
+ // charge.)
151
+ if (limits !== undefined) {
152
+ const L = {
153
+ maxOutput: 1 << 20,
154
+ maxFileSize: 10 << 20,
155
+ maxFds: 128,
156
+ maxBgJobs: 8,
157
+ maxPipeline: 16,
158
+ maxInput: 1 << 20,
159
+ maxInodes: 10000,
160
+ maxDepth: 64,
161
+ ...limits,
162
+ }
163
+ b.maxOutput(L.maxOutput)
164
+ b.maxFileSize(L.maxFileSize)
165
+ b.maxFds(L.maxFds)
166
+ b.maxBgJobs(L.maxBgJobs)
167
+ b.maxPipeline(L.maxPipeline)
168
+ b.maxInput(L.maxInput)
169
+ b.maxInodes(L.maxInodes)
170
+ b.maxDepth(L.maxDepth)
171
+ }
172
+
173
+ const inner = await b.build()
174
+ return new Shell(inner)
175
+ }
176
+
177
+ // ---- Command execution ----
178
+
179
+ run(command) {
180
+ return this._inner.run(command)
181
+ }
182
+
183
+ // ---- Environment ----
184
+
185
+ setEnv(key, value) {
186
+ return this._inner.setEnv(key, value)
187
+ }
188
+
189
+ getEnv(key) {
190
+ return this._inner.getEnv(key)
191
+ }
192
+
193
+ // ---- VFS file operations ----
194
+
195
+ readFile(path) {
196
+ return mapErrors(this._inner.readFile(path))
197
+ }
198
+
199
+ writeFile(path, content) {
200
+ return mapErrors(this._inner.writeFile(path, content))
201
+ }
202
+
203
+ removeFile(path) {
204
+ return mapErrors(this._inner.removeFile(path))
205
+ }
206
+
207
+ listFiles(path) {
208
+ return mapErrors(this._inner.listFiles(path))
209
+ }
210
+ }
211
+
212
+ module.exports = {
213
+ Shell,
214
+ ShellError,
215
+ NotFoundError,
216
+ PermissionDeniedError,
217
+ FileTooLargeError,
218
+ }
package/native.d.ts ADDED
@@ -0,0 +1,111 @@
1
+ /* auto-generated by NAPI-RS */
2
+ /* eslint-disable */
3
+ /** A sandboxed shell environment. */
4
+ export declare class Shell {
5
+ /** Create a new ShellBuilder. */
6
+ static builder(): ShellBuilder
7
+ /** Run a command and capture output. */
8
+ run(command: string): Promise<Output>
9
+ /** Set an environment variable. */
10
+ setEnv(key: string, value: string): Promise<void>
11
+ /** Get an environment variable. */
12
+ getEnv(key: string): Promise<string | null>
13
+ /** Read a file from the virtual filesystem as raw bytes. */
14
+ readFile(path: string): Promise<Uint8Array>
15
+ /**
16
+ * Write raw bytes to a file in the virtual filesystem.
17
+ *
18
+ * Creates parent directories if missing. Truncates any existing file.
19
+ */
20
+ writeFile(path: string, content: Uint8Array): Promise<void>
21
+ /** Remove a file from the virtual filesystem. */
22
+ removeFile(path: string): Promise<void>
23
+ /**
24
+ * List entries in a directory, returning structured `FileInfo` objects.
25
+ *
26
+ * Names are basenames (no leading path).
27
+ */
28
+ listFiles(path: string): Promise<Array<FileInfo>>
29
+ }
30
+
31
+ /**
32
+ * Builder for configuring a Shell.
33
+ *
34
+ * The inner `crate::shell::ShellBuilder` lives behind a `Mutex<Option<...>>`
35
+ * so we can take it out on `build()`. Re-using a consumed builder
36
+ * throws `Error("builder consumed")`, matching the Python binding.
37
+ */
38
+ export declare class ShellBuilder {
39
+ constructor()
40
+ /** Bind a host path into the VFS (copy mode). */
41
+ bind(source: string, destination: string): this
42
+ /** Bind a host path as read-only (copy mode). */
43
+ bindReadonly(source: string, destination: string): this
44
+ /** Bind a host path with direct passthrough. */
45
+ bindDirect(source: string, destination: string): this
46
+ /** Bind a host path as read-only with direct passthrough. */
47
+ bindDirectReadonly(source: string, destination: string): this
48
+ /** Add a bearer token credential for URLs matching a pattern. */
49
+ credential(urlPattern: string, token: string): this
50
+ /** Add a bearer token credential from an environment variable. */
51
+ credentialFromEnv(urlPattern: string, envVar: string): this
52
+ /** Allow curl requests to URLs matching prefix (bypasses SSRF protection). */
53
+ allowUrl(prefix: string): this
54
+ /** Set an environment variable. */
55
+ env(key: string, value: string): this
56
+ /** Set the umask for file creation (default: 0o022). */
57
+ umask(umask: number): this
58
+ /** Set timeout in seconds. */
59
+ timeout(seconds: number): this
60
+ /** Set max recursion depth for functions/subshells. */
61
+ maxDepth(n: number): this
62
+ /** Set max output size in bytes. */
63
+ maxOutput(n: number): this
64
+ /** Set max file size in bytes. */
65
+ maxFileSize(n: number): this
66
+ /** Set max open file descriptors. */
67
+ maxFds(n: number): this
68
+ /** Set max concurrent background jobs. */
69
+ maxBgJobs(n: number): this
70
+ /** Set max pipeline stages. */
71
+ maxPipeline(n: number): this
72
+ /** Set max input size for parser in bytes. */
73
+ maxInput(n: number): this
74
+ /** Set max inodes (files + directories) in VFS. */
75
+ maxInodes(n: number): this
76
+ /** Load config from a TOML file. */
77
+ configFile(path: string): this
78
+ /**
79
+ * Build the Shell. Async because mount materialization may do I/O.
80
+ *
81
+ * The actual build runs on the new shell's dedicated worker thread
82
+ * — see `Worker::spawn`. We hop onto napi's blocking thread pool
83
+ * only to avoid stalling the JS event loop while waiting for the
84
+ * worker's build oneshot.
85
+ */
86
+ build(): Promise<Shell>
87
+ }
88
+
89
+ /**
90
+ * Metadata about a file or directory in the VFS.
91
+ *
92
+ * Mirrors the eventual Strands TS Sandbox `FileInfo` shape so adapters
93
+ * can spread by attribute copy.
94
+ */
95
+ export interface FileInfo {
96
+ name: string
97
+ isDir?: boolean
98
+ size?: number
99
+ }
100
+
101
+ /**
102
+ * Output from a shell command execution.
103
+ *
104
+ * Defined as `#[napi(object)]` so it surfaces in JS as a plain object
105
+ * literal rather than a class. Easier to mock and `JSON.stringify`-friendly.
106
+ */
107
+ export interface Output {
108
+ status: number
109
+ stdout: string
110
+ stderr: string
111
+ }