@pal-code/core 0.0.12 → 0.0.14

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.12",
3
+ "version": "0.0.14",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/src/agent/run.ts CHANGED
@@ -85,6 +85,7 @@ export interface ChildProviderConfig {
85
85
  args: string,
86
86
  id: string,
87
87
  providerConfig: ChildProviderConfig,
88
+ signal?: AbortSignal,
88
89
  ) => Promise<{content: string; error?: boolean}>;
89
90
  }
90
91
 
@@ -171,12 +172,16 @@ export interface RunAgentOptions {
171
172
  /**
172
173
  * Tool executor. Injected by the caller so this module never imports the
173
174
  * tool registry (which would create a cycle: executor → run → executor).
175
+ *
176
+ * `signal` is the turn's abort signal, forwarded so long-running tools
177
+ * (delegated child agents) can be cancelled by the same ESC as the stream.
174
178
  */
175
179
  executeTool: (
176
180
  name: string,
177
181
  args: string,
178
182
  id: string,
179
183
  providerConfig: ChildProviderConfig,
184
+ signal?: AbortSignal,
180
185
  ) => Promise<{content: string; error?: boolean}>;
181
186
  }
182
187
 
@@ -675,7 +680,7 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
675
680
  type Display = (typeof displays)[number];
676
681
  const runOne = async (d: Display) => {
677
682
  const started = Date.now();
678
- const result = await executeTool(d.tc.name, d.tc.arguments, d.tc.id, providerConfig);
683
+ const result = await executeTool(d.tc.name, d.tc.arguments, d.tc.id, providerConfig, signal);
679
684
  return {tc: d.tc, result, ms: Date.now() - started};
680
685
  };
681
686
 
@@ -754,6 +759,16 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
754
759
  // Safe now the tool group is complete.
755
760
  for (const content of nudges) messages.push({role: 'user', content});
756
761
 
762
+ // A user interrupt may have landed while a tool (e.g. a delegated child)
763
+ // was executing. Every tool result above is already recorded, so the
764
+ // transcript stays protocol-valid; end the turn here with the same
765
+ // `aborted` event a stream interrupt produces — before hardStop/budget,
766
+ // which would otherwise fall through to `done`.
767
+ if (signal?.aborted) {
768
+ yield {type: 'aborted'};
769
+ return;
770
+ }
771
+
757
772
  if (hardStop) {
758
773
  yield {type: 'notice', text: `! loop detected (same call ${REPEAT_STOP}×) — stopping early`};
759
774
  stoppedEarly = true;
package/src/config.ts CHANGED
@@ -41,8 +41,15 @@ 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;
46
53
  /**
47
54
  * Orchestration settings from `.pal.json` (`{"orchestration": {"max_parallel": 3}}`).
48
55
  *
package/src/extensions.ts CHANGED
@@ -34,6 +34,7 @@ import {realpathSync} from 'node:fs';
34
34
  import {homedir} from 'node:os';
35
35
  import {isAbsolute, join, relative} from 'node:path';
36
36
  import type {ToolDef} from './tools/definitions.js';
37
+ import {clearExtensionTools} from './tools/definitions.js';
37
38
  import type {ToolConfig} from './config.js';
38
39
  import type {LifecycleHandlers} from './lifecycle.js';
39
40
  import {clearRoleProvider} from './agent/roles.js';
@@ -205,6 +206,9 @@ export async function loadExtensions(
205
206
  // Clear any previously-registered role provider *before* (re)loading. If the
206
207
  // extension that provides it is gone or fails, its roles must not linger.
207
208
  clearRoleProvider();
209
+ // Same for extension tools: clear previously-registered ones *before*
210
+ // (re)loading, so a removed extension or MCP server's tools don't linger on /reload.
211
+ clearExtensionTools();
208
212
 
209
213
  for (const pkg of extensionPackages) {
210
214
  try {
package/src/index.ts CHANGED
@@ -108,6 +108,7 @@ export {
108
108
  CORE_TOOLS,
109
109
  getAllTools,
110
110
  registerExtensionTools,
111
+ clearExtensionTools,
111
112
  getExtensionTools,
112
113
  } from './tools/definitions.js';
113
114
  export type {ToolDef} from './tools/definitions.js';
package/src/lifecycle.ts CHANGED
@@ -71,7 +71,9 @@ export type LifecycleHandlers = {
71
71
  /**
72
72
  * Replace the registered lifecycle hooks. Called when extensions load and on
73
73
  * `/reload` — replace rather than merge so a removed extension's hooks neither
74
- * linger nor duplicate (same semantics as `registerExtensionTools`).
74
+ * linger nor duplicate. (Unlike `registerExtensionTools`, which merges — tools
75
+ * may register themselves from inside an extension's `setup()` before the load
76
+ * list arrives.)
75
77
  */
76
78
  export function registerExtensionLifecycle(hooks: readonly LifecycleHandlers[]): void {
77
79
  registry.lifecycleHooks = [...hooks];
@@ -4,6 +4,7 @@
4
4
 
5
5
  import {registry} from '../registry.js';
6
6
  import {ensureSkillTool} from '../agent/skills.js';
7
+ import {listRoleSpecs, type RoleSpec} from '../agent/roles.js';
7
8
 
8
9
  export interface ToolDef {
9
10
  type: 'function';
@@ -21,10 +22,36 @@ export interface ToolDef {
21
22
  * so that `delegate` can hand the *full* toolset to child agents. Without this
22
23
  * a role like `librarian`, whose tools are all extension-provided, would spawn
23
24
  * a child with no usable tools at all.
25
+ *
26
+ * Two registration paths feed this: extensions like @pal-code/mcp register
27
+ * discovered tools from inside their `setup()` (packages/mcp/src/index.ts:58),
28
+ * while the rest arrive via `loadExtensions`' returned list registered by the
29
+ * CLI (packages/cli/src/turn.ts:58).
30
+ */
31
+ /**
32
+ * Merge the registered extension tools by `function.name` — a later
33
+ * registration of the same name wins (upsert). Called on load and on `/reload`.
34
+ *
35
+ * Merge, not replace: replacing wiped whichever path registered first — e.g.
36
+ * turn.ts's register of the load list erased the 34 MCP tools mcp's `setup()`
37
+ * had already registered ("34 MCP tools wiped to 4"). Removal of reload-stale
38
+ * tools is `clearExtensionTools()`'s job, called at load start.
39
+ * Non-array input still resets the registry (defensive).
24
40
  */
25
- /** Replace the registered extension tools. Called on load and on `/reload`. */
26
41
  export function registerExtensionTools(tools: ToolDef[]): void {
27
- registry.extensionTools = Array.isArray(tools) ? [...tools] : [];
42
+ if (!Array.isArray(tools)) {
43
+ registry.extensionTools = [];
44
+ return;
45
+ }
46
+ // O(n): one Map keyed on function.name; existing entries keep their order.
47
+ const byName = new Map(registry.extensionTools.map((t) => [t.function.name, t]));
48
+ for (const tool of tools) byName.set(tool.function.name, tool);
49
+ registry.extensionTools = [...byName.values()];
50
+ }
51
+
52
+ /** Drop every registered extension tool — called before (re)loading extensions. */
53
+ export function clearExtensionTools(): void {
54
+ registry.extensionTools = [];
28
55
  }
29
56
 
30
57
  /** The extension tools currently registered (read-only view). */
@@ -38,10 +65,161 @@ export function getExtensionTools(): readonly ToolDef[] {
38
65
  *
39
66
  * `load_skill` is appended here (rather than sitting in `CORE_TOOLS`) so it
40
67
  * exists only while skill files do — no skills, no tool schema tokens.
68
+ *
69
+ * `delegate` / `delegate_parallel` are rebuilt from the live role registry on
70
+ * every call: extensions register their role provider from `setup()` AFTER this
71
+ * module loads, so a module-load snapshot would keep advertising roles that
72
+ * don't exist (production bug: `agent="explore"` with no extension loaded).
41
73
  */
42
74
  export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
43
75
  const skillTool = ensureSkillTool();
44
- return [...CORE_TOOLS, ...registry.extensionTools, ...extra, ...(skillTool ? [skillTool] : [])];
76
+ const roles = listRoleSpecs();
77
+ const core = CORE_TOOLS.map((tool) => ROLE_DERIVED_TOOLS[tool.function.name]?.(roles) ?? tool);
78
+ return [...core, ...registry.extensionTools, ...extra, ...(skillTool ? [skillTool] : [])];
79
+ }
80
+
81
+ const ROLE_DERIVED_TOOLS: Record<string, (roles: RoleSpec[]) => ToolDef> = {
82
+ delegate: buildDelegateTool,
83
+ delegate_parallel: buildDelegateParallelTool,
84
+ };
85
+
86
+ function formatRoles(roles: RoleSpec[]): string {
87
+ return roles.map((r) => `${r.name} — ${r.description.replace(/\.$/, '')}`).join('; ');
88
+ }
89
+
90
+ /**
91
+ * The `delegate` description, derived from the live role registry.
92
+ *
93
+ * Pure over `roles` so tests can drive the no-provider case (`[]`) and a fake
94
+ * provider without touching the global registry; the default reads `listRoleSpecs()`
95
+ * — the same source `buildRolesPrompt()` uses.
96
+ *
97
+ * With no roles it is generic: it must never name roles that don't exist.
98
+ * With roles it lists the actual configured names + one-line descriptions, so
99
+ * custom `agents.json` setups see *their* roles, not hardcoded OMO names.
100
+ *
101
+ * The trailing sentences are brief-writing guidance (fix #3): the child starts
102
+ * fresh by design, so facts the parent knows must go into `task` — and
103
+ * `recall_history` is the opt-in hatch for earlier main-session context.
104
+ */
105
+ export function buildDelegateDescription(roles: RoleSpec[] = listRoleSpecs()): string {
106
+ const agents = roles.filter((r) => r.kind === 'agent');
107
+ const categories = roles.filter((r) => r.kind === 'category');
108
+
109
+ const routing: string[] = [];
110
+ if (roles.length === 0) {
111
+ routing.push('Omit `agent`/`category` — ad-hoc delegation with default read-only tools.');
112
+ } else {
113
+ if (agents.length > 0) {
114
+ routing.push(`Pass \`agent\` for a read-only specialist: ${formatRoles(agents)}.`);
115
+ }
116
+ if (categories.length > 0) {
117
+ routing.push(`Pass \`category\` for an implementation lane: ${formatRoles(categories)}.`);
118
+ }
119
+ routing.push('Omit both for ad-hoc delegation with default read-only tools.');
120
+ }
121
+
122
+ return [
123
+ 'Delegate a sub-task to a child agent with its own context.',
124
+ ...routing,
125
+ 'The child starts with a fresh context — deliberate isolation (focus, cost, no prompt poisoning) — so put known facts INTO `task`: paths, schema/constraints, and hypotheses you already disproved; anything omitted must be re-discovered from scratch.',
126
+ "For earlier main-session context, paste the relevant facts into `task` yourself, or have the child call `recall_history` — an opt-in hatch that returns the main conversation's earlier messages.",
127
+ ].join(' ');
128
+ }
129
+
130
+ export function buildDelegateParallelDescription(roles: RoleSpec[] = listRoleSpecs()): string {
131
+ const hint = roles.length > 0 ? ` Available roles: ${roles.map((r) => r.name).join(', ')}.` : '';
132
+ return (
133
+ 'Run several delegates concurrently — each entry takes the same `agent`/`category` as `delegate`.' +
134
+ hint +
135
+ ' Use when sub-tasks are independent (e.g. fan out across three parts of a codebase).' +
136
+ ' Respects the configured max_parallel limit and returns results in input order.'
137
+ );
138
+ }
139
+
140
+ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
141
+ const agentNames = roles.filter((r) => r.kind === 'agent').map((r) => r.name);
142
+ const categoryNames = roles.filter((r) => r.kind === 'category').map((r) => r.name);
143
+ return {
144
+ type: 'function',
145
+ function: {
146
+ name: 'delegate',
147
+ description: buildDelegateDescription(roles),
148
+ parameters: {
149
+ type: 'object',
150
+ properties: {
151
+ task: {
152
+ type: 'string',
153
+ description: 'Clear description of what the child agent should do',
154
+ },
155
+ agent: {
156
+ type: 'string',
157
+ description:
158
+ agentNames.length > 0
159
+ ? `Read-only specialist role, one of: ${agentNames.join(', ')}. Mutually exclusive with \`category\`.`
160
+ : 'Read-only specialist role. Mutually exclusive with `category`.',
161
+ },
162
+ category: {
163
+ type: 'string',
164
+ description:
165
+ categoryNames.length > 0
166
+ ? `Implementation lane, one of: ${categoryNames.join(', ')}. Mutually exclusive with \`agent\`.`
167
+ : 'Implementation lane. Mutually exclusive with `agent`.',
168
+ },
169
+ model: {
170
+ type: 'string',
171
+ description: 'Explicit `provider/model` override. Takes precedence over the role.',
172
+ },
173
+ reasoning: {
174
+ type: 'string',
175
+ enum: ['low', 'medium', 'high'],
176
+ description: 'Reasoning effort override. Takes precedence over the role.',
177
+ },
178
+ tools: {
179
+ type: 'array',
180
+ items: {type: 'string'},
181
+ description:
182
+ 'Tool names the child may use. Default: read-only tools (read_file, list_directory, grep_search, ast_grep, glob_search).',
183
+ },
184
+ max_rounds: {
185
+ type: 'number',
186
+ description: 'Max tool-call rounds for the child (default 5, cap 16)',
187
+ },
188
+ },
189
+ required: ['task'],
190
+ },
191
+ },
192
+ };
193
+ }
194
+
195
+ function buildDelegateParallelTool(roles: RoleSpec[]): ToolDef {
196
+ return {
197
+ type: 'function',
198
+ function: {
199
+ name: 'delegate_parallel',
200
+ description: buildDelegateParallelDescription(roles),
201
+ parameters: {
202
+ type: 'object',
203
+ properties: {
204
+ tasks: {
205
+ type: 'array',
206
+ description: 'Independent delegates to run at the same time.',
207
+ items: {
208
+ type: 'object',
209
+ properties: {
210
+ task: {type: 'string', description: 'Task description'},
211
+ agent: {type: 'string', description: 'Read-only specialist role'},
212
+ category: {type: 'string', description: 'Implementation lane'},
213
+ model: {type: 'string', description: 'Explicit provider/model override'},
214
+ },
215
+ required: ['task'],
216
+ },
217
+ },
218
+ },
219
+ required: ['tasks'],
220
+ },
221
+ },
222
+ };
45
223
  }
46
224
 
47
225
  export const CORE_TOOLS: ToolDef[] = [
@@ -231,81 +409,8 @@ export const CORE_TOOLS: ToolDef[] = [
231
409
  },
232
410
  },
233
411
  },
234
- {
235
- type: 'function',
236
- function: {
237
- name: 'delegate',
238
- description:
239
- 'Delegate a sub-task to a child agent with its own context. Pass `agent` for a read-only specialist (explore, librarian, plan-consultant, plan-reviewer) or `category` for an implementation lane (build, architect, deep, quick, writing, review). Omit both for ad-hoc delegation with default read-only tools.',
240
- parameters: {
241
- type: 'object',
242
- properties: {
243
- task: {
244
- type: 'string',
245
- description: 'Clear description of what the child agent should do',
246
- },
247
- agent: {
248
- type: 'string',
249
- description:
250
- 'Read-only specialist role (e.g. "explore", "librarian"). Mutually exclusive with `category`.',
251
- },
252
- category: {
253
- type: 'string',
254
- description:
255
- 'Implementation lane (e.g. "build", "deep", "architect"). Mutually exclusive with `agent`.',
256
- },
257
- model: {
258
- type: 'string',
259
- description: 'Explicit `provider/model` override. Takes precedence over the role.',
260
- },
261
- reasoning: {
262
- type: 'string',
263
- enum: ['low', 'medium', 'high'],
264
- description: 'Reasoning effort override. Takes precedence over the role.',
265
- },
266
- tools: {
267
- type: 'array',
268
- items: {type: 'string'},
269
- description:
270
- 'Tool names the child may use. Default: read-only tools (read_file, list_directory, grep_search, ast_grep, glob_search).',
271
- },
272
- max_rounds: {
273
- type: 'number',
274
- description: 'Max tool-call rounds for the child (default 5, cap 16)',
275
- },
276
- },
277
- required: ['task'],
278
- },
279
- },
280
- },
281
- {
282
- type: 'function',
283
- function: {
284
- name: 'delegate_parallel',
285
- description:
286
- 'Run several delegates concurrently. Use when sub-tasks are independent (e.g. explore three parts of a codebase, or research + explore at once). Respects the configured max_parallel limit and returns results in input order.',
287
- parameters: {
288
- type: 'object',
289
- properties: {
290
- tasks: {
291
- type: 'array',
292
- description: 'Independent delegates to run at the same time.',
293
- items: {
294
- type: 'object',
295
- properties: {
296
- task: {type: 'string', description: 'Task description'},
297
- agent: {type: 'string', description: 'Read-only specialist role'},
298
- category: {type: 'string', description: 'Implementation lane'},
299
- model: {type: 'string', description: 'Explicit provider/model override'},
300
- },
301
- required: ['task'],
302
- },
303
- },
304
- },
305
- required: ['tasks'],
306
- },
307
- },
308
- },
412
+ buildDelegateTool([]),
413
+ buildDelegateParallelTool([]),
309
414
  {
310
415
  type: 'function',
311
416
  function: {
@@ -331,7 +436,7 @@ export const CORE_TOOLS: ToolDef[] = [
331
436
  function: {
332
437
  name: 'recall_history',
333
438
  description:
334
- 'Read transcript that was summarized away by context compaction. When older messages are folded into a checkpoint they stop being sent to you, but they remain on disk — use this to recover exact details (a path, an error, an earlier decision) from that summarized prefix. Returns the raw messages, not a summary.',
439
+ "Opt-in context hatch for delegation and continuation: returns the main conversation's earlier messages as raw transcript rows (not a summary). Only the prefix context compaction folded away is returned — messages still being sent to the model are excluded — and it reports when nothing has been compacted yet. Use it to recover an exact path, error, or earlier decision; a delegated child, whose own context starts empty, can pull the parent's earlier context the same way. Paginate with offset (default 0) and limit (default 20, max 100).",
335
440
  parameters: {
336
441
  type: 'object',
337
442
  properties: {
@@ -1042,6 +1042,7 @@ export async function executeTool(
1042
1042
  readOnly?: boolean;
1043
1043
  allowedTools?: string[];
1044
1044
  },
1045
+ signal?: AbortSignal,
1045
1046
  ): Promise<ToolResult> {
1046
1047
  const fn = tools[name] ?? registry.extensionHandlers[name];
1047
1048
  if (!fn) {
@@ -1081,6 +1082,11 @@ export async function executeTool(
1081
1082
  config.provider = providerConfigOverride;
1082
1083
  }
1083
1084
 
1085
+ // Attach the turn's signal per call only — never to the cached config,
1086
+ // where a stale aborted signal would kill later delegations. Undefined
1087
+ // signal → the exact cached object, so non-abort paths are unchanged.
1088
+ const execConfig: ToolConfig = signal ? {...config, signal} : config;
1089
+
1084
1090
  // ── Path containment guard ──
1085
1091
  // Resolve file-mutating paths against the project root and refuse to write
1086
1092
  // outside it. The ignore-list is a deny-list that fails open for `..`
@@ -1107,7 +1113,7 @@ export async function executeTool(
1107
1113
  const startedAt = Date.now();
1108
1114
  let content: string;
1109
1115
  try {
1110
- content = await fn(args, config);
1116
+ content = await fn(args, execConfig);
1111
1117
  } catch (toolErr) {
1112
1118
  // The dispatch record must fire for a failed call too — then rethrow so
1113
1119
  // the outer catch formats the error result exactly as before.
@@ -1381,6 +1387,7 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1381
1387
  // settle is symmetric on success, error, and abort — a leaked count would
1382
1388
  // leave a permanent phantom "subagents running" line in the UI.
1383
1389
  subagentSpawned();
1390
+ const cancelled = 'Delegate cancelled (aborted by user).';
1384
1391
  try {
1385
1392
  const childExec = providerCfg.childExecuteTool ?? executeTool;
1386
1393
  for await (const ev of runAgent({
@@ -1393,6 +1400,7 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1393
1400
  reasoningEffort: reasoning,
1394
1401
  providerConfig: providerCfg,
1395
1402
  executeTool: childExec,
1403
+ signal: config.signal,
1396
1404
  budget: plan.budget,
1397
1405
  })) {
1398
1406
  if (ev.type === 'round-start') {
@@ -1408,6 +1416,10 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1408
1416
  }
1409
1417
  }
1410
1418
  } catch (err) {
1419
+ if (config.signal?.aborted) {
1420
+ emitAgentEvent({type: 'delegate-done', id: agentId, summary: cancelled, error: true});
1421
+ return cancelled;
1422
+ }
1411
1423
  const msg = err instanceof Error ? err.message : String(err);
1412
1424
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: msg, error: true});
1413
1425
  return `Delegate error: ${msg}`;
@@ -1420,6 +1432,13 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1420
1432
  emitAgentEvent({type: 'todos-updated', todos: getTodos()});
1421
1433
  }
1422
1434
 
1435
+ // Aborted mid-run: the run ended with `aborted` (not a summary), so report
1436
+ // the cancellation instead of claiming completion.
1437
+ if (config.signal?.aborted) {
1438
+ emitAgentEvent({type: 'delegate-done', id: agentId, summary: cancelled});
1439
+ return cancelled;
1440
+ }
1441
+
1423
1442
  const summary = roundText.trim() || previousText.trim();
1424
1443
  const finalSummary = summary || 'Task completed (no summary generated).';
1425
1444
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: finalSummary});