@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pal-code/core",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -179,6 +179,11 @@ export interface RunWithFallbackOptions {
179
179
  */
180
180
  childExecuteTool?: RunAgentOptions['executeTool'];
181
181
  signal?: AbortSignal;
182
+ /**
183
+ * Active primary agent name, threaded through to `runAgent` so lifecycle
184
+ * hooks see it in `TurnContext.primary`. `''` when the turn has none.
185
+ */
186
+ primary?: string;
182
187
  /** Read-only turn — `delegate` may not spawn anything that mutates state. */
183
188
  readOnly?: boolean;
184
189
  /**
@@ -219,6 +224,7 @@ export async function* runWithFallback(
219
224
  executeTool,
220
225
  childExecuteTool,
221
226
  signal,
227
+ primary,
222
228
  readOnly,
223
229
  allowedTools,
224
230
  createProvider = createProviderFor,
@@ -299,6 +305,7 @@ export async function* runWithFallback(
299
305
  providerConfig,
300
306
  executeTool,
301
307
  signal,
308
+ primary,
302
309
  });
303
310
  return;
304
311
  } catch (err) {
@@ -0,0 +1,183 @@
1
+ /**
2
+ * File-based roles — `.pal/agents/*.md` from the project and `~/.pal/agents/`.
3
+ *
4
+ * Each file is a plain markdown doc: YAML-ish frontmatter (`name`, `model`,
5
+ * `tools`, `category`, plus optional `description`/`reasoning`/`max_rounds`)
6
+ * over a body that becomes the role's system prompt. This is the
7
+ * dotfile-shareable counterpart to the extension's `agents.json` — zero plugin
8
+ * runtime, committable, reviewable in a PR.
9
+ *
10
+ * Precedence (highest first):
11
+ * project file → user file → extension JSON config → built-in
12
+ *
13
+ * Files are layered *on top of* the registered provider: this module only owns
14
+ * the two file roots and returns plain `RoleSpec`s that slot into the existing
15
+ * two-axis model (`agent` | `category`). `roles.ts` consults it before the
16
+ * provider, so a file always shadows a JSON/built-in role of the same name and
17
+ * axis, and a project file shadows a user file.
18
+ *
19
+ * A malformed file is skipped with a `console.warn` — never a crash.
20
+ */
21
+
22
+ import {readFileSync} from 'fs';
23
+ import {homedir} from 'os';
24
+ import {basename, join} from 'path';
25
+ import type {RoleKind, RoleSpec} from './roles.js';
26
+ import {listMarkdownFiles, parseFrontmatter, parseToolsValue} from './frontmatter.js';
27
+
28
+ const DEFAULT_REASONING: NonNullable<RoleSpec['reasoning']> = 'medium';
29
+ const DEFAULT_MAX_ROUNDS = 5;
30
+ const DESCRIPTION_LIMIT = 100;
31
+
32
+ function skipFile(path: string, reason: string): null {
33
+ console.warn(`pal: ignoring ${path} — ${reason}`);
34
+ return null;
35
+ }
36
+
37
+ function skipField(path: string, field: string, reason: string): void {
38
+ console.warn(`pal: ignoring ${field} in ${path} — ${reason}`);
39
+ }
40
+
41
+ function firstBodyLine(body: string): string {
42
+ const line = body
43
+ .split('\n')
44
+ .map((l) => l.trim())
45
+ .find((l) => l !== '');
46
+ if (!line) return '';
47
+ const cleaned = line.replace(/^#+\s*/, '');
48
+ return cleaned.length > DESCRIPTION_LIMIT ? `${cleaned.slice(0, DESCRIPTION_LIMIT)}…` : cleaned;
49
+ }
50
+
51
+ function roleFrom(path: string, fields: Record<string, string>, body: string): RoleSpec | null {
52
+ const kindValue = fields.category ?? 'agent';
53
+ if (kindValue !== 'agent' && kindValue !== 'category') {
54
+ return skipFile(path, `unknown category "${kindValue}" (expected "agent" or "category")`);
55
+ }
56
+ const kind: RoleKind = kindValue;
57
+
58
+ let reasoning: RoleSpec['reasoning'] = DEFAULT_REASONING;
59
+ if (fields.reasoning !== undefined) {
60
+ if (fields.reasoning === 'low' || fields.reasoning === 'high') {
61
+ reasoning = fields.reasoning;
62
+ } else if (fields.reasoning !== 'medium') {
63
+ skipField(
64
+ path,
65
+ 'reasoning',
66
+ `unknown value "${fields.reasoning}" (using ${DEFAULT_REASONING})`,
67
+ );
68
+ reasoning = DEFAULT_REASONING;
69
+ }
70
+ }
71
+
72
+ let maxRounds = DEFAULT_MAX_ROUNDS;
73
+ if (fields.max_rounds !== undefined) {
74
+ if (/^\d+$/.test(fields.max_rounds)) {
75
+ maxRounds = Number(fields.max_rounds);
76
+ } else {
77
+ skipField(
78
+ path,
79
+ 'max_rounds',
80
+ `invalid value "${fields.max_rounds}" (using ${DEFAULT_MAX_ROUNDS})`,
81
+ );
82
+ }
83
+ }
84
+
85
+ let tools: string[] | undefined;
86
+ if (fields.tools !== undefined && fields.tools.trim() !== '') {
87
+ const parsed = parseToolsValue(fields.tools);
88
+ if (parsed === null) {
89
+ skipField(path, 'tools', `unparseable value "${fields.tools}" (using default tools)`);
90
+ } else {
91
+ tools = parsed;
92
+ }
93
+ }
94
+
95
+ const description = fields.description?.trim() || firstBodyLine(body);
96
+
97
+ return {
98
+ name: fields.name?.trim() || basename(path, '.md'),
99
+ kind,
100
+ description,
101
+ model: fields.model?.trim() || undefined,
102
+ reasoning,
103
+ tools,
104
+ maxRounds,
105
+ systemPrompt: body,
106
+ };
107
+ }
108
+
109
+ function readRolesDir(dir: string): RoleSpec[] {
110
+ const roles: RoleSpec[] = [];
111
+ for (const path of listMarkdownFiles(dir)) {
112
+ let text: string;
113
+ try {
114
+ text = readFileSync(path, 'utf-8');
115
+ } catch (err) {
116
+ skipFile(path, err instanceof Error ? err.message : String(err));
117
+ continue;
118
+ }
119
+
120
+ const parsed = parseFrontmatter(text);
121
+ if (parsed === null) {
122
+ skipFile(path, 'missing or malformed frontmatter');
123
+ continue;
124
+ }
125
+
126
+ const role = roleFrom(path, parsed.fields, parsed.body);
127
+ if (role) roles.push(role);
128
+ }
129
+ return roles;
130
+ }
131
+
132
+ /**
133
+ * Scan two role roots. `userDir` is applied first so `projectDir` wins on a
134
+ * same-name/same-axis collision (project → user shadowing).
135
+ */
136
+ export function scanFileRoles(projectDir: string, userDir: string): RoleSpec[] {
137
+ const byKey = new Map<string, RoleSpec>();
138
+ for (const role of [...readRolesDir(userDir), ...readRolesDir(projectDir)]) {
139
+ byKey.set(`${role.kind}:${role.name}`, role);
140
+ }
141
+ return [...byKey.values()];
142
+ }
143
+
144
+ interface FileRolesCache {
145
+ projectDir: string;
146
+ userDir: string;
147
+ roles: RoleSpec[];
148
+ }
149
+
150
+ let cache: FileRolesCache | undefined;
151
+
152
+ function defaultRoots(): {projectDir: string; userDir: string} {
153
+ // Same convention as `agents.json`: project = cwd (see loadAgentsConfig),
154
+ // user = ~/.pal, resolved through os.homedir() so HOME/USERPROFILE overrides work.
155
+ return {
156
+ projectDir: join(process.cwd(), '.pal', 'agents'),
157
+ userDir: join(homedir(), '.pal', 'agents'),
158
+ };
159
+ }
160
+
161
+ /** File roles from the default roots, cached until {@link clearFileRolesCache}. */
162
+ export function getFileRoles(): RoleSpec[] {
163
+ const roots = defaultRoots();
164
+ if (cache && cache.projectDir === roots.projectDir && cache.userDir === roots.userDir) {
165
+ return cache.roles;
166
+ }
167
+ cache = {
168
+ projectDir: roots.projectDir,
169
+ userDir: roots.userDir,
170
+ roles: scanFileRoles(roots.projectDir, roots.userDir),
171
+ };
172
+ return cache.roles;
173
+ }
174
+
175
+ /** Resolve a file-based role by name and axis, or null when no file defines it. */
176
+ export function resolveFileRole(name: string, kind: RoleKind): RoleSpec | null {
177
+ return getFileRoles().find((r) => r.name === name && r.kind === kind) ?? null;
178
+ }
179
+
180
+ /** Drop the cache so `/reload` and tests pick up file edits. */
181
+ export function clearFileRolesCache(): void {
182
+ cache = undefined;
183
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Hand-rolled frontmatter parser for plain-`.md` agent/skill files.
3
+ *
4
+ * Deliberately tiny and dependency-free: we only need `key: value` pairs above
5
+ * a `---` delimiter, not real YAML. A file that doesn't match this shape is
6
+ * rejected up front (`null`) so the caller can warn and skip it rather than
7
+ * crash or silently mis-parse.
8
+ *
9
+ * Malformed input → `null`. The caller decides policy (warn + skip).
10
+ */
11
+
12
+ import {readdirSync} from 'fs';
13
+ import {join} from 'path';
14
+
15
+ export interface Frontmatter {
16
+ /** Keys from the frontmatter block; values are unquoted strings. */
17
+ fields: Record<string, string>;
18
+ /** Everything after the closing `---` line. */
19
+ body: string;
20
+ }
21
+
22
+ /** Absolute paths of every `.md` file directly inside `dir`; [] when absent. */
23
+ export function listMarkdownFiles(dir: string): string[] {
24
+ try {
25
+ return readdirSync(dir, {withFileTypes: true})
26
+ .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
27
+ .map((entry) => join(dir, entry.name));
28
+ } catch {
29
+ return []; // absent root is the normal "nothing here" case
30
+ }
31
+ }
32
+
33
+ /** Strip one layer of matching surrounding quotes, if present. */
34
+ function unquote(value: string): string {
35
+ if (value.length >= 2) {
36
+ const first = value[0];
37
+ const last = value[value.length - 1];
38
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
39
+ return value.slice(1, -1);
40
+ }
41
+ }
42
+ return value;
43
+ }
44
+
45
+ /**
46
+ * Parse `---`-delimited frontmatter.
47
+ *
48
+ * Returns `null` when the file has no frontmatter block, the closing `---` is
49
+ * missing, or a line inside the block is not `key: value`.
50
+ */
51
+ export function parseFrontmatter(text: string): Frontmatter | null {
52
+ const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
53
+ const lines = source.split(/\r?\n/);
54
+
55
+ if (lines[0]?.trim() !== '---') return null;
56
+
57
+ const fields: Record<string, string> = {};
58
+ let closing = -1;
59
+
60
+ for (let i = 1; i < lines.length; i++) {
61
+ const line = lines[i].trim();
62
+ if (line === '---') {
63
+ closing = i;
64
+ break;
65
+ }
66
+ if (line === '' || line.startsWith('#')) continue;
67
+
68
+ const colon = line.indexOf(':');
69
+ if (colon <= 0) return null; // not `key: value` → malformed
70
+ const key = line.slice(0, colon).trim();
71
+ if (key === '') return null;
72
+ fields[key] = unquote(line.slice(colon + 1).trim());
73
+ }
74
+
75
+ if (closing === -1) return null; // unterminated block
76
+ return {fields, body: lines.slice(closing + 1).join('\n')};
77
+ }
78
+
79
+ function isStringArray(value: unknown): value is string[] {
80
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
81
+ }
82
+
83
+ /**
84
+ * Parse a `tools` frontmatter value: either a JSON array (`["a","b"]`) or a
85
+ * comma-separated list (`a, b`). Returns `null` when the value is present but
86
+ * unusable (bad JSON, non-string entries, no names) so the caller can warn.
87
+ */
88
+ export function parseToolsValue(value: string): string[] | null {
89
+ const trimmed = value.trim();
90
+ if (trimmed.startsWith('[')) {
91
+ let parsed: unknown;
92
+ try {
93
+ parsed = JSON.parse(trimmed);
94
+ } catch {
95
+ return null;
96
+ }
97
+ return isStringArray(parsed) ? parsed : null;
98
+ }
99
+
100
+ const names = trimmed
101
+ .split(',')
102
+ .map((v) => unquote(v.trim()))
103
+ .filter((v) => v !== '');
104
+ return names.length > 0 ? names : null;
105
+ }
@@ -13,7 +13,9 @@
13
13
  * - `category` — implementation lane (build, deep, quick, architect, …)
14
14
  */
15
15
 
16
+ import {loadAgentConfig} from '../config.js';
16
17
  import {registry} from '../registry.js';
18
+ import {getFileRoles, resolveFileRole} from './file-roles.js';
17
19
 
18
20
  export type RoleKind = 'agent' | 'category';
19
21
 
@@ -44,6 +46,12 @@ export interface RoleProvider {
44
46
  list: () => RoleSpec[];
45
47
  /** Concurrency cap for `delegate_parallel`. Defaults to 3 when omitted. */
46
48
  maxParallel?: () => number;
49
+ /**
50
+ * Per-role token budget for a delegated child, in tokens. Resolved ONCE at
51
+ * the delegate call site and handed to the child's loop as plain data — the
52
+ * loop never looks up roles. `undefined` → no budget for that role.
53
+ */
54
+ budget?: (roleName: string) => number | undefined;
47
55
  /** Primary agents the user can Tab between. Omitted → none. */
48
56
  listPrimary?: () => PrimarySpec[];
49
57
  /** Name of the primary agent selected on startup. Omitted → first primary. */
@@ -105,20 +113,48 @@ export function clearRoleProvider(): void {
105
113
  registry.roleProvider = null;
106
114
  }
107
115
 
108
- /** Resolve a role by name and axis. Returns null when no provider is registered. */
116
+ /**
117
+ * Resolve a role by name and axis.
118
+ *
119
+ * Precedence: file-based role (`.pal/agents/*.md`, project before user) →
120
+ * provider role (extension JSON config over its built-ins) → null. Wiring the
121
+ * file layer here means every caller — `delegate`, the "Available:" hint,
122
+ * `buildRolesPrompt` — sees one consistent order.
123
+ */
109
124
  export function resolveRoleSpec(name: string, kind: RoleKind): RoleSpec | null {
125
+ const fromFiles = resolveFileRole(name, kind);
126
+ if (fromFiles) return fromFiles;
110
127
  return registry.roleProvider?.resolve(name, kind) ?? null;
111
128
  }
112
129
 
113
- /** All roles, or an empty array when no provider is registered. */
130
+ /**
131
+ * All roles: provider list with file-based roles layered on top (a file with
132
+ * the same name and axis replaces its JSON/built-in counterpart).
133
+ */
114
134
  export function listRoleSpecs(): RoleSpec[] {
115
- return registry.roleProvider?.list() ?? [];
135
+ const roles = [...(registry.roleProvider?.list() ?? [])];
136
+ for (const fileRole of getFileRoles()) {
137
+ const idx = roles.findIndex((r) => r.name === fileRole.name && r.kind === fileRole.kind);
138
+ if (idx >= 0) roles[idx] = fileRole;
139
+ else roles.push(fileRole);
140
+ }
141
+ return roles;
116
142
  }
117
143
 
118
- /** Concurrency cap for `delegate_parallel`. */
144
+ /**
145
+ * Concurrency cap for delegate fan-out (`delegate_parallel` batches and the
146
+ * multi-delegate dispatch lane in `run.ts`).
147
+ *
148
+ * Precedence: explicit `.pal.json` `orchestration.max_parallel` → extension
149
+ * `agents.json` `max_parallel` (role provider) → `DEFAULT_MAX_PARALLEL`.
150
+ */
119
151
  export function getMaxParallel(): number {
120
152
  try {
121
- return registry.roleProvider?.maxParallel?.() ?? DEFAULT_MAX_PARALLEL;
153
+ return (
154
+ loadAgentConfig().orchestration?.maxParallel ??
155
+ registry.roleProvider?.maxParallel?.() ??
156
+ DEFAULT_MAX_PARALLEL
157
+ );
122
158
  } catch {
123
159
  return DEFAULT_MAX_PARALLEL;
124
160
  }
package/src/agent/run.ts CHANGED
@@ -8,8 +8,11 @@
8
8
  */
9
9
 
10
10
  import {shouldCompact, compactionBoundary, summarizeRange} from '../compaction.js';
11
+ import {getDiagnosticsMode, takeDiagnosticsLine} from '../diagnostics.js';
12
+ import {emitLifecycleEvent, type TurnContext} from '../lifecycle.js';
11
13
  import {complete} from '../provider/complete.js';
12
14
  import type {Provider, StreamEvent} from '../provider/types.js';
15
+ import {getMaxParallel} from './roles.js';
13
16
 
14
17
  // ---------------------------------------------------------------------------
15
18
  // Conversation shape
@@ -82,6 +85,7 @@ export interface ChildProviderConfig {
82
85
  args: string,
83
86
  id: string,
84
87
  providerConfig: ChildProviderConfig,
88
+ signal?: AbortSignal,
85
89
  ) => Promise<{content: string; error?: boolean}>;
86
90
  }
87
91
 
@@ -124,6 +128,13 @@ export interface RunAgentOptions {
124
128
  systemPrompt: string;
125
129
  /** Max tool-call rounds (default 100). */
126
130
  maxRounds?: number;
131
+ /**
132
+ * Per-role token budget for a DELEGATED child run, handed down as plain data
133
+ * by the delegate call site (never resolved here). Checked only at round
134
+ * boundaries; absent → no budget (the parent/orchestrator run never carries
135
+ * one).
136
+ */
137
+ budget?: {roleName: string; limit: number};
127
138
  /** Context window used to decide when to compact (default 100_000). */
128
139
  contextLimit?: number;
129
140
  /** Reasoning effort forwarded to the provider (default 'medium'). */
@@ -150,17 +161,27 @@ export interface RunAgentOptions {
150
161
  * an `aborted` notice instead of `done`.
151
162
  */
152
163
  signal?: AbortSignal;
164
+ /**
165
+ * Active primary agent name for this turn, surfaced to lifecycle hooks via
166
+ * `TurnContext.primary`. `''` when the turn has no primary — a delegate
167
+ * child's role is a different axis than the turn's primary.
168
+ */
169
+ primary?: string;
153
170
  /** Provider credentials handed to tools that spawn sub-agents. */
154
171
  providerConfig: ChildProviderConfig;
155
172
  /**
156
173
  * Tool executor. Injected by the caller so this module never imports the
157
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.
158
178
  */
159
179
  executeTool: (
160
180
  name: string,
161
181
  args: string,
162
182
  id: string,
163
183
  providerConfig: ChildProviderConfig,
184
+ signal?: AbortSignal,
164
185
  ) => Promise<{content: string; error?: boolean}>;
165
186
  }
166
187
 
@@ -207,6 +228,9 @@ const PARALLEL_SAFE = new Set([
207
228
  'repo_map',
208
229
  ]);
209
230
 
231
+ /** Delegate-family tools — dispatched through the bounded fan-out lane. */
232
+ const DELEGATE_TOOLS = new Set(['delegate', 'delegate_parallel']);
233
+
210
234
  // ---------------------------------------------------------------------------
211
235
  // Helpers
212
236
  // ---------------------------------------------------------------------------
@@ -314,7 +338,8 @@ export function buildApiMessages(
314
338
  ): Array<Record<string, unknown>> {
315
339
  // The summarized prefix is represented by `compactionNote` in the system
316
340
  // prompt; sending it again would waste context and could contradict the note.
317
- const visible = compactedUpto > 0 ? messages.slice(Math.min(compactedUpto, messages.length)) : messages;
341
+ const visible =
342
+ compactedUpto > 0 ? messages.slice(Math.min(compactedUpto, messages.length)) : messages;
318
343
  const wire: Array<Record<string, unknown>> = [
319
344
  {
320
345
  role: 'system',
@@ -445,8 +470,33 @@ async function summarizeViaProvider(
445
470
  *
446
471
  * Terminates when the model stops requesting tools, when `maxRounds` is hit,
447
472
  * or when the same tool call repeats `REPEAT_STOP` times.
473
+ *
474
+ * Wraps {@link agentTurn} with the extension lifecycle boundary hooks:
475
+ * `onTurnStart` before the loop begins, `onTurnEnd` in a `finally` so every
476
+ * exit path — done, abort, throw, or the consumer abandoning the generator —
477
+ * completes the turn.
448
478
  */
449
479
  export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent> {
480
+ const turnId = `turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
481
+ const context = (): TurnContext => ({
482
+ turnId,
483
+ primary: opts.primary ?? '',
484
+ messageCount: opts.messages.length,
485
+ });
486
+
487
+ await emitLifecycleEvent('onTurnStart', context());
488
+ try {
489
+ yield* agentTurn(opts);
490
+ } finally {
491
+ await emitLifecycleEvent('onTurnEnd', context());
492
+ }
493
+ }
494
+
495
+ /**
496
+ * The round loop behind {@link runAgent}. Split out so the turn-boundary
497
+ * lifecycle hooks can wrap it in try/finally without re-indenting the loop.
498
+ */
499
+ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent> {
450
500
  const {
451
501
  messages,
452
502
  tools,
@@ -458,6 +508,7 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
458
508
  reasoningEffort = 'medium',
459
509
  providerConfig,
460
510
  executeTool,
511
+ budget,
461
512
  signal,
462
513
  compactedSeq = 0,
463
514
  compactionNote: initialCompactionNote = '',
@@ -543,8 +594,29 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
543
594
  const noteEntry = `[messages ${compactedUpto + 1}-${compactedUpto + midBoundary}]\n${midSummary}`;
544
595
  compactionNote = compactionNote ? `${compactionNote}\n\n${noteEntry}` : noteEntry;
545
596
  compactedUpto += midBoundary;
546
- yield {type: 'compacted', boundary: compactedUpto, summarized: midBoundary, summary: midSummary};
547
- yield {type: 'notice', text: `Context compacted mid-turn (${midBoundary} messages summarized).`};
597
+ yield {
598
+ type: 'compacted',
599
+ boundary: compactedUpto,
600
+ summarized: midBoundary,
601
+ summary: midSummary,
602
+ };
603
+ yield {
604
+ type: 'notice',
605
+ text: `Context compacted mid-turn (${midBoundary} messages summarized).`,
606
+ };
607
+ }
608
+ }
609
+
610
+ // One-line edit diagnostics from the previous round: the check ran off the
611
+ // critical path; take() resolves no later than its ~2s budget. Auto mode
612
+ // pushes it into the model's context; verify-only surfaces it to the user.
613
+ const diagLine = await takeDiagnosticsLine();
614
+ if (diagLine !== null) {
615
+ const diagMode = getDiagnosticsMode();
616
+ if (diagMode === 'auto') {
617
+ messages.push({role: 'user', content: diagLine});
618
+ } else if (diagMode === 'verify-only') {
619
+ yield {type: 'notice', text: diagLine};
548
620
  }
549
621
  }
550
622
 
@@ -608,15 +680,42 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
608
680
  type Display = (typeof displays)[number];
609
681
  const runOne = async (d: Display) => {
610
682
  const started = Date.now();
611
- 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);
612
684
  return {tc: d.tc, result, ms: Date.now() - started};
613
685
  };
614
686
 
615
687
  const byId = new Map<string, Awaited<ReturnType<typeof runOne>>>();
616
688
  const parallel = displays.filter((d) => PARALLEL_SAFE.has(d.tc.name));
617
- const sequential = displays.filter((d) => !PARALLEL_SAFE.has(d.tc.name));
689
+ const delegates = displays.filter((d) => DELEGATE_TOOLS.has(d.tc.name));
690
+ const sequential = displays.filter(
691
+ (d) => !PARALLEL_SAFE.has(d.tc.name) && !DELEGATE_TOOLS.has(d.tc.name),
692
+ );
618
693
 
619
694
  for (const r of await Promise.all(parallel.map(runOne))) byId.set(r.tc.id, r);
695
+
696
+ // Delegate fan-out: non-mutating children run in batches of `max_parallel`,
697
+ // then mutating children run strictly one at a time. Phases never overlap,
698
+ // so two writers can't race the same file; batches can't exceed the cap.
699
+ if (delegates.length > 0) {
700
+ const {delegateCallIsMutating} = await import('../tools/executor.js');
701
+ const flags = await Promise.all(
702
+ delegates.map((d) => delegateCallIsMutating(d.tc.name, d.tc.arguments)),
703
+ );
704
+ const fanOut = delegates.filter((_, i) => !flags[i]);
705
+ const serial = delegates.filter((_, i) => flags[i]);
706
+
707
+ const limit = Math.max(1, getMaxParallel());
708
+ for (let i = 0; i < fanOut.length; i += limit) {
709
+ for (const r of await Promise.all(fanOut.slice(i, i + limit).map(runOne))) {
710
+ byId.set(r.tc.id, r);
711
+ }
712
+ }
713
+ for (const d of serial) {
714
+ const r = await runOne(d);
715
+ byId.set(r.tc.id, r);
716
+ }
717
+ }
718
+
620
719
  for (const d of sequential) {
621
720
  const r = await runOne(d);
622
721
  byId.set(r.tc.id, r);
@@ -660,11 +759,37 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
660
759
  // Safe now the tool group is complete.
661
760
  for (const content of nudges) messages.push({role: 'user', content});
662
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
+
663
772
  if (hardStop) {
664
773
  yield {type: 'notice', text: `! loop detected (same call ${REPEAT_STOP}×) — stopping early`};
665
774
  stoppedEarly = true;
666
775
  break;
667
776
  }
777
+
778
+ // Round boundary: cumulative prompt+completion vs the child's budget.
779
+ // Intentionally double-counts re-sent history — locked semantics.
780
+ if (budget) {
781
+ const used = totalInput + totalOutput;
782
+ if (used > budget.limit) {
783
+ const stopMessage = `Stopped: token budget ${budget.limit} exceeded (used ~${used})`;
784
+ yield {type: 'notice', text: stopMessage};
785
+ // Also streamed as text: executeChild builds the child's result string
786
+ // from text-delta events, so this is what puts the stop in front of
787
+ // the parent. Leading newlines keep the exact message intact after trim.
788
+ yield {type: 'text-delta', content: `\n\n${stopMessage}`};
789
+ stoppedEarly = true;
790
+ break;
791
+ }
792
+ }
668
793
  }
669
794
 
670
795
  // ── Round cap reached → degrade gracefully ──