@yanzc/claude-pro 0.7.2 → 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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.7.2",
4
- "description": "claude-pro: a command line coding agent for the gateway, Anthropic-compatible APIs or a Claude subscription. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
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
@@ -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 { readGatewayLogin, fetchGatewayModels, cachedGatewayModel, gatewayEffort, gatewayDefaultEffort } from './gateway.js';
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 = readGatewayLogin(config.gatewayUrl);
82
- if (!login) throw new APIError(`Not logged in to the gateway ${config.gatewayUrl}. Run /login and choose the gateway.`, { status: 401, retryable: false });
83
- return login.apiKey;
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, login = null) {
87
- if (config.usesGateway || config.usesCodex) {
88
- const gateway = config.usesGateway;
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, // retries are handled in streamMessage so the UI can report them
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, login) => `${login ? 'claude-code' : config.baseURL}|${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, config.usesClaudeCode)) || [])];
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 GPT model, the gateway's metadata or the local Codex models cache. null for
204
- // a model that takes none or is not known.
205
- // The environment that says where the Codex install is: CODEX_HOME may be set in the shell only.
206
- const codexEnv = (config) => ({ ...process.env, ...(config?.env || {}) });
207
- const gatewayModelInfo = (config, id) => (config?.usesGateway ? cachedGatewayModel(readGatewayLogin(config.gatewayUrl), id) : null);
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)) || codexModels(codexEnv(config)).models.find((m) => m.slug === id)?.defaultEffort || null;
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. A GPT model
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) : codexEffort(modelId, effort, codexEnv(config));
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 }, login = null) {
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, login));
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
- // The codex provider, and the gateway for a GPT model, take the request to the Codex backend.
281
- const toCodex = config.usesCodex || /^gpt-/i.test(model.id);
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 (or the local Codex cache
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 = config?.usesClaudeCode
329
- ? `The Claude subscription login was refused (401). Check the subscription credentials in ${config.claudeCodeCredentialsFile}. ${msg}`
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, loginExpiresAt}
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 (config.usesGateway && /^gpt-/i.test(request.model?.id)) {
376
- const gatewayLogin = readGatewayLogin(config.gatewayUrl);
377
- if (gatewayLogin) {
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(gatewayLogin, { signal }); } catch { if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] }); }
275
+ try { await fetchGatewayModels(login, { signal }); } catch { if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] }); }
380
276
  }
381
277
  }
382
- let client = getClient(config, login);
383
- const params = buildParams(config, request, login);
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, login);
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/commands.js CHANGED
@@ -6,9 +6,7 @@ import { c, padEnd, truncate } from './ui/ansi.js';
6
6
  import { SelectDialog } from './ui/dialogs.js';
7
7
  import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
8
8
  import { loadConfig, settingsFiles, updateSettingsFile, rememberChoice, applyRememberedChoices, KNOWN_KEYS, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
9
- import { loginWithBrowser, readGatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
10
- import { codexLoginSummary, codexModels, codexEfforts } from './codex/client.js';
11
- import { readClaudeCodeLogin } from './claude-code.js';
9
+ import { loginWithBrowser, readGatewayLogin, gatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
12
10
  import { SessionStore } from './session.js';
13
11
  import { memoryFiles, listAutoMemories } from './context.js';
14
12
  import { INIT_PROMPT } from './prompts.js';
@@ -25,13 +23,11 @@ import { describeHost, normalizeDir } from './host.js';
25
23
 
26
24
  const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
27
25
  const isGpt = (modelId) => /^gpt-/i.test(modelId);
28
- // The levels /effort offers for a model: Claude's own (as in Claude Code); for a GPT model the gateway's metadata,
29
- // else the local Codex cache; EFFORTS for other models (an Anthropic-compatible API may take any of them).
26
+ // The levels /effort offers for a gateway model: use its advertised levels when available.
30
27
  const effortLevels = (modelId, modelInfo = null) => {
31
28
  if (/^claude-/i.test(modelId)) return CLAUDE_EFFORTS;
32
29
  const remote = gatewayEfforts(modelInfo);
33
- if (remote.length) return remote;
34
- return isGpt(modelId) && codexEfforts(modelId).length ? codexEfforts(modelId) : EFFORTS;
30
+ return remote.length ? remote : EFFORTS;
35
31
  };
36
32
 
37
33
  // What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
@@ -40,15 +36,10 @@ const effortLevels = (modelId, modelInfo = null) => {
40
36
  export async function modelChoices(cfg) {
41
37
  const configured = cfg.configuredModelSpec;
42
38
  const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).id}` }];
43
- if (cfg.usesCodex) {
44
- // The models the local Codex install lists.
45
- for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ value: m.slug, label: m.slug, description: m.contextWindow ? `${formatTokens(m.contextWindow)} context` : '' });
46
- } else {
47
- opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
48
- }
39
+ opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
49
40
  if (cfg.usesGateway) {
50
41
  // The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
51
- const login = readGatewayLogin(cfg.gatewayUrl);
42
+ const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
52
43
  let served = null;
53
44
  try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
54
45
  const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
@@ -57,7 +48,6 @@ export async function modelChoices(cfg) {
57
48
  opts.push({ value: m.id, label: m.id, description: isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || '' });
58
49
  }
59
50
  }
60
- if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, label: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, description: 'sub-agent model' });
61
51
  return opts;
62
52
  }
63
53
 
@@ -67,7 +57,7 @@ export async function effortChoices(cfg) {
67
57
  const id = cfg.mainModel.id;
68
58
  let info = null;
69
59
  if (cfg.usesGateway && isGpt(id)) {
70
- const login = readGatewayLogin(cfg.gatewayUrl);
60
+ const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
71
61
  try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
72
62
  }
73
63
  const levels = effortLevels(id, info);
@@ -106,7 +96,6 @@ export function buildCommands(app) {
106
96
  cfg.env = fresh.env;
107
97
  cfg.sources = fresh.sources;
108
98
  cfg.settings = fresh.settings;
109
- cfg.ignoredFromDotEnv = fresh.ignoredFromDotEnv;
110
99
  // What the system prompt is built from may have changed (memory switched off, say). It is not rebuilt in the
111
100
  // middle of a conversation, which would lose its prompt cache; it is, at the next /clear or compaction. A
112
101
  // different model is the exception: the prompt names it, and the new model has a cache of its own anyway.
@@ -278,7 +267,6 @@ export function buildCommands(app) {
278
267
  if (v === undefined) continue;
279
268
  lines.push(`${padEnd(k, 34)} ${c.bold(v)} ${c.dim(cfg.sources[k] || '')}`);
280
269
  }
281
- if (cfg.ignoredFromDotEnv.length) lines.push('', c.dim(`Not applied from .env with the claude-code provider (it is the API provider's setup; the subscription's defaults are used instead): ${cfg.ignoredFromDotEnv.join(', ')}. Set them with /config set or /effort to apply them here.`));
282
270
  lines.push('', c.dim('Other keys: ' + Object.keys(KNOWN_KEYS).filter((k) => cfg.env[k] === undefined).join(', ')));
283
271
  lines.push('', `${c.dim('Change with')} /config set KEY VALUE [--project|--local] ${c.dim('or edit')} ${settingsFiles(app.cwd).user}`);
284
272
  log(lines, '');
@@ -312,7 +300,7 @@ export function buildCommands(app) {
312
300
  name: 'effort',
313
301
  get argHint() {
314
302
  const cfg = app.runtime.config;
315
- const login = cfg.usesGateway ? readGatewayLogin(cfg.gatewayUrl) : null;
303
+ const login = cfg.usesGateway ? gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) : null;
316
304
  return `[${effortLevels(cfg.mainModel.id, cachedGatewayModel(login, cfg.mainModel.id)).join('|')}|auto|default]`;
317
305
  },
318
306
  description: 'Set reasoning effort (output_config.effort; kept for later sessions)',
@@ -345,7 +333,7 @@ export function buildCommands(app) {
345
333
  },
346
334
  });
347
335
 
348
- // Switch the provider (kept in the user settings) and take up its own remembered /model and /effort.
336
+ // Keep the gateway selection in the user settings and apply its remembered /model and /effort.
349
337
  const switchProvider = (provider) => {
350
338
  const cfg = app.runtime.config;
351
339
  const files = settingsFiles(app.cwd);
@@ -381,50 +369,13 @@ export function buildCommands(app) {
381
369
 
382
370
  add({
383
371
  name: 'login',
384
- argHint: '[claude|gateway|codex]',
385
- description: 'Choose where model requests go: the Claude subscription, the codex-gateway account (browser login), or the Codex subscription',
372
+ argHint: '[gateway]',
373
+ description: 'Log in to the codex-gateway account in your browser',
386
374
  async run(args) {
387
375
  const cfg = app.runtime.config;
388
- let choice = args.trim().toLowerCase();
389
- if (choice === 'claude') choice = 'claude-code';
390
- if (!choice) {
391
- const saved = readGatewayLogin(cfg.gatewayUrl);
392
- const codex = codexLoginSummary({ ...process.env, ...cfg.env });
393
- choice = await app.showDialog(new SelectDialog({
394
- title: 'Log in',
395
- question: `Now: ${c.bold(cfg.provider)} (${cfg.endpointLabel})`,
396
- options: [
397
- { label: `Gateway ${cfg.gatewayUrl} ${c.dim(saved ? `(logged in as ${saved.account?.email || 'this machine'}; paid from the account balance)` : '(log in in the browser; paid from the account balance)')}`, value: 'gateway' },
398
- { label: `Claude subscription ${c.dim('(the login of the claude command on this computer)')}`, value: 'claude-code' },
399
- { label: `Codex subscription ${c.dim(codex.ok ? `(the local Codex login${codex.plan ? `, ${codex.plan}` : ''})` : '(run `codex login` first)')}`, value: 'codex' },
400
- ],
401
- }));
402
- if (!choice) return;
403
- }
404
- if (!['claude-code', 'gateway', 'codex'].includes(choice)) { out(c.red(`Unknown choice "${choice}". Use claude, gateway or codex.`)); return; }
405
- if (choice !== cfg.provider && !(await confirmCacheLoss('Switching the provider'))) { out(c.dim('Nothing was changed.')); return; }
406
-
407
- if (choice === 'claude-code') {
408
- try { readClaudeCodeLogin(cfg); } catch (e) {
409
- // An expired token is renewed at the first request; a missing login is not.
410
- if (!/expired/i.test(e.message)) {
411
- out(c.red(`The Claude subscription login cannot be used: ${e.message}. Log in with the official \`claude\` once, then run /login again.`));
412
- return;
413
- }
414
- }
415
- const note = switchProvider('claude-code');
416
- out(`Using the ${c.bold('Claude subscription')}: ${cfg.mainModel.label}${note}`);
417
- return;
418
- }
419
- if (choice === 'codex') {
420
- const codex = codexLoginSummary({ ...process.env, ...cfg.env });
421
- if (!codex.ok) { out(c.red(`The Codex login cannot be used: ${codex.error}`)); return; }
422
- const note = switchProvider('codex');
423
- out(`Using the ${c.bold('Codex subscription')}${codex.email ? ` (${codex.email}${codex.plan ? `, ${codex.plan}` : ''})` : ''}: ${cfg.mainModel.label}${note}`);
424
- return;
425
- }
376
+ const choice = args.trim().toLowerCase();
377
+ if (choice && choice !== 'gateway') { out(c.red(`Unknown login method "${choice}". Only gateway login is supported.`)); return; }
426
378
 
427
- // The gateway: a saved key that still works is used as it is; otherwise log in through the browser.
428
379
  const url = cfg.gatewayUrl;
429
380
  const saved = readGatewayLogin(url);
430
381
  if (saved) {
@@ -436,7 +387,7 @@ export function buildCommands(app) {
436
387
  return;
437
388
  } catch (e) {
438
389
  if (e.status !== 401 && e.status !== 403) { out(c.red(`Cannot reach the gateway ${url}: ${e.message}`)); return; }
439
- clearGatewayLogin(); // the key was revoked: log in again
390
+ clearGatewayLogin();
440
391
  }
441
392
  }
442
393
  pendingLogin?.abort();
@@ -468,8 +419,8 @@ export function buildCommands(app) {
468
419
  const wasOnline = Boolean(app.remote);
469
420
  app.stopRemote(); // the other sessions of this computer and its computer service follow within seconds
470
421
  out(had
471
- ? `Logged out of the gateway ${cfg.gatewayUrl}.${wasOnline ? ' This session is offline there now.' : ''}${cfg.usesGateway ? ' Run /login to log in again or choose another provider.' : ''}`
472
- : c.dim('There was no gateway login. (The Claude and Codex subscription logins belong to their own CLIs.)'));
422
+ ? `Logged out of the gateway ${cfg.gatewayUrl}.${wasOnline ? ' This session is offline there now.' : ''} Run /login to log in again.`
423
+ : c.dim('There was no gateway login. Run /login to log in.'));
473
424
  },
474
425
  });
475
426
 
@@ -488,10 +439,7 @@ export function buildCommands(app) {
488
439
  row('cwd', app.cwd),
489
440
  row('Provider', cfg.provider),
490
441
  row('Endpoint', cfg.endpointLabel),
491
- row('Auth', cfg.usesClaudeCode ? `Claude subscription (${cfg.claudeCodeCredentialsFile})`
492
- : cfg.usesGateway ? (readGatewayLogin(cfg.gatewayUrl) ? `gateway key of ${readGatewayLogin(cfg.gatewayUrl).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)'))
493
- : cfg.usesCodex ? (() => { const s = codexLoginSummary({ ...process.env, ...cfg.env }); return s.ok ? `Codex login${s.email ? ` of ${s.email}` : ''}${s.plan ? ` (${s.plan})` : ''} ${c.dim(s.file)}` : c.red(s.error); })()
494
- : cfg.authToken ? `ANTHROPIC_AUTH_TOKEN (${cfg.display('ANTHROPIC_AUTH_TOKEN')})` : cfg.apiKey ? `ANTHROPIC_API_KEY (${cfg.display('ANTHROPIC_API_KEY')})` : c.red('none')),
442
+ row('Auth', gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? `gateway key of ${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)')),
495
443
  row('Model', `${cfg.mainModel.label} ${c.dim(`(sent as "${cfg.mainModel.id}", ${formatTokens(cfg.mainModel.contextWindow)} context)`)}`),
496
444
  row('Sub-agent model', cfg.subagentModelChosen ? `chosen per task by difficulty ${c.dim(`(haiku, sonnet or opus; not chosen: ${cfg.subagentModel.label})`)}` : cfg.subagentModel.label),
497
445
  row('Small model', cfg.smallModel.label),
@@ -544,7 +492,7 @@ export function buildCommands(app) {
544
492
  `Session time: ${formatDuration(Date.now() - app.sessionStart)}`,
545
493
  ]);
546
494
  const cfg = app.runtime.config;
547
- const saved = cfg.usesGateway && readGatewayLogin(cfg.gatewayUrl);
495
+ const saved = cfg.usesGateway && gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
548
496
  if (!saved) return;
549
497
  try {
550
498
  const account = await fetchGatewayAccount(saved);
@@ -665,21 +613,12 @@ export function buildCommands(app) {
665
613
  ...(remote.length ? [c.dim('On your other computers, through the gateway:'), ...remote.map((p) => `${c.bold('&' + p.label)} ${c.dim(`${p.cwd}${p.busy ? ' · busy' : ''}`)}`)] : []),
666
614
  ...(local.length || remote.length ? [] : [c.dim('No other session is running.')]),
667
615
  c.dim(online
668
- ? 'Type "&" for the list, "&name task" to send a task; its answer is shown here. On another computer: "&computer/name task", or "&computer task" when it runs one session. /sendfile &name file... sends files (saved in its Downloads folder). /rename names this session. The agent can use ListPeers / MessagePeer too.'
616
+ ? 'Type "&" for the list, "&name task" to send a task; its answer is shown here. On another computer: "&computer/name task", or "&computer task" when it runs one session. /rename names this session. The agent can use ListPeers / MessagePeer too.'
669
617
  : 'Type "&" for the list, "&name task" to send a task; its answer is shown here. Sessions on your other computers show up here once this one is online at the gateway (/login; /status says why it is not).'),
670
618
  ]);
671
619
  },
672
620
  });
673
621
 
674
- add({
675
- name: 'sendfile',
676
- aliases: ['sf'],
677
- argHint: '&session <file...>',
678
- argRequired: true,
679
- description: 'Send files to another session, on this computer or on another one: it saves them in its Downloads folder',
680
- async run(args) { await app.sendFiles(args); },
681
- });
682
-
683
622
  add({
684
623
  name: 'tui',
685
624
  argHint: '[fullscreen | default]',
@@ -916,11 +855,7 @@ export function buildCommands(app) {
916
855
  `${c.green('✔')} Node ${process.versions.node}`,
917
856
  `${app.runtime.shell.kind === 'bash' ? c.green('✔') : c.yellow('!')} Shell: ${app.runtime.shell.name} (${app.runtime.shell.path})`,
918
857
  `${rg ? c.green('✔') : c.yellow('!')} ripgrep ${rg ? 'found' : 'not found (Grep uses the built-in JS scanner, which is slower; set CLAUDE_PRO_RIPGREP_PATH to use an rg.exe)'}`,
919
- cfg.usesClaudeCode
920
- ? `${c.yellow('!')} Claude subscription: ${cfg.claudeCodeCredentialsFile} (checked by the request below)`
921
- : cfg.usesGateway ? `${readGatewayLogin(cfg.gatewayUrl) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${readGatewayLogin(cfg.gatewayUrl) ? '' : ' missing (/login)'}`
922
- : cfg.usesCodex ? (() => { const s = codexLoginSummary({ ...process.env, ...cfg.env }); return `${s.ok ? c.green('✔') : c.red('✘')} Codex login ${s.ok ? s.file : s.error}`; })()
923
- : `${cfg.authToken || cfg.apiKey ? c.green('✔') : c.red('✘')} Credentials ${cfg.authToken ? 'ANTHROPIC_AUTH_TOKEN' : cfg.apiKey ? 'ANTHROPIC_API_KEY' : 'missing'}`,
858
+ `${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? '' : ' missing (/login)'}`,
924
859
  ];
925
860
  out(lines);
926
861
  app.busy = true;