pal-code 0.0.5
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/LICENSE +21 -0
- package/README.md +169 -0
- package/SYSTEM.md +146 -0
- package/bin/pal-code.js +131 -0
- package/package.json +68 -0
- package/packages/cli/README.md +77 -0
- package/packages/cli/src/agent-panel.ts +94 -0
- package/packages/cli/src/commands/ext.ts +79 -0
- package/packages/cli/src/commands/mcp-registry.ts +136 -0
- package/packages/cli/src/commands/mcp.ts +186 -0
- package/packages/cli/src/commands.ts +153 -0
- package/packages/cli/src/components/message-box.ts +35 -0
- package/packages/cli/src/components/permission-prompt.ts +185 -0
- package/packages/cli/src/components/render-history.ts +143 -0
- package/packages/cli/src/components/run-view.ts +256 -0
- package/packages/cli/src/components/sidebar.ts +120 -0
- package/packages/cli/src/components/status-line.ts +26 -0
- package/packages/cli/src/config.ts +107 -0
- package/packages/cli/src/index.ts +1606 -0
- package/packages/cli/src/overlays/key-input.ts +167 -0
- package/packages/cli/src/overlays/model-picker.ts +106 -0
- package/packages/cli/src/overlays/session-picker.ts +168 -0
- package/packages/cli/src/overlays/wizard.ts +145 -0
- package/packages/cli/src/state.ts +133 -0
- package/packages/cli/src/theme.ts +88 -0
- package/packages/cli/src/turn.ts +266 -0
- package/packages/cli/src/utils/cost.ts +111 -0
- package/packages/cli/src/utils/format.test.ts +167 -0
- package/packages/cli/src/utils/format.ts +248 -0
- package/packages/cli/src/utils/highlight.ts +358 -0
- package/packages/cli/src/utils/permissions.ts +196 -0
- package/packages/core/src/agent/events.ts +36 -0
- package/packages/core/src/agent/fallback.test.ts +99 -0
- package/packages/core/src/agent/fallback.ts +344 -0
- package/packages/core/src/agent/index.ts +35 -0
- package/packages/core/src/agent/protocol.test.ts +136 -0
- package/packages/core/src/agent/resume-compaction.test.ts +116 -0
- package/packages/core/src/agent/roles.ts +188 -0
- package/packages/core/src/agent/run.test.ts +207 -0
- package/packages/core/src/agent/run.ts +713 -0
- package/packages/core/src/agent/scope.ts +34 -0
- package/packages/core/src/agent/todos.ts +66 -0
- package/packages/core/src/compaction.protocol.test.ts +90 -0
- package/packages/core/src/compaction.test.ts +101 -0
- package/packages/core/src/compaction.ts +243 -0
- package/packages/core/src/config.test.ts +40 -0
- package/packages/core/src/config.ts +387 -0
- package/packages/core/src/extensions.ts +178 -0
- package/packages/core/src/index.ts +157 -0
- package/packages/core/src/logger.ts +54 -0
- package/packages/core/src/provider/auth.ts +153 -0
- package/packages/core/src/provider/complete.ts +63 -0
- package/packages/core/src/provider/index.ts +6 -0
- package/packages/core/src/provider/openrouter.test.ts +59 -0
- package/packages/core/src/provider/openrouter.ts +304 -0
- package/packages/core/src/provider/pick-model.ts +43 -0
- package/packages/core/src/provider/registry.ts +222 -0
- package/packages/core/src/provider/types.ts +61 -0
- package/packages/core/src/repo-map.ts +177 -0
- package/packages/core/src/session/index.ts +2 -0
- package/packages/core/src/session/migration.test.ts +104 -0
- package/packages/core/src/session/store-v2-repair.test.ts +209 -0
- package/packages/core/src/session/store.test.ts +235 -0
- package/packages/core/src/session/store.ts +677 -0
- package/packages/core/src/session/types.ts +72 -0
- package/packages/core/src/snapshots.ts +107 -0
- package/packages/core/src/tools/definitions.ts +365 -0
- package/packages/core/src/tools/executor.test.ts +122 -0
- package/packages/core/src/tools/executor.ts +1363 -0
- package/packages/core/src/tools/index.ts +5 -0
- package/packages/core/src/tools/search.ts +201 -0
- package/scripts/postinstall.js +121 -0
- package/scripts/preinstall.js +51 -0
|
@@ -0,0 +1,1363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool executor — runs tool calls from the model and returns results.
|
|
3
|
+
* Each tool is a pure function: (args) => Promise<string>.
|
|
4
|
+
*
|
|
5
|
+
* Applies ignore patterns from .pal.json to all file operations.
|
|
6
|
+
* Blocks reads/writes to ignored paths, filters directory listings, enforces size limits.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {readFile, writeFile, readdir, mkdir} from 'fs/promises';
|
|
10
|
+
import {spawn, exec} from 'child_process';
|
|
11
|
+
import {promisify} from 'util';
|
|
12
|
+
|
|
13
|
+
const execAsync = promisify(exec);
|
|
14
|
+
import {createInterface} from 'readline';
|
|
15
|
+
import {dirname, resolve, isAbsolute, sep} from 'path';
|
|
16
|
+
import {minimatch} from 'minimatch';
|
|
17
|
+
import {
|
|
18
|
+
loadAgentConfig,
|
|
19
|
+
isPathIgnored,
|
|
20
|
+
filterEntries,
|
|
21
|
+
checkFileSize,
|
|
22
|
+
resolveProjectRoot,
|
|
23
|
+
type ToolConfig,
|
|
24
|
+
} from '../config.js';
|
|
25
|
+
import {snapshotFile} from '../snapshots.js';
|
|
26
|
+
import type {ConversationMessage} from '../agent/run.js';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `rg --glob '!pat'` args for each `.pal.json` ignore pattern, so ripgrep
|
|
30
|
+
* honours the same ignores as read_file / list_directory.
|
|
31
|
+
*/
|
|
32
|
+
function ignoreGlobArgs(config: ToolConfig): string[] {
|
|
33
|
+
return (config.ignore ?? []).flatMap((p) => ['--glob', `!${p}`]);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Predicate form of the same ignores, for the pure-JS walkers. */
|
|
37
|
+
function ignorePredicate(config: ToolConfig): (absPath: string) => boolean {
|
|
38
|
+
return (absPath) => isPathIgnored(absPath, config);
|
|
39
|
+
}
|
|
40
|
+
import {log} from '../logger.js';
|
|
41
|
+
import {emitAgentEvent} from '../agent/events.js';
|
|
42
|
+
import {grepJS, globJS} from './search.js';
|
|
43
|
+
import {setTodos, formatTodos, type TodoStatus} from '../agent/todos.js';
|
|
44
|
+
|
|
45
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
46
|
+
// Stateless Shell — spawn a fresh process per command, track cwd manually.
|
|
47
|
+
// Reliable across platforms (no shared-stream / marker-detection races).
|
|
48
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
49
|
+
|
|
50
|
+
let shellCwd = process.cwd();
|
|
51
|
+
|
|
52
|
+
/** Current tracked shell cwd — exposed so nested runs can be scoped. */
|
|
53
|
+
export function getShellCwd(): string {
|
|
54
|
+
return shellCwd;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Override the tracked shell cwd — exposed so nested runs can be scoped. */
|
|
58
|
+
export function setShellCwd(next: string): void {
|
|
59
|
+
shellCwd = next;
|
|
60
|
+
}
|
|
61
|
+
const SHELL_TIMEOUT_MS = 120_000;
|
|
62
|
+
|
|
63
|
+
async function execCommand(
|
|
64
|
+
command: string,
|
|
65
|
+
timeoutMs: number,
|
|
66
|
+
cwdOverride?: string,
|
|
67
|
+
): Promise<{stdout: string; stderr: string; exitCode: number}> {
|
|
68
|
+
const isWin = process.platform === 'win32';
|
|
69
|
+
const workdir = cwdOverride ?? shellCwd;
|
|
70
|
+
|
|
71
|
+
const proc = Bun.spawn(isWin ? ['cmd', '/d', '/c', command] : ['bash', '-c', command], {
|
|
72
|
+
stdout: 'pipe',
|
|
73
|
+
stderr: 'pipe',
|
|
74
|
+
stdin: 'ignore',
|
|
75
|
+
cwd: workdir,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
let timedOut = false;
|
|
79
|
+
const timer = setTimeout(() => {
|
|
80
|
+
timedOut = true;
|
|
81
|
+
try {
|
|
82
|
+
proc.kill();
|
|
83
|
+
} catch {
|
|
84
|
+
// already dead
|
|
85
|
+
}
|
|
86
|
+
}, timeoutMs);
|
|
87
|
+
|
|
88
|
+
const [stdout, stderr] = await Promise.all([
|
|
89
|
+
new Response(proc.stdout as ReadableStream<Uint8Array>).text(),
|
|
90
|
+
new Response(proc.stderr as ReadableStream<Uint8Array>).text(),
|
|
91
|
+
]);
|
|
92
|
+
const exitCode = await proc.exited;
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
|
|
95
|
+
if (timedOut) {
|
|
96
|
+
throw new Error(`Command timed out after ${timeoutMs}ms`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Track cwd changes for subsequent calls (only if cd succeeded, no override)
|
|
100
|
+
const cdMatch = command.match(/^\s*cd\s+(?:\/d\s+)?["']?([^"'\s;&]+)["']?\s*(?:;|&&|$)/);
|
|
101
|
+
if (cdMatch && exitCode === 0 && !cwdOverride) {
|
|
102
|
+
const next = cdMatch[1];
|
|
103
|
+
shellCwd = isAbsolute(next) ? next : resolve(shellCwd, next);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {stdout, stderr, exitCode};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Reset the tracked shell working directory (e.g., on /clear or session reset). */
|
|
110
|
+
export function resetShell() {
|
|
111
|
+
shellCwd = process.cwd();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface ToolResult {
|
|
115
|
+
toolCallId: string;
|
|
116
|
+
content: string;
|
|
117
|
+
error?: boolean;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const MAX_OUTPUT = 32_000; // Truncate large outputs
|
|
121
|
+
|
|
122
|
+
function truncate(s: string): string {
|
|
123
|
+
if (s.length <= MAX_OUTPUT) return s;
|
|
124
|
+
return s.slice(0, MAX_OUTPUT) + `\n\n... (truncated, ${s.length} chars total)`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Parse Aider-style SEARCH/REPLACE blocks from model output.
|
|
129
|
+
* Matches: <<<<<<< SEARCH\n....\n=======\n....\n>>>>>>> REPLACE
|
|
130
|
+
*/
|
|
131
|
+
function parseEditBlocks(raw: string): Array<{search: string; replace: string}> {
|
|
132
|
+
const blocks: Array<{search: string; replace: string}> = [];
|
|
133
|
+
const regex = /<<<<<<<\s*SEARCH\n(.*?)\n=======\n(.*?)\n>>>>>>>\s*REPLACE/gs;
|
|
134
|
+
let match;
|
|
135
|
+
while ((match = regex.exec(raw)) !== null) {
|
|
136
|
+
blocks.push({search: match[1], replace: match[2]});
|
|
137
|
+
}
|
|
138
|
+
return blocks;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const coreHandlers: Record<
|
|
142
|
+
string,
|
|
143
|
+
(args: Record<string, unknown>, config: ToolConfig) => Promise<string>
|
|
144
|
+
> = {};
|
|
145
|
+
|
|
146
|
+
const extensionHandlers: Record<
|
|
147
|
+
string,
|
|
148
|
+
(args: Record<string, unknown>, config: ToolConfig) => Promise<string>
|
|
149
|
+
> = {};
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Register extension tool handlers.
|
|
153
|
+
* These are merged with core handlers and used as fallbacks.
|
|
154
|
+
*/
|
|
155
|
+
export function registerExtensionHandlers(
|
|
156
|
+
handlers: Record<string, (args: Record<string, unknown>, config: ToolConfig) => Promise<string>>,
|
|
157
|
+
): void {
|
|
158
|
+
Object.assign(extensionHandlers, handlers);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const tools: Record<
|
|
162
|
+
string,
|
|
163
|
+
(args: Record<string, unknown>, config: ToolConfig) => Promise<string>
|
|
164
|
+
> = {
|
|
165
|
+
async read_file(args, config) {
|
|
166
|
+
const filePath = String(args.path);
|
|
167
|
+
const offset = args.offset ? Number(args.offset) : undefined;
|
|
168
|
+
const limit = args.limit ? Number(args.limit) : undefined;
|
|
169
|
+
|
|
170
|
+
// Check ignore patterns
|
|
171
|
+
if (isPathIgnored(filePath, config)) {
|
|
172
|
+
return `(ignored — ${filePath} matches ignore patterns in .pal.json)`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Check file size limit
|
|
176
|
+
const sizeError = checkFileSize(filePath, config);
|
|
177
|
+
if (sizeError) return sizeError;
|
|
178
|
+
|
|
179
|
+
const buf = await readFile(filePath);
|
|
180
|
+
// Binary sniff: a NUL byte in the head means this isn't text. Dumping it
|
|
181
|
+
// would flood the context with garbage and can corrupt the conversation.
|
|
182
|
+
if (buf.subarray(0, 8000).includes(0)) {
|
|
183
|
+
return `(binary file — ${buf.length} bytes, not shown)`;
|
|
184
|
+
}
|
|
185
|
+
const content = buf.toString('utf-8');
|
|
186
|
+
const lines = content.split('\n');
|
|
187
|
+
const start = offset ? Math.max(0, offset - 1) : 0;
|
|
188
|
+
const effectiveLimit = limit ?? config.readLineLimit;
|
|
189
|
+
const end = start + effectiveLimit;
|
|
190
|
+
|
|
191
|
+
const numbered = lines
|
|
192
|
+
.slice(start, end)
|
|
193
|
+
.map((line, i) => `${start + i + 1}: ${line}`)
|
|
194
|
+
.join('\n');
|
|
195
|
+
|
|
196
|
+
const truncated =
|
|
197
|
+
lines.length > end
|
|
198
|
+
? `\n\n... (${lines.length - end} more lines, use offset/limit to read more)`
|
|
199
|
+
: '';
|
|
200
|
+
|
|
201
|
+
return numbered + truncated || '(empty file)';
|
|
202
|
+
},
|
|
203
|
+
|
|
204
|
+
async write_file(args, config) {
|
|
205
|
+
const filePath = String(args.path);
|
|
206
|
+
const content = String(args.content);
|
|
207
|
+
|
|
208
|
+
if (isPathIgnored(filePath, config)) {
|
|
209
|
+
throw new Error(`Cannot write to ${filePath} — matches ignore patterns`);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
await mkdir(dirname(filePath), {recursive: true});
|
|
213
|
+
snapshotFile(filePath, 'write_file');
|
|
214
|
+
await writeFile(filePath, content, 'utf-8');
|
|
215
|
+
return `Wrote ${content.length} bytes to ${filePath}`;
|
|
216
|
+
},
|
|
217
|
+
|
|
218
|
+
async edit_file(args, config) {
|
|
219
|
+
const filePath = String(args.path);
|
|
220
|
+
const oldString = String(args.old_string);
|
|
221
|
+
const newString = String(args.new_string);
|
|
222
|
+
|
|
223
|
+
if (isPathIgnored(filePath, config)) {
|
|
224
|
+
throw new Error(`Cannot edit ${filePath} — matches ignore patterns`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const content = await readFile(filePath, 'utf-8');
|
|
228
|
+
|
|
229
|
+
// Reject non-unique old_string: replacing only the first occurrence is a
|
|
230
|
+
// silent footgun — the model gets "Edited successfully" while the wrong
|
|
231
|
+
// site was changed.
|
|
232
|
+
const occurrences = content.split(oldString).length - 1;
|
|
233
|
+
if (occurrences === 0) {
|
|
234
|
+
throw new Error(`old_string not found in ${filePath}`);
|
|
235
|
+
}
|
|
236
|
+
if (occurrences > 1) {
|
|
237
|
+
throw new Error(
|
|
238
|
+
`old_string is not unique in ${filePath} (${occurrences} occurrences). ` +
|
|
239
|
+
`Narrow the match to exactly one occurrence.`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const updated = content.replace(oldString, newString);
|
|
244
|
+
snapshotFile(filePath, 'edit_file');
|
|
245
|
+
await writeFile(filePath, updated, 'utf-8');
|
|
246
|
+
return `Edited ${filePath} successfully`;
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
async edit_block(args, config) {
|
|
250
|
+
const filePath = String(args.path ?? '');
|
|
251
|
+
const editsRaw = String(args.edits ?? '');
|
|
252
|
+
|
|
253
|
+
if (!filePath || !editsRaw) return 'Error: path and edits are required';
|
|
254
|
+
|
|
255
|
+
if (isPathIgnored(filePath, config)) {
|
|
256
|
+
throw new Error(`Cannot edit ${filePath} — matches ignore patterns`);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const blocks = parseEditBlocks(editsRaw);
|
|
260
|
+
if (blocks.length === 0) {
|
|
261
|
+
return 'Error: no valid SEARCH/REPLACE blocks found. Format:\n<<<<<<< SEARCH\nold code\n=======\nnew code\n>>>>>>> REPLACE';
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const content = await readFile(filePath, 'utf-8');
|
|
265
|
+
let modified = content;
|
|
266
|
+
let applied = 0;
|
|
267
|
+
const errors: string[] = [];
|
|
268
|
+
|
|
269
|
+
for (const block of blocks) {
|
|
270
|
+
const search = block.search.replace(/\r\n/g, '\n');
|
|
271
|
+
const replace = block.replace.replace(/\r\n/g, '\n');
|
|
272
|
+
|
|
273
|
+
let idx = modified.indexOf(search);
|
|
274
|
+
let matchLen = search.length;
|
|
275
|
+
|
|
276
|
+
if (idx === -1) {
|
|
277
|
+
// Fuzzy fallback: trim the search block
|
|
278
|
+
const trimmed = search.trim();
|
|
279
|
+
idx = trimmed ? modified.indexOf(trimmed) : -1;
|
|
280
|
+
matchLen = trimmed.length;
|
|
281
|
+
if (idx === -1) {
|
|
282
|
+
errors.push(`SEARCH block not found: "${search.slice(0, 60).replace(/\n/g, '\\n')}..."`);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
modified = modified.slice(0, idx) + replace + modified.slice(idx + matchLen);
|
|
288
|
+
applied++;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (applied === 0) {
|
|
292
|
+
return `Error: none of ${blocks.length} edit(s) applied\n${errors.join('\n')}`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
snapshotFile(filePath, 'edit_block');
|
|
296
|
+
await writeFile(filePath, modified, 'utf-8');
|
|
297
|
+
|
|
298
|
+
const result = `Applied ${applied}/${blocks.length} edit(s) to ${filePath}`;
|
|
299
|
+
return errors.length ? `${result}\n${errors.join('\n')}` : result;
|
|
300
|
+
},
|
|
301
|
+
|
|
302
|
+
async bash(args, _config) {
|
|
303
|
+
// This tool already runs every command inside a shell (cmd.exe on Windows,
|
|
304
|
+
// bash elsewhere). Models frequently add their own wrapper, which breaks on
|
|
305
|
+
// nested quoting — e.g. `cmd /c "dir /a"` becomes `cmd /d /c cmd /c "dir /a"`
|
|
306
|
+
// and cmd.exe rejects it. Unwrap a leading `cmd[.exe] /c` so the command
|
|
307
|
+
// reaches the shell exactly once.
|
|
308
|
+
const rawCommand = String(args.command);
|
|
309
|
+
const command =
|
|
310
|
+
process.platform === 'win32'
|
|
311
|
+
? rawCommand
|
|
312
|
+
.replace(/^\s*cmd(?:\.exe)?\s+(?:\/[dqs]\s+)*\/c\s+/i, '')
|
|
313
|
+
.replace(/^"(.*)"$/s, '$1')
|
|
314
|
+
: rawCommand;
|
|
315
|
+
|
|
316
|
+
// If the user passes a cwd arg, update the tracked working directory
|
|
317
|
+
if (args.cwd) {
|
|
318
|
+
const requested = String(args.cwd);
|
|
319
|
+
shellCwd = isAbsolute(requested) ? requested : resolve(shellCwd, requested);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
try {
|
|
323
|
+
const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS);
|
|
324
|
+
|
|
325
|
+
let output = '';
|
|
326
|
+
if (stdout) output += stdout;
|
|
327
|
+
if (stderr) output += (output ? '\n--- stderr ---\n' : '') + stderr;
|
|
328
|
+
if (exitCode !== 0) {
|
|
329
|
+
output += `${output ? '\n' : ''}(exit code ${exitCode})`;
|
|
330
|
+
}
|
|
331
|
+
return truncate(output || '(no output)');
|
|
332
|
+
} catch (err: unknown) {
|
|
333
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
334
|
+
return truncate(`Command failed: ${msg}`);
|
|
335
|
+
}
|
|
336
|
+
},
|
|
337
|
+
|
|
338
|
+
async verify(args, _config) {
|
|
339
|
+
const projectPath = args.path ? resolve(String(args.path)) : shellCwd;
|
|
340
|
+
const requested = Array.isArray(args.checks) ? args.checks.map(String) : [];
|
|
341
|
+
|
|
342
|
+
// Walk up to find the nearest config (monorepo-friendly: a subpackage
|
|
343
|
+
// usually inherits tsconfig.json / test script from the repo root).
|
|
344
|
+
const findUp = async (name: string, maxLevels = 20): Promise<string | null> => {
|
|
345
|
+
let dir = projectPath;
|
|
346
|
+
for (let i = 0; i < maxLevels; i++) {
|
|
347
|
+
const candidate = resolve(dir, name);
|
|
348
|
+
try {
|
|
349
|
+
await readFile(candidate, 'utf-8');
|
|
350
|
+
return candidate;
|
|
351
|
+
} catch {
|
|
352
|
+
// keep climbing
|
|
353
|
+
}
|
|
354
|
+
const parent = dirname(dir);
|
|
355
|
+
if (parent === dir) break;
|
|
356
|
+
dir = parent;
|
|
357
|
+
}
|
|
358
|
+
return null;
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
const tsconfigPath = await findUp('tsconfig.json');
|
|
362
|
+
const pkgPath = await findUp('package.json');
|
|
363
|
+
const hasTsconfig = tsconfigPath !== null;
|
|
364
|
+
|
|
365
|
+
let testScript: string | null = null;
|
|
366
|
+
if (pkgPath) {
|
|
367
|
+
try {
|
|
368
|
+
const pkg = JSON.parse(await readFile(pkgPath, 'utf-8')) as {
|
|
369
|
+
scripts?: Record<string, string>;
|
|
370
|
+
};
|
|
371
|
+
testScript = pkg.scripts?.test ?? null;
|
|
372
|
+
} catch {
|
|
373
|
+
// malformed package.json — ignore
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// Run from the directory that owns the config we found.
|
|
378
|
+
const checkRoot = tsconfigPath
|
|
379
|
+
? dirname(tsconfigPath)
|
|
380
|
+
: pkgPath
|
|
381
|
+
? dirname(pkgPath)
|
|
382
|
+
: projectPath;
|
|
383
|
+
|
|
384
|
+
const runTs = hasTsconfig && (requested.length === 0 || requested.includes('typescript'));
|
|
385
|
+
const runTest = !!testScript && (requested.length === 0 || requested.includes('test'));
|
|
386
|
+
|
|
387
|
+
if (!runTs && !runTest) {
|
|
388
|
+
return `No checks available (searched up from ${projectPath}): hasTsconfig=${hasTsconfig}, testScript=${testScript ?? 'none'}`;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const lines: string[] = [];
|
|
392
|
+
let allPassed = true;
|
|
393
|
+
|
|
394
|
+
if (runTs) {
|
|
395
|
+
const {stdout, stderr, exitCode} = await execCommand(
|
|
396
|
+
'bunx tsc --noEmit 2>&1',
|
|
397
|
+
120_000,
|
|
398
|
+
checkRoot,
|
|
399
|
+
);
|
|
400
|
+
const out = (stdout + stderr).trim();
|
|
401
|
+
if (exitCode === 0) {
|
|
402
|
+
lines.push('✓ typescript: passed');
|
|
403
|
+
} else {
|
|
404
|
+
allPassed = false;
|
|
405
|
+
lines.push('✗ typescript: FAILED');
|
|
406
|
+
lines.push(out.slice(0, 3000) || '(no output)');
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (runTest) {
|
|
411
|
+
const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot);
|
|
412
|
+
const out = (stdout + stderr).trim();
|
|
413
|
+
if (exitCode === 0) {
|
|
414
|
+
lines.push('✓ test: passed');
|
|
415
|
+
} else {
|
|
416
|
+
allPassed = false;
|
|
417
|
+
lines.push('✗ test: FAILED');
|
|
418
|
+
lines.push(out.slice(-3000) || '(no output)');
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
return `${allPassed ? 'ALL PASSED' : 'FAILURES FOUND'}\n\n${lines.join('\n\n')}`;
|
|
423
|
+
},
|
|
424
|
+
|
|
425
|
+
async todo(args, _config) {
|
|
426
|
+
if (!Array.isArray(args.todos)) {
|
|
427
|
+
return 'Error: `todos` must be an array of {content, status}.';
|
|
428
|
+
}
|
|
429
|
+
const list = setTodos(
|
|
430
|
+
(args.todos as Array<Record<string, unknown>>).map((t) => ({
|
|
431
|
+
content: String(t?.content ?? ''),
|
|
432
|
+
status: String(t?.status ?? 'pending') as TodoStatus,
|
|
433
|
+
})),
|
|
434
|
+
);
|
|
435
|
+
emitAgentEvent({type: 'todos-updated', todos: list});
|
|
436
|
+
return formatTodos(list);
|
|
437
|
+
},
|
|
438
|
+
|
|
439
|
+
async list_directory(args, config) {
|
|
440
|
+
const dirPath = String(args.path);
|
|
441
|
+
const pattern = args.pattern ? String(args.pattern) : undefined;
|
|
442
|
+
|
|
443
|
+
const entries = await readdir(dirPath, {withFileTypes: true});
|
|
444
|
+
|
|
445
|
+
// Filter by ignore patterns
|
|
446
|
+
const mapped = entries.map((e) => ({name: e.name, isDirectory: e.isDirectory()}));
|
|
447
|
+
let filtered = filterEntries(mapped, dirPath, config);
|
|
448
|
+
|
|
449
|
+
// Filter by user pattern
|
|
450
|
+
if (pattern) {
|
|
451
|
+
filtered = filtered.filter((entry) => minimatch(entry.name, pattern, {matchBase: true}));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const results: string[] = [];
|
|
455
|
+
for (const entry of filtered) {
|
|
456
|
+
results.push(entry.isDirectory ? `${entry.name}/` : entry.name);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
if (results.length === 0) return '(empty directory)';
|
|
460
|
+
|
|
461
|
+
const hidden = entries.length - filtered.length;
|
|
462
|
+
const suffix = hidden > 0 ? `\n\n(${hidden} ignored entries hidden)` : '';
|
|
463
|
+
|
|
464
|
+
return results.join('\n') + suffix;
|
|
465
|
+
},
|
|
466
|
+
|
|
467
|
+
async grep(args, config) {
|
|
468
|
+
const pattern = String(args.pattern);
|
|
469
|
+
const searchPath = args.path ? String(args.path) : '.';
|
|
470
|
+
const include = args.include ? String(args.include) : undefined;
|
|
471
|
+
const limit = args.limit ? Number(args.limit) : 100;
|
|
472
|
+
|
|
473
|
+
// Pure-JS search: works on every platform (no GNU grep / ripgrep needed).
|
|
474
|
+
// Honours .pal.json ignores, same as every other file-touching tool.
|
|
475
|
+
return truncate(
|
|
476
|
+
await grepJS({
|
|
477
|
+
pattern,
|
|
478
|
+
path: searchPath,
|
|
479
|
+
include,
|
|
480
|
+
limit,
|
|
481
|
+
isIgnored: ignorePredicate(config),
|
|
482
|
+
}),
|
|
483
|
+
);
|
|
484
|
+
},
|
|
485
|
+
|
|
486
|
+
async grep_search(args, config) {
|
|
487
|
+
const limit = args.limit ? Number(args.limit) : 100;
|
|
488
|
+
const searchPath = args.path ? String(args.path) : '.';
|
|
489
|
+
const rgArgs: string[] = [
|
|
490
|
+
'--json',
|
|
491
|
+
'--line-number',
|
|
492
|
+
'--color=never',
|
|
493
|
+
'--hidden',
|
|
494
|
+
'--no-messages',
|
|
495
|
+
];
|
|
496
|
+
if (args.include) {
|
|
497
|
+
rgArgs.push('--glob', String(args.include));
|
|
498
|
+
}
|
|
499
|
+
// Excludes go LAST: ripgrep resolves overlapping --glob flags by "last match
|
|
500
|
+
// wins", so an include placed after them would re-include ignored files.
|
|
501
|
+
rgArgs.push(...ignoreGlobArgs(config));
|
|
502
|
+
rgArgs.push('--', String(args.pattern), searchPath);
|
|
503
|
+
|
|
504
|
+
return new Promise<string>((resolve) => {
|
|
505
|
+
const proc = spawn('rg', rgArgs, {
|
|
506
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
507
|
+
timeout: 30_000,
|
|
508
|
+
});
|
|
509
|
+
let output = '';
|
|
510
|
+
let matchCount = 0;
|
|
511
|
+
let currentFile = '';
|
|
512
|
+
|
|
513
|
+
const rl = createInterface({input: proc.stdout});
|
|
514
|
+
rl.on('line', (line) => {
|
|
515
|
+
try {
|
|
516
|
+
const event = JSON.parse(line) as {
|
|
517
|
+
type: string;
|
|
518
|
+
data: {path: {text: string}; line_number: number; lines: {text: string}};
|
|
519
|
+
};
|
|
520
|
+
if (event.type === 'match') {
|
|
521
|
+
const filePath = event.data.path.text;
|
|
522
|
+
const lineNum = event.data.line_number;
|
|
523
|
+
const text = event.data.lines.text.trimEnd();
|
|
524
|
+
if (filePath !== currentFile) {
|
|
525
|
+
currentFile = filePath;
|
|
526
|
+
if (matchCount > 0) output += '\n';
|
|
527
|
+
output += filePath + ':\n';
|
|
528
|
+
}
|
|
529
|
+
if (matchCount < limit) {
|
|
530
|
+
output += ` Line ${lineNum}: ${text}\n`;
|
|
531
|
+
}
|
|
532
|
+
matchCount++;
|
|
533
|
+
}
|
|
534
|
+
} catch {
|
|
535
|
+
// Non-JSON line, skip
|
|
536
|
+
}
|
|
537
|
+
});
|
|
538
|
+
|
|
539
|
+
rl.on('close', () => {
|
|
540
|
+
if (matchCount === 0) {
|
|
541
|
+
resolve('No matches found.');
|
|
542
|
+
} else {
|
|
543
|
+
const header = `Found ${matchCount} match${matchCount !== 1 ? 'es' : ''}`;
|
|
544
|
+
const truncNotice =
|
|
545
|
+
matchCount > limit
|
|
546
|
+
? `\n\n[${matchCount} matches found. Showing first ${limit}. Use limit parameter for more.]`
|
|
547
|
+
: '';
|
|
548
|
+
resolve(`${header}${truncNotice}\n\n${output}`);
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
|
|
552
|
+
proc.on('error', (err) => {
|
|
553
|
+
if (err.message.includes('ENOENT')) {
|
|
554
|
+
// No ripgrep — fall back to the pure-JS search.
|
|
555
|
+
grepJS({
|
|
556
|
+
pattern: String(args.pattern),
|
|
557
|
+
path: searchPath,
|
|
558
|
+
include: args.include ? String(args.include) : undefined,
|
|
559
|
+
limit,
|
|
560
|
+
isIgnored: ignorePredicate(config),
|
|
561
|
+
})
|
|
562
|
+
.then(resolve)
|
|
563
|
+
.catch((e) => resolve(`Search error: ${e instanceof Error ? e.message : String(e)}`));
|
|
564
|
+
} else {
|
|
565
|
+
resolve(`Error running ripgrep: ${err.message}`);
|
|
566
|
+
}
|
|
567
|
+
});
|
|
568
|
+
});
|
|
569
|
+
},
|
|
570
|
+
|
|
571
|
+
async glob_search(args, config) {
|
|
572
|
+
const limit = args.limit ? Number(args.limit) : 100;
|
|
573
|
+
const searchPath = args.path ? String(args.path) : '.';
|
|
574
|
+
const rgArgs: string[] = [
|
|
575
|
+
'--files',
|
|
576
|
+
'--hidden',
|
|
577
|
+
'--glob',
|
|
578
|
+
String(args.pattern),
|
|
579
|
+
// Excludes last — see grep_search for why.
|
|
580
|
+
...ignoreGlobArgs(config),
|
|
581
|
+
searchPath,
|
|
582
|
+
];
|
|
583
|
+
|
|
584
|
+
return new Promise<string>((resolve) => {
|
|
585
|
+
const proc = spawn('rg', rgArgs, {
|
|
586
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
587
|
+
timeout: 30_000,
|
|
588
|
+
});
|
|
589
|
+
const files: string[] = [];
|
|
590
|
+
|
|
591
|
+
const rl = createInterface({input: proc.stdout});
|
|
592
|
+
rl.on('line', (line) => {
|
|
593
|
+
if (line && files.length < limit + 1) {
|
|
594
|
+
files.push(line);
|
|
595
|
+
}
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
rl.on('close', () => {
|
|
599
|
+
if (files.length === 0) {
|
|
600
|
+
resolve('No files found matching pattern.');
|
|
601
|
+
} else {
|
|
602
|
+
const truncated = files.length > limit;
|
|
603
|
+
const display = files.slice(0, limit);
|
|
604
|
+
const header = `Found ${truncated ? `${files.length}+` : files.length} file${files.length !== 1 ? 's' : ''}`;
|
|
605
|
+
const truncNotice = truncated
|
|
606
|
+
? `\n\n[Showing first ${limit} of ${files.length}+ results. Refine pattern or increase limit.]`
|
|
607
|
+
: '';
|
|
608
|
+
resolve(`${header}${truncNotice}\n\n${display.join('\n')}`);
|
|
609
|
+
}
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
proc.on('error', (err) => {
|
|
613
|
+
if (err.message.includes('ENOENT')) {
|
|
614
|
+
// No ripgrep — fall back to the pure-JS glob walker.
|
|
615
|
+
globJS({
|
|
616
|
+
pattern: String(args.pattern),
|
|
617
|
+
path: searchPath,
|
|
618
|
+
limit,
|
|
619
|
+
isIgnored: ignorePredicate(config),
|
|
620
|
+
})
|
|
621
|
+
.then(resolve)
|
|
622
|
+
.catch((e) => resolve(`Search error: ${e instanceof Error ? e.message : String(e)}`));
|
|
623
|
+
} else {
|
|
624
|
+
resolve(`Error running ripgrep: ${err.message}`);
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
});
|
|
628
|
+
},
|
|
629
|
+
|
|
630
|
+
async ast_grep(args, config) {
|
|
631
|
+
const {readFile: rf} = await import('fs/promises');
|
|
632
|
+
const pattern = String(args.pattern ?? '');
|
|
633
|
+
const filePath = String(args.path ?? '');
|
|
634
|
+
const lang = String(args.language ?? 'typescript');
|
|
635
|
+
|
|
636
|
+
if (!pattern) return 'Error: pattern is required';
|
|
637
|
+
if (!filePath) return 'Error: path is required';
|
|
638
|
+
|
|
639
|
+
// Enforce ignore patterns and file size limits — matches every other
|
|
640
|
+
// file-touching tool. Without this, ast_grep could read node_modules,
|
|
641
|
+
// .env, or any other file the user intended to exclude.
|
|
642
|
+
if (isPathIgnored(filePath, config)) {
|
|
643
|
+
return `(ignored — ${filePath} matches ignore patterns in .pal.json)`;
|
|
644
|
+
}
|
|
645
|
+
const sizeError = checkFileSize(filePath, config);
|
|
646
|
+
if (sizeError) return sizeError;
|
|
647
|
+
|
|
648
|
+
let fileContent: string;
|
|
649
|
+
try {
|
|
650
|
+
fileContent = await rf(filePath, 'utf-8');
|
|
651
|
+
} catch (err) {
|
|
652
|
+
return `Error reading file: ${err instanceof Error ? err.message : String(err)}`;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// Try AST-grep first, fall back to regex
|
|
656
|
+
try {
|
|
657
|
+
const sg = await import('@ast-grep/napi');
|
|
658
|
+
const LangMap: Record<string, (typeof sg.Lang)[keyof typeof sg.Lang]> = {
|
|
659
|
+
typescript: sg.Lang.TypeScript,
|
|
660
|
+
javascript: sg.Lang.JavaScript,
|
|
661
|
+
tsx: sg.Lang.Tsx,
|
|
662
|
+
jsx: sg.Lang.Tsx,
|
|
663
|
+
html: sg.Lang.Html,
|
|
664
|
+
css: sg.Lang.Css,
|
|
665
|
+
};
|
|
666
|
+
const LangChoice = LangMap[lang] ?? sg.Lang.TypeScript;
|
|
667
|
+
const root = sg.parse(LangChoice, fileContent);
|
|
668
|
+
const matches = root.root().findAll(pattern);
|
|
669
|
+
|
|
670
|
+
if (matches.length === 0) return 'No matches found.';
|
|
671
|
+
|
|
672
|
+
const results = matches.slice(0, 50).map((m: any) => {
|
|
673
|
+
const range = m.range();
|
|
674
|
+
return {
|
|
675
|
+
text: m.text(),
|
|
676
|
+
startLine: range.start.line + 1,
|
|
677
|
+
startCol: range.start.column + 1,
|
|
678
|
+
endLine: range.end.line + 1,
|
|
679
|
+
endCol: range.end.column + 1,
|
|
680
|
+
};
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
const lines = results.map(
|
|
684
|
+
(r: any) => ` Line ${r.startLine}:${r.startCol}-${r.endLine}:${r.endCol}:\n ${r.text}`,
|
|
685
|
+
);
|
|
686
|
+
|
|
687
|
+
const header = `Found ${matches.length} match${matches.length !== 1 ? 'es' : ''}`;
|
|
688
|
+
const trunc =
|
|
689
|
+
matches.length > 50 ? `\n\n[Showing first 50 of ${matches.length} matches]` : '';
|
|
690
|
+
return `${header}${trunc}\n\n${filePath}:\n${lines.join('\n\n')}`;
|
|
691
|
+
} catch (importErr) {
|
|
692
|
+
// @ast-grep/napi import failed — use regex fallback
|
|
693
|
+
return regexFallback(pattern, fileContent, filePath);
|
|
694
|
+
}
|
|
695
|
+
},
|
|
696
|
+
|
|
697
|
+
async repo_map(args, config) {
|
|
698
|
+
const dir = String(args.path ?? process.cwd());
|
|
699
|
+
const maxTokens = Number(args.max_tokens ?? 1000);
|
|
700
|
+
const {buildRepoMap} = await import('../repo-map.js');
|
|
701
|
+
return buildRepoMap(dir, maxTokens, ignorePredicate(config));
|
|
702
|
+
},
|
|
703
|
+
|
|
704
|
+
async recall_history(args, _config) {
|
|
705
|
+
if (!historyProvider) {
|
|
706
|
+
return 'No session history is available in this context (no active session store).';
|
|
707
|
+
}
|
|
708
|
+
const limit = Math.min(Math.max(Number(args.limit ?? 20) || 20, 1), RECALL_MAX_LIMIT);
|
|
709
|
+
const offset = Math.max(Number(args.offset ?? 0) || 0, 0);
|
|
710
|
+
|
|
711
|
+
const rows = historyProvider.read();
|
|
712
|
+
const mark = historyProvider.mark();
|
|
713
|
+
// Only the summarized prefix is recallable: everything at or past the
|
|
714
|
+
// high-water mark is still in the model's context, so re-sending it would
|
|
715
|
+
// duplicate tokens and waste the budget.
|
|
716
|
+
const prefix = rows.filter((m) => m.seq <= mark);
|
|
717
|
+
if (prefix.length === 0) {
|
|
718
|
+
return 'Nothing has been compacted yet — the full transcript is already in context.';
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const page = prefix.slice(offset, offset + limit);
|
|
722
|
+
if (page.length === 0) {
|
|
723
|
+
return `No messages at offset ${offset} (the summarized prefix holds ${prefix.length} messages).`;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const body = page
|
|
727
|
+
.map((m) => {
|
|
728
|
+
const calls = m.toolCalls?.length
|
|
729
|
+
? `\n[tool calls: ${m.toolCalls.map((c) => c.name).join(', ')}]`
|
|
730
|
+
: '';
|
|
731
|
+
const text = m.content?.trim() ? m.content.trim() : '(no text)';
|
|
732
|
+
return `<seq ${m.seq} | ${m.role}>\n${text}${calls}`;
|
|
733
|
+
})
|
|
734
|
+
.join('\n\n');
|
|
735
|
+
|
|
736
|
+
const end = offset + page.length;
|
|
737
|
+
const more =
|
|
738
|
+
end < prefix.length
|
|
739
|
+
? `\n\n... (${prefix.length - end} more recalled messages, use offset=${end})`
|
|
740
|
+
: '';
|
|
741
|
+
|
|
742
|
+
return `Recalled ${page.length} of ${prefix.length} summarized messages:\n\n${body}${more}`;
|
|
743
|
+
},
|
|
744
|
+
};
|
|
745
|
+
|
|
746
|
+
// ── recall_history plumbing ──
|
|
747
|
+
//
|
|
748
|
+
// The session store lives in the CLI layer, and core must not import it (that
|
|
749
|
+
// would invert the dependency). The CLI installs a reader here at startup, so
|
|
750
|
+
// the tool stays available to every agent — including delegated children, which
|
|
751
|
+
// hit the same summarized prefix but have no store of their own.
|
|
752
|
+
let historyProvider: {read: () => RecallableRow[]; mark: () => number} | null = null;
|
|
753
|
+
|
|
754
|
+
/** Max messages a single recall may return. */
|
|
755
|
+
const RECALL_MAX_LIMIT = 100;
|
|
756
|
+
|
|
757
|
+
export interface RecallableRow {
|
|
758
|
+
seq: number;
|
|
759
|
+
role: string;
|
|
760
|
+
content: string;
|
|
761
|
+
toolCalls?: Array<{name: string}>;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Install the transcript reader used by `recall_history`.
|
|
766
|
+
*
|
|
767
|
+
* `read` returns the session's messages in seq order; `mark` returns the
|
|
768
|
+
* high-water seq below which messages have been summarized away.
|
|
769
|
+
*/
|
|
770
|
+
export function registerHistoryProvider(provider: {
|
|
771
|
+
read: () => RecallableRow[];
|
|
772
|
+
mark: () => number;
|
|
773
|
+
}): void {
|
|
774
|
+
historyProvider = provider;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Regex fallback for AST-grep pattern matching.
|
|
779
|
+
* Converts simple AST patterns to regex and searches line by line.
|
|
780
|
+
* Returns results in the same format as the AST-grep path, prefixed with "[regex fallback]".
|
|
781
|
+
*/
|
|
782
|
+
export function regexFallback(pattern: string, content: string, filePath: string): string {
|
|
783
|
+
const lines = content.split('\n');
|
|
784
|
+
const matches: Array<{line: number; text: string; startCol: number; endCol: number}> = [];
|
|
785
|
+
|
|
786
|
+
// Convert AST pattern to regex
|
|
787
|
+
const regexStr = convertPatternToRegex(pattern);
|
|
788
|
+
|
|
789
|
+
if (!regexStr) {
|
|
790
|
+
return `Error: Could not convert pattern to regex. Pattern: ${pattern}`;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const regex = new RegExp(regexStr, 'g');
|
|
794
|
+
|
|
795
|
+
for (let i = 0; i < lines.length; i++) {
|
|
796
|
+
const line = lines[i];
|
|
797
|
+
regex.lastIndex = 0; // reset for each new line (g-flag regex carries state)
|
|
798
|
+
let match;
|
|
799
|
+
while ((match = regex.exec(line)) !== null) {
|
|
800
|
+
const startCol = match.index;
|
|
801
|
+
const endCol = match.index + match[0].length;
|
|
802
|
+
matches.push({
|
|
803
|
+
line: i + 1,
|
|
804
|
+
text: match[0],
|
|
805
|
+
startCol,
|
|
806
|
+
endCol,
|
|
807
|
+
});
|
|
808
|
+
// Move past this match (guard against zero-length matches — a bare
|
|
809
|
+
// `$$$` pattern expands to `.*?` which can match empty and would
|
|
810
|
+
// otherwise loop forever with the `g` flag)
|
|
811
|
+
regex.lastIndex = match[0].length === 0 ? endCol + 1 : endCol;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
if (matches.length === 0) return 'No matches found.';
|
|
816
|
+
|
|
817
|
+
const results = matches
|
|
818
|
+
.slice(0, 50)
|
|
819
|
+
.map((m) => ` Line ${m.line}:${m.startCol}-${m.endCol}:\n ${m.text}`);
|
|
820
|
+
|
|
821
|
+
const header = `Found ${matches.length} match${matches.length !== 1 ? 'es' : ''} [regex fallback]`;
|
|
822
|
+
const trunc = matches.length > 50 ? `\n\n[Showing first 50 of ${matches.length} matches]` : '';
|
|
823
|
+
return `${header}${trunc}\n\n${filePath}:\n${results.join('\n\n')}`;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Converts a simple AST pattern to a regex string.
|
|
828
|
+
* Handles $A, $NAME, $VAR, $EXPR, $$$ placeholders.
|
|
829
|
+
* Returns null for patterns with unknown meta-variables or invalid regex.
|
|
830
|
+
*/
|
|
831
|
+
export function convertPatternToRegex(pattern: string): string | null {
|
|
832
|
+
// Bare $$$ = "match the whole structure" — a lone `.*?` would match empty
|
|
833
|
+
// strings at every position, so use `.+` (the whole line) instead.
|
|
834
|
+
if (pattern.trim() === '$$$') return '.+';
|
|
835
|
+
|
|
836
|
+
// Detect unknown meta-variables ($XXX) — return null so caller can error helpfully
|
|
837
|
+
const unknownMeta = pattern.match(/\$[A-Z_][A-Z0-9_]*/g);
|
|
838
|
+
if (unknownMeta) {
|
|
839
|
+
const known = new Set(['$A', '$NAME', '$VAR', '$EXPR', '$$$']);
|
|
840
|
+
for (const m of unknownMeta) {
|
|
841
|
+
if (!known.has(m)) return null;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
// Split into literal parts and meta-variables
|
|
846
|
+
const parts = pattern.split(/(\$A|\$\$\$|\$NAME|\$VAR|\$EXPR)/);
|
|
847
|
+
|
|
848
|
+
let result = '';
|
|
849
|
+
for (const part of parts) {
|
|
850
|
+
if (part === '$A') {
|
|
851
|
+
result += '(.+?)';
|
|
852
|
+
} else if (part === '$$$') {
|
|
853
|
+
result += '.*?';
|
|
854
|
+
} else if (part === '$NAME') {
|
|
855
|
+
result += '\\w+';
|
|
856
|
+
} else if (part === '$VAR') {
|
|
857
|
+
result += '\\w+';
|
|
858
|
+
} else if (part === '$EXPR') {
|
|
859
|
+
result += '.+';
|
|
860
|
+
} else if (part) {
|
|
861
|
+
result += escapeLiteral(part);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// If the result looks invalid, return null
|
|
866
|
+
try {
|
|
867
|
+
new RegExp(result);
|
|
868
|
+
return result;
|
|
869
|
+
} catch {
|
|
870
|
+
return null;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/**
|
|
875
|
+
* Escapes literal pattern text into regex, converting whitespace runs:
|
|
876
|
+
* - Whitespace before/after `=` becomes `\s*` (optional)
|
|
877
|
+
* - Other whitespace runs become `\s+`
|
|
878
|
+
* - Regex special chars are escaped
|
|
879
|
+
*/
|
|
880
|
+
function escapeLiteral(text: string): string {
|
|
881
|
+
let result = '';
|
|
882
|
+
for (let i = 0; i < text.length; i++) {
|
|
883
|
+
const ch = text[i];
|
|
884
|
+
if (/\s/.test(ch)) {
|
|
885
|
+
// Whitespace run — check neighbors for `=`
|
|
886
|
+
let j = i;
|
|
887
|
+
while (j < text.length && /\s/.test(text[j])) j++;
|
|
888
|
+
const nextChar = text[j];
|
|
889
|
+
const prevChar = text[i - 1];
|
|
890
|
+
if (nextChar === '=' || prevChar === '=') {
|
|
891
|
+
result += '\\s*';
|
|
892
|
+
} else {
|
|
893
|
+
result += '\\s+';
|
|
894
|
+
}
|
|
895
|
+
i = j - 1;
|
|
896
|
+
} else if (/[.*+?^${}()|[\]\\]/.test(ch)) {
|
|
897
|
+
result += '\\' + ch;
|
|
898
|
+
} else {
|
|
899
|
+
result += ch;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
return result;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* Execute a tool call and return the result.
|
|
907
|
+
*
|
|
908
|
+
* @param providerConfigOverride — Optional provider config override (used by CLI
|
|
909
|
+
* to pass model/key to delegate's child agent loop). When provided, it is
|
|
910
|
+
* merged into the ToolConfig so delegate tools can create their own provider.
|
|
911
|
+
*/
|
|
912
|
+
export async function executeTool(
|
|
913
|
+
name: string,
|
|
914
|
+
argsStr: string,
|
|
915
|
+
toolCallId: string,
|
|
916
|
+
providerConfigOverride?: {
|
|
917
|
+
model: string;
|
|
918
|
+
apiKey: string;
|
|
919
|
+
baseUrl: string;
|
|
920
|
+
keys?: Record<string, string>;
|
|
921
|
+
readOnly?: boolean;
|
|
922
|
+
allowedTools?: string[];
|
|
923
|
+
},
|
|
924
|
+
): Promise<ToolResult> {
|
|
925
|
+
const fn = tools[name] ?? extensionHandlers[name];
|
|
926
|
+
if (!fn) {
|
|
927
|
+
const allTools = [...Object.keys(tools), ...Object.keys(extensionHandlers)];
|
|
928
|
+
return {
|
|
929
|
+
toolCallId,
|
|
930
|
+
content: `Unknown tool: ${name}. Available tools: ${allTools.join(', ')}`,
|
|
931
|
+
error: true,
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// ── Permission gate ──
|
|
936
|
+
// Omitting a tool from the definitions the model receives is *advisory*: a
|
|
937
|
+
// model can still emit a call for a tool it was never offered (hallucination,
|
|
938
|
+
// or prompt injection via fetched content). A restricted primary must be
|
|
939
|
+
// enforced here, where the call is actually dispatched.
|
|
940
|
+
const allow = providerConfigOverride?.allowedTools;
|
|
941
|
+
if (allow && !allow.includes(name)) {
|
|
942
|
+
log('tool-denied', {name, reason: 'not in allowlist'});
|
|
943
|
+
return {
|
|
944
|
+
toolCallId,
|
|
945
|
+
content:
|
|
946
|
+
`Error: the "${name}" tool is not available in the current mode. ` +
|
|
947
|
+
`Allowed: ${allow.join(', ')}.`,
|
|
948
|
+
error: true,
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
try {
|
|
953
|
+
const args = (argsStr && argsStr.trim() ? JSON.parse(argsStr) : {}) as Record<string, unknown>;
|
|
954
|
+
const config = loadAgentConfig();
|
|
955
|
+
if (providerConfigOverride) {
|
|
956
|
+
config.provider = providerConfigOverride;
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// ── Path containment guard ──
|
|
960
|
+
// Resolve file-mutating paths against the project root and refuse to write
|
|
961
|
+
// outside it. The ignore-list is a deny-list that fails open for `..`
|
|
962
|
+
// segments; this is the actual containment boundary.
|
|
963
|
+
const PROJECT_ROOT = resolveProjectRoot() ?? process.cwd();
|
|
964
|
+
// Only guard tools that actually write files — bash and recall_history are
|
|
965
|
+
// excluded (bash can trivially escape via shell; recall_history is read-only).
|
|
966
|
+
const FILE_WRITERS = new Set(['write_file', 'edit_file', 'edit_block']);
|
|
967
|
+
if (FILE_WRITERS.has(name) && args.path) {
|
|
968
|
+
const rawPath = String(args.path);
|
|
969
|
+
const resolved = resolve(PROJECT_ROOT, rawPath);
|
|
970
|
+
// Use the platform separator for the prefix check — on Windows resolve()
|
|
971
|
+
// produces backslash paths, so `PROJECT_ROOT + '/'` would never match.
|
|
972
|
+
if (!resolved.startsWith(PROJECT_ROOT + sep) && resolved !== PROJECT_ROOT) {
|
|
973
|
+
return {
|
|
974
|
+
toolCallId,
|
|
975
|
+
content: `Error: path "${rawPath}" resolves outside the project root (${PROJECT_ROOT}). Refusing.`,
|
|
976
|
+
error: true,
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
log('tool-call', {name, args: argsStr});
|
|
982
|
+
const content = await fn(args, config);
|
|
983
|
+
log('tool-result', {name, error: false, length: content.length});
|
|
984
|
+
return {toolCallId, content};
|
|
985
|
+
} catch (err) {
|
|
986
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
987
|
+
log('tool-result', {name, error: true, message: msg});
|
|
988
|
+
return {toolCallId, content: `Error executing ${name}: ${msg}`, error: true};
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
993
|
+
// Delegate — spawn a child agent with a focused task and limited tools.
|
|
994
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
995
|
+
|
|
996
|
+
/** Default read-only toolset for ad-hoc (role-less) delegation. */
|
|
997
|
+
const DEFAULT_CHILD_TOOLS = [
|
|
998
|
+
'read_file',
|
|
999
|
+
'list_directory',
|
|
1000
|
+
'grep_search',
|
|
1001
|
+
'ast_grep',
|
|
1002
|
+
'glob_search',
|
|
1003
|
+
];
|
|
1004
|
+
|
|
1005
|
+
const DEFAULT_CHILD_PROMPT =
|
|
1006
|
+
'You are a sub-agent. Complete the task and return a concise summary of your findings.\n\n' +
|
|
1007
|
+
'Rules:\n- Use the provided tools to gather information\n- Return a clear summary at the end\n- Be thorough but concise';
|
|
1008
|
+
|
|
1009
|
+
/** Cap on child rounds regardless of what a role asks for. */
|
|
1010
|
+
const CHILD_MAX_ROUNDS_CAP = 16;
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* Tools that mutate process-global state — the filesystem, or the shell's cwd.
|
|
1014
|
+
*
|
|
1015
|
+
* Children share this process, so two of these running at once would interleave
|
|
1016
|
+
* their effects. `delegate_parallel` runs any child carrying one of these
|
|
1017
|
+
* strictly one at a time.
|
|
1018
|
+
*
|
|
1019
|
+
* `verify` is included even though it writes no source: it runs the project's
|
|
1020
|
+
* build and test commands in the shared working directory, which is exactly the
|
|
1021
|
+
* kind of cwd-sensitive work that must not overlap.
|
|
1022
|
+
*
|
|
1023
|
+
* NOTE: this list is closed. An extension tool that writes is not classified
|
|
1024
|
+
* here, so it would be scheduled in the parallel phase. Extensions can declare
|
|
1025
|
+
* their own by calling `registerMutatingTools`.
|
|
1026
|
+
*/
|
|
1027
|
+
const MUTATING_TOOLS = new Set(['write_file', 'edit_file', 'edit_block', 'bash', 'verify']);
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* Let an extension declare tools that mutate shared state, so they are
|
|
1031
|
+
* serialized by `delegate_parallel` rather than run concurrently.
|
|
1032
|
+
*/
|
|
1033
|
+
export function registerMutatingTools(names: readonly string[]): void {
|
|
1034
|
+
for (const n of names) MUTATING_TOOLS.add(n);
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/**
|
|
1038
|
+
* Whether a child holding these tools could mutate shared process state.
|
|
1039
|
+
*
|
|
1040
|
+
* Exported so the concurrency-safety rule is directly testable rather than
|
|
1041
|
+
* only reachable through a live delegation.
|
|
1042
|
+
*/
|
|
1043
|
+
export function isMutatingToolset(toolNames: readonly string[]): boolean {
|
|
1044
|
+
return toolNames.some((t) => MUTATING_TOOLS.has(t));
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** A validated child launch request — everything needed to run it. */
|
|
1048
|
+
interface ChildPlan {
|
|
1049
|
+
task: string;
|
|
1050
|
+
/** Role name, when one was resolved (used for the UI label). */
|
|
1051
|
+
roleName?: string;
|
|
1052
|
+
/** Tool names the child may use. */
|
|
1053
|
+
tools: string[];
|
|
1054
|
+
maxRounds: number;
|
|
1055
|
+
reasoning: 'low' | 'medium' | 'high';
|
|
1056
|
+
systemPrompt: string;
|
|
1057
|
+
/** `provider/model` override for this child, if any. */
|
|
1058
|
+
modelSpec?: string;
|
|
1059
|
+
/** True when `tools` contains anything that mutates global state. */
|
|
1060
|
+
mutating: boolean;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
interface SpawnArgs {
|
|
1064
|
+
task: string;
|
|
1065
|
+
agent?: string;
|
|
1066
|
+
category?: string;
|
|
1067
|
+
model?: string;
|
|
1068
|
+
reasoning?: 'low' | 'medium' | 'high';
|
|
1069
|
+
tools?: string[];
|
|
1070
|
+
max_rounds?: number;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* Spawn one child agent, resolving an optional role first.
|
|
1075
|
+
*
|
|
1076
|
+
* Resolution precedence (highest first):
|
|
1077
|
+
* explicit arg > role config > built-in default
|
|
1078
|
+
*
|
|
1079
|
+
* A role's `model` is resolved to its own provider when the parent handed down
|
|
1080
|
+
* the full key set; if that provider has no key we silently fall back to the
|
|
1081
|
+
* parent's model rather than failing the delegation.
|
|
1082
|
+
*/
|
|
1083
|
+
/**
|
|
1084
|
+
* Validate a delegate request and resolve its role into a runnable plan.
|
|
1085
|
+
*
|
|
1086
|
+
* Deliberately free of side effects: `delegate_parallel` plans the whole batch
|
|
1087
|
+
* up front so it can see which children mutate state *before* deciding what may
|
|
1088
|
+
* run concurrently.
|
|
1089
|
+
*
|
|
1090
|
+
* Resolution precedence (highest first):
|
|
1091
|
+
* explicit arg > role config > built-in default
|
|
1092
|
+
*/
|
|
1093
|
+
async function planChild(
|
|
1094
|
+
args: SpawnArgs,
|
|
1095
|
+
config: ToolConfig,
|
|
1096
|
+
): Promise<ChildPlan | {error: string}> {
|
|
1097
|
+
const task = String(args.task ?? '');
|
|
1098
|
+
if (!task) return {error: 'Error: task description is required'};
|
|
1099
|
+
|
|
1100
|
+
if (args.agent && args.category) {
|
|
1101
|
+
return {error: 'Error: pass either `agent` or `category`, not both.'};
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
const {resolveRoleSpec, listRoleSpecs} = await import('../agent/roles.js');
|
|
1105
|
+
|
|
1106
|
+
let role = null;
|
|
1107
|
+
if (args.agent) role = resolveRoleSpec(args.agent, 'agent');
|
|
1108
|
+
else if (args.category) role = resolveRoleSpec(args.category, 'category');
|
|
1109
|
+
|
|
1110
|
+
if ((args.agent || args.category) && !role) {
|
|
1111
|
+
const kind = args.agent ? 'agent' : 'category';
|
|
1112
|
+
const available = listRoleSpecs()
|
|
1113
|
+
.filter((r) => r.kind === kind)
|
|
1114
|
+
.map((r) => r.name);
|
|
1115
|
+
const which = args.agent ? `agent "${args.agent}"` : `category "${args.category}"`;
|
|
1116
|
+
const hint = available.length
|
|
1117
|
+
? `Available: ${available.join(', ')}`
|
|
1118
|
+
: 'No orchestration extension is loaded.';
|
|
1119
|
+
return {error: `Error: unknown ${which}. ${hint}`};
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
const tools = args.tools ?? role?.tools ?? DEFAULT_CHILD_TOOLS;
|
|
1123
|
+
const mutating = isMutatingToolset(tools);
|
|
1124
|
+
|
|
1125
|
+
// A read-only parent (e.g. the `plan` agent) must not reach a writer via
|
|
1126
|
+
// delegation — otherwise the restriction is trivially bypassed.
|
|
1127
|
+
if (mutating && config.provider?.readOnly) {
|
|
1128
|
+
return {
|
|
1129
|
+
error:
|
|
1130
|
+
'Error: this turn is read-only, so it cannot delegate work that would modify files. ' +
|
|
1131
|
+
'Produce the plan instead, then leave plan mode to implement it.',
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
return {
|
|
1136
|
+
task,
|
|
1137
|
+
roleName: role?.name,
|
|
1138
|
+
tools,
|
|
1139
|
+
maxRounds: Math.min(args.max_rounds ?? role?.maxRounds ?? 5, CHILD_MAX_ROUNDS_CAP),
|
|
1140
|
+
reasoning: args.reasoning ?? role?.reasoning ?? 'medium',
|
|
1141
|
+
systemPrompt: role?.systemPrompt ?? DEFAULT_CHILD_PROMPT,
|
|
1142
|
+
modelSpec: args.model ?? role?.model,
|
|
1143
|
+
mutating,
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
/**
|
|
1148
|
+
* Run one planned child agent to completion and return its summary.
|
|
1149
|
+
*
|
|
1150
|
+
* A role's `model` is resolved to its own provider when the parent handed down
|
|
1151
|
+
* the full key set; if that provider has no key we fall back to the parent's
|
|
1152
|
+
* model rather than failing the delegation.
|
|
1153
|
+
*/
|
|
1154
|
+
async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string> {
|
|
1155
|
+
if (!config.provider) {
|
|
1156
|
+
return 'Error: delegate requires provider config (model, apiKey, baseUrl). Only available through the CLI agent loop.';
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
const {task, tools: allowedTools, maxRounds, reasoning, systemPrompt, modelSpec} = plan;
|
|
1160
|
+
|
|
1161
|
+
// ── Resolve the provider/model for the child ──
|
|
1162
|
+
const {createOpenRouterProvider} = await import('../provider/openrouter.js');
|
|
1163
|
+
let provider = createOpenRouterProvider({
|
|
1164
|
+
id: 'delegate',
|
|
1165
|
+
baseUrl: config.provider.baseUrl,
|
|
1166
|
+
apiKey: config.provider.apiKey,
|
|
1167
|
+
});
|
|
1168
|
+
const providerCfg = config.provider;
|
|
1169
|
+
let childModel = providerCfg.model;
|
|
1170
|
+
|
|
1171
|
+
if (modelSpec && providerCfg.keys) {
|
|
1172
|
+
const keys = providerCfg.keys;
|
|
1173
|
+
const {providerForModel} = await import('../provider/registry.js');
|
|
1174
|
+
const {createProviderFor, providerAccessible} = await import('../agent/fallback.js');
|
|
1175
|
+
const {provider: def, model: bare} = providerForModel(modelSpec, Object.keys(keys));
|
|
1176
|
+
if (providerAccessible(def, keys)) {
|
|
1177
|
+
provider = createProviderFor(modelSpec, keys);
|
|
1178
|
+
childModel = bare;
|
|
1179
|
+
}
|
|
1180
|
+
// else: provider unreachable → stay on the parent's model (soft fallback)
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
const agentId = `agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
|
|
1184
|
+
const label = plan.roleName ? `[${plan.roleName}] ` : '';
|
|
1185
|
+
emitAgentEvent({type: 'delegate-start', id: agentId, task: `${label}${task}`.trim()});
|
|
1186
|
+
|
|
1187
|
+
// The child shares this process's module state. Snapshot it so a child that
|
|
1188
|
+
// calls `todo` or `cd`s cannot clobber the parent's plan or cwd.
|
|
1189
|
+
const {captureRunScope, restoreRunScope} = await import('../agent/scope.js');
|
|
1190
|
+
const scope = captureRunScope();
|
|
1191
|
+
|
|
1192
|
+
const childMessages: ConversationMessage[] = [{role: 'user', content: task}];
|
|
1193
|
+
|
|
1194
|
+
// Build the child's toolset from *all* tools — core plus extensions. A role
|
|
1195
|
+
// like `librarian` declares only extension tools (fetch_url, web_search); if
|
|
1196
|
+
// we filtered CORE_TOOLS alone the child would spawn with nothing usable.
|
|
1197
|
+
const {getAllTools} = await import('./definitions.js');
|
|
1198
|
+
const childTools = getAllTools().filter((t) => allowedTools.includes(t.function.name));
|
|
1199
|
+
|
|
1200
|
+
// Dynamic import avoids the executor → run → executor import cycle.
|
|
1201
|
+
const {runAgent} = await import('../agent/run.js');
|
|
1202
|
+
|
|
1203
|
+
await provider.init();
|
|
1204
|
+
|
|
1205
|
+
let roundText = '';
|
|
1206
|
+
let previousText = '';
|
|
1207
|
+
|
|
1208
|
+
try {
|
|
1209
|
+
const childExec = providerCfg.childExecuteTool ?? executeTool;
|
|
1210
|
+
for await (const ev of runAgent({
|
|
1211
|
+
messages: childMessages,
|
|
1212
|
+
tools: childTools,
|
|
1213
|
+
provider,
|
|
1214
|
+
model: childModel,
|
|
1215
|
+
systemPrompt,
|
|
1216
|
+
maxRounds,
|
|
1217
|
+
reasoningEffort: reasoning,
|
|
1218
|
+
providerConfig: providerCfg,
|
|
1219
|
+
executeTool: childExec,
|
|
1220
|
+
})) {
|
|
1221
|
+
if (ev.type === 'round-start') {
|
|
1222
|
+
if (roundText) {
|
|
1223
|
+
previousText = roundText;
|
|
1224
|
+
roundText = '';
|
|
1225
|
+
}
|
|
1226
|
+
emitAgentEvent({type: 'delegate-round', id: agentId, round: ev.round});
|
|
1227
|
+
} else if (ev.type === 'text-delta') {
|
|
1228
|
+
roundText += ev.content;
|
|
1229
|
+
} else if (ev.type === 'tool-start') {
|
|
1230
|
+
emitAgentEvent({type: 'delegate-tool', id: agentId, tool: ev.name});
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
} catch (err) {
|
|
1234
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1235
|
+
emitAgentEvent({type: 'delegate-done', id: agentId, summary: msg, error: true});
|
|
1236
|
+
return `Delegate error: ${msg}`;
|
|
1237
|
+
} finally {
|
|
1238
|
+
// Hand the parent's state back, and re-sync the UI (which may have rendered
|
|
1239
|
+
// the child's todo list via todos-updated).
|
|
1240
|
+
restoreRunScope(scope);
|
|
1241
|
+
const {getTodos} = await import('../agent/todos.js');
|
|
1242
|
+
emitAgentEvent({type: 'todos-updated', todos: getTodos()});
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
const summary = roundText.trim() || previousText.trim();
|
|
1246
|
+
const finalSummary = summary || 'Task completed (no summary generated).';
|
|
1247
|
+
emitAgentEvent({type: 'delegate-done', id: agentId, summary: finalSummary});
|
|
1248
|
+
return finalSummary;
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
/** Normalise the raw tool args into the internal SpawnArgs shape. */
|
|
1252
|
+
function toSpawnArgs(raw: Record<string, unknown>): SpawnArgs {
|
|
1253
|
+
return {
|
|
1254
|
+
task: String(raw.task ?? ''),
|
|
1255
|
+
agent: raw.agent ? String(raw.agent) : undefined,
|
|
1256
|
+
category: raw.category ? String(raw.category) : undefined,
|
|
1257
|
+
model: raw.model ? String(raw.model) : undefined,
|
|
1258
|
+
reasoning: raw.reasoning as SpawnArgs['reasoning'],
|
|
1259
|
+
tools: Array.isArray(raw.tools) ? raw.tools.map(String) : undefined,
|
|
1260
|
+
max_rounds: raw.max_rounds !== undefined ? Number(raw.max_rounds) : undefined,
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
/**
|
|
1265
|
+
* `planChild`, but a throw becomes an error result instead of propagating.
|
|
1266
|
+
* Planning performs dynamic imports, so it can fail for reasons unrelated to
|
|
1267
|
+
* the task.
|
|
1268
|
+
*/
|
|
1269
|
+
async function safePlan(args: SpawnArgs, config: ToolConfig): Promise<ChildPlan | {error: string}> {
|
|
1270
|
+
try {
|
|
1271
|
+
return await planChild(args, config);
|
|
1272
|
+
} catch (err) {
|
|
1273
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1274
|
+
return {error: `Delegate error: ${msg}`};
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* Plan and run one child, converting any throw into a result string.
|
|
1280
|
+
*
|
|
1281
|
+
* `executeChild` catches failures *inside* the agent loop, but provider
|
|
1282
|
+
* resolution and `provider.init()` happen before that and can throw (network,
|
|
1283
|
+
* auth, a malformed model spec). In `delegate_parallel` an escaping rejection
|
|
1284
|
+
* would abort the whole `Promise.all` batch — killing results already collected
|
|
1285
|
+
* and skipping every later phase. Children must therefore never throw.
|
|
1286
|
+
*/
|
|
1287
|
+
async function safeChild(args: SpawnArgs, config: ToolConfig): Promise<string> {
|
|
1288
|
+
try {
|
|
1289
|
+
const plan = await planChild(args, config);
|
|
1290
|
+
if ('error' in plan) return plan.error;
|
|
1291
|
+
return await executeChild(plan, config);
|
|
1292
|
+
} catch (err) {
|
|
1293
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1294
|
+
return `Delegate error: ${msg}`;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
tools.delegate = async (args, config) => {
|
|
1299
|
+
return safeChild(toSpawnArgs(args), config);
|
|
1300
|
+
};
|
|
1301
|
+
|
|
1302
|
+
/**
|
|
1303
|
+
* Run several delegates concurrently, bounded by `max_parallel`.
|
|
1304
|
+
*
|
|
1305
|
+
* Concurrency is *safety-gated*, not just rate-gated. Children share this
|
|
1306
|
+
* process, so a batch is split into two phases:
|
|
1307
|
+
*
|
|
1308
|
+
* 1. non-mutating children (the default — read-only agents) run in parallel,
|
|
1309
|
+
* in chunks of `max_parallel`;
|
|
1310
|
+
* 2. mutating children (anything with write_file / edit_file / edit_block /
|
|
1311
|
+
* bash) then run strictly one after another.
|
|
1312
|
+
*
|
|
1313
|
+
* Phases never overlap, so a child that edits files or changes the shell cwd
|
|
1314
|
+
* can't interleave with another. Results come back in input order.
|
|
1315
|
+
*/
|
|
1316
|
+
tools.delegate_parallel = async (args, config) => {
|
|
1317
|
+
const raw = Array.isArray(args.tasks) ? args.tasks : [];
|
|
1318
|
+
if (raw.length === 0) return 'Error: tasks array is required and must not be empty';
|
|
1319
|
+
|
|
1320
|
+
const {getMaxParallel} = await import('../agent/roles.js');
|
|
1321
|
+
const limit = Math.max(1, getMaxParallel());
|
|
1322
|
+
|
|
1323
|
+
const tasks = raw.map((t) => t as Record<string, unknown>);
|
|
1324
|
+
const results: string[] = new Array(tasks.length);
|
|
1325
|
+
|
|
1326
|
+
// Plan everything first — this both validates and tells us what may run in
|
|
1327
|
+
// parallel, so the safety partition is decided before anything starts.
|
|
1328
|
+
const parallel: Array<{index: number; spawn: SpawnArgs}> = [];
|
|
1329
|
+
const serial: Array<{index: number; spawn: SpawnArgs}> = [];
|
|
1330
|
+
|
|
1331
|
+
for (let i = 0; i < tasks.length; i++) {
|
|
1332
|
+
const spawn = toSpawnArgs(tasks[i]);
|
|
1333
|
+
const plan = await safePlan(spawn, config);
|
|
1334
|
+
if ('error' in plan) {
|
|
1335
|
+
results[i] = plan.error;
|
|
1336
|
+
continue;
|
|
1337
|
+
}
|
|
1338
|
+
(plan.mutating ? serial : parallel).push({index: i, spawn});
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
// Phase 1 — read-only children, in parallel batches. Each runs through
|
|
1342
|
+
// `safeChild`, so one failure cannot abort the batch or skip phase 2.
|
|
1343
|
+
for (let i = 0; i < parallel.length; i += limit) {
|
|
1344
|
+
const batch = parallel.slice(i, i + limit);
|
|
1345
|
+
const settled = await Promise.all(batch.map(({spawn}) => safeChild(spawn, config)));
|
|
1346
|
+
settled.forEach((r, j) => {
|
|
1347
|
+
results[batch[j].index] = r;
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
// Phase 2 — mutating children, one at a time.
|
|
1352
|
+
for (const {index, spawn} of serial) {
|
|
1353
|
+
results[index] = await safeChild(spawn, config);
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
return results
|
|
1357
|
+
.map((r, i) => {
|
|
1358
|
+
const t = tasks[i];
|
|
1359
|
+
const label = t.agent ?? t.category ?? `task ${i + 1}`;
|
|
1360
|
+
return `## [${label}]\n${r}`;
|
|
1361
|
+
})
|
|
1362
|
+
.join('\n\n');
|
|
1363
|
+
};
|