bugzero 0.0.62 → 0.0.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -6
- package/dist/index.js +520 -67
- 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/`,
|
|
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/`, its own `.opspilot.bak` backups, or its settings file `.bugzerorc`. 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), except that a fix can never edit `.bugzerorc` itself, so it cannot change these rules. 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). |
|
|
334
|
-
| `allow` | Files from the built-in list that BugZero may edit and read after all, such as `.env.example`. A `protect` pattern still wins. |
|
|
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. |
|
|
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, and `.bugzerorc` is never editable. |
|
|
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
|
@@ -502,6 +502,7 @@ var require_dist2 = __commonJS({
|
|
|
502
502
|
DEFAULT_UNREADABLE_PATTERNS: () => DEFAULT_UNREADABLE_PATTERNS,
|
|
503
503
|
MAX_REPLY_TOKENS: () => MAX_REPLY_TOKENS,
|
|
504
504
|
MIN_REPLY_TOKENS: () => MIN_REPLY_TOKENS,
|
|
505
|
+
SETTINGS_PATTERNS: () => SETTINGS_PATTERNS,
|
|
505
506
|
checkBudget: () => checkBudget,
|
|
506
507
|
countCallTokens: () => countCallTokens,
|
|
507
508
|
createProtectedPathRules: () => createProtectedPathRules2,
|
|
@@ -573,6 +574,8 @@ var require_dist2 = __commonJS({
|
|
|
573
574
|
...DEFAULT_SECRET_PATTERNS,
|
|
574
575
|
".git/",
|
|
575
576
|
"node_modules/",
|
|
577
|
+
"build/",
|
|
578
|
+
"dist/",
|
|
576
579
|
"*.opspilot.bak",
|
|
577
580
|
"*.opspilot.bak.sha"
|
|
578
581
|
];
|
|
@@ -593,6 +596,7 @@ var require_dist2 = __commonJS({
|
|
|
593
596
|
"*.opspilot.bak",
|
|
594
597
|
"*.opspilot.bak.sha"
|
|
595
598
|
];
|
|
599
|
+
var SETTINGS_PATTERNS = [".bugzerorc"];
|
|
596
600
|
function normalizePath(relPath) {
|
|
597
601
|
return relPath.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+/, "").toLowerCase();
|
|
598
602
|
}
|
|
@@ -637,6 +641,7 @@ var require_dist2 = __commonJS({
|
|
|
637
641
|
const defaults = compileAll(DEFAULT_PROTECTED_PATTERNS);
|
|
638
642
|
const secrets = compileAll(DEFAULT_SECRET_PATTERNS);
|
|
639
643
|
const unreadable = compileAll(DEFAULT_UNREADABLE_PATTERNS);
|
|
644
|
+
const settingsFiles = compileAll(SETTINGS_PATTERNS);
|
|
640
645
|
const extra = compileAll(settings.protect);
|
|
641
646
|
const allowed = compileAll(settings.allow);
|
|
642
647
|
const blockedUnlessAllowed = (matchers, relPath) => {
|
|
@@ -644,16 +649,12 @@ var require_dist2 = __commonJS({
|
|
|
644
649
|
if (firstMatch(allowed, normalized)) return void 0;
|
|
645
650
|
return firstMatch(matchers, normalized)?.pattern;
|
|
646
651
|
};
|
|
652
|
+
const blockedOrProtected = (matchers, relPath) => firstMatch(extra, normalizePath(relPath))?.pattern ?? blockedUnlessAllowed(matchers, relPath);
|
|
647
653
|
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
|
-
},
|
|
654
|
+
editBlockedBy: (relPath) => firstMatch(settingsFiles, normalizePath(relPath))?.pattern ?? blockedOrProtected(defaults, relPath),
|
|
655
655
|
secretBlockedBy: (relPath) => blockedUnlessAllowed(secrets, relPath),
|
|
656
|
-
readBlockedBy: (relPath) =>
|
|
656
|
+
readBlockedBy: (relPath) => blockedOrProtected(unreadable, relPath),
|
|
657
|
+
restoreBlockedBy: (relPath) => blockedOrProtected(defaults, relPath)
|
|
657
658
|
};
|
|
658
659
|
}
|
|
659
660
|
function toRelative(root, target) {
|
|
@@ -1279,7 +1280,7 @@ var require_dist3 = __commonJS({
|
|
|
1279
1280
|
entries.push(entry("failed", "The file is outside the project."));
|
|
1280
1281
|
continue;
|
|
1281
1282
|
}
|
|
1282
|
-
const blockedBy = (0, import_shared32.projectRelativePaths)(root, target).map((relPath) => protection.
|
|
1283
|
+
const blockedBy = (0, import_shared32.projectRelativePaths)(root, target).map((relPath) => protection.restoreBlockedBy(relPath)).find((pattern) => pattern !== void 0);
|
|
1283
1284
|
if (blockedBy !== void 0) {
|
|
1284
1285
|
entries.push(entry("protected", `It is protected (it matches "${blockedBy}"), so BugZero does not write to it.`));
|
|
1285
1286
|
continue;
|
|
@@ -1816,8 +1817,12 @@ var require_dist6 = __commonJS({
|
|
|
1816
1817
|
MAX_FILES_PER_REQUEST: () => MAX_FILES_PER_REQUEST,
|
|
1817
1818
|
MAX_REQUESTED_FILE_CHARS: () => MAX_REQUESTED_FILE_CHARS,
|
|
1818
1819
|
MAX_REQUEST_CHARS: () => MAX_REQUEST_CHARS,
|
|
1820
|
+
MAX_SEARCH_MATCHES: () => MAX_SEARCH_MATCHES,
|
|
1821
|
+
MAX_SEARCH_MATCHES_PER_FILE: () => MAX_SEARCH_MATCHES_PER_FILE,
|
|
1822
|
+
MAX_SEARCH_TEXT_CHARS: () => MAX_SEARCH_TEXT_CHARS,
|
|
1823
|
+
SEARCH_REQUEST_EXAMPLE: () => SEARCH_REQUEST_EXAMPLE,
|
|
1819
1824
|
buildAnalysisPrompt: () => buildAnalysisPrompt,
|
|
1820
|
-
|
|
1825
|
+
toolInstructions: () => toolInstructions,
|
|
1821
1826
|
truncateLogs: () => truncateLogs
|
|
1822
1827
|
});
|
|
1823
1828
|
module2.exports = __toCommonJS(index_exports);
|
|
@@ -1827,14 +1832,26 @@ var require_dist6 = __commonJS({
|
|
|
1827
1832
|
var MAX_FILES_PER_REQUEST = 5;
|
|
1828
1833
|
var MAX_REQUESTED_FILE_CHARS = 2e4;
|
|
1829
1834
|
var MAX_REQUEST_CHARS = 6e4;
|
|
1835
|
+
var MAX_SEARCH_TEXT_CHARS = 200;
|
|
1836
|
+
var MAX_SEARCH_MATCHES = 50;
|
|
1837
|
+
var MAX_SEARCH_MATCHES_PER_FILE = 10;
|
|
1830
1838
|
var FILE_REQUEST_EXAMPLE = '{"tool": "read_file", "files": [{"path": "src/types.ts"}, {"path": "src/server.ts", "startLine": 200, "endLine": 320}]}';
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1839
|
+
var SEARCH_REQUEST_EXAMPLE = '{"tool": "search", "text": "interface User", "path": "src"}';
|
|
1840
|
+
function toolInstructions(maxRequests) {
|
|
1841
|
+
return `### Looking at more of the project
|
|
1842
|
+
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.
|
|
1843
|
+
|
|
1844
|
+
To read files:
|
|
1834
1845
|
${FILE_REQUEST_EXAMPLE}
|
|
1835
1846
|
- "path" is relative to the project root. "startLine" and "endLine" are optional.
|
|
1836
1847
|
- 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
|
-
|
|
1848
|
+
|
|
1849
|
+
To find the lines that contain a piece of text:
|
|
1850
|
+
${SEARCH_REQUEST_EXAMPLE}
|
|
1851
|
+
- The text is matched exactly, ignoring case. It is not a pattern or regular expression.
|
|
1852
|
+
- "path" is optional and limits the search to one folder or file. At most ${MAX_SEARCH_MATCHES} matching lines are returned.
|
|
1853
|
+
|
|
1854
|
+
Secret and protected files, .git, node_modules and build output are never shown or searched.`;
|
|
1838
1855
|
}
|
|
1839
1856
|
var MAX_LOG_CHARS = 2e4;
|
|
1840
1857
|
var MAX_FILE_CHARS = 2e4;
|
|
@@ -2008,9 +2025,9 @@ ${w}`).join("\n\n")}
|
|
|
2008
2025
|
}
|
|
2009
2026
|
compilerLogs = truncateLogs(compilerLogs);
|
|
2010
2027
|
const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared4.createProtectedPathRules)());
|
|
2011
|
-
const
|
|
2028
|
+
const toolSection = options.toolRequests ? `
|
|
2012
2029
|
|
|
2013
|
-
${
|
|
2030
|
+
${toolInstructions(options.toolRequests)}` : "";
|
|
2014
2031
|
return `You are an expert software engineer specialising in fixing build, lint, and test failures.
|
|
2015
2032
|
|
|
2016
2033
|
A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
|
|
@@ -2040,11 +2057,11 @@ Reply with ONLY a valid JSON object in this exact shape \u2014 no markdown fence
|
|
|
2040
2057
|
Critical rules:
|
|
2041
2058
|
- "patches" must contain at least one entry. Only include more than one when the fix truly requires editing multiple files \u2014 most fixes need just one.
|
|
2042
2059
|
- Each "filePath" must be a relative path from the project root (no leading /).
|
|
2043
|
-
- Never change secret files (.env and key files), lockfiles, CI workflow files, .git or node_modules. Patches to them are rejected, so fix the problem in another file.
|
|
2060
|
+
- Never change secret files (.env and key files), lockfiles, CI workflow files, .bugzerorc, .git or node_modules. Patches to them are rejected, so fix the problem in another file.
|
|
2044
2061
|
- Each "search" must be an EXACT character-for-character substring of that file's current content.
|
|
2045
2062
|
- Each "replace" must be syntactically valid code.
|
|
2046
2063
|
- 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.${
|
|
2064
|
+
- Do NOT add backticks, markdown, or any text outside the JSON object.${toolSection}`;
|
|
2048
2065
|
}
|
|
2049
2066
|
}
|
|
2050
2067
|
});
|
|
@@ -2053,13 +2070,15 @@ Critical rules:
|
|
|
2053
2070
|
var require_dist7 = __commonJS({
|
|
2054
2071
|
"../../packages/agents/dist/index.js"(exports2, module2) {
|
|
2055
2072
|
"use strict";
|
|
2073
|
+
var __create2 = Object.create;
|
|
2056
2074
|
var __defProp2 = Object.defineProperty;
|
|
2057
2075
|
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
2058
2076
|
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
2077
|
+
var __getProtoOf2 = Object.getPrototypeOf;
|
|
2059
2078
|
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
2060
|
-
var __export = (
|
|
2079
|
+
var __export = (target2, all) => {
|
|
2061
2080
|
for (var name in all)
|
|
2062
|
-
__defProp2(
|
|
2081
|
+
__defProp2(target2, name, { get: all[name], enumerable: true });
|
|
2063
2082
|
};
|
|
2064
2083
|
var __copyProps2 = (to, from, except, desc) => {
|
|
2065
2084
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -2069,6 +2088,14 @@ var require_dist7 = __commonJS({
|
|
|
2069
2088
|
}
|
|
2070
2089
|
return to;
|
|
2071
2090
|
};
|
|
2091
|
+
var __toESM2 = (mod, isNodeMode, target2) => (target2 = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
|
|
2092
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
2093
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
2094
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
2095
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
2096
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp2(target2, "default", { value: mod, enumerable: true }) : target2,
|
|
2097
|
+
mod
|
|
2098
|
+
));
|
|
2072
2099
|
var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
|
|
2073
2100
|
var index_exports = {};
|
|
2074
2101
|
__export(index_exports, {
|
|
@@ -2207,6 +2234,16 @@ var require_dist7 = __commonJS({
|
|
|
2207
2234
|
reducer: (_, value) => value,
|
|
2208
2235
|
default: () => null
|
|
2209
2236
|
}),
|
|
2237
|
+
/** Whether the model may ask to read and search the project before proposing a fix */
|
|
2238
|
+
tools: (0, import_langgraph.Annotation)({
|
|
2239
|
+
reducer: (_, value) => value,
|
|
2240
|
+
default: () => false
|
|
2241
|
+
}),
|
|
2242
|
+
/** With tools on, the most requests to read or search in each attempt */
|
|
2243
|
+
maxToolRequests: (0, import_langgraph.Annotation)({
|
|
2244
|
+
reducer: (_, value) => value ?? 3,
|
|
2245
|
+
default: () => 3
|
|
2246
|
+
}),
|
|
2210
2247
|
/** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
|
|
2211
2248
|
timeoutMs: (0, import_langgraph.Annotation)({
|
|
2212
2249
|
reducer: (_, value) => value,
|
|
@@ -2214,7 +2251,7 @@ var require_dist7 = __commonJS({
|
|
|
2214
2251
|
})
|
|
2215
2252
|
});
|
|
2216
2253
|
var import_ai_provider = require_dist5();
|
|
2217
|
-
var
|
|
2254
|
+
var import_prompts5 = require_dist6();
|
|
2218
2255
|
var import_config2 = require_dist();
|
|
2219
2256
|
var import_patcher3 = require_dist3();
|
|
2220
2257
|
var import_analyzers2 = require_dist4();
|
|
@@ -2253,62 +2290,436 @@ var require_dist7 = __commonJS({
|
|
|
2253
2290
|
if (snapshot.errorCount === null) return `output it cannot count${where}`;
|
|
2254
2291
|
return `${snapshot.errorCount} error${snapshot.errorCount === 1 ? "" : "s"}${where}`;
|
|
2255
2292
|
}
|
|
2293
|
+
var import_prompts4 = require_dist6();
|
|
2294
|
+
var import_shared22 = require_dist2();
|
|
2256
2295
|
var import_shared4 = require_dist2();
|
|
2296
|
+
function oneLine(text) {
|
|
2297
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").slice(0, 500);
|
|
2298
|
+
}
|
|
2299
|
+
function fenced(content) {
|
|
2300
|
+
const longest = Math.max(0, ...(content.match(/`+/g) ?? []).map((run) => run.length));
|
|
2301
|
+
const fence = "`".repeat(Math.max(3, longest + 1));
|
|
2302
|
+
return `${fence}
|
|
2303
|
+
${content}${content.endsWith("\n") ? "" : "\n"}${fence}`;
|
|
2304
|
+
}
|
|
2305
|
+
function neverShown(pattern) {
|
|
2306
|
+
return `files matching "${pattern}" are never shown (secrets, protected files, .git, node_modules, build output and BugZero's backups).`;
|
|
2307
|
+
}
|
|
2308
|
+
function locate(cwd, requested, rules) {
|
|
2309
|
+
const resolved = (0, import_shared4.resolveInsideProject)(cwd, requested);
|
|
2310
|
+
if (!resolved.ok) return { ok: false, reason: resolved.error };
|
|
2311
|
+
const relPaths = (0, import_shared4.projectRelativePaths)(cwd, resolved.absolutePath);
|
|
2312
|
+
if (relPaths.some((rel) => rel.includes(":"))) return { ok: false, reason: 'the path contains ":".' };
|
|
2313
|
+
for (const rel of relPaths) {
|
|
2314
|
+
const pattern = rules.readBlockedBy(rel);
|
|
2315
|
+
if (pattern !== void 0) return { ok: false, reason: neverShown(pattern) };
|
|
2316
|
+
}
|
|
2317
|
+
return { ok: true, absolutePath: resolved.absolutePath, relPath: relPaths[0] };
|
|
2318
|
+
}
|
|
2319
|
+
var import_fs2 = __toESM2(require("fs"));
|
|
2320
|
+
var import_prompts = require_dist6();
|
|
2321
|
+
var MAX_LOADABLE_BYTES = 5 * 1024 * 1024;
|
|
2322
|
+
function notShown(name, reason) {
|
|
2323
|
+
return { text: `--- File: ${oneLine(name)} ---
|
|
2324
|
+
Not shown: ${oneLine(reason)}`, used: 0, refused: oneLine(name) };
|
|
2325
|
+
}
|
|
2326
|
+
function load(cwd, requested, rules) {
|
|
2327
|
+
const found = locate(cwd, requested, rules);
|
|
2328
|
+
if (!found.ok) return found;
|
|
2329
|
+
try {
|
|
2330
|
+
const stats = import_fs2.default.statSync(found.absolutePath);
|
|
2331
|
+
if (stats.isDirectory()) return { ok: false, reason: "that is a folder, not a file." };
|
|
2332
|
+
if (!stats.isFile()) return { ok: false, reason: "that is not a regular file." };
|
|
2333
|
+
if (stats.size > MAX_LOADABLE_BYTES) return { ok: false, reason: "the file is too large to read." };
|
|
2334
|
+
const bytes = import_fs2.default.readFileSync(found.absolutePath);
|
|
2335
|
+
if (bytes.includes(0)) return { ok: false, reason: "it looks like a binary file." };
|
|
2336
|
+
return { ok: true, relPath: found.relPath, content: bytes.toString("utf-8") };
|
|
2337
|
+
} catch (error) {
|
|
2338
|
+
const missing = error.code === "ENOENT";
|
|
2339
|
+
return { ok: false, reason: missing ? "there is no such file." : "the file could not be read." };
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
function readOne(cwd, request, rules, remaining) {
|
|
2343
|
+
const file = load(cwd, request.path, rules);
|
|
2344
|
+
if (!file.ok) return notShown(request.path, file.reason);
|
|
2345
|
+
const name = oneLine(file.relPath);
|
|
2346
|
+
if (file.content === "") {
|
|
2347
|
+
return { text: `--- File: ${name} ---
|
|
2348
|
+
(the file is empty)`, used: 0, sent: `${name} (empty)` };
|
|
2349
|
+
}
|
|
2350
|
+
const lines = file.content.split(/(?<=\n)/);
|
|
2351
|
+
const total = lines.length;
|
|
2352
|
+
const start = request.startLine ?? 1;
|
|
2353
|
+
if (start > total) {
|
|
2354
|
+
return notShown(file.relPath, `the file has only ${total} line${total === 1 ? "" : "s"}.`);
|
|
2355
|
+
}
|
|
2356
|
+
const end = Math.min(request.endLine ?? total, total);
|
|
2357
|
+
const limit = Math.min(import_prompts.MAX_REQUESTED_FILE_CHARS, remaining);
|
|
2358
|
+
let content = "";
|
|
2359
|
+
let last = start - 1;
|
|
2360
|
+
while (last < end && content.length + lines[last].length <= limit) {
|
|
2361
|
+
content += lines[last];
|
|
2362
|
+
last++;
|
|
2363
|
+
}
|
|
2364
|
+
let note = "";
|
|
2365
|
+
if (last < start) {
|
|
2366
|
+
if (limit < import_prompts.MAX_REQUESTED_FILE_CHARS) {
|
|
2367
|
+
return notShown(file.relPath, "this request has reached its size limit. Ask for this file again.");
|
|
2368
|
+
}
|
|
2369
|
+
content = lines[start - 1].slice(0, limit);
|
|
2370
|
+
last = start;
|
|
2371
|
+
note = `
|
|
2372
|
+
[Cut here: line ${start} is longer than the limit.${start < total ? ` To see what follows it, ask for "startLine": ${start + 1}.` : ""}]`;
|
|
2373
|
+
} else if (last < end) {
|
|
2374
|
+
const left = total - last;
|
|
2375
|
+
note = `
|
|
2376
|
+
[Cut here by the size limit: ${left} more line${left === 1 ? "" : "s"} in this file. To see them, ask for "startLine": ${last + 1}.]`;
|
|
2377
|
+
}
|
|
2378
|
+
const range = `lines ${start}-${last} of ${total}`;
|
|
2379
|
+
return {
|
|
2380
|
+
text: `--- File: ${name} (${range}) ---
|
|
2381
|
+
${fenced(content)}${note}`,
|
|
2382
|
+
used: content.length,
|
|
2383
|
+
sent: `${name} (${range})`
|
|
2384
|
+
};
|
|
2385
|
+
}
|
|
2386
|
+
function readRequestedFiles(cwd, files, rules) {
|
|
2387
|
+
let remaining = import_prompts.MAX_REQUEST_CHARS;
|
|
2388
|
+
const sections = files.slice(0, import_prompts.MAX_FILES_PER_REQUEST).map((request) => {
|
|
2389
|
+
const section = readOne(cwd, request, rules, remaining);
|
|
2390
|
+
remaining -= section.used;
|
|
2391
|
+
return section;
|
|
2392
|
+
});
|
|
2393
|
+
const texts = sections.map((section) => section.text);
|
|
2394
|
+
const extra = files.length - import_prompts.MAX_FILES_PER_REQUEST;
|
|
2395
|
+
if (extra > 0) {
|
|
2396
|
+
texts.push(
|
|
2397
|
+
`${extra} more file${extra === 1 ? " was" : "s were"} not read: one request may ask for at most ${import_prompts.MAX_FILES_PER_REQUEST} files.`
|
|
2398
|
+
);
|
|
2399
|
+
}
|
|
2400
|
+
const sent = sections.flatMap((section) => section.sent ?? []);
|
|
2401
|
+
const refused = sections.flatMap((section) => section.refused ?? []);
|
|
2402
|
+
const withheld = refused.length ? `; not sending ${refused.join(", ")}` : "";
|
|
2403
|
+
return {
|
|
2404
|
+
text: `### Files you asked for
|
|
2405
|
+
|
|
2406
|
+
${texts.join("\n\n")}`,
|
|
2407
|
+
summary: `sending ${sent.join(", ") || "no files"}${withheld}`
|
|
2408
|
+
};
|
|
2409
|
+
}
|
|
2410
|
+
var import_prompts2 = require_dist6();
|
|
2411
|
+
var NONE = { kind: "none" };
|
|
2412
|
+
function invalid(error) {
|
|
2413
|
+
return { kind: "invalid", error };
|
|
2414
|
+
}
|
|
2415
|
+
function isObject(value) {
|
|
2416
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2417
|
+
}
|
|
2418
|
+
function isLineNumber(value) {
|
|
2419
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1;
|
|
2420
|
+
}
|
|
2421
|
+
function parseFile(entry) {
|
|
2422
|
+
const file = typeof entry === "string" ? { path: entry } : entry;
|
|
2423
|
+
if (!isObject(file) || typeof file.path !== "string" || file.path.trim() === "") {
|
|
2424
|
+
return 'Every entry in "files" needs a "path" that names a file.';
|
|
2425
|
+
}
|
|
2426
|
+
const request = { path: file.path };
|
|
2427
|
+
for (const key of ["startLine", "endLine"]) {
|
|
2428
|
+
const value = file[key];
|
|
2429
|
+
if (value === void 0 || value === null) continue;
|
|
2430
|
+
if (!isLineNumber(value)) return `"${key}" must be a line number: a whole number, 1 or more.`;
|
|
2431
|
+
request[key] = value;
|
|
2432
|
+
}
|
|
2433
|
+
if (request.endLine !== void 0 && request.endLine < (request.startLine ?? 1)) {
|
|
2434
|
+
return 'The line range is backwards: "endLine" is before "startLine".';
|
|
2435
|
+
}
|
|
2436
|
+
return request;
|
|
2437
|
+
}
|
|
2438
|
+
function parseReadFile(request) {
|
|
2439
|
+
if (!Array.isArray(request.files) || request.files.length === 0) {
|
|
2440
|
+
return invalid('"files" must be a list with at least one entry, each with a "path".');
|
|
2441
|
+
}
|
|
2442
|
+
const files = [];
|
|
2443
|
+
for (const entry of request.files) {
|
|
2444
|
+
const file = parseFile(entry);
|
|
2445
|
+
if (typeof file === "string") return invalid(file);
|
|
2446
|
+
files.push(file);
|
|
2447
|
+
}
|
|
2448
|
+
return { kind: "read_file", files };
|
|
2449
|
+
}
|
|
2450
|
+
function parseSearch({ text, path: path22 }) {
|
|
2451
|
+
if (typeof text !== "string" || text.trim() === "" || /[\r\n]/.test(text) || text.length > import_prompts2.MAX_SEARCH_TEXT_CHARS) {
|
|
2452
|
+
return invalid(`"text" must be the text to find: one line of at most ${import_prompts2.MAX_SEARCH_TEXT_CHARS} characters.`);
|
|
2453
|
+
}
|
|
2454
|
+
if (path22 === void 0 || path22 === null || typeof path22 === "string" && path22.trim() === "") {
|
|
2455
|
+
return { kind: "search", text };
|
|
2456
|
+
}
|
|
2457
|
+
if (typeof path22 !== "string") return invalid('"path" must name one folder or file, or be left out.');
|
|
2458
|
+
return { kind: "search", text, path: path22 };
|
|
2459
|
+
}
|
|
2460
|
+
function parseToolRequest(reply) {
|
|
2461
|
+
const cleaned = reply.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
|
|
2462
|
+
const start = cleaned.indexOf("{");
|
|
2463
|
+
if (start === -1) return NONE;
|
|
2464
|
+
const looksLikeRequest = /^\{\s*"tool"\s*:/.test(cleaned.slice(start));
|
|
2465
|
+
let parsed;
|
|
2466
|
+
try {
|
|
2467
|
+
parsed = JSON.parse(cleaned.slice(start, cleaned.lastIndexOf("}") + 1));
|
|
2468
|
+
} catch {
|
|
2469
|
+
return looksLikeRequest ? invalid("The request is not valid JSON. Reply with exactly one complete JSON object.") : NONE;
|
|
2470
|
+
}
|
|
2471
|
+
if (!isObject(parsed) || !("tool" in parsed)) return NONE;
|
|
2472
|
+
if (Array.isArray(parsed.patches) && parsed.patches.length > 0) return NONE;
|
|
2473
|
+
switch (parsed.tool) {
|
|
2474
|
+
case "read_file":
|
|
2475
|
+
return parseReadFile(parsed);
|
|
2476
|
+
case "search":
|
|
2477
|
+
return parseSearch(parsed);
|
|
2478
|
+
default:
|
|
2479
|
+
return invalid(`There is no tool called ${JSON.stringify(parsed.tool)}. The tools are "read_file" and "search".`);
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
var import_fs22 = __toESM2(require("fs"));
|
|
2483
|
+
var import_path3 = __toESM2(require("path"));
|
|
2484
|
+
var import_prompts3 = require_dist6();
|
|
2485
|
+
var MAX_SEARCHED_FILES = 5e3;
|
|
2486
|
+
var MAX_SEARCHED_BYTES = 1024 * 1024;
|
|
2487
|
+
var MAX_LINE_CHARS = 200;
|
|
2488
|
+
var GENERATED_FOLDERS = /* @__PURE__ */ new Set([".next", ".turbo", "coverage"]);
|
|
2489
|
+
var joinRel = (folder, name) => folder === "" ? name : `${folder}/${name}`;
|
|
2490
|
+
function allowed(rules, relPaths) {
|
|
2491
|
+
return relPaths.every((rel) => rules.readBlockedBy(rel) === void 0);
|
|
2492
|
+
}
|
|
2493
|
+
function* filesBelow(folder, rules) {
|
|
2494
|
+
let entries;
|
|
2495
|
+
try {
|
|
2496
|
+
entries = import_fs22.default.readdirSync(folder.absolutePath, { withFileTypes: true });
|
|
2497
|
+
} catch {
|
|
2498
|
+
return;
|
|
2499
|
+
}
|
|
2500
|
+
entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
2501
|
+
const child = (name) => ({
|
|
2502
|
+
absolutePath: import_path3.default.join(folder.absolutePath, name),
|
|
2503
|
+
relPaths: [joinRel(folder.relPaths[0], name), joinRel(folder.relPaths[1], name)]
|
|
2504
|
+
});
|
|
2505
|
+
for (const entry of entries) {
|
|
2506
|
+
if (!entry.isFile()) continue;
|
|
2507
|
+
const file = child(entry.name);
|
|
2508
|
+
if (allowed(rules, file.relPaths)) yield file;
|
|
2509
|
+
}
|
|
2510
|
+
for (const entry of entries) {
|
|
2511
|
+
if (!entry.isDirectory() || GENERATED_FOLDERS.has(entry.name)) continue;
|
|
2512
|
+
const subfolder = child(entry.name);
|
|
2513
|
+
if (allowed(rules, subfolder.relPaths)) yield* filesBelow(subfolder, rules);
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2516
|
+
function target(cwd, requested, rules) {
|
|
2517
|
+
const root = import_path3.default.resolve(cwd);
|
|
2518
|
+
if (requested === void 0 || import_path3.default.resolve(root, requested) === root) {
|
|
2519
|
+
return { ok: true, files: filesBelow({ absolutePath: root, relPaths: ["", ""] }, rules), where: "" };
|
|
2520
|
+
}
|
|
2521
|
+
const found = locate(cwd, requested, rules);
|
|
2522
|
+
if (!found.ok) return found;
|
|
2523
|
+
try {
|
|
2524
|
+
const stats = import_fs22.default.statSync(found.absolutePath);
|
|
2525
|
+
const realPath = import_fs22.default.realpathSync.native(found.absolutePath);
|
|
2526
|
+
const real = import_path3.default.relative(import_fs22.default.realpathSync.native(root), realPath).split(import_path3.default.sep).join("/");
|
|
2527
|
+
const start = { absolutePath: realPath, relPaths: [real, found.relPath] };
|
|
2528
|
+
const where = found.relPath;
|
|
2529
|
+
if (stats.isDirectory()) return { ok: true, files: filesBelow(start, rules), where };
|
|
2530
|
+
if (stats.isFile()) return { ok: true, files: [start], where };
|
|
2531
|
+
return { ok: false, reason: "that is not a file or a folder." };
|
|
2532
|
+
} catch {
|
|
2533
|
+
return { ok: false, reason: "there is no such file or folder." };
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
function excerpt(line, matchAt) {
|
|
2537
|
+
if (line.length <= MAX_LINE_CHARS) return line;
|
|
2538
|
+
const from = Math.max(0, matchAt - MAX_LINE_CHARS / 2);
|
|
2539
|
+
const to = from + MAX_LINE_CHARS;
|
|
2540
|
+
return `${from > 0 ? "..." : ""}${line.slice(from, to)}${to < line.length ? "..." : ""}`;
|
|
2541
|
+
}
|
|
2542
|
+
var plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
2543
|
+
function searchProject(cwd, request, rules) {
|
|
2544
|
+
const quoted = oneLine(JSON.stringify(request.text));
|
|
2545
|
+
const found = target(cwd, request.path, rules);
|
|
2546
|
+
if (!found.ok) {
|
|
2547
|
+
return {
|
|
2548
|
+
text: `### Search results for ${quoted}
|
|
2549
|
+
Not searched: ${oneLine(found.reason)}`,
|
|
2550
|
+
summary: `searched for ${quoted}: not searched (${oneLine(request.path ?? "")} cannot be searched)`
|
|
2551
|
+
};
|
|
2552
|
+
}
|
|
2553
|
+
const needle = request.text.toLowerCase();
|
|
2554
|
+
const matches = [];
|
|
2555
|
+
const notes = /* @__PURE__ */ new Set();
|
|
2556
|
+
let searched = 0;
|
|
2557
|
+
let matchedFiles = 0;
|
|
2558
|
+
let large = 0;
|
|
2559
|
+
search: for (const file of found.files) {
|
|
2560
|
+
if (searched >= MAX_SEARCHED_FILES) {
|
|
2561
|
+
notes.add(`The search stopped after ${MAX_SEARCHED_FILES} files. Give a "path" to search the rest.`);
|
|
2562
|
+
break;
|
|
2563
|
+
}
|
|
2564
|
+
searched++;
|
|
2565
|
+
let content;
|
|
2566
|
+
try {
|
|
2567
|
+
if (import_fs22.default.statSync(file.absolutePath).size > MAX_SEARCHED_BYTES) {
|
|
2568
|
+
large++;
|
|
2569
|
+
continue;
|
|
2570
|
+
}
|
|
2571
|
+
const bytes = import_fs22.default.readFileSync(file.absolutePath);
|
|
2572
|
+
if (bytes.includes(0)) continue;
|
|
2573
|
+
content = bytes.toString("utf-8");
|
|
2574
|
+
} catch {
|
|
2575
|
+
continue;
|
|
2576
|
+
}
|
|
2577
|
+
let inThisFile = 0;
|
|
2578
|
+
for (const [index, line] of content.split(/\r?\n/).entries()) {
|
|
2579
|
+
const at = line.toLowerCase().indexOf(needle);
|
|
2580
|
+
if (at === -1) continue;
|
|
2581
|
+
if (inThisFile === import_prompts3.MAX_SEARCH_MATCHES_PER_FILE) {
|
|
2582
|
+
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.`);
|
|
2583
|
+
break;
|
|
2584
|
+
}
|
|
2585
|
+
if (matches.length === import_prompts3.MAX_SEARCH_MATCHES) {
|
|
2586
|
+
notes.add(`Only the first ${import_prompts3.MAX_SEARCH_MATCHES} matching lines are shown. Search a narrower "path" or a longer text.`);
|
|
2587
|
+
break search;
|
|
2588
|
+
}
|
|
2589
|
+
if (inThisFile === 0) matchedFiles++;
|
|
2590
|
+
inThisFile++;
|
|
2591
|
+
matches.push(`${oneLine(file.relPaths[1])}:${index + 1}: ${excerpt(line, at)}`);
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
if (large > 0) notes.add(`${plural(large, "large file")} ${large === 1 ? "was" : "were"} not searched.`);
|
|
2595
|
+
const heading = `### Search results for ${quoted}${found.where ? ` in ${oneLine(found.where)}` : ""}`;
|
|
2596
|
+
const body = matches.length ? fenced(matches.join("\n")) : "No lines containing that text were found in the files you may see.";
|
|
2597
|
+
const footer = [...notes].map((note) => `
|
|
2598
|
+
[${note}]`).join("");
|
|
2599
|
+
const sending = matches.length ? `sending ${plural(matches.length, "matching line")} from ${plural(matchedFiles, "file")}` : "0 matching lines";
|
|
2600
|
+
return { text: `${heading}
|
|
2601
|
+
${body}${footer}`, summary: `searched for ${quoted}: ${sending}` };
|
|
2602
|
+
}
|
|
2603
|
+
function answerToolRequest(reply, cwd, rules = (0, import_shared22.createProtectedPathRules)()) {
|
|
2604
|
+
const request = parseToolRequest(reply);
|
|
2605
|
+
switch (request.kind) {
|
|
2606
|
+
case "none":
|
|
2607
|
+
return null;
|
|
2608
|
+
case "invalid":
|
|
2609
|
+
return {
|
|
2610
|
+
text: `### Your request could not be used
|
|
2611
|
+
${request.error}
|
|
2612
|
+
|
|
2613
|
+
Reply with the fix, or with a request like one of these:
|
|
2614
|
+
${import_prompts4.FILE_REQUEST_EXAMPLE}
|
|
2615
|
+
${import_prompts4.SEARCH_REQUEST_EXAMPLE}`,
|
|
2616
|
+
summary: `a request that could not be used: ${oneLine(request.error)}`
|
|
2617
|
+
};
|
|
2618
|
+
case "read_file":
|
|
2619
|
+
return readRequestedFiles(cwd, request.files, rules);
|
|
2620
|
+
case "search":
|
|
2621
|
+
return searchProject(cwd, request, rules);
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
function remainingNote(left) {
|
|
2625
|
+
if (left === 0) return "That was your last request in this attempt. Reply with the fix now.";
|
|
2626
|
+
return `You may make ${left} more request${left === 1 ? "" : "s"} in this attempt, or reply with the fix now.`;
|
|
2627
|
+
}
|
|
2628
|
+
async function runToolConversation(options) {
|
|
2629
|
+
const { cwd, rules, maxRequests, ask, onRequest } = options;
|
|
2630
|
+
let prompt = options.prompt;
|
|
2631
|
+
let reply = await ask(prompt);
|
|
2632
|
+
for (let used = 1; reply !== null && used <= maxRequests; used++) {
|
|
2633
|
+
const answer = answerToolRequest(reply, cwd, rules);
|
|
2634
|
+
if (answer === null) break;
|
|
2635
|
+
onRequest?.(answer.summary, used);
|
|
2636
|
+
prompt += `
|
|
2637
|
+
|
|
2638
|
+
${answer.text}
|
|
2639
|
+
|
|
2640
|
+
${remainingNote(maxRequests - used)}`;
|
|
2641
|
+
reply = await ask(prompt);
|
|
2642
|
+
}
|
|
2643
|
+
const limitReached = maxRequests > 0 && reply !== null && parseToolRequest(reply).kind !== "none";
|
|
2644
|
+
return { reply, limitReached };
|
|
2645
|
+
}
|
|
2646
|
+
var import_shared32 = require_dist2();
|
|
2257
2647
|
var provider = new import_ai_provider.OpenRouterProvider();
|
|
2258
2648
|
function protectionFor(cwd) {
|
|
2259
|
-
return (0,
|
|
2649
|
+
return (0, import_shared32.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
|
|
2260
2650
|
}
|
|
2261
|
-
function previewAnalysisPrompt(cwd, logs) {
|
|
2262
|
-
return (0,
|
|
2651
|
+
function previewAnalysisPrompt(cwd, logs, options = {}) {
|
|
2652
|
+
return (0, import_prompts5.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd), toolRequests: options.toolRequests });
|
|
2263
2653
|
}
|
|
2264
|
-
|
|
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;
|
|
2654
|
+
function parseFix(response) {
|
|
2287
2655
|
try {
|
|
2288
2656
|
const cleaned = response.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
|
|
2289
2657
|
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 {
|
|
2658
|
+
if (!jsonMatch) {
|
|
2298
2659
|
console.warn("[BugZero] AI response did not contain a valid JSON object.");
|
|
2660
|
+
return null;
|
|
2299
2661
|
}
|
|
2662
|
+
const parsed = JSON.parse(jsonMatch[0]);
|
|
2663
|
+
if (Array.isArray(parsed.patches) && parsed.patches.length > 0) return parsed;
|
|
2664
|
+
console.warn('[BugZero] AI response JSON did not contain a non-empty "patches" array.');
|
|
2300
2665
|
} catch (e) {
|
|
2301
2666
|
console.error("[BugZero] Failed to parse AI response:", e);
|
|
2302
2667
|
}
|
|
2303
|
-
return
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2668
|
+
return null;
|
|
2669
|
+
}
|
|
2670
|
+
async function analyzeNode(state) {
|
|
2671
|
+
const attempt = state.attempts + 1;
|
|
2672
|
+
const maxRequests = state.tools ? state.maxToolRequests : 0;
|
|
2673
|
+
const spent = { promptTokens: 0, completionTokens: 0, estimated: false };
|
|
2674
|
+
let sent = 0;
|
|
2675
|
+
let modelUsed = "";
|
|
2676
|
+
let budgetStop = null;
|
|
2677
|
+
const ask = async (prompt) => {
|
|
2678
|
+
const used = () => state.promptTokens + state.completionTokens + spent.promptTokens + spent.completionTokens;
|
|
2679
|
+
const budget = (0, import_shared32.checkBudget)(state.maxTokens, used(), prompt);
|
|
2680
|
+
if (!budget.allowed) {
|
|
2681
|
+
budgetStop = budget.reason;
|
|
2682
|
+
console.log(`
|
|
2683
|
+
[BugZero] ${budget.reason} Stopping ${sent === 0 ? "before" : "during"} attempt ${attempt}.`);
|
|
2684
|
+
return null;
|
|
2685
|
+
}
|
|
2686
|
+
if (sent === 0) console.log(`
|
|
2687
|
+
[BugZero] Attempt ${attempt}/${state.maxAttempts} \u2014 asking AI\u2026`);
|
|
2688
|
+
const result = await provider.invoke(prompt, { cwd: state.cwd, maxTokens: budget.maxReplyTokens });
|
|
2689
|
+
sent++;
|
|
2690
|
+
modelUsed = result.model;
|
|
2691
|
+
const tokens = (0, import_shared32.countCallTokens)(state.maxTokens, prompt, result);
|
|
2692
|
+
spent.promptTokens += tokens.promptTokens;
|
|
2693
|
+
spent.completionTokens += tokens.completionTokens;
|
|
2694
|
+
spent.estimated ||= tokens.estimated;
|
|
2695
|
+
if (state.maxTokens !== void 0) {
|
|
2696
|
+
const note = tokens.estimated ? " (an estimate: the model did not report its token usage)" : "";
|
|
2697
|
+
console.log(`[BugZero] Token budget: ${used()} of ${state.maxTokens} used${note}.`);
|
|
2698
|
+
if (result.truncated) console.log("[BugZero] The AI reply was cut off by its length limit, so it may be unusable.");
|
|
2699
|
+
}
|
|
2700
|
+
return result.content;
|
|
2311
2701
|
};
|
|
2702
|
+
const { reply, limitReached } = await runToolConversation({
|
|
2703
|
+
prompt: previewAnalysisPrompt(state.cwd, state.logs, { toolRequests: maxRequests }),
|
|
2704
|
+
cwd: state.cwd,
|
|
2705
|
+
rules: protectionFor(state.cwd),
|
|
2706
|
+
maxRequests,
|
|
2707
|
+
ask,
|
|
2708
|
+
onRequest: (summary, used) => console.log(`[BugZero] The AI asked to look further (request ${used} of ${maxRequests}): ${summary}`)
|
|
2709
|
+
});
|
|
2710
|
+
if (sent === 0) return { budgetStop };
|
|
2711
|
+
const cost = {
|
|
2712
|
+
attempts: attempt,
|
|
2713
|
+
modelUsed,
|
|
2714
|
+
promptTokens: spent.promptTokens,
|
|
2715
|
+
completionTokens: spent.completionTokens,
|
|
2716
|
+
tokensEstimated: spent.estimated
|
|
2717
|
+
};
|
|
2718
|
+
if (reply === null) return { ...cost, budgetStop };
|
|
2719
|
+
if (limitReached) {
|
|
2720
|
+
console.warn("[BugZero] The AI asked to look further again after its last request, so this attempt has no fix.");
|
|
2721
|
+
}
|
|
2722
|
+
return { ...cost, analysis: reply, fixSuggestion: limitReached ? null : parseFix(reply) };
|
|
2312
2723
|
}
|
|
2313
2724
|
function patchFailure(state, error) {
|
|
2314
2725
|
console.error(`[BugZero] Patch failed: ${error}`);
|
|
@@ -2479,6 +2890,7 @@ var require_dist8 = __commonJS({
|
|
|
2479
2890
|
var index_exports = {};
|
|
2480
2891
|
__export(index_exports, {
|
|
2481
2892
|
DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS,
|
|
2893
|
+
DEFAULT_MAX_TOOL_REQUESTS: () => DEFAULT_MAX_TOOL_REQUESTS,
|
|
2482
2894
|
DEFAULT_PATIENCE: () => DEFAULT_PATIENCE,
|
|
2483
2895
|
REPORT_FILENAME: () => REPORT_FILENAME2,
|
|
2484
2896
|
detectFramework: () => detectFramework2,
|
|
@@ -2488,8 +2900,10 @@ var require_dist8 = __commonJS({
|
|
|
2488
2900
|
resolveFocusTests: () => resolveFocusTests,
|
|
2489
2901
|
resolveMaxAttempts: () => resolveMaxAttempts2,
|
|
2490
2902
|
resolveMaxTokens: () => resolveMaxTokens2,
|
|
2903
|
+
resolveMaxToolRequests: () => resolveMaxToolRequests2,
|
|
2491
2904
|
resolvePatience: () => resolvePatience2,
|
|
2492
|
-
resolveTimeoutMs: () => resolveTimeoutMs2
|
|
2905
|
+
resolveTimeoutMs: () => resolveTimeoutMs2,
|
|
2906
|
+
resolveTools: () => resolveTools
|
|
2493
2907
|
});
|
|
2494
2908
|
module2.exports = __toCommonJS(index_exports);
|
|
2495
2909
|
var import_fs2 = __toESM2(require("fs"));
|
|
@@ -2679,6 +3093,25 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2679
3093
|
}
|
|
2680
3094
|
return value;
|
|
2681
3095
|
}
|
|
3096
|
+
function resolveTools(flag, configured) {
|
|
3097
|
+
if (flag !== void 0) return flag;
|
|
3098
|
+
if (configured === void 0) return false;
|
|
3099
|
+
if (typeof configured !== "boolean") {
|
|
3100
|
+
throw new Error(`tools in .bugzerorc must be true or false (received ${JSON.stringify(configured)}).`);
|
|
3101
|
+
}
|
|
3102
|
+
return configured;
|
|
3103
|
+
}
|
|
3104
|
+
var DEFAULT_MAX_TOOL_REQUESTS = 3;
|
|
3105
|
+
var HIGHEST_MAX_TOOL_REQUESTS = 20;
|
|
3106
|
+
function resolveMaxToolRequests2(flag, configured) {
|
|
3107
|
+
const source = flag !== void 0 ? "--max-tool-requests" : "maxToolRequests in .bugzerorc";
|
|
3108
|
+
const value = flag !== void 0 ? flag : configured;
|
|
3109
|
+
if (value === void 0) return DEFAULT_MAX_TOOL_REQUESTS;
|
|
3110
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > HIGHEST_MAX_TOOL_REQUESTS) {
|
|
3111
|
+
throw new Error(`${source} must be a whole number from 1 to ${HIGHEST_MAX_TOOL_REQUESTS} (received ${JSON.stringify(value) ?? String(value)}).`);
|
|
3112
|
+
}
|
|
3113
|
+
return value;
|
|
3114
|
+
}
|
|
2682
3115
|
var import_fs22 = __toESM2(require("fs"));
|
|
2683
3116
|
var import_path22 = __toESM2(require("path"));
|
|
2684
3117
|
function assertNodeProject(cwd) {
|
|
@@ -2731,6 +3164,17 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2731
3164
|
const patience = resolvePatience2(options.patience, config.patience);
|
|
2732
3165
|
const focusTests = resolveFocusTests(options.focusTests, config.focusTests);
|
|
2733
3166
|
const maxTokens = resolveMaxTokens2(options.maxTokens, config.maxTokens);
|
|
3167
|
+
const tools = resolveTools(options.tools, config.tools);
|
|
3168
|
+
const maxToolRequests = resolveMaxToolRequests2(options.maxToolRequests, config.maxToolRequests);
|
|
3169
|
+
const announceTools = () => {
|
|
3170
|
+
if (tools) {
|
|
3171
|
+
console.log(
|
|
3172
|
+
`[BugZero] Tools on: the AI model may ask to read and search project files, up to ${maxToolRequests} request${maxToolRequests === 1 ? "" : "s"} per attempt.`
|
|
3173
|
+
);
|
|
3174
|
+
} else if (options.maxToolRequests !== void 0) {
|
|
3175
|
+
console.log("[BugZero] --max-tool-requests has no effect because tools are off (turn them on with --tools).");
|
|
3176
|
+
}
|
|
3177
|
+
};
|
|
2734
3178
|
console.log(`[BugZero] Running validation pipeline in: ${cwd}`);
|
|
2735
3179
|
const pipelineResult = await (0, import_analyzers.runValidationPipeline)(cwd, { timeoutMs });
|
|
2736
3180
|
if (pipelineResult.success) {
|
|
@@ -2752,11 +3196,12 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2752
3196
|
console.log(`[BugZero] Detected ${errors.length} error(s) (type: ${errors[0]?.type ?? "unknown"})`);
|
|
2753
3197
|
if (options.printPrompt) {
|
|
2754
3198
|
console.log("[BugZero] --print-prompt: showing the first prompt without sending it.");
|
|
3199
|
+
announceTools();
|
|
2755
3200
|
return {
|
|
2756
3201
|
success: false,
|
|
2757
3202
|
attempts: 0,
|
|
2758
3203
|
finalOutput: pipelineResult.output,
|
|
2759
|
-
promptPreview: (0, import_agents.previewAnalysisPrompt)(cwd, pipelineResult.output)
|
|
3204
|
+
promptPreview: (0, import_agents.previewAnalysisPrompt)(cwd, pipelineResult.output, { toolRequests: tools ? maxToolRequests : 0 })
|
|
2760
3205
|
};
|
|
2761
3206
|
}
|
|
2762
3207
|
if (options.dryRun) {
|
|
@@ -2778,6 +3223,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2778
3223
|
...tokenBudgetUse(maxTokens, spend2)
|
|
2779
3224
|
};
|
|
2780
3225
|
}
|
|
3226
|
+
announceTools();
|
|
2781
3227
|
const finalState = await (0, import_agents.runRepairWorkflow)({
|
|
2782
3228
|
cwd,
|
|
2783
3229
|
logs: pipelineResult.output,
|
|
@@ -2787,6 +3233,8 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2787
3233
|
patience,
|
|
2788
3234
|
focusTests,
|
|
2789
3235
|
maxTokens,
|
|
3236
|
+
tools,
|
|
3237
|
+
maxToolRequests,
|
|
2790
3238
|
initialStep: pipelineResult.step
|
|
2791
3239
|
});
|
|
2792
3240
|
const result = {
|
|
@@ -3353,7 +3801,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
|
|
|
3353
3801
|
finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
|
|
3354
3802
|
}
|
|
3355
3803
|
});
|
|
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) => {
|
|
3804
|
+
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
3805
|
const json = opts.json === true;
|
|
3358
3806
|
const printPrompt = opts.printPrompt === true;
|
|
3359
3807
|
if (json || printPrompt) routeLogsToStderr();
|
|
@@ -3367,6 +3815,9 @@ program.command("rescue").description("Detect build failures and automatically a
|
|
|
3367
3815
|
const maxTokens = opts.maxTokens === void 0 ? void 0 : Number(opts.maxTokens);
|
|
3368
3816
|
(0, import_core.resolveMaxTokens)(maxTokens, void 0);
|
|
3369
3817
|
const focusTests = opts.focusTests === false ? false : void 0;
|
|
3818
|
+
const tools = opts.tools;
|
|
3819
|
+
const maxToolRequests = opts.maxToolRequests === void 0 ? void 0 : Number(opts.maxToolRequests);
|
|
3820
|
+
(0, import_core.resolveMaxToolRequests)(maxToolRequests, void 0);
|
|
3370
3821
|
const dryRun = opts.dryRun;
|
|
3371
3822
|
let approve;
|
|
3372
3823
|
if (opts.approve === true && !dryRun && !printPrompt) {
|
|
@@ -3400,7 +3851,9 @@ program.command("rescue").description("Detect build failures and automatically a
|
|
|
3400
3851
|
approve,
|
|
3401
3852
|
patience,
|
|
3402
3853
|
focusTests,
|
|
3403
|
-
maxTokens
|
|
3854
|
+
maxTokens,
|
|
3855
|
+
tools,
|
|
3856
|
+
maxToolRequests
|
|
3404
3857
|
});
|
|
3405
3858
|
if (result.promptPreview !== void 0) {
|
|
3406
3859
|
if (json) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bugzero",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.64",
|
|
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)",
|