@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.
@@ -1,328 +0,0 @@
1
- // Copied from codex-gateway (src/translate-stream.mjs): OpenAI Responses SSE -> Anthropic Messages SSE events.
2
- // OpenAI Responses SSE events -> Anthropic Messages SSE events (and a non-streaming aggregator).
3
- import crypto from "node:crypto";
4
- import { SIGNATURE_PREFIX } from "./translate-request.js";
5
-
6
- /** Async iterator over parsed SSE `data:` JSON payloads from a Node readable stream. */
7
- export async function* parseSSE(stream) {
8
- let buf = "";
9
- const decoder = new TextDecoder();
10
- const parseFrame = (frame) => {
11
- const data = frame
12
- .split(/\r?\n/)
13
- .filter((l) => l.startsWith("data:"))
14
- .map((l) => l.slice(5).replace(/^ /, ""))
15
- .join("\n");
16
- if (!data || data === "[DONE]") return null;
17
- try {
18
- return JSON.parse(data);
19
- } catch {
20
- return null;
21
- }
22
- };
23
- for await (const chunk of stream) {
24
- buf += decoder.decode(chunk, { stream: true });
25
- let m;
26
- while ((m = buf.match(/\r?\n\r?\n/))) {
27
- const frame = buf.slice(0, m.index);
28
- buf = buf.slice(m.index + m[0].length);
29
- const ev = parseFrame(frame);
30
- if (ev) yield ev;
31
- }
32
- }
33
- const ev = parseFrame(buf);
34
- if (ev) yield ev;
35
- }
36
-
37
- /** Merges usage objects, skipping null/undefined fields so a partial update cannot erase counts. */
38
- export function mergeUsage(base, update) {
39
- const merged = { ...(base || {}) };
40
- for (const [key, value] of Object.entries(update || {})) {
41
- if (value !== null && value !== undefined) merged[key] = value;
42
- }
43
- return merged;
44
- }
45
-
46
- export function anthropicUsage(u) {
47
- if (!u) return { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
48
- const cached = u.input_tokens_details?.cached_tokens || 0;
49
- return {
50
- input_tokens: Math.max(0, (u.input_tokens || 0) - cached),
51
- output_tokens: u.output_tokens || 0,
52
- cache_read_input_tokens: cached,
53
- cache_creation_input_tokens: 0,
54
- };
55
- }
56
-
57
- /**
58
- * Feed upstream events through handle(); Anthropic events come out through onEvent(name, data).
59
- * Content blocks are emitted strictly one after another, as the Anthropic protocol requires.
60
- */
61
- export class ResponsesToAnthropic {
62
- constructor({ model, toolNames, emitThinking = true, onEvent }) {
63
- this.model = model;
64
- this.toolNames = toolNames || new Map();
65
- this.emitThinking = emitThinking;
66
- this.onEvent = onEvent;
67
- this.messageId = "msg_" + crypto.randomBytes(12).toString("hex");
68
- this.index = -1;
69
- this.open = null; // { key, type, sawDelta, summaryIndex, citations }
70
- this.closedKeys = new Set();
71
- this.sawToolUse = false;
72
- this.started = false;
73
- this.done = false;
74
- this.usage = null;
75
- this.error = null;
76
- }
77
-
78
- emit(name, data) {
79
- this.onEvent(name, { type: name, ...data });
80
- }
81
-
82
- start() {
83
- if (this.started) return;
84
- this.started = true;
85
- this.emit("message_start", {
86
- message: {
87
- id: this.messageId,
88
- type: "message",
89
- role: "assistant",
90
- model: this.model,
91
- content: [],
92
- stop_reason: null,
93
- stop_sequence: null,
94
- usage: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 },
95
- },
96
- });
97
- }
98
-
99
- openBlock(key, contentBlock, extra = {}) {
100
- if (this.open?.key === key) return this.open;
101
- this.closeBlock();
102
- this.index += 1;
103
- this.open = { key, type: contentBlock.type, sawDelta: false, ...extra };
104
- this.emit("content_block_start", { index: this.index, content_block: contentBlock });
105
- return this.open;
106
- }
107
-
108
- closeBlock() {
109
- if (!this.open) return;
110
- this.emit("content_block_stop", { index: this.index });
111
- this.closedKeys.add(this.open.key);
112
- this.open = null;
113
- }
114
-
115
- delta(delta) {
116
- this.emit("content_block_delta", { index: this.index, delta });
117
- }
118
-
119
- textBlock(key) {
120
- return this.openBlock(key, { type: "text", text: "" }, { citations: [] });
121
- }
122
-
123
- thinkingBlock(key) {
124
- return this.openBlock(key, { type: "thinking", thinking: "", signature: "" }, { summaryIndex: null });
125
- }
126
-
127
- handle(ev) {
128
- if (this.done) return;
129
- this.start();
130
- const item = ev.item;
131
- switch (ev.type) {
132
- case "response.output_item.added":
133
- // Reasoning blocks open lazily (first summary delta or item done) to avoid empty blocks.
134
- if (item?.type === "function_call") this.toolBlock(ev.output_index, item);
135
- break;
136
-
137
- case "response.reasoning_summary_part.added":
138
- case "response.reasoning_summary_text.delta":
139
- case "response.reasoning_text.delta": {
140
- if (!this.emitThinking) break;
141
- const key = `rs:${ev.output_index}`;
142
- if (this.closedKeys.has(key) || (!ev.delta && this.open?.key !== key)) break;
143
- const blk = this.thinkingBlock(key);
144
- const part = ev.summary_index ?? ev.content_index ?? 0;
145
- if (blk.summaryIndex !== null && blk.summaryIndex !== part && blk.sawDelta) {
146
- this.delta({ type: "thinking_delta", thinking: "\n\n" });
147
- }
148
- blk.summaryIndex = part;
149
- if (ev.delta) {
150
- blk.sawDelta = true;
151
- this.delta({ type: "thinking_delta", thinking: ev.delta });
152
- }
153
- break;
154
- }
155
-
156
- case "response.output_text.delta":
157
- case "response.refusal.delta": {
158
- const key = `msg:${ev.output_index}:${ev.content_index ?? 0}`;
159
- if (this.closedKeys.has(key)) break;
160
- const blk = this.textBlock(key);
161
- if (ev.delta) {
162
- blk.sawDelta = true;
163
- this.delta({ type: "text_delta", text: ev.delta });
164
- }
165
- break;
166
- }
167
-
168
- case "response.output_text.annotation.added": {
169
- const a = ev.annotation;
170
- if (a?.type === "url_citation" && this.open?.type === "text") this.open.citations.push(a);
171
- break;
172
- }
173
-
174
- case "response.function_call_arguments.delta": {
175
- const key = `fc:${ev.output_index}`;
176
- if (this.open?.key !== key || !ev.delta) break;
177
- this.open.sawDelta = true;
178
- this.delta({ type: "input_json_delta", partial_json: ev.delta });
179
- break;
180
- }
181
-
182
- case "response.output_item.done":
183
- this.itemDone(ev.output_index, item);
184
- break;
185
-
186
- case "response.completed":
187
- case "response.incomplete":
188
- this.finish(ev.response);
189
- break;
190
-
191
- case "response.failed":
192
- this.fail(ev.response?.error?.message || "Upstream response failed", ev.response?.error?.code);
193
- break;
194
-
195
- case "error":
196
- this.fail(ev.message || ev.error?.message || "Upstream error", ev.code || ev.error?.code || ev.error?.type);
197
- break;
198
- }
199
- }
200
-
201
- toolBlock(outputIndex, item) {
202
- this.sawToolUse = true;
203
- return this.openBlock(`fc:${outputIndex}`, {
204
- type: "tool_use",
205
- id: item.call_id || item.id,
206
- name: this.toolNames.get(item.name) || item.name,
207
- input: {},
208
- });
209
- }
210
-
211
- itemDone(outputIndex, item) {
212
- if (!item) return;
213
- if (item.type === "reasoning") {
214
- if (!this.emitThinking) return;
215
- const key = `rs:${outputIndex}`;
216
- if (this.closedKeys.has(key)) return;
217
- const text = (item.summary || []).map((s) => s.text).filter(Boolean).join("\n\n");
218
- if (this.open?.key !== key && !text && !item.encrypted_content) return;
219
- const blk = this.thinkingBlock(key);
220
- if (!blk.sawDelta && text) this.delta({ type: "thinking_delta", thinking: text });
221
- if (item.encrypted_content) {
222
- this.delta({ type: "signature_delta", signature: SIGNATURE_PREFIX + item.encrypted_content });
223
- }
224
- this.closeBlock();
225
- } else if (item.type === "function_call") {
226
- const key = `fc:${outputIndex}`;
227
- if (this.closedKeys.has(key)) return;
228
- const blk = this.open?.key === key ? this.open : this.toolBlock(outputIndex, item);
229
- if (!blk.sawDelta && item.arguments) this.delta({ type: "input_json_delta", partial_json: item.arguments });
230
- this.closeBlock();
231
- } else if (item.type === "message") {
232
- (item.content || []).forEach((part, ci) => {
233
- const key = `msg:${outputIndex}:${ci}`;
234
- if (this.closedKeys.has(key)) return;
235
- const text = part.text ?? part.refusal ?? "";
236
- const blk = this.open?.key === key ? this.open : text ? this.textBlock(key) : null;
237
- if (!blk) return;
238
- if (!blk.sawDelta && text) this.delta({ type: "text_delta", text });
239
- const cites = blk.citations.length ? blk.citations : (part.annotations || []).filter((a) => a.type === "url_citation");
240
- const seen = new Set();
241
- const lines = cites
242
- .filter((c) => c.url && !seen.has(c.url) && seen.add(c.url))
243
- .map((c) => `- [${c.title || c.url}](${c.url})`);
244
- if (lines.length) this.delta({ type: "text_delta", text: `\n\nSources:\n${lines.join("\n")}` });
245
- this.closeBlock();
246
- });
247
- }
248
- }
249
-
250
- finish(response) {
251
- if (this.done) return;
252
- this.closeBlock();
253
- this.done = true;
254
- this.usage = anthropicUsage(response?.usage);
255
- let stop = this.sawToolUse ? "tool_use" : "end_turn";
256
- if (response?.status === "incomplete") {
257
- const reason = response.incomplete_details?.reason;
258
- stop = reason === "max_output_tokens" ? "max_tokens" : reason === "content_filter" ? "refusal" : stop;
259
- }
260
- this.stopReason = stop;
261
- this.emit("message_delta", { delta: { stop_reason: stop, stop_sequence: null }, usage: this.usage });
262
- this.emit("message_stop", {});
263
- }
264
-
265
- fail(message, code) {
266
- if (this.done) return;
267
- this.closeBlock();
268
- this.done = true;
269
- const type = /rate|limit|quota/i.test(`${code} ${message}`) ? "rate_limit_error" : /overload|capacity/i.test(message) ? "overloaded_error" : "api_error";
270
- this.error = { type, message: code ? `${message} (${code})` : message };
271
- this.emit("error", { error: this.error });
272
- }
273
-
274
- /** Call when the upstream stream ended; reports truncated streams as errors. */
275
- end() {
276
- if (!this.done) {
277
- this.start();
278
- this.fail("Upstream stream ended before the response completed");
279
- }
280
- }
281
- }
282
-
283
- /** Rebuilds a complete Anthropic message object from the Anthropic event stream. */
284
- export class MessageAggregator {
285
- constructor() {
286
- this.message = null;
287
- this.json = new Map();
288
- this.error = null;
289
- }
290
-
291
- onEvent = (name, data) => {
292
- switch (name) {
293
- case "message_start":
294
- this.message = { ...data.message, content: [] };
295
- break;
296
- case "content_block_start":
297
- this.message.content[data.index] = { ...data.content_block };
298
- break;
299
- case "content_block_delta": {
300
- const b = this.message.content[data.index];
301
- const d = data.delta;
302
- if (d.type === "text_delta") b.text += d.text;
303
- else if (d.type === "thinking_delta") b.thinking += d.thinking;
304
- else if (d.type === "signature_delta") b.signature = d.signature;
305
- else if (d.type === "input_json_delta") this.json.set(data.index, (this.json.get(data.index) || "") + d.partial_json);
306
- break;
307
- }
308
- case "content_block_stop": {
309
- const b = this.message.content[data.index];
310
- if (b.type === "tool_use") {
311
- try {
312
- b.input = JSON.parse(this.json.get(data.index) || "{}");
313
- } catch {
314
- b.input = {};
315
- }
316
- }
317
- break;
318
- }
319
- case "message_delta":
320
- Object.assign(this.message, data.delta);
321
- this.message.usage = mergeUsage(this.message.usage, data.usage);
322
- break;
323
- case "error":
324
- this.error = data.error;
325
- break;
326
- }
327
- };
328
- }
package/src/oauth.js DELETED
@@ -1,287 +0,0 @@
1
- // Renewing the Claude Code subscription login.
2
- //
3
- // The access token in ~/.claude/.credentials.json lives 8 hours. The official client renews it when it
4
- // is used, with the refresh token stored next to it, and so does this program now: a token that is
5
- // expired or about to be is renewed before a request is sent, instead of failing and asking the user to
6
- // go and run `claude`.
7
- //
8
- // Renewing rotates the refresh token: the server answers with a new one and the old one stops working.
9
- // So the new tokens must reach the credentials file, or the official client (which reads the same file)
10
- // is left holding a dead one, and nobody may renew at the same moment as somebody else. The protocol is
11
- // the official client's, read from its code:
12
- // - two directory locks (proper-lockfile style: mkdir to take it, rmdir to release, the holder touches
13
- // it every 5 s, one not touched for 60 s is stale): <config dir>/.oauth_refresh.lock and, for older
14
- // versions, <config dir>.lock, taken in that order;
15
- // - after getting the locks, read the file again: whoever held them may just have renewed it;
16
- // - the request: POST {grant_type: "refresh_token", refresh_token, client_id, scope} as JSON to
17
- // the token endpoint; the answer has access_token, expires_in and, normally, a new refresh_token;
18
- // - a refresh token that is rejected may have been used by another process a moment ago: look in the
19
- // file before giving up.
20
- // Only the token fields of the file are changed, and it is replaced atomically.
21
-
22
- import fs from 'node:fs';
23
- import path from 'node:path';
24
- import crypto from 'node:crypto';
25
-
26
- export const OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
27
- export const OAUTH_TOKEN_URL = 'https://platform.claude.com/v1/oauth/token';
28
-
29
- const REFRESH_MARGIN_MS = 5 * 60_000; // renew when this close to expiry, like the official client
30
- const LOCK_STALE_MS = 60_000;
31
- const LOCK_UPDATE_MS = 5_000;
32
- const LOCK_WAIT_MS = 30_000;
33
- const REQUEST_TIMEOUT_MS = 30_000;
34
-
35
- // The token endpoint. Only tests replace it: it is deliberately not a setting, because the refresh token
36
- // is sent there, and a setting can come from a .env file or a settings file of whatever project is open.
37
- export const endpoint = { url: OAUTH_TOKEN_URL };
38
-
39
- export const timing = { // replaceable so tests need not wait
40
- now: () => Date.now(),
41
- sleep: (ms, signal) => new Promise((resolve, reject) => {
42
- if (signal?.aborted) return reject(abortError());
43
- const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
44
- const onAbort = () => { clearTimeout(timer); reject(abortError()); };
45
- signal?.addEventListener('abort', onAbort, { once: true });
46
- }),
47
- };
48
-
49
- const abortError = () => Object.assign(new Error('aborted'), { name: 'AbortError' });
50
-
51
- // What the credentials file holds, or null when it cannot be read.
52
- export function readStoredLogin(file) {
53
- try {
54
- const text = fs.readFileSync(file, 'utf8');
55
- const json = JSON.parse(text.replace(/^\uFEFF/, ''));
56
- return { json, oauth: json?.claudeAiOauth || null, text };
57
- } catch {
58
- return null;
59
- }
60
- }
61
-
62
- export function needsRefresh(oauth, now = timing.now()) {
63
- const expiresAt = Number(oauth?.expiresAt);
64
- return Number.isFinite(expiresAt) && expiresAt > 0 && now + REFRESH_MARGIN_MS >= expiresAt;
65
- }
66
-
67
- const isExpired = (oauth, now = timing.now()) => Number(oauth?.expiresAt) > 0 && Number(oauth.expiresAt) <= now;
68
-
69
- // ---------------------------------------------------------------- locks
70
-
71
- async function takeLock(lockPath, signal) {
72
- const began = timing.now();
73
- for (;;) {
74
- try {
75
- fs.mkdirSync(lockPath);
76
- break;
77
- } catch (err) {
78
- if (err.code !== 'EEXIST') throw err;
79
- let age;
80
- try {
81
- age = timing.now() - fs.statSync(lockPath).mtimeMs;
82
- } catch (statErr) {
83
- if (statErr.code === 'ENOENT') continue; // released just now: take it
84
- throw statErr;
85
- }
86
- if (age > LOCK_STALE_MS) { // its holder is gone
87
- try { fs.rmdirSync(lockPath); } catch { /* somebody else took it over first */ }
88
- continue;
89
- }
90
- if (timing.now() - began > LOCK_WAIT_MS) throw Object.assign(new Error(`Another process has held ${lockPath} for ${Math.round(LOCK_WAIT_MS / 1000)} seconds.`), { code: 'ELOCKED' });
91
- await timing.sleep(250 + Math.floor(Math.random() * 250), signal);
92
- }
93
- }
94
- const touch = setInterval(() => { try { const t = new Date(); fs.utimesSync(lockPath, t, t); } catch { /* released */ } }, LOCK_UPDATE_MS);
95
- touch.unref?.();
96
- return () => {
97
- clearInterval(touch);
98
- try { fs.rmdirSync(lockPath); } catch { /* already gone */ }
99
- };
100
- }
101
-
102
- // Both of the official client's locks. Returns the function that lets go of them.
103
- async function lockLoginFile(file, signal) {
104
- const dir = path.dirname(file);
105
- const release = [];
106
- try {
107
- release.push(await takeLock(path.join(dir, '.oauth_refresh.lock'), signal));
108
- release.push(await takeLock(`${dir}.lock`, signal));
109
- } catch (err) {
110
- for (const fn of release.reverse()) fn();
111
- throw err;
112
- }
113
- return () => { for (const fn of release.reverse()) fn(); };
114
- }
115
-
116
- // ---------------------------------------------------------------- writing the file
117
-
118
- function replaceFile(file, text) {
119
- const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
120
- fs.writeFileSync(tmp, text, { mode: 0o600 });
121
- try {
122
- for (let attempt = 1; ; attempt++) {
123
- try {
124
- fs.renameSync(tmp, file);
125
- return;
126
- } catch (err) {
127
- // On Windows the file may be open in another process for a moment.
128
- if (attempt >= 8 || !['EPERM', 'EBUSY', 'EACCES'].includes(err.code)) throw err;
129
- const until = Date.now() + 40 * attempt;
130
- while (Date.now() < until) { /* a short blocking wait: this is a rare, tiny operation */ }
131
- }
132
- }
133
- } finally {
134
- try { fs.rmSync(tmp, { force: true }); } catch { /* best effort */ }
135
- }
136
- }
137
-
138
- // Put the new tokens into the file, keeping everything else in it as it is (and its layout).
139
- function storeTokens(file, tokens, now) {
140
- const stored = readStoredLogin(file);
141
- if (!stored) throw new Error(`Could not read ${file} to store the renewed login.`);
142
- const oauth = { ...(stored.oauth || {}) };
143
- oauth.accessToken = tokens.accessToken;
144
- oauth.refreshToken = tokens.refreshToken;
145
- oauth.expiresAt = now + tokens.expiresInSec * 1000;
146
- if (tokens.refreshExpiresInSec) oauth.refreshTokenExpiresAt = now + tokens.refreshExpiresInSec * 1000;
147
- if (tokens.scopes?.length) oauth.scopes = tokens.scopes;
148
- const json = { ...stored.json, claudeAiOauth: oauth };
149
- const indent = /^\uFEFF?\{\r?\n([ \t]+)"/.exec(stored.text)?.[1];
150
- const text = JSON.stringify(json, null, indent) + (/\n$/.test(stored.text) ? '\n' : '');
151
- replaceFile(file, text);
152
- // what was written is what is read back: a renewed token that did not reach the file is worse than none
153
- const check = readStoredLogin(file);
154
- if (check?.oauth?.accessToken !== tokens.accessToken || check?.oauth?.refreshToken !== tokens.refreshToken) {
155
- throw new Error(`The renewed login was not saved correctly in ${file}.`);
156
- }
157
- }
158
-
159
- // ---------------------------------------------------------------- the request
160
-
161
- // The server's own words about a failure, without anything that could be a token.
162
- function describeFailure(data) {
163
- const text = [data?.error, data?.error_description || data?.error?.message].filter((x) => typeof x === 'string').join(': ');
164
- return text.replace(/[A-Za-z0-9_-]{40,}/g, '…').slice(0, 200);
165
- }
166
-
167
- async function requestTokens(config, { refreshToken, scopes, signal }) {
168
- const url = endpoint.url;
169
- const post = async (withScope) => {
170
- const body = { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: OAUTH_CLIENT_ID };
171
- if (withScope && scopes?.length) body.scope = scopes.join(' ');
172
- const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
173
- const res = await fetch(url, {
174
- method: 'POST',
175
- headers: { 'content-type': 'application/json', accept: 'application/json', 'user-agent': 'claude-cli (external, cli)' },
176
- body: JSON.stringify(body),
177
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
178
- });
179
- let data = null;
180
- try { data = await res.json(); } catch { /* not JSON */ }
181
- return { status: res.status, data };
182
- };
183
- let res = await post(true);
184
- // a scope the server does not know (any more): renewing without one keeps the scopes the token had
185
- if (res.status === 400 && /invalid_scope/i.test(JSON.stringify(res.data?.error ?? '')) && scopes?.length) res = await post(false);
186
- return res;
187
- }
188
-
189
- function parseTokens(data, oldRefreshToken) {
190
- if (typeof data?.access_token !== 'string' || !data.access_token || !(Number(data.expires_in) > 0)) return null;
191
- return {
192
- accessToken: data.access_token,
193
- refreshToken: typeof data.refresh_token === 'string' && data.refresh_token ? data.refresh_token : oldRefreshToken,
194
- expiresInSec: Number(data.expires_in),
195
- refreshExpiresInSec: Number(data.refresh_token_expires_in) > 0 ? Number(data.refresh_token_expires_in) : null,
196
- scopes: typeof data.scope === 'string' && data.scope.trim() ? data.scope.trim().split(/\s+/) : null,
197
- };
198
- }
199
-
200
- // ---------------------------------------------------------------- renewing
201
-
202
- const SIGN_IN_AGAIN = 'Sign in again: run `claude` and use /login.';
203
-
204
- async function renew(config, { force }) {
205
- const signal = undefined; // one renewal serves every caller in the process, so none of them cancels it
206
- const file = config.claudeCodeCredentialsFile;
207
- const first = readStoredLogin(file);
208
- const oauth = first?.oauth;
209
- if (!oauth?.refreshToken) return { refreshed: false, reason: 'no refresh token' };
210
- if (!force && !needsRefresh(oauth)) return { refreshed: false, reason: 'still valid' };
211
- if (Number(oauth.refreshTokenExpiresAt) > 0 && Number(oauth.refreshTokenExpiresAt) <= timing.now()) {
212
- throw new Error(`The Claude subscription login has expired and cannot be renewed: its refresh token ran out. ${SIGN_IN_AGAIN}`);
213
- }
214
- const startedWith = oauth.accessToken;
215
- // somebody else renewed it while we were looking: take theirs
216
- const renewedElsewhere = () => {
217
- const now = readStoredLogin(file)?.oauth;
218
- return now && now.accessToken !== startedWith && !needsRefresh(now) ? now : null;
219
- };
220
- const failed = (why) => {
221
- const now = readStoredLogin(file)?.oauth;
222
- // renewing early failed but the token still works: carry on with it (unless renewing was asked for)
223
- if (!force && now && !isExpired(now)) return { refreshed: false, reason: why, stillValid: true };
224
- throw new Error(force ? `The Claude subscription login could not be renewed: ${why}` : `The Claude subscription access token has expired and could not be renewed: ${why}`);
225
- };
226
-
227
- let release;
228
- try {
229
- release = await lockLoginFile(file, signal);
230
- } catch (err) {
231
- if (err.name === 'AbortError') throw err;
232
- if (renewedElsewhere()) return { refreshed: false, reason: 'renewed by another process' };
233
- return failed(err.message);
234
- }
235
- try {
236
- if (renewedElsewhere()) return { refreshed: false, reason: 'renewed by another process' };
237
- const current = readStoredLogin(file)?.oauth || oauth;
238
- let res;
239
- try {
240
- res = await requestTokens(config, { refreshToken: current.refreshToken, scopes: current.scopes, signal });
241
- } catch (err) {
242
- return failed(err.name === 'TimeoutError' ? 'the token server did not answer in time' : `the token server could not be reached (${err.cause?.code || err.message})`);
243
- }
244
- if (res.status === 200) {
245
- const tokens = parseTokens(res.data, current.refreshToken);
246
- if (!tokens) return failed('the token server sent an answer that is not a login');
247
- storeTokens(file, tokens, timing.now());
248
- return { refreshed: true, expiresAt: timing.now() + tokens.expiresInSec * 1000 };
249
- }
250
- // The refresh token was refused. Another process may have used it a moment ago and already stored the
251
- // new one: look before giving up.
252
- if (res.status === 400 || res.status === 401 || res.status === 403) {
253
- if (renewedElsewhere()) return { refreshed: false, reason: 'renewed by another process' };
254
- throw new Error(`The Claude subscription login can no longer be renewed (${describeFailure(res.data) || `HTTP ${res.status}`}). ${SIGN_IN_AGAIN}`);
255
- }
256
- return failed(`the token server answered HTTP ${res.status}${describeFailure(res.data) ? ` (${describeFailure(res.data)})` : ''}`);
257
- } finally {
258
- release();
259
- }
260
- }
261
-
262
- const inflight = new Map();
263
-
264
- const refreshDisabled = (config) => /^(1|true|yes)$/i.test(config.env?.CLAUDE_PRO_DISABLE_TOKEN_REFRESH || '');
265
-
266
- // Whether this program is able to renew the login by itself: switched on, and the file has a refresh
267
- // token that has not run out. (Whether the server will accept it is only known by asking.)
268
- export function canRenewLogin(config) {
269
- if (refreshDisabled(config)) return false;
270
- const oauth = readStoredLogin(config.claudeCodeCredentialsFile)?.oauth;
271
- if (!oauth?.refreshToken) return false;
272
- return !(Number(oauth.refreshTokenExpiresAt) > 0 && Number(oauth.refreshTokenExpiresAt) <= timing.now());
273
- }
274
-
275
- // Renew the login in the credentials file if it is expired or about to expire (always with `force`).
276
- // Resolves {refreshed, reason}; throws only when the login is unusable and could not be renewed: a
277
- // failure to renew a token that still has a few minutes left is not an error. Callers in the same
278
- // process share one renewal; `signal` only stops this caller from waiting for it.
279
- export async function refreshClaudeCodeLogin(config, { signal, force = false } = {}) {
280
- if (refreshDisabled(config)) return { refreshed: false, reason: 'disabled' };
281
- if (signal?.aborted) throw abortError();
282
- const key = config.claudeCodeCredentialsFile;
283
- if (!inflight.has(key)) inflight.set(key, renew(config, { force }).finally(() => inflight.delete(key)));
284
- const shared = inflight.get(key);
285
- if (!signal) return shared;
286
- return Promise.race([shared, new Promise((resolve, reject) => signal.addEventListener('abort', () => reject(abortError()), { once: true }))]);
287
- }