@pal-code/core 0.0.22 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pal-code/core",
3
- "version": "0.0.22",
3
+ "version": "0.0.23",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/src/agent/run.ts CHANGED
@@ -12,6 +12,8 @@ import {getDiagnosticsMode, takeDiagnosticsLine} from '../diagnostics.js';
12
12
  import {emitLifecycleEvent, type TurnContext} from '../lifecycle.js';
13
13
  import {complete} from '../provider/complete.js';
14
14
  import type {Provider, StreamEvent} from '../provider/types.js';
15
+ import type {Effort} from '../provider/effort.js';
16
+ import {DEFAULT_REASONING_EFFORT} from '../app-config.js';
15
17
  import {getMaxParallel} from './roles.js';
16
18
 
17
19
  // ---------------------------------------------------------------------------
@@ -148,8 +150,8 @@ export interface RunAgentOptions {
148
150
  budget?: {roleName: string; limit: number};
149
151
  /** Context window used to decide when to compact (default 200_000). */
150
152
  contextLimit?: number;
151
- /** Reasoning effort forwarded to the provider (default 'medium'). */
152
- reasoningEffort?: 'low' | 'medium' | 'high';
153
+ /** Reasoning effort forwarded to the provider (default `high`). */
154
+ reasoningEffort?: Effort;
153
155
  /**
154
156
  * High-water mark of genuinely-uncompacted history, as a 1-based store seq.
155
157
  * Messages at seq `<= compactedSeq` have already been folded into a persisted
@@ -273,24 +275,12 @@ export function summarizeArgs(name: string, args: Record<string, unknown>): stri
273
275
  }
274
276
  }
275
277
 
276
- /** Provider-specific reasoning/thinking parameters. */
277
- export function getEffortParams(
278
- model: string,
279
- effort: 'low' | 'medium' | 'high',
280
- ): Record<string, unknown> {
281
- if (/^o[134]/.test(model) || model.includes('gpt-5') || model.includes('gpt-6')) {
282
- return {reasoning_effort: effort};
283
- }
284
- if (model.startsWith('claude') || model.includes('anthropic') || model.includes('fable')) {
285
- const budget = effort === 'low' ? 2000 : effort === 'medium' ? 8000 : 16000;
286
- return {thinking: {type: 'enabled', budget_tokens: budget}};
287
- }
288
- if (model.startsWith('gemini')) {
289
- const budget = effort === 'low' ? 1024 : effort === 'medium' ? 8192 : 24576;
290
- return {generationConfig: {thinkingConfig: {thinkingBudget: budget}}};
291
- }
292
- return {};
293
- }
278
+ // `getEffortParams` now lives in `provider/effort.ts`, where it is
279
+ // protocol-aware. Re-exported so existing importers keep working.
280
+ export {getEffortParams} from '../provider/effort.js';
281
+
282
+ /** Process default, applied when `reasoningEffort` is omitted (see app-config). */
283
+ export const DEFAULT_EFFORT: Effort = DEFAULT_REASONING_EFFORT;
294
284
 
295
285
  /** Map the conversation to the OpenAI-compatible wire format. */
296
286
  /**
@@ -516,7 +506,7 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
516
506
  systemPrompt,
517
507
  maxRounds = DEFAULT_MAX_ROUNDS,
518
508
  contextLimit = DEFAULT_CONTEXT_LIMIT,
519
- reasoningEffort = 'medium',
509
+ reasoningEffort = DEFAULT_REASONING_EFFORT,
520
510
  providerConfig,
521
511
  executeTool,
522
512
  budget,
@@ -646,8 +636,10 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
646
636
  messages: apiMessages,
647
637
  tools: tools as never,
648
638
  signal,
649
- ...getEffortParams(model, reasoningEffort),
650
- } as never) as AsyncGenerator<StreamEvent>) {
639
+ // Effort is an *intent*; the provider translates it to the wire shape of
640
+ // whichever protocol it routes this model to (see provider/effort.ts).
641
+ effort: reasoningEffort,
642
+ })) {
651
643
  if (event.type === 'text' && event.content) {
652
644
  if (thinkingMs === null && thinkingStart !== null) thinkingMs = Date.now() - thinkingStart;
653
645
  textContent += event.content;
@@ -844,8 +836,8 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
844
836
  messages: buildApiMessages(messages, systemPrompt, compactionNote, compactedUpto),
845
837
  tools: [] as never,
846
838
  signal,
847
- ...getEffortParams(model, reasoningEffort),
848
- } as never) as AsyncGenerator<StreamEvent>) {
839
+ effort: reasoningEffort,
840
+ })) {
849
841
  if (event.type === 'text' && event.content) {
850
842
  wrapText += event.content;
851
843
  yield {type: 'text-delta', content: event.content};
package/src/app-config.ts CHANGED
@@ -55,6 +55,16 @@ const DEFAULT_SYSTEM_PROMPT = [
55
55
 
56
56
  const EFFORTS = ['low', 'medium', 'high'] as const;
57
57
 
58
+ /**
59
+ * Effort used when neither the env var nor `config.json` says otherwise.
60
+ *
61
+ * `high` on purpose: reasoning quality is the thing users most notice losing,
62
+ * and a silent downgrade to `medium` is worse than paying for the tokens the
63
+ * model actually needed. Override per-session with `/effort`, permanently with
64
+ * `REASONING_EFFORT` or `~/.pal/config.json`.
65
+ */
66
+ export const DEFAULT_REASONING_EFFORT = 'high' as const;
67
+
58
68
  /**
59
69
  * Extensions every install gets when `~/.pal/config.json` names none.
60
70
  *
@@ -92,12 +102,16 @@ function intEnv(name: string, fallback: number, min = 0): number {
92
102
  return n;
93
103
  }
94
104
 
95
- function effortEnv(): 'low' | 'medium' | 'high' {
105
+ /**
106
+ * `REASONING_EFFORT` from the env, or `undefined` when unset so the caller can
107
+ * fall through to config.json. An invalid value is reported and ignored.
108
+ */
109
+ function effortEnv(): 'low' | 'medium' | 'high' | undefined {
96
110
  const raw = process.env.REASONING_EFFORT;
97
- if (raw === undefined || raw === '') return 'medium';
111
+ if (raw === undefined || raw === '') return undefined;
98
112
  if ((EFFORTS as readonly string[]).includes(raw)) return raw as (typeof EFFORTS)[number];
99
- console.error(`pal: ignoring invalid REASONING_EFFORT=${JSON.stringify(raw)} — using medium`);
100
- return 'medium';
113
+ console.error(`pal: ignoring invalid REASONING_EFFORT=${JSON.stringify(raw)}`);
114
+ return undefined;
101
115
  }
102
116
 
103
117
  function strEnv(name: string, fallback: string): string {
@@ -152,6 +166,16 @@ export function loadConfig(): Config {
152
166
  // Context limit: env wins, then config.json, then the built-in default.
153
167
  const savedContextLimit = intConfig(saved.contextLimit, 'contextLimit');
154
168
 
169
+ // Effort: env wins, then config.json, then the default. Reading it back from
170
+ // config.json is what makes `/effort` survive a restart — `saveSetting` wrote
171
+ // the key but nothing ever loaded it.
172
+ const savedEffort = saved.reasoningEffort;
173
+ const reasoningEffort =
174
+ effortEnv() ??
175
+ ((EFFORTS as readonly string[]).includes(savedEffort as string)
176
+ ? (savedEffort as (typeof EFFORTS)[number])
177
+ : DEFAULT_REASONING_EFFORT);
178
+
155
179
  return {
156
180
  model: strEnv('MODEL', strEnv('PAL_MODEL', savedModel ?? 'deepseek/deepseek-chat')),
157
181
  systemPrompt: strEnv('SYSTEM_PROMPT', savedPrompt ?? DEFAULT_SYSTEM_PROMPT),
@@ -159,7 +183,7 @@ export function loadConfig(): Config {
159
183
  maxRetries: intEnv('MAX_RETRIES', 1, 0),
160
184
  retryBaseMs: intEnv('RETRY_BASE_MS', 2000, 0),
161
185
  contextLimit: intEnv('CONTEXT_LIMIT', savedContextLimit ?? 200_000, 1000),
162
- reasoningEffort: effortEnv(),
186
+ reasoningEffort,
163
187
  extensions,
164
188
  modelRotation: boolEnv('PAL_MODEL_ROTATION', boolValue(saved.modelRotation) ?? false),
165
189
  };
package/src/compaction.ts CHANGED
@@ -33,6 +33,25 @@ export function estimateMessagesTokens(messages: CompactableMessage[]): number {
33
33
  }, 0);
34
34
  }
35
35
 
36
+ /**
37
+ * The fixed per-request overhead the model is charged on *every* call: the
38
+ * composed system prompt plus the tool schemas.
39
+ *
40
+ * The context gauge used to count only `config.systemPrompt` — but
41
+ * `composeSystemPrompt()` appends the primary preamble, the role table, the
42
+ * skill listing and extension guidance, and the tool schemas (~2k tokens, 93%
43
+ * of the fixed cost) were never counted at all. That made the reported context
44
+ * fill materially optimistic, especially early in a conversation where the
45
+ * fixed overhead dominates.
46
+ *
47
+ * `toolTokens` is passed in rather than imported to keep this module free of a
48
+ * dependency on the tool registry (which would make the cycle
49
+ * compaction → definitions → compaction).
50
+ */
51
+ export function fixedPromptTokens(systemPrompt: string, toolTokens = 0): number {
52
+ return estimateTokens(systemPrompt) + toolTokens;
53
+ }
54
+
36
55
  export interface CompactionConfig {
37
56
  maxTokens: number;
38
57
  reservedTokens: number;
package/src/index.ts CHANGED
@@ -6,7 +6,7 @@ export type {
6
6
  StreamEvent,
7
7
  ModelRoute,
8
8
  } from './provider/types.js';
9
- export {createOpenRouterProvider} from './provider/openrouter.js';
9
+ export {createOpenRouterProvider, resetProviderSession} from './provider/openrouter.js';
10
10
  export {
11
11
  resolveAuth,
12
12
  resolveAllKeys,
@@ -33,7 +33,6 @@ export type {ProviderDef} from './provider/registry.js';
33
33
  export {
34
34
  runAgent,
35
35
  summarizeArgs,
36
- getEffortParams,
37
36
  buildApiMessages,
38
37
  sanitizeWireMessages,
39
38
  rollbackTurn,
@@ -121,7 +120,12 @@ export {createSharedState} from './runtime/state.js';
121
120
  export type {SharedState, BackgroundAgent, TodoItem} from './runtime/state.js';
122
121
 
123
122
  // Config
124
- export {loadConfig, loadPermissions, clearPermissionsCache} from './app-config.js';
123
+ export {
124
+ loadConfig,
125
+ loadPermissions,
126
+ clearPermissionsCache,
127
+ DEFAULT_REASONING_EFFORT,
128
+ } from './app-config.js';
125
129
  export type {Config} from './app-config.js';
126
130
  export {loadAgentConfig, isPathIgnored, clearConfigCache, resolveProjectRoot} from './config.js';
127
131
  export {
@@ -140,6 +144,7 @@ export {
140
144
  TOOL_NAME_ALIASES,
141
145
  getAllTools,
142
146
  getWireTools,
147
+ estimateToolSchemaTokens,
143
148
  registerExtensionTools,
144
149
  validateRequiredArgs,
145
150
  clearExtensionTools,
@@ -219,6 +224,7 @@ export {
219
224
  compactMessages,
220
225
  shouldCompact,
221
226
  estimateMessagesTokens,
227
+ fixedPromptTokens,
222
228
  buildModelView,
223
229
  summarizeRange,
224
230
  compactionBoundary,
@@ -230,6 +236,10 @@ export {complete} from './provider/complete.js';
230
236
  export type {CompleteOptions, CompleteResult} from './provider/complete.js';
231
237
  export {pickCheapModel} from './provider/pick-model.js';
232
238
 
239
+ // Reasoning effort → wire shape (protocol-aware)
240
+ export {getEffortParams, isReasoningModel} from './provider/effort.js';
241
+ export type {Effort, WireProtocol} from './provider/effort.js';
242
+
233
243
  // Model pricing / cost resolution
234
244
  export {
235
245
  estimateCost,
@@ -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
- /** Header token for N random lowercase hex chars, optionally prefixed.
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
- /** Expand header-value tokens.
43
- * `__sesid__` → `ses_` + 12 lowercase hex + 14 base62
44
- * `__random:32__` → 32-char random hex
45
- * `__random:ses_:32__` → `ses_` + 32-char random hex
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
- return `ses_${randomBytes(6).toString('hex')}${randomBase62(14)}`;
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', {
@@ -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
  }
@@ -111,12 +111,30 @@ export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
111
111
  * (`validateRequiredArgs`) and child-agent construction both resolve tools
112
112
  * through it and must never see a stub.
113
113
  *
114
- * Off by default. `PAL_LAZY_TOOLS` unset → byte-for-byte today's list.
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).
115
119
  */
116
120
  export function getWireTools(extra: ToolDef[] = []): ToolDef[] {
117
121
  return projectTools(getAllTools(extra));
118
122
  }
119
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
+
120
138
  const ROLE_DERIVED_TOOLS: Record<string, (roles: RoleSpec[]) => ToolDef> = {
121
139
  delegate: buildDelegateTool,
122
140
  delegate_parallel: buildDelegateParallelTool,