@pal-code/core 0.0.15 → 0.0.16
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/package.json +1 -1
- package/src/agent/frontmatter.ts +7 -2
- package/src/agent/run.ts +7 -7
- package/src/compaction.ts +1 -1
- package/src/config.ts +22 -10
- package/src/extensions.ts +420 -21
- package/src/index.ts +7 -1
- package/src/lifecycle.ts +1 -1
- package/src/provider/complete.ts +20 -1
- package/src/tools/definitions.ts +16 -7
- package/src/tools/executor.ts +15 -15
package/package.json
CHANGED
package/src/agent/frontmatter.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import {readdirSync} from 'fs';
|
|
13
13
|
import {join} from 'path';
|
|
14
|
+
import {TOOL_NAME_ALIASES} from '../tools/definitions.js';
|
|
14
15
|
|
|
15
16
|
export interface Frontmatter {
|
|
16
17
|
/** Keys from the frontmatter block; values are unquoted strings. */
|
|
@@ -94,12 +95,16 @@ export function parseToolsValue(value: string): string[] | null {
|
|
|
94
95
|
} catch {
|
|
95
96
|
return null;
|
|
96
97
|
}
|
|
97
|
-
return isStringArray(parsed) ? parsed : null;
|
|
98
|
+
return isStringArray(parsed) ? normalizeToolNames(parsed) : null;
|
|
98
99
|
}
|
|
99
100
|
|
|
100
101
|
const names = trimmed
|
|
101
102
|
.split(',')
|
|
102
103
|
.map((v) => unquote(v.trim()))
|
|
103
104
|
.filter((v) => v !== '');
|
|
104
|
-
return names.length > 0 ? names : null;
|
|
105
|
+
return names.length > 0 ? normalizeToolNames(names) : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function normalizeToolNames(names: string[]): string[] {
|
|
109
|
+
return names.map((n) => TOOL_NAME_ALIASES[n] ?? n);
|
|
105
110
|
}
|
package/src/agent/run.ts
CHANGED
|
@@ -219,11 +219,11 @@ Response must include:
|
|
|
219
219
|
|
|
220
220
|
/** Tools that only read — safe to run concurrently. */
|
|
221
221
|
const PARALLEL_SAFE = new Set([
|
|
222
|
-
'
|
|
223
|
-
'
|
|
222
|
+
'read',
|
|
223
|
+
'ls',
|
|
224
224
|
'grep',
|
|
225
225
|
'grep_search',
|
|
226
|
-
'
|
|
226
|
+
'glob',
|
|
227
227
|
'ast_grep',
|
|
228
228
|
'repo_map',
|
|
229
229
|
]);
|
|
@@ -243,9 +243,9 @@ function truncate(text: string, max: number): string {
|
|
|
243
243
|
export function summarizeArgs(name: string, args: Record<string, unknown>): string {
|
|
244
244
|
const v = (key: string) => String(args[key] ?? '');
|
|
245
245
|
switch (name) {
|
|
246
|
-
case '
|
|
247
|
-
case '
|
|
248
|
-
case '
|
|
246
|
+
case 'read':
|
|
247
|
+
case 'write':
|
|
248
|
+
case 'edit': {
|
|
249
249
|
const fp = v('path') || v('file') || v('file_path') || v('filePath');
|
|
250
250
|
return fp.split(/[/\\]/).pop() || truncate(fp, 40);
|
|
251
251
|
}
|
|
@@ -253,7 +253,7 @@ export function summarizeArgs(name: string, args: Record<string, unknown>): stri
|
|
|
253
253
|
return truncate(v('command') || v('cmd'), 40);
|
|
254
254
|
case 'grep':
|
|
255
255
|
return v('pattern') || v('query') || truncate(v('regex'), 40);
|
|
256
|
-
case '
|
|
256
|
+
case 'ls':
|
|
257
257
|
return v('path') || v('directory');
|
|
258
258
|
case 'glob':
|
|
259
259
|
return v('pattern') || v('glob');
|
package/src/compaction.ts
CHANGED
|
@@ -22,7 +22,7 @@ export function estimateTokens(text: string): number {
|
|
|
22
22
|
export function estimateMessagesTokens(messages: CompactableMessage[]): number {
|
|
23
23
|
return messages.reduce((sum, m) => {
|
|
24
24
|
let tokens = estimateTokens(m.content || '') + 4;
|
|
25
|
-
// Count tool-call arguments — a transcript dominated by large
|
|
25
|
+
// Count tool-call arguments — a transcript dominated by large write
|
|
26
26
|
// bodies or long bash commands would otherwise under-count massively.
|
|
27
27
|
if (m.toolCalls) {
|
|
28
28
|
for (const tc of m.toolCalls) {
|
package/src/config.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import {readFileSync, statSync} from 'fs';
|
|
10
10
|
import {resolve, relative, isAbsolute, basename} from 'path';
|
|
11
11
|
import {minimatch} from 'minimatch';
|
|
12
|
+
import {TOOL_NAME_ALIASES} from './tools/definitions.js';
|
|
12
13
|
|
|
13
14
|
/** Config file schema. */
|
|
14
15
|
export interface ToolConfig {
|
|
@@ -16,9 +17,9 @@ export interface ToolConfig {
|
|
|
16
17
|
ignore: string[];
|
|
17
18
|
/** Whether to skip files larger than maxFileSizeKB. */
|
|
18
19
|
ignoreLargeFiles: boolean;
|
|
19
|
-
/** Max file size in KB for
|
|
20
|
+
/** Max file size in KB for read (default: 512). */
|
|
20
21
|
maxFileSizeKB: number;
|
|
21
|
-
/** Max lines to return from
|
|
22
|
+
/** Max lines to return from read (default: 2000). */
|
|
22
23
|
readLineLimit: number;
|
|
23
24
|
/** Provider config for delegate tool — set by CLI to pass model/key to child agents. */
|
|
24
25
|
provider?: {
|
|
@@ -127,15 +128,15 @@ export const BUILTIN_SENSITIVE_RULES: PermissionRule[] = [
|
|
|
127
128
|
|
|
128
129
|
/** Built-in default actions per tool. */
|
|
129
130
|
export const BUILTIN_PERMISSION_DEFAULTS: Record<string, 'allow' | 'ask' | 'deny'> = {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
131
|
+
read: 'allow',
|
|
132
|
+
write: 'allow',
|
|
133
|
+
edit: 'allow',
|
|
133
134
|
edit_block: 'allow',
|
|
134
135
|
bash: 'allow',
|
|
135
|
-
|
|
136
|
+
ls: 'allow',
|
|
136
137
|
grep: 'allow',
|
|
137
138
|
grep_search: 'allow',
|
|
138
|
-
|
|
139
|
+
glob: 'allow',
|
|
139
140
|
ast_grep: 'allow',
|
|
140
141
|
repo_map: 'allow',
|
|
141
142
|
delegate: 'allow',
|
|
@@ -215,12 +216,23 @@ export function loadPermissionConfig(cwd?: string): PermissionConfig {
|
|
|
215
216
|
|
|
216
217
|
// Merge user defaults (override built-in defaults)
|
|
217
218
|
if (parsed.defaults && typeof parsed.defaults === 'object') {
|
|
218
|
-
Object.
|
|
219
|
+
for (const [tool, action] of Object.entries(parsed.defaults)) {
|
|
220
|
+
if (action === 'allow' || action === 'ask' || action === 'deny') {
|
|
221
|
+
config.defaults[TOOL_NAME_ALIASES[tool] ?? tool] = action;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
219
224
|
}
|
|
220
225
|
|
|
221
226
|
// Append user rules (after built-in rules, so built-ins match first)
|
|
222
227
|
if (Array.isArray(parsed.rules)) {
|
|
223
|
-
config.rules.push(
|
|
228
|
+
config.rules.push(
|
|
229
|
+
...parsed.rules.map((rule: PermissionRule) => ({
|
|
230
|
+
...rule,
|
|
231
|
+
tool: Array.isArray(rule.tool)
|
|
232
|
+
? rule.tool.map((t) => TOOL_NAME_ALIASES[t] ?? t)
|
|
233
|
+
: TOOL_NAME_ALIASES[rule.tool] ?? rule.tool,
|
|
234
|
+
})),
|
|
235
|
+
);
|
|
224
236
|
}
|
|
225
237
|
|
|
226
238
|
return config;
|
|
@@ -430,7 +442,7 @@ export function checkFileSize(filePath: string, config: ToolConfig): string | nu
|
|
|
430
442
|
const st = statSync(filePath);
|
|
431
443
|
const sizeKB = st.size / 1024;
|
|
432
444
|
if (sizeKB > config.maxFileSizeKB) {
|
|
433
|
-
return `File too large (${Math.round(sizeKB)}KB > ${config.maxFileSizeKB}KB limit). Use
|
|
445
|
+
return `File too large (${Math.round(sizeKB)}KB > ${config.maxFileSizeKB}KB limit). Use read with offset/limit to read sections.`;
|
|
434
446
|
}
|
|
435
447
|
} catch {
|
|
436
448
|
// File doesn't exist — let the tool handle that error
|
package/src/extensions.ts
CHANGED
|
@@ -28,11 +28,37 @@
|
|
|
28
28
|
* *other* root (or to a stale global install) and the loop stops early — the
|
|
29
29
|
* user's freshly `pal add`-ed extension would never be reached. See
|
|
30
30
|
* `isInsideRoot`.
|
|
31
|
+
*
|
|
32
|
+
* The lookup itself reads each root's `package.json` rather than delegating to
|
|
33
|
+
* `Bun.resolveSync`, because the resolver is unusable from inside a
|
|
34
|
+
* `bun build --compile` binary: it throws for *every* package, since its entry
|
|
35
|
+
* module lives at the virtual `B:\~BUN\root` path with no filesystem context.
|
|
36
|
+
* That made all extensions silently fail in the shipped `pal` binary while the
|
|
37
|
+
* same code worked under `bun run`. See `resolveFromRoot`.
|
|
38
|
+
*
|
|
39
|
+
* ## Loading from the compiled binary
|
|
40
|
+
*
|
|
41
|
+
* Finding the entry is only half of it. Extensions are published as TypeScript
|
|
42
|
+
* *source* and import their own dependencies bare — `@pal-code/core`,
|
|
43
|
+
* `cheerio` — and inside a compiled binary that import fails for the same
|
|
44
|
+
* reason `Bun.resolveSync` does: there is no module to resolve it against. No
|
|
45
|
+
* amount of loader code fixes that, because resolution happens before the
|
|
46
|
+
* call.
|
|
47
|
+
*
|
|
48
|
+
* So in a compiled binary the entry is bundled first (`Bun.build`, with `bun`
|
|
49
|
+
* left external) and the *bundle* is imported. Bundling runs while a real
|
|
50
|
+
* entrypoint still exists, so its whole graph resolves normally. See
|
|
51
|
+
* `importExtension`.
|
|
52
|
+
*
|
|
53
|
+
* The cost is that every extension gets its own copy of core. That is exactly
|
|
54
|
+
* what the `globalThis.__pal_core_registry__` store is for: the only things
|
|
55
|
+
* extensions push *into* core are the role provider and MCP-discovered tools,
|
|
56
|
+
* and both travel through that shared object, so the CLI's copy reads them.
|
|
31
57
|
*/
|
|
32
58
|
|
|
33
|
-
import {realpathSync} from 'node:fs';
|
|
34
|
-
import {homedir} from 'node:os';
|
|
35
|
-
import {isAbsolute, join, relative} from 'node:path';
|
|
59
|
+
import {existsSync, mkdirSync, readFileSync, realpathSync} from 'node:fs';
|
|
60
|
+
import {tmpdir, homedir} from 'node:os';
|
|
61
|
+
import {isAbsolute, join, normalize, relative, dirname} from 'node:path';
|
|
36
62
|
import type {ToolDef} from './tools/definitions.js';
|
|
37
63
|
import {clearExtensionTools} from './tools/definitions.js';
|
|
38
64
|
import type {ToolConfig} from './config.js';
|
|
@@ -87,17 +113,33 @@ export interface LoadExtensionsOptions {
|
|
|
87
113
|
* source is re-imported. Used by `/reload`; never for a normal start.
|
|
88
114
|
*/
|
|
89
115
|
cacheBust?: boolean;
|
|
116
|
+
/**
|
|
117
|
+
* Force the compiled-binary bundling path regardless of how pal itself was
|
|
118
|
+
* started. Off in production — it is `true` only under `bun test`, where the
|
|
119
|
+
* binary-detection below can never fire (the runner's `Bun.main` is a test
|
|
120
|
+
* file on disk) but the code being tested is exactly the code that would run
|
|
121
|
+
* there.
|
|
122
|
+
*/
|
|
123
|
+
forceBundle?: boolean;
|
|
90
124
|
}
|
|
91
125
|
|
|
92
126
|
/**
|
|
93
127
|
* Where extensions are looked for, in order:
|
|
94
|
-
* 1.
|
|
95
|
-
* 2. `~/.pal
|
|
96
|
-
* 3.
|
|
128
|
+
* 1. `~/.pal/extensions` (user-installed, node_modules layout)
|
|
129
|
+
* 2. `~/.pal` (user-installed, flat layout)
|
|
130
|
+
* 3. the project's own node_modules (workspace/hoisted packages)
|
|
131
|
+
*
|
|
132
|
+
* Installed copies deliberately come *before* the project root. `cwd` used to
|
|
133
|
+
* be first, which meant running `pal` from inside a checkout of pal's own repo
|
|
134
|
+
* resolved `@pal-code/*` to that working tree instead of the user's installed
|
|
135
|
+
* extensions — a stale checkout silently shadowed a current install. Ranking
|
|
136
|
+
* the home roots higher keeps a project-local extension working as a fallback
|
|
137
|
+
* without letting one hijack the user's set.
|
|
97
138
|
*/
|
|
98
139
|
export function defaultExtensionRoots(): string[] {
|
|
99
140
|
const home = safeHomedir();
|
|
100
|
-
|
|
141
|
+
const homeRoots = home ? [join(home, '.pal', 'extensions'), join(home, '.pal')] : [];
|
|
142
|
+
return [...homeRoots, process.cwd()];
|
|
101
143
|
}
|
|
102
144
|
|
|
103
145
|
/**
|
|
@@ -105,9 +147,8 @@ export function defaultExtensionRoots(): string[] {
|
|
|
105
147
|
*
|
|
106
148
|
* Path-like specifiers are left alone (the caller is pointing at a file).
|
|
107
149
|
* Package names are resolved from each root in turn; a root counts as a match
|
|
108
|
-
* only if the
|
|
109
|
-
*
|
|
110
|
-
* NODE_PATH-visible packages).
|
|
150
|
+
* only if the entry really sits inside it. If no root matches we return the bare
|
|
151
|
+
* name so a plain `import()` still gets a chance (globally installed packages).
|
|
111
152
|
*
|
|
112
153
|
* Exported so the CLI can resolve an extension the same way `loadExtensions`
|
|
113
154
|
* does. A bare `import('@pal-code/mcp')` only searches the CLI's own
|
|
@@ -121,19 +162,100 @@ export function resolveExtensionSpecifier(
|
|
|
121
162
|
if (isPathLike(pkg)) return pkg;
|
|
122
163
|
|
|
123
164
|
for (const root of roots) {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
// Only accept a hit that really belongs to this root: resolveSync also
|
|
127
|
-
// searches ancestor node_modules and Bun's global cache, which would
|
|
128
|
-
// otherwise mask a later, more specific root.
|
|
129
|
-
if (isInsideRoot(root, resolved)) return resolved;
|
|
130
|
-
} catch {
|
|
131
|
-
// Not resolvable from this root — try the next.
|
|
132
|
-
}
|
|
165
|
+
const resolved = resolveFromRoot(pkg, root);
|
|
166
|
+
if (resolved) return resolved;
|
|
133
167
|
}
|
|
134
168
|
return pkg;
|
|
135
169
|
}
|
|
136
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Resolve `pkg` strictly within a single root, or undefined if this root does
|
|
173
|
+
* not contain it.
|
|
174
|
+
*
|
|
175
|
+
* Deliberately does not rely on `Bun.resolveSync(pkg, root)` alone: inside a
|
|
176
|
+
* `bun build --compile` binary the resolver has no filesystem context for the
|
|
177
|
+
* virtual `B:\~BUN\root` entry module, so it reports
|
|
178
|
+
* `Cannot find package '@pal-code/mcp' imported from B:\~BUN\root\pal.exe` for
|
|
179
|
+
* *every* package — including ones physically present in the root's own
|
|
180
|
+
* `node_modules`. That killed every extension in the shipped binary while the
|
|
181
|
+
* same code worked under `bun run`, which is exactly the "works in dev,
|
|
182
|
+
* silently empty once installed" failure this guards against.
|
|
183
|
+
*
|
|
184
|
+
* `Bun.resolveSync` is still consulted as a second chance, because it applies
|
|
185
|
+
* `exports` maps (subpath conditions, `import` vs `require`) more faithfully
|
|
186
|
+
* than the manual walk. It is trusted only when the answer lands inside this
|
|
187
|
+
* root, so its upward walk and global cache cannot leak a foreign copy.
|
|
188
|
+
*/
|
|
189
|
+
function resolveFromRoot(pkg: string, root: string): string | undefined {
|
|
190
|
+
const direct = readPackageEntry(pkg, root);
|
|
191
|
+
if (direct) return direct;
|
|
192
|
+
|
|
193
|
+
try {
|
|
194
|
+
const resolved = Bun.resolveSync(pkg, root);
|
|
195
|
+
// Only accept a hit that really belongs to this root: resolveSync also
|
|
196
|
+
// searches ancestor node_modules and Bun's global cache, which would
|
|
197
|
+
// otherwise mask a later, more specific root.
|
|
198
|
+
if (isInsideRoot(root, resolved)) return resolved;
|
|
199
|
+
} catch {
|
|
200
|
+
// Not resolvable from this root — treat as no match and try the next.
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Resolve `<root>/node_modules/<pkg>` to its entry file by reading package.json.
|
|
207
|
+
*
|
|
208
|
+
* Returns undefined when the package is not installed in this root, so the
|
|
209
|
+
* caller can move on. The answer is always inside `root`, which is what makes
|
|
210
|
+
* this plain directory walk trustworthy where the resolver itself is not.
|
|
211
|
+
*
|
|
212
|
+
* Honours `exports`, then `module`/`main`, then the legacy index fallback.
|
|
213
|
+
* Subpath conditions are not distinguished — every extension pal loads is a
|
|
214
|
+
* single default export, so the first string match wins.
|
|
215
|
+
*/
|
|
216
|
+
function readPackageEntry(pkg: string, root: string): string | undefined {
|
|
217
|
+
const pkgDir = join(root, 'node_modules', ...pkg.split('/'));
|
|
218
|
+
const manifest = readJson(join(pkgDir, 'package.json'));
|
|
219
|
+
if (manifest === undefined) return undefined;
|
|
220
|
+
|
|
221
|
+
const candidates: string[] = [];
|
|
222
|
+
const exportsField = manifest.exports;
|
|
223
|
+
if (typeof exportsField === 'string') {
|
|
224
|
+
candidates.push(exportsField);
|
|
225
|
+
} else if (exportsField && typeof exportsField === 'object') {
|
|
226
|
+
const rootExport = (exportsField as Record<string, unknown>)['.'];
|
|
227
|
+
if (typeof rootExport === 'string') {
|
|
228
|
+
candidates.push(rootExport);
|
|
229
|
+
} else if (rootExport && typeof rootExport === 'object') {
|
|
230
|
+
for (const value of Object.values(rootExport as Record<string, unknown>)) {
|
|
231
|
+
if (typeof value === 'string') candidates.push(value);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (typeof manifest.module === 'string') candidates.push(manifest.module);
|
|
236
|
+
if (typeof manifest.main === 'string') candidates.push(manifest.main);
|
|
237
|
+
candidates.push('index.js', 'index.ts');
|
|
238
|
+
|
|
239
|
+
for (const candidate of candidates) {
|
|
240
|
+
const entry = normalize(join(pkgDir, candidate));
|
|
241
|
+
if (isInsideRoot(root, entry) && existsSync(entry)) return entry;
|
|
242
|
+
}
|
|
243
|
+
return undefined;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Parse a JSON object file, or undefined when missing or malformed. */
|
|
247
|
+
function readJson(path: string): Record<string, unknown> | undefined {
|
|
248
|
+
try {
|
|
249
|
+
const parsed = JSON.parse(readFileSync(path, 'utf-8')) as unknown;
|
|
250
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
251
|
+
return parsed as Record<string, unknown>;
|
|
252
|
+
}
|
|
253
|
+
} catch {
|
|
254
|
+
// Missing or malformed manifest — treat the package as absent.
|
|
255
|
+
}
|
|
256
|
+
return undefined;
|
|
257
|
+
}
|
|
258
|
+
|
|
137
259
|
/**
|
|
138
260
|
* True when `target` is `root` itself or lives beneath it.
|
|
139
261
|
*
|
|
@@ -186,6 +308,278 @@ function safeHomedir(): string | undefined {
|
|
|
186
308
|
}
|
|
187
309
|
}
|
|
188
310
|
|
|
311
|
+
/** Where transpiled extension bundles are written. */
|
|
312
|
+
const CACHE_DIR_NAME = '.cache';
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Files copied next to a bundle, e.g. `@ast-grep/napi`'s `.node` binary.
|
|
316
|
+
*
|
|
317
|
+
* `Bun.build` emits native modules as hashed *asset* outputs; only `entry-point`
|
|
318
|
+
* outputs carry JS. Everything else has to land beside the bundle or the first
|
|
319
|
+
* call into it fails with a bare "dlopen failed".
|
|
320
|
+
*/
|
|
321
|
+
const NON_ENTRY_SUFFIXES = ['.node'];
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Load one extension entry, bundling it first when we have to.
|
|
325
|
+
*
|
|
326
|
+
* The split matters:
|
|
327
|
+
*
|
|
328
|
+
* - **not a compiled binary** — plain `import()` already resolves the
|
|
329
|
+
* extension's own dependencies (Bun has a real filesystem context), so
|
|
330
|
+
* bundling would only add work and a second copy of core.
|
|
331
|
+
* - **inside `bun build --compile`** — Bun has no resolution context for the
|
|
332
|
+
* binary's virtual `B:\~BUN\root` entry module, so importing an extension's
|
|
333
|
+
* *source* fails on its first bare import (`Cannot find package
|
|
334
|
+
* '@pal-code/core'`) even when that package is installed right next to it.
|
|
335
|
+
* Nothing the loader can do about `import()` fixes that, because resolution
|
|
336
|
+
* happens before the call. Bundling is the only remaining route: it runs
|
|
337
|
+
* while a real entrypoint still exists on disk, so every dependency resolves.
|
|
338
|
+
*
|
|
339
|
+
* Bundling means each extension gets its **own copy of core**. That is safe
|
|
340
|
+
* precisely because of the `globalThis.__pal_core_registry__` store (see
|
|
341
|
+
* registry.ts): the pieces that cross the boundary — role providers, runtime
|
|
342
|
+
* MCP tools — are written to that shared object, so the CLI's copy reads what
|
|
343
|
+
* the extension registered. Verified in extensions.test.ts.
|
|
344
|
+
*
|
|
345
|
+
* @param specifier Resolved extension entry, absolute path or bare name.
|
|
346
|
+
* @param roots Roots to resolve the entry and its dependencies from.
|
|
347
|
+
* @param cacheBust Append a unique suffix so edited source is re-imported.
|
|
348
|
+
* Bundles are keyed by source digest instead, so this only affects the
|
|
349
|
+
* unbundled path.
|
|
350
|
+
* @param forceBundle Skip compiled-binary detection — see
|
|
351
|
+
* {@link LoadExtensionsOptions.forceBundle}.
|
|
352
|
+
*/
|
|
353
|
+
/**
|
|
354
|
+
* Import an extension's module, bundling first when we have to.
|
|
355
|
+
*
|
|
356
|
+
* Exported because callers that need an extension's *other* exports — the MCP
|
|
357
|
+
* manager, say, for the sidebar — face exactly the same resolution wall as
|
|
358
|
+
* `loadExtensions` does. A bare `import()` there fails in the compiled binary,
|
|
359
|
+
* and reading it as "the MCP extension isn't available" would silently empty the
|
|
360
|
+
* server list.
|
|
361
|
+
*/
|
|
362
|
+
export async function importExtensionModule(
|
|
363
|
+
specifier: string,
|
|
364
|
+
options: LoadExtensionsOptions = {},
|
|
365
|
+
): Promise<unknown> {
|
|
366
|
+
return importExtension(
|
|
367
|
+
specifier,
|
|
368
|
+
options.roots ?? defaultExtensionRoots(),
|
|
369
|
+
Boolean(options.cacheBust),
|
|
370
|
+
Boolean(options.forceBundle),
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async function importExtension(
|
|
375
|
+
specifier: string,
|
|
376
|
+
roots: string[],
|
|
377
|
+
cacheBust: boolean,
|
|
378
|
+
forceBundle: boolean,
|
|
379
|
+
): Promise<unknown> {
|
|
380
|
+
const entry = isPathLike(specifier) ? specifier : resolveExtensionSpecifier(specifier, roots);
|
|
381
|
+
|
|
382
|
+
if (!forceBundle && !needsBundling()) {
|
|
383
|
+
return import(cacheBust ? `${entry}?t=${Date.now()}` : entry);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const dir = await bundleExtension(entry, roots);
|
|
387
|
+
return import(cacheBust ? `${dir}?t=${Date.now()}` : dir);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* True when we are running from a `bun build --compile` binary, where bare
|
|
392
|
+
* specifiers cannot be resolved at runtime.
|
|
393
|
+
*
|
|
394
|
+
* `Bun.main` is the entry module's path: on disk for `bun run` and inside the
|
|
395
|
+
* executable for a compiled one. Distinguishing on it (rather than trusting
|
|
396
|
+
* the caller) keeps the slow path confined to the binary that needs it.
|
|
397
|
+
*/
|
|
398
|
+
function needsBundling(): boolean {
|
|
399
|
+
if (process.versions.bun === undefined) return false;
|
|
400
|
+
return isInsideVirtualBinary(Bun.main);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* True when `main` is the virtual entry path of a compiled binary, not a file.
|
|
405
|
+
*
|
|
406
|
+
* A compiled binary reports `B:/~BUN/root/pal.exe`, and — the reason this cannot
|
|
407
|
+
* just test `existsSync` — that path *does* resolve, because Bun's virtual
|
|
408
|
+
* filesystem maps it onto the running executable. So the `~BUN` segment is what
|
|
409
|
+
* actually identifies a bundle; a real `bun run` entrypoint is never under it.
|
|
410
|
+
*/
|
|
411
|
+
function isInsideVirtualBinary(main: string): boolean {
|
|
412
|
+
return /~BUN[/\\]/.test(main);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** File extension of `path`, lowercased, or `''` when it has none. */
|
|
416
|
+
function extOf(path: string): string {
|
|
417
|
+
const base = path.slice(path.replace(/\\/g, '/').lastIndexOf('/') + 1);
|
|
418
|
+
const dot = base.lastIndexOf('.');
|
|
419
|
+
return dot <= 0 ? '' : base.slice(dot).toLowerCase();
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* `Bun.build` **terminates the process** when it cannot resolve an import: the
|
|
424
|
+
* rejected build prints a diagnostic and exits, so the awaiter never resumes
|
|
425
|
+
* and `loadExtensions` cannot record the failure — one broken extension would
|
|
426
|
+
* take down the whole CLI, contradicting the collect-and-continue contract
|
|
427
|
+
* every caller relies on.
|
|
428
|
+
*
|
|
429
|
+
* So resolution is taken over by this plugin, which lets every failure be
|
|
430
|
+
* reported instead of fatal: an unresolvable specifier is answered with a
|
|
431
|
+
* loadable virtual module that throws at import time, landing in `failed` like
|
|
432
|
+
* any other bad extension.
|
|
433
|
+
*
|
|
434
|
+
* The plugin resolves in two steps. First the roots' `node_modules`, which is
|
|
435
|
+
* where an extension's dependencies actually live. Then Bun's own resolver,
|
|
436
|
+
* hand-fed the *importer's real directory* — because that is the part that
|
|
437
|
+
* works: `Bun.resolveSync` fails inside a compiled binary only when it has to
|
|
438
|
+
* guess a context, and an extension's entry file is a genuine path on disk.
|
|
439
|
+
*
|
|
440
|
+
* Only a genuine miss reaches the throwaway module. Getting that order wrong is
|
|
441
|
+
* fatal: Bun never revisits a specifier it has already failed on, so a
|
|
442
|
+
* first-pass `undefined` cannot be corrected on a second ask.
|
|
443
|
+
*/
|
|
444
|
+
function extensionPlugin(roots: string[]): {name: string; setup: (build: unknown) => void} {
|
|
445
|
+
return {
|
|
446
|
+
name: 'pal-extension-resolver',
|
|
447
|
+
setup(build: unknown) {
|
|
448
|
+
const api = build as {
|
|
449
|
+
onResolve: (
|
|
450
|
+
args: {filter: RegExp; namespace?: string},
|
|
451
|
+
cb: (args: {path: string; importer: string}) =>
|
|
452
|
+
| {
|
|
453
|
+
path: string;
|
|
454
|
+
namespace?: string;
|
|
455
|
+
}
|
|
456
|
+
| undefined,
|
|
457
|
+
) => void;
|
|
458
|
+
onLoad: (
|
|
459
|
+
args: {filter: RegExp; namespace: string},
|
|
460
|
+
cb: (args: {path: string}) => {contents: string; loader: string},
|
|
461
|
+
) => void;
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
// Bare specifiers only: `^.` guards against the filter matching an
|
|
465
|
+
// absolute path like `C:\...\index.ts`, whose `C:` is not `.` or `/`.
|
|
466
|
+
api.onResolve({filter: /^[^./]/}, ({path, importer}) => {
|
|
467
|
+
for (const root of roots) {
|
|
468
|
+
const entry = resolveFromRoot(path, root);
|
|
469
|
+
if (entry) return {path: entry};
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const viaBun = importer ? resolveWithBun(path, importer) : undefined;
|
|
473
|
+
if (viaBun) return {path: viaBun};
|
|
474
|
+
|
|
475
|
+
return {path, namespace: MISSING_NAMESPACE};
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
api.onLoad({filter: /.*/, namespace: MISSING_NAMESPACE}, ({path}) => ({
|
|
479
|
+
contents: `throw new Error(${JSON.stringify(
|
|
480
|
+
`pal: cannot resolve '${path}' from any extension root`,
|
|
481
|
+
)});`,
|
|
482
|
+
loader: 'js',
|
|
483
|
+
}));
|
|
484
|
+
},
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Bun's resolver, pointed at a real directory.
|
|
490
|
+
*
|
|
491
|
+
* `importer` is an extension file that exists on disk, which is what makes
|
|
492
|
+
* this usable from inside a compiled binary at all.
|
|
493
|
+
*/
|
|
494
|
+
function resolveWithBun(specifier: string, importer: string): string | undefined {
|
|
495
|
+
try {
|
|
496
|
+
const resolved = Bun.resolveSync(specifier, dirname(importer));
|
|
497
|
+
return resolved && existsSync(resolved) ? resolved : undefined;
|
|
498
|
+
} catch {
|
|
499
|
+
return undefined;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** Namespace for the throwaway modules described in {@link extensionPlugin}. */
|
|
504
|
+
const MISSING_NAMESPACE = 'pal-unresolved';
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Bundle one extension entry, reporting failure as a returned error rather than
|
|
508
|
+
* a dead process.
|
|
509
|
+
*
|
|
510
|
+
* Bundles are cached by the entry's contents, so a second pal process pays only
|
|
511
|
+
* the import, and `/reload` after an edit rebuilds automatically.
|
|
512
|
+
*
|
|
513
|
+
* `bun` stays external: those are runtime built-ins, resolvable only inside Bun
|
|
514
|
+
* itself, and inlining them would break the very binary this exists for.
|
|
515
|
+
*/
|
|
516
|
+
async function bundleExtension(entry: string, roots: string[]): Promise<string> {
|
|
517
|
+
const outDir = join(extensionCacheRoot(), hash(await Bun.file(entry).arrayBuffer()));
|
|
518
|
+
const outFile = join(outDir, 'extension.mjs');
|
|
519
|
+
|
|
520
|
+
if (!existsSync(outFile)) {
|
|
521
|
+
let result: Awaited<ReturnType<typeof Bun.build>>;
|
|
522
|
+
try {
|
|
523
|
+
result = await Bun.build({
|
|
524
|
+
entrypoints: [entry],
|
|
525
|
+
target: 'bun',
|
|
526
|
+
format: 'esm',
|
|
527
|
+
external: ['bun', 'bun:*'],
|
|
528
|
+
plugins: [extensionPlugin(roots)],
|
|
529
|
+
});
|
|
530
|
+
} catch (err) {
|
|
531
|
+
throw new Error(`bundling failed — ${err instanceof Error ? err.message : String(err)}`);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
if (!result.success) {
|
|
535
|
+
const detail = result.logs.map((log) => log.message).join('; ');
|
|
536
|
+
throw new Error(`bundling failed — ${detail || 'no detail'}`);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const entryOut = result.outputs.find((o) => o.kind === 'entry-point');
|
|
540
|
+
if (!entryOut) throw new Error('bundling failed — no entry point');
|
|
541
|
+
|
|
542
|
+
mkdirSync(outDir, {recursive: true});
|
|
543
|
+
await Bun.write(outFile, entryOut);
|
|
544
|
+
// `Bun.build` emits native modules as hashed *asset* outputs; only
|
|
545
|
+
// `entry-point` outputs carry JS. Everything else has to land beside the
|
|
546
|
+
// bundle or the first call into it fails with a bare "dlopen failed".
|
|
547
|
+
for (const asset of result.outputs) {
|
|
548
|
+
const name = assetPath(asset);
|
|
549
|
+
if (name && NON_ENTRY_SUFFIXES.some((suffix) => name.endsWith(suffix))) {
|
|
550
|
+
await Bun.write(join(outDir, name), asset);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return outFile;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** Bare file name of an output path, or undefined when it has none. */
|
|
559
|
+
function assetPath(output: {path?: string}): string | undefined {
|
|
560
|
+
const p = output.path;
|
|
561
|
+
if (!p) return undefined;
|
|
562
|
+
const name = p.replace(/\\/g, '/').split('/').pop();
|
|
563
|
+
return name && extOf(name) !== '' ? name : undefined;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Directory for cached bundles, beside the extensions that are being loaded.
|
|
568
|
+
*
|
|
569
|
+
* Kept inside the extension root so `pal add`, upgrades and `rm -r` treat it as
|
|
570
|
+
* part of the extension install, and so the path is stable across runs (unlike
|
|
571
|
+
* a temp dir, which would defeat caching).
|
|
572
|
+
*/
|
|
573
|
+
function extensionCacheRoot(): string {
|
|
574
|
+
const base = defaultExtensionRoots()[0];
|
|
575
|
+
return base ? join(base, CACHE_DIR_NAME, 'bundles') : join(tmpdir(), 'pal-ext-bundles');
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** Content hash, as hex. Used to key the bundle cache. */
|
|
579
|
+
function hash(bytes: ArrayBuffer): string {
|
|
580
|
+
return Bun.hash(bytes).toString(16);
|
|
581
|
+
}
|
|
582
|
+
|
|
189
583
|
/**
|
|
190
584
|
* Load extensions from package names.
|
|
191
585
|
*
|
|
@@ -213,8 +607,13 @@ export async function loadExtensions(
|
|
|
213
607
|
for (const pkg of extensionPackages) {
|
|
214
608
|
try {
|
|
215
609
|
const base = resolveExtensionSpecifier(pkg, roots);
|
|
216
|
-
const
|
|
217
|
-
|
|
610
|
+
const mod = (await importExtension(
|
|
611
|
+
base,
|
|
612
|
+
roots,
|
|
613
|
+
Boolean(options.cacheBust),
|
|
614
|
+
Boolean(options.forceBundle),
|
|
615
|
+
)) as {default?: ToolExtension};
|
|
616
|
+
const ext = mod.default;
|
|
218
617
|
|
|
219
618
|
if (!ext || !ext.name || !Array.isArray(ext.tools) || !ext.handlers) {
|
|
220
619
|
failed.push({pkg, reason: 'invalid shape — expected a default ToolExtension'});
|
package/src/index.ts
CHANGED
|
@@ -106,6 +106,7 @@ export type {ToolConfig, PermissionConfig, PermissionRule} from './config.js';
|
|
|
106
106
|
// Tools
|
|
107
107
|
export {
|
|
108
108
|
CORE_TOOLS,
|
|
109
|
+
TOOL_NAME_ALIASES,
|
|
109
110
|
getAllTools,
|
|
110
111
|
registerExtensionTools,
|
|
111
112
|
validateRequiredArgs,
|
|
@@ -124,7 +125,12 @@ export {
|
|
|
124
125
|
export type {ToolResult, RecallableRow} from './tools/executor.js';
|
|
125
126
|
|
|
126
127
|
// Extensions
|
|
127
|
-
export {
|
|
128
|
+
export {
|
|
129
|
+
loadExtensions,
|
|
130
|
+
defaultExtensionRoots,
|
|
131
|
+
resolveExtensionSpecifier,
|
|
132
|
+
importExtensionModule,
|
|
133
|
+
} from './extensions.js';
|
|
128
134
|
export type {
|
|
129
135
|
ToolExtension,
|
|
130
136
|
ToolHandler,
|
package/src/lifecycle.ts
CHANGED
|
@@ -43,7 +43,7 @@ export interface ToolCallEvent {
|
|
|
43
43
|
/** A failure observed while dispatching a tool call. */
|
|
44
44
|
export interface ErrorEvent {
|
|
45
45
|
readonly error: Error;
|
|
46
|
-
/** What was happening when it failed, e.g. `tool:
|
|
46
|
+
/** What was happening when it failed, e.g. `tool:read`. */
|
|
47
47
|
readonly context: string;
|
|
48
48
|
}
|
|
49
49
|
|
package/src/provider/complete.ts
CHANGED
|
@@ -25,6 +25,25 @@ export interface CompleteResult {
|
|
|
25
25
|
usage?: {promptTokens: number; completionTokens: number; cachedTokens?: number};
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
const FREE_TIER_STUB_TOOLS = [
|
|
29
|
+
{
|
|
30
|
+
type: 'function',
|
|
31
|
+
function: {
|
|
32
|
+
name: 'read',
|
|
33
|
+
description: 'Read a file',
|
|
34
|
+
parameters: {type: 'object', properties: {}},
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
type: 'function',
|
|
39
|
+
function: {
|
|
40
|
+
name: 'bash',
|
|
41
|
+
description: 'Run a shell command',
|
|
42
|
+
parameters: {type: 'object', properties: {}},
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
];
|
|
46
|
+
|
|
28
47
|
/**
|
|
29
48
|
* Run a completion to finish and return the concatenated text.
|
|
30
49
|
*
|
|
@@ -42,7 +61,7 @@ export async function complete(
|
|
|
42
61
|
for await (const event of provider.stream({
|
|
43
62
|
model: opts.model,
|
|
44
63
|
messages: opts.messages,
|
|
45
|
-
tools: [],
|
|
64
|
+
tools: /-free$/.test(opts.model) ? FREE_TIER_STUB_TOOLS : [],
|
|
46
65
|
signal: opts.signal,
|
|
47
66
|
...(opts.params ?? {}),
|
|
48
67
|
} as never)) {
|
package/src/tools/definitions.ts
CHANGED
|
@@ -66,7 +66,7 @@ export function getExtensionTools(): ToolDef[] {
|
|
|
66
66
|
* Fail-open by design: an unknown tool is the executor's unknown-tool branch
|
|
67
67
|
* (no schema here to check against), and a schema without `required` has
|
|
68
68
|
* nothing to check. A key present with any value — including `null` — counts
|
|
69
|
-
* as provided; this only catches *absent* keys, e.g. `
|
|
69
|
+
* as provided; this only catches *absent* keys, e.g. `edit` dispatched
|
|
70
70
|
* without `path` (the `ENOENT ... open 'undefined'` failure mode).
|
|
71
71
|
*/
|
|
72
72
|
export function validateRequiredArgs(name: string, args: Record<string, unknown>): string | null {
|
|
@@ -201,7 +201,7 @@ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
|
|
|
201
201
|
type: 'array',
|
|
202
202
|
items: {type: 'string'},
|
|
203
203
|
description:
|
|
204
|
-
'Tool names the child may use. Default: read-only tools (
|
|
204
|
+
'Tool names the child may use. Default: read-only tools (read, ls, grep_search, ast_grep, glob).',
|
|
205
205
|
},
|
|
206
206
|
max_rounds: {
|
|
207
207
|
type: 'number',
|
|
@@ -244,11 +244,20 @@ function buildDelegateParallelTool(roles: RoleSpec[]): ToolDef {
|
|
|
244
244
|
};
|
|
245
245
|
}
|
|
246
246
|
|
|
247
|
+
// Old Zen-era tool names → current names; applied to user-supplied tool lists.
|
|
248
|
+
export const TOOL_NAME_ALIASES: Record<string, string> = {
|
|
249
|
+
read_file: 'read',
|
|
250
|
+
write_file: 'write',
|
|
251
|
+
edit_file: 'edit',
|
|
252
|
+
glob_search: 'glob',
|
|
253
|
+
list_directory: 'ls',
|
|
254
|
+
};
|
|
255
|
+
|
|
247
256
|
export const CORE_TOOLS: ToolDef[] = [
|
|
248
257
|
{
|
|
249
258
|
type: 'function',
|
|
250
259
|
function: {
|
|
251
|
-
name: '
|
|
260
|
+
name: 'read',
|
|
252
261
|
description: 'Read file with line numbers.',
|
|
253
262
|
parameters: {
|
|
254
263
|
type: 'object',
|
|
@@ -264,7 +273,7 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
264
273
|
{
|
|
265
274
|
type: 'function',
|
|
266
275
|
function: {
|
|
267
|
-
name: '
|
|
276
|
+
name: 'write',
|
|
268
277
|
description: 'Create or overwrite file.',
|
|
269
278
|
parameters: {
|
|
270
279
|
type: 'object',
|
|
@@ -279,7 +288,7 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
279
288
|
{
|
|
280
289
|
type: 'function',
|
|
281
290
|
function: {
|
|
282
|
-
name: '
|
|
291
|
+
name: 'edit',
|
|
283
292
|
description:
|
|
284
293
|
'Replace exact string in file; structural pattern+rewrite fallback when exact text unknown.',
|
|
285
294
|
parameters: {
|
|
@@ -339,7 +348,7 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
339
348
|
{
|
|
340
349
|
type: 'function',
|
|
341
350
|
function: {
|
|
342
|
-
name: '
|
|
351
|
+
name: 'ls',
|
|
343
352
|
description: 'List directory contents.',
|
|
344
353
|
parameters: {
|
|
345
354
|
type: 'object',
|
|
@@ -387,7 +396,7 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
387
396
|
{
|
|
388
397
|
type: 'function',
|
|
389
398
|
function: {
|
|
390
|
-
name: '
|
|
399
|
+
name: 'glob',
|
|
391
400
|
description: 'Find files by glob pattern.',
|
|
392
401
|
parameters: {
|
|
393
402
|
type: 'object',
|
package/src/tools/executor.ts
CHANGED
|
@@ -30,7 +30,7 @@ import {validateRequiredArgs} from './definitions.js';
|
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
32
|
* `rg --glob '!pat'` args for each `.pal.json` ignore pattern, so ripgrep
|
|
33
|
-
* honours the same ignores as
|
|
33
|
+
* honours the same ignores as read / ls.
|
|
34
34
|
*/
|
|
35
35
|
function ignoreGlobArgs(config: ToolConfig): string[] {
|
|
36
36
|
return (config.ignore ?? []).flatMap((p) => ['--glob', `!${p}`]);
|
|
@@ -164,7 +164,7 @@ export function registerExtensionHandlers(
|
|
|
164
164
|
}
|
|
165
165
|
|
|
166
166
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
167
|
-
// Structural edit — ast-grep fallback for
|
|
167
|
+
// Structural edit — ast-grep fallback for edit (roadmap #2): locate the
|
|
168
168
|
// node by SHAPE when old_string misses whitespace/format churn, then rebuild
|
|
169
169
|
// it from a rewrite template of $A-style captures. One tool, not a general
|
|
170
170
|
// tree-sitter layer.
|
|
@@ -269,7 +269,7 @@ const tools: Record<
|
|
|
269
269
|
string,
|
|
270
270
|
(args: Record<string, unknown>, config: ToolConfig) => Promise<string>
|
|
271
271
|
> = {
|
|
272
|
-
async
|
|
272
|
+
async read(args, config) {
|
|
273
273
|
const filePath = String(args.path);
|
|
274
274
|
const offset = args.offset ? Number(args.offset) : undefined;
|
|
275
275
|
const limit = args.limit ? Number(args.limit) : undefined;
|
|
@@ -308,7 +308,7 @@ const tools: Record<
|
|
|
308
308
|
return numbered + truncated || '(empty file)';
|
|
309
309
|
},
|
|
310
310
|
|
|
311
|
-
async
|
|
311
|
+
async write(args, config) {
|
|
312
312
|
const filePath = String(args.path);
|
|
313
313
|
const content = String(args.content);
|
|
314
314
|
|
|
@@ -317,12 +317,12 @@ const tools: Record<
|
|
|
317
317
|
}
|
|
318
318
|
|
|
319
319
|
await mkdir(dirname(filePath), {recursive: true});
|
|
320
|
-
snapshotFile(filePath, '
|
|
320
|
+
snapshotFile(filePath, 'write');
|
|
321
321
|
await writeFile(filePath, content, 'utf-8');
|
|
322
322
|
return `Wrote ${content.length} bytes to ${filePath}`;
|
|
323
323
|
},
|
|
324
324
|
|
|
325
|
-
async
|
|
325
|
+
async edit(args, config) {
|
|
326
326
|
const filePath = String(args.path);
|
|
327
327
|
const oldString = String(args.old_string);
|
|
328
328
|
const newString = String(args.new_string);
|
|
@@ -361,7 +361,7 @@ const tools: Record<
|
|
|
361
361
|
throw new Error(stringError);
|
|
362
362
|
}
|
|
363
363
|
|
|
364
|
-
snapshotFile(filePath, '
|
|
364
|
+
snapshotFile(filePath, 'edit');
|
|
365
365
|
await writeFile(filePath, updated, 'utf-8');
|
|
366
366
|
return `Edited ${filePath} successfully`;
|
|
367
367
|
},
|
|
@@ -556,7 +556,7 @@ const tools: Record<
|
|
|
556
556
|
return formatTodos(list);
|
|
557
557
|
},
|
|
558
558
|
|
|
559
|
-
async
|
|
559
|
+
async ls(args, config) {
|
|
560
560
|
const dirPath = String(args.path);
|
|
561
561
|
const pattern = args.pattern ? String(args.pattern) : undefined;
|
|
562
562
|
|
|
@@ -688,7 +688,7 @@ const tools: Record<
|
|
|
688
688
|
});
|
|
689
689
|
},
|
|
690
690
|
|
|
691
|
-
async
|
|
691
|
+
async glob(args, config) {
|
|
692
692
|
const limit = args.limit ? Number(args.limit) : 100;
|
|
693
693
|
const searchPath = args.path ? String(args.path) : '.';
|
|
694
694
|
const rgArgs: string[] = [
|
|
@@ -1099,7 +1099,7 @@ export async function executeTool(
|
|
|
1099
1099
|
const PROJECT_ROOT = resolveProjectRoot() ?? process.cwd();
|
|
1100
1100
|
// Only guard tools that actually write files — bash and recall_history are
|
|
1101
1101
|
// excluded (bash can trivially escape via shell; recall_history is read-only).
|
|
1102
|
-
const FILE_WRITERS = new Set(['
|
|
1102
|
+
const FILE_WRITERS = new Set(['write', 'edit', 'edit_block']);
|
|
1103
1103
|
if (FILE_WRITERS.has(name) && args.path) {
|
|
1104
1104
|
const rawPath = String(args.path);
|
|
1105
1105
|
const resolved = resolve(PROJECT_ROOT, rawPath);
|
|
@@ -1160,11 +1160,11 @@ export async function executeTool(
|
|
|
1160
1160
|
|
|
1161
1161
|
/** Default read-only toolset for ad-hoc (role-less) delegation. */
|
|
1162
1162
|
const DEFAULT_CHILD_TOOLS = [
|
|
1163
|
-
'
|
|
1164
|
-
'
|
|
1163
|
+
'read',
|
|
1164
|
+
'ls',
|
|
1165
1165
|
'grep_search',
|
|
1166
1166
|
'ast_grep',
|
|
1167
|
-
'
|
|
1167
|
+
'glob',
|
|
1168
1168
|
];
|
|
1169
1169
|
|
|
1170
1170
|
const DEFAULT_CHILD_PROMPT =
|
|
@@ -1189,7 +1189,7 @@ const CHILD_MAX_ROUNDS_CAP = 16;
|
|
|
1189
1189
|
* here, so it would be scheduled in the parallel phase. Extensions can declare
|
|
1190
1190
|
* their own by calling `registerMutatingTools`.
|
|
1191
1191
|
*/
|
|
1192
|
-
const MUTATING_TOOLS = new Set(['
|
|
1192
|
+
const MUTATING_TOOLS = new Set(['write', 'edit', 'edit_block', 'bash', 'verify']);
|
|
1193
1193
|
|
|
1194
1194
|
/**
|
|
1195
1195
|
* Let an extension declare tools that mutate shared state, so they are
|
|
@@ -1548,7 +1548,7 @@ tools.delegate = async (args, config) => {
|
|
|
1548
1548
|
*
|
|
1549
1549
|
* 1. non-mutating children (the default — read-only agents) run in parallel,
|
|
1550
1550
|
* in chunks of `max_parallel`;
|
|
1551
|
-
* 2. mutating children (anything with
|
|
1551
|
+
* 2. mutating children (anything with write / edit / edit_block /
|
|
1552
1552
|
* bash) then run strictly one after another.
|
|
1553
1553
|
*
|
|
1554
1554
|
* Phases never overlap, so a child that edits files or changes the shell cwd
|