@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.
@@ -3,6 +3,8 @@
3
3
  */
4
4
 
5
5
  import {registry} from '../registry.js';
6
+ import {ensureSkillTool} from '../agent/skills.js';
7
+ import {listRoleSpecs, type RoleSpec} from '../agent/roles.js';
6
8
 
7
9
  export interface ToolDef {
8
10
  type: 'function';
@@ -34,9 +36,164 @@ export function getExtensionTools(): readonly ToolDef[] {
34
36
  /**
35
37
  * Get all tools — core tools plus registered extension tools, plus any
36
38
  * explicitly supplied ones (kept for callers that aren't the registry).
39
+ *
40
+ * `load_skill` is appended here (rather than sitting in `CORE_TOOLS`) so it
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).
37
47
  */
38
48
  export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
39
- return [...CORE_TOOLS, ...registry.extensionTools, ...extra];
49
+ const skillTool = ensureSkillTool();
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
+ };
40
197
  }
41
198
 
42
199
  export const CORE_TOOLS: ToolDef[] = [
@@ -75,13 +232,22 @@ export const CORE_TOOLS: ToolDef[] = [
75
232
  type: 'function',
76
233
  function: {
77
234
  name: 'edit_file',
78
- description: 'Replace exact string in file.',
235
+ description:
236
+ 'Replace exact string in file; structural pattern+rewrite fallback when exact text unknown.',
79
237
  parameters: {
80
238
  type: 'object',
81
239
  properties: {
82
240
  path: {type: 'string'},
83
241
  old_string: {type: 'string'},
84
242
  new_string: {type: 'string'},
243
+ pattern: {
244
+ type: 'string',
245
+ description: 'ast-grep pattern with $A captures; tried if old_string misses.',
246
+ },
247
+ rewrite: {
248
+ type: 'string',
249
+ description: 'Replacement built from $A captures; used with pattern.',
250
+ },
85
251
  },
86
252
  required: ['path', 'old_string', 'new_string'],
87
253
  },
@@ -217,81 +383,8 @@ export const CORE_TOOLS: ToolDef[] = [
217
383
  },
218
384
  },
219
385
  },
220
- {
221
- type: 'function',
222
- function: {
223
- name: 'delegate',
224
- description:
225
- '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.',
226
- parameters: {
227
- type: 'object',
228
- properties: {
229
- task: {
230
- type: 'string',
231
- description: 'Clear description of what the child agent should do',
232
- },
233
- agent: {
234
- type: 'string',
235
- description:
236
- 'Read-only specialist role (e.g. "explore", "librarian"). Mutually exclusive with `category`.',
237
- },
238
- category: {
239
- type: 'string',
240
- description:
241
- 'Implementation lane (e.g. "build", "deep", "architect"). Mutually exclusive with `agent`.',
242
- },
243
- model: {
244
- type: 'string',
245
- description: 'Explicit `provider/model` override. Takes precedence over the role.',
246
- },
247
- reasoning: {
248
- type: 'string',
249
- enum: ['low', 'medium', 'high'],
250
- description: 'Reasoning effort override. Takes precedence over the role.',
251
- },
252
- tools: {
253
- type: 'array',
254
- items: {type: 'string'},
255
- description:
256
- 'Tool names the child may use. Default: read-only tools (read_file, list_directory, grep_search, ast_grep, glob_search).',
257
- },
258
- max_rounds: {
259
- type: 'number',
260
- description: 'Max tool-call rounds for the child (default 5, cap 16)',
261
- },
262
- },
263
- required: ['task'],
264
- },
265
- },
266
- },
267
- {
268
- type: 'function',
269
- function: {
270
- name: 'delegate_parallel',
271
- description:
272
- '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.',
273
- parameters: {
274
- type: 'object',
275
- properties: {
276
- tasks: {
277
- type: 'array',
278
- description: 'Independent delegates to run at the same time.',
279
- items: {
280
- type: 'object',
281
- properties: {
282
- task: {type: 'string', description: 'Task description'},
283
- agent: {type: 'string', description: 'Read-only specialist role'},
284
- category: {type: 'string', description: 'Implementation lane'},
285
- model: {type: 'string', description: 'Explicit provider/model override'},
286
- },
287
- required: ['task'],
288
- },
289
- },
290
- },
291
- required: ['tasks'],
292
- },
293
- },
294
- },
386
+ buildDelegateTool([]),
387
+ buildDelegateParallelTool([]),
295
388
  {
296
389
  type: 'function',
297
390
  function: {
@@ -317,7 +410,7 @@ export const CORE_TOOLS: ToolDef[] = [
317
410
  function: {
318
411
  name: 'recall_history',
319
412
  description:
320
- '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).",
321
414
  parameters: {
322
415
  type: 'object',
323
416
  properties: {
@@ -12,7 +12,7 @@ import {promisify} from 'util';
12
12
 
13
13
  const execAsync = promisify(exec);
14
14
  import {createInterface} from 'readline';
15
- import {dirname, resolve, isAbsolute, sep} from 'path';
15
+ import {dirname, resolve, isAbsolute, sep, extname} from 'path';
16
16
  import {minimatch} from 'minimatch';
17
17
  import {
18
18
  loadAgentConfig,
@@ -23,6 +23,7 @@ import {
23
23
  type ToolConfig,
24
24
  } from '../config.js';
25
25
  import {snapshotFile} from '../snapshots.js';
26
+ import {noteEditedFile} from '../diagnostics.js';
26
27
  import type {ConversationMessage} from '../agent/run.js';
27
28
  import {registry} from '../registry.js';
28
29
 
@@ -40,6 +41,8 @@ function ignorePredicate(config: ToolConfig): (absPath: string) => boolean {
40
41
  }
41
42
  import {log} from '../logger.js';
42
43
  import {emitAgentEvent} from '../agent/events.js';
44
+ import {subagentSpawned, subagentSettled} from '../agent/subagent-status.js';
45
+ import {emitLifecycleEvent} from '../lifecycle.js';
43
46
  import {grepJS, globJS} from './search.js';
44
47
  import {setTodos, formatTodos, type TodoStatus} from '../agent/todos.js';
45
48
 
@@ -159,6 +162,108 @@ export function registerExtensionHandlers(
159
162
  Object.assign(registry.extensionHandlers, handlers);
160
163
  }
161
164
 
165
+ // ═══════════════════════════════════════════════════════════════════════════════
166
+ // Structural edit — ast-grep fallback for edit_file (roadmap #2): locate the
167
+ // node by SHAPE when old_string misses whitespace/format churn, then rebuild
168
+ // it from a rewrite template of $A-style captures. One tool, not a general
169
+ // tree-sitter layer.
170
+ // ═══════════════════════════════════════════════════════════════════════════════
171
+
172
+ type StructuralEditResult = {ok: true; updated: string} | {ok: false; reason: string};
173
+
174
+ /** File-extension → grammar map; mirrors `ast_grep`'s LangMap (napi ships no json/markdown). */
175
+ function structuralLangFor(
176
+ sg: typeof import('@ast-grep/napi'),
177
+ ext: string,
178
+ ): (typeof sg.Lang)[keyof typeof sg.Lang] | null {
179
+ switch (ext) {
180
+ case '.ts':
181
+ case '.mts':
182
+ case '.cts':
183
+ return sg.Lang.TypeScript;
184
+ case '.tsx':
185
+ case '.jsx':
186
+ return sg.Lang.Tsx;
187
+ case '.js':
188
+ case '.mjs':
189
+ case '.cjs':
190
+ return sg.Lang.JavaScript;
191
+ case '.css':
192
+ return sg.Lang.Css;
193
+ case '.html':
194
+ case '.htm':
195
+ return sg.Lang.Html;
196
+ default:
197
+ return null;
198
+ }
199
+ }
200
+
201
+ /** Find `pattern` (exactly one match) and rebuild the node from `rewrite`, substituting `$NAME` captures. */
202
+ async function structuralEdit(opts: {
203
+ content: string;
204
+ filePath: string;
205
+ pattern: string;
206
+ rewrite: string;
207
+ }): Promise<StructuralEditResult> {
208
+ const {content, filePath, pattern, rewrite} = opts;
209
+ if (!rewrite) {
210
+ return {ok: false, reason: 'pattern provided without rewrite'};
211
+ }
212
+
213
+ const ext = extname(filePath).toLowerCase();
214
+ let sg: typeof import('@ast-grep/napi');
215
+ try {
216
+ sg = await import('@ast-grep/napi');
217
+ } catch {
218
+ return {ok: false, reason: '@ast-grep/napi unavailable for structural edit'};
219
+ }
220
+
221
+ const lang = structuralLangFor(sg, ext);
222
+ if (!lang) {
223
+ return {
224
+ ok: false,
225
+ reason: `unsupported file type for structural edit: ${ext || '(no extension)'}`,
226
+ };
227
+ }
228
+
229
+ try {
230
+ const root = sg.parse(lang, content);
231
+ const matches = root.root().findAll(pattern);
232
+ if (matches.length === 0) {
233
+ return {ok: false, reason: `structural pattern not found in ${filePath}`};
234
+ }
235
+ if (matches.length > 1) {
236
+ return {
237
+ ok: false,
238
+ reason: `structural pattern matched ${matches.length} nodes in ${filePath} (must match exactly one)`,
239
+ };
240
+ }
241
+
242
+ const match = matches[0];
243
+ const missing: string[] = [];
244
+ const finalText = rewrite.replace(/\$([A-Z][A-Z0-9_]*)/g, (whole, name) => {
245
+ const captured = match.getMatch(name);
246
+ if (!captured) {
247
+ missing.push(name);
248
+ return whole;
249
+ }
250
+ return captured.text();
251
+ });
252
+ if (missing.length > 0) {
253
+ return {
254
+ ok: false,
255
+ reason: `rewrite references ${missing.map((n) => `$${n}`).join(', ')} not captured by pattern`,
256
+ };
257
+ }
258
+ return {ok: true, updated: root.root().commitEdits([match.replace(finalText)])};
259
+ } catch (err) {
260
+ return {
261
+ ok: false,
262
+ reason: `structural pattern error: ${err instanceof Error ? err.message : String(err)}`,
263
+ };
264
+ }
265
+ }
266
+
162
267
  const tools: Record<
163
268
  string,
164
269
  (args: Record<string, unknown>, config: ToolConfig) => Promise<string>
@@ -220,6 +325,8 @@ const tools: Record<
220
325
  const filePath = String(args.path);
221
326
  const oldString = String(args.old_string);
222
327
  const newString = String(args.new_string);
328
+ const pattern = args.pattern == null ? '' : String(args.pattern);
329
+ const rewrite = args.rewrite == null ? '' : String(args.rewrite);
223
330
 
224
331
  if (isPathIgnored(filePath, config)) {
225
332
  throw new Error(`Cannot edit ${filePath} — matches ignore patterns`);
@@ -231,17 +338,28 @@ const tools: Record<
231
338
  // silent footgun — the model gets "Edited successfully" while the wrong
232
339
  // site was changed.
233
340
  const occurrences = content.split(oldString).length - 1;
234
- if (occurrences === 0) {
235
- throw new Error(`old_string not found in ${filePath}`);
236
- }
237
- if (occurrences > 1) {
238
- throw new Error(
239
- `old_string is not unique in ${filePath} (${occurrences} occurrences). ` +
240
- `Narrow the match to exactly one occurrence.`,
241
- );
341
+ const stringError =
342
+ occurrences === 0
343
+ ? `old_string not found in ${filePath}`
344
+ : occurrences > 1
345
+ ? `old_string is not unique in ${filePath} (${occurrences} occurrences). ` +
346
+ `Narrow the match to exactly one occurrence.`
347
+ : null;
348
+
349
+ let updated: string;
350
+ if (stringError === null) {
351
+ updated = content.replace(oldString, newString);
352
+ } else if (pattern) {
353
+ // Spec: exact string match → ast-grep structural match → combined error.
354
+ const structural = await structuralEdit({content, filePath, pattern, rewrite});
355
+ if (!structural.ok) {
356
+ throw new Error(`${stringError} Structural attempt failed: ${structural.reason}`);
357
+ }
358
+ updated = structural.updated;
359
+ } else {
360
+ throw new Error(stringError);
242
361
  }
243
362
 
244
- const updated = content.replace(oldString, newString);
245
363
  snapshotFile(filePath, 'edit_file');
246
364
  await writeFile(filePath, updated, 'utf-8');
247
365
  return `Edited ${filePath} successfully`;
@@ -924,6 +1042,7 @@ export async function executeTool(
924
1042
  readOnly?: boolean;
925
1043
  allowedTools?: string[];
926
1044
  },
1045
+ signal?: AbortSignal,
927
1046
  ): Promise<ToolResult> {
928
1047
  const fn = tools[name] ?? registry.extensionHandlers[name];
929
1048
  if (!fn) {
@@ -953,12 +1072,21 @@ export async function executeTool(
953
1072
  }
954
1073
 
955
1074
  try {
956
- const args = (argsStr && argsStr.trim() ? JSON.parse(argsStr) : {}) as Record<string, unknown>;
1075
+ // Strip NULs (model-emitted or resumed-history corruption) before parse —
1076
+ // a raw null byte makes JSON.parse throw and the whole tool call fail.
1077
+ const args = (
1078
+ argsStr && argsStr.trim() ? JSON.parse(argsStr.replaceAll('\u0000', '')) : {}
1079
+ ) as Record<string, unknown>;
957
1080
  const config = loadAgentConfig();
958
1081
  if (providerConfigOverride) {
959
1082
  config.provider = providerConfigOverride;
960
1083
  }
961
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
+
962
1090
  // ── Path containment guard ──
963
1091
  // Resolve file-mutating paths against the project root and refuse to write
964
1092
  // outside it. The ignore-list is a deny-list that fails open for `..`
@@ -982,12 +1110,41 @@ export async function executeTool(
982
1110
  }
983
1111
 
984
1112
  log('tool-call', {name, args: argsStr});
985
- const content = await fn(args, config);
1113
+ const startedAt = Date.now();
1114
+ let content: string;
1115
+ try {
1116
+ content = await fn(args, execConfig);
1117
+ } catch (toolErr) {
1118
+ // The dispatch record must fire for a failed call too — then rethrow so
1119
+ // the outer catch formats the error result exactly as before.
1120
+ await emitLifecycleEvent('onToolCall', {
1121
+ tool: name,
1122
+ args,
1123
+ durationMs: Date.now() - startedAt,
1124
+ success: false,
1125
+ });
1126
+ throw toolErr;
1127
+ }
986
1128
  log('tool-result', {name, error: false, length: content.length});
1129
+ await emitLifecycleEvent('onToolCall', {
1130
+ tool: name,
1131
+ args,
1132
+ durationMs: Date.now() - startedAt,
1133
+ success: true,
1134
+ });
1135
+ // Fire-and-forget: noteEditedFile only schedules a debounced background
1136
+ // check; the handler returns its result without waiting on diagnostics.
1137
+ if (FILE_WRITERS.has(name) && args.path) {
1138
+ noteEditedFile(String(args.path));
1139
+ }
987
1140
  return {toolCallId, content};
988
1141
  } catch (err) {
989
1142
  const msg = err instanceof Error ? err.message : String(err);
990
1143
  log('tool-result', {name, error: true, message: msg});
1144
+ await emitLifecycleEvent('onError', {
1145
+ error: err instanceof Error ? err : new Error(msg),
1146
+ context: `tool:${name}`,
1147
+ });
991
1148
  return {toolCallId, content: `Error executing ${name}: ${msg}`, error: true};
992
1149
  }
993
1150
  }
@@ -1061,6 +1218,12 @@ interface ChildPlan {
1061
1218
  modelSpec?: string;
1062
1219
  /** True when `tools` contains anything that mutates global state. */
1063
1220
  mutating: boolean;
1221
+ /**
1222
+ * Per-role token budget, resolved once from the role provider at plan time.
1223
+ * Plain data: the child's round loop never consults the provider. Absent →
1224
+ * the child runs unbudgeted.
1225
+ */
1226
+ budget?: {roleName: string; limit: number};
1064
1227
  }
1065
1228
 
1066
1229
  interface SpawnArgs {
@@ -1125,6 +1288,14 @@ async function planChild(
1125
1288
  const tools = args.tools ?? role?.tools ?? DEFAULT_CHILD_TOOLS;
1126
1289
  const mutating = isMutatingToolset(tools);
1127
1290
 
1291
+ // Resolve the token budget once, at the delegate call site: the child's
1292
+ // round loop receives plain data and never consults the role provider.
1293
+ let budget: {roleName: string; limit: number} | undefined;
1294
+ if (role) {
1295
+ const limit = registry.roleProvider?.budget?.(role.name);
1296
+ if (limit !== undefined) budget = {roleName: role.name, limit};
1297
+ }
1298
+
1128
1299
  // A read-only parent (e.g. the `plan` agent) must not reach a writer via
1129
1300
  // delegation — otherwise the restriction is trivially bypassed.
1130
1301
  if (mutating && config.provider?.readOnly) {
@@ -1144,6 +1315,7 @@ async function planChild(
1144
1315
  systemPrompt: role?.systemPrompt ?? DEFAULT_CHILD_PROMPT,
1145
1316
  modelSpec: args.model ?? role?.model,
1146
1317
  mutating,
1318
+ budget,
1147
1319
  };
1148
1320
  }
1149
1321
 
@@ -1210,6 +1382,12 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1210
1382
  let roundText = '';
1211
1383
  let previousText = '';
1212
1384
 
1385
+ // Live-activity counter for the front-end's status line. Spawned strictly
1386
+ // around the child run: everything below passes through the finally, so the
1387
+ // settle is symmetric on success, error, and abort — a leaked count would
1388
+ // leave a permanent phantom "subagents running" line in the UI.
1389
+ subagentSpawned();
1390
+ const cancelled = 'Delegate cancelled (aborted by user).';
1213
1391
  try {
1214
1392
  const childExec = providerCfg.childExecuteTool ?? executeTool;
1215
1393
  for await (const ev of runAgent({
@@ -1222,6 +1400,8 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1222
1400
  reasoningEffort: reasoning,
1223
1401
  providerConfig: providerCfg,
1224
1402
  executeTool: childExec,
1403
+ signal: config.signal,
1404
+ budget: plan.budget,
1225
1405
  })) {
1226
1406
  if (ev.type === 'round-start') {
1227
1407
  if (roundText) {
@@ -1236,10 +1416,15 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1236
1416
  }
1237
1417
  }
1238
1418
  } catch (err) {
1419
+ if (config.signal?.aborted) {
1420
+ emitAgentEvent({type: 'delegate-done', id: agentId, summary: cancelled, error: true});
1421
+ return cancelled;
1422
+ }
1239
1423
  const msg = err instanceof Error ? err.message : String(err);
1240
1424
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: msg, error: true});
1241
1425
  return `Delegate error: ${msg}`;
1242
1426
  } finally {
1427
+ subagentSettled();
1243
1428
  // Hand the parent's state back, and re-sync the UI (which may have rendered
1244
1429
  // the child's todo list via todos-updated).
1245
1430
  restoreRunScope(scope);
@@ -1247,6 +1432,13 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1247
1432
  emitAgentEvent({type: 'todos-updated', todos: getTodos()});
1248
1433
  }
1249
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
+
1250
1442
  const summary = roundText.trim() || previousText.trim();
1251
1443
  const finalSummary = summary || 'Task completed (no summary generated).';
1252
1444
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: finalSummary});
@@ -1266,6 +1458,45 @@ function toSpawnArgs(raw: Record<string, unknown>): SpawnArgs {
1266
1458
  };
1267
1459
  }
1268
1460
 
1461
+ async function spawnArgsMutating(args: SpawnArgs): Promise<boolean> {
1462
+ if (args.tools) return isMutatingToolset(args.tools);
1463
+ if (args.agent) {
1464
+ const {resolveRoleSpec} = await import('../agent/roles.js');
1465
+ const tools = resolveRoleSpec(args.agent, 'agent')?.tools;
1466
+ return isMutatingToolset(tools ?? DEFAULT_CHILD_TOOLS);
1467
+ }
1468
+ if (args.category) {
1469
+ const {resolveRoleSpec} = await import('../agent/roles.js');
1470
+ const tools = resolveRoleSpec(args.category, 'category')?.tools;
1471
+ return isMutatingToolset(tools ?? DEFAULT_CHILD_TOOLS);
1472
+ }
1473
+ return isMutatingToolset(DEFAULT_CHILD_TOOLS);
1474
+ }
1475
+
1476
+ /**
1477
+ * Classify a raw `delegate` / `delegate_parallel` tool call as mutating, for
1478
+ * turn-level scheduling in `run.ts`.
1479
+ *
1480
+ * Mirrors `planChild`'s toolset precedence (explicit `tools` > role config >
1481
+ * read-only default) but needs no `ToolConfig`. Never throws: unparseable args
1482
+ * classify as non-mutating because the handler rejects them before spawning.
1483
+ */
1484
+ export async function delegateCallIsMutating(name: string, argsStr: string): Promise<boolean> {
1485
+ try {
1486
+ const raw = JSON.parse(argsStr) as Record<string, unknown>;
1487
+ if (name === 'delegate_parallel') {
1488
+ const tasks = Array.isArray(raw.tasks) ? raw.tasks : [];
1489
+ for (const t of tasks) {
1490
+ if (await spawnArgsMutating(toSpawnArgs(t as Record<string, unknown>))) return true;
1491
+ }
1492
+ return false;
1493
+ }
1494
+ return await spawnArgsMutating(toSpawnArgs(raw));
1495
+ } catch {
1496
+ return false;
1497
+ }
1498
+ }
1499
+
1269
1500
  /**
1270
1501
  * `planChild`, but a throw becomes an error result instead of propagating.
1271
1502
  * Planning performs dynamic imports, so it can fail for reasons unrelated to