@vite-hub/shell 0.0.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/workspace.js CHANGED
@@ -1,21 +1,41 @@
1
- import { t as createShellRuntime } from "./session-0OrrlmE9.js";
2
- import { createJustBashProvider } from "./providers/just-bash.js";
1
+ import { n as splitShellCommandSegments, r as shellErrorDiagnostics } from "./analyze-kSc2pmy2.js";
2
+ import { t as createShellRuntime } from "./session-DjjZUIPE.js";
3
+ import { createJustBashDriver } from "./providers/just-bash.js";
4
+ import { Buffer } from "node:buffer";
3
5
  import { posix } from "node:path";
4
6
  //#region src/workspace/filesystem.ts
5
7
  const workspaceMountPoint = "/workspace";
6
8
  function createEscapeError(path) {
7
- return /* @__PURE__ */ new Error(`[vitehub] Workspace path escapes the workspace root: "${path}".`);
9
+ return shellErrorDiagnostics.SHELL_R0013({ message: `[vitehub] Workspace path escapes the workspace root: "${path}".` });
8
10
  }
9
11
  function createReadonlyError() {
10
- return /* @__PURE__ */ new Error("[vitehub] Workspace filesystem is read-only.");
12
+ return shellErrorDiagnostics.SHELL_R0014({ message: "[vitehub] Workspace filesystem is read-only." });
11
13
  }
12
- function toShellContent(content) {
13
- return typeof content === "string" ? new TextEncoder().encode(content) : content;
14
+ function toShellContent(content, encoding) {
15
+ if (typeof content !== "string") return content;
16
+ if (encoding === "base64") {
17
+ const decoded = atob(content);
18
+ const bytes = new Uint8Array(decoded.length);
19
+ for (let index = 0; index < decoded.length; index++) bytes[index] = decoded.charCodeAt(index);
20
+ return bytes;
21
+ }
22
+ if (encoding === "hex") {
23
+ const bytes = new Uint8Array(content.length / 2);
24
+ for (let index = 0; index < content.length; index += 2) bytes[index / 2] = Number.parseInt(content.slice(index, index + 2), 16);
25
+ return bytes;
26
+ }
27
+ if (encoding === "binary" || encoding === "latin1") {
28
+ if (content.length <= 65536) return Uint8Array.from(content, (char) => char.charCodeAt(0));
29
+ const bytes = new Uint8Array(content.length);
30
+ for (let index = 0; index < content.length; index++) bytes[index] = content.charCodeAt(index);
31
+ return bytes;
32
+ }
33
+ return new TextEncoder().encode(content);
14
34
  }
15
35
  function decodeContent(content, encoding) {
16
36
  if (encoding === "base64") return Buffer.from(content).toString("base64");
17
37
  if (encoding === "hex") return Buffer.from(content).toString("hex");
18
- if (encoding === "ascii" || encoding === "latin1") return Buffer.from(content).toString(encoding);
38
+ if (encoding === "latin1" || encoding === "binary") return Buffer.from(content).toString(encoding);
19
39
  return new TextDecoder().decode(content);
20
40
  }
21
41
  function normalizeInputPath(path) {
@@ -58,6 +78,7 @@ var WorkspaceFileSystem = class {
58
78
  writeFs;
59
79
  #paths = [workspaceMountPoint];
60
80
  #refreshPromise;
81
+ #refreshAgain = false;
61
82
  constructor(workspace, writeFs) {
62
83
  this.workspace = workspace;
63
84
  this.writeFs = writeFs;
@@ -69,15 +90,20 @@ var WorkspaceFileSystem = class {
69
90
  const relativePath = this.#toRelativePath(path);
70
91
  return toShellContent(await this.workspace.readFile(relativePath, { encoding: "binary" }));
71
92
  }
72
- async writeFile(path, content, _options) {
73
- await this.#requireWritable().writeFile(this.#toRelativePath(path), content);
93
+ async writeFile(path, content, options) {
94
+ const workspace = this.#requireWritable();
95
+ const encoding = typeof options === "string" ? options : options?.encoding;
96
+ await workspace.writeFile(this.#toRelativePath(path), encoding ? toShellContent(content, encoding) : content);
74
97
  await this.#refreshPaths();
75
98
  }
76
- async appendFile(path, content, _options) {
99
+ async appendFile(path, content, options) {
77
100
  const workspace = this.#requireWritable();
78
101
  const relativePath = this.#toRelativePath(path);
79
- const current = toShellContent(await workspace.readFile(relativePath, { encoding: "binary" }).catch(() => new Uint8Array()));
80
- const next = toShellContent(content);
102
+ const current = toShellContent(await workspace.readFile(relativePath, { encoding: "binary" }).catch(async (error) => {
103
+ if (await workspace.exists(relativePath)) throw error;
104
+ return /* @__PURE__ */ new Uint8Array();
105
+ }));
106
+ const next = toShellContent(content, typeof options === "string" ? options : options?.encoding);
81
107
  const merged = new Uint8Array(current.byteLength + next.byteLength);
82
108
  merged.set(current, 0);
83
109
  merged.set(next, current.byteLength);
@@ -87,21 +113,28 @@ var WorkspaceFileSystem = class {
87
113
  async exists(path) {
88
114
  try {
89
115
  const relativePath = this.#toRelativePath(path);
116
+ if (!relativePath) return true;
90
117
  return await this.workspace.exists(relativePath);
91
118
  } catch {
92
119
  return false;
93
120
  }
94
121
  }
95
122
  async stat(path) {
96
- const absolutePath = this.#resolveFromRoot(path);
97
- if (absolutePath === "/workspace") return statFromEntry({
123
+ const relativePath = this.#toRelativePath(path);
124
+ if (!relativePath) return statFromEntry({
98
125
  path: "",
99
126
  type: "directory"
100
127
  });
101
- return statFromEntry(await this.workspace.stat(this.#toRelativePath(absolutePath)));
128
+ return statFromEntry(await this.workspace.stat(relativePath));
102
129
  }
103
130
  async mkdir(path, options) {
104
- await this.#requireWritable().mkdir(this.#toRelativePath(path), { recursive: options?.recursive });
131
+ const workspace = this.#requireWritable();
132
+ const relativePath = this.#toRelativePath(path);
133
+ if (!relativePath) {
134
+ if (options?.recursive) return;
135
+ throw shellErrorDiagnostics.SHELL_R0023({ message: `[vitehub] Workspace directory already exists: "${path}".` });
136
+ }
137
+ await workspace.mkdir(relativePath, { recursive: options?.recursive });
105
138
  await this.#refreshPaths();
106
139
  }
107
140
  async readdir(path) {
@@ -133,8 +166,14 @@ var WorkspaceFileSystem = class {
133
166
  }
134
167
  async mv(src, dest) {
135
168
  const workspace = this.#requireWritable();
136
- const from = this.#toRelativePath(src);
137
- await copyWorkspacePath(workspace, from, this.#toRelativePath(dest));
169
+ const from = this.#toRelativePath(src).replace(/\/$/, "");
170
+ const to = this.#toRelativePath(dest).replace(/\/$/, "");
171
+ if (from === to) {
172
+ if (from) await workspace.stat(from);
173
+ return;
174
+ }
175
+ if (!from || to.startsWith(`${from}/`)) throw shellErrorDiagnostics.SHELL_R0022({ message: `[vitehub] Cannot move Workspace path "${src}" into itself, "${dest}".` });
176
+ await copyWorkspacePath(workspace, from, to);
138
177
  await workspace.rm(from, {
139
178
  recursive: true,
140
179
  force: true
@@ -155,16 +194,16 @@ var WorkspaceFileSystem = class {
155
194
  return [...this.#paths];
156
195
  }
157
196
  async chmod(_path, _mode) {
158
- throw new Error("chmod is not supported by the workspace filesystem.");
197
+ throw shellErrorDiagnostics.SHELL_R0015({ message: "chmod is not supported by the workspace filesystem." });
159
198
  }
160
199
  async symlink(_target, _linkPath) {
161
- throw new Error("symlink is not supported by the workspace filesystem.");
200
+ throw shellErrorDiagnostics.SHELL_R0016({ message: "symlink is not supported by the workspace filesystem." });
162
201
  }
163
202
  async link(_existingPath, _newPath) {
164
- throw new Error("link is not supported by the workspace filesystem.");
203
+ throw shellErrorDiagnostics.SHELL_R0017({ message: "link is not supported by the workspace filesystem." });
165
204
  }
166
205
  async readlink(_path) {
167
- throw new Error("readlink is not supported by the workspace filesystem.");
206
+ throw shellErrorDiagnostics.SHELL_R0018({ message: "readlink is not supported by the workspace filesystem." });
168
207
  }
169
208
  async lstat(path) {
170
209
  return await this.stat(path);
@@ -173,7 +212,7 @@ var WorkspaceFileSystem = class {
173
212
  return this.#resolveFromRoot(path);
174
213
  }
175
214
  async utimes(_path, _atime, _mtime) {
176
- throw new Error("utimes is not supported by the workspace filesystem.");
215
+ throw shellErrorDiagnostics.SHELL_R0019({ message: "utimes is not supported by the workspace filesystem." });
177
216
  }
178
217
  #requireWritable() {
179
218
  if (!this.writeFs) throw createReadonlyError();
@@ -192,18 +231,22 @@ var WorkspaceFileSystem = class {
192
231
  #toRelativePath(path) {
193
232
  const absolutePath = this.#resolveFromRoot(path);
194
233
  if (absolutePath === "/workspace") return "";
195
- return absolutePath.slice(`${workspaceMountPoint}/`.length);
234
+ return absolutePath.slice(`${workspaceMountPoint}/`.length).replace(/\/$/, "");
196
235
  }
197
236
  async #refreshPaths() {
198
- this.#refreshPromise ||= (async () => {
199
- const entries = await this.workspace.list("", { recursive: true });
200
- this.#paths = [workspaceMountPoint, ...entries.map((entry) => entry.path ? `${workspaceMountPoint}/${entry.path}` : workspaceMountPoint).sort((left, right) => left.localeCompare(right))];
201
- })();
202
- try {
203
- await this.#refreshPromise;
204
- } finally {
205
- this.#refreshPromise = void 0;
206
- }
237
+ this.#refreshAgain = true;
238
+ this.#refreshPromise ||= Promise.resolve().then(async () => {
239
+ try {
240
+ do {
241
+ this.#refreshAgain = false;
242
+ const entries = await this.workspace.list("", { recursive: true });
243
+ this.#paths = [workspaceMountPoint, ...entries.map((entry) => entry.path ? `${workspaceMountPoint}/${entry.path}` : workspaceMountPoint).sort((left, right) => left.localeCompare(right))];
244
+ } while (this.#refreshAgain);
245
+ } finally {
246
+ this.#refreshPromise = void 0;
247
+ }
248
+ });
249
+ await this.#refreshPromise;
207
250
  }
208
251
  };
209
252
  function createReadonlyWorkspaceFs(workspace) {
@@ -214,16 +257,12 @@ function createWritableWorkspaceFs(workspace) {
214
257
  }
215
258
  //#endregion
216
259
  //#region src/workspace/command-analysis.ts
217
- function analyzeWorkspaceInspectionCommand(command) {
218
- return splitShellCommandSegments(command).map((segment) => {
219
- const words = parseShellWords(segment.command);
220
- return {
221
- ...segment,
222
- paths: shellPathArguments(words),
223
- searchRecursive: hasRecursiveGrepFlag(words),
224
- words
225
- };
226
- });
260
+ async function analyzeWorkspaceInspectionCommand(command) {
261
+ return (await splitShellCommandSegments(command)).map((segment) => ({
262
+ ...segment,
263
+ paths: shellPathArguments(segment.words),
264
+ searchRecursive: hasRecursiveGrepFlag(segment.words)
265
+ }));
227
266
  }
228
267
  function shellPathArguments(words) {
229
268
  switch (words[0]) {
@@ -384,75 +423,6 @@ function pathArgumentsUntilShellBoundary(args) {
384
423
  }
385
424
  return paths;
386
425
  }
387
- function splitShellCommandSegments(command) {
388
- const segments = [];
389
- let current = "";
390
- let quote;
391
- let escaped = false;
392
- let followsPipe = false;
393
- for (let index = 0; index < command.length; index++) {
394
- const char = command[index];
395
- if (escaped) {
396
- current += char;
397
- escaped = false;
398
- continue;
399
- }
400
- if (char === "\\") {
401
- current += char;
402
- escaped = true;
403
- continue;
404
- }
405
- if (quote) {
406
- if (char === quote) quote = void 0;
407
- current += char;
408
- continue;
409
- }
410
- if (char === "'" || char === "\"") {
411
- quote = char;
412
- current += char;
413
- continue;
414
- }
415
- const next = command[index + 1];
416
- if (char === "&" && next === "&") {
417
- segments.push({
418
- command: current,
419
- followsPipe,
420
- separatorAfter: "&&"
421
- });
422
- current = "";
423
- followsPipe = false;
424
- index += 1;
425
- continue;
426
- }
427
- if (char === "|" && next === "|") {
428
- segments.push({
429
- command: current,
430
- followsPipe,
431
- separatorAfter: "||"
432
- });
433
- current = "";
434
- followsPipe = false;
435
- index += 1;
436
- continue;
437
- }
438
- if (char === "|" || char === ";" || char === "\n") {
439
- segments.push({
440
- command: current,
441
- followsPipe,
442
- separatorAfter: char
443
- });
444
- current = "";
445
- followsPipe = char === "|";
446
- continue;
447
- }
448
- current += char;
449
- }
450
- segments.push({
451
- command: current,
452
- followsPipe
453
- });
454
- return segments;
455
- }
456
426
  function hasRecursiveGrepFlag(words) {
457
427
  const args = words.slice(1);
458
428
  for (let index = 0; index < args.length; index++) {
@@ -472,82 +442,65 @@ function hasRecursiveGrepFlag(words) {
472
442
  }
473
443
  return false;
474
444
  }
475
- function parseShellWords(command) {
476
- const words = [];
477
- let current = "";
478
- let quote;
479
- let escaped = false;
480
- for (const char of command) {
481
- if (escaped) {
482
- current += char;
483
- escaped = false;
484
- continue;
485
- }
486
- if (char === "\\") {
487
- escaped = true;
488
- continue;
489
- }
490
- if (quote) {
491
- if (char === quote) quote = void 0;
492
- else current += char;
493
- continue;
494
- }
495
- if (char === "'" || char === "\"") {
496
- quote = char;
497
- continue;
498
- }
499
- if (/\s/.test(char)) {
500
- if (current) {
501
- words.push(current);
502
- current = "";
503
- }
504
- continue;
505
- }
506
- current += char;
507
- }
508
- if (current) words.push(current);
509
- return words;
510
- }
511
445
  //#endregion
512
446
  //#region src/workspace/path.ts
513
447
  function cleanWorkspaceShellPath(path = ".") {
514
- const trimmed = path.trim() || ".";
515
- if (trimmed === "." || trimmed === "./" || trimmed === "/" || trimmed === "/workspace") return "";
516
- return normalizeSafeShellPath(trimmed.replace(/^\/workspace(\/|$)/, ""));
448
+ const input = path || ".";
449
+ if (input === "." || input === "./" || input === "/" || input === "/workspace") return "";
450
+ return normalizeSafeShellPath(input.replace(/^\/workspace(\/|$)/, ""));
517
451
  }
518
452
  function cleanWorkspaceMutationPath(path) {
519
453
  const normalized = cleanWorkspaceShellPath(path);
520
- if (!normalized) throw new Error("[vitehub] Workspace root is not a valid mutation target.");
454
+ if (!normalized) throw shellErrorDiagnostics.SHELL_R0020({ message: "[vitehub] Workspace root is not a valid mutation target." });
521
455
  return normalized;
522
456
  }
523
457
  function normalizeSafeShellPath(path) {
524
458
  const normalized = posix.normalize(path.replace(/\\/g, "/")).replace(/^\//, "");
525
459
  if (normalized === ".") return "";
526
- if (normalized === ".." || normalized.startsWith("../")) throw new Error(`[vitehub] Workspace path escapes the workspace root: "${path}".`);
460
+ if (normalized === ".." || normalized.startsWith("../")) throw shellErrorDiagnostics.SHELL_R0021({ message: `[vitehub] Workspace path escapes the workspace root: "${path}".` });
527
461
  return normalized;
528
462
  }
529
463
  //#endregion
530
464
  //#region src/workspace/inspection.ts
531
465
  async function runWorkspaceInspectionCommand(_input, command, options) {
532
- const maxOutputLength = options.maxOutputLength || 3e4;
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;
537
- const preflight = await preflightWorkspaceInspectionCommand(command, options.fs, options.broadSearchPaths, options.cwd);
538
- if (preflight) return preflight;
539
- const pipedBroadSearch = preflightPipedSearchWithoutPath(command, options.broadSearchPaths);
540
- if (pipedBroadSearch) return pipedBroadSearch;
541
- const missingPath = await preflightMissingWorkspacePath(command, options.fs, options.cwd);
542
- if (missingPath) return missingPath;
543
- const unsupported = preflightUnsupportedWorkspaceCommand(command, options.commands, Boolean(provider));
544
- if (unsupported) return unsupported;
466
+ throwIfAborted(options.signal);
467
+ const maxOutputLength = options.maxOutputLength === void 0 ? 3e4 : normalizeOutputLength(options.maxOutputLength);
468
+ const timeout = options.timeout ?? 3e4;
469
+ const driver = options.driver && options.networkGrants && await usesWorkspaceNetworkGrant(command) ? void 0 : options.driver;
470
+ const chargeRejected = () => {
471
+ if (!options.budgetCharged) options.budget?.recordToolCall(new TextEncoder().encode(command).byteLength);
472
+ };
473
+ const segments = await analyzeWorkspaceInspectionCommand(command);
474
+ const unsupportedSyntax = preflightUnsupportedWorkspaceSyntax(command, segments, options.commands, Boolean(driver));
475
+ if (unsupportedSyntax) {
476
+ chargeRejected();
477
+ return limitInspectionObservation(unsupportedSyntax, maxOutputLength);
478
+ }
479
+ const preflight = await withInspectionTimeout(timeout, options.signal, async (signal) => {
480
+ const broad = await preflightWorkspaceInspectionCommand(segments, options.fs, options.broadSearchPaths, options.cwd, signal);
481
+ if (broad) return broad;
482
+ return await preflightMissingWorkspacePath(command, segments, options.fs, options.cwd, signal);
483
+ }, command, options.cwd);
484
+ if (preflight) {
485
+ chargeRejected();
486
+ return limitInspectionObservation(preflight, maxOutputLength);
487
+ }
488
+ const pipedBroadSearch = preflightPipedSearchWithoutPath(segments, options.broadSearchPaths);
489
+ if (pipedBroadSearch) {
490
+ chargeRejected();
491
+ return limitInspectionObservation(pipedBroadSearch, maxOutputLength);
492
+ }
493
+ const unsupported = preflightUnsupportedWorkspaceCommand(command, segments, options.commands, Boolean(driver));
494
+ if (unsupported) {
495
+ chargeRejected();
496
+ return limitInspectionObservation(unsupported, maxOutputLength);
497
+ }
545
498
  const runtime = createShellRuntime({
546
499
  policy: {
547
500
  maxOutputLength,
548
501
  timeout
549
502
  },
550
- provider: provider ?? createJustBashProvider({
503
+ driver: driver ?? createJustBashDriver({
551
504
  commands: options.commands,
552
505
  cwd: options.cwd || "/workspace",
553
506
  fs: options.fs,
@@ -556,22 +509,93 @@ async function runWorkspaceInspectionCommand(_input, command, options) {
556
509
  });
557
510
  const cwd = options.cwd || "/workspace";
558
511
  const result = await runtime.exec(command, {
512
+ budget: options.budget,
513
+ budgetCharged: options.budgetCharged,
559
514
  cwd,
560
515
  timeout,
561
- workspacePaths: workspaceSessionPaths(command, cwd)
516
+ signal: options.signal,
517
+ workspacePaths: workspaceSessionPaths(segments, cwd)
562
518
  });
563
- const noMatchFeedback = searchNoMatchFeedback(command, result, options.broadSearchPaths, options.cwd);
564
- return noMatchFeedback ? {
519
+ const noMatchFeedback = searchNoMatchFeedback(segments, result, options.broadSearchPaths, options.cwd);
520
+ if (!noMatchFeedback) return result;
521
+ const bounded = limitInspectionFeedback(noMatchFeedback, maxOutputLength);
522
+ return {
565
523
  ...result,
566
- stdout: noMatchFeedback,
524
+ stdout: bounded.stdout,
525
+ outputTruncated: result.outputTruncated || bounded.outputTruncated,
567
526
  workspaceGuardrail: { kind: "no_match" }
568
- } : result;
527
+ };
569
528
  }
570
- function workspaceSessionPaths(command, cwd = workspaceMountPoint) {
529
+ function limitInspectionFeedback(feedback, maxLength) {
530
+ if (maxLength === void 0 || feedback.length <= maxLength) return {
531
+ stdout: feedback,
532
+ outputTruncated: false
533
+ };
534
+ return {
535
+ stdout: `${feedback.slice(0, maxLength)}\n[output truncated to ${maxLength} characters]\n`,
536
+ outputTruncated: true
537
+ };
538
+ }
539
+ function limitInspectionObservation(observation, maxLength) {
540
+ const bounded = limitInspectionFeedback(observation.stdout, maxLength);
541
+ const boundedError = limitInspectionFeedback(observation.stderr, maxLength);
542
+ if (!bounded.outputTruncated && !boundedError.outputTruncated) return observation;
543
+ return {
544
+ ...observation,
545
+ stdout: bounded.stdout,
546
+ stderr: boundedError.stdout,
547
+ outputTruncated: true
548
+ };
549
+ }
550
+ function normalizeOutputLength(value) {
551
+ if (value === void 0) return void 0;
552
+ if (value === Number.POSITIVE_INFINITY) return void 0;
553
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
554
+ }
555
+ async function withInspectionTimeout(timeout, callerSignal, run, command, cwd) {
556
+ const controller = new AbortController();
557
+ const signal = callerSignal ? AbortSignal.any([callerSignal, controller.signal]) : controller.signal;
558
+ if (!Number.isFinite(timeout) || timeout < 0) return await run(signal);
559
+ let timer;
560
+ let removeCallerAbortListener;
561
+ try {
562
+ const callerCancellation = callerSignal ? new Promise((_, reject) => {
563
+ const rejectOnAbort = () => reject(callerSignal.reason);
564
+ if (callerSignal.aborted) rejectOnAbort();
565
+ else {
566
+ callerSignal.addEventListener("abort", rejectOnAbort, { once: true });
567
+ removeCallerAbortListener = () => callerSignal.removeEventListener("abort", rejectOnAbort);
568
+ }
569
+ }) : void 0;
570
+ return await Promise.race([
571
+ run(signal),
572
+ ...callerCancellation ? [callerCancellation] : [],
573
+ new Promise((resolve) => {
574
+ timer = setTimeout(() => {
575
+ resolve({
576
+ command,
577
+ cwd,
578
+ event: "command_timed_out",
579
+ exitCode: null,
580
+ stderr: `[vitehub] Workspace shell command timed out after ${timeout}ms.`,
581
+ stdout: "",
582
+ timedOut: true,
583
+ workspaceGuardrail: { kind: "timeout" }
584
+ });
585
+ controller.abort(/* @__PURE__ */ new Error("Workspace inspection preflight timed out."));
586
+ }, timeout);
587
+ })
588
+ ]);
589
+ } finally {
590
+ if (timer) clearTimeout(timer);
591
+ removeCallerAbortListener?.();
592
+ }
593
+ }
594
+ function workspaceSessionPaths(segments, cwd = workspaceMountPoint) {
571
595
  try {
572
596
  const paths = /* @__PURE__ */ new Set();
573
597
  let currentCwd = cwd;
574
- for (const segment of analyzeWorkspaceInspectionCommand(command)) {
598
+ for (const segment of segments) {
575
599
  const words = segment.words;
576
600
  if (words[0] === "cd") {
577
601
  const path = words[1] || "/workspace";
@@ -588,9 +612,9 @@ function workspaceSessionPaths(command, cwd = workspaceMountPoint) {
588
612
  return;
589
613
  }
590
614
  }
591
- function preflightPipedSearchWithoutPath(command, broadSearchPaths = []) {
615
+ function preflightPipedSearchWithoutPath(segments, broadSearchPaths = []) {
592
616
  try {
593
- for (const segment of analyzeWorkspaceInspectionCommand(command)) {
617
+ for (const segment of segments) {
594
618
  if (segment.separatorAfter !== "|" || segment.paths.length) continue;
595
619
  const name = segment.words[0];
596
620
  if (name === "rg" || name === "grep") return broadWorkspaceSearchFeedback(broadSearchPaths);
@@ -599,82 +623,97 @@ function preflightPipedSearchWithoutPath(command, broadSearchPaths = []) {
599
623
  return;
600
624
  }
601
625
  }
602
- function usesWorkspaceNetworkGrant(command) {
626
+ async function usesWorkspaceNetworkGrant(command) {
603
627
  try {
604
- return analyzeWorkspaceInspectionCommand(command).some((segment) => workspaceExecutable(segment.words)?.name === "curl");
628
+ const { Bash } = await import("just-bash/browser");
629
+ return containsCurlCommand(new Bash({ commands: [] }).transform(command).ast);
605
630
  } catch {
606
631
  return false;
607
632
  }
608
633
  }
609
- async function preflightWorkspaceInspectionCommand(command, fs, broadSearchPaths = [], cwd = workspaceMountPoint) {
634
+ function containsCurlCommand(node) {
635
+ if ("type" in node && node.type === "SimpleCommand") {
636
+ const { name } = node;
637
+ if (name && staticCommandWord(name.parts) === "curl") return true;
638
+ }
639
+ return Object.values(node).some((value) => value && typeof value === "object" && containsCurlCommand(value));
640
+ }
641
+ function staticCommandWord(parts) {
642
+ let word = "";
643
+ for (const part of parts) if (part.type === "Literal" || part.type === "SingleQuoted" || part.type === "Escaped") word += part.value;
644
+ else if (part.type === "DoubleQuoted") {
645
+ const quoted = staticCommandWord(part.parts);
646
+ if (quoted === void 0) return void 0;
647
+ word += quoted;
648
+ } else return void 0;
649
+ return word;
650
+ }
651
+ async function preflightWorkspaceInspectionCommand(segments, fs, broadSearchPaths = [], cwd = workspaceMountPoint, signal) {
610
652
  try {
611
- let currentCwd = cwd;
612
- let skipAndChain = false;
613
- let skipOrChain = false;
614
- for (const segment of analyzeWorkspaceInspectionCommand(command)) {
615
- if (skipAndChain) {
616
- skipAndChain = segment.separatorAfter === "&&";
617
- continue;
618
- }
619
- if (skipOrChain) {
620
- skipOrChain = segment.separatorAfter === "||";
621
- continue;
622
- }
623
- const words = segment.words;
624
- if (words[0] === "cd") {
625
- const path = words[1] || "/workspace";
626
- if (!isWorkspacePathCandidate(path)) continue;
627
- const resolvedPath = resolveWorkspaceShellPath(currentCwd, path);
628
- const directory = await workspacePathIsDirectory(fs, resolvedPath);
629
- if (segment.separatorAfter === "&&" && !directory) skipAndChain = true;
630
- if (segment.separatorAfter === "||" && directory) skipOrChain = true;
631
- if (directory) currentCwd = resolvedPath ? posix.join(workspaceMountPoint, resolvedPath) : workspaceMountPoint;
632
- continue;
633
- }
634
- if (isBroadWorkspaceSearch(segment, broadSearchPaths, currentCwd)) return broadWorkspaceSearchFeedback(broadSearchPaths);
653
+ for await (const { segment, cwd: segmentCwd } of walkWorkspaceInspectionCommand(segments, fs, cwd, signal)) {
654
+ throwIfAborted(signal);
655
+ if (isBroadWorkspaceSearch(segment, broadSearchPaths, segmentCwd)) return broadWorkspaceSearchFeedback(broadSearchPaths);
635
656
  }
636
657
  } catch {
658
+ throwIfAborted(signal);
637
659
  return;
638
660
  }
639
661
  }
640
- async function preflightMissingWorkspacePath(command, fs, cwd = workspaceMountPoint) {
662
+ async function preflightMissingWorkspacePath(command, segments, fs, cwd = workspaceMountPoint, signal) {
641
663
  try {
642
- let currentCwd = cwd;
643
- let skipAndChain = false;
644
- let skipOrChain = false;
645
- for (const segment of analyzeWorkspaceInspectionCommand(command)) {
646
- if (skipAndChain) {
647
- skipAndChain = segment.separatorAfter === "&&";
648
- continue;
649
- }
650
- if (skipOrChain) {
651
- skipOrChain = segment.separatorAfter === "||";
652
- continue;
653
- }
654
- const words = segment.words;
655
- if (words[0] === "cd") {
656
- const path = words[1] || "/workspace";
657
- if (!isWorkspacePathCandidate(path)) continue;
658
- const resolvedPath = resolveWorkspaceShellPath(currentCwd, path);
659
- const directory = await workspacePathIsDirectory(fs, resolvedPath);
660
- if (segment.separatorAfter === "&&" && !directory) skipAndChain = true;
661
- if (segment.separatorAfter === "||" && directory) skipOrChain = true;
662
- if (directory) currentCwd = resolvedPath ? posix.join(workspaceMountPoint, resolvedPath) : workspaceMountPoint;
663
- continue;
664
- }
664
+ for await (const { segment, cwd: segmentCwd } of walkWorkspaceInspectionCommand(segments, fs, cwd, signal)) {
665
+ throwIfAborted(signal);
665
666
  for (const path of segment.paths) {
666
667
  if (!isConcreteWorkspacePath(path)) continue;
667
- const resolvedPath = resolveWorkspaceShellPath(currentCwd, path);
668
- if (await fs.exists(resolvedPath)) continue;
668
+ const resolvedPath = resolveWorkspaceShellPath(segmentCwd, path);
669
+ const exists = await fs.exists(resolvedPath);
670
+ throwIfAborted(signal);
671
+ if (exists) continue;
669
672
  if (segment.separatorAfter === "||") continue;
670
673
  return missingWorkspacePathFeedback(command, resolvedPath);
671
674
  }
672
675
  if (segment.separatorAfter === "&&" || segment.separatorAfter === "||") return void 0;
673
676
  }
674
677
  } catch {
678
+ throwIfAborted(signal);
675
679
  return;
676
680
  }
677
681
  }
682
+ async function* walkWorkspaceInspectionCommand(segments, fs, cwd, signal) {
683
+ let currentCwd = cwd;
684
+ let skipAndChain = false;
685
+ let skipOrChain = false;
686
+ for (const segment of segments) {
687
+ throwIfAborted(signal);
688
+ if (skipAndChain) {
689
+ skipAndChain = segment.separatorAfter === "&&";
690
+ continue;
691
+ }
692
+ if (skipOrChain) {
693
+ skipOrChain = segment.separatorAfter === "||";
694
+ continue;
695
+ }
696
+ const words = segment.words;
697
+ if (words[0] === "cd") {
698
+ const path = words[1] || "/workspace";
699
+ if (!isWorkspacePathCandidate(path)) continue;
700
+ const resolvedPath = resolveWorkspaceShellPath(currentCwd, path);
701
+ const directory = await workspacePathIsDirectory(fs, resolvedPath);
702
+ throwIfAborted(signal);
703
+ if (segment.separatorAfter === "&&" && !directory) skipAndChain = true;
704
+ if (segment.separatorAfter === "||" && directory) skipOrChain = true;
705
+ if (directory) currentCwd = resolvedPath ? posix.join(workspaceMountPoint, resolvedPath) : workspaceMountPoint;
706
+ continue;
707
+ }
708
+ yield {
709
+ segment,
710
+ cwd: currentCwd
711
+ };
712
+ }
713
+ }
714
+ function throwIfAborted(signal) {
715
+ signal?.throwIfAborted();
716
+ }
678
717
  async function workspacePathIsDirectory(fs, path) {
679
718
  if (path === "") return true;
680
719
  try {
@@ -733,11 +772,11 @@ function isBroadWorkspacePath(path, broadSearchPaths = [], cwd = workspaceMountP
733
772
  const normalized = cleanWorkspaceShellPath(resolvedWorkspaceCwd(cwd, path)) || ".";
734
773
  return normalized === "." || broadSearchPaths.includes(normalized);
735
774
  }
736
- function searchNoMatchFeedback(command, result, broadSearchPaths = [], cwd = workspaceMountPoint) {
775
+ function searchNoMatchFeedback(segments, result, broadSearchPaths = [], cwd = workspaceMountPoint) {
737
776
  if (result.exitCode !== 1 || result.stderr || result.stdout) return "";
738
777
  try {
739
778
  let currentCwd = cwd;
740
- for (const segment of analyzeWorkspaceInspectionCommand(command)) {
779
+ for (const segment of segments) {
741
780
  const words = segment.words;
742
781
  if (words[0] === "cd") {
743
782
  const path = words[1] || "/workspace";
@@ -748,7 +787,10 @@ function searchNoMatchFeedback(command, result, broadSearchPaths = [], cwd = wor
748
787
  if (segment.separatorAfter === "&&") return "";
749
788
  continue;
750
789
  }
751
- if (!segment.paths.some((path) => isBroadWorkspacePath(path, broadSearchPaths, currentCwd))) {
790
+ if (!segment.paths.some((path) => {
791
+ const resolved = cleanWorkspaceShellPath(resolvedWorkspaceCwd(currentCwd, path));
792
+ return isBroadWorkspacePath(path, broadSearchPaths, currentCwd) || broadSearchPaths.some((root) => resolved.startsWith(`${cleanWorkspaceShellPath(root)}/`));
793
+ })) {
752
794
  if (segment.separatorAfter === "&&") return "";
753
795
  continue;
754
796
  }
@@ -759,30 +801,31 @@ function searchNoMatchFeedback(command, result, broadSearchPaths = [], cwd = wor
759
801
  }
760
802
  return "";
761
803
  }
762
- function preflightUnsupportedWorkspaceCommand(command, commands, strictProvider = false) {
763
- const syntax = preflightUnsupportedWorkspaceSyntax(command, commands, strictProvider);
804
+ function preflightUnsupportedWorkspaceCommand(command, segments, commands, strictDriver = false) {
805
+ const syntax = preflightUnsupportedWorkspaceSyntax(command, segments, commands, strictDriver);
764
806
  if (syntax) return syntax;
765
- if (!strictProvider && usesCompoundShellSyntax(command)) return void 0;
807
+ if (!strictDriver && (usesShellSubstitution(command) || usesCompoundShellSyntax(segments))) return void 0;
766
808
  if (!commands) return void 0;
767
- const allowed = new Set([
809
+ const allowed = /* @__PURE__ */ new Set([
768
810
  ...commands,
769
811
  "cd",
770
812
  "false",
771
813
  "true"
772
814
  ]);
773
- for (const segment of analyzeWorkspaceInspectionCommand(command)) {
815
+ for (const segment of segments) {
774
816
  const executable = workspaceExecutable(segment.words);
775
817
  if (!executable || allowed.has(executable.name)) continue;
776
818
  return unsupportedWorkspaceCommandFeedback(command, executable.name, commands);
777
819
  }
778
820
  }
779
- function preflightUnsupportedWorkspaceSyntax(command, commands, strictProvider = false) {
821
+ function preflightUnsupportedWorkspaceSyntax(command, segments, commands, strictDriver = false) {
822
+ if (segments.some((segment) => segment.invalid)) return unsupportedWorkspaceCommandFeedback(command, "invalid shell syntax", commands);
780
823
  if (usesShellSubstitution(command)) {
781
- if (strictProvider || commands) return unsupportedWorkspaceCommandFeedback(command, "shell substitution", commands);
824
+ if (strictDriver) return unsupportedWorkspaceCommandFeedback(command, "shell substitution", commands);
782
825
  return;
783
826
  }
784
- if (usesCompoundShellSyntax(command)) {
785
- if (strictProvider) return unsupportedWorkspaceCommandFeedback(command, "compound shell syntax", commands);
827
+ if (usesCompoundShellSyntax(segments)) {
828
+ if (strictDriver) return unsupportedWorkspaceCommandFeedback(command, "compound shell syntax", commands);
786
829
  return;
787
830
  }
788
831
  }
@@ -841,8 +884,8 @@ function workspaceExecutable(words) {
841
884
  };
842
885
  }
843
886
  }
844
- function usesCompoundShellSyntax(command) {
845
- return analyzeWorkspaceInspectionCommand(command).some((segment) => isCompoundShellSyntaxWord(segment.words[0] || ""));
887
+ function usesCompoundShellSyntax(segments) {
888
+ return segments.some((segment) => isCompoundShellSyntaxWord(segment.words[0] || ""));
846
889
  }
847
890
  function isCompoundShellSyntaxWord(word) {
848
891
  return word === "{" || word.startsWith("(") || /^[A-Za-z_][A-Za-z0-9_]*\(\)$/.test(word) || shellSyntaxWords.has(word);
@@ -850,7 +893,7 @@ function isCompoundShellSyntaxWord(word) {
850
893
  function isAssignmentWord(word) {
851
894
  return /^[A-Za-z_][A-Za-z0-9_]*=.*/.test(word);
852
895
  }
853
- const shellSyntaxWords = new Set([
896
+ const shellSyntaxWords = /* @__PURE__ */ new Set([
854
897
  "case",
855
898
  "do",
856
899
  "done",