@pal-code/core 0.0.12 → 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.
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.13",
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
  *
@@ -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';
@@ -38,10 +39,161 @@ export function getExtensionTools(): readonly ToolDef[] {
38
39
  *
39
40
  * `load_skill` is appended here (rather than sitting in `CORE_TOOLS`) so it
40
41
  * exists only while skill files do — no skills, no tool schema tokens.
42
+ *
43
+ * `delegate` / `delegate_parallel` are rebuilt from the live role registry on
44
+ * every call: extensions register their role provider from `setup()` AFTER this
45
+ * module loads, so a module-load snapshot would keep advertising roles that
46
+ * don't exist (production bug: `agent="explore"` with no extension loaded).
41
47
  */
42
48
  export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
43
49
  const skillTool = ensureSkillTool();
44
- return [...CORE_TOOLS, ...registry.extensionTools, ...extra, ...(skillTool ? [skillTool] : [])];
50
+ const roles = listRoleSpecs();
51
+ const core = CORE_TOOLS.map((tool) => ROLE_DERIVED_TOOLS[tool.function.name]?.(roles) ?? tool);
52
+ return [...core, ...registry.extensionTools, ...extra, ...(skillTool ? [skillTool] : [])];
53
+ }
54
+
55
+ const ROLE_DERIVED_TOOLS: Record<string, (roles: RoleSpec[]) => ToolDef> = {
56
+ delegate: buildDelegateTool,
57
+ delegate_parallel: buildDelegateParallelTool,
58
+ };
59
+
60
+ function formatRoles(roles: RoleSpec[]): string {
61
+ return roles.map((r) => `${r.name} — ${r.description.replace(/\.$/, '')}`).join('; ');
62
+ }
63
+
64
+ /**
65
+ * The `delegate` description, derived from the live role registry.
66
+ *
67
+ * Pure over `roles` so tests can drive the no-provider case (`[]`) and a fake
68
+ * provider without touching the global registry; the default reads `listRoleSpecs()`
69
+ * — the same source `buildRolesPrompt()` uses.
70
+ *
71
+ * With no roles it is generic: it must never name roles that don't exist.
72
+ * With roles it lists the actual configured names + one-line descriptions, so
73
+ * custom `agents.json` setups see *their* roles, not hardcoded OMO names.
74
+ *
75
+ * The trailing sentences are brief-writing guidance (fix #3): the child starts
76
+ * fresh by design, so facts the parent knows must go into `task` — and
77
+ * `recall_history` is the opt-in hatch for earlier main-session context.
78
+ */
79
+ export function buildDelegateDescription(roles: RoleSpec[] = listRoleSpecs()): string {
80
+ const agents = roles.filter((r) => r.kind === 'agent');
81
+ const categories = roles.filter((r) => r.kind === 'category');
82
+
83
+ const routing: string[] = [];
84
+ if (roles.length === 0) {
85
+ routing.push('Omit `agent`/`category` — ad-hoc delegation with default read-only tools.');
86
+ } else {
87
+ if (agents.length > 0) {
88
+ routing.push(`Pass \`agent\` for a read-only specialist: ${formatRoles(agents)}.`);
89
+ }
90
+ if (categories.length > 0) {
91
+ routing.push(`Pass \`category\` for an implementation lane: ${formatRoles(categories)}.`);
92
+ }
93
+ routing.push('Omit both for ad-hoc delegation with default read-only tools.');
94
+ }
95
+
96
+ return [
97
+ 'Delegate a sub-task to a child agent with its own context.',
98
+ ...routing,
99
+ '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.',
100
+ "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.",
101
+ ].join(' ');
102
+ }
103
+
104
+ export function buildDelegateParallelDescription(roles: RoleSpec[] = listRoleSpecs()): string {
105
+ const hint = roles.length > 0 ? ` Available roles: ${roles.map((r) => r.name).join(', ')}.` : '';
106
+ return (
107
+ 'Run several delegates concurrently — each entry takes the same `agent`/`category` as `delegate`.' +
108
+ hint +
109
+ ' Use when sub-tasks are independent (e.g. fan out across three parts of a codebase).' +
110
+ ' Respects the configured max_parallel limit and returns results in input order.'
111
+ );
112
+ }
113
+
114
+ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
115
+ const agentNames = roles.filter((r) => r.kind === 'agent').map((r) => r.name);
116
+ const categoryNames = roles.filter((r) => r.kind === 'category').map((r) => r.name);
117
+ return {
118
+ type: 'function',
119
+ function: {
120
+ name: 'delegate',
121
+ description: buildDelegateDescription(roles),
122
+ parameters: {
123
+ type: 'object',
124
+ properties: {
125
+ task: {
126
+ type: 'string',
127
+ description: 'Clear description of what the child agent should do',
128
+ },
129
+ agent: {
130
+ type: 'string',
131
+ description:
132
+ agentNames.length > 0
133
+ ? `Read-only specialist role, one of: ${agentNames.join(', ')}. Mutually exclusive with \`category\`.`
134
+ : 'Read-only specialist role. Mutually exclusive with `category`.',
135
+ },
136
+ category: {
137
+ type: 'string',
138
+ description:
139
+ categoryNames.length > 0
140
+ ? `Implementation lane, one of: ${categoryNames.join(', ')}. Mutually exclusive with \`agent\`.`
141
+ : 'Implementation lane. Mutually exclusive with `agent`.',
142
+ },
143
+ model: {
144
+ type: 'string',
145
+ description: 'Explicit `provider/model` override. Takes precedence over the role.',
146
+ },
147
+ reasoning: {
148
+ type: 'string',
149
+ enum: ['low', 'medium', 'high'],
150
+ description: 'Reasoning effort override. Takes precedence over the role.',
151
+ },
152
+ tools: {
153
+ type: 'array',
154
+ items: {type: 'string'},
155
+ description:
156
+ 'Tool names the child may use. Default: read-only tools (read_file, list_directory, grep_search, ast_grep, glob_search).',
157
+ },
158
+ max_rounds: {
159
+ type: 'number',
160
+ description: 'Max tool-call rounds for the child (default 5, cap 16)',
161
+ },
162
+ },
163
+ required: ['task'],
164
+ },
165
+ },
166
+ };
167
+ }
168
+
169
+ function buildDelegateParallelTool(roles: RoleSpec[]): ToolDef {
170
+ return {
171
+ type: 'function',
172
+ function: {
173
+ name: 'delegate_parallel',
174
+ description: buildDelegateParallelDescription(roles),
175
+ parameters: {
176
+ type: 'object',
177
+ properties: {
178
+ tasks: {
179
+ type: 'array',
180
+ description: 'Independent delegates to run at the same time.',
181
+ items: {
182
+ type: 'object',
183
+ properties: {
184
+ task: {type: 'string', description: 'Task description'},
185
+ agent: {type: 'string', description: 'Read-only specialist role'},
186
+ category: {type: 'string', description: 'Implementation lane'},
187
+ model: {type: 'string', description: 'Explicit provider/model override'},
188
+ },
189
+ required: ['task'],
190
+ },
191
+ },
192
+ },
193
+ required: ['tasks'],
194
+ },
195
+ },
196
+ };
45
197
  }
46
198
 
47
199
  export const CORE_TOOLS: ToolDef[] = [
@@ -231,81 +383,8 @@ export const CORE_TOOLS: ToolDef[] = [
231
383
  },
232
384
  },
233
385
  },
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
- },
386
+ buildDelegateTool([]),
387
+ buildDelegateParallelTool([]),
309
388
  {
310
389
  type: 'function',
311
390
  function: {
@@ -331,7 +410,7 @@ export const CORE_TOOLS: ToolDef[] = [
331
410
  function: {
332
411
  name: 'recall_history',
333
412
  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.',
413
+ "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
414
  parameters: {
336
415
  type: 'object',
337
416
  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});