brocodex 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Dockerfile +7 -0
- package/dist/index.js +2330 -0
- package/package.json +58 -3
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2330 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import readline3 from "node:readline/promises";
|
|
5
|
+
import { stdin as input3, stdout as output3 } from "node:process";
|
|
6
|
+
import http from "node:http";
|
|
7
|
+
import fs5 from "node:fs";
|
|
8
|
+
import path5 from "node:path";
|
|
9
|
+
|
|
10
|
+
// src/tools/executor.ts
|
|
11
|
+
import fs3 from "node:fs/promises";
|
|
12
|
+
import path3 from "node:path";
|
|
13
|
+
|
|
14
|
+
// src/tools/patch/parser.ts
|
|
15
|
+
var HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: .*)?$/;
|
|
16
|
+
function reject(message) {
|
|
17
|
+
throw new Error(`PATCH_REJECTED: ${message}`);
|
|
18
|
+
}
|
|
19
|
+
function parsePatch(diff) {
|
|
20
|
+
if (!diff.trim()) {
|
|
21
|
+
reject("empty patch");
|
|
22
|
+
}
|
|
23
|
+
const normalized = diff.replace(/\r\n/g, "\n");
|
|
24
|
+
if (normalized.includes("\r")) {
|
|
25
|
+
reject("unsupported patch line endings");
|
|
26
|
+
}
|
|
27
|
+
const lines = normalized.split("\n");
|
|
28
|
+
if (lines.at(-1) === "") {
|
|
29
|
+
lines.pop();
|
|
30
|
+
}
|
|
31
|
+
if (lines.length < 3) {
|
|
32
|
+
reject("incomplete patch");
|
|
33
|
+
}
|
|
34
|
+
const oldHeader = lines[0].match(/^--- a\/(.+)$/);
|
|
35
|
+
const newHeader = lines[1].match(/^\+\+\+ b\/(.+)$/);
|
|
36
|
+
if (!oldHeader || !newHeader) {
|
|
37
|
+
reject("invalid file header pair");
|
|
38
|
+
}
|
|
39
|
+
const filePath = oldHeader[1];
|
|
40
|
+
if (filePath !== newHeader[1]) {
|
|
41
|
+
reject("patch must target exactly one file");
|
|
42
|
+
}
|
|
43
|
+
if (filePath.includes("\\") || filePath.includes("\0") || filePath.startsWith("/") || filePath.split("/").some(
|
|
44
|
+
(part) => part === "." || part === ".." || part === ""
|
|
45
|
+
)) {
|
|
46
|
+
reject("invalid or unsafe file path");
|
|
47
|
+
}
|
|
48
|
+
const hunks = [];
|
|
49
|
+
let current = null;
|
|
50
|
+
let oldCount = 0;
|
|
51
|
+
let newCount = 0;
|
|
52
|
+
function finishHunk() {
|
|
53
|
+
if (!current) return;
|
|
54
|
+
if (oldCount !== current.oldCount || newCount !== current.newCount) {
|
|
55
|
+
reject(
|
|
56
|
+
`hunk count mismatch: expected -${current.oldCount}/+${current.newCount}, got -${oldCount}/+${newCount}`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
hunks.push(current);
|
|
60
|
+
current = null;
|
|
61
|
+
oldCount = 0;
|
|
62
|
+
newCount = 0;
|
|
63
|
+
}
|
|
64
|
+
for (let i = 2; i < lines.length; i++) {
|
|
65
|
+
const line = lines[i];
|
|
66
|
+
const match = line.match(HUNK_RE);
|
|
67
|
+
if (match) {
|
|
68
|
+
finishHunk();
|
|
69
|
+
current = {
|
|
70
|
+
oldStart: Number(match[1]),
|
|
71
|
+
oldCount: match[2] === void 0 ? 1 : Number(match[2]),
|
|
72
|
+
newStart: Number(match[3]),
|
|
73
|
+
newCount: match[4] === void 0 ? 1 : Number(match[4]),
|
|
74
|
+
lines: []
|
|
75
|
+
};
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (line.startsWith("@@")) {
|
|
79
|
+
reject(`invalid hunk header at patch line ${i + 1}`);
|
|
80
|
+
}
|
|
81
|
+
if (!current) {
|
|
82
|
+
reject(`unexpected content at patch line ${i + 1}`);
|
|
83
|
+
}
|
|
84
|
+
if (line.startsWith("\")) {
|
|
85
|
+
reject("no-newline markers are not supported");
|
|
86
|
+
}
|
|
87
|
+
const prefix = line[0];
|
|
88
|
+
const content = line.slice(1);
|
|
89
|
+
if (prefix === " ") {
|
|
90
|
+
current.lines.push({ type: "context", content });
|
|
91
|
+
oldCount++;
|
|
92
|
+
newCount++;
|
|
93
|
+
} else if (prefix === "-") {
|
|
94
|
+
current.lines.push({ type: "remove", content });
|
|
95
|
+
oldCount++;
|
|
96
|
+
} else if (prefix === "+") {
|
|
97
|
+
current.lines.push({ type: "add", content });
|
|
98
|
+
newCount++;
|
|
99
|
+
} else {
|
|
100
|
+
reject(`invalid hunk line at patch line ${i + 1}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
finishHunk();
|
|
104
|
+
if (hunks.length === 0) {
|
|
105
|
+
reject("no hunks in patch");
|
|
106
|
+
}
|
|
107
|
+
return { filePath, hunks };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// src/tools/patch/engine.ts
|
|
111
|
+
import fs from "node:fs/promises";
|
|
112
|
+
import path from "node:path";
|
|
113
|
+
import { createHash } from "node:crypto";
|
|
114
|
+
function reject2(message) {
|
|
115
|
+
throw new Error(`PATCH_REJECTED: ${message}`);
|
|
116
|
+
}
|
|
117
|
+
function hash(content) {
|
|
118
|
+
return createHash("sha256").update(content).digest("hex");
|
|
119
|
+
}
|
|
120
|
+
async function resolveTarget(cwd, filePath) {
|
|
121
|
+
const root2 = await fs.realpath(cwd);
|
|
122
|
+
const target = path.resolve(root2, filePath);
|
|
123
|
+
const relative = path.relative(root2, target);
|
|
124
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
125
|
+
reject2("path escapes workspace");
|
|
126
|
+
}
|
|
127
|
+
let realTarget;
|
|
128
|
+
try {
|
|
129
|
+
realTarget = await fs.realpath(target);
|
|
130
|
+
} catch {
|
|
131
|
+
reject2("target file does not exist");
|
|
132
|
+
}
|
|
133
|
+
const realRelative = path.relative(root2, realTarget);
|
|
134
|
+
if (realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
|
|
135
|
+
reject2("symlink escapes workspace");
|
|
136
|
+
}
|
|
137
|
+
const stat = await fs.stat(realTarget);
|
|
138
|
+
if (!stat.isFile()) {
|
|
139
|
+
reject2("target is not a regular file");
|
|
140
|
+
}
|
|
141
|
+
return realTarget;
|
|
142
|
+
}
|
|
143
|
+
function splitFile(content) {
|
|
144
|
+
const hasCRLF = content.includes("\r\n");
|
|
145
|
+
const withoutCRLF = content.replace(/\r\n/g, "");
|
|
146
|
+
if (hasCRLF && withoutCRLF.includes("\n")) {
|
|
147
|
+
reject2("mixed line endings are not supported");
|
|
148
|
+
}
|
|
149
|
+
const newline = hasCRLF ? "\r\n" : "\n";
|
|
150
|
+
const hasFinalNewline = content.endsWith(newline);
|
|
151
|
+
if (content.length === 0) {
|
|
152
|
+
return {
|
|
153
|
+
lines: [],
|
|
154
|
+
newline,
|
|
155
|
+
hasFinalNewline: false
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const lines = content.split(newline);
|
|
159
|
+
if (hasFinalNewline) {
|
|
160
|
+
lines.pop();
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
lines,
|
|
164
|
+
newline,
|
|
165
|
+
hasFinalNewline
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function applyHunks(original, patch) {
|
|
169
|
+
const result = [];
|
|
170
|
+
const summaries = [];
|
|
171
|
+
let sourceCursor = 0;
|
|
172
|
+
for (const hunk of patch.hunks) {
|
|
173
|
+
const oldIndex = hunk.oldCount === 0 ? hunk.oldStart : hunk.oldStart - 1;
|
|
174
|
+
const newIndex = hunk.newCount === 0 ? hunk.newStart : hunk.newStart - 1;
|
|
175
|
+
if (oldIndex < 0 || oldIndex < sourceCursor || oldIndex > original.length) {
|
|
176
|
+
reject2("invalid or overlapping hunk positions");
|
|
177
|
+
}
|
|
178
|
+
const expectedNewIndex = result.length + (oldIndex - sourceCursor);
|
|
179
|
+
if (newIndex !== expectedNewIndex) {
|
|
180
|
+
reject2("old/new hunk positions are inconsistent");
|
|
181
|
+
}
|
|
182
|
+
result.push(
|
|
183
|
+
...original.slice(sourceCursor, oldIndex)
|
|
184
|
+
);
|
|
185
|
+
sourceCursor = oldIndex;
|
|
186
|
+
let added = 0;
|
|
187
|
+
let removed = 0;
|
|
188
|
+
for (const line of hunk.lines) {
|
|
189
|
+
if (line.type === "add") {
|
|
190
|
+
result.push(line.content);
|
|
191
|
+
added++;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const actual = original[sourceCursor];
|
|
195
|
+
if (actual === void 0) {
|
|
196
|
+
reject2("hunk references lines beyond end of file");
|
|
197
|
+
}
|
|
198
|
+
if (actual !== line.content) {
|
|
199
|
+
reject2(
|
|
200
|
+
`${line.type} mismatch at line ${sourceCursor + 1}: expected ${JSON.stringify(line.content)}, got ${JSON.stringify(actual)}`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
if (line.type === "context") {
|
|
204
|
+
result.push(actual);
|
|
205
|
+
} else {
|
|
206
|
+
removed++;
|
|
207
|
+
}
|
|
208
|
+
sourceCursor++;
|
|
209
|
+
}
|
|
210
|
+
summaries.push({
|
|
211
|
+
header: `@@ -${hunk.oldStart},${hunk.oldCount} +${hunk.newStart},${hunk.newCount} @@`,
|
|
212
|
+
added,
|
|
213
|
+
removed
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
result.push(...original.slice(sourceCursor));
|
|
217
|
+
return {
|
|
218
|
+
lines: result,
|
|
219
|
+
summaries
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
async function dryRun(cwd, patch) {
|
|
223
|
+
const absPath = await resolveTarget(cwd, patch.filePath);
|
|
224
|
+
const buffer = await fs.readFile(absPath);
|
|
225
|
+
const before = buffer.toString("utf8");
|
|
226
|
+
if (!Buffer.from(before, "utf8").equals(buffer)) {
|
|
227
|
+
reject2("binary or invalid UTF-8 files are not supported");
|
|
228
|
+
}
|
|
229
|
+
const {
|
|
230
|
+
lines: originalLines,
|
|
231
|
+
newline,
|
|
232
|
+
hasFinalNewline
|
|
233
|
+
} = splitFile(before);
|
|
234
|
+
const { lines, summaries } = applyHunks(
|
|
235
|
+
originalLines,
|
|
236
|
+
patch
|
|
237
|
+
);
|
|
238
|
+
const after = lines.join(newline) + (hasFinalNewline ? newline : "");
|
|
239
|
+
return {
|
|
240
|
+
filePath: patch.filePath,
|
|
241
|
+
before,
|
|
242
|
+
after,
|
|
243
|
+
originalHash: hash(buffer),
|
|
244
|
+
hunkSummaries: summaries
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// src/tools/patch/commit.ts
|
|
249
|
+
import fs2 from "node:fs/promises";
|
|
250
|
+
import path2 from "node:path";
|
|
251
|
+
import { randomUUID } from "node:crypto";
|
|
252
|
+
function reject3(message) {
|
|
253
|
+
throw new Error(`PATCH_REJECTED: ${message}`);
|
|
254
|
+
}
|
|
255
|
+
async function commit(cwd, result) {
|
|
256
|
+
const absPath = await resolveTarget(cwd, result.filePath);
|
|
257
|
+
const current = await fs2.readFile(absPath);
|
|
258
|
+
if (hash(current) !== result.originalHash) {
|
|
259
|
+
reject3("file changed since dry-run");
|
|
260
|
+
}
|
|
261
|
+
if (!current.equals(Buffer.from(result.before, "utf8"))) {
|
|
262
|
+
reject3("original file content changed");
|
|
263
|
+
}
|
|
264
|
+
const originalStat = await fs2.stat(absPath);
|
|
265
|
+
const directory = path2.dirname(absPath);
|
|
266
|
+
const tempPath = path2.join(
|
|
267
|
+
directory,
|
|
268
|
+
`.${path2.basename(absPath)}.${randomUUID()}.tmp`
|
|
269
|
+
);
|
|
270
|
+
try {
|
|
271
|
+
const handle = await fs2.open(tempPath, "wx");
|
|
272
|
+
try {
|
|
273
|
+
await handle.writeFile(result.after, "utf8");
|
|
274
|
+
await handle.chmod(originalStat.mode);
|
|
275
|
+
await handle.sync();
|
|
276
|
+
} finally {
|
|
277
|
+
await handle.close();
|
|
278
|
+
}
|
|
279
|
+
const latest = await fs2.readFile(absPath);
|
|
280
|
+
if (hash(latest) !== result.originalHash) {
|
|
281
|
+
reject3("file changed before commit");
|
|
282
|
+
}
|
|
283
|
+
await fs2.rename(tempPath, absPath);
|
|
284
|
+
} catch (error2) {
|
|
285
|
+
await fs2.rm(tempPath, { force: true });
|
|
286
|
+
throw error2;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// src/tools/command-policy.ts
|
|
291
|
+
function badPath(p) {
|
|
292
|
+
if (p === "") return "empty path";
|
|
293
|
+
if (p.startsWith("/") || p.startsWith("~")) {
|
|
294
|
+
return `absolute paths are not allowed: ${p}`;
|
|
295
|
+
}
|
|
296
|
+
if (p.split(/[\\/]/).includes("..")) {
|
|
297
|
+
return `".." is not allowed in paths: ${p}`;
|
|
298
|
+
}
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
function simple(flags) {
|
|
302
|
+
return (args) => {
|
|
303
|
+
for (const a of args) {
|
|
304
|
+
if (a.startsWith("-")) {
|
|
305
|
+
if (!flags.test(a)) return `flag not allowed: ${a}`;
|
|
306
|
+
} else {
|
|
307
|
+
const reason = badPath(a);
|
|
308
|
+
if (reason) return reason;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return null;
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
var noArgs = (args) => args.length === 0 ? null : "this command takes no arguments";
|
|
315
|
+
var gitRule = (args) => {
|
|
316
|
+
let a = args;
|
|
317
|
+
if (a[0] === "--version") return a.length === 1 ? null : "no extra arguments";
|
|
318
|
+
if (a[0] === "--no-pager") a = a.slice(1);
|
|
319
|
+
const [sub, ...rest] = a;
|
|
320
|
+
if (sub === "branch") {
|
|
321
|
+
return rest.length === 1 && rest[0] === "--show-current" ? null : "only `git branch --show-current` is allowed";
|
|
322
|
+
}
|
|
323
|
+
if (!sub || !["status", "diff", "log", "show"].includes(sub)) {
|
|
324
|
+
return "only git status, diff, log, show and branch --show-current are allowed";
|
|
325
|
+
}
|
|
326
|
+
for (const x of rest) {
|
|
327
|
+
if (x.startsWith("-")) {
|
|
328
|
+
if (!/^(--short|--stat|--oneline|--no-ext-diff|--name-only|--cached|--staged|-n|-\d+)$/.test(
|
|
329
|
+
x
|
|
330
|
+
)) {
|
|
331
|
+
return `git flag not allowed: ${x}`;
|
|
332
|
+
}
|
|
333
|
+
} else {
|
|
334
|
+
const reason = badPath(x);
|
|
335
|
+
if (reason) return reason;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return null;
|
|
339
|
+
};
|
|
340
|
+
var findRule = (args) => {
|
|
341
|
+
const flags = ["-name", "-iname", "-type", "-maxdepth", "-mindepth", "-path"];
|
|
342
|
+
for (const a of args) {
|
|
343
|
+
if (a.startsWith("-")) {
|
|
344
|
+
if (!flags.includes(a)) return `find flag not allowed: ${a}`;
|
|
345
|
+
} else if (a.startsWith("/") || a.startsWith("~") || a.split(/[\\/]/).includes("..")) {
|
|
346
|
+
return `unsafe path or pattern: ${a}`;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return null;
|
|
350
|
+
};
|
|
351
|
+
var rmRule = (args) => {
|
|
352
|
+
for (const a of args) {
|
|
353
|
+
if (a.startsWith("-")) {
|
|
354
|
+
if (!/^-[rf]+$/.test(a)) return `rm flag not allowed: ${a}`;
|
|
355
|
+
} else {
|
|
356
|
+
const reason = badPath(a);
|
|
357
|
+
if (reason) return reason;
|
|
358
|
+
if (a === "." || a === "./" || a.includes("*")) {
|
|
359
|
+
return "refusing to delete the whole workspace or use wildcards";
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return args.some((a) => !a.startsWith("-")) ? null : "rm needs at least one file path";
|
|
364
|
+
};
|
|
365
|
+
function scriptRunner(version, check, ext) {
|
|
366
|
+
return (args) => {
|
|
367
|
+
if (args.length === 0) return "missing script path";
|
|
368
|
+
if (version.includes(args[0])) {
|
|
369
|
+
return args.length === 1 ? null : "no extra arguments";
|
|
370
|
+
}
|
|
371
|
+
if (check && args[0] === check[0]) {
|
|
372
|
+
return args.length === 2 && !badPath(args[1]) && ext.test(args[1]) ? null : `usage: ${check[0]} <file>`;
|
|
373
|
+
}
|
|
374
|
+
const script = args[0];
|
|
375
|
+
if (script.startsWith("-")) return `flag not allowed: ${script}`;
|
|
376
|
+
const reason = badPath(script);
|
|
377
|
+
if (reason) return reason;
|
|
378
|
+
if (!ext.test(script)) return `script must match ${ext}`;
|
|
379
|
+
return null;
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
var PKG_SCRIPTS = ["build", "test", "lint", "typecheck", "check"];
|
|
383
|
+
var pkgRule = (args) => {
|
|
384
|
+
const [cmd, ...rest] = args;
|
|
385
|
+
if (cmd === "--version") return rest.length === 0 ? null : "no extra arguments";
|
|
386
|
+
if (cmd === "list" || cmd === "ls") {
|
|
387
|
+
return rest.every((x) => /^(--depth|--depth=\d+|\d+)$/.test(x)) ? null : "only --depth is allowed with list";
|
|
388
|
+
}
|
|
389
|
+
if (cmd === "test") return rest.length === 0 ? null : "test takes no arguments";
|
|
390
|
+
if (cmd !== void 0 && PKG_SCRIPTS.includes(cmd) && rest.length === 0) return null;
|
|
391
|
+
if (cmd === "run") {
|
|
392
|
+
return rest.length === 1 && PKG_SCRIPTS.includes(rest[0]) ? null : `only: run ${PKG_SCRIPTS.join(" | ")}`;
|
|
393
|
+
}
|
|
394
|
+
return `only: --version, list, test, run <${PKG_SCRIPTS.join("|")}>. Installing packages is not available (no internet).`;
|
|
395
|
+
};
|
|
396
|
+
var tscRule = (args) => {
|
|
397
|
+
for (let i = 0; i < args.length; i++) {
|
|
398
|
+
const a = args[i];
|
|
399
|
+
if (a === "--noEmit" || a === "--version" || a === "-p") continue;
|
|
400
|
+
if (!a.startsWith("-") && args[i - 1] === "-p" && !badPath(a)) continue;
|
|
401
|
+
return `tsc argument not allowed: ${a}`;
|
|
402
|
+
}
|
|
403
|
+
return null;
|
|
404
|
+
};
|
|
405
|
+
var RULES = {
|
|
406
|
+
// info
|
|
407
|
+
pwd: noArgs,
|
|
408
|
+
whoami: noArgs,
|
|
409
|
+
date: noArgs,
|
|
410
|
+
uname: (a) => a.length === 0 || a.length === 1 && a[0] === "-a" ? null : "only uname or uname -a",
|
|
411
|
+
// look around
|
|
412
|
+
ls: simple(/^-[laAhRt1]+$/),
|
|
413
|
+
tree: (args) => {
|
|
414
|
+
for (let i = 0; i < args.length; i++) {
|
|
415
|
+
const a = args[i];
|
|
416
|
+
if (a === "-a") continue;
|
|
417
|
+
if (a === "-L" && /^[1-4]$/.test(args[i + 1] ?? "")) {
|
|
418
|
+
i++;
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
if (!a.startsWith("-") && !badPath(a)) continue;
|
|
422
|
+
return `tree argument not allowed: ${a}`;
|
|
423
|
+
}
|
|
424
|
+
return null;
|
|
425
|
+
},
|
|
426
|
+
cat: simple(/^-n$/),
|
|
427
|
+
head: simple(/^-(n|c|\d+)$/),
|
|
428
|
+
tail: simple(/^-(n|c|\d+)$/),
|
|
429
|
+
wc: simple(/^-[lwc]+$/),
|
|
430
|
+
find: findRule,
|
|
431
|
+
grep: simple(/^-[a-zA-Z]+$/),
|
|
432
|
+
rg: simple(/^-[a-zA-Z]+$|^--(files|hidden|no-ignore)$/),
|
|
433
|
+
// change files (only touches the sandbox copy)
|
|
434
|
+
mkdir: simple(/^-p$/),
|
|
435
|
+
touch: simple(/^$/),
|
|
436
|
+
cp: simple(/^-r$/),
|
|
437
|
+
mv: simple(/^$/),
|
|
438
|
+
rm: rmRule,
|
|
439
|
+
// git (read-only)
|
|
440
|
+
git: gitRule,
|
|
441
|
+
// run code
|
|
442
|
+
node: scriptRunner(["--version"], ["--check"], /\.(m|c)?js$/),
|
|
443
|
+
python3: scriptRunner(["--version"], null, /\.py$/),
|
|
444
|
+
// package managers (no installs)
|
|
445
|
+
npm: pkgRule,
|
|
446
|
+
pnpm: pkgRule,
|
|
447
|
+
tsc: tscRule
|
|
448
|
+
};
|
|
449
|
+
function validateCommand(executable, args) {
|
|
450
|
+
if (typeof executable !== "string" || executable.trim() === "") {
|
|
451
|
+
throw new Error("Invalid executable");
|
|
452
|
+
}
|
|
453
|
+
if (!Array.isArray(args) || !args.every((a) => typeof a === "string")) {
|
|
454
|
+
throw new Error("Invalid command arguments");
|
|
455
|
+
}
|
|
456
|
+
const rule = Object.prototype.hasOwnProperty.call(RULES, executable) ? RULES[executable] : void 0;
|
|
457
|
+
if (!rule) {
|
|
458
|
+
throw new Error(
|
|
459
|
+
`Command not permitted: "${executable}". Allowed programs: ${Object.keys(RULES).join(", ")}`
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
const problem = rule(args);
|
|
463
|
+
if (problem) {
|
|
464
|
+
throw new Error(`Command not permitted: ${executable} ${args.join(" ")} (${problem})`);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
var ALLOWED_COMMANDS_HELP = "Programs: pwd, whoami, date, uname, ls, tree, cat, head, tail, wc, find, grep, rg, mkdir -p, touch, cp, mv, rm, git (read-only: status, diff, log, show), node <file.js>, node --check <file.js>, python3 <file.py>, npm/pnpm (list, test, run build|test|lint|typecheck|check), tsc --noEmit. Paths must be relative and cannot contain '..'. No shell features (pipes, &&, >, *) and no internet: installing packages, curl and wget do not work.";
|
|
468
|
+
|
|
469
|
+
// src/tools/executor.ts
|
|
470
|
+
var sandbox = null;
|
|
471
|
+
function useSandbox(sb) {
|
|
472
|
+
sandbox = sb;
|
|
473
|
+
}
|
|
474
|
+
function root() {
|
|
475
|
+
if (!sandbox) throw new Error("sandbox not started");
|
|
476
|
+
return sandbox.workDir;
|
|
477
|
+
}
|
|
478
|
+
function safeResolve(p) {
|
|
479
|
+
if (path3.isAbsolute(p)) {
|
|
480
|
+
throw new Error("Absolute paths not allowed");
|
|
481
|
+
}
|
|
482
|
+
const base = root();
|
|
483
|
+
const resolved = path3.resolve(base, p);
|
|
484
|
+
const relative = path3.relative(base, resolved);
|
|
485
|
+
if (relative === ".." || relative.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative)) {
|
|
486
|
+
throw new Error("Path escapes workspace");
|
|
487
|
+
}
|
|
488
|
+
return resolved;
|
|
489
|
+
}
|
|
490
|
+
async function applyPatchTool(diff) {
|
|
491
|
+
const parsed = parsePatch(diff);
|
|
492
|
+
const result = await dryRun(root(), parsed);
|
|
493
|
+
await commit(root(), result);
|
|
494
|
+
const summary = result.hunkSummaries.map((hunk) => `${hunk.header}: +${hunk.added} -${hunk.removed}`).join("\n");
|
|
495
|
+
return [
|
|
496
|
+
`Successfully patched ${result.filePath}.`,
|
|
497
|
+
`${result.hunkSummaries.length} hunk(s) applied.`,
|
|
498
|
+
summary
|
|
499
|
+
].join("\n");
|
|
500
|
+
}
|
|
501
|
+
async function runTool(name, input4) {
|
|
502
|
+
try {
|
|
503
|
+
if (name === "read_file") {
|
|
504
|
+
const p = safeResolve(String(input4.path));
|
|
505
|
+
const content = await fs3.readFile(p, "utf-8");
|
|
506
|
+
return content.length > 2e4 ? content.slice(0, 2e4) + "\n\u2026[truncated]" : content;
|
|
507
|
+
}
|
|
508
|
+
if (name === "list_dir") {
|
|
509
|
+
const p = safeResolve(String(input4.path ?? "."));
|
|
510
|
+
const entries = await fs3.readdir(p, { withFileTypes: true });
|
|
511
|
+
return entries.map((entry) => entry.isDirectory() ? entry.name + "/" : entry.name).join("\n");
|
|
512
|
+
}
|
|
513
|
+
if (name === "write_file") {
|
|
514
|
+
const p = safeResolve(String(input4.path));
|
|
515
|
+
const content = String(input4.content ?? "");
|
|
516
|
+
const overwrite = input4.overwrite === true;
|
|
517
|
+
let exists = false;
|
|
518
|
+
try {
|
|
519
|
+
await fs3.access(p);
|
|
520
|
+
exists = true;
|
|
521
|
+
} catch {
|
|
522
|
+
}
|
|
523
|
+
if (exists && !overwrite) {
|
|
524
|
+
return "TOOL_ERROR: file already exists. Use apply_patch to edit it, or call write_file again with overwrite=true to replace it.";
|
|
525
|
+
}
|
|
526
|
+
await fs3.mkdir(path3.dirname(p), { recursive: true });
|
|
527
|
+
await fs3.writeFile(p, content, "utf-8");
|
|
528
|
+
return `${exists ? "Overwrote" : "Created"} ${String(input4.path)} (${content.length} chars).`;
|
|
529
|
+
}
|
|
530
|
+
if (name === "run_command") {
|
|
531
|
+
const executable = String(input4.executable ?? "");
|
|
532
|
+
const args = input4.args;
|
|
533
|
+
if (!Array.isArray(args) || !args.every((arg) => typeof arg === "string")) {
|
|
534
|
+
return "TOOL_ERROR: Invalid arguments";
|
|
535
|
+
}
|
|
536
|
+
validateCommand(executable, args);
|
|
537
|
+
if (!sandbox) return "TOOL_ERROR: sandbox not started";
|
|
538
|
+
const r = await sandbox.execArgs(executable, args, 15);
|
|
539
|
+
if (r.timedOut) return "TOOL_ERROR: command timed out";
|
|
540
|
+
return (r.stdout + (r.stderr ? "\n[stderr]\n" + r.stderr : "")).slice(
|
|
541
|
+
0,
|
|
542
|
+
2e4
|
|
543
|
+
) || `(empty, exit code ${r.exitCode})`;
|
|
544
|
+
}
|
|
545
|
+
if (name === "install_packages") {
|
|
546
|
+
if (!sandbox) return "TOOL_ERROR: sandbox not started";
|
|
547
|
+
const pkgs = input4.packages;
|
|
548
|
+
const validName = /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-z0-9._^~*-]+)?$/i;
|
|
549
|
+
if (pkgs !== void 0 && (!Array.isArray(pkgs) || !pkgs.every((p) => typeof p === "string" && validName.test(p)))) {
|
|
550
|
+
return "TOOL_ERROR: invalid package name";
|
|
551
|
+
}
|
|
552
|
+
const list = pkgs ?? [];
|
|
553
|
+
const args = list.length > 0 ? ["add", ...list] : ["install"];
|
|
554
|
+
const r = await sandbox.execWithNetwork("pnpm", args);
|
|
555
|
+
if (r.timedOut) return "TOOL_ERROR: install timed out";
|
|
556
|
+
return (r.stdout + (r.stderr ? "\n[stderr]\n" + r.stderr : "")).slice(
|
|
557
|
+
-5e3
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
if (name === "apply_patch") {
|
|
561
|
+
const diff = String(input4.diff ?? "");
|
|
562
|
+
if (!diff) {
|
|
563
|
+
return "TOOL_ERROR: missing diff argument";
|
|
564
|
+
}
|
|
565
|
+
try {
|
|
566
|
+
return await applyPatchTool(diff);
|
|
567
|
+
} catch (error2) {
|
|
568
|
+
const msg = error2 instanceof Error ? error2.message : String(error2);
|
|
569
|
+
return msg + "\nHINT: apply_patch only accepts unified diffs starting with '--- a/PATH' and '+++ b/PATH'. Do NOT use the '*** Begin Patch' format. Easiest fix: read_file, then call write_file with overwrite=true and the full updated content.";
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return `Unknown tool: ${name}`;
|
|
573
|
+
} catch (error2) {
|
|
574
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
575
|
+
return `TOOL_ERROR: ${message}`;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// src/tools/definitions.ts
|
|
580
|
+
var TOOLS = [
|
|
581
|
+
{
|
|
582
|
+
name: "list_dir",
|
|
583
|
+
description: "List the files and folders inside a directory of the project. Folders end with '/'. Use it first to see what already exists. Use path '.' for the project root.",
|
|
584
|
+
parameters: {
|
|
585
|
+
type: "OBJECT",
|
|
586
|
+
properties: {
|
|
587
|
+
path: {
|
|
588
|
+
type: "STRING",
|
|
589
|
+
description: "Relative directory path, e.g. '.' or 'src/css'"
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
},
|
|
594
|
+
{
|
|
595
|
+
name: "read_file",
|
|
596
|
+
description: "Read a text file from the project. Always read a file before editing it so your changes match its current content. Output is cut after 20,000 characters.",
|
|
597
|
+
parameters: {
|
|
598
|
+
type: "OBJECT",
|
|
599
|
+
properties: {
|
|
600
|
+
path: {
|
|
601
|
+
type: "STRING",
|
|
602
|
+
description: "Relative file path, e.g. 'index.html'"
|
|
603
|
+
}
|
|
604
|
+
},
|
|
605
|
+
required: ["path"]
|
|
606
|
+
}
|
|
607
|
+
},
|
|
608
|
+
{
|
|
609
|
+
name: "write_file",
|
|
610
|
+
description: "Create a file with the full content you provide. Missing folders are created automatically. By default it fails if the file already exists. Set overwrite=true to replace an existing file completely. Prefer this for new files and for rewriting small files (like an HTML page or a stylesheet). For small edits to a large file, use apply_patch instead.",
|
|
611
|
+
parameters: {
|
|
612
|
+
type: "OBJECT",
|
|
613
|
+
properties: {
|
|
614
|
+
path: {
|
|
615
|
+
type: "STRING",
|
|
616
|
+
description: "Relative path, e.g. 'index.html' or 'css/style.css'"
|
|
617
|
+
},
|
|
618
|
+
content: {
|
|
619
|
+
type: "STRING",
|
|
620
|
+
description: "The complete content of the file"
|
|
621
|
+
},
|
|
622
|
+
overwrite: {
|
|
623
|
+
type: "BOOLEAN",
|
|
624
|
+
description: "Set true to replace a file that already exists. Default false."
|
|
625
|
+
}
|
|
626
|
+
},
|
|
627
|
+
required: ["path", "content"]
|
|
628
|
+
}
|
|
629
|
+
},
|
|
630
|
+
{
|
|
631
|
+
name: "apply_patch",
|
|
632
|
+
description: "Edit ONE EXISTING file with a unified diff. It cannot create files (use write_file). Format:\n--- a/PATH\n+++ b/PATH\n@@ -START,COUNT +START,COUNT @@\n context line\n-removed line\n+added line\nRules: every hunk header needs line numbers like '@@ -3,2 +3,2 @@'; lines start with ' ' (unchanged), '-' (remove) or '+' (add); context lines must match the file exactly, so read_file first. If a patch is rejected, re-read the file and retry, or use write_file with overwrite=true.",
|
|
633
|
+
parameters: {
|
|
634
|
+
type: "OBJECT",
|
|
635
|
+
properties: {
|
|
636
|
+
diff: {
|
|
637
|
+
type: "STRING",
|
|
638
|
+
description: "A unified diff for exactly one file"
|
|
639
|
+
}
|
|
640
|
+
},
|
|
641
|
+
required: ["diff"]
|
|
642
|
+
}
|
|
643
|
+
},
|
|
644
|
+
{
|
|
645
|
+
name: "run_command",
|
|
646
|
+
description: "Run one command inside an isolated sandbox (copy of the project, no internet). Pass the program and its arguments separately, e.g. executable 'ls', args ['-la']. Use it to inspect files, check syntax, or run scripts and tests. Do not use it to create or edit files (use write_file). " + ALLOWED_COMMANDS_HELP,
|
|
647
|
+
parameters: {
|
|
648
|
+
type: "OBJECT",
|
|
649
|
+
properties: {
|
|
650
|
+
executable: {
|
|
651
|
+
type: "STRING",
|
|
652
|
+
description: "Program name only, e.g. 'node' or 'ls'"
|
|
653
|
+
},
|
|
654
|
+
args: {
|
|
655
|
+
type: "ARRAY",
|
|
656
|
+
items: { type: "STRING" },
|
|
657
|
+
description: "Arguments, one per item, e.g. ['--check', 'script.js']"
|
|
658
|
+
}
|
|
659
|
+
},
|
|
660
|
+
required: ["executable", "args"]
|
|
661
|
+
}
|
|
662
|
+
},
|
|
663
|
+
{
|
|
664
|
+
name: "install_packages",
|
|
665
|
+
description: "Install npm packages into the project. This is the ONLY tool with internet access, and it is only online while installing. Pass package names like ['vite', 'react@18'], or leave packages empty to install everything listed in package.json. After installing, use run_command to run scripts (e.g. pnpm run build).",
|
|
666
|
+
parameters: {
|
|
667
|
+
type: "OBJECT",
|
|
668
|
+
properties: {
|
|
669
|
+
packages: {
|
|
670
|
+
type: "ARRAY",
|
|
671
|
+
items: { type: "STRING" },
|
|
672
|
+
description: "Package names, optionally with a version, e.g. 'react@18'"
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
];
|
|
678
|
+
|
|
679
|
+
// src/agent/context/observation-compaction.ts
|
|
680
|
+
var DEFAULT_KEEP_RECENT = 4;
|
|
681
|
+
var PLACEHOLDER_PREFIX = "[observation masked \u2014";
|
|
682
|
+
function createPlaceholder(content) {
|
|
683
|
+
const lineCount = content.split("\n").length;
|
|
684
|
+
return `${PLACEHOLDER_PREFIX} ${lineCount} lines omitted]`;
|
|
685
|
+
}
|
|
686
|
+
function maskOldObservations(history, keep = DEFAULT_KEEP_RECENT) {
|
|
687
|
+
if (!Number.isInteger(keep) || keep < 0) {
|
|
688
|
+
throw new Error("keep must be a non-negative integer");
|
|
689
|
+
}
|
|
690
|
+
const toolIndices = [];
|
|
691
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
692
|
+
if (history[i].role === "tool") {
|
|
693
|
+
toolIndices.push(i);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
const indicesToMask = toolIndices.slice(keep);
|
|
697
|
+
if (indicesToMask.length === 0) {
|
|
698
|
+
return history;
|
|
699
|
+
}
|
|
700
|
+
const next = [...history];
|
|
701
|
+
for (const index of indicesToMask) {
|
|
702
|
+
const message = history[index];
|
|
703
|
+
if (message.role !== "tool") continue;
|
|
704
|
+
next[index] = {
|
|
705
|
+
...message,
|
|
706
|
+
content: createPlaceholder(message.content)
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
return next;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// src/agent/context/token-estimation.ts
|
|
713
|
+
function approxTokens(history) {
|
|
714
|
+
let chars = 0;
|
|
715
|
+
for (const message of history) {
|
|
716
|
+
chars += message.content.length;
|
|
717
|
+
chars += 4;
|
|
718
|
+
if (message.role === "assistant" && message.toolCalls) {
|
|
719
|
+
for (const call of message.toolCalls) {
|
|
720
|
+
chars += call.name.length;
|
|
721
|
+
chars += JSON.stringify(call.input).length;
|
|
722
|
+
chars += (call.id?.length ?? 0) + 20;
|
|
723
|
+
if (call.providerMetadata) {
|
|
724
|
+
chars += JSON.stringify(call.providerMetadata).length;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if (message.role === "tool") {
|
|
729
|
+
chars += message.toolName.length;
|
|
730
|
+
chars += message.toolCallId?.length ?? 0;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return Math.ceil(chars / 4);
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// src/agent/context/compact-context.ts
|
|
737
|
+
function compactContext(history, options) {
|
|
738
|
+
const {
|
|
739
|
+
maxTokens,
|
|
740
|
+
keepRecentObservations = 4
|
|
741
|
+
} = options;
|
|
742
|
+
if (!Number.isFinite(maxTokens) || maxTokens <= 0) {
|
|
743
|
+
throw new Error("maxTokens must be greater than zero");
|
|
744
|
+
}
|
|
745
|
+
const originalTokens = approxTokens(history);
|
|
746
|
+
if (originalTokens <= maxTokens) {
|
|
747
|
+
return {
|
|
748
|
+
messages: history,
|
|
749
|
+
originalTokens,
|
|
750
|
+
compactedTokens: originalTokens,
|
|
751
|
+
observationsMasked: 0,
|
|
752
|
+
wasCompacted: false
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
const messages = maskOldObservations(
|
|
756
|
+
history,
|
|
757
|
+
keepRecentObservations
|
|
758
|
+
);
|
|
759
|
+
const compactedTokens = approxTokens(messages);
|
|
760
|
+
const observationsMasked = messages.filter(
|
|
761
|
+
(message, index) => message.role === "tool" && history[index].role === "tool" && history[index].content !== message.content
|
|
762
|
+
).length;
|
|
763
|
+
return {
|
|
764
|
+
messages,
|
|
765
|
+
originalTokens,
|
|
766
|
+
compactedTokens,
|
|
767
|
+
observationsMasked,
|
|
768
|
+
wasCompacted: observationsMasked > 0
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/ui.ts
|
|
773
|
+
var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
|
|
774
|
+
var wrap = (open, close) => (s) => useColor ? `\x1B[${open}m${s}\x1B[${close}m` : s;
|
|
775
|
+
var c = {
|
|
776
|
+
bold: wrap(1, 22),
|
|
777
|
+
dim: wrap(2, 22),
|
|
778
|
+
red: wrap(31, 39),
|
|
779
|
+
green: wrap(32, 39),
|
|
780
|
+
yellow: wrap(33, 39),
|
|
781
|
+
blue: wrap(34, 39),
|
|
782
|
+
magenta: wrap(35, 39),
|
|
783
|
+
cyan: wrap(36, 39),
|
|
784
|
+
gray: wrap(90, 39)
|
|
785
|
+
};
|
|
786
|
+
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
787
|
+
var timer = null;
|
|
788
|
+
function startSpinner(label = "Thinking") {
|
|
789
|
+
if (!process.stdout.isTTY || timer) return;
|
|
790
|
+
let i = 0;
|
|
791
|
+
const started = Date.now();
|
|
792
|
+
process.stdout.write("\x1B[?25l");
|
|
793
|
+
timer = setInterval(() => {
|
|
794
|
+
const secs = Math.floor((Date.now() - started) / 1e3);
|
|
795
|
+
process.stdout.write(
|
|
796
|
+
`\r${c.cyan(FRAMES[i++ % FRAMES.length])} ${c.dim(`${label}\u2026 ${secs}s`)}\x1B[K`
|
|
797
|
+
);
|
|
798
|
+
}, 80);
|
|
799
|
+
}
|
|
800
|
+
function stopSpinner() {
|
|
801
|
+
if (!timer) return;
|
|
802
|
+
clearInterval(timer);
|
|
803
|
+
timer = null;
|
|
804
|
+
process.stdout.write("\r\x1B[K\x1B[?25h");
|
|
805
|
+
}
|
|
806
|
+
process.on("exit", () => {
|
|
807
|
+
if (process.stdout.isTTY) process.stdout.write("\x1B[?25h");
|
|
808
|
+
});
|
|
809
|
+
function banner(info2) {
|
|
810
|
+
console.log(`
|
|
811
|
+
${c.bold(c.cyan("BroCodeX"))} ${c.dim("\xB7 sandboxed AI coding agent")}`);
|
|
812
|
+
console.log(c.dim(` ${info2.provider} / ${info2.model}`));
|
|
813
|
+
console.log(c.dim(` ${info2.cwd}`));
|
|
814
|
+
console.log(c.dim(" Type /help for commands\n"));
|
|
815
|
+
}
|
|
816
|
+
function help() {
|
|
817
|
+
const rows = [
|
|
818
|
+
["/chat", "talk only, no file access"],
|
|
819
|
+
["/agent", "let BroCodeX read, write and run commands in the sandbox"],
|
|
820
|
+
["/preview", "serve the sandbox copy on http://localhost"],
|
|
821
|
+
["/setup", "change provider, API key or model id"],
|
|
822
|
+
["/help", "show this list"],
|
|
823
|
+
["/exit", "review the changes, then apply or discard them"]
|
|
824
|
+
];
|
|
825
|
+
console.log("");
|
|
826
|
+
for (const [cmd, text] of rows) {
|
|
827
|
+
console.log(` ${c.cyan(cmd.padEnd(10))} ${c.dim(text)}`);
|
|
828
|
+
}
|
|
829
|
+
console.log("");
|
|
830
|
+
}
|
|
831
|
+
function prompt(mode) {
|
|
832
|
+
const label = mode === "agent" ? c.magenta("agent") : c.cyan("chat");
|
|
833
|
+
return `${label} ${c.dim("\u276F")} `;
|
|
834
|
+
}
|
|
835
|
+
var info = (msg) => console.log(c.dim(msg));
|
|
836
|
+
var success = (msg) => console.log(`${c.green("\u2713")} ${msg}`);
|
|
837
|
+
var warn = (msg) => console.log(`${c.yellow("!")} ${msg}`);
|
|
838
|
+
var error = (msg) => console.error(`${c.red("\u2717")} ${c.red(msg)}`);
|
|
839
|
+
function summarize(name, input4) {
|
|
840
|
+
const s = (v) => String(v ?? "");
|
|
841
|
+
switch (name) {
|
|
842
|
+
case "read_file":
|
|
843
|
+
case "list_dir":
|
|
844
|
+
return s(input4.path || ".");
|
|
845
|
+
case "write_file": {
|
|
846
|
+
const len = s(input4.content).length;
|
|
847
|
+
return `${s(input4.path)} ${c.gray(`(${len} chars${input4.overwrite ? ", overwrite" : ""})`)}`;
|
|
848
|
+
}
|
|
849
|
+
case "run_command": {
|
|
850
|
+
const args = Array.isArray(input4.args) ? input4.args.map(s) : [];
|
|
851
|
+
return [s(input4.executable), ...args].join(" ");
|
|
852
|
+
}
|
|
853
|
+
case "install_packages": {
|
|
854
|
+
const pk = Array.isArray(input4.packages) ? input4.packages.map(s) : [];
|
|
855
|
+
return pk.length ? pk.join(" ") : "(from package.json)";
|
|
856
|
+
}
|
|
857
|
+
case "apply_patch": {
|
|
858
|
+
const m = s(input4.diff).match(/^\+\+\+ b\/(.+)$/m);
|
|
859
|
+
return m?.[1] ?? "patch";
|
|
860
|
+
}
|
|
861
|
+
default:
|
|
862
|
+
return "";
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
function toolCall(name, input4) {
|
|
866
|
+
console.log(`
|
|
867
|
+
${c.blue("\u25CF")} ${c.bold(name)} ${c.dim(summarize(name, input4))}`);
|
|
868
|
+
}
|
|
869
|
+
function toolResult(result) {
|
|
870
|
+
const failed = /^(TOOL_ERROR|PATCH_REJECTED|Command not permitted)/.test(result.trim());
|
|
871
|
+
const lines = result.trim().split("\n");
|
|
872
|
+
let first = lines[0] ?? "";
|
|
873
|
+
if (first.length > 100) first = first.slice(0, 100) + "\u2026";
|
|
874
|
+
const more = lines.length > 1 ? c.gray(` (+${lines.length - 1} more lines)`) : "";
|
|
875
|
+
console.log(
|
|
876
|
+
failed ? ` ${c.red("\u2717")} ${c.red(first)}${more}` : ` ${c.green("\u2713")} ${c.dim(first)}${more}`
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
function summarizeDiff(diff) {
|
|
880
|
+
let files = 0, added = 0, removed = 0;
|
|
881
|
+
for (const line of diff.split("\n")) {
|
|
882
|
+
if (line.startsWith("diff --git")) files++;
|
|
883
|
+
else if (line.startsWith("+") && !line.startsWith("+++")) added++;
|
|
884
|
+
else if (line.startsWith("-") && !line.startsWith("---")) removed++;
|
|
885
|
+
}
|
|
886
|
+
return { files, added, removed };
|
|
887
|
+
}
|
|
888
|
+
function printDiff(diff) {
|
|
889
|
+
for (const line of diff.split("\n")) {
|
|
890
|
+
if (line.startsWith("diff --git")) console.log(c.bold(c.yellow(line)));
|
|
891
|
+
else if (line.startsWith("+++") || line.startsWith("---")) console.log(c.bold(line));
|
|
892
|
+
else if (line.startsWith("@@")) console.log(c.cyan(line));
|
|
893
|
+
else if (line.startsWith("+")) console.log(c.green(line));
|
|
894
|
+
else if (line.startsWith("-")) console.log(c.red(line));
|
|
895
|
+
else console.log(c.dim(line));
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// src/agent/agent.ts
|
|
900
|
+
var SYSTEM = `You are BroCodeX, an AI coding agent working inside a sandboxed copy of the user's project.
|
|
901
|
+
For general questions, answer directly without tools. For tasks that change the project, use tools.
|
|
902
|
+
|
|
903
|
+
Working method:
|
|
904
|
+
1. Call list_dir to see what exists. Read a file before you edit it.
|
|
905
|
+
2. For a new project, decide the file structure in one sentence, then create the files with write_file.
|
|
906
|
+
3. After writing, verify your work: list_dir to confirm the files exist, node --check on any .js file, and grep to confirm every file you link (css, js, images) actually exists.
|
|
907
|
+
4. Finish with a short summary: what you built and which file to open.
|
|
908
|
+
5. To change an existing file, the most reliable way is: read_file, then write_file with overwrite=true containing the complete updated file. Use apply_patch only for tiny edits to very large files, and never use the '*** Begin Patch' format.
|
|
909
|
+
Do not ask unnecessary questions; make sensible choices and mention them.
|
|
910
|
+
|
|
911
|
+
When building websites:
|
|
912
|
+
- Make plain static sites: index.html as the entry point, plus css/style.css and js/main.js when useful. For apps that need a framework, use install_packages first, then run_command with pnpm run build.
|
|
913
|
+
- Use semantic HTML, a viewport meta tag, responsive CSS (flexbox or grid, a mobile breakpoint), good contrast, alt text on images and labels on form fields.
|
|
914
|
+
- Use relative links only. Write complete, working files with real content, not placeholders.`;
|
|
915
|
+
var MAX_TOOL_ROUNDS = 40;
|
|
916
|
+
var Agent = class {
|
|
917
|
+
constructor(provider, tools = TOOLS, systemPrompt = SYSTEM, approveTool = async () => false) {
|
|
918
|
+
this.provider = provider;
|
|
919
|
+
this.tools = tools;
|
|
920
|
+
this.systemPrompt = systemPrompt;
|
|
921
|
+
this.approveTool = approveTool;
|
|
922
|
+
this.history.push({
|
|
923
|
+
role: "system",
|
|
924
|
+
content: this.systemPrompt
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
provider;
|
|
928
|
+
tools;
|
|
929
|
+
systemPrompt;
|
|
930
|
+
approveTool;
|
|
931
|
+
history = [];
|
|
932
|
+
async run(userText, mode = "chat") {
|
|
933
|
+
this.history.push({
|
|
934
|
+
role: "user",
|
|
935
|
+
content: userText
|
|
936
|
+
});
|
|
937
|
+
for (let i = 0; i < MAX_TOOL_ROUNDS; i++) {
|
|
938
|
+
const context = compactContext(this.history, {
|
|
939
|
+
maxTokens: 16e3,
|
|
940
|
+
keepRecentObservations: 4
|
|
941
|
+
});
|
|
942
|
+
if (context.wasCompacted) {
|
|
943
|
+
console.log(
|
|
944
|
+
`
|
|
945
|
+
[context] ${context.originalTokens} \u2192 ${context.compactedTokens} tokens | ${context.observationsMasked} observations masked
|
|
946
|
+
`
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
const availableTools = mode === "agent" ? this.tools : [];
|
|
950
|
+
startSpinner(mode === "agent" ? "Working" : "Thinking");
|
|
951
|
+
let response;
|
|
952
|
+
let spinnerActive = true;
|
|
953
|
+
try {
|
|
954
|
+
for await (const event of this.provider.stream(
|
|
955
|
+
context.messages,
|
|
956
|
+
availableTools
|
|
957
|
+
)) {
|
|
958
|
+
if (event.type === "text_delta") {
|
|
959
|
+
if (spinnerActive) {
|
|
960
|
+
stopSpinner();
|
|
961
|
+
spinnerActive = false;
|
|
962
|
+
}
|
|
963
|
+
process.stdout.write(event.delta);
|
|
964
|
+
}
|
|
965
|
+
if (event.type === "done") {
|
|
966
|
+
response = event.response;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
} finally {
|
|
970
|
+
if (spinnerActive) {
|
|
971
|
+
stopSpinner();
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
if (!response) {
|
|
975
|
+
throw new Error("Provider stream ended without a response");
|
|
976
|
+
}
|
|
977
|
+
if (response.content && response.toolCalls.length > 0) {
|
|
978
|
+
process.stdout.write("\n");
|
|
979
|
+
}
|
|
980
|
+
this.history.push({
|
|
981
|
+
role: "assistant",
|
|
982
|
+
content: response.content ?? "",
|
|
983
|
+
toolCalls: mode === "agent" ? response.toolCalls : []
|
|
984
|
+
});
|
|
985
|
+
if (response.toolCalls.length === 0) {
|
|
986
|
+
process.stdout.write("\n");
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
for (const call of response.toolCalls) {
|
|
990
|
+
toolCall(call.name, call.input);
|
|
991
|
+
const requiresApproval = call.name === "run_command" || call.name === "apply_patch";
|
|
992
|
+
let result;
|
|
993
|
+
if (requiresApproval) {
|
|
994
|
+
const approved = await this.approveTool(call.name, call.input);
|
|
995
|
+
if (!approved) {
|
|
996
|
+
result = "TOOL_ERROR: User denied this tool call.";
|
|
997
|
+
} else {
|
|
998
|
+
result = await runTool(call.name, call.input);
|
|
999
|
+
}
|
|
1000
|
+
} else {
|
|
1001
|
+
result = await runTool(call.name, call.input);
|
|
1002
|
+
}
|
|
1003
|
+
toolResult(result);
|
|
1004
|
+
this.history.push({
|
|
1005
|
+
role: "tool",
|
|
1006
|
+
toolCallId: call.id,
|
|
1007
|
+
toolName: call.name,
|
|
1008
|
+
content: result
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
throw new Error("Maximum tool-calling rounds exceeded");
|
|
1013
|
+
}
|
|
1014
|
+
clearHistory() {
|
|
1015
|
+
this.history = [
|
|
1016
|
+
{
|
|
1017
|
+
role: "system",
|
|
1018
|
+
content: this.systemPrompt
|
|
1019
|
+
}
|
|
1020
|
+
];
|
|
1021
|
+
}
|
|
1022
|
+
};
|
|
1023
|
+
|
|
1024
|
+
// src/providers/gemini.ts
|
|
1025
|
+
import { GoogleGenAI, Type } from "@google/genai";
|
|
1026
|
+
function normalizeFinishReason(reason) {
|
|
1027
|
+
switch (reason) {
|
|
1028
|
+
case "STOP":
|
|
1029
|
+
return "stop";
|
|
1030
|
+
case "MAX_TOKENS":
|
|
1031
|
+
return "length";
|
|
1032
|
+
case "SAFETY":
|
|
1033
|
+
case "RECITATION":
|
|
1034
|
+
case "BLOCKLIST":
|
|
1035
|
+
case "PROHIBITED_CONTENT":
|
|
1036
|
+
case "SPII":
|
|
1037
|
+
return "content_filter";
|
|
1038
|
+
default:
|
|
1039
|
+
return "unknown";
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
function mergeArgs(target, incoming) {
|
|
1043
|
+
for (const [key, value] of Object.entries(incoming)) {
|
|
1044
|
+
const existing = target[key];
|
|
1045
|
+
if (existing && typeof existing === "object" && !Array.isArray(existing) && value && typeof value === "object" && !Array.isArray(value)) {
|
|
1046
|
+
target[key] = mergeArgs(
|
|
1047
|
+
existing,
|
|
1048
|
+
value
|
|
1049
|
+
);
|
|
1050
|
+
} else {
|
|
1051
|
+
target[key] = value;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
return target;
|
|
1055
|
+
}
|
|
1056
|
+
function toGeminiSchema(schema) {
|
|
1057
|
+
const typeMap = {
|
|
1058
|
+
OBJECT: Type.OBJECT,
|
|
1059
|
+
STRING: Type.STRING,
|
|
1060
|
+
NUMBER: Type.NUMBER,
|
|
1061
|
+
INTEGER: Type.INTEGER,
|
|
1062
|
+
BOOLEAN: Type.BOOLEAN,
|
|
1063
|
+
ARRAY: Type.ARRAY
|
|
1064
|
+
};
|
|
1065
|
+
const type = String(schema.type ?? "OBJECT");
|
|
1066
|
+
const properties = schema.properties;
|
|
1067
|
+
const items = schema.items;
|
|
1068
|
+
return {
|
|
1069
|
+
type: typeMap[type] ?? Type.OBJECT,
|
|
1070
|
+
...typeof schema.description === "string" ? { description: schema.description } : {},
|
|
1071
|
+
...properties ? {
|
|
1072
|
+
properties: Object.fromEntries(
|
|
1073
|
+
Object.entries(properties).map(([key, value]) => [
|
|
1074
|
+
key,
|
|
1075
|
+
toGeminiSchema(value)
|
|
1076
|
+
])
|
|
1077
|
+
)
|
|
1078
|
+
} : {},
|
|
1079
|
+
...Array.isArray(schema.required) ? { required: schema.required } : {},
|
|
1080
|
+
...items ? { items: toGeminiSchema(items) } : {},
|
|
1081
|
+
...Array.isArray(schema.enum) ? { enum: schema.enum } : {}
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
function toGeminiTools(tools) {
|
|
1085
|
+
return tools.map((tool) => ({
|
|
1086
|
+
name: tool.name,
|
|
1087
|
+
description: tool.description,
|
|
1088
|
+
parameters: toGeminiSchema(tool.parameters)
|
|
1089
|
+
}));
|
|
1090
|
+
}
|
|
1091
|
+
function toGeminiMessages(messages) {
|
|
1092
|
+
const contents = [];
|
|
1093
|
+
for (let i = 0; i < messages.length; i++) {
|
|
1094
|
+
const message = messages[i];
|
|
1095
|
+
if (message.role === "system") {
|
|
1096
|
+
continue;
|
|
1097
|
+
}
|
|
1098
|
+
if (message.role === "user") {
|
|
1099
|
+
contents.push({
|
|
1100
|
+
role: "user",
|
|
1101
|
+
parts: [{ text: message.content }]
|
|
1102
|
+
});
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
if (message.role === "assistant") {
|
|
1106
|
+
const parts2 = [];
|
|
1107
|
+
if (message.content) {
|
|
1108
|
+
parts2.push({ text: message.content });
|
|
1109
|
+
}
|
|
1110
|
+
for (const call of message.toolCalls ?? []) {
|
|
1111
|
+
const geminiMetadata = call.providerMetadata?.gemini;
|
|
1112
|
+
parts2.push({
|
|
1113
|
+
functionCall: {
|
|
1114
|
+
...call.id ? { id: call.id } : {},
|
|
1115
|
+
name: call.name,
|
|
1116
|
+
args: call.input
|
|
1117
|
+
},
|
|
1118
|
+
...geminiMetadata?.thoughtSignature ? { thoughtSignature: geminiMetadata.thoughtSignature } : {}
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
contents.push({
|
|
1122
|
+
role: "model",
|
|
1123
|
+
parts: parts2
|
|
1124
|
+
});
|
|
1125
|
+
continue;
|
|
1126
|
+
}
|
|
1127
|
+
const parts = [];
|
|
1128
|
+
while (i < messages.length && messages[i].role === "tool") {
|
|
1129
|
+
const toolMessage = messages[i];
|
|
1130
|
+
if (toolMessage.role !== "tool") break;
|
|
1131
|
+
parts.push({
|
|
1132
|
+
functionResponse: {
|
|
1133
|
+
...toolMessage.toolCallId ? { id: toolMessage.toolCallId } : {},
|
|
1134
|
+
name: toolMessage.toolName,
|
|
1135
|
+
response: {
|
|
1136
|
+
result: toolMessage.content
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
i++;
|
|
1141
|
+
}
|
|
1142
|
+
i--;
|
|
1143
|
+
contents.push({
|
|
1144
|
+
role: "user",
|
|
1145
|
+
parts
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
return contents;
|
|
1149
|
+
}
|
|
1150
|
+
var GeminiProvider = class {
|
|
1151
|
+
client;
|
|
1152
|
+
model;
|
|
1153
|
+
constructor(apiKey, model) {
|
|
1154
|
+
this.client = new GoogleGenAI({ apiKey });
|
|
1155
|
+
this.model = model;
|
|
1156
|
+
}
|
|
1157
|
+
async *stream(messages, tools) {
|
|
1158
|
+
const systemInstruction = messages.filter((message) => message.role === "system").map((message) => message.content).join("\n");
|
|
1159
|
+
const contents = toGeminiMessages(messages);
|
|
1160
|
+
const functionDeclarations = toGeminiTools(tools);
|
|
1161
|
+
const stream = await this.client.models.generateContentStream({
|
|
1162
|
+
model: this.model,
|
|
1163
|
+
contents,
|
|
1164
|
+
config: {
|
|
1165
|
+
systemInstruction: systemInstruction || void 0,
|
|
1166
|
+
maxOutputTokens: 2048,
|
|
1167
|
+
tools: functionDeclarations.length ? [{ functionDeclarations }] : void 0
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
let content = "";
|
|
1171
|
+
let finishReason = "unknown";
|
|
1172
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
1173
|
+
for await (const chunk of stream) {
|
|
1174
|
+
const candidate = chunk.candidates?.[0];
|
|
1175
|
+
if (!candidate) continue;
|
|
1176
|
+
const parts = candidate.content?.parts ?? [];
|
|
1177
|
+
for (const part of parts) {
|
|
1178
|
+
if (part.text) {
|
|
1179
|
+
content += part.text;
|
|
1180
|
+
yield {
|
|
1181
|
+
type: "text_delta",
|
|
1182
|
+
delta: part.text
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
const functionParts = parts.filter(
|
|
1187
|
+
(part) => part.functionCall?.name
|
|
1188
|
+
);
|
|
1189
|
+
for (let i = 0; i < functionParts.length; i++) {
|
|
1190
|
+
const part = functionParts[i];
|
|
1191
|
+
const call = part.functionCall;
|
|
1192
|
+
let existing = toolCalls.get(i);
|
|
1193
|
+
if (!existing) {
|
|
1194
|
+
existing = {
|
|
1195
|
+
name: call.name,
|
|
1196
|
+
args: {}
|
|
1197
|
+
};
|
|
1198
|
+
toolCalls.set(i, existing);
|
|
1199
|
+
}
|
|
1200
|
+
if (call.id) {
|
|
1201
|
+
existing.id = call.id;
|
|
1202
|
+
}
|
|
1203
|
+
if (call.args) {
|
|
1204
|
+
mergeArgs(
|
|
1205
|
+
existing.args,
|
|
1206
|
+
call.args
|
|
1207
|
+
);
|
|
1208
|
+
}
|
|
1209
|
+
if (part.thoughtSignature) {
|
|
1210
|
+
existing.thoughtSignature = part.thoughtSignature;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
if (candidate.finishReason) {
|
|
1214
|
+
finishReason = normalizeFinishReason(
|
|
1215
|
+
String(candidate.finishReason)
|
|
1216
|
+
);
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
const completedToolCalls = Array.from(toolCalls.values()).map((call) => ({
|
|
1220
|
+
...call.id ? { id: call.id } : {},
|
|
1221
|
+
name: call.name,
|
|
1222
|
+
input: call.args,
|
|
1223
|
+
providerMetadata: {
|
|
1224
|
+
gemini: {
|
|
1225
|
+
...call.thoughtSignature ? {
|
|
1226
|
+
thoughtSignature: call.thoughtSignature
|
|
1227
|
+
} : {}
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}));
|
|
1231
|
+
yield {
|
|
1232
|
+
type: "done",
|
|
1233
|
+
response: {
|
|
1234
|
+
content: content || void 0,
|
|
1235
|
+
toolCalls: completedToolCalls,
|
|
1236
|
+
finishReason
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
};
|
|
1241
|
+
|
|
1242
|
+
// src/providers/openai.ts
|
|
1243
|
+
import OpenAI from "openai";
|
|
1244
|
+
function normalizeSchema(value) {
|
|
1245
|
+
if (Array.isArray(value)) {
|
|
1246
|
+
return value.map(normalizeSchema);
|
|
1247
|
+
}
|
|
1248
|
+
if (value !== null && typeof value === "object") {
|
|
1249
|
+
return Object.fromEntries(
|
|
1250
|
+
Object.entries(value).map(([key, nested]) => [
|
|
1251
|
+
key,
|
|
1252
|
+
key === "type" && typeof nested === "string" ? nested.toLowerCase() : normalizeSchema(nested)
|
|
1253
|
+
])
|
|
1254
|
+
);
|
|
1255
|
+
}
|
|
1256
|
+
return value;
|
|
1257
|
+
}
|
|
1258
|
+
function toOpenAITools(tools) {
|
|
1259
|
+
return tools.map((tool) => ({
|
|
1260
|
+
type: "function",
|
|
1261
|
+
function: {
|
|
1262
|
+
name: tool.name,
|
|
1263
|
+
description: tool.description,
|
|
1264
|
+
parameters: normalizeSchema(
|
|
1265
|
+
tool.parameters
|
|
1266
|
+
)
|
|
1267
|
+
}
|
|
1268
|
+
}));
|
|
1269
|
+
}
|
|
1270
|
+
function toOpenAIMessages(messages) {
|
|
1271
|
+
const result = [];
|
|
1272
|
+
const pendingIds = /* @__PURE__ */ new Map();
|
|
1273
|
+
let fallbackId = 0;
|
|
1274
|
+
for (const message of messages) {
|
|
1275
|
+
if (message.role === "system") {
|
|
1276
|
+
result.push({
|
|
1277
|
+
role: "system",
|
|
1278
|
+
content: message.content
|
|
1279
|
+
});
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
if (message.role === "user") {
|
|
1283
|
+
result.push({
|
|
1284
|
+
role: "user",
|
|
1285
|
+
content: message.content
|
|
1286
|
+
});
|
|
1287
|
+
continue;
|
|
1288
|
+
}
|
|
1289
|
+
if (message.role === "assistant") {
|
|
1290
|
+
const toolCalls = (message.toolCalls ?? []).map((call) => {
|
|
1291
|
+
const id = call.id ?? `brocodex_call_${fallbackId++}`;
|
|
1292
|
+
if (!call.id) {
|
|
1293
|
+
const queue = pendingIds.get(call.name) ?? [];
|
|
1294
|
+
queue.push(id);
|
|
1295
|
+
pendingIds.set(call.name, queue);
|
|
1296
|
+
}
|
|
1297
|
+
return {
|
|
1298
|
+
id,
|
|
1299
|
+
type: "function",
|
|
1300
|
+
function: {
|
|
1301
|
+
name: call.name,
|
|
1302
|
+
arguments: JSON.stringify(call.input)
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
});
|
|
1306
|
+
result.push({
|
|
1307
|
+
role: "assistant",
|
|
1308
|
+
content: message.content || null,
|
|
1309
|
+
...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
|
|
1310
|
+
});
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1313
|
+
if (message.role === "tool") {
|
|
1314
|
+
const id = message.toolCallId ?? pendingIds.get(message.toolName)?.shift();
|
|
1315
|
+
if (!id) {
|
|
1316
|
+
throw new Error(
|
|
1317
|
+
`Missing tool call ID for ${message.toolName}`
|
|
1318
|
+
);
|
|
1319
|
+
}
|
|
1320
|
+
result.push({
|
|
1321
|
+
role: "tool",
|
|
1322
|
+
tool_call_id: id,
|
|
1323
|
+
content: message.content
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
return result;
|
|
1328
|
+
}
|
|
1329
|
+
function normalizeFinishReason2(reason) {
|
|
1330
|
+
switch (reason) {
|
|
1331
|
+
case "stop":
|
|
1332
|
+
return "stop";
|
|
1333
|
+
case "length":
|
|
1334
|
+
return "length";
|
|
1335
|
+
case "tool_calls":
|
|
1336
|
+
case "function_call":
|
|
1337
|
+
return "tool_calls";
|
|
1338
|
+
case "content_filter":
|
|
1339
|
+
return "content_filter";
|
|
1340
|
+
default:
|
|
1341
|
+
return "unknown";
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
function parseArguments(argumentsString) {
|
|
1345
|
+
const parsed = JSON.parse(argumentsString);
|
|
1346
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1347
|
+
throw new Error("OpenAI returned invalid tool arguments");
|
|
1348
|
+
}
|
|
1349
|
+
return parsed;
|
|
1350
|
+
}
|
|
1351
|
+
var OpenAIProvider = class {
|
|
1352
|
+
client;
|
|
1353
|
+
model;
|
|
1354
|
+
constructor(apiKey, model, baseURL) {
|
|
1355
|
+
this.client = new OpenAI({
|
|
1356
|
+
apiKey,
|
|
1357
|
+
...baseURL ? { baseURL } : {}
|
|
1358
|
+
});
|
|
1359
|
+
this.model = model;
|
|
1360
|
+
}
|
|
1361
|
+
async *stream(messages, tools) {
|
|
1362
|
+
const stream = await this.client.chat.completions.create({
|
|
1363
|
+
model: this.model,
|
|
1364
|
+
messages: toOpenAIMessages(messages),
|
|
1365
|
+
max_completion_tokens: 2048,
|
|
1366
|
+
stream: true,
|
|
1367
|
+
...tools.length > 0 ? {
|
|
1368
|
+
tools: toOpenAITools(tools),
|
|
1369
|
+
tool_choice: "auto"
|
|
1370
|
+
} : {
|
|
1371
|
+
tool_choice: "none"
|
|
1372
|
+
}
|
|
1373
|
+
});
|
|
1374
|
+
let content = "";
|
|
1375
|
+
let finishReason = "unknown";
|
|
1376
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
1377
|
+
for await (const chunk of stream) {
|
|
1378
|
+
const choice = chunk.choices[0];
|
|
1379
|
+
if (!choice) continue;
|
|
1380
|
+
const delta = choice.delta;
|
|
1381
|
+
if (delta.content) {
|
|
1382
|
+
content += delta.content;
|
|
1383
|
+
yield {
|
|
1384
|
+
type: "text_delta",
|
|
1385
|
+
delta: delta.content
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
for (const toolDelta of delta.tool_calls ?? []) {
|
|
1389
|
+
const index = toolDelta.index;
|
|
1390
|
+
let call = toolCalls.get(index);
|
|
1391
|
+
if (!call) {
|
|
1392
|
+
call = {
|
|
1393
|
+
name: "",
|
|
1394
|
+
arguments: ""
|
|
1395
|
+
};
|
|
1396
|
+
toolCalls.set(index, call);
|
|
1397
|
+
}
|
|
1398
|
+
if (toolDelta.id) {
|
|
1399
|
+
call.id = toolDelta.id;
|
|
1400
|
+
}
|
|
1401
|
+
if (toolDelta.function?.name) {
|
|
1402
|
+
call.name += toolDelta.function.name;
|
|
1403
|
+
}
|
|
1404
|
+
if (toolDelta.function?.arguments) {
|
|
1405
|
+
call.arguments += toolDelta.function.arguments;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
if (choice.finish_reason) {
|
|
1409
|
+
finishReason = normalizeFinishReason2(
|
|
1410
|
+
choice.finish_reason
|
|
1411
|
+
);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
const completedToolCalls = Array.from(toolCalls.values()).map((call) => ({
|
|
1415
|
+
id: call.id,
|
|
1416
|
+
name: call.name,
|
|
1417
|
+
input: parseArguments(call.arguments)
|
|
1418
|
+
}));
|
|
1419
|
+
yield {
|
|
1420
|
+
type: "done",
|
|
1421
|
+
response: {
|
|
1422
|
+
content: content || void 0,
|
|
1423
|
+
toolCalls: completedToolCalls,
|
|
1424
|
+
finishReason
|
|
1425
|
+
}
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
};
|
|
1429
|
+
|
|
1430
|
+
// src/providers/groq.ts
|
|
1431
|
+
import Groq from "groq-sdk";
|
|
1432
|
+
function normalizeSchema2(value) {
|
|
1433
|
+
if (Array.isArray(value)) {
|
|
1434
|
+
return value.map(normalizeSchema2);
|
|
1435
|
+
}
|
|
1436
|
+
if (value !== null && typeof value === "object") {
|
|
1437
|
+
return Object.fromEntries(
|
|
1438
|
+
Object.entries(value).map(([key, nested]) => [
|
|
1439
|
+
key,
|
|
1440
|
+
key === "type" && typeof nested === "string" ? nested.toLowerCase() : normalizeSchema2(nested)
|
|
1441
|
+
])
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
return value;
|
|
1445
|
+
}
|
|
1446
|
+
function toGroqTools(tools) {
|
|
1447
|
+
return tools.map((tool) => ({
|
|
1448
|
+
type: "function",
|
|
1449
|
+
function: {
|
|
1450
|
+
name: tool.name,
|
|
1451
|
+
description: tool.description,
|
|
1452
|
+
parameters: normalizeSchema2(
|
|
1453
|
+
tool.parameters
|
|
1454
|
+
)
|
|
1455
|
+
}
|
|
1456
|
+
}));
|
|
1457
|
+
}
|
|
1458
|
+
function toGroqMessages(messages) {
|
|
1459
|
+
const result = [];
|
|
1460
|
+
const pendingIds = /* @__PURE__ */ new Map();
|
|
1461
|
+
let fallbackId = 0;
|
|
1462
|
+
for (const message of messages) {
|
|
1463
|
+
if (message.role === "system") {
|
|
1464
|
+
result.push({
|
|
1465
|
+
role: "system",
|
|
1466
|
+
content: message.content
|
|
1467
|
+
});
|
|
1468
|
+
continue;
|
|
1469
|
+
}
|
|
1470
|
+
if (message.role === "user") {
|
|
1471
|
+
result.push({
|
|
1472
|
+
role: "user",
|
|
1473
|
+
content: message.content
|
|
1474
|
+
});
|
|
1475
|
+
continue;
|
|
1476
|
+
}
|
|
1477
|
+
if (message.role === "assistant") {
|
|
1478
|
+
const toolCalls = (message.toolCalls ?? []).map((call) => {
|
|
1479
|
+
const id = call.id ?? `brocodex_call_${fallbackId++}`;
|
|
1480
|
+
if (!call.id) {
|
|
1481
|
+
const queue = pendingIds.get(call.name) ?? [];
|
|
1482
|
+
queue.push(id);
|
|
1483
|
+
pendingIds.set(call.name, queue);
|
|
1484
|
+
}
|
|
1485
|
+
return {
|
|
1486
|
+
id,
|
|
1487
|
+
type: "function",
|
|
1488
|
+
function: {
|
|
1489
|
+
name: call.name,
|
|
1490
|
+
arguments: JSON.stringify(call.input)
|
|
1491
|
+
}
|
|
1492
|
+
};
|
|
1493
|
+
});
|
|
1494
|
+
result.push({
|
|
1495
|
+
role: "assistant",
|
|
1496
|
+
content: message.content || null,
|
|
1497
|
+
...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
|
|
1498
|
+
});
|
|
1499
|
+
continue;
|
|
1500
|
+
}
|
|
1501
|
+
if (message.role === "tool") {
|
|
1502
|
+
const id = message.toolCallId ?? pendingIds.get(message.toolName)?.shift();
|
|
1503
|
+
if (!id) {
|
|
1504
|
+
throw new Error(
|
|
1505
|
+
`Missing tool call ID for ${message.toolName}`
|
|
1506
|
+
);
|
|
1507
|
+
}
|
|
1508
|
+
result.push({
|
|
1509
|
+
role: "tool",
|
|
1510
|
+
tool_call_id: id,
|
|
1511
|
+
content: message.content
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
return result;
|
|
1516
|
+
}
|
|
1517
|
+
function normalizeFinishReason3(reason) {
|
|
1518
|
+
switch (reason) {
|
|
1519
|
+
case "stop":
|
|
1520
|
+
return "stop";
|
|
1521
|
+
case "length":
|
|
1522
|
+
return "length";
|
|
1523
|
+
case "tool_calls":
|
|
1524
|
+
case "function_call":
|
|
1525
|
+
return "tool_calls";
|
|
1526
|
+
case "content_filter":
|
|
1527
|
+
return "content_filter";
|
|
1528
|
+
default:
|
|
1529
|
+
return "unknown";
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
function parseArguments2(argumentsString) {
|
|
1533
|
+
const parsed = JSON.parse(argumentsString);
|
|
1534
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1535
|
+
throw new Error("Groq returned invalid tool arguments");
|
|
1536
|
+
}
|
|
1537
|
+
return parsed;
|
|
1538
|
+
}
|
|
1539
|
+
var GroqProvider = class {
|
|
1540
|
+
client;
|
|
1541
|
+
model;
|
|
1542
|
+
constructor(apiKey, model) {
|
|
1543
|
+
this.client = new Groq({ apiKey });
|
|
1544
|
+
this.model = model;
|
|
1545
|
+
}
|
|
1546
|
+
async *stream(messages, tools) {
|
|
1547
|
+
const stream = await this.client.chat.completions.create({
|
|
1548
|
+
model: this.model,
|
|
1549
|
+
messages: toGroqMessages(messages),
|
|
1550
|
+
max_completion_tokens: 2048,
|
|
1551
|
+
stream: true,
|
|
1552
|
+
...tools.length > 0 ? {
|
|
1553
|
+
tools: toGroqTools(tools),
|
|
1554
|
+
tool_choice: "auto"
|
|
1555
|
+
} : {
|
|
1556
|
+
tool_choice: "none"
|
|
1557
|
+
}
|
|
1558
|
+
});
|
|
1559
|
+
let content = "";
|
|
1560
|
+
let finishReason = "unknown";
|
|
1561
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
1562
|
+
for await (const chunk of stream) {
|
|
1563
|
+
const choice = chunk.choices[0];
|
|
1564
|
+
if (!choice) continue;
|
|
1565
|
+
const delta = choice.delta;
|
|
1566
|
+
if (delta.content) {
|
|
1567
|
+
content += delta.content;
|
|
1568
|
+
yield {
|
|
1569
|
+
type: "text_delta",
|
|
1570
|
+
delta: delta.content
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
for (const toolDelta of delta.tool_calls ?? []) {
|
|
1574
|
+
const index = toolDelta.index;
|
|
1575
|
+
let call = toolCalls.get(index);
|
|
1576
|
+
if (!call) {
|
|
1577
|
+
call = {
|
|
1578
|
+
name: "",
|
|
1579
|
+
arguments: ""
|
|
1580
|
+
};
|
|
1581
|
+
toolCalls.set(index, call);
|
|
1582
|
+
}
|
|
1583
|
+
if (toolDelta.id) {
|
|
1584
|
+
call.id = toolDelta.id;
|
|
1585
|
+
}
|
|
1586
|
+
if (toolDelta.function?.name) {
|
|
1587
|
+
call.name += toolDelta.function.name;
|
|
1588
|
+
}
|
|
1589
|
+
if (toolDelta.function?.arguments) {
|
|
1590
|
+
call.arguments += toolDelta.function.arguments;
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
if (choice.finish_reason) {
|
|
1594
|
+
finishReason = normalizeFinishReason3(
|
|
1595
|
+
choice.finish_reason
|
|
1596
|
+
);
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
const completedToolCalls = Array.from(toolCalls.values()).map((call) => ({
|
|
1600
|
+
id: call.id,
|
|
1601
|
+
name: call.name,
|
|
1602
|
+
input: parseArguments2(call.arguments)
|
|
1603
|
+
}));
|
|
1604
|
+
yield {
|
|
1605
|
+
type: "done",
|
|
1606
|
+
response: {
|
|
1607
|
+
content: content || void 0,
|
|
1608
|
+
toolCalls: completedToolCalls,
|
|
1609
|
+
finishReason
|
|
1610
|
+
}
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
};
|
|
1614
|
+
|
|
1615
|
+
// src/providers/openrouter.ts
|
|
1616
|
+
var OpenRouterProvider = class extends OpenAIProvider {
|
|
1617
|
+
constructor(apiKey, model) {
|
|
1618
|
+
super(
|
|
1619
|
+
apiKey,
|
|
1620
|
+
model,
|
|
1621
|
+
"https://openrouter.ai/api/v1"
|
|
1622
|
+
);
|
|
1623
|
+
}
|
|
1624
|
+
};
|
|
1625
|
+
|
|
1626
|
+
// src/providers/factory.ts
|
|
1627
|
+
function createProvider(config) {
|
|
1628
|
+
switch (config.provider) {
|
|
1629
|
+
case "gemini":
|
|
1630
|
+
return new GeminiProvider(config.apiKey, config.model);
|
|
1631
|
+
case "openai":
|
|
1632
|
+
return new OpenAIProvider(config.apiKey, config.model);
|
|
1633
|
+
case "groq":
|
|
1634
|
+
return new GroqProvider(config.apiKey, config.model);
|
|
1635
|
+
case "openrouter":
|
|
1636
|
+
return new OpenRouterProvider(config.apiKey, config.model);
|
|
1637
|
+
default:
|
|
1638
|
+
throw new Error(`Unsupported provider: ${String(config.provider)}`);
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// src/config.ts
|
|
1643
|
+
import fs4 from "node:fs";
|
|
1644
|
+
import os from "node:os";
|
|
1645
|
+
import path4 from "node:path";
|
|
1646
|
+
var PROVIDERS = [
|
|
1647
|
+
{
|
|
1648
|
+
id: "gemini",
|
|
1649
|
+
label: "Google Gemini",
|
|
1650
|
+
keyUrl: "https://aistudio.google.com/apikey",
|
|
1651
|
+
modelExample: "gemini-2.5-flash"
|
|
1652
|
+
},
|
|
1653
|
+
{
|
|
1654
|
+
id: "openai",
|
|
1655
|
+
label: "OpenAI",
|
|
1656
|
+
keyUrl: "https://platform.openai.com/api-keys",
|
|
1657
|
+
modelExample: "gpt-4o-mini"
|
|
1658
|
+
},
|
|
1659
|
+
{
|
|
1660
|
+
id: "groq",
|
|
1661
|
+
label: "Groq",
|
|
1662
|
+
keyUrl: "https://console.groq.com/keys",
|
|
1663
|
+
modelExample: "llama-3.3-70b-versatile"
|
|
1664
|
+
},
|
|
1665
|
+
{
|
|
1666
|
+
id: "openrouter",
|
|
1667
|
+
label: "OpenRouter",
|
|
1668
|
+
keyUrl: "https://openrouter.ai/keys",
|
|
1669
|
+
modelExample: "vendor/model-name (copy it from openrouter.ai/models)"
|
|
1670
|
+
}
|
|
1671
|
+
];
|
|
1672
|
+
var providerInfo = (id) => PROVIDERS.find((p) => p.id === id);
|
|
1673
|
+
function configFilePath() {
|
|
1674
|
+
const dir = process.env.BROCODEX_CONFIG_DIR ?? path4.join(os.homedir(), ".brocodex");
|
|
1675
|
+
return path4.join(dir, "config.json");
|
|
1676
|
+
}
|
|
1677
|
+
function maskKey(key) {
|
|
1678
|
+
return key.length <= 8 ? "\u2022\u2022\u2022\u2022" : `\u2022\u2022\u2022\u2022${key.slice(-4)}`;
|
|
1679
|
+
}
|
|
1680
|
+
function loadSavedConfig() {
|
|
1681
|
+
try {
|
|
1682
|
+
const raw = JSON.parse(fs4.readFileSync(configFilePath(), "utf8"));
|
|
1683
|
+
if (raw && providerInfo(String(raw.provider)) && typeof raw.apiKey === "string" && raw.apiKey && typeof raw.model === "string" && raw.model) {
|
|
1684
|
+
return { provider: raw.provider, apiKey: raw.apiKey, model: raw.model };
|
|
1685
|
+
}
|
|
1686
|
+
} catch {
|
|
1687
|
+
}
|
|
1688
|
+
return null;
|
|
1689
|
+
}
|
|
1690
|
+
function loadConfig() {
|
|
1691
|
+
const saved = loadSavedConfig();
|
|
1692
|
+
return saved ? { config: saved, source: "saved" } : null;
|
|
1693
|
+
}
|
|
1694
|
+
function saveConfig(config) {
|
|
1695
|
+
const file = configFilePath();
|
|
1696
|
+
fs4.mkdirSync(path4.dirname(file), { recursive: true, mode: 448 });
|
|
1697
|
+
fs4.writeFileSync(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
1698
|
+
try {
|
|
1699
|
+
fs4.chmodSync(file, 384);
|
|
1700
|
+
} catch {
|
|
1701
|
+
}
|
|
1702
|
+
return file;
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
// src/wizard.ts
|
|
1706
|
+
import readline from "node:readline/promises";
|
|
1707
|
+
import { stdin as input, stdout as output } from "node:process";
|
|
1708
|
+
var WizardCancelled = class extends Error {
|
|
1709
|
+
};
|
|
1710
|
+
var TEST_TIMEOUT_MS = 3e4;
|
|
1711
|
+
async function ask(question) {
|
|
1712
|
+
const rl = readline.createInterface({ input, output });
|
|
1713
|
+
const abort = new AbortController();
|
|
1714
|
+
rl.once("SIGINT", () => abort.abort());
|
|
1715
|
+
try {
|
|
1716
|
+
return (await rl.question(question, { signal: abort.signal })).trim();
|
|
1717
|
+
} catch (err) {
|
|
1718
|
+
if (abort.signal.aborted) throw new WizardCancelled();
|
|
1719
|
+
throw err;
|
|
1720
|
+
} finally {
|
|
1721
|
+
rl.close();
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
function askSecret(question) {
|
|
1725
|
+
return new Promise((resolve2, reject4) => {
|
|
1726
|
+
let buf = "";
|
|
1727
|
+
output.write(question);
|
|
1728
|
+
input.setRawMode(true);
|
|
1729
|
+
input.setEncoding("utf8");
|
|
1730
|
+
input.resume();
|
|
1731
|
+
const finish = (err) => {
|
|
1732
|
+
input.off("data", onData);
|
|
1733
|
+
input.setRawMode(false);
|
|
1734
|
+
input.pause();
|
|
1735
|
+
output.write("\n");
|
|
1736
|
+
if (err) reject4(err);
|
|
1737
|
+
else resolve2(buf.trim());
|
|
1738
|
+
};
|
|
1739
|
+
const onData = (chunk) => {
|
|
1740
|
+
if (chunk.startsWith("\x1B")) return;
|
|
1741
|
+
for (const ch of chunk) {
|
|
1742
|
+
if (ch === "\r" || ch === "\n") return finish();
|
|
1743
|
+
if (ch === "" || ch === "") return finish(new WizardCancelled());
|
|
1744
|
+
if (ch === "\x7F" || ch === "\b") {
|
|
1745
|
+
if (buf) {
|
|
1746
|
+
buf = buf.slice(0, -1);
|
|
1747
|
+
output.write("\b \b");
|
|
1748
|
+
}
|
|
1749
|
+
continue;
|
|
1750
|
+
}
|
|
1751
|
+
if (ch < " ") continue;
|
|
1752
|
+
buf += ch;
|
|
1753
|
+
output.write("\u2022");
|
|
1754
|
+
}
|
|
1755
|
+
};
|
|
1756
|
+
input.on("data", onData);
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
async function chooseProvider(current) {
|
|
1760
|
+
console.log(c.bold("\n1) Provider"));
|
|
1761
|
+
PROVIDERS.forEach((p, i) => {
|
|
1762
|
+
const mark = p.id === current ? c.dim(" (current)") : "";
|
|
1763
|
+
console.log(` ${c.cyan(String(i + 1))} ${p.label}${mark}`);
|
|
1764
|
+
});
|
|
1765
|
+
const defaultIndex = PROVIDERS.findIndex((p) => p.id === current);
|
|
1766
|
+
const hint = defaultIndex >= 0 ? c.dim(` [${defaultIndex + 1}]`) : "";
|
|
1767
|
+
while (true) {
|
|
1768
|
+
const answer = (await ask(`Choose 1-${PROVIDERS.length}${hint}: `)).toLowerCase();
|
|
1769
|
+
if (!answer && defaultIndex >= 0) return PROVIDERS[defaultIndex];
|
|
1770
|
+
const byNumber = PROVIDERS[Number(answer) - 1];
|
|
1771
|
+
const byName = PROVIDERS.find(
|
|
1772
|
+
(p) => p.id === answer || p.label.toLowerCase() === answer
|
|
1773
|
+
);
|
|
1774
|
+
const picked = byNumber ?? byName;
|
|
1775
|
+
if (picked) return picked;
|
|
1776
|
+
warn(`Enter a number from 1 to ${PROVIDERS.length}.`);
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
async function promptKey(provider, existing) {
|
|
1780
|
+
console.log(c.bold(`
|
|
1781
|
+
2) ${provider.label} API key`));
|
|
1782
|
+
console.log(c.dim(` Create one at ${provider.keyUrl}`));
|
|
1783
|
+
console.log(c.dim(" Your typing is hidden. Paste it and press Enter."));
|
|
1784
|
+
const keep = existing ? c.dim(` (Enter keeps ${maskKey(existing)})`) : "";
|
|
1785
|
+
while (true) {
|
|
1786
|
+
const key = (await askSecret(`API key${keep}: `)).replace(/^["']+|["']+$/g, "");
|
|
1787
|
+
if (!key && existing) return existing;
|
|
1788
|
+
if (!key) {
|
|
1789
|
+
warn("The API key can't be empty.");
|
|
1790
|
+
continue;
|
|
1791
|
+
}
|
|
1792
|
+
if (/\s/.test(key)) {
|
|
1793
|
+
warn("That contains spaces. Paste just the key.");
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
success(`Key received ${c.dim(`(ends in ${key.slice(-4)})`)}`);
|
|
1797
|
+
return key;
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
async function promptModel(provider, existing) {
|
|
1801
|
+
console.log(c.bold("\n3) Model ID"));
|
|
1802
|
+
console.log(c.dim(" Type the exact id your provider lists, character for character."));
|
|
1803
|
+
console.log(c.dim(` Format example: ${provider.modelExample}`));
|
|
1804
|
+
const keep = existing ? c.dim(` [${existing}]`) : "";
|
|
1805
|
+
while (true) {
|
|
1806
|
+
const model = (await ask(`Model ID${keep}: `)).replace(/^["']+|["']+$/g, "");
|
|
1807
|
+
if (!model && existing) return existing;
|
|
1808
|
+
if (!model) {
|
|
1809
|
+
warn("The model id can't be empty.");
|
|
1810
|
+
continue;
|
|
1811
|
+
}
|
|
1812
|
+
if (/\s/.test(model)) {
|
|
1813
|
+
warn("Model ids don't contain spaces. Check what you typed.");
|
|
1814
|
+
continue;
|
|
1815
|
+
}
|
|
1816
|
+
return model;
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
async function testConnection(config) {
|
|
1820
|
+
startSpinner("Testing connection");
|
|
1821
|
+
let timer2;
|
|
1822
|
+
try {
|
|
1823
|
+
const provider = createProvider(config);
|
|
1824
|
+
const request = (async () => {
|
|
1825
|
+
for await (const event of provider.stream(
|
|
1826
|
+
[{ role: "user", content: "Reply with the single word: ok" }],
|
|
1827
|
+
[]
|
|
1828
|
+
)) {
|
|
1829
|
+
if (event.type === "text_delta" || event.type === "done") break;
|
|
1830
|
+
}
|
|
1831
|
+
})();
|
|
1832
|
+
request.catch(() => {
|
|
1833
|
+
});
|
|
1834
|
+
const timeout = new Promise((_, reject4) => {
|
|
1835
|
+
timer2 = setTimeout(
|
|
1836
|
+
() => reject4(new Error(`No response after ${TEST_TIMEOUT_MS / 1e3}s`)),
|
|
1837
|
+
TEST_TIMEOUT_MS
|
|
1838
|
+
);
|
|
1839
|
+
});
|
|
1840
|
+
await Promise.race([request, timeout]);
|
|
1841
|
+
return { ok: true };
|
|
1842
|
+
} catch (err) {
|
|
1843
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
1844
|
+
return { ok: false, message: raw.split(config.apiKey).join("\u2022\u2022\u2022\u2022") };
|
|
1845
|
+
} finally {
|
|
1846
|
+
clearTimeout(timer2);
|
|
1847
|
+
stopSpinner();
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
function save(config) {
|
|
1851
|
+
const file = saveConfig(config);
|
|
1852
|
+
const label = providerInfo(config.provider)?.label ?? config.provider;
|
|
1853
|
+
success(`Saved ${label} / ${config.model}`);
|
|
1854
|
+
info(` ${file}`);
|
|
1855
|
+
}
|
|
1856
|
+
async function runSetupWizard(existing) {
|
|
1857
|
+
if (!input.isTTY || !output.isTTY) {
|
|
1858
|
+
throw new Error(
|
|
1859
|
+
"Setup needs an interactive terminal. Run `brocodex --setup` in a normal terminal."
|
|
1860
|
+
);
|
|
1861
|
+
}
|
|
1862
|
+
console.log(`
|
|
1863
|
+
${c.bold(c.cyan("BroCodeX setup"))}`);
|
|
1864
|
+
console.log(c.dim(" Pick a provider, paste your API key and enter the model id. Ctrl+C cancels."));
|
|
1865
|
+
let draft = existing ? { ...existing } : {};
|
|
1866
|
+
try {
|
|
1867
|
+
while (true) {
|
|
1868
|
+
const provider = await chooseProvider(draft.provider);
|
|
1869
|
+
const same = draft.provider === provider.id;
|
|
1870
|
+
const apiKey = await promptKey(provider, same ? draft.apiKey : void 0);
|
|
1871
|
+
const model = await promptModel(provider, same ? draft.model : void 0);
|
|
1872
|
+
const config = { provider: provider.id, apiKey, model };
|
|
1873
|
+
draft = config;
|
|
1874
|
+
const result = await testConnection(config);
|
|
1875
|
+
if (result.ok) {
|
|
1876
|
+
success("Connection works.");
|
|
1877
|
+
save(config);
|
|
1878
|
+
console.log("");
|
|
1879
|
+
return config;
|
|
1880
|
+
}
|
|
1881
|
+
error(`Test failed: ${result.message}`);
|
|
1882
|
+
while (true) {
|
|
1883
|
+
const choice = (await ask("[r]etry, [s]ave anyway, or [c]ancel? ")).toLowerCase();
|
|
1884
|
+
if (choice.startsWith("s")) {
|
|
1885
|
+
save(config);
|
|
1886
|
+
console.log("");
|
|
1887
|
+
return config;
|
|
1888
|
+
}
|
|
1889
|
+
if (choice.startsWith("c")) throw new WizardCancelled();
|
|
1890
|
+
if (choice.startsWith("r")) break;
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
} catch (err) {
|
|
1894
|
+
if (err instanceof WizardCancelled) {
|
|
1895
|
+
console.log("");
|
|
1896
|
+
info("Setup cancelled. Nothing was changed.\n");
|
|
1897
|
+
return null;
|
|
1898
|
+
}
|
|
1899
|
+
throw err;
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
// src/docker-setup.ts
|
|
1904
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
1905
|
+
import { copyFileSync, existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
1906
|
+
import { tmpdir } from "node:os";
|
|
1907
|
+
import { join } from "node:path";
|
|
1908
|
+
import { fileURLToPath } from "node:url";
|
|
1909
|
+
import readline2 from "node:readline/promises";
|
|
1910
|
+
import { stdin as input2, stdout as output2 } from "node:process";
|
|
1911
|
+
|
|
1912
|
+
// src/sandbox/docker-client.ts
|
|
1913
|
+
import { execFile } from "node:child_process";
|
|
1914
|
+
function docker(args, timeoutMs = 12e4) {
|
|
1915
|
+
return new Promise((resolve2) => {
|
|
1916
|
+
execFile(
|
|
1917
|
+
"docker",
|
|
1918
|
+
args,
|
|
1919
|
+
{ timeout: timeoutMs, maxBuffer: 10 * 1024 * 1024 },
|
|
1920
|
+
(err, stdout, stderr) => {
|
|
1921
|
+
const e = err;
|
|
1922
|
+
resolve2({
|
|
1923
|
+
exitCode: e ? typeof e.code === "number" ? e.code : 1 : 0,
|
|
1924
|
+
stdout,
|
|
1925
|
+
stderr,
|
|
1926
|
+
timedOut: !!e?.killed
|
|
1927
|
+
});
|
|
1928
|
+
}
|
|
1929
|
+
);
|
|
1930
|
+
});
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
// src/docker-setup.ts
|
|
1934
|
+
var SANDBOX_IMAGE = "agent-sandbox";
|
|
1935
|
+
var DOCKERFILE = fileURLToPath(new URL("../Dockerfile", import.meta.url));
|
|
1936
|
+
async function confirm(question) {
|
|
1937
|
+
const rl = readline2.createInterface({ input: input2, output: output2 });
|
|
1938
|
+
const abort = new AbortController();
|
|
1939
|
+
rl.once("SIGINT", () => abort.abort());
|
|
1940
|
+
try {
|
|
1941
|
+
const answer = (await rl.question(question, { signal: abort.signal })).trim().toLowerCase();
|
|
1942
|
+
return answer === "" || answer.startsWith("y");
|
|
1943
|
+
} catch {
|
|
1944
|
+
return false;
|
|
1945
|
+
} finally {
|
|
1946
|
+
rl.close();
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
function buildImage() {
|
|
1950
|
+
if (!existsSync(DOCKERFILE)) {
|
|
1951
|
+
throw new Error(`Dockerfile not found at ${DOCKERFILE}`);
|
|
1952
|
+
}
|
|
1953
|
+
const context = mkdtempSync(join(tmpdir(), "brocodex-image-"));
|
|
1954
|
+
try {
|
|
1955
|
+
copyFileSync(DOCKERFILE, join(context, "Dockerfile"));
|
|
1956
|
+
const result = spawnSync("docker", ["build", "-t", SANDBOX_IMAGE, context], {
|
|
1957
|
+
stdio: "inherit"
|
|
1958
|
+
});
|
|
1959
|
+
if (result.status !== 0) {
|
|
1960
|
+
throw new Error("Building the sandbox image failed (see the Docker output above).");
|
|
1961
|
+
}
|
|
1962
|
+
} finally {
|
|
1963
|
+
rmSync(context, { recursive: true, force: true });
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
async function prepareSandbox(opts = {}) {
|
|
1967
|
+
try {
|
|
1968
|
+
execFileSync("git", ["--version"], { stdio: "ignore" });
|
|
1969
|
+
} catch {
|
|
1970
|
+
throw new Error(
|
|
1971
|
+
"git is required (BroCodeX uses it to work out what the agent changed). Install git and try again."
|
|
1972
|
+
);
|
|
1973
|
+
}
|
|
1974
|
+
const info2 = await docker(["info", "--format", "{{.ServerVersion}}"], 15e3);
|
|
1975
|
+
if (info2.exitCode !== 0) {
|
|
1976
|
+
throw new Error(
|
|
1977
|
+
"Docker isn't available. Install Docker and make sure it is running (on macOS/Windows, start Docker Desktop), then try again."
|
|
1978
|
+
);
|
|
1979
|
+
}
|
|
1980
|
+
const present = (await docker(["image", "inspect", SANDBOX_IMAGE], 15e3)).exitCode === 0;
|
|
1981
|
+
if (present && !opts.rebuild) return;
|
|
1982
|
+
if (!opts.rebuild) {
|
|
1983
|
+
if (!input2.isTTY) {
|
|
1984
|
+
throw new Error(
|
|
1985
|
+
`Sandbox image "${SANDBOX_IMAGE}" not found. Run \`brocodex --rebuild-image\` once to create it.`
|
|
1986
|
+
);
|
|
1987
|
+
}
|
|
1988
|
+
info(`
|
|
1989
|
+
First run: the sandbox image "${SANDBOX_IMAGE}" doesn't exist yet.`);
|
|
1990
|
+
info("Building it takes a minute or two and only happens once.");
|
|
1991
|
+
if (!await confirm(`${c.bold("Build it now?")} ${c.dim("[Y/n]")} `)) {
|
|
1992
|
+
throw new Error("Can't continue without the sandbox image.");
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
info(`Building ${SANDBOX_IMAGE}\u2026
|
|
1996
|
+
`);
|
|
1997
|
+
buildImage();
|
|
1998
|
+
success("Sandbox image ready.\n");
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
// src/sandbox/sandbox-manager.ts
|
|
2002
|
+
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
2003
|
+
import { cpSync, mkdtempSync as mkdtempSync2, rmSync as rmSync2, appendFileSync } from "node:fs";
|
|
2004
|
+
import { tmpdir as tmpdir2 } from "node:os";
|
|
2005
|
+
import { basename, join as join2, resolve } from "node:path";
|
|
2006
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
2007
|
+
var git = (args, cwd, input4) => execFileSync2(
|
|
2008
|
+
"git",
|
|
2009
|
+
["-c", "user.name=agent", "-c", "user.email=agent@local", ...args],
|
|
2010
|
+
{ cwd, input: input4, maxBuffer: 50 * 1024 * 1024, stdio: "pipe" }
|
|
2011
|
+
// pipe stderr so git's hints don't leak into the terminal
|
|
2012
|
+
).toString();
|
|
2013
|
+
var SKIP = [".git", "node_modules", ".env", ".env.local", ".env.production", ".env.development", ".env.test"];
|
|
2014
|
+
var SandboxManager = class {
|
|
2015
|
+
projectPath;
|
|
2016
|
+
image;
|
|
2017
|
+
network;
|
|
2018
|
+
tempDir = "";
|
|
2019
|
+
container = `agent-${randomUUID2().slice(0, 8)}`;
|
|
2020
|
+
constructor(opts) {
|
|
2021
|
+
this.projectPath = resolve(opts.projectPath);
|
|
2022
|
+
this.image = opts.image ?? "agent-sandbox";
|
|
2023
|
+
this.network = opts.network ?? false;
|
|
2024
|
+
}
|
|
2025
|
+
/** Folder on your computer that holds the agent's temporary copy */
|
|
2026
|
+
get workDir() {
|
|
2027
|
+
return this.tempDir;
|
|
2028
|
+
}
|
|
2029
|
+
/** 1. Copy project to a temp folder and start the container on it */
|
|
2030
|
+
async start() {
|
|
2031
|
+
this.tempDir = mkdtempSync2(join2(tmpdir2(), "agent-"));
|
|
2032
|
+
cpSync(this.projectPath, this.tempDir, {
|
|
2033
|
+
recursive: true,
|
|
2034
|
+
filter: (src) => !SKIP.includes(basename(src))
|
|
2035
|
+
});
|
|
2036
|
+
git(["init"], this.tempDir);
|
|
2037
|
+
appendFileSync(join2(this.tempDir, ".git", "info", "exclude"), "node_modules\n");
|
|
2038
|
+
git(["add", "-A"], this.tempDir);
|
|
2039
|
+
git(["commit", "-m", "baseline", "--allow-empty"], this.tempDir);
|
|
2040
|
+
const args = [
|
|
2041
|
+
"run",
|
|
2042
|
+
"-d",
|
|
2043
|
+
"--rm",
|
|
2044
|
+
"--name",
|
|
2045
|
+
this.container,
|
|
2046
|
+
"--memory=2g",
|
|
2047
|
+
"--cpus=2",
|
|
2048
|
+
"--pids-limit=256",
|
|
2049
|
+
"--cap-drop=ALL",
|
|
2050
|
+
"--security-opt=no-new-privileges",
|
|
2051
|
+
"-e",
|
|
2052
|
+
"HOME=/tmp",
|
|
2053
|
+
"-v",
|
|
2054
|
+
`${this.tempDir}:/workspace`
|
|
2055
|
+
];
|
|
2056
|
+
if (process.platform === "linux" && process.getuid) {
|
|
2057
|
+
args.push("--user", `${process.getuid()}:${process.getgid()}`);
|
|
2058
|
+
}
|
|
2059
|
+
args.push(this.image, "sleep", "infinity");
|
|
2060
|
+
const r = await docker(args);
|
|
2061
|
+
if (r.exitCode !== 0) {
|
|
2062
|
+
rmSync2(this.tempDir, { recursive: true, force: true });
|
|
2063
|
+
throw new Error(
|
|
2064
|
+
`Failed to start container (is Docker running? try "brocodex --rebuild-image")
|
|
2065
|
+
${r.stderr}`
|
|
2066
|
+
);
|
|
2067
|
+
}
|
|
2068
|
+
if (!this.network) {
|
|
2069
|
+
await docker(["network", "disconnect", "bridge", this.container]);
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
/** 2a. Run a shell command inside the box */
|
|
2073
|
+
async exec(command, timeoutSec = 60) {
|
|
2074
|
+
return docker(
|
|
2075
|
+
[
|
|
2076
|
+
"exec",
|
|
2077
|
+
"-w",
|
|
2078
|
+
"/workspace",
|
|
2079
|
+
this.container,
|
|
2080
|
+
"timeout",
|
|
2081
|
+
"-s",
|
|
2082
|
+
"KILL",
|
|
2083
|
+
String(timeoutSec),
|
|
2084
|
+
"bash",
|
|
2085
|
+
"-lc",
|
|
2086
|
+
command
|
|
2087
|
+
],
|
|
2088
|
+
(timeoutSec + 10) * 1e3
|
|
2089
|
+
);
|
|
2090
|
+
}
|
|
2091
|
+
/** 2b. Run a program with arguments directly (no shell) */
|
|
2092
|
+
async execArgs(executable, args, timeoutSec = 60) {
|
|
2093
|
+
return docker(
|
|
2094
|
+
[
|
|
2095
|
+
"exec",
|
|
2096
|
+
"-w",
|
|
2097
|
+
"/workspace",
|
|
2098
|
+
this.container,
|
|
2099
|
+
"timeout",
|
|
2100
|
+
"-s",
|
|
2101
|
+
"KILL",
|
|
2102
|
+
String(timeoutSec),
|
|
2103
|
+
executable,
|
|
2104
|
+
...args
|
|
2105
|
+
],
|
|
2106
|
+
(timeoutSec + 10) * 1e3
|
|
2107
|
+
);
|
|
2108
|
+
}
|
|
2109
|
+
/** 3. Get everything the agent changed, as a patch */
|
|
2110
|
+
getDiff() {
|
|
2111
|
+
git(["add", "-A"], this.tempDir);
|
|
2112
|
+
return git(["diff", "--cached", "--binary"], this.tempDir);
|
|
2113
|
+
}
|
|
2114
|
+
/** 4. Apply the agent's changes to the REAL project */
|
|
2115
|
+
applyToOriginal() {
|
|
2116
|
+
const patch = this.getDiff();
|
|
2117
|
+
if (!patch.trim()) return;
|
|
2118
|
+
git(["apply", "-"], this.projectPath, patch);
|
|
2119
|
+
}
|
|
2120
|
+
/** 5. Delete the container and the temp folder */
|
|
2121
|
+
async destroy() {
|
|
2122
|
+
await docker(["rm", "-f", this.container]);
|
|
2123
|
+
if (this.tempDir) rmSync2(this.tempDir, { recursive: true, force: true });
|
|
2124
|
+
}
|
|
2125
|
+
/** 6. Run a command with internet, then cut the internet again */
|
|
2126
|
+
async execWithNetwork(executable, args, timeoutSec = 180) {
|
|
2127
|
+
const c2 = await docker(["network", "connect", "bridge", this.container]);
|
|
2128
|
+
if (c2.exitCode !== 0) return c2;
|
|
2129
|
+
try {
|
|
2130
|
+
return await this.execArgs(executable, args, timeoutSec);
|
|
2131
|
+
} finally {
|
|
2132
|
+
await docker(["network", "disconnect", "bridge", this.container]);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
};
|
|
2136
|
+
|
|
2137
|
+
// src/index.ts
|
|
2138
|
+
var VERSION = true ? "0.1.0" : "dev";
|
|
2139
|
+
function usage() {
|
|
2140
|
+
console.log(`
|
|
2141
|
+
${c.bold("brocodex")} ${c.dim(`v${VERSION}`)} ${c.dim("\xB7 sandboxed AI coding agent")}
|
|
2142
|
+
|
|
2143
|
+
${c.bold("Usage")}
|
|
2144
|
+
brocodex start in the current folder
|
|
2145
|
+
brocodex --setup choose provider, API key and model id
|
|
2146
|
+
brocodex --rebuild-image rebuild the Docker sandbox image, then exit
|
|
2147
|
+
brocodex --version print the version
|
|
2148
|
+
brocodex --help show this help
|
|
2149
|
+
`);
|
|
2150
|
+
}
|
|
2151
|
+
var MIME = {
|
|
2152
|
+
".html": "text/html; charset=utf-8",
|
|
2153
|
+
".css": "text/css; charset=utf-8",
|
|
2154
|
+
".js": "text/javascript; charset=utf-8",
|
|
2155
|
+
".json": "application/json",
|
|
2156
|
+
".svg": "image/svg+xml",
|
|
2157
|
+
".png": "image/png",
|
|
2158
|
+
".jpg": "image/jpeg",
|
|
2159
|
+
".jpeg": "image/jpeg",
|
|
2160
|
+
".gif": "image/gif",
|
|
2161
|
+
".ico": "image/x-icon",
|
|
2162
|
+
".txt": "text/plain; charset=utf-8",
|
|
2163
|
+
".woff2": "font/woff2"
|
|
2164
|
+
};
|
|
2165
|
+
function startPreview(root2) {
|
|
2166
|
+
const server = http.createServer((req, res) => {
|
|
2167
|
+
try {
|
|
2168
|
+
const urlPath = decodeURIComponent((req.url ?? "/").split("?")[0]);
|
|
2169
|
+
let file = path5.join(root2, urlPath);
|
|
2170
|
+
if (file !== root2 && !file.startsWith(root2 + path5.sep)) {
|
|
2171
|
+
res.writeHead(403).end("Forbidden");
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
if (fs5.existsSync(file) && fs5.statSync(file).isDirectory()) {
|
|
2175
|
+
file = path5.join(file, "index.html");
|
|
2176
|
+
}
|
|
2177
|
+
fs5.readFile(file, (err, data) => {
|
|
2178
|
+
if (err) {
|
|
2179
|
+
res.writeHead(404, { "Content-Type": "text/plain" }).end("Not found");
|
|
2180
|
+
return;
|
|
2181
|
+
}
|
|
2182
|
+
res.writeHead(200, {
|
|
2183
|
+
"Content-Type": MIME[path5.extname(file).toLowerCase()] ?? "application/octet-stream"
|
|
2184
|
+
});
|
|
2185
|
+
res.end(data);
|
|
2186
|
+
});
|
|
2187
|
+
} catch {
|
|
2188
|
+
res.writeHead(400).end("Bad request");
|
|
2189
|
+
}
|
|
2190
|
+
});
|
|
2191
|
+
server.listen(0, "127.0.0.1");
|
|
2192
|
+
return server;
|
|
2193
|
+
}
|
|
2194
|
+
async function main() {
|
|
2195
|
+
const flags = process.argv.slice(2);
|
|
2196
|
+
if (flags.includes("--version") || flags.includes("-v")) {
|
|
2197
|
+
console.log(VERSION);
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
if (flags.includes("--help") || flags.includes("-h")) {
|
|
2201
|
+
usage();
|
|
2202
|
+
return;
|
|
2203
|
+
}
|
|
2204
|
+
if (flags.includes("--rebuild-image")) {
|
|
2205
|
+
await prepareSandbox({ rebuild: true });
|
|
2206
|
+
return;
|
|
2207
|
+
}
|
|
2208
|
+
let config;
|
|
2209
|
+
if (flags.includes("--setup")) {
|
|
2210
|
+
const result = await runSetupWizard(loadSavedConfig() ?? loadConfig()?.config);
|
|
2211
|
+
if (!result) return;
|
|
2212
|
+
config = result;
|
|
2213
|
+
} else {
|
|
2214
|
+
const found = loadConfig();
|
|
2215
|
+
if (found) {
|
|
2216
|
+
config = found.config;
|
|
2217
|
+
} else if (process.stdin.isTTY) {
|
|
2218
|
+
info("No API key configured yet. Let's set one up.");
|
|
2219
|
+
const result = await runSetupWizard();
|
|
2220
|
+
if (!result) return;
|
|
2221
|
+
config = result;
|
|
2222
|
+
} else {
|
|
2223
|
+
throw new Error(
|
|
2224
|
+
"No API key configured. Run `brocodex --setup`."
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
const providerLabel = () => providerInfo(config.provider)?.label ?? config.provider;
|
|
2229
|
+
const makeAgent = () => new Agent(createProvider(config), void 0, void 0, async () => true);
|
|
2230
|
+
await prepareSandbox();
|
|
2231
|
+
const sandbox2 = new SandboxManager({ projectPath: process.cwd() });
|
|
2232
|
+
await sandbox2.start();
|
|
2233
|
+
useSandbox(sandbox2);
|
|
2234
|
+
let rl = readline3.createInterface({ input: input3, output: output3 });
|
|
2235
|
+
let agent = makeAgent();
|
|
2236
|
+
let mode = "chat";
|
|
2237
|
+
let preview = null;
|
|
2238
|
+
banner({ provider: config.provider, model: config.model, cwd: process.cwd() });
|
|
2239
|
+
try {
|
|
2240
|
+
while (true) {
|
|
2241
|
+
const line = (await rl.question(prompt(mode))).trim();
|
|
2242
|
+
if (line === "/exit") break;
|
|
2243
|
+
if (!line) continue;
|
|
2244
|
+
if (line === "/chat") {
|
|
2245
|
+
mode = "chat";
|
|
2246
|
+
console.log("Switched to chat mode.\n");
|
|
2247
|
+
continue;
|
|
2248
|
+
}
|
|
2249
|
+
if (line === "/setup") {
|
|
2250
|
+
rl.close();
|
|
2251
|
+
let updated = null;
|
|
2252
|
+
try {
|
|
2253
|
+
updated = await runSetupWizard(config);
|
|
2254
|
+
} catch (error2) {
|
|
2255
|
+
error(error2 instanceof Error ? error2.message : String(error2));
|
|
2256
|
+
}
|
|
2257
|
+
rl = readline3.createInterface({ input: input3, output: output3 });
|
|
2258
|
+
if (updated) {
|
|
2259
|
+
config = updated;
|
|
2260
|
+
agent = makeAgent();
|
|
2261
|
+
success(`Now using ${providerLabel()} / ${config.model}`);
|
|
2262
|
+
info("Conversation history was reset.\n");
|
|
2263
|
+
}
|
|
2264
|
+
continue;
|
|
2265
|
+
}
|
|
2266
|
+
if (line === "/help") {
|
|
2267
|
+
help();
|
|
2268
|
+
continue;
|
|
2269
|
+
}
|
|
2270
|
+
if (line === "/agent") {
|
|
2271
|
+
mode = "agent";
|
|
2272
|
+
console.log("Switched to agent mode.\n");
|
|
2273
|
+
continue;
|
|
2274
|
+
}
|
|
2275
|
+
if (line === "/preview") {
|
|
2276
|
+
if (!preview) {
|
|
2277
|
+
preview = startPreview(sandbox2.workDir);
|
|
2278
|
+
await new Promise((r) => preview.once("listening", () => r()));
|
|
2279
|
+
}
|
|
2280
|
+
const { port } = preview.address();
|
|
2281
|
+
console.log(`Open in your browser: http://localhost:${port}
|
|
2282
|
+
`);
|
|
2283
|
+
continue;
|
|
2284
|
+
}
|
|
2285
|
+
try {
|
|
2286
|
+
await agent.run(line, mode);
|
|
2287
|
+
} catch (error2) {
|
|
2288
|
+
error(error2 instanceof Error ? error2.message : String(error2));
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
} finally {
|
|
2292
|
+
try {
|
|
2293
|
+
const diff = sandbox2.getDiff();
|
|
2294
|
+
if (diff.trim()) {
|
|
2295
|
+
const s = summarizeDiff(diff);
|
|
2296
|
+
console.log("");
|
|
2297
|
+
printDiff(diff);
|
|
2298
|
+
console.log(
|
|
2299
|
+
`
|
|
2300
|
+
${c.bold(`${s.files} file(s) changed`)} ${c.green(`+${s.added}`)} ${c.red(`-${s.removed}`)}`
|
|
2301
|
+
);
|
|
2302
|
+
const answer = await rl.question(
|
|
2303
|
+
`${c.bold("Apply to your real project?")} ${c.dim("[y/N]")} `
|
|
2304
|
+
);
|
|
2305
|
+
if (answer.trim().toLowerCase() === "y") {
|
|
2306
|
+
sandbox2.applyToOriginal();
|
|
2307
|
+
success("Applied to your project.");
|
|
2308
|
+
} else {
|
|
2309
|
+
info("Discarded. Nothing was changed.");
|
|
2310
|
+
}
|
|
2311
|
+
} else {
|
|
2312
|
+
info("No changes.");
|
|
2313
|
+
}
|
|
2314
|
+
} catch (error2) {
|
|
2315
|
+
console.error(
|
|
2316
|
+
"\n[could not apply changes]",
|
|
2317
|
+
error2 instanceof Error ? error2.message : error2
|
|
2318
|
+
);
|
|
2319
|
+
}
|
|
2320
|
+
preview?.closeAllConnections();
|
|
2321
|
+
preview?.close();
|
|
2322
|
+
await sandbox2.destroy();
|
|
2323
|
+
rl.close();
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
main().catch((error2) => {
|
|
2327
|
+
if (process.env.BROCODEX_DEBUG) console.error(error2);
|
|
2328
|
+
else error(error2 instanceof Error ? error2.message : String(error2));
|
|
2329
|
+
process.exitCode = 1;
|
|
2330
|
+
});
|