@vite-hub/shell 0.0.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,310 @@
1
+ import { r as shellErrorDiagnostics, t as analyzeShellCommand } from "./analyze-kSc2pmy2.js";
2
+ //#region src/runtime/session.ts
3
+ function applyOutputLimit(result, maxLength) {
4
+ const limit = normalizeLimit(maxLength);
5
+ if (limit === void 0) return result;
6
+ const next = {
7
+ command: result.command,
8
+ cwd: result.cwd,
9
+ durationMs: result.durationMs,
10
+ event: result.event,
11
+ exitCode: result.exitCode,
12
+ maxOutputLength: limit,
13
+ outputTruncated: result.outputTruncated,
14
+ stderr: result.stderr,
15
+ stdout: result.stdout,
16
+ timedOut: result.timedOut,
17
+ workspaceGuardrail: result.workspaceGuardrail
18
+ };
19
+ let truncated = false;
20
+ if (next.stdout.length > limit) {
21
+ next.stdout = `${next.stdout.slice(0, limit)}\n[output truncated to ${limit} characters]\n`;
22
+ truncated = true;
23
+ }
24
+ if (next.stderr.length > limit) {
25
+ next.stderr = `${next.stderr.slice(0, limit)}\n[output truncated to ${limit} characters]\n`;
26
+ truncated = true;
27
+ }
28
+ return truncated ? {
29
+ ...next,
30
+ outputTruncated: true
31
+ } : next;
32
+ }
33
+ function normalizeLimit(value) {
34
+ if (value === void 0) return void 0;
35
+ if (value === Number.POSITIVE_INFINITY) return void 0;
36
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
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
+ }
46
+ function limitOutputOptions(options, policy) {
47
+ const maxOutputLength = lowerLimit(options.maxOutputLength, policy.maxOutputLength);
48
+ let stdoutRemaining = maxOutputLength;
49
+ let stderrRemaining = maxOutputLength;
50
+ const limitedCallback = (callback, remaining, consume) => callback && ((data) => {
51
+ const limit = remaining();
52
+ if (limit === void 0) return callback(data);
53
+ if (limit <= 0) return;
54
+ const chunk = data.slice(0, limit);
55
+ consume(chunk.length);
56
+ if (chunk) callback(chunk);
57
+ });
58
+ return {
59
+ ...options,
60
+ maxOutputLength,
61
+ timeout: lowerLimit(options.timeout, policy.timeout),
62
+ onStdout: limitedCallback(options.onStdout, () => stdoutRemaining, (value) => {
63
+ stdoutRemaining = Math.max(0, (stdoutRemaining ?? 0) - value);
64
+ }),
65
+ onStderr: limitedCallback(options.onStderr, () => stderrRemaining, (value) => {
66
+ stderrRemaining = Math.max(0, (stderrRemaining ?? 0) - value);
67
+ })
68
+ };
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
+ }
102
+ function createPolicyObservation(command, cwd, message) {
103
+ return {
104
+ command,
105
+ cwd,
106
+ event: "policy_denied",
107
+ exitCode: 126,
108
+ stderr: message.endsWith("\n") ? message : `${message}\n`,
109
+ stdout: ""
110
+ };
111
+ }
112
+ const shellSessionDisposedMessage = "[vitehub] Shell session is disposed.";
113
+ var RuntimeShellSession = class {
114
+ driver;
115
+ env;
116
+ boundary;
117
+ policy;
118
+ #disposed = false;
119
+ #disposeTask;
120
+ #processes = /* @__PURE__ */ new Set();
121
+ #starts = /* @__PURE__ */ new Set();
122
+ #cancelStarts = /* @__PURE__ */ new Set();
123
+ #shellCalls = 0;
124
+ constructor(driver, policy, env) {
125
+ this.driver = driver;
126
+ this.env = env;
127
+ this.boundary = driver.boundary;
128
+ this.policy = policy;
129
+ }
130
+ async analyze(command, options) {
131
+ return await (this.driver.analyze ?? analyzeShellCommand).call(this.driver, command, options);
132
+ }
133
+ async exec(command, options = {}) {
134
+ if (this.#disposed) return createPolicyObservation(command, options.cwd, shellSessionDisposedMessage);
135
+ if (!options.budgetCharged) options.budget?.recordToolCall(new TextEncoder().encode(command).byteLength);
136
+ 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.`);
137
+ this.#shellCalls += 1;
138
+ const started = Date.now();
139
+ options = limitOutputOptions(options, this.policy);
140
+ const maxOutputLength = options.maxOutputLength;
141
+ const signal = options.budget && options.signal && options.signal !== options.budget.signal ? AbortSignal.any([options.signal, options.budget.signal]) : options.budget?.signal ?? options.signal;
142
+ const execOptions = {
143
+ ...options,
144
+ env: {
145
+ ...this.env,
146
+ ...options.env
147
+ },
148
+ maxOutputLength,
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);
152
+ options.budget?.recordOutputBytes(new TextEncoder().encode(result.stdout).byteLength + new TextEncoder().encode(result.stderr).byteLength);
153
+ const timedOut = result.timedOut;
154
+ return applyOutputLimit({
155
+ command: result.command ?? command,
156
+ cwd: result.cwd ?? options.cwd,
157
+ durationMs: result.durationMs ?? Date.now() - started,
158
+ event: timedOut ? "command_timed_out" : result.event,
159
+ exitCode: result.exitCode,
160
+ maxOutputLength: result.maxOutputLength,
161
+ outputTruncated: result.outputTruncated,
162
+ stderr: result.stderr,
163
+ stdout: result.stdout,
164
+ timedOut,
165
+ workspaceGuardrail: result.workspaceGuardrail
166
+ }, maxOutputLength);
167
+ }
168
+ async startProcess(command, options = {}) {
169
+ if (this.#disposed) throw shellErrorDiagnostics.SHELL_R0008({ message: shellSessionDisposedMessage });
170
+ if (!this.driver.startProcess || !this.boundary.processes.background) throw shellErrorDiagnostics.SHELL_R0009({ message: "[vitehub] Shell driver does not support long-running processes." });
171
+ if (!options.budgetCharged) options.budget?.recordToolCall(new TextEncoder().encode(command).byteLength);
172
+ const maxProcesses = this.policy.maxProcesses;
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.` });
174
+ options = limitOutputOptions(options, this.policy);
175
+ const signal = options.budget && options.signal && options.signal !== options.budget.signal ? AbortSignal.any([options.signal, options.budget.signal]) : options.budget?.signal ?? options.signal;
176
+ let finishStart;
177
+ const start = new Promise((resolve) => {
178
+ finishStart = resolve;
179
+ });
180
+ this.#starts.add(start);
181
+ start.finally(() => this.#starts.delete(start));
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;
202
+ try {
203
+ starting = this.driver.startProcess(command, {
204
+ ...options,
205
+ signal: controller ? signal ? AbortSignal.any([signal, controller.signal]) : controller.signal : signal,
206
+ env: {
207
+ ...this.env,
208
+ ...options.env
209
+ }
210
+ });
211
+ started = await (controller ? Promise.race([starting, cancelled]) : starting);
212
+ } catch (error) {
213
+ clearTimeout(timer);
214
+ finishStart();
215
+ if (controller?.signal.aborted) starting?.then((late) => late.stop()).catch(() => {});
216
+ throw error;
217
+ } finally {
218
+ this.#cancelStarts.delete(cancelStart);
219
+ }
220
+ let stopTask;
221
+ let trackedProcess;
222
+ stop = () => {
223
+ clearTimeout(timer);
224
+ if (stopTask) return stopTask;
225
+ stopTask = Promise.resolve().then(() => started.stop()).then((result) => {
226
+ this.#processes.delete(trackedProcess);
227
+ return applyOutputLimit(result, options.maxOutputLength);
228
+ }, (error) => {
229
+ stopTask = void 0;
230
+ throw error;
231
+ });
232
+ return stopTask;
233
+ };
234
+ trackedProcess = {
235
+ get id() {
236
+ return started.id;
237
+ },
238
+ get command() {
239
+ return started.command;
240
+ },
241
+ get cwd() {
242
+ return started.cwd;
243
+ },
244
+ stop
245
+ };
246
+ this.#processes.add(trackedProcess);
247
+ finishStart();
248
+ if (this.#disposed) {
249
+ try {
250
+ await trackedProcess.stop();
251
+ } catch (error) {
252
+ throw new AggregateError([shellErrorDiagnostics.SHELL_R0011({ message: shellSessionDisposedMessage }), error], "[vitehub] Shell session was disposed while starting a background process, and stopping it failed.");
253
+ }
254
+ throw shellErrorDiagnostics.SHELL_R0012({ message: shellSessionDisposedMessage });
255
+ }
256
+ return trackedProcess;
257
+ }
258
+ async listProcesses() {
259
+ return [...this.#processes];
260
+ }
261
+ dispose() {
262
+ this.#disposed = true;
263
+ if (this.#disposeTask) return this.#disposeTask;
264
+ this.#disposeTask = (async () => {
265
+ for (const cancel of this.#cancelStarts) cancel(shellErrorDiagnostics.SHELL_R0012({ message: shellSessionDisposedMessage }));
266
+ await Promise.all(this.#starts);
267
+ const failures = [];
268
+ for (const process of [...this.#processes].reverse()) try {
269
+ await process.stop();
270
+ } catch (error) {
271
+ failures.push(error);
272
+ }
273
+ if (failures.length === 1) throw failures[0];
274
+ if (failures.length > 1) throw new AggregateError(failures, "[vitehub] Shell session failed to stop multiple background processes.");
275
+ return {
276
+ event: "session_disposed",
277
+ exitCode: null,
278
+ stderr: "",
279
+ stdout: ""
280
+ };
281
+ })().catch((error) => {
282
+ this.#disposeTask = void 0;
283
+ throw error;
284
+ });
285
+ return this.#disposeTask;
286
+ }
287
+ };
288
+ function createShellRuntime(options) {
289
+ const { driver } = options;
290
+ const policy = { ...options.policy ?? {} };
291
+ return {
292
+ boundary: driver.boundary,
293
+ createSession(sessionOptions = {}) {
294
+ return new RuntimeShellSession(driver, {
295
+ ...policy,
296
+ ...sessionOptions.policy
297
+ }, sessionOptions.env);
298
+ },
299
+ async exec(command, execOptions = {}) {
300
+ const session = new RuntimeShellSession(driver, policy);
301
+ try {
302
+ return await session.exec(command, execOptions);
303
+ } finally {
304
+ await session.dispose();
305
+ }
306
+ }
307
+ };
308
+ }
309
+ //#endregion
310
+ export { createShellRuntime as t };
@@ -1,8 +1,16 @@
1
+ import { ExecutionBudget } from "@vite-hub/runtime";
1
2
  //#region src/runtime/types.d.ts
2
3
  type ShellObservationEvent = "command_finished" | "command_timed_out" | "policy_denied" | "session_disposed";
3
4
  interface ShellRuntimeExecOptions {
5
+ budget?: ExecutionBudget;
6
+ /** Set when the caller already charged this command against the budget. */
7
+ budgetCharged?: boolean;
4
8
  cwd?: string;
5
9
  env?: Record<string, string>;
10
+ /** Abort the command and any driver-owned work, such as a Source request. */
11
+ signal?: AbortSignal;
12
+ /** A driver may enforce this before buffering output. The runtime always enforces its policy limit. */
13
+ maxOutputLength?: number;
6
14
  onStderr?: (data: string) => void;
7
15
  onStdout?: (data: string) => void;
8
16
  stdin?: string;
@@ -62,14 +70,26 @@ interface ShellBoundary {
62
70
  enforcedBy: "provider" | "runtime" | "unsupported";
63
71
  supported: boolean;
64
72
  };
73
+ /** Driver execution details that callers can inspect without knowing the host implementation. */
74
+ execution?: {
75
+ isolation: "in_process" | "process" | "provider_managed" | "unknown";
76
+ model: "virtual" | "host" | "unknown";
77
+ };
78
+ /** Resource controls that this driver can enforce before buffering work. */
79
+ resources?: {
80
+ output: {
81
+ enforcedBy: "provider" | "runtime" | "unsupported";
82
+ unit: "characters";
83
+ };
84
+ };
65
85
  }
66
86
  interface ShellProcess {
67
- id: string;
68
- command: string;
69
- cwd?: string;
87
+ readonly id: string;
88
+ readonly command: string;
89
+ readonly cwd?: string;
70
90
  stop(): Promise<ShellObservation>;
71
91
  }
72
- interface ShellExecutionProvider {
92
+ interface ShellDriver {
73
93
  analyze?: (command: string, options?: ShellAnalyzeOptions) => Promise<ShellAnalyzeResult>;
74
94
  boundary: ShellBoundary;
75
95
  exec(command: string, options?: ShellRuntimeExecOptions): Promise<ShellObservation>;
@@ -90,7 +110,8 @@ interface ShellRuntime {
90
110
  exec(command: string, options?: ShellRuntimeExecOptions): Promise<ShellObservation>;
91
111
  }
92
112
  interface CreateShellRuntimeOptions {
93
- provider: ShellExecutionProvider;
113
+ /** The driver that runs commands, such as `createJustBashDriver()`. */
114
+ driver: ShellDriver;
94
115
  policy?: ShellSessionPolicy;
95
116
  }
96
117
  interface CreateShellSessionOptions {
@@ -98,4 +119,4 @@ interface CreateShellSessionOptions {
98
119
  policy?: ShellSessionPolicy;
99
120
  }
100
121
  //#endregion
101
- 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 };
@@ -1,7 +1,7 @@
1
- import { o as ShellExecutionProvider, s as ShellObservation } from "./types-CNRdehmi.js";
2
- import { r as ShellNetworkGrantExecutor } from "./just-bash-D84udCFy.js";
1
+ import { o as ShellDriver, s as ShellObservation } from "./types-wPMXgnB0.js";
2
+ import { a as ShellNetworkGrantExecutor } from "./just-bash-CHpGR1dZ.js";
3
+ import { ExecutionBudget } from "@vite-hub/runtime";
3
4
  import { IFileSystem } from "just-bash";
4
-
5
5
  //#region src/workspace/types.d.ts
6
6
  type ShellContent = string | Uint8Array;
7
7
  interface ShellReadFileOptions {
@@ -47,7 +47,7 @@ interface SearchableShellWorkspace extends ReadonlyShellWorkspace {
47
47
  search(query: ShellSearchQuery): Promise<ShellSearchHit[]>;
48
48
  }
49
49
  interface WritableShellWorkspace extends ReadonlyShellWorkspace {
50
- writeFile(path: string, content: ShellContent): Promise<void>;
50
+ writeFile(path: string, content: ShellContent): Promise<unknown>;
51
51
  mkdir(path: string, options?: ShellMkdirOptions): Promise<void>;
52
52
  rm(path: string, options?: ShellRmOptions): Promise<void>;
53
53
  }
@@ -56,25 +56,28 @@ interface WritableShellWorkspace extends ReadonlyShellWorkspace {
56
56
  interface WorkspaceShellFileSystem extends IFileSystem {
57
57
  readonly writeFs: boolean;
58
58
  }
59
- declare const workspaceMountPoint = "/workspace";
60
- declare function createReadonlyWorkspaceFs(workspace: ReadonlyShellWorkspace): WorkspaceShellFileSystem;
61
- declare function createWritableWorkspaceFs(workspace: WritableShellWorkspace): WorkspaceShellFileSystem;
59
+ export declare const workspaceMountPoint = "/workspace";
60
+ export declare function createReadonlyWorkspaceFs(workspace: ReadonlyShellWorkspace): WorkspaceShellFileSystem;
61
+ export declare function createWritableWorkspaceFs(workspace: WritableShellWorkspace): WorkspaceShellFileSystem;
62
62
  //#endregion
63
63
  //#region src/workspace/inspection.d.ts
64
64
  interface WorkspaceInspectionCommandOptions {
65
+ budget?: ExecutionBudget;
66
+ budgetCharged?: boolean;
65
67
  broadSearchPaths?: string[];
66
68
  commands?: string[];
67
69
  cwd?: string;
68
70
  fs: WorkspaceShellFileSystem;
69
71
  maxOutputLength?: number;
70
72
  networkGrants?: ShellNetworkGrantExecutor;
71
- provider?: ShellExecutionProvider;
73
+ driver?: ShellDriver;
74
+ signal?: AbortSignal;
72
75
  timeout?: number;
73
76
  }
74
- declare function runWorkspaceInspectionCommand(_input: SearchableShellWorkspace, command: string, options: WorkspaceInspectionCommandOptions): Promise<ShellObservation>;
77
+ export declare function runWorkspaceInspectionCommand(_input: SearchableShellWorkspace, command: string, options: WorkspaceInspectionCommandOptions): Promise<ShellObservation>;
75
78
  //#endregion
76
79
  //#region src/workspace/path.d.ts
77
- declare function cleanWorkspaceShellPath(path?: string): string;
78
- declare function cleanWorkspaceMutationPath(path: string): string;
80
+ export declare function cleanWorkspaceShellPath(path?: string): string;
81
+ export declare function cleanWorkspaceMutationPath(path: string): string;
79
82
  //#endregion
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 };
83
+ export type { ReadonlyShellWorkspace, SearchableShellWorkspace, ShellContent, ShellEntry, ShellListOptions, ShellMkdirOptions, ShellReadFileOptions, ShellRmOptions, ShellSearchHit, ShellSearchQuery, ShellStat, WorkspaceShellFileSystem, WritableShellWorkspace };