@yanzc/claude-pro 0.7.1 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +24 -36
- package/README.md +317 -372
- package/package.json +2 -2
- package/src/agent.js +14 -2
- package/src/api.js +40 -173
- package/src/attach.js +14 -0
- package/src/background.js +102 -12
- package/src/checkpoints.js +4 -2
- package/src/commands.js +20 -85
- package/src/config.js +40 -151
- package/src/gateway.js +9 -3
- package/src/history.js +69 -0
- package/src/host.js +71 -14
- package/src/main.js +19 -2
- package/src/peers.js +3 -6
- package/src/print.js +1 -1
- package/src/prompts.js +1 -4
- package/src/ratelimit.js +6 -19
- package/src/remote.js +6 -40
- package/src/runtime.js +4 -2
- package/src/tools/peers.js +5 -9
- package/src/ui/repl.js +43 -215
- package/src/claude-code.js +0 -60
- package/src/codex/client.js +0 -310
- package/src/codex/translate-request.js +0 -239
- package/src/codex/translate-stream.js +0 -328
- package/src/oauth.js +0 -287
- package/src/transfer.js +0 -260
- package/src/utils/downloads.js +0 -83
package/src/config.js
CHANGED
|
@@ -15,7 +15,6 @@ import path from 'node:path';
|
|
|
15
15
|
import os from 'node:os';
|
|
16
16
|
import { fileURLToPath } from 'node:url';
|
|
17
17
|
import { normalizeTtl } from './cache.js';
|
|
18
|
-
import { codexModels, codexConfigDefaults } from './codex/client.js';
|
|
19
18
|
|
|
20
19
|
export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
21
20
|
// A source checkout (a git clone, also when npm links to one), as opposed to a copy installed from npm: the agent
|
|
@@ -23,50 +22,29 @@ export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.u
|
|
|
23
22
|
export const SOURCE_CHECKOUT = fs.existsSync(path.join(INSTALL_DIR, '.git'));
|
|
24
23
|
export const CONFIG_DIR = process.env.CLAUDE_PRO_CONFIG_DIR || path.join(os.homedir(), '.claude-pro');
|
|
25
24
|
export const APP_NAME = 'claude-pro';
|
|
26
|
-
export const PROVIDERS = ['
|
|
25
|
+
export const PROVIDERS = ['gateway'];
|
|
27
26
|
export const GATEWAY_DEFAULT_URL = 'https://gw.predix.icu';
|
|
28
|
-
// The codex provider's model when neither CLAUDE_PRO_CODEX_MODEL nor the Codex config.toml names one.
|
|
29
|
-
export const CODEX_DEFAULT_MODEL = 'gpt-6.1-sol';
|
|
30
27
|
export const VERSION = JSON.parse(fs.readFileSync(path.join(INSTALL_DIR, 'package.json'), 'utf8')).version;
|
|
31
28
|
|
|
32
29
|
// Every key we understand, with a short description (shown by /config).
|
|
33
30
|
export const KNOWN_KEYS = {
|
|
34
|
-
CLAUDE_PRO_PROVIDER: 'Authentication backend: gateway
|
|
35
|
-
CLAUDE_PRO_GATEWAY_URL: `codex-gateway address
|
|
31
|
+
CLAUDE_PRO_PROVIDER: 'Authentication backend: gateway only (codex-gateway account, /login)',
|
|
32
|
+
CLAUDE_PRO_GATEWAY_URL: `codex-gateway address (default https://gw.predix.icu)`,
|
|
33
|
+
CLAUDE_PRO_GATEWAY_API_KEY: 'Gateway API key (normally saved by /login in gateway.json)',
|
|
36
34
|
CLAUDE_PRO_GATEWAY_MODEL: 'Model with the gateway provider (default: opus; also sonnet, haiku, gpt-6.1-sol)',
|
|
37
|
-
CLAUDE_PRO_CODEX_MODEL: 'Model with the codex provider (default: the model in ~/.codex/config.toml, else gpt-6.1-sol)',
|
|
38
|
-
CLAUDE_PRO_CLAUDE_CONFIG_FILE: 'Existing Claude Code account metadata file (default: ~/.claude.json)',
|
|
39
|
-
CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE: 'Existing Claude Code OAuth credentials file (default: ~/.claude/.credentials.json)',
|
|
40
|
-
CLAUDE_PRO_CLAUDE_CODE_VERSION: 'Claude Code version in the HTTP User-Agent (default: installed npm version)',
|
|
41
|
-
CLAUDE_PRO_DISABLE_TOKEN_REFRESH: 'Set to 1 to stop this program renewing the Claude Code login by itself (it then only reads what the official client keeps up to date)',
|
|
42
35
|
CLAUDE_PRO_ONLINE: 'Internal (the self-check and the tests set it): 0 keeps interactive sessions off the gateway. Otherwise a session is online there whenever this computer is logged in to the gateway: its 远程控制 page shows it, and sessions on your other computers can send it tasks (&computer/name)',
|
|
43
36
|
CLAUDE_PRO_HOST: 'Set to 0 so that sessions do not start the computer service (claude-pro host) by themselves; the service lets the gateway\'s 远程控制 page open new sessions on this computer',
|
|
44
|
-
CLAUDE_PRO_DOWNLOAD_DIR: 'Where files that other sessions send this one are saved (default: the Downloads folder)',
|
|
45
37
|
CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
|
|
46
|
-
CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside
|
|
47
|
-
CLAUDE_PRO_SCROLL_SPEED: 'Fullscreen: rows the mouse wheel scrolls a notch (default 3, at most 20)',
|
|
48
|
-
CLAUDE_PRO_PIN_INPUT: 'Set to 0 to show the input box right below the output instead of on the last rows of the window',
|
|
38
|
+
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',
|
|
49
39
|
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)',
|
|
50
|
-
|
|
51
|
-
CLAUDE_CONFIG_DIR: 'Official Claude Code configuration directory, for selecting the locally signed-in account',
|
|
52
|
-
ANTHROPIC_BASE_URL: 'API base URL (Anthropic compatible endpoint)',
|
|
53
|
-
ANTHROPIC_AUTH_TOKEN: 'Bearer token sent as Authorization header',
|
|
54
|
-
ANTHROPIC_API_KEY: 'API key sent as x-api-key header (used if no auth token)',
|
|
55
|
-
ANTHROPIC_CUSTOM_HEADERS: 'Extra headers, "Name: Value" separated by newlines',
|
|
56
|
-
ANTHROPIC_MODEL: 'Main model (name or alias opus/sonnet/haiku; suffix [1m] = 1M context)',
|
|
57
|
-
ANTHROPIC_DEFAULT_OPUS_MODEL: 'Model used for the "opus" alias',
|
|
58
|
-
ANTHROPIC_DEFAULT_SONNET_MODEL: 'Model used for the "sonnet" alias',
|
|
59
|
-
ANTHROPIC_DEFAULT_HAIKU_MODEL: 'Small/fast model (web page summarising, titles)',
|
|
60
|
-
ANTHROPIC_SMALL_FAST_MODEL: 'Deprecated alias of ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
|
61
|
-
CLAUDE_CODE_SUBAGENT_MODEL: 'Model used by Task sub-agents (API providers; default: the main model)',
|
|
62
|
-
CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL: 'Model used by Task sub-agents with the claude-code provider (default: sonnet)',
|
|
40
|
+
|
|
63
41
|
CLAUDE_CODE_EFFORT_LEVEL: 'Reasoning effort: none|minimal|low|medium|high|xhigh|max (sent as output_config.effort)',
|
|
64
42
|
CLAUDE_CODE_AUTO_COMPACT_WINDOW: 'Context size (tokens) used for auto-compaction calculations',
|
|
65
43
|
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE: 'Percentage (1-100) of the window at which auto-compaction triggers',
|
|
66
44
|
DISABLE_AUTOCOMPACT: 'Set to 1 to disable auto-compaction',
|
|
67
|
-
CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default
|
|
45
|
+
CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default 48000; lowered automatically if the gateway allows less)',
|
|
68
46
|
MAX_THINKING_TOKENS: 'Thinking budget: 0 disables thinking, N enables with budget N',
|
|
69
|
-
CLAUDE_CODE_PROMPT_CACHE_TTL: 'Prompt cache TTL of the conversation itself: 5m or 1h (default: 1h with the
|
|
47
|
+
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',
|
|
70
48
|
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',
|
|
71
49
|
ENABLE_PROMPT_CACHING_1H: 'Set to 1 to request the 1-hour TTL for both (the two TTL variables above win over it)',
|
|
72
50
|
FORCE_PROMPT_CACHING_5M: 'Set to 1 to force the 5-minute TTL for both, over every other TTL setting',
|
|
@@ -78,7 +56,6 @@ export const KNOWN_KEYS = {
|
|
|
78
56
|
API_TIMEOUT_MS: 'Request timeout in milliseconds',
|
|
79
57
|
CLAUDE_PRO_MAX_RETRIES: 'Retries for failed API requests (0 = no retries at all, which also turns off the rate limit wait)',
|
|
80
58
|
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)',
|
|
81
|
-
CLAUDE_PRO_RATE_LIMIT_POLL_MS: 'When a rate limit does not say when it resets, try again at most this far apart (default 300000 = 5 minutes)',
|
|
82
59
|
CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS: 'First wait before retrying a request refused as overloaded (529); doubled at each retry (default 1000)',
|
|
83
60
|
CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS: 'Longest wait between retries of an overloaded (529) request (default 32000)',
|
|
84
61
|
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)',
|
|
@@ -87,16 +64,12 @@ export const KNOWN_KEYS = {
|
|
|
87
64
|
BASH_MAX_OUTPUT_LENGTH: 'Max characters of Bash output returned to the model; the full text is saved to a file (default 60000)',
|
|
88
65
|
CLAUDE_CODE_GIT_BASH_PATH: 'Windows: path to bash.exe (Git Bash)',
|
|
89
66
|
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)',
|
|
90
|
-
CLAUDE_PRO_MAX_TOOL_RESULT_CHARS: 'Tool results longer than this are saved to a file and only a preview is sent (default 100000)',
|
|
91
|
-
CLAUDE_PRO_CLEAR_AFTER_IDLE: 'Back after more than 65 minutes away (the prompt cache has expired): clear old tool results and thinking, keeping the last 5 results, as Claude Code does. 1 = on, 0 = off (default: on for the Claude Code login and api.anthropic.com, off for other endpoints, whose cache may last for hours)',
|
|
92
|
-
CLAUDE_PRO_MAX_SUBAGENT_DEPTH: 'How deep sub-agents may nest: agents below this depth can start their own sub-agents (default 2; 0 = no nesting)',
|
|
93
67
|
CLAUDE_PRO_VERIFY_COMMAND: 'Command run after the agent edits files (e.g. "npm test"); failures are sent back to fix',
|
|
94
|
-
CLAUDE_PRO_VERIFY_MAX_ROUNDS: 'How many times a failing verify command is sent back before giving up (default 3)',
|
|
95
68
|
CLAUDE_PRO_DISABLE_AUTO_MEMORY: 'Set to 1 to turn off the persistent per-project memory',
|
|
96
69
|
CLAUDE_PRO_DISABLE_TOPIC_TITLE: 'Set to 1 to stop asking the small model for the current topic after each message (the tab title then shows the first message of the session)',
|
|
97
70
|
};
|
|
98
71
|
|
|
99
|
-
const SECRET_KEYS = new Set(['
|
|
72
|
+
const SECRET_KEYS = new Set(['CLAUDE_PRO_GATEWAY_API_KEY']);
|
|
100
73
|
|
|
101
74
|
export function parseDotEnv(text) {
|
|
102
75
|
const env = {};
|
|
@@ -136,15 +109,7 @@ export function settingsFiles(cwd) {
|
|
|
136
109
|
};
|
|
137
110
|
}
|
|
138
111
|
|
|
139
|
-
|
|
140
|
-
// models, and how hard and how long that model works. The subscription provider (claude-code) does not take that
|
|
141
|
-
// tuning over: it starts from Claude Code's own defaults (the model's default effort, the model's whole context
|
|
142
|
-
// window), which is what makes it work without any setting. The same keys in a settings file, in the shell, as a
|
|
143
|
-
// flag, or chosen with /effort do apply there.
|
|
144
|
-
export const API_ONLY_DOTENV_KEYS = ['CLAUDE_CODE_EFFORT_LEVEL', 'CLAUDE_CODE_AUTO_COMPACT_WINDOW', 'CLAUDE_AUTOCOMPACT_PCT_OVERRIDE', 'CLAUDE_CODE_MAX_OUTPUT_TOKENS', 'MAX_THINKING_TOKENS'];
|
|
145
|
-
|
|
146
|
-
// The variable that holds the model, per provider.
|
|
147
|
-
const MODEL_KEYS = { api: 'ANTHROPIC_MODEL', 'claude-code': 'CLAUDE_PRO_CLAUDE_CODE_MODEL', gateway: 'CLAUDE_PRO_GATEWAY_MODEL', codex: 'CLAUDE_PRO_CODEX_MODEL' };
|
|
112
|
+
const MODEL_KEYS = { gateway: 'CLAUDE_PRO_GATEWAY_MODEL' };
|
|
148
113
|
|
|
149
114
|
export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.join(INSTALL_DIR, '.env') } = {}) {
|
|
150
115
|
const env = {};
|
|
@@ -174,7 +139,7 @@ export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.
|
|
|
174
139
|
for (const [event, entries] of Object.entries(json.hooks || {})) {
|
|
175
140
|
if (Array.isArray(entries)) (settings.hooks[event] ||= []).push(...entries);
|
|
176
141
|
}
|
|
177
|
-
if (json.model) { env.
|
|
142
|
+
if (json.model) { env.CLAUDE_PRO_GATEWAY_MODEL = json.model; sources.CLAUDE_PRO_GATEWAY_MODEL = `${file} (model)`; }
|
|
178
143
|
settings[scope] = json;
|
|
179
144
|
}
|
|
180
145
|
// Project level .mcp.json, same format as Claude Code.
|
|
@@ -187,24 +152,13 @@ export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.
|
|
|
187
152
|
|
|
188
153
|
if (flags.provider) { env.CLAUDE_PRO_PROVIDER = flags.provider; sources.CLAUDE_PRO_PROVIDER = '--provider flag'; }
|
|
189
154
|
if (flags.model) {
|
|
190
|
-
const key = MODEL_KEYS[(env.CLAUDE_PRO_PROVIDER || '').trim().toLowerCase()] || '
|
|
155
|
+
const key = MODEL_KEYS[(env.CLAUDE_PRO_PROVIDER || 'gateway').trim().toLowerCase()] || 'CLAUDE_PRO_GATEWAY_MODEL';
|
|
191
156
|
env[key] = flags.model;
|
|
192
157
|
sources[key] = '--model flag';
|
|
193
158
|
}
|
|
194
159
|
if (flags.effort) { env.CLAUDE_CODE_EFFORT_LEVEL = flags.effort; sources.CLAUDE_CODE_EFFORT_LEVEL = '--effort flag'; }
|
|
195
160
|
|
|
196
|
-
|
|
197
|
-
if (!['', 'api'].includes((env.CLAUDE_PRO_PROVIDER || '').trim().toLowerCase())) {
|
|
198
|
-
for (const key of API_ONLY_DOTENV_KEYS) {
|
|
199
|
-
if (sources[key] !== dotEnvFile) continue;
|
|
200
|
-
delete env[key];
|
|
201
|
-
delete sources[key];
|
|
202
|
-
ignoredFromDotEnv.push(key);
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
const config = new Config(env, sources, settings, cwd);
|
|
206
|
-
config.ignoredFromDotEnv = ignoredFromDotEnv; // shown by /config
|
|
207
|
-
return config;
|
|
161
|
+
return new Config(env, sources, settings, cwd);
|
|
208
162
|
}
|
|
209
163
|
|
|
210
164
|
const int = (v, d) => {
|
|
@@ -224,64 +178,19 @@ export class Config {
|
|
|
224
178
|
this.effortBoost = null; // set by the model with the Effort tool, for the rest of the user's current request
|
|
225
179
|
this.effortBoostKeepNext = false; // a restart continues the request: the next turn keeps the boost
|
|
226
180
|
this.verifyOverride = null; // set by /verify or --verify during a session
|
|
227
|
-
this.ignoredFromDotEnv = []; // .env keys that are not applied because of the provider (see API_ONLY_DOTENV_KEYS)
|
|
228
181
|
}
|
|
229
182
|
|
|
230
|
-
// Not set: an API endpoint, key or model that is configured (.env, settings) means the api provider, as before;
|
|
231
|
-
// otherwise the gateway, where /login gets an account in the browser.
|
|
232
183
|
get provider() {
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
return value;
|
|
184
|
+
const value = (this.env.CLAUDE_PRO_PROVIDER || 'gateway').trim().toLowerCase();
|
|
185
|
+
if (value !== 'gateway') throw new Error(`Only the gateway provider is supported. Set CLAUDE_PRO_PROVIDER=gateway (received ${value}).`);
|
|
186
|
+
return 'gateway';
|
|
237
187
|
}
|
|
238
|
-
get
|
|
239
|
-
get usesGateway() { return this.provider === 'gateway'; }
|
|
240
|
-
get usesCodex() { return this.provider === 'codex'; }
|
|
188
|
+
get usesGateway() { return true; }
|
|
241
189
|
get gatewayUrl() { return (this.env.CLAUDE_PRO_GATEWAY_URL || GATEWAY_DEFAULT_URL).trim().replace(/\/+$/, ''); }
|
|
242
|
-
|
|
243
|
-
// Claude through a subscription login too).
|
|
244
|
-
get claudeIds() { return this.usesClaudeCode || this.usesGateway; }
|
|
245
|
-
get claudeCodeConfigFile() { return path.resolve(this.cwd, this.env.CLAUDE_PRO_CLAUDE_CONFIG_FILE || path.join(os.homedir(), '.claude.json')); }
|
|
246
|
-
get claudeCodeCredentialsFile() {
|
|
247
|
-
return path.resolve(this.cwd, this.env.CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE || path.join(
|
|
248
|
-
this.env.CLAUDE_CONFIG_DIR || path.join(path.dirname(this.claudeCodeConfigFile), '.claude'), '.credentials.json'));
|
|
249
|
-
}
|
|
250
|
-
get endpointLabel() {
|
|
251
|
-
if (this.usesClaudeCode) return 'https://api.anthropic.com (Claude Code OAuth)';
|
|
252
|
-
if (this.usesGateway) return `${this.gatewayUrl} (codex-gateway)`;
|
|
253
|
-
if (this.usesCodex) return 'https://chatgpt.com/backend-api/codex (Codex login)';
|
|
254
|
-
return this.baseURL;
|
|
255
|
-
}
|
|
256
|
-
get baseURL() { return this.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com'; }
|
|
257
|
-
get authToken() { return this.env.ANTHROPIC_AUTH_TOKEN || null; }
|
|
258
|
-
get apiKey() { return this.env.ANTHROPIC_API_KEY || null; }
|
|
259
|
-
get customHeaders() {
|
|
260
|
-
const headers = {};
|
|
261
|
-
for (const line of (this.env.ANTHROPIC_CUSTOM_HEADERS || '').split(/\n/)) {
|
|
262
|
-
const i = line.indexOf(':');
|
|
263
|
-
if (i > 0) headers[line.slice(0, i).trim()] = line.slice(i + 1).trim();
|
|
264
|
-
}
|
|
265
|
-
return headers;
|
|
266
|
-
}
|
|
190
|
+
get endpointLabel() { return `${this.gatewayUrl} (codex-gateway)`; }
|
|
267
191
|
|
|
268
192
|
aliasTarget(alias) {
|
|
269
|
-
|
|
270
|
-
return { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' }[alias] || null;
|
|
271
|
-
}
|
|
272
|
-
// The gateway prices models by their undated names.
|
|
273
|
-
if (this.usesGateway) return { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' }[alias] || null;
|
|
274
|
-
if (this.usesCodex) {
|
|
275
|
-
// No Claude here: the big aliases mean the Codex model, haiku the small one when the Codex install has it.
|
|
276
|
-
if (alias === 'haiku') return codexModels(this.env).models.some((m) => m.slug === 'gpt-6-luna') ? 'gpt-6-luna' : this.codexModelSpec;
|
|
277
|
-
return alias === 'opus' || alias === 'sonnet' ? this.codexModelSpec : null;
|
|
278
|
-
}
|
|
279
|
-
switch (alias) {
|
|
280
|
-
case 'opus': return this.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'claude-opus-4-5';
|
|
281
|
-
case 'sonnet': return this.env.ANTHROPIC_DEFAULT_SONNET_MODEL || 'claude-sonnet-4-5';
|
|
282
|
-
case 'haiku': return this.env.ANTHROPIC_DEFAULT_HAIKU_MODEL || this.env.ANTHROPIC_SMALL_FAST_MODEL || 'claude-haiku-4-5';
|
|
283
|
-
default: return null;
|
|
284
|
-
}
|
|
193
|
+
return { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' }[alias] || null;
|
|
285
194
|
}
|
|
286
195
|
|
|
287
196
|
// Resolve a model spec (alias or name, maybe with [1m]) to {id, contextWindow, label}.
|
|
@@ -294,36 +203,18 @@ export class Config {
|
|
|
294
203
|
const inner = this.resolveModel(aliased);
|
|
295
204
|
return { ...inner, contextWindow: oneM ? 1_000_000 : inner.contextWindow, label: `${name}${oneM ? '[1m]' : ''} (${inner.label})` };
|
|
296
205
|
}
|
|
297
|
-
const nativeOneM =
|
|
298
|
-
//
|
|
299
|
-
|
|
300
|
-
if (/^gpt-/i.test(name)) {
|
|
301
|
-
const known = codexModels(this.env).models.find((m) => m.slug === name)?.contextWindow;
|
|
302
|
-
return { id: name, contextWindow: known || 272_000, label: name };
|
|
303
|
-
}
|
|
206
|
+
const nativeOneM = /^claude-(?:(?:sonnet|haiku)-5(?:-|$)|opus-(?:5(?:-|$)|4-[78](?:-|$)))/i.test(name);
|
|
207
|
+
// GPT models are served by the gateway's Codex backend and use its standard context window.
|
|
208
|
+
if (/^gpt-/i.test(name)) return { id: name, contextWindow: 272_000, label: name };
|
|
304
209
|
return { id: name, contextWindow: oneM || nativeOneM ? 1_000_000 : 200_000, label: `${name}${oneM ? '[1m]' : ''}` };
|
|
305
210
|
}
|
|
306
211
|
|
|
307
|
-
// The model the
|
|
308
|
-
get configuredModelSpec() {
|
|
309
|
-
if (this.usesGateway) return this.env.CLAUDE_PRO_GATEWAY_MODEL || 'opus';
|
|
310
|
-
if (this.usesCodex) return this.codexModelSpec;
|
|
311
|
-
return (this.usesClaudeCode ? this.env.CLAUDE_PRO_CLAUDE_CODE_MODEL : this.env.ANTHROPIC_MODEL) || 'sonnet';
|
|
312
|
-
}
|
|
313
|
-
get codexModelSpec() { return this.env.CLAUDE_PRO_CODEX_MODEL || codexConfigDefaults(this.env).model || CODEX_DEFAULT_MODEL; }
|
|
212
|
+
// The model the gateway is configured with, before any /model override.
|
|
213
|
+
get configuredModelSpec() { return this.env.CLAUDE_PRO_GATEWAY_MODEL || 'opus'; }
|
|
314
214
|
get mainModelSpec() { return this.modelOverride || this.configuredModelSpec; }
|
|
315
215
|
get mainModel() { return this.resolveModel(this.mainModelSpec); }
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
// well-specified subtasks they are given. CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL (or a sub-agent's own model) changes it.
|
|
319
|
-
if (this.usesClaudeCode) return this.resolveModel(this.env.CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL || 'sonnet');
|
|
320
|
-
// The gateway: no fixed sub-agent model. Under a Claude main model the main agent picks one for each Task by how
|
|
321
|
-
// hard the task is (see subagentModelChosen and the Task tool's description); this is what an agent runs on when
|
|
322
|
-
// it was not given one: the main model. A GPT main model keeps its own.
|
|
323
|
-
if (this.usesGateway) return this.mainModel;
|
|
324
|
-
if (this.usesCodex) return this.mainModel;
|
|
325
|
-
return this.env.CLAUDE_CODE_SUBAGENT_MODEL ? this.resolveModel(this.env.CLAUDE_CODE_SUBAGENT_MODEL) : this.mainModel;
|
|
326
|
-
}
|
|
216
|
+
// The gateway lets the main agent choose Claude sub-agent models by task difficulty.
|
|
217
|
+
get subagentModel() { return this.mainModel; }
|
|
327
218
|
// The main agent chooses each sub-agent's model (haiku, sonnet, opus) by the task, rather than one being set.
|
|
328
219
|
get subagentModelChosen() { return this.usesGateway && /^claude-/i.test(this.mainModel.id); }
|
|
329
220
|
get smallModel() { return this.resolveModel('haiku'); }
|
|
@@ -338,15 +229,14 @@ export class Config {
|
|
|
338
229
|
// The gateway holds back balance for max_tokens of output before each request, so a smaller default there keeps a
|
|
339
230
|
// modest balance usable. 48K: in 812 Opus requests through it (2026-10-12) p99 was 14K, three went over 24K (the
|
|
340
231
|
// longest that finished: 27K) and one was cut off at the old 32K; the hold is $0.96 on Opus instead of $0.64.
|
|
341
|
-
get maxOutputTokens() { return int(this.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS,
|
|
232
|
+
get maxOutputTokens() { return int(this.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS, 48_000); }
|
|
342
233
|
get thinkingBudget() {
|
|
343
234
|
return this.env.MAX_THINKING_TOKENS === undefined ? null : int(this.env.MAX_THINKING_TOKENS, null);
|
|
344
235
|
}
|
|
345
236
|
// Prompt cache TTL for a request bucket, by Claude Code's rules: "main" is the conversation itself, "other"
|
|
346
237
|
// is everything else (sub-agents, compaction, side queries). In order: FORCE_PROMPT_CACHING_5M; the bucket's
|
|
347
|
-
// own variable or setting; ENABLE_PROMPT_CACHING_1H; then the default:
|
|
348
|
-
//
|
|
349
|
-
// usage); with an API key or another endpoint, and for everything else, 5 minutes.
|
|
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.
|
|
350
240
|
cacheTtl(bucket = 'main') {
|
|
351
241
|
if (isOn(this.env.FORCE_PROMPT_CACHING_5M)) return '5m';
|
|
352
242
|
// an invalid value is ignored, and the next rule applies (as in Claude Code)
|
|
@@ -357,7 +247,7 @@ export class Config {
|
|
|
357
247
|
if (isOn(this.env.ENABLE_PROMPT_CACHING_1H)) return '1h';
|
|
358
248
|
// The gateway too: measured on its usage records (533 Opus requests), pauses of 5 to 60 minutes rewrote the whole
|
|
359
249
|
// conversation 9 times at 1.25x, $14.77; writing every turn at 2x instead costs $2.80 more.
|
|
360
|
-
return bucket === 'main' &&
|
|
250
|
+
return bucket === 'main' && this.usesGateway ? '1h' : '5m';
|
|
361
251
|
}
|
|
362
252
|
// DISABLE_PROMPT_CACHING turns it off for everything; the per-model variables only for the model that
|
|
363
253
|
// their alias resolves to (a different version pinned as the model keeps its caching), wherever it runs.
|
|
@@ -373,7 +263,8 @@ export class Config {
|
|
|
373
263
|
get apiTimeout() { return int(this.env.API_TIMEOUT_MS, 600_000); }
|
|
374
264
|
get maxRetries() { return int(this.env.CLAUDE_PRO_MAX_RETRIES, 6); }
|
|
375
265
|
get rateLimitMaxWait() { return Math.max(0, int(this.env.CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS, 6 * 3_600_000)); }
|
|
376
|
-
|
|
266
|
+
// A rate limit that does not say when it resets is tried again at most this far apart.
|
|
267
|
+
get rateLimitPoll() { return 300_000; }
|
|
377
268
|
// An overloaded API (529): the backoff, and how long to keep trying once the retries are used up (see planRetry).
|
|
378
269
|
get overloadedRetryBaseDelay() { return Math.max(100, int(this.env.CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS, 1000)); }
|
|
379
270
|
get overloadedRetryMaxDelay() { return Math.max(this.overloadedRetryBaseDelay, int(this.env.CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS, 32_000)); }
|
|
@@ -398,23 +289,21 @@ export class Config {
|
|
|
398
289
|
get bashDefaultTimeout() { return int(this.env.BASH_DEFAULT_TIMEOUT_MS, 600_000); }
|
|
399
290
|
get bashMaxTimeout() { return int(this.env.BASH_MAX_TIMEOUT_MS, 3_600_000); }
|
|
400
291
|
get bashMaxOutput() { return int(this.env.BASH_MAX_OUTPUT_LENGTH, 60_000); }
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
//
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
if (v) return isOn(v);
|
|
407
|
-
return this.usesClaudeCode || this.usesGateway || /^https:\/\/api\.anthropic\.com\/?$/i.test(this.baseURL);
|
|
408
|
-
}
|
|
292
|
+
// Tool results longer than this are saved to a file and only a preview is sent.
|
|
293
|
+
get maxToolResultChars() { return 100_000; }
|
|
294
|
+
// Clearing old tool results after a long pause (see Agent.clearAfterIdle): the gateway prompt cache has
|
|
295
|
+
// expired by then, so retaining old tool payloads would only make the next request larger.
|
|
296
|
+
get clearAfterIdle() { return true; }
|
|
409
297
|
// How deep sub-agents may nest: the main agent is depth 0; an agent below this depth gets the Task tool.
|
|
410
|
-
get maxSubagentDepth() { return
|
|
298
|
+
get maxSubagentDepth() { return 2; }
|
|
411
299
|
|
|
412
300
|
// Verification after edits: session override (/verify, --verify) wins over the env setting.
|
|
413
301
|
get verifyCommand() {
|
|
414
302
|
const v = this.verifyOverride ?? this.env.CLAUDE_PRO_VERIFY_COMMAND ?? '';
|
|
415
303
|
return v.trim() && v.trim() !== 'off' ? v.trim() : null;
|
|
416
304
|
}
|
|
417
|
-
|
|
305
|
+
// How many times a failing verify command is sent back before giving up.
|
|
306
|
+
get verifyMaxRounds() { return 3; }
|
|
418
307
|
get autoMemoryEnabled() { return !/^(1|true|yes)$/i.test(this.env.CLAUDE_PRO_DISABLE_AUTO_MEMORY || ''); }
|
|
419
308
|
|
|
420
309
|
display(key) {
|
package/src/gateway.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
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
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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
5
|
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import fs from 'node:fs';
|
|
@@ -28,6 +28,12 @@ export function readGatewayLogin(url) {
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
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
|
+
|
|
31
37
|
export function saveGatewayLogin(login) {
|
|
32
38
|
const file = gatewayLoginFile();
|
|
33
39
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
package/src/history.js
CHANGED
|
@@ -92,3 +92,72 @@ export function listConversations({ projects, query = '', cwd = null, limit = 50
|
|
|
92
92
|
}
|
|
93
93
|
return { items, more };
|
|
94
94
|
}
|
|
95
|
+
|
|
96
|
+
// A conversation's id as it may be used in a path: what SessionStore makes (a UUID), letters, digits, - and _ in
|
|
97
|
+
// any case. Anything else (a dot, a slash: "../x") is refused before it gets near a path.
|
|
98
|
+
export const CONVERSATION_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
99
|
+
|
|
100
|
+
// Delete what this computer keeps of the conversation `id` (the web page's "delete"): its session file (in every
|
|
101
|
+
// project it is in: /cd moves it), the tool results saved for it (the outputs too long for the conversation, named
|
|
102
|
+
// after its tool calls or referred to by path in it) and its checkpoints (the file snapshots of /rewind, tagged
|
|
103
|
+
// with the conversation they belong to). What belongs to the project stays: its memory, CLAUDE.md, the input
|
|
104
|
+
// history, the checkpoints of other conversations. `extra`: more files to delete (a background session's log).
|
|
105
|
+
// Returns {files, bytes}; throws when there is no such conversation.
|
|
106
|
+
export function deleteConversation({ projects, id, extra = [] }) {
|
|
107
|
+
if (!CONVERSATION_ID.test(String(id || ''))) throw new Error('对话 id 不对');
|
|
108
|
+
let dirs = [];
|
|
109
|
+
try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(projects, d.name)); } catch { /* none */ }
|
|
110
|
+
const sessionFiles = dirs.map((d) => path.join(d, `${id}.jsonl`)).filter((f) => fs.existsSync(f));
|
|
111
|
+
if (!sessionFiles.length) throw new Error('这台电脑上没有这段对话');
|
|
112
|
+
// the tool results it saved: <tool call id>.txt (persistLargeOutput) and bash-<time>-<random>.txt (the Bash tool)
|
|
113
|
+
const names = new Set();
|
|
114
|
+
for (const file of sessionFiles) {
|
|
115
|
+
let text = '';
|
|
116
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { continue; }
|
|
117
|
+
for (const m of text.matchAll(/"(?:tool_use_id|id)":"([^"]{1,200})"/g)) names.add(`${m[1].replace(/[^\w-]/g, '_')}.txt`);
|
|
118
|
+
for (const m of text.matchAll(/bash-\d+-[a-z0-9]+\.txt/g)) names.add(m[0]);
|
|
119
|
+
}
|
|
120
|
+
const doomed = [...sessionFiles, ...extra];
|
|
121
|
+
const rewrites = []; // checkpoint indexes that keep other conversations' entries
|
|
122
|
+
for (const dir of dirs) {
|
|
123
|
+
const results = path.join(dir, 'tool-results');
|
|
124
|
+
for (const name of names) {
|
|
125
|
+
const f = path.join(results, name);
|
|
126
|
+
if (fs.existsSync(f)) doomed.push(f);
|
|
127
|
+
}
|
|
128
|
+
let runs = [];
|
|
129
|
+
try { runs = fs.readdirSync(path.join(dir, 'checkpoints')); } catch { continue; }
|
|
130
|
+
for (const run of runs) {
|
|
131
|
+
const runDir = path.join(dir, 'checkpoints', run);
|
|
132
|
+
let entries;
|
|
133
|
+
try { entries = JSON.parse(fs.readFileSync(path.join(runDir, 'index.json'), 'utf8')); } catch { continue; }
|
|
134
|
+
if (!Array.isArray(entries) || !entries.some((e) => e?.conversation === id)) continue;
|
|
135
|
+
const kept = entries.filter((e) => e?.conversation !== id);
|
|
136
|
+
for (const e of entries) {
|
|
137
|
+
if (e?.conversation !== id) continue;
|
|
138
|
+
for (const f of e.files || []) if (f?.snap && /^[\w-]+$/.test(f.snap)) doomed.push(path.join(runDir, f.snap));
|
|
139
|
+
}
|
|
140
|
+
if (kept.length) rewrites.push({ file: path.join(runDir, 'index.json'), entries: kept });
|
|
141
|
+
else doomed.push(path.join(runDir, 'index.json'), runDir);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
let files = 0;
|
|
145
|
+
let bytes = 0;
|
|
146
|
+
const failed = [];
|
|
147
|
+
for (const f of doomed) {
|
|
148
|
+
try {
|
|
149
|
+
const st = fs.statSync(f);
|
|
150
|
+
if (st.isDirectory()) { fs.rmSync(f, { recursive: true, force: true }); continue; }
|
|
151
|
+
fs.rmSync(f);
|
|
152
|
+
files++;
|
|
153
|
+
bytes += st.size;
|
|
154
|
+
} catch (e) {
|
|
155
|
+
if (e.code !== 'ENOENT') failed.push(`${path.basename(f)}: ${e.code || e.message}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
for (const r of rewrites) {
|
|
159
|
+
try { fs.writeFileSync(r.file, JSON.stringify(r.entries, null, 1)); } catch (e) { failed.push(`${r.file}: ${e.code || e.message}`); }
|
|
160
|
+
}
|
|
161
|
+
if (sessionFiles.some((f) => fs.existsSync(f))) throw new Error(`删除失败:${failed.join(';') || '会话文件还在'}`);
|
|
162
|
+
return { files, bytes, ...(failed.length ? { failed } : {}) };
|
|
163
|
+
}
|
package/src/host.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// Protocol (Bearer = the gateway API key; ARCHITECTURE.md 3.1.5):
|
|
9
9
|
// POST /v1/remote/hosts {id, machine, host, platform, version, home, terminal, autostart, sessions, stats}
|
|
10
10
|
// GET /v1/remote/hosts/:id/commands (SSE): online while it is open; {cid, type, body}: list, open, stop,
|
|
11
|
-
// restart, logs, history, update
|
|
11
|
+
// restart, window, logs, history, delete, update
|
|
12
12
|
// POST /v1/remote/hosts/:id/results {cid, ok: true, ...} | {cid, ok: false, error}
|
|
13
13
|
// POST /v1/remote/hosts/:id/state {sessions, stats}: on a change of the sessions, and every minute
|
|
14
14
|
// DELETE /v1/remote/hosts/:id: off the page's list (`host stop`, a logout, another account)
|
|
@@ -27,10 +27,10 @@ import path from 'node:path';
|
|
|
27
27
|
import crypto from 'node:crypto';
|
|
28
28
|
import { spawn, spawnSync } from 'node:child_process';
|
|
29
29
|
import { CONFIG_DIR, INSTALL_DIR, VERSION, GATEWAY_DEFAULT_URL, loadConfig } from './config.js';
|
|
30
|
-
import {
|
|
30
|
+
import { gatewayLogin, normalizeGatewayUrl } from './gateway.js';
|
|
31
31
|
import { machineName, cleanName, listPeers } from './peers.js';
|
|
32
32
|
import { BackgroundSessions, markEnded, tailFile } from './background.js';
|
|
33
|
-
import { listConversations } from './history.js';
|
|
33
|
+
import { listConversations, deleteConversation, CONVERSATION_ID } from './history.js';
|
|
34
34
|
import { checkForUpdate, installUpdate } from './updater.js';
|
|
35
35
|
import { ENV_SUPERVISED, ENV_RESTART_FILE, ENV_RESTARTED } from './supervisor.js';
|
|
36
36
|
|
|
@@ -411,7 +411,7 @@ const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
|
411
411
|
// The settings of this service's environment that a session it opens needs too (the config directory, the
|
|
412
412
|
// gateway's address, the computer's name ...): Windows Terminal starts the program with its own environment, and
|
|
413
413
|
// tmux and a desktop's terminal with theirs. Not the secrets: those stay where they were set.
|
|
414
|
-
const PASS_ENV = /^(CLAUDE_PRO_|
|
|
414
|
+
const PASS_ENV = /^(CLAUDE_PRO_|CLAUDE_CODE_)/;
|
|
415
415
|
const SECRET = /TOKEN|KEY|SECRET|PASSWORD|HEADERS/i;
|
|
416
416
|
export function passedEnv(env = process.env) {
|
|
417
417
|
const out = {};
|
|
@@ -444,15 +444,15 @@ function writeEnvFile(sessionId, vars) {
|
|
|
444
444
|
|
|
445
445
|
// How `term` opens a window that runs `node entry ...args` in `cwd`: {cmd, args, options, wait}. `wait`: 'exit'
|
|
446
446
|
// when the command ends once the window is open (its exit code says whether it worked), 'spawn' when it is the
|
|
447
|
-
// terminal itself.
|
|
448
|
-
export function launchCommand(term, { cwd, node = process.execPath, entry = ENTRY, args = [], env = {}, envFile = null, sessionId = '' }) {
|
|
447
|
+
// terminal itself. `title`: the tab's first title, where the terminal takes one (Windows Terminal).
|
|
448
|
+
export function launchCommand(term, { cwd, node = process.execPath, entry = ENTRY, args = [], env = {}, envFile = null, sessionId = '', title = '' }) {
|
|
449
449
|
const program = [node, ...(envFile ? [`--env-file=${envFile}`] : []), entry, ...args];
|
|
450
450
|
const pairs = Object.entries(env).map(([k, v]) => `${k}=${v}`);
|
|
451
451
|
const posix = [...(pairs.length ? ['env', ...pairs] : []), node, entry, ...args];
|
|
452
452
|
const line = posix.map(shQuote).join(' ');
|
|
453
453
|
switch (term.kind) {
|
|
454
454
|
case 'wt': // a new window; wt reads ; as the start of another command
|
|
455
|
-
return { cmd: term.path, args: ['-w', 'new', '-d', cwd, ...program].map((a) => a.replace(/;/g, '\\;')), options: { windowsHide: false }, wait: 'exit' };
|
|
455
|
+
return { cmd: term.path, args: ['-w', 'new', ...(title ? ['--title', title] : []), '-d', cwd, ...program].map((a) => a.replace(/;/g, '\\;')), options: { windowsHide: false }, wait: 'exit' };
|
|
456
456
|
case 'console': { // a console window of its own; Start-Process takes the command line as it is
|
|
457
457
|
// what went wrong: only its message, in UTF-8 (PowerShell writes errors as CLIXML in the system's code page)
|
|
458
458
|
const script = [
|
|
@@ -527,7 +527,10 @@ export class HostService {
|
|
|
527
527
|
this.launch = launch;
|
|
528
528
|
this.home = home;
|
|
529
529
|
this.loadConfig = load || (() => loadConfig({ cwd: home }));
|
|
530
|
-
this.readLogin = readLogin || (() =>
|
|
530
|
+
this.readLogin = readLogin || (() => {
|
|
531
|
+
const cfg = this.cfg();
|
|
532
|
+
return gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
533
|
+
});
|
|
531
534
|
this.config = null;
|
|
532
535
|
this.configAt = 0;
|
|
533
536
|
this.login = null; // {url, apiKey, account} of gateway.json
|
|
@@ -778,6 +781,8 @@ export class HostService {
|
|
|
778
781
|
else if (cmd.type === 'logs') r = this.logs(body);
|
|
779
782
|
else if (cmd.type === 'history') r = this.history(body);
|
|
780
783
|
else if (cmd.type === 'update') r = await this.update();
|
|
784
|
+
else if (cmd.type === 'window') r = await this.window(body);
|
|
785
|
+
else if (cmd.type === 'delete') r = await this.deleteConversation(body);
|
|
781
786
|
else throw new Error(`这台电脑上的 claude-pro ${VERSION} 不认识命令 ${cmd.type},请升级`);
|
|
782
787
|
result = { cid: cmd.cid, ok: true, ...r };
|
|
783
788
|
} catch (e) {
|
|
@@ -805,6 +810,57 @@ export class HostService {
|
|
|
805
810
|
});
|
|
806
811
|
}
|
|
807
812
|
|
|
813
|
+
// window: a background session brought to the front in a terminal window of this computer, `claude-pro attach` in
|
|
814
|
+
// it (chosen as open's terminal window is). A turn that runs goes on and shows there as it goes; the session stays
|
|
815
|
+
// the service's. Closing the window (its X included: the attach process ends) only detaches it. Each call opens
|
|
816
|
+
// another window. Without a desktop, a tmux session to attach to (`tmux attach -t claude-pro-<id>-…`).
|
|
817
|
+
async window({ sessionId } = {}) {
|
|
818
|
+
if (typeof sessionId !== 'string' || !ID.test(sessionId)) throw new Error('会话 id 不对');
|
|
819
|
+
const rec = this.sessions?.sessions.get(sessionId);
|
|
820
|
+
if (!rec) {
|
|
821
|
+
if (this.sessions?.ended.some((e) => e.sessionId === sessionId)) throw new Error('会话没有在运行');
|
|
822
|
+
throw new Error('这个会话不是这台电脑上的后台会话');
|
|
823
|
+
}
|
|
824
|
+
if (rec.state !== 'running' || !this.sessions.alive(rec)) throw new Error('会话没有在运行');
|
|
825
|
+
const label = rec.name || sessionId;
|
|
826
|
+
const term = this.terminal;
|
|
827
|
+
if (!term) throw new Error(`这台电脑没有可以打开窗口的桌面(可以在终端里运行 claude-pro attach ${label})`);
|
|
828
|
+
let cwd = rec.cwd;
|
|
829
|
+
try { if (!fs.statSync(cwd).isDirectory()) cwd = this.home; } catch { cwd = this.home; }
|
|
830
|
+
const env = passedEnv();
|
|
831
|
+
const key = `${sessionId}-w${Date.now().toString(36)}`; // its own env file and tmux session: one window more each time
|
|
832
|
+
const envFile = process.platform === 'win32' && term.kind === 'wt' ? writeEnvFile(key, env) : null;
|
|
833
|
+
try {
|
|
834
|
+
await this.launch(launchCommand(term, { cwd, args: ['attach', sessionId, '--keep-open'], env, envFile, sessionId: key, title: `${label} · claude-pro` }));
|
|
835
|
+
} catch (e) {
|
|
836
|
+
throw new Error(`无法用 ${term.name} 打开终端:${e.message}`);
|
|
837
|
+
}
|
|
838
|
+
this.log(`opened ${term.name} attached to the background session ${sessionId} (${label})`);
|
|
839
|
+
return { terminal: term.name };
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// delete: what this computer keeps of a conversation (see history.js), for good. Open in a background session of this
|
|
843
|
+
// service, that session is ended first with `stop` (as the stop command does), else it is refused; open in a terminal,
|
|
844
|
+
// it is refused: a terminal the user works in is not closed for them. {files, bytes}
|
|
845
|
+
async deleteConversation({ conversationId, stop = false } = {}) {
|
|
846
|
+
const id = conversationId;
|
|
847
|
+
if (typeof id !== 'string' || !CONVERSATION_ID.test(id)) throw new Error('对话 id 不对');
|
|
848
|
+
const open = listPeers().filter((p) => p.conversationId === id);
|
|
849
|
+
const ours = (p) => p.kind === 'background' && this.sessions?.sessions.has(p.remoteId);
|
|
850
|
+
const terminal = open.find((p) => !ours(p) && p.kind !== 'background');
|
|
851
|
+
if (terminal) throw new Error(`这段对话正开在终端里的会话 &${terminal.name} 里:请先在那台电脑上结束它(/exit)`);
|
|
852
|
+
const other = open.find((p) => !ours(p));
|
|
853
|
+
if (other) throw new Error(`这段对话正开在会话 &${other.name} 里:先结束它`);
|
|
854
|
+
// the service's own sessions with it: those in the registry, and those starting or restarting
|
|
855
|
+
const running = [...(this.sessions?.sessions.values() || [])].filter((r) => (r.conversationId === id || open.some((p) => p.remoteId === r.sessionId)) && this.sessions.alive(r));
|
|
856
|
+
if (running.length && stop !== true) throw new Error(`这段对话正开在会话 &${running[0].name || running[0].sessionId} 里:先结束它`);
|
|
857
|
+
for (const r of running) await this.sessions.stop(r.sessionId);
|
|
858
|
+
const logs = this.sessions ? this.sessions.forgetConversation(id) : [];
|
|
859
|
+
const r = deleteConversation({ projects: path.join(configDir(), 'projects'), id, extra: logs });
|
|
860
|
+
this.log(`deleted the conversation ${id}: ${r.files} files, ${r.bytes} bytes${running.length ? ` (its session ${running.map((x) => x.sessionId).join(', ')} ended first)` : ''}`);
|
|
861
|
+
return { files: r.files, bytes: r.bytes };
|
|
862
|
+
}
|
|
863
|
+
|
|
808
864
|
// The conversations kept on this computer (see history.js), with the session each one is open in.
|
|
809
865
|
history({ query, cwd, limit, before } = {}) {
|
|
810
866
|
if (before != null && Number.isNaN(Date.parse(before))) throw new Error('before 不是时间');
|
|
@@ -1066,7 +1122,7 @@ export async function runHost({ background = false } = {}) {
|
|
|
1066
1122
|
|
|
1067
1123
|
async function gatewayRequest(method, route) {
|
|
1068
1124
|
const cfg = loadConfig({ cwd: os.homedir() });
|
|
1069
|
-
const login =
|
|
1125
|
+
const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
1070
1126
|
if (!login) return false;
|
|
1071
1127
|
const res = await fetch(`${normalizeGatewayUrl(login.url || cfg.gatewayUrl)}${route}`, { method, headers: { authorization: `Bearer ${login.apiKey}` }, signal: AbortSignal.timeout(8000) });
|
|
1072
1128
|
return res.ok || res.status === 404;
|
|
@@ -1085,7 +1141,7 @@ async function startCommand() {
|
|
|
1085
1141
|
const now = readHostState();
|
|
1086
1142
|
if (hostRunning(now)) {
|
|
1087
1143
|
const cfg = loadConfig({ cwd: os.homedir() });
|
|
1088
|
-
const login =
|
|
1144
|
+
const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
1089
1145
|
console.log(`claude-pro host started in the background (pid ${now.pid}). Log: ${hostFiles().log}`);
|
|
1090
1146
|
if (!login) console.log(`This computer is not logged in to the gateway ${cfg.gatewayUrl}: it waits until /login in a session.`);
|
|
1091
1147
|
return 0;
|
|
@@ -1370,10 +1426,11 @@ const USAGE = `Usage: claude-pro host [run | start | stop | status | install | u
|
|
|
1370
1426
|
|
|
1371
1427
|
The computer service: it makes this computer one the gateway's web page (远程控制) runs sessions on. From the
|
|
1372
1428
|
page: new sessions here, in the directory chosen there, in the background without a window (or, when asked, in
|
|
1373
|
-
a terminal window);
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1429
|
+
a terminal window); bringing a background session to the front in a terminal window here (also while it works;
|
|
1430
|
+
closing the window sends it back); ending and restarting them; opening a conversation kept here again (history),
|
|
1431
|
+
or deleting it from this computer; their logs and its own; updating claude-pro. A background session that
|
|
1432
|
+
crashes is opened again, and after a restart of the computer the service opens again those that ran (the
|
|
1433
|
+
conversation, not the task that was running). \`claude-pro attach\` shows a background session in a terminal here.
|
|
1377
1434
|
|
|
1378
1435
|
It uses the gateway login of /login or claude-pro connect, and only connects out to the gateway. A session
|
|
1379
1436
|
logged in to the gateway starts it by itself, and /login and connect set it up to start at logon
|