bugzero 0.0.62 → 0.0.63

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 (3) hide show
  1. package/README.md +13 -5
  2. package/dist/index.js +514 -65
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -101,7 +101,7 @@ bugzero rescue
101
101
 
102
102
  - **Backups on every patch.** Each file BugZero modifies gets a `.opspilot.bak` copy of its original content first. The backup is written once per run, so it always restores what you had, even if the fix took several attempts. A leftover backup from an earlier run is replaced.
103
103
  - **Project boundary.** BugZero only reads and edits files inside the project you point it at. A patch whose path leaves the project (with `../`, an absolute path elsewhere, or a symlink or junction that points out) is refused before any file changes, and the model is told why. Files outside the project are never added to what is sent to the model, even if an error log mentions them.
104
- - **Protected files.** BugZero never edits secrets (`.env`, `.env.*`, `*.pem`, `*.key`, `.npmrc`, `.netrc`, `.pypirc`), `.git/`, CI configuration (`.github/workflows/`, `.gitlab-ci.yml`, `.circleci/`, and similar), lockfiles (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`), `node_modules/`, or its own `.opspilot.bak` backups. A patch to one of them is refused before any file changes, and the model is told to fix the problem elsewhere. Secret files are also never sent to the model, even if an error log names them. You can adjust the list in `.bugzerorc` (see Configuration).
104
+ - **Protected files.** BugZero never edits secrets (`.env`, `.env.*`, `*.pem`, `*.key`, `.npmrc`, `.netrc`, `.pypirc`), `.git/`, CI configuration (`.github/workflows/`, `.gitlab-ci.yml`, `.circleci/`, and similar), lockfiles (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`), `node_modules/`, or its own `.opspilot.bak` backups. A patch to one of them is refused before any file changes, and the model is told to fix the problem elsewhere. Secret files are also never sent to the model, even if an error log names them. You can adjust the list in `.bugzerorc` (see Configuration). Files you add with `protect` also cannot be read or searched by the model when you use `--tools`.
105
105
  - **Dry-run mode.** `bugzero rescue --dry-run` runs validation and error analysis, but makes no fix attempts and never modifies your source files (it still writes a report that diagnoses the failures it found). It exits with code 1 if it found failures and 0 if everything already passes, so you can use it as a check in scripts.
106
106
  - **Prompt size limits.** Very long error output and very large source files are shortened before being sent to the model (for logs, the start and end are kept), so a big failure can't exceed the model's context window or waste tokens.
107
107
  - **Command timeouts.** `--timeout <seconds>` (available on both `hunt` and `rescue`) stops any build, lint, or test command that runs longer than that. It kills the whole process tree rather than just the shell, so a hung test run cannot linger in the background, and the step is reported as failed along with whatever output it produced. Without it, a command that hangs will hang BugZero too, so it is worth setting in CI.
@@ -232,6 +232,8 @@ The whole proposed fix is shown at once, because a fix that spans several files
232
232
 
233
233
  **Token budget.** `--max-tokens <n>` (or `"maxTokens"` in `.bugzerorc`) limits the AI tokens one `rescue` run may use, fix attempts and the report together; there is no limit unless you set one. Before each request BugZero estimates the prompt (about 4 characters per token) and caps the reply to what is left, up to 8192 tokens. If less than 500 tokens would remain for a reply, the request is not made: the run stops and says so, and the report is written from the raw results without the AI. Because the prompt is only estimated, a run can finish somewhat above the number you give, so treat it as a guard against runaway cost rather than an exact cap. A model that does not report its token usage is counted by the same estimate, and BugZero says when the total includes estimates. `0` means no limit. `hunt` is not covered; use `--no-ai-report` there.
234
234
 
235
+ **Letting the model look further.** With `rescue --tools` (or `"tools": true` in `.bugzerorc`), the model may ask to read files, or to search the project for a piece of text, before it proposes a fix. **This sends more of your code to the model**, and each request is another AI call that costs tokens, so it is off by default. Each attempt allows up to 3 requests (`--max-tool-requests`, or `maxToolRequests`, from 1 to 20). One request reads at most 5 files, up to 20,000 characters of each and 60,000 in total, with line ranges for longer files. A search matches plain text, ignoring case, and returns up to 50 lines, at most 10 from one file. Secrets, files listed in `protect`, `.git`, `node_modules`, `build` and `dist` folders, BugZero's backups and anything outside the project are never read or searched. Each request is logged with what is sent for it, and counts against `--max-tokens`. `--no-tools` turns it off for one run.
236
+
235
237
  <details>
236
238
  <summary><strong>Options for <code>rescue</code></strong></summary>
237
239
 
@@ -242,6 +244,8 @@ The whole proposed fix is shown at once, because a fix that spans several files
242
244
  | `--timeout <seconds>` | `-t` | none | Stop any build, lint, or test command that runs longer than this many seconds |
243
245
  | `--patience <n>` | | `2` | Stop early after this many attempts in a row make no progress. `0` turns it off |
244
246
  | `--max-tokens <n>` | | none | Limit the AI tokens the run may use, the report included. `0` means no limit |
247
+ | `--tools` | | off | Let the model ask to read and search project files before proposing a fix. Sends more of your code. `--no-tools` overrides `.bugzerorc` |
248
+ | `--max-tool-requests <n>` | | `3` | With tools, the most such requests per attempt, 1 to 20 |
245
249
  | `--no-focus-tests` | | off | Always run the full build, lint and tests, instead of re-running only the failing test files between attempts |
246
250
  | `--dry-run` | | `false` | Analyze only — no files will be written |
247
251
  | `--approve` | | `false` | Show each proposed fix as a diff and ask before writing it. Needs an interactive terminal |
@@ -302,8 +306,8 @@ bugzero rescue --json --dry-run | jq -r '.outcome'
302
306
 
303
307
  BugZero runs your build, lint and tests on your own machine. The only time your code can leave it is when BugZero asks an AI model for help, through [OpenRouter](https://openrouter.ai) with your own API key.
304
308
 
305
- - **What is sent:** the error output of the failing command and the contents of the project's source files that output mentions (each shortened to a size limit), plus your project folder's path. Nothing is sent when your project already passes.
306
- - **What is never sent:** files outside your project, secret files (`.env`, `.env.*`, `*.pem`, `*.key`, `.npmrc`, `.netrc`, `.pypirc`), `node_modules`, build output and `.git`. BugZero cannot recognise a secret by its content, so a password that your build prints is sent like any other text.
309
+ - **What is sent:** the error output of the failing command and the contents of the project's source files that output mentions (each shortened to a size limit), plus your project folder's path. With `--tools`, also the files and search results the model asks for. Nothing is sent when your project already passes.
310
+ - **What is never sent:** files outside your project, secret files (`.env`, `.env.*`, `*.pem`, `*.key`, `.npmrc`, `.netrc`, `.pypirc`), `node_modules`, build output and `.git`. With `--tools`, files you list in `protect` are never read or searched either. BugZero cannot recognise a secret by its content, so a password that your build prints is sent like any other text.
307
311
  - **See it first:** `bugzero rescue --print-prompt` prints the exact prompt and sends nothing.
308
312
  - **Stay offline:** `bugzero hunt --no-ai-report` makes no network call.
309
313
  - There is no telemetry, analytics or update check.
@@ -323,18 +327,22 @@ BugZero reads a `.bugzerorc` JSON file in your target project directory to pick
323
327
  "allow": [".env.example"],
324
328
  "patience": 2,
325
329
  "focusTests": true,
326
- "maxTokens": 100000
330
+ "maxTokens": 100000,
331
+ "tools": false,
332
+ "maxToolRequests": 3
327
333
  }
328
334
  ```
329
335
 
330
336
  | Key | Meaning |
331
337
  |---|---|
332
338
  | `model` | The OpenRouter model to use. Set it with `bugzero vibe`. |
333
- | `protect` | Extra files BugZero must never edit, added to the built-in list (see Protected files above). |
339
+ | `protect` | Extra files BugZero must never edit, added to the built-in list (see Protected files above). With tools on, the model cannot read or search them either. |
334
340
  | `allow` | Files from the built-in list that BugZero may edit and read after all, such as `.env.example`. A `protect` pattern still wins. |
335
341
  | `patience` | How many attempts in a row may make no progress before `rescue` stops early. Default 2, `0` turns it off. `--patience` overrides it. |
336
342
  | `focusTests` | Set to `false` to always run the full pipeline, instead of re-running only the failing test files between attempts. Default `true`. `--no-focus-tests` overrides it. |
337
343
  | `maxTokens` | The most AI tokens a `rescue` run may use, the report included. Not set or `0` means no limit. `--max-tokens` overrides it. |
344
+ | `tools` | Set to `true` to let the model ask to read and search project files during `rescue`, which sends more of your code. Default `false`. `--tools` and `--no-tools` override it. |
345
+ | `maxToolRequests` | With tools, the most requests per fix attempt, from 1 to 20. Default 3. `--max-tool-requests` overrides it. |
338
346
 
339
347
  Patterns are relative to the project and ignore case. `*` matches within a folder, `**` matches across folders, `?` matches one character, and a trailing `/` means a folder and everything in it. A pattern with no `/` matches that name at any depth, so `.env.*` also covers `apps/web/.env.local`; a pattern with a `/` is anchored to the project root. All keys are optional.
340
348
 
package/dist/index.js CHANGED
@@ -573,6 +573,8 @@ var require_dist2 = __commonJS({
573
573
  ...DEFAULT_SECRET_PATTERNS,
574
574
  ".git/",
575
575
  "node_modules/",
576
+ "build/",
577
+ "dist/",
576
578
  "*.opspilot.bak",
577
579
  "*.opspilot.bak.sha"
578
580
  ];
@@ -644,16 +646,11 @@ var require_dist2 = __commonJS({
644
646
  if (firstMatch(allowed, normalized)) return void 0;
645
647
  return firstMatch(matchers, normalized)?.pattern;
646
648
  };
649
+ const blockedOrProtected = (matchers, relPath) => firstMatch(extra, normalizePath(relPath))?.pattern ?? blockedUnlessAllowed(matchers, relPath);
647
650
  return {
648
- editBlockedBy(relPath) {
649
- const normalized = normalizePath(relPath);
650
- const own = firstMatch(extra, normalized);
651
- if (own) return own.pattern;
652
- if (firstMatch(allowed, normalized)) return void 0;
653
- return firstMatch(defaults, normalized)?.pattern;
654
- },
651
+ editBlockedBy: (relPath) => blockedOrProtected(defaults, relPath),
655
652
  secretBlockedBy: (relPath) => blockedUnlessAllowed(secrets, relPath),
656
- readBlockedBy: (relPath) => blockedUnlessAllowed(unreadable, relPath)
653
+ readBlockedBy: (relPath) => blockedOrProtected(unreadable, relPath)
657
654
  };
658
655
  }
659
656
  function toRelative(root, target) {
@@ -1816,8 +1813,12 @@ var require_dist6 = __commonJS({
1816
1813
  MAX_FILES_PER_REQUEST: () => MAX_FILES_PER_REQUEST,
1817
1814
  MAX_REQUESTED_FILE_CHARS: () => MAX_REQUESTED_FILE_CHARS,
1818
1815
  MAX_REQUEST_CHARS: () => MAX_REQUEST_CHARS,
1816
+ MAX_SEARCH_MATCHES: () => MAX_SEARCH_MATCHES,
1817
+ MAX_SEARCH_MATCHES_PER_FILE: () => MAX_SEARCH_MATCHES_PER_FILE,
1818
+ MAX_SEARCH_TEXT_CHARS: () => MAX_SEARCH_TEXT_CHARS,
1819
+ SEARCH_REQUEST_EXAMPLE: () => SEARCH_REQUEST_EXAMPLE,
1819
1820
  buildAnalysisPrompt: () => buildAnalysisPrompt,
1820
- fileRequestInstructions: () => fileRequestInstructions,
1821
+ toolInstructions: () => toolInstructions,
1821
1822
  truncateLogs: () => truncateLogs
1822
1823
  });
1823
1824
  module2.exports = __toCommonJS(index_exports);
@@ -1827,14 +1828,26 @@ var require_dist6 = __commonJS({
1827
1828
  var MAX_FILES_PER_REQUEST = 5;
1828
1829
  var MAX_REQUESTED_FILE_CHARS = 2e4;
1829
1830
  var MAX_REQUEST_CHARS = 6e4;
1831
+ var MAX_SEARCH_TEXT_CHARS = 200;
1832
+ var MAX_SEARCH_MATCHES = 50;
1833
+ var MAX_SEARCH_MATCHES_PER_FILE = 10;
1830
1834
  var FILE_REQUEST_EXAMPLE = '{"tool": "read_file", "files": [{"path": "src/types.ts"}, {"path": "src/server.ts", "startLine": 200, "endLine": 320}]}';
1831
- function fileRequestInstructions() {
1832
- return `### Asking for files
1833
- If you cannot write a correct fix without seeing a file that is not shown above, reply with ONLY a request like this instead of a fix:
1835
+ var SEARCH_REQUEST_EXAMPLE = '{"tool": "search", "text": "interface User", "path": "src"}';
1836
+ function toolInstructions(maxRequests) {
1837
+ return `### Looking at more of the project
1838
+ If you cannot write a correct fix from what is shown above, you may look further first: reply with ONLY one of the requests below instead of a fix. You may make up to ${maxRequests} request${maxRequests === 1 ? "" : "s"} in this attempt.
1839
+
1840
+ To read files:
1834
1841
  ${FILE_REQUEST_EXAMPLE}
1835
1842
  - "path" is relative to the project root. "startLine" and "endLine" are optional.
1836
1843
  - One request may ask for at most ${MAX_FILES_PER_REQUEST} files. At most ${MAX_REQUESTED_FILE_CHARS} characters of each file, and ${MAX_REQUEST_CHARS} in total, are returned; use line ranges to see the rest.
1837
- - Secret files, .git and node_modules are never shown.`;
1844
+
1845
+ To find the lines that contain a piece of text:
1846
+ ${SEARCH_REQUEST_EXAMPLE}
1847
+ - The text is matched exactly, ignoring case. It is not a pattern or regular expression.
1848
+ - "path" is optional and limits the search to one folder or file. At most ${MAX_SEARCH_MATCHES} matching lines are returned.
1849
+
1850
+ Secret and protected files, .git, node_modules and build output are never shown or searched.`;
1838
1851
  }
1839
1852
  var MAX_LOG_CHARS = 2e4;
1840
1853
  var MAX_FILE_CHARS = 2e4;
@@ -2008,9 +2021,9 @@ ${w}`).join("\n\n")}
2008
2021
  }
2009
2022
  compilerLogs = truncateLogs(compilerLogs);
2010
2023
  const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared4.createProtectedPathRules)());
2011
- const fileRequestSection = options.fileRequests ? `
2024
+ const toolSection = options.toolRequests ? `
2012
2025
 
2013
- ${fileRequestInstructions()}` : "";
2026
+ ${toolInstructions(options.toolRequests)}` : "";
2014
2027
  return `You are an expert software engineer specialising in fixing build, lint, and test failures.
2015
2028
 
2016
2029
  A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
@@ -2044,7 +2057,7 @@ Critical rules:
2044
2057
  - Each "search" must be an EXACT character-for-character substring of that file's current content.
2045
2058
  - Each "replace" must be syntactically valid code.
2046
2059
  - If two patches target the same file, list them in the order they should be applied, and make sure each "search" reflects the file's content *after* the previous patch in this list has been applied to it.
2047
- - Do NOT add backticks, markdown, or any text outside the JSON object.${fileRequestSection}`;
2060
+ - Do NOT add backticks, markdown, or any text outside the JSON object.${toolSection}`;
2048
2061
  }
2049
2062
  }
2050
2063
  });
@@ -2053,13 +2066,15 @@ Critical rules:
2053
2066
  var require_dist7 = __commonJS({
2054
2067
  "../../packages/agents/dist/index.js"(exports2, module2) {
2055
2068
  "use strict";
2069
+ var __create2 = Object.create;
2056
2070
  var __defProp2 = Object.defineProperty;
2057
2071
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
2058
2072
  var __getOwnPropNames2 = Object.getOwnPropertyNames;
2073
+ var __getProtoOf2 = Object.getPrototypeOf;
2059
2074
  var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2060
- var __export = (target, all) => {
2075
+ var __export = (target2, all) => {
2061
2076
  for (var name in all)
2062
- __defProp2(target, name, { get: all[name], enumerable: true });
2077
+ __defProp2(target2, name, { get: all[name], enumerable: true });
2063
2078
  };
2064
2079
  var __copyProps2 = (to, from, except, desc) => {
2065
2080
  if (from && typeof from === "object" || typeof from === "function") {
@@ -2069,6 +2084,14 @@ var require_dist7 = __commonJS({
2069
2084
  }
2070
2085
  return to;
2071
2086
  };
2087
+ var __toESM2 = (mod, isNodeMode, target2) => (target2 = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
2088
+ // If the importer is in node compatibility mode or this is not an ESM
2089
+ // file that has been converted to a CommonJS file using a Babel-
2090
+ // compatible transform (i.e. "__esModule" has not been set), then set
2091
+ // "default" to the CommonJS "module.exports" for node compatibility.
2092
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target2, "default", { value: mod, enumerable: true }) : target2,
2093
+ mod
2094
+ ));
2072
2095
  var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
2073
2096
  var index_exports = {};
2074
2097
  __export(index_exports, {
@@ -2207,6 +2230,16 @@ var require_dist7 = __commonJS({
2207
2230
  reducer: (_, value) => value,
2208
2231
  default: () => null
2209
2232
  }),
2233
+ /** Whether the model may ask to read and search the project before proposing a fix */
2234
+ tools: (0, import_langgraph.Annotation)({
2235
+ reducer: (_, value) => value,
2236
+ default: () => false
2237
+ }),
2238
+ /** With tools on, the most requests to read or search in each attempt */
2239
+ maxToolRequests: (0, import_langgraph.Annotation)({
2240
+ reducer: (_, value) => value ?? 3,
2241
+ default: () => 3
2242
+ }),
2210
2243
  /** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
2211
2244
  timeoutMs: (0, import_langgraph.Annotation)({
2212
2245
  reducer: (_, value) => value,
@@ -2214,7 +2247,7 @@ var require_dist7 = __commonJS({
2214
2247
  })
2215
2248
  });
2216
2249
  var import_ai_provider = require_dist5();
2217
- var import_prompts = require_dist6();
2250
+ var import_prompts5 = require_dist6();
2218
2251
  var import_config2 = require_dist();
2219
2252
  var import_patcher3 = require_dist3();
2220
2253
  var import_analyzers2 = require_dist4();
@@ -2253,62 +2286,436 @@ var require_dist7 = __commonJS({
2253
2286
  if (snapshot.errorCount === null) return `output it cannot count${where}`;
2254
2287
  return `${snapshot.errorCount} error${snapshot.errorCount === 1 ? "" : "s"}${where}`;
2255
2288
  }
2289
+ var import_prompts4 = require_dist6();
2290
+ var import_shared22 = require_dist2();
2256
2291
  var import_shared4 = require_dist2();
2292
+ function oneLine(text) {
2293
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").slice(0, 500);
2294
+ }
2295
+ function fenced(content) {
2296
+ const longest = Math.max(0, ...(content.match(/`+/g) ?? []).map((run) => run.length));
2297
+ const fence = "`".repeat(Math.max(3, longest + 1));
2298
+ return `${fence}
2299
+ ${content}${content.endsWith("\n") ? "" : "\n"}${fence}`;
2300
+ }
2301
+ function neverShown(pattern) {
2302
+ return `files matching "${pattern}" are never shown (secrets, protected files, .git, node_modules, build output and BugZero's backups).`;
2303
+ }
2304
+ function locate(cwd, requested, rules) {
2305
+ const resolved = (0, import_shared4.resolveInsideProject)(cwd, requested);
2306
+ if (!resolved.ok) return { ok: false, reason: resolved.error };
2307
+ const relPaths = (0, import_shared4.projectRelativePaths)(cwd, resolved.absolutePath);
2308
+ if (relPaths.some((rel) => rel.includes(":"))) return { ok: false, reason: 'the path contains ":".' };
2309
+ for (const rel of relPaths) {
2310
+ const pattern = rules.readBlockedBy(rel);
2311
+ if (pattern !== void 0) return { ok: false, reason: neverShown(pattern) };
2312
+ }
2313
+ return { ok: true, absolutePath: resolved.absolutePath, relPath: relPaths[0] };
2314
+ }
2315
+ var import_fs2 = __toESM2(require("fs"));
2316
+ var import_prompts = require_dist6();
2317
+ var MAX_LOADABLE_BYTES = 5 * 1024 * 1024;
2318
+ function notShown(name, reason) {
2319
+ return { text: `--- File: ${oneLine(name)} ---
2320
+ Not shown: ${oneLine(reason)}`, used: 0, refused: oneLine(name) };
2321
+ }
2322
+ function load(cwd, requested, rules) {
2323
+ const found = locate(cwd, requested, rules);
2324
+ if (!found.ok) return found;
2325
+ try {
2326
+ const stats = import_fs2.default.statSync(found.absolutePath);
2327
+ if (stats.isDirectory()) return { ok: false, reason: "that is a folder, not a file." };
2328
+ if (!stats.isFile()) return { ok: false, reason: "that is not a regular file." };
2329
+ if (stats.size > MAX_LOADABLE_BYTES) return { ok: false, reason: "the file is too large to read." };
2330
+ const bytes = import_fs2.default.readFileSync(found.absolutePath);
2331
+ if (bytes.includes(0)) return { ok: false, reason: "it looks like a binary file." };
2332
+ return { ok: true, relPath: found.relPath, content: bytes.toString("utf-8") };
2333
+ } catch (error) {
2334
+ const missing = error.code === "ENOENT";
2335
+ return { ok: false, reason: missing ? "there is no such file." : "the file could not be read." };
2336
+ }
2337
+ }
2338
+ function readOne(cwd, request, rules, remaining) {
2339
+ const file = load(cwd, request.path, rules);
2340
+ if (!file.ok) return notShown(request.path, file.reason);
2341
+ const name = oneLine(file.relPath);
2342
+ if (file.content === "") {
2343
+ return { text: `--- File: ${name} ---
2344
+ (the file is empty)`, used: 0, sent: `${name} (empty)` };
2345
+ }
2346
+ const lines = file.content.split(/(?<=\n)/);
2347
+ const total = lines.length;
2348
+ const start = request.startLine ?? 1;
2349
+ if (start > total) {
2350
+ return notShown(file.relPath, `the file has only ${total} line${total === 1 ? "" : "s"}.`);
2351
+ }
2352
+ const end = Math.min(request.endLine ?? total, total);
2353
+ const limit = Math.min(import_prompts.MAX_REQUESTED_FILE_CHARS, remaining);
2354
+ let content = "";
2355
+ let last = start - 1;
2356
+ while (last < end && content.length + lines[last].length <= limit) {
2357
+ content += lines[last];
2358
+ last++;
2359
+ }
2360
+ let note = "";
2361
+ if (last < start) {
2362
+ if (limit < import_prompts.MAX_REQUESTED_FILE_CHARS) {
2363
+ return notShown(file.relPath, "this request has reached its size limit. Ask for this file again.");
2364
+ }
2365
+ content = lines[start - 1].slice(0, limit);
2366
+ last = start;
2367
+ note = `
2368
+ [Cut here: line ${start} is longer than the limit.${start < total ? ` To see what follows it, ask for "startLine": ${start + 1}.` : ""}]`;
2369
+ } else if (last < end) {
2370
+ const left = total - last;
2371
+ note = `
2372
+ [Cut here by the size limit: ${left} more line${left === 1 ? "" : "s"} in this file. To see them, ask for "startLine": ${last + 1}.]`;
2373
+ }
2374
+ const range = `lines ${start}-${last} of ${total}`;
2375
+ return {
2376
+ text: `--- File: ${name} (${range}) ---
2377
+ ${fenced(content)}${note}`,
2378
+ used: content.length,
2379
+ sent: `${name} (${range})`
2380
+ };
2381
+ }
2382
+ function readRequestedFiles(cwd, files, rules) {
2383
+ let remaining = import_prompts.MAX_REQUEST_CHARS;
2384
+ const sections = files.slice(0, import_prompts.MAX_FILES_PER_REQUEST).map((request) => {
2385
+ const section = readOne(cwd, request, rules, remaining);
2386
+ remaining -= section.used;
2387
+ return section;
2388
+ });
2389
+ const texts = sections.map((section) => section.text);
2390
+ const extra = files.length - import_prompts.MAX_FILES_PER_REQUEST;
2391
+ if (extra > 0) {
2392
+ texts.push(
2393
+ `${extra} more file${extra === 1 ? " was" : "s were"} not read: one request may ask for at most ${import_prompts.MAX_FILES_PER_REQUEST} files.`
2394
+ );
2395
+ }
2396
+ const sent = sections.flatMap((section) => section.sent ?? []);
2397
+ const refused = sections.flatMap((section) => section.refused ?? []);
2398
+ const withheld = refused.length ? `; not sending ${refused.join(", ")}` : "";
2399
+ return {
2400
+ text: `### Files you asked for
2401
+
2402
+ ${texts.join("\n\n")}`,
2403
+ summary: `sending ${sent.join(", ") || "no files"}${withheld}`
2404
+ };
2405
+ }
2406
+ var import_prompts2 = require_dist6();
2407
+ var NONE = { kind: "none" };
2408
+ function invalid(error) {
2409
+ return { kind: "invalid", error };
2410
+ }
2411
+ function isObject(value) {
2412
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2413
+ }
2414
+ function isLineNumber(value) {
2415
+ return typeof value === "number" && Number.isInteger(value) && value >= 1;
2416
+ }
2417
+ function parseFile(entry) {
2418
+ const file = typeof entry === "string" ? { path: entry } : entry;
2419
+ if (!isObject(file) || typeof file.path !== "string" || file.path.trim() === "") {
2420
+ return 'Every entry in "files" needs a "path" that names a file.';
2421
+ }
2422
+ const request = { path: file.path };
2423
+ for (const key of ["startLine", "endLine"]) {
2424
+ const value = file[key];
2425
+ if (value === void 0 || value === null) continue;
2426
+ if (!isLineNumber(value)) return `"${key}" must be a line number: a whole number, 1 or more.`;
2427
+ request[key] = value;
2428
+ }
2429
+ if (request.endLine !== void 0 && request.endLine < (request.startLine ?? 1)) {
2430
+ return 'The line range is backwards: "endLine" is before "startLine".';
2431
+ }
2432
+ return request;
2433
+ }
2434
+ function parseReadFile(request) {
2435
+ if (!Array.isArray(request.files) || request.files.length === 0) {
2436
+ return invalid('"files" must be a list with at least one entry, each with a "path".');
2437
+ }
2438
+ const files = [];
2439
+ for (const entry of request.files) {
2440
+ const file = parseFile(entry);
2441
+ if (typeof file === "string") return invalid(file);
2442
+ files.push(file);
2443
+ }
2444
+ return { kind: "read_file", files };
2445
+ }
2446
+ function parseSearch({ text, path: path22 }) {
2447
+ if (typeof text !== "string" || text.trim() === "" || /[\r\n]/.test(text) || text.length > import_prompts2.MAX_SEARCH_TEXT_CHARS) {
2448
+ return invalid(`"text" must be the text to find: one line of at most ${import_prompts2.MAX_SEARCH_TEXT_CHARS} characters.`);
2449
+ }
2450
+ if (path22 === void 0 || path22 === null || typeof path22 === "string" && path22.trim() === "") {
2451
+ return { kind: "search", text };
2452
+ }
2453
+ if (typeof path22 !== "string") return invalid('"path" must name one folder or file, or be left out.');
2454
+ return { kind: "search", text, path: path22 };
2455
+ }
2456
+ function parseToolRequest(reply) {
2457
+ const cleaned = reply.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
2458
+ const start = cleaned.indexOf("{");
2459
+ if (start === -1) return NONE;
2460
+ const looksLikeRequest = /^\{\s*"tool"\s*:/.test(cleaned.slice(start));
2461
+ let parsed;
2462
+ try {
2463
+ parsed = JSON.parse(cleaned.slice(start, cleaned.lastIndexOf("}") + 1));
2464
+ } catch {
2465
+ return looksLikeRequest ? invalid("The request is not valid JSON. Reply with exactly one complete JSON object.") : NONE;
2466
+ }
2467
+ if (!isObject(parsed) || !("tool" in parsed)) return NONE;
2468
+ if (Array.isArray(parsed.patches) && parsed.patches.length > 0) return NONE;
2469
+ switch (parsed.tool) {
2470
+ case "read_file":
2471
+ return parseReadFile(parsed);
2472
+ case "search":
2473
+ return parseSearch(parsed);
2474
+ default:
2475
+ return invalid(`There is no tool called ${JSON.stringify(parsed.tool)}. The tools are "read_file" and "search".`);
2476
+ }
2477
+ }
2478
+ var import_fs22 = __toESM2(require("fs"));
2479
+ var import_path3 = __toESM2(require("path"));
2480
+ var import_prompts3 = require_dist6();
2481
+ var MAX_SEARCHED_FILES = 5e3;
2482
+ var MAX_SEARCHED_BYTES = 1024 * 1024;
2483
+ var MAX_LINE_CHARS = 200;
2484
+ var GENERATED_FOLDERS = /* @__PURE__ */ new Set([".next", ".turbo", "coverage"]);
2485
+ var joinRel = (folder, name) => folder === "" ? name : `${folder}/${name}`;
2486
+ function allowed(rules, relPaths) {
2487
+ return relPaths.every((rel) => rules.readBlockedBy(rel) === void 0);
2488
+ }
2489
+ function* filesBelow(folder, rules) {
2490
+ let entries;
2491
+ try {
2492
+ entries = import_fs22.default.readdirSync(folder.absolutePath, { withFileTypes: true });
2493
+ } catch {
2494
+ return;
2495
+ }
2496
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
2497
+ const child = (name) => ({
2498
+ absolutePath: import_path3.default.join(folder.absolutePath, name),
2499
+ relPaths: [joinRel(folder.relPaths[0], name), joinRel(folder.relPaths[1], name)]
2500
+ });
2501
+ for (const entry of entries) {
2502
+ if (!entry.isFile()) continue;
2503
+ const file = child(entry.name);
2504
+ if (allowed(rules, file.relPaths)) yield file;
2505
+ }
2506
+ for (const entry of entries) {
2507
+ if (!entry.isDirectory() || GENERATED_FOLDERS.has(entry.name)) continue;
2508
+ const subfolder = child(entry.name);
2509
+ if (allowed(rules, subfolder.relPaths)) yield* filesBelow(subfolder, rules);
2510
+ }
2511
+ }
2512
+ function target(cwd, requested, rules) {
2513
+ const root = import_path3.default.resolve(cwd);
2514
+ if (requested === void 0 || import_path3.default.resolve(root, requested) === root) {
2515
+ return { ok: true, files: filesBelow({ absolutePath: root, relPaths: ["", ""] }, rules), where: "" };
2516
+ }
2517
+ const found = locate(cwd, requested, rules);
2518
+ if (!found.ok) return found;
2519
+ try {
2520
+ const stats = import_fs22.default.statSync(found.absolutePath);
2521
+ const realPath = import_fs22.default.realpathSync.native(found.absolutePath);
2522
+ const real = import_path3.default.relative(import_fs22.default.realpathSync.native(root), realPath).split(import_path3.default.sep).join("/");
2523
+ const start = { absolutePath: realPath, relPaths: [real, found.relPath] };
2524
+ const where = found.relPath;
2525
+ if (stats.isDirectory()) return { ok: true, files: filesBelow(start, rules), where };
2526
+ if (stats.isFile()) return { ok: true, files: [start], where };
2527
+ return { ok: false, reason: "that is not a file or a folder." };
2528
+ } catch {
2529
+ return { ok: false, reason: "there is no such file or folder." };
2530
+ }
2531
+ }
2532
+ function excerpt(line, matchAt) {
2533
+ if (line.length <= MAX_LINE_CHARS) return line;
2534
+ const from = Math.max(0, matchAt - MAX_LINE_CHARS / 2);
2535
+ const to = from + MAX_LINE_CHARS;
2536
+ return `${from > 0 ? "..." : ""}${line.slice(from, to)}${to < line.length ? "..." : ""}`;
2537
+ }
2538
+ var plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
2539
+ function searchProject(cwd, request, rules) {
2540
+ const quoted = oneLine(JSON.stringify(request.text));
2541
+ const found = target(cwd, request.path, rules);
2542
+ if (!found.ok) {
2543
+ return {
2544
+ text: `### Search results for ${quoted}
2545
+ Not searched: ${oneLine(found.reason)}`,
2546
+ summary: `searched for ${quoted}: not searched (${oneLine(request.path ?? "")} cannot be searched)`
2547
+ };
2548
+ }
2549
+ const needle = request.text.toLowerCase();
2550
+ const matches = [];
2551
+ const notes = /* @__PURE__ */ new Set();
2552
+ let searched = 0;
2553
+ let matchedFiles = 0;
2554
+ let large = 0;
2555
+ search: for (const file of found.files) {
2556
+ if (searched >= MAX_SEARCHED_FILES) {
2557
+ notes.add(`The search stopped after ${MAX_SEARCHED_FILES} files. Give a "path" to search the rest.`);
2558
+ break;
2559
+ }
2560
+ searched++;
2561
+ let content;
2562
+ try {
2563
+ if (import_fs22.default.statSync(file.absolutePath).size > MAX_SEARCHED_BYTES) {
2564
+ large++;
2565
+ continue;
2566
+ }
2567
+ const bytes = import_fs22.default.readFileSync(file.absolutePath);
2568
+ if (bytes.includes(0)) continue;
2569
+ content = bytes.toString("utf-8");
2570
+ } catch {
2571
+ continue;
2572
+ }
2573
+ let inThisFile = 0;
2574
+ for (const [index, line] of content.split(/\r?\n/).entries()) {
2575
+ const at = line.toLowerCase().indexOf(needle);
2576
+ if (at === -1) continue;
2577
+ if (inThisFile === import_prompts3.MAX_SEARCH_MATCHES_PER_FILE) {
2578
+ notes.add(`Only the first ${import_prompts3.MAX_SEARCH_MATCHES_PER_FILE} matching lines of a file are shown. Read the file to see the rest.`);
2579
+ break;
2580
+ }
2581
+ if (matches.length === import_prompts3.MAX_SEARCH_MATCHES) {
2582
+ notes.add(`Only the first ${import_prompts3.MAX_SEARCH_MATCHES} matching lines are shown. Search a narrower "path" or a longer text.`);
2583
+ break search;
2584
+ }
2585
+ if (inThisFile === 0) matchedFiles++;
2586
+ inThisFile++;
2587
+ matches.push(`${oneLine(file.relPaths[1])}:${index + 1}: ${excerpt(line, at)}`);
2588
+ }
2589
+ }
2590
+ if (large > 0) notes.add(`${plural(large, "large file")} ${large === 1 ? "was" : "were"} not searched.`);
2591
+ const heading = `### Search results for ${quoted}${found.where ? ` in ${oneLine(found.where)}` : ""}`;
2592
+ const body = matches.length ? fenced(matches.join("\n")) : "No lines containing that text were found in the files you may see.";
2593
+ const footer = [...notes].map((note) => `
2594
+ [${note}]`).join("");
2595
+ const sending = matches.length ? `sending ${plural(matches.length, "matching line")} from ${plural(matchedFiles, "file")}` : "0 matching lines";
2596
+ return { text: `${heading}
2597
+ ${body}${footer}`, summary: `searched for ${quoted}: ${sending}` };
2598
+ }
2599
+ function answerToolRequest(reply, cwd, rules = (0, import_shared22.createProtectedPathRules)()) {
2600
+ const request = parseToolRequest(reply);
2601
+ switch (request.kind) {
2602
+ case "none":
2603
+ return null;
2604
+ case "invalid":
2605
+ return {
2606
+ text: `### Your request could not be used
2607
+ ${request.error}
2608
+
2609
+ Reply with the fix, or with a request like one of these:
2610
+ ${import_prompts4.FILE_REQUEST_EXAMPLE}
2611
+ ${import_prompts4.SEARCH_REQUEST_EXAMPLE}`,
2612
+ summary: `a request that could not be used: ${oneLine(request.error)}`
2613
+ };
2614
+ case "read_file":
2615
+ return readRequestedFiles(cwd, request.files, rules);
2616
+ case "search":
2617
+ return searchProject(cwd, request, rules);
2618
+ }
2619
+ }
2620
+ function remainingNote(left) {
2621
+ if (left === 0) return "That was your last request in this attempt. Reply with the fix now.";
2622
+ return `You may make ${left} more request${left === 1 ? "" : "s"} in this attempt, or reply with the fix now.`;
2623
+ }
2624
+ async function runToolConversation(options) {
2625
+ const { cwd, rules, maxRequests, ask, onRequest } = options;
2626
+ let prompt = options.prompt;
2627
+ let reply = await ask(prompt);
2628
+ for (let used = 1; reply !== null && used <= maxRequests; used++) {
2629
+ const answer = answerToolRequest(reply, cwd, rules);
2630
+ if (answer === null) break;
2631
+ onRequest?.(answer.summary, used);
2632
+ prompt += `
2633
+
2634
+ ${answer.text}
2635
+
2636
+ ${remainingNote(maxRequests - used)}`;
2637
+ reply = await ask(prompt);
2638
+ }
2639
+ const limitReached = maxRequests > 0 && reply !== null && parseToolRequest(reply).kind !== "none";
2640
+ return { reply, limitReached };
2641
+ }
2642
+ var import_shared32 = require_dist2();
2257
2643
  var provider = new import_ai_provider.OpenRouterProvider();
2258
2644
  function protectionFor(cwd) {
2259
- return (0, import_shared4.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
2645
+ return (0, import_shared32.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
2260
2646
  }
2261
- function previewAnalysisPrompt(cwd, logs) {
2262
- return (0, import_prompts.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd) });
2647
+ function previewAnalysisPrompt(cwd, logs, options = {}) {
2648
+ return (0, import_prompts5.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd), toolRequests: options.toolRequests });
2263
2649
  }
2264
- async function analyzeNode(state) {
2265
- const prompt = previewAnalysisPrompt(state.cwd, state.logs);
2266
- const used = state.promptTokens + state.completionTokens;
2267
- const budget = (0, import_shared4.checkBudget)(state.maxTokens, used, prompt);
2268
- if (!budget.allowed) {
2269
- console.log(`
2270
- [BugZero] ${budget.reason} Stopping before attempt ${state.attempts + 1}.`);
2271
- return { budgetStop: budget.reason };
2272
- }
2273
- console.log(
2274
- `
2275
- [BugZero] Attempt ${state.attempts + 1}/${state.maxAttempts} \u2014 asking AI\u2026`
2276
- );
2277
- const result = await provider.invoke(prompt, { cwd: state.cwd, maxTokens: budget.maxReplyTokens });
2278
- const response = result.content;
2279
- const tokens = (0, import_shared4.countCallTokens)(state.maxTokens, prompt, result);
2280
- if (state.maxTokens !== void 0) {
2281
- const total = used + tokens.promptTokens + tokens.completionTokens;
2282
- const note = tokens.estimated ? " (an estimate: the model did not report its token usage)" : "";
2283
- console.log(`[BugZero] Token budget: ${total} of ${state.maxTokens} used${note}.`);
2284
- if (result.truncated) console.log("[BugZero] The AI reply was cut off by its length limit, so it may be unusable.");
2285
- }
2286
- let fixSuggestion = null;
2650
+ function parseFix(response) {
2287
2651
  try {
2288
2652
  const cleaned = response.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
2289
2653
  const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
2290
- if (jsonMatch) {
2291
- const parsed = JSON.parse(jsonMatch[0]);
2292
- if (Array.isArray(parsed.patches) && parsed.patches.length > 0) {
2293
- fixSuggestion = parsed;
2294
- } else {
2295
- console.warn('[BugZero] AI response JSON did not contain a non-empty "patches" array.');
2296
- }
2297
- } else {
2654
+ if (!jsonMatch) {
2298
2655
  console.warn("[BugZero] AI response did not contain a valid JSON object.");
2656
+ return null;
2299
2657
  }
2658
+ const parsed = JSON.parse(jsonMatch[0]);
2659
+ if (Array.isArray(parsed.patches) && parsed.patches.length > 0) return parsed;
2660
+ console.warn('[BugZero] AI response JSON did not contain a non-empty "patches" array.');
2300
2661
  } catch (e) {
2301
2662
  console.error("[BugZero] Failed to parse AI response:", e);
2302
2663
  }
2303
- return {
2304
- analysis: response,
2305
- fixSuggestion,
2306
- attempts: state.attempts + 1,
2307
- modelUsed: result.model,
2308
- promptTokens: tokens.promptTokens,
2309
- completionTokens: tokens.completionTokens,
2310
- tokensEstimated: tokens.estimated
2664
+ return null;
2665
+ }
2666
+ async function analyzeNode(state) {
2667
+ const attempt = state.attempts + 1;
2668
+ const maxRequests = state.tools ? state.maxToolRequests : 0;
2669
+ const spent = { promptTokens: 0, completionTokens: 0, estimated: false };
2670
+ let sent = 0;
2671
+ let modelUsed = "";
2672
+ let budgetStop = null;
2673
+ const ask = async (prompt) => {
2674
+ const used = () => state.promptTokens + state.completionTokens + spent.promptTokens + spent.completionTokens;
2675
+ const budget = (0, import_shared32.checkBudget)(state.maxTokens, used(), prompt);
2676
+ if (!budget.allowed) {
2677
+ budgetStop = budget.reason;
2678
+ console.log(`
2679
+ [BugZero] ${budget.reason} Stopping ${sent === 0 ? "before" : "during"} attempt ${attempt}.`);
2680
+ return null;
2681
+ }
2682
+ if (sent === 0) console.log(`
2683
+ [BugZero] Attempt ${attempt}/${state.maxAttempts} \u2014 asking AI\u2026`);
2684
+ const result = await provider.invoke(prompt, { cwd: state.cwd, maxTokens: budget.maxReplyTokens });
2685
+ sent++;
2686
+ modelUsed = result.model;
2687
+ const tokens = (0, import_shared32.countCallTokens)(state.maxTokens, prompt, result);
2688
+ spent.promptTokens += tokens.promptTokens;
2689
+ spent.completionTokens += tokens.completionTokens;
2690
+ spent.estimated ||= tokens.estimated;
2691
+ if (state.maxTokens !== void 0) {
2692
+ const note = tokens.estimated ? " (an estimate: the model did not report its token usage)" : "";
2693
+ console.log(`[BugZero] Token budget: ${used()} of ${state.maxTokens} used${note}.`);
2694
+ if (result.truncated) console.log("[BugZero] The AI reply was cut off by its length limit, so it may be unusable.");
2695
+ }
2696
+ return result.content;
2311
2697
  };
2698
+ const { reply, limitReached } = await runToolConversation({
2699
+ prompt: previewAnalysisPrompt(state.cwd, state.logs, { toolRequests: maxRequests }),
2700
+ cwd: state.cwd,
2701
+ rules: protectionFor(state.cwd),
2702
+ maxRequests,
2703
+ ask,
2704
+ onRequest: (summary, used) => console.log(`[BugZero] The AI asked to look further (request ${used} of ${maxRequests}): ${summary}`)
2705
+ });
2706
+ if (sent === 0) return { budgetStop };
2707
+ const cost = {
2708
+ attempts: attempt,
2709
+ modelUsed,
2710
+ promptTokens: spent.promptTokens,
2711
+ completionTokens: spent.completionTokens,
2712
+ tokensEstimated: spent.estimated
2713
+ };
2714
+ if (reply === null) return { ...cost, budgetStop };
2715
+ if (limitReached) {
2716
+ console.warn("[BugZero] The AI asked to look further again after its last request, so this attempt has no fix.");
2717
+ }
2718
+ return { ...cost, analysis: reply, fixSuggestion: limitReached ? null : parseFix(reply) };
2312
2719
  }
2313
2720
  function patchFailure(state, error) {
2314
2721
  console.error(`[BugZero] Patch failed: ${error}`);
@@ -2479,6 +2886,7 @@ var require_dist8 = __commonJS({
2479
2886
  var index_exports = {};
2480
2887
  __export(index_exports, {
2481
2888
  DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS,
2889
+ DEFAULT_MAX_TOOL_REQUESTS: () => DEFAULT_MAX_TOOL_REQUESTS,
2482
2890
  DEFAULT_PATIENCE: () => DEFAULT_PATIENCE,
2483
2891
  REPORT_FILENAME: () => REPORT_FILENAME2,
2484
2892
  detectFramework: () => detectFramework2,
@@ -2488,8 +2896,10 @@ var require_dist8 = __commonJS({
2488
2896
  resolveFocusTests: () => resolveFocusTests,
2489
2897
  resolveMaxAttempts: () => resolveMaxAttempts2,
2490
2898
  resolveMaxTokens: () => resolveMaxTokens2,
2899
+ resolveMaxToolRequests: () => resolveMaxToolRequests2,
2491
2900
  resolvePatience: () => resolvePatience2,
2492
- resolveTimeoutMs: () => resolveTimeoutMs2
2901
+ resolveTimeoutMs: () => resolveTimeoutMs2,
2902
+ resolveTools: () => resolveTools
2493
2903
  });
2494
2904
  module2.exports = __toCommonJS(index_exports);
2495
2905
  var import_fs2 = __toESM2(require("fs"));
@@ -2679,6 +3089,25 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2679
3089
  }
2680
3090
  return value;
2681
3091
  }
3092
+ function resolveTools(flag, configured) {
3093
+ if (flag !== void 0) return flag;
3094
+ if (configured === void 0) return false;
3095
+ if (typeof configured !== "boolean") {
3096
+ throw new Error(`tools in .bugzerorc must be true or false (received ${JSON.stringify(configured)}).`);
3097
+ }
3098
+ return configured;
3099
+ }
3100
+ var DEFAULT_MAX_TOOL_REQUESTS = 3;
3101
+ var HIGHEST_MAX_TOOL_REQUESTS = 20;
3102
+ function resolveMaxToolRequests2(flag, configured) {
3103
+ const source = flag !== void 0 ? "--max-tool-requests" : "maxToolRequests in .bugzerorc";
3104
+ const value = flag !== void 0 ? flag : configured;
3105
+ if (value === void 0) return DEFAULT_MAX_TOOL_REQUESTS;
3106
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > HIGHEST_MAX_TOOL_REQUESTS) {
3107
+ throw new Error(`${source} must be a whole number from 1 to ${HIGHEST_MAX_TOOL_REQUESTS} (received ${JSON.stringify(value) ?? String(value)}).`);
3108
+ }
3109
+ return value;
3110
+ }
2682
3111
  var import_fs22 = __toESM2(require("fs"));
2683
3112
  var import_path22 = __toESM2(require("path"));
2684
3113
  function assertNodeProject(cwd) {
@@ -2731,6 +3160,17 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2731
3160
  const patience = resolvePatience2(options.patience, config.patience);
2732
3161
  const focusTests = resolveFocusTests(options.focusTests, config.focusTests);
2733
3162
  const maxTokens = resolveMaxTokens2(options.maxTokens, config.maxTokens);
3163
+ const tools = resolveTools(options.tools, config.tools);
3164
+ const maxToolRequests = resolveMaxToolRequests2(options.maxToolRequests, config.maxToolRequests);
3165
+ const announceTools = () => {
3166
+ if (tools) {
3167
+ console.log(
3168
+ `[BugZero] Tools on: the AI model may ask to read and search project files, up to ${maxToolRequests} request${maxToolRequests === 1 ? "" : "s"} per attempt.`
3169
+ );
3170
+ } else if (options.maxToolRequests !== void 0) {
3171
+ console.log("[BugZero] --max-tool-requests has no effect because tools are off (turn them on with --tools).");
3172
+ }
3173
+ };
2734
3174
  console.log(`[BugZero] Running validation pipeline in: ${cwd}`);
2735
3175
  const pipelineResult = await (0, import_analyzers.runValidationPipeline)(cwd, { timeoutMs });
2736
3176
  if (pipelineResult.success) {
@@ -2752,11 +3192,12 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2752
3192
  console.log(`[BugZero] Detected ${errors.length} error(s) (type: ${errors[0]?.type ?? "unknown"})`);
2753
3193
  if (options.printPrompt) {
2754
3194
  console.log("[BugZero] --print-prompt: showing the first prompt without sending it.");
3195
+ announceTools();
2755
3196
  return {
2756
3197
  success: false,
2757
3198
  attempts: 0,
2758
3199
  finalOutput: pipelineResult.output,
2759
- promptPreview: (0, import_agents.previewAnalysisPrompt)(cwd, pipelineResult.output)
3200
+ promptPreview: (0, import_agents.previewAnalysisPrompt)(cwd, pipelineResult.output, { toolRequests: tools ? maxToolRequests : 0 })
2760
3201
  };
2761
3202
  }
2762
3203
  if (options.dryRun) {
@@ -2778,6 +3219,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2778
3219
  ...tokenBudgetUse(maxTokens, spend2)
2779
3220
  };
2780
3221
  }
3222
+ announceTools();
2781
3223
  const finalState = await (0, import_agents.runRepairWorkflow)({
2782
3224
  cwd,
2783
3225
  logs: pipelineResult.output,
@@ -2787,6 +3229,8 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
2787
3229
  patience,
2788
3230
  focusTests,
2789
3231
  maxTokens,
3232
+ tools,
3233
+ maxToolRequests,
2790
3234
  initialStep: pipelineResult.step
2791
3235
  });
2792
3236
  const result = {
@@ -3353,7 +3797,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
3353
3797
  finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
3354
3798
  }
3355
3799
  });
3356
- program.command("rescue").description("Detect build failures and automatically apply AI-generated fixes").option("-p, --path <dir>", "Path to the target project", ".").option("-n, --max-attempts <number>", "Maximum AI fix attempts", "3").option("-t, --timeout <seconds>", TIMEOUT_DESCRIPTION).option("--patience <n>", "Stop early after this many attempts in a row make no progress (default 2, 0 turns it off)").option("--max-tokens <n>", "Limit the AI tokens the run may use, the report included (default no limit, 0 for none)").option("--no-focus-tests", "Always run the full build, lint and tests, instead of re-running only the failing test files between attempts").option("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).option("--approve", "Show each proposed fix as a diff and ask before writing it (needs an interactive terminal)").option("--print-prompt", "Print the exact prompt that would be sent to the AI model, then stop (nothing is sent, no files are written)").option("--json", JSON_DESCRIPTION).action(async (opts) => {
3800
+ program.command("rescue").description("Detect build failures and automatically apply AI-generated fixes").option("-p, --path <dir>", "Path to the target project", ".").option("-n, --max-attempts <number>", "Maximum AI fix attempts", "3").option("-t, --timeout <seconds>", TIMEOUT_DESCRIPTION).option("--patience <n>", "Stop early after this many attempts in a row make no progress (default 2, 0 turns it off)").option("--max-tokens <n>", "Limit the AI tokens the run may use, the report included (default no limit, 0 for none)").option("--no-focus-tests", "Always run the full build, lint and tests, instead of re-running only the failing test files between attempts").option("--tools", "Let the AI model ask to read and search project files before proposing a fix (off by default; sends more of your code)").option("--no-tools", "Do not offer those tools, even if .bugzerorc turns them on").option("--max-tool-requests <n>", "With tools, the most such requests per attempt, 1 to 20 (default 3)").option("--dry-run", "Analyse only \u2014 print what would be fixed without writing files", false).option("--approve", "Show each proposed fix as a diff and ask before writing it (needs an interactive terminal)").option("--print-prompt", "Print the exact prompt that would be sent to the AI model, then stop (nothing is sent, no files are written)").option("--json", JSON_DESCRIPTION).action(async (opts) => {
3357
3801
  const json = opts.json === true;
3358
3802
  const printPrompt = opts.printPrompt === true;
3359
3803
  if (json || printPrompt) routeLogsToStderr();
@@ -3367,6 +3811,9 @@ program.command("rescue").description("Detect build failures and automatically a
3367
3811
  const maxTokens = opts.maxTokens === void 0 ? void 0 : Number(opts.maxTokens);
3368
3812
  (0, import_core.resolveMaxTokens)(maxTokens, void 0);
3369
3813
  const focusTests = opts.focusTests === false ? false : void 0;
3814
+ const tools = opts.tools;
3815
+ const maxToolRequests = opts.maxToolRequests === void 0 ? void 0 : Number(opts.maxToolRequests);
3816
+ (0, import_core.resolveMaxToolRequests)(maxToolRequests, void 0);
3370
3817
  const dryRun = opts.dryRun;
3371
3818
  let approve;
3372
3819
  if (opts.approve === true && !dryRun && !printPrompt) {
@@ -3400,7 +3847,9 @@ program.command("rescue").description("Detect build failures and automatically a
3400
3847
  approve,
3401
3848
  patience,
3402
3849
  focusTests,
3403
- maxTokens
3850
+ maxTokens,
3851
+ tools,
3852
+ maxToolRequests
3404
3853
  });
3405
3854
  if (result.promptPreview !== void 0) {
3406
3855
  if (json) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugzero",
3
- "version": "0.0.62",
3
+ "version": "0.0.63",
4
4
  "description": "Autonomous AI-powered CLI and GitHub Action that detects build, lint, and test failures, generates multi-file patches, applies them atomically with fuzzy matching, and re-verifies until your project is green.",
5
5
  "license": "MIT",
6
6
  "author": "Saksham Agarwal (https://github.com/Saksham1800t)",