@vite-hub/shell 0.0.4 → 0.3.1

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/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # @vite-hub/shell
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
- <img alt="Shell" src="https://img.shields.io/badge/Shell-controlled%20runtime-18181b?style=flat-square">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
+ <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
+ <img alt="Shell" src="https://comark-ui.onmax.me/badge.svg?label=Shell&amp;value=controlled+runtime">
7
7
  </p>
8
8
 
9
9
  `@vite-hub/shell` gives server code structured command analysis and execution with explicit filesystem, network, process, and timeout boundaries.
@@ -28,11 +28,11 @@ console.log(analysis.hasPipelines); // false
28
28
  console.log(analysis.ok); // true
29
29
  ```
30
30
 
31
- Analysis reports command names, pipelines, redirects, heredocs, and command substitution. It does not make a command safe to run. The caller's policy and the execution provider remain the enforcement boundaries.
31
+ Analysis reports command names, pipelines, redirects, heredocs, and command substitution. It does not make a command safe to run. The caller's policy and the Shell driver remain the enforcement boundaries.
32
32
 
33
33
  ## Run against a Workspace
34
34
 
35
- The built-in Just Bash provider executes Bash-compatible commands against the filesystem adapter you give it. This example mounts a ViteHub Workspace read-only, permits four inspection commands, and returns a structured observation.
35
+ The built-in Just Bash driver executes Bash-compatible commands against the filesystem adapter you give it. This example mounts a ViteHub Workspace read-only, permits four inspection commands, and returns a structured observation.
36
36
 
37
37
  ```sh
38
38
  pnpm add @vite-hub/shell @vite-hub/workspace
@@ -41,7 +41,7 @@ pnpm add @vite-hub/shell @vite-hub/workspace
41
41
  ```ts
42
42
  // server/tasks/search-docs.ts
43
43
  import { createShellRuntime } from "@vite-hub/shell";
44
- import { createJustBashProvider } from "@vite-hub/shell/providers/just-bash";
44
+ import { createJustBashDriver } from "@vite-hub/shell/providers/just-bash";
45
45
  import { createReadonlyWorkspaceFs, workspaceMountPoint } from "@vite-hub/shell/workspace";
46
46
  import { useWorkspace } from "@vite-hub/workspace";
47
47
 
@@ -53,7 +53,7 @@ export async function searchDocs() {
53
53
  maxShellCalls: 1,
54
54
  timeout: 30_000,
55
55
  },
56
- provider: createJustBashProvider({
56
+ driver: createJustBashDriver({
57
57
  commands: ["cat", "ls", "pwd", "rg"],
58
58
  cwd: workspaceMountPoint,
59
59
  fs: createReadonlyWorkspaceFs(workspace.fs),
@@ -64,20 +64,45 @@ export async function searchDocs() {
64
64
  }
65
65
  ```
66
66
 
67
- `shell.exec()` creates a short-lived Shell Session and returns a Shell Observation with `event`, `exitCode`, `stdout`, and `stderr`. The provider above has no network access, background processes, or interactive processes, and its Workspace filesystem cannot write.
67
+ `shell.exec()` creates a short-lived Shell Session and returns a Shell Observation with `event`, `exitCode`, `stdout`, and `stderr`. The driver above has no network access, background processes, or interactive processes, and its Workspace filesystem cannot write.
68
68
 
69
- ## Providers and boundaries
69
+ For writable access, pass `useWorkspace(name, { mode: "write" }).fs` directly to `createWritableWorkspaceFs()`. The adapter accepts Workspace writes that return revision receipts. Its `writeFile()` and `appendFile()` methods wait for the write and return `void`.
70
+
71
+ ## Drivers and boundaries
70
72
 
71
73
  - `@vite-hub/shell/providers/just-bash` runs selected commands in `just-bash` against a supplied filesystem adapter.
72
- - `@vite-hub/shell/providers/cloudflare` adapts a Cloudflare execution client and reports the boundary that client can prove.
73
- - A custom `ShellExecutionProvider` declares its boundary and implements execution for another host.
74
+ - A custom `ShellDriver` declares its boundary and implements execution for another host.
75
+
76
+ Custom drivers can return Shell Processes as class instances. Sessions read the process ID, command, and working directory from the driver handle when inspected. These public metadata fields are readonly. A failed metadata read does not prevent process cleanup.
77
+
78
+ Shell policy can bound calls, processes, output size, and timeouts. A declared boundary describes the driver contract; it is not proof of operating-system isolation. Use [Sandbox](https://vitehub.dev/docs/sandbox) when work needs provider-managed isolation.
79
+
80
+ `runtime.boundary.execution` and `runtime.boundary.resources` expose the driver's execution model and resource controls. The Just Bash driver runs in a virtual in-process filesystem and truncates completed output before it creates a Shell Observation. It buffers the full result first, so this is not an execution memory limit. Pass an `AbortSignal` to `exec()` to cancel the command and any controlled Source request it starts.
81
+
82
+ Custom drivers can return Shell Observations as class instances. Sessions preserve every declared observation field, including fields exposed through getters.
83
+
84
+ The Workspace filesystem has a virtual root at `/workspace`. Root existence checks return true. On a writable filesystem, recursive directory creation at the root succeeds without changing the Workspace. Creating the root without `recursive` fails because it already exists.
85
+
86
+ Directory paths may end in `/`. Listing or copying `models/` preserves each child's full name, just as `models` does.
87
+
88
+ The Just Bash `commands` list also applies to controlled `curl` requests. A Source network grant permits access to its declared target, but `curl` must still be included when you configure a command list.
89
+
90
+ The driver copies the command list at creation. Later changes to the supplied list do not change its permissions or network boundary.
91
+
92
+ Pass `executionLimits` or `executionLimitProfile: "hardened"` to bound Just Bash interpreter work such as loop iterations, command count, and retained bytes. Both options pass through to Just Bash and are copied at creation. Controlled `curl` runs as a Just Bash command through Source network grants, so interpreter output limits and command deadlines apply, including in pipelines and substitutions. Interpreter deadlines, Shell timeouts, and Shell cancellation abort the signal forwarded to the Source request. The Source executor must honor that signal. `maxOutputLength` truncates returned output characters. Source responses are buffered before interpreter output checks and Shell truncation; enforce response byte or memory limits while reading the response in the Source executor.
93
+
94
+ The writable Workspace filesystem leaves content unchanged when a move resolves to the same source and destination. Missing sources fail. It rejects moves into descendants before changing content.
95
+
96
+ Workspace filesystem adapters preserve binary output from redirection and `tee`. Their read, write, and append methods honor Just Bash encoding options.
97
+
98
+ Just Bash defaults to `/workspace`. A driver `cwd` changes that default, and an `exec` `cwd` takes precedence. The driver reports the selected directory in its observations. Set `cwd` for a custom filesystem with another root.
74
99
 
75
- Shell policy can bound calls, processes, output size, and timeouts. A declared boundary describes the provider contract; it is not proof of operating-system isolation. Use [Sandbox](https://vitehub.dev/docs/server-primitives/sandbox) when work needs provider-managed isolation.
100
+ Appending creates an absent Workspace file. A read failure for an existing file fails the append before changing its content.
76
101
 
77
102
  ## Use with Agents
78
103
 
79
104
  `workspaceShell()` in [`@vite-hub/agent`](../agent/README.md) exposes scoped shell work through an Agent Capability. It attaches Workspace Scope, Shell policy, metadata, and tools to the Agent Definition; do not expose an unrestricted raw runtime to a model.
80
105
 
81
- Built on [just-bash](https://www.npmjs.com/package/just-bash) for the built-in shell provider and [sh-syntax](https://www.npmjs.com/package/sh-syntax) for command analysis.
106
+ Built on [just-bash](https://www.npmjs.com/package/just-bash) for the built-in Shell driver and [sh-syntax](https://www.npmjs.com/package/sh-syntax) for command analysis.
82
107
 
83
- Read the complete [Shell guide](https://vitehub.dev/docs/server-primitives/shell), the [Bash contract](https://vitehub.dev/docs/concepts/bash), and the [official Capabilities guide](https://vitehub.dev/docs/capabilities/official-capabilities).
108
+ Read the complete [Shell guide](https://vitehub.dev/docs/shell), the [Workspace shell Capability](https://vitehub.dev/docs/workspace/agent-capability), and the [official Capabilities guide](https://vitehub.dev/docs/agents/capabilities/official).
@@ -0,0 +1,459 @@
1
+ import { BinCmdOperator, LangVariant, RedirOperator, walk } from "sh-syntax";
2
+ import { defineDiagnostics } from "nostics";
3
+ //#region src/error-diagnostics.ts
4
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
5
+ const shellErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
6
+ docsBase: "https://vitehub.dev/docs/shell/diagnostics",
7
+ codes: {
8
+ SHELL_R0001: {
9
+ ...dynamicError,
10
+ fix: "Pass a positive `timeoutMs` to `analyzeShellCommand()` or `session.analyze()`, or remove it to use the 100 ms default."
11
+ },
12
+ SHELL_R0002: {
13
+ ...dynamicError,
14
+ fix: "Shorten the command, or raise `timeoutMs` of `analyzeShellCommand()` or `session.analyze()`. The default is 100 ms."
15
+ },
16
+ SHELL_R0003: {
17
+ ...dynamicError,
18
+ fix: "Correct the shell syntax of the command at the place that the message names. For example, close each quote, bracket, and `if` block."
19
+ },
20
+ SHELL_R0004: {
21
+ ...dynamicError,
22
+ fix: "Write the `curl` command with one valid URL and only `-s`, `-S`, `-L`, `-X` with `GET`, `HEAD`, or `POST`, `--url`, `--json` with valid JSON, or `-d`. Do not pass headers or cookies, because the Source grant adds the credentials."
23
+ },
24
+ SHELL_R0007: {
25
+ ...dynamicError,
26
+ fix: "Pass exactly one URL to `curl`. Run one `curl` command for each URL."
27
+ },
28
+ SHELL_R0008: {
29
+ ...dynamicError,
30
+ fix: "Create a new Shell session to start the process. Do not call `startProcess()` after `dispose()`."
31
+ },
32
+ SHELL_R0009: {
33
+ ...dynamicError,
34
+ fix: "Use a Shell driver that supports background processes, or run the command with `exec()`."
35
+ },
36
+ SHELL_R0010: {
37
+ ...dynamicError,
38
+ fix: "Stop a background process before you start another, or raise `policy.maxProcesses` in `createShellRuntime()`."
39
+ },
40
+ SHELL_R0011: {
41
+ ...dynamicError,
42
+ fix: "Do not dispose the Shell session while `startProcess()` runs. The other error in the `AggregateError` says why the process did not stop; stop it with the driver if it still runs."
43
+ },
44
+ SHELL_R0012: {
45
+ ...dynamicError,
46
+ fix: "Do not dispose the Shell session while `startProcess()` runs. Create a new session to start the process."
47
+ },
48
+ SHELL_R0013: {
49
+ ...dynamicError,
50
+ fix: "Use a path inside `/workspace`. Remove the `..` segments that leave the Workspace."
51
+ },
52
+ SHELL_R0014: {
53
+ ...dynamicError,
54
+ fix: "Mount the Workspace with `createWritableWorkspaceFs()` to let commands write, or run only commands that read files."
55
+ },
56
+ SHELL_R0015: {
57
+ ...dynamicError,
58
+ fix: "Do not run `chmod` in the Workspace filesystem. It does not keep file modes."
59
+ },
60
+ SHELL_R0016: {
61
+ ...dynamicError,
62
+ fix: "Do not create symbolic links, such as with `ln -s`, in the Workspace filesystem. Copy the file instead."
63
+ },
64
+ SHELL_R0017: {
65
+ ...dynamicError,
66
+ fix: "Do not create hard links, such as with `ln`, in the Workspace filesystem. Copy the file instead."
67
+ },
68
+ SHELL_R0018: {
69
+ ...dynamicError,
70
+ fix: "Do not run `readlink` in the Workspace filesystem. It has no symbolic links."
71
+ },
72
+ SHELL_R0019: {
73
+ ...dynamicError,
74
+ fix: "Do not run commands that set file times in the Workspace filesystem. It does not keep them."
75
+ },
76
+ SHELL_R0020: {
77
+ ...dynamicError,
78
+ fix: "Pass a path below the Workspace root to `cleanWorkspaceMutationPath()`, not `/`, `.`, or `/workspace`."
79
+ },
80
+ SHELL_R0021: {
81
+ ...dynamicError,
82
+ fix: "Use a path inside the Workspace. Remove the `..` segments that leave `/workspace`."
83
+ },
84
+ SHELL_R0022: {
85
+ ...dynamicError,
86
+ fix: "Move the path to a place outside itself. A directory cannot move into one of its own subdirectories."
87
+ },
88
+ SHELL_R0023: {
89
+ ...dynamicError,
90
+ fix: "The Workspace root exists already. Pass `-p` to `mkdir`, or create a directory below the root."
91
+ },
92
+ SHELL_R0024: {
93
+ ...dynamicError,
94
+ fix: "Make the driver return its process handle within the Shell timeout, or raise the Shell policy timeout if longer startup is expected."
95
+ },
96
+ SHELL_SH_SYNTAX_WASM_UNAVAILABLE: {
97
+ why: "[vitehub] sh-syntax cannot load its WebAssembly parser on this host.",
98
+ fix: "Build the server with `vitehub()`, which bundles the sh-syntax WebAssembly parser, or run it on Node, where sh-syntax reads `main.wasm` from its own package."
99
+ }
100
+ }
101
+ });
102
+ //#endregion
103
+ //#region src/command/sh-syntax.ts
104
+ let parser;
105
+ async function parseShell(text, options) {
106
+ parser ??= loadParser().catch((error) => {
107
+ parser = void 0;
108
+ throw error;
109
+ });
110
+ return (await parser)(text, options);
111
+ }
112
+ async function loadParser() {
113
+ const shSyntax = await import("sh-syntax");
114
+ const wasm = await bundledWasmModule();
115
+ if (!wasm) {
116
+ if (!shSyntax.parse) throw shellErrorDiagnostics.SHELL_SH_SYNTAX_WASM_UNAVAILABLE();
117
+ return shSyntax.parse;
118
+ }
119
+ const processor = shSyntax.getProcessor((imports) => WebAssembly.instantiate(wasm, imports));
120
+ return (text, options) => processor(text, options);
121
+ }
122
+ async function bundledWasmModule() {
123
+ try {
124
+ const wasm = await (await import("sh-syntax/main.wasm?module")).default;
125
+ if (wasm instanceof Uint8Array) return await WebAssembly.compile(wasm);
126
+ return wasm instanceof WebAssembly.Module ? wasm : void 0;
127
+ } catch {
128
+ return;
129
+ }
130
+ }
131
+ //#endregion
132
+ //#region src/command/parse.ts
133
+ function wordText(word, source, toIndex = createSourceIndex(source)) {
134
+ return word.parts.map((part) => wordPartText(part, source, toIndex, false)).join("");
135
+ }
136
+ function wordPartText(part, source, toIndex, doubleQuoted) {
137
+ switch (part.type) {
138
+ case "Lit": return doubleQuoted ? unescapeDoubleQuoted(part.value) : unescapeUnquoted(part.value);
139
+ case "SglQuoted": return part.value;
140
+ case "DblQuoted": return part.parts.map((nested) => wordPartText(nested, source, toIndex, true)).join("");
141
+ default: return source.slice(toIndex(part.start), toIndex(part.end));
142
+ }
143
+ }
144
+ function unescapeUnquoted(value) {
145
+ return value.replace(/\\(\n|.)/gs, (_, next) => next === "\n" ? "" : next);
146
+ }
147
+ function unescapeDoubleQuoted(value) {
148
+ let result = "";
149
+ for (let index = 0; index < value.length; index++) {
150
+ const char = value[index];
151
+ if (char === "\\" && index + 1 < value.length && /[\\$`"\n]/.test(value[index + 1])) {
152
+ const next = value[index + 1];
153
+ if (next !== "\n") result += next;
154
+ index += 1;
155
+ continue;
156
+ }
157
+ result += char;
158
+ }
159
+ return result;
160
+ }
161
+ function statementWords(stmt, command, toIndex, negated = stmt.negated) {
162
+ const words = commandWords(stmt, command, toIndex);
163
+ return negated && words[0] !== "!" ? ["!", ...words] : words;
164
+ }
165
+ function commandWords(stmt, command, toIndex) {
166
+ const call = stmt.cmd;
167
+ if (call?.type === "FuncDecl") return [`${call.name?.value ?? ""}()`];
168
+ if (call?.type !== "CallExpr") {
169
+ const firstToken = command.slice(toIndex(stmt.start), toIndex(stmt.end)).trim().match(/^\S+/);
170
+ return firstToken ? [firstToken[0]] : [];
171
+ }
172
+ return [
173
+ ...call.assigns.map((assign) => command.slice(toIndex(assign.start), toIndex(assign.end))),
174
+ ...call.args.map((arg) => wordText(arg, command, toIndex)),
175
+ ...stmt.redirs.map((redir) => command.slice(toIndex(redir.start), toIndex((redir.hdoc ? redir.word : redir)?.end ?? redir.end)))
176
+ ];
177
+ }
178
+ async function splitShellCommandSegments(command) {
179
+ let file;
180
+ try {
181
+ file = await parseShell(command, {
182
+ keepComments: true,
183
+ variant: LangVariant.LangBash
184
+ });
185
+ } catch {
186
+ return [{
187
+ command,
188
+ followsPipe: false,
189
+ invalid: true,
190
+ words: []
191
+ }];
192
+ }
193
+ const toIndex = createSourceIndex(command);
194
+ const scanned = withoutHeredocBodies(file, command, toIndex);
195
+ if (scanned === void 0 || stripLineContinuations(scanned).commentContinuation) return [{
196
+ command,
197
+ followsPipe: false,
198
+ invalid: true,
199
+ words: []
200
+ }];
201
+ const leaves = [];
202
+ file.stmts.forEach((stmt, index) => {
203
+ flattenStatement(stmt, statementSeparator(file.stmts, index, command, toIndex), toIndex, leaves);
204
+ });
205
+ const segments = [];
206
+ let cursor = 0;
207
+ let followsPipe = false;
208
+ for (const { negated, stmt, separator } of leaves) {
209
+ const trailingComment = stmt.comments.find((comment) => comment.start >= stmt.end);
210
+ const rawEnd = separator?.offset ?? (trailingComment ? toIndex(trailingComment.start) : toIndex(stmt.end));
211
+ const raw = stripLineContinuations(command.slice(cursor, Math.max(cursor, rawEnd))).text;
212
+ segments.push({
213
+ command: raw,
214
+ followsPipe,
215
+ ...separator ? { separatorAfter: separator.kind } : {},
216
+ words: statementWords(stmt, command, toIndex, negated)
217
+ });
218
+ if (separator) cursor = separator.offset + separator.length;
219
+ followsPipe = separator?.kind === "|";
220
+ }
221
+ return segments;
222
+ }
223
+ function withoutHeredocBodies(file, command, toIndex) {
224
+ let result = command;
225
+ walk(file, (node) => {
226
+ if (result === void 0) return false;
227
+ if (node.type === "Redirect" && !node.hdoc && (node.op === RedirOperator.Hdoc || node.op === RedirOperator.DashHdoc)) {
228
+ result = withoutTerminatorLine(result, node.word ? wordText(node.word, command, toIndex) : "", toIndex(node.end), node.op === RedirOperator.DashHdoc);
229
+ return result !== void 0;
230
+ }
231
+ if (node.type === "Redirect" && node.hdoc) {
232
+ const start = toIndex(node.hdoc.start);
233
+ const end = toIndex(node.hdoc.end);
234
+ result = result.slice(0, start) + " ".repeat(end - start) + result.slice(end);
235
+ }
236
+ return true;
237
+ });
238
+ return result;
239
+ }
240
+ function withoutTerminatorLine(source, delimiter, from, stripTabs) {
241
+ let start = source.indexOf("\n", from) + 1;
242
+ while (start > 0 && start < source.length) {
243
+ const end = source.indexOf("\n", start) === -1 ? source.length : source.indexOf("\n", start);
244
+ const line = source.slice(start, end);
245
+ if ((stripTabs ? line.replace(/^\t+/, "") : line) === delimiter) return source.slice(0, start) + " ".repeat(end - start) + source.slice(end);
246
+ start = end + 1;
247
+ }
248
+ }
249
+ function flattenStatement(stmt, outer, toIndex, leaves, negated = false) {
250
+ if (stmt.cmd?.type === "BinaryCmd") {
251
+ const operator = binaryOperator(stmt.cmd.op, toIndex(stmt.cmd.opPos.offset));
252
+ flattenStatement(stmt.cmd.x, operator, toIndex, leaves, negated || stmt.negated);
253
+ flattenStatement(stmt.cmd.y, outer, toIndex, leaves);
254
+ return;
255
+ }
256
+ leaves.push({
257
+ negated: negated || stmt.negated,
258
+ stmt,
259
+ ...outer ? { separator: outer } : {}
260
+ });
261
+ }
262
+ function statementSeparator(stmts, index, command, toIndex) {
263
+ const stmt = stmts[index];
264
+ if (stmt.semicolon.offset > 0) return {
265
+ kind: ";",
266
+ offset: toIndex(stmt.semicolon.offset),
267
+ length: 1
268
+ };
269
+ const next = stmts[index + 1];
270
+ if (!next) return void 0;
271
+ for (let offset = toIndex(stmt.end); offset < toIndex(next.start); offset++) if (command[offset] === "\n") return {
272
+ kind: "\n",
273
+ offset,
274
+ length: 1
275
+ };
276
+ }
277
+ function binaryOperator(op, offset) {
278
+ switch (op) {
279
+ case BinCmdOperator.Pipe: return {
280
+ kind: "|",
281
+ offset,
282
+ length: 1
283
+ };
284
+ case BinCmdOperator.PipeAll: return {
285
+ kind: "|",
286
+ offset,
287
+ length: 2
288
+ };
289
+ case BinCmdOperator.AndStmt: return {
290
+ kind: "&&",
291
+ offset,
292
+ length: 2
293
+ };
294
+ case BinCmdOperator.OrStmt: return {
295
+ kind: "||",
296
+ offset,
297
+ length: 2
298
+ };
299
+ default: return;
300
+ }
301
+ }
302
+ function createSourceIndex(source) {
303
+ const indexes = [0];
304
+ let byteOffset = 0;
305
+ for (let index = 0; index < source.length;) {
306
+ const codePoint = source.codePointAt(index);
307
+ byteOffset += utf8Length(codePoint);
308
+ index += codePoint > 65535 ? 2 : 1;
309
+ indexes[byteOffset] = index;
310
+ }
311
+ return (offset) => indexes[offset] ?? source.length;
312
+ }
313
+ function utf8Length(codePoint) {
314
+ if (codePoint <= 127) return 1;
315
+ if (codePoint <= 2047) return 2;
316
+ if (codePoint <= 65535) return 3;
317
+ return 4;
318
+ }
319
+ function stripLineContinuations(command) {
320
+ let result = "";
321
+ let commentContinuation = false;
322
+ let quote;
323
+ let ansiCQuoted = false;
324
+ let escaped = false;
325
+ let comment = false;
326
+ for (let index = 0; index < command.length; index++) {
327
+ const char = command[index];
328
+ if (comment) {
329
+ result += char;
330
+ if (char === "\n") {
331
+ comment = false;
332
+ if (command[index - 1] === "\\") commentContinuation = true;
333
+ }
334
+ continue;
335
+ }
336
+ if (escaped) {
337
+ if (char === "\n" && !ansiCQuoted) {
338
+ result = result.slice(0, -1);
339
+ escaped = false;
340
+ continue;
341
+ }
342
+ result += char;
343
+ escaped = false;
344
+ continue;
345
+ }
346
+ if (char === "\\" && (quote !== "'" || ansiCQuoted)) {
347
+ result += char;
348
+ escaped = true;
349
+ continue;
350
+ }
351
+ if (quote) {
352
+ if (char === quote) {
353
+ quote = void 0;
354
+ ansiCQuoted = false;
355
+ }
356
+ result += char;
357
+ continue;
358
+ }
359
+ if (char === "$" && command[index + 1] === "'") {
360
+ quote = "'";
361
+ ansiCQuoted = true;
362
+ result += "$'";
363
+ index += 1;
364
+ continue;
365
+ }
366
+ if (char === "#" && (index === 0 || /[\s;|&()]/.test(command[index - 1]))) {
367
+ comment = true;
368
+ result += char;
369
+ continue;
370
+ }
371
+ if (char === "'" || char === "\"") quote = char;
372
+ result += char;
373
+ }
374
+ return {
375
+ commentContinuation,
376
+ text: result
377
+ };
378
+ }
379
+ //#endregion
380
+ //#region src/command/analyze.ts
381
+ const defaultMaxInputBytes = 65536;
382
+ const defaultTimeoutMs = 100;
383
+ async function analyzeShellCommand(command, options = {}) {
384
+ const maxInputBytes = options.maxInputBytes ?? defaultMaxInputBytes;
385
+ if (new TextEncoder().encode(command).byteLength > maxInputBytes) return {
386
+ error: `Shell command exceeds ${maxInputBytes} bytes.`,
387
+ ok: false,
388
+ parser: "sh-syntax"
389
+ };
390
+ try {
391
+ return {
392
+ ...analyzeAst(await withTimeout(parseWithShSyntax(command), options.timeoutMs ?? defaultTimeoutMs), command),
393
+ ok: true,
394
+ parser: "sh-syntax"
395
+ };
396
+ } catch (error) {
397
+ return {
398
+ error: error instanceof Error ? error.message : String(error),
399
+ ok: false,
400
+ parser: "sh-syntax"
401
+ };
402
+ }
403
+ }
404
+ async function parseWithShSyntax(command) {
405
+ return parseShell(command, {
406
+ keepComments: true,
407
+ variant: LangVariant.LangBash
408
+ });
409
+ }
410
+ function analyzeAst(file, command) {
411
+ const commands = [];
412
+ const toIndex = createSourceIndex(command);
413
+ let hasCommandSubstitution = false;
414
+ let hasHeredocs = false;
415
+ let hasPipelines = false;
416
+ let hasRedirects = false;
417
+ walk(file, (node) => {
418
+ switch (node.type) {
419
+ case "CallExpr":
420
+ if (node.args.length) commands.push(wordText(node.args[0], command, toIndex));
421
+ break;
422
+ case "DeclClause":
423
+ if (node.variant) commands.push(node.variant.value);
424
+ break;
425
+ case "LetClause":
426
+ commands.push("let");
427
+ break;
428
+ case "CmdSubst":
429
+ hasCommandSubstitution = true;
430
+ break;
431
+ case "Redirect":
432
+ hasRedirects = true;
433
+ if (node.op === RedirOperator.Hdoc || node.op === RedirOperator.DashHdoc) hasHeredocs = true;
434
+ break;
435
+ case "BinaryCmd": if (node.op === BinCmdOperator.Pipe || node.op === BinCmdOperator.PipeAll || node.op === BinCmdOperator.OrStmt) hasPipelines = true;
436
+ }
437
+ return true;
438
+ });
439
+ return {
440
+ commands: [...new Set(commands.filter(Boolean))],
441
+ hasCommandSubstitution,
442
+ hasHeredocs,
443
+ hasPipelines,
444
+ hasRedirects
445
+ };
446
+ }
447
+ async function withTimeout(promise, timeoutMs) {
448
+ if (timeoutMs <= 0) throw shellErrorDiagnostics.SHELL_R0001({ message: `Shell analysis timed out after ${timeoutMs}ms.` });
449
+ let timeout;
450
+ try {
451
+ return await Promise.race([promise, new Promise((_, reject) => {
452
+ timeout = setTimeout(() => reject(shellErrorDiagnostics.SHELL_R0002({ message: `Shell analysis timed out after ${timeoutMs}ms.` })), timeoutMs);
453
+ })]);
454
+ } finally {
455
+ if (timeout) clearTimeout(timeout);
456
+ }
457
+ }
458
+ //#endregion
459
+ export { splitShellCommandSegments as n, shellErrorDiagnostics as r, analyzeShellCommand as t };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,8 @@
1
- import { a as ShellBoundary, c as ShellObservationEvent, d as ShellRuntimeExecOptions, f as ShellSession, i as ShellAnalyzeResult, l as ShellProcess, n as CreateShellSessionOptions, o as ShellExecutionProvider, p as ShellSessionPolicy, r as ShellAnalyzeOptions, s as ShellObservation, t as CreateShellRuntimeOptions, u as ShellRuntime } from "./types-CNRdehmi.js";
2
-
1
+ import { a as ShellBoundary, c as ShellObservationEvent, d as ShellRuntimeExecOptions, f as ShellSession, i as ShellAnalyzeResult, l as ShellProcess, n as CreateShellSessionOptions, o as ShellDriver, p as ShellSessionPolicy, r as ShellAnalyzeOptions, s as ShellObservation, t as CreateShellRuntimeOptions, u as ShellRuntime } from "./types-wPMXgnB0.js";
3
2
  //#region src/command/analyze.d.ts
4
- declare function analyzeShellCommand(command: string, options?: ShellAnalyzeOptions): Promise<ShellAnalyzeResult>;
3
+ export declare function analyzeShellCommand(command: string, options?: ShellAnalyzeOptions): Promise<ShellAnalyzeResult>;
5
4
  //#endregion
6
5
  //#region src/runtime/session.d.ts
7
- declare function createShellRuntime(options: CreateShellRuntimeOptions): ShellRuntime;
6
+ export declare function createShellRuntime(options: CreateShellRuntimeOptions): ShellRuntime;
8
7
  //#endregion
9
- export { type CreateShellRuntimeOptions, type CreateShellSessionOptions, type ShellAnalyzeOptions, type ShellAnalyzeResult, type ShellBoundary, type ShellExecutionProvider, type ShellObservation, type ShellObservationEvent, type ShellProcess, type ShellRuntime, type ShellRuntimeExecOptions, type ShellSession, type ShellSessionPolicy, analyzeShellCommand, createShellRuntime };
8
+ export type { CreateShellRuntimeOptions, CreateShellSessionOptions, ShellAnalyzeOptions, ShellAnalyzeResult, ShellBoundary, ShellDriver, ShellObservation, ShellObservationEvent, ShellProcess, ShellRuntime, ShellRuntimeExecOptions, ShellSession, ShellSessionPolicy };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as analyzeShellCommand } from "./analyze-Bu5Ueqph.js";
2
- import { t as createShellRuntime } from "./session-0OrrlmE9.js";
1
+ import { t as analyzeShellCommand } from "./analyze-kSc2pmy2.js";
2
+ import { t as createShellRuntime } from "./session-DjjZUIPE.js";
3
3
  export { analyzeShellCommand, createShellRuntime };
@@ -0,0 +1,37 @@
1
+ import { o as ShellDriver } from "./types-wPMXgnB0.js";
2
+ import { BashOptions } from "just-bash/browser";
3
+ import { IFileSystem } from "just-bash";
4
+ //#region src/providers/just-bash.d.ts
5
+ interface JustBashFileSystem extends IFileSystem {
6
+ readonly writeFs: boolean;
7
+ }
8
+ type JustBashExecutionLimits = NonNullable<BashOptions["executionLimits"]>;
9
+ type JustBashExecutionLimitProfile = NonNullable<BashOptions["executionLimitProfile"]>;
10
+ interface JustBashDriverOptions {
11
+ commands?: string[];
12
+ cwd?: string;
13
+ /**
14
+ * Limits for commands evaluated by Just Bash, including loops, command count, call depth, and output size.
15
+ * Also applies to controlled curl output and command deadlines; deadlines abort the Source request signal.
16
+ */
17
+ executionLimits?: JustBashExecutionLimits;
18
+ /** Just Bash preset applied before `executionLimits` (default: `normal`). */
19
+ executionLimitProfile?: JustBashExecutionLimitProfile;
20
+ fs: JustBashFileSystem;
21
+ networkGrants?: ShellNetworkGrantExecutor;
22
+ }
23
+ interface ShellNetworkGrantExecutor {
24
+ executeSourceRequest(input: ShellNetworkRequest): Promise<ShellNetworkRequestResult>;
25
+ }
26
+ interface ShellNetworkRequest {
27
+ body?: unknown;
28
+ method: "GET" | "HEAD" | "POST";
29
+ signal?: AbortSignal;
30
+ url: string;
31
+ }
32
+ interface ShellNetworkRequestResult {
33
+ content: string | Uint8Array;
34
+ }
35
+ declare function createJustBashDriver(options: JustBashDriverOptions): ShellDriver;
36
+ //#endregion
37
+ export { ShellNetworkGrantExecutor as a, createJustBashDriver as c, JustBashFileSystem as i, JustBashExecutionLimitProfile as n, ShellNetworkRequest as o, JustBashExecutionLimits as r, ShellNetworkRequestResult as s, JustBashDriverOptions as t };
@@ -1,2 +1,2 @@
1
- import { a as ShellNetworkRequestResult, i as ShellNetworkRequest, n as JustBashProviderOptions, o as createJustBashProvider, r as ShellNetworkGrantExecutor, t as JustBashFileSystem } from "../just-bash-D84udCFy.js";
2
- export { JustBashFileSystem, JustBashProviderOptions, ShellNetworkGrantExecutor, ShellNetworkRequest, ShellNetworkRequestResult, createJustBashProvider };
1
+ import { a as ShellNetworkGrantExecutor, c as createJustBashDriver, i as JustBashFileSystem, n as JustBashExecutionLimitProfile, o as ShellNetworkRequest, r as JustBashExecutionLimits, s as ShellNetworkRequestResult, t as JustBashDriverOptions } from "../just-bash-CHpGR1dZ.js";
2
+ export { JustBashDriverOptions, JustBashExecutionLimitProfile, JustBashExecutionLimits, JustBashFileSystem, ShellNetworkGrantExecutor, ShellNetworkRequest, ShellNetworkRequestResult, createJustBashDriver };