@pal-code/core 0.0.11 → 0.0.12

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/src/extensions.ts CHANGED
@@ -35,6 +35,7 @@ import {homedir} from 'node:os';
35
35
  import {isAbsolute, join, relative} from 'node:path';
36
36
  import type {ToolDef} from './tools/definitions.js';
37
37
  import type {ToolConfig} from './config.js';
38
+ import type {LifecycleHandlers} from './lifecycle.js';
38
39
  import {clearRoleProvider} from './agent/roles.js';
39
40
 
40
41
  /** Tool handler function signature. */
@@ -54,11 +55,20 @@ export interface ToolExtension {
54
55
  * `@pal-code/agents` registers the role provider used by core's `delegate`.
55
56
  */
56
57
  setup?: () => void | Promise<void>;
58
+ /**
59
+ * Optional lifecycle handlers, called by the agent loop and tool executor
60
+ * at the points the roadmap's Hooks section specifies (turn boundaries,
61
+ * tool dispatch, failures). Collected during `loadExtensions()` — same
62
+ * pattern as tools/handlers.
63
+ */
64
+ lifecycle?: LifecycleHandlers;
57
65
  }
58
66
 
59
67
  export interface LoadedExtensions {
60
68
  tools: ToolDef[];
61
69
  handlers: Record<string, ToolHandler>;
70
+ /** Lifecycle handler sets, one entry per extension that declared them. */
71
+ lifecycle: LifecycleHandlers[];
62
72
  /** Package names that loaded successfully, in input order. */
63
73
  loaded: string[];
64
74
  /** Package names that failed, with the reason. */
@@ -188,6 +198,7 @@ export async function loadExtensions(
188
198
  const roots = options.roots ?? defaultExtensionRoots();
189
199
  const allTools: ToolDef[] = [];
190
200
  const allHandlers: Record<string, ToolHandler> = {};
201
+ const allLifecycle: LifecycleHandlers[] = [];
191
202
  const loaded: string[] = [];
192
203
  const failed: Array<{pkg: string; reason: string}> = [];
193
204
 
@@ -208,6 +219,11 @@ export async function loadExtensions(
208
219
 
209
220
  allTools.push(...ext.tools);
210
221
  Object.assign(allHandlers, ext.handlers);
222
+ // Kept per-extension (not merged key-wise like handlers) so one
223
+ // extension's onToolCall cannot clobber another's at load time.
224
+ if (ext.lifecycle && typeof ext.lifecycle === 'object') {
225
+ allLifecycle.push(ext.lifecycle);
226
+ }
211
227
  loaded.push(pkg);
212
228
 
213
229
  // Extension-granted capabilities (non-tool) — e.g. the role provider.
@@ -230,5 +246,5 @@ export async function loadExtensions(
230
246
  }
231
247
  }
232
248
 
233
- return {tools: allTools, handlers: allHandlers, loaded, failed};
249
+ return {tools: allTools, handlers: allHandlers, lifecycle: allLifecycle, loaded, failed};
234
250
  }
package/src/index.ts CHANGED
@@ -55,6 +55,13 @@ export type {
55
55
  } from './agent/run.js';
56
56
  export {onAgentEvent, emitAgentEvent} from './agent/events.js';
57
57
  export type {AgentEvent as AgentLifecycleEvent} from './agent/events.js';
58
+ export {
59
+ subagentSpawned,
60
+ subagentSettled,
61
+ getSubagentStatus,
62
+ onSubagentStatusChange,
63
+ } from './agent/subagent-status.js';
64
+ export type {SubagentStatus} from './agent/subagent-status.js';
58
65
  export {
59
66
  setTodos,
60
67
  getTodos,
@@ -80,6 +87,9 @@ export {
80
87
  buildRolesPrompt,
81
88
  } from './agent/roles.js';
82
89
  export type {RoleSpec, RoleKind, RoleProvider, PrimarySpec} from './agent/roles.js';
90
+ export {buildSkillsPrompt, clearSkillsCache, listSkills} from './agent/skills.js';
91
+ export type {Skill} from './agent/skills.js';
92
+ export {clearFileRolesCache} from './agent/file-roles.js';
83
93
 
84
94
  // Config
85
95
  export {loadAgentConfig, isPathIgnored, clearConfigCache, resolveProjectRoot} from './config.js';
@@ -120,6 +130,17 @@ export type {
120
130
  LoadExtensionsOptions,
121
131
  } from './extensions.js';
122
132
 
133
+ // Extension lifecycle hooks
134
+ export {emitLifecycleEvent, registerExtensionLifecycle} from './lifecycle.js';
135
+ export type {
136
+ TurnContext,
137
+ ToolCallEvent,
138
+ ErrorEvent,
139
+ LifecycleEventMap,
140
+ LifecycleEventName,
141
+ LifecycleHandlers,
142
+ } from './lifecycle.js';
143
+
123
144
  // Repo Map
124
145
  export {buildRepoMap} from './repo-map.js';
125
146
 
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Extension lifecycle hooks — roadmap #6, `## 🪝 Extension Lifecycle Hooks`.
3
+ *
4
+ * Lets an extension observe agent activity through the optional `lifecycle`
5
+ * field on `ToolExtension`: turn boundaries, tool dispatch, and failures.
6
+ * `loadExtensions()` collects the handlers (same pattern as tools/handlers);
7
+ * whoever loads them calls {@link registerExtensionLifecycle}, and the agent
8
+ * loop / tool executor call {@link emitLifecycleEvent} at the points the
9
+ * roadmap's Implementation subsection enumerates — before/after the loop,
10
+ * inside `executeTool`.
11
+ *
12
+ * The store lives in the shared {@link registry} global slot for the same
13
+ * reason extension tools do: an extension installed under `~/.pal/extensions`
14
+ * resolves its own copy of core, so a module-local store would swallow the
15
+ * registration and the CLI's copy would never fire it.
16
+ *
17
+ * A handler that throws or rejects is caught and logged — never propagated.
18
+ * Hooks run alongside the agent loop, so a broken extension must not fail the
19
+ * tool call or the turn (same isolation policy as `setup()`).
20
+ */
21
+
22
+ import {log} from './logger.js';
23
+ import {registry} from './registry.js';
24
+
25
+ /** Context handed to turn-boundary hooks. */
26
+ export interface TurnContext {
27
+ /** Unique id for this turn (one `runAgent` invocation). */
28
+ readonly turnId: string;
29
+ /** Active primary agent name; `''` when the turn has no primary (e.g. a delegate child). */
30
+ readonly primary: string;
31
+ /** Messages in the conversation so far. */
32
+ readonly messageCount: number;
33
+ }
34
+
35
+ /** One completed tool dispatch. */
36
+ export interface ToolCallEvent {
37
+ readonly tool: string;
38
+ readonly args: Record<string, unknown>;
39
+ readonly durationMs: number;
40
+ readonly success: boolean;
41
+ }
42
+
43
+ /** A failure observed while dispatching a tool call. */
44
+ export interface ErrorEvent {
45
+ readonly error: Error;
46
+ /** What was happening when it failed, e.g. `tool:read_file`. */
47
+ readonly context: string;
48
+ }
49
+
50
+ /** Payload carried by each lifecycle event, keyed by event name. */
51
+ export interface LifecycleEventMap {
52
+ onTurnStart: TurnContext;
53
+ onTurnEnd: TurnContext;
54
+ onToolCall: ToolCallEvent;
55
+ onError: ErrorEvent;
56
+ }
57
+
58
+ /** The lifecycle event names an extension can observe. */
59
+ export type LifecycleEventName = keyof LifecycleEventMap;
60
+
61
+ /**
62
+ * The handlers an extension declares under `ToolExtension.lifecycle`.
63
+ *
64
+ * Derived from {@link LifecycleEventMap} so registration and emission are
65
+ * checked against one source; the shape is the roadmap's inline interface.
66
+ */
67
+ export type LifecycleHandlers = {
68
+ readonly [K in LifecycleEventName]?: (ev: LifecycleEventMap[K]) => void | Promise<void>;
69
+ };
70
+
71
+ /**
72
+ * Replace the registered lifecycle hooks. Called when extensions load and on
73
+ * `/reload` — replace rather than merge so a removed extension's hooks neither
74
+ * linger nor duplicate (same semantics as `registerExtensionTools`).
75
+ */
76
+ export function registerExtensionLifecycle(hooks: readonly LifecycleHandlers[]): void {
77
+ registry.lifecycleHooks = [...hooks];
78
+ }
79
+
80
+ /**
81
+ * Notify every registered lifecycle hook for `event`, in registration order.
82
+ *
83
+ * Handlers are awaited sequentially so async hooks complete deterministically
84
+ * before the turn moves on. A hook that throws or rejects is caught and logged
85
+ * (`PAL_DEBUG=1`); the remaining hooks still run. Never throws — a broken
86
+ * extension cannot fail the tool call or the turn. Returns immediately when
87
+ * nothing is registered for `event`, so turns without lifecycle extensions pay
88
+ * only one empty-array check.
89
+ */
90
+ export async function emitLifecycleEvent<K extends LifecycleEventName>(
91
+ event: K,
92
+ payload: LifecycleEventMap[K],
93
+ ): Promise<void> {
94
+ const hooks = registry.lifecycleHooks;
95
+ if (hooks.length === 0) return;
96
+
97
+ for (const set of hooks) {
98
+ const handler = set[event];
99
+ if (handler === undefined) continue;
100
+ try {
101
+ await handler(payload);
102
+ } catch (err) {
103
+ // Isolation, not silence: narrow and record. Console output would smear
104
+ // the TUI frame mid-turn — the same reason setup() failures avoid it.
105
+ const message = err instanceof Error ? err.message : String(err);
106
+ log('lifecycle-hook-error', {event, message});
107
+ }
108
+ }
109
+ }
@@ -38,7 +38,9 @@ export function expandRandomValue(val: string): string {
38
38
  if (!m) return val;
39
39
  const prefix = m[1] ?? '';
40
40
  const len = Number(m[2]);
41
- const hex = randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
41
+ const hex = randomBytes(Math.ceil(len / 2))
42
+ .toString('hex')
43
+ .slice(0, len);
42
44
  return prefix + hex;
43
45
  }
44
46
 
@@ -233,7 +235,10 @@ class OpenRouterProvider implements Provider {
233
235
  if (data === '[DONE]') continue;
234
236
 
235
237
  try {
236
- const parsed = JSON.parse(data);
238
+ // Providers/gateways occasionally emit raw NUL bytes, which make
239
+ // JSON.parse throw — the catch below would then drop the whole chunk,
240
+ // losing tool-call argument fragments. Strip them before parsing.
241
+ const parsed = JSON.parse(data.replaceAll('\u0000', ''));
237
242
  const choice = parsed.choices?.[0];
238
243
 
239
244
  // Extract usage from chunk (Gemini puts it in the last chunk)
@@ -252,9 +257,10 @@ class OpenRouterProvider implements Provider {
252
257
 
253
258
  const delta = choice.delta;
254
259
 
255
- // Text content
260
+ // Text content — strip escaped NULs that survive JSON.parse
261
+ // (stray null bytes corrupt rendered text and commands downstream).
256
262
  if (delta?.content) {
257
- yield {type: 'text', content: delta.content};
263
+ yield {type: 'text', content: delta.content.replaceAll('\u0000', '')};
258
264
  }
259
265
 
260
266
  // Tool calls — accumulate arguments across chunks.
@@ -285,9 +291,12 @@ class OpenRouterProvider implements Provider {
285
291
  toolCallAccumulators.set(idxKey, existing);
286
292
  }
287
293
 
288
- if (tc.id) existing.id = tc.id;
289
- if (tc.function?.name) existing.name = tc.function.name;
290
- if (tc.function?.arguments) existing.arguments += tc.function.arguments;
294
+ // Strip NULs at the read point: escaped null bytes survive
295
+ // JSON.parse and would otherwise corrupt ids/names/arguments.
296
+ if (tc.id) existing.id = tc.id.replaceAll('\u0000', '');
297
+ if (tc.function?.name) existing.name = tc.function.name.replaceAll('\u0000', '');
298
+ if (tc.function?.arguments)
299
+ existing.arguments += tc.function.arguments.replaceAll('\u0000', '');
291
300
  // Capture Gemini's extra_content (contains thought_signature)
292
301
  if (tc.extra_content && !existing.extra_content) {
293
302
  existing.extra_content = tc.extra_content;
package/src/registry.ts CHANGED
@@ -31,13 +31,11 @@
31
31
 
32
32
  import type {ToolConfig} from './config.js';
33
33
  import type {RoleProvider} from './agent/roles.js';
34
+ import type {LifecycleHandlers} from './lifecycle.js';
34
35
  import type {ToolDef} from './tools/definitions.js';
35
36
 
36
37
  /** A tool handler: `(args, config) => Promise<string>`. */
37
- export type ToolHandlerFn = (
38
- args: Record<string, unknown>,
39
- config: ToolConfig,
40
- ) => Promise<string>;
38
+ export type ToolHandlerFn = (args: Record<string, unknown>, config: ToolConfig) => Promise<string>;
41
39
 
42
40
  export interface CoreRegistry {
43
41
  /** Orchestration role provider, registered by `@pal-code/agents`. */
@@ -46,6 +44,8 @@ export interface CoreRegistry {
46
44
  extensionTools: ToolDef[];
47
45
  /** Handlers for {@link extensionTools}, keyed by tool name. */
48
46
  extensionHandlers: Record<string, ToolHandlerFn>;
47
+ /** Lifecycle hooks declared by loaded extensions (roadmap #6). */
48
+ lifecycleHooks: LifecycleHandlers[];
49
49
  }
50
50
 
51
51
  const KEY = '__pal_core_registry__';
@@ -60,4 +60,5 @@ export const registry: CoreRegistry = (store[KEY] ??= {
60
60
  roleProvider: null,
61
61
  extensionTools: [],
62
62
  extensionHandlers: {},
63
+ lifecycleHooks: [],
63
64
  });
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import {registry} from '../registry.js';
6
+ import {ensureSkillTool} from '../agent/skills.js';
6
7
 
7
8
  export interface ToolDef {
8
9
  type: 'function';
@@ -34,9 +35,13 @@ export function getExtensionTools(): readonly ToolDef[] {
34
35
  /**
35
36
  * Get all tools — core tools plus registered extension tools, plus any
36
37
  * explicitly supplied ones (kept for callers that aren't the registry).
38
+ *
39
+ * `load_skill` is appended here (rather than sitting in `CORE_TOOLS`) so it
40
+ * exists only while skill files do — no skills, no tool schema tokens.
37
41
  */
38
42
  export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
39
- return [...CORE_TOOLS, ...registry.extensionTools, ...extra];
43
+ const skillTool = ensureSkillTool();
44
+ return [...CORE_TOOLS, ...registry.extensionTools, ...extra, ...(skillTool ? [skillTool] : [])];
40
45
  }
41
46
 
42
47
  export const CORE_TOOLS: ToolDef[] = [
@@ -75,13 +80,22 @@ export const CORE_TOOLS: ToolDef[] = [
75
80
  type: 'function',
76
81
  function: {
77
82
  name: 'edit_file',
78
- description: 'Replace exact string in file.',
83
+ description:
84
+ 'Replace exact string in file; structural pattern+rewrite fallback when exact text unknown.',
79
85
  parameters: {
80
86
  type: 'object',
81
87
  properties: {
82
88
  path: {type: 'string'},
83
89
  old_string: {type: 'string'},
84
90
  new_string: {type: 'string'},
91
+ pattern: {
92
+ type: 'string',
93
+ description: 'ast-grep pattern with $A captures; tried if old_string misses.',
94
+ },
95
+ rewrite: {
96
+ type: 'string',
97
+ description: 'Replacement built from $A captures; used with pattern.',
98
+ },
85
99
  },
86
100
  required: ['path', 'old_string', 'new_string'],
87
101
  },
@@ -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`;
@@ -953,7 +1071,11 @@ export async function executeTool(
953
1071
  }
954
1072
 
955
1073
  try {
956
- const args = (argsStr && argsStr.trim() ? JSON.parse(argsStr) : {}) as Record<string, unknown>;
1074
+ // Strip NULs (model-emitted or resumed-history corruption) before parse —
1075
+ // a raw null byte makes JSON.parse throw and the whole tool call fail.
1076
+ const args = (
1077
+ argsStr && argsStr.trim() ? JSON.parse(argsStr.replaceAll('\u0000', '')) : {}
1078
+ ) as Record<string, unknown>;
957
1079
  const config = loadAgentConfig();
958
1080
  if (providerConfigOverride) {
959
1081
  config.provider = providerConfigOverride;
@@ -982,12 +1104,41 @@ export async function executeTool(
982
1104
  }
983
1105
 
984
1106
  log('tool-call', {name, args: argsStr});
985
- const content = await fn(args, config);
1107
+ const startedAt = Date.now();
1108
+ let content: string;
1109
+ try {
1110
+ content = await fn(args, config);
1111
+ } catch (toolErr) {
1112
+ // The dispatch record must fire for a failed call too — then rethrow so
1113
+ // the outer catch formats the error result exactly as before.
1114
+ await emitLifecycleEvent('onToolCall', {
1115
+ tool: name,
1116
+ args,
1117
+ durationMs: Date.now() - startedAt,
1118
+ success: false,
1119
+ });
1120
+ throw toolErr;
1121
+ }
986
1122
  log('tool-result', {name, error: false, length: content.length});
1123
+ await emitLifecycleEvent('onToolCall', {
1124
+ tool: name,
1125
+ args,
1126
+ durationMs: Date.now() - startedAt,
1127
+ success: true,
1128
+ });
1129
+ // Fire-and-forget: noteEditedFile only schedules a debounced background
1130
+ // check; the handler returns its result without waiting on diagnostics.
1131
+ if (FILE_WRITERS.has(name) && args.path) {
1132
+ noteEditedFile(String(args.path));
1133
+ }
987
1134
  return {toolCallId, content};
988
1135
  } catch (err) {
989
1136
  const msg = err instanceof Error ? err.message : String(err);
990
1137
  log('tool-result', {name, error: true, message: msg});
1138
+ await emitLifecycleEvent('onError', {
1139
+ error: err instanceof Error ? err : new Error(msg),
1140
+ context: `tool:${name}`,
1141
+ });
991
1142
  return {toolCallId, content: `Error executing ${name}: ${msg}`, error: true};
992
1143
  }
993
1144
  }
@@ -1061,6 +1212,12 @@ interface ChildPlan {
1061
1212
  modelSpec?: string;
1062
1213
  /** True when `tools` contains anything that mutates global state. */
1063
1214
  mutating: boolean;
1215
+ /**
1216
+ * Per-role token budget, resolved once from the role provider at plan time.
1217
+ * Plain data: the child's round loop never consults the provider. Absent →
1218
+ * the child runs unbudgeted.
1219
+ */
1220
+ budget?: {roleName: string; limit: number};
1064
1221
  }
1065
1222
 
1066
1223
  interface SpawnArgs {
@@ -1125,6 +1282,14 @@ async function planChild(
1125
1282
  const tools = args.tools ?? role?.tools ?? DEFAULT_CHILD_TOOLS;
1126
1283
  const mutating = isMutatingToolset(tools);
1127
1284
 
1285
+ // Resolve the token budget once, at the delegate call site: the child's
1286
+ // round loop receives plain data and never consults the role provider.
1287
+ let budget: {roleName: string; limit: number} | undefined;
1288
+ if (role) {
1289
+ const limit = registry.roleProvider?.budget?.(role.name);
1290
+ if (limit !== undefined) budget = {roleName: role.name, limit};
1291
+ }
1292
+
1128
1293
  // A read-only parent (e.g. the `plan` agent) must not reach a writer via
1129
1294
  // delegation — otherwise the restriction is trivially bypassed.
1130
1295
  if (mutating && config.provider?.readOnly) {
@@ -1144,6 +1309,7 @@ async function planChild(
1144
1309
  systemPrompt: role?.systemPrompt ?? DEFAULT_CHILD_PROMPT,
1145
1310
  modelSpec: args.model ?? role?.model,
1146
1311
  mutating,
1312
+ budget,
1147
1313
  };
1148
1314
  }
1149
1315
 
@@ -1210,6 +1376,11 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1210
1376
  let roundText = '';
1211
1377
  let previousText = '';
1212
1378
 
1379
+ // Live-activity counter for the front-end's status line. Spawned strictly
1380
+ // around the child run: everything below passes through the finally, so the
1381
+ // settle is symmetric on success, error, and abort — a leaked count would
1382
+ // leave a permanent phantom "subagents running" line in the UI.
1383
+ subagentSpawned();
1213
1384
  try {
1214
1385
  const childExec = providerCfg.childExecuteTool ?? executeTool;
1215
1386
  for await (const ev of runAgent({
@@ -1222,6 +1393,7 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1222
1393
  reasoningEffort: reasoning,
1223
1394
  providerConfig: providerCfg,
1224
1395
  executeTool: childExec,
1396
+ budget: plan.budget,
1225
1397
  })) {
1226
1398
  if (ev.type === 'round-start') {
1227
1399
  if (roundText) {
@@ -1240,6 +1412,7 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1240
1412
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: msg, error: true});
1241
1413
  return `Delegate error: ${msg}`;
1242
1414
  } finally {
1415
+ subagentSettled();
1243
1416
  // Hand the parent's state back, and re-sync the UI (which may have rendered
1244
1417
  // the child's todo list via todos-updated).
1245
1418
  restoreRunScope(scope);
@@ -1266,6 +1439,45 @@ function toSpawnArgs(raw: Record<string, unknown>): SpawnArgs {
1266
1439
  };
1267
1440
  }
1268
1441
 
1442
+ async function spawnArgsMutating(args: SpawnArgs): Promise<boolean> {
1443
+ if (args.tools) return isMutatingToolset(args.tools);
1444
+ if (args.agent) {
1445
+ const {resolveRoleSpec} = await import('../agent/roles.js');
1446
+ const tools = resolveRoleSpec(args.agent, 'agent')?.tools;
1447
+ return isMutatingToolset(tools ?? DEFAULT_CHILD_TOOLS);
1448
+ }
1449
+ if (args.category) {
1450
+ const {resolveRoleSpec} = await import('../agent/roles.js');
1451
+ const tools = resolveRoleSpec(args.category, 'category')?.tools;
1452
+ return isMutatingToolset(tools ?? DEFAULT_CHILD_TOOLS);
1453
+ }
1454
+ return isMutatingToolset(DEFAULT_CHILD_TOOLS);
1455
+ }
1456
+
1457
+ /**
1458
+ * Classify a raw `delegate` / `delegate_parallel` tool call as mutating, for
1459
+ * turn-level scheduling in `run.ts`.
1460
+ *
1461
+ * Mirrors `planChild`'s toolset precedence (explicit `tools` > role config >
1462
+ * read-only default) but needs no `ToolConfig`. Never throws: unparseable args
1463
+ * classify as non-mutating because the handler rejects them before spawning.
1464
+ */
1465
+ export async function delegateCallIsMutating(name: string, argsStr: string): Promise<boolean> {
1466
+ try {
1467
+ const raw = JSON.parse(argsStr) as Record<string, unknown>;
1468
+ if (name === 'delegate_parallel') {
1469
+ const tasks = Array.isArray(raw.tasks) ? raw.tasks : [];
1470
+ for (const t of tasks) {
1471
+ if (await spawnArgsMutating(toSpawnArgs(t as Record<string, unknown>))) return true;
1472
+ }
1473
+ return false;
1474
+ }
1475
+ return await spawnArgsMutating(toSpawnArgs(raw));
1476
+ } catch {
1477
+ return false;
1478
+ }
1479
+ }
1480
+
1269
1481
  /**
1270
1482
  * `planChild`, but a throw becomes an error result instead of propagating.
1271
1483
  * Planning performs dynamic imports, so it can fail for reasons unrelated to