@wrongstack/tools 0.155.0 → 0.236.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/audit.js +21 -1
  2. package/dist/audit.js.map +1 -1
  3. package/dist/bash.js +116 -24
  4. package/dist/bash.js.map +1 -1
  5. package/dist/builtin.js +673 -202
  6. package/dist/builtin.js.map +1 -1
  7. package/dist/circuit-breaker.d.ts +9 -2
  8. package/dist/circuit-breaker.js +11 -2
  9. package/dist/circuit-breaker.js.map +1 -1
  10. package/dist/codebase-index/index.js +19 -10
  11. package/dist/codebase-index/index.js.map +1 -1
  12. package/dist/diff.js +1 -1
  13. package/dist/diff.js.map +1 -1
  14. package/dist/document.js +1 -1
  15. package/dist/document.js.map +1 -1
  16. package/dist/edit.js +1 -1
  17. package/dist/edit.js.map +1 -1
  18. package/dist/exec.js +60 -11
  19. package/dist/exec.js.map +1 -1
  20. package/dist/fetch.js.map +1 -1
  21. package/dist/format.js +21 -1
  22. package/dist/format.js.map +1 -1
  23. package/dist/git.js.map +1 -1
  24. package/dist/glob.js +1 -1
  25. package/dist/glob.js.map +1 -1
  26. package/dist/grep.js +1 -1
  27. package/dist/grep.js.map +1 -1
  28. package/dist/index.d.ts +4 -3
  29. package/dist/index.js +680 -209
  30. package/dist/index.js.map +1 -1
  31. package/dist/install.js +65 -14
  32. package/dist/install.js.map +1 -1
  33. package/dist/lint.js +21 -1
  34. package/dist/lint.js.map +1 -1
  35. package/dist/logs.js +1 -1
  36. package/dist/logs.js.map +1 -1
  37. package/dist/outdated.js +1 -1
  38. package/dist/outdated.js.map +1 -1
  39. package/dist/pack.js +673 -202
  40. package/dist/pack.js.map +1 -1
  41. package/dist/patch.js +1 -1
  42. package/dist/patch.js.map +1 -1
  43. package/dist/process-registry.d.ts +21 -16
  44. package/dist/process-registry.js +48 -10
  45. package/dist/process-registry.js.map +1 -1
  46. package/dist/read.js +1 -1
  47. package/dist/read.js.map +1 -1
  48. package/dist/replace.js +1 -1
  49. package/dist/replace.js.map +1 -1
  50. package/dist/scaffold.js +1 -1
  51. package/dist/scaffold.js.map +1 -1
  52. package/dist/search.js +19 -16
  53. package/dist/search.js.map +1 -1
  54. package/dist/test.js +21 -1
  55. package/dist/test.js.map +1 -1
  56. package/dist/todo.js +44 -0
  57. package/dist/todo.js.map +1 -1
  58. package/dist/tree.js +1 -1
  59. package/dist/tree.js.map +1 -1
  60. package/dist/typecheck.js +21 -1
  61. package/dist/typecheck.js.map +1 -1
  62. package/dist/write.js +1 -1
  63. package/dist/write.js.map +1 -1
  64. package/package.json +5 -5
package/dist/audit.js CHANGED
@@ -29,6 +29,7 @@ function resolveWin32Command(cmd) {
29
29
  async function* spawnStream(opts) {
30
30
  const max = opts.maxBytes;
31
31
  const flushAt = opts.flushBytes ?? 4 * 1024;
32
+ const maxQueue = opts.maxQueueSize ?? 500;
32
33
  let stdout = "";
33
34
  let stderr = "";
34
35
  let pending = "";
@@ -44,6 +45,7 @@ async function* spawnStream(opts) {
44
45
  });
45
46
  const queue = [];
46
47
  let waiter;
48
+ let paused = false;
47
49
  const wake = () => {
48
50
  if (waiter) {
49
51
  const w = waiter;
@@ -51,17 +53,34 @@ async function* spawnStream(opts) {
51
53
  w();
52
54
  }
53
55
  };
56
+ const resume = () => {
57
+ if (paused && queue.length < maxQueue) {
58
+ paused = false;
59
+ child.stdout?.resume();
60
+ child.stderr?.resume();
61
+ }
62
+ };
54
63
  child.stdout?.on("data", (c) => {
55
64
  const s = c.toString();
56
65
  if (stdout.length < max) stdout += s;
57
66
  queue.push({ kind: "out", data: s });
58
67
  wake();
68
+ if (!paused && queue.length >= maxQueue) {
69
+ paused = true;
70
+ child.stdout?.pause();
71
+ child.stderr?.pause();
72
+ }
59
73
  });
60
74
  child.stderr?.on("data", (c) => {
61
75
  const s = c.toString();
62
76
  if (stderr.length < max) stderr += s;
63
77
  queue.push({ kind: "err", data: s });
64
78
  wake();
79
+ if (!paused && queue.length >= maxQueue) {
80
+ paused = true;
81
+ child.stdout?.pause();
82
+ child.stderr?.pause();
83
+ }
65
84
  });
66
85
  child.on("error", (e) => {
67
86
  error = e.message;
@@ -81,6 +100,7 @@ async function* spawnStream(opts) {
81
100
  });
82
101
  }
83
102
  const chunk = queue.shift();
103
+ resume();
84
104
  if (chunk.kind === "close") {
85
105
  if (!spawnFailed) exitCode = chunk.code ?? 0;
86
106
  break;
@@ -122,7 +142,7 @@ async function detectPackageManager(cwd) {
122
142
  return "npm";
123
143
  }
124
144
  function resolvePath(input, ctx) {
125
- return path2.isAbsolute(input) ? path2.normalize(input) : path2.resolve(ctx.cwd, input);
145
+ return path2.isAbsolute(input) ? path2.normalize(input) : path2.resolve(ctx.workingDir ?? ctx.cwd, input);
126
146
  }
127
147
  function ensureInsideRoot(absPath, ctx) {
128
148
  const root = path2.resolve(ctx.projectRoot);
package/dist/audit.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_win32-resolve.ts","../src/_spawn-stream.ts","../src/_util.ts","../src/audit.ts"],"names":["path","resolve"],"mappings":";;;;;;AAYO,SAAS,oBAAoB,GAAA,EAAqB;AACvD,EAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,OAAA,EAAS,OAAO,GAAA;AAGzC,EAAA,IAAI,GAAA,CAAI,QAAA,CAAS,GAAG,CAAA,IAAK,GAAA,CAAI,SAAS,IAAI,CAAA,IAAUA,KAAA,CAAA,OAAA,CAAQ,GAAG,CAAA,EAAG;AAChE,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,MAAM,OAAA,GAAA,CAAW,QAAQ,GAAA,CAAI,SAAS,KAAK,uCAAA,EACxC,WAAA,EAAY,CACZ,KAAA,CAAM,GAAG,CAAA;AAEZ,EAAA,MAAM,YAAY,OAAA,CAAQ,GAAA,CAAI,MAAM,CAAA,IAAK,EAAA,EAAI,MAAWA,KAAA,CAAA,SAAS,CAAA;AAEjE,EAAA,KAAA,MAAW,OAAO,QAAA,EAA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AA,CAAE,QAAA,KAAa,MAAM,CAAA,CAAE,MAAM,CAAA,KAAA,CAAA;AAEvK,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,QAAA;AAAA,MACX,eAAA,EAAiB,UAAA;AAAA,MACjB,KAAA;AAAA,MACA,OAAA;AAAA,MACA,MAAA,EAAQ,IAAA;AAAA,MACR,SAAA,EAAW,KAAK,MAAA,IAAU;AAAA,KAC5B;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,QAAA;AAAA,MACX,iBAAiB,EAAC;AAAA,MAClB,KAAA,EAAO,CAAA;AAAA,MACP,OAAA,EAAS,8BAAA;AAAA,MACT,MAAA,EAAQ,IAAA;AAAA,MACR,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AACF","file":"audit.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * On Windows, Node.js `spawn()` without a shell does NOT resolve .cmd/.bat\n * extensions through PATHEXT — it only auto-resolves .exe. Most Node.js CLI\n * tools (npx, pnpm, biome, tsc, vitest, etc.) ship as .cmd wrappers on\n * Windows. This function resolves the command name to its full path so spawn\n * can find it without relying on shell-mode argument concatenation.\n *\n * On non-Windows, returns the command unchanged.\n */\nexport function resolveWin32Command(cmd: string): string {\n if (process.platform !== 'win32') return cmd;\n\n // Already has a path or extension — use as-is\n if (cmd.includes('/') || cmd.includes('\\\\') || path.extname(cmd)) {\n return cmd;\n }\n\n const pathext = (process.env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC')\n .toLowerCase()\n .split(';');\n\n const pathDirs = (process.env['PATH'] ?? '').split(path.delimiter);\n\n for (const dir of pathDirs) {\n const base = path.join(dir, cmd);\n // Check extensions in PATHEXT order. .EXE should win first because\n // it's typically listed first, and .exe doesn't need shell: true.\n for (const ext of pathext) {\n const full = `${base}${ext}`;\n try {\n fs.accessSync(full, fs.constants.X_OK);\n return full;\n } catch {\n // Not found with this extension — try next\n }\n }\n }\n\n // Not found — return original; let spawn report ENOENT with the\n // expected error message so tools can surface it properly.\n return cmd;\n}\n","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { ToolProgressEvent } from '@wrongstack/core';\nimport { resolveWin32Command } from './_win32-resolve.js';\nexport interface SpawnStreamResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n truncated: boolean;\n error?: string | undefined;\n}\n\nexport interface SpawnStreamOptions {\n cmd: string;\n args: string[];\n cwd: string;\n signal: AbortSignal;\n maxBytes?: number | undefined;\n /** Bytes of new stdout/stderr to accumulate before yielding a `partial_output` event. */\n flushBytes?: number | undefined;\n}\n\n/**\n * Spawn a child process and yield `partial_output` progress events as\n * stdout/stderr arrive (batched by byte threshold), then return the full\n * buffered result. Shared between install/lint/format/typecheck/test/audit\n * so the TUI live tail sees consistent progress regardless of which tool\n * is running.\n */\nexport async function* spawnStream(\n opts: SpawnStreamOptions,\n): AsyncGenerator<ToolProgressEvent, SpawnStreamResult> {\n const max = opts.maxBytes ?? 200_000;\n const flushAt = opts.flushBytes ?? 4 * 1024;\n let stdout = '';\n let stderr = '';\n let pending = '';\n let error: string | undefined;\n\n const cmd = resolveWin32Command(opts.cmd);\n const needsShell = process.platform === 'win32' && (cmd.endsWith('.cmd') || cmd.endsWith('.bat'));\n\n const child = spawn(cmd, opts.args, {\n cwd: opts.cwd,\n signal: opts.signal,\n env: buildChildEnv(),\n stdio: ['ignore', 'pipe', 'pipe'],\n ...(needsShell ? { shell: true, windowsVerbatimArguments: true } : {}),\n });\n\n type Chunk = { kind: 'out' | 'err' | 'close' | 'error'; data: string; code?: number | undefined };\n const queue: Chunk[] = [];\n let waiter: (() => void) | undefined;\n const wake = () => {\n if (waiter) {\n const w = waiter;\n waiter = undefined;\n w();\n }\n };\n\n child.stdout?.on('data', (c) => {\n const s = c.toString();\n if (stdout.length < max) stdout += s;\n queue.push({ kind: 'out', data: s });\n wake();\n });\n child.stderr?.on('data', (c) => {\n const s = c.toString();\n if (stderr.length < max) stderr += s;\n queue.push({ kind: 'err', data: s });\n wake();\n });\n child.on('error', (e) => {\n error = e.message;\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', (code) => {\n queue.push({ kind: 'close', data: '', code: code ?? 0 });\n wake();\n });\n\n let exitCode = 0;\n let spawnFailed = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n }\n const chunk = queue.shift()!;\n if (chunk.kind === 'close') {\n // If we already saw a spawn error (ENOENT etc.), keep exitCode=1\n // rather than the negative platform code Node fabricates.\n if (!spawnFailed) exitCode = chunk.code ?? 0;\n break;\n }\n if (chunk.kind === 'error') {\n spawnFailed = true;\n exitCode = 1;\n // close usually follows\n continue;\n }\n pending += chunk.data;\n if (pending.length >= flushAt) {\n yield { type: 'partial_output', text: pending };\n pending = '';\n }\n }\n if (pending.length > 0) {\n yield { type: 'partial_output', text: pending };\n }\n\n return {\n stdout,\n stderr,\n exitCode,\n truncated: stdout.length >= max || stderr.length >= max,\n error,\n };\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { spawnStream } from './_spawn-stream.js';\nimport { detectPackageManager, safeResolve } from './_util.js';\n\ninterface AuditInput {\n cwd?: string | undefined;\n level?: 'low' | 'moderate' | 'high' | 'critical' | undefined;\n fix?: boolean | undefined;\n packages?: string | string[] | undefined;\n}\n\ninterface AuditVulnerability {\n severity: string;\n package: string;\n title: string;\n url: string;\n}\n\ninterface AuditOutput {\n exit_code: number;\n vulnerabilities: AuditVulnerability[];\n total: number;\n summary: string;\n output: string;\n truncated: boolean;\n}\n\nexport const auditTool: Tool<AuditInput, AuditOutput> = {\n name: 'audit',\n category: 'Package Management',\n description:\n 'Run a security audit against project dependencies (using pnpm/npm audit). Reports known vulnerabilities with severity.',\n usageHint:\n 'CRITICAL SECURITY TOOL:\\n\\n' +\n '- Run regularly and especially before any release.\\n' +\n '- Use `level` to focus on high/critical issues.\\n' +\n '- `fix` can attempt automatic remediation for some vulnerabilities.\\n' +\n 'This is one of the most important tools for supply chain security.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 60_000,\n inputSchema: {\n type: 'object',\n properties: {\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n level: {\n type: 'string',\n enum: ['low', 'moderate', 'high', 'critical'],\n description: 'Minimum severity level to report',\n },\n fix: { type: 'boolean', description: 'Attempt to fix vulnerabilities (default: false)' },\n packages: { type: 'string', description: 'Specific package(s) to audit (comma-separated)' },\n },\n },\n async execute(input, ctx, opts) {\n let final: AuditOutput | undefined;\n const executeStream = auditTool.executeStream;\n if (!executeStream) throw new Error('auditTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('audit: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<AuditOutput>> {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const manager = await detectPackageManager(cwd);\n yield { type: 'log', text: `Auditing with ${manager}…`, data: { manager } };\n\n const args = ['audit', '--json'];\n if (input.fix) args.push('--fix');\n if (input.packages) {\n const pkgs = Array.isArray(input.packages) ? input.packages : input.packages.split(',');\n args.push(...pkgs.map((p: string) => p.trim()));\n }\n\n const result = yield* spawnStream({\n cmd: manager,\n args,\n cwd,\n signal: opts.signal,\n maxBytes: 100_000,\n });\n\n yield { type: 'final', output: parseAuditOutput(result.stdout, result.exitCode) };\n },\n};\n\nfunction parseAuditOutput(json: string, exitCode: number): AuditOutput {\n if (!json) {\n return {\n exit_code: exitCode,\n vulnerabilities: [],\n total: 0,\n summary: exitCode === 0 ? 'No vulnerabilities found' : 'Audit failed',\n output: '',\n truncated: false,\n };\n }\n\n try {\n const data = JSON.parse(json);\n const advisories: AuditVulnerability[] = [];\n const ads = data.advisories ?? {};\n for (const id of Object.keys(ads)) {\n const adv = ads[id];\n advisories.push({\n severity: adv.severity ?? 'unknown',\n package: adv.module_name ?? id,\n title: adv.title ?? 'Unknown vulnerability',\n url: adv.url ?? '',\n });\n }\n\n const total = advisories.length;\n const summary =\n total === 0\n ? 'No vulnerabilities found'\n : `Found ${total} vulnerabilities: ${advisories.filter((a) => a.severity === 'critical').length} critical, ${advisories.filter((a) => a.severity === 'high').length} high`;\n\n return {\n exit_code: exitCode,\n vulnerabilities: advisories,\n total,\n summary,\n output: json,\n truncated: json.length >= 100_000,\n };\n } catch {\n return {\n exit_code: exitCode,\n vulnerabilities: [],\n total: 0,\n summary: 'Could not parse audit output',\n output: json,\n truncated: false,\n };\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/_win32-resolve.ts","../src/_spawn-stream.ts","../src/_util.ts","../src/audit.ts"],"names":["path","resolve"],"mappings":";;;;;;AAYO,SAAS,oBAAoB,GAAA,EAAqB;AACvD,EAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,OAAA,EAAS,OAAO,GAAA;AAGzC,EAAA,IAAI,GAAA,CAAI,QAAA,CAAS,GAAG,CAAA,IAAK,GAAA,CAAI,SAAS,IAAI,CAAA,IAAUA,KAAA,CAAA,OAAA,CAAQ,GAAG,CAAA,EAAG;AAChE,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,MAAM,OAAA,GAAA,CAAW,QAAQ,GAAA,CAAI,SAAS,KAAK,uCAAA,EACxC,WAAA,EAAY,CACZ,KAAA,CAAM,GAAG,CAAA;AAEZ,EAAA,MAAM,YAAY,OAAA,CAAQ,GAAA,CAAI,MAAM,CAAA,IAAK,EAAA,EAAI,MAAWA,KAAA,CAAA,SAAS,CAAA;AAEjE,EAAA,KAAA,MAAW,OAAO,QAAA,EAAU;AAC1B,IAAA,MAAM,IAAA,GAAYA,KAAA,CAAA,IAAA,CAAK,GAAA,EAAK,GAAG,CAAA;AAG/B,IAAA,KAAA,MAAW,OAAO,OAAA,EAAS;AACzB,MAAA,MAAM,IAAA,GAAO,CAAA,EAAG,IAAI,CAAA,EAAG,GAAG,CAAA,CAAA;AAC1B,MAAA,IAAI;AACF,QAAG,EAAA,CAAA,UAAA,CAAW,IAAA,EAAS,EAAA,CAAA,SAAA,CAAU,IAAI,CAAA;AACrC,QAAA,OAAO,IAAA;AAAA,MACT,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AAIA,EAAA,OAAO,GAAA;AACT;;;ACbA,gBAAuB,YACrB,IAAA,EACsD;AACtD,EAAA,MAAM,GAAA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A,IAAA,MAAM,QAAQ,UAAA,CAAW,MAAA;AACzB,IAAA,MAAM,OAAA,GACJ,KAAA,KAAU,CAAA,GACN,0BAAA,GACA,CAAA,MAAA,EAAS,KAAK,CAAA,kBAAA,EAAqB,UAAA,CAAW,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,aAAa,UAAU,CAAA,CAAE,MAAM,CAAA,WAAA,EAAc,UAAA,CAAW,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,KAAa,MAAM,CAAA,CAAE,MAAM,CAAA,KAAA,CAAA;AAEvK,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,QAAA;AAAA,MACX,eAAA,EAAiB,UAAA;AAAA,MACjB,KAAA;AAAA,MACA,OAAA;AAAA,MACA,MAAA,EAAQ,IAAA;AAAA,MACR,SAAA,EAAW,KAAK,MAAA,IAAU;AAAA,KAC5B;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,QAAA;AAAA,MACX,iBAAiB,EAAC;AAAA,MAClB,KAAA,EAAO,CAAA;AAAA,MACP,OAAA,EAAS,8BAAA;AAAA,MACT,MAAA,EAAQ,IAAA;AAAA,MACR,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AACF","file":"audit.js","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * On Windows, Node.js `spawn()` without a shell does NOT resolve .cmd/.bat\n * extensions through PATHEXT — it only auto-resolves .exe. Most Node.js CLI\n * tools (npx, pnpm, biome, tsc, vitest, etc.) ship as .cmd wrappers on\n * Windows. This function resolves the command name to its full path so spawn\n * can find it without relying on shell-mode argument concatenation.\n *\n * On non-Windows, returns the command unchanged.\n */\nexport function resolveWin32Command(cmd: string): string {\n if (process.platform !== 'win32') return cmd;\n\n // Already has a path or extension — use as-is\n if (cmd.includes('/') || cmd.includes('\\\\') || path.extname(cmd)) {\n return cmd;\n }\n\n const pathext = (process.env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC')\n .toLowerCase()\n .split(';');\n\n const pathDirs = (process.env['PATH'] ?? '').split(path.delimiter);\n\n for (const dir of pathDirs) {\n const base = path.join(dir, cmd);\n // Check extensions in PATHEXT order. .EXE should win first because\n // it's typically listed first, and .exe doesn't need shell: true.\n for (const ext of pathext) {\n const full = `${base}${ext}`;\n try {\n fs.accessSync(full, fs.constants.X_OK);\n return full;\n } catch {\n // Not found with this extension — try next\n }\n }\n }\n\n // Not found — return original; let spawn report ENOENT with the\n // expected error message so tools can surface it properly.\n return cmd;\n}\n","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { ToolProgressEvent } from '@wrongstack/core';\nimport { resolveWin32Command } from './_win32-resolve.js';\nexport interface SpawnStreamResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n truncated: boolean;\n error?: string | undefined;\n}\n\nexport interface SpawnStreamOptions {\n cmd: string;\n args: string[];\n cwd: string;\n signal: AbortSignal;\n maxBytes?: number | undefined;\n /** Bytes of new stdout/stderr to accumulate before yielding a `partial_output` event. */\n flushBytes?: number | undefined;\n /** Maximum chunks to buffer before applying backpressure to the child. Default 500. */\n maxQueueSize?: number | undefined;\n}\n\n/**\n * Spawn a child process and yield `partial_output` progress events as\n * stdout/stderr arrive (batched by byte threshold), then return the full\n * buffered result. Shared between install/lint/format/typecheck/test/audit\n * so the TUI live tail sees consistent progress regardless of which tool\n * is running.\n */\nexport async function* spawnStream(\n opts: SpawnStreamOptions,\n): AsyncGenerator<ToolProgressEvent, SpawnStreamResult> {\n const max = opts.maxBytes ?? 200_000;\n const flushAt = opts.flushBytes ?? 4 * 1024;\n const maxQueue = opts.maxQueueSize ?? 500;\n let stdout = '';\n let stderr = '';\n let pending = '';\n let error: string | undefined;\n\n const cmd = resolveWin32Command(opts.cmd);\n const needsShell = process.platform === 'win32' && (cmd.endsWith('.cmd') || cmd.endsWith('.bat'));\n\n const child = spawn(cmd, opts.args, {\n cwd: opts.cwd,\n signal: opts.signal,\n env: buildChildEnv(),\n stdio: ['ignore', 'pipe', 'pipe'],\n ...(needsShell ? { shell: true, windowsVerbatimArguments: true } : {}),\n });\n\n type Chunk = { kind: 'out' | 'err' | 'close' | 'error'; data: string; code?: number | undefined };\n const queue: Chunk[] = [];\n let waiter: (() => void) | undefined;\n let paused = false;\n const wake = () => {\n if (waiter) {\n const w = waiter;\n waiter = undefined;\n w();\n }\n };\n\n // Resume the stream when there's room in the queue\n const resume = () => {\n if (paused && queue.length < maxQueue) {\n paused = false;\n child.stdout?.resume();\n child.stderr?.resume();\n }\n };\n\n // Note: chunks may still arrive briefly after pause() (already in flight) —\n // they are accumulated and queued rather than dropped, so the queue can\n // overshoot maxQueue by a few entries but no output is silently lost.\n child.stdout?.on('data', (c) => {\n const s = c.toString();\n if (stdout.length < max) stdout += s;\n queue.push({ kind: 'out', data: s });\n wake();\n // Apply backpressure if queue is growing faster than we consume\n if (!paused && queue.length >= maxQueue) {\n paused = true;\n child.stdout?.pause();\n child.stderr?.pause();\n }\n });\n child.stderr?.on('data', (c) => {\n const s = c.toString();\n if (stderr.length < max) stderr += s;\n queue.push({ kind: 'err', data: s });\n wake();\n if (!paused && queue.length >= maxQueue) {\n paused = true;\n child.stdout?.pause();\n child.stderr?.pause();\n }\n });\n child.on('error', (e) => {\n error = e.message;\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', (code) => {\n queue.push({ kind: 'close', data: '', code: code ?? 0 });\n wake();\n });\n\n let exitCode = 0;\n let spawnFailed = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n }\n const chunk = queue.shift()!;\n // Resume reading after consuming a chunk\n resume();\n if (chunk.kind === 'close') {\n // If we already saw a spawn error (ENOENT etc.), keep exitCode=1\n // rather than the negative platform code Node fabricates.\n if (!spawnFailed) exitCode = chunk.code ?? 0;\n break;\n }\n if (chunk.kind === 'error') {\n spawnFailed = true;\n exitCode = 1;\n // close usually follows\n continue;\n }\n pending += chunk.data;\n if (pending.length >= flushAt) {\n yield { type: 'partial_output', text: pending };\n pending = '';\n }\n }\n if (pending.length > 0) {\n yield { type: 'partial_output', text: pending };\n }\n\n return {\n stdout,\n stderr,\n exitCode,\n truncated: stdout.length >= max || stderr.length >= max,\n error,\n };\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { spawnStream } from './_spawn-stream.js';\nimport { detectPackageManager, safeResolve } from './_util.js';\n\ninterface AuditInput {\n cwd?: string | undefined;\n level?: 'low' | 'moderate' | 'high' | 'critical' | undefined;\n fix?: boolean | undefined;\n packages?: string | string[] | undefined;\n}\n\ninterface AuditVulnerability {\n severity: string;\n package: string;\n title: string;\n url: string;\n}\n\ninterface AuditOutput {\n exit_code: number;\n vulnerabilities: AuditVulnerability[];\n total: number;\n summary: string;\n output: string;\n truncated: boolean;\n}\n\nexport const auditTool: Tool<AuditInput, AuditOutput> = {\n name: 'audit',\n category: 'Package Management',\n description:\n 'Run a security audit against project dependencies (using pnpm/npm audit). Reports known vulnerabilities with severity.',\n usageHint:\n 'CRITICAL SECURITY TOOL:\\n\\n' +\n '- Run regularly and especially before any release.\\n' +\n '- Use `level` to focus on high/critical issues.\\n' +\n '- `fix` can attempt automatic remediation for some vulnerabilities.\\n' +\n 'This is one of the most important tools for supply chain security.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 60_000,\n inputSchema: {\n type: 'object',\n properties: {\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n level: {\n type: 'string',\n enum: ['low', 'moderate', 'high', 'critical'],\n description: 'Minimum severity level to report',\n },\n fix: { type: 'boolean', description: 'Attempt to fix vulnerabilities (default: false)' },\n packages: { type: 'string', description: 'Specific package(s) to audit (comma-separated)' },\n },\n },\n async execute(input, ctx, opts) {\n let final: AuditOutput | undefined;\n const executeStream = auditTool.executeStream;\n if (!executeStream) throw new Error('auditTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('audit: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<AuditOutput>> {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const manager = await detectPackageManager(cwd);\n yield { type: 'log', text: `Auditing with ${manager}…`, data: { manager } };\n\n const args = ['audit', '--json'];\n if (input.fix) args.push('--fix');\n if (input.packages) {\n const pkgs = Array.isArray(input.packages) ? input.packages : input.packages.split(',');\n args.push(...pkgs.map((p: string) => p.trim()));\n }\n\n const result = yield* spawnStream({\n cmd: manager,\n args,\n cwd,\n signal: opts.signal,\n maxBytes: 100_000,\n });\n\n yield { type: 'final', output: parseAuditOutput(result.stdout, result.exitCode) };\n },\n};\n\nfunction parseAuditOutput(json: string, exitCode: number): AuditOutput {\n if (!json) {\n return {\n exit_code: exitCode,\n vulnerabilities: [],\n total: 0,\n summary: exitCode === 0 ? 'No vulnerabilities found' : 'Audit failed',\n output: '',\n truncated: false,\n };\n }\n\n try {\n const data = JSON.parse(json);\n const advisories: AuditVulnerability[] = [];\n const ads = data.advisories ?? {};\n for (const id of Object.keys(ads)) {\n const adv = ads[id];\n advisories.push({\n severity: adv.severity ?? 'unknown',\n package: adv.module_name ?? id,\n title: adv.title ?? 'Unknown vulnerability',\n url: adv.url ?? '',\n });\n }\n\n const total = advisories.length;\n const summary =\n total === 0\n ? 'No vulnerabilities found'\n : `Found ${total} vulnerabilities: ${advisories.filter((a) => a.severity === 'critical').length} critical, ${advisories.filter((a) => a.severity === 'high').length} high`;\n\n return {\n exit_code: exitCode,\n vulnerabilities: advisories,\n total,\n summary,\n output: json,\n truncated: json.length >= 100_000,\n };\n } catch {\n return {\n exit_code: exitCode,\n vulnerabilities: [],\n total: 0,\n summary: 'Could not parse audit output',\n output: json,\n truncated: false,\n };\n }\n}\n"]}
package/dist/bash.js CHANGED
@@ -139,8 +139,13 @@ var CircuitBreaker = class {
139
139
  * Call this BEFORE spawning a bash/exec process.
140
140
  * Returns true if the call is allowed; false if the breaker is open.
141
141
  * When false, callers MUST NOT spawn a process.
142
+ *
143
+ * @param bypass - If true, skip the circuit breaker check entirely.
144
+ * Use for background/fire-and-forget processes that should
145
+ * not affect breaker state.
142
146
  */
143
- beforeCall() {
147
+ beforeCall(bypass = false) {
148
+ if (bypass) return true;
144
149
  this._checkStateTransition();
145
150
  if (this.state === "open") return false;
146
151
  return true;
@@ -150,8 +155,12 @@ var CircuitBreaker = class {
150
155
  * `durationMs` is the wall-clock time the process ran.
151
156
  * `failed` is true when the process returned a non-zero exit code or
152
157
  * threw an exception before spawning.
158
+ *
159
+ * @param bypass - If true, do not update breaker state.
160
+ * Use for background/fire-and-forget processes.
153
161
  */
154
- afterCall(durationMs, failed) {
162
+ afterCall(durationMs, failed, bypass = false) {
163
+ if (bypass) return;
155
164
  const now = Date.now();
156
165
  if (this.state === "half-open") {
157
166
  if (failed) {
@@ -250,6 +259,17 @@ function redactCommand(cmd) {
250
259
  return result;
251
260
  }
252
261
  var DEFAULT_GRACE_MS = 2e3;
262
+ function killWin32Tree(pid) {
263
+ try {
264
+ spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
265
+ stdio: "ignore",
266
+ windowsHide: true
267
+ }).unref();
268
+ return true;
269
+ } catch {
270
+ return false;
271
+ }
272
+ }
253
273
  var ProcessRegistryImpl = class {
254
274
  processes = /* @__PURE__ */ new Map();
255
275
  breaker;
@@ -307,16 +327,20 @@ var ProcessRegistryImpl = class {
307
327
  /**
308
328
  * Called before spawning a process. Returns true if allowed; false if
309
329
  * the circuit breaker is open.
330
+ *
331
+ * @param bypass - If true, skip circuit breaker check (for background processes).
310
332
  */
311
- beforeCall() {
312
- return this.breaker.beforeCall();
333
+ beforeCall(bypass = false) {
334
+ return this.breaker.beforeCall(bypass);
313
335
  }
314
336
  /**
315
337
  * Called after a process finishes. `durationMs` is wall-clock time;
316
338
  * `failed` is true for non-zero exit codes.
339
+ *
340
+ * @param bypass - If true, do not update circuit breaker state (for background processes).
317
341
  */
318
- afterCall(durationMs, failed) {
319
- this.breaker.afterCall(durationMs, failed);
342
+ afterCall(durationMs, failed, bypass = false) {
343
+ this.breaker.afterCall(durationMs, failed, bypass);
320
344
  }
321
345
  /** Force-open the circuit breaker (Ctrl+C, /kill force). */
322
346
  forceBreakerOpen() {
@@ -347,9 +371,22 @@ var ProcessRegistryImpl = class {
347
371
  const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
348
372
  const isWin = os.platform() === "win32";
349
373
  if (isWin) {
350
- try {
351
- p.child.kill(force ? "SIGKILL" : "SIGTERM");
352
- } catch {
374
+ const liveRealChild = p.child.exitCode === null && typeof p.child.pid === "number";
375
+ if (liveRealChild && killWin32Tree(pid)) {
376
+ const fallback = setTimeout(() => {
377
+ if (p.child.exitCode === null) {
378
+ try {
379
+ p.child.kill("SIGKILL");
380
+ } catch {
381
+ }
382
+ }
383
+ }, graceMs);
384
+ fallback.unref?.();
385
+ } else {
386
+ try {
387
+ p.child.kill(force ? "SIGKILL" : "SIGTERM");
388
+ } catch {
389
+ }
353
390
  }
354
391
  p.killed = true;
355
392
  return true;
@@ -425,6 +462,7 @@ var MAX_OUTPUT = 32768;
425
462
  var DEFAULT_TIMEOUT_MS = 3e5;
426
463
  var STREAM_FLUSH_INTERVAL_MS = 200;
427
464
  var STREAM_FLUSH_BYTES = 4 * 1024;
465
+ var MAX_QUEUE_CHUNKS = 500;
428
466
  var bashTool = {
429
467
  name: "bash",
430
468
  category: "Shell",
@@ -472,7 +510,8 @@ var bashTool = {
472
510
  async *executeStream(input, ctx, opts) {
473
511
  if (!input?.command) throw new Error("bash: command is required");
474
512
  const registry = getProcessRegistry();
475
- if (!registry.beforeCall()) {
513
+ const bypassBreaker = !!input.background;
514
+ if (!registry.beforeCall(bypassBreaker)) {
476
515
  yield {
477
516
  type: "final",
478
517
  output: {
@@ -485,6 +524,17 @@ var bashTool = {
485
524
  };
486
525
  return;
487
526
  }
527
+ const PIPE_TO_SHELL_PATTERN = /\|\s*(sh|bash|ksh|zsh|fish|cmd|powershell|pwsh)/i;
528
+ if (PIPE_TO_SHELL_PATTERN.test(input.command)) {
529
+ console.warn(JSON.stringify({
530
+ level: "warn",
531
+ event: "bash.pipe_to_shell_detected",
532
+ message: "Detected pipe-to-shell pattern. Consider reviewing the full command before confirming.",
533
+ command_prefix: input.command.slice(0, 100),
534
+ // Log first 100 chars for review
535
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
536
+ }));
537
+ }
488
538
  const timeoutMs = Math.max(1, Math.min(input.timeout_ms ?? DEFAULT_TIMEOUT_MS, 6e5));
489
539
  const isWin = os.platform() === "win32";
490
540
  const shell = (() => {
@@ -543,7 +593,7 @@ var bashTool = {
543
593
  }
544
594
  });
545
595
  child2.on("close", () => {
546
- registry.afterCall(Date.now() - startedAt, false);
596
+ registry.afterCall(Date.now() - startedAt, false, bypassBreaker);
547
597
  });
548
598
  if (typeof pid2 === "number") child2.unref();
549
599
  yield {
@@ -562,7 +612,7 @@ var bashTool = {
562
612
  env,
563
613
  stdio: ["ignore", "pipe", "pipe"],
564
614
  detached,
565
- signal: opts.signal
615
+ ...isWin ? {} : { signal: opts.signal }
566
616
  });
567
617
  const pid = child.pid;
568
618
  if (typeof pid === "number") {
@@ -581,9 +631,22 @@ var bashTool = {
581
631
  const timers = [];
582
632
  function killWithTimeout(child2, timeoutMs2) {
583
633
  if (isWin) {
584
- try {
585
- child2.kill();
586
- } catch {
634
+ if (typeof child2.pid === "number" && child2.exitCode === null && killWin32Tree(child2.pid)) {
635
+ const fallback = setTimeout(() => {
636
+ if (child2.exitCode === null) {
637
+ try {
638
+ child2.kill();
639
+ } catch {
640
+ }
641
+ }
642
+ }, 2e3);
643
+ timers.push(fallback);
644
+ fallback.unref?.();
645
+ } else {
646
+ try {
647
+ child2.kill();
648
+ } catch {
649
+ }
587
650
  }
588
651
  return;
589
652
  }
@@ -622,6 +685,11 @@ var bashTool = {
622
685
  }, timeoutMs);
623
686
  timers.push(timer);
624
687
  timer.unref?.();
688
+ const onAbort = () => killWithTimeout(child, 2e3);
689
+ if (isWin) {
690
+ if (opts.signal.aborted) onAbort();
691
+ else opts.signal.addEventListener("abort", onAbort, { once: true });
692
+ }
625
693
  const queue = [];
626
694
  let resolveNext = null;
627
695
  const push = (c) => {
@@ -646,18 +714,32 @@ var bashTool = {
646
714
  lastFlush = Date.now();
647
715
  return text;
648
716
  };
649
- child.stdout?.on("data", (chunk) => {
650
- const text = chunk.toString();
651
- buf += text;
652
- pending += text;
653
- push({ kind: "data", text });
654
- });
655
- child.stderr?.on("data", (chunk) => {
717
+ let paused = false;
718
+ const pauseIfFlooded = () => {
719
+ if (!paused && queue.length >= MAX_QUEUE_CHUNKS) {
720
+ paused = true;
721
+ child.stdout?.pause();
722
+ child.stderr?.pause();
723
+ }
724
+ };
725
+ const resumeIfDrained = () => {
726
+ if (paused && queue.length < MAX_QUEUE_CHUNKS) {
727
+ paused = false;
728
+ child.stdout?.resume();
729
+ child.stderr?.resume();
730
+ }
731
+ };
732
+ const onData = (chunk) => {
656
733
  const text = chunk.toString();
657
- buf += text;
734
+ if (buf.length < MAX_OUTPUT) {
735
+ buf += text.slice(0, MAX_OUTPUT - buf.length);
736
+ }
658
737
  pending += text;
659
738
  push({ kind: "data", text });
660
- });
739
+ pauseIfFlooded();
740
+ };
741
+ child.stdout?.on("data", onData);
742
+ child.stderr?.on("data", onData);
661
743
  child.on("error", (err) => {
662
744
  for (const t of timers) clearTimeout(t);
663
745
  registry.afterCall(Date.now() - startedAt, true);
@@ -672,6 +754,7 @@ var bashTool = {
672
754
  try {
673
755
  while (true) {
674
756
  const c = await next();
757
+ resumeIfDrained();
675
758
  if (c.kind === "error") throw c.err;
676
759
  if (c.kind === "end") {
677
760
  const remainder = flush();
@@ -696,6 +779,15 @@ var bashTool = {
696
779
  }
697
780
  } finally {
698
781
  for (const t of timers) clearTimeout(t);
782
+ if (isWin) opts.signal.removeEventListener("abort", onAbort);
783
+ child.stdout?.off("data", onData);
784
+ child.stderr?.off("data", onData);
785
+ child.stdout?.destroy();
786
+ child.stderr?.destroy();
787
+ if (child.exitCode === null && !child.killed) {
788
+ if (typeof pid === "number") registry.kill(pid, { force: true });
789
+ else killWithTimeout(child, 2e3);
790
+ }
699
791
  }
700
792
  }
701
793
  };