pal-code 0.0.9 → 0.0.11
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/README.md +3 -3
- package/SYSTEM.md +3 -3
- package/bin/pal-code.js +37 -11
- package/package.json +7 -14
- package/packages/cli/README.md +2 -2
- package/packages/cli/src/commands/ext.ts +1 -1
- package/packages/cli/src/commands.ts +1 -1
- package/packages/cli/src/components/render-history.ts +2 -2
- package/packages/cli/src/config.ts +2 -2
- package/packages/cli/src/index.ts +7 -7
- package/packages/cli/src/overlays/key-input.ts +1 -1
- package/packages/cli/src/overlays/model-picker.ts +2 -2
- package/packages/cli/src/overlays/session-picker.ts +1 -1
- package/packages/cli/src/overlays/wizard.ts +1 -1
- package/packages/cli/src/state.ts +2 -2
- package/packages/cli/src/turn.ts +16 -9
- package/packages/cli/src/utils/permissions.ts +3 -3
- package/packages/core/src/agent/events.ts +0 -36
- package/packages/core/src/agent/fallback.ts +0 -344
- package/packages/core/src/agent/index.ts +0 -35
- package/packages/core/src/agent/roles.ts +0 -188
- package/packages/core/src/agent/run.ts +0 -713
- package/packages/core/src/agent/scope.ts +0 -34
- package/packages/core/src/agent/todos.ts +0 -66
- package/packages/core/src/compaction.ts +0 -243
- package/packages/core/src/config.ts +0 -387
- package/packages/core/src/extensions.ts +0 -178
- package/packages/core/src/index.ts +0 -157
- package/packages/core/src/logger.ts +0 -54
- package/packages/core/src/provider/auth.ts +0 -153
- package/packages/core/src/provider/complete.ts +0 -63
- package/packages/core/src/provider/index.ts +0 -6
- package/packages/core/src/provider/openrouter.ts +0 -304
- package/packages/core/src/provider/pick-model.ts +0 -43
- package/packages/core/src/provider/registry.ts +0 -222
- package/packages/core/src/provider/types.ts +0 -61
- package/packages/core/src/repo-map.ts +0 -177
- package/packages/core/src/session/index.ts +0 -2
- package/packages/core/src/session/store.ts +0 -677
- package/packages/core/src/session/types.ts +0 -72
- package/packages/core/src/snapshots.ts +0 -107
- package/packages/core/src/tools/definitions.ts +0 -365
- package/packages/core/src/tools/executor.ts +0 -1363
- package/packages/core/src/tools/index.ts +0 -5
- package/packages/core/src/tools/search.ts +0 -201
- package/scripts/postinstall.js +0 -121
- package/scripts/preinstall.js +0 -51
|
@@ -1,387 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Agent configuration — loads .pal.json or .pal.config.json, resolves ignore patterns,
|
|
3
|
-
* provides path filtering to prevent context-bombing.
|
|
4
|
-
*
|
|
5
|
-
* Config resolution order: .pal.json / .pal.config.json → defaults
|
|
6
|
-
* Ignore patterns use minimatch (.gitignore-style globs).
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import {readFileSync, statSync} from 'fs';
|
|
10
|
-
import {resolve, relative, isAbsolute, basename} from 'path';
|
|
11
|
-
import {minimatch} from 'minimatch';
|
|
12
|
-
|
|
13
|
-
/** Config file schema. */
|
|
14
|
-
export interface ToolConfig {
|
|
15
|
-
/** Glob patterns to ignore (applied to all tools). */
|
|
16
|
-
ignore: string[];
|
|
17
|
-
/** Whether to skip files larger than maxFileSizeKB. */
|
|
18
|
-
ignoreLargeFiles: boolean;
|
|
19
|
-
/** Max file size in KB for read_file (default: 512). */
|
|
20
|
-
maxFileSizeKB: number;
|
|
21
|
-
/** Max lines to return from read_file (default: 2000). */
|
|
22
|
-
readLineLimit: number;
|
|
23
|
-
/** Provider config for delegate tool — set by CLI to pass model/key to child agents. */
|
|
24
|
-
provider?: {
|
|
25
|
-
model: string;
|
|
26
|
-
apiKey: string;
|
|
27
|
-
baseUrl: string;
|
|
28
|
-
/** Provider id → key, so `delegate` can resolve a role's own model. */
|
|
29
|
-
keys?: Record<string, string>;
|
|
30
|
-
/** Set when the parent turn is read-only; blocks spawning mutating children. */
|
|
31
|
-
readOnly?: boolean;
|
|
32
|
-
/** Tool allowlist enforced by `executeTool` for the current turn. */
|
|
33
|
-
allowedTools?: string[];
|
|
34
|
-
/** CLI-injected permission-gated executor for child agents. */
|
|
35
|
-
childExecuteTool?: (
|
|
36
|
-
name: string,
|
|
37
|
-
args: string,
|
|
38
|
-
id: string,
|
|
39
|
-
providerConfig: unknown,
|
|
40
|
-
) => Promise<{content: string; error?: boolean}>;
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const DEFAULT_CONFIG: ToolConfig = {
|
|
45
|
-
ignore: ['node_modules', '.git', 'dist', 'build', '*.lockb', '*.log'],
|
|
46
|
-
ignoreLargeFiles: true,
|
|
47
|
-
maxFileSizeKB: 512,
|
|
48
|
-
readLineLimit: 2000,
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
const CONFIG_FILENAMES = ['.pal.json', '.pal.config.json'];
|
|
52
|
-
|
|
53
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
54
|
-
// Permission system
|
|
55
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
56
|
-
|
|
57
|
-
/** A single permission rule: matches a tool + glob pattern → action. */
|
|
58
|
-
export interface PermissionRule {
|
|
59
|
-
/** Tool name(s) this rule applies to. '*' means all tools. */
|
|
60
|
-
tool: string | string[];
|
|
61
|
-
/** Glob pattern matched against the tool's relevant arg (file path or command). */
|
|
62
|
-
match: string;
|
|
63
|
-
/** What to do when the rule matches. */
|
|
64
|
-
action: 'allow' | 'ask' | 'deny';
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Permission configuration — loaded from permissions.json. */
|
|
68
|
-
export interface PermissionConfig {
|
|
69
|
-
/** Default action per tool name when no rule matches. */
|
|
70
|
-
defaults: Record<string, 'allow' | 'ask' | 'deny'>;
|
|
71
|
-
/** Ordered rules — first match wins. */
|
|
72
|
-
rules: PermissionRule[];
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Built-in sensitive-file rules. Applied BEFORE user rules — these protect
|
|
77
|
-
* secret files out of the box with zero configuration.
|
|
78
|
-
*/
|
|
79
|
-
export const BUILTIN_SENSITIVE_RULES: PermissionRule[] = [
|
|
80
|
-
{tool: '*', match: '*.env', action: 'ask'},
|
|
81
|
-
{tool: '*', match: '*.env.*', action: 'ask'},
|
|
82
|
-
{tool: '*', match: '*.pem', action: 'ask'},
|
|
83
|
-
{tool: '*', match: '*.key', action: 'ask'},
|
|
84
|
-
{tool: '*', match: '*.p12', action: 'ask'},
|
|
85
|
-
{tool: '*', match: '*.pfx', action: 'ask'},
|
|
86
|
-
{tool: '*', match: '*.jks', action: 'ask'},
|
|
87
|
-
];
|
|
88
|
-
|
|
89
|
-
/** Built-in default actions per tool. */
|
|
90
|
-
export const BUILTIN_PERMISSION_DEFAULTS: Record<string, 'allow' | 'ask' | 'deny'> = {
|
|
91
|
-
read_file: 'allow',
|
|
92
|
-
write_file: 'allow',
|
|
93
|
-
edit_file: 'allow',
|
|
94
|
-
edit_block: 'allow',
|
|
95
|
-
bash: 'allow',
|
|
96
|
-
list_directory: 'allow',
|
|
97
|
-
grep: 'allow',
|
|
98
|
-
grep_search: 'allow',
|
|
99
|
-
glob_search: 'allow',
|
|
100
|
-
ast_grep: 'allow',
|
|
101
|
-
repo_map: 'allow',
|
|
102
|
-
delegate: 'allow',
|
|
103
|
-
delegate_parallel: 'allow',
|
|
104
|
-
verify: 'allow',
|
|
105
|
-
todo: 'allow',
|
|
106
|
-
'*': 'allow',
|
|
107
|
-
};
|
|
108
|
-
|
|
109
|
-
/** Permission config file names (checked in order). */
|
|
110
|
-
export const PERMISSION_FILENAMES = ['permissions.json'];
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Known dangerous bash patterns. These are ALWAYS denied regardless of rules
|
|
114
|
-
* or user overrides — they represent catastrophic commands that no agent
|
|
115
|
-
* should ever run without extreme deliberation.
|
|
116
|
-
*
|
|
117
|
-
* Patterns are tested case-insensitively against the full command string.
|
|
118
|
-
* Each entry is a [regex, description] pair.
|
|
119
|
-
*/
|
|
120
|
-
export const DANGEROUS_BASH_PATTERNS: Array<[RegExp, string]> = [
|
|
121
|
-
[/rm\s+(-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*f[a-zA-Z]*r[a-zA-Z]*)\s+[\/~]/, 'recursive force delete from root or home'],
|
|
122
|
-
[/rm\s+(-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*f[a-zA-Z]*r[a-zA-Z]*)\s+\*\s*$/, 'recursive force delete with wildcard'],
|
|
123
|
-
[/\bcurl\b.*\|\s*(ba)?sh\b/, 'piping curl output to shell'],
|
|
124
|
-
[/\bwget\b.*\|\s*(ba)?sh\b/, 'piping wget output to shell'],
|
|
125
|
-
[/\bsh\b\s+-c\s+["'].*curl/, 'executing curl via sh -c'],
|
|
126
|
-
[/mkfs\b/, 'formatting a filesystem'],
|
|
127
|
-
[/dd\s+if=.*of=\/dev\//, 'writing directly to a device'],
|
|
128
|
-
[/chmod\s+(-R\s+)?777\s+/, 'setting world-writable permissions'],
|
|
129
|
-
[/>\s*\/etc\//, 'writing to /etc'],
|
|
130
|
-
[/mv\s+.*\s+\/etc\//, 'moving files into /etc'],
|
|
131
|
-
[/kill\s+-9\s+1\b/, 'killing PID 1 (init)'],
|
|
132
|
-
[/shutdown\b/, 'shutdown command'],
|
|
133
|
-
[/reboot\b/, 'reboot command'],
|
|
134
|
-
[/init\s+[06]\b/, 'changing runlevel to halt/reboot'],
|
|
135
|
-
];
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Check if a bash command matches any known dangerous pattern.
|
|
139
|
-
* Returns null if safe, or a description of why it's dangerous.
|
|
140
|
-
*/
|
|
141
|
-
export function detectDangerousBash(command: string): string | null {
|
|
142
|
-
const lower = command.toLowerCase();
|
|
143
|
-
for (const [pattern, desc] of DANGEROUS_BASH_PATTERNS) {
|
|
144
|
-
if (pattern.test(lower)) {
|
|
145
|
-
return desc;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
return null;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Load permissions from the nearest permissions.json (walks up from cwd).
|
|
153
|
-
* Returns the merged config: built-in defaults → file config.
|
|
154
|
-
*/
|
|
155
|
-
export function loadPermissionConfig(cwd?: string): PermissionConfig {
|
|
156
|
-
const dir = cwd ?? process.cwd();
|
|
157
|
-
const config: PermissionConfig = {
|
|
158
|
-
defaults: {...BUILTIN_PERMISSION_DEFAULTS},
|
|
159
|
-
rules: [...BUILTIN_SENSITIVE_RULES],
|
|
160
|
-
};
|
|
161
|
-
|
|
162
|
-
// Walk up to find permissions.json
|
|
163
|
-
let searchDir = dir;
|
|
164
|
-
for (let i = 0; i < 20; i++) {
|
|
165
|
-
for (const filename of PERMISSION_FILENAMES) {
|
|
166
|
-
const configPath = resolve(searchDir, filename);
|
|
167
|
-
try {
|
|
168
|
-
const raw = readFileSync(configPath, 'utf-8');
|
|
169
|
-
const parsed = JSON.parse(raw);
|
|
170
|
-
|
|
171
|
-
// Merge user defaults (override built-in defaults)
|
|
172
|
-
if (parsed.defaults && typeof parsed.defaults === 'object') {
|
|
173
|
-
Object.assign(config.defaults, parsed.defaults);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// Append user rules (after built-in rules, so built-ins match first)
|
|
177
|
-
if (Array.isArray(parsed.rules)) {
|
|
178
|
-
config.rules.push(...parsed.rules);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
return config;
|
|
182
|
-
} catch {
|
|
183
|
-
// Config not found at this level, try next
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
const parent = resolve(searchDir, '..');
|
|
188
|
-
if (parent === searchDir) break; // root
|
|
189
|
-
searchDir = parent;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
return config;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* Check whether a tool call is permitted by the given config + whitelist.
|
|
197
|
-
*
|
|
198
|
-
* @param toolName — the tool being called
|
|
199
|
-
* @param target — the file path or command string to match against
|
|
200
|
-
* @param config — merged permission config
|
|
201
|
-
* @param whitelist — session-scoped "always allow" entries
|
|
202
|
-
* @returns 'allow' | 'ask' | 'deny'
|
|
203
|
-
*/
|
|
204
|
-
export function checkPermission(
|
|
205
|
-
toolName: string,
|
|
206
|
-
target: string,
|
|
207
|
-
config: PermissionConfig,
|
|
208
|
-
whitelist: Array<{tool: string; pattern: string}> = [],
|
|
209
|
-
): 'allow' | 'ask' | 'deny' {
|
|
210
|
-
// 1. Session whitelist (user said "always" this session)
|
|
211
|
-
for (const entry of whitelist) {
|
|
212
|
-
if (entry.tool === toolName || entry.tool === '*') {
|
|
213
|
-
if (minimatch(target, entry.pattern, {matchBase: true, dot: true})) {
|
|
214
|
-
return 'allow';
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// 2. Built-in sensitive rules + user rules (first match wins)
|
|
220
|
-
for (const rule of config.rules) {
|
|
221
|
-
const tools = Array.isArray(rule.tool) ? rule.tool : [rule.tool];
|
|
222
|
-
const toolMatch = tools.includes(toolName) || tools.includes('*');
|
|
223
|
-
if (!toolMatch) continue;
|
|
224
|
-
|
|
225
|
-
if (minimatch(target, rule.match, {matchBase: true, dot: true})) {
|
|
226
|
-
return rule.action;
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
// 3. Default for this tool
|
|
231
|
-
return config.defaults[toolName] ?? config.defaults['*'] ?? 'allow';
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/**
|
|
235
|
-
* Walk up from `dir` (default: cwd) to find the directory containing a
|
|
236
|
-
* `.pal.json` or `.pal.config.json`. Returns the directory path, or `null`
|
|
237
|
-
* if none found (walks up to filesystem root, max 20 levels).
|
|
238
|
-
*/
|
|
239
|
-
export function resolveProjectRoot(dir?: string): string | null {
|
|
240
|
-
let searchDir = dir ?? process.cwd();
|
|
241
|
-
for (let i = 0; i < 20; i++) {
|
|
242
|
-
for (const filename of CONFIG_FILENAMES) {
|
|
243
|
-
const configPath = resolve(searchDir, filename);
|
|
244
|
-
try {
|
|
245
|
-
// readFileSync throws if missing — we just need existence
|
|
246
|
-
readFileSync(configPath, 'utf-8');
|
|
247
|
-
return searchDir;
|
|
248
|
-
} catch {
|
|
249
|
-
// not found at this level, try next filename
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
const parent = resolve(searchDir, '..');
|
|
253
|
-
if (parent === searchDir) break; // root
|
|
254
|
-
searchDir = parent;
|
|
255
|
-
}
|
|
256
|
-
return null;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
let _cachedConfig: ToolConfig | null = null;
|
|
260
|
-
let _cachedCwd: string | null = null;
|
|
261
|
-
|
|
262
|
-
/** Load config from the nearest .pal.json or .pal.config.json (walks up from cwd). */
|
|
263
|
-
export function loadAgentConfig(cwd?: string): ToolConfig {
|
|
264
|
-
const dir = cwd ?? process.cwd();
|
|
265
|
-
|
|
266
|
-
if (_cachedConfig && _cachedCwd === dir) {
|
|
267
|
-
return _cachedConfig;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
const config: ToolConfig = {...DEFAULT_CONFIG};
|
|
271
|
-
let foundPath: string | null = null;
|
|
272
|
-
|
|
273
|
-
// Walk up to find config file
|
|
274
|
-
let searchDir = dir;
|
|
275
|
-
for (let i = 0; i < 20; i++) {
|
|
276
|
-
for (const filename of CONFIG_FILENAMES) {
|
|
277
|
-
const configPath = resolve(searchDir, filename);
|
|
278
|
-
try {
|
|
279
|
-
const raw = readFileSync(configPath, 'utf-8');
|
|
280
|
-
const parsed = JSON.parse(raw);
|
|
281
|
-
|
|
282
|
-
// Merge with defaults
|
|
283
|
-
if (Array.isArray(parsed.ignore)) {
|
|
284
|
-
config.ignore = [...DEFAULT_CONFIG.ignore, ...parsed.ignore];
|
|
285
|
-
}
|
|
286
|
-
if (typeof parsed.ignoreLargeFiles === 'boolean') {
|
|
287
|
-
config.ignoreLargeFiles = parsed.ignoreLargeFiles;
|
|
288
|
-
}
|
|
289
|
-
if (typeof parsed.maxFileSizeKB === 'number') {
|
|
290
|
-
config.maxFileSizeKB = parsed.maxFileSizeKB;
|
|
291
|
-
}
|
|
292
|
-
if (typeof parsed.readLineLimit === 'number') {
|
|
293
|
-
config.readLineLimit = parsed.readLineLimit;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
foundPath = configPath;
|
|
297
|
-
break;
|
|
298
|
-
} catch {
|
|
299
|
-
// Config not found at this level, try next filename
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
if (foundPath) break;
|
|
303
|
-
|
|
304
|
-
const parent = resolve(searchDir, '..');
|
|
305
|
-
if (parent === searchDir) break; // root
|
|
306
|
-
searchDir = parent;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
_cachedConfig = config;
|
|
310
|
-
_cachedCwd = dir;
|
|
311
|
-
return config;
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/** Clear config cache (for testing or config reload). */
|
|
315
|
-
export function clearConfigCache(): void {
|
|
316
|
-
_cachedConfig = null;
|
|
317
|
-
_cachedCwd = null;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/**
|
|
321
|
-
* Check if a path should be ignored based on config patterns.
|
|
322
|
-
* Handles both relative and absolute paths.
|
|
323
|
-
* Patterns match against: full path, basename, or relative segments.
|
|
324
|
-
*/
|
|
325
|
-
export function isPathIgnored(targetPath: string, config: ToolConfig, cwd?: string): boolean {
|
|
326
|
-
const base = cwd ?? process.cwd();
|
|
327
|
-
|
|
328
|
-
// Normalize to relative path
|
|
329
|
-
let relPath = targetPath;
|
|
330
|
-
if (isAbsolute(targetPath)) {
|
|
331
|
-
relPath = relative(base, targetPath);
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
// Always normalize to forward slashes for glob matching
|
|
335
|
-
relPath = relPath.replace(/\\/g, '/');
|
|
336
|
-
|
|
337
|
-
const name = basename(targetPath);
|
|
338
|
-
|
|
339
|
-
for (const pattern of config.ignore) {
|
|
340
|
-
// Match against full relative path
|
|
341
|
-
if (minimatch(relPath, pattern, {matchBase: true, dot: true})) return true;
|
|
342
|
-
// Match against basename (for patterns like "node_modules", "*.lockb")
|
|
343
|
-
if (minimatch(name, pattern, {matchBase: true, dot: true})) return true;
|
|
344
|
-
// Match against each path segment (for directory patterns like "node_modules")
|
|
345
|
-
const segments = relPath.split('/');
|
|
346
|
-
for (const seg of segments) {
|
|
347
|
-
if (minimatch(seg, pattern, {matchBase: true, dot: true})) return true;
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
return false;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Filter directory entries by ignore patterns.
|
|
356
|
-
* Returns only non-ignored entries.
|
|
357
|
-
*/
|
|
358
|
-
export function filterEntries(
|
|
359
|
-
entries: Array<{name: string; isDirectory: boolean}>,
|
|
360
|
-
dirPath: string,
|
|
361
|
-
config: ToolConfig,
|
|
362
|
-
cwd?: string,
|
|
363
|
-
): Array<{name: string; isDirectory: boolean}> {
|
|
364
|
-
return entries.filter((entry) => {
|
|
365
|
-
const fullPath = resolve(dirPath, entry.name);
|
|
366
|
-
return !isPathIgnored(fullPath, config, cwd);
|
|
367
|
-
});
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
/**
|
|
371
|
-
* Check if a file exceeds the size limit.
|
|
372
|
-
* Returns null if OK, or an error message if too large.
|
|
373
|
-
*/
|
|
374
|
-
export function checkFileSize(filePath: string, config: ToolConfig): string | null {
|
|
375
|
-
if (!config.ignoreLargeFiles) return null;
|
|
376
|
-
|
|
377
|
-
try {
|
|
378
|
-
const st = statSync(filePath);
|
|
379
|
-
const sizeKB = st.size / 1024;
|
|
380
|
-
if (sizeKB > config.maxFileSizeKB) {
|
|
381
|
-
return `File too large (${Math.round(sizeKB)}KB > ${config.maxFileSizeKB}KB limit). Use read_file with offset/limit to read sections.`;
|
|
382
|
-
}
|
|
383
|
-
} catch {
|
|
384
|
-
// File doesn't exist — let the tool handle that error
|
|
385
|
-
}
|
|
386
|
-
return null;
|
|
387
|
-
}
|
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Extension system for pal.
|
|
3
|
-
*
|
|
4
|
-
* Extensions add new tools to the agent without modifying core. Each package
|
|
5
|
-
* exports a default `ToolExtension`.
|
|
6
|
-
*
|
|
7
|
-
* ## Plug and play
|
|
8
|
-
*
|
|
9
|
-
* Extensions are resolved **at runtime**, not compiled in. Core never lists an
|
|
10
|
-
* extension as a dependency, so the shipped backbone stays small and any
|
|
11
|
-
* extension can be added by dropping it somewhere resolvable and naming it in
|
|
12
|
-
* `~/.pal/config.json`:
|
|
13
|
-
*
|
|
14
|
-
* ```json
|
|
15
|
-
* { "extensions": ["@pal-code/web-search", "@pal-code/agents"] }
|
|
16
|
-
* ```
|
|
17
|
-
*
|
|
18
|
-
* Resolution tries each root in `roots` (see `defaultExtensionRoots`) and falls
|
|
19
|
-
* back to a bare import, so all of these work:
|
|
20
|
-
* - a workspace/hoisted package in the project's `node_modules`
|
|
21
|
-
* - `~/.pal/extensions/node_modules/<pkg>` (user-installed)
|
|
22
|
-
* - `~/.pal/node_modules/<pkg>` (user-installed, flat)
|
|
23
|
-
* - an absolute or relative path to an extension entry file
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
import {homedir} from 'node:os';
|
|
27
|
-
import {join} from 'node:path';
|
|
28
|
-
import type {ToolDef} from './tools/definitions.js';
|
|
29
|
-
import type {ToolConfig} from './config.js';
|
|
30
|
-
import {clearRoleProvider} from './agent/roles.js';
|
|
31
|
-
|
|
32
|
-
/** Tool handler function signature. */
|
|
33
|
-
export type ToolHandler = (args: Record<string, unknown>, config: ToolConfig) => Promise<string>;
|
|
34
|
-
|
|
35
|
-
/** Extension interface — what each extension package must export as default. */
|
|
36
|
-
export interface ToolExtension {
|
|
37
|
-
/** Unique extension name (e.g., 'web-search'). */
|
|
38
|
-
name: string;
|
|
39
|
-
/** Tool definitions to add to the agent. */
|
|
40
|
-
tools: ToolDef[];
|
|
41
|
-
/** Tool name → handler function mapping. */
|
|
42
|
-
handlers: Record<string, ToolHandler>;
|
|
43
|
-
/**
|
|
44
|
-
* Optional setup hook, called once after the extension loads. Lets an
|
|
45
|
-
* extension register process-wide capabilities that aren't tools — e.g.
|
|
46
|
-
* `@pal-code/agents` registers the role provider used by core's `delegate`.
|
|
47
|
-
*/
|
|
48
|
-
setup?: () => void | Promise<void>;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export interface LoadedExtensions {
|
|
52
|
-
tools: ToolDef[];
|
|
53
|
-
handlers: Record<string, ToolHandler>;
|
|
54
|
-
/** Package names that loaded successfully, in input order. */
|
|
55
|
-
loaded: string[];
|
|
56
|
-
/** Package names that failed, with the reason. */
|
|
57
|
-
failed: Array<{pkg: string; reason: string}>;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export interface LoadExtensionsOptions {
|
|
61
|
-
/**
|
|
62
|
-
* Directories to resolve package names from, in order. Defaults to
|
|
63
|
-
* `defaultExtensionRoots()`.
|
|
64
|
-
*/
|
|
65
|
-
roots?: string[];
|
|
66
|
-
/**
|
|
67
|
-
* Append a cache-busting query to the resolved entry so edited extension
|
|
68
|
-
* source is re-imported. Used by `/reload`; never for a normal start.
|
|
69
|
-
*/
|
|
70
|
-
cacheBust?: boolean;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Where extensions are looked for, in order:
|
|
75
|
-
* 1. the project's own node_modules (workspace/hoisted packages)
|
|
76
|
-
* 2. `~/.pal/extensions` (user-installed, node_modules layout)
|
|
77
|
-
* 3. `~/.pal` (user-installed, flat layout)
|
|
78
|
-
*/
|
|
79
|
-
export function defaultExtensionRoots(): string[] {
|
|
80
|
-
const home = safeHomedir();
|
|
81
|
-
return [process.cwd(), ...(home ? [join(home, '.pal', 'extensions'), join(home, '.pal')] : [])];
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Resolve a package name to an importable specifier.
|
|
86
|
-
*
|
|
87
|
-
* Path-like specifiers are left alone (the caller is pointing at a file).
|
|
88
|
-
* Package names are resolved from each root in turn; if none match we return
|
|
89
|
-
* the bare name so a plain `import()` still gets a chance (globally installed
|
|
90
|
-
* or NODE_PATH-visible packages).
|
|
91
|
-
*/
|
|
92
|
-
function resolveSpecifier(pkg: string, roots: string[]): string {
|
|
93
|
-
if (isPathLike(pkg)) return pkg;
|
|
94
|
-
|
|
95
|
-
for (const root of roots) {
|
|
96
|
-
try {
|
|
97
|
-
return Bun.resolveSync(pkg, root);
|
|
98
|
-
} catch {
|
|
99
|
-
// Not resolvable from this root — try the next.
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
return pkg;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function isPathLike(spec: string): boolean {
|
|
106
|
-
return (
|
|
107
|
-
spec.startsWith('./') ||
|
|
108
|
-
spec.startsWith('../') ||
|
|
109
|
-
spec.startsWith('/') ||
|
|
110
|
-
/^[A-Za-z]:[\\/]/.test(spec)
|
|
111
|
-
);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
function safeHomedir(): string | undefined {
|
|
115
|
-
try {
|
|
116
|
-
return homedir();
|
|
117
|
-
} catch {
|
|
118
|
-
return undefined;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Load extensions from package names.
|
|
124
|
-
*
|
|
125
|
-
* Each package must export a default `ToolExtension`. Failures are collected
|
|
126
|
-
* rather than thrown — one broken extension must never stop pal from starting.
|
|
127
|
-
*/
|
|
128
|
-
export async function loadExtensions(
|
|
129
|
-
extensionPackages: string[],
|
|
130
|
-
options: LoadExtensionsOptions = {},
|
|
131
|
-
): Promise<LoadedExtensions> {
|
|
132
|
-
const roots = options.roots ?? defaultExtensionRoots();
|
|
133
|
-
const allTools: ToolDef[] = [];
|
|
134
|
-
const allHandlers: Record<string, ToolHandler> = {};
|
|
135
|
-
const loaded: string[] = [];
|
|
136
|
-
const failed: Array<{pkg: string; reason: string}> = [];
|
|
137
|
-
|
|
138
|
-
// Clear any previously-registered role provider *before* (re)loading. If the
|
|
139
|
-
// extension that provides it is gone or fails, its roles must not linger.
|
|
140
|
-
clearRoleProvider();
|
|
141
|
-
|
|
142
|
-
for (const pkg of extensionPackages) {
|
|
143
|
-
try {
|
|
144
|
-
const base = resolveSpecifier(pkg, roots);
|
|
145
|
-
const specifier = options.cacheBust ? `${base}?t=${Date.now()}` : base;
|
|
146
|
-
const ext = await import(specifier).then((m) => m.default as ToolExtension);
|
|
147
|
-
|
|
148
|
-
if (!ext || !ext.name || !Array.isArray(ext.tools) || !ext.handlers) {
|
|
149
|
-
failed.push({pkg, reason: 'invalid shape — expected a default ToolExtension'});
|
|
150
|
-
continue;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
allTools.push(...ext.tools);
|
|
154
|
-
Object.assign(allHandlers, ext.handlers);
|
|
155
|
-
loaded.push(pkg);
|
|
156
|
-
|
|
157
|
-
// Extension-granted capabilities (non-tool) — e.g. the role provider.
|
|
158
|
-
// A failed setup is reported through `failed`, not the console: loading
|
|
159
|
-
// happens after the CLI's TUI starts, and any stdout/stderr write smears
|
|
160
|
-
// the frame.
|
|
161
|
-
if (typeof ext.setup === 'function') {
|
|
162
|
-
try {
|
|
163
|
-
await ext.setup();
|
|
164
|
-
} catch (err) {
|
|
165
|
-
failed.push({
|
|
166
|
-
pkg,
|
|
167
|
-
reason: `setup failed — ${err instanceof Error ? err.message : String(err)}`,
|
|
168
|
-
});
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
} catch (err) {
|
|
172
|
-
const reason = err instanceof Error ? err.message : String(err);
|
|
173
|
-
failed.push({pkg, reason});
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
return {tools: allTools, handlers: allHandlers, loaded, failed};
|
|
178
|
-
}
|