@vite-hub/shell 0.1.0 → 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.
@@ -1,8 +1,10 @@
1
- import { i as shellErrorDiagnostics, n as parseShellCommand, t as analyzeShellCommand } from "../analyze-BXwz20IH.js";
1
+ import { r as shellErrorDiagnostics, t as analyzeShellCommand } from "../analyze-kSc2pmy2.js";
2
2
  //#region src/providers/just-bash.ts
3
- function createJustBashProvider(options) {
3
+ function createJustBashDriver(options) {
4
4
  const commands = options.commands?.slice();
5
5
  const networkGrants = options.networkGrants;
6
+ const executionLimits = options.executionLimits && { ...options.executionLimits };
7
+ const executionLimitProfile = options.executionLimitProfile;
6
8
  const boundary = {
7
9
  cwd: true,
8
10
  env: true,
@@ -34,34 +36,40 @@ function createJustBashProvider(options) {
34
36
  boundary,
35
37
  async exec(command, execOptions = {}) {
36
38
  const cwd = execOptions.cwd ?? options.cwd ?? "/workspace";
37
- const result = await withProviderTimeout(command, {
39
+ const result = await withDriverTimeout(command, {
38
40
  ...execOptions,
39
41
  cwd
40
42
  }, async (runOptions) => {
41
- const curlResult = await runControlledCurlCommand(command, {
42
- commands,
43
- cwd,
44
- networkGrants,
45
- maxOutputLength: runOptions.maxOutputLength,
46
- signal: runOptions.signal
43
+ const { Bash, defineCommand } = await import("just-bash/browser");
44
+ let policyDenied = false;
45
+ const curl = defineCommand("curl", async (args, ctx) => {
46
+ const curlResult = await runControlledCurl(args, {
47
+ commands,
48
+ networkGrants,
49
+ signal: ctx.signal ?? runOptions.signal
50
+ });
51
+ policyDenied ||= curlResult.policyDenied;
52
+ return curlResult;
47
53
  });
48
- if (curlResult) return curlResult;
49
- const { Bash } = await import("just-bash/browser");
50
54
  return await new Bash({
51
55
  commands,
56
+ customCommands: [curl],
52
57
  cwd,
58
+ executionLimitProfile,
59
+ executionLimits,
53
60
  fs: options.fs
54
61
  }).exec(command, {
55
62
  cwd,
56
63
  env: execOptions.env,
57
- signal: runOptions.signal
64
+ signal: runOptions.signal,
65
+ stdin: execOptions.stdin
58
66
  }).then((result) => {
59
67
  const stdout = boundOutput(result.stdout, runOptions.maxOutputLength);
60
68
  const stderr = boundOutput(result.stderr, runOptions.maxOutputLength);
61
69
  return {
62
70
  command,
63
71
  cwd,
64
- event: "command_finished",
72
+ event: policyDenied ? "policy_denied" : "command_finished",
65
73
  exitCode: result.exitCode,
66
74
  maxOutputLength: runOptions.maxOutputLength,
67
75
  outputTruncated: stdout.truncated || stderr.truncated,
@@ -86,13 +94,12 @@ function createJustBashProvider(options) {
86
94
  }
87
95
  };
88
96
  }
89
- async function runControlledCurlCommand(command, options) {
90
- if (!mentionsCurlCommand(command)) return void 0;
97
+ async function runControlledCurl(args, options) {
91
98
  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.");
93
- const [parseError, parsed] = parseControlledCurlCommand(command);
94
- if (parseError) return policyDeniedCurl(command, options.cwd, parseError.message);
95
- if (!options.networkGrants) return policyDeniedCurl(command, options.cwd, "No API-backed Source request descriptors are visible in this workspace.");
99
+ if (options.commands && !options.commands.includes("curl")) return policyDeniedCurl("curl is not in the permitted commands for this shell.");
100
+ const [parseError, parsed] = parseControlledCurlArgs(args);
101
+ if (parseError) return policyDeniedCurl(parseError.message);
102
+ if (!options.networkGrants) return policyDeniedCurl("No API-backed Source request descriptors are visible in this workspace.");
96
103
  try {
97
104
  const request = {
98
105
  body: parsed.body,
@@ -106,26 +113,19 @@ async function runControlledCurlCommand(command, options) {
106
113
  value: options.signal
107
114
  });
108
115
  const result = await options.networkGrants.executeSourceRequest(request);
109
- const bounded = boundOutput(typeof result.content === "string" ? result.content : new TextDecoder().decode(result.content), options.maxOutputLength);
110
116
  return {
111
- command,
112
- cwd: options.cwd,
113
- event: "command_finished",
114
117
  exitCode: 0,
118
+ policyDenied: false,
115
119
  stderr: "",
116
- maxOutputLength: options.maxOutputLength,
117
- outputTruncated: bounded.truncated,
118
- stdout: bounded.content
120
+ stdout: typeof result.content === "string" ? result.content : new TextDecoder().decode(result.content)
119
121
  };
120
122
  } catch (error) {
121
123
  if (options.signal?.aborted) throw options.signal.reason;
122
124
  const message = error instanceof Error ? error.message : String(error);
123
125
  const httpFailure = message.includes("HTTP request failed");
124
126
  return {
125
- command,
126
- cwd: options.cwd,
127
- event: httpFailure ? "command_finished" : "policy_denied",
128
127
  exitCode: httpFailure ? 22 : 126,
128
+ policyDenied: !httpFailure,
129
129
  stderr: `${message}\n`,
130
130
  stdout: ""
131
131
  };
@@ -134,132 +134,86 @@ async function runControlledCurlCommand(command, options) {
134
134
  function parseFailure(message) {
135
135
  return [shellErrorDiagnostics.SHELL_R0004({ message }), void 0];
136
136
  }
137
- function parseControlledCurlCommand(command) {
138
- if (hasUnsupportedCurlShellSyntax(command)) return parseFailure("Controlled curl must be a single command without pipes, redirects, chaining, command substitution, or heredocs.");
139
- let words;
140
- try {
141
- words = parseShellCommand(command);
142
- } catch (error) {
143
- return [error instanceof Error ? error : shellErrorDiagnostics.SHELL_R0005({ message: String(error) }), void 0];
144
- }
145
- if (words[0] !== "curl") return parseFailure("Controlled curl command must start with curl.");
137
+ function parseControlledCurlArgs(words) {
146
138
  let body;
147
139
  let method;
148
140
  let url;
149
- try {
150
- for (let index = 1; index < words.length; index += 1) {
151
- const word = words[index];
152
- if (word === "-s" || word === "-S" || word === "-sS" || word === "--silent" || word === "--show-error" || word === "-L" || word === "--location") continue;
153
- if (word === "-X" || word === "--request") {
154
- const value = words[++index];
155
- if (!value) return parseFailure(`${word} requires a method.`);
156
- method = parseCurlMethod(value);
157
- if (!method) return parseFailure(`Unsupported curl request method: ${value}.`);
158
- continue;
159
- }
160
- if (word.startsWith("--request=")) {
161
- method = parseCurlMethod(word.slice(10));
162
- if (!method) return parseFailure(`Unsupported curl request method: ${word.slice(10)}.`);
163
- continue;
164
- }
165
- if (word === "--url") {
166
- const value = words[++index];
167
- if (!value) return parseFailure("--url requires a URL.");
168
- url = setCurlUrl(url, value);
169
- continue;
170
- }
171
- if (word.startsWith("--url=")) {
172
- url = setCurlUrl(url, word.slice(6));
173
- continue;
174
- }
175
- if (word === "--json") {
176
- const value = words[++index];
177
- if (!value) return parseFailure("--json requires a JSON body.");
178
- const [error, parsedBody] = parseJsonCurlBody(value);
179
- if (error) return [error, void 0];
180
- body = parsedBody;
181
- method ??= "POST";
182
- continue;
183
- }
184
- if (word.startsWith("--json=")) {
185
- const [error, parsedBody] = parseJsonCurlBody(word.slice(7));
186
- if (error) return [error, void 0];
187
- body = parsedBody;
188
- method ??= "POST";
189
- continue;
190
- }
191
- if (word === "-d" || word === "--data" || word === "--data-raw" || word === "--data-binary") {
192
- const value = words[++index];
193
- if (value === void 0) return parseFailure(`${word} requires a body.`);
194
- body = parseCurlDataBody(value);
195
- method ??= "POST";
196
- continue;
197
- }
198
- if (word.startsWith("-d") && word !== "-d") {
199
- body = parseCurlDataBody(word.slice(2));
200
- method ??= "POST";
201
- continue;
202
- }
203
- if (word.startsWith("--data=") || word.startsWith("--data-raw=") || word.startsWith("--data-binary=")) {
204
- body = parseCurlDataBody(word.slice(word.indexOf("=") + 1));
205
- method ??= "POST";
206
- continue;
207
- }
208
- 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.");
209
- if (word.startsWith("-")) return parseFailure(`Unsupported curl flag: ${word}.`);
210
- url = setCurlUrl(url, word);
141
+ for (let index = 0; index < words.length; index += 1) {
142
+ const word = words[index];
143
+ if (word === "-s" || word === "-S" || word === "-sS" || word === "--silent" || word === "--show-error" || word === "-L" || word === "--location") continue;
144
+ if (word === "-X" || word === "--request") {
145
+ const value = words[++index];
146
+ if (!value) return parseFailure(`${word} requires a method.`);
147
+ method = parseCurlMethod(value);
148
+ if (!method) return parseFailure(`Unsupported curl request method: ${value}.`);
149
+ continue;
211
150
  }
212
- } catch (error) {
213
- return [error instanceof Error ? error : shellErrorDiagnostics.SHELL_R0006({ message: String(error) }), void 0];
214
- }
215
- if (!url) return parseFailure("Controlled curl requires a URL.");
216
- try {
217
- url = new URL(url).toString();
218
- } catch {
219
- return parseFailure(`Controlled curl URL is invalid: ${url}.`);
220
- }
221
- return [null, {
222
- body,
223
- method: method ?? "GET",
224
- url
225
- }];
226
- }
227
- function mentionsCurlCommand(command) {
228
- return parseShellCommandLenient(command)[0] === "curl";
229
- }
230
- function hasUnsupportedCurlShellSyntax(command) {
231
- let quote;
232
- let escaped = false;
233
- for (let index = 0; index < command.length; index += 1) {
234
- const char = command[index];
235
- const next = command[index + 1];
236
- if (escaped) {
237
- escaped = false;
151
+ if (word.startsWith("--request=")) {
152
+ method = parseCurlMethod(word.slice(10));
153
+ if (!method) return parseFailure(`Unsupported curl request method: ${word.slice(10)}.`);
154
+ continue;
155
+ }
156
+ if (word === "--url") {
157
+ const value = words[++index];
158
+ if (!value) return parseFailure("--url requires a URL.");
159
+ if (url) return multipleCurlUrls();
160
+ url = value;
161
+ continue;
162
+ }
163
+ if (word.startsWith("--url=")) {
164
+ if (url) return multipleCurlUrls();
165
+ url = word.slice(6);
166
+ continue;
167
+ }
168
+ if (word === "--json") {
169
+ const value = words[++index];
170
+ if (!value) return parseFailure("--json requires a JSON body.");
171
+ const [error, parsedBody] = parseJsonCurlBody(value);
172
+ if (error) return [error, void 0];
173
+ body = parsedBody;
174
+ method ??= "POST";
175
+ continue;
176
+ }
177
+ if (word.startsWith("--json=")) {
178
+ const [error, parsedBody] = parseJsonCurlBody(word.slice(7));
179
+ if (error) return [error, void 0];
180
+ body = parsedBody;
181
+ method ??= "POST";
238
182
  continue;
239
183
  }
240
- if (char === "\\") {
241
- escaped = true;
184
+ if (word === "-d" || word === "--data" || word === "--data-raw" || word === "--data-binary") {
185
+ const value = words[++index];
186
+ if (value === void 0) return parseFailure(`${word} requires a body.`);
187
+ body = parseCurlDataBody(value);
188
+ method ??= "POST";
242
189
  continue;
243
190
  }
244
- if (quote) {
245
- if (char === quote) quote = void 0;
191
+ if (word.startsWith("-d") && word !== "-d") {
192
+ body = parseCurlDataBody(word.slice(2));
193
+ method ??= "POST";
246
194
  continue;
247
195
  }
248
- if (char === "'" || char === "\"") {
249
- quote = char;
196
+ if (word.startsWith("--data=") || word.startsWith("--data-raw=") || word.startsWith("--data-binary=")) {
197
+ body = parseCurlDataBody(word.slice(word.indexOf("=") + 1));
198
+ method ??= "POST";
250
199
  continue;
251
200
  }
252
- if (char === "|" || char === ";" || char === "<" || char === ">" || char === "`" || char === "$" && next === "(") return true;
253
- if ((char === "&" || char === "|") && next === char) return true;
201
+ 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.");
202
+ if (word.startsWith("-")) return parseFailure(`Unsupported curl flag: ${word}.`);
203
+ if (url) return multipleCurlUrls();
204
+ url = word;
254
205
  }
255
- return /<<-?/.test(command);
256
- }
257
- function parseShellCommandLenient(command) {
206
+ if (!url) return parseFailure("Controlled curl requires a URL.");
258
207
  try {
259
- return parseShellCommand(command);
208
+ url = new URL(url).toString();
260
209
  } catch {
261
- return command.trim().split(/\s+/).filter(Boolean);
210
+ return parseFailure(`Controlled curl URL is invalid: ${url}.`);
262
211
  }
212
+ return [null, {
213
+ body,
214
+ method: method ?? "GET",
215
+ url
216
+ }];
263
217
  }
264
218
  function parseCurlDataBody(value) {
265
219
  const [error, body] = parseJsonCurlBody(value);
@@ -276,29 +230,26 @@ function parseJsonCurlBody(value) {
276
230
  return parseFailure("--json body must be valid JSON.");
277
231
  }
278
232
  }
279
- function setCurlUrl(current, next) {
280
- if (current) throw shellErrorDiagnostics.SHELL_R0007({ message: "Controlled curl accepts exactly one URL." });
281
- return next;
233
+ function multipleCurlUrls() {
234
+ return [shellErrorDiagnostics.SHELL_R0007({ message: "Controlled curl accepts exactly one URL." }), void 0];
282
235
  }
283
- function policyDeniedCurl(command, cwd, message) {
236
+ function policyDeniedCurl(message) {
284
237
  return {
285
- command,
286
- cwd,
287
- event: "policy_denied",
288
238
  exitCode: 126,
239
+ policyDenied: true,
289
240
  stderr: `[vitehub] ${message}\n`,
290
- 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"
241
+ stdout: ["[vitehub] Controlled curl request was not run.", "Expected a curl command matching a visible Source Request Descriptor at `.vitehub/sources/<sourceKey>.json`."].join("\n") + "\n"
291
242
  };
292
243
  }
293
- async function withProviderTimeout(command, options, run) {
244
+ async function withDriverTimeout(command, options, run) {
294
245
  options.signal?.throwIfAborted();
295
246
  const controller = new AbortController();
296
247
  const abortListener = options.signal ? () => controller.abort(options.signal?.reason) : void 0;
297
248
  if (abortListener) options.signal?.addEventListener("abort", abortListener, { once: true });
298
- const runOptions = options.signal || typeof options.timeout === "number" ? {
249
+ const runOptions = {
299
250
  ...options,
300
251
  signal: controller.signal
301
- } : options;
252
+ };
302
253
  let timeout;
303
254
  let onAbort;
304
255
  const aborted = options.signal ? new Promise((_resolve, reject) => {
@@ -347,4 +298,4 @@ function boundOutput(content, maxLength) {
347
298
  };
348
299
  }
349
300
  //#endregion
350
- export { createJustBashProvider };
301
+ export { createJustBashDriver };
@@ -1,7 +1,7 @@
1
- import { i as shellErrorDiagnostics, t as analyzeShellCommand } from "./analyze-BXwz20IH.js";
1
+ import { r as shellErrorDiagnostics, t as analyzeShellCommand } from "./analyze-kSc2pmy2.js";
2
2
  //#region src/runtime/session.ts
3
3
  function applyOutputLimit(result, maxLength) {
4
- const limit = normalizeOutputLength(maxLength);
4
+ const limit = normalizeLimit(maxLength);
5
5
  if (limit === void 0) return result;
6
6
  const next = {
7
7
  command: result.command,
@@ -30,15 +30,21 @@ function applyOutputLimit(result, maxLength) {
30
30
  outputTruncated: true
31
31
  } : next;
32
32
  }
33
- function normalizeOutputLength(value) {
33
+ function normalizeLimit(value) {
34
34
  if (value === void 0) return void 0;
35
35
  if (value === Number.POSITIVE_INFINITY) return void 0;
36
36
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
37
37
  }
38
+ /** A per-call limit can only lower the policy limit. */
39
+ function lowerLimit(requested, policy) {
40
+ const call = normalizeLimit(requested);
41
+ const bound = normalizeLimit(policy);
42
+ if (call === void 0) return bound;
43
+ if (bound === void 0) return call;
44
+ return Math.min(call, bound);
45
+ }
38
46
  function limitOutputOptions(options, policy) {
39
- const requestedOutputLength = normalizeOutputLength(options.maxOutputLength);
40
- const policyOutputLength = normalizeOutputLength(policy.maxOutputLength);
41
- const maxOutputLength = requestedOutputLength === void 0 ? policyOutputLength : policyOutputLength === void 0 ? requestedOutputLength : Math.min(requestedOutputLength, policyOutputLength);
47
+ const maxOutputLength = lowerLimit(options.maxOutputLength, policy.maxOutputLength);
42
48
  let stdoutRemaining = maxOutputLength;
43
49
  let stderrRemaining = maxOutputLength;
44
50
  const limitedCallback = (callback, remaining, consume) => callback && ((data) => {
@@ -52,6 +58,7 @@ function limitOutputOptions(options, policy) {
52
58
  return {
53
59
  ...options,
54
60
  maxOutputLength,
61
+ timeout: lowerLimit(options.timeout, policy.timeout),
55
62
  onStdout: limitedCallback(options.onStdout, () => stdoutRemaining, (value) => {
56
63
  stdoutRemaining = Math.max(0, (stdoutRemaining ?? 0) - value);
57
64
  }),
@@ -60,6 +67,38 @@ function limitOutputOptions(options, policy) {
60
67
  })
61
68
  };
62
69
  }
70
+ function createTimeoutObservation(command, cwd, timeout) {
71
+ return {
72
+ command,
73
+ cwd,
74
+ event: "command_timed_out",
75
+ exitCode: null,
76
+ stderr: `[vitehub] Shell command timed out after ${timeout}ms.\n`,
77
+ stdout: "",
78
+ timedOut: true
79
+ };
80
+ }
81
+ /** Race the driver against the timeout, then abort the driver work. */
82
+ async function execWithRuntimeTimeout(driver, command, options, timeout) {
83
+ const controller = new AbortController();
84
+ const running = driver.exec(command, {
85
+ ...options,
86
+ signal: options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal
87
+ });
88
+ running.catch(() => {});
89
+ let timer;
90
+ const timedOut = new Promise((resolve) => {
91
+ timer = setTimeout(() => {
92
+ resolve(createTimeoutObservation(command, options.cwd, timeout));
93
+ controller.abort();
94
+ }, timeout);
95
+ });
96
+ try {
97
+ return await Promise.race([running, timedOut]);
98
+ } finally {
99
+ clearTimeout(timer);
100
+ }
101
+ }
63
102
  function createPolicyObservation(command, cwd, message) {
64
103
  return {
65
104
  command,
@@ -72,7 +111,7 @@ function createPolicyObservation(command, cwd, message) {
72
111
  }
73
112
  const shellSessionDisposedMessage = "[vitehub] Shell session is disposed.";
74
113
  var RuntimeShellSession = class {
75
- provider;
114
+ driver;
76
115
  env;
77
116
  boundary;
78
117
  policy;
@@ -80,15 +119,16 @@ var RuntimeShellSession = class {
80
119
  #disposeTask;
81
120
  #processes = /* @__PURE__ */ new Set();
82
121
  #starts = /* @__PURE__ */ new Set();
122
+ #cancelStarts = /* @__PURE__ */ new Set();
83
123
  #shellCalls = 0;
84
- constructor(provider, policy, env) {
85
- this.provider = provider;
124
+ constructor(driver, policy, env) {
125
+ this.driver = driver;
86
126
  this.env = env;
87
- this.boundary = provider.boundary;
127
+ this.boundary = driver.boundary;
88
128
  this.policy = policy;
89
129
  }
90
130
  async analyze(command, options) {
91
- return await (this.provider.analyze ?? analyzeShellCommand).call(this.provider, command, options);
131
+ return await (this.driver.analyze ?? analyzeShellCommand).call(this.driver, command, options);
92
132
  }
93
133
  async exec(command, options = {}) {
94
134
  if (this.#disposed) return createPolicyObservation(command, options.cwd, shellSessionDisposedMessage);
@@ -99,16 +139,16 @@ var RuntimeShellSession = class {
99
139
  options = limitOutputOptions(options, this.policy);
100
140
  const maxOutputLength = options.maxOutputLength;
101
141
  const signal = options.budget && options.signal && options.signal !== options.budget.signal ? AbortSignal.any([options.signal, options.budget.signal]) : options.budget?.signal ?? options.signal;
102
- const result = await this.provider.exec(command, {
142
+ const execOptions = {
103
143
  ...options,
104
144
  env: {
105
145
  ...this.env,
106
146
  ...options.env
107
147
  },
108
148
  maxOutputLength,
109
- signal,
110
- timeout: options.timeout ?? this.policy.timeout
111
- });
149
+ signal
150
+ };
151
+ const result = this.boundary.timeout.enforcedBy === "runtime" && options.timeout !== void 0 ? await execWithRuntimeTimeout(this.driver, command, execOptions, options.timeout) : await this.driver.exec(command, execOptions);
112
152
  options.budget?.recordOutputBytes(new TextEncoder().encode(result.stdout).byteLength + new TextEncoder().encode(result.stderr).byteLength);
113
153
  const timedOut = result.timedOut;
114
154
  return applyOutputLimit({
@@ -127,7 +167,7 @@ var RuntimeShellSession = class {
127
167
  }
128
168
  async startProcess(command, options = {}) {
129
169
  if (this.#disposed) throw shellErrorDiagnostics.SHELL_R0008({ message: shellSessionDisposedMessage });
130
- if (!this.provider.startProcess || !this.boundary.processes.background) throw shellErrorDiagnostics.SHELL_R0009({ message: "[vitehub] Shell provider does not support long-running processes." });
170
+ if (!this.driver.startProcess || !this.boundary.processes.background) throw shellErrorDiagnostics.SHELL_R0009({ message: "[vitehub] Shell driver does not support long-running processes." });
131
171
  if (!options.budgetCharged) options.budget?.recordToolCall(new TextEncoder().encode(command).byteLength);
132
172
  const maxProcesses = this.policy.maxProcesses;
133
173
  if (maxProcesses !== void 0 && this.#processes.size + this.#starts.size >= maxProcesses) throw shellErrorDiagnostics.SHELL_R0010({ message: `[vitehub] Shell session process budget exhausted after ${this.policy.maxProcesses} processes.` });
@@ -139,26 +179,50 @@ var RuntimeShellSession = class {
139
179
  });
140
180
  this.#starts.add(start);
141
181
  start.finally(() => this.#starts.delete(start));
142
- let process;
182
+ const timeout = this.boundary.timeout.enforcedBy === "runtime" ? options.timeout : void 0;
183
+ const controller = timeout === void 0 ? void 0 : new AbortController();
184
+ let stop;
185
+ let timer;
186
+ let cancelStart;
187
+ const cancelled = new Promise((_, reject) => {
188
+ cancelStart = (error) => {
189
+ reject(error);
190
+ controller?.abort(error);
191
+ };
192
+ });
193
+ if (timeout !== void 0) {
194
+ timer = setTimeout(() => {
195
+ if (stop) stop().catch(() => {});
196
+ else cancelStart(shellErrorDiagnostics.SHELL_R0024({ message: `[vitehub] Shell process start timed out after ${timeout}ms.` }));
197
+ }, timeout);
198
+ this.#cancelStarts.add(cancelStart);
199
+ }
200
+ let starting;
201
+ let started;
143
202
  try {
144
- process = await this.provider.startProcess(command, {
203
+ starting = this.driver.startProcess(command, {
145
204
  ...options,
146
- signal,
205
+ signal: controller ? signal ? AbortSignal.any([signal, controller.signal]) : controller.signal : signal,
147
206
  env: {
148
207
  ...this.env,
149
208
  ...options.env
150
- },
151
- timeout: options.timeout ?? this.policy.timeout
209
+ }
152
210
  });
211
+ started = await (controller ? Promise.race([starting, cancelled]) : starting);
153
212
  } catch (error) {
213
+ clearTimeout(timer);
154
214
  finishStart();
215
+ if (controller?.signal.aborted) starting?.then((late) => late.stop()).catch(() => {});
155
216
  throw error;
217
+ } finally {
218
+ this.#cancelStarts.delete(cancelStart);
156
219
  }
157
220
  let stopTask;
158
221
  let trackedProcess;
159
- const stop = () => {
222
+ stop = () => {
223
+ clearTimeout(timer);
160
224
  if (stopTask) return stopTask;
161
- stopTask = Promise.resolve().then(() => process.stop()).then((result) => {
225
+ stopTask = Promise.resolve().then(() => started.stop()).then((result) => {
162
226
  this.#processes.delete(trackedProcess);
163
227
  return applyOutputLimit(result, options.maxOutputLength);
164
228
  }, (error) => {
@@ -169,13 +233,13 @@ var RuntimeShellSession = class {
169
233
  };
170
234
  trackedProcess = {
171
235
  get id() {
172
- return process.id;
236
+ return started.id;
173
237
  },
174
238
  get command() {
175
- return process.command;
239
+ return started.command;
176
240
  },
177
241
  get cwd() {
178
- return process.cwd;
242
+ return started.cwd;
179
243
  },
180
244
  stop
181
245
  };
@@ -183,7 +247,7 @@ var RuntimeShellSession = class {
183
247
  finishStart();
184
248
  if (this.#disposed) {
185
249
  try {
186
- await stop();
250
+ await trackedProcess.stop();
187
251
  } catch (error) {
188
252
  throw new AggregateError([shellErrorDiagnostics.SHELL_R0011({ message: shellSessionDisposedMessage }), error], "[vitehub] Shell session was disposed while starting a background process, and stopping it failed.");
189
253
  }
@@ -198,6 +262,7 @@ var RuntimeShellSession = class {
198
262
  this.#disposed = true;
199
263
  if (this.#disposeTask) return this.#disposeTask;
200
264
  this.#disposeTask = (async () => {
265
+ for (const cancel of this.#cancelStarts) cancel(shellErrorDiagnostics.SHELL_R0012({ message: shellSessionDisposedMessage }));
201
266
  await Promise.all(this.#starts);
202
267
  const failures = [];
203
268
  for (const process of [...this.#processes].reverse()) try {
@@ -221,18 +286,18 @@ var RuntimeShellSession = class {
221
286
  }
222
287
  };
223
288
  function createShellRuntime(options) {
224
- const { provider } = options;
289
+ const { driver } = options;
225
290
  const policy = { ...options.policy ?? {} };
226
291
  return {
227
- boundary: provider.boundary,
292
+ boundary: driver.boundary,
228
293
  createSession(sessionOptions = {}) {
229
- return new RuntimeShellSession(provider, {
294
+ return new RuntimeShellSession(driver, {
230
295
  ...policy,
231
296
  ...sessionOptions.policy
232
297
  }, sessionOptions.env);
233
298
  },
234
299
  async exec(command, execOptions = {}) {
235
- const session = new RuntimeShellSession(provider, policy);
300
+ const session = new RuntimeShellSession(driver, policy);
236
301
  try {
237
302
  return await session.exec(command, execOptions);
238
303
  } finally {
@@ -7,9 +7,9 @@ interface ShellRuntimeExecOptions {
7
7
  budgetCharged?: boolean;
8
8
  cwd?: string;
9
9
  env?: Record<string, string>;
10
- /** Abort the command and any provider-owned work, such as a Source request. */
10
+ /** Abort the command and any driver-owned work, such as a Source request. */
11
11
  signal?: AbortSignal;
12
- /** A provider may enforce this before buffering output. The runtime always enforces its policy limit. */
12
+ /** A driver may enforce this before buffering output. The runtime always enforces its policy limit. */
13
13
  maxOutputLength?: number;
14
14
  onStderr?: (data: string) => void;
15
15
  onStdout?: (data: string) => void;
@@ -70,12 +70,12 @@ interface ShellBoundary {
70
70
  enforcedBy: "provider" | "runtime" | "unsupported";
71
71
  supported: boolean;
72
72
  };
73
- /** Provider execution details that callers can inspect without knowing the host implementation. */
73
+ /** Driver execution details that callers can inspect without knowing the host implementation. */
74
74
  execution?: {
75
75
  isolation: "in_process" | "process" | "provider_managed" | "unknown";
76
76
  model: "virtual" | "host" | "unknown";
77
77
  };
78
- /** Resource controls that this provider can enforce before buffering work. */
78
+ /** Resource controls that this driver can enforce before buffering work. */
79
79
  resources?: {
80
80
  output: {
81
81
  enforcedBy: "provider" | "runtime" | "unsupported";
@@ -89,7 +89,7 @@ interface ShellProcess {
89
89
  readonly cwd?: string;
90
90
  stop(): Promise<ShellObservation>;
91
91
  }
92
- interface ShellExecutionProvider {
92
+ interface ShellDriver {
93
93
  analyze?: (command: string, options?: ShellAnalyzeOptions) => Promise<ShellAnalyzeResult>;
94
94
  boundary: ShellBoundary;
95
95
  exec(command: string, options?: ShellRuntimeExecOptions): Promise<ShellObservation>;
@@ -110,7 +110,8 @@ interface ShellRuntime {
110
110
  exec(command: string, options?: ShellRuntimeExecOptions): Promise<ShellObservation>;
111
111
  }
112
112
  interface CreateShellRuntimeOptions {
113
- provider: ShellExecutionProvider;
113
+ /** The driver that runs commands, such as `createJustBashDriver()`. */
114
+ driver: ShellDriver;
114
115
  policy?: ShellSessionPolicy;
115
116
  }
116
117
  interface CreateShellSessionOptions {
@@ -118,4 +119,4 @@ interface CreateShellSessionOptions {
118
119
  policy?: ShellSessionPolicy;
119
120
  }
120
121
  //#endregion
121
- export { ShellBoundary as a, ShellObservationEvent as c, ShellRuntimeExecOptions as d, ShellSession as f, ShellAnalyzeResult as i, ShellProcess as l, CreateShellSessionOptions as n, ShellExecutionProvider as o, ShellSessionPolicy as p, ShellAnalyzeOptions as r, ShellObservation as s, CreateShellRuntimeOptions as t, ShellRuntime as u };
122
+ export { ShellBoundary as a, ShellObservationEvent as c, ShellRuntimeExecOptions as d, ShellSession as f, ShellAnalyzeResult as i, ShellProcess as l, CreateShellSessionOptions as n, ShellDriver as o, ShellSessionPolicy as p, ShellAnalyzeOptions as r, ShellObservation as s, CreateShellRuntimeOptions as t, ShellRuntime as u };