@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.
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Turning LSP diagnostics into the one line pal feeds back to the model.
3
+ *
4
+ * Pure — the client owns processes and timers; this owns the meaning. Two rules
5
+ * matter more than they look:
6
+ *
7
+ * 1. **Only errors.** A language server reports hints, information, warnings and
8
+ * errors. pal injects the result into the model's next context, so a warning
9
+ * about an unused variable would be noise the model then tries to "fix".
10
+ * 2. **Only the edited files.** A server happily reports pre-existing errors
11
+ * across the whole workspace. Those were not caused by this edit, and telling
12
+ * the model about them sends it chasing someone else's bug.
13
+ */
14
+
15
+ import {isAbsolute, relative, resolve, sep} from 'path';
16
+
17
+ /** The subset of LSP's `Diagnostic` this module reads. */
18
+ export interface LspDiagnostic {
19
+ range?: {start?: {line?: number; character?: number}};
20
+ severity?: number;
21
+ message?: string;
22
+ source?: string;
23
+ }
24
+
25
+ /** LSP severity numbers. 1 = Error is the only one that means "broken". */
26
+ export const SEVERITY_ERROR = 1;
27
+
28
+ export interface MappedDiagnostic {
29
+ path: string;
30
+ /** 1-based, because every editor and compiler pal already speaks to is 1-based. */
31
+ line: number;
32
+ message: string;
33
+ }
34
+
35
+ /**
36
+ * Normalise a server-reported URI to a project-relative path.
37
+ *
38
+ * Servers send `file:///C:/x/y.ts` (Windows), `file:///home/x/y.ts` (POSIX), and
39
+ * sometimes percent-escaped (`%20` for a space). `fileURLToPath` handles all
40
+ * three; the manual fallback exists only for servers that send a bare path,
41
+ * which is out of spec but not unheard of.
42
+ */
43
+ export function uriToRelPath(uri: string, cwd: string): string | null {
44
+ let filePath: string;
45
+ try {
46
+ if (uri.startsWith('file:')) {
47
+ filePath = decodeURIComponent(new URL(uri).pathname);
48
+ // Windows: `file:///C:/x` yields `/C:/x`; drop the leading slash.
49
+ if (/^\/[a-zA-Z]:/.test(filePath)) filePath = filePath.slice(1);
50
+ } else {
51
+ filePath = uri;
52
+ }
53
+ } catch {
54
+ return null;
55
+ }
56
+
57
+ const abs = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);
58
+ const rel = relative(cwd, abs);
59
+ // Outside the project: report the absolute path rather than `../../..`.
60
+ if (rel.startsWith('..') || rel === '') return abs.split(sep).join('/');
61
+ return rel.split(sep).join('/');
62
+ }
63
+
64
+ /**
65
+ * Keep only error-severity diagnostics that belong to `changedFiles`.
66
+ *
67
+ * @param byUri `textDocument/publishDiagnostics` payloads, already keyed by URI.
68
+ */
69
+ export function mapDiagnostics(
70
+ byUri: ReadonlyMap<string, readonly LspDiagnostic[]>,
71
+ changedFiles: readonly string[],
72
+ cwd: string,
73
+ ): MappedDiagnostic[] {
74
+ // Compare on normalised relative paths: the server may report `src/a.ts` while
75
+ // the caller passed `/abs/project/src/a.ts`, and those must be the same file.
76
+ const wanted = new Set(changedFiles.map((f) => normalise(f, cwd)));
77
+ const out: MappedDiagnostic[] = [];
78
+
79
+ for (const [uri, diagnostics] of byUri) {
80
+ const rel = uriToRelPath(uri, cwd);
81
+ if (rel === null) continue;
82
+ if (!wanted.has(normalise(rel, cwd))) continue;
83
+
84
+ for (const d of diagnostics) {
85
+ if (d.severity !== undefined && d.severity !== SEVERITY_ERROR) continue;
86
+ const message = (d.message ?? '').replace(/\s+/g, ' ').trim();
87
+ if (message === '') continue;
88
+ out.push({
89
+ path: rel,
90
+ // LSP lines are 0-based; every other tool pal reports from is 1-based.
91
+ line: (d.range?.start?.line ?? 0) + 1,
92
+ message: d.source ? `${message} (${d.source})` : message,
93
+ });
94
+ }
95
+ }
96
+
97
+ return out;
98
+ }
99
+
100
+ function normalise(p: string, cwd: string): string {
101
+ const abs = isAbsolute(p) ? p : resolve(cwd, p);
102
+ return abs.split(sep).join('/').toLowerCase();
103
+ }
104
+
105
+ /**
106
+ * A configuration a language server can actually start from.
107
+ *
108
+ * The single most likely failure is "spawned a real server against a workspace
109
+ * with no config and got a wall of setup errors", which would then be injected
110
+ * into the model as if the edit broke something. So this generates a minimal
111
+ * in-memory config for the two cases where such errors are guaranteed:
112
+ *
113
+ * - **pyright** reports every import as unresolved without a `venvPath`, which is
114
+ * not a real error and is the classic false-positive wall.
115
+ * - **`tsc` LSP** (typescript-language-server) needs *some* compiler options; an
116
+ * empty object means it falls back to defaults that may not match the project,
117
+ * but importantly it does not report "no config found" as a diagnostic.
118
+ *
119
+ * Deliberately minimal: a real project config on disk always wins, because the
120
+ * server only uses this when nothing else is available.
121
+ */
122
+ export function fallbackWorkspaceConfig(languageId: string): {settings: unknown} | null {
123
+ if (languageId === 'python') {
124
+ return {
125
+ settings: {
126
+ python: {
127
+ analysis: {
128
+ // Do not flag every third-party import as unresolved. This is the
129
+ // difference between a useful signal and 40 lines of noise.
130
+ diagnosticSeverityOverrides: {reportMissingImports: 'none'},
131
+ useLibraryCodeForTypes: true,
132
+ },
133
+ },
134
+ },
135
+ };
136
+ }
137
+ return null;
138
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * A fake LSP server for testing `runLspChecks` against real process I/O.
3
+ *
4
+ * Reads `Content-Length` frames on stdin, answers `initialize` and `shutdown`,
5
+ * and on `didOpen` publishes a configurable set of diagnostics. Behaviour comes
6
+ * from `argv[2]` (not an env var: `Bun.spawn` does not reliably inherit a
7
+ * `process.env` mutation made after the test process started):
8
+ *
9
+ * - `clean` — publishes nothing at all (the "no opinion" case that must fall
10
+ * back rather than claim the file is fine)
11
+ * - `errors` — publishes one error + one warning per opened file, in two
12
+ * separate frames so the client's quiet-period logic is exercised
13
+ * - `slow` — never answers `initialize` (must time out, not hang)
14
+ * - `die` — exits immediately after spawn
15
+ */
16
+
17
+ const mode = process.argv[2] ?? 'errors';
18
+
19
+ function send(payload: unknown): void {
20
+ const json = JSON.stringify(payload);
21
+ process.stdout.write(`Content-Length: ${Buffer.byteLength(json, 'utf8')}\r\n\r\n${json}`);
22
+ }
23
+
24
+ if (mode === 'die') process.exit(0);
25
+
26
+ let buffer = Buffer.alloc(0);
27
+
28
+ process.stdin.on('data', (chunk: Buffer) => {
29
+ buffer = Buffer.concat([buffer, chunk]);
30
+
31
+ for (;;) {
32
+ const headerEnd = buffer.indexOf('\r\n\r\n');
33
+ if (headerEnd === -1) return;
34
+ const header = buffer.subarray(0, headerEnd).toString('ascii');
35
+ const len = Number(/content-length:\s*(\d+)/i.exec(header)?.[1] ?? -1);
36
+ if (len < 0) {
37
+ buffer = buffer.subarray(headerEnd + 4);
38
+ continue;
39
+ }
40
+ const start = headerEnd + 4;
41
+ if (buffer.length < start + len) return;
42
+
43
+ const msg = JSON.parse(buffer.subarray(start, start + len).toString('utf8'));
44
+ buffer = buffer.subarray(start + len);
45
+ handle(msg);
46
+ }
47
+ });
48
+
49
+ function handle(msg: {id?: number; method?: string; params?: Record<string, unknown>}): void {
50
+ switch (msg.method) {
51
+ case 'initialize': {
52
+ if (mode === 'slow') return; // never answer → caller must time out
53
+ send({jsonrpc: '2.0', id: msg.id, result: {capabilities: {}}});
54
+ return;
55
+ }
56
+ case 'shutdown': {
57
+ send({jsonrpc: '2.0', id: msg.id, result: null});
58
+ return;
59
+ }
60
+ case 'exit': {
61
+ process.exit(0);
62
+ return;
63
+ }
64
+ case 'textDocument/didOpen': {
65
+ const td = msg.params?.textDocument as {uri: string} | undefined;
66
+ if (!td || mode === 'clean') return;
67
+
68
+ // Two publishes, like a real server: errors first, then the full set.
69
+ send({
70
+ jsonrpc: '2.0',
71
+ method: 'textDocument/publishDiagnostics',
72
+ params: {
73
+ uri: td.uri,
74
+ diagnostics: [
75
+ {
76
+ range: {start: {line: 4, character: 0}},
77
+ severity: 1,
78
+ source: 'fake',
79
+ message: 'undefined name: x',
80
+ },
81
+ ],
82
+ },
83
+ });
84
+ if (mode !== 'errors') return;
85
+
86
+ setTimeout(() => {
87
+ send({
88
+ jsonrpc: '2.0',
89
+ method: 'textDocument/publishDiagnostics',
90
+ params: {
91
+ uri: td.uri,
92
+ diagnostics: [
93
+ {
94
+ range: {start: {line: 4, character: 0}},
95
+ severity: 1,
96
+ source: 'fake',
97
+ message: 'undefined name: x',
98
+ },
99
+ // Must be filtered out: warnings never reach the model.
100
+ {range: {start: {line: 6}}, severity: 2, message: 'unused import'},
101
+ ],
102
+ },
103
+ });
104
+ }, 40);
105
+ return;
106
+ }
107
+ default:
108
+ return;
109
+ }
110
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * LSP wire framing: `Content-Length: N\r\n\r\n<json>`.
3
+ *
4
+ * Pure on purpose — no process, no I/O, no timers. Framing bugs (a split header,
5
+ * a body arriving in three chunks, a stray `\r\n` after the JSON) are the kind
6
+ * of thing that looks fine until a large diagnostic payload lands, so they get
7
+ * their own testable unit rather than hiding inside the client.
8
+ */
9
+
10
+ /** A single LSP message on the wire, once framed. */
11
+ export interface Frame {
12
+ /** The decoded JSON body. Malformed bodies are surfaced, never silently dropped. */
13
+ body: unknown;
14
+ /** Set when the body could not be parsed, with the raw text for the log. */
15
+ parseError?: string;
16
+ }
17
+
18
+ /**
19
+ * Encode one message for a server's stdin.
20
+ *
21
+ * `JSON.stringify` output is byte-length-safe here: LSP bodies are JSON, and
22
+ * `Content-Length` is defined in **bytes**, so the UTF-8 length is what must be
23
+ * sent — `Buffer.byteLength` rather than `String.length`, or a message containing
24
+ * an em-dash or a non-ASCII path desynchronises the stream permanently.
25
+ */
26
+ export function encodeMessage(payload: unknown): string {
27
+ const json = JSON.stringify(payload);
28
+ const bytes = Buffer.byteLength(json, 'utf8');
29
+ return `Content-Length: ${bytes}\r\n\r\n${json}`;
30
+ }
31
+
32
+ /**
33
+ * Incremental decoder for a byte stream of LSP frames.
34
+ *
35
+ * Feed it whatever `stdout` hands over — headers split mid-line, two messages in
36
+ * one chunk, a body split across three — and it yields whole frames in order.
37
+ * Anything it cannot parse is yielded as a `parseError` frame so the client can
38
+ * log and continue instead of wedging.
39
+ */
40
+ export class FrameDecoder {
41
+ private buffer = Buffer.alloc(0);
42
+
43
+ /** Append a chunk and return every frame that is now complete. */
44
+ push(chunk: Buffer | Uint8Array): Frame[] {
45
+ this.buffer = Buffer.concat([this.buffer, Buffer.from(chunk)]);
46
+ const frames: Frame[] = [];
47
+
48
+ for (;;) {
49
+ const headerEnd = this.buffer.indexOf('\r\n\r\n');
50
+ if (headerEnd === -1) break;
51
+
52
+ const header = this.buffer.subarray(0, headerEnd).toString('ascii');
53
+ const length = parseContentLength(header);
54
+ if (length === null) {
55
+ // A header with no usable Content-Length cannot be framed. Drop the
56
+ // header and report it, rather than waiting forever for a body.
57
+ this.buffer = this.buffer.subarray(headerEnd + 4);
58
+ frames.push({body: null, parseError: `bad header: ${header.slice(0, 120)}`});
59
+ continue;
60
+ }
61
+
62
+ const bodyStart = headerEnd + 4;
63
+ const bodyEnd = bodyStart + length;
64
+ if (this.buffer.length < bodyEnd) break; // body not fully arrived yet
65
+
66
+ const bodyText = this.buffer.subarray(bodyStart, bodyEnd).toString('utf8');
67
+ this.buffer = this.buffer.subarray(bodyEnd);
68
+
69
+ try {
70
+ frames.push({body: JSON.parse(bodyText)});
71
+ } catch (err) {
72
+ frames.push({
73
+ body: null,
74
+ parseError: `bad body: ${err instanceof Error ? err.message : String(err)}`,
75
+ });
76
+ }
77
+ }
78
+
79
+ return frames;
80
+ }
81
+ }
82
+
83
+ /** `Content-Length: 123` → 123, or null when absent/not a non-negative integer. */
84
+ export function parseContentLength(header: string): number | null {
85
+ for (const line of header.split('\r\n')) {
86
+ const match = /^content-length:\s*(\d+)\s*$/i.exec(line.trim());
87
+ if (!match) continue;
88
+ const n = Number(match[1]);
89
+ if (!Number.isSafeInteger(n) || n < 0) return null;
90
+ return n;
91
+ }
92
+ return null;
93
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Which language server to start, if any.
3
+ *
4
+ * pal's rule for every optional dependency is the same: **absent infrastructure
5
+ * is not an error**, it is a silent skip. So this module never says "you should
6
+ * have pyright" — it says "no server binary on PATH", and the caller falls back
7
+ * to whatever it did before. Nothing here spawns anything; `isAvailable` only
8
+ * resolves a binary path.
9
+ *
10
+ * Coverage is deliberately small. biome + tsc already handle JS/TS well and are
11
+ * the path that ships enabled, so LSP exists for the languages that currently
12
+ * get *no* post-edit feedback at all. TypeScript is pointedly **not** in this
13
+ * list: `typescript-language-server` would claim `.ts` and displace biome+tsc,
14
+ * trading lint coverage for nothing. A language joins this list only when it has
15
+ * no working checker today.
16
+ */
17
+
18
+ import {extname} from 'path';
19
+
20
+ export interface ServerSpec {
21
+ /** Language id sent to the server in `didOpen`. */
22
+ languageId: string;
23
+ /** Binary to look for on PATH. */
24
+ command: string;
25
+ args: readonly string[];
26
+ /** Extensions this server claims. */
27
+ extensions: readonly string[];
28
+ }
29
+
30
+ /**
31
+ * The supported set, in priority order.
32
+ *
33
+ * Each entry needs only to exist on PATH: type checkers that are installed as
34
+ * project dependencies (pyright, gopls, rust-analyzer) are already resolvable
35
+ * through the normal PATH/`node_modules/.bin` lookup, so there is no separate
36
+ * install step to manage and no bundled binaries to ship.
37
+ */
38
+ export const SERVERS: readonly ServerSpec[] = [
39
+ {
40
+ languageId: 'python',
41
+ command: 'pyright-langserver',
42
+ args: ['--stdio'],
43
+ extensions: ['.py', '.pyi'],
44
+ },
45
+ {
46
+ languageId: 'go',
47
+ command: 'gopls',
48
+ args: [],
49
+ extensions: ['.go'],
50
+ },
51
+ {
52
+ languageId: 'rust',
53
+ command: 'rust-analyzer',
54
+ args: [],
55
+ extensions: ['.rs'],
56
+ },
57
+ ];
58
+
59
+ /** The server that claims this file's extension, if any. */
60
+ export function serverForFile(file: string): ServerSpec | null {
61
+ const ext = extname(file).toLowerCase();
62
+ if (ext === '') return null;
63
+ return SERVERS.find((s) => s.extensions.includes(ext)) ?? null;
64
+ }
65
+
66
+ /**
67
+ * The one server that can check *all* of `files`.
68
+ *
69
+ * Batching exists so a multi-file edit pays one server start, not N. Files that
70
+ * no server claims, or that need a different server, are simply left out — the
71
+ * caller compares the returned list against its input to know what was covered.
72
+ */
73
+ export function serverForBatch(files: readonly string[]): {
74
+ spec: ServerSpec;
75
+ covered: string[];
76
+ } | null {
77
+ const counts = new Map<ServerSpec, string[]>();
78
+ for (const file of files) {
79
+ const spec = serverForFile(file);
80
+ if (spec === null) continue;
81
+ const list = counts.get(spec) ?? [];
82
+ list.push(file);
83
+ counts.set(spec, list);
84
+ }
85
+
86
+ let best: {spec: ServerSpec; covered: string[]} | null = null;
87
+ for (const [spec, covered] of counts) {
88
+ if (best === null || covered.length > best.covered.length) best = {spec, covered};
89
+ }
90
+ return best;
91
+ }
92
+
93
+ /**
94
+ * Resolve a binary on PATH, or `null`.
95
+ *
96
+ * `Bun.which` handles the platform split (`.exe`/`.cmd` on Windows, `PATHEXT`,
97
+ * executable bit on POSIX) that a manual PATH walk gets wrong. Wrapped in
98
+ * try/catch because a malformed PATH should degrade to "not available", not
99
+ * throw inside the edit path.
100
+ */
101
+ export function isAvailable(command: string): string | null {
102
+ try {
103
+ return Bun.which(command) ?? null;
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Is the LSP path switched on?
111
+ *
112
+ * Default **OFF** — the opposite default from lazy schemas, and for a different
113
+ * reason. Lazy schemas only change bytes pal sends to an API it already trusts;
114
+ * this spawns a foreign process against the user's workspace. That is a
115
+ * behaviour change users did not ask for, so it stays opt-in until it has real
116
+ * mileage. `PAL_LSP=1|true|on|yes` enables it.
117
+ */
118
+ export const LSP_ENV = 'PAL_LSP';
119
+
120
+ const OPT_IN = new Set(['1', 'true', 'on', 'yes', 'enabled']);
121
+
122
+ export function isLspEnabled(): boolean {
123
+ const raw = (process.env[LSP_ENV] ?? '').trim().toLowerCase();
124
+ return OPT_IN.has(raw);
125
+ }
@@ -5,6 +5,7 @@
5
5
  import {registry} from '../registry.js';
6
6
  import {ensureSkillTool} from '../agent/skills.js';
7
7
  import {listRoleSpecs, type RoleSpec} from '../agent/roles.js';
8
+ import {projectTools} from './lazy.js';
8
9
 
9
10
  export interface ToolDef {
10
11
  type: 'function';
@@ -100,15 +101,27 @@ export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
100
101
  return [...core, ...registry.extensionTools, ...extra, ...(skillTool ? [skillTool] : [])];
101
102
  }
102
103
 
104
+ /**
105
+ * The tool list as the MODEL should see it.
106
+ *
107
+ * Identical to {@link getAllTools} unless lazy schemas are enabled, in which case
108
+ * deferrable tools are replaced by one-line stubs (see `lazy.ts`). This is the
109
+ * ONLY place the projection is applied, and it is applied to the wire list only:
110
+ * `getAllTools()` keeps returning real schemas, because argument validation
111
+ * (`validateRequiredArgs`) and child-agent construction both resolve tools
112
+ * through it and must never see a stub.
113
+ *
114
+ * Off by default. `PAL_LAZY_TOOLS` unset → byte-for-byte today's list.
115
+ */
116
+ export function getWireTools(extra: ToolDef[] = []): ToolDef[] {
117
+ return projectTools(getAllTools(extra));
118
+ }
119
+
103
120
  const ROLE_DERIVED_TOOLS: Record<string, (roles: RoleSpec[]) => ToolDef> = {
104
121
  delegate: buildDelegateTool,
105
122
  delegate_parallel: buildDelegateParallelTool,
106
123
  };
107
124
 
108
- function formatRoles(roles: RoleSpec[]): string {
109
- return roles.map((r) => `${r.name} — ${r.description.replace(/\.$/, '')}`).join('; ');
110
- }
111
-
112
125
  /**
113
126
  * The `delegate` description, derived from the live role registry.
114
127
  *
@@ -116,46 +129,41 @@ function formatRoles(roles: RoleSpec[]): string {
116
129
  * provider without touching the global registry; the default reads `listRoleSpecs()`
117
130
  * — the same source `buildRolesPrompt()` uses.
118
131
  *
119
- * With no roles it is generic: it must never name roles that don't exist.
120
- * With roles it lists the actual configured names + one-line descriptions, so
121
- * custom `agents.json` setups see *their* roles, not hardcoded OMO names.
132
+ * Role names are deliberately NOT inlined here. They are already listed in the
133
+ * system prompt's role block (`buildRolesPrompt`), so inlining them printed the
134
+ * same catalogue twice — and this copy is the expensive one: it sits in the tool
135
+ * schema, which is re-sent with every request and grows with every role the user
136
+ * configures. Referencing the block instead keeps the schema flat.
137
+ *
138
+ * With no roles configured the wording stays generic, so it can never name a
139
+ * role that does not exist.
122
140
  *
123
141
  * The trailing sentences are brief-writing guidance (fix #3): the child starts
124
142
  * fresh by design, so facts the parent knows must go into `task` — and
125
143
  * `recall_history` is the opt-in hatch for earlier main-session context.
126
144
  */
127
145
  export function buildDelegateDescription(roles: RoleSpec[] = listRoleSpecs()): string {
128
- const agents = roles.filter((r) => r.kind === 'agent');
129
- const categories = roles.filter((r) => r.kind === 'category');
146
+ const hasRoles = roles.length > 0;
130
147
 
131
- const routing: string[] = [];
132
- if (roles.length === 0) {
133
- routing.push('Omit `agent`/`category` — ad-hoc delegation with default read-only tools.');
134
- } else {
135
- if (agents.length > 0) {
136
- routing.push(`Pass \`agent\` for a read-only specialist: ${formatRoles(agents)}.`);
137
- }
138
- if (categories.length > 0) {
139
- routing.push(`Pass \`category\` for an implementation lane: ${formatRoles(categories)}.`);
140
- }
141
- routing.push('Omit both for ad-hoc delegation with default read-only tools.');
142
- }
148
+ const routing = hasRoles
149
+ ? 'Pass `agent` (read-only specialist) or `category` (implementation lane); names are in your system prompt’s role table. Omit both for ad-hoc read-only delegation.'
150
+ : 'Omit `agent`/`category` — ad-hoc delegation with default read-only tools.';
143
151
 
144
152
  return [
145
- 'Delegate a sub-task to a child agent with its own context.',
146
- ...routing,
147
- '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.',
148
- "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.",
153
+ 'Delegate a sub-task to a child agent with its own fresh context.',
154
+ routing,
155
+ 'The child sees none of this conversation: put facts INTO `task` (paths, constraints, disproved hypotheses) or it re-discovers them.',
156
+ 'It can call `recall_history` to pull earlier messages.',
149
157
  ].join(' ');
150
158
  }
151
159
 
152
160
  export function buildDelegateParallelDescription(roles: RoleSpec[] = listRoleSpecs()): string {
153
- const hint = roles.length > 0 ? ` Available roles: ${roles.map((r) => r.name).join(', ')}.` : '';
161
+ // Same reasoning as `buildDelegateDescription`: the role names live in the
162
+ // system prompt's role table, not in this schema.
154
163
  return (
155
- 'Run several delegates concurrently — each entry takes the same `agent`/`category` as `delegate`.' +
156
- hint +
157
- ' Use when sub-tasks are independent (e.g. fan out across three parts of a codebase).' +
158
- ' Respects the configured max_parallel limit and returns results in input order.'
164
+ 'Run several delegates concurrently. Each entry takes the same `agent`/`category` as `delegate`' +
165
+ (roles.length > 0 ? ' (names in your system prompt’s role table)' : '') +
166
+ '. Use when sub-tasks are independent. Bounded by max_parallel; results return in input order.'
159
167
  );
160
168
  }
161
169
 
@@ -174,18 +182,21 @@ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
174
182
  type: 'string',
175
183
  description: 'Clear description of what the child agent should do',
176
184
  },
185
+ // Role names are NOT enumerated here. They already appear in the
186
+ // system prompt's role table; repeating them in the schema grew the
187
+ // per-request cost with every configured role (see budget.test.ts).
177
188
  agent: {
178
189
  type: 'string',
179
190
  description:
180
191
  agentNames.length > 0
181
- ? `Read-only specialist role, one of: ${agentNames.join(', ')}. Mutually exclusive with \`category\`.`
192
+ ? 'Read-only specialist role, one of the names in the role table in your system prompt. Mutually exclusive with `category`.'
182
193
  : 'Read-only specialist role. Mutually exclusive with `category`.',
183
194
  },
184
195
  category: {
185
196
  type: 'string',
186
197
  description:
187
198
  categoryNames.length > 0
188
- ? `Implementation lane, one of: ${categoryNames.join(', ')}. Mutually exclusive with \`agent\`.`
199
+ ? 'Implementation lane, one of the names in the role table in your system prompt. Mutually exclusive with `agent`.'
189
200
  : 'Implementation lane. Mutually exclusive with `agent`.',
190
201
  },
191
202
  model: {
@@ -207,6 +218,10 @@ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
207
218
  type: 'number',
208
219
  description: 'Max tool-call rounds for the child (default 5, cap 16)',
209
220
  },
221
+ schema: {
222
+ type: 'object',
223
+ description: "Optional JSON Schema the child's final answer must satisfy.",
224
+ },
210
225
  },
211
226
  required: ['task'],
212
227
  },
@@ -233,6 +248,10 @@ function buildDelegateParallelTool(roles: RoleSpec[]): ToolDef {
233
248
  agent: {type: 'string', description: 'Read-only specialist role'},
234
249
  category: {type: 'string', description: 'Implementation lane'},
235
250
  model: {type: 'string', description: 'Explicit provider/model override'},
251
+ schema: {
252
+ type: 'object',
253
+ description: "Optional JSON Schema the child's answer must satisfy",
254
+ },
236
255
  },
237
256
  required: ['task'],
238
257
  },
@@ -447,17 +466,16 @@ export const CORE_TOOLS: ToolDef[] = [
447
466
  function: {
448
467
  name: 'verify',
449
468
  description:
450
- "Run the project's verification checks (typecheck and/or tests) and return structured pass/fail. Use after edits to confirm nothing broke.",
469
+ "Run the project's verification checks (typecheck and/or tests), returning structured pass/fail. Use after edits to confirm nothing broke.",
451
470
  parameters: {
452
471
  type: 'object',
453
472
  properties: {
454
473
  checks: {
455
474
  type: 'array',
456
475
  items: {type: 'string'},
457
- description:
458
- 'Which checks to run: "typescript" (tsc --noEmit) and/or "test" (test script). Default: auto-detect both.',
476
+ description: '"typescript" (tsc --noEmit) and/or "test". Default: auto-detect both.',
459
477
  },
460
- path: {type: 'string', description: 'Project directory (default: current directory)'},
478
+ path: {type: 'string', description: 'Project directory (default: cwd)'},
461
479
  },
462
480
  },
463
481
  },
@@ -467,13 +485,13 @@ export const CORE_TOOLS: ToolDef[] = [
467
485
  function: {
468
486
  name: 'recall_history',
469
487
  description:
470
- "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).",
488
+ "Earlier messages from this conversation, as raw transcript rows (not a summary). Returns only the prefix that context compaction folded away; it reports when nothing has been compacted yet. Use it to recover an exact path, error, or earlier decision — a delegated child, whose context starts empty, can pull the parent's context the same way.",
471
489
  parameters: {
472
490
  type: 'object',
473
491
  properties: {
474
492
  offset: {
475
493
  type: 'number',
476
- description: 'Message index to start from within the summarized prefix (default 0).',
494
+ description: 'Start index within the summarized prefix (default 0).',
477
495
  },
478
496
  limit: {
479
497
  type: 'number',
@@ -488,7 +506,7 @@ export const CORE_TOOLS: ToolDef[] = [
488
506
  function: {
489
507
  name: 'todo',
490
508
  description:
491
- 'Track a multi-step task. Call with the FULL list every time (it replaces the previous plan). Keep exactly one item in_progress, mark items completed as you finish them, and only stop when every item is completed or cancelled. Use this for any task needing more than ~2 steps.',
509
+ 'Track a multi-step task. Send the FULL list every call (it replaces the previous plan). Exactly one item in_progress; mark items completed as you finish. Use for any task needing more than ~2 steps.',
492
510
  parameters: {
493
511
  type: 'object',
494
512
  properties: {