@aragon-agent/core 0.2.93 → 0.2.94
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/dist/engine/accept-steering.js +1 -15
- package/dist/engine/agent-loop.js +1 -533
- package/dist/engine/agent.js +1 -538
- package/dist/engine/compaction.js +1 -268
- package/dist/engine/context-manager.js +1 -13
- package/dist/engine/message-manager.js +1 -39
- package/dist/engine/steering.js +1 -72
- package/dist/engine/tool-result-content.js +1 -39
- package/dist/engine/watchdog.js +1 -73
- package/dist/index.js +1 -99
- package/dist/llm/context-window.js +1 -46
- package/dist/llm/image-tokens.js +1 -11
- package/dist/llm/model-discovery.js +1 -18
- package/dist/llm/model-registry.js +1 -370
- package/dist/llm/output-limit-recovery.js +1 -263
- package/dist/llm/output-limits.js +1 -283
- package/dist/llm/provider.js +1 -171
- package/dist/llm/providers/anthropic.js +1 -514
- package/dist/llm/providers/google.js +1 -464
- package/dist/llm/providers/index.js +1 -205
- package/dist/llm/providers/openai.js +1 -520
- package/dist/llm/providers/tool-result-images.js +1 -52
- package/dist/llm/retry.js +1 -948
- package/dist/llm/sse-parser.js +1 -103
- package/dist/llm/stream-utils.js +1 -118
- package/dist/llm/types.js +1 -17
- package/dist/sandbox/console-capture.js +1 -56
- package/dist/sandbox/http-bridge.js +1 -143
- package/dist/sandbox/isolated-vm-sandbox.js +1 -226
- package/dist/sandbox/tool-bridge.js +1 -98
- package/dist/sandbox/types.js +1 -8
- package/dist/skills/constants.js +1 -179
- package/dist/skills/disclosure.js +1 -788
- package/dist/skills/frontmatter.js +1 -177
- package/dist/skills/index.js +1 -18
- package/dist/skills/skill-find-tool.js +1 -117
- package/dist/skills/skill-registry.js +1 -208
- package/dist/skills/skill-tool.js +1 -96
- package/dist/skills/tool-policy.js +1 -272
- package/dist/skills/types.js +1 -8
- package/dist/skills/validate.js +1 -264
- package/dist/tools/executor.js +1 -281
- package/dist/tools/helpers.js +1 -87
- package/dist/tools/registry.js +1 -119
- package/dist/tools/types.js +1 -7
- package/dist/tools/validator.js +1 -210
- package/dist/types.js +1 -7
- package/package.json +3 -2
|
@@ -1,263 +1 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* One-shot self-healing for a request the provider rejected because of the
|
|
3
|
-
* output-token cap.
|
|
4
|
-
*
|
|
5
|
-
* The static table in `output-limits.ts` makes the common case correct without a
|
|
6
|
-
* round trip; this module makes the UNCOMMON case survivable — a proxy, a model
|
|
7
|
-
* that shipped last week, a dialect the heuristic guessed wrong. It reads the
|
|
8
|
-
* true ceiling out of the provider's own error text, repairs the request, sends
|
|
9
|
-
* it EXACTLY ONCE more, and teaches `output-limits.ts` what it learned so the
|
|
10
|
-
* rest of the process gets it right on the first try.
|
|
11
|
-
*
|
|
12
|
-
* TWO CONTRACTS THAT BREAK LOUDLY IF IGNORED:
|
|
13
|
-
*
|
|
14
|
-
* 1. A `Response` body can be read once. `RecoveryAttempt.bodyText` carries the
|
|
15
|
-
* already-consumed error body; callers MUST pass it on rather than calling
|
|
16
|
-
* `response.text()` again, which throws `TypeError: Body is unusable`. On
|
|
17
|
-
* the success path the body is NEVER touched — a streaming response has to
|
|
18
|
-
* reach the SSE parser intact.
|
|
19
|
-
*
|
|
20
|
-
* 2. Exactly one retry, structurally: `send` is called at most twice and there
|
|
21
|
-
* is no loop construct in this file. A recovery loop doubles every user's
|
|
22
|
-
* bill.
|
|
23
|
-
*
|
|
24
|
-
* TEST HYGIENE: `learnTokenField` writes a module-level map with process
|
|
25
|
-
* lifetime. Any test that memoizes a dialect MUST call `clearLearnedTokenFields()`
|
|
26
|
-
* from `afterEach`.
|
|
27
|
-
*/
|
|
28
|
-
import { CONTEXT_SAFETY_MARGIN_TOKENS, MIN_MAX_OUTPUT_TOKENS, MIN_THINKING_BUDGET_TOKENS, SAFE_FALLBACK_MAX_OUTPUT_TOKENS, THINKING_HEADROOM_TOKENS, learnModelCeiling, normalizeModelId, } from './output-limits.js';
|
|
29
|
-
const UNSUPPORTED_FIELD_PATTERNS = [
|
|
30
|
-
/unsupported parameter:?\s*'?max_tokens'?/i,
|
|
31
|
-
/use\s+'?max_completion_tokens'?/i,
|
|
32
|
-
];
|
|
33
|
-
const THINKING_CONFLICT_PATTERN = /max_tokens must be greater than (?:thinking\.)?budget_tokens/i;
|
|
34
|
-
/** Numeric ceiling captures, in priority order; group 1 is the real ceiling. */
|
|
35
|
-
const CEILING_PATTERNS = [
|
|
36
|
-
/max_tokens:\s*\d+\s*>\s*(\d+),\s*which is the maximum/i,
|
|
37
|
-
/supports at most (\d+) completion tokens/i,
|
|
38
|
-
/exceeds the model limit of (\d+)/i,
|
|
39
|
-
];
|
|
40
|
-
const CONTEXT_SUM_PATTERN = /maximum context length is (\d+) tokens.*?you requested \d+ tokens \((\d+) in the messages/is;
|
|
41
|
-
/** Last resort: the provider named the field but gave us no number to work with. */
|
|
42
|
-
const GENERIC_LIMIT_PATTERN = /max(?:imum)?[_ ](?:output|completion)[_ ]tokens/i;
|
|
43
|
-
function parseCount(raw) {
|
|
44
|
-
if (raw === undefined)
|
|
45
|
-
return undefined;
|
|
46
|
-
const n = Number.parseInt(raw, 10);
|
|
47
|
-
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Decide whether a provider rejection was about the output-token cap.
|
|
51
|
-
*
|
|
52
|
-
* ONLY `status === 400` is inspected — every other status is somebody else's
|
|
53
|
-
* problem and repairing the cap would just spend a second round trip to fail the
|
|
54
|
-
* same way.
|
|
55
|
-
*/
|
|
56
|
-
export function classifyOutputLimitFailure(providerId, status, body) {
|
|
57
|
-
if (status !== 400 || typeof body !== 'string' || body.length === 0)
|
|
58
|
-
return undefined;
|
|
59
|
-
void providerId; // the patterns are provider-specific but mutually exclusive
|
|
60
|
-
if (UNSUPPORTED_FIELD_PATTERNS.some((p) => p.test(body))) {
|
|
61
|
-
return { kind: 'unsupported_field', expected: 'max_completion_tokens' };
|
|
62
|
-
}
|
|
63
|
-
if (THINKING_CONFLICT_PATTERN.test(body))
|
|
64
|
-
return { kind: 'thinking_conflict' };
|
|
65
|
-
for (const pattern of CEILING_PATTERNS) {
|
|
66
|
-
const match = pattern.exec(body);
|
|
67
|
-
if (match) {
|
|
68
|
-
const ceiling = parseCount(match[1]);
|
|
69
|
-
return ceiling === undefined ? { kind: 'exceeds_ceiling' } : { kind: 'exceeds_ceiling', ceiling };
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
const ctx = CONTEXT_SUM_PATTERN.exec(body);
|
|
73
|
-
if (ctx) {
|
|
74
|
-
return {
|
|
75
|
-
kind: 'context_sum',
|
|
76
|
-
...(parseCount(ctx[1]) !== undefined ? { contextWindow: parseCount(ctx[1]) } : {}),
|
|
77
|
-
...(parseCount(ctx[2]) !== undefined ? { promptTokens: parseCount(ctx[2]) } : {}),
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
if (GENERIC_LIMIT_PATTERN.test(body))
|
|
81
|
-
return { kind: 'exceeds_ceiling' };
|
|
82
|
-
return undefined;
|
|
83
|
-
}
|
|
84
|
-
const learnedTokenFields = new Map();
|
|
85
|
-
function fieldKey(providerId, modelId) {
|
|
86
|
-
return `${String(providerId ?? '').toLowerCase()}:${normalizeModelId(modelId)}`;
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Remember which parameter name this `provider:model` actually accepts.
|
|
90
|
-
*
|
|
91
|
-
* The heuristic in `openai.ts` is only the first guess; a proxy fronting an
|
|
92
|
-
* o-series model under a `gpt-` alias disagrees with it. One round trip corrects
|
|
93
|
-
* that, permanently for the life of the process.
|
|
94
|
-
*/
|
|
95
|
-
export function learnTokenField(providerId, modelId, field) {
|
|
96
|
-
learnedTokenFields.set(fieldKey(providerId, modelId), field);
|
|
97
|
-
}
|
|
98
|
-
export function getLearnedTokenField(providerId, modelId) {
|
|
99
|
-
return learnedTokenFields.get(fieldKey(providerId, modelId));
|
|
100
|
-
}
|
|
101
|
-
/** Test hook. MUST be called from `afterEach` in every test that memoizes a dialect. */
|
|
102
|
-
export function clearLearnedTokenFields() {
|
|
103
|
-
learnedTokenFields.clear();
|
|
104
|
-
}
|
|
105
|
-
// ---------------------------------------------------------------------------
|
|
106
|
-
// Body field access (Google's field is a dotted path)
|
|
107
|
-
// ---------------------------------------------------------------------------
|
|
108
|
-
function readTokenValue(body, field) {
|
|
109
|
-
if (field !== 'generationConfig.maxOutputTokens') {
|
|
110
|
-
const v = body[field];
|
|
111
|
-
return typeof v === 'number' ? v : undefined;
|
|
112
|
-
}
|
|
113
|
-
const nested = body.generationConfig;
|
|
114
|
-
const v = nested?.maxOutputTokens;
|
|
115
|
-
return typeof v === 'number' ? v : undefined;
|
|
116
|
-
}
|
|
117
|
-
function withTokenValue(body, field, value) {
|
|
118
|
-
if (field !== 'generationConfig.maxOutputTokens') {
|
|
119
|
-
return { ...body, [field]: value };
|
|
120
|
-
}
|
|
121
|
-
const nested = (body.generationConfig ?? {});
|
|
122
|
-
return { ...body, generationConfig: { ...nested, maxOutputTokens: value } };
|
|
123
|
-
}
|
|
124
|
-
function readThinkingBudget(body) {
|
|
125
|
-
const thinking = body.thinking;
|
|
126
|
-
const v = thinking?.budget_tokens;
|
|
127
|
-
return typeof v === 'number' ? v : undefined;
|
|
128
|
-
}
|
|
129
|
-
function repairCeiling(ctx, current, ceiling) {
|
|
130
|
-
const target = Math.max(MIN_MAX_OUTPUT_TOKENS, ceiling ?? Math.min(current, SAFE_FALLBACK_MAX_OUTPUT_TOKENS));
|
|
131
|
-
if (target >= current)
|
|
132
|
-
return undefined;
|
|
133
|
-
learnModelCeiling(ctx.providerId, ctx.modelId, target, 'error');
|
|
134
|
-
return {
|
|
135
|
-
body: withTokenValue(ctx.body, ctx.field, target),
|
|
136
|
-
from: current,
|
|
137
|
-
to: target,
|
|
138
|
-
summary: `output cap ${current} -> ${target}`,
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
function repairContextSum(ctx, current, failure) {
|
|
142
|
-
const window = failure.contextWindow;
|
|
143
|
-
const prompt = failure.promptTokens;
|
|
144
|
-
if (window === undefined || prompt === undefined)
|
|
145
|
-
return undefined;
|
|
146
|
-
// NOT learned: a context-sum failure is conversation-specific, not a property
|
|
147
|
-
// of the model, and recording it as a ceiling would cap every later turn.
|
|
148
|
-
const target = Math.max(MIN_MAX_OUTPUT_TOKENS, window - prompt - CONTEXT_SAFETY_MARGIN_TOKENS);
|
|
149
|
-
if (target >= current)
|
|
150
|
-
return undefined;
|
|
151
|
-
return {
|
|
152
|
-
body: withTokenValue(ctx.body, ctx.field, target),
|
|
153
|
-
from: current,
|
|
154
|
-
to: target,
|
|
155
|
-
summary: `output cap ${current} -> ${target} to fit the context window`,
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
function repairThinkingConflict(ctx, current) {
|
|
159
|
-
const budget = readThinkingBudget(ctx.body);
|
|
160
|
-
if (budget === undefined || budget <= 0)
|
|
161
|
-
return undefined;
|
|
162
|
-
const raised = budget + THINKING_HEADROOM_TOKENS;
|
|
163
|
-
if (raised > current) {
|
|
164
|
-
return {
|
|
165
|
-
body: withTokenValue(ctx.body, ctx.field, raised),
|
|
166
|
-
from: current,
|
|
167
|
-
to: raised,
|
|
168
|
-
summary: `output cap ${current} -> ${raised} to clear the thinking budget`,
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
// The ceiling forbids raising the cap, so lower the budget instead.
|
|
172
|
-
const lowered = Math.max(MIN_THINKING_BUDGET_TOKENS, current - THINKING_HEADROOM_TOKENS);
|
|
173
|
-
if (lowered >= current)
|
|
174
|
-
return undefined;
|
|
175
|
-
const thinking = ctx.body.thinking;
|
|
176
|
-
return {
|
|
177
|
-
body: { ...ctx.body, thinking: { ...thinking, budget_tokens: lowered } },
|
|
178
|
-
from: budget,
|
|
179
|
-
to: lowered,
|
|
180
|
-
// `from`/`to` are the BUDGET here, not the cap — the cap is what could not
|
|
181
|
-
// move. Saying "output cap" would name the wrong number.
|
|
182
|
-
summary: `thinking budget ${budget} -> ${lowered}`,
|
|
183
|
-
};
|
|
184
|
-
}
|
|
185
|
-
function planRepair(opts, failure) {
|
|
186
|
-
const current = readTokenValue(opts.body, opts.tokenField);
|
|
187
|
-
const ctx = {
|
|
188
|
-
providerId: opts.providerId,
|
|
189
|
-
modelId: opts.modelId,
|
|
190
|
-
body: opts.body,
|
|
191
|
-
field: opts.tokenField,
|
|
192
|
-
};
|
|
193
|
-
if (failure.kind === 'unsupported_field') {
|
|
194
|
-
if (opts.tokenField === 'generationConfig.maxOutputTokens')
|
|
195
|
-
return undefined;
|
|
196
|
-
if (opts.tokenField === failure.expected)
|
|
197
|
-
return undefined;
|
|
198
|
-
learnTokenField(opts.providerId, opts.modelId, failure.expected);
|
|
199
|
-
const renamed = { ...opts.body };
|
|
200
|
-
delete renamed[opts.tokenField];
|
|
201
|
-
// The reasoning family rejects `temperature` for the same reason it rejects
|
|
202
|
-
// `max_tokens`; leaving it behind just buys a second 400 on a different key.
|
|
203
|
-
delete renamed.temperature;
|
|
204
|
-
renamed[failure.expected] = current ?? MIN_MAX_OUTPUT_TOKENS;
|
|
205
|
-
return {
|
|
206
|
-
body: renamed,
|
|
207
|
-
from: current ?? 0,
|
|
208
|
-
to: current ?? 0,
|
|
209
|
-
summary: `token parameter ${opts.tokenField} -> ${failure.expected}`,
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
if (current === undefined)
|
|
213
|
-
return undefined;
|
|
214
|
-
if (failure.kind === 'thinking_conflict')
|
|
215
|
-
return repairThinkingConflict(ctx, current);
|
|
216
|
-
if (failure.kind === 'context_sum')
|
|
217
|
-
return repairContextSum(ctx, current, failure);
|
|
218
|
-
return repairCeiling(ctx, current, failure.ceiling);
|
|
219
|
-
}
|
|
220
|
-
/**
|
|
221
|
-
* Send a request, and on an output-limit 400 repair it and send it once more.
|
|
222
|
-
*
|
|
223
|
-
* The hot path is untouched: a 2xx returns immediately with an unread body.
|
|
224
|
-
*/
|
|
225
|
-
export async function sendWithOutputLimitRecovery(opts) {
|
|
226
|
-
const first = await opts.send(opts.body);
|
|
227
|
-
// The body is NOT read here — a streaming response must reach the SSE parser
|
|
228
|
-
// intact, and `bodyUsed` would already be true if we peeked.
|
|
229
|
-
if (first.ok)
|
|
230
|
-
return { response: first, bodyText: '' };
|
|
231
|
-
const bodyText = await first.text().catch(() => '');
|
|
232
|
-
const failure = classifyOutputLimitFailure(opts.providerId, first.status, bodyText);
|
|
233
|
-
if (!failure)
|
|
234
|
-
return { response: first, bodyText };
|
|
235
|
-
const plan = planRepair(opts, failure);
|
|
236
|
-
if (!plan)
|
|
237
|
-
return { response: first, bodyText };
|
|
238
|
-
const second = await opts.send(plan.body);
|
|
239
|
-
const adjustment = { from: plan.from, to: plan.to, reason: failure.kind };
|
|
240
|
-
if (!second.ok) {
|
|
241
|
-
// A second failure surfaces exactly as it would have without recovery.
|
|
242
|
-
return { response: second, bodyText: await second.text().catch(() => ''), adjustment };
|
|
243
|
-
}
|
|
244
|
-
warnAdjusted(opts.providerId, opts.modelId, plan.summary, failure.kind);
|
|
245
|
-
return { response: second, bodyText: '', adjustment };
|
|
246
|
-
}
|
|
247
|
-
/** Display names for the adapters this package ships; `Openai` reads as a typo. */
|
|
248
|
-
const PROVIDER_LABELS = {
|
|
249
|
-
anthropic: 'Anthropic',
|
|
250
|
-
openai: 'OpenAI',
|
|
251
|
-
google: 'Google',
|
|
252
|
-
};
|
|
253
|
-
/**
|
|
254
|
-
* Core has no logger and must not acquire one (that would be host coupling), so
|
|
255
|
-
* this is `console.warn` — exactly what `anthropic.ts` already does for a
|
|
256
|
-
* malformed tool call. In the CLI it reaches the transcript through the console
|
|
257
|
-
* bridge; in a headless embedder it is a plain warning.
|
|
258
|
-
*/
|
|
259
|
-
function warnAdjusted(providerId, modelId, summary, reason) {
|
|
260
|
-
const key = String(providerId ?? '').toLowerCase();
|
|
261
|
-
const name = PROVIDER_LABELS[key] ?? providerId.charAt(0).toUpperCase() + providerId.slice(1);
|
|
262
|
-
console.warn(`[${name}] adjusted ${summary} (${reason}) for ${modelId}`);
|
|
263
|
-
}
|
|
1
|
+
const _0x4ddf91=_0x5734;function _0x4262(){const _0x1ff421=['Bw9KzwXjza','C3rHDhvZ','A2LUza','zMLLBgq','yNvKz2v0x3rVA2vUCW','D2fYBG','Dg9mB3DLCKnHC2u','Bwf4t3v0Chv0vg9Rzw5Z','ChjVDMLKzxjjza','qw50AhjVCgLJ','y29Uy2f0','z2vUzxjHDgLVBKnVBMzPzY5TyxHpDxrWDxruB2TLBNm','B3v0Chv0ignHCca','zxHLyW','C2v0','DgHPBMTPBMDFy29UzMXPy3q','z2vUzxjHDgLVBKnVBMzPzW','mtmXnJaYmMTQtvv5CG','mtm5odu2C2D4rfPq','zxHJzwvKC19JzwLSAw5N','Dg9Rzw5gAwvSza','mJu4nZu4uK9SrKPg','t3bLBKfj','r29Vz2XL','C3rYAw5N','mtiYnta2mfLbzhnjqq','C3vTBwfYEq','y2vPBgLUzW','C29Tzq','Bwf4','z2v0','DgvZDa','y2HHCKf0','zxHWzwn0zwq','Dg9Rzw4GCgfYyw1LDgvYia','ic0+ia','DgHPBMTPBMCGyNvKz2v0ia','Bwf4x2nVBxbSzxrPB25FDg9Rzw5Z','nfPbzLPqyq','DgvTCgvYyxr1CMu','nZDSAxzOzgy','ihrVignSzwfYihrOzsb0AgLUA2LUzYbIDwrNzxq','yM9KEq','y29UDgv4DfDPBMrVDW','ihrVigzPDcb0AguGy29UDgv4Dcb3Aw5KB3C','AxngAw5PDgu','BgvUz3rO','Dg9vChbLCKnHC2u','BNvTyMvY','Dw5ZDxbWB3j0zwrFzMLLBgq','mJa2mti3me13D2PJuG','BwLU','zxjYB3i','odK4oda0whrnBfzZ','mtq1mduWq09oz0ry','CgfYC2vjBNq','y2f0y2G'];_0x4262=function(){return _0x1ff421;};return _0x4262();}(function(_0x4fdaf5,_0x209acb){const _0x50fbb3=_0x5734,_0x3c5d9a=_0x4fdaf5();while(!![]){try{const _0x533f65=-parseInt(_0x50fbb3(0x212))/0x1*(-parseInt(_0x50fbb3(0x1ea))/0x2)+-parseInt(_0x50fbb3(0x1fa))/0x3+parseInt(_0x50fbb3(0x1f9))/0x4+-parseInt(_0x50fbb3(0x1dd))/0x5+-parseInt(_0x50fbb3(0x20e))/0x6+-parseInt(_0x50fbb3(0x1ec))/0x7*(parseInt(_0x50fbb3(0x20f))/0x8)+parseInt(_0x50fbb3(0x1f6))/0x9;if(_0x533f65===_0x209acb)break;else _0x3c5d9a['push'](_0x3c5d9a['shift']());}catch(_0x47339d){_0x3c5d9a['push'](_0x3c5d9a['shift']());}}}(_0x4262,0x41006));function _0x5734(_0x4652a7,_0x3ca728){_0x4652a7=_0x4652a7-0x1dd;const _0x42626c=_0x4262();let _0x573436=_0x42626c[_0x4652a7];if(_0x5734['hOKSUF']===undefined){var _0x18b3d9=function(_0x5792da){const _0x300293='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x2a7c2c='',_0x393d7d='';for(let _0x4f77ee=0x0,_0x1bd024,_0x3b723,_0x42999c=0x0;_0x3b723=_0x5792da['charAt'](_0x42999c++);~_0x3b723&&(_0x1bd024=_0x4f77ee%0x4?_0x1bd024*0x40+_0x3b723:_0x3b723,_0x4f77ee++%0x4)?_0x2a7c2c+=String['fromCharCode'](0xff&_0x1bd024>>(-0x2*_0x4f77ee&0x6)):0x0){_0x3b723=_0x300293['indexOf'](_0x3b723);}for(let _0x57650a=0x0,_0x3a47e5=_0x2a7c2c['length'];_0x57650a<_0x3a47e5;_0x57650a++){_0x393d7d+='%'+('00'+_0x2a7c2c['charCodeAt'](_0x57650a)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x393d7d);};_0x5734['tiZRjV']=_0x18b3d9,_0x5734['rnOcGR']={},_0x5734['hOKSUF']=!![];}const _0x40f731=_0x42626c[0x0];_0x5734['AaoZpi']!==_0x40f731&&(_0x5734['rnOcGR']={},_0x5734['AaoZpi']=_0x40f731);const _0x34bbf6=_0x5734['rnOcGR'][_0x4652a7];return _0x34bbf6===undefined?(_0x573436=_0x5734['tiZRjV'](_0x573436),_0x5734['rnOcGR'][_0x4652a7]=_0x573436):_0x573436=_0x34bbf6,_0x573436;}import{CONTEXT_SAFETY_MARGIN_TOKENS,MIN_MAX_OUTPUT_TOKENS,MIN_THINKING_BUDGET_TOKENS,SAFE_FALLBACK_MAX_OUTPUT_TOKENS,THINKING_HEADROOM_TOKENS,learnModelCeiling,normalizeModelId}from'./output-limits.js';const UNSUPPORTED_FIELD_PATTERNS=[/unsupported parameter:?\s*'?max_tokens'?/i,/use\s+'?max_completion_tokens'?/i],THINKING_CONFLICT_PATTERN=/max_tokens must be greater than (?:thinking\.)?budget_tokens/i,CEILING_PATTERNS=[/max_tokens:\s*\d+\s*>\s*(\d+),\s*which is the maximum/i,/supports at most (\d+) completion tokens/i,/exceeds the model limit of (\d+)/i],CONTEXT_SUM_PATTERN=/maximum context length is (\d+) tokens.*?you requested \d+ tokens \((\d+) in the messages/is,GENERIC_LIMIT_PATTERN=/max(?:imum)?[_ ](?:output|completion)[_ ]tokens/i;function parseCount(_0x393d7d){const _0x1b1614=_0x5734;if(_0x393d7d===undefined)return undefined;const _0x4f77ee=Number[_0x1b1614(0x1fb)](_0x393d7d,0xa);return Number[_0x1b1614(0x1f1)](_0x4f77ee)&&_0x4f77ee>0x0?_0x4f77ee:undefined;}export function classifyOutputLimitFailure(_0x1bd024,_0x3b723,_0x42999c){const _0x41b39e=_0x5734;if(_0x3b723!==0x190||typeof _0x42999c!==_0x41b39e(0x215)||_0x42999c[_0x41b39e(0x1f2)]===0x0)return undefined;void _0x1bd024;if(UNSUPPORTED_FIELD_PATTERNS[_0x41b39e(0x1e0)](_0x3a47e5=>_0x3a47e5[_0x41b39e(0x1e3)](_0x42999c)))return{'kind':_0x41b39e(0x1f5),'expected':_0x41b39e(0x1e9)};if(THINKING_CONFLICT_PATTERN[_0x41b39e(0x1e3)](_0x42999c))return{'kind':'thinking_conflict'};for(const _0x475545 of CEILING_PATTERNS){const _0x48839e=_0x475545['exec'](_0x42999c);if(_0x48839e){const _0x105ea3=parseCount(_0x48839e[0x1]);return _0x105ea3===undefined?{'kind':_0x41b39e(0x210)}:{'kind':_0x41b39e(0x210),'ceiling':_0x105ea3};}}const _0x57650a=CONTEXT_SUM_PATTERN[_0x41b39e(0x20a)](_0x42999c);if(_0x57650a)return{'kind':'context_sum',...parseCount(_0x57650a[0x1])!==undefined?{'contextWindow':parseCount(_0x57650a[0x1])}:{},...parseCount(_0x57650a[0x2])!==undefined?{'promptTokens':parseCount(_0x57650a[0x2])}:{}};if(GENERIC_LIMIT_PATTERN[_0x41b39e(0x1e3)](_0x42999c))return{'kind':'exceeds_ceiling'};return undefined;}const learnedTokenFields=new Map();function fieldKey(_0x4a977d,_0x1e3e7b){const _0x8a1819=_0x5734;return''['concat'](String(_0x4a977d??'')[_0x8a1819(0x203)](),':')['concat'](normalizeModelId(_0x1e3e7b));}export function learnTokenField(_0x2df841,_0x4c82d4,_0x14c321){const _0x2036af=_0x5734;learnedTokenFields[_0x2036af(0x20b)](fieldKey(_0x2df841,_0x4c82d4),_0x14c321);}export function getLearnedTokenField(_0x1f5c7c,_0x1b3ab8){const _0x59037e=_0x5734;return learnedTokenFields[_0x59037e(0x1e2)](fieldKey(_0x1f5c7c,_0x1b3ab8));}export function clearLearnedTokenFields(){learnedTokenFields['clear']();}function readTokenValue(_0x4a773f,_0x1896d5){const _0x7b2682=_0x5734;if(_0x1896d5!==_0x7b2682(0x208)){const _0x13ee87=_0x4a773f[_0x1896d5];return typeof _0x13ee87===_0x7b2682(0x1f4)?_0x13ee87:undefined;}const _0x5ee3fa=_0x4a773f[_0x7b2682(0x20d)],_0x4541ec=_0x5ee3fa?.[_0x7b2682(0x204)];return typeof _0x4541ec==='number'?_0x4541ec:undefined;}function withTokenValue(_0x465d80,_0x2d2809,_0xfd6d87){const _0x1b345b=_0x5734;if(_0x2d2809!==_0x1b345b(0x208))return{..._0x465d80,[_0x2d2809]:_0xfd6d87};const _0x11bb42=_0x465d80[_0x1b345b(0x20d)]??{};return{..._0x465d80,'generationConfig':{..._0x11bb42,'maxOutputTokens':_0xfd6d87}};}function readThinkingBudget(_0x5125a4){const _0x55d5ae=_0x5734,_0x196b42=_0x5125a4['thinking'],_0x24a208=_0x196b42?.[_0x55d5ae(0x201)];return typeof _0x24a208===_0x55d5ae(0x1f4)?_0x24a208:undefined;}function repairCeiling(_0xb97fd2,_0x354554,_0x24caf3){const _0x3b4cbf=_0x5734,_0x1e7632=Math['max'](MIN_MAX_OUTPUT_TOKENS,_0x24caf3??Math[_0x3b4cbf(0x1f7)](_0x354554,SAFE_FALLBACK_MAX_OUTPUT_TOKENS));if(_0x1e7632>=_0x354554)return undefined;return learnModelCeiling(_0xb97fd2[_0x3b4cbf(0x205)],_0xb97fd2[_0x3b4cbf(0x1fd)],_0x1e7632,_0x3b4cbf(0x1f8)),{'body':withTokenValue(_0xb97fd2[_0x3b4cbf(0x1ee)],_0xb97fd2[_0x3b4cbf(0x200)],_0x1e7632),'from':_0x354554,'to':_0x1e7632,'summary':_0x3b4cbf(0x209)[_0x3b4cbf(0x207)](_0x354554,_0x3b4cbf(0x1e7))[_0x3b4cbf(0x207)](_0x1e7632)};}function repairContextSum(_0x5b8f05,_0x4598b7,_0x3ed7c7){const _0x5ecdd1=_0x5734,_0x127f8c=_0x3ed7c7[_0x5ecdd1(0x1ef)],_0x219fbc=_0x3ed7c7['promptTokens'];if(_0x127f8c===undefined||_0x219fbc===undefined)return undefined;const _0x357a48=Math[_0x5ecdd1(0x1e1)](MIN_MAX_OUTPUT_TOKENS,_0x127f8c-_0x219fbc-CONTEXT_SAFETY_MARGIN_TOKENS);if(_0x357a48>=_0x4598b7)return undefined;return{'body':withTokenValue(_0x5b8f05[_0x5ecdd1(0x1ee)],_0x5b8f05[_0x5ecdd1(0x200)],_0x357a48),'from':_0x4598b7,'to':_0x357a48,'summary':'output\x20cap\x20'[_0x5ecdd1(0x207)](_0x4598b7,_0x5ecdd1(0x1e7))[_0x5ecdd1(0x207)](_0x357a48,_0x5ecdd1(0x1f0))};}function repairThinkingConflict(_0x20db2b,_0x39e16a){const _0x4cd996=_0x5734,_0x564f76=readThinkingBudget(_0x20db2b[_0x4cd996(0x1ee)]);if(_0x564f76===undefined||_0x564f76<=0x0)return undefined;const _0x434fc8=_0x564f76+THINKING_HEADROOM_TOKENS;if(_0x434fc8>_0x39e16a)return{'body':withTokenValue(_0x20db2b['body'],_0x20db2b[_0x4cd996(0x200)],_0x434fc8),'from':_0x39e16a,'to':_0x434fc8,'summary':'output\x20cap\x20'['concat'](_0x39e16a,_0x4cd996(0x1e7))[_0x4cd996(0x207)](_0x434fc8,_0x4cd996(0x1ed))};const _0x1dde55=Math['max'](MIN_THINKING_BUDGET_TOKENS,_0x39e16a-THINKING_HEADROOM_TOKENS);if(_0x1dde55>=_0x39e16a)return undefined;const _0x17a1e2=_0x20db2b[_0x4cd996(0x1ee)]['thinking'];return{'body':{..._0x20db2b['body'],'thinking':{..._0x17a1e2,'budget_tokens':_0x1dde55}},'from':_0x564f76,'to':_0x1dde55,'summary':_0x4cd996(0x1e8)[_0x4cd996(0x207)](_0x564f76,'\x20->\x20')['concat'](_0x1dde55)};}function planRepair(_0x48ff71,_0x43b511){const _0x16d29b=_0x5734,_0x344bce=readTokenValue(_0x48ff71[_0x16d29b(0x1ee)],_0x48ff71['tokenField']),_0x14f698={'providerId':_0x48ff71[_0x16d29b(0x205)],'modelId':_0x48ff71[_0x16d29b(0x1fd)],'body':_0x48ff71[_0x16d29b(0x1ee)],'field':_0x48ff71[_0x16d29b(0x211)]};if(_0x43b511[_0x16d29b(0x1ff)]===_0x16d29b(0x1f5)){if(_0x48ff71[_0x16d29b(0x211)]===_0x16d29b(0x208))return undefined;if(_0x48ff71[_0x16d29b(0x211)]===_0x43b511[_0x16d29b(0x1e5)])return undefined;learnTokenField(_0x48ff71[_0x16d29b(0x205)],_0x48ff71[_0x16d29b(0x1fd)],_0x43b511[_0x16d29b(0x1e5)]);const _0x1267be={..._0x48ff71[_0x16d29b(0x1ee)]};return delete _0x1267be[_0x48ff71[_0x16d29b(0x211)]],delete _0x1267be[_0x16d29b(0x1eb)],_0x1267be[_0x43b511['expected']]=_0x344bce??MIN_MAX_OUTPUT_TOKENS,{'body':_0x1267be,'from':_0x344bce??0x0,'to':_0x344bce??0x0,'summary':_0x16d29b(0x1e6)[_0x16d29b(0x207)](_0x48ff71['tokenField'],_0x16d29b(0x1e7))['concat'](_0x43b511[_0x16d29b(0x1e5)])};}if(_0x344bce===undefined)return undefined;if(_0x43b511[_0x16d29b(0x1ff)]===_0x16d29b(0x20c))return repairThinkingConflict(_0x14f698,_0x344bce);if(_0x43b511[_0x16d29b(0x1ff)]==='context_sum')return repairContextSum(_0x14f698,_0x344bce,_0x43b511);return repairCeiling(_0x14f698,_0x344bce,_0x43b511[_0x16d29b(0x1df)]);}export async function sendWithOutputLimitRecovery(_0x3f299f){const _0x1ddb24=_0x5734,_0xcbd913=await _0x3f299f['send'](_0x3f299f[_0x1ddb24(0x1ee)]);if(_0xcbd913['ok'])return{'response':_0xcbd913,'bodyText':''};const _0x4b07f9=await _0xcbd913['text']()[_0x1ddb24(0x1fc)](()=>''),_0x2f5b81=classifyOutputLimitFailure(_0x3f299f[_0x1ddb24(0x205)],_0xcbd913[_0x1ddb24(0x1fe)],_0x4b07f9);if(!_0x2f5b81)return{'response':_0xcbd913,'bodyText':_0x4b07f9};const _0x5948cb=planRepair(_0x3f299f,_0x2f5b81);if(!_0x5948cb)return{'response':_0xcbd913,'bodyText':_0x4b07f9};const _0x448034=await _0x3f299f['send'](_0x5948cb['body']),_0x3d4d01={'from':_0x5948cb['from'],'to':_0x5948cb['to'],'reason':_0x2f5b81[_0x1ddb24(0x1ff)]};if(!_0x448034['ok'])return{'response':_0x448034,'bodyText':await _0x448034['text']()[_0x1ddb24(0x1fc)](()=>''),'adjustment':_0x3d4d01};return warnAdjusted(_0x3f299f[_0x1ddb24(0x205)],_0x3f299f[_0x1ddb24(0x1fd)],_0x5948cb[_0x1ddb24(0x1de)],_0x2f5b81['kind']),{'response':_0x448034,'bodyText':'','adjustment':_0x3d4d01};}const PROVIDER_LABELS={'anthropic':_0x4ddf91(0x206),'openai':_0x4ddf91(0x213),'google':_0x4ddf91(0x214)};function warnAdjusted(_0x394f1c,_0x33726d,_0x212991,_0x3fd9e5){const _0x3c7f99=_0x4ddf91,_0x5f2e66=String(_0x394f1c??'')[_0x3c7f99(0x203)](),_0x11d1c9=PROVIDER_LABELS[_0x5f2e66]??_0x394f1c[_0x3c7f99(0x1e4)](0x0)[_0x3c7f99(0x1f3)]()+_0x394f1c['slice'](0x1);console[_0x3c7f99(0x202)]('['['concat'](_0x11d1c9,']\x20adjusted\x20')[_0x3c7f99(0x207)](_0x212991,'\x20(')[_0x3c7f99(0x207)](_0x3fd9e5,')\x20for\x20')[_0x3c7f99(0x207)](_0x33726d));}
|
|
@@ -1,283 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* Output-token authority — the single source of truth for "how many tokens may
|
|
3
|
-
* this model produce", and the resolver every provider adapter consults before
|
|
4
|
-
* putting a number on the wire.
|
|
5
|
-
*
|
|
6
|
-
* Why this module exists at all: sending a generous `max_tokens` unconditionally
|
|
7
|
-
* is only safe for models whose ceiling is at least that generous. Anthropic,
|
|
8
|
-
* OpenAI and Google all answer an over-large cap with an HTTP 400, and a 400
|
|
9
|
-
* during the agent loop ends the turn with a raw provider string in the
|
|
10
|
-
* transcript. So the product default is the AMBITION and the model's real
|
|
11
|
-
* ceiling is the LAW, with the gap closed silently rather than by a failed run.
|
|
12
|
-
*
|
|
13
|
-
* Four ranked ceiling sources feed one resolver:
|
|
14
|
-
*
|
|
15
|
-
* learned-from-error > discovery (API-reported) > static table > default
|
|
16
|
-
*
|
|
17
|
-
* TEST HYGIENE: `learnModelCeiling` writes a MODULE-LEVEL map that lives for the
|
|
18
|
-
* whole process. Any test that learns MUST call `clearLearnedCeilings()` from
|
|
19
|
-
* `afterEach`, or a learned 8192 leaks into the next test file and produces a
|
|
20
|
-
* failure whose cause is not in the failing file.
|
|
21
|
-
*/
|
|
22
|
-
import { IMAGE_TOKEN_ESTIMATE } from './image-tokens.js';
|
|
23
|
-
// ---------------------------------------------------------------------------
|
|
24
|
-
// Constants — nothing else in this package may spell these numbers
|
|
25
|
-
// ---------------------------------------------------------------------------
|
|
26
|
-
/** The product default. THE single source of truth; nothing else may spell 64000. */
|
|
27
|
-
export const DEFAULT_MAX_OUTPUT_TOKENS = 64_000;
|
|
28
|
-
/** Below this a turn cannot produce a usable tool call; never clamp under it. */
|
|
29
|
-
export const MIN_MAX_OUTPUT_TOKENS = 256;
|
|
30
|
-
/**
|
|
31
|
-
* Every model in the supported set accepts at least this. Used when recovery
|
|
32
|
-
* cannot parse a real ceiling out of the provider's error.
|
|
33
|
-
*/
|
|
34
|
-
export const SAFE_FALLBACK_MAX_OUTPUT_TOKENS = 8_192;
|
|
35
|
-
/** Anthropic requires max_tokens > thinking.budget_tokens; this is the margin. */
|
|
36
|
-
export const THINKING_HEADROOM_TOKENS = 4_096;
|
|
37
|
-
/** Sanity ceiling for a hand-edited config file. */
|
|
38
|
-
export const ABSOLUTE_MAX_OUTPUT_TOKENS = 200_000;
|
|
39
|
-
/** Subtracted from a context-window computation so the estimate may be wrong. */
|
|
40
|
-
export const CONTEXT_SAFETY_MARGIN_TOKENS = 1_024;
|
|
41
|
-
/**
|
|
42
|
-
* Anthropic's floor for `thinking.budget_tokens`. A downgrade that lands below
|
|
43
|
-
* it is illegal, so the resolver returns `thinkingBudget: 0` instead and the
|
|
44
|
-
* adapter omits the block entirely.
|
|
45
|
-
*/
|
|
46
|
-
export const MIN_THINKING_BUDGET_TOKENS = 1_024;
|
|
47
|
-
/**
|
|
48
|
-
* Ordered; FIRST MATCH WINS. Matched against the model id lowercased with any
|
|
49
|
-
* `models/` prefix stripped (Google returns `models/gemini-1.5-pro`).
|
|
50
|
-
*
|
|
51
|
-
* ORDER IS LOAD-BEARING, not cosmetic: `claude-3-7-sonnet` also matches the
|
|
52
|
-
* broad `^claude-3(-|\.)` rule, so the specific 3.7 entry has to come first or
|
|
53
|
-
* it is dead code and every 3.7 request is clamped to 8192 (see the design's
|
|
54
|
-
* "Issues found during implementation" note).
|
|
55
|
-
*/
|
|
56
|
-
const CEILING_TABLE = {
|
|
57
|
-
anthropic: [
|
|
58
|
-
{ pattern: /^claude-3-7-sonnet/, ceiling: 64_000 },
|
|
59
|
-
{ pattern: /^claude-3-5-sonnet/, ceiling: 8_192 },
|
|
60
|
-
{ pattern: /^claude-3(-|\.)/, ceiling: 8_192 },
|
|
61
|
-
{ pattern: /^claude-opus-4-(0|1)\b/, ceiling: 32_000 },
|
|
62
|
-
{ pattern: /^claude-(sonnet|haiku|opus)-4/, ceiling: 64_000 },
|
|
63
|
-
],
|
|
64
|
-
openai: [
|
|
65
|
-
{ pattern: /^(o1|o3|o4)-mini/, ceiling: 65_536 },
|
|
66
|
-
{ pattern: /^(o1|o3|o4)\b/, ceiling: 100_000 },
|
|
67
|
-
{ pattern: /^gpt-5/, ceiling: 128_000 },
|
|
68
|
-
{ pattern: /^gpt-4\.1/, ceiling: 32_768 },
|
|
69
|
-
{ pattern: /^gpt-4o/, ceiling: 16_384 },
|
|
70
|
-
{ pattern: /^gpt-4(-turbo)?$/, ceiling: 4_096 },
|
|
71
|
-
{ pattern: /^gpt-3\.5/, ceiling: 4_096 },
|
|
72
|
-
],
|
|
73
|
-
google: [
|
|
74
|
-
{ pattern: /^gemini-1\.5/, ceiling: 8_192 },
|
|
75
|
-
{ pattern: /^gemini-2\.0-flash/, ceiling: 8_192 },
|
|
76
|
-
{ pattern: /^gemini-2\.5/, ceiling: 65_536 },
|
|
77
|
-
],
|
|
78
|
-
};
|
|
79
|
-
/** Lowercase and strip Google's `models/` prefix so one key shape is used everywhere. */
|
|
80
|
-
export function normalizeModelId(modelId) {
|
|
81
|
-
return String(modelId ?? '').trim().toLowerCase().replace(/^models\//, '');
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* The statically known output ceiling for a model, or `undefined`.
|
|
85
|
-
*
|
|
86
|
-
* A MISS RETURNS `undefined`, NOT A NUMBER. "Unknown" and "small" must stay
|
|
87
|
-
* distinguishable: an unknown model gets the product default and, if that is
|
|
88
|
-
* wrong, recovery fixes it. Baking a pessimistic 8192 into every unrecognised id
|
|
89
|
-
* would silently halve the output of every proxy user.
|
|
90
|
-
*/
|
|
91
|
-
export function staticCeilingFor(providerId, modelId) {
|
|
92
|
-
const rules = CEILING_TABLE[String(providerId ?? '').toLowerCase()];
|
|
93
|
-
if (!rules)
|
|
94
|
-
return undefined;
|
|
95
|
-
const id = normalizeModelId(modelId);
|
|
96
|
-
if (id.length === 0)
|
|
97
|
-
return undefined;
|
|
98
|
-
for (const rule of rules) {
|
|
99
|
-
if (rule.pattern.test(id))
|
|
100
|
-
return rule.ceiling;
|
|
101
|
-
}
|
|
102
|
-
return undefined;
|
|
103
|
-
}
|
|
104
|
-
/** `'error'` outranks everything because it came from the API itself. */
|
|
105
|
-
const RANK = { catalog: 1, discovery: 2, error: 3 };
|
|
106
|
-
/** Process-lifetime only; never persisted. Key: `${providerId}:${normalizedModelId}`. */
|
|
107
|
-
const learnedCeilings = new Map();
|
|
108
|
-
function ceilingKey(providerId, modelId) {
|
|
109
|
-
return `${String(providerId ?? '').toLowerCase()}:${normalizeModelId(modelId)}`;
|
|
110
|
-
}
|
|
111
|
-
/** Record a ceiling. A lower-ranked source never overwrites a higher-ranked one. */
|
|
112
|
-
export function learnModelCeiling(providerId, modelId, ceiling, source) {
|
|
113
|
-
if (!Number.isFinite(ceiling) || ceiling <= 0)
|
|
114
|
-
return;
|
|
115
|
-
const key = ceilingKey(providerId, modelId);
|
|
116
|
-
if (key.endsWith(':'))
|
|
117
|
-
return; // no model id — nothing worth remembering
|
|
118
|
-
const existing = learnedCeilings.get(key);
|
|
119
|
-
if (existing && RANK[existing.source] > RANK[source])
|
|
120
|
-
return;
|
|
121
|
-
learnedCeilings.set(key, { ceiling: Math.floor(ceiling), source });
|
|
122
|
-
}
|
|
123
|
-
export function getLearnedCeiling(providerId, modelId) {
|
|
124
|
-
return learnedCeilings.get(ceilingKey(providerId, modelId));
|
|
125
|
-
}
|
|
126
|
-
/** Test hook. MUST be called from `afterEach` in every test that learns. */
|
|
127
|
-
export function clearLearnedCeilings() {
|
|
128
|
-
learnedCeilings.clear();
|
|
129
|
-
}
|
|
130
|
-
/** OpenAI charges `max_tokens` against the context window; the others do not. */
|
|
131
|
-
function providerUsesContextSum(providerId) {
|
|
132
|
-
return String(providerId ?? '').toLowerCase() === 'openai';
|
|
133
|
-
}
|
|
134
|
-
/** Step 1: the strongest ceiling anyone knows about, or `undefined`. */
|
|
135
|
-
function resolveCeiling(input) {
|
|
136
|
-
const learned = getLearnedCeiling(input.providerId, input.modelId);
|
|
137
|
-
if (learned)
|
|
138
|
-
return learned.ceiling;
|
|
139
|
-
const declared = input.modelLimits?.maxOutputTokens;
|
|
140
|
-
if (typeof declared === 'number' && Number.isFinite(declared) && declared > 0) {
|
|
141
|
-
return Math.floor(declared);
|
|
142
|
-
}
|
|
143
|
-
return staticCeilingFor(input.providerId, input.modelId);
|
|
144
|
-
}
|
|
145
|
-
/** Step 4: `max_tokens + prompt <= context` on the providers that enforce it. */
|
|
146
|
-
function contextBound(input) {
|
|
147
|
-
if (!providerUsesContextSum(input.providerId))
|
|
148
|
-
return undefined;
|
|
149
|
-
const window = input.modelLimits?.contextWindow;
|
|
150
|
-
const prompt = input.estimatedPromptTokens;
|
|
151
|
-
if (typeof window !== 'number' || !Number.isFinite(window) || window <= 0)
|
|
152
|
-
return undefined;
|
|
153
|
-
if (typeof prompt !== 'number' || !Number.isFinite(prompt) || prompt < 0)
|
|
154
|
-
return undefined;
|
|
155
|
-
return window - prompt - CONTEXT_SAFETY_MARGIN_TOKENS;
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* Step 6: keep Anthropic's `max_tokens > thinking.budget_tokens` invariant.
|
|
159
|
-
*
|
|
160
|
-
* Returns the (possibly raised) cap and the budget to send. A returned budget of
|
|
161
|
-
* `0` means "omit the thinking block entirely" — `budget_tokens` has a hard floor
|
|
162
|
-
* of 1024 and sending less is illegal, so refusing to think is the only legal
|
|
163
|
-
* move left on a model whose ceiling cannot house both.
|
|
164
|
-
*/
|
|
165
|
-
function fitThinking(value, thinkingBudget, ceiling) {
|
|
166
|
-
if (thinkingBudget <= 0 || value > thinkingBudget)
|
|
167
|
-
return { value };
|
|
168
|
-
const raised = Math.min(ceiling ?? Number.POSITIVE_INFINITY, thinkingBudget + THINKING_HEADROOM_TOKENS);
|
|
169
|
-
if (raised > thinkingBudget)
|
|
170
|
-
return { value: raised };
|
|
171
|
-
const lowered = Math.max(MIN_THINKING_BUDGET_TOKENS, raised - THINKING_HEADROOM_TOKENS);
|
|
172
|
-
if (lowered < raised)
|
|
173
|
-
return { value: raised, thinkingBudget: lowered };
|
|
174
|
-
return { value: raised, thinkingBudget: 0 };
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Resolve the output-token cap for one request.
|
|
178
|
-
*
|
|
179
|
-
* Pure apart from reading the learned map. Never throws, never returns `NaN`,
|
|
180
|
-
* `0` or a negative.
|
|
181
|
-
*/
|
|
182
|
-
export function resolveOutputTokens(input) {
|
|
183
|
-
const ceiling = resolveCeiling(input);
|
|
184
|
-
const requested = typeof input.requested === 'number' && Number.isFinite(input.requested) && input.requested > 0
|
|
185
|
-
? Math.floor(input.requested)
|
|
186
|
-
: undefined;
|
|
187
|
-
// AUTO NEVER EXCEEDS THE PRODUCT DEFAULT, even when the model would allow
|
|
188
|
-
// 100000: on OpenAI `max_tokens` is charged against the context window, so an
|
|
189
|
-
// AUTO of 100000 would make long conversations fail with a context error. An
|
|
190
|
-
// explicit `requested` may exceed 64000 up to the ceiling — the user's call.
|
|
191
|
-
//
|
|
192
|
-
// The AMBITION is kept separate from the clamp on purpose. Folding the ceiling
|
|
193
|
-
// into the AUTO base (`min(DEFAULT, ceiling)`) yields the same number but
|
|
194
|
-
// leaves `clampedBy` unset, and `clampedBy` is what the settings preview and
|
|
195
|
-
// the one-time warning are built on: the user would see a bare
|
|
196
|
-
// `Effective: 16384` with nothing saying where the other 47616 went.
|
|
197
|
-
const ambition = requested ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
198
|
-
let value = ambition;
|
|
199
|
-
let clampedBy;
|
|
200
|
-
if (ceiling !== undefined && ceiling < value) {
|
|
201
|
-
value = ceiling;
|
|
202
|
-
clampedBy = 'ceiling';
|
|
203
|
-
}
|
|
204
|
-
const bound = contextBound(input);
|
|
205
|
-
if (bound !== undefined && bound < value) {
|
|
206
|
-
value = bound;
|
|
207
|
-
clampedBy = 'context';
|
|
208
|
-
}
|
|
209
|
-
if (value > ABSOLUTE_MAX_OUTPUT_TOKENS) {
|
|
210
|
-
value = ABSOLUTE_MAX_OUTPUT_TOKENS;
|
|
211
|
-
clampedBy = 'absolute';
|
|
212
|
-
}
|
|
213
|
-
const fitted = fitThinking(value, input.thinkingBudget ?? 0, ceiling);
|
|
214
|
-
value = Math.floor(Math.max(fitted.value, MIN_MAX_OUTPUT_TOKENS));
|
|
215
|
-
return {
|
|
216
|
-
value,
|
|
217
|
-
...(ceiling !== undefined ? { ceiling } : {}),
|
|
218
|
-
source: requested !== undefined ? 'requested' : 'auto',
|
|
219
|
-
...(clampedBy ? { clampedBy } : {}),
|
|
220
|
-
...(fitted.thinkingBudget !== undefined ? { thinkingBudget: fitted.thinkingBudget } : {}),
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
// ---------------------------------------------------------------------------
|
|
224
|
-
// Prompt estimation
|
|
225
|
-
// ---------------------------------------------------------------------------
|
|
226
|
-
/**
|
|
227
|
-
* Average characters per token across the model families this package speaks to.
|
|
228
|
-
*
|
|
229
|
-
* EXPORTED (context-auto-compaction P2-3). It was module-private, which would
|
|
230
|
-
* have forced the CLI's compaction digest to grow a second copy for its budget
|
|
231
|
-
* arithmetic — two chars-per-token constants that must agree and nothing
|
|
232
|
-
* checking that they do is exactly how a digest budget and an occupancy estimate
|
|
233
|
-
* drift apart. No behaviour change here.
|
|
234
|
-
*/
|
|
235
|
-
export const CHARS_PER_TOKEN = 4;
|
|
236
|
-
/** Role markers, separators and tool-call scaffolding, per message. */
|
|
237
|
-
const PER_MESSAGE_OVERHEAD_TOKENS = 4;
|
|
238
|
-
function partLength(content) {
|
|
239
|
-
if (typeof content === 'string')
|
|
240
|
-
return content.length;
|
|
241
|
-
if (!Array.isArray(content))
|
|
242
|
-
return 0;
|
|
243
|
-
let total = 0;
|
|
244
|
-
for (const part of content) {
|
|
245
|
-
if (typeof part?.text === 'string')
|
|
246
|
-
total += part.text.length;
|
|
247
|
-
// Base64 image payloads are counted at a flat rate rather than by length:
|
|
248
|
-
// their character count says nothing useful about their token cost.
|
|
249
|
-
else if (part?.type === 'image')
|
|
250
|
-
total += CHARS_PER_TOKEN * IMAGE_TOKEN_ESTIMATE;
|
|
251
|
-
}
|
|
252
|
-
return total;
|
|
253
|
-
}
|
|
254
|
-
function messageLength(message) {
|
|
255
|
-
if (message.role === 'assistant') {
|
|
256
|
-
let total = 0;
|
|
257
|
-
for (const block of message.content) {
|
|
258
|
-
if (block.type === 'text' || block.type === 'thinking')
|
|
259
|
-
total += block.text.length;
|
|
260
|
-
else if (block.type === 'tool_call')
|
|
261
|
-
total += JSON.stringify(block.args ?? {}).length;
|
|
262
|
-
}
|
|
263
|
-
return total;
|
|
264
|
-
}
|
|
265
|
-
return partLength(message.content);
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Deliberately crude: ~4 chars/token plus per-message framing. Used ONLY to keep
|
|
269
|
-
* `max_tokens + prompt <= context` on OpenAI, where being 20 % wrong is absorbed
|
|
270
|
-
* by `CONTEXT_SAFETY_MARGIN_TOKENS` and, failing that, by `context_sum` recovery.
|
|
271
|
-
*
|
|
272
|
-
* No tokenizer dependency is added on purpose — this is a guard rail, not an
|
|
273
|
-
* accounting function.
|
|
274
|
-
*/
|
|
275
|
-
export function estimatePromptTokens(messages, systemPrompt) {
|
|
276
|
-
let chars = systemPrompt ? systemPrompt.length : 0;
|
|
277
|
-
let overhead = 0;
|
|
278
|
-
for (const message of messages ?? []) {
|
|
279
|
-
chars += messageLength(message);
|
|
280
|
-
overhead += PER_MESSAGE_OVERHEAD_TOKENS;
|
|
281
|
-
}
|
|
282
|
-
return Math.ceil(chars / CHARS_PER_TOKEN) + overhead;
|
|
283
|
-
}
|
|
1
|
+
(function(_0x1c9b3e,_0x4dbb5f){const _0x1ff61b=_0x46db,_0x251cdb=_0x1c9b3e();while(!![]){try{const _0x303ddc=-parseInt(_0x1ff61b(0xa6))/0x1*(-parseInt(_0x1ff61b(0xa9))/0x2)+parseInt(_0x1ff61b(0xa7))/0x3+-parseInt(_0x1ff61b(0x8a))/0x4+-parseInt(_0x1ff61b(0xab))/0x5+parseInt(_0x1ff61b(0xa3))/0x6+-parseInt(_0x1ff61b(0x83))/0x7+-parseInt(_0x1ff61b(0xa4))/0x8*(-parseInt(_0x1ff61b(0x93))/0x9);if(_0x303ddc===_0x4dbb5f)break;else _0x251cdb['push'](_0x251cdb['shift']());}catch(_0x450e50){_0x251cdb['push'](_0x251cdb['shift']());}}}(_0xd099,0x88a89));import{IMAGE_TOKEN_ESTIMATE}from'./image-tokens.js';export const DEFAULT_MAX_OUTPUT_TOKENS=0xfa00;export const MIN_MAX_OUTPUT_TOKENS=0x100;export const SAFE_FALLBACK_MAX_OUTPUT_TOKENS=0x2000;export const THINKING_HEADROOM_TOKENS=0x1000;export const ABSOLUTE_MAX_OUTPUT_TOKENS=0x30d40;export const CONTEXT_SAFETY_MARGIN_TOKENS=0x400;export const MIN_THINKING_BUDGET_TOKENS=0x400;const CEILING_TABLE={'anthropic':[{'pattern':/^claude-3-7-sonnet/,'ceiling':0xfa00},{'pattern':/^claude-3-5-sonnet/,'ceiling':0x2000},{'pattern':/^claude-3(-|\.)/,'ceiling':0x2000},{'pattern':/^claude-opus-4-(0|1)\b/,'ceiling':0x7d00},{'pattern':/^claude-(sonnet|haiku|opus)-4/,'ceiling':0xfa00}],'openai':[{'pattern':/^(o1|o3|o4)-mini/,'ceiling':0x10000},{'pattern':/^(o1|o3|o4)\b/,'ceiling':0x186a0},{'pattern':/^gpt-5/,'ceiling':0x1f400},{'pattern':/^gpt-4\.1/,'ceiling':0x8000},{'pattern':/^gpt-4o/,'ceiling':0x4000},{'pattern':/^gpt-4(-turbo)?$/,'ceiling':0x1000},{'pattern':/^gpt-3\.5/,'ceiling':0x1000}],'google':[{'pattern':/^gemini-1\.5/,'ceiling':0x2000},{'pattern':/^gemini-2\.0-flash/,'ceiling':0x2000},{'pattern':/^gemini-2\.5/,'ceiling':0x10000}]};export function normalizeModelId(_0x3483d1){const _0x2b3e63=_0x46db;return String(_0x3483d1??'')[_0x2b3e63(0x84)]()['toLowerCase']()[_0x2b3e63(0xa5)](/^models\//,'');}export function staticCeilingFor(_0x1fe42e,_0x30ccb0){const _0x4ae5ec=_0x46db,_0x33b0ec=CEILING_TABLE[String(_0x1fe42e??'')[_0x4ae5ec(0x9f)]()];if(!_0x33b0ec)return undefined;const _0x2d473b=normalizeModelId(_0x30ccb0);if(_0x2d473b[_0x4ae5ec(0x99)]===0x0)return undefined;for(const _0x30b9bd of _0x33b0ec){if(_0x30b9bd['pattern'][_0x4ae5ec(0xa0)](_0x2d473b))return _0x30b9bd[_0x4ae5ec(0xaf)];}return undefined;}const RANK={'catalog':0x1,'discovery':0x2,'error':0x3},learnedCeilings=new Map();function ceilingKey(_0x464d7d,_0x4012f8){const _0x34fc7e=_0x46db;return''[_0x34fc7e(0x8d)](String(_0x464d7d??'')[_0x34fc7e(0x9f)](),':')[_0x34fc7e(0x8d)](normalizeModelId(_0x4012f8));}export function learnModelCeiling(_0x49246f,_0x3c3a93,_0x257fdf,_0x1ca800){const _0x56c56d=_0x46db;if(!Number[_0x56c56d(0x9b)](_0x257fdf)||_0x257fdf<=0x0)return;const _0x128e10=ceilingKey(_0x49246f,_0x3c3a93);if(_0x128e10[_0x56c56d(0x90)](':'))return;const _0x14679f=learnedCeilings[_0x56c56d(0xac)](_0x128e10);if(_0x14679f&&RANK[_0x14679f[_0x56c56d(0x9d)]]>RANK[_0x1ca800])return;learnedCeilings['set'](_0x128e10,{'ceiling':Math[_0x56c56d(0x8b)](_0x257fdf),'source':_0x1ca800});}export function getLearnedCeiling(_0x548307,_0x546323){return learnedCeilings['get'](ceilingKey(_0x548307,_0x546323));}export function clearLearnedCeilings(){const _0x55f607=_0x46db;learnedCeilings[_0x55f607(0xa1)]();}function providerUsesContextSum(_0x589bec){const _0x26c8f0=_0x46db;return String(_0x589bec??'')[_0x26c8f0(0x9f)]()===_0x26c8f0(0x8c);}function _0xd099(){const _0x5d7cf3=['mte3ntiWnMzusK5Uta','Dg9VBf9JywXS','otGWnZvQtxLtveK','z2v0','CM9Szq','Bwf4t3v0Chv0vg9Rzw5Z','y2vPBgLUzW','DgHPBMTPBMC','y2vPBa','BNvTyMvY','C3rYAw5NAwz5','CMvXDwvZDgvK','nJa1nJG0mvfZzMHTvG','DhjPBq','DMfSDwu','Bwf4','zxn0Aw1HDgvKuhjVBxb0vg9Rzw5Z','yxnZAxn0yw50','BwLU','mZGWmZK4ne9iufnrsq','zMXVB3i','B3bLBMfP','y29Uy2f0','Dgv4Da','y29UDgv4DfDPBMrVDW','zw5KC1DPDgG','DgHPBMTPBMDcDwrNzxq','DhLWzq','mJG4BNzptMH4','y29UDgvUDa','yxjNCW','Bw9KzwXmAw1PDhm','Aw1Hz2u','Bw9KzwXjza','BgvUz3rO','ChjVDMLKzxjjza','AxngAw5PDgu','C3rYAw5N','C291CMnL','ue9tsvrjvKvFsu5gsu5jvfK','Dg9mB3DLCKnHC2u','DgvZDa','y2XLyxi','y29UDgv4Da','mJmZmJq1oeTZz2jovq','mtuZodq4r1Prz09w','CMvWBgfJzq','murkuvr3sW','mJqXmty2n3PYDKPbwG','AxnbCNjHEq'];_0xd099=function(){return _0x5d7cf3;};return _0xd099();}function resolveCeiling(_0x3399cb){const _0x5cd8b8=_0x46db,_0x1a582a=getLearnedCeiling(_0x3399cb[_0x5cd8b8(0x9a)],_0x3399cb[_0x5cd8b8(0x98)]);if(_0x1a582a)return _0x1a582a[_0x5cd8b8(0xaf)];const _0x3ee59f=_0x3399cb[_0x5cd8b8(0x96)]?.[_0x5cd8b8(0xae)];if(typeof _0x3ee59f===_0x5cd8b8(0xb2)&&Number[_0x5cd8b8(0x9b)](_0x3ee59f)&&_0x3ee59f>0x0)return Math['floor'](_0x3ee59f);return staticCeilingFor(_0x3399cb[_0x5cd8b8(0x9a)],_0x3399cb[_0x5cd8b8(0x98)]);}function _0x46db(_0x3104df,_0xfd5cad){_0x3104df=_0x3104df-0x83;const _0xd099b=_0xd099();let _0x46dba3=_0xd099b[_0x3104df];if(_0x46db['kMYXGN']===undefined){var _0x261783=function(_0x135bdd){const _0x4c34f9='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x14570a='',_0x3483d1='';for(let _0x1fe42e=0x0,_0x30ccb0,_0x33b0ec,_0x2d473b=0x0;_0x33b0ec=_0x135bdd['charAt'](_0x2d473b++);~_0x33b0ec&&(_0x30ccb0=_0x1fe42e%0x4?_0x30ccb0*0x40+_0x33b0ec:_0x33b0ec,_0x1fe42e++%0x4)?_0x14570a+=String['fromCharCode'](0xff&_0x30ccb0>>(-0x2*_0x1fe42e&0x6)):0x0){_0x33b0ec=_0x4c34f9['indexOf'](_0x33b0ec);}for(let _0x30b9bd=0x0,_0x464d7d=_0x14570a['length'];_0x30b9bd<_0x464d7d;_0x30b9bd++){_0x3483d1+='%'+('00'+_0x14570a['charCodeAt'](_0x30b9bd)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x3483d1);};_0x46db['JaNdDm']=_0x261783,_0x46db['hqudlx']={},_0x46db['kMYXGN']=!![];}const _0x3f8c8b=_0xd099b[0x0];_0x46db['zJOfNx']!==_0x3f8c8b&&(_0x46db['hqudlx']={},_0x46db['zJOfNx']=_0x3f8c8b);const _0x335d4d=_0x46db['hqudlx'][_0x3104df];return _0x335d4d===undefined?(_0x46dba3=_0x46db['JaNdDm'](_0x46dba3),_0x46db['hqudlx'][_0x3104df]=_0x46dba3):_0x46dba3=_0x335d4d,_0x46dba3;}function contextBound(_0x554caa){const _0x4ebd78=_0x46db;if(!providerUsesContextSum(_0x554caa['providerId']))return undefined;const _0x5401a8=_0x554caa[_0x4ebd78(0x96)]?.[_0x4ebd78(0x8f)],_0x50f38b=_0x554caa[_0x4ebd78(0x87)];if(typeof _0x5401a8!==_0x4ebd78(0xb2)||!Number[_0x4ebd78(0x9b)](_0x5401a8)||_0x5401a8<=0x0)return undefined;if(typeof _0x50f38b!==_0x4ebd78(0xb2)||!Number[_0x4ebd78(0x9b)](_0x50f38b)||_0x50f38b<0x0)return undefined;return _0x5401a8-_0x50f38b-CONTEXT_SAFETY_MARGIN_TOKENS;}function fitThinking(_0x5b352f,_0x23eebe,_0x2110a4){const _0x5952cb=_0x46db;if(_0x23eebe<=0x0||_0x5b352f>_0x23eebe)return{'value':_0x5b352f};const _0x41ff38=Math[_0x5952cb(0x89)](_0x2110a4??Number[_0x5952cb(0x9e)],_0x23eebe+THINKING_HEADROOM_TOKENS);if(_0x41ff38>_0x23eebe)return{'value':_0x41ff38};const _0x2510f4=Math[_0x5952cb(0x86)](MIN_THINKING_BUDGET_TOKENS,_0x41ff38-THINKING_HEADROOM_TOKENS);if(_0x2510f4<_0x41ff38)return{'value':_0x41ff38,'thinkingBudget':_0x2510f4};return{'value':_0x41ff38,'thinkingBudget':0x0};}export function resolveOutputTokens(_0x333ce5){const _0x408c4f=_0x46db,_0x47201a=resolveCeiling(_0x333ce5),_0x1c25b1=typeof _0x333ce5[_0x408c4f(0xb4)]==='number'&&Number[_0x408c4f(0x9b)](_0x333ce5[_0x408c4f(0xb4)])&&_0x333ce5[_0x408c4f(0xb4)]>0x0?Math[_0x408c4f(0x8b)](_0x333ce5[_0x408c4f(0xb4)]):undefined,_0x33da31=_0x1c25b1??DEFAULT_MAX_OUTPUT_TOKENS;let _0x4a60e4=_0x33da31,_0x5ccfe0;_0x47201a!==undefined&&_0x47201a<_0x4a60e4&&(_0x4a60e4=_0x47201a,_0x5ccfe0=_0x408c4f(0xaf));const _0x392144=contextBound(_0x333ce5);_0x392144!==undefined&&_0x392144<_0x4a60e4&&(_0x4a60e4=_0x392144,_0x5ccfe0=_0x408c4f(0xa2));_0x4a60e4>ABSOLUTE_MAX_OUTPUT_TOKENS&&(_0x4a60e4=ABSOLUTE_MAX_OUTPUT_TOKENS,_0x5ccfe0='absolute');const _0x4aa6d1=fitThinking(_0x4a60e4,_0x333ce5['thinkingBudget']??0x0,_0x47201a);return _0x4a60e4=Math['floor'](Math[_0x408c4f(0x86)](_0x4aa6d1[_0x408c4f(0x85)],MIN_MAX_OUTPUT_TOKENS)),{'value':_0x4a60e4,..._0x47201a!==undefined?{'ceiling':_0x47201a}:{},'source':_0x1c25b1!==undefined?_0x408c4f(0xb4):'auto',..._0x5ccfe0?{'clampedBy':_0x5ccfe0}:{},..._0x4aa6d1[_0x408c4f(0x91)]!==undefined?{'thinkingBudget':_0x4aa6d1[_0x408c4f(0x91)]}:{}};}export const CHARS_PER_TOKEN=0x4;const PER_MESSAGE_OVERHEAD_TOKENS=0x4;function partLength(_0x4a0119){const _0x57937f=_0x46db;if(typeof _0x4a0119===_0x57937f(0x9c))return _0x4a0119['length'];if(!Array[_0x57937f(0xa8)](_0x4a0119))return 0x0;let _0x17a066=0x0;for(const _0x952b34 of _0x4a0119){if(typeof _0x952b34?.[_0x57937f(0x8e)]===_0x57937f(0x9c))_0x17a066+=_0x952b34[_0x57937f(0x8e)][_0x57937f(0x99)];else{if(_0x952b34?.[_0x57937f(0x92)]===_0x57937f(0x97))_0x17a066+=CHARS_PER_TOKEN*IMAGE_TOKEN_ESTIMATE;}}return _0x17a066;}function messageLength(_0x3d7993){const _0x39f439=_0x46db;if(_0x3d7993[_0x39f439(0xad)]===_0x39f439(0x88)){let _0x4bce12=0x0;for(const _0x5d7f69 of _0x3d7993[_0x39f439(0x94)]){if(_0x5d7f69['type']===_0x39f439(0x8e)||_0x5d7f69['type']===_0x39f439(0xb0))_0x4bce12+=_0x5d7f69[_0x39f439(0x8e)]['length'];else{if(_0x5d7f69['type']===_0x39f439(0xaa))_0x4bce12+=JSON[_0x39f439(0xb3)](_0x5d7f69[_0x39f439(0x95)]??{})[_0x39f439(0x99)];}}return _0x4bce12;}return partLength(_0x3d7993[_0x39f439(0x94)]);}export function estimatePromptTokens(_0x3e68c6,_0x4dd138){const _0x57a3ee=_0x46db;let _0x56b6a2=_0x4dd138?_0x4dd138[_0x57a3ee(0x99)]:0x0,_0x4fdae3=0x0;for(const _0x164811 of _0x3e68c6??[]){_0x56b6a2+=messageLength(_0x164811),_0x4fdae3+=PER_MESSAGE_OVERHEAD_TOKENS;}return Math[_0x57a3ee(0xb1)](_0x56b6a2/CHARS_PER_TOKEN)+_0x4fdae3;}
|