@yanzc/claude-pro 0.9.0 → 0.9.1
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/README.md +342 -320
- package/package.json +1 -2
- package/src/agent.js +79 -13
- package/src/agents.js +3 -2
- package/src/api.js +39 -34
- package/src/browser/broker.js +367 -0
- package/src/browser/cdp.js +114 -0
- package/src/browser/render.js +242 -0
- package/src/browser/session.js +948 -0
- package/src/browser/snapshot.js +212 -0
- package/src/cache.js +1 -1
- package/src/checkpoints.js +1 -0
- package/src/commands.js +169 -67
- package/src/compaction.js +75 -0
- package/src/config.js +143 -143
- package/src/context.js +45 -18
- package/src/filestate.js +2 -1
- package/src/gateway.js +208 -164
- package/src/hooks.js +2 -2
- package/src/keepalive.js +1 -1
- package/src/main.js +52 -40
- package/src/mcp.js +2 -2
- package/src/peers.js +1 -10
- package/src/print.js +9 -3
- package/src/prompt-profiles.js +0 -6
- package/src/prompts.js +5 -61
- package/src/ratelimit.js +2 -4
- package/src/remote.js +26 -10
- package/src/runtime.js +33 -10
- package/src/selfcheck.js +3 -3
- package/src/session.js +93 -3
- package/src/supervisor.js +10 -1
- package/src/tools/bash.js +18 -17
- package/src/tools/browser.js +365 -0
- package/src/tools/code.js +430 -0
- package/src/tools/effort.js +3 -4
- package/src/tools/files.js +92 -19
- package/src/tools/index.js +6 -0
- package/src/tools/notebook.js +11 -4
- package/src/tools/processes.js +274 -0
- package/src/tools/search.js +33 -8
- package/src/tools/web.js +316 -46
- package/src/trace.js +0 -4
- package/src/ui/ansi.js +92 -13
- package/src/ui/dialogs.js +16 -54
- package/src/ui/editor.js +231 -34
- package/src/ui/markdown.js +1 -2
- package/src/ui/render.js +1 -2
- package/src/ui/repl.js +185 -104
- package/src/ui/screen.js +139 -31
- package/src/updater.js +135 -165
- package/src/utils/clipboard.js +5 -3
- package/src/utils/paths.js +15 -17
- package/src/utils/shell.js +66 -11
- package/.env.example +0 -29
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "claude-pro: a command line coding agent for the codex-gateway. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -21,7 +21,6 @@
|
|
|
21
21
|
"files": [
|
|
22
22
|
"bin/",
|
|
23
23
|
"src/",
|
|
24
|
-
".env.example",
|
|
25
24
|
"README.md",
|
|
26
25
|
"LICENSE"
|
|
27
26
|
],
|
package/src/agent.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { streamMessage, contextTokens, isAbort } from './api.js';
|
|
7
|
-
import {
|
|
7
|
+
import { loadGatewayModels } from './gateway.js';
|
|
8
|
+
import { compactPrompt, partialCompactPrompt, partialSummaryMessage, continuationMessage, keptUserMessagesIn, SUMMARY_SYSTEM } from './compaction.js';
|
|
8
9
|
import { toolResultsDir } from './session.js';
|
|
9
10
|
import { rebuildFileState } from './filestate.js';
|
|
10
11
|
import { CacheStats, TTL_MS } from './cache.js';
|
|
@@ -143,6 +144,49 @@ function toBlocks(content) {
|
|
|
143
144
|
return typeof content === 'string' ? [{ type: 'text', text: content }] : content;
|
|
144
145
|
}
|
|
145
146
|
|
|
147
|
+
// How much of the user's own messages a compaction keeps word for word, in estimated tokens (Codex keeps 20k).
|
|
148
|
+
const KEPT_USER_TOKENS = 20_000;
|
|
149
|
+
// Text the program puts in a user message, not the user: notes for the model, reports of background agents and of
|
|
150
|
+
// other sessions, bash mode, interruptions. The summaries of earlier compactions are read for the messages they kept.
|
|
151
|
+
const PROGRAM_TEXT = /^(?:<(?:system-reminder|task-notification|peer-message|bash-input)\b|\[Request interrupted by user)/;
|
|
152
|
+
const SUMMARY_TEXT = /^(?:This session is being continued|\[Summarized conversation\])/;
|
|
153
|
+
// The note a restarted session goes on with (see restartNote), in front of what the user had queued meanwhile: not the
|
|
154
|
+
// user's either, and in a session that restarts often those notes took the room of what the user wrote.
|
|
155
|
+
const RESTART_NOTE = /^\[claude-pro restarted[\s\S]*?\](?:\n\n|$)/;
|
|
156
|
+
|
|
157
|
+
// The user's own messages in `messages`, oldest first, to keep word for word through a compaction as Codex does: what
|
|
158
|
+
// they typed ("[image]" for a picture) and what earlier summaries kept. The newest that fit in `budget` estimated
|
|
159
|
+
// tokens are kept whole, the next one shortened in the middle to what is left (when that is worth it), none older.
|
|
160
|
+
export function keptUserMessages(messages, budget = KEPT_USER_TOKENS) {
|
|
161
|
+
const all = [];
|
|
162
|
+
for (const m of messages) {
|
|
163
|
+
if (m.role !== 'user') continue;
|
|
164
|
+
const typed = [];
|
|
165
|
+
for (const b of toBlocks(m.content)) {
|
|
166
|
+
if (b.type === 'image') { typed.push('[image]'); continue; }
|
|
167
|
+
if (b.type !== 'text') continue;
|
|
168
|
+
const text = (b.text || '').replace(RESTART_NOTE, '');
|
|
169
|
+
if (!text.trim() || PROGRAM_TEXT.test(text)) continue;
|
|
170
|
+
if (SUMMARY_TEXT.test(text)) all.push(...keptUserMessagesIn(text));
|
|
171
|
+
else typed.push(text);
|
|
172
|
+
}
|
|
173
|
+
if (typed.length) all.push(typed.join('\n'));
|
|
174
|
+
}
|
|
175
|
+
const kept = [];
|
|
176
|
+
let left = budget;
|
|
177
|
+
for (let i = all.length - 1; i >= 0 && left > 0; i--) {
|
|
178
|
+
const text = all[i];
|
|
179
|
+
const tokens = estimateTokens(text);
|
|
180
|
+
if (tokens <= left) { kept.push(text); left -= tokens; continue; }
|
|
181
|
+
if (left >= 200) {
|
|
182
|
+
const half = Math.floor(text.length * left / tokens / 2);
|
|
183
|
+
kept.push(`${text.slice(0, half)}\n[… ${text.length - 2 * half} characters left out …]\n${text.slice(text.length - half)}`);
|
|
184
|
+
}
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
return kept.reverse();
|
|
188
|
+
}
|
|
189
|
+
|
|
146
190
|
// Merge consecutive same-role messages and drop empties so the API always sees a valid sequence.
|
|
147
191
|
export function normalizeMessages(messages) {
|
|
148
192
|
const out = [];
|
|
@@ -305,6 +349,7 @@ export class Agent {
|
|
|
305
349
|
this.projectRoot = cwd;
|
|
306
350
|
this.cwd = cwd;
|
|
307
351
|
this.lastContextTokens = 0;
|
|
352
|
+
this.usageModel = null; // the model whose usage report last set lastContextTokens (see shouldAutoCompact)
|
|
308
353
|
this.tokensSinceUsage = 0;
|
|
309
354
|
this.heldTokens = 0; // room taken by tool results not yet in the conversation (see takeContext)
|
|
310
355
|
// What this agent's own requests used. `requests` counts the turns' requests; the summary requests of
|
|
@@ -337,7 +382,7 @@ export class Agent {
|
|
|
337
382
|
// Tokens the context can still take before it reaches the auto-compaction threshold: what a Read with allow_large
|
|
338
383
|
// may use (a larger one would be compacted away right after it was read).
|
|
339
384
|
contextRoom() {
|
|
340
|
-
return this.config.
|
|
385
|
+
return this.config.compactWindow(this.model, this.compactWindow) - this.contextEstimate - this.heldTokens;
|
|
341
386
|
}
|
|
342
387
|
|
|
343
388
|
// Claim room for a tool result that is about to be added. Read-only tools run in parallel, so what each one
|
|
@@ -394,7 +439,7 @@ export class Agent {
|
|
|
394
439
|
cache: {
|
|
395
440
|
bucket: cacheBucket,
|
|
396
441
|
messages: Boolean(cacheMessages),
|
|
397
|
-
caching: !this.config.promptCachingDisabled(
|
|
442
|
+
caching: !this.config.promptCachingDisabled(),
|
|
398
443
|
ttl: this.config.cacheTtl(cacheBucket),
|
|
399
444
|
},
|
|
400
445
|
compaction_id: compactionId,
|
|
@@ -619,7 +664,7 @@ export class Agent {
|
|
|
619
664
|
this.busy++; // undone in the finally below
|
|
620
665
|
try {
|
|
621
666
|
if (!this.isSubagent) {
|
|
622
|
-
this.beforeTurn?.();
|
|
667
|
+
await this.beforeTurn?.();
|
|
623
668
|
this.endEffortBoost();
|
|
624
669
|
this.noteUserTurn(userContent);
|
|
625
670
|
}
|
|
@@ -651,6 +696,9 @@ export class Agent {
|
|
|
651
696
|
let compactedForError = false;
|
|
652
697
|
let finalText = '';
|
|
653
698
|
for (;;) {
|
|
699
|
+
// The model's window may come from the gateway's model list (see Config.resolveModel): loaded before the check,
|
|
700
|
+
// or a resumed conversation is measured against a guess (deepseek-v4.1-flash was compacted at 160k of its 1M).
|
|
701
|
+
await loadGatewayModels(this.config, signal);
|
|
654
702
|
if (signal?.aborted) return tracedReturn(this.handleInterrupt(null));
|
|
655
703
|
if (this.shouldAutoCompact()) {
|
|
656
704
|
const outcome = await this.compactOnTheWay(signal);
|
|
@@ -693,6 +741,7 @@ export class Agent {
|
|
|
693
741
|
continue;
|
|
694
742
|
}
|
|
695
743
|
const queued = [...toQueuedBlocks(this.io.takeQueued?.() || []), ...(this.isSubagent ? [] : this.drainNotifications())];
|
|
744
|
+
await fitImagesIn(queued); // a pasted photo at full size: scaled now, not after the API refuses it
|
|
696
745
|
if (queued.length) {
|
|
697
746
|
this.pushMessage({ role: 'user', content: queued });
|
|
698
747
|
continue;
|
|
@@ -730,14 +779,21 @@ export class Agent {
|
|
|
730
779
|
continue;
|
|
731
780
|
}
|
|
732
781
|
}
|
|
733
|
-
|
|
782
|
+
// A refusal (stop_reason "refusal") comes without text too, but the model did not just fall silent: it declined
|
|
783
|
+
// the request, and the same request, or "go on" after it, is usually declined again. Said as such, with what
|
|
784
|
+
// helps, as Claude Code does: the message reworded, or the context that led to it left out.
|
|
785
|
+
if (!text) {
|
|
786
|
+
this.io.notice?.(stopReason !== 'refusal' ? 'The model ended its turn without a reply.'
|
|
787
|
+
: `The model declined this request (stop_reason: refusal) and gave no reply.${this.isSubagent ? '' : ' Press esc twice to go back and reword the message, or /compact or /clear to leave out the context that led to it.'}`, 'warn');
|
|
788
|
+
}
|
|
734
789
|
return tracedReturn({ text: finalText, interrupted: false });
|
|
735
790
|
}
|
|
736
791
|
|
|
737
792
|
const outcome = await this.runTools(toolUses, signal);
|
|
738
793
|
const resultContent = [...outcome.results];
|
|
739
|
-
const queued = this.io.takeQueued?.() || [];
|
|
740
|
-
|
|
794
|
+
const queued = toQueuedBlocks(this.io.takeQueued?.() || []);
|
|
795
|
+
await fitImagesIn(queued);
|
|
796
|
+
resultContent.push(...queued);
|
|
741
797
|
if (!this.isSubagent) resultContent.push(...this.drainNotifications());
|
|
742
798
|
if (outcome.interrupted) {
|
|
743
799
|
resultContent.push({ type: 'text', text: INTERRUPT_TOOL_MESSAGE });
|
|
@@ -765,9 +821,13 @@ export class Agent {
|
|
|
765
821
|
}
|
|
766
822
|
|
|
767
823
|
shouldAutoCompact() {
|
|
768
|
-
if (
|
|
824
|
+
if (this.messages.length <= 2) return false;
|
|
769
825
|
if (this.compactFailures >= MAX_COMPACT_FAILURES) return false;
|
|
770
|
-
|
|
826
|
+
// A count reported by another model (the user switched) is in another tokenizer's tokens: Opus counted 304k where
|
|
827
|
+
// GPT had counted 207k of the same conversation, and GPT compacted at once. The next request measures it instead;
|
|
828
|
+
// a conversation too long for this model is compacted on the error.
|
|
829
|
+
if (this.usageModel && this.usageModel !== this.model.id) return false;
|
|
830
|
+
const threshold = this.config.compactWindow(this.model, this.compactWindow);
|
|
771
831
|
if (this.contextEstimate < threshold) return false;
|
|
772
832
|
// Right after a compaction the base context (system prompt, tools, summary) may itself be
|
|
773
833
|
// near a very small window; require real growth so we don't compact on every step.
|
|
@@ -862,6 +922,7 @@ export class Agent {
|
|
|
862
922
|
onEvent: (ev) => this.io.streamEvent?.(ev, this),
|
|
863
923
|
});
|
|
864
924
|
this.lastContextTokens = contextTokens(res.usage);
|
|
925
|
+
this.usageModel = request.model.id;
|
|
865
926
|
this.tokensSinceUsage = 0;
|
|
866
927
|
if (this.postCompactTokens === null) this.postCompactTokens = this.lastContextTokens;
|
|
867
928
|
return res;
|
|
@@ -949,7 +1010,10 @@ export class Agent {
|
|
|
949
1010
|
const fail = (content, extra = {}) => finish({ block: { type: 'tool_result', tool_use_id: tu.id, is_error: true, content }, ...extra }, { error: true, ...extra });
|
|
950
1011
|
try {
|
|
951
1012
|
if (!tool) return fail(`Error: No such tool available: ${tu.name}`, { error_type: 'unknown_tool' });
|
|
952
|
-
|
|
1013
|
+
// A copy: validation turns numbers sent as strings into numbers, and the tool_use block must stay as it was sent
|
|
1014
|
+
// and saved, or a restarted session sends it differently and the prompt cache misses from there on.
|
|
1015
|
+
const own = tu.input && typeof tu.input === 'object' ? { ...tu.input } : (tu.input || {});
|
|
1016
|
+
const input = tool.normalizeInput && tu.input && typeof tu.input === 'object' ? tool.normalizeInput(own) : own;
|
|
953
1017
|
if (input.__invalid_json !== undefined) {
|
|
954
1018
|
return fail('Error: the tool input was not valid JSON (it may have been truncated by the output token limit). Try again with a smaller input, e.g. write large files in several steps.', { validation_error: true, error_type: 'invalid_json' });
|
|
955
1019
|
}
|
|
@@ -1151,8 +1215,9 @@ export class Agent {
|
|
|
1151
1215
|
throw err;
|
|
1152
1216
|
}
|
|
1153
1217
|
const state = this.compactWorkState(res);
|
|
1154
|
-
const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary, state.state) }] };
|
|
1218
|
+
const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary, state.state, keptUserMessages(part === 'before' ? before : after)) }] };
|
|
1155
1219
|
this.replaceMessages(part === 'before' ? [note, ...after] : [...before, note]);
|
|
1220
|
+
this.fileState.clear(); // the files read in the part summarized are not in view any more: Write wants them read again
|
|
1156
1221
|
if (part === 'before') this.cache.noteCompacted(); // from its first message on: nothing of it is cached (the start of "after" still is)
|
|
1157
1222
|
if (part === 'after') this.todos = []; // what they were about may be summarized away; the model keeps them in the summary
|
|
1158
1223
|
this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
|
|
@@ -1191,9 +1256,10 @@ export class Agent {
|
|
|
1191
1256
|
}
|
|
1192
1257
|
const state = this.compactWorkState(res);
|
|
1193
1258
|
const todoNote = this.todos.length ? `\n\n<system-reminder>Current todo list:\n${this.todos.map((t) => `- [${t.status}] ${t.content}`).join('\n')}</system-reminder>` : '';
|
|
1194
|
-
|
|
1259
|
+
const userMessages = keptUserMessages(this.messages);
|
|
1260
|
+
this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto, workState: state.state, workStateWarning: state.warning, userMessages }) + todoNote }] }]);
|
|
1195
1261
|
this.cache.noteCompacted();
|
|
1196
|
-
this.refreshSystemPrompt?.(); // the conversation starts over: it may start from a freshly built system prompt
|
|
1262
|
+
await this.refreshSystemPrompt?.(); // the conversation starts over: it may start from a freshly built system prompt
|
|
1197
1263
|
this.fileState.clear();
|
|
1198
1264
|
if (!this.isSubagent) this.checkpoints?.markConversationStale(); // the checkpoints are the main conversation's: a sub-agent's own compaction does not end them
|
|
1199
1265
|
this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
|
package/src/agents.js
CHANGED
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { CONFIG_DIR } from './config.js';
|
|
7
|
+
import { CLAUDE_EFFORTS } from './api.js';
|
|
7
8
|
|
|
8
9
|
const READ_ONLY_TOOLS = ['Glob', 'Grep', 'Read', 'Bash', 'WebFetch', 'WebSearch', 'BashOutput'];
|
|
9
|
-
// The effort levels a Task call or an agent definition may ask for (as Claude Code's Agent tool takes them).
|
|
10
|
-
export const EFFORTS =
|
|
10
|
+
// The effort levels a Task call or an agent definition may ask for (as Claude Code's Agent tool takes them): Claude's.
|
|
11
|
+
export const EFFORTS = CLAUDE_EFFORTS;
|
|
11
12
|
|
|
12
13
|
export const BUILTIN_AGENTS = [
|
|
13
14
|
{
|
package/src/api.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Thin layer over the Anthropic SDK: builds request params from config and turns the
|
|
2
2
|
// raw SSE stream into a fully assembled assistant message while reporting progress.
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
// The SDK is loaded with the first request: importing it took about 70 ms of every start, restarts included.
|
|
5
|
+
let Anthropic = null;
|
|
6
|
+
import { parseRateLimit, parseRetryAfter, planRetry, sleepUntil, timing } from './ratelimit.js';
|
|
6
7
|
import { cacheControl, cachePlanOf, fingerprint } from './cache.js';
|
|
7
|
-
import { gatewayLogin,
|
|
8
|
+
import { gatewayLogin, loadGatewayModels, cachedGatewayModel, gatewayEffort, gatewayDefaultEffort, nearestEffort } from './gateway.js';
|
|
8
9
|
import { fitImagesIn } from './utils/images.js';
|
|
9
10
|
import { costOf } from './pricing.js';
|
|
10
11
|
|
|
@@ -13,13 +14,13 @@ const SIGNATURE_PREFIX = 'cgw1:';
|
|
|
13
14
|
|
|
14
15
|
// The gateway provider's key, from /login. Without one the request fails the way a refused key does.
|
|
15
16
|
function gatewayKey(config) {
|
|
16
|
-
const
|
|
17
|
-
const key = login?.apiKey || config.env.CLAUDE_PRO_GATEWAY_API_KEY;
|
|
17
|
+
const key = gatewayLogin(config.gatewayUrl)?.apiKey;
|
|
18
18
|
if (!key) throw new APIError(`Not logged in to the gateway ${config.gatewayUrl}. Run /login and choose the gateway.`, { status: 401, retryable: false });
|
|
19
19
|
return key;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
export function getClient(config) {
|
|
22
|
+
export async function getClient(config) {
|
|
23
|
+
Anthropic ??= (await import('@anthropic-ai/sdk')).default;
|
|
23
24
|
const authToken = gatewayKey(config);
|
|
24
25
|
const key = `${config.gatewayUrl}|${authToken}|${config.apiTimeout}`;
|
|
25
26
|
if (cached?.key === key && cached.fetch === globalThis.fetch) return cached.client;
|
|
@@ -108,14 +109,7 @@ const thinkingStaysOn = new Set();
|
|
|
108
109
|
|
|
109
110
|
// The effort a model uses when none is sent (docs.claude.com, "Effort"): medium on Opus 5.5 and Haiku 5.5, high on
|
|
110
111
|
// the other models that take one; null for a model that takes none or is not known.
|
|
111
|
-
const gatewayModelInfo = (config, id) => cachedGatewayModel(gatewayLogin(config.gatewayUrl
|
|
112
|
-
const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
|
|
113
|
-
const nearestEffort = (effort, supported) => {
|
|
114
|
-
if (!effort || !supported.length || supported.includes(effort)) return effort;
|
|
115
|
-
const want = EFFORT_ORDER.indexOf(effort);
|
|
116
|
-
return supported.reduce((best, item) => Math.abs(EFFORT_ORDER.indexOf(item) - want) < Math.abs(EFFORT_ORDER.indexOf(best) - want) ? item : best, supported[0]);
|
|
117
|
-
};
|
|
118
|
-
|
|
112
|
+
const gatewayModelInfo = (config, id) => cachedGatewayModel(gatewayLogin(config.gatewayUrl), id);
|
|
119
113
|
export function defaultEffort(modelId, config = null) {
|
|
120
114
|
const id = String(modelId || '');
|
|
121
115
|
if (!effortSupported(id)) return null;
|
|
@@ -181,7 +175,7 @@ function withoutCodexThinking(messages) {
|
|
|
181
175
|
export function buildParams(config, { model, system, messages, tools, maxTokens, effort, cacheBucket = 'main', cacheMessages = true }) {
|
|
182
176
|
const wanted = maxTokens || config.maxOutputTokens;
|
|
183
177
|
const refused = cacheRefused.get(cacheKey(config, model.id));
|
|
184
|
-
const caching = !config.promptCachingDisabled(
|
|
178
|
+
const caching = !config.promptCachingDisabled();
|
|
185
179
|
const ttl = refused?.has('ttl') ? '5m' : config.cacheTtl(cacheBucket);
|
|
186
180
|
const mark = (place) => (caching && !refused?.has(place) ? { ...cacheControl(ttl) } : null);
|
|
187
181
|
const systemMark = mark('system');
|
|
@@ -192,7 +186,9 @@ export function buildParams(config, { model, system, messages, tools, maxTokens,
|
|
|
192
186
|
const params = {
|
|
193
187
|
model: model.id,
|
|
194
188
|
max_tokens: outputCaps.has(model.id) ? Math.min(wanted, outputCaps.get(model.id)) : wanted,
|
|
195
|
-
system
|
|
189
|
+
// An empty system prompt (an empty profile chosen with /prompts) is left out: Anthropic refuses an empty text
|
|
190
|
+
// block ("cache_control cannot be set for empty text blocks"), and DeepSeek and the others take none as well.
|
|
191
|
+
...(typeof system === 'string' && system.trim() ? { system: [{ type: 'text', text: system, ...(systemMark ? { cache_control: systemMark } : {}) }] } : {}),
|
|
196
192
|
messages: withCacheControl(messages, cacheMessages ? mark('messages') : null),
|
|
197
193
|
stream: true,
|
|
198
194
|
};
|
|
@@ -223,14 +219,17 @@ export class APIError extends Error {
|
|
|
223
219
|
}
|
|
224
220
|
|
|
225
221
|
function describeError(err, config) {
|
|
226
|
-
if (err?.name === 'AbortError' || err instanceof Anthropic.APIUserAbortError) return err;
|
|
222
|
+
if (err?.name === 'AbortError' || (Anthropic && err instanceof Anthropic.APIUserAbortError)) return err;
|
|
227
223
|
const status = err?.status;
|
|
228
224
|
let msg = err?.error?.error?.message || err?.error?.message || err?.message || String(err);
|
|
229
|
-
const promptTooLong = /prompt is too long|context length|maximum context|too many tokens|context_length_exceeded/i.test(msg);
|
|
225
|
+
const promptTooLong = /prompt is too long|context length|maximum context|too many tokens|context_length_exceeded|exceeds the context window/i.test(msg);
|
|
230
226
|
if (err instanceof APIError) return err;
|
|
231
227
|
if (status === 401) msg = `The gateway refused the login (401). Run /login to log in again. ${msg}`;
|
|
232
228
|
if (status === 402) msg = `The gateway account's balance is too low for this request. Top up at ${config.gatewayUrl}/user (or run /login to check the balance). ${msg}`;
|
|
233
|
-
|
|
229
|
+
// A prompt over the window fails the same way every time, so it is not retried: the agent compacts at once. Through
|
|
230
|
+
// the gateway a GPT overflow comes in the stream, without a 4xx: "Your input exceeds the context window of this
|
|
231
|
+
// model. ... (context_length_exceeded)", and was sent 6 more times, with the waits in between, before compacting.
|
|
232
|
+
const retryable = !promptTooLong && (!status || status === 408 || status === 409 || status === 429 || status >= 500);
|
|
234
233
|
const header = typeof err?.headers?.get === 'function' ? err.headers.get('retry-after') : err?.headers?.['retry-after'];
|
|
235
234
|
const overloaded = status === 529 || (err?.error?.error?.type || err?.error?.type) === 'overloaded_error';
|
|
236
235
|
return new APIError(msg, { status, retryable, promptTooLong, retryAfterMs: parseRetryAfter(header), rateLimit: parseRateLimit(err?.headers, timing.now()), overloaded });
|
|
@@ -239,7 +238,7 @@ function describeError(err, config) {
|
|
|
239
238
|
// Our own aborts are named AbortError and the SDK's is an APIUserAbortError. The message test only
|
|
240
239
|
// accepts the bare "aborted" wording: a server error that merely mentions "aborted" is not the user.
|
|
241
240
|
export function isAbort(err) {
|
|
242
|
-
return err?.name === 'AbortError' || err instanceof Anthropic.APIUserAbortError || /^(?:request was )?aborted\.?$/i.test(err?.message || '');
|
|
241
|
+
return err?.name === 'AbortError' || (Anthropic !== null && err instanceof Anthropic.APIUserAbortError) || /^(?:request was )?aborted\.?$/i.test(err?.message || '');
|
|
243
242
|
}
|
|
244
243
|
|
|
245
244
|
// USD for a request at the list prices (see pricing.js), by the model that answered, else the one asked for;
|
|
@@ -267,19 +266,15 @@ function charge(config, requested, served, usage) {
|
|
|
267
266
|
export async function streamMessage(config, request, { signal, onEvent = () => {}, waitForRateLimit = true } = {}) {
|
|
268
267
|
if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
|
|
269
268
|
// Load gateway model metadata before the synchronous parameter builder; the cache is keyed by gateway and key,
|
|
270
|
-
// so changing accounts or gateway URLs cannot leak a model's effort levels into another context.
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
try { await fetchGatewayModels(login, { signal }); } catch { if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] }); }
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
const client = getClient(config);
|
|
269
|
+
// so changing accounts or gateway URLs cannot leak a model's effort levels into another context. A gateway that
|
|
270
|
+
// does not answer costs at most a few seconds once (see fetchGatewayModels), not the request.
|
|
271
|
+
await loadGatewayModels(config, signal);
|
|
272
|
+
if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
|
|
273
|
+
const client = await getClient(config);
|
|
279
274
|
const params = buildParams(config, request);
|
|
280
275
|
// The gateway keeps a conversation on the upstream account that served it, where its prompt cache is; the
|
|
281
276
|
// session id names the conversation, in the header Claude Code sends it in.
|
|
282
|
-
const options = { signal, ...(config.
|
|
277
|
+
const options = { signal, ...(config.sessionId ? { headers: { 'X-Claude-Code-Session-Id': config.sessionId } } : {}) };
|
|
283
278
|
let imagesFitted = false;
|
|
284
279
|
const refused = new Set(); // what the endpoint refused for this request: remembered once a request got through
|
|
285
280
|
const retryState = { attempt: 0, rateLimitHits: 0, waitedMs: 0, overloaded: 0, overloadedWaitMs: 0 };
|
|
@@ -311,7 +306,8 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
311
306
|
break;
|
|
312
307
|
case 'content_block_start': {
|
|
313
308
|
const b = { ...ev.content_block };
|
|
314
|
-
|
|
309
|
+
// (server_tool_use: a search the model ran on the server, in WebSearch's request; its input is the query)
|
|
310
|
+
if (b.type === 'tool_use' || b.type === 'server_tool_use') { b.input = {}; jsonBufs[ev.index] = ''; }
|
|
315
311
|
if (b.type === 'text') b.text = b.text || '';
|
|
316
312
|
if (b.type === 'thinking') { b.thinking = b.thinking || ''; b.signature = b.signature || ''; }
|
|
317
313
|
blocks[ev.index] = b;
|
|
@@ -326,6 +322,8 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
326
322
|
if (d.type === 'text_delta') { b.text += d.text; onEvent({ type: 'text', index: ev.index, text: d.text }); }
|
|
327
323
|
else if (d.type === 'thinking_delta') { b.thinking += d.thinking; onEvent({ type: 'thinking', index: ev.index, text: d.thinking }); }
|
|
328
324
|
else if (d.type === 'signature_delta') b.signature = (b.signature || '') + d.signature;
|
|
325
|
+
// where a text block's statement comes from, in a web search answer: kept (see WebSearch)
|
|
326
|
+
else if (d.type === 'citations_delta') (b.citations ||= []).push(d.citation);
|
|
329
327
|
else if (d.type === 'input_json_delta') {
|
|
330
328
|
jsonBufs[ev.index] += d.partial_json;
|
|
331
329
|
onEvent({ type: 'tool_input', index: ev.index, partial: jsonBufs[ev.index], block: b });
|
|
@@ -334,7 +332,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
334
332
|
}
|
|
335
333
|
case 'content_block_stop': {
|
|
336
334
|
const b = blocks[ev.index];
|
|
337
|
-
if (b?.type === 'tool_use') {
|
|
335
|
+
if (b?.type === 'tool_use' || b?.type === 'server_tool_use') {
|
|
338
336
|
const raw = jsonBufs[ev.index];
|
|
339
337
|
try { b.input = raw ? JSON.parse(raw) : {}; } catch { b.input = { __invalid_json: raw }; }
|
|
340
338
|
}
|
|
@@ -365,12 +363,19 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
365
363
|
const cost = charge(config, params.model, model, usage);
|
|
366
364
|
return { message: { role: 'assistant', content }, usage, stopReason, model, cost, cache: { ...cachePlanOf(params), fingerprint: fingerprint(params), at: startedAt } };
|
|
367
365
|
} catch (raw) {
|
|
368
|
-
|
|
369
|
-
|
|
366
|
+
// A reply cut off (interrupted, or failed on the way: a stream error, a stream that ended early) is billed for
|
|
367
|
+
// what it had read and written once it started: the output so far is estimated. A failure before it started
|
|
368
|
+
// (an error status) costs nothing.
|
|
369
|
+
const chargeCut = () => {
|
|
370
|
+
if (usage.input_tokens == null) return;
|
|
370
371
|
const written = blocks.reduce((n, b) => n + (b?.text?.length || 0) + (b?.thinking?.length || 0), 0) + jsonBufs.join('').length;
|
|
371
372
|
charge(config, params.model, model, { ...usage, output_tokens: Math.max(usage.output_tokens || 0, Math.ceil(written / 4)) });
|
|
373
|
+
};
|
|
374
|
+
if (signal?.aborted || isAbort(raw)) {
|
|
375
|
+
chargeCut();
|
|
372
376
|
throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: raw?.partial || [] });
|
|
373
377
|
}
|
|
378
|
+
chargeCut();
|
|
374
379
|
const err = describeError(raw, config);
|
|
375
380
|
// Not every model takes an effort level. Leave it out for this one, and for the rest of the session.
|
|
376
381
|
if (err.status === 400 && params.output_config && /does not support the effort parameter/i.test(err.message)) {
|