@yanzc/claude-pro 0.7.1 → 0.7.3
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 -36
- package/README.md +317 -372
- package/package.json +2 -2
- package/src/agent.js +14 -2
- package/src/api.js +40 -173
- package/src/attach.js +14 -0
- package/src/background.js +102 -12
- package/src/checkpoints.js +4 -2
- package/src/commands.js +20 -85
- package/src/config.js +40 -151
- package/src/gateway.js +9 -3
- package/src/history.js +69 -0
- package/src/host.js +71 -14
- package/src/main.js +19 -2
- package/src/peers.js +3 -6
- package/src/print.js +1 -1
- package/src/prompts.js +1 -4
- package/src/ratelimit.js +6 -19
- package/src/remote.js +6 -40
- package/src/runtime.js +4 -2
- package/src/tools/peers.js +5 -9
- package/src/ui/repl.js +43 -215
- 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
|
|
3
|
+
"version": "0.7.3",
|
|
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
|
@@ -419,7 +419,7 @@ export class Agent {
|
|
|
419
419
|
if (this.reminders.length) content = [...content, ...this.reminders.splice(0).map((text) => ({ type: 'text', text: `<system-reminder>${text}</system-reminder>` }))];
|
|
420
420
|
if (!this.isSubagent && this.checkpoints) {
|
|
421
421
|
const prompt = content.find((b) => b.type === 'text' && !b.text.startsWith('<system-reminder>') && !b.text.startsWith('<task-notification>'))?.text;
|
|
422
|
-
this.checkpoints.beginTurn({ label: prompt || '(background agent report)', messageIndex: this.messages.length });
|
|
422
|
+
this.checkpoints.beginTurn({ label: prompt || '(background agent report)', messageIndex: this.messages.length, conversation: this.config.sessionId || null });
|
|
423
423
|
}
|
|
424
424
|
this.pushMessage({ role: 'user', content });
|
|
425
425
|
|
|
@@ -427,6 +427,7 @@ export class Agent {
|
|
|
427
427
|
let verifyRounds = 0;
|
|
428
428
|
let stopHookRounds = 0;
|
|
429
429
|
let continuations = 0;
|
|
430
|
+
let silentEnds = 0;
|
|
430
431
|
let compactedForError = false;
|
|
431
432
|
let finalText = '';
|
|
432
433
|
for (;;) {
|
|
@@ -456,12 +457,12 @@ export class Agent {
|
|
|
456
457
|
throw err;
|
|
457
458
|
}
|
|
458
459
|
const { message, stopReason } = res;
|
|
460
|
+
const text = message.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim();
|
|
459
461
|
if (!message.content.length) message.content.push({ type: 'text', text: '(no content)' });
|
|
460
462
|
this.pushMessage(message);
|
|
461
463
|
this.io.assistantMessage?.(message, this);
|
|
462
464
|
|
|
463
465
|
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
466
|
if (text) finalText = text;
|
|
466
467
|
|
|
467
468
|
if (!toolUses.length) {
|
|
@@ -476,6 +477,16 @@ export class Agent {
|
|
|
476
477
|
this.pushMessage({ role: 'user', content: queued });
|
|
477
478
|
continue;
|
|
478
479
|
}
|
|
480
|
+
// A response with nothing but thinking (or nothing at all) ends the turn with no reply on the screen: the user
|
|
481
|
+
// cannot tell whether the work is done or stuck. The model is asked once, in a new user message (the
|
|
482
|
+
// continuation Anthropic recommends for empty end_turn responses; the thinking-only message stays, so the
|
|
483
|
+
// cached prefix does too, and the API takes it).
|
|
484
|
+
if (!text && stopReason !== 'refusal' && silentEnds < 1) {
|
|
485
|
+
silentEnds++;
|
|
486
|
+
this.io.notice?.('The model ended its turn without a reply; asking it to go on…');
|
|
487
|
+
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>' }] });
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
479
490
|
const verify = this.config.verifyCommand;
|
|
480
491
|
if (verify && !this.isSubagent && this.editsThisRun > 0) {
|
|
481
492
|
this.editsThisRun = 0;
|
|
@@ -499,6 +510,7 @@ export class Agent {
|
|
|
499
510
|
continue;
|
|
500
511
|
}
|
|
501
512
|
}
|
|
513
|
+
if (!text) this.io.notice?.('The model ended its turn without a reply.', 'warn');
|
|
502
514
|
return { text: finalText, interrupted: false };
|
|
503
515
|
}
|
|
504
516
|
|
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 });
|
package/src/attach.js
CHANGED
|
@@ -83,6 +83,16 @@ function connect(peer, io) {
|
|
|
83
83
|
});
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
// A window the computer service opened for it (--keep-open, see HostService.window): what went wrong, or that the
|
|
87
|
+
// session ended, stays readable until a key is pressed (a window that closes at once says nothing).
|
|
88
|
+
function keepOpen(args, io) {
|
|
89
|
+
if (!args.includes('--keep-open') || !io.stdin.isTTY) return Promise.resolve();
|
|
90
|
+
io.stdout.write('Press any key to close this window.');
|
|
91
|
+
io.stdin.setRawMode(true);
|
|
92
|
+
io.stdin.resume();
|
|
93
|
+
return new Promise((resolve) => io.stdin.once('data', () => { io.stdin.setRawMode(false); io.stdin.pause(); resolve(); }));
|
|
94
|
+
}
|
|
95
|
+
|
|
86
96
|
// io: the terminal (process.stdin/stdout/stderr; the tests give their own).
|
|
87
97
|
export async function attachCommand(args = [], io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
|
|
88
98
|
if (!io.stdin.isTTY || !io.stdout.isTTY) {
|
|
@@ -92,12 +102,14 @@ export async function attachCommand(args = [], io = { stdin: process.stdin, stdo
|
|
|
92
102
|
const sessions = backgroundSessions();
|
|
93
103
|
if (!sessions.length) {
|
|
94
104
|
io.stdout.write('No background session runs on this computer. The web page opens them (新建会话, without "open a terminal window").\n');
|
|
105
|
+
await keepOpen(args, io);
|
|
95
106
|
return 1;
|
|
96
107
|
}
|
|
97
108
|
const ref = args.find((a) => !a.startsWith('-'));
|
|
98
109
|
let peer = ref ? findBackground(ref, sessions) : sessions.length === 1 ? sessions[0] : await choose(sessions, io);
|
|
99
110
|
if (!peer) {
|
|
100
111
|
io.stderr.write(`No background session called "${ref}". These run here: ${sessions.map((p) => `&${p.name}`).join(', ')}\n`);
|
|
112
|
+
await keepOpen(args, io);
|
|
101
113
|
return 1;
|
|
102
114
|
}
|
|
103
115
|
const label = `&${peer.name}`;
|
|
@@ -122,11 +134,13 @@ export async function attachCommand(args = [], io = { stdin: process.stdin, stdo
|
|
|
122
134
|
io.stdout.write(RESET);
|
|
123
135
|
io.stdin.setRawMode(false);
|
|
124
136
|
io.stderr.write(`Could not attach to ${label}: ${e.message}\n`);
|
|
137
|
+
await keepOpen(args, io);
|
|
125
138
|
return 1;
|
|
126
139
|
}
|
|
127
140
|
io.stdout.write(RESET);
|
|
128
141
|
io.stdin.setRawMode(false);
|
|
129
142
|
io.stdin.pause();
|
|
130
143
|
io.stdout.write(how === 'detached' ? `Detached from ${label}: it goes on in the background (claude-pro attach ${peer.name} comes back).\n` : `${label} has ended.\n`);
|
|
144
|
+
if (how !== 'detached') await keepOpen(args, io);
|
|
131
145
|
return 0;
|
|
132
146
|
}
|