@yanzc/claude-pro 0.9.0 → 0.9.2

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.
Files changed (57) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +240 -62
  4. package/src/agents.js +3 -2
  5. package/src/api.js +83 -41
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +177 -71
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +153 -153
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +2 -1
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +6 -62
  27. package/src/ratelimit.js +3 -5
  28. package/src/remote.js +26 -10
  29. package/src/restart.js +3 -0
  30. package/src/runtime.js +33 -10
  31. package/src/selfcheck.js +3 -3
  32. package/src/session.js +93 -3
  33. package/src/supervisor.js +10 -1
  34. package/src/tools/bash.js +19 -18
  35. package/src/tools/browser.js +365 -0
  36. package/src/tools/code.js +430 -0
  37. package/src/tools/effort.js +3 -4
  38. package/src/tools/files.js +92 -19
  39. package/src/tools/index.js +6 -0
  40. package/src/tools/notebook.js +11 -4
  41. package/src/tools/processes.js +274 -0
  42. package/src/tools/search.js +104 -21
  43. package/src/tools/web.js +316 -46
  44. package/src/trace.js +0 -4
  45. package/src/ui/ansi.js +92 -13
  46. package/src/ui/dialogs.js +16 -54
  47. package/src/ui/editor.js +231 -34
  48. package/src/ui/markdown.js +1 -2
  49. package/src/ui/render.js +1 -2
  50. package/src/ui/repl.js +246 -119
  51. package/src/ui/screen.js +139 -31
  52. package/src/updater.js +135 -165
  53. package/src/utils/clipboard.js +5 -3
  54. package/src/utils/paths.js +15 -17
  55. package/src/utils/shell.js +75 -21
  56. package/.env.example +0 -29
  57. package/src/verify.js +0 -57
package/src/gateway.js CHANGED
@@ -1,164 +1,208 @@
1
- // The codex-gateway provider: model requests go to a shared gateway (https://gw.predix.icu by default) with an
2
- // API key of the user's gateway account, which pays for them from its balance. /login starts a local callback
3
- // server, opens the gateway login page in the browser, and exchanges a one-time code for a key belonging to this machine
4
- // (see handleCli in codex-gateway's server.mjs).
5
-
6
- import crypto from 'node:crypto';
7
- import fs from 'node:fs';
8
- import http from 'node:http';
9
- import os from 'node:os';
10
- import path from 'node:path';
11
- import { spawn } from 'node:child_process';
12
- import { CONFIG_DIR, GATEWAY_DEFAULT_URL } from './config.js';
13
-
14
- export { GATEWAY_DEFAULT_URL };
15
- export const gatewayLoginFile = () => path.join(process.env.CLAUDE_PRO_CONFIG_DIR || CONFIG_DIR, 'gateway.json');
16
- const LOGIN_TIMEOUT_MS = 10 * 60_000;
17
-
18
- export const normalizeGatewayUrl = (url) => String(url || GATEWAY_DEFAULT_URL).trim().replace(/\/+$/, '');
19
-
20
- // {url, apiKey, account, savedAt}, or null when there is none for this gateway.
21
- export function readGatewayLogin(url) {
22
- try {
23
- const data = JSON.parse(fs.readFileSync(gatewayLoginFile(), 'utf8'));
24
- if (!data?.apiKey || (url && normalizeGatewayUrl(data.url) !== normalizeGatewayUrl(url))) return null;
25
- return data;
26
- } catch {
27
- return null;
28
- }
29
- }
30
-
31
- // A key supplied for a headless run is equivalent to a saved login for model and remote requests.
32
- // It has no account metadata, so the UI uses a neutral account label.
33
- export function gatewayLogin(url, apiKey = process.env.CLAUDE_PRO_GATEWAY_API_KEY) {
34
- return readGatewayLogin(url) || (apiKey ? { url: normalizeGatewayUrl(url), apiKey, account: {} } : null);
35
- }
36
-
37
- export function saveGatewayLogin(login) {
38
- const file = gatewayLoginFile();
39
- fs.mkdirSync(path.dirname(file), { recursive: true });
40
- const tmp = `${file}.${process.pid}.tmp`;
41
- fs.writeFileSync(tmp, JSON.stringify({ ...login, url: normalizeGatewayUrl(login.url), savedAt: new Date().toISOString() }, null, 2), { mode: 0o600 });
42
- fs.renameSync(tmp, file);
43
- }
44
-
45
- export function clearGatewayLogin() {
46
- try { fs.unlinkSync(gatewayLoginFile()); return true; } catch { return false; }
47
- }
48
-
49
- export function openBrowser(url) {
50
- try {
51
- const [cmd, args] = process.platform === 'win32'
52
- ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
53
- : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
54
- const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
55
- child.on('error', () => {});
56
- child.unref();
57
- return true;
58
- } catch {
59
- return false;
60
- }
61
- }
62
-
63
- async function gatewayJson(url, init = {}, fetchImpl = globalThis.fetch) {
64
- const res = await fetchImpl(url, { ...init, headers: { 'content-type': 'application/json', ...(init.headers || {}) } });
65
- const body = await res.json().catch(() => ({}));
66
- if (!res.ok) throw Object.assign(new Error(body?.error?.message || `HTTP ${res.status}`), { status: res.status });
67
- return body;
68
- }
69
-
70
- // The account behind a key: balance, usage totals (GET /v1/account).
71
- export async function fetchGatewayAccount({ url, apiKey }, { fetchImpl = globalThis.fetch, signal } = {}) {
72
- const body = await gatewayJson(`${normalizeGatewayUrl(url)}/v1/account`, { headers: { authorization: `Bearer ${apiKey}` }, signal }, fetchImpl);
73
- return body.account;
74
- }
75
-
76
- // The models the gateway serves (GET /v1/models), fetched once per gateway and key. The reasoning fields are
77
- // optional so older gateways still work; when present they are kept with the model for /effort and requests.
78
- // Every GPT request waits for it the first time, so it gives up after a few seconds, and after a failure it is not
79
- // asked again for a minute: a gateway whose /v1/models fails must not slow down every request.
80
- const modelLists = new Map();
81
- const modelListFailures = new Map(); // key -> {at, error}
82
- const MODELS_TIMEOUT_MS = 5000;
83
- const MODELS_RETRY_MS = 60_000;
84
- export async function fetchGatewayModels({ url, apiKey }, { fetchImpl = globalThis.fetch, signal, timeoutMs = MODELS_TIMEOUT_MS } = {}) {
85
- const key = `${normalizeGatewayUrl(url)}\n${apiKey}`;
86
- if (modelLists.has(key)) return modelLists.get(key);
87
- const failed = modelListFailures.get(key);
88
- if (failed && Date.now() - failed.at < MODELS_RETRY_MS) throw failed.error;
89
- const timeout = AbortSignal.timeout(timeoutMs);
90
- let body;
91
- try {
92
- body = await gatewayJson(`${normalizeGatewayUrl(url)}/v1/models`, { headers: { authorization: `Bearer ${apiKey}` }, signal: signal ? AbortSignal.any([signal, timeout]) : timeout }, fetchImpl);
93
- } catch (e) {
94
- if (!signal?.aborted) modelListFailures.set(key, { at: Date.now(), error: e });
95
- throw e;
96
- }
97
- modelListFailures.delete(key);
98
- const list = (body.data || []).filter((m) => typeof m?.id === 'string').map((m) => ({
99
- ...m,
100
- supported_reasoning_levels: (Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : Array.isArray(m.reasoning_levels) ? m.reasoning_levels : [])
101
- .map((r) => typeof r === 'string' ? r : r?.effort || r?.name).filter(Boolean),
102
- default_reasoning_level: typeof m.default_reasoning_level === 'string' ? m.default_reasoning_level
103
- : m.default_reasoning_level?.effort || m.default_effort || null,
104
- }));
105
- modelLists.set(key, list);
106
- return list;
107
- }
108
-
109
- export function cachedGatewayModel(login, modelId) {
110
- if (!login?.url || !login?.apiKey) return null;
111
- return modelLists.get(`${normalizeGatewayUrl(login.url)}\n${login.apiKey}`)?.find((m) => m.id === modelId) || null;
112
- }
113
-
114
- const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
115
- export function gatewayEfforts(model) { return model?.supported_reasoning_levels || []; }
116
- export function gatewayDefaultEffort(model) { return model?.default_reasoning_level || null; }
117
- export function gatewayEffort(model, effort) {
118
- const supported = gatewayEfforts(model);
119
- if (!effort || !supported.length || supported.includes(effort)) return effort;
120
- const want = EFFORT_ORDER.indexOf(effort);
121
- return supported.reduce((best, item) => (Math.abs(EFFORT_ORDER.indexOf(item) - want) < Math.abs(EFFORT_ORDER.indexOf(best) - want) ? item : best), supported[0]);
122
- }
123
-
124
- const PAGE = (title, text) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;line-height:1.6"><h2>${title}</h2><p>${text}</p></body>`;
125
-
126
- // Log in through the browser. `onUrl(url)` is told the login page's address (to show it, for when the browser
127
- // does not open by itself); `open` opens it. Resolves with the saved login once the key is in.
128
- export async function loginWithBrowser({ url = GATEWAY_DEFAULT_URL, onUrl = () => {}, open = openBrowser, signal, fetchImpl = globalThis.fetch, timeoutMs = LOGIN_TIMEOUT_MS } = {}) {
129
- const base = normalizeGatewayUrl(url);
130
- const state = crypto.randomBytes(24).toString('base64url');
131
- let settle;
132
- const result = new Promise((resolve, reject) => { settle = { resolve, reject }; });
133
- const server = http.createServer((req, res) => {
134
- const u = new URL(req.url, 'http://127.0.0.1');
135
- if (u.pathname !== '/callback') { res.writeHead(404).end(); return; }
136
- const ok = u.searchParams.get('state') === state && u.searchParams.get('code');
137
- res.writeHead(ok ? 200 : 400, { 'content-type': 'text/html; charset=utf-8' });
138
- res.end(ok ? PAGE('登录成功', '可以关掉这个页面,回到终端继续使用 claude-pro。') : PAGE('登录失败', '链接无效或已过期。请回到终端重新执行 /login。'));
139
- if (ok) settle.resolve(u.searchParams.get('code'));
140
- });
141
- await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
142
- const timer = setTimeout(() => settle.reject(new Error('Login timed out: the browser did not come back within 10 minutes.')), timeoutMs);
143
- const onAbort = () => settle.reject(Object.assign(new Error('Login cancelled'), { name: 'AbortError' }));
144
- signal?.addEventListener('abort', onAbort, { once: true });
145
- try {
146
- const page = `${base}/cli/login?${new URLSearchParams({ port: String(server.address().port), state, client: 'claude-pro', device: os.hostname().slice(0, 60) })}`;
147
- onUrl(page);
148
- Promise.resolve().then(() => open(page)).catch((e) => settle.reject(e));
149
- const code = await result;
150
- const token = await gatewayJson(`${base}/cli/token`, { method: 'POST', body: JSON.stringify({ code, state }) }, fetchImpl);
151
- const login = { url: base, apiKey: token.api_key, account: { id: token.account?.id, name: token.account?.name, email: token.account?.email } };
152
- saveGatewayLogin(login);
153
- return { ...login, balance: token.account };
154
- } finally {
155
- clearTimeout(timer);
156
- signal?.removeEventListener('abort', onAbort);
157
- server.close();
158
- }
159
- }
160
-
161
- export const formatUsd = (value) => {
162
- const n = Number(value);
163
- return Number.isFinite(n) ? `$${n.toFixed(n !== 0 && Math.abs(n) < 0.01 ? 4 : 2)}` : '-';
164
- };
1
+ // The codex-gateway provider: model requests go to a shared gateway (https://gw.predix.icu by default) with an
2
+ // API key of the user's gateway account, which pays for them from its balance. /login starts a local callback
3
+ // server, opens the gateway login page in the browser, and exchanges a one-time code for a key belonging to this machine
4
+ // (see handleCli in codex-gateway's server.mjs).
5
+
6
+ import crypto from 'node:crypto';
7
+ import fs from 'node:fs';
8
+ import http from 'node:http';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { spawn } from 'node:child_process';
12
+ import { CONFIG_DIR, GATEWAY_DEFAULT_URL, noteServedModels } from './config.js';
13
+
14
+ export { GATEWAY_DEFAULT_URL };
15
+ export const gatewayLoginFile = () => path.join(process.env.CLAUDE_PRO_CONFIG_DIR || CONFIG_DIR, 'gateway.json');
16
+ const LOGIN_TIMEOUT_MS = 10 * 60_000;
17
+
18
+ export const normalizeGatewayUrl = (url) => String(url || GATEWAY_DEFAULT_URL).trim().replace(/\/+$/, '');
19
+
20
+ // The login /login saved for this gateway, {url, apiKey, account, savedAt}, or null when there is none. It is where
21
+ // the key of every model and remote request comes from: there is no environment variable or .env file for it.
22
+ export function gatewayLogin(url) {
23
+ try {
24
+ const data = JSON.parse(fs.readFileSync(gatewayLoginFile(), 'utf8'));
25
+ if (!data?.apiKey || (url && normalizeGatewayUrl(data.url) !== normalizeGatewayUrl(url))) return null;
26
+ return data;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ export function saveGatewayLogin(login) {
33
+ const file = gatewayLoginFile();
34
+ fs.mkdirSync(path.dirname(file), { recursive: true });
35
+ const tmp = `${file}.${process.pid}.tmp`;
36
+ fs.writeFileSync(tmp, JSON.stringify({ ...login, url: normalizeGatewayUrl(login.url), savedAt: new Date().toISOString() }, null, 2), { mode: 0o600 });
37
+ fs.renameSync(tmp, file);
38
+ }
39
+
40
+ export function clearGatewayLogin() {
41
+ try { fs.unlinkSync(gatewayLoginFile()); return true; } catch { return false; }
42
+ }
43
+
44
+ export function openBrowser(url) {
45
+ try {
46
+ const [cmd, args] = process.platform === 'win32'
47
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
48
+ : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
49
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
50
+ child.on('error', () => {});
51
+ child.unref();
52
+ return true;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ async function gatewayJson(url, init = {}, fetchImpl = globalThis.fetch) {
59
+ const res = await fetchImpl(url, { ...init, headers: { 'content-type': 'application/json', ...(init.headers || {}) } });
60
+ const body = await res.json().catch(() => ({}));
61
+ if (!res.ok) throw Object.assign(new Error(body?.error?.message || `HTTP ${res.status}`), { status: res.status });
62
+ return body;
63
+ }
64
+
65
+ // The account behind a key: balance, usage totals (GET /v1/account).
66
+ export async function fetchGatewayAccount({ url, apiKey }, { fetchImpl = globalThis.fetch, signal } = {}) {
67
+ const body = await gatewayJson(`${normalizeGatewayUrl(url)}/v1/account`, { headers: { authorization: `Bearer ${apiKey}` }, signal }, fetchImpl);
68
+ return body.account;
69
+ }
70
+
71
+ // The models the gateway serves (GET /v1/models), kept per gateway and key. The reasoning fields are optional so
72
+ // older gateways still work; when present they are kept with the model for /effort and requests. Each model's
73
+ // max_input_tokens is its window (see Config.resolveModel).
74
+ // The first request waits for the list, so it gives up after a few seconds, and after a failure it is not asked again
75
+ // for a minute: a gateway whose /v1/models fails must not slow down every request. A list older than
76
+ // MODELS_MAX_AGE_MS is still answered at once, and a new one is fetched behind it; `fresh` (the /model and /effort
77
+ // pickers, the remote page's options) asks the gateway now and falls back to the kept list when it does not answer.
78
+ // The list used to be kept for the life of the process: a model the gateway added (or dropped) showed up in /model
79
+ // only after a restart.
80
+ const modelLists = new Map(); // key -> {list, at}
81
+ const modelListFailures = new Map(); // key -> {at, error}
82
+ const modelListFetches = new Map(); // key -> the request in flight, shared by its callers
83
+ const MODELS_TIMEOUT_MS = 5000;
84
+ const MODELS_RETRY_MS = 60_000;
85
+ const MODELS_MAX_AGE_MS = 10 * 60_000;
86
+
87
+ const listKey = ({ url, apiKey }) => `${normalizeGatewayUrl(url)}\n${apiKey}`;
88
+
89
+ // One GET /v1/models at a time per key. It carries only its own timeout: a caller that gives up (its signal) leaves
90
+ // it running for the others and the cache (see untilAborted).
91
+ function requestModels(key, { url, apiKey }, { fetchImpl, timeoutMs }) {
92
+ if (modelListFetches.has(key)) return modelListFetches.get(key);
93
+ const base = normalizeGatewayUrl(url);
94
+ const pending = gatewayJson(`${base}/v1/models`, { headers: { authorization: `Bearer ${apiKey}` }, signal: AbortSignal.timeout(timeoutMs) }, fetchImpl)
95
+ .then((body) => {
96
+ const list = (body.data || []).filter((m) => typeof m?.id === 'string').map((m) => ({
97
+ ...m,
98
+ supported_reasoning_levels: (Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : Array.isArray(m.reasoning_levels) ? m.reasoning_levels : [])
99
+ .map((r) => typeof r === 'string' ? r : r?.effort || r?.name).filter(Boolean),
100
+ default_reasoning_level: typeof m.default_reasoning_level === 'string' ? m.default_reasoning_level
101
+ : m.default_reasoning_level?.effort || m.default_effort || null,
102
+ }));
103
+ modelLists.set(key, { list, at: Date.now() });
104
+ modelListFailures.delete(key);
105
+ noteServedModels(base, list);
106
+ return list;
107
+ }, (e) => {
108
+ modelListFailures.set(key, { at: Date.now(), error: e });
109
+ throw e;
110
+ })
111
+ .finally(() => modelListFetches.delete(key));
112
+ modelListFetches.set(key, pending);
113
+ return pending;
114
+ }
115
+
116
+ const untilAborted = (promise, signal) => (!signal ? promise : new Promise((resolve, reject) => {
117
+ const onAbort = () => reject(signal.reason ?? Object.assign(new Error('aborted'), { name: 'AbortError' }));
118
+ if (signal.aborted) return onAbort();
119
+ signal.addEventListener('abort', onAbort, { once: true });
120
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
121
+ }));
122
+
123
+ export async function fetchGatewayModels(login, { fetchImpl = globalThis.fetch, signal, timeoutMs = MODELS_TIMEOUT_MS, fresh = false } = {}) {
124
+ const key = listKey(login);
125
+ const kept = modelLists.get(key);
126
+ const failed = modelListFailures.get(key);
127
+ const failedLately = failed && Date.now() - failed.at < MODELS_RETRY_MS;
128
+ if (kept && !fresh) {
129
+ if (Date.now() - kept.at >= MODELS_MAX_AGE_MS && !failedLately) requestModels(key, login, { fetchImpl, timeoutMs }).catch(() => {});
130
+ return kept.list;
131
+ }
132
+ if (failedLately && !fresh) throw failed.error;
133
+ try {
134
+ return await untilAborted(requestModels(key, login, { fetchImpl, timeoutMs }), signal);
135
+ } catch (e) {
136
+ if (kept) return kept.list; // the gateway does not answer now: the list it gave last
137
+ throw e;
138
+ }
139
+ }
140
+
141
+ // The gateway's model list for a configuration, for the synchronous code that reads it: buildParams (a GPT model's
142
+ // effort levels) and Config.resolveModel (every model's window). When the gateway does not answer, the built-in
143
+ // values stand in. Never throws.
144
+ export async function loadGatewayModels(config, signal) {
145
+ const login = gatewayLogin(config.gatewayUrl);
146
+ if (!login) return;
147
+ try { await fetchGatewayModels(login, { signal }); } catch { /* the built-in values stand in */ }
148
+ }
149
+
150
+ export function cachedGatewayModel(login, modelId) {
151
+ if (!login?.url || !login?.apiKey) return null;
152
+ return modelLists.get(listKey(login))?.list.find((m) => m.id === modelId) || null;
153
+ }
154
+
155
+ const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
156
+ export function gatewayEfforts(model) { return model?.supported_reasoning_levels || []; }
157
+ export function gatewayDefaultEffort(model) { return model?.default_reasoning_level || null; }
158
+ export function gatewayEffort(model, effort) { return nearestEffort(effort, gatewayEfforts(model)); }
159
+
160
+ // The level of `supported` nearest to `effort` (in EFFORT_ORDER), or `effort` itself when it is one of them or there
161
+ // are none.
162
+ export function nearestEffort(effort, supported) {
163
+ if (!effort || !supported.length || supported.includes(effort)) return effort;
164
+ const want = EFFORT_ORDER.indexOf(effort);
165
+ return supported.reduce((best, item) => (Math.abs(EFFORT_ORDER.indexOf(item) - want) < Math.abs(EFFORT_ORDER.indexOf(best) - want) ? item : best), supported[0]);
166
+ }
167
+
168
+ const PAGE = (title, text) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;line-height:1.6"><h2>${title}</h2><p>${text}</p></body>`;
169
+
170
+ // Log in through the browser. `onUrl(url)` is told the login page's address (to show it, for when the browser
171
+ // does not open by itself); `open` opens it. Resolves with the saved login once the key is in.
172
+ export async function loginWithBrowser({ url = GATEWAY_DEFAULT_URL, onUrl = () => {}, open = openBrowser, signal, fetchImpl = globalThis.fetch, timeoutMs = LOGIN_TIMEOUT_MS } = {}) {
173
+ const base = normalizeGatewayUrl(url);
174
+ const state = crypto.randomBytes(24).toString('base64url');
175
+ let settle;
176
+ const result = new Promise((resolve, reject) => { settle = { resolve, reject }; });
177
+ const server = http.createServer((req, res) => {
178
+ const u = new URL(req.url, 'http://127.0.0.1');
179
+ if (u.pathname !== '/callback') { res.writeHead(404).end(); return; }
180
+ const ok = u.searchParams.get('state') === state && u.searchParams.get('code');
181
+ res.writeHead(ok ? 200 : 400, { 'content-type': 'text/html; charset=utf-8' });
182
+ res.end(ok ? PAGE('登录成功', '可以关掉这个页面,回到终端继续使用 claude-pro。') : PAGE('登录失败', '链接无效或已过期。请回到终端重新执行 /login。'));
183
+ if (ok) settle.resolve(u.searchParams.get('code'));
184
+ });
185
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
186
+ const timer = setTimeout(() => settle.reject(new Error('Login timed out: the browser did not come back within 10 minutes.')), timeoutMs);
187
+ const onAbort = () => settle.reject(Object.assign(new Error('Login cancelled'), { name: 'AbortError' }));
188
+ signal?.addEventListener('abort', onAbort, { once: true });
189
+ try {
190
+ const page = `${base}/cli/login?${new URLSearchParams({ port: String(server.address().port), state, client: 'claude-pro', device: os.hostname().slice(0, 60) })}`;
191
+ onUrl(page);
192
+ Promise.resolve().then(() => open(page)).catch((e) => settle.reject(e));
193
+ const code = await result;
194
+ const token = await gatewayJson(`${base}/cli/token`, { method: 'POST', body: JSON.stringify({ code, state }) }, fetchImpl);
195
+ const login = { url: base, apiKey: token.api_key, account: { id: token.account?.id, name: token.account?.name, email: token.account?.email } };
196
+ saveGatewayLogin(login);
197
+ return { ...login, balance: token.account };
198
+ } finally {
199
+ clearTimeout(timer);
200
+ signal?.removeEventListener('abort', onAbort);
201
+ server.close();
202
+ }
203
+ }
204
+
205
+ export const formatUsd = (value) => {
206
+ const n = Number(value);
207
+ return Number.isFinite(n) ? `$${n.toFixed(n !== 0 && Math.abs(n) < 0.01 ? 4 : 2)}` : '-';
208
+ };
package/src/hooks.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // let through, unless the hook says "onFailure": "block" (as in Claude Code): then they block like exit code 2.
9
9
  // <system-reminder> tags in a hook's output are escaped, so that it cannot pass itself off as the harness.
10
10
 
11
- import { spawnShell, killTree, findShell, watchShell } from './utils/shell.js';
11
+ import { childEnv, spawnShell, killTree, findShell, watchShell } from './utils/shell.js';
12
12
  import { stripAnsi } from './ui/ansi.js';
13
13
 
14
14
  const DEFAULT_TIMEOUT_MS = 60_000;
@@ -28,7 +28,7 @@ function runCommand(shell, command, { cwd, payload, timeout, signal }) {
28
28
  const json = JSON.stringify(payload);
29
29
  child = spawnShell(shell, command, {
30
30
  cwd,
31
- env: { ...process.env, CLAUDE_PRO_HOOK_INPUT: json, CLAUDE_PROJECT_DIR: cwd, CLAUDE_PRO: '1' },
31
+ env: { ...childEnv(), CLAUDE_PRO_HOOK_INPUT: json, CLAUDE_PROJECT_DIR: cwd },
32
32
  stdin: json,
33
33
  });
34
34
  } catch (e) {
package/src/keepalive.js CHANGED
@@ -41,7 +41,7 @@ export class CacheKeepAlive {
41
41
  const cfg = a.config;
42
42
  if (a.isSubagent || a.busy > 0 || !(this.hours > 0)) return false;
43
43
  const id = a.model?.id || '';
44
- if (!/^claude-/i.test(id) || cfg.promptCachingDisabled(id)) return false;
44
+ if (!/^claude-/i.test(id) || cfg.promptCachingDisabled()) return false;
45
45
  if (!a.cache.isWarm(now) || a.cache.ttl !== '1h' || (a.cache.expected || 0) < MIN_TOKENS) return false;
46
46
  // A raised effort ends with the next user request, and with it this entry (the effort is part of its key).
47
47
  if (cfg.effortBoost && !cfg.effortBoostKeepNext) return false;
package/src/main.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
- import { VERSION, KNOWN_KEYS, loadConfig, settingsFiles, updateSettingsFile, applyRememberedChoices } from './config.js';
2
+ import { VERSION, loadConfig, settingsFiles, configKey, configEntries, writeConfigSetting, unsetConfigSetting, applyRememberedChoices } from './config.js';
3
+ import { loadGatewayModels } from './gateway.js';
3
4
  import { resolvePath } from './utils/paths.js';
4
5
  import { SessionStore } from './session.js';
5
6
  import { takeRestartState } from './restart.js';
@@ -13,7 +14,6 @@ Options:
13
14
  -p, --print Print the response and exit (useful for pipes)
14
15
  -c, --continue Continue the most recent conversation in this directory
15
16
  -r, --resume [sessionId] Resume a conversation (picker if no id given)
16
- --provider <backend> gateway only (the codex-gateway account)
17
17
  --model <model> Model for this session (name or alias: opus, sonnet, haiku)
18
18
  --effort <level> Reasoning effort: none|minimal|low|medium|high|xhigh|max
19
19
  --output-format <format> text | json | stream-json (with --print)
@@ -21,7 +21,7 @@ Options:
21
21
  --append-system-prompt <text> Append text to the system prompt
22
22
  --system-prompt <text> Replace the system prompt
23
23
  --system-prompt-file <file> Replace the system prompt with the contents of a file
24
- --verbose Show thinking and full tool output
24
+ --verbose Show detailed tool output
25
25
  --no-mcp Do not start MCP servers
26
26
  --name <name> Name this session, as /rename does (other sessions reach it with @name)
27
27
  -v, --version Print version
@@ -34,7 +34,7 @@ are accepted and ignored, and so are --plan (there is no plan mode: ask for a pl
34
34
  --remote-control (--rc): a session is online at the gateway whenever this computer is logged in to it.
35
35
 
36
36
  Commands:
37
- claude-pro config list Show effective configuration and where each value comes from
37
+ claude-pro config list [--advanced] Show ordinary settings (add --advanced for optional controls)
38
38
  claude-pro config set <KEY> <VALUE> [--project|--local] Save a setting (default: ~/.claude-pro/settings.json)
39
39
  claude-pro config unset <KEY> [--project|--local]
40
40
  Interactive prompt commands:
@@ -62,7 +62,6 @@ function parseArgs(argv) {
62
62
  if (argv[i + 1] && !argv[i + 1].startsWith('-') && /^[0-9a-f-]{8,}$/i.test(argv[i + 1])) flags.resumeId = next();
63
63
  break;
64
64
  case '--model': flags.model = next(); break;
65
- case '--provider': flags.provider = next(); break;
66
65
  case '--effort': flags.effort = next(); break;
67
66
  case '--plan': break; // no plan mode any more: asking for a plan in the message does it
68
67
  case '--permission-mode': next(); break;
@@ -88,45 +87,53 @@ function parseArgs(argv) {
88
87
  return { flags, positional };
89
88
  }
90
89
 
91
- function configCommand(args, cwd) {
92
- const [sub, key, ...rest] = args;
93
- const scopeFlag = rest.find((r) => r === '--project' || r === '--local') || (key === '--project' || key === '--local' ? key : null);
90
+ async function configCommand(args, cwd) {
91
+ const [sub = 'list', ...tail] = args;
92
+ const scopeFlag = tail.includes('--project') ? '--project' : tail.includes('--local') ? '--local' : null;
93
+ const advanced = sub === 'advanced' || tail.includes('--advanced');
94
+ const [key, ...rest] = tail.filter((r) => !['--project', '--local', '--advanced'].includes(r));
94
95
  const files = settingsFiles(cwd);
95
96
  const file = scopeFlag === '--project' ? files.project : scopeFlag === '--local' ? files.local : files.user;
96
- if (!sub || sub === 'list' || sub === 'get') {
97
- const cfg = loadConfig({ cwd });
98
- const remembered = applyRememberedChoices(cfg);
99
- const keys = sub === 'get' && key ? [key] : Object.keys(KNOWN_KEYS);
100
- for (const k of keys) {
101
- const v = cfg.display(k);
102
- if (v === undefined && sub !== 'get') continue;
103
- console.log(`${k}=${v ?? ''}${cfg.sources[k] ? ` # ${cfg.sources[k]}` : ''}`);
104
- }
105
- if (sub !== 'get') {
106
- console.log(`\nprovider: ${cfg.provider} (${cfg.endpointLabel})`);
107
- console.log(`model: ${cfg.model.label} (context ${cfg.model.contextWindow.toLocaleString()})${cfg.effort ? `, effort ${cfg.effort}` : ''}`);
108
- if (remembered.model || remembered.effort) {
109
- const what = Object.entries(remembered).map(([k, v]) => `${k} ${v}`).join(', ');
110
- console.log(`chosen with /model, /effort: ${what} (kept in ${files.user}; wins over the settings above, --model/--effort win over it)`);
97
+ try {
98
+ if (sub === 'list' || sub === 'advanced' || sub === 'get') {
99
+ const cfg = loadConfig({ cwd });
100
+ const remembered = applyRememberedChoices(cfg);
101
+ if (sub === 'get' && key) {
102
+ const name = configKey(key);
103
+ console.log(`${name}=${cfg.setting(name) ?? ''}${cfg.sources[name] ? ` # ${cfg.sources[name]}` : ''}`);
104
+ } else {
105
+ for (const entry of configEntries(cfg, { advanced })) {
106
+ console.log(`${entry.key}=${entry.value ?? '(default)'} # ${entry.source}${advanced ? ` · ${entry.description}` : ''}`);
107
+ }
108
+ }
109
+ if (sub !== 'get') {
110
+ await loadGatewayModels(cfg);
111
+ console.log(`\ngateway: ${cfg.endpointLabel}`);
112
+ console.log(`model: ${cfg.model.label} (context ${cfg.model.contextWindow.toLocaleString()})${cfg.effort ? `, effort ${cfg.effort}` : ''}`);
113
+ if (remembered.model || remembered.effort) {
114
+ const what = Object.entries(remembered).map(([k, v]) => `${k} ${v}`).join(', ');
115
+ console.log(`chosen with /model, /effort: ${what} (kept in ${files.user}; wins over the settings above, --model/--effort win over it)`);
116
+ }
117
+ console.log(`auto-compact at ${cfg.compactWindow().toLocaleString()} tokens (the window, less room for the summary)`);
118
+ if (!advanced) console.log('More controls: claude-pro config list --advanced');
111
119
  }
112
- console.log(`auto-compact at ${cfg.autoCompactThreshold().toLocaleString()} tokens (window ${cfg.compactWindow().toLocaleString()})`);
120
+ return 0;
113
121
  }
114
- return 0;
115
- }
116
- if (sub === 'set') {
117
- const value = rest.filter((r) => r !== '--project' && r !== '--local').join(' ');
118
- if (!key || !value) { console.error('Usage: claude-pro config set <KEY> <VALUE> [--project|--local]'); return 2; }
119
- if (!KNOWN_KEYS[key]) console.error(`note: ${key} is not a known key; saving anyway`);
120
- updateSettingsFile(file, (json) => { json.env = { ...(json.env || {}), [key]: value }; });
121
- console.log(`Set ${key} in ${file}`);
122
- return 0;
123
- }
124
- if (sub === 'unset') {
125
- updateSettingsFile(file, (json) => { if (json.env) delete json.env[key]; });
126
- console.log(`Removed ${key} from ${file}`);
127
- return 0;
128
- }
129
- console.error(`Unknown config command: ${sub}`);
122
+ if (sub === 'set') {
123
+ const value = rest.join(' ');
124
+ if (!key || !value) { console.error('Usage: claude-pro config set <KEY> <VALUE> [--project|--local]'); return 2; }
125
+ const name = writeConfigSetting(file, key, value);
126
+ console.log(`Set ${name} in ${file}`);
127
+ return 0;
128
+ }
129
+ if (sub === 'unset') {
130
+ if (!key) { console.error('Usage: claude-pro config unset <KEY> [--project|--local]'); return 2; }
131
+ const name = unsetConfigSetting(file, key);
132
+ console.log(`Removed ${name} from ${file}`);
133
+ return 0;
134
+ }
135
+ console.error(`Unknown config command: ${sub}`);
136
+ } catch (e) { console.error(e.message); }
130
137
  return 2;
131
138
  }
132
139
 
@@ -215,6 +222,11 @@ export async function main(argv) {
215
222
  }
216
223
 
217
224
  // mintty (Git Bash's default window) connects programs through pipes, not a console.
225
+ // -r without an id opens the picker of an interactive session; a -p run has none, and went on as a new conversation
226
+ if (flags.resume && !flags.resumeId && (flags.print || !process.stdout.isTTY || !process.stdin.isTTY)) {
227
+ process.stderr.write('Error: -r without a conversation id needs an interactive session to pick one. Give the id (-r <id>), or use -c for the newest conversation.\n');
228
+ return 2;
229
+ }
218
230
  if (!flags.print && !process.stdin.isTTY && process.env.TERM_PROGRAM === 'mintty') {
219
231
  process.stderr.write('Interactive mode needs a real console. In mintty/Git Bash run `winpty claude-pro` (or `winpty node bin/claude-pro.js`), or use Windows Terminal. For scripts use `claude-pro -p`.\n');
220
232
  return 1;
package/src/mcp.js CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { spawn } from 'node:child_process';
7
7
  import { VERSION } from './config.js';
8
- import { killTreeSync } from './utils/shell.js';
8
+ import { childEnv, killTreeSync } from './utils/shell.js';
9
9
 
10
10
  const PROTOCOL_VERSION = '2025-06-18';
11
11
  const isWin = process.platform === 'win32';
@@ -32,7 +32,7 @@ class StdioTransport {
32
32
  }
33
33
 
34
34
  async connect() {
35
- const env = { ...process.env };
35
+ const env = childEnv();
36
36
  for (const [k, v] of Object.entries(this.cfg.env || {})) env[k] = expandEnv(v);
37
37
  const command = expandEnv(this.cfg.command);
38
38
  const args = (this.cfg.args || []).map(expandEnv);
package/src/peers.js CHANGED
@@ -11,6 +11,7 @@ import path from 'node:path';
11
11
  import http from 'node:http';
12
12
  import crypto from 'node:crypto';
13
13
  import { CONFIG_DIR } from './config.js';
14
+ import { processAlive as alive } from './utils/shell.js';
14
15
 
15
16
  export const PEERS_DIR = path.join(CONFIG_DIR, 'peers');
16
17
  const MAX_BODY = 2_000_000;
@@ -19,10 +20,6 @@ export function peersEnabled(env = process.env) {
19
20
  return !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_PEERS || '');
20
21
  }
21
22
 
22
- function alive(pid) {
23
- try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
24
- }
25
-
26
23
  export const cleanName = (s) => String(s || '').replace(/[^\p{L}\p{M}\p{N}_.-]+/gu, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 40) || 'agent';
27
24
 
28
25
  // The sessions that are running now (stale entries of sessions that died are removed).
@@ -113,12 +110,6 @@ export class PeerNode {
113
110
  return n;
114
111
  }
115
112
 
116
- setCwd(cwd) {
117
- if (cwd === this.cwd) return;
118
- this.cwd = cwd;
119
- this.write();
120
- }
121
-
122
113
  write() {
123
114
  if (!this.port) return;
124
115
  fs.mkdirSync(PEERS_DIR, { recursive: true });