@pal-code/core 0.0.15 → 0.0.17
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 +47 -14
- package/src/compaction.ts +1 -1
- package/src/config.ts +22 -10
- package/src/extensions.ts +420 -21
- package/src/index.ts +16 -2
- package/src/lifecycle.ts +1 -1
- package/src/provider/chat.ts +250 -0
- package/src/provider/complete.ts +20 -1
- package/src/provider/index.ts +2 -1
- package/src/provider/openrouter.ts +42 -213
- package/src/provider/registry.ts +54 -10
- package/src/provider/responses.ts +271 -0
- package/src/provider/types.ts +19 -1
- package/src/session/store.ts +35 -6
- package/src/session/types.ts +4 -0
- package/src/tools/definitions.ts +16 -7
- package/src/tools/executor.ts +52 -21
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
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
// Provider abstraction (preferred)
|
|
2
|
-
export type {
|
|
2
|
+
export type {
|
|
3
|
+
Provider,
|
|
4
|
+
ProviderConfig,
|
|
5
|
+
ProviderModel,
|
|
6
|
+
StreamEvent,
|
|
7
|
+
ModelRoute,
|
|
8
|
+
} from './provider/types.js';
|
|
3
9
|
export {createOpenRouterProvider} from './provider/openrouter.js';
|
|
4
10
|
export {
|
|
5
11
|
resolveAuth,
|
|
@@ -18,6 +24,8 @@ export {
|
|
|
18
24
|
detectProvider,
|
|
19
25
|
providerForModel,
|
|
20
26
|
loadCustomProviders,
|
|
27
|
+
resolveRoute,
|
|
28
|
+
mergeProviders,
|
|
21
29
|
} from './provider/registry.js';
|
|
22
30
|
export type {ProviderDef} from './provider/registry.js';
|
|
23
31
|
|
|
@@ -106,6 +114,7 @@ export type {ToolConfig, PermissionConfig, PermissionRule} from './config.js';
|
|
|
106
114
|
// Tools
|
|
107
115
|
export {
|
|
108
116
|
CORE_TOOLS,
|
|
117
|
+
TOOL_NAME_ALIASES,
|
|
109
118
|
getAllTools,
|
|
110
119
|
registerExtensionTools,
|
|
111
120
|
validateRequiredArgs,
|
|
@@ -124,7 +133,12 @@ export {
|
|
|
124
133
|
export type {ToolResult, RecallableRow} from './tools/executor.js';
|
|
125
134
|
|
|
126
135
|
// Extensions
|
|
127
|
-
export {
|
|
136
|
+
export {
|
|
137
|
+
loadExtensions,
|
|
138
|
+
defaultExtensionRoots,
|
|
139
|
+
resolveExtensionSpecifier,
|
|
140
|
+
importExtensionModule,
|
|
141
|
+
} from './extensions.js';
|
|
128
142
|
export type {
|
|
129
143
|
ToolExtension,
|
|
130
144
|
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
|
|