@yanzc/claude-pro 0.9.0 → 0.9.1

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 (55) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +79 -13
  4. package/src/agents.js +3 -2
  5. package/src/api.js +39 -34
  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 +169 -67
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +143 -143
  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 +5 -61
  27. package/src/ratelimit.js +2 -4
  28. package/src/remote.js +26 -10
  29. package/src/runtime.js +33 -10
  30. package/src/selfcheck.js +3 -3
  31. package/src/session.js +93 -3
  32. package/src/supervisor.js +10 -1
  33. package/src/tools/bash.js +18 -17
  34. package/src/tools/browser.js +365 -0
  35. package/src/tools/code.js +430 -0
  36. package/src/tools/effort.js +3 -4
  37. package/src/tools/files.js +92 -19
  38. package/src/tools/index.js +6 -0
  39. package/src/tools/notebook.js +11 -4
  40. package/src/tools/processes.js +274 -0
  41. package/src/tools/search.js +33 -8
  42. package/src/tools/web.js +316 -46
  43. package/src/trace.js +0 -4
  44. package/src/ui/ansi.js +92 -13
  45. package/src/ui/dialogs.js +16 -54
  46. package/src/ui/editor.js +231 -34
  47. package/src/ui/markdown.js +1 -2
  48. package/src/ui/render.js +1 -2
  49. package/src/ui/repl.js +185 -104
  50. package/src/ui/screen.js +139 -31
  51. package/src/updater.js +135 -165
  52. package/src/utils/clipboard.js +5 -3
  53. package/src/utils/paths.js +15 -17
  54. package/src/utils/shell.js +66 -11
  55. package/.env.example +0 -29
package/src/config.js CHANGED
@@ -1,14 +1,14 @@
1
- // Configuration loading. Mirrors Claude Code's environment variables so the same
2
- // settings work here. Sources, lowest precedence first:
1
+ // Ordinary settings live at the top level of settings.json; optional advanced keys live in its env block.
2
+ // Sources, lowest precedence first:
3
3
  // 1. built-in defaults
4
- // 2. <install dir>/.env
5
- // 3. ~/.claude-pro/settings.json ("env" block)
6
- // 4. <project>/.claude-pro/settings.json ("env" block)
7
- // 5. <project>/.claude-pro/settings.local.json
8
- // 6. process environment
9
- // 7. command line flags (--model, --effort ...)
4
+ // 2. ~/.claude-pro/settings.json
5
+ // 3. <project>/.claude-pro/settings.json
6
+ // 4. <project>/.claude-pro/settings.local.json
7
+ // 5. process environment (advanced keys only)
8
+ // 6. command line flags (--model, --effort ...)
10
9
  // The model and effort chosen with /model and /effort are remembered apart from these (see
11
- // rememberChoice) and win over 1-6.
10
+ // rememberChoice) and win over 1-5. The gateway key comes from /login alone (gateway.json, see
11
+ // gatewayLogin): there is no variable for it, and no .env file is read.
12
12
 
13
13
  import fs from 'node:fs';
14
14
  import path from 'node:path';
@@ -23,83 +23,103 @@ export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.u
23
23
  export const SOURCE_CHECKOUT = fs.existsSync(path.join(INSTALL_DIR, '.git'));
24
24
  export const CONFIG_DIR = process.env.CLAUDE_PRO_CONFIG_DIR || path.join(os.homedir(), '.claude-pro');
25
25
  export const APP_NAME = 'claude-pro';
26
- export const PROVIDERS = ['gateway'];
27
26
  export const GATEWAY_DEFAULT_URL = 'https://gw.predix.icu';
28
27
  export const VERSION = JSON.parse(fs.readFileSync(path.join(INSTALL_DIR, 'package.json'), 'utf8')).version;
29
28
 
30
- // Every key we understand, with a short description (shown by /config).
29
+ // The ordinary settings /config shows. `legacy`: the old spelling accepted in settings.json.env and by config
30
+ // commands, but no longer read from the process environment. Writes use only the ordinary spelling.
31
+ export const BASIC_SETTINGS = {
32
+ model: { default: 'opus', legacy: 'CLAUDE_PRO_GATEWAY_MODEL', description: 'Default model; /model and --model override it' },
33
+ effort: { default: 'auto', legacy: 'CLAUDE_CODE_EFFORT_LEVEL', description: 'Reasoning effort; /effort and --effort override it' },
34
+ tui: { default: 'fullscreen', legacy: 'CLAUDE_PRO_TUI', description: 'fullscreen or default; /tui switches and remembers it' },
35
+ promptCacheTtl: { default: '1h', legacy: 'CLAUDE_CODE_PROMPT_CACHE_TTL', description: 'Conversation prompt cache: 5m or 1h' },
36
+ subagentPromptCacheTtl: { default: '5m', legacy: 'CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL', description: 'Sub-agent, compaction and side-query prompt cache: 5m or 1h' },
37
+ };
38
+
39
+ // Advanced keys, shown only by /config advanced (or config list --advanced). Settings files may also carry
40
+ // unrelated env entries; those are left alone, but are not advertised as configuration of this program.
31
41
  export const KNOWN_KEYS = {
32
- CLAUDE_PRO_PROVIDER: 'Authentication backend: gateway only (codex-gateway account, /login)',
33
42
  CLAUDE_PRO_GATEWAY_URL: `codex-gateway address (default https://gw.predix.icu)`,
34
- CLAUDE_PRO_GATEWAY_API_KEY: 'Gateway API key (normally saved by /login in gateway.json)',
35
- CLAUDE_PRO_GATEWAY_MODEL: 'Model with the gateway provider (default: opus; also sonnet, haiku, gpt-6.1-sol)',
36
43
  CLAUDE_PRO_ONLINE: 'Set to 0 to keep interactive sessions off the gateway. Otherwise a session is online on the gateway\'s web page whenever this computer is logged in, and sessions on your other computers can send it tasks (@computer/name)',
37
44
  CLAUDE_PRO_REMOTE_COMMANDS: 'Set to 0 to make this computer\'s sessions read-only on the gateway\'s web page: it can watch them, but not send them messages, answer their questions, stop them, switch model or effort, or change their directory (default: on; read when a session goes online)',
38
45
  CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
39
- CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside) or default (classic: it scrolls in the terminal); /tui switches',
40
- CLAUDE_PRO_AUTO_RESTART: 'Restart by itself when a turn ends and claude-pro\'s own source files changed (default 1; 0 = only on /restart or the Restart tool)',
41
46
 
42
- CLAUDE_CODE_EFFORT_LEVEL: 'Reasoning effort: none|minimal|low|medium|high|xhigh|max (sent as output_config.effort)',
43
- CLAUDE_CODE_AUTO_COMPACT_WINDOW: 'Context size (tokens) used for auto-compaction calculations',
44
- CLAUDE_AUTOCOMPACT_PCT_OVERRIDE: 'Percentage (1-100) of the window at which auto-compaction triggers',
45
- DISABLE_AUTOCOMPACT: 'Set to 1 to disable auto-compaction',
46
47
  CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default 48000; lowered automatically if the gateway allows less)',
47
48
  MAX_THINKING_TOKENS: 'Thinking budget: 0 disables thinking, N enables with budget N',
48
- CLAUDE_CODE_PROMPT_CACHE_TTL: 'Prompt cache TTL of the conversation itself: 5m or 1h (default: 1h with the gateway; 1h writes cost more, they pay off when you pause for more than 5 minutes). Also the promptCacheTtl setting',
49
- CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 'Prompt cache TTL of everything else (sub-agents, compaction, side queries): 5m (default) or 1h. Also the subagentPromptCacheTtl setting',
50
- ENABLE_PROMPT_CACHING_1H: 'Set to 1 to request the 1-hour TTL for both (the two TTL variables above win over it)',
51
- FORCE_PROMPT_CACHING_5M: 'Set to 1 to force the 5-minute TTL for both, over every other TTL setting',
52
49
  CLAUDE_PRO_CACHE_KEEPALIVE_HOURS: 'Claude models with the 1-hour TTL: while you are away, refresh the conversation\'s prompt cache shortly before it runs out (a read costs 1/40 of a rewrite), for a pause of up to this many hours (default 8; 0 turns it off)',
53
50
  DISABLE_PROMPT_CACHING: 'Set to 1 to send no cache_control markers at all (prompt caching off for every model)',
54
- DISABLE_PROMPT_CACHING_HAIKU: 'Set to 1 to turn prompt caching off for the model the haiku alias resolves to',
55
- DISABLE_PROMPT_CACHING_SONNET: 'Set to 1 to turn prompt caching off for the model the sonnet alias resolves to',
56
- DISABLE_PROMPT_CACHING_OPUS: 'Set to 1 to turn prompt caching off for the model the opus alias resolves to',
57
- DISABLE_PROMPT_CACHING_FABLE: 'Set to 1 to turn prompt caching off for Fable models',
58
51
  API_TIMEOUT_MS: 'Request timeout in milliseconds',
59
52
  CLAUDE_PRO_MAX_RETRIES: 'Retries for failed API requests (0 = no retries at all, which also turns off the rate limit wait)',
60
53
  CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS: 'Longest total time to wait for a rate limit (e.g. the 5-hour window) to reset before continuing by itself (default 21600000 = 6 hours; 0 = report the error instead of waiting)',
61
- CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS: 'First wait before retrying a request refused as overloaded (529); doubled at each retry (default 1000)',
62
- CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS: 'Longest wait between retries of an overloaded (529) request (default 32000)',
63
- CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS: 'How long to keep retrying an overloaded (529) API once the usual retries are used up, before reporting the error (default: CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS, 6 hours; 0 = give up after the retries)',
64
- BASH_DEFAULT_TIMEOUT_MS: 'Default timeout for Bash commands (default 600000 = 10 minutes)',
65
- BASH_MAX_TIMEOUT_MS: 'Maximum timeout the model may request for Bash commands (default 3600000 = 1 hour)',
66
- BASH_MAX_OUTPUT_LENGTH: 'Max characters of Bash output returned to the model; the full text is saved to a file (default 60000)',
67
54
  CLAUDE_CODE_GIT_BASH_PATH: 'Windows: path to bash.exe (Git Bash)',
68
55
  CLAUDE_PRO_RIPGREP_PATH: 'Path to ripgrep (rg) for Grep and @-file suggestions; "off" forces the built-in JS scanner (default: rg from PATH, else the JS scanner)',
56
+ CLAUDE_PRO_BROWSER: 'The browser the Browser tool drives: auto (default: the first of Edge, Chrome, Brave, Chromium whose remote debugging is turned on, at edge://inspect/#remote-debugging and the like), edge, chrome, brave, chromium, own (claude-pro\'s own Chrome profile, nothing to allow), a DevTools address (ws://…, http://host:port, a port), or off (no Browser tool)',
57
+ CLAUDE_PRO_PYTHON: 'The Python interpreter the REPL tool runs (default: python on Windows, python3 elsewhere, from PATH)',
69
58
  CLAUDE_PRO_VERIFY_COMMAND: 'Command run after the agent edits files (e.g. "npm test"); failures are sent back to fix',
70
59
  CLAUDE_PRO_DISABLE_AUTO_MEMORY: 'Set to 1 to turn off the persistent per-project memory',
71
60
  CLAUDE_PRO_DISABLE_TOPIC_TITLE: 'Set to 1 to stop asking the current model for the current topic after each message (the tab title then shows the first message of the session)',
72
61
  CLAUDE_PRO_TRACE: 'Set to 0 to disable the privacy-preserving runtime JSONL trace (enabled by default)',
73
- CLAUDE_PRO_TRACE_DIR: 'Directory for runtime trace files (default: the project session directory)',
74
- CLAUDE_PRO_TRACE_MAX_SIZE: 'Maximum size of one runtime trace file in bytes before rotating it (default 20 MB)',
75
62
  };
76
63
 
77
- const SECRET_KEYS = new Set(['CLAUDE_PRO_GATEWAY_API_KEY']);
64
+ function basicValue(key, value) {
65
+ if (typeof value !== 'string') throw new Error(`${key} must be a string.`);
66
+ const text = value.trim();
67
+ if (key === 'model') {
68
+ if (!text) throw new Error('model must not be empty.');
69
+ return text;
70
+ }
71
+ const normalized = text.toLowerCase();
72
+ if (key === 'effort' && ['auto', 'default', 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(normalized)) return normalized;
73
+ if (key === 'tui' && ['fullscreen', 'default'].includes(normalized)) return normalized;
74
+ if ((key === 'promptCacheTtl' || key === 'subagentPromptCacheTtl') && normalizeTtl(normalized)) return normalized;
75
+ throw new Error(`Invalid ${key}: ${text}. ${BASIC_SETTINGS[key].description}.`);
76
+ }
77
+
78
+ // The supported spelling, or an error instead of saving a setting that will do nothing.
79
+ export function configKey(key) {
80
+ if (Object.hasOwn(BASIC_SETTINGS, key) || Object.hasOwn(KNOWN_KEYS, key)) return key;
81
+ const alias = Object.entries(BASIC_SETTINGS).find(([, spec]) => spec.legacy === key);
82
+ if (alias) return alias[0];
83
+ throw new Error(`Unknown setting: ${key}. Use /config for ordinary settings or /config advanced for advanced settings.`);
84
+ }
78
85
 
79
- export function parseDotEnv(text) {
80
- const env = {};
81
- for (let line of text.split(/\r?\n/)) {
82
- line = line.trim();
83
- if (!line || line.startsWith('#')) continue;
84
- if (line.startsWith('export ')) line = line.slice(7);
85
- const eq = line.indexOf('=');
86
- if (eq <= 0) continue;
87
- const key = line.slice(0, eq).trim();
88
- let val = line.slice(eq + 1).trim();
89
- if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
90
- val = val.slice(1, -1);
91
- if (line[eq + 1] === '"') val = val.replace(/\\n/g, '\n');
92
- } else {
93
- val = val.replace(/\s+#.*$/, '');
86
+ // Shared by the terminal and slash commands, so both list and write the same settings.
87
+ export function configEntries(config, { advanced = false } = {}) {
88
+ const keys = [...Object.keys(BASIC_SETTINGS), ...(advanced ? Object.keys(KNOWN_KEYS) : [])];
89
+ return keys.map((key) => ({ key, value: config.setting(key), source: config.sources[key] || 'default', description: BASIC_SETTINGS[key]?.description || KNOWN_KEYS[key] }));
90
+ }
91
+
92
+ export function writeConfigSetting(file, key, value) {
93
+ key = configKey(key);
94
+ const basic = BASIC_SETTINGS[key];
95
+ const normalized = basic ? basicValue(key, value) : String(value);
96
+ updateSettingsFile(file, (json) => {
97
+ if (basic) {
98
+ json[key] = normalized;
99
+ if (json.env) { delete json.env[basic.legacy]; if (!Object.keys(json.env).length) delete json.env; }
100
+ } else json.env = { ...(json.env || {}), [key]: normalized };
101
+ });
102
+ return key;
103
+ }
104
+
105
+ export function unsetConfigSetting(file, key) {
106
+ // Unknown env names may still be removed, including settings that this program no longer reads.
107
+ try { key = configKey(key); } catch { /* old or unrelated env name */ }
108
+ updateSettingsFile(file, (json) => {
109
+ const basic = Object.hasOwn(BASIC_SETTINGS, key) ? BASIC_SETTINGS[key] : null;
110
+ if (basic) delete json[key];
111
+ if (json.env) {
112
+ delete json.env[basic?.legacy || key];
113
+ if (!Object.keys(json.env).length) delete json.env;
94
114
  }
95
- env[key] = val;
96
- }
97
- return env;
115
+ });
116
+ return key;
98
117
  }
99
118
 
100
119
  function readJson(file) {
101
120
  try {
102
- return JSON.parse(fs.readFileSync(file, 'utf8'));
121
+ // a BOM in front (Windows PowerShell's Set-Content -Encoding UTF8 writes one) made the whole file unreadable
122
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
103
123
  } catch (e) {
104
124
  if (e.code !== 'ENOENT') process.stderr.write(`warning: could not parse ${file}: ${e.message}\n`);
105
125
  return null;
@@ -114,9 +134,8 @@ export function settingsFiles(cwd) {
114
134
  };
115
135
  }
116
136
 
117
- const MODEL_KEYS = { gateway: 'CLAUDE_PRO_GATEWAY_MODEL' };
118
137
 
119
- export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.join(INSTALL_DIR, '.env') } = {}) {
138
+ export function loadConfig({ cwd = process.cwd(), flags = {} } = {}) {
120
139
  const env = {};
121
140
  const sources = {};
122
141
  const set = (obj, source) => {
@@ -127,24 +146,23 @@ export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.
127
146
  }
128
147
  };
129
148
 
130
- if (fs.existsSync(dotEnvFile)) set(parseDotEnv(fs.readFileSync(dotEnvFile, 'utf8')), dotEnvFile);
131
-
132
149
  const files = settingsFiles(cwd);
133
150
  // Settings files can still carry "permissions" from other tools; there are no permission rules here, so they are ignored.
134
151
  const settings = { mcpServers: {}, hooks: {} };
135
152
  for (const [scope, file] of Object.entries(files)) {
136
153
  const json = readJson(file);
137
154
  if (!json) continue;
138
- // Claude Code's settings for the prompt cache TTL. They stay settings (the variables rank above them, whichever
139
- // file they come from; see Config.cacheTtl); a later file's setting replaces an earlier one's.
140
- if (json.promptCacheTtl !== undefined) settings.promptCacheTtl = json.promptCacheTtl;
141
- if (json.subagentPromptCacheTtl !== undefined) settings.subagentPromptCacheTtl = json.subagentPromptCacheTtl;
142
155
  set(json.env, file);
156
+ for (const [key, spec] of Object.entries(BASIC_SETTINGS)) {
157
+ // A top-level field wins over its legacy spelling in the same file; later files win over earlier ones.
158
+ const value = json[key] ?? json.env?.[spec.legacy];
159
+ if (value == null) continue;
160
+ try { settings[key] = basicValue(key, value); sources[key] = file; } catch { /* invalid: use the earlier value or default */ }
161
+ }
143
162
  if (json.mcpServers) Object.assign(settings.mcpServers, json.mcpServers);
144
163
  for (const [event, entries] of Object.entries(json.hooks || {})) {
145
164
  if (Array.isArray(entries)) (settings.hooks[event] ||= []).push(...entries);
146
165
  }
147
- if (json.model) { env.CLAUDE_PRO_GATEWAY_MODEL = json.model; sources.CLAUDE_PRO_GATEWAY_MODEL = `${file} (model)`; }
148
166
  settings[scope] = json;
149
167
  }
150
168
  // Project level .mcp.json, same format as Claude Code.
@@ -155,13 +173,9 @@ export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.
155
173
  for (const k of Object.keys(KNOWN_KEYS)) if (process.env[k] !== undefined && process.env[k] !== '') fromProcess[k] = process.env[k];
156
174
  set(fromProcess, 'process environment');
157
175
 
158
- if (flags.provider) { env.CLAUDE_PRO_PROVIDER = flags.provider; sources.CLAUDE_PRO_PROVIDER = '--provider flag'; }
159
- if (flags.model) {
160
- const key = MODEL_KEYS[(env.CLAUDE_PRO_PROVIDER || 'gateway').trim().toLowerCase()] || 'CLAUDE_PRO_GATEWAY_MODEL';
161
- env[key] = flags.model;
162
- sources[key] = '--model flag';
176
+ for (const key of ['model', 'effort']) {
177
+ if (flags[key]) { settings[key] = basicValue(key, flags[key]); sources[key] = `--${key} flag`; }
163
178
  }
164
- if (flags.effort) { env.CLAUDE_CODE_EFFORT_LEVEL = flags.effort; sources.CLAUDE_CODE_EFFORT_LEVEL = '--effort flag'; }
165
179
 
166
180
  return new Config(env, sources, settings, cwd);
167
181
  }
@@ -172,6 +186,16 @@ const int = (v, d) => {
172
186
  };
173
187
  const isOn = (v) => /^(1|true|yes)$/i.test(String(v ?? '').trim());
174
188
 
189
+ // The input window of each model a gateway serves (max_input_tokens in its GET /v1/models, which fetchGatewayModels
190
+ // passes on here), by gateway and model id: what resolveModel takes once the list is in.
191
+ const servedWindows = new Map();
192
+ export function noteServedModels(url, models) {
193
+ for (const m of models || []) {
194
+ const tokens = Number(m?.max_input_tokens);
195
+ if (typeof m?.id === 'string' && Number.isInteger(tokens) && tokens > 0) servedWindows.set(`${url}\n${m.id}`, tokens);
196
+ }
197
+ }
198
+
175
199
  export class Config {
176
200
  constructor(env, sources, settings, cwd) {
177
201
  this.env = env;
@@ -185,12 +209,6 @@ export class Config {
185
209
  this.verifyOverride = null; // set by /verify or --verify during a session
186
210
  }
187
211
 
188
- get provider() {
189
- const value = (this.env.CLAUDE_PRO_PROVIDER || 'gateway').trim().toLowerCase();
190
- if (value !== 'gateway') throw new Error(`Only the gateway provider is supported. Set CLAUDE_PRO_PROVIDER=gateway (received ${value}).`);
191
- return 'gateway';
192
- }
193
- get usesGateway() { return true; }
194
212
  get gatewayUrl() { return (this.env.CLAUDE_PRO_GATEWAY_URL || GATEWAY_DEFAULT_URL).trim().replace(/\/+$/, ''); }
195
213
  get endpointLabel() { return `${this.gatewayUrl} (codex-gateway)`; }
196
214
 
@@ -198,7 +216,8 @@ export class Config {
198
216
  return { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' }[alias] || null;
199
217
  }
200
218
 
201
- // Resolve a model spec (alias or name, maybe with [1m]) to {id, contextWindow, label}.
219
+ // Resolve a model spec (alias or name, maybe with [1m]) to {id, contextWindow, label}. The window is the model's
220
+ // max_input_tokens from the gateway's model list, once loaded, else what is known of it here; [1m] asks for 1M.
202
221
  resolveModel(spec) {
203
222
  let name = (spec || '').trim() || 'sonnet';
204
223
  let oneM = false;
@@ -208,19 +227,27 @@ export class Config {
208
227
  const inner = this.resolveModel(aliased);
209
228
  return { ...inner, contextWindow: oneM ? 1_000_000 : inner.contextWindow, label: `${name}${oneM ? '[1m]' : ''} (${inner.label})` };
210
229
  }
230
+ const served = servedWindows.get(`${this.gatewayUrl}\n${name}`);
231
+ // GPT models are served by the gateway's Codex backend, whose standard window is 272k. A request above 272k costs
232
+ // twice as much (see pricing.js), but the user wants the gateway's window here too (2026-10-27).
233
+ if (/^gpt-/i.test(name)) return { id: name, contextWindow: served || 272_000, label: name };
211
234
  const nativeOneM = /^claude-(?:(?:sonnet|haiku)-5(?:-|$)|opus-(?:5(?:-|$)|4-[78](?:-|$)))/i.test(name);
212
- // GPT models are served by the gateway's Codex backend and use its standard context window.
213
- if (/^gpt-/i.test(name)) return { id: name, contextWindow: 272_000, label: name };
214
- return { id: name, contextWindow: oneM || nativeOneM ? 1_000_000 : 200_000, label: `${name}${oneM ? '[1m]' : ''}` };
235
+ return { id: name, contextWindow: oneM ? 1_000_000 : served || (nativeOneM ? 1_000_000 : 200_000), label: `${name}${oneM ? '[1m]' : ''}` };
215
236
  }
216
237
 
217
238
  // The selected model: the configured default unless /model has overridden it for this session.
218
- get configuredModelSpec() { return this.env.CLAUDE_PRO_GATEWAY_MODEL || 'opus'; }
239
+ get configuredModelSpec() { return this.setting('model'); }
240
+ get configuredEffort() { return this.setting('effort'); }
241
+
242
+ setting(key) {
243
+ const spec = BASIC_SETTINGS[key];
244
+ return spec ? this.settings[key] ?? spec.default : this.env[key];
245
+ }
219
246
  get modelSpec() { return this.modelOverride || this.configuredModelSpec; }
220
247
  get model() { return this.resolveModel(this.modelSpec); }
221
248
 
222
249
  get effort() {
223
- const v = (this.effortBoost ?? this.effortOverride ?? this.env.CLAUDE_CODE_EFFORT_LEVEL ?? '').trim().toLowerCase();
250
+ const v = (this.effortBoost ?? this.effortOverride ?? this.configuredEffort).trim().toLowerCase();
224
251
  return v && v !== 'auto' && v !== 'default' ? v : null;
225
252
  }
226
253
 
@@ -233,62 +260,33 @@ export class Config {
233
260
  get thinkingBudget() {
234
261
  return this.env.MAX_THINKING_TOKENS === undefined ? null : int(this.env.MAX_THINKING_TOKENS, null);
235
262
  }
236
- // Prompt cache TTL for a request bucket, by Claude Code's rules: "main" is the conversation itself, "other"
237
- // is everything else (sub-agents, compaction, side queries). In order: FORCE_PROMPT_CACHING_5M; the bucket's
238
- // own variable or setting; ENABLE_PROMPT_CACHING_1H; then the gateway default: the conversation's own
239
- // requests use 1 hour and everything else uses 5 minutes.
263
+ // The conversation uses the main TTL (default 1h); sub-agents, compaction and side queries use the other (5m).
240
264
  cacheTtl(bucket = 'main') {
241
- if (isOn(this.env.FORCE_PROMPT_CACHING_5M)) return '5m';
242
- // an invalid value is ignored, and the next rule applies (as in Claude Code)
243
- const own = bucket === 'main'
244
- ? normalizeTtl(this.env.CLAUDE_CODE_PROMPT_CACHE_TTL) || normalizeTtl(this.settings?.promptCacheTtl)
245
- : normalizeTtl(this.env.CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL) || normalizeTtl(this.settings?.subagentPromptCacheTtl);
265
+ const own = normalizeTtl(this.setting(bucket === 'main' ? 'promptCacheTtl' : 'subagentPromptCacheTtl'));
246
266
  if (own) return own;
247
- if (isOn(this.env.ENABLE_PROMPT_CACHING_1H)) return '1h';
248
267
  // The gateway too: measured on its usage records (533 Opus requests), pauses of 5 to 60 minutes rewrote the whole
249
268
  // conversation 9 times at 1.25x, $14.77; writing every turn at 2x instead costs $2.80 more.
250
- return bucket === 'main' && this.usesGateway ? '1h' : '5m';
251
- }
252
- // DISABLE_PROMPT_CACHING turns it off for everything; the per-model variables only for the model that
253
- // their alias resolves to (a different version pinned as the model keeps its caching), wherever it runs.
254
- promptCachingDisabled(modelId) {
255
- if (isOn(this.env.DISABLE_PROMPT_CACHING)) return true;
256
- for (const alias of ['haiku', 'sonnet', 'opus']) {
257
- if (!isOn(this.env[`DISABLE_PROMPT_CACHING_${alias.toUpperCase()}`])) continue;
258
- const target = this.aliasTarget(alias);
259
- if (target && this.resolveModel(target).id === modelId) return true;
260
- }
261
- return isOn(this.env.DISABLE_PROMPT_CACHING_FABLE) && /fable/i.test(modelId || '');
269
+ return bucket === 'main' ? '1h' : '5m';
262
270
  }
271
+ promptCachingDisabled() { return isOn(this.env.DISABLE_PROMPT_CACHING); }
263
272
  get apiTimeout() { return int(this.env.API_TIMEOUT_MS, 600_000); }
264
273
  get maxRetries() { return int(this.env.CLAUDE_PRO_MAX_RETRIES, 6); }
265
274
  get rateLimitMaxWait() { return Math.max(0, int(this.env.CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS, 6 * 3_600_000)); }
266
275
  // A rate limit that does not say when it resets is tried again at most this far apart.
267
276
  get rateLimitPoll() { return 300_000; }
268
277
  // An overloaded API (529): the backoff, and how long to keep trying once the retries are used up (see planRetry).
269
- get overloadedRetryBaseDelay() { return Math.max(100, int(this.env.CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS, 1000)); }
270
- get overloadedRetryMaxDelay() { return Math.max(this.overloadedRetryBaseDelay, int(this.env.CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS, 32_000)); }
271
- get overloadedMaxWait() { return Math.max(0, int(this.env.CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS, this.rateLimitMaxWait)); }
278
+ get overloadedRetryBaseDelay() { return 1000; }
279
+ get overloadedRetryMaxDelay() { return 32_000; }
280
+ get overloadedMaxWait() { return this.rateLimitMaxWait; }
272
281
 
273
- // Effective window for compaction: the configured auto-compact window capped by the model window. `own`: a
274
- // sub-agent's autoCompactWindow, which takes the place of the configured one.
282
+ // Always at the full input window; only sub-agent definitions may ask for a smaller window.
275
283
  compactWindow(model = this.model, own = 0) {
276
- const configured = own > 0 ? own : int(this.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW, 0);
277
- return configured > 0 ? Math.min(configured, model.contextWindow) : model.contextWindow;
278
- }
279
- get autoCompactEnabled() { return !/^(1|true|yes)$/i.test(this.env.DISABLE_AUTOCOMPACT || ''); }
280
- autoCompactThreshold(model = this.model, own = 0) {
281
- const window = this.compactWindow(model, own);
282
- const pct = int(this.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE, 0);
283
- if (pct > 0 && pct <= 100) return Math.floor(window * pct / 100);
284
- // Leave room for the summary itself and the next response (replies rarely come close to the
285
- // max_tokens ceiling, so the reserve is capped; an overflow is handled by compacting on the error).
286
- return Math.floor(window - Math.min(window * 0.2, Math.max(20_000, Math.min(this.maxOutputTokens, 64_000))));
284
+ return own > 0 ? Math.min(own, model.contextWindow) : model.contextWindow;
287
285
  }
288
286
 
289
- get bashDefaultTimeout() { return int(this.env.BASH_DEFAULT_TIMEOUT_MS, 600_000); }
290
- get bashMaxTimeout() { return int(this.env.BASH_MAX_TIMEOUT_MS, 3_600_000); }
291
- get bashMaxOutput() { return int(this.env.BASH_MAX_OUTPUT_LENGTH, 60_000); }
287
+ get bashDefaultTimeout() { return 600_000; }
288
+ get bashMaxTimeout() { return 3_600_000; }
289
+ get bashMaxOutput() { return 60_000; }
292
290
  // Tool results longer than this are saved to a file and only a preview is sent.
293
291
  get maxToolResultChars() { return 100_000; }
294
292
  // Clearing old tool results after a long pause (see Agent.clearAfterIdle): the gateway prompt cache has
@@ -321,18 +319,7 @@ export class Config {
321
319
  const value = this.env.CLAUDE_PRO_TRACE;
322
320
  return value === undefined || !/^(0|false|no|off)$/i.test(String(value).trim());
323
321
  }
324
- get traceDir() {
325
- const value = String(this.env.CLAUDE_PRO_TRACE_DIR || '').trim();
326
- return value ? path.resolve(this.cwd, value) : null;
327
- }
328
- get traceMaxBytes() { return Math.max(100_000, int(this.env.CLAUDE_PRO_TRACE_MAX_SIZE, 20 * 1024 * 1024)); }
329
322
 
330
- display(key) {
331
- const v = this.env[key];
332
- if (v === undefined) return undefined;
333
- if (SECRET_KEYS.has(key)) return v.length > 10 ? `${v.slice(0, 5)}…${v.slice(-4)}` : '****';
334
- return v;
335
- }
336
323
  }
337
324
 
338
325
  // Update the "env" block (or another top level key) of a settings file. A file that is there but is not
@@ -346,7 +333,17 @@ export function updateSettingsFile(file, mutate) {
346
333
  }
347
334
  mutate(json);
348
335
  fs.mkdirSync(path.dirname(file), { recursive: true });
349
- fs.writeFileSync(file, JSON.stringify(json, null, 2) + '\n');
336
+ // written aside and renamed over it, so that a crash or a full disk does not leave half a settings file; when the
337
+ // rename is refused (Windows: the file held open by another program), written in place as before
338
+ const text2 = JSON.stringify(json, null, 2) + '\n';
339
+ const tmp = `${file}.${process.pid}.tmp`;
340
+ try {
341
+ fs.writeFileSync(tmp, text2);
342
+ fs.renameSync(tmp, file);
343
+ } catch {
344
+ try { fs.rmSync(tmp, { force: true }); } catch { /* ignore */ }
345
+ fs.writeFileSync(file, text2);
346
+ }
350
347
  }
351
348
 
352
349
  // What /model and /effort chose, kept per provider in the "remembered" block of the user settings so that
@@ -355,14 +352,17 @@ export function updateSettingsFile(file, mutate) {
355
352
  // the command line win over it, for that run. "/model default" and "/effort default" forget it.
356
353
  const userSettingsFile = () => path.join(CONFIG_DIR, 'settings.json');
357
354
 
358
- export function rememberedChoices(provider) {
359
- const entry = readJson(userSettingsFile())?.remembered?.[provider];
355
+ // Kept under the name of the provider they were made with, from when there were others: the gateway's.
356
+ const REMEMBERED_KEY = 'gateway';
357
+
358
+ function rememberedChoices() {
359
+ const entry = readJson(userSettingsFile())?.remembered?.[REMEMBERED_KEY];
360
360
  return entry && typeof entry === 'object' ? entry : {};
361
361
  }
362
362
 
363
363
  // patch: {model?, effort?}; null or '' forgets that one. Returns whether the file changed.
364
- export function rememberChoice(provider, patch) {
365
- const before = rememberedChoices(provider);
364
+ export function rememberChoice(patch) {
365
+ const before = rememberedChoices();
366
366
  const after = { ...before };
367
367
  for (const [key, value] of Object.entries(patch)) {
368
368
  if (value === undefined) continue;
@@ -372,8 +372,8 @@ export function rememberChoice(provider, patch) {
372
372
  if (JSON.stringify(after) === JSON.stringify(before)) return false;
373
373
  updateSettingsFile(userSettingsFile(), (json) => {
374
374
  const all = json.remembered && typeof json.remembered === 'object' ? json.remembered : {};
375
- if (Object.keys(after).length) all[provider] = after;
376
- else delete all[provider];
375
+ if (Object.keys(after).length) all[REMEMBERED_KEY] = after;
376
+ else delete all[REMEMBERED_KEY];
377
377
  if (Object.keys(all).length) json.remembered = all;
378
378
  else delete json.remembered;
379
379
  });
@@ -381,7 +381,7 @@ export function rememberChoice(provider, patch) {
381
381
  }
382
382
 
383
383
  export function applyRememberedChoices(config, flags = {}) {
384
- const remembered = rememberedChoices(config.provider);
384
+ const remembered = rememberedChoices();
385
385
  if (!flags.model && typeof remembered.model === 'string' && remembered.model.trim()) config.modelOverride = remembered.model.trim();
386
386
  if (!flags.effort && typeof remembered.effort === 'string' && remembered.effort.trim()) config.effortOverride = remembered.effort.trim().toLowerCase();
387
387
  return remembered;
package/src/context.js CHANGED
@@ -4,22 +4,48 @@
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
- import { run } from './utils/shell.js';
7
+ import { run, runText } from './utils/shell.js';
8
8
  import { CONFIG_DIR } from './config.js';
9
9
 
10
+ // The git facts of the system prompt, or null outside a git repository. Four commands give them all (status -b
11
+ // names the branch too); seven ran one after another before, about 55 ms each on Windows, blocking the program for
12
+ // 400 ms at each start, /clear and compaction. gitInfoAsync runs them at once without blocking (75 ms).
13
+ // quotepath=false: file names with non-ASCII characters (Chinese ones) are shown as they are, not as "\344\275\240".
14
+ const GIT_STATUS = ['-c', 'core.quotepath=false', 'status', '--porcelain=v1', '-b'];
15
+ const GIT_MAIN = ['for-each-ref', '--format=%(refname:short)', 'refs/heads/main', 'refs/heads/master'];
16
+ const GIT_LOG = ['log', '--oneline', '-n', '5'];
17
+ const GIT_USER = ['config', 'user.name'];
18
+ const GIT_STATUS_MAX = 64 * 1024 * 1024;
19
+
10
20
  export function gitInfo(cwd) {
11
- const inside = run('git', ['rev-parse', '--is-inside-work-tree'], { cwd });
12
- if (inside !== 'true') return null;
13
- const branch = run('git', ['branch', '--show-current'], { cwd }) || '(detached)';
14
- let main = null;
15
- for (const b of ['main', 'master']) if (run('git', ['rev-parse', '--verify', '--quiet', b], { cwd }) !== null) { main = b; break; }
16
- // quotepath=false: file names with non-ASCII characters (Chinese ones) are shown as they are, not as "\344\275\240".
17
- let status = run('git', ['-c', 'core.quotepath=false', 'status', '--short'], { cwd }) || '';
18
- const statusLines = status.split('\n');
19
- if (statusLines.length > 40) status = statusLines.slice(0, 40).join('\n') + `\n... (${statusLines.length - 40} more lines, run "git status" for the rest)`;
20
- const log = run('git', ['log', '--oneline', '-n', '5'], { cwd }) || '';
21
- const user = run('git', ['config', 'user.name'], { cwd });
22
- return { branch, main, status, log, user };
21
+ const status = run('git', GIT_STATUS, { cwd, maxBuffer: GIT_STATUS_MAX });
22
+ if (status === null && run('git', ['rev-parse', '--is-inside-work-tree'], { cwd }) !== 'true') return null;
23
+ const branch = status === null ? run('git', ['branch', '--show-current'], { cwd }) : null;
24
+ return gitFacts(status, run('git', GIT_MAIN, { cwd }), run('git', GIT_LOG, { cwd }), run('git', GIT_USER, { cwd }), branch);
25
+ }
26
+
27
+ export async function gitInfoAsync(cwd) {
28
+ const [status, main, log, user] = await Promise.all([GIT_STATUS, GIT_MAIN, GIT_LOG, GIT_USER].map((args) => runText('git', args, { cwd, maxChars: GIT_STATUS_MAX })));
29
+ if (status === null && (await runText('git', ['rev-parse', '--is-inside-work-tree'], { cwd })) !== 'true') return null;
30
+ const branch = status === null ? await runText('git', ['branch', '--show-current'], { cwd }) : null;
31
+ return gitFacts(status, main, log, user, branch);
32
+ }
33
+
34
+ // `statusOut`: git status -b's output, null when it failed or took too long (a huge tree), which is not a clean
35
+ // tree (status null). `branch`: the branch when status gave none.
36
+ function gitFacts(statusOut, mainOut, log, user, branch) {
37
+ let status = null;
38
+ if (statusOut !== null) {
39
+ const lines = statusOut.split('\n');
40
+ const head = lines[0]?.startsWith('## ') ? lines.shift().slice(3) : '';
41
+ // "main...origin/main [ahead 1]", "main", "No commits yet on main", "HEAD (no branch)"
42
+ branch = /^HEAD \(no branch\)/.test(head) ? '' : /^(?:No commits yet on |Initial commit on )?(.+?)(?:\.\.\.| \[|$)/.exec(head)?.[1] ?? '';
43
+ const changes = lines.filter((l) => l.trim());
44
+ status = changes.length > 40 ? changes.slice(0, 40).join('\n') + `\n... (${changes.length - 40} more lines, run "git status" for the rest)` : changes.join('\n');
45
+ }
46
+ const refs = (mainOut || '').split('\n').map((s) => s.trim());
47
+ const main = refs.includes('main') ? 'main' : refs.includes('master') ? 'master' : null;
48
+ return { branch: branch || '(detached)', main, status, log: log || '', user };
23
49
  }
24
50
 
25
51
  // Memory files, lowest priority first: user memory, then project files from the
@@ -70,10 +96,6 @@ export function listAutoMemories(dir) {
70
96
  try { return fs.readdirSync(dir).filter((f) => f.endsWith('.md') && f !== 'MEMORY.md'); } catch { return []; }
71
97
  }
72
98
 
73
- export function projectMemoryFile(cwd) {
74
- return path.join(cwd, 'CLAUDE.md');
75
- }
76
-
77
99
  // The date where the user is (YYYY-MM-DD). toISOString() would give the UTC date, which for someone in
78
100
  // UTC+8 is yesterday's between midnight and 8 o'clock.
79
101
  export function localDate(now = new Date()) {
@@ -88,6 +110,10 @@ export function takeEnvSnapshot(cwd) {
88
110
  return { date: localDate(), git: gitInfo(cwd) };
89
111
  }
90
112
 
113
+ export async function takeEnvSnapshotAsync(cwd) {
114
+ return { date: localDate(), git: await gitInfoAsync(cwd) };
115
+ }
116
+
91
117
  export function environmentBlock(cwd, { model, shellName, snapshot = null }) {
92
118
  const { date, git } = snapshot || takeEnvSnapshot(cwd);
93
119
  const lines = [
@@ -108,7 +134,8 @@ export function environmentBlock(cwd, { model, shellName, snapshot = null }) {
108
134
  // gateway refuses requests carrying that exact line (code 11128, shown as a 529 "overloaded") for its models.
109
135
  if (git.main) lines.push(`Main branch: ${git.main}`);
110
136
  if (git.user) lines.push(`Git user: ${git.user}`);
111
- lines.push('', `Status:\n${git.status || '(clean)'}`, '', `Recent commits:\n${git.log || '(none)'}`);
137
+ const status = git.status === null ? '(unknown: git status failed or timed out; run it to see)' : git.status || '(clean)';
138
+ lines.push('', `Status:\n${status}`, '', `Recent commits:\n${git.log || '(none)'}`);
112
139
  }
113
140
  return lines.join('\n');
114
141
  }
package/src/filestate.js CHANGED
@@ -21,7 +21,8 @@ const resultText = (content) => (typeof content === 'string' ? content : '');
21
21
  function readWasPartial(input, text) {
22
22
  return Number(input?.offset) > 1
23
23
  || /\(File has \d+ lines total; showing lines /.test(text)
24
- || /\[output cut at \d+ characters/.test(text);
24
+ || /\[output cut at /.test(text) // "… characters" or "about 25k tokens"
25
+ || /… \[line truncated\]/.test(text);
25
26
  }
26
27
 
27
28
  // messages: the restored conversation. times: when each message was stored (ms since epoch,