@vite-hub/shell 0.0.1 → 0.0.3

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/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
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-BNtJGjIv.js";
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
2
 
3
3
  //#region src/command/analyze.d.ts
4
4
  declare function analyzeShellCommand(command: string, options?: ShellAnalyzeOptions): Promise<ShellAnalyzeResult>;
@@ -6,4 +6,4 @@ declare function analyzeShellCommand(command: string, options?: ShellAnalyzeOpti
6
6
  //#region src/runtime/session.d.ts
7
7
  declare function createShellRuntime(options: CreateShellRuntimeOptions): ShellRuntime;
8
8
  //#endregion
9
- export { CreateShellRuntimeOptions, CreateShellSessionOptions, ShellAnalyzeOptions, ShellAnalyzeResult, ShellBoundary, ShellExecutionProvider, ShellObservation, ShellObservationEvent, ShellProcess, ShellRuntime, ShellRuntimeExecOptions, ShellSession, ShellSessionPolicy, analyzeShellCommand, createShellRuntime };
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 };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as analyzeShellCommand } from "./analyze-BhMXNtZg.js";
2
- import { t as createShellRuntime } from "./session-Qzhl3bqv.js";
1
+ import { t as analyzeShellCommand } from "./analyze-Bu5Ueqph.js";
2
+ import { t as createShellRuntime } from "./session-0OrrlmE9.js";
3
3
  export { analyzeShellCommand, createShellRuntime };
@@ -0,0 +1,27 @@
1
+ import { o as ShellExecutionProvider } from "./types-CNRdehmi.js";
2
+ import { IFileSystem } from "just-bash";
3
+
4
+ //#region src/providers/just-bash.d.ts
5
+ interface JustBashFileSystem extends IFileSystem {
6
+ readonly writeFs: boolean;
7
+ }
8
+ interface JustBashProviderOptions {
9
+ commands?: string[];
10
+ cwd?: string;
11
+ fs: JustBashFileSystem;
12
+ networkGrants?: ShellNetworkGrantExecutor;
13
+ }
14
+ interface ShellNetworkGrantExecutor {
15
+ executeSourceRequest(input: ShellNetworkRequest): Promise<ShellNetworkRequestResult>;
16
+ }
17
+ interface ShellNetworkRequest {
18
+ body?: unknown;
19
+ method: "GET" | "HEAD" | "POST";
20
+ url: string;
21
+ }
22
+ interface ShellNetworkRequestResult {
23
+ content: string | Uint8Array;
24
+ }
25
+ declare function createJustBashProvider(options: JustBashProviderOptions): ShellExecutionProvider;
26
+ //#endregion
27
+ export { ShellNetworkRequestResult as a, ShellNetworkRequest as i, JustBashProviderOptions as n, createJustBashProvider as o, ShellNetworkGrantExecutor as r, JustBashFileSystem as t };
@@ -0,0 +1,41 @@
1
+ //#region src/command/parse.ts
2
+ function parseShellCommand(command) {
3
+ const words = [];
4
+ let current = "";
5
+ let quote;
6
+ let escaped = false;
7
+ for (const char of command) {
8
+ if (escaped) {
9
+ current += char;
10
+ escaped = false;
11
+ continue;
12
+ }
13
+ if (char === "\\") {
14
+ escaped = true;
15
+ continue;
16
+ }
17
+ if (quote) {
18
+ if (char === quote) quote = void 0;
19
+ else current += char;
20
+ continue;
21
+ }
22
+ if (char === "'" || char === "\"") {
23
+ quote = char;
24
+ continue;
25
+ }
26
+ if (/\s/.test(char)) {
27
+ if (current) {
28
+ words.push(current);
29
+ current = "";
30
+ }
31
+ continue;
32
+ }
33
+ current += char;
34
+ }
35
+ if (escaped) current += "\\";
36
+ if (quote) throw new Error("unterminated quote");
37
+ if (current) words.push(current);
38
+ return words;
39
+ }
40
+ //#endregion
41
+ export { parseShellCommand as t };
@@ -1,4 +1,4 @@
1
- import { o as ShellExecutionProvider } from "../types-BNtJGjIv.js";
1
+ import { o as ShellExecutionProvider } from "../types-CNRdehmi.js";
2
2
 
3
3
  //#region src/providers/cloudflare.d.ts
4
4
  interface CloudflareShellClient {
@@ -1,44 +1,5 @@
1
- import { t as analyzeShellCommand } from "../analyze-BhMXNtZg.js";
2
- //#region src/command/parse.ts
3
- function parseShellCommand(command) {
4
- const words = [];
5
- let current = "";
6
- let quote;
7
- let escaped = false;
8
- for (const char of command) {
9
- if (escaped) {
10
- current += char;
11
- escaped = false;
12
- continue;
13
- }
14
- if (char === "\\") {
15
- escaped = true;
16
- continue;
17
- }
18
- if (quote) {
19
- if (char === quote) quote = void 0;
20
- else current += char;
21
- continue;
22
- }
23
- if (char === "'" || char === "\"") {
24
- quote = char;
25
- continue;
26
- }
27
- if (/\s/.test(char)) {
28
- if (current) {
29
- words.push(current);
30
- current = "";
31
- }
32
- continue;
33
- }
34
- current += char;
35
- }
36
- if (escaped) current += "\\";
37
- if (quote) throw new Error("unterminated quote");
38
- if (current) words.push(current);
39
- return words;
40
- }
41
- //#endregion
1
+ import { t as analyzeShellCommand } from "../analyze-Bu5Ueqph.js";
2
+ import { t as parseShellCommand } from "../parse-D9VT4P6N.js";
42
3
  //#region src/providers/cloudflare.ts
43
4
  function createCloudflareShellProvider(options) {
44
5
  return {
@@ -1,15 +1,2 @@
1
- import { o as ShellExecutionProvider } from "../types-BNtJGjIv.js";
2
- import { IFileSystem } from "just-bash";
3
-
4
- //#region src/providers/just-bash.d.ts
5
- interface JustBashFileSystem extends IFileSystem {
6
- readonly writeFs: boolean;
7
- }
8
- interface JustBashProviderOptions {
9
- commands?: string[];
10
- cwd?: string;
11
- fs: JustBashFileSystem;
12
- }
13
- declare function createJustBashProvider(options: JustBashProviderOptions): ShellExecutionProvider;
14
- //#endregion
15
- export { JustBashFileSystem, JustBashProviderOptions, createJustBashProvider };
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,4 +1,5 @@
1
- import { t as analyzeShellCommand } from "../analyze-BhMXNtZg.js";
1
+ import { t as analyzeShellCommand } from "../analyze-Bu5Ueqph.js";
2
+ import { t as parseShellCommand } from "../parse-D9VT4P6N.js";
2
3
  //#region src/providers/just-bash.ts
3
4
  function createJustBashProvider(options) {
4
5
  return {
@@ -10,7 +11,7 @@ function createJustBashProvider(options) {
10
11
  mountPoint: "/workspace",
11
12
  writable: options.fs.writeFs
12
13
  },
13
- network: false,
14
+ network: Boolean(options.networkGrants),
14
15
  processes: {
15
16
  background: false,
16
17
  interactive: false
@@ -23,6 +24,11 @@ function createJustBashProvider(options) {
23
24
  },
24
25
  async exec(command, execOptions = {}) {
25
26
  const result = await withProviderTimeout(command, execOptions, async () => {
27
+ const curlResult = await runControlledCurlCommand(command, {
28
+ cwd: execOptions.cwd || options.cwd,
29
+ networkGrants: options.networkGrants
30
+ });
31
+ if (curlResult) return curlResult;
26
32
  const { Bash } = await import("just-bash/browser");
27
33
  const bash = new Bash({
28
34
  commands: options.commands,
@@ -34,29 +40,229 @@ function createJustBashProvider(options) {
34
40
  cwd: execOptions.cwd,
35
41
  env: execOptions.env,
36
42
  signal
37
- });
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
+ }));
38
51
  });
39
- const timedOut = "timedOut" in result && result.timedOut === true;
40
52
  execOptions.onStdout?.(result.stdout);
41
53
  execOptions.onStderr?.(result.stderr);
42
54
  return {
43
- command,
44
- cwd: execOptions.cwd,
45
- event: timedOut ? "command_timed_out" : "command_finished",
55
+ command: result.command ?? command,
56
+ cwd: result.cwd ?? execOptions.cwd,
57
+ event: result.timedOut ? "command_timed_out" : result.event,
46
58
  exitCode: result.exitCode,
47
59
  stderr: result.stderr,
48
60
  stdout: result.stdout,
49
- timedOut
61
+ timedOut: result.timedOut
50
62
  };
51
63
  }
52
64
  };
53
65
  }
66
+ async function runControlledCurlCommand(command, options) {
67
+ if (!mentionsCurlCommand(command)) return void 0;
68
+ const [parseError, parsed] = parseControlledCurlCommand(command);
69
+ if (parseError) return policyDeniedCurl(command, options.cwd, parseError.message);
70
+ if (!options.networkGrants) return policyDeniedCurl(command, options.cwd, "No API-backed Source request descriptors are visible in this workspace.");
71
+ try {
72
+ const result = await options.networkGrants.executeSourceRequest({
73
+ body: parsed.body,
74
+ method: parsed.method,
75
+ url: parsed.url
76
+ });
77
+ return {
78
+ command,
79
+ cwd: options.cwd,
80
+ event: "command_finished",
81
+ exitCode: 0,
82
+ stderr: "",
83
+ stdout: typeof result.content === "string" ? result.content : new TextDecoder().decode(result.content)
84
+ };
85
+ } catch (error) {
86
+ const message = error instanceof Error ? error.message : String(error);
87
+ const httpFailure = message.includes("HTTP request failed");
88
+ return {
89
+ command,
90
+ cwd: options.cwd,
91
+ event: httpFailure ? "command_finished" : "policy_denied",
92
+ exitCode: httpFailure ? 22 : 126,
93
+ stderr: `${message}\n`,
94
+ stdout: ""
95
+ };
96
+ }
97
+ }
98
+ function parseFailure(message) {
99
+ return [new Error(message), void 0];
100
+ }
101
+ function parseControlledCurlCommand(command) {
102
+ if (hasUnsupportedCurlShellSyntax(command)) return parseFailure("Controlled curl must be a single command without pipes, redirects, chaining, command substitution, or heredocs.");
103
+ let words;
104
+ try {
105
+ words = parseShellCommand(command);
106
+ } catch (error) {
107
+ return [error instanceof Error ? error : new Error(String(error)), void 0];
108
+ }
109
+ if (words[0] !== "curl") return parseFailure("Controlled curl command must start with curl.");
110
+ let body;
111
+ let method;
112
+ let url;
113
+ try {
114
+ for (let index = 1; index < words.length; index += 1) {
115
+ const word = words[index];
116
+ if (word === "-s" || word === "-S" || word === "-sS" || word === "--silent" || word === "--show-error" || word === "-L" || word === "--location") continue;
117
+ if (word === "-X" || word === "--request") {
118
+ const value = words[++index];
119
+ if (!value) return parseFailure(`${word} requires a method.`);
120
+ method = parseCurlMethod(value);
121
+ if (!method) return parseFailure(`Unsupported curl request method: ${value}.`);
122
+ continue;
123
+ }
124
+ if (word.startsWith("--request=")) {
125
+ method = parseCurlMethod(word.slice(10));
126
+ if (!method) return parseFailure(`Unsupported curl request method: ${word.slice(10)}.`);
127
+ continue;
128
+ }
129
+ if (word === "--url") {
130
+ const value = words[++index];
131
+ if (!value) return parseFailure("--url requires a URL.");
132
+ url = setCurlUrl(url, value);
133
+ continue;
134
+ }
135
+ if (word.startsWith("--url=")) {
136
+ url = setCurlUrl(url, word.slice(6));
137
+ continue;
138
+ }
139
+ if (word === "--json") {
140
+ const value = words[++index];
141
+ if (!value) return parseFailure("--json requires a JSON body.");
142
+ const [error, parsedBody] = parseJsonCurlBody(value);
143
+ if (error) return [error, void 0];
144
+ body = parsedBody;
145
+ method ??= "POST";
146
+ continue;
147
+ }
148
+ if (word.startsWith("--json=")) {
149
+ const [error, parsedBody] = parseJsonCurlBody(word.slice(7));
150
+ if (error) return [error, void 0];
151
+ body = parsedBody;
152
+ method ??= "POST";
153
+ continue;
154
+ }
155
+ if (word === "-d" || word === "--data" || word === "--data-raw" || word === "--data-binary") {
156
+ const value = words[++index];
157
+ if (!value) return parseFailure(`${word} requires a body.`);
158
+ body = parseCurlDataBody(value);
159
+ method ??= "POST";
160
+ continue;
161
+ }
162
+ if (word.startsWith("-d") && word !== "-d") {
163
+ body = parseCurlDataBody(word.slice(2));
164
+ method ??= "POST";
165
+ continue;
166
+ }
167
+ if (word.startsWith("--data=") || word.startsWith("--data-raw=") || word.startsWith("--data-binary=")) {
168
+ body = parseCurlDataBody(word.slice(word.indexOf("=") + 1));
169
+ method ??= "POST";
170
+ continue;
171
+ }
172
+ if (word === "-H" || word === "--header" || word === "-b" || word === "--cookie" || word.startsWith("--header=") || word.startsWith("--cookie=")) return parseFailure("Controlled curl injects Source credentials itself; do not pass headers or cookies in the command.");
173
+ if (word.startsWith("-")) return parseFailure(`Unsupported curl flag: ${word}.`);
174
+ url = setCurlUrl(url, word);
175
+ }
176
+ } catch (error) {
177
+ return [error instanceof Error ? error : new Error(String(error)), void 0];
178
+ }
179
+ if (!url) return parseFailure("Controlled curl requires a URL.");
180
+ try {
181
+ url = new URL(url).toString();
182
+ } catch {
183
+ return parseFailure(`Controlled curl URL is invalid: ${url}.`);
184
+ }
185
+ return [null, {
186
+ body,
187
+ method: method ?? "GET",
188
+ url
189
+ }];
190
+ }
191
+ function mentionsCurlCommand(command) {
192
+ return parseShellCommandLenient(command)[0] === "curl";
193
+ }
194
+ function hasUnsupportedCurlShellSyntax(command) {
195
+ let quote;
196
+ let escaped = false;
197
+ for (let index = 0; index < command.length; index += 1) {
198
+ const char = command[index];
199
+ const next = command[index + 1];
200
+ if (escaped) {
201
+ escaped = false;
202
+ continue;
203
+ }
204
+ if (char === "\\") {
205
+ escaped = true;
206
+ continue;
207
+ }
208
+ if (quote) {
209
+ if (char === quote) quote = void 0;
210
+ continue;
211
+ }
212
+ if (char === "'" || char === "\"") {
213
+ quote = char;
214
+ continue;
215
+ }
216
+ if (char === "|" || char === ";" || char === "<" || char === ">" || char === "`" || char === "$" && next === "(") return true;
217
+ if ((char === "&" || char === "|") && next === char) return true;
218
+ }
219
+ return /<<-?/.test(command);
220
+ }
221
+ function parseShellCommandLenient(command) {
222
+ try {
223
+ return parseShellCommand(command);
224
+ } catch {
225
+ return command.trim().split(/\s+/).filter(Boolean);
226
+ }
227
+ }
228
+ function parseCurlDataBody(value) {
229
+ const [error, body] = parseJsonCurlBody(value);
230
+ return error ? value : body;
231
+ }
232
+ function parseCurlMethod(value) {
233
+ const method = value.toUpperCase();
234
+ return method === "GET" || method === "HEAD" || method === "POST" ? method : void 0;
235
+ }
236
+ function parseJsonCurlBody(value) {
237
+ try {
238
+ return [null, JSON.parse(value)];
239
+ } catch {
240
+ return parseFailure("--json body must be valid JSON.");
241
+ }
242
+ }
243
+ function setCurlUrl(current, next) {
244
+ if (current) throw new Error("Controlled curl accepts exactly one URL.");
245
+ return next;
246
+ }
247
+ function policyDeniedCurl(command, cwd, message) {
248
+ return {
249
+ command,
250
+ cwd,
251
+ event: "policy_denied",
252
+ exitCode: 126,
253
+ stderr: `[vitehub] ${message}\n`,
254
+ stdout: ["[vitehub] Controlled curl request was not run.", "Expected a single curl command matching a visible Source Request Descriptor at `.vitehub/sources/<sourceKey>.json`."].join("\n") + "\n"
255
+ };
256
+ }
54
257
  async function withProviderTimeout(command, options, run) {
55
258
  if (typeof options.timeout !== "number") return await run();
56
259
  let timeout;
57
260
  try {
58
261
  return await Promise.race([run(), new Promise((resolve) => {
59
262
  timeout = setTimeout(() => resolve({
263
+ command,
264
+ cwd: options.cwd,
265
+ event: "command_timed_out",
60
266
  exitCode: null,
61
267
  stderr: `[vitehub] Workspace shell command timed out after ${options.timeout}ms.`,
62
268
  stdout: "",
@@ -1,4 +1,4 @@
1
- import { t as analyzeShellCommand } from "./analyze-BhMXNtZg.js";
1
+ import { t as analyzeShellCommand } from "./analyze-Bu5Ueqph.js";
2
2
  //#region src/runtime/session.ts
3
3
  function applyOutputLimit(result, maxLength) {
4
4
  if (!maxLength) return result;
@@ -30,11 +30,16 @@ function createPolicyObservation(command, cwd, message) {
30
30
  stdout: ""
31
31
  };
32
32
  }
33
+ const shellSessionDisposedMessage = "[vitehub] Shell session is disposed.";
33
34
  var RuntimeShellSession = class {
35
+ provider;
36
+ env;
34
37
  boundary;
35
38
  policy;
36
39
  #disposed = false;
37
- #processes = /* @__PURE__ */ new Map();
40
+ #disposeTask;
41
+ #processes = /* @__PURE__ */ new Set();
42
+ #starts = /* @__PURE__ */ new Set();
38
43
  #shellCalls = 0;
39
44
  constructor(provider, policy, env) {
40
45
  this.provider = provider;
@@ -46,8 +51,8 @@ var RuntimeShellSession = class {
46
51
  return await (this.provider.analyze ?? analyzeShellCommand)(command, options);
47
52
  }
48
53
  async exec(command, options = {}) {
49
- if (this.#disposed) return createPolicyObservation(command, options.cwd, "[vitehub] Shell session is disposed.");
50
- if (typeof this.policy.maxShellCalls === "number" && this.#shellCalls >= this.policy.maxShellCalls) return createPolicyObservation(command, options.cwd, `[vitehub] Shell session command budget exhausted after ${this.policy.maxShellCalls} calls. Answer from the evidence already collected instead of running more shell commands.`);
54
+ if (this.#disposed) return createPolicyObservation(command, options.cwd, shellSessionDisposedMessage);
55
+ if (typeof this.policy.maxShellCalls === "number" && this.#shellCalls >= this.policy.maxShellCalls) return createPolicyObservation(command, options.cwd, `[vitehub] Shell session command budget exhausted after ${this.policy.maxShellCalls} calls. The Shell Session policy limits command calls for this run.`);
51
56
  this.#shellCalls += 1;
52
57
  const started = Date.now();
53
58
  const result = await this.provider.exec(command, {
@@ -67,41 +72,85 @@ var RuntimeShellSession = class {
67
72
  }, this.policy.maxOutputLength);
68
73
  }
69
74
  async startProcess(command, options = {}) {
70
- if (this.#disposed) throw new Error("[vitehub] Shell session is disposed.");
75
+ if (this.#disposed) throw new Error(shellSessionDisposedMessage);
71
76
  if (!this.provider.startProcess || !this.boundary.processes.background) throw new Error("[vitehub] Shell provider does not support long-running processes.");
72
77
  if (typeof this.policy.maxProcesses === "number" && this.#processes.size >= this.policy.maxProcesses) throw new Error(`[vitehub] Shell session process budget exhausted after ${this.policy.maxProcesses} processes.`);
73
- const process = await this.provider.startProcess(command, {
74
- ...options,
75
- env: {
76
- ...this.env,
77
- ...options.env
78
- },
79
- timeout: options.timeout ?? this.policy.timeout
78
+ let finishStart;
79
+ const start = new Promise((resolve) => {
80
+ finishStart = resolve;
80
81
  });
81
- const trackedProcess = {
82
+ this.#starts.add(start);
83
+ start.finally(() => this.#starts.delete(start));
84
+ let process;
85
+ try {
86
+ process = await this.provider.startProcess(command, {
87
+ ...options,
88
+ env: {
89
+ ...this.env,
90
+ ...options.env
91
+ },
92
+ timeout: options.timeout ?? this.policy.timeout
93
+ });
94
+ } catch (error) {
95
+ finishStart();
96
+ throw error;
97
+ }
98
+ let stopTask;
99
+ let trackedProcess;
100
+ const stop = () => {
101
+ if (stopTask) return stopTask;
102
+ stopTask = Promise.resolve().then(() => process.stop()).then((result) => {
103
+ this.#processes.delete(trackedProcess);
104
+ return result;
105
+ }, (error) => {
106
+ stopTask = void 0;
107
+ throw error;
108
+ });
109
+ return stopTask;
110
+ };
111
+ trackedProcess = {
82
112
  ...process,
83
- stop: async () => {
84
- try {
85
- return await process.stop();
86
- } finally {
87
- this.#processes.delete(process.id);
88
- }
89
- }
113
+ stop
90
114
  };
91
- this.#processes.set(process.id, trackedProcess);
115
+ this.#processes.add(trackedProcess);
116
+ finishStart();
117
+ if (this.#disposed) {
118
+ try {
119
+ await stop();
120
+ } catch (error) {
121
+ throw new AggregateError([/* @__PURE__ */ new Error(shellSessionDisposedMessage), error], "[vitehub] Shell session was disposed while starting a background process, and stopping it failed.");
122
+ }
123
+ throw new Error(shellSessionDisposedMessage);
124
+ }
92
125
  return trackedProcess;
93
126
  }
94
127
  async listProcesses() {
95
- return [...this.#processes.values()];
128
+ return [...this.#processes];
96
129
  }
97
- async dispose() {
130
+ dispose() {
98
131
  this.#disposed = true;
99
- return {
100
- event: "session_disposed",
101
- exitCode: null,
102
- stderr: "",
103
- stdout: ""
104
- };
132
+ if (this.#disposeTask) return this.#disposeTask;
133
+ this.#disposeTask = (async () => {
134
+ await Promise.all(this.#starts);
135
+ const failures = [];
136
+ for (const process of [...this.#processes].reverse()) try {
137
+ await process.stop();
138
+ } catch (error) {
139
+ failures.push(error);
140
+ }
141
+ if (failures.length === 1) throw failures[0];
142
+ if (failures.length > 1) throw new AggregateError(failures, "[vitehub] Shell session failed to stop multiple background processes.");
143
+ return {
144
+ event: "session_disposed",
145
+ exitCode: null,
146
+ stderr: "",
147
+ stdout: ""
148
+ };
149
+ })().catch((error) => {
150
+ this.#disposeTask = void 0;
151
+ throw error;
152
+ });
153
+ return this.#disposeTask;
105
154
  }
106
155
  };
107
156
  function createShellRuntime(options) {
@@ -7,6 +7,7 @@ interface ShellRuntimeExecOptions {
7
7
  onStdout?: (data: string) => void;
8
8
  stdin?: string;
9
9
  timeout?: number;
10
+ workspacePaths?: string[];
10
11
  }
11
12
  interface ShellObservation {
12
13
  command?: string;
@@ -1,4 +1,5 @@
1
- import { s as ShellObservation } from "./types-BNtJGjIv.js";
1
+ import { o as ShellExecutionProvider, s as ShellObservation } from "./types-CNRdehmi.js";
2
+ import { r as ShellNetworkGrantExecutor } from "./just-bash-D84udCFy.js";
2
3
  import { IFileSystem } from "just-bash";
3
4
 
4
5
  //#region src/workspace/types.d.ts
@@ -66,6 +67,8 @@ interface WorkspaceInspectionCommandOptions {
66
67
  cwd?: string;
67
68
  fs: WorkspaceShellFileSystem;
68
69
  maxOutputLength?: number;
70
+ networkGrants?: ShellNetworkGrantExecutor;
71
+ provider?: ShellExecutionProvider;
69
72
  timeout?: number;
70
73
  }
71
74
  declare function runWorkspaceInspectionCommand(_input: SearchableShellWorkspace, command: string, options: WorkspaceInspectionCommandOptions): Promise<ShellObservation>;
@@ -74,4 +77,4 @@ declare function runWorkspaceInspectionCommand(_input: SearchableShellWorkspace,
74
77
  declare function cleanWorkspaceShellPath(path?: string): string;
75
78
  declare function cleanWorkspaceMutationPath(path: string): string;
76
79
  //#endregion
77
- export { ReadonlyShellWorkspace, SearchableShellWorkspace, ShellContent, ShellEntry, ShellListOptions, ShellMkdirOptions, ShellReadFileOptions, ShellRmOptions, ShellSearchHit, ShellSearchQuery, ShellStat, type WorkspaceShellFileSystem, WritableShellWorkspace, cleanWorkspaceMutationPath, cleanWorkspaceShellPath, createReadonlyWorkspaceFs, createWritableWorkspaceFs, runWorkspaceInspectionCommand, workspaceMountPoint };
80
+ export { type ReadonlyShellWorkspace, type SearchableShellWorkspace, type ShellContent, type ShellEntry, type ShellListOptions, type ShellMkdirOptions, type ShellReadFileOptions, type ShellRmOptions, type ShellSearchHit, type ShellSearchQuery, type ShellStat, type WorkspaceShellFileSystem, type WritableShellWorkspace, cleanWorkspaceMutationPath, cleanWorkspaceShellPath, createReadonlyWorkspaceFs, createWritableWorkspaceFs, runWorkspaceInspectionCommand, workspaceMountPoint };
package/dist/workspace.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createShellRuntime } from "./session-Qzhl3bqv.js";
1
+ import { t as createShellRuntime } from "./session-0OrrlmE9.js";
2
2
  import { createJustBashProvider } from "./providers/just-bash.js";
3
3
  import { posix } from "node:path";
4
4
  //#region src/workspace/filesystem.ts
@@ -54,6 +54,7 @@ async function copyWorkspacePath(workspace, from, to) {
54
54
  }
55
55
  }
56
56
  var WorkspaceFileSystem = class {
57
+ workspace;
57
58
  writeFs;
58
59
  #paths = [workspaceMountPoint];
59
60
  #refreshPromise;
@@ -530,23 +531,34 @@ function normalizeSafeShellPath(path) {
530
531
  async function runWorkspaceInspectionCommand(_input, command, options) {
531
532
  const maxOutputLength = options.maxOutputLength || 3e4;
532
533
  const timeout = options.timeout || 3e4;
534
+ const provider = options.networkGrants && usesWorkspaceNetworkGrant(command) ? void 0 : options.provider;
535
+ const unsupportedSyntax = preflightUnsupportedWorkspaceSyntax(command, options.commands, Boolean(provider));
536
+ if (unsupportedSyntax) return unsupportedSyntax;
533
537
  const preflight = await preflightWorkspaceInspectionCommand(command, options.fs, options.broadSearchPaths, options.cwd);
534
538
  if (preflight) return preflight;
539
+ const pipedBroadSearch = preflightPipedSearchWithoutPath(command, options.broadSearchPaths);
540
+ if (pipedBroadSearch) return pipedBroadSearch;
535
541
  const missingPath = await preflightMissingWorkspacePath(command, options.fs, options.cwd);
536
542
  if (missingPath) return missingPath;
537
- const result = await createShellRuntime({
543
+ const unsupported = preflightUnsupportedWorkspaceCommand(command, options.commands, Boolean(provider));
544
+ if (unsupported) return unsupported;
545
+ const runtime = createShellRuntime({
538
546
  policy: {
539
547
  maxOutputLength,
540
548
  timeout
541
549
  },
542
- provider: createJustBashProvider({
550
+ provider: provider ?? createJustBashProvider({
543
551
  commands: options.commands,
544
552
  cwd: options.cwd || "/workspace",
545
- fs: options.fs
553
+ fs: options.fs,
554
+ networkGrants: options.networkGrants
546
555
  })
547
- }).exec(command, {
548
- cwd: options.cwd || "/workspace",
549
- timeout
556
+ });
557
+ const cwd = options.cwd || "/workspace";
558
+ const result = await runtime.exec(command, {
559
+ cwd,
560
+ timeout,
561
+ workspacePaths: workspaceSessionPaths(command, cwd)
550
562
  });
551
563
  const noMatchFeedback = searchNoMatchFeedback(command, result, options.broadSearchPaths, options.cwd);
552
564
  return noMatchFeedback ? {
@@ -555,6 +567,45 @@ async function runWorkspaceInspectionCommand(_input, command, options) {
555
567
  workspaceGuardrail: { kind: "no_match" }
556
568
  } : result;
557
569
  }
570
+ function workspaceSessionPaths(command, cwd = workspaceMountPoint) {
571
+ try {
572
+ const paths = /* @__PURE__ */ new Set();
573
+ let currentCwd = cwd;
574
+ for (const segment of analyzeWorkspaceInspectionCommand(command)) {
575
+ const words = segment.words;
576
+ if (words[0] === "cd") {
577
+ const path = words[1] || "/workspace";
578
+ if (isWorkspacePathCandidate(path)) currentCwd = resolvedWorkspaceCwd(currentCwd, path);
579
+ continue;
580
+ }
581
+ for (const path of segment.paths) {
582
+ const resolvedPath = resolveConcreteWorkspacePath(currentCwd, path);
583
+ if (resolvedPath) paths.add(resolvedPath);
584
+ }
585
+ }
586
+ return paths.size ? [...paths].sort() : void 0;
587
+ } catch {
588
+ return;
589
+ }
590
+ }
591
+ function preflightPipedSearchWithoutPath(command, broadSearchPaths = []) {
592
+ try {
593
+ for (const segment of analyzeWorkspaceInspectionCommand(command)) {
594
+ if (segment.separatorAfter !== "|" || segment.paths.length) continue;
595
+ const name = segment.words[0];
596
+ if (name === "rg" || name === "grep") return broadWorkspaceSearchFeedback(broadSearchPaths);
597
+ }
598
+ } catch {
599
+ return;
600
+ }
601
+ }
602
+ function usesWorkspaceNetworkGrant(command) {
603
+ try {
604
+ return analyzeWorkspaceInspectionCommand(command).some((segment) => workspaceExecutable(segment.words)?.name === "curl");
605
+ } catch {
606
+ return false;
607
+ }
608
+ }
558
609
  async function preflightWorkspaceInspectionCommand(command, fs, broadSearchPaths = [], cwd = workspaceMountPoint) {
559
610
  try {
560
611
  let currentCwd = cwd;
@@ -640,9 +691,8 @@ function missingWorkspacePathFeedback(command, resolvedPath) {
640
691
  stderr: "",
641
692
  stdout: [
642
693
  `[vitehub] Workspace path is not mounted: ${resolvedPath}`,
643
- "The agent cannot inspect files outside the configured workspace sources.",
644
- "If this path should exist, update the Agent workspace source configuration or materialize the correct mounted source.",
645
- "Otherwise answer that the requested evidence is unavailable in the current workspace."
694
+ "Configured Workspace Sources do not expose this path.",
695
+ "This usually means the Workspace Source configuration or materialized source selection does not include it."
646
696
  ].join("\n") + "\n",
647
697
  workspaceGuardrail: {
648
698
  kind: "missing_path",
@@ -664,11 +714,11 @@ function isBroadWorkspaceSearch(segment, broadSearchPaths = [], cwd = workspaceM
664
714
  return false;
665
715
  }
666
716
  function broadWorkspaceSearchFeedback(broadSearchPaths = []) {
667
- const hint = broadSearchPaths.length ? ` Try one of these paths: ${broadSearchPaths.map((path) => `"${path}"`).join(", ")}.` : " Use a narrow mounted source or subdirectory path instead.";
717
+ const hint = broadSearchPaths.length ? ` Mounted search roots: ${broadSearchPaths.map((path) => `"${path}"`).join(", ")}.` : " Expected a mounted source or subdirectory path.";
668
718
  const feedback = [
669
719
  "[vitehub] Workspace search is too broad for this agent tool.",
670
- "Use one specific mounted subdirectory or file path.",
671
- "If the requested evidence is not in the mounted workspace paths, answer that it is unavailable instead of trying broader searches."
720
+ "The command targets the workspace root or too many paths.",
721
+ "Workspace searches are bounded to mounted source subdirectories."
672
722
  ].join("\n") + "\n";
673
723
  return {
674
724
  command: "",
@@ -702,20 +752,133 @@ function searchNoMatchFeedback(command, result, broadSearchPaths = [], cwd = wor
702
752
  if (segment.separatorAfter === "&&") return "";
703
753
  continue;
704
754
  }
705
- return [
706
- "[vitehub] Search returned no matches in the mounted workspace source.",
707
- "If the expected file is outside this mounted source, tell the user the evidence is unavailable in the current workspace instead of continuing broad searches.",
708
- "Use a more specific mounted subdirectory only if the user request can be answered from the listed workspace paths."
709
- ].join("\n") + "\n";
755
+ return ["[vitehub] Search returned no matches in the mounted workspace source.", "Expected content may be outside the mounted workspace paths or under a different mounted subdirectory."].join("\n") + "\n";
710
756
  }
711
757
  } catch {
712
758
  return "";
713
759
  }
714
760
  return "";
715
761
  }
762
+ function preflightUnsupportedWorkspaceCommand(command, commands, strictProvider = false) {
763
+ const syntax = preflightUnsupportedWorkspaceSyntax(command, commands, strictProvider);
764
+ if (syntax) return syntax;
765
+ if (!strictProvider && usesCompoundShellSyntax(command)) return void 0;
766
+ if (!commands) return void 0;
767
+ const allowed = new Set([
768
+ ...commands,
769
+ "cd",
770
+ "false",
771
+ "true"
772
+ ]);
773
+ for (const segment of analyzeWorkspaceInspectionCommand(command)) {
774
+ const executable = workspaceExecutable(segment.words);
775
+ if (!executable || allowed.has(executable.name)) continue;
776
+ return unsupportedWorkspaceCommandFeedback(command, executable.name, commands);
777
+ }
778
+ }
779
+ function preflightUnsupportedWorkspaceSyntax(command, commands, strictProvider = false) {
780
+ if (usesShellSubstitution(command)) {
781
+ if (strictProvider || commands) return unsupportedWorkspaceCommandFeedback(command, "shell substitution", commands);
782
+ return;
783
+ }
784
+ if (usesCompoundShellSyntax(command)) {
785
+ if (strictProvider) return unsupportedWorkspaceCommandFeedback(command, "compound shell syntax", commands);
786
+ return;
787
+ }
788
+ }
789
+ function unsupportedWorkspaceCommandFeedback(command, name, commands = []) {
790
+ const available = [...new Set(commands)].sort();
791
+ const formatted = available.length ? available.map((command) => `\`${command}\``).join(", ") : "none";
792
+ return {
793
+ command,
794
+ event: "policy_denied",
795
+ exitCode: 126,
796
+ stderr: `[vitehub] Unsupported workspace shell command: ${name}. Available commands: ${available.join(", ") || "none"}.\n`,
797
+ stdout: [
798
+ `[vitehub] Workspace shell command is not available: ${name}`,
799
+ `Available workspace commands: ${formatted}.`,
800
+ "This shell only supports configured Workspace inspection commands."
801
+ ].join("\n") + "\n"
802
+ };
803
+ }
804
+ function usesShellSubstitution(command) {
805
+ let quote;
806
+ let escaped = false;
807
+ for (let index = 0; index < command.length; index++) {
808
+ const char = command[index];
809
+ const next = command[index + 1];
810
+ if (escaped) {
811
+ escaped = false;
812
+ continue;
813
+ }
814
+ if (char === "\\") {
815
+ escaped = true;
816
+ continue;
817
+ }
818
+ if (quote === "'") {
819
+ if (char === "'") quote = void 0;
820
+ continue;
821
+ }
822
+ if (quote === "\"") {
823
+ if (char === "\"") quote = void 0;
824
+ else if (char === "`" || char === "$" && next === "(" || (char === "<" || char === ">") && next === "(") return true;
825
+ continue;
826
+ }
827
+ if (char === "'" || char === "\"") {
828
+ quote = char;
829
+ continue;
830
+ }
831
+ if (char === "`" || char === "$" && next === "(" || (char === "<" || char === ">") && next === "(") return true;
832
+ }
833
+ return false;
834
+ }
835
+ function workspaceExecutable(words) {
836
+ for (const [index, word] of words.entries()) {
837
+ if (isAssignmentWord(word)) continue;
838
+ return {
839
+ index,
840
+ name: word
841
+ };
842
+ }
843
+ }
844
+ function usesCompoundShellSyntax(command) {
845
+ return analyzeWorkspaceInspectionCommand(command).some((segment) => isCompoundShellSyntaxWord(segment.words[0] || ""));
846
+ }
847
+ function isCompoundShellSyntaxWord(word) {
848
+ return word === "{" || word.startsWith("(") || /^[A-Za-z_][A-Za-z0-9_]*\(\)$/.test(word) || shellSyntaxWords.has(word);
849
+ }
850
+ function isAssignmentWord(word) {
851
+ return /^[A-Za-z_][A-Za-z0-9_]*=.*/.test(word);
852
+ }
853
+ const shellSyntaxWords = new Set([
854
+ "case",
855
+ "do",
856
+ "done",
857
+ "elif",
858
+ "else",
859
+ "esac",
860
+ "fi",
861
+ "for",
862
+ "function",
863
+ "if",
864
+ "select",
865
+ "then",
866
+ "time",
867
+ "until",
868
+ "while"
869
+ ]);
716
870
  function isConcreteWorkspacePath(path) {
717
871
  return isWorkspacePathCandidate(path) && cleanWorkspaceShellPath(path) !== "";
718
872
  }
873
+ function resolveConcreteWorkspacePath(cwd, path) {
874
+ if (!isWorkspacePathCandidate(path)) return void 0;
875
+ try {
876
+ const resolvedPath = resolveWorkspaceShellPath(cwd, path);
877
+ return resolvedPath === "" ? void 0 : resolvedPath;
878
+ } catch {
879
+ return;
880
+ }
881
+ }
719
882
  function isWorkspacePathCandidate(path) {
720
883
  return Boolean(path) && path !== "-" && !path.includes("$") && !path.includes("`") && !path.includes("*") && !path.includes("?") && !path.includes("[");
721
884
  }
package/package.json CHANGED
@@ -1,24 +1,28 @@
1
1
  {
2
2
  "name": "@vite-hub/shell",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Unified shell runtimes for ViteHub.",
5
- "author": "onmax <maximogarciamtnez@gmail.com>",
6
- "license": "Apache-2.0",
5
+ "keywords": [
6
+ "cloudflare",
7
+ "just-bash",
8
+ "shell",
9
+ "vitehub"
10
+ ],
7
11
  "homepage": "https://github.com/vite-hub/vitehub#readme",
12
+ "bugs": "https://github.com/vite-hub/vitehub/issues",
13
+ "license": "Apache-2.0",
14
+ "author": "onmax <maximogarciamtnez@gmail.com>",
8
15
  "repository": {
9
16
  "type": "git",
10
17
  "url": "git+https://github.com/vite-hub/vitehub.git",
11
18
  "directory": "packages/shell"
12
19
  },
13
- "bugs": "https://github.com/vite-hub/vitehub/issues",
14
- "keywords": [
15
- "vitehub",
16
- "shell",
17
- "just-bash",
18
- "cloudflare"
20
+ "files": [
21
+ "dist",
22
+ "package.json"
19
23
  ],
20
- "sideEffects": false,
21
24
  "type": "module",
25
+ "sideEffects": false,
22
26
  "types": "./dist/index.d.ts",
23
27
  "exports": {
24
28
  ".": "./dist/index.js",
@@ -27,25 +31,24 @@
27
31
  "./workspace": "./dist/workspace.js",
28
32
  "./package.json": "./package.json"
29
33
  },
30
- "files": [
31
- "dist",
32
- "package.json"
33
- ],
34
34
  "dependencies": {
35
- "just-bash": "^2.14.4",
36
- "sh-syntax": "0.5.8"
35
+ "just-bash": "^3.1.0",
36
+ "sh-syntax": "0.6.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@types/node": "^25.6.0",
40
- "publint": "^0.3.15",
41
- "tsdown": "^0.21.8",
42
- "typescript": "^6.0.2",
39
+ "@types/node": "^24.13.3",
40
+ "publint": "^0.3.21",
41
+ "typescript": "^6.0.3",
42
+ "vite-plus": "^0.1.24",
43
43
  "vitest": "^4.1.4"
44
44
  },
45
+ "engines": {
46
+ "node": ">=24.0.0"
47
+ },
45
48
  "scripts": {
46
- "build": "tsdown --tsconfig tsconfig.build.json",
47
- "dev": "tsdown --watch",
49
+ "build": "vp pack",
50
+ "dev": "vp pack --watch",
48
51
  "typecheck": "tsc --noEmit -p ./tsconfig.json",
49
- "test": "pnpm --filter @vite-hub/shell build && vitest run"
52
+ "test": "vp run -t @vite-hub/shell#build && vp test"
50
53
  }
51
54
  }