@pal-code/core 0.0.14 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pal-code/core",
3
- "version": "0.0.14",
3
+ "version": "0.0.16",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -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
- 'read_file',
223
- 'list_directory',
222
+ 'read',
223
+ 'ls',
224
224
  'grep',
225
225
  'grep_search',
226
- 'glob_search',
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 'read_file':
247
- case 'write_file':
248
- case 'edit_file': {
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 'list_directory':
256
+ case 'ls':
257
257
  return v('path') || v('directory');
258
258
  case 'glob':
259
259
  return v('pattern') || v('glob');
@@ -656,6 +656,9 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
656
656
 
657
657
  // ── No tool calls → turn complete ──
658
658
  if (toolCalls.length === 0) {
659
+ if (!textContent.trim()) {
660
+ console.warn('pal: empty assistant response (no text and no tool calls)');
661
+ }
659
662
  messages.push({role: 'assistant', content: textContent});
660
663
  yield {type: 'done', model, rounds: roundsRun, usage: usage()};
661
664
  return;
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 write_file
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 read_file (default: 512). */
20
+ /** Max file size in KB for read (default: 512). */
20
21
  maxFileSizeKB: number;
21
- /** Max lines to return from read_file (default: 2000). */
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
- read_file: 'allow',
131
- write_file: 'allow',
132
- edit_file: 'allow',
131
+ read: 'allow',
132
+ write: 'allow',
133
+ edit: 'allow',
133
134
  edit_block: 'allow',
134
135
  bash: 'allow',
135
- list_directory: 'allow',
136
+ ls: 'allow',
136
137
  grep: 'allow',
137
138
  grep_search: 'allow',
138
- glob_search: 'allow',
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.assign(config.defaults, parsed.defaults);
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(...parsed.rules);
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 read_file with offset/limit to read sections.`;
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. the project's own node_modules (workspace/hoisted packages)
95
- * 2. `~/.pal/extensions` (user-installed, node_modules layout)
96
- * 3. `~/.pal` (user-installed, flat layout)
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
- return [process.cwd(), ...(home ? [join(home, '.pal', 'extensions'), join(home, '.pal')] : [])];
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 resolved entry lies within it. If no root matches we return the
109
- * bare name so a plain `import()` still gets a chance (globally installed or
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
- try {
125
- const resolved = Bun.resolveSync(pkg, root);
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 specifier = options.cacheBust ? `${base}?t=${Date.now()}` : base;
217
- const ext = await import(specifier).then((m) => m.default as ToolExtension);
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,8 +106,10 @@ 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,
112
+ validateRequiredArgs,
111
113
  clearExtensionTools,
112
114
  getExtensionTools,
113
115
  } from './tools/definitions.js';
@@ -123,7 +125,12 @@ export {
123
125
  export type {ToolResult, RecallableRow} from './tools/executor.js';
124
126
 
125
127
  // Extensions
126
- export {loadExtensions, defaultExtensionRoots, resolveExtensionSpecifier} from './extensions.js';
128
+ export {
129
+ loadExtensions,
130
+ defaultExtensionRoots,
131
+ resolveExtensionSpecifier,
132
+ importExtensionModule,
133
+ } from './extensions.js';
127
134
  export type {
128
135
  ToolExtension,
129
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:read_file`. */
46
+ /** What was happening when it failed, e.g. `tool:read`. */
47
47
  readonly context: string;
48
48
  }
49
49
 
@@ -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)) {
@@ -55,10 +55,32 @@ export function clearExtensionTools(): void {
55
55
  }
56
56
 
57
57
  /** The extension tools currently registered (read-only view). */
58
- export function getExtensionTools(): readonly ToolDef[] {
58
+ export function getExtensionTools(): ToolDef[] {
59
59
  return registry.extensionTools;
60
60
  }
61
61
 
62
+ /**
63
+ * Presence check for every `required` argument in the tool's JSON schema.
64
+ * Returns the model-facing error string, or `null` when the call is acceptable.
65
+ *
66
+ * Fail-open by design: an unknown tool is the executor's unknown-tool branch
67
+ * (no schema here to check against), and a schema without `required` has
68
+ * nothing to check. A key present with any value — including `null` — counts
69
+ * as provided; this only catches *absent* keys, e.g. `edit` dispatched
70
+ * without `path` (the `ENOENT ... open 'undefined'` failure mode).
71
+ */
72
+ export function validateRequiredArgs(name: string, args: Record<string, unknown>): string | null {
73
+ const params = getAllTools().find((t) => t.function.name === name)?.function.parameters;
74
+ if (!params || !('required' in params)) return null;
75
+ const required: unknown = params.required;
76
+ if (!Array.isArray(required)) return null;
77
+ const missing = required.filter((key) => typeof key === 'string' && args[key] === undefined);
78
+ if (missing.length === 0) return null;
79
+ return missing.length === 1
80
+ ? `missing required argument: ${String(missing[0])}`
81
+ : `missing required argument(s): ${missing.map(String).join(', ')}`;
82
+ }
83
+
62
84
  /**
63
85
  * Get all tools — core tools plus registered extension tools, plus any
64
86
  * explicitly supplied ones (kept for callers that aren't the registry).
@@ -179,7 +201,7 @@ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
179
201
  type: 'array',
180
202
  items: {type: 'string'},
181
203
  description:
182
- 'Tool names the child may use. Default: read-only tools (read_file, list_directory, grep_search, ast_grep, glob_search).',
204
+ 'Tool names the child may use. Default: read-only tools (read, ls, grep_search, ast_grep, glob).',
183
205
  },
184
206
  max_rounds: {
185
207
  type: 'number',
@@ -222,11 +244,20 @@ function buildDelegateParallelTool(roles: RoleSpec[]): ToolDef {
222
244
  };
223
245
  }
224
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
+
225
256
  export const CORE_TOOLS: ToolDef[] = [
226
257
  {
227
258
  type: 'function',
228
259
  function: {
229
- name: 'read_file',
260
+ name: 'read',
230
261
  description: 'Read file with line numbers.',
231
262
  parameters: {
232
263
  type: 'object',
@@ -242,7 +273,7 @@ export const CORE_TOOLS: ToolDef[] = [
242
273
  {
243
274
  type: 'function',
244
275
  function: {
245
- name: 'write_file',
276
+ name: 'write',
246
277
  description: 'Create or overwrite file.',
247
278
  parameters: {
248
279
  type: 'object',
@@ -257,7 +288,7 @@ export const CORE_TOOLS: ToolDef[] = [
257
288
  {
258
289
  type: 'function',
259
290
  function: {
260
- name: 'edit_file',
291
+ name: 'edit',
261
292
  description:
262
293
  'Replace exact string in file; structural pattern+rewrite fallback when exact text unknown.',
263
294
  parameters: {
@@ -317,7 +348,7 @@ export const CORE_TOOLS: ToolDef[] = [
317
348
  {
318
349
  type: 'function',
319
350
  function: {
320
- name: 'list_directory',
351
+ name: 'ls',
321
352
  description: 'List directory contents.',
322
353
  parameters: {
323
354
  type: 'object',
@@ -365,7 +396,7 @@ export const CORE_TOOLS: ToolDef[] = [
365
396
  {
366
397
  type: 'function',
367
398
  function: {
368
- name: 'glob_search',
399
+ name: 'glob',
369
400
  description: 'Find files by glob pattern.',
370
401
  parameters: {
371
402
  type: 'object',
@@ -26,10 +26,11 @@ import {snapshotFile} from '../snapshots.js';
26
26
  import {noteEditedFile} from '../diagnostics.js';
27
27
  import type {ConversationMessage} from '../agent/run.js';
28
28
  import {registry} from '../registry.js';
29
+ import {validateRequiredArgs} from './definitions.js';
29
30
 
30
31
  /**
31
32
  * `rg --glob '!pat'` args for each `.pal.json` ignore pattern, so ripgrep
32
- * honours the same ignores as read_file / list_directory.
33
+ * honours the same ignores as read / ls.
33
34
  */
34
35
  function ignoreGlobArgs(config: ToolConfig): string[] {
35
36
  return (config.ignore ?? []).flatMap((p) => ['--glob', `!${p}`]);
@@ -163,7 +164,7 @@ export function registerExtensionHandlers(
163
164
  }
164
165
 
165
166
  // ═══════════════════════════════════════════════════════════════════════════════
166
- // Structural edit — ast-grep fallback for edit_file (roadmap #2): locate the
167
+ // Structural edit — ast-grep fallback for edit (roadmap #2): locate the
167
168
  // node by SHAPE when old_string misses whitespace/format churn, then rebuild
168
169
  // it from a rewrite template of $A-style captures. One tool, not a general
169
170
  // tree-sitter layer.
@@ -268,7 +269,7 @@ const tools: Record<
268
269
  string,
269
270
  (args: Record<string, unknown>, config: ToolConfig) => Promise<string>
270
271
  > = {
271
- async read_file(args, config) {
272
+ async read(args, config) {
272
273
  const filePath = String(args.path);
273
274
  const offset = args.offset ? Number(args.offset) : undefined;
274
275
  const limit = args.limit ? Number(args.limit) : undefined;
@@ -307,7 +308,7 @@ const tools: Record<
307
308
  return numbered + truncated || '(empty file)';
308
309
  },
309
310
 
310
- async write_file(args, config) {
311
+ async write(args, config) {
311
312
  const filePath = String(args.path);
312
313
  const content = String(args.content);
313
314
 
@@ -316,12 +317,12 @@ const tools: Record<
316
317
  }
317
318
 
318
319
  await mkdir(dirname(filePath), {recursive: true});
319
- snapshotFile(filePath, 'write_file');
320
+ snapshotFile(filePath, 'write');
320
321
  await writeFile(filePath, content, 'utf-8');
321
322
  return `Wrote ${content.length} bytes to ${filePath}`;
322
323
  },
323
324
 
324
- async edit_file(args, config) {
325
+ async edit(args, config) {
325
326
  const filePath = String(args.path);
326
327
  const oldString = String(args.old_string);
327
328
  const newString = String(args.new_string);
@@ -360,7 +361,7 @@ const tools: Record<
360
361
  throw new Error(stringError);
361
362
  }
362
363
 
363
- snapshotFile(filePath, 'edit_file');
364
+ snapshotFile(filePath, 'edit');
364
365
  await writeFile(filePath, updated, 'utf-8');
365
366
  return `Edited ${filePath} successfully`;
366
367
  },
@@ -555,7 +556,7 @@ const tools: Record<
555
556
  return formatTodos(list);
556
557
  },
557
558
 
558
- async list_directory(args, config) {
559
+ async ls(args, config) {
559
560
  const dirPath = String(args.path);
560
561
  const pattern = args.pattern ? String(args.pattern) : undefined;
561
562
 
@@ -687,7 +688,7 @@ const tools: Record<
687
688
  });
688
689
  },
689
690
 
690
- async glob_search(args, config) {
691
+ async glob(args, config) {
691
692
  const limit = args.limit ? Number(args.limit) : 100;
692
693
  const searchPath = args.path ? String(args.path) : '.';
693
694
  const rgArgs: string[] = [
@@ -1077,6 +1078,10 @@ export async function executeTool(
1077
1078
  const args = (
1078
1079
  argsStr && argsStr.trim() ? JSON.parse(argsStr.replaceAll('\u0000', '')) : {}
1079
1080
  ) as Record<string, unknown>;
1081
+ const validationError = validateRequiredArgs(name, args);
1082
+ if (validationError) {
1083
+ return {toolCallId, content: validationError, error: true};
1084
+ }
1080
1085
  const config = loadAgentConfig();
1081
1086
  if (providerConfigOverride) {
1082
1087
  config.provider = providerConfigOverride;
@@ -1094,7 +1099,7 @@ export async function executeTool(
1094
1099
  const PROJECT_ROOT = resolveProjectRoot() ?? process.cwd();
1095
1100
  // Only guard tools that actually write files — bash and recall_history are
1096
1101
  // excluded (bash can trivially escape via shell; recall_history is read-only).
1097
- const FILE_WRITERS = new Set(['write_file', 'edit_file', 'edit_block']);
1102
+ const FILE_WRITERS = new Set(['write', 'edit', 'edit_block']);
1098
1103
  if (FILE_WRITERS.has(name) && args.path) {
1099
1104
  const rawPath = String(args.path);
1100
1105
  const resolved = resolve(PROJECT_ROOT, rawPath);
@@ -1155,11 +1160,11 @@ export async function executeTool(
1155
1160
 
1156
1161
  /** Default read-only toolset for ad-hoc (role-less) delegation. */
1157
1162
  const DEFAULT_CHILD_TOOLS = [
1158
- 'read_file',
1159
- 'list_directory',
1163
+ 'read',
1164
+ 'ls',
1160
1165
  'grep_search',
1161
1166
  'ast_grep',
1162
- 'glob_search',
1167
+ 'glob',
1163
1168
  ];
1164
1169
 
1165
1170
  const DEFAULT_CHILD_PROMPT =
@@ -1184,7 +1189,7 @@ const CHILD_MAX_ROUNDS_CAP = 16;
1184
1189
  * here, so it would be scheduled in the parallel phase. Extensions can declare
1185
1190
  * their own by calling `registerMutatingTools`.
1186
1191
  */
1187
- const MUTATING_TOOLS = new Set(['write_file', 'edit_file', 'edit_block', 'bash', 'verify']);
1192
+ const MUTATING_TOOLS = new Set(['write', 'edit', 'edit_block', 'bash', 'verify']);
1188
1193
 
1189
1194
  /**
1190
1195
  * Let an extension declare tools that mutate shared state, so they are
@@ -1543,7 +1548,7 @@ tools.delegate = async (args, config) => {
1543
1548
  *
1544
1549
  * 1. non-mutating children (the default — read-only agents) run in parallel,
1545
1550
  * in chunks of `max_parallel`;
1546
- * 2. mutating children (anything with write_file / edit_file / edit_block /
1551
+ * 2. mutating children (anything with write / edit / edit_block /
1547
1552
  * bash) then run strictly one after another.
1548
1553
  *
1549
1554
  * Phases never overlap, so a child that edits files or changes the shell cwd