@vite-hub/shell 0.0.4 → 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/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.
@@ -66,13 +66,36 @@ export async function searchDocs() {
66
66
 
67
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.
68
68
 
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
+
69
71
  ## Providers 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
74
  - A custom `ShellExecutionProvider` declares its boundary and implements execution for another host.
74
75
 
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.
76
+ Custom providers can return Shell Processes as class instances. Sessions read the process ID, command, and working directory from the provider 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 provider 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 provider's execution model and resource controls. The Just Bash provider 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 providers 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 provider copies the command list at creation. Later changes to the supplied list do not change its permissions or network boundary.
91
+
92
+ 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.
93
+
94
+ Workspace filesystem adapters preserve binary output from redirection and `tee`. Their read, write, and append methods honor Just Bash encoding options.
95
+
96
+ Just Bash defaults to `/workspace`. A provider `cwd` changes that default, and an `exec` `cwd` takes precedence. The provider reports the selected directory in its observations. Set `cwd` for a custom filesystem with another root.
97
+
98
+ Appending creates an absent Workspace file. A read failure for an existing file fails the append before changing its content.
76
99
 
77
100
  ## Use with Agents
78
101
 
@@ -80,4 +103,4 @@ Shell policy can bound calls, processes, output size, and timeouts. A declared b
80
103
 
81
104
  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.
82
105
 
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).
106
+ 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,247 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const shellErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ SHELL_R0001: dynamicError,
8
+ SHELL_R0002: dynamicError,
9
+ SHELL_R0003: dynamicError,
10
+ SHELL_R0004: dynamicError,
11
+ SHELL_R0005: dynamicError,
12
+ SHELL_R0006: dynamicError,
13
+ SHELL_R0007: dynamicError,
14
+ SHELL_R0008: dynamicError,
15
+ SHELL_R0009: dynamicError,
16
+ SHELL_R0010: dynamicError,
17
+ SHELL_R0011: dynamicError,
18
+ SHELL_R0012: dynamicError,
19
+ SHELL_R0013: dynamicError,
20
+ SHELL_R0014: dynamicError,
21
+ SHELL_R0015: dynamicError,
22
+ SHELL_R0016: dynamicError,
23
+ SHELL_R0017: dynamicError,
24
+ SHELL_R0018: dynamicError,
25
+ SHELL_R0019: dynamicError,
26
+ SHELL_R0020: dynamicError,
27
+ SHELL_R0021: dynamicError,
28
+ SHELL_R0022: dynamicError,
29
+ SHELL_R0023: dynamicError
30
+ }
31
+ });
32
+ //#endregion
33
+ //#region src/command/parse.ts
34
+ function parseShellCommand(command, mode = "execution") {
35
+ const words = [];
36
+ let current = "";
37
+ let wordStarted = false;
38
+ let quote;
39
+ let escaped = false;
40
+ for (let index = 0; index < command.length; index += 1) {
41
+ const char = command[index];
42
+ if (escaped) {
43
+ if (char !== "\n") {
44
+ current += char;
45
+ wordStarted = true;
46
+ }
47
+ escaped = false;
48
+ continue;
49
+ }
50
+ if (quote) {
51
+ if (char === quote) quote = void 0;
52
+ else if (char === "\\" && quote === "\"" && /[\\$`"\n]/.test(command[index + 1] ?? "")) escaped = true;
53
+ else current += char;
54
+ wordStarted = true;
55
+ continue;
56
+ }
57
+ if (char === "\\") {
58
+ escaped = true;
59
+ continue;
60
+ }
61
+ if (char === "'" || char === "\"") {
62
+ quote = char;
63
+ wordStarted = true;
64
+ continue;
65
+ }
66
+ if (/\s/.test(char)) {
67
+ if (wordStarted) {
68
+ words.push(current);
69
+ current = "";
70
+ wordStarted = false;
71
+ }
72
+ continue;
73
+ }
74
+ current += char;
75
+ wordStarted = true;
76
+ }
77
+ if (mode === "execution") {
78
+ if (escaped) {
79
+ current += "\\";
80
+ wordStarted = true;
81
+ }
82
+ if (quote) throw shellErrorDiagnostics.SHELL_R0003({ message: "unterminated quote" });
83
+ }
84
+ if (wordStarted) words.push(current);
85
+ return words;
86
+ }
87
+ function splitShellCommandSegments(command) {
88
+ const segments = [];
89
+ let current = "";
90
+ let quote;
91
+ let ansiCQuoted = false;
92
+ let escaped = false;
93
+ let comment = false;
94
+ let wordBoundary = true;
95
+ let followsPipe = false;
96
+ for (let index = 0; index < command.length; index++) {
97
+ const char = command[index];
98
+ if (comment) {
99
+ if (char !== "\n") continue;
100
+ comment = false;
101
+ }
102
+ if (escaped) {
103
+ if (char === "\n" && !ansiCQuoted) {
104
+ current = current.slice(0, -1);
105
+ escaped = false;
106
+ continue;
107
+ }
108
+ current += char;
109
+ wordBoundary = false;
110
+ escaped = false;
111
+ continue;
112
+ }
113
+ if (char === "\\" && (quote !== "'" || ansiCQuoted)) {
114
+ current += char;
115
+ escaped = true;
116
+ continue;
117
+ }
118
+ if (quote) {
119
+ if (char === quote) {
120
+ quote = void 0;
121
+ ansiCQuoted = false;
122
+ }
123
+ current += char;
124
+ wordBoundary = false;
125
+ continue;
126
+ }
127
+ if (char === "$" && command[index + 1] === "'") {
128
+ quote = "'";
129
+ ansiCQuoted = true;
130
+ current += "$'";
131
+ wordBoundary = false;
132
+ index += 1;
133
+ continue;
134
+ }
135
+ if (char === "'" || char === "\"") {
136
+ quote = char;
137
+ current += char;
138
+ wordBoundary = false;
139
+ continue;
140
+ }
141
+ if (char === "#" && wordBoundary) {
142
+ comment = true;
143
+ continue;
144
+ }
145
+ const next = command[index + 1];
146
+ if (char === "&" && next === "&") {
147
+ segments.push({
148
+ command: current,
149
+ followsPipe,
150
+ separatorAfter: "&&"
151
+ });
152
+ current = "";
153
+ followsPipe = false;
154
+ wordBoundary = true;
155
+ index += 1;
156
+ continue;
157
+ }
158
+ if (char === "|" && next === "|") {
159
+ segments.push({
160
+ command: current,
161
+ followsPipe,
162
+ separatorAfter: "||"
163
+ });
164
+ current = "";
165
+ followsPipe = false;
166
+ wordBoundary = true;
167
+ index += 1;
168
+ continue;
169
+ }
170
+ if (char === "|" || char === ";" || char === "\n") {
171
+ segments.push({
172
+ command: current,
173
+ followsPipe,
174
+ separatorAfter: char
175
+ });
176
+ current = "";
177
+ followsPipe = char === "|";
178
+ wordBoundary = true;
179
+ continue;
180
+ }
181
+ current += char;
182
+ wordBoundary = /[\s()<>]/.test(char) || char === "&";
183
+ }
184
+ segments.push({
185
+ command: current,
186
+ followsPipe
187
+ });
188
+ return segments;
189
+ }
190
+ //#endregion
191
+ //#region src/command/analyze.ts
192
+ const defaultMaxInputBytes = 65536;
193
+ const defaultTimeoutMs = 100;
194
+ async function analyzeShellCommand(command, options = {}) {
195
+ const maxInputBytes = options.maxInputBytes ?? defaultMaxInputBytes;
196
+ if (new TextEncoder().encode(command).byteLength > maxInputBytes) return {
197
+ error: `Shell command exceeds ${maxInputBytes} bytes.`,
198
+ ok: false,
199
+ parser: "sh-syntax"
200
+ };
201
+ const segments = splitShellCommandSegments(command);
202
+ const commands = [...new Set(segments.map((segment) => firstCommandWord(segment.command)).filter((name) => name !== void 0))];
203
+ try {
204
+ await withTimeout(parseWithShSyntax(command), options.timeoutMs ?? defaultTimeoutMs);
205
+ } catch (error) {
206
+ return {
207
+ commands,
208
+ error: error instanceof Error ? error.message : String(error),
209
+ ok: false,
210
+ parser: "sh-syntax"
211
+ };
212
+ }
213
+ return {
214
+ commands,
215
+ hasCommandSubstitution: /(?:\$\(|`)/.test(command),
216
+ hasHeredocs: /<<-?/.test(command),
217
+ hasPipelines: segments.some((segment) => segment.separatorAfter === "|" || segment.separatorAfter === "||"),
218
+ hasRedirects: /(?:^|[^<])(?:>>?|<)/.test(command),
219
+ ok: true,
220
+ parser: "sh-syntax"
221
+ };
222
+ }
223
+ async function parseWithShSyntax(command) {
224
+ const { parse, LangVariant } = await import("sh-syntax");
225
+ await parse(command, { variant: LangVariant.LangBash });
226
+ }
227
+ async function withTimeout(promise, timeoutMs) {
228
+ if (timeoutMs <= 0) throw shellErrorDiagnostics.SHELL_R0001({ message: `Shell analysis timed out after ${timeoutMs}ms.` });
229
+ let timeout;
230
+ try {
231
+ return await Promise.race([promise, new Promise((_, reject) => {
232
+ timeout = setTimeout(() => reject(shellErrorDiagnostics.SHELL_R0002({ message: `Shell analysis timed out after ${timeoutMs}ms.` })), timeoutMs);
233
+ })]);
234
+ } finally {
235
+ if (timeout) clearTimeout(timeout);
236
+ }
237
+ }
238
+ function firstCommandWord(segment) {
239
+ const words = segment.trim().match(/[^\s]+/g) || [];
240
+ for (const word of words) {
241
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) continue;
242
+ if (/^\d*(?:>>?|<<?-?|<&|>&)/.test(word)) continue;
243
+ return word.replace(/^command$/, "") || void 0;
244
+ }
245
+ }
246
+ //#endregion
247
+ export { shellErrorDiagnostics as i, parseShellCommand as n, splitShellCommandSegments 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 ShellExecutionProvider, p as ShellSessionPolicy, r as ShellAnalyzeOptions, s as ShellObservation, t as CreateShellRuntimeOptions, u as ShellRuntime } from "./types-2uHfTVHi.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, ShellExecutionProvider, 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-BXwz20IH.js";
2
+ import { t as createShellRuntime } from "./session-CIy2VLp9.js";
3
3
  export { analyzeShellCommand, createShellRuntime };
@@ -1,6 +1,5 @@
1
- import { o as ShellExecutionProvider } from "./types-CNRdehmi.js";
1
+ import { o as ShellExecutionProvider } from "./types-2uHfTVHi.js";
2
2
  import { IFileSystem } from "just-bash";
3
-
4
3
  //#region src/providers/just-bash.d.ts
5
4
  interface JustBashFileSystem extends IFileSystem {
6
5
  readonly writeFs: boolean;
@@ -17,6 +16,7 @@ interface ShellNetworkGrantExecutor {
17
16
  interface ShellNetworkRequest {
18
17
  body?: unknown;
19
18
  method: "GET" | "HEAD" | "POST";
19
+ signal?: AbortSignal;
20
20
  url: string;
21
21
  }
22
22
  interface ShellNetworkRequestResult {
@@ -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";
1
+ import { a as ShellNetworkRequestResult, i as ShellNetworkRequest, n as JustBashProviderOptions, o as createJustBashProvider, r as ShellNetworkGrantExecutor, t as JustBashFileSystem } from "../just-bash-DAyZQWLK.js";
2
2
  export { JustBashFileSystem, JustBashProviderOptions, ShellNetworkGrantExecutor, ShellNetworkRequest, ShellNetworkRequestResult, createJustBashProvider };
@@ -1,61 +1,84 @@
1
- import { t as analyzeShellCommand } from "../analyze-Bu5Ueqph.js";
2
- import { t as parseShellCommand } from "../parse-D9VT4P6N.js";
1
+ import { i as shellErrorDiagnostics, n as parseShellCommand, t as analyzeShellCommand } from "../analyze-BXwz20IH.js";
3
2
  //#region src/providers/just-bash.ts
4
3
  function createJustBashProvider(options) {
4
+ const commands = options.commands?.slice();
5
+ const networkGrants = options.networkGrants;
6
+ const boundary = {
7
+ cwd: true,
8
+ env: true,
9
+ filesystem: {
10
+ mountPoint: "/workspace",
11
+ writable: options.fs.writeFs
12
+ },
13
+ network: Boolean(networkGrants) && (!commands || commands.includes("curl")),
14
+ processes: {
15
+ background: false,
16
+ interactive: false
17
+ },
18
+ streaming: false,
19
+ timeout: {
20
+ enforcedBy: "provider",
21
+ supported: true
22
+ },
23
+ execution: {
24
+ isolation: "in_process",
25
+ model: "virtual"
26
+ },
27
+ resources: { output: {
28
+ enforcedBy: "unsupported",
29
+ unit: "characters"
30
+ } }
31
+ };
5
32
  return {
6
33
  analyze: analyzeShellCommand,
7
- boundary: {
8
- cwd: true,
9
- env: true,
10
- filesystem: {
11
- mountPoint: "/workspace",
12
- writable: options.fs.writeFs
13
- },
14
- network: Boolean(options.networkGrants),
15
- processes: {
16
- background: false,
17
- interactive: false
18
- },
19
- streaming: false,
20
- timeout: {
21
- enforcedBy: "provider",
22
- supported: true
23
- }
24
- },
34
+ boundary,
25
35
  async exec(command, execOptions = {}) {
26
- const result = await withProviderTimeout(command, execOptions, async () => {
36
+ const cwd = execOptions.cwd ?? options.cwd ?? "/workspace";
37
+ const result = await withProviderTimeout(command, {
38
+ ...execOptions,
39
+ cwd
40
+ }, async (runOptions) => {
27
41
  const curlResult = await runControlledCurlCommand(command, {
28
- cwd: execOptions.cwd || options.cwd,
29
- networkGrants: options.networkGrants
42
+ commands,
43
+ cwd,
44
+ networkGrants,
45
+ maxOutputLength: runOptions.maxOutputLength,
46
+ signal: runOptions.signal
30
47
  });
31
48
  if (curlResult) return curlResult;
32
49
  const { Bash } = await import("just-bash/browser");
33
- const bash = new Bash({
34
- commands: options.commands,
35
- cwd: options.cwd,
50
+ return await new Bash({
51
+ commands,
52
+ cwd,
36
53
  fs: options.fs
37
- });
38
- const signal = typeof execOptions.timeout === "number" ? AbortSignal.timeout(execOptions.timeout) : void 0;
39
- return await bash.exec(command, {
40
- cwd: execOptions.cwd,
54
+ }).exec(command, {
55
+ cwd,
41
56
  env: execOptions.env,
42
- signal
43
- }).then((result) => ({
44
- command,
45
- cwd: execOptions.cwd,
46
- event: "command_finished",
47
- exitCode: result.exitCode,
48
- stderr: result.stderr,
49
- stdout: result.stdout
50
- }));
57
+ signal: runOptions.signal
58
+ }).then((result) => {
59
+ const stdout = boundOutput(result.stdout, runOptions.maxOutputLength);
60
+ const stderr = boundOutput(result.stderr, runOptions.maxOutputLength);
61
+ return {
62
+ command,
63
+ cwd,
64
+ event: "command_finished",
65
+ exitCode: result.exitCode,
66
+ maxOutputLength: runOptions.maxOutputLength,
67
+ outputTruncated: stdout.truncated || stderr.truncated,
68
+ stderr: stderr.content,
69
+ stdout: stdout.content
70
+ };
71
+ });
51
72
  });
52
73
  execOptions.onStdout?.(result.stdout);
53
74
  execOptions.onStderr?.(result.stderr);
54
75
  return {
55
76
  command: result.command ?? command,
56
- cwd: result.cwd ?? execOptions.cwd,
77
+ cwd: result.cwd ?? cwd,
57
78
  event: result.timedOut ? "command_timed_out" : result.event,
58
79
  exitCode: result.exitCode,
80
+ maxOutputLength: result.maxOutputLength,
81
+ outputTruncated: result.outputTruncated,
59
82
  stderr: result.stderr,
60
83
  stdout: result.stdout,
61
84
  timedOut: result.timedOut
@@ -65,24 +88,37 @@ function createJustBashProvider(options) {
65
88
  }
66
89
  async function runControlledCurlCommand(command, options) {
67
90
  if (!mentionsCurlCommand(command)) return void 0;
91
+ options.signal?.throwIfAborted();
92
+ if (options.commands && !options.commands.includes("curl")) return policyDeniedCurl(command, options.cwd, "curl is not in the permitted commands for this shell.");
68
93
  const [parseError, parsed] = parseControlledCurlCommand(command);
69
94
  if (parseError) return policyDeniedCurl(command, options.cwd, parseError.message);
70
95
  if (!options.networkGrants) return policyDeniedCurl(command, options.cwd, "No API-backed Source request descriptors are visible in this workspace.");
71
96
  try {
72
- const result = await options.networkGrants.executeSourceRequest({
97
+ const request = {
73
98
  body: parsed.body,
74
99
  method: parsed.method,
100
+ signal: options.signal,
75
101
  url: parsed.url
102
+ };
103
+ if (options.signal) Object.defineProperty(request, "signal", {
104
+ configurable: true,
105
+ enumerable: false,
106
+ value: options.signal
76
107
  });
108
+ const result = await options.networkGrants.executeSourceRequest(request);
109
+ const bounded = boundOutput(typeof result.content === "string" ? result.content : new TextDecoder().decode(result.content), options.maxOutputLength);
77
110
  return {
78
111
  command,
79
112
  cwd: options.cwd,
80
113
  event: "command_finished",
81
114
  exitCode: 0,
82
115
  stderr: "",
83
- stdout: typeof result.content === "string" ? result.content : new TextDecoder().decode(result.content)
116
+ maxOutputLength: options.maxOutputLength,
117
+ outputTruncated: bounded.truncated,
118
+ stdout: bounded.content
84
119
  };
85
120
  } catch (error) {
121
+ if (options.signal?.aborted) throw options.signal.reason;
86
122
  const message = error instanceof Error ? error.message : String(error);
87
123
  const httpFailure = message.includes("HTTP request failed");
88
124
  return {
@@ -96,7 +132,7 @@ async function runControlledCurlCommand(command, options) {
96
132
  }
97
133
  }
98
134
  function parseFailure(message) {
99
- return [new Error(message), void 0];
135
+ return [shellErrorDiagnostics.SHELL_R0004({ message }), void 0];
100
136
  }
101
137
  function parseControlledCurlCommand(command) {
102
138
  if (hasUnsupportedCurlShellSyntax(command)) return parseFailure("Controlled curl must be a single command without pipes, redirects, chaining, command substitution, or heredocs.");
@@ -104,7 +140,7 @@ function parseControlledCurlCommand(command) {
104
140
  try {
105
141
  words = parseShellCommand(command);
106
142
  } catch (error) {
107
- return [error instanceof Error ? error : new Error(String(error)), void 0];
143
+ return [error instanceof Error ? error : shellErrorDiagnostics.SHELL_R0005({ message: String(error) }), void 0];
108
144
  }
109
145
  if (words[0] !== "curl") return parseFailure("Controlled curl command must start with curl.");
110
146
  let body;
@@ -154,7 +190,7 @@ function parseControlledCurlCommand(command) {
154
190
  }
155
191
  if (word === "-d" || word === "--data" || word === "--data-raw" || word === "--data-binary") {
156
192
  const value = words[++index];
157
- if (!value) return parseFailure(`${word} requires a body.`);
193
+ if (value === void 0) return parseFailure(`${word} requires a body.`);
158
194
  body = parseCurlDataBody(value);
159
195
  method ??= "POST";
160
196
  continue;
@@ -174,7 +210,7 @@ function parseControlledCurlCommand(command) {
174
210
  url = setCurlUrl(url, word);
175
211
  }
176
212
  } catch (error) {
177
- return [error instanceof Error ? error : new Error(String(error)), void 0];
213
+ return [error instanceof Error ? error : shellErrorDiagnostics.SHELL_R0006({ message: String(error) }), void 0];
178
214
  }
179
215
  if (!url) return parseFailure("Controlled curl requires a URL.");
180
216
  try {
@@ -241,7 +277,7 @@ function parseJsonCurlBody(value) {
241
277
  }
242
278
  }
243
279
  function setCurlUrl(current, next) {
244
- if (current) throw new Error("Controlled curl accepts exactly one URL.");
280
+ if (current) throw shellErrorDiagnostics.SHELL_R0007({ message: "Controlled curl accepts exactly one URL." });
245
281
  return next;
246
282
  }
247
283
  function policyDeniedCurl(command, cwd, message) {
@@ -255,23 +291,60 @@ function policyDeniedCurl(command, cwd, message) {
255
291
  };
256
292
  }
257
293
  async function withProviderTimeout(command, options, run) {
258
- if (typeof options.timeout !== "number") return await run();
294
+ options.signal?.throwIfAborted();
295
+ const controller = new AbortController();
296
+ const abortListener = options.signal ? () => controller.abort(options.signal?.reason) : void 0;
297
+ if (abortListener) options.signal?.addEventListener("abort", abortListener, { once: true });
298
+ const runOptions = options.signal || typeof options.timeout === "number" ? {
299
+ ...options,
300
+ signal: controller.signal
301
+ } : options;
259
302
  let timeout;
303
+ let onAbort;
304
+ const aborted = options.signal ? new Promise((_resolve, reject) => {
305
+ const handleAbort = () => reject(options.signal?.reason);
306
+ onAbort = handleAbort;
307
+ options.signal?.addEventListener("abort", handleAbort, { once: true });
308
+ if (options.signal?.aborted) handleAbort();
309
+ }) : void 0;
260
310
  try {
261
- return await Promise.race([run(), new Promise((resolve) => {
262
- timeout = setTimeout(() => resolve({
263
- command,
264
- cwd: options.cwd,
265
- event: "command_timed_out",
266
- exitCode: null,
267
- stderr: `[vitehub] Workspace shell command timed out after ${options.timeout}ms.`,
268
- stdout: "",
269
- timedOut: true
270
- }), options.timeout);
271
- })]);
311
+ const running = run(runOptions);
312
+ if (typeof options.timeout !== "number" && !aborted) return await running;
313
+ const races = [running];
314
+ if (aborted) races.push(aborted);
315
+ if (typeof options.timeout === "number") races.push(new Promise((resolve) => {
316
+ timeout = setTimeout(() => {
317
+ resolve({
318
+ command,
319
+ cwd: options.cwd,
320
+ event: "command_timed_out",
321
+ exitCode: null,
322
+ maxOutputLength: options.maxOutputLength,
323
+ outputTruncated: false,
324
+ stderr: `[vitehub] Workspace shell command timed out after ${options.timeout}ms.`,
325
+ stdout: "",
326
+ timedOut: true
327
+ });
328
+ controller.abort(/* @__PURE__ */ new Error("Shell command timed out."));
329
+ }, options.timeout);
330
+ }));
331
+ return await Promise.race(races);
272
332
  } finally {
273
333
  if (timeout) clearTimeout(timeout);
334
+ if (onAbort) options.signal?.removeEventListener("abort", onAbort);
335
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener);
274
336
  }
275
337
  }
338
+ function boundOutput(content, maxLength) {
339
+ const limit = maxLength === void 0 ? void 0 : maxLength === Number.POSITIVE_INFINITY ? void 0 : Number.isFinite(maxLength) ? Math.max(0, Math.floor(maxLength)) : 0;
340
+ if (limit === void 0 || content.length <= limit) return {
341
+ content,
342
+ truncated: false
343
+ };
344
+ return {
345
+ content: `${content.slice(0, limit)}\n[output truncated to ${limit} characters]\n`,
346
+ truncated: true
347
+ };
348
+ }
276
349
  //#endregion
277
350
  export { createJustBashProvider };