bugzero 0.0.61 → 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.
- package/README.md +13 -5
- package/dist/index.js +552 -63
- 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`), `.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`), `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
|
@@ -499,6 +499,7 @@ var require_dist2 = __commonJS({
|
|
|
499
499
|
__export(index_exports, {
|
|
500
500
|
DEFAULT_PROTECTED_PATTERNS: () => DEFAULT_PROTECTED_PATTERNS,
|
|
501
501
|
DEFAULT_SECRET_PATTERNS: () => DEFAULT_SECRET_PATTERNS,
|
|
502
|
+
DEFAULT_UNREADABLE_PATTERNS: () => DEFAULT_UNREADABLE_PATTERNS,
|
|
502
503
|
MAX_REPLY_TOKENS: () => MAX_REPLY_TOKENS,
|
|
503
504
|
MIN_REPLY_TOKENS: () => MIN_REPLY_TOKENS,
|
|
504
505
|
checkBudget: () => checkBudget,
|
|
@@ -558,7 +559,25 @@ var require_dist2 = __commonJS({
|
|
|
558
559
|
}
|
|
559
560
|
var import_fs22 = __toESM2(require("fs"));
|
|
560
561
|
var import_path22 = __toESM2(require("path"));
|
|
561
|
-
var DEFAULT_SECRET_PATTERNS = [
|
|
562
|
+
var DEFAULT_SECRET_PATTERNS = [
|
|
563
|
+
".env",
|
|
564
|
+
".env.*",
|
|
565
|
+
"*.pem",
|
|
566
|
+
"*.key",
|
|
567
|
+
// These can hold registry or login tokens.
|
|
568
|
+
".npmrc",
|
|
569
|
+
".netrc",
|
|
570
|
+
".pypirc"
|
|
571
|
+
];
|
|
572
|
+
var DEFAULT_UNREADABLE_PATTERNS = [
|
|
573
|
+
...DEFAULT_SECRET_PATTERNS,
|
|
574
|
+
".git/",
|
|
575
|
+
"node_modules/",
|
|
576
|
+
"build/",
|
|
577
|
+
"dist/",
|
|
578
|
+
"*.opspilot.bak",
|
|
579
|
+
"*.opspilot.bak.sha"
|
|
580
|
+
];
|
|
562
581
|
var DEFAULT_PROTECTED_PATTERNS = [
|
|
563
582
|
...DEFAULT_SECRET_PATTERNS,
|
|
564
583
|
".git/",
|
|
@@ -619,21 +638,19 @@ var require_dist2 = __commonJS({
|
|
|
619
638
|
function createProtectedPathRules2(settings = {}) {
|
|
620
639
|
const defaults = compileAll(DEFAULT_PROTECTED_PATTERNS);
|
|
621
640
|
const secrets = compileAll(DEFAULT_SECRET_PATTERNS);
|
|
641
|
+
const unreadable = compileAll(DEFAULT_UNREADABLE_PATTERNS);
|
|
622
642
|
const extra = compileAll(settings.protect);
|
|
623
643
|
const allowed = compileAll(settings.allow);
|
|
644
|
+
const blockedUnlessAllowed = (matchers, relPath) => {
|
|
645
|
+
const normalized = normalizePath(relPath);
|
|
646
|
+
if (firstMatch(allowed, normalized)) return void 0;
|
|
647
|
+
return firstMatch(matchers, normalized)?.pattern;
|
|
648
|
+
};
|
|
649
|
+
const blockedOrProtected = (matchers, relPath) => firstMatch(extra, normalizePath(relPath))?.pattern ?? blockedUnlessAllowed(matchers, relPath);
|
|
624
650
|
return {
|
|
625
|
-
editBlockedBy(relPath)
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
if (own) return own.pattern;
|
|
629
|
-
if (firstMatch(allowed, normalized)) return void 0;
|
|
630
|
-
return firstMatch(defaults, normalized)?.pattern;
|
|
631
|
-
},
|
|
632
|
-
secretBlockedBy(relPath) {
|
|
633
|
-
const normalized = normalizePath(relPath);
|
|
634
|
-
if (firstMatch(allowed, normalized)) return void 0;
|
|
635
|
-
return firstMatch(secrets, normalized)?.pattern;
|
|
636
|
-
}
|
|
651
|
+
editBlockedBy: (relPath) => blockedOrProtected(defaults, relPath),
|
|
652
|
+
secretBlockedBy: (relPath) => blockedUnlessAllowed(secrets, relPath),
|
|
653
|
+
readBlockedBy: (relPath) => blockedOrProtected(unreadable, relPath)
|
|
637
654
|
};
|
|
638
655
|
}
|
|
639
656
|
function toRelative(root, target) {
|
|
@@ -1792,13 +1809,46 @@ var require_dist6 = __commonJS({
|
|
|
1792
1809
|
var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
|
|
1793
1810
|
var index_exports = {};
|
|
1794
1811
|
__export(index_exports, {
|
|
1812
|
+
FILE_REQUEST_EXAMPLE: () => FILE_REQUEST_EXAMPLE,
|
|
1813
|
+
MAX_FILES_PER_REQUEST: () => MAX_FILES_PER_REQUEST,
|
|
1814
|
+
MAX_REQUESTED_FILE_CHARS: () => MAX_REQUESTED_FILE_CHARS,
|
|
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,
|
|
1795
1820
|
buildAnalysisPrompt: () => buildAnalysisPrompt,
|
|
1821
|
+
toolInstructions: () => toolInstructions,
|
|
1796
1822
|
truncateLogs: () => truncateLogs
|
|
1797
1823
|
});
|
|
1798
1824
|
module2.exports = __toCommonJS(index_exports);
|
|
1799
1825
|
var import_shared4 = require_dist2();
|
|
1800
1826
|
var import_fs2 = __toESM2(require("fs"));
|
|
1801
1827
|
var import_path3 = __toESM2(require("path"));
|
|
1828
|
+
var MAX_FILES_PER_REQUEST = 5;
|
|
1829
|
+
var MAX_REQUESTED_FILE_CHARS = 2e4;
|
|
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;
|
|
1834
|
+
var FILE_REQUEST_EXAMPLE = '{"tool": "read_file", "files": [{"path": "src/types.ts"}, {"path": "src/server.ts", "startLine": 200, "endLine": 320}]}';
|
|
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:
|
|
1841
|
+
${FILE_REQUEST_EXAMPLE}
|
|
1842
|
+
- "path" is relative to the project root. "startLine" and "endLine" are optional.
|
|
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.
|
|
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.`;
|
|
1851
|
+
}
|
|
1802
1852
|
var MAX_LOG_CHARS = 2e4;
|
|
1803
1853
|
var MAX_FILE_CHARS = 2e4;
|
|
1804
1854
|
var MAX_CONTEXT_CHARS = 6e4;
|
|
@@ -1971,6 +2021,9 @@ ${w}`).join("\n\n")}
|
|
|
1971
2021
|
}
|
|
1972
2022
|
compilerLogs = truncateLogs(compilerLogs);
|
|
1973
2023
|
const contextSection = getContextFiles(compilerLogs, cwd, options.rules ?? (0, import_shared4.createProtectedPathRules)());
|
|
2024
|
+
const toolSection = options.toolRequests ? `
|
|
2025
|
+
|
|
2026
|
+
${toolInstructions(options.toolRequests)}` : "";
|
|
1974
2027
|
return `You are an expert software engineer specialising in fixing build, lint, and test failures.
|
|
1975
2028
|
|
|
1976
2029
|
A project located at "${cwd}" failed to build. Here is the error output (very long output is shortened in the middle):
|
|
@@ -2004,7 +2057,7 @@ Critical rules:
|
|
|
2004
2057
|
- Each "search" must be an EXACT character-for-character substring of that file's current content.
|
|
2005
2058
|
- Each "replace" must be syntactically valid code.
|
|
2006
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.
|
|
2007
|
-
- Do NOT add backticks, markdown, or any text outside the JSON object
|
|
2060
|
+
- Do NOT add backticks, markdown, or any text outside the JSON object.${toolSection}`;
|
|
2008
2061
|
}
|
|
2009
2062
|
}
|
|
2010
2063
|
});
|
|
@@ -2013,13 +2066,15 @@ Critical rules:
|
|
|
2013
2066
|
var require_dist7 = __commonJS({
|
|
2014
2067
|
"../../packages/agents/dist/index.js"(exports2, module2) {
|
|
2015
2068
|
"use strict";
|
|
2069
|
+
var __create2 = Object.create;
|
|
2016
2070
|
var __defProp2 = Object.defineProperty;
|
|
2017
2071
|
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
2018
2072
|
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
2073
|
+
var __getProtoOf2 = Object.getPrototypeOf;
|
|
2019
2074
|
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
2020
|
-
var __export = (
|
|
2075
|
+
var __export = (target2, all) => {
|
|
2021
2076
|
for (var name in all)
|
|
2022
|
-
__defProp2(
|
|
2077
|
+
__defProp2(target2, name, { get: all[name], enumerable: true });
|
|
2023
2078
|
};
|
|
2024
2079
|
var __copyProps2 = (to, from, except, desc) => {
|
|
2025
2080
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -2029,6 +2084,14 @@ var require_dist7 = __commonJS({
|
|
|
2029
2084
|
}
|
|
2030
2085
|
return to;
|
|
2031
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
|
+
));
|
|
2032
2095
|
var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
|
|
2033
2096
|
var index_exports = {};
|
|
2034
2097
|
__export(index_exports, {
|
|
@@ -2167,6 +2230,16 @@ var require_dist7 = __commonJS({
|
|
|
2167
2230
|
reducer: (_, value) => value,
|
|
2168
2231
|
default: () => null
|
|
2169
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
|
+
}),
|
|
2170
2243
|
/** Per-command timeout in milliseconds for validation steps (undefined = no limit) */
|
|
2171
2244
|
timeoutMs: (0, import_langgraph.Annotation)({
|
|
2172
2245
|
reducer: (_, value) => value,
|
|
@@ -2174,7 +2247,7 @@ var require_dist7 = __commonJS({
|
|
|
2174
2247
|
})
|
|
2175
2248
|
});
|
|
2176
2249
|
var import_ai_provider = require_dist5();
|
|
2177
|
-
var
|
|
2250
|
+
var import_prompts5 = require_dist6();
|
|
2178
2251
|
var import_config2 = require_dist();
|
|
2179
2252
|
var import_patcher3 = require_dist3();
|
|
2180
2253
|
var import_analyzers2 = require_dist4();
|
|
@@ -2213,62 +2286,436 @@ var require_dist7 = __commonJS({
|
|
|
2213
2286
|
if (snapshot.errorCount === null) return `output it cannot count${where}`;
|
|
2214
2287
|
return `${snapshot.errorCount} error${snapshot.errorCount === 1 ? "" : "s"}${where}`;
|
|
2215
2288
|
}
|
|
2289
|
+
var import_prompts4 = require_dist6();
|
|
2290
|
+
var import_shared22 = require_dist2();
|
|
2216
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();
|
|
2217
2643
|
var provider = new import_ai_provider.OpenRouterProvider();
|
|
2218
2644
|
function protectionFor(cwd) {
|
|
2219
|
-
return (0,
|
|
2645
|
+
return (0, import_shared32.createProtectedPathRules)((0, import_config2.getProtectionSettings)(cwd));
|
|
2220
2646
|
}
|
|
2221
|
-
function previewAnalysisPrompt(cwd, logs) {
|
|
2222
|
-
return (0,
|
|
2647
|
+
function previewAnalysisPrompt(cwd, logs, options = {}) {
|
|
2648
|
+
return (0, import_prompts5.buildAnalysisPrompt)(logs, cwd, { rules: protectionFor(cwd), toolRequests: options.toolRequests });
|
|
2223
2649
|
}
|
|
2224
|
-
|
|
2225
|
-
const prompt = previewAnalysisPrompt(state.cwd, state.logs);
|
|
2226
|
-
const used = state.promptTokens + state.completionTokens;
|
|
2227
|
-
const budget = (0, import_shared4.checkBudget)(state.maxTokens, used, prompt);
|
|
2228
|
-
if (!budget.allowed) {
|
|
2229
|
-
console.log(`
|
|
2230
|
-
[BugZero] ${budget.reason} Stopping before attempt ${state.attempts + 1}.`);
|
|
2231
|
-
return { budgetStop: budget.reason };
|
|
2232
|
-
}
|
|
2233
|
-
console.log(
|
|
2234
|
-
`
|
|
2235
|
-
[BugZero] Attempt ${state.attempts + 1}/${state.maxAttempts} \u2014 asking AI\u2026`
|
|
2236
|
-
);
|
|
2237
|
-
const result = await provider.invoke(prompt, { cwd: state.cwd, maxTokens: budget.maxReplyTokens });
|
|
2238
|
-
const response = result.content;
|
|
2239
|
-
const tokens = (0, import_shared4.countCallTokens)(state.maxTokens, prompt, result);
|
|
2240
|
-
if (state.maxTokens !== void 0) {
|
|
2241
|
-
const total = used + tokens.promptTokens + tokens.completionTokens;
|
|
2242
|
-
const note = tokens.estimated ? " (an estimate: the model did not report its token usage)" : "";
|
|
2243
|
-
console.log(`[BugZero] Token budget: ${total} of ${state.maxTokens} used${note}.`);
|
|
2244
|
-
if (result.truncated) console.log("[BugZero] The AI reply was cut off by its length limit, so it may be unusable.");
|
|
2245
|
-
}
|
|
2246
|
-
let fixSuggestion = null;
|
|
2650
|
+
function parseFix(response) {
|
|
2247
2651
|
try {
|
|
2248
2652
|
const cleaned = response.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
|
|
2249
2653
|
const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
|
|
2250
|
-
if (jsonMatch) {
|
|
2251
|
-
const parsed = JSON.parse(jsonMatch[0]);
|
|
2252
|
-
if (Array.isArray(parsed.patches) && parsed.patches.length > 0) {
|
|
2253
|
-
fixSuggestion = parsed;
|
|
2254
|
-
} else {
|
|
2255
|
-
console.warn('[BugZero] AI response JSON did not contain a non-empty "patches" array.');
|
|
2256
|
-
}
|
|
2257
|
-
} else {
|
|
2654
|
+
if (!jsonMatch) {
|
|
2258
2655
|
console.warn("[BugZero] AI response did not contain a valid JSON object.");
|
|
2656
|
+
return null;
|
|
2259
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.');
|
|
2260
2661
|
} catch (e) {
|
|
2261
2662
|
console.error("[BugZero] Failed to parse AI response:", e);
|
|
2262
2663
|
}
|
|
2263
|
-
return
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
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;
|
|
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
|
|
2271
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) };
|
|
2272
2719
|
}
|
|
2273
2720
|
function patchFailure(state, error) {
|
|
2274
2721
|
console.error(`[BugZero] Patch failed: ${error}`);
|
|
@@ -2439,6 +2886,7 @@ var require_dist8 = __commonJS({
|
|
|
2439
2886
|
var index_exports = {};
|
|
2440
2887
|
__export(index_exports, {
|
|
2441
2888
|
DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS,
|
|
2889
|
+
DEFAULT_MAX_TOOL_REQUESTS: () => DEFAULT_MAX_TOOL_REQUESTS,
|
|
2442
2890
|
DEFAULT_PATIENCE: () => DEFAULT_PATIENCE,
|
|
2443
2891
|
REPORT_FILENAME: () => REPORT_FILENAME2,
|
|
2444
2892
|
detectFramework: () => detectFramework2,
|
|
@@ -2448,8 +2896,10 @@ var require_dist8 = __commonJS({
|
|
|
2448
2896
|
resolveFocusTests: () => resolveFocusTests,
|
|
2449
2897
|
resolveMaxAttempts: () => resolveMaxAttempts2,
|
|
2450
2898
|
resolveMaxTokens: () => resolveMaxTokens2,
|
|
2899
|
+
resolveMaxToolRequests: () => resolveMaxToolRequests2,
|
|
2451
2900
|
resolvePatience: () => resolvePatience2,
|
|
2452
|
-
resolveTimeoutMs: () => resolveTimeoutMs2
|
|
2901
|
+
resolveTimeoutMs: () => resolveTimeoutMs2,
|
|
2902
|
+
resolveTools: () => resolveTools
|
|
2453
2903
|
});
|
|
2454
2904
|
module2.exports = __toCommonJS(index_exports);
|
|
2455
2905
|
var import_fs2 = __toESM2(require("fs"));
|
|
@@ -2639,6 +3089,25 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2639
3089
|
}
|
|
2640
3090
|
return value;
|
|
2641
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
|
+
}
|
|
2642
3111
|
var import_fs22 = __toESM2(require("fs"));
|
|
2643
3112
|
var import_path22 = __toESM2(require("path"));
|
|
2644
3113
|
function assertNodeProject(cwd) {
|
|
@@ -2691,6 +3160,17 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2691
3160
|
const patience = resolvePatience2(options.patience, config.patience);
|
|
2692
3161
|
const focusTests = resolveFocusTests(options.focusTests, config.focusTests);
|
|
2693
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
|
+
};
|
|
2694
3174
|
console.log(`[BugZero] Running validation pipeline in: ${cwd}`);
|
|
2695
3175
|
const pipelineResult = await (0, import_analyzers.runValidationPipeline)(cwd, { timeoutMs });
|
|
2696
3176
|
if (pipelineResult.success) {
|
|
@@ -2712,11 +3192,12 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2712
3192
|
console.log(`[BugZero] Detected ${errors.length} error(s) (type: ${errors[0]?.type ?? "unknown"})`);
|
|
2713
3193
|
if (options.printPrompt) {
|
|
2714
3194
|
console.log("[BugZero] --print-prompt: showing the first prompt without sending it.");
|
|
3195
|
+
announceTools();
|
|
2715
3196
|
return {
|
|
2716
3197
|
success: false,
|
|
2717
3198
|
attempts: 0,
|
|
2718
3199
|
finalOutput: pipelineResult.output,
|
|
2719
|
-
promptPreview: (0, import_agents.previewAnalysisPrompt)(cwd, pipelineResult.output)
|
|
3200
|
+
promptPreview: (0, import_agents.previewAnalysisPrompt)(cwd, pipelineResult.output, { toolRequests: tools ? maxToolRequests : 0 })
|
|
2720
3201
|
};
|
|
2721
3202
|
}
|
|
2722
3203
|
if (options.dryRun) {
|
|
@@ -2738,6 +3219,7 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2738
3219
|
...tokenBudgetUse(maxTokens, spend2)
|
|
2739
3220
|
};
|
|
2740
3221
|
}
|
|
3222
|
+
announceTools();
|
|
2741
3223
|
const finalState = await (0, import_agents.runRepairWorkflow)({
|
|
2742
3224
|
cwd,
|
|
2743
3225
|
logs: pipelineResult.output,
|
|
@@ -2747,6 +3229,8 @@ Re-run without \`--dry-run\` to let BugZero attempt a fix.
|
|
|
2747
3229
|
patience,
|
|
2748
3230
|
focusTests,
|
|
2749
3231
|
maxTokens,
|
|
3232
|
+
tools,
|
|
3233
|
+
maxToolRequests,
|
|
2750
3234
|
initialStep: pipelineResult.step
|
|
2751
3235
|
});
|
|
2752
3236
|
const result = {
|
|
@@ -3313,7 +3797,7 @@ ${allPassed ? "\u2705 All checks passed" : "\u274C Issues found \u2014 run 'bugz
|
|
|
3313
3797
|
finish(1, json ? buildErrorJson(String(error.message || error)) : void 0);
|
|
3314
3798
|
}
|
|
3315
3799
|
});
|
|
3316
|
-
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) => {
|
|
3317
3801
|
const json = opts.json === true;
|
|
3318
3802
|
const printPrompt = opts.printPrompt === true;
|
|
3319
3803
|
if (json || printPrompt) routeLogsToStderr();
|
|
@@ -3327,6 +3811,9 @@ program.command("rescue").description("Detect build failures and automatically a
|
|
|
3327
3811
|
const maxTokens = opts.maxTokens === void 0 ? void 0 : Number(opts.maxTokens);
|
|
3328
3812
|
(0, import_core.resolveMaxTokens)(maxTokens, void 0);
|
|
3329
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);
|
|
3330
3817
|
const dryRun = opts.dryRun;
|
|
3331
3818
|
let approve;
|
|
3332
3819
|
if (opts.approve === true && !dryRun && !printPrompt) {
|
|
@@ -3360,7 +3847,9 @@ program.command("rescue").description("Detect build failures and automatically a
|
|
|
3360
3847
|
approve,
|
|
3361
3848
|
patience,
|
|
3362
3849
|
focusTests,
|
|
3363
|
-
maxTokens
|
|
3850
|
+
maxTokens,
|
|
3851
|
+
tools,
|
|
3852
|
+
maxToolRequests
|
|
3364
3853
|
});
|
|
3365
3854
|
if (result.promptPreview !== void 0) {
|
|
3366
3855
|
if (json) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bugzero",
|
|
3
|
-
"version": "0.0.
|
|
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)",
|