@pal-code/core 0.0.21 → 0.0.22

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.
@@ -24,9 +24,20 @@ import {
24
24
  } from '../config.js';
25
25
  import {snapshotFile} from '../snapshots.js';
26
26
  import {noteEditedFile} from '../diagnostics.js';
27
- import type {ConversationMessage} from '../agent/run.js';
27
+ import type {ChildProviderConfig, ConversationMessage} from '../agent/run.js';
28
+ import type {Provider} from '../provider/types.js';
29
+ import type {ToolDef} from './definitions.js';
30
+ import {
31
+ correctionPrompt,
32
+ excerpt,
33
+ extractJson,
34
+ formatProblems,
35
+ schemaInstruction,
36
+ validateAgainstSchema,
37
+ } from './json-schema.js';
28
38
  import {registry} from '../registry.js';
29
39
  import {validateRequiredArgs} from './definitions.js';
40
+ import {expandTools} from './lazy.js';
30
41
 
31
42
  /**
32
43
  * `rg --glob '!pat'` args for each `.pal.json` ignore pattern, so ripgrep
@@ -45,6 +56,12 @@ import {emitAgentEvent} from '../agent/events.js';
45
56
  import {subagentSpawned, subagentSettled} from '../agent/subagent-status.js';
46
57
  import {emitLifecycleEvent} from '../lifecycle.js';
47
58
  import {grepJS, globJS} from './search.js';
59
+ import {
60
+ findNormalisedMatch,
61
+ findOccurrences,
62
+ formatOccurrenceSites,
63
+ reindentBlock,
64
+ } from './edit-match.js';
48
65
  import {setTodos, formatTodos, type TodoStatus} from '../agent/todos.js';
49
66
 
50
67
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -54,6 +71,26 @@ import {setTodos, formatTodos, type TodoStatus} from '../agent/todos.js';
54
71
 
55
72
  let shellCwd = process.cwd();
56
73
 
74
+ /**
75
+ * Containment root, when one has been pinned. `undefined` → no sandbox.
76
+ *
77
+ * Deliberately opt-in rather than always-on. An interactive session must keep
78
+ * reaching the whole filesystem the user can (reading `~/.pal/config.json`,
79
+ * a sibling checkout, an absolute path from a prior message) — pinning every
80
+ * read to the project root would break that for no safety gain, since the
81
+ * human is right there approving commands.
82
+ *
83
+ * A HEADLESS run is the case that needs it. The eval harness drives `runAgent`
84
+ * unattended, and a live run was observed `cd`-ing into the real repo and
85
+ * writing there; on one task it could read the answer from the repo it was
86
+ * meant to solve the task independently of. Nothing approves those commands, so
87
+ * the harness pins a root and the process is confined to it.
88
+ *
89
+ * Set by `setShellRoot`. Scoped through `captureRunScope`/`restoreRunScope` so a
90
+ * delegated child cannot widen its parent's containment.
91
+ */
92
+ let sandboxRoot: string | undefined;
93
+
57
94
  /** Current tracked shell cwd — exposed so nested runs can be scoped. */
58
95
  export function getShellCwd(): string {
59
96
  return shellCwd;
@@ -63,6 +100,37 @@ export function getShellCwd(): string {
63
100
  export function setShellCwd(next: string): void {
64
101
  shellCwd = next;
65
102
  }
103
+
104
+ /** The pinned containment root, or `undefined` when unsandboxed. */
105
+ export function getShellRoot(): string | undefined {
106
+ return sandboxRoot;
107
+ }
108
+
109
+ /**
110
+ * Pin (or, with `undefined`, release) the containment root.
111
+ *
112
+ * Also moves the shell into the root, because pinning a boundary and leaving the
113
+ * shell outside it would make the very first command escape.
114
+ */
115
+ export function setShellRoot(next: string | undefined): void {
116
+ sandboxRoot = next ? resolve(next) : undefined;
117
+ if (sandboxRoot) shellCwd = sandboxRoot;
118
+ }
119
+
120
+ /**
121
+ * Whether `candidate` is `root` or sits beneath it.
122
+ *
123
+ * Uses the platform separator for the prefix test: on Windows `resolve()`
124
+ * yields backslashes, so `root + '/'` would never match, and it compares
125
+ * resolved paths so `..` cannot walk out of the check itself.
126
+ */
127
+ function isInside(root: string, candidate: string): boolean {
128
+ const base = resolve(root);
129
+ const target = resolve(candidate);
130
+ if (target === base) return true;
131
+ return target.startsWith(base.endsWith(sep) ? base : base + sep);
132
+ }
133
+
66
134
  const SHELL_TIMEOUT_MS = 120_000;
67
135
 
68
136
  async function execCommand(
@@ -76,6 +144,15 @@ async function execCommand(
76
144
 
77
145
  if (signal?.aborted) throw new Error('Command cancelled (aborted by user).');
78
146
 
147
+ // Under a pinned root, never spawn outside it. Checked here rather than at the
148
+ // call site so every path into a shell (`bash`'s own args, `verify`'s test
149
+ // command) is covered by one gate.
150
+ if (sandboxRoot && !isInside(sandboxRoot, workdir)) {
151
+ throw new Error(
152
+ `Command would run outside the workspace (${workdir}). Refusing — working directory is confined to ${sandboxRoot}.`,
153
+ );
154
+ }
155
+
79
156
  const proc = Bun.spawn(isWin ? ['cmd', '/d', '/c', command] : ['bash', '-c', command], {
80
157
  stdout: 'pipe',
81
158
  stderr: 'pipe',
@@ -135,7 +212,11 @@ async function execCommand(
135
212
  const cdMatch = command.match(/^\s*cd\s+(?:\/d\s+)?["']?([^"'\s;&]+)["']?\s*(?:;|&&|$)/);
136
213
  if (cdMatch && exitCode === 0 && !cwdOverride) {
137
214
  const next = cdMatch[1];
138
- shellCwd = isAbsolute(next) ? next : resolve(shellCwd, next);
215
+ const resolved = isAbsolute(next) ? next : resolve(shellCwd, next);
216
+ // A `cd` out of a pinned root is the escape this sandbox exists to stop: the
217
+ // tracked cwd is what later RELATIVE tool calls resolve against, so letting it
218
+ // drift outside would carry a subsequent `write`/`read` out with it.
219
+ if (!sandboxRoot || isInside(sandboxRoot, resolved)) shellCwd = resolved;
139
220
  }
140
221
 
141
222
  return {stdout, stderr, exitCode};
@@ -143,7 +224,7 @@ async function execCommand(
143
224
 
144
225
  /** Reset the tracked shell working directory (e.g., on /clear or session reset). */
145
226
  export function resetShell() {
146
- shellCwd = process.cwd();
227
+ shellCwd = sandboxRoot ?? process.cwd();
147
228
  }
148
229
 
149
230
  export interface ToolResult {
@@ -379,21 +460,35 @@ const tools: Record<
379
460
  ? `old_string not found in ${filePath}`
380
461
  : occurrences > 1
381
462
  ? `old_string is not unique in ${filePath} (${occurrences} occurrences). ` +
382
- `Narrow the match to exactly one occurrence.`
463
+ `Narrow the match to exactly one occurrence.` +
464
+ // Say WHERE. Without this the model retries blind or re-reads the
465
+ // whole file; with it, one narrow read is enough.
466
+ `\n${formatOccurrenceSites(findOccurrences(content, oldString))}`
383
467
  : null;
384
468
 
385
469
  let updated: string;
386
470
  if (stringError === null) {
387
471
  updated = content.replace(oldString, newString);
388
- } else if (pattern) {
389
- // Spec: exact string match → ast-grep structural match → combined error.
390
- const structural = await structuralEdit({content, filePath, pattern, rewrite});
391
- if (!structural.ok) {
392
- throw new Error(`${stringError} Structural attempt failed: ${structural.reason}`);
393
- }
394
- updated = structural.updated;
395
472
  } else {
396
- throw new Error(stringError);
473
+ // Before giving up, retry past formatting drift: the usual cause of a
474
+ // false "not found" is that the file was re-indented, not that the code
475
+ // changed. Only multi-line needles qualify (see findNormalisedMatch).
476
+ const normalised = occurrences === 0 ? findNormalisedMatch(content, oldString) : null;
477
+ if (normalised !== null) {
478
+ // The matched span includes the original indent, so the replacement has
479
+ // to be shifted to match or the block would flatten to the left margin.
480
+ const replacement = reindentBlock(newString, normalised.indent, normalised.indents);
481
+ updated = content.slice(0, normalised.start) + replacement + content.slice(normalised.end);
482
+ } else if (pattern) {
483
+ // Spec: exact string match → whitespace-normalised → ast-grep structural.
484
+ const structural = await structuralEdit({content, filePath, pattern, rewrite});
485
+ if (!structural.ok) {
486
+ throw new Error(`${stringError} Structural attempt failed: ${structural.reason}`);
487
+ }
488
+ updated = structural.updated;
489
+ } else {
490
+ throw new Error(stringError);
491
+ }
397
492
  }
398
493
 
399
494
  snapshotFile(filePath, 'edit');
@@ -471,11 +566,20 @@ const tools: Record<
471
566
  // If the user passes a cwd arg, update the tracked working directory
472
567
  if (args.cwd) {
473
568
  const requested = String(args.cwd);
474
- shellCwd = isAbsolute(requested) ? requested : resolve(shellCwd, requested);
569
+ const resolved = isAbsolute(requested) ? requested : resolve(shellCwd, requested);
570
+ if (sandboxRoot && !isInside(sandboxRoot, resolved)) {
571
+ return `Error: cwd "${requested}" resolves outside the workspace (${sandboxRoot}). Refusing.`;
572
+ }
573
+ shellCwd = resolved;
475
574
  }
476
575
 
477
576
  try {
478
- const {stdout, stderr, exitCode} = await execCommand(command, SHELL_TIMEOUT_MS, undefined, config.signal);
577
+ const {stdout, stderr, exitCode} = await execCommand(
578
+ command,
579
+ SHELL_TIMEOUT_MS,
580
+ undefined,
581
+ config.signal,
582
+ );
479
583
 
480
584
  let output = '';
481
585
  if (stdout) output += stdout;
@@ -564,7 +668,12 @@ const tools: Record<
564
668
  }
565
669
 
566
670
  if (runTest) {
567
- const {stdout, stderr, exitCode} = await execCommand('bun run test 2>&1', 180_000, checkRoot, config.signal);
671
+ const {stdout, stderr, exitCode} = await execCommand(
672
+ 'bun run test 2>&1',
673
+ 180_000,
674
+ checkRoot,
675
+ config.signal,
676
+ );
568
677
  const out = (stdout + stderr).trim();
569
678
  if (exitCode === 0) {
570
679
  lines.push('✓ test: passed');
@@ -1069,16 +1178,7 @@ export async function executeTool(
1069
1178
  name: string,
1070
1179
  argsStr: string,
1071
1180
  toolCallId: string,
1072
- providerConfigOverride?: {
1073
- model: string;
1074
- apiKey: string;
1075
- baseUrl: string;
1076
- keys?: Record<string, string>;
1077
- headers?: Record<string, string>;
1078
- systemPromptAppend?: string;
1079
- readOnly?: boolean;
1080
- allowedTools?: string[];
1081
- },
1181
+ providerConfigOverride?: ChildProviderConfig,
1082
1182
  signal?: AbortSignal,
1083
1183
  ): Promise<ToolResult> {
1084
1184
  const fn = tools[name] ?? registry.extensionHandlers[name];
@@ -1091,6 +1191,19 @@ export async function executeTool(
1091
1191
  };
1092
1192
  }
1093
1193
 
1194
+ // ── Lazy schema expansion ──
1195
+ // The model called a tool it only saw a stub for: from the next round its full
1196
+ // schema goes out. Placed BEFORE the allowlist gate on purpose — expansion is
1197
+ // a property of what we advertise, never of what may run, so denying the call
1198
+ // must not leave the tool advertised as a stub forever. Best-effort: expansion
1199
+ // is a prompt optimisation, so a failure here must never break a tool call.
1200
+ try {
1201
+ const lifted = expandTools([name]);
1202
+ if (lifted.length > 0) log('lazy-tool-expanded', {tool: name});
1203
+ } catch {
1204
+ // ignore — the call proceeds against the real schema either way
1205
+ }
1206
+
1094
1207
  // ── Permission gate ──
1095
1208
  // Omitting a tool from the definitions the model receives is *advisory*: a
1096
1209
  // model can still emit a call for a tool it was never offered (hallucination,
@@ -1129,25 +1242,54 @@ export async function executeTool(
1129
1242
  const execConfig: ToolConfig = signal ? {...config, signal} : config;
1130
1243
 
1131
1244
  // ── Path containment guard ──
1132
- // Resolve file-mutating paths against the project root and refuse to write
1133
- // outside it. The ignore-list is a deny-list that fails open for `..`
1134
- // segments; this is the actual containment boundary.
1135
- const PROJECT_ROOT = resolveProjectRoot() ?? process.cwd();
1136
- // Only guard tools that actually write files — bash and recall_history are
1137
- // excluded (bash can trivially escape via shell; recall_history is read-only).
1138
- const FILE_WRITERS = new Set(['write', 'edit', 'edit_block']);
1139
- if (FILE_WRITERS.has(name) && args.path) {
1140
- const rawPath = String(args.path);
1141
- const resolved = resolve(PROJECT_ROOT, rawPath);
1142
- // Use the platform separator for the prefix check — on Windows resolve()
1143
- // produces backslash paths, so `PROJECT_ROOT + '/'` would never match.
1144
- if (!resolved.startsWith(PROJECT_ROOT + sep) && resolved !== PROJECT_ROOT) {
1145
- return {
1146
- toolCallId,
1147
- content: `Error: path "${rawPath}" resolves outside the project root (${PROJECT_ROOT}). Refusing.`,
1148
- error: true,
1149
- };
1245
+ // Resolve path-bearing arguments against the containment root and refuse
1246
+ // anything outside it. The ignore-list is a deny-list that fails open for
1247
+ // `..` segments; this is the actual containment boundary.
1248
+ //
1249
+ // The root is a PINNED sandbox root when one is set (headless/eval), and the
1250
+ // project root otherwise. Without a pinned root this is a write-only guard,
1251
+ // exactly as before — an interactive session may still read anywhere, but
1252
+ // cannot write outside the project by absolute path.
1253
+ //
1254
+ // Reads are included ONLY under a pinned root, because that is the
1255
+ // answer-leak vector: a live eval was observed `read`-ing and
1256
+ // `grep_search`-ing the real repo for the solution. `bash` is never covered
1257
+ // here — it can escape via the shell itself, which is why `execCommand` and
1258
+ // the `cd` tracker are the real shell boundary.
1259
+ const PROJECT_ROOT = sandboxRoot ?? resolveProjectRoot() ?? process.cwd();
1260
+ const WRITERS = new Set(['write', 'edit', 'edit_block']);
1261
+ const READERS = new Set([
1262
+ 'read',
1263
+ 'ls',
1264
+ 'glob',
1265
+ 'grep',
1266
+ 'grep_search',
1267
+ 'ast_grep',
1268
+ 'repo_map',
1269
+ 'verify',
1270
+ 'write',
1271
+ 'edit',
1272
+ 'edit_block',
1273
+ ]);
1274
+ const guarded = sandboxRoot ? READERS : WRITERS;
1275
+ // `ls`/`glob`/`repo_map` default to the tracked cwd when no path is given,
1276
+ // so absence is checked against that too rather than being waved through.
1277
+ const rawPath = args.path !== undefined ? String(args.path) : undefined;
1278
+ if (guarded.has(name)) {
1279
+ const candidate = rawPath ?? (sandboxRoot ? shellCwd : undefined);
1280
+ if (candidate !== undefined) {
1281
+ const resolved = resolve(PROJECT_ROOT, candidate);
1282
+ if (!isInside(PROJECT_ROOT, resolved)) {
1283
+ return {
1284
+ toolCallId,
1285
+ content: `Error: path "${candidate}" resolves outside the workspace (${PROJECT_ROOT}). Refusing.`,
1286
+ error: true,
1287
+ };
1288
+ }
1150
1289
  }
1290
+ // `glob` takes its root as `path` when given, else the cwd — covered above.
1291
+ // `repo_map`/`verify` accept an optional `path`; when omitted they run at
1292
+ // the tracked cwd, which the shell guard already keeps inside.
1151
1293
  }
1152
1294
 
1153
1295
  log('tool-call', {name, args: argsStr});
@@ -1175,7 +1317,7 @@ export async function executeTool(
1175
1317
  });
1176
1318
  // Fire-and-forget: noteEditedFile only schedules a debounced background
1177
1319
  // check; the handler returns its result without waiting on diagnostics.
1178
- if (FILE_WRITERS.has(name) && args.path) {
1320
+ if (WRITERS.has(name) && args.path) {
1179
1321
  noteEditedFile(String(args.path));
1180
1322
  }
1181
1323
  return {toolCallId, content};
@@ -1195,13 +1337,7 @@ export async function executeTool(
1195
1337
  // ═══════════════════════════════════════════════════════════════════════════════
1196
1338
 
1197
1339
  /** Default read-only toolset for ad-hoc (role-less) delegation. */
1198
- const DEFAULT_CHILD_TOOLS = [
1199
- 'read',
1200
- 'ls',
1201
- 'grep_search',
1202
- 'ast_grep',
1203
- 'glob',
1204
- ];
1340
+ const DEFAULT_CHILD_TOOLS = ['read', 'ls', 'grep_search', 'ast_grep', 'glob'];
1205
1341
 
1206
1342
  const DEFAULT_CHILD_PROMPT =
1207
1343
  'You are a sub-agent. Complete the task and return a concise summary of your findings.\n\n' +
@@ -1245,6 +1381,49 @@ export function isMutatingToolset(toolNames: readonly string[]): boolean {
1245
1381
  return toolNames.some((t) => MUTATING_TOOLS.has(t));
1246
1382
  }
1247
1383
 
1384
+ /**
1385
+ * Tools a role declares that this process did not load.
1386
+ *
1387
+ * A role's tool list is a *declaration*, not a guarantee: extension tools only
1388
+ * exist once their extension is loaded. A declared-but-absent tool is silently
1389
+ * dropped by the definitions filter, and the child then works with a strictly
1390
+ * smaller toolset than its prompt assumes — a librarian whose `fetch_url` and
1391
+ * `web_search` never loaded produces confident fabricated research with
1392
+ * invented URLs. Callers warn on this rather than swallowing it.
1393
+ *
1394
+ * Exported as a pure function so the diagnostic is directly testable.
1395
+ */
1396
+ export function missingChildTools(
1397
+ declared: readonly string[],
1398
+ loaded: readonly string[],
1399
+ ): string[] {
1400
+ const available = new Set(loaded);
1401
+ return declared.filter((d) => !available.has(d));
1402
+ }
1403
+
1404
+ /**
1405
+ * The provider config a delegated child runs under.
1406
+ *
1407
+ * `allowedTools` is enforced transitively by `executeTool`, so passing the
1408
+ * parent's config down would hand the child the parent's allowlist. That is
1409
+ * wrong in both directions: it strips tools the child's own role declares
1410
+ * (librarian's web tools under the read-only plan primary), and it grants the
1411
+ * child anything the parent happened to be allowed. The child is rebuilt with
1412
+ * an allowlist of exactly the tools it was actually given.
1413
+ *
1414
+ * Every other field spreads through untouched — `readOnly` in particular, which
1415
+ * `planChild` uses to refuse mutating children. Dropping it here would let a
1416
+ * read-only turn reach a writer through delegation.
1417
+ *
1418
+ * Pure, so the inheritance rule is testable without spawning a provider.
1419
+ */
1420
+ export function buildChildProviderConfig<T extends {allowedTools?: string[]}>(
1421
+ parent: T,
1422
+ childToolNames: readonly string[],
1423
+ ): T & {allowedTools: string[]} {
1424
+ return {...parent, allowedTools: [...childToolNames]};
1425
+ }
1426
+
1248
1427
  /** A validated child launch request — everything needed to run it. */
1249
1428
  interface ChildPlan {
1250
1429
  task: string;
@@ -1265,6 +1444,12 @@ interface ChildPlan {
1265
1444
  * the child runs unbudgeted.
1266
1445
  */
1267
1446
  budget?: {roleName: string; limit: number};
1447
+ /**
1448
+ * Optional JSON Schema (a supported subset — see `json-schema.ts`) the child's
1449
+ * final answer must satisfy. Absent → the child returns free text, exactly as
1450
+ * before this feature existed.
1451
+ */
1452
+ schema?: unknown;
1268
1453
  }
1269
1454
 
1270
1455
  interface SpawnArgs {
@@ -1275,6 +1460,7 @@ interface SpawnArgs {
1275
1460
  reasoning?: 'low' | 'medium' | 'high';
1276
1461
  tools?: string[];
1277
1462
  max_rounds?: number;
1463
+ schema?: unknown;
1278
1464
  }
1279
1465
 
1280
1466
  /**
@@ -1347,6 +1533,19 @@ async function planChild(
1347
1533
  };
1348
1534
  }
1349
1535
 
1536
+ // A schema that is not an object constrains nothing, so catching it here beats
1537
+ // spawning a child that can never satisfy it. `null`/arrays are the shapes a
1538
+ // model plausibly emits by mistake (a JSON string, or a list of schemas).
1539
+ if (
1540
+ args.schema !== undefined &&
1541
+ (typeof args.schema !== 'object' || args.schema === null || Array.isArray(args.schema))
1542
+ ) {
1543
+ return {
1544
+ error:
1545
+ 'Error: `schema` must be a JSON Schema object, e.g. {"type":"object","required":["summary"]}.',
1546
+ };
1547
+ }
1548
+
1350
1549
  return {
1351
1550
  task,
1352
1551
  roleName: role?.name,
@@ -1357,6 +1556,108 @@ async function planChild(
1357
1556
  modelSpec: args.model ?? role?.model,
1358
1557
  mutating,
1359
1558
  budget,
1559
+ schema: args.schema,
1560
+ };
1561
+ }
1562
+
1563
+ /**
1564
+ * Run one child `runAgent` loop and report what it said.
1565
+ *
1566
+ * Split out of `executeChild` so the schema-repair path can enter the loop a
1567
+ * second time without duplicating the event plumbing. `roundText` is reset on
1568
+ * every `round-start` — so the returned `text` is the LAST round only, not a
1569
+ * transcript. For a schema-constrained child that is exactly what we want (the
1570
+ * final answer, not the mid-run commentary); for the free-text path it is
1571
+ * today's behaviour, unchanged.
1572
+ */
1573
+ async function runChildLoop(params: {
1574
+ runAgent: typeof import('../agent/run.js').runAgent;
1575
+ messages: ConversationMessage[];
1576
+ tools: ToolDef[];
1577
+ provider: Provider;
1578
+ model: string;
1579
+ systemPrompt: string;
1580
+ maxRounds: number;
1581
+ reasoning: 'low' | 'medium' | 'high';
1582
+ childProviderCfg: ChildProviderConfig;
1583
+ executeTool: NonNullable<ChildProviderConfig['childExecuteTool']>;
1584
+ budget?: {roleName: string; limit: number};
1585
+ controller: AbortController;
1586
+ agentId: string;
1587
+ signal?: AbortSignal;
1588
+ }): Promise<
1589
+ {ok: true; text: string; interrupted: boolean} | {ok: false; error: string; interrupted: boolean}
1590
+ > {
1591
+ let roundText = '';
1592
+ let previousText = '';
1593
+ try {
1594
+ for await (const ev of params.runAgent({
1595
+ messages: params.messages,
1596
+ tools: params.tools,
1597
+ provider: params.provider,
1598
+ model: params.model,
1599
+ systemPrompt: params.systemPrompt,
1600
+ maxRounds: params.maxRounds,
1601
+ reasoningEffort: params.reasoning,
1602
+ providerConfig: params.childProviderCfg,
1603
+ executeTool: params.executeTool,
1604
+ signal: params.controller.signal,
1605
+ budget: params.budget,
1606
+ })) {
1607
+ if (ev.type === 'round-start') {
1608
+ if (roundText) {
1609
+ previousText = roundText;
1610
+ roundText = '';
1611
+ }
1612
+ emitAgentEvent({type: 'delegate-round', id: params.agentId, round: ev.round});
1613
+ } else if (ev.type === 'text-delta') {
1614
+ roundText += ev.content;
1615
+ } else if (ev.type === 'tool-start') {
1616
+ emitAgentEvent({type: 'delegate-tool', id: params.agentId, tool: ev.name});
1617
+ }
1618
+ }
1619
+ } catch (err) {
1620
+ if (params.signal?.aborted || params.controller.signal.aborted)
1621
+ return {ok: false, error: '', interrupted: true};
1622
+ const msg = err instanceof Error ? err.message : String(err);
1623
+ return {ok: false, error: msg, interrupted: false};
1624
+ }
1625
+ // Only the LAST round's text counts as the answer — see the doc comment.
1626
+ return {ok: true, text: roundText.trim() || previousText.trim(), interrupted: false};
1627
+ }
1628
+
1629
+ /**
1630
+ * Try to turn a child's answer into a schema-satisfying value.
1631
+ *
1632
+ * The three failures are kept distinct because the fix differs for each and
1633
+ * collapsing them would waste the one repair round we are willing to spend:
1634
+ *
1635
+ * - nothing found → the child never attempted JSON (tell it to)
1636
+ * - unparseable → it tried and produced malformed text (show it)
1637
+ * - schema mismatch → valid JSON, wrong shape (list the paths)
1638
+ */
1639
+ function interpretChildAnswer(
1640
+ text: string,
1641
+ schema: unknown,
1642
+ ): {ok: true; value: unknown} | {ok: false; reason: string} {
1643
+ if (!text.trim()) {
1644
+ return {ok: false, reason: 'the answer was empty — no JSON value was returned'};
1645
+ }
1646
+ const extraction = extractJson(text);
1647
+ if (extraction.status === 'absent') {
1648
+ return {ok: false, reason: 'no JSON value found in the answer (it was prose only)'};
1649
+ }
1650
+ if (extraction.status === 'unparseable') {
1651
+ return {
1652
+ ok: false,
1653
+ reason: `the answer contained JSON-like text that did not parse: ${excerpt(extraction.text, 200)}`,
1654
+ };
1655
+ }
1656
+ const verdict = validateAgainstSchema(extraction.value, schema);
1657
+ if (verdict.ok) return {ok: true, value: extraction.value};
1658
+ return {
1659
+ ok: false,
1660
+ reason: `the JSON did not match the schema:\n${formatProblems(verdict.problems)}`,
1360
1661
  };
1361
1662
  }
1362
1663
 
@@ -1406,7 +1707,16 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1406
1707
  const {captureRunScope, restoreRunScope} = await import('../agent/scope.js');
1407
1708
  const scope = captureRunScope();
1408
1709
 
1409
- const childMessages: ConversationMessage[] = [{role: 'user', content: task}];
1710
+ // The child's ONLY input is this one message, so a schema the child is never
1711
+ // told about is a guaranteed validation failure. The instruction rides on the
1712
+ // task rather than the system prompt so it survives any role prompt verbatim.
1713
+ // Without a schema this is the bare task — today's behaviour, byte for byte.
1714
+ const childMessages: ConversationMessage[] = [
1715
+ {
1716
+ role: 'user',
1717
+ content: plan.schema === undefined ? task : `${task}${schemaInstruction(plan.schema)}`,
1718
+ },
1719
+ ];
1410
1720
 
1411
1721
  // Build the child's toolset from *all* tools — core plus extensions. A role
1412
1722
  // like `librarian` declares only extension tools (fetch_url, web_search); if
@@ -1414,58 +1724,155 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1414
1724
  const {getAllTools} = await import('./definitions.js');
1415
1725
  const childTools = getAllTools().filter((t) => allowedTools.includes(t.function.name));
1416
1726
 
1727
+ // A role can declare a tool this process never loaded (its extension is
1728
+ // absent from `config.extensions`). Silence here is what made a librarian
1729
+ // with no retriever look like "the model is flaky" instead of "the tool was
1730
+ // never there" — say so, once, at spawn time.
1731
+ const missing = missingChildTools(
1732
+ allowedTools,
1733
+ childTools.map((t) => t.function.name),
1734
+ );
1735
+ if (missing.length > 0) {
1736
+ console.warn(
1737
+ `pal: role "${plan.roleName ?? 'ad-hoc delegate'}" declares ` +
1738
+ `${missing.join(', ')} but ${missing.length === 1 ? 'it is' : 'they are'} not loaded`,
1739
+ );
1740
+ }
1741
+
1742
+ // The child gets *its own* allowlist, not the parent's. Inheriting is wrong
1743
+ // twice over: it strips tools the role legitimately needs (librarian's
1744
+ // fetch_url/web_search under the read-only plan primary), and it lets the
1745
+ // child call whatever the parent could. This is strictly tighter — the child
1746
+ // can now reach only its declared tools. `readOnly` and the mutating check
1747
+ // spread through unchanged, so plan mode still cannot write.
1748
+ const childProviderCfg = buildChildProviderConfig(
1749
+ providerCfg,
1750
+ childTools.map((t) => t.function.name),
1751
+ );
1752
+
1417
1753
  // Dynamic import avoids the executor → run → executor import cycle.
1418
1754
  const {runAgent} = await import('../agent/run.js');
1419
1755
  const {withSystemPromptAppend} = await import('../provider/registry.js');
1420
1756
 
1421
1757
  await provider.init();
1422
1758
 
1423
- let roundText = '';
1424
- let previousText = '';
1759
+ const cancelled = 'Delegate cancelled (aborted by user).';
1760
+ const childExec = providerCfg.childExecuteTool ?? executeTool;
1761
+ const childSystemPrompt = withSystemPromptAppend(systemPrompt, config.provider);
1762
+
1763
+ // One controller per child, rather than passing the turn signal straight
1764
+ // through: aborting the TURN must still cancel the child, but a run that ends
1765
+ // for its own reasons must not be reported as a user interrupt. The child's
1766
+ // abort state is therefore `signal.aborted || controller.signal.aborted`, and
1767
+ // a self-abort carries a namespaced reason so it is never mistaken for one.
1768
+ const controller = new AbortController();
1769
+ const onTurnAbort = () => controller.abort(config.signal?.reason);
1770
+ if (config.signal?.aborted) controller.abort(config.signal.reason);
1771
+ else config.signal?.addEventListener('abort', onTurnAbort, {once: true});
1772
+ const abortedByUser = () => config.signal?.aborted === true;
1425
1773
 
1426
1774
  // Live-activity counter for the front-end's status line. Spawned strictly
1427
1775
  // around the child run: everything below passes through the finally, so the
1428
1776
  // settle is symmetric on success, error, and abort — a leaked count would
1429
1777
  // leave a permanent phantom "subagents running" line in the UI.
1430
1778
  subagentSpawned();
1431
- const cancelled = 'Delegate cancelled (aborted by user).';
1779
+ let summary: string;
1432
1780
  try {
1433
- const childExec = providerCfg.childExecuteTool ?? executeTool;
1434
- for await (const ev of runAgent({
1435
- messages: childMessages,
1436
- tools: childTools,
1437
- provider,
1438
- model: childModel,
1439
- systemPrompt: withSystemPromptAppend(systemPrompt, config.provider),
1440
- maxRounds,
1441
- reasoningEffort: reasoning,
1442
- providerConfig: providerCfg,
1443
- executeTool: childExec,
1444
- signal: config.signal,
1445
- budget: plan.budget,
1446
- })) {
1447
- if (ev.type === 'round-start') {
1448
- if (roundText) {
1449
- previousText = roundText;
1450
- roundText = '';
1451
- }
1452
- emitAgentEvent({type: 'delegate-round', id: agentId, round: ev.round});
1453
- } else if (ev.type === 'text-delta') {
1454
- roundText += ev.content;
1455
- } else if (ev.type === 'tool-start') {
1456
- emitAgentEvent({type: 'delegate-tool', id: agentId, tool: ev.name});
1457
- }
1781
+ const run = (messages: ConversationMessage[]) =>
1782
+ runChildLoop({
1783
+ runAgent,
1784
+ messages,
1785
+ tools: childTools,
1786
+ provider,
1787
+ model: childModel,
1788
+ systemPrompt: childSystemPrompt,
1789
+ maxRounds,
1790
+ reasoning,
1791
+ childProviderCfg,
1792
+ executeTool: childExec,
1793
+ budget: plan.budget,
1794
+ controller,
1795
+ agentId,
1796
+ signal: config.signal,
1797
+ });
1798
+
1799
+ const first = await run(childMessages);
1800
+
1801
+ // A budget stop is a deliberate early exit whose message the parent already
1802
+ // recognises. Checked BEFORE the schema branch so a schema-constrained child
1803
+ // that ran out of tokens reports the budget line — not a schema failure, and
1804
+ // without spending the repair round on an answer it will never produce.
1805
+ if (first.ok && first.text.includes('Stopped: token budget')) {
1806
+ emitAgentEvent({type: 'delegate-done', id: agentId, summary: first.text, error: true});
1807
+ return first.text;
1458
1808
  }
1459
- } catch (err) {
1460
- if (config.signal?.aborted) {
1809
+
1810
+ if (first.interrupted) {
1461
1811
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: cancelled, error: true});
1462
1812
  return cancelled;
1463
1813
  }
1464
- const msg = err instanceof Error ? err.message : String(err);
1465
- emitAgentEvent({type: 'delegate-done', id: agentId, summary: msg, error: true});
1466
- return `Delegate error: ${msg}`;
1814
+ if (!first.ok) {
1815
+ // A genuine error keeps today's `Delegate error:` prefix, so nothing
1816
+ // downstream has to learn a new shape.
1817
+ const msg = `Delegate error: ${first.error}`;
1818
+ emitAgentEvent({type: 'delegate-done', id: agentId, summary: msg, error: true});
1819
+ return msg;
1820
+ }
1821
+
1822
+ // No schema → today's behaviour, byte for byte: the last round's text, or
1823
+ // the "no summary" fallback. Nothing below this branch runs.
1824
+ if (plan.schema === undefined) {
1825
+ summary = first.text || 'Task completed (no summary generated).';
1826
+ } else {
1827
+ const firstVerdict = interpretChildAnswer(first.text, plan.schema);
1828
+ if (firstVerdict.ok) {
1829
+ // Re-serialised, not echoed: a child that answered inside a fence or
1830
+ // with a prose sign-off hands the parent a clean JSON document.
1831
+ summary = JSON.stringify(firstVerdict.value, null, 2);
1832
+ } else {
1833
+ // Exactly one repair round. Retrying until it agrees is a treadmill: a
1834
+ // child that cannot produce the shape once rarely produces it on the
1835
+ // third attempt, and the parent needs to hear about it either way.
1836
+ //
1837
+ // The correction goes in as a `user` message because the child's own
1838
+ // last answer is often null (a model that emitted prose and no tool
1839
+ // call never gets an assistant message appended) — so there is no
1840
+ // guaranteed assistant turn to answer. A user message is valid in every
1841
+ // case and carries the same instruction.
1842
+ childMessages.push({
1843
+ role: 'user',
1844
+ content: correctionPrompt(plan.schema, firstVerdict.reason),
1845
+ });
1846
+ emitAgentEvent({type: 'delegate-round', id: agentId, round: 1});
1847
+ const second = await run(childMessages);
1848
+ if (second.interrupted) {
1849
+ emitAgentEvent({type: 'delegate-done', id: agentId, summary: cancelled});
1850
+ return cancelled;
1851
+ }
1852
+ const secondVerdict = second.ok
1853
+ ? interpretChildAnswer(second.text, plan.schema)
1854
+ : undefined;
1855
+ if (secondVerdict?.ok) {
1856
+ summary = JSON.stringify(secondVerdict.value, null, 2);
1857
+ } else if (second.ok && !second.text.trim()) {
1858
+ // The repair round said nothing at all. Blaming "an empty answer"
1859
+ // would point at the wrong round and discard the only diagnosis we
1860
+ // have, so report the FIRST answer's problem and keep it as evidence.
1861
+ summary = schemaFailure(firstVerdict, first.text);
1862
+ } else {
1863
+ summary = schemaFailure(
1864
+ secondVerdict ?? {
1865
+ ok: false,
1866
+ reason: `the repair round failed: ${second.ok ? '' : second.error}`,
1867
+ },
1868
+ second.ok ? second.text : first.text,
1869
+ );
1870
+ }
1871
+ }
1872
+ }
1467
1873
  } finally {
1468
1874
  subagentSettled();
1875
+ config.signal?.removeEventListener('abort', onTurnAbort);
1469
1876
  // Hand the parent's state back, and re-sync the UI (which may have rendered
1470
1877
  // the child's todo list via todos-updated).
1471
1878
  restoreRunScope(scope);
@@ -1473,17 +1880,34 @@ async function executeChild(plan: ChildPlan, config: ToolConfig): Promise<string
1473
1880
  emitAgentEvent({type: 'todos-updated', todos: getTodos()});
1474
1881
  }
1475
1882
 
1476
- // Aborted mid-run: the run ended with `aborted` (not a summary), so report
1477
- // the cancellation instead of claiming completion.
1478
- if (config.signal?.aborted) {
1883
+ // Aborted by the user mid-run: report the cancellation rather than a summary.
1884
+ if (abortedByUser()) {
1479
1885
  emitAgentEvent({type: 'delegate-done', id: agentId, summary: cancelled});
1480
1886
  return cancelled;
1481
1887
  }
1482
1888
 
1483
- const summary = roundText.trim() || previousText.trim();
1484
- const finalSummary = summary || 'Task completed (no summary generated).';
1485
- emitAgentEvent({type: 'delegate-done', id: agentId, summary: finalSummary});
1486
- return finalSummary;
1889
+ emitAgentEvent({type: 'delegate-done', id: agentId, summary});
1890
+ return summary;
1891
+ }
1892
+
1893
+ /**
1894
+ * The string a parent gets when a child answered but never satisfied the schema.
1895
+ *
1896
+ * A failure, not a warning: returning the prose with a note would leave the
1897
+ * parent parsing free text it explicitly asked not to receive. The problems name
1898
+ * paths, so the parent can either fix the child's task or decide the answer is
1899
+ * good enough on its own terms — and the raw text is kept, truncated, so no
1900
+ * information is lost in the process.
1901
+ */
1902
+ function schemaFailure(
1903
+ verdict: {ok: true; value: unknown} | {ok: false; reason: string},
1904
+ rawText: string,
1905
+ ): string {
1906
+ const reason = verdict.ok
1907
+ ? 'the answer satisfied the schema but could not be re-serialised'
1908
+ : verdict.reason;
1909
+ const tail = rawText.trim() ? `\n\nChild's last answer: ${excerpt(rawText, 300)}` : '';
1910
+ return `Delegate returned no schema-valid answer after one repair attempt: ${reason}${tail}`;
1487
1911
  }
1488
1912
 
1489
1913
  /** Normalise the raw tool args into the internal SpawnArgs shape. */
@@ -1496,6 +1920,7 @@ function toSpawnArgs(raw: Record<string, unknown>): SpawnArgs {
1496
1920
  reasoning: raw.reasoning as SpawnArgs['reasoning'],
1497
1921
  tools: Array.isArray(raw.tools) ? raw.tools.map(String) : undefined,
1498
1922
  max_rounds: raw.max_rounds !== undefined ? Number(raw.max_rounds) : undefined,
1923
+ schema: raw.schema,
1499
1924
  };
1500
1925
  }
1501
1926