@pal-code/core 0.0.21 → 0.0.23
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 +1 -1
- package/src/agent/run.ts +17 -25
- package/src/agent/scope.ts +12 -1
- package/src/agent/turn.ts +17 -4
- package/src/app-config.ts +48 -6
- package/src/compaction.ts +19 -0
- package/src/config.ts +2 -1
- package/src/diagnostics-checks.ts +19 -0
- package/src/index.ts +29 -3
- package/src/lsp/client.ts +361 -0
- package/src/lsp/diagnostics-map.ts +138 -0
- package/src/lsp/fixtures/fake-lsp-server.ts +110 -0
- package/src/lsp/framing.ts +93 -0
- package/src/lsp/servers.ts +125 -0
- package/src/provider/chat.ts +13 -0
- package/src/provider/effort.ts +72 -0
- package/src/provider/openrouter.ts +37 -6
- package/src/provider/responses.ts +13 -0
- package/src/provider/types.ts +12 -0
- package/src/tools/definitions.ts +75 -39
- package/src/tools/edit-match.ts +201 -0
- package/src/tools/executor.ts +517 -92
- package/src/tools/json-schema.ts +341 -0
- package/src/tools/lazy.ts +191 -0
|
@@ -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
|
+
}
|
package/src/provider/chat.ts
CHANGED
|
@@ -35,6 +35,11 @@ export interface ChatStreamOptions {
|
|
|
35
35
|
tools?: ToolDef[];
|
|
36
36
|
headers: Record<string, string>;
|
|
37
37
|
signal?: AbortSignal;
|
|
38
|
+
/**
|
|
39
|
+
* Extra body fields (e.g. `reasoning_effort`), merged in *after* the required
|
|
40
|
+
* fields so they cannot clobber `model`/`messages`/`stream`.
|
|
41
|
+
*/
|
|
42
|
+
params?: Record<string, unknown>;
|
|
38
43
|
}
|
|
39
44
|
|
|
40
45
|
/**
|
|
@@ -96,6 +101,14 @@ export async function* streamChat(opts: ChatStreamOptions): AsyncGenerator<Strea
|
|
|
96
101
|
body.tools = opts.tools;
|
|
97
102
|
}
|
|
98
103
|
|
|
104
|
+
// Merge protocol-level knobs last: required fields win over caller params.
|
|
105
|
+
if (opts.params) {
|
|
106
|
+
for (const [key, value] of Object.entries(opts.params)) {
|
|
107
|
+
if (key in body) continue;
|
|
108
|
+
body[key] = value;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
99
112
|
log('request', {
|
|
100
113
|
provider: opts.id,
|
|
101
114
|
baseUrl: opts.baseUrl,
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reasoning-effort → wire-parameter translation.
|
|
3
|
+
*
|
|
4
|
+
* Effort is an *intent* ("think a little / a normal amount / hard"), not a wire
|
|
5
|
+
* field. Each protocol spells it differently, so the mapping lives here and the
|
|
6
|
+
* adapters call it with the protocol they are about to speak:
|
|
7
|
+
*
|
|
8
|
+
* - **chat** (OpenAI-compatible): `reasoning_effort` — the field DeepSeek,
|
|
9
|
+
* OpenAI's o-series/GPT-5 and every OpenAI-compatible gateway read.
|
|
10
|
+
* - **responses** (OpenAI Responses): `reasoning: {effort, summary}`. The
|
|
11
|
+
* `summary: 'auto'` is what makes reasoning surface as `thinking` deltas;
|
|
12
|
+
* without it the Responses wire emits no reasoning at all.
|
|
13
|
+
*
|
|
14
|
+
* Anthropic's `thinking: {budget_tokens}` and Gemini's
|
|
15
|
+
* `generationConfig.thinkingConfig` are *native* API shapes. pal speaks neither
|
|
16
|
+
* wire (see `types.ts` — protocols are `chat` and `responses` only), so sending
|
|
17
|
+
* them down a chat-completions body was a no-op at best and a 400 at worst.
|
|
18
|
+
* Gateways that front those models normalise `reasoning_effort`/`reasoning`
|
|
19
|
+
* themselves, so the protocol shape is the right lever.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export type Effort = 'low' | 'medium' | 'high';
|
|
23
|
+
|
|
24
|
+
/** The wire protocol the request will use. */
|
|
25
|
+
export type WireProtocol = 'chat' | 'responses';
|
|
26
|
+
|
|
27
|
+
/** Strip a `provider/` prefix — model gates must test the bare id. */
|
|
28
|
+
function bareModel(model: string): string {
|
|
29
|
+
return model.includes('/') ? model.slice(model.lastIndexOf('/') + 1) : model;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* True for model families that accept a reasoning-effort knob.
|
|
34
|
+
*
|
|
35
|
+
* The gate is deliberately conservative: sending `reasoning_effort` to a model
|
|
36
|
+
* that does not reason is a 400 on strict gateways, so unknown models get no
|
|
37
|
+
* parameters at all. Extend the pattern rather than dropping the gate.
|
|
38
|
+
*/
|
|
39
|
+
export function isReasoningModel(model: string): boolean {
|
|
40
|
+
const bare = bareModel(model).toLowerCase();
|
|
41
|
+
// OpenAI o-series (o1, o3, o4-mini, …) and GPT-5 onward.
|
|
42
|
+
if (/^o[1-9](?:$|[-.])/.test(bare)) return true;
|
|
43
|
+
if (/^gpt-(?:[5-9]|\d{2,})/.test(bare)) return true;
|
|
44
|
+
// DeepSeek reasoner / gateway aliases that name reasoning explicitly.
|
|
45
|
+
if (bare.includes('reasoner')) return true;
|
|
46
|
+
if (bare.includes('-reasoning')) return true;
|
|
47
|
+
// Claude and Gemini are reached through a normalising gateway.
|
|
48
|
+
if (/^(?:claude|gemini|fable)/.test(bare)) return true;
|
|
49
|
+
if (bare.includes('anthropic') || bare.includes('google/')) return true;
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Body parameters for a protocol, or `{}` when the model takes no effort knob.
|
|
55
|
+
*
|
|
56
|
+
* Callers merge the result into the request body. An empty object is the
|
|
57
|
+
* correct answer for a non-reasoning model — never a reason to send `low`.
|
|
58
|
+
*/
|
|
59
|
+
export function getEffortParams(
|
|
60
|
+
model: string,
|
|
61
|
+
effort: Effort,
|
|
62
|
+
protocol: WireProtocol = 'chat',
|
|
63
|
+
): Record<string, unknown> {
|
|
64
|
+
if (!isReasoningModel(model)) return {};
|
|
65
|
+
|
|
66
|
+
if (protocol === 'responses') {
|
|
67
|
+
// `summary: 'auto'` is required for reasoning to arrive as a summary at all.
|
|
68
|
+
return {reasoning: {effort, summary: 'auto'}};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return {reasoning_effort: effort};
|
|
72
|
+
}
|
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import type {Provider, ProviderConfig, ProviderModel, StreamEvent, ModelRoute} from './types.js';
|
|
12
|
+
import type {Effort} from './effort.js';
|
|
13
|
+
import {getEffortParams} from './effort.js';
|
|
12
14
|
import {randomBytes} from 'crypto';
|
|
13
15
|
import {getProvider, resolveRoute} from './registry.js';
|
|
14
16
|
import {streamChat, type ToolDef} from './chat.js';
|
|
@@ -33,23 +35,49 @@ function randomBase62(len: number): string {
|
|
|
33
35
|
return out;
|
|
34
36
|
}
|
|
35
37
|
|
|
36
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Header token for N random lowercase hex chars, optionally prefixed.
|
|
37
40
|
* The prefix may not contain `__`, otherwise a composite such as
|
|
38
41
|
* `ses___random:9__ffe___random:14__` parses as one greedy token instead of two.
|
|
39
42
|
*/
|
|
40
43
|
const RANDOM_TOKEN = /__random(?::((?:(?!__)[^:])+))?:(\d+)__/g;
|
|
41
44
|
|
|
42
|
-
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
45
|
+
/**
|
|
46
|
+
* The process-wide `__sesid__` value.
|
|
47
|
+
*
|
|
48
|
+
* Deliberately NOT regenerated per request. Gateways such as OpenCode use a
|
|
49
|
+
* session header to route a conversation to the same prompt-cache shard, so a
|
|
50
|
+
* fresh id on every request sends each turn to a cold shard and destroys the
|
|
51
|
+
* cache hit rate — which is exactly what "only 40-70% cached" looked like.
|
|
52
|
+
* One pal process is one session, so one id for the process is right.
|
|
53
|
+
*/
|
|
54
|
+
let sessionId: string | null = null;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Start a new session id — call this when the user starts a new conversation
|
|
58
|
+
* (`/new`, `/clear`) so the next turn is cached under a fresh shard.
|
|
59
|
+
*/
|
|
60
|
+
export function resetProviderSession(): void {
|
|
61
|
+
sessionId = null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function newSessionId(): string {
|
|
65
|
+
return `ses_${randomBytes(6).toString('hex')}${randomBase62(14)}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Expand header-value tokens.
|
|
70
|
+
* `__sesid__` → a *stable* `ses_` + 12 lowercase hex + 14 base62, one per process
|
|
71
|
+
* `__random:32__` → 32-char random hex, fresh on every call
|
|
72
|
+
* `__random:ses_:32__` → `ses_` + 32-char random hex, fresh on every call
|
|
46
73
|
* Tokens also expand when embedded in surrounding literal text, so composite
|
|
47
74
|
* values can interleave fixed and random parts in any order.
|
|
48
75
|
* Anything without a token is returned unchanged.
|
|
49
76
|
*/
|
|
50
77
|
export function expandRandomValue(val: string): string {
|
|
51
78
|
if (val === '__sesid__') {
|
|
52
|
-
|
|
79
|
+
sessionId ??= newSessionId();
|
|
80
|
+
return sessionId;
|
|
53
81
|
}
|
|
54
82
|
return val.replace(RANDOM_TOKEN, (_match, prefix: string | undefined, len: string) => {
|
|
55
83
|
const width = Number(len);
|
|
@@ -173,6 +201,7 @@ class OpenRouterProvider implements Provider {
|
|
|
173
201
|
messages: Array<Record<string, unknown>>;
|
|
174
202
|
tools?: ToolDef[];
|
|
175
203
|
signal?: AbortSignal;
|
|
204
|
+
effort?: Effort;
|
|
176
205
|
}): AsyncGenerator<StreamEvent> {
|
|
177
206
|
const model = this.modelPrefix ? opts.model.replace(this.modelPrefix, '') : opts.model;
|
|
178
207
|
const route = resolveRoute(
|
|
@@ -191,6 +220,7 @@ class OpenRouterProvider implements Provider {
|
|
|
191
220
|
headers,
|
|
192
221
|
signal: opts.signal,
|
|
193
222
|
path: route.path,
|
|
223
|
+
params: opts.effort ? getEffortParams(model, opts.effort, 'responses') : undefined,
|
|
194
224
|
});
|
|
195
225
|
return;
|
|
196
226
|
}
|
|
@@ -203,6 +233,7 @@ class OpenRouterProvider implements Provider {
|
|
|
203
233
|
tools: opts.tools,
|
|
204
234
|
headers,
|
|
205
235
|
signal: opts.signal,
|
|
236
|
+
params: opts.effort ? getEffortParams(model, opts.effort, 'chat') : undefined,
|
|
206
237
|
});
|
|
207
238
|
}
|
|
208
239
|
}
|
|
@@ -20,6 +20,11 @@ export interface ResponsesStreamOptions {
|
|
|
20
20
|
headers: Record<string, string>;
|
|
21
21
|
signal?: AbortSignal;
|
|
22
22
|
path?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Extra body fields (e.g. `reasoning: {effort}`), merged in *after* the
|
|
25
|
+
* required fields so they cannot clobber `model`/`input`/`stream`.
|
|
26
|
+
*/
|
|
27
|
+
params?: Record<string, unknown>;
|
|
23
28
|
}
|
|
24
29
|
|
|
25
30
|
/**
|
|
@@ -93,6 +98,14 @@ export async function* streamResponses(opts: ResponsesStreamOptions): AsyncGener
|
|
|
93
98
|
const tools = toResponsesTools(opts.tools);
|
|
94
99
|
if (tools) body.tools = tools;
|
|
95
100
|
|
|
101
|
+
// Merge protocol-level knobs last: required fields win over caller params.
|
|
102
|
+
if (opts.params) {
|
|
103
|
+
for (const [key, value] of Object.entries(opts.params)) {
|
|
104
|
+
if (key in body) continue;
|
|
105
|
+
body[key] = value;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
96
109
|
const url = resolveUrl(opts.baseUrl, opts.path);
|
|
97
110
|
|
|
98
111
|
log('request', {
|
package/src/provider/types.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* The CLI/engine talks to Provider, not directly to HTTP.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import type {Effort} from './effort.js';
|
|
9
|
+
|
|
8
10
|
/**
|
|
9
11
|
* A per-model wire-protocol route. `pattern` is a regex tested against the
|
|
10
12
|
* bare model id; the first matching route wins (declaration order).
|
|
@@ -83,5 +85,15 @@ export interface Provider {
|
|
|
83
85
|
}>;
|
|
84
86
|
/** Abort signal — cancels the in-flight HTTP request (user interrupt). */
|
|
85
87
|
signal?: AbortSignal;
|
|
88
|
+
/**
|
|
89
|
+
* How hard the model should think. An *intent*, not a wire field: the
|
|
90
|
+
* provider translates it into the shape its protocol expects
|
|
91
|
+
* (`reasoning_effort` for chat, `reasoning: {effort}` for responses).
|
|
92
|
+
*
|
|
93
|
+
* Declared on the interface deliberately. It used to be spread into this
|
|
94
|
+
* call behind an `as never` cast with no matching field here, so every
|
|
95
|
+
* adapter silently dropped it and `/effort` did nothing.
|
|
96
|
+
*/
|
|
97
|
+
effort?: Effort;
|
|
86
98
|
}): AsyncGenerator<StreamEvent>;
|
|
87
99
|
}
|
package/src/tools/definitions.ts
CHANGED
|
@@ -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,45 @@ 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
|
+
* **On by default.** `PAL_LAZY_TOOLS` unset or empty → stubs on the wire;
|
|
115
|
+
* `PAL_LAZY_TOOLS=0|false|off|no|disabled` restores the fully-eager list
|
|
116
|
+
* byte-for-byte. The gate is `isLazyToolsEnabled()` in `lazy.ts` — read it there
|
|
117
|
+
* rather than trusting a comment (this one said the opposite of the code for a
|
|
118
|
+
* while after the default was flipped).
|
|
119
|
+
*/
|
|
120
|
+
export function getWireTools(extra: ToolDef[] = []): ToolDef[] {
|
|
121
|
+
return projectTools(getAllTools(extra));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Token cost of the tool schemas actually sent, for the context gauge.
|
|
126
|
+
*
|
|
127
|
+
* Uses JSON serialisation because tool schemas are pure structure — names,
|
|
128
|
+
* descriptions, property lists — so the serialized size is the honest measure.
|
|
129
|
+
* ~4 chars/token, matching `estimateTokens` in `compaction.ts`.
|
|
130
|
+
*
|
|
131
|
+
* Reads {@link getWireTools} (not `getAllTools`) so the figure matches the
|
|
132
|
+
* request byte-for-byte: with lazy schemas on, the stubs really are cheaper.
|
|
133
|
+
*/
|
|
134
|
+
export function estimateToolSchemaTokens(extra: ToolDef[] = []): number {
|
|
135
|
+
return Math.ceil(JSON.stringify(getWireTools(extra)).length / 4);
|
|
136
|
+
}
|
|
137
|
+
|
|
103
138
|
const ROLE_DERIVED_TOOLS: Record<string, (roles: RoleSpec[]) => ToolDef> = {
|
|
104
139
|
delegate: buildDelegateTool,
|
|
105
140
|
delegate_parallel: buildDelegateParallelTool,
|
|
106
141
|
};
|
|
107
142
|
|
|
108
|
-
function formatRoles(roles: RoleSpec[]): string {
|
|
109
|
-
return roles.map((r) => `${r.name} — ${r.description.replace(/\.$/, '')}`).join('; ');
|
|
110
|
-
}
|
|
111
|
-
|
|
112
143
|
/**
|
|
113
144
|
* The `delegate` description, derived from the live role registry.
|
|
114
145
|
*
|
|
@@ -116,46 +147,41 @@ function formatRoles(roles: RoleSpec[]): string {
|
|
|
116
147
|
* provider without touching the global registry; the default reads `listRoleSpecs()`
|
|
117
148
|
* — the same source `buildRolesPrompt()` uses.
|
|
118
149
|
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
150
|
+
* Role names are deliberately NOT inlined here. They are already listed in the
|
|
151
|
+
* system prompt's role block (`buildRolesPrompt`), so inlining them printed the
|
|
152
|
+
* same catalogue twice — and this copy is the expensive one: it sits in the tool
|
|
153
|
+
* schema, which is re-sent with every request and grows with every role the user
|
|
154
|
+
* configures. Referencing the block instead keeps the schema flat.
|
|
155
|
+
*
|
|
156
|
+
* With no roles configured the wording stays generic, so it can never name a
|
|
157
|
+
* role that does not exist.
|
|
122
158
|
*
|
|
123
159
|
* The trailing sentences are brief-writing guidance (fix #3): the child starts
|
|
124
160
|
* fresh by design, so facts the parent knows must go into `task` — and
|
|
125
161
|
* `recall_history` is the opt-in hatch for earlier main-session context.
|
|
126
162
|
*/
|
|
127
163
|
export function buildDelegateDescription(roles: RoleSpec[] = listRoleSpecs()): string {
|
|
128
|
-
const
|
|
129
|
-
const categories = roles.filter((r) => r.kind === 'category');
|
|
164
|
+
const hasRoles = roles.length > 0;
|
|
130
165
|
|
|
131
|
-
const routing
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
}
|
|
166
|
+
const routing = hasRoles
|
|
167
|
+
? '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.'
|
|
168
|
+
: 'Omit `agent`/`category` — ad-hoc delegation with default read-only tools.';
|
|
143
169
|
|
|
144
170
|
return [
|
|
145
|
-
'Delegate a sub-task to a child agent with its own context.',
|
|
146
|
-
|
|
147
|
-
'The child
|
|
148
|
-
|
|
171
|
+
'Delegate a sub-task to a child agent with its own fresh context.',
|
|
172
|
+
routing,
|
|
173
|
+
'The child sees none of this conversation: put facts INTO `task` (paths, constraints, disproved hypotheses) or it re-discovers them.',
|
|
174
|
+
'It can call `recall_history` to pull earlier messages.',
|
|
149
175
|
].join(' ');
|
|
150
176
|
}
|
|
151
177
|
|
|
152
178
|
export function buildDelegateParallelDescription(roles: RoleSpec[] = listRoleSpecs()): string {
|
|
153
|
-
|
|
179
|
+
// Same reasoning as `buildDelegateDescription`: the role names live in the
|
|
180
|
+
// system prompt's role table, not in this schema.
|
|
154
181
|
return (
|
|
155
|
-
'Run several delegates concurrently
|
|
156
|
-
|
|
157
|
-
' Use when sub-tasks are independent
|
|
158
|
-
' Respects the configured max_parallel limit and returns results in input order.'
|
|
182
|
+
'Run several delegates concurrently. Each entry takes the same `agent`/`category` as `delegate`' +
|
|
183
|
+
(roles.length > 0 ? ' (names in your system prompt’s role table)' : '') +
|
|
184
|
+
'. Use when sub-tasks are independent. Bounded by max_parallel; results return in input order.'
|
|
159
185
|
);
|
|
160
186
|
}
|
|
161
187
|
|
|
@@ -174,18 +200,21 @@ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
|
|
|
174
200
|
type: 'string',
|
|
175
201
|
description: 'Clear description of what the child agent should do',
|
|
176
202
|
},
|
|
203
|
+
// Role names are NOT enumerated here. They already appear in the
|
|
204
|
+
// system prompt's role table; repeating them in the schema grew the
|
|
205
|
+
// per-request cost with every configured role (see budget.test.ts).
|
|
177
206
|
agent: {
|
|
178
207
|
type: 'string',
|
|
179
208
|
description:
|
|
180
209
|
agentNames.length > 0
|
|
181
|
-
?
|
|
210
|
+
? 'Read-only specialist role, one of the names in the role table in your system prompt. Mutually exclusive with `category`.'
|
|
182
211
|
: 'Read-only specialist role. Mutually exclusive with `category`.',
|
|
183
212
|
},
|
|
184
213
|
category: {
|
|
185
214
|
type: 'string',
|
|
186
215
|
description:
|
|
187
216
|
categoryNames.length > 0
|
|
188
|
-
?
|
|
217
|
+
? 'Implementation lane, one of the names in the role table in your system prompt. Mutually exclusive with `agent`.'
|
|
189
218
|
: 'Implementation lane. Mutually exclusive with `agent`.',
|
|
190
219
|
},
|
|
191
220
|
model: {
|
|
@@ -207,6 +236,10 @@ function buildDelegateTool(roles: RoleSpec[]): ToolDef {
|
|
|
207
236
|
type: 'number',
|
|
208
237
|
description: 'Max tool-call rounds for the child (default 5, cap 16)',
|
|
209
238
|
},
|
|
239
|
+
schema: {
|
|
240
|
+
type: 'object',
|
|
241
|
+
description: "Optional JSON Schema the child's final answer must satisfy.",
|
|
242
|
+
},
|
|
210
243
|
},
|
|
211
244
|
required: ['task'],
|
|
212
245
|
},
|
|
@@ -233,6 +266,10 @@ function buildDelegateParallelTool(roles: RoleSpec[]): ToolDef {
|
|
|
233
266
|
agent: {type: 'string', description: 'Read-only specialist role'},
|
|
234
267
|
category: {type: 'string', description: 'Implementation lane'},
|
|
235
268
|
model: {type: 'string', description: 'Explicit provider/model override'},
|
|
269
|
+
schema: {
|
|
270
|
+
type: 'object',
|
|
271
|
+
description: "Optional JSON Schema the child's answer must satisfy",
|
|
272
|
+
},
|
|
236
273
|
},
|
|
237
274
|
required: ['task'],
|
|
238
275
|
},
|
|
@@ -447,17 +484,16 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
447
484
|
function: {
|
|
448
485
|
name: 'verify',
|
|
449
486
|
description:
|
|
450
|
-
"Run the project's verification checks (typecheck and/or tests)
|
|
487
|
+
"Run the project's verification checks (typecheck and/or tests), returning structured pass/fail. Use after edits to confirm nothing broke.",
|
|
451
488
|
parameters: {
|
|
452
489
|
type: 'object',
|
|
453
490
|
properties: {
|
|
454
491
|
checks: {
|
|
455
492
|
type: 'array',
|
|
456
493
|
items: {type: 'string'},
|
|
457
|
-
description:
|
|
458
|
-
'Which checks to run: "typescript" (tsc --noEmit) and/or "test" (test script). Default: auto-detect both.',
|
|
494
|
+
description: '"typescript" (tsc --noEmit) and/or "test". Default: auto-detect both.',
|
|
459
495
|
},
|
|
460
|
-
path: {type: 'string', description: 'Project directory (default:
|
|
496
|
+
path: {type: 'string', description: 'Project directory (default: cwd)'},
|
|
461
497
|
},
|
|
462
498
|
},
|
|
463
499
|
},
|
|
@@ -467,13 +503,13 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
467
503
|
function: {
|
|
468
504
|
name: 'recall_history',
|
|
469
505
|
description:
|
|
470
|
-
"
|
|
506
|
+
"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
507
|
parameters: {
|
|
472
508
|
type: 'object',
|
|
473
509
|
properties: {
|
|
474
510
|
offset: {
|
|
475
511
|
type: 'number',
|
|
476
|
-
description: '
|
|
512
|
+
description: 'Start index within the summarized prefix (default 0).',
|
|
477
513
|
},
|
|
478
514
|
limit: {
|
|
479
515
|
type: 'number',
|
|
@@ -488,7 +524,7 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
488
524
|
function: {
|
|
489
525
|
name: 'todo',
|
|
490
526
|
description:
|
|
491
|
-
'Track a multi-step task.
|
|
527
|
+
'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
528
|
parameters: {
|
|
493
529
|
type: 'object',
|
|
494
530
|
properties: {
|