@pal-code/core 0.0.11 → 0.0.13

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.
@@ -0,0 +1,177 @@
1
+ /**
2
+ * File-based skills — `.pal/skills/*.md` from the project and `~/.pal/skills/`.
3
+ *
4
+ * Frontmatter (`name`, `description`) over a body of instructions.
5
+ *
6
+ * ## How descriptions reach the model (and why `load_skill`, not auto-injection)
7
+ *
8
+ * The cheap path is a compact listing: `buildSkillsPrompt()` emits one
9
+ * `- name: description` line per skill (~15 tokens each) and is injected into
10
+ * the system prompt next to the roles block. Full bodies are **never** inlined —
11
+ * they are fetched on demand through the `load_skill` tool, which is added to
12
+ * `getAllTools()` *only while at least one skill file exists*, so skill-free
13
+ * users pay zero tokens and zero tool-schema cost.
14
+ *
15
+ * `load_skill` was chosen over auto-injection-on-reference because reference
16
+ * matching requires prompt heuristics (which mention counts as a reference?
17
+ * what if the model names the skill but not verbatim?), while a tool keeps
18
+ * retrieval deterministic, supports loading several skills, and reports unknown
19
+ * names instead of silently injecting nothing.
20
+ *
21
+ * Precedence: project file → user file (same name, project wins). Malformed
22
+ * files are skipped with a `console.warn`, never a crash.
23
+ */
24
+
25
+ import {readFileSync} from 'fs';
26
+ import {homedir} from 'os';
27
+ import {basename, join} from 'path';
28
+ import type {ToolHandlerFn} from '../registry.js';
29
+ import {registry} from '../registry.js';
30
+ import type {ToolDef} from '../tools/definitions.js';
31
+ import {listMarkdownFiles, parseFrontmatter} from './frontmatter.js';
32
+
33
+ export interface Skill {
34
+ name: string;
35
+ description: string;
36
+ body: string;
37
+ path: string;
38
+ }
39
+
40
+ function skipFile(path: string, reason: string): null {
41
+ console.warn(`pal: ignoring ${path} — ${reason}`);
42
+ return null;
43
+ }
44
+
45
+ function readSkillsDir(dir: string): Skill[] {
46
+ const skills: Skill[] = [];
47
+ for (const path of listMarkdownFiles(dir)) {
48
+ let text: string;
49
+ try {
50
+ text = readFileSync(path, 'utf-8');
51
+ } catch (err) {
52
+ skipFile(path, err instanceof Error ? err.message : String(err));
53
+ continue;
54
+ }
55
+
56
+ const parsed = parseFrontmatter(text);
57
+ if (parsed === null) {
58
+ skipFile(path, 'missing or malformed frontmatter');
59
+ continue;
60
+ }
61
+
62
+ const description = parsed.fields.description?.trim();
63
+ if (!description) {
64
+ skipFile(path, 'missing required `description` field');
65
+ continue;
66
+ }
67
+
68
+ skills.push({
69
+ name: parsed.fields.name?.trim() || basename(path, '.md'),
70
+ description,
71
+ body: parsed.body,
72
+ path,
73
+ });
74
+ }
75
+ return skills;
76
+ }
77
+
78
+ /**
79
+ * Scan two skill roots. `userDir` first so `projectDir` wins on a same-name
80
+ * collision (project → user shadowing).
81
+ */
82
+ export function scanSkills(projectDir: string, userDir: string): Skill[] {
83
+ const byName = new Map<string, Skill>();
84
+ for (const skill of [...readSkillsDir(userDir), ...readSkillsDir(projectDir)]) {
85
+ byName.set(skill.name, skill);
86
+ }
87
+ return [...byName.values()];
88
+ }
89
+
90
+ interface SkillsCache {
91
+ projectDir: string;
92
+ userDir: string;
93
+ skills: Skill[];
94
+ }
95
+
96
+ let cache: SkillsCache | undefined;
97
+
98
+ function defaultRoots(): {projectDir: string; userDir: string} {
99
+ return {
100
+ projectDir: join(process.cwd(), '.pal', 'skills'),
101
+ userDir: join(homedir(), '.pal', 'skills'),
102
+ };
103
+ }
104
+
105
+ /** Skills from the default roots, cached until {@link clearSkillsCache}. */
106
+ export function listSkills(): Skill[] {
107
+ const roots = defaultRoots();
108
+ if (cache && cache.projectDir === roots.projectDir && cache.userDir === roots.userDir) {
109
+ return cache.skills;
110
+ }
111
+ cache = {
112
+ projectDir: roots.projectDir,
113
+ userDir: roots.userDir,
114
+ skills: scanSkills(roots.projectDir, roots.userDir),
115
+ };
116
+ return cache.skills;
117
+ }
118
+
119
+ /** One skill by exact name, or null. */
120
+ export function getSkill(name: string): Skill | null {
121
+ return listSkills().find((s) => s.name === name) ?? null;
122
+ }
123
+
124
+ /** Drop the cache so `/reload` and tests pick up file edits. */
125
+ export function clearSkillsCache(): void {
126
+ cache = undefined;
127
+ }
128
+
129
+ /** Compact `name: description` listing for the system prompt; '' when none. */
130
+ export function buildSkillsPrompt(): string {
131
+ const skills = listSkills();
132
+ if (skills.length === 0) return '';
133
+ return [
134
+ 'Skills — load full instructions with the `load_skill` tool before following one:',
135
+ ...skills.map((s) => `- ${s.name}: ${s.description}`),
136
+ ].join('\n');
137
+ }
138
+
139
+ const LOAD_SKILL_TOOL: ToolDef = {
140
+ type: 'function',
141
+ function: {
142
+ name: 'load_skill',
143
+ description:
144
+ 'Load a skill’s full instructions by name (skills are listed in the system prompt).',
145
+ parameters: {
146
+ type: 'object',
147
+ properties: {
148
+ name: {type: 'string', description: 'Skill name'},
149
+ },
150
+ required: ['name'],
151
+ },
152
+ },
153
+ };
154
+
155
+ const loadSkillHandler: ToolHandlerFn = async (args) => {
156
+ const name = String(args.name ?? '').trim();
157
+ const skill = name ? getSkill(name) : null;
158
+ if (!skill) {
159
+ const names = listSkills()
160
+ .map((s) => s.name)
161
+ .join(', ');
162
+ return `Error: unknown skill "${name}". Available: ${names || '(none)'}`;
163
+ }
164
+ return skill.body;
165
+ };
166
+
167
+ /**
168
+ * The `load_skill` tool definition, or null when no skill files exist.
169
+ *
170
+ * Side effect: registers the handler once — idempotent, so per-turn
171
+ * `getAllTools()` calls don't churn the registry.
172
+ */
173
+ export function ensureSkillTool(): ToolDef | null {
174
+ if (listSkills().length === 0) return null;
175
+ registry.extensionHandlers.load_skill ??= loadSkillHandler;
176
+ return LOAD_SKILL_TOOL;
177
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Live subagent activity — a tiny shared counter the UI can observe while the
3
+ * main agent loop is parked awaiting `delegate` / `delegate_parallel` children.
4
+ *
5
+ * The executor increments around child spawn/wait (`executeChild`), so the
6
+ * count is symmetric by construction: every start has a matching settle on the
7
+ * success, error, and abort paths. A leaked count would leave a permanent
8
+ * phantom status line, so the pairing lives next to the spawn's try/finally.
9
+ *
10
+ * Design notes:
11
+ * - Zero imports ⇒ no cycle risk; safe to import from the tool executor.
12
+ * - The listener set is empty in normal CLI-free/embed use: notify() returns
13
+ * immediately when nobody subscribed, so the idle path adds no events.
14
+ * - Listeners are invoked defensively (a broken listener must not break the
15
+ * agent), mirroring `emitAgentEvent` in ./events.ts.
16
+ */
17
+
18
+ /** Snapshot of current child activity. */
19
+ export interface SubagentStatus {
20
+ /** Children currently spawned and not yet settled. */
21
+ readonly active: number;
22
+ /** Epoch ms of the first spawn in the current burst; 0 when `active` is 0. */
23
+ readonly startedAt: number;
24
+ }
25
+
26
+ type Listener = (status: SubagentStatus) => void;
27
+
28
+ let active = 0;
29
+ let startedAt = 0;
30
+ const listeners = new Set<Listener>();
31
+
32
+ /** Record a child spawn. Starts the burst clock on the 0 → 1 transition. */
33
+ export function subagentSpawned(): void {
34
+ if (active === 0) startedAt = Date.now();
35
+ active += 1;
36
+ notify();
37
+ }
38
+
39
+ /**
40
+ * Record a child settling (success, error, or abort). Floors at 0 so an
41
+ * unbalanced settle can never flip the count negative — a negative count would
42
+ * hide the indicator for every later burst.
43
+ */
44
+ export function subagentSettled(): void {
45
+ if (active === 0) return;
46
+ active -= 1;
47
+ if (active === 0) startedAt = 0;
48
+ notify();
49
+ }
50
+
51
+ /** Current snapshot — `startedAt` is meaningful only while `active > 0`. */
52
+ export function getSubagentStatus(): SubagentStatus {
53
+ return {active, startedAt};
54
+ }
55
+
56
+ /**
57
+ * Subscribe to count changes. Returns an unsubscribe function; after calling
58
+ * it the listener is never invoked again. Not called on subscribe (the UI
59
+ * reads `getSubagentStatus()` for the initial render).
60
+ */
61
+ export function onSubagentStatusChange(fn: Listener): () => void {
62
+ listeners.add(fn);
63
+ return () => {
64
+ listeners.delete(fn);
65
+ };
66
+ }
67
+
68
+ function notify(): void {
69
+ if (listeners.size === 0) return;
70
+ const status: SubagentStatus = {active, startedAt};
71
+ for (const fn of [...listeners]) {
72
+ try {
73
+ fn(status);
74
+ } catch {
75
+ /* a broken listener must not break the agent */
76
+ }
77
+ }
78
+ }
package/src/config.ts CHANGED
@@ -41,15 +41,50 @@ export interface ToolConfig {
41
41
  args: string,
42
42
  id: string,
43
43
  providerConfig: unknown,
44
+ signal?: AbortSignal,
44
45
  ) => Promise<{content: string; error?: boolean}>;
45
46
  };
47
+ /**
48
+ * The turn's abort signal, attached by `executeTool` for the duration of one
49
+ * call so delegate handlers can hand it to their child runs. Never written
50
+ * to the cached config — only present on the per-call copy.
51
+ */
52
+ signal?: AbortSignal;
53
+ /**
54
+ * Orchestration settings from `.pal.json` (`{"orchestration": {"max_parallel": 3}}`).
55
+ *
56
+ * Absent when the key is missing or invalid — callers fall back through
57
+ * the role provider to `DEFAULT_MAX_PARALLEL` (see `getMaxParallel`).
58
+ */
59
+ orchestration?: {
60
+ /** Max concurrent children in a delegate fan-out. */
61
+ maxParallel: number;
62
+ };
63
+ /**
64
+ * Auto-diagnostics after successful edits (`.pal.json` → `"diagnostics"`).
65
+ *
66
+ * - `auto` — run checks and inject one line into the model's next round (default)
67
+ * - `verify-only` — run checks and surface the line to the user only
68
+ * - `off` — never run
69
+ */
70
+ diagnostics: DiagnosticsMode;
46
71
  }
47
72
 
73
+ /** `.pal.json` → `"diagnostics"` modes. `auto` is the default. */
74
+ export type DiagnosticsMode = 'auto' | 'verify-only' | 'off';
75
+
76
+ const DIAGNOSTICS_MODES: ReadonlySet<string> = new Set<DiagnosticsMode>([
77
+ 'auto',
78
+ 'verify-only',
79
+ 'off',
80
+ ]);
81
+
48
82
  const DEFAULT_CONFIG: ToolConfig = {
49
83
  ignore: ['node_modules', '.git', 'dist', 'build', '*.lockb', '*.log'],
50
84
  ignoreLargeFiles: true,
51
85
  maxFileSizeKB: 512,
52
86
  readLineLimit: 2000,
87
+ diagnostics: 'auto',
53
88
  };
54
89
 
55
90
  const CONFIG_FILENAMES = ['.pal.json', '.pal.config.json'];
@@ -122,8 +157,14 @@ export const PERMISSION_FILENAMES = ['permissions.json'];
122
157
  * Each entry is a [regex, description] pair.
123
158
  */
124
159
  export const DANGEROUS_BASH_PATTERNS: Array<[RegExp, string]> = [
125
- [/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'],
126
- [/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'],
160
+ [
161
+ /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+[\/~]/,
162
+ 'recursive force delete from root or home',
163
+ ],
164
+ [
165
+ /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*$/,
166
+ 'recursive force delete with wildcard',
167
+ ],
127
168
  [/\bcurl\b.*\|\s*(ba)?sh\b/, 'piping curl output to shell'],
128
169
  [/\bwget\b.*\|\s*(ba)?sh\b/, 'piping wget output to shell'],
129
170
  [/\bsh\b\s+-c\s+["'].*curl/, 'executing curl via sh -c'],
@@ -296,6 +337,13 @@ export function loadAgentConfig(cwd?: string): ToolConfig {
296
337
  if (typeof parsed.readLineLimit === 'number') {
297
338
  config.readLineLimit = parsed.readLineLimit;
298
339
  }
340
+ const maxParallel = parsed.orchestration?.max_parallel;
341
+ if (typeof maxParallel === 'number' && Number.isFinite(maxParallel) && maxParallel >= 1) {
342
+ config.orchestration = {maxParallel: Math.floor(maxParallel)};
343
+ }
344
+ if (DIAGNOSTICS_MODES.has(parsed.diagnostics)) {
345
+ config.diagnostics = parsed.diagnostics;
346
+ }
299
347
 
300
348
  foundPath = configPath;
301
349
  break;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Subprocess layer for auto-diagnostics (roadmap #1, Phase 1).
3
+ *
4
+ * Spawns `biome check` on the changed files and `tsc --noEmit --incremental`
5
+ * on the project, both bounded by the caller's budget. Every infrastructure
6
+ * failure (missing binary, spawn error, timeout, unparseable output) resolves
7
+ * to `null` — never throws into the agent loop.
8
+ */
9
+
10
+ import {extname, relative, resolve} from 'path';
11
+ import {log} from './logger.js';
12
+ import type {DiagnosticError} from './diagnostics.js';
13
+
14
+ const BIOME_EXTS = new Set([
15
+ '.ts',
16
+ '.tsx',
17
+ '.mts',
18
+ '.cts',
19
+ '.js',
20
+ '.jsx',
21
+ '.mjs',
22
+ '.cjs',
23
+ '.json',
24
+ '.jsonc',
25
+ '.css',
26
+ ]);
27
+ const TS_EXTS = new Set(['.ts', '.tsx', '.mts', '.cts']);
28
+
29
+ /**
30
+ * Run biome + incremental tsc against a batch of changed files.
31
+ * Returns `null` when nothing could be checked (skip), `[]` when clean.
32
+ */
33
+ export async function runChecks(
34
+ files: readonly string[],
35
+ ctx: {cwd: string; budgetMs: number},
36
+ ): Promise<DiagnosticError[] | null> {
37
+ // Spawning bunx from inside the test process leaves orphan children behind;
38
+ // tests exercise the flow through an injected checker instead.
39
+ if (process.env.NODE_ENV === 'test') return null;
40
+
41
+ const biomeFiles = files.filter((f) => BIOME_EXTS.has(extname(f).toLowerCase()));
42
+ const needsTsc = files.some((f) => TS_EXTS.has(extname(f).toLowerCase()));
43
+ if (biomeFiles.length === 0 && !needsTsc) return null;
44
+
45
+ const [biome, tsc] = await Promise.all([
46
+ biomeFiles.length > 0 ? runBiome(biomeFiles, ctx) : Promise.resolve(null),
47
+ needsTsc ? runTsc(ctx) : Promise.resolve(null),
48
+ ]);
49
+ if (biome === null && tsc === null) return null;
50
+
51
+ const changed = new Set(files.map((f) => toRelPath(f, ctx.cwd)));
52
+ const tscErrors = tsc ?? [];
53
+ return [
54
+ ...(biome ?? []),
55
+ ...tscErrors.filter((e) => changed.has(e.path)),
56
+ ...tscErrors.filter((e) => !changed.has(e.path)),
57
+ ];
58
+ }
59
+
60
+ async function runBiome(
61
+ files: readonly string[],
62
+ ctx: {cwd: string; budgetMs: number},
63
+ ): Promise<DiagnosticError[] | null> {
64
+ const args = files.map((f) => quoteArg(toRelPath(f, ctx.cwd))).join(' ');
65
+ const res = await runCommand(`bunx biome check --reporter=json ${args}`, ctx.cwd, ctx.budgetMs);
66
+ if (res === null || res.timedOut) return null;
67
+ return parseBiomeReport(res.stdout);
68
+ }
69
+
70
+ async function runTsc(ctx: {cwd: string; budgetMs: number}): Promise<DiagnosticError[] | null> {
71
+ const res = await runCommand('bunx tsc --noEmit --incremental', ctx.cwd, ctx.budgetMs);
72
+ if (res === null || res.timedOut) return null;
73
+ if (res.exitCode === 0) return [];
74
+ const errors = parseTscOutput(`${res.stdout}\n${res.stderr}`);
75
+ return errors.length > 0 ? errors : null;
76
+ }
77
+
78
+ interface CommandResult {
79
+ stdout: string;
80
+ stderr: string;
81
+ exitCode: number;
82
+ timedOut: boolean;
83
+ }
84
+
85
+ function spawnCommand(command: string, cwd: string) {
86
+ try {
87
+ return Bun.spawn(
88
+ process.platform === 'win32' ? ['cmd', '/d', '/c', command] : ['bash', '-c', command],
89
+ {
90
+ stdout: 'pipe',
91
+ stderr: 'pipe',
92
+ stdin: 'ignore',
93
+ cwd,
94
+ },
95
+ );
96
+ } catch (err) {
97
+ // Spawn-class failure (ENOENT/EACCES) — skip silently, never reach the model.
98
+ log('diagnostics-spawn', {command, message: err instanceof Error ? err.message : String(err)});
99
+ return null;
100
+ }
101
+ }
102
+
103
+ async function runCommand(
104
+ command: string,
105
+ cwd: string,
106
+ timeoutMs: number,
107
+ ): Promise<CommandResult | null> {
108
+ const proc = spawnCommand(command, cwd);
109
+ if (proc === null) return null;
110
+
111
+ let timedOut = false;
112
+ const timer = setTimeout(() => {
113
+ timedOut = true;
114
+ try {
115
+ proc.kill();
116
+ } catch {
117
+ // Kill races the exit — a dead process has nothing to kill.
118
+ }
119
+ }, timeoutMs);
120
+
121
+ try {
122
+ const [stdout, stderr] = await Promise.all([
123
+ new Response(proc.stdout as ReadableStream<Uint8Array>).text(),
124
+ new Response(proc.stderr as ReadableStream<Uint8Array>).text(),
125
+ ]);
126
+ const exitCode = await proc.exited;
127
+ return {stdout, stderr, exitCode, timedOut};
128
+ } catch (err) {
129
+ log('diagnostics-read', {command, message: err instanceof Error ? err.message : String(err)});
130
+ return null;
131
+ } finally {
132
+ clearTimeout(timer);
133
+ }
134
+ }
135
+
136
+ /** biome `--reporter=json` output → errors; `null` when the output is unusable. */
137
+ export function parseBiomeReport(stdout: string): DiagnosticError[] | null {
138
+ const start = stdout.indexOf('{');
139
+ const end = stdout.lastIndexOf('}');
140
+ if (start === -1 || end < start) return null;
141
+
142
+ let data: unknown;
143
+ try {
144
+ data = JSON.parse(stdout.slice(start, end + 1));
145
+ } catch (err) {
146
+ log('diagnostics-parse', {
147
+ tool: 'biome',
148
+ message: err instanceof Error ? err.message : String(err),
149
+ });
150
+ return null;
151
+ }
152
+ if (typeof data !== 'object' || data === null || !('diagnostics' in data)) return null;
153
+ const list = data.diagnostics;
154
+ if (!Array.isArray(list)) return null;
155
+
156
+ const errors: DiagnosticError[] = [];
157
+ for (const item of list) {
158
+ const parsed = asBiomeError(item);
159
+ if (parsed !== null) errors.push(parsed);
160
+ }
161
+ return errors;
162
+ }
163
+
164
+ function asBiomeError(item: unknown): DiagnosticError | null {
165
+ if (typeof item !== 'object' || item === null) return null;
166
+ const d = item as {severity?: unknown; message?: unknown; location?: unknown};
167
+ if (d.severity !== 'error' || typeof d.message !== 'string') return null;
168
+ if (typeof d.location !== 'object' || d.location === null) return null;
169
+ const loc = d.location as {path?: unknown; start?: unknown};
170
+ if (typeof loc.path !== 'string' || typeof loc.start !== 'object' || loc.start === null) {
171
+ return null;
172
+ }
173
+ const line = (loc.start as {line?: unknown}).line;
174
+ if (typeof line !== 'number') return null;
175
+ return {path: normalizeSlashes(loc.path), line, message: d.message};
176
+ }
177
+
178
+ const TSC_DIAGNOSTIC = /^(.+?)\((\d+),\d+\):\s+(?:error|warning)\s+(TS\d+):\s*(.+)$/;
179
+
180
+ /** tsc stdout+stderr → errors; non-file diagnostics (config errors) are dropped. */
181
+ export function parseTscOutput(text: string): DiagnosticError[] {
182
+ const errors: DiagnosticError[] = [];
183
+ for (const raw of text.split(/\r?\n/)) {
184
+ const m = TSC_DIAGNOSTIC.exec(raw);
185
+ if (m === null) continue;
186
+ errors.push({path: normalizeSlashes(m[1]), line: Number(m[2]), message: `${m[3]}: ${m[4]}`});
187
+ }
188
+ return errors;
189
+ }
190
+
191
+ function normalizeSlashes(p: string): string {
192
+ return p.replace(/\\/g, '/');
193
+ }
194
+
195
+ function toRelPath(filePath: string, cwd: string): string {
196
+ return normalizeSlashes(relative(cwd, resolve(filePath)));
197
+ }
198
+
199
+ function quoteArg(arg: string): string {
200
+ return /[\s"]/.test(arg) ? `"${arg.replaceAll('"', '\\"')}"` : arg;
201
+ }