@yanzc/claude-pro 0.5.9 → 0.7.0

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/src/commands.js CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import { c, padEnd, truncate } from './ui/ansi.js';
5
+ import { c, padEnd, truncate, colorEnabled } from './ui/ansi.js';
6
6
  import { SelectDialog } from './ui/dialogs.js';
7
7
  import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
8
8
  import { loadConfig, settingsFiles, updateSettingsFile, rememberChoice, applyRememberedChoices, KNOWN_KEYS, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
9
- import { loginWithBrowser, readGatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd, openBrowser } from './gateway.js';
9
+ import { loginWithBrowser, readGatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
10
10
  import { codexLoginSummary, codexModels, codexEfforts } from './codex/client.js';
11
11
  import { readClaudeCodeLogin } from './claude-code.js';
12
12
  import { SessionStore } from './session.js';
@@ -21,6 +21,8 @@ import { displayPath } from './utils/paths.js';
21
21
  import { cleanName, machineName } from './peers.js';
22
22
  import { rewind, promptAt } from './checkpoints.js';
23
23
  import { canRestart, runSelfCheck } from './restart.js';
24
+ import { describeHost, normalizeDir } from './host.js';
25
+ import { qrLines } from './qr.js';
24
26
 
25
27
  const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
26
28
  const isGpt = (modelId) => /^gpt-/i.test(modelId);
@@ -33,6 +35,55 @@ const effortLevels = (modelId, modelInfo = null) => {
33
35
  return isGpt(modelId) && codexEfforts(modelId).length ? codexEfforts(modelId) : EFFORTS;
34
36
  };
35
37
 
38
+ // What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
39
+ // default first. `value` is what /model <value> takes. The gateway's list of models is asked for (4 seconds at
40
+ // most); without an answer gpt-6.1-sol stands for its GPT models.
41
+ export async function modelChoices(cfg) {
42
+ const configured = cfg.configuredModelSpec;
43
+ const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).id}` }];
44
+ if (cfg.usesCodex) {
45
+ // The models the local Codex install lists.
46
+ for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ value: m.slug, label: m.slug, description: m.contextWindow ? `${formatTokens(m.contextWindow)} context` : '' });
47
+ } else {
48
+ opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
49
+ }
50
+ if (cfg.usesGateway) {
51
+ // The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
52
+ const login = readGatewayLogin(cfg.gatewayUrl);
53
+ let served = null;
54
+ try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
55
+ const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
56
+ for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
57
+ if (aliased.has(m.id)) continue;
58
+ opts.push({ value: m.id, label: m.id, description: isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || '' });
59
+ }
60
+ }
61
+ if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, label: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, description: 'sub-agent model' });
62
+ return opts;
63
+ }
64
+
65
+ // What /effort offers for the current model: {levels, options: [{value, label, description}]} in plain text (the
66
+ // levels, auto, default).
67
+ export async function effortChoices(cfg) {
68
+ const id = cfg.mainModel.id;
69
+ let info = null;
70
+ if (cfg.usesGateway && isGpt(id)) {
71
+ const login = readGatewayLogin(cfg.gatewayUrl);
72
+ try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
73
+ }
74
+ const levels = effortLevels(id, info);
75
+ const configured = (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '').trim().toLowerCase() || 'auto';
76
+ const fallback = defaultEffort(id, cfg);
77
+ return {
78
+ levels,
79
+ options: [
80
+ ...levels.map((e) => ({ value: e, label: e, description: '' })),
81
+ { value: 'auto', label: 'auto', description: fallback ? `model default: ${fallback}` : 'use API default' },
82
+ { value: 'default', label: 'default', description: `configured: ${configured}` },
83
+ ],
84
+ };
85
+ }
86
+
36
87
  export function buildCommands(app) {
37
88
  const commands = new Map();
38
89
  const add = (cmd) => commands.set(cmd.name, cmd);
@@ -107,6 +158,27 @@ export function buildCommands(app) {
107
158
  },
108
159
  });
109
160
 
161
+ add({
162
+ name: 'cd',
163
+ argHint: '<directory>',
164
+ argRequired: true,
165
+ description: 'Change the working directory; the conversation goes on there (with that project\'s settings, CLAUDE.md and memory)',
166
+ run(args) {
167
+ const wanted = args.trim().replace(/^(["'])(.*)\1$/, '$2').trim();
168
+ if (!wanted) { out(`Working directory: ${app.cwd} ${c.dim('(/cd <directory> changes it)')}`); return; }
169
+ // absolute, ~ for the home directory, D: for a drive; else from the working directory
170
+ const dir = normalizeDir(wanted) ?? path.resolve(app.cwd, wanted);
171
+ let st = null;
172
+ try { st = fs.statSync(dir); } catch { /* below */ }
173
+ if (!st) { out(c.red(`No such directory: ${dir}`)); return; }
174
+ if (!st.isDirectory()) { out(c.red(`Not a directory: ${dir}`)); return; }
175
+ const same = (a, b) => (process.platform === 'win32' ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
176
+ if (same(dir, app.cwd)) { out(`Working directory: ${app.cwd} ${c.dim('(already)')}`); return; }
177
+ const res = app.changeDirectory(dir);
178
+ if (!res.ok) out(c.red(res.message));
179
+ },
180
+ });
181
+
110
182
  add({
111
183
  name: 'clear',
112
184
  aliases: ['reset', 'new'],
@@ -222,27 +294,7 @@ export function buildCommands(app) {
222
294
  const cfg = app.runtime.config;
223
295
  let choice = args.trim();
224
296
  if (!choice) {
225
- const configured = cfg.configuredModelSpec;
226
- const opts = [{ label: `Default ${c.dim(`(${configured} → ${cfg.resolveModel(configured).id})`)}`, value: '__default__' }];
227
- if (cfg.usesCodex) {
228
- // The models the local Codex install lists.
229
- for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ label: `${m.slug}${m.contextWindow ? c.dim(` (${formatTokens(m.contextWindow)} context)`) : ''}`, value: m.slug });
230
- } else {
231
- opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ label: `${a} ${c.dim(`→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}`)}`, value: a })));
232
- }
233
- if (cfg.usesGateway) {
234
- // The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
235
- const login = readGatewayLogin(cfg.gatewayUrl);
236
- let served = null;
237
- try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
238
- const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
239
- for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
240
- if (aliased.has(m.id)) continue;
241
- const note = /^gpt-/i.test(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name;
242
- opts.push({ label: `${m.id}${note ? ` ${c.dim(`(${note})`)}` : ''}`, value: m.id });
243
- }
244
- }
245
- if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ label: `${cfg.env.CLAUDE_CODE_SUBAGENT_MODEL} ${c.dim('(sub-agent model)')}`, value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL });
297
+ const opts = (await modelChoices(cfg)).map((o) => ({ label: `${o.label}${o.description ? ` ${c.dim(o.description.startsWith('→') ? o.description : `(${o.description})`)}` : ''}`, value: o.value }));
246
298
  choice = await app.showDialog(new SelectDialog({ title: 'Select model', question: `Current: ${c.bold(cfg.mainModel.label)}. Any name works too: /model <name>`, options: opts }));
247
299
  if (!choice) return;
248
300
  }
@@ -268,15 +320,9 @@ export function buildCommands(app) {
268
320
  async run(args) {
269
321
  const cfg = app.runtime.config;
270
322
  const id = cfg.mainModel.id;
271
- let modelInfo = null;
272
- if (cfg.usesGateway && isGpt(id)) {
273
- const login = readGatewayLogin(cfg.gatewayUrl);
274
- try { if (login) modelInfo = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
275
- }
276
- const levels = effortLevels(id, modelInfo);
323
+ const { levels, options } = await effortChoices(cfg);
277
324
  let choice = args.trim().toLowerCase();
278
325
  if (!choice) {
279
- const configured = (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '').trim().toLowerCase() || 'auto';
280
326
  const fallback = defaultEffort(id, cfg);
281
327
  // A level this model does not take goes out as the nearest one it does.
282
328
  const sent = effortToSend(cfg, id, cfg.effort);
@@ -285,11 +331,7 @@ export function buildCommands(app) {
285
331
  choice = await app.showDialog(new SelectDialog({
286
332
  title: `Reasoning effort · ${id}`,
287
333
  question: `Current: ${current}`,
288
- options: [
289
- ...levels.map((e) => ({ label: e, value: e })),
290
- { label: `auto ${c.dim(fallback ? `(model default: ${fallback})` : '(use API default)')}`, value: 'auto' },
291
- { label: `default ${c.dim(`(configured: ${configured})`)}`, value: 'default' },
292
- ],
334
+ options: options.map((o) => ({ label: `${o.label}${o.description ? ` ${c.dim(`(${o.description})`)}` : ''}`, value: o.value })),
293
335
  }));
294
336
  if (!choice) return;
295
337
  }
@@ -327,6 +369,16 @@ export function buildCommands(app) {
327
369
  };
328
370
  const accountLine = (account) => `${account.name || ''}${account.email ? ` <${account.email}>` : ''} · balance ${c.bold(formatUsd(account.available_usd ?? account.balance_usd))}`;
329
371
  let pendingLogin = null;
372
+ // Logged in to the gateway: this session goes online there at once (remote control, the other computers'
373
+ // sessions), and the computer service starts (the web page opens new sessions through it).
374
+ const goOnline = async () => {
375
+ const remote = await app.syncRemote();
376
+ app.ensureHost({ login: true });
377
+ if (!remote) return;
378
+ out(remote.url
379
+ ? `${c.green('⇄')} This session is online at the gateway: ${c.blue(remote.url)} ${c.dim('(/status shows it, with a QR code for a phone)')}`
380
+ : c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
381
+ };
330
382
 
331
383
  add({
332
384
  name: 'login',
@@ -381,6 +433,7 @@ export function buildCommands(app) {
381
433
  const account = await fetchGatewayAccount(saved);
382
434
  const note = switchProvider('gateway');
383
435
  out([`Using the gateway ${c.bold(url)}: ${cfg.mainModel.label}${note}`, accountLine(account), c.dim(`Top up and usage: ${url}/user · another account: /logout, then /login`)]);
436
+ await goOnline();
384
437
  return;
385
438
  } catch (e) {
386
439
  if (e.status !== 401 && e.status !== 403) { out(c.red(`Cannot reach the gateway ${url}: ${e.message}`)); return; }
@@ -398,6 +451,7 @@ export function buildCommands(app) {
398
451
  });
399
452
  const note = switchProvider('gateway');
400
453
  out([`Logged in to the gateway ${c.bold(url)}: ${cfg.mainModel.label}${note}`, accountLine(login.balance || login.account), c.dim(`Top up and usage: ${url}/user`)]);
454
+ await goOnline();
401
455
  } catch (e) {
402
456
  if (e.name !== 'AbortError') out(c.red(`Gateway login failed: ${e.message}`));
403
457
  } finally {
@@ -408,11 +462,15 @@ export function buildCommands(app) {
408
462
 
409
463
  add({
410
464
  name: 'logout',
411
- description: 'Forget the gateway login of this machine',
465
+ description: 'Forget the gateway login of this machine (its sessions go offline there)',
412
466
  run() {
413
467
  const cfg = app.runtime.config;
414
468
  const had = clearGatewayLogin();
415
- out(had ? `Logged out of the gateway ${cfg.gatewayUrl}.${cfg.usesGateway ? ' Run /login to log in again or choose another provider.' : ''}` : c.dim('There was no gateway login. (The Claude and Codex subscription logins belong to their own CLIs.)'));
469
+ const wasOnline = Boolean(app.remote);
470
+ app.stopRemote(); // the other sessions of this computer and its computer service follow within seconds
471
+ out(had
472
+ ? `Logged out of the gateway ${cfg.gatewayUrl}.${wasOnline ? ' This session is offline there now.' : ''}${cfg.usesGateway ? ' Run /login to log in again or choose another provider.' : ''}`
473
+ : c.dim('There was no gateway login. (The Claude and Codex subscription logins belong to their own CLIs.)'));
416
474
  },
417
475
  });
418
476
 
@@ -437,7 +495,7 @@ export function buildCommands(app) {
437
495
  : cfg.usesCodex ? (() => { const s = codexLoginSummary({ ...process.env, ...cfg.env }); return s.ok ? `Codex login${s.email ? ` of ${s.email}` : ''}${s.plan ? ` (${s.plan})` : ''} ${c.dim(s.file)}` : c.red(s.error); })()
438
496
  : cfg.authToken ? `ANTHROPIC_AUTH_TOKEN (${cfg.display('ANTHROPIC_AUTH_TOKEN')})` : cfg.apiKey ? `ANTHROPIC_API_KEY (${cfg.display('ANTHROPIC_API_KEY')})` : c.red('none')),
439
497
  row('Model', `${cfg.mainModel.label} ${c.dim(`(sent as "${cfg.mainModel.id}", ${formatTokens(cfg.mainModel.contextWindow)} context)`)}`),
440
- row('Sub-agent model', cfg.subagentModel.label),
498
+ row('Sub-agent model', cfg.subagentModelChosen ? `chosen per task by difficulty ${c.dim(`(haiku, sonnet or opus; not chosen: ${cfg.subagentModel.label})`)}` : cfg.subagentModel.label),
441
499
  row('Small model', cfg.smallModel.label),
442
500
  row('Effort', cfg.effort || 'auto'),
443
501
  row('Max output', formatTokens(cfg.maxOutputTokens)),
@@ -449,10 +507,32 @@ export function buildCommands(app) {
449
507
  row('ripgrep', hasRipgrep(cfg) ? 'yes' : 'no (using JS fallback)'),
450
508
  row('Memory', mem.length ? mem.map((m) => m.file).join(', ') : c.dim('none')),
451
509
  row('MCP servers', mcp.length ? mcp.map((m) => `${m.name} (${m.status})`).join(', ') : c.dim('none')),
510
+ '',
511
+ ...remoteLines(row),
452
512
  ], '');
453
513
  },
454
514
  });
455
515
 
516
+ // /status about the gateway: this session there (its page, and a QR code of it for a phone), its name for the
517
+ // sessions on the other computers, and the computer service.
518
+ function remoteLines(row) {
519
+ const cfg = app.runtime.config;
520
+ const remote = app.remoteState();
521
+ const me = app.peerLabel();
522
+ const lines = [
523
+ row('Remote control', remote.text),
524
+ ...(remote.url ? [row('', c.blue(remote.url))] : []),
525
+ row('Name', `&${me} ${c.dim(`(on your other computers: &${machineName(cfg.env)}/${me}; /rename changes it)`)}`),
526
+ row('Computer service', describeHost(cfg.env)),
527
+ ];
528
+ const qr = remote.url && app.remote?.online ? qrLines(remote.url, { color: colorEnabled }) : null;
529
+ if (qr) {
530
+ lines.push('', c.dim(' Scan with a phone to open this session (log in to the gateway there):'), ...qr.map((l) => ` ${l}`));
531
+ lines.push(c.dim(` Whoever can log in to this gateway account, or holds one of its API keys, can run anything on this computer through it.`));
532
+ }
533
+ return lines;
534
+ }
535
+
456
536
  add({
457
537
  name: 'cost',
458
538
  aliases: ['usage'],
@@ -594,7 +674,7 @@ export function buildCommands(app) {
594
674
  ...(local.length || remote.length ? [] : [c.dim('No other session is running.')]),
595
675
  c.dim(online
596
676
  ? 'Type "&" for the list, "&name task" to send a task; its answer is shown here. On another computer: "&computer/name task", or "&computer task" when it runs one session. /sendfile &name file... sends files (saved in its Downloads folder). /rename names this session. The agent can use ListPeers / MessagePeer too.'
597
- : 'Type "&" for the list, "&name task" to send a task; its answer is shown here. Sessions on your other computers show up here once this one is online at the gateway (/login, then /rc).'),
677
+ : 'Type "&" for the list, "&name task" to send a task; its answer is shown here. Sessions on your other computers show up here once this one is online at the gateway (/login; /status says why it is not).'),
598
678
  ]);
599
679
  },
600
680
  });
@@ -643,47 +723,6 @@ export function buildCommands(app) {
643
723
  },
644
724
  });
645
725
 
646
- add({
647
- name: 'remote-control',
648
- aliases: ['rc'],
649
- argHint: '[stop | open]',
650
- description: 'Watch and steer this session from a browser or phone, through the gateway (its 远程控制 page): prints the link and a QR code',
651
- async run(args) {
652
- const action = args.trim().toLowerCase();
653
- if (/^(stop|off|disconnect)$/.test(action)) {
654
- if (!app.remote) { out(c.dim('Remote control is not on.')); return; }
655
- app.stopRemote();
656
- out('Remote control is off: the gateway no longer reaches this session.');
657
- return;
658
- }
659
- if (app.remote) log(app.remoteInfo());
660
- else {
661
- const url = app.runtime.config.gatewayUrl;
662
- // It goes through the gateway account: log in to it first (in the browser) when this machine is not; the
663
- // provider of the model requests stays what it is.
664
- if (!readGatewayLogin(url)) {
665
- pendingLogin?.abort();
666
- const controller = new AbortController();
667
- pendingLogin = controller;
668
- try {
669
- await loginWithBrowser({
670
- url,
671
- signal: controller.signal,
672
- onUrl: (page) => out([`Remote control goes through the gateway ${c.bold(url)}: log in to it in your browser. If it does not open, visit:`, c.blue(page), c.dim('Waiting for the browser (10 minutes at most)…')]),
673
- });
674
- } catch (e) {
675
- if (e.name !== 'AbortError') out(c.red(`Gateway login failed: ${e.message}`));
676
- return;
677
- } finally {
678
- if (pendingLogin === controller) pendingLogin = null;
679
- }
680
- }
681
- try { await app.startRemote(); } catch (e) { out(c.red(`Could not start remote control: ${e.message}`)); return; }
682
- }
683
- if (action === 'open' && app.remote.url && !openBrowser(app.remote.url)) out(c.yellow(`Could not open a browser: open ${app.remote.url}`));
684
- },
685
- });
686
-
687
726
  add({
688
727
  name: 'plan',
689
728
  description: 'Toggle read-only plan mode (same as shift+tab)',
package/src/config.js CHANGED
@@ -18,6 +18,9 @@ import { normalizeTtl } from './cache.js';
18
18
  import { codexModels, codexConfigDefaults } from './codex/client.js';
19
19
 
20
20
  export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
21
+ // A source checkout (a git clone, also when npm links to one), as opposed to a copy installed from npm: the agent
22
+ // edits its own code only in a checkout, since the next update replaces an installed copy.
23
+ export const SOURCE_CHECKOUT = fs.existsSync(path.join(INSTALL_DIR, '.git'));
21
24
  export const CONFIG_DIR = process.env.CLAUDE_PRO_CONFIG_DIR || path.join(os.homedir(), '.claude-pro');
22
25
  export const APP_NAME = 'claude-pro';
23
26
  export const PROVIDERS = ['api', 'claude-code', 'gateway', 'codex'];
@@ -36,7 +39,8 @@ export const KNOWN_KEYS = {
36
39
  CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE: 'Existing Claude Code OAuth credentials file (default: ~/.claude/.credentials.json)',
37
40
  CLAUDE_PRO_CLAUDE_CODE_VERSION: 'Claude Code version in the HTTP User-Agent (default: installed npm version)',
38
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)',
39
- CLAUDE_PRO_ONLINE: 'Set to 0 to keep interactive sessions off the gateway until /rc. By default a session goes online there when this computer is logged in to the gateway: its 远程控制 page shows it, and sessions on your other computers can send it tasks (@computer/name)',
42
+ 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
+ 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',
40
44
  CLAUDE_PRO_DOWNLOAD_DIR: 'Where files that other sessions send this one are saved (default: the Downloads folder)',
41
45
  CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
42
46
  CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside, like Claude Code\'s /tui fullscreen) or default (classic: it scrolls in the terminal); /tui switches',
@@ -60,7 +64,7 @@ export const KNOWN_KEYS = {
60
64
  CLAUDE_CODE_AUTO_COMPACT_WINDOW: 'Context size (tokens) used for auto-compaction calculations',
61
65
  CLAUDE_AUTOCOMPACT_PCT_OVERRIDE: 'Percentage (1-100) of the window at which auto-compaction triggers',
62
66
  DISABLE_AUTOCOMPACT: 'Set to 1 to disable auto-compaction',
63
- CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default 128000; lowered automatically if the API allows less)',
67
+ CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default 128000, 48000 with the gateway; lowered automatically if the API allows less)',
64
68
  MAX_THINKING_TOKENS: 'Thinking budget: 0 disables thinking, N enables with budget N',
65
69
  CLAUDE_CODE_PROMPT_CACHE_TTL: 'Prompt cache TTL of the conversation itself: 5m or 1h (default: 1h with the subscription login, as in Claude Code, and with the gateway, else 5m; 1h writes cost more, they pay off when you pause for more than 5 minutes). Also the promptCacheTtl setting',
66
70
  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',
@@ -313,11 +317,15 @@ export class Config {
313
317
  // With the subscription login sub-agents run on Sonnet: much cheaper than Opus, and good at the searching and
314
318
  // well-specified subtasks they are given. CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL (or a sub-agent's own model) changes it.
315
319
  if (this.usesClaudeCode) return this.resolveModel(this.env.CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL || 'sonnet');
316
- // The gateway: Sonnet under a Claude main model, as with the subscription; a GPT main model keeps its own.
317
- if (this.usesGateway) return /^claude-/i.test(this.mainModel.id) ? this.resolveModel('sonnet') : this.mainModel;
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;
318
324
  if (this.usesCodex) return this.mainModel;
319
325
  return this.env.CLAUDE_CODE_SUBAGENT_MODEL ? this.resolveModel(this.env.CLAUDE_CODE_SUBAGENT_MODEL) : this.mainModel;
320
326
  }
327
+ // The main agent chooses each sub-agent's model (haiku, sonnet, opus) by the task, rather than one being set.
328
+ get subagentModelChosen() { return this.usesGateway && /^claude-/i.test(this.mainModel.id); }
321
329
  get smallModel() { return this.resolveModel('haiku'); }
322
330
 
323
331
  get effort() {
@@ -327,9 +335,10 @@ export class Config {
327
335
 
328
336
  // Generous by default so large files can be written in one go; if the API turns out to allow
329
337
  // less, streamMessage learns the real limit from the error and clamps (see api.js).
330
- // The gateway holds back balance for max_tokens of output before each request, so a smaller default there (the
331
- // 32K Claude Code uses) keeps a modest balance usable.
332
- get maxOutputTokens() { return int(this.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS, this.usesGateway ? 32_000 : 128_000); }
338
+ // The gateway holds back balance for max_tokens of output before each request, so a smaller default there keeps a
339
+ // modest balance usable. 48K: in 812 Opus requests through it (2026-10-12) p99 was 14K, three went over 24K (the
340
+ // 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, this.usesGateway ? 48_000 : 128_000); }
333
342
  get thinkingBudget() {
334
343
  return this.env.MAX_THINKING_TOKENS === undefined ? null : int(this.env.MAX_THINKING_TOKENS, null);
335
344
  }
package/src/connect.js ADDED
@@ -0,0 +1,79 @@
1
+ // `claude-pro connect <code> [--url U]`: a new computer joins the user's gateway account with the pairing code the
2
+ // web page shows (添加电脑). No login in a browser: the code stands for it. The gateway answers with an API key of
3
+ // this computer's own, which is saved as /login saves one (gateway.json); then the computer service is set up to
4
+ // start at logon and started, so that the page can use this computer at once and after every restart.
5
+ //
6
+ // POST {url}/v1/remote/pair {code, id, machine, host, platform, version, home} (no authentication)
7
+ // 200 {apiKey, computerId, url, account: {name, email}} · 400 配对码无效或已过期 · 429 too many tries
8
+
9
+ import os from 'node:os';
10
+ import { VERSION, GATEWAY_DEFAULT_URL, loadConfig, settingsFiles, updateSettingsFile } from './config.js';
11
+ import { saveGatewayLogin, normalizeGatewayUrl } from './gateway.js';
12
+ import { machineName } from './peers.js';
13
+ import { computerId, setComputerId, hostEnabled, ensureAutostart, startHostInBackground, hostRunning, readHostState, updateHostState } from './host.js';
14
+
15
+ // The code as typed: 8 letters and digits (I, O, 0 and 1 are not used), maybe with a dash or spaces, in any case.
16
+ export function normalizePairingCode(input) {
17
+ const code = String(input ?? '').toUpperCase().replace(/[\s-]+/g, '');
18
+ return /^[A-Z2-9]{8}$/.test(code) ? code : null;
19
+ }
20
+
21
+ const USAGE = `Usage: claude-pro connect <code> [--url <gateway>]
22
+
23
+ Connects this computer to your gateway account with the pairing code the web page shows (远程控制 → 添加电脑),
24
+ then starts the computer service and sets it to start at logon, so that the page can use this computer.
25
+ --url: the gateway's address (default ${GATEWAY_DEFAULT_URL}, or CLAUDE_PRO_GATEWAY_URL).
26
+ `;
27
+
28
+ export async function connectCommand(args = [], { fetchImpl = globalThis.fetch, out = (s) => process.stdout.write(`${s}\n`), err = (s) => process.stderr.write(`${s}\n`), startService = true } = {}) {
29
+ let url = null;
30
+ const rest = [];
31
+ for (let i = 0; i < args.length; i++) {
32
+ if (args[i] === '--url') url = args[++i];
33
+ else if (args[i].startsWith('--url=')) url = args[i].slice(6);
34
+ else if (args[i] === '-h' || args[i] === '--help') { out(USAGE); return 0; }
35
+ else rest.push(args[i]);
36
+ }
37
+ const code = normalizePairingCode(rest.join(''));
38
+ if (!code) { err(`配对码应是 8 位字母和数字(例如 K7QF-M2XD),不是 "${rest.join(' ')}"\n\n${USAGE}`); return 2; }
39
+ const home = os.homedir();
40
+ const cfg = loadConfig({ cwd: home });
41
+ const base = normalizeGatewayUrl(url || cfg.gatewayUrl);
42
+ let res;
43
+ let data = {};
44
+ try {
45
+ res = await fetchImpl(`${base}/v1/remote/pair`, {
46
+ method: 'POST',
47
+ headers: { 'content-type': 'application/json' },
48
+ body: JSON.stringify({ code, id: computerId(), machine: machineName(cfg.env), host: os.hostname(), platform: process.platform, version: VERSION, home }),
49
+ signal: AbortSignal.timeout(20_000),
50
+ });
51
+ data = await res.json().catch(() => ({}));
52
+ } catch (e) {
53
+ err(`连不上网关 ${base}:${e.message}`);
54
+ return 1;
55
+ }
56
+ if (!res.ok || !data.apiKey) {
57
+ const said = data?.error?.message || (typeof data?.error === 'string' ? data.error : '');
58
+ err(res.status === 429 ? `请求太频繁,请稍后再试${said ? `(${said})` : ''}` : said || `配对失败(HTTP ${res.status})`);
59
+ return 1;
60
+ }
61
+ const gateway = normalizeGatewayUrl(data.url || base);
62
+ saveGatewayLogin({ url: gateway, apiKey: data.apiKey, account: data.account || {} });
63
+ // another gateway than the one configured: the sessions and the service use this one from now on
64
+ if (gateway !== normalizeGatewayUrl(cfg.gatewayUrl)) {
65
+ updateSettingsFile(settingsFiles(home).user, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_GATEWAY_URL: gateway }; });
66
+ }
67
+ if (data.computerId && data.computerId !== computerId()) setComputerId(data.computerId);
68
+ const who = data.account?.name || data.account?.email || '你的账户';
69
+ if (!hostEnabled(cfg.env)) {
70
+ out(`已连接到 ${who}。CLAUDE_PRO_HOST=0:电脑服务不会自己启动,用 claude-pro host start 启动它,网页才能使用这台电脑。`);
71
+ return 0;
72
+ }
73
+ updateHostState({ disabled: undefined, autostartDeclined: undefined });
74
+ const auto = ensureAutostart({ force: true, env: cfg.env });
75
+ if (startService && !hostRunning(readHostState())) startHostInBackground();
76
+ // (one that runs already picks the new login up within seconds)
77
+ out(`已连接到 ${who},可以在网页上使用这台电脑了。${auto?.file ? `\n登录后自动启动:${auto.file}` : ''}`);
78
+ return 0;
79
+ }
package/src/history.js ADDED
@@ -0,0 +1,94 @@
1
+ // The conversations kept on this computer (CONFIG_DIR/projects/<directory>/<id>.jsonl, see session.js), for the web
2
+ // page's history (the computer service's `history` command): newest first, searched by title and first message,
3
+ // a page at a time. A file is read once for as long as it does not change (a session file can be tens of MB): its
4
+ // messages are counted without parsing them, only the first prompt and the meta lines are.
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { firstUserText, projectDir } from './session.js';
9
+
10
+ const cache = new Map(); // file -> {mtimeMs, size, summary}
11
+
12
+ // {conversationId, cwd, title, firstPrompt, messages, updatedAt} of one session file, or null when it has none.
13
+ export function conversationSummary(file) {
14
+ let st;
15
+ try { st = fs.statSync(file); } catch { return null; }
16
+ const hit = cache.get(file);
17
+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.summary;
18
+ let text = '';
19
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return null; }
20
+ let cwd = null;
21
+ let name = null;
22
+ let topic = null;
23
+ let first = null;
24
+ let messages = 0;
25
+ for (const line of text.split('\n')) {
26
+ if (!line) continue;
27
+ if (line.startsWith('{"type":"message"')) {
28
+ messages++;
29
+ if (!first && line.includes('"role":"user"')) {
30
+ try { first = firstUserText(JSON.parse(line).message) || null; } catch { /* a broken line */ }
31
+ }
32
+ continue;
33
+ }
34
+ let e;
35
+ try { e = JSON.parse(line); } catch { continue; }
36
+ if (e.type === 'meta') {
37
+ if (cwd === null && typeof e.cwd === 'string') cwd = e.cwd;
38
+ if ('name' in e) name = typeof e.name === 'string' && e.name.trim() ? e.name : null;
39
+ if (typeof e.topic === 'string' && e.topic.trim()) topic = e.topic;
40
+ } else if (e.type === 'reset' && Array.isArray(e.messages)) {
41
+ messages = e.messages.length;
42
+ } else if (e.type === 'message') {
43
+ messages++;
44
+ if (!first && e.message?.role === 'user') first = firstUserText(e.message) || null;
45
+ }
46
+ }
47
+ const summary = messages ? {
48
+ conversationId: path.basename(file, '.jsonl'),
49
+ cwd,
50
+ title: name || topic || first || '(no prompt)',
51
+ firstPrompt: first || '',
52
+ messages,
53
+ updatedAt: new Date(st.mtimeMs).toISOString(),
54
+ } : null;
55
+ cache.set(file, { mtimeMs: st.mtimeMs, size: st.size, summary });
56
+ if (cache.size > 5000) cache.delete(cache.keys().next().value);
57
+ return summary;
58
+ }
59
+
60
+ // {items: [{conversationId, cwd, title, updatedAt, messages, sessionId?}], more}. `cwd`: only that directory's
61
+ // conversations. `before`: older than this time (ISO), for the next page. `open`: conversationId -> the id at the
62
+ // gateway of the session it is open in.
63
+ export function listConversations({ projects, query = '', cwd = null, limit = 50, before = null, open = new Map() } = {}) {
64
+ const max = Math.max(1, Math.min(200, Number(limit) || 50));
65
+ const until = before ? Date.parse(before) : Infinity;
66
+ const q = String(query || '').trim().toLowerCase();
67
+ const dirs = cwd ? [projectDir(cwd)] : (() => {
68
+ try { return fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(projects, d.name)); } catch { return []; }
69
+ })();
70
+ const files = [];
71
+ for (const dir of dirs) {
72
+ let names = [];
73
+ try { names = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { continue; }
74
+ for (const f of names) {
75
+ const file = path.join(dir, f);
76
+ try {
77
+ const st = fs.statSync(file);
78
+ if (st.mtimeMs < until) files.push({ file, mtimeMs: st.mtimeMs });
79
+ } catch { /* gone meanwhile */ }
80
+ }
81
+ }
82
+ files.sort((a, b) => b.mtimeMs - a.mtimeMs);
83
+ const items = [];
84
+ let more = false;
85
+ for (const { file } of files) {
86
+ const s = conversationSummary(file);
87
+ if (!s) continue;
88
+ if (q && !`${s.title}\n${s.firstPrompt}`.toLowerCase().includes(q)) continue;
89
+ if (items.length === max) { more = true; break; }
90
+ const sessionId = open.get(s.conversationId);
91
+ items.push({ conversationId: s.conversationId, cwd: s.cwd, title: s.title, updatedAt: s.updatedAt, messages: s.messages, ...(sessionId ? { sessionId } : {}) });
92
+ }
93
+ return { items, more };
94
+ }