@yanzc/claude-pro 0.7.2 → 0.7.4
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/.env.example +24 -34
- package/README.md +317 -331
- package/package.json +2 -2
- package/src/agent.js +41 -4
- package/src/api.js +40 -173
- package/src/commands.js +19 -84
- package/src/config.js +32 -137
- package/src/gateway.js +9 -3
- package/src/host.js +8 -5
- package/src/main.js +19 -2
- package/src/mcp.js +14 -0
- package/src/peers.js +3 -6
- package/src/print.js +1 -1
- package/src/prompts.js +23 -14
- package/src/ratelimit.js +6 -19
- package/src/remote.js +6 -40
- package/src/runtime.js +7 -4
- package/src/tools/peers.js +5 -9
- package/src/ui/repl.js +24 -204
- package/src/work-state.js +62 -0
- package/src/claude-code.js +0 -60
- package/src/codex/client.js +0 -310
- package/src/codex/translate-request.js +0 -239
- package/src/codex/translate-stream.js +0 -328
- package/src/oauth.js +0 -287
- package/src/transfer.js +0 -260
- package/src/utils/downloads.js +0 -83
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.7.
|
|
4
|
-
"description": "claude-pro: a command line coding agent for the gateway
|
|
3
|
+
"version": "0.7.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": {
|
|
7
7
|
"type": "git",
|
package/src/agent.js
CHANGED
|
@@ -10,6 +10,7 @@ import { rebuildFileState } from './filestate.js';
|
|
|
10
10
|
import { CacheStats, TTL_MS } from './cache.js';
|
|
11
11
|
import { resolvePath } from './utils/paths.js';
|
|
12
12
|
import { fitImagesIn, lightenImagesIn } from './utils/images.js';
|
|
13
|
+
import { latestWorkState, workStateFromText } from './work-state.js';
|
|
13
14
|
|
|
14
15
|
export const INTERRUPT_MESSAGE = '[Request interrupted by user]';
|
|
15
16
|
export const INTERRUPT_TOOL_MESSAGE = '[Request interrupted by user for tool use]';
|
|
@@ -188,6 +189,7 @@ export class Agent {
|
|
|
188
189
|
this.spawnSubagent = spawnSubagent;
|
|
189
190
|
this.messages = [];
|
|
190
191
|
this.todos = [];
|
|
192
|
+
this.workState = null; // last validated state emitted by compaction; the transcript remains the source on resume
|
|
191
193
|
this.userTurns = 0; // turns the user started (see noteUserTurn)
|
|
192
194
|
this.todosTurn = 0; // ... and the one in which the todo list was last written
|
|
193
195
|
this.fileState = new Map();
|
|
@@ -331,6 +333,7 @@ export class Agent {
|
|
|
331
333
|
resetConversation() {
|
|
332
334
|
this.messages = [];
|
|
333
335
|
this.todos = [];
|
|
336
|
+
this.workState = null;
|
|
334
337
|
this.fileState.clear();
|
|
335
338
|
this.lastContextTokens = 0;
|
|
336
339
|
this.tokensSinceUsage = 0;
|
|
@@ -427,6 +430,7 @@ export class Agent {
|
|
|
427
430
|
let verifyRounds = 0;
|
|
428
431
|
let stopHookRounds = 0;
|
|
429
432
|
let continuations = 0;
|
|
433
|
+
let silentEnds = 0;
|
|
430
434
|
let compactedForError = false;
|
|
431
435
|
let finalText = '';
|
|
432
436
|
for (;;) {
|
|
@@ -456,12 +460,12 @@ export class Agent {
|
|
|
456
460
|
throw err;
|
|
457
461
|
}
|
|
458
462
|
const { message, stopReason } = res;
|
|
463
|
+
const text = message.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim();
|
|
459
464
|
if (!message.content.length) message.content.push({ type: 'text', text: '(no content)' });
|
|
460
465
|
this.pushMessage(message);
|
|
461
466
|
this.io.assistantMessage?.(message, this);
|
|
462
467
|
|
|
463
468
|
const toolUses = message.content.filter((b) => b.type === 'tool_use');
|
|
464
|
-
const text = message.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim();
|
|
465
469
|
if (text) finalText = text;
|
|
466
470
|
|
|
467
471
|
if (!toolUses.length) {
|
|
@@ -476,6 +480,16 @@ export class Agent {
|
|
|
476
480
|
this.pushMessage({ role: 'user', content: queued });
|
|
477
481
|
continue;
|
|
478
482
|
}
|
|
483
|
+
// A response with nothing but thinking (or nothing at all) ends the turn with no reply on the screen: the user
|
|
484
|
+
// cannot tell whether the work is done or stuck. The model is asked once, in a new user message (the
|
|
485
|
+
// continuation Anthropic recommends for empty end_turn responses; the thinking-only message stays, so the
|
|
486
|
+
// cached prefix does too, and the API takes it).
|
|
487
|
+
if (!text && stopReason !== 'refusal' && silentEnds < 1) {
|
|
488
|
+
silentEnds++;
|
|
489
|
+
this.io.notice?.('The model ended its turn without a reply; asking it to go on…');
|
|
490
|
+
this.pushMessage({ role: 'user', content: [{ type: 'text', text: '<system-reminder>Your previous response ended your turn without any text or tool call, so the user got no reply and cannot tell whether you are done. If the task is not finished, carry on with it; if it is, give the user your answer now.</system-reminder>' }] });
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
479
493
|
const verify = this.config.verifyCommand;
|
|
480
494
|
if (verify && !this.isSubagent && this.editsThisRun > 0) {
|
|
481
495
|
this.editsThisRun = 0;
|
|
@@ -499,6 +513,7 @@ export class Agent {
|
|
|
499
513
|
continue;
|
|
500
514
|
}
|
|
501
515
|
}
|
|
516
|
+
if (!text) this.io.notice?.('The model ended its turn without a reply.', 'warn');
|
|
502
517
|
return { text: finalText, interrupted: false };
|
|
503
518
|
}
|
|
504
519
|
|
|
@@ -742,6 +757,26 @@ export class Agent {
|
|
|
742
757
|
return summary.replace(/<\/?(?:summary|analysis)>/g, '').trim();
|
|
743
758
|
}
|
|
744
759
|
|
|
760
|
+
static workStateOf(res) {
|
|
761
|
+
const text = res.message.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim();
|
|
762
|
+
return workStateFromText(text);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// Keep a valid state when the model emits one; if a legacy or malformed response is returned, retain the last
|
|
766
|
+
// state from this process or the transcript instead of replacing it with unvalidated data.
|
|
767
|
+
compactWorkState(res) {
|
|
768
|
+
const parsed = Agent.workStateOf(res);
|
|
769
|
+
if (parsed.present && !parsed.state) {
|
|
770
|
+
const reason = parsed.errors.slice(0, 3).join('; ');
|
|
771
|
+
this.io.notice?.(`Compaction returned an invalid structured work state${reason ? ` (${reason})` : ''}; keeping the narrative summary.`, 'warn');
|
|
772
|
+
}
|
|
773
|
+
if (parsed.state) this.workState = parsed.state;
|
|
774
|
+
return {
|
|
775
|
+
state: parsed.state || this.workState || latestWorkState(this.messages),
|
|
776
|
+
warning: parsed.present && !parsed.state ? 'The structured work state failed validation during compaction. Verify the state below against the narrative summary before relying on it.' : '',
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
|
|
745
780
|
// Ask the model for the summary. The request is the conversation's own request with the summary instruction
|
|
746
781
|
// at its end: the same model, system prompt, tools and effort, so that the API reads the conversation from the
|
|
747
782
|
// cache the turns have been filling instead of processing it all again (this is what Claude Code does; it is
|
|
@@ -791,7 +826,8 @@ export class Agent {
|
|
|
791
826
|
this.io.compactEnd?.(null, this, err);
|
|
792
827
|
throw err;
|
|
793
828
|
}
|
|
794
|
-
const
|
|
829
|
+
const state = this.compactWorkState(res);
|
|
830
|
+
const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary, state.state) }] };
|
|
795
831
|
this.replaceMessages(part === 'before' ? [note, ...after] : [...before, note]);
|
|
796
832
|
if (part === 'before') this.cache.noteCompacted(); // from its first message on: nothing of it is cached (the start of "after" still is)
|
|
797
833
|
if (part === 'after') this.todos = []; // what they were about may be summarized away; the model keeps them in the summary
|
|
@@ -822,13 +858,14 @@ export class Agent {
|
|
|
822
858
|
this.io.compactEnd?.(null, this, err);
|
|
823
859
|
throw err;
|
|
824
860
|
}
|
|
861
|
+
const state = this.compactWorkState(res);
|
|
825
862
|
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>` : '';
|
|
826
|
-
this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto }) + todoNote }] }]);
|
|
863
|
+
this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto, workState: state.state, workStateWarning: state.warning }) + todoNote }] }]);
|
|
827
864
|
this.cache.noteCompacted();
|
|
828
865
|
this.refreshSystemPrompt?.(); // the conversation starts over: it may start from a freshly built system prompt
|
|
829
866
|
this.fileState.clear();
|
|
830
867
|
if (!this.isSubagent) this.checkpoints?.markConversationStale(); // the checkpoints are the main conversation's: a sub-agent's own compaction does not end them
|
|
831
|
-
this.lastContextTokens = estimateTokens(
|
|
868
|
+
this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
|
|
832
869
|
this.tokensSinceUsage = 0;
|
|
833
870
|
this.postCompactTokens = null; // measured on the next request
|
|
834
871
|
this.compactFailures = 0;
|
package/src/api.js
CHANGED
|
@@ -2,126 +2,33 @@
|
|
|
2
2
|
// raw SSE stream into a fully assembled assistant message while reporting progress.
|
|
3
3
|
|
|
4
4
|
import Anthropic from '@anthropic-ai/sdk';
|
|
5
|
-
import { readClaudeCodeLogin, claudeCodeHeaders, CLAUDE_CODE_API_URL, CLAUDE_CODE_SYSTEM } from './claude-code.js';
|
|
6
|
-
import { refreshClaudeCodeLogin, canRenewLogin } from './oauth.js';
|
|
7
5
|
import { humanDuration, parseRateLimit, parseRetryAfter, planRetry, sleepUntil, timing } from './ratelimit.js';
|
|
8
6
|
import { cacheControl, cachePlanOf, fingerprint } from './cache.js';
|
|
9
|
-
import {
|
|
10
|
-
import { createCodexFetch, codexModels, codexEffort, nearestEffort } from './codex/client.js';
|
|
11
|
-
import { SIGNATURE_PREFIX } from './codex/translate-request.js';
|
|
7
|
+
import { gatewayLogin, fetchGatewayModels, cachedGatewayModel, gatewayEffort, gatewayDefaultEffort } from './gateway.js';
|
|
12
8
|
import { fitImagesIn } from './utils/images.js';
|
|
13
9
|
import { costOf } from './pricing.js';
|
|
14
10
|
|
|
15
11
|
let cached = null;
|
|
16
|
-
|
|
17
|
-
const LOGIN_POLL_MS = 15_000; // how often to look for a refreshed login after a pause
|
|
18
|
-
const LOGIN_RENEW_RETRY_MS = 5 * 60_000; // how often to try renewing it while waiting for one
|
|
19
|
-
|
|
20
|
-
// Renew the subscription login if it needs it. Returns true when the file now holds a new login. A login
|
|
21
|
-
// that cannot be renewed is an error with its reason, in place of the bare "token has expired" -- unless
|
|
22
|
-
// the caller has its own way of dealing with that: `onError` is told and the call returns false (the
|
|
23
|
-
// wait for a login), and so does `force` (a 401: the request is reported as it is).
|
|
24
|
-
async function renewLogin(config, signal, { force = false, onError } = {}) {
|
|
25
|
-
try {
|
|
26
|
-
return (await refreshClaudeCodeLogin(config, { signal, force })).refreshed;
|
|
27
|
-
} catch (err) {
|
|
28
|
-
if (err.name === 'AbortError' || signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
|
|
29
|
-
if (onError) { onError(err); return false; }
|
|
30
|
-
if (force) return false;
|
|
31
|
-
throw err;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// The login expiry worth warning about before a long pause: none when this program renews it itself.
|
|
36
|
-
const loginExpiryToWarnAbout = (config, login) => (config.usesClaudeCode && !canRenewLogin(config) ? login?.expiresAt ?? null : null);
|
|
37
|
-
|
|
38
|
-
// The subscription login to use once a pause is over. Its access token lives 8 hours, so after hours of
|
|
39
|
-
// waiting it has most likely expired: it is renewed first, with the refresh token that is stored with it.
|
|
40
|
-
// If that is not possible (the refresh token was refused, the token server cannot be reached for the
|
|
41
|
-
// moment, renewing is switched off) the wait is not wasted by failing at its end: keep looking for a
|
|
42
|
-
// valid login for what is left of the waiting budget, renewing again every few minutes, and say so. A
|
|
43
|
-
// login done in the meantime (running `claude`) is picked up. The file may also be half written at this
|
|
44
|
-
// very moment by another process.
|
|
45
|
-
async function loginAfterPause(config, state, { signal, onEvent }) {
|
|
46
|
-
let spent = 0;
|
|
47
|
-
let renewedAt = 0;
|
|
48
|
-
let renewError = null;
|
|
49
|
-
for (;;) {
|
|
50
|
-
if (!renewedAt || timing.now() - renewedAt >= LOGIN_RENEW_RETRY_MS) {
|
|
51
|
-
renewedAt = timing.now();
|
|
52
|
-
renewError = null;
|
|
53
|
-
await renewLogin(config, signal, { onError: (err) => { renewError = err; } });
|
|
54
|
-
}
|
|
55
|
-
try {
|
|
56
|
-
return readClaudeCodeLogin(config);
|
|
57
|
-
} catch (err) {
|
|
58
|
-
const left = config.rateLimitMaxWait - state.waitedMs;
|
|
59
|
-
if (left < LOGIN_POLL_MS) {
|
|
60
|
-
if (renewError && /access token has expired/.test(err.message)) err.message = renewError.message; // the reason, not just the fact
|
|
61
|
-
if (spent) err.message += ` (Waited ${humanDuration(spent)} for it after the limit reset.)`;
|
|
62
|
-
throw err;
|
|
63
|
-
}
|
|
64
|
-
const now = timing.now();
|
|
65
|
-
onEvent({
|
|
66
|
-
type: 'rate_limit_wait', error: err, delayMs: LOGIN_POLL_MS, resumeAt: now + LOGIN_POLL_MS, resetAt: null, label: 'login',
|
|
67
|
-
polling: true, waitingForLogin: true, giveUpAt: now + left, waitedMs: state.waitedMs, maxWaitMs: config.rateLimitMaxWait,
|
|
68
|
-
renewError: renewError?.message || null,
|
|
69
|
-
});
|
|
70
|
-
state.waitedMs += LOGIN_POLL_MS;
|
|
71
|
-
spent += LOGIN_POLL_MS;
|
|
72
|
-
await sleepUntil(now + LOGIN_POLL_MS, signal);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
let codexFetch = null;
|
|
12
|
+
const SIGNATURE_PREFIX = 'cgw1:';
|
|
78
13
|
|
|
79
14
|
// The gateway provider's key, from /login. Without one the request fails the way a refused key does.
|
|
80
15
|
function gatewayKey(config) {
|
|
81
|
-
const login =
|
|
82
|
-
|
|
83
|
-
|
|
16
|
+
const login = gatewayLogin(config.gatewayUrl, config.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
17
|
+
const key = login?.apiKey || config.env.CLAUDE_PRO_GATEWAY_API_KEY;
|
|
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
|
+
return key;
|
|
84
20
|
}
|
|
85
21
|
|
|
86
|
-
export function getClient(config
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const baseURL = gateway ? config.gatewayUrl : 'https://codex.invalid';
|
|
90
|
-
const authToken = gateway ? gatewayKey(config) : 'codex-login';
|
|
91
|
-
if (!gateway) codexFetch ||= createCodexFetch({ env: { ...process.env, ...config.env } });
|
|
92
|
-
const key = `${config.provider}|${baseURL}|${authToken}|${config.apiTimeout}`;
|
|
93
|
-
if (cached?.key === key && cached.fetch === globalThis.fetch) return cached.client;
|
|
94
|
-
const client = new Anthropic({
|
|
95
|
-
baseURL,
|
|
96
|
-
authToken,
|
|
97
|
-
apiKey: null,
|
|
98
|
-
timeout: config.apiTimeout,
|
|
99
|
-
maxRetries: 0,
|
|
100
|
-
...(gateway ? {} : { fetch: codexFetch }),
|
|
101
|
-
});
|
|
102
|
-
cached = { key, client, fetch: globalThis.fetch };
|
|
103
|
-
return client;
|
|
104
|
-
}
|
|
105
|
-
if (config.usesClaudeCode) login ||= readClaudeCodeLogin(config);
|
|
106
|
-
// Subscription credentials must only go to Anthropic, regardless of an API
|
|
107
|
-
// endpoint or custom auth headers left over from .env (e.g. DeepSeek).
|
|
108
|
-
const baseURL = login ? CLAUDE_CODE_API_URL : config.baseURL;
|
|
109
|
-
const authToken = login ? login.accessToken : config.authToken;
|
|
110
|
-
const apiKey = login || authToken ? null : (config.apiKey || null);
|
|
111
|
-
const headers = login ? claudeCodeHeaders(login) : config.customHeaders;
|
|
112
|
-
const key = `${baseURL}|${authToken}|${apiKey}|${JSON.stringify(headers)}|${config.apiTimeout}`;
|
|
22
|
+
export function getClient(config) {
|
|
23
|
+
const authToken = gatewayKey(config);
|
|
24
|
+
const key = `${config.gatewayUrl}|${authToken}|${config.apiTimeout}`;
|
|
113
25
|
if (cached?.key === key && cached.fetch === globalThis.fetch) return cached.client;
|
|
114
26
|
const client = new Anthropic({
|
|
115
|
-
baseURL,
|
|
116
|
-
// Prefer the bearer token; pass null explicitly so the SDK never falls back to env vars.
|
|
27
|
+
baseURL: config.gatewayUrl,
|
|
117
28
|
authToken,
|
|
118
|
-
apiKey,
|
|
119
|
-
defaultHeaders: headers,
|
|
120
|
-
defaultQuery: login ? { beta: 'true' } : undefined,
|
|
29
|
+
apiKey: null,
|
|
121
30
|
timeout: config.apiTimeout,
|
|
122
|
-
maxRetries: 0,
|
|
123
|
-
|
|
124
|
-
dangerouslyAllowBrowser: false,
|
|
31
|
+
maxRetries: 0,
|
|
125
32
|
});
|
|
126
33
|
cached = { key, client, fetch: globalThis.fetch };
|
|
127
34
|
return client;
|
|
@@ -150,7 +57,7 @@ function withCacheControl(messages, mark) {
|
|
|
150
57
|
// errors. Claude Code carries on without the marker instead of failing the request, and so does this: the
|
|
151
58
|
// marker is left off from then on, so the endpoint is not asked the same thing again.
|
|
152
59
|
const cacheRefused = new Map();
|
|
153
|
-
const cacheKey = (config, modelId
|
|
60
|
+
const cacheKey = (config, modelId) => `${config.gatewayUrl}|${modelId}`;
|
|
154
61
|
|
|
155
62
|
const PLACES = ['system', 'tools', 'messages'];
|
|
156
63
|
const blocksAt = (params, place) => {
|
|
@@ -162,7 +69,7 @@ const hasMark = (params, place) => blocksAt(params, place).some((b) => b.cache_c
|
|
|
162
69
|
|
|
163
70
|
// What an endpoint has refused so far, for /status: the places (system, tools, messages) and "ttl".
|
|
164
71
|
export function cacheRefusals(config, modelId) {
|
|
165
|
-
return [...(cacheRefused.get(cacheKey(config, modelId
|
|
72
|
+
return [...(cacheRefused.get(cacheKey(config, modelId)) || [])];
|
|
166
73
|
}
|
|
167
74
|
|
|
168
75
|
// Take cache_control (or only its ttl) off a request after the endpoint refused it. Returns what was taken off
|
|
@@ -200,17 +107,20 @@ export const effortSupported = (modelId) => !noEffort.has(modelId);
|
|
|
200
107
|
const thinkingStaysOn = new Set();
|
|
201
108
|
|
|
202
109
|
// The effort a model uses when none is sent (docs.claude.com, "Effort"): medium on Opus 5.5 and Haiku 5.5, high on
|
|
203
|
-
// the other models that take one; for a
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
|
|
110
|
+
// 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, config.env.CLAUDE_PRO_GATEWAY_API_KEY), id);
|
|
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
|
+
};
|
|
208
118
|
|
|
209
119
|
export function defaultEffort(modelId, config = null) {
|
|
210
120
|
const id = String(modelId || '');
|
|
211
121
|
if (!effortSupported(id)) return null;
|
|
212
122
|
if (/^gpt-/i.test(id)) {
|
|
213
|
-
return gatewayDefaultEffort(gatewayModelInfo(config, id)) ||
|
|
123
|
+
return gatewayDefaultEffort(gatewayModelInfo(config, id)) || null;
|
|
214
124
|
}
|
|
215
125
|
if (/^claude-(?:opus|haiku)-5-5(?:-|$)/i.test(id)) return 'medium';
|
|
216
126
|
if (/^claude-(?:fable|mythos|opus-(?:5|4-[5-8])|sonnet-(?:5|4-6))(?:-|$)/i.test(id)) return 'high';
|
|
@@ -221,14 +131,13 @@ export function defaultEffort(modelId, config = null) {
|
|
|
221
131
|
// some GPT models are not among them; a level chosen on a GPT model stays chosen after a switch to Claude.
|
|
222
132
|
export const CLAUDE_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
223
133
|
|
|
224
|
-
// The level a request for this model carries when `effort` is chosen: the nearest one the model takes.
|
|
225
|
-
// lists its own (the gateway's /v1/models, else the local Codex models cache); Claude takes CLAUDE_EFFORTS.
|
|
134
|
+
// The level a request for this model carries when `effort` is chosen: the nearest one the gateway model takes.
|
|
226
135
|
export function effortToSend(config, modelId, effort) {
|
|
227
136
|
if (!effort) return effort;
|
|
228
137
|
if (/^claude-/i.test(modelId)) return nearestEffort(effort, CLAUDE_EFFORTS);
|
|
229
138
|
if (!/^gpt-/i.test(modelId)) return effort === 'ultra' ? 'max' : effort;
|
|
230
139
|
const info = gatewayModelInfo(config, modelId);
|
|
231
|
-
return info ? gatewayEffort(info, effort) :
|
|
140
|
+
return info ? gatewayEffort(info, effort) : effort === 'ultra' ? 'max' : effort;
|
|
232
141
|
}
|
|
233
142
|
|
|
234
143
|
// Pull the allowed maximum out of an error such as
|
|
@@ -269,16 +178,15 @@ function withoutCodexThinking(messages) {
|
|
|
269
178
|
// `cacheBucket` says which prompt cache TTL applies: "main" for the conversation itself (the default), "other"
|
|
270
179
|
// for sub-agents, compaction and side queries (see Config.cacheTtl). `cacheMessages: false` leaves the messages
|
|
271
180
|
// unmarked: for a request whose messages are never sent twice, writing them to the cache only costs more.
|
|
272
|
-
export function buildParams(config, { model, system, messages, tools, maxTokens, effort, cacheBucket = 'main', cacheMessages = true }
|
|
273
|
-
if (config.usesClaudeCode) login ||= readClaudeCodeLogin(config);
|
|
181
|
+
export function buildParams(config, { model, system, messages, tools, maxTokens, effort, cacheBucket = 'main', cacheMessages = true }) {
|
|
274
182
|
const wanted = maxTokens || config.maxOutputTokens;
|
|
275
|
-
const refused = cacheRefused.get(cacheKey(config, model.id
|
|
183
|
+
const refused = cacheRefused.get(cacheKey(config, model.id));
|
|
276
184
|
const caching = !config.promptCachingDisabled(model.id);
|
|
277
185
|
const ttl = refused?.has('ttl') ? '5m' : config.cacheTtl(cacheBucket);
|
|
278
186
|
const mark = (place) => (caching && !refused?.has(place) ? { ...cacheControl(ttl) } : null);
|
|
279
187
|
const systemMark = mark('system');
|
|
280
|
-
//
|
|
281
|
-
const toCodex =
|
|
188
|
+
// GPT models are handled by the gateway's Codex backend.
|
|
189
|
+
const toCodex = /^gpt-/i.test(model.id);
|
|
282
190
|
let turnLostThinking = false;
|
|
283
191
|
if (!toCodex) ({ messages, inTurn: turnLostThinking } = withoutCodexThinking(messages));
|
|
284
192
|
const params = {
|
|
@@ -288,16 +196,11 @@ export function buildParams(config, { model, system, messages, tools, maxTokens,
|
|
|
288
196
|
messages: withCacheControl(messages, cacheMessages ? mark('messages') : null),
|
|
289
197
|
stream: true,
|
|
290
198
|
};
|
|
291
|
-
if (login) {
|
|
292
|
-
params.system.unshift({ type: 'text', text: CLAUDE_CODE_SYSTEM });
|
|
293
|
-
params.metadata = { user_id: login.userId };
|
|
294
|
-
}
|
|
295
199
|
if (tools?.length) {
|
|
296
200
|
const toolMark = mark('tools');
|
|
297
201
|
params.tools = tools.map((t, i) => (i === tools.length - 1 && toolMark ? { ...t, cache_control: toolMark } : t));
|
|
298
202
|
}
|
|
299
|
-
// A GPT model with no effort set gets its default from the gateway's model metadata
|
|
300
|
-
// when using the Codex provider), sent explicitly so that the footer and backend use the same level.
|
|
203
|
+
// A GPT model with no effort set gets its default from the gateway's model metadata.
|
|
301
204
|
const eff = effortToSend(config, model.id, (effort === undefined ? config.effort : effort) || (/^gpt-/i.test(model.id) ? defaultEffort(model.id, config) : null));
|
|
302
205
|
if (eff && !noEffort.has(model.id)) params.output_config = { effort: eff };
|
|
303
206
|
const budget = config.thinkingBudget;
|
|
@@ -325,12 +228,8 @@ function describeError(err, config) {
|
|
|
325
228
|
let msg = err?.error?.error?.message || err?.error?.message || err?.message || String(err);
|
|
326
229
|
const promptTooLong = /prompt is too long|context length|maximum context|too many tokens|context_length_exceeded/i.test(msg);
|
|
327
230
|
if (err instanceof APIError) return err;
|
|
328
|
-
if (status === 401) msg =
|
|
329
|
-
|
|
330
|
-
: config?.usesGateway ? `The gateway refused the login (401). Run /login to log in again. ${msg}`
|
|
331
|
-
: config?.usesCodex ? msg
|
|
332
|
-
: `Authentication failed (401). Check ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY. ${msg}`;
|
|
333
|
-
if (status === 402 && config?.usesGateway) 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}`;
|
|
231
|
+
if (status === 401) msg = `The gateway refused the login (401). Run /login to log in again. ${msg}`;
|
|
232
|
+
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}`;
|
|
334
233
|
const retryable = !status || status === 408 || status === 409 || status === 429 || status >= 500;
|
|
335
234
|
const header = typeof err?.headers?.get === 'function' ? err.headers.get('retry-after') : err?.headers?.['retry-after'];
|
|
336
235
|
const overloaded = status === 529 || (err?.error?.error?.type || err?.error?.type) === 'overloaded_error';
|
|
@@ -358,7 +257,7 @@ function charge(config, requested, served, usage) {
|
|
|
358
257
|
// {type:'tool_input', index, partial} partial JSON of a tool call
|
|
359
258
|
// {type:'block_stop', index, block} finished block (tool_use input parsed)
|
|
360
259
|
// {type:'retry', attempt, error, delayMs, maxRetries} a quick retry is about to wait delayMs
|
|
361
|
-
// {type:'rate_limit_wait', error, delayMs, resumeAt, resetAt, label, polling, waitedMs, maxWaitMs
|
|
260
|
+
// {type:'rate_limit_wait', error, delayMs, resumeAt, resetAt, label, polling, waitedMs, maxWaitMs}
|
|
362
261
|
// a rate limit was hit: paused until resumeAt, then the request is repeated
|
|
363
262
|
// {type:'rate_limit_resume', waitedMs} the repeated request was accepted: the pause is over
|
|
364
263
|
// {type:'reset'} partial output from a failed attempt must be discarded
|
|
@@ -367,24 +266,20 @@ function charge(config, requested, served, usage) {
|
|
|
367
266
|
// What each request costs (an interrupted one too) goes to config.onCost, the conversation's running total.
|
|
368
267
|
export async function streamMessage(config, request, { signal, onEvent = () => {}, waitForRateLimit = true } = {}) {
|
|
369
268
|
if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
|
|
370
|
-
// A token that has expired (or is about to) is renewed first, as the official client does.
|
|
371
|
-
if (config.usesClaudeCode) await renewLogin(config, signal);
|
|
372
|
-
let login = config.usesClaudeCode ? readClaudeCodeLogin(config) : null;
|
|
373
269
|
// Load gateway model metadata before the synchronous parameter builder; the cache is keyed by gateway and key,
|
|
374
270
|
// so changing accounts or gateway URLs cannot leak a model's effort levels into another context.
|
|
375
|
-
if (
|
|
376
|
-
const
|
|
377
|
-
if (
|
|
271
|
+
if (/^gpt-/i.test(request.model?.id)) {
|
|
272
|
+
const login = gatewayLogin(config.gatewayUrl, config.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
273
|
+
if (login) {
|
|
378
274
|
// A gateway that does not answer costs at most a few seconds once (see fetchGatewayModels), not the request.
|
|
379
|
-
try { await fetchGatewayModels(
|
|
275
|
+
try { await fetchGatewayModels(login, { signal }); } catch { if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] }); }
|
|
380
276
|
}
|
|
381
277
|
}
|
|
382
|
-
|
|
383
|
-
const params = buildParams(config, request
|
|
278
|
+
const client = getClient(config);
|
|
279
|
+
const params = buildParams(config, request);
|
|
384
280
|
// The gateway keeps a conversation on the upstream account that served it, where its prompt cache is; the
|
|
385
281
|
// session id names the conversation, in the header Claude Code sends it in.
|
|
386
282
|
const options = { signal, ...(config.usesGateway && config.sessionId ? { headers: { 'X-Claude-Code-Session-Id': config.sessionId } } : {}) };
|
|
387
|
-
let authReloaded = false;
|
|
388
283
|
let imagesFitted = false;
|
|
389
284
|
const refused = new Set(); // what the endpoint refused for this request: remembered once a request got through
|
|
390
285
|
const retryState = { attempt: 0, rateLimitHits: 0, waitedMs: 0, overloaded: 0, overloadedWaitMs: 0 };
|
|
@@ -464,7 +359,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
464
359
|
if (!stopped && !stopReason) throw Object.assign(new Error('The response stream ended unexpectedly'), { status: 503 });
|
|
465
360
|
const content = blocks.filter(Boolean).filter((b) => !(b.type === 'text' && !b.text));
|
|
466
361
|
if (refused.size) { // it got through without what the endpoint refused: leave that off from now on
|
|
467
|
-
const key = cacheKey(config, params.model
|
|
362
|
+
const key = cacheKey(config, params.model);
|
|
468
363
|
cacheRefused.set(key, new Set([...(cacheRefused.get(key) || []), ...refused]));
|
|
469
364
|
}
|
|
470
365
|
const cost = charge(config, params.model, model, usage);
|
|
@@ -477,26 +372,6 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
477
372
|
throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: raw?.partial || [] });
|
|
478
373
|
}
|
|
479
374
|
const err = describeError(raw, config);
|
|
480
|
-
// The token was refused. A running native Claude Code session may have renewed the shared token
|
|
481
|
-
// while this request was in flight: read it again. If it is the same one, it may have been revoked
|
|
482
|
-
// early or the local clock may be off: renew it once and try again.
|
|
483
|
-
if (login && err.status === 401 && !authReloaded) {
|
|
484
|
-
authReloaded = true;
|
|
485
|
-
const readValid = () => { try { return readClaudeCodeLogin(config); } catch { return null; } };
|
|
486
|
-
let updated = readValid();
|
|
487
|
-
if (!updated || updated.accessToken === login.accessToken) {
|
|
488
|
-
let failure = null;
|
|
489
|
-
if (await renewLogin(config, signal, { force: true, onError: (e) => { failure = e; } })) updated = readValid();
|
|
490
|
-
else if (!updated && failure) throw failure; // the token ran out meanwhile and cannot be renewed: say why, not just "401"
|
|
491
|
-
}
|
|
492
|
-
if (updated && updated.accessToken !== login.accessToken) {
|
|
493
|
-
login = updated;
|
|
494
|
-
client = getClient(config, login);
|
|
495
|
-
params.metadata = { user_id: login.userId };
|
|
496
|
-
if (emitted) onEvent({ type: 'reset' });
|
|
497
|
-
continue;
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
375
|
// Not every model takes an effort level. Leave it out for this one, and for the rest of the session.
|
|
501
376
|
if (err.status === 400 && params.output_config && /does not support the effort parameter/i.test(err.message)) {
|
|
502
377
|
noEffort.add(params.model);
|
|
@@ -550,16 +425,8 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
550
425
|
...(plan.overloaded
|
|
551
426
|
? { overloaded: true, waitedMs: retryState.overloadedWaitMs, maxWaitMs: config.overloadedMaxWait }
|
|
552
427
|
: { waitedMs: retryState.waitedMs, maxWaitMs: config.rateLimitMaxWait }),
|
|
553
|
-
loginExpiresAt: loginExpiryToWarnAbout(config, login),
|
|
554
428
|
});
|
|
555
429
|
await sleepUntil(plan.resumeAt, signal);
|
|
556
|
-
// Hours may have passed: pick up the login again, the local Claude Code may have refreshed
|
|
557
|
-
// the token (and if it has expired, wait for that rather than fail with a 401).
|
|
558
|
-
if (config.usesClaudeCode) {
|
|
559
|
-
login = await loginAfterPause(config, retryState, { signal, onEvent });
|
|
560
|
-
client = getClient(config, login);
|
|
561
|
-
params.metadata = { user_id: login.userId };
|
|
562
|
-
}
|
|
563
430
|
retryState.attempt = 0; // the pause is a fresh start: quick retries made before it do not count after it
|
|
564
431
|
} else {
|
|
565
432
|
onEvent({ type: 'retry', attempt: plan.attempt, error: err, delayMs: plan.delayMs, maxRetries: plan.maxRetries });
|