@pal-code/core 0.0.20 → 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,341 @@
1
+ /**
2
+ * A hand-written JSON Schema subset, for validating a delegated child's answer.
3
+ *
4
+ * ## Why not a dependency
5
+ *
6
+ * `packages/core` ships `@ast-grep/napi` and `minimatch` and nothing else. A
7
+ * full validator is ~40 KB of ajv to check a return value the parent model just
8
+ * wrote itself; the supported subset below covers essentially every realistic
9
+ * delegation return. Hand-writing it keeps the lean stance and, more usefully,
10
+ * lets the *messages* be written for the reader that has to act on them — a
11
+ * parent agent deciding whether to retry.
12
+ *
13
+ * ## Supported keywords
14
+ *
15
+ * type object | array | string | number | integer | boolean | null
16
+ * (also accepts an array of those, e.g. ["string", "null"])
17
+ * properties recurse into named members
18
+ * required every named key must be present
19
+ * items recurse into every array element
20
+ * enum value must deep-equal one of the listed values
21
+ *
22
+ * Everything else is **ignored, not rejected**: `additionalProperties`,
23
+ * `oneOf`/`anyOf`/`allOf`, `$ref`, `pattern`, `format`, numeric ranges and
24
+ * `patternProperties` do not exist here. Ignoring is deliberate — a validator
25
+ * that silently ignored a keyword would be a trap, so the subset is stated in
26
+ * the README and in the failure messages themselves. Being permissive in the
27
+ * direction of "accept the answer" is the safe error: it can only let a
28
+ * slightly-too-loose answer through, never reject a correct one.
29
+ *
30
+ * Pure: no I/O, no imports, no globals. Every rule below is a table test in
31
+ * `json-schema.test.ts`.
32
+ */
33
+
34
+ /** Cap on reported problems — a wall of paths is not more actionable than ten. */
35
+ export const MAX_PROBLEMS = 8;
36
+
37
+ export type SchemaVerdict = {ok: true} | {ok: false; problems: string[]};
38
+
39
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
40
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
41
+ }
42
+
43
+ /** The JSON type name of a value, for messages. */
44
+ function jsonType(value: unknown): string {
45
+ if (value === null) return 'null';
46
+ if (Array.isArray(value)) return 'array';
47
+ if (typeof value === 'number') return 'number';
48
+ return typeof value;
49
+ }
50
+
51
+ function matchesType(value: unknown, expected: string): boolean {
52
+ switch (expected) {
53
+ case 'object':
54
+ return isPlainObject(value);
55
+ case 'array':
56
+ return Array.isArray(value);
57
+ case 'string':
58
+ return typeof value === 'string';
59
+ case 'number':
60
+ return typeof value === 'number' && Number.isFinite(value);
61
+ case 'integer':
62
+ return typeof value === 'number' && Number.isInteger(value);
63
+ case 'boolean':
64
+ return typeof value === 'boolean';
65
+ case 'null':
66
+ return value === null;
67
+ // An unknown type name is not a constraint we can enforce. Treat it as
68
+ // absent rather than failing every value against it.
69
+ default:
70
+ return true;
71
+ }
72
+ }
73
+
74
+ function deepEqual(a: unknown, b: unknown): boolean {
75
+ if (a === b) return true;
76
+ if (Array.isArray(a) && Array.isArray(b)) {
77
+ return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
78
+ }
79
+ if (isPlainObject(a) && isPlainObject(b)) {
80
+ const ak = Object.keys(a);
81
+ const bk = Object.keys(b);
82
+ return ak.length === bk.length && ak.every((k) => k in b && deepEqual(a[k], b[k]));
83
+ }
84
+ return false;
85
+ }
86
+
87
+ /** A short, unambiguous rendering of a literal for a failure message. */
88
+ function renderLiteral(value: unknown): string {
89
+ let text: string;
90
+ try {
91
+ text = JSON.stringify(value) ?? String(value);
92
+ } catch {
93
+ text = String(value);
94
+ }
95
+ return text.length > 60 ? `${text.slice(0, 57)}…` : text;
96
+ }
97
+
98
+ function renderPath(path: string): string {
99
+ return path === '' ? 'the top level' : path;
100
+ }
101
+
102
+ function joinPath(path: string, key: string): string {
103
+ return path === '' ? key : `${path}.${key}`;
104
+ }
105
+
106
+ function checkValue(value: unknown, schema: unknown, path: string, problems: string[]): void {
107
+ if (problems.length >= MAX_PROBLEMS) return;
108
+ // A non-object schema constrains nothing. `true`/`{}` are both "accept".
109
+ if (!isPlainObject(schema)) return;
110
+
111
+ const type = schema.type;
112
+ if (typeof type === 'string') {
113
+ if (!matchesType(value, type)) {
114
+ problems.push(`${renderPath(path)} expected ${type}, got ${jsonType(value)}`);
115
+ // A type mismatch makes every deeper assertion noise ("expected string,
116
+ // got number" repeated for each field). Stop descending here.
117
+ return;
118
+ }
119
+ } else if (Array.isArray(type) && type.length > 0) {
120
+ const allowed = type.map(String);
121
+ if (!allowed.some((t) => matchesType(value, t))) {
122
+ problems.push(`${renderPath(path)} expected ${allowed.join(' or ')}, got ${jsonType(value)}`);
123
+ return;
124
+ }
125
+ }
126
+
127
+ if (Array.isArray(schema.enum)) {
128
+ const options = schema.enum;
129
+ if (!options.some((option) => deepEqual(option, value))) {
130
+ problems.push(
131
+ `${renderPath(path)} expected one of ${options.map(renderLiteral).join(' | ')}, ` +
132
+ `got ${renderLiteral(value)}`,
133
+ );
134
+ }
135
+ }
136
+
137
+ // `required` and `properties` only mean anything for an object.
138
+ if (isPlainObject(value)) {
139
+ if (Array.isArray(schema.required)) {
140
+ for (const key of schema.required.map(String)) {
141
+ if (!Object.hasOwn(value, key)) {
142
+ problems.push(`${joinPath(path, key)} is required but missing`);
143
+ if (problems.length >= MAX_PROBLEMS) return;
144
+ }
145
+ }
146
+ }
147
+ if (isPlainObject(schema.properties)) {
148
+ for (const [key, subSchema] of Object.entries(schema.properties)) {
149
+ if (!Object.hasOwn(value, key)) continue; // absence is `required`'s job
150
+ checkValue(value[key], subSchema, joinPath(path, key), problems);
151
+ if (problems.length >= MAX_PROBLEMS) return;
152
+ }
153
+ }
154
+ }
155
+
156
+ if (Array.isArray(value) && schema.items !== undefined) {
157
+ for (let i = 0; i < value.length; i++) {
158
+ checkValue(value[i], schema.items, `${path}[${i}]`, problems);
159
+ if (problems.length >= MAX_PROBLEMS) return;
160
+ }
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Validate a parsed JSON value against the supported schema subset.
166
+ *
167
+ * Returns every problem it can find (up to {@link MAX_PROBLEMS}), each naming a
168
+ * path and an expectation — `findings[2].line expected number, got string` —
169
+ * because "invalid" alone gives the caller nothing to fix.
170
+ */
171
+ export function validateAgainstSchema(value: unknown, schema: unknown): SchemaVerdict {
172
+ const problems: string[] = [];
173
+ checkValue(value, schema, '', problems);
174
+ return problems.length === 0 ? {ok: true} : {ok: false, problems};
175
+ }
176
+
177
+ /** Render problems as the bullet list a parent agent (or a retried child) reads. */
178
+ export function formatProblems(problems: readonly string[]): string {
179
+ return problems.map((p) => `- ${p}`).join('\n');
180
+ }
181
+
182
+ /** A short excerpt of an unusable answer, for a failure message. */
183
+ export function excerpt(text: string, limit = 300): string {
184
+ const flat = text.replace(/\s+/g, ' ').trim();
185
+ return flat.length > limit ? `${flat.slice(0, limit - 1)}…` : flat;
186
+ }
187
+
188
+ // ── Extracting JSON from a child's prose ──
189
+
190
+ /**
191
+ * What we found in the child's answer.
192
+ *
193
+ * `absent` and `unparseable` are deliberately distinct: the first means the
194
+ * child never attempted JSON (tell it to), the second means it tried and the
195
+ * text is malformed (show it what it wrote). Collapsing them wastes the retry.
196
+ */
197
+ export type JsonExtraction =
198
+ | {status: 'ok'; value: unknown}
199
+ | {status: 'absent'}
200
+ | {status: 'unparseable'; text: string};
201
+
202
+ function tryParse(text: string): {ok: true; value: unknown} | {ok: false} {
203
+ const trimmed = text.trim();
204
+ if (!trimmed) return {ok: false};
205
+ try {
206
+ return {ok: true, value: JSON.parse(trimmed)};
207
+ } catch {
208
+ return {ok: false};
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Every balanced `{…}` / `[…]` span in `text`, in order of appearance.
214
+ *
215
+ * Brace counting respects strings and escapes so a `}` inside a string or an
216
+ * escaped quote cannot truncate a span. A span that never closes is dropped —
217
+ * it is truncated output, and `extractJson` reports that case as unparseable.
218
+ */
219
+ function balancedSpans(text: string): string[] {
220
+ const spans: string[] = [];
221
+ let depth = 0;
222
+ let start = -1;
223
+ let inString = false;
224
+ let escaped = false;
225
+ for (let i = 0; i < text.length; i++) {
226
+ const ch = text[i];
227
+ if (inString) {
228
+ if (escaped) escaped = false;
229
+ else if (ch === '\\') escaped = true;
230
+ else if (ch === '"') inString = false;
231
+ continue;
232
+ }
233
+ if (ch === '"' && depth > 0) {
234
+ inString = true;
235
+ continue;
236
+ }
237
+ if (ch === '{' || ch === '[') {
238
+ if (depth === 0) start = i;
239
+ depth++;
240
+ continue;
241
+ }
242
+ if (ch === '}' || ch === ']') {
243
+ if (depth === 0) continue; // stray closer
244
+ depth--;
245
+ if (depth === 0 && start >= 0) {
246
+ spans.push(text.slice(start, i + 1));
247
+ start = -1;
248
+ }
249
+ }
250
+ }
251
+ return spans;
252
+ }
253
+
254
+ /**
255
+ * Pull a JSON value out of a child's answer.
256
+ *
257
+ * Children wrap answers in ``` fences and add a prose sign-off, so plain
258
+ * `JSON.parse` is the wrong tool. Tried in order: fenced blocks (a ```json
259
+ * fence first — the likeliest home), the whole answer, then balanced spans
260
+ * **last-first**, because when a child puts JSON mid-answer and prose after it,
261
+ * the JSON is what we want and prose is not parseable anyway.
262
+ */
263
+ export function extractJson(text: string): JsonExtraction {
264
+ const raw = typeof text === 'string' ? text : '';
265
+ const trimmed = raw.trim();
266
+ if (!trimmed) return {status: 'absent'};
267
+
268
+ // 1. Fenced blocks. A ```json fence wins over an untagged one.
269
+ const fences = [...trimmed.matchAll(/```([A-Za-z0-9_+-]*)[ \t]*\r?\n?([\s\S]*?)```/g)].map(
270
+ (m) => ({
271
+ lang: (m[1] ?? '').toLowerCase(),
272
+ body: m[2] ?? '',
273
+ }),
274
+ );
275
+ const ordered = [
276
+ ...fences.filter((f) => f.lang.startsWith('json')),
277
+ ...fences.filter((f) => !f.lang.startsWith('json')),
278
+ ];
279
+ for (const fence of ordered) {
280
+ const parsed = tryParse(fence.body);
281
+ if (parsed.ok) return {status: 'ok', value: parsed.value};
282
+ }
283
+
284
+ // 2. The answer is nothing but JSON.
285
+ const whole = tryParse(trimmed);
286
+ if (whole.ok) return {status: 'ok', value: whole.value};
287
+
288
+ // 3. Embedded spans — last first, then first forward.
289
+ const spans = balancedSpans(trimmed);
290
+ for (let i = spans.length - 1; i >= 0; i--) {
291
+ const parsed = tryParse(spans[i]);
292
+ if (parsed.ok) return {status: 'ok', value: parsed.value};
293
+ }
294
+ for (const span of spans) {
295
+ const parsed = tryParse(span);
296
+ if (parsed.ok) return {status: 'ok', value: parsed.value};
297
+ }
298
+
299
+ // Something was attempted (a fence, a bracket, a brace) but nothing parsed.
300
+ if (fences.length > 0 || spans.length > 0 || /[[{]/.test(trimmed)) {
301
+ const longest = spans.reduce((best, s) => (s.length > best.length ? s : best), '');
302
+ return {status: 'unparseable', text: longest || trimmed};
303
+ }
304
+ return {status: 'absent'};
305
+ }
306
+
307
+ // ── Instructions ──
308
+
309
+ /** The schema text appended to the child's task, so it knows what to answer. */
310
+ export function schemaInstruction(schema: unknown): string {
311
+ let text: string;
312
+ try {
313
+ text = JSON.stringify(schema) ?? '{}';
314
+ } catch {
315
+ text = '{}';
316
+ }
317
+ return (
318
+ `\n\nReturn ONLY a JSON value that satisfies this JSON Schema — no prose, ` +
319
+ `no markdown fences, nothing after it:\n${text}`
320
+ );
321
+ }
322
+
323
+ /**
324
+ * The corrective message sent to a child whose answer failed validation.
325
+ *
326
+ * Names exactly what was wrong, because a generic "please return JSON" makes
327
+ * the child guess and usually repeat the same mistake.
328
+ */
329
+ export function correctionPrompt(schema: unknown, failure: string): string {
330
+ let text: string;
331
+ try {
332
+ text = JSON.stringify(schema) ?? '{}';
333
+ } catch {
334
+ text = '{}';
335
+ }
336
+ return (
337
+ `Your previous answer could not be used as a structured return: ${failure}\n\n` +
338
+ `Reply again with ONLY a JSON value satisfying this schema — no prose, no ` +
339
+ `markdown fences, nothing after it:\n${text}`
340
+ );
341
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Lazy tool schemas — advertise a stub until the model actually uses the tool.
3
+ *
4
+ * ## Why
5
+ *
6
+ * Every tool schema is re-sent on every round, so the fixed prompt cost is paid
7
+ * per request for tools a session may never touch. Measured on pal's 17 core
8
+ * tools: ~1,881 tok, of which the orchestration/continuation tools (`delegate`,
9
+ * `delegate_parallel`, `recall_history`, `todo`, `repo_map`, `verify`) are
10
+ * ~1,089 — over half — yet a one-line edit task touches none of them.
11
+ *
12
+ * ## How a tool gets expanded
13
+ *
14
+ * There is deliberately no "load this tool" tool: adding one costs ~100 tok
15
+ * unconditionally and would eat most of the saving. Instead a deferred tool
16
+ * expands the first time the model *calls* it. That is safe because:
17
+ *
18
+ * - The stub still names the tool, so the model knows it exists and may call it.
19
+ * - Every deferrable tool's *required* arguments are guessable from its stub
20
+ * (`delegate` needs `task`, `verify` needs nothing, `todo` needs `todos`), so
21
+ * the first call is usually correct anyway.
22
+ * - Argument validation and dispatch never consult this module, so a call is
23
+ * validated against the real schema regardless of what was advertised.
24
+ *
25
+ * The cost of the trade is at worst one round where the model does not know an
26
+ * *optional* argument — after which the full schema is being sent.
27
+ *
28
+ * ## Why this module is dependency-free
29
+ *
30
+ * It imports nothing (the `ToolDef` import is type-only and erased). That keeps
31
+ * it loadable before the registry exists and makes every rule below testable
32
+ * without a provider, a registry, or a terminal.
33
+ *
34
+ * ## Safety properties (each is a test)
35
+ *
36
+ * 1. **Default ON, with an exact-enough opt-out.** Unset or empty → enabled.
37
+ * `PAL_LAZY_TOOLS=0|false|off|no|disabled` → disabled, and the wire list is
38
+ * byte-for-byte what it was before this module existed. This was flipped from
39
+ * default-OFF only after live measurement (see the header of `lazy.ts`'s test
40
+ * file and `.memory/runs/lazy-schema-comparison-2026-11-21.md`).
41
+ * 2. **Kill switch.** The env var is read per call, not captured at import, so
42
+ * setting it to `0` takes effect without a restart or a code change.
43
+ * 3. **Additive only.** A tool is either passed through untouched or replaced by
44
+ * a stub. Nothing is dropped and no argument schema of an eager tool is
45
+ * rewritten. A name that is not deferrable passes through, so an unexpected
46
+ * input degrades to today's behaviour.
47
+ * 4. **Unknown names expand nothing** — only deferrable tools can be expanded.
48
+ * 5. **No truth depends on it.** `executeTool` never reads this state, so
49
+ * validating and dispatching a call always uses the real schema.
50
+ */
51
+
52
+ import type {ToolDef} from './definitions.js';
53
+
54
+ /**
55
+ * Tools whose full schema is worth withholding from the first round.
56
+ *
57
+ * Every one is either only needed on longer/multi-step work, or ships with
58
+ * system-prompt guidance saying when to reach for it. Nothing here is required
59
+ * to read, write, edit or run a command — those stay eager, because a missing
60
+ * schema there would cost a wasted round on the most common task in the product.
61
+ */
62
+ export const DEFAULT_DEFERRABLE: readonly string[] = [
63
+ 'delegate',
64
+ 'delegate_parallel',
65
+ 'recall_history',
66
+ 'todo',
67
+ 'repo_map',
68
+ 'verify',
69
+ ];
70
+
71
+ /** Env var that turns the whole feature on. */
72
+ export const LAZY_ENV = 'PAL_LAZY_TOOLS';
73
+
74
+ /** Names currently expanded from a stub, process-wide. */
75
+ const expanded = new Set<string>();
76
+
77
+ /**
78
+ * Values that explicitly turn the feature OFF, overriding the default.
79
+ *
80
+ * Deliberately an opt-OUT list rather than an opt-in one: after the flip,
81
+ * `PAL_LAZY_TOOLS` unset means ON, so the kill switch has to be something a
82
+ * user can reach for deliberately at a shell. Anything not in this set —
83
+ * including a typo like `ture` — leaves the default (ON) in place, which is the
84
+ * safe direction: the feature is additive and a wrong value does not corrupt
85
+ * anything, whereas a wrong value silently disabling the saving would be
86
+ * confusing to debug.
87
+ */
88
+ const FALSY = new Set(['0', 'false', 'off', 'no', 'disabled']);
89
+
90
+ /**
91
+ * Whether lazy schemas are enabled right now. **Default: ON.**
92
+ *
93
+ * Measured before the flip (`.memory/runs/lazy-schema-comparison-2026-11-21.md`):
94
+ * 767 tok/round saved against 749 predicted from the static schema count (98%
95
+ * agreement), no regressions in three repeats, and lower run-to-run variance on
96
+ * the enabled arm.
97
+ *
98
+ * Read per call, not captured at import, so `PAL_LAZY_TOOLS=0` restores the
99
+ * fully-eager tool list without a code change or a module reload.
100
+ */
101
+ export function isLazyToolsEnabled(): boolean {
102
+ const raw = process.env[LAZY_ENV];
103
+ if (typeof raw !== 'string') return true;
104
+ const value = raw.trim().toLowerCase();
105
+ // An empty string is "unset, but exported" — same as absent.
106
+ if (value === '') return true;
107
+ return !FALSY.has(value);
108
+ }
109
+
110
+ /** The deferrable set, or a `PAL_LAZY_TOOLS_DEFER` override when supplied. */
111
+ export function deferrableTools(): readonly string[] {
112
+ const override = process.env[`${LAZY_ENV}_DEFER`];
113
+ if (typeof override === 'string' && override.trim() !== '') {
114
+ const names = override
115
+ .split(',')
116
+ .map((n) => n.trim())
117
+ .filter((n) => n !== '');
118
+ // An override naming nothing usable falls back to the default set rather
119
+ // than quietly turning the feature into a no-op.
120
+ if (names.length > 0) return names;
121
+ }
122
+ return DEFAULT_DEFERRABLE;
123
+ }
124
+
125
+ /** Whether a tool's schema is currently withheld. */
126
+ export function isDeferred(name: string): boolean {
127
+ if (!isLazyToolsEnabled()) return false;
128
+ if (!deferrableTools().includes(name)) return false;
129
+ return !expanded.has(name);
130
+ }
131
+
132
+ /**
133
+ * Expand tools so their real schemas go out from the next round on.
134
+ *
135
+ * @returns the names actually expanded — already-expanded and non-deferrable
136
+ * names are omitted, so a caller emits an event only when something changed.
137
+ */
138
+ export function expandTools(names: readonly string[]): string[] {
139
+ const allowed = new Set(deferrableTools());
140
+ const changed: string[] = [];
141
+ for (const raw of names) {
142
+ const name = String(raw).trim();
143
+ if (!allowed.has(name)) continue;
144
+ if (expanded.has(name)) continue;
145
+ expanded.add(name);
146
+ changed.push(name);
147
+ }
148
+ return changed;
149
+ }
150
+
151
+ /** Force everything eager again — used by /reload and by tests. */
152
+ export function resetExpanded(): void {
153
+ expanded.clear();
154
+ }
155
+
156
+ /** The expanded set, for tests and a `/tools` readout. */
157
+ export function expandedTools(): string[] {
158
+ return [...expanded];
159
+ }
160
+
161
+ /**
162
+ * The stub that replaces a withheld tool's schema.
163
+ *
164
+ * It must still tell the model the tool EXISTS and when to use it — otherwise
165
+ * the tool is effectively removed and any system-prompt advice about it becomes
166
+ * a dead reference. The summary is the tool's own first sentence, so the stub
167
+ * cannot drift from what the tool actually does.
168
+ */
169
+ export function stubFor(tool: ToolDef): ToolDef {
170
+ const summary = tool.function.description.split(/(?<=\.)\s/)[0] ?? tool.function.description;
171
+ return {
172
+ type: 'function',
173
+ function: {
174
+ name: tool.function.name,
175
+ description: `${summary} (Full argument schema loads after your first call.)`,
176
+ parameters: {type: 'object', properties: {}},
177
+ },
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Apply lazy behaviour to a tool list.
183
+ *
184
+ * **Additive only:** each tool is either passed through untouched or replaced by
185
+ * a stub. Nothing is dropped. When the feature is off this is the identity
186
+ * function — which is what makes the default path exactly today's behaviour.
187
+ */
188
+ export function projectTools(tools: readonly ToolDef[]): ToolDef[] {
189
+ if (!isLazyToolsEnabled()) return [...tools];
190
+ return tools.map((tool) => (isDeferred(tool.function.name) ? stubFor(tool) : tool));
191
+ }