@yanzc/claude-pro 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +240 -62
  4. package/src/agents.js +3 -2
  5. package/src/api.js +83 -41
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +177 -71
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +153 -153
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +2 -1
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +6 -62
  27. package/src/ratelimit.js +3 -5
  28. package/src/remote.js +26 -10
  29. package/src/restart.js +3 -0
  30. package/src/runtime.js +33 -10
  31. package/src/selfcheck.js +3 -3
  32. package/src/session.js +93 -3
  33. package/src/supervisor.js +10 -1
  34. package/src/tools/bash.js +19 -18
  35. package/src/tools/browser.js +365 -0
  36. package/src/tools/code.js +430 -0
  37. package/src/tools/effort.js +3 -4
  38. package/src/tools/files.js +92 -19
  39. package/src/tools/index.js +6 -0
  40. package/src/tools/notebook.js +11 -4
  41. package/src/tools/processes.js +274 -0
  42. package/src/tools/search.js +104 -21
  43. package/src/tools/web.js +316 -46
  44. package/src/trace.js +0 -4
  45. package/src/ui/ansi.js +92 -13
  46. package/src/ui/dialogs.js +16 -54
  47. package/src/ui/editor.js +231 -34
  48. package/src/ui/markdown.js +1 -2
  49. package/src/ui/render.js +1 -2
  50. package/src/ui/repl.js +246 -119
  51. package/src/ui/screen.js +139 -31
  52. package/src/updater.js +135 -165
  53. package/src/utils/clipboard.js +5 -3
  54. package/src/utils/paths.js +15 -17
  55. package/src/utils/shell.js +75 -21
  56. package/.env.example +0 -29
  57. package/src/verify.js +0 -57
package/src/commands.js CHANGED
@@ -5,8 +5,8 @@ import path from 'node:path';
5
5
  import { c, padEnd, truncate } from './ui/ansi.js';
6
6
  import { SelectDialog } from './ui/dialogs.js';
7
7
  import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
8
- import { loadConfig, settingsFiles, updateSettingsFile, rememberChoice, applyRememberedChoices, KNOWN_KEYS, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
9
- import { loginWithBrowser, readGatewayLogin, gatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
8
+ import { loadConfig, settingsFiles, configEntries, writeConfigSetting, unsetConfigSetting, rememberChoice, applyRememberedChoices, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
9
+ import { loginWithBrowser, gatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, loadGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
10
10
  import { SessionStore } from './session.js';
11
11
  import { memoryFiles, listAutoMemories } from './context.js';
12
12
  import { INIT_PROMPT } from './prompts.js';
@@ -20,6 +20,7 @@ import { activePromptName, listPromptProfiles, loadActivePrompt, promptDirectory
20
20
  import { cleanName, machineName } from './peers.js';
21
21
  import { rewind, promptAt } from './checkpoints.js';
22
22
  import { canRestart, runSelfCheck } from './restart.js';
23
+ import { browserSession, browserInstances, sameBrowser, safeUrl } from './browser/session.js';
23
24
 
24
25
  const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
25
26
  const isGpt = (modelId) => /^gpt-/i.test(modelId);
@@ -31,22 +32,21 @@ const effortLevels = (modelId, modelInfo = null) => {
31
32
  };
32
33
 
33
34
  // What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
34
- // default first. `value` is what /model <value> takes. The gateway's list of models is asked for (4 seconds at
35
- // most); without an answer gpt-6.1-sol stands for its GPT models.
35
+ // default first. `value` is what /model <value> takes. The gateway's list of models is asked for anew each time (4
36
+ // seconds at most), so a model it has just added is there without a restart; without an answer the list it gave
37
+ // last, else gpt-6.1-sol for its GPT models.
36
38
  export async function modelChoices(cfg) {
37
39
  const configured = cfg.configuredModelSpec;
38
40
  const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).id}` }];
39
41
  opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
40
- if (cfg.usesGateway) {
41
- // The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
42
- const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
43
- let served = null;
44
- try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
45
- const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
46
- for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
47
- if (aliased.has(m.id)) continue;
48
- opts.push({ value: m.id, label: m.id, description: isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || '' });
49
- }
42
+ // The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
43
+ const login = gatewayLogin(cfg.gatewayUrl);
44
+ let served = null;
45
+ try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: true }); } catch { /* offline: the fallback below */ }
46
+ const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
47
+ for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
48
+ if (aliased.has(m.id)) continue;
49
+ opts.push({ value: m.id, label: m.id, description: isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || '' });
50
50
  }
51
51
  return opts;
52
52
  }
@@ -56,12 +56,12 @@ export async function modelChoices(cfg) {
56
56
  export async function effortChoices(cfg) {
57
57
  const id = cfg.model.id;
58
58
  let info = null;
59
- if (cfg.usesGateway && isGpt(id)) {
60
- const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
61
- try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
59
+ if (isGpt(id)) {
60
+ const login = gatewayLogin(cfg.gatewayUrl);
61
+ try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: true })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
62
62
  }
63
63
  const levels = effortLevels(id, info);
64
- const configured = (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '').trim().toLowerCase() || 'auto';
64
+ const configured = cfg.configuredEffort;
65
65
  const fallback = defaultEffort(id, cfg);
66
66
  return {
67
67
  levels,
@@ -82,7 +82,7 @@ export function buildCommands(app) {
82
82
  // /model and /effort choices are kept for later sessions (rememberChoice); say so, or why they are not.
83
83
  const keep = (cfg, patch, forgotten) => {
84
84
  try {
85
- rememberChoice(cfg.provider, patch);
85
+ rememberChoice(patch);
86
86
  return c.dim(forgotten ? ' · the configured default from now on' : ' · kept for later sessions');
87
87
  } catch (e) {
88
88
  return c.yellow(` · for this session only (${e.message})`);
@@ -325,7 +325,7 @@ export function buildCommands(app) {
325
325
 
326
326
  add({
327
327
  name: 'config',
328
- argHint: '[set KEY VALUE | unset KEY] [--project|--local]',
328
+ argHint: '[advanced | set KEY VALUE | unset KEY] [--project|--local]',
329
329
  description: 'Show or change configuration (API URL, models, effort, …)',
330
330
  run(args) {
331
331
  const parts = args.split(/\s+/).filter(Boolean);
@@ -334,26 +334,28 @@ export function buildCommands(app) {
334
334
  const file = settingsFiles(app.cwd)[scope];
335
335
  if (rest[0] === 'set' && rest[1] && rest.length >= 3) {
336
336
  const value = rest.slice(2).join(' ');
337
- updateSettingsFile(file, (json) => { json.env = { ...(json.env || {}), [rest[1]]: value }; });
337
+ const key = writeConfigSetting(file, rest[1], value);
338
338
  reloadConfig();
339
- out([`Set ${c.bold(rest[1])} in ${file}`, ...(app.runtime.config.sources[rest[1]] !== file ? [c.yellow(`Note: overridden by ${app.runtime.config.sources[rest[1]]}`)] : [])]);
339
+ out([`Set ${c.bold(key)} in ${file}`, ...(app.runtime.config.sources[key] !== file ? [c.yellow(`Note: overridden by ${app.runtime.config.sources[key]}`)] : [])]);
340
340
  return;
341
341
  }
342
342
  if (rest[0] === 'unset' && rest[1]) {
343
- updateSettingsFile(file, (json) => { if (json.env) delete json.env[rest[1]]; });
343
+ const key = unsetConfigSetting(file, rest[1]);
344
344
  reloadConfig();
345
- out(`Removed ${c.bold(rest[1])} from ${file}`);
345
+ out(`Removed ${c.bold(key)} from ${file}`);
346
346
  return;
347
347
  }
348
348
  const cfg = app.runtime.config;
349
- const lines = [c.bold('Configuration') + c.dim(' (precedence: .env < ~/.claude-pro/settings.json < .claude-pro/settings.json < .claude-pro/settings.local.json < shell env < flags)'), ''];
350
- for (const k of Object.keys(KNOWN_KEYS)) {
351
- const v = cfg.display(k);
352
- if (v === undefined) continue;
353
- lines.push(`${padEnd(k, 34)} ${c.bold(v)} ${c.dim(cfg.sources[k] || '')}`);
349
+ const advanced = rest[0] === 'advanced' || rest.includes('--advanced');
350
+ const lines = [c.bold(advanced ? 'Configuration · advanced' : 'Configuration'), ''];
351
+ for (const entry of configEntries(cfg, { advanced })) {
352
+ lines.push(`${padEnd(entry.key, 28)} ${c.bold(String(entry.value ?? '(default)'))} ${c.dim(entry.source)}`);
353
+ if (advanced) lines.push(c.dim(` ${entry.description}`));
354
354
  }
355
- lines.push('', c.dim('Other keys: ' + Object.keys(KNOWN_KEYS).filter((k) => cfg.env[k] === undefined).join(', ')));
356
- lines.push('', `${c.dim('Change with')} /config set KEY VALUE [--project|--local] ${c.dim('or edit')} ${settingsFiles(app.cwd).user}`);
355
+ lines.push('', c.dim('Precedence: user settings < project settings < local settings; shell env applies only to advanced keys; --model/--effort win.'));
356
+ if (cfg.modelOverride || cfg.effortOverride) lines.push(c.dim('The choices made with /model and /effort override the configured defaults above.'));
357
+ if (!advanced) lines.push(c.dim('More controls: /config advanced'));
358
+ lines.push('', `${c.dim('Change with')} /config set KEY VALUE [--project|--local] ${c.dim('or edit')} ${file}`);
357
359
  log(lines, '');
358
360
  },
359
361
  });
@@ -394,11 +396,16 @@ export function buildCommands(app) {
394
396
  const forget = choice === '__default__' || choice === 'default';
395
397
  const next = cfg.resolveModel(forget ? cfg.configuredModelSpec : choice).id;
396
398
  const changed = next !== cfg.model.id;
397
- if (changed && !(await confirmCacheLoss('Switching the model', { model: next }))) { out(c.dim('The model was not changed.')); return; }
399
+ // (Not asked at a pause for a rate limit: the cache runs out while waiting for the limit as well.)
400
+ if (changed && !app.agent.pausedForLimit && !(await confirmCacheLoss('Switching the model', { model: next }))) { out(c.dim('The model was not changed.')); return; }
398
401
  cfg.modelOverride = forget ? null : choice;
399
402
  if (changed) app.runtime.invalidateSystemPrompt(); // the prompt names the model; the new model starts a cache of its own anyway
400
403
  const kept = keep(cfg, { model: cfg.modelOverride }, forget);
401
- out(`Model set to ${c.bold(cfg.model.label)} ${c.dim(`(${formatTokens(cfg.model.contextWindow)} context)`)}${kept}${changed ? c.dim(' · restored conversation remains in context for the next request') : ''}`);
404
+ await loadGatewayModels(cfg); // the window shown may come from the gateway's model list (see Config.resolveModel)
405
+ // A turn paused for the other model's rate limit goes on with this one now (the one case in which /model runs
406
+ // during a turn, see App.modelSwitchAtPause).
407
+ const resumed = changed && app.agent.wakePause();
408
+ out(`Model set to ${c.bold(cfg.model.label)} ${c.dim(`(${formatTokens(cfg.model.contextWindow)} context)`)}${kept}${resumed ? c.dim(' · the paused request goes on with it now') : changed ? c.dim(' · restored conversation remains in context for the next request') : ''}`);
402
409
  },
403
410
  });
404
411
 
@@ -406,7 +413,7 @@ export function buildCommands(app) {
406
413
  name: 'effort',
407
414
  get argHint() {
408
415
  const cfg = app.runtime.config;
409
- const login = cfg.usesGateway ? gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) : null;
416
+ const login = gatewayLogin(cfg.gatewayUrl);
410
417
  return `[${effortLevels(cfg.model.id, cachedGatewayModel(login, cfg.model.id)).join('|')}|auto|default]`;
411
418
  },
412
419
  description: 'Set reasoning effort (output_config.effort; kept for later sessions)',
@@ -430,7 +437,7 @@ export function buildCommands(app) {
430
437
  }
431
438
  if (choice !== 'auto' && choice !== 'default' && !levels.includes(choice)) { out(c.red(`${id} does not take effort "${choice}". Use one of: ${levels.join(', ')}, auto, default`)); return; }
432
439
  const forget = choice === 'default';
433
- const wanted = (forget ? (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '') : choice).trim().toLowerCase();
440
+ const wanted = (forget ? cfg.configuredEffort : choice).trim().toLowerCase();
434
441
  const next = wanted && wanted !== 'auto' && wanted !== 'default' ? wanted : null;
435
442
  if (next !== cfg.effort && !(await confirmCacheLoss('Changing the effort'))) { out(c.dim('The effort was not changed.')); return; }
436
443
  cfg.effortOverride = forget ? null : choice;
@@ -439,17 +446,9 @@ export function buildCommands(app) {
439
446
  },
440
447
  });
441
448
 
442
- // Keep the gateway selection in the user settings and apply its remembered /model and /effort.
443
- const switchProvider = (provider) => {
449
+ // After a login: the configuration read again, with the remembered /model and /effort.
450
+ const afterLogin = () => {
444
451
  const cfg = app.runtime.config;
445
- const files = settingsFiles(app.cwd);
446
- // The choice goes where the setting that wins is now: a project's settings file overrides the user's,
447
- // so writing only the user's file would change nothing in this project.
448
- const winning = cfg.sources.CLAUDE_PRO_PROVIDER;
449
- const file = [files.local, files.project].includes(winning) ? winning : files.user;
450
- const set = (f) => updateSettingsFile(f, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_PROVIDER: provider }; });
451
- set(files.user); // the default for the other projects too
452
- if (file !== files.user) set(file);
453
452
  const model = cfg.model.id;
454
453
  reloadConfig();
455
454
  cfg.modelOverride = null;
@@ -457,17 +456,20 @@ export function buildCommands(app) {
457
456
  cfg.effortBoost = null;
458
457
  applyRememberedChoices(cfg, app.flags);
459
458
  if (cfg.model.id !== model) app.runtime.invalidateSystemPrompt();
460
- if (cfg.provider !== provider) return c.red(` · NOT switched: CLAUDE_PRO_PROVIDER=${cfg.provider} is set by ${cfg.sources.CLAUDE_PRO_PROVIDER}, which overrides the settings files; change it there`);
461
- return file !== files.user ? c.dim(` · also saved in ${displayPath(file, app.cwd)}, which overrides the user settings in this project`) : '';
462
459
  };
463
460
  const accountLine = (account) => `${account.name || ''}${account.email ? ` <${account.email}>` : ''} · balance ${c.bold(formatUsd(account.available_usd ?? account.balance_usd))}`;
464
461
  let pendingLogin = null;
465
- // Logged in to the gateway: this session goes online there at once for read-only viewing and peer messaging.
462
+ // Logged in to the gateway: this session goes online there at once, for its web page and peer messaging. The page
463
+ // can steer the session too (send messages, `!` commands, /cd...) unless CLAUDE_PRO_REMOTE_COMMANDS=0: said as it
464
+ // is, since this message called the page read-only.
466
465
  const goOnline = async () => {
467
466
  const remote = await app.syncRemote();
468
467
  if (!remote) return;
468
+ const page = remote.commands?.length
469
+ ? 'its web page shows it and can send it messages and commands (CLAUDE_PRO_REMOTE_COMMANDS=0 makes the page read-only)'
470
+ : 'the read-only web page shows it';
469
471
  out(remote.registered
470
- ? `${c.green('⇄')} This session is online at the gateway: the read-only web page shows it.`
472
+ ? `${c.green('⇄')} This session is online at the gateway: ${page}.`
471
473
  : c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
472
474
  };
473
475
 
@@ -481,12 +483,12 @@ export function buildCommands(app) {
481
483
  if (choice && choice !== 'gateway') { out(c.red(`Unknown login method "${choice}". Only gateway login is supported.`)); return; }
482
484
 
483
485
  const url = cfg.gatewayUrl;
484
- const saved = readGatewayLogin(url);
486
+ const saved = gatewayLogin(url);
485
487
  if (saved) {
486
488
  try {
487
489
  const account = await fetchGatewayAccount(saved);
488
- const note = switchProvider('gateway');
489
- out([`Using the gateway ${c.bold(url)}: ${cfg.model.label}${note}`, accountLine(account), c.dim(`Top up and usage: ${url}/user · another account: /logout, then /login`)]);
490
+ afterLogin();
491
+ out([`Using the gateway ${c.bold(url)}: ${cfg.model.label}`, accountLine(account), c.dim(`Top up and usage: ${url}/user · another account: /logout, then /login`)]);
490
492
  await goOnline();
491
493
  return;
492
494
  } catch (e) {
@@ -503,8 +505,8 @@ export function buildCommands(app) {
503
505
  signal: controller.signal,
504
506
  onUrl: (page) => out([`Opening the gateway login in your browser. If it does not open, visit:`, c.blue(page), c.dim('Waiting for the browser (10 minutes at most)…')]),
505
507
  });
506
- const note = switchProvider('gateway');
507
- out([`Logged in to the gateway ${c.bold(url)}: ${cfg.model.label}${note}`, accountLine(login.balance || login.account), c.dim(`Top up and usage: ${url}/user`)]);
508
+ afterLogin();
509
+ out([`Logged in to the gateway ${c.bold(url)}: ${cfg.model.label}`, accountLine(login.balance || login.account), c.dim(`Top up and usage: ${url}/user`)]);
508
510
  await goOnline();
509
511
  } catch (e) {
510
512
  if (e.name !== 'AbortError') out(c.red(`Gateway login failed: ${e.message}`));
@@ -542,17 +544,17 @@ export function buildCommands(app) {
542
544
  row('Version', VERSION),
543
545
  row('Session ID', app.store.id),
544
546
  row('cwd', app.cwd),
545
- row('Provider', cfg.provider),
547
+ row('Provider', 'gateway'),
546
548
  row('Endpoint', cfg.endpointLabel),
547
- row('Auth', gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? `gateway key of ${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)')),
549
+ row('Auth', gatewayLogin(cfg.gatewayUrl) ? `gateway key of ${gatewayLogin(cfg.gatewayUrl).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)')),
548
550
  row('Model', `${cfg.model.label} ${c.dim(`(sent as "${cfg.model.id}", ${formatTokens(cfg.model.contextWindow)} context)`)}`),
549
551
  row('Effort', cfg.effort || 'auto'),
550
552
  row('System prompt', app.flags.systemPrompt !== undefined
551
553
  ? 'command line override'
552
554
  : savedPrompt?.text != null ? `${savedPrompt.name} (saved)` : savedPrompt?.error ? `${savedPrompt.name} (missing; using built-in)` : 'built-in default'),
553
555
  row('Max output', formatTokens(cfg.maxOutputTokens)),
554
- row('Prompt cache', cfg.promptCachingDisabled(cfg.model.id) ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.model.id).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.model.id).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
555
- row('Auto-compact', cfg.autoCompactEnabled ? `at ${formatTokens(cfg.autoCompactThreshold())} tokens (window ${formatTokens(cfg.compactWindow())})` : 'disabled'),
556
+ row('Prompt cache', cfg.promptCachingDisabled() ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.model.id).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.model.id).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
557
+ row('Auto-compact', `at ${formatTokens(cfg.compactWindow())} tokens (the window, less room for the summary)`),
556
558
  row('Access', 'full (no permission prompts)'),
557
559
  row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
558
560
  row('Shell', `${app.runtime.shell.name} ${c.dim(app.runtime.shell.path)}`),
@@ -565,8 +567,8 @@ export function buildCommands(app) {
565
567
  },
566
568
  });
567
569
 
568
- // /status about the gateway: whether this session is publishing a read-only view there and its
569
- // name for sessions on the other computers.
570
+ // /status about the gateway: whether this session is online there (its web page) and its name for sessions on the
571
+ // other computers.
570
572
  function remoteLines(row) {
571
573
  const cfg = app.runtime.config;
572
574
  const remote = app.remoteState();
@@ -601,7 +603,7 @@ export function buildCommands(app) {
601
603
  `Session time: ${formatDuration(Date.now() - app.sessionStart)}`,
602
604
  ]);
603
605
  const cfg = app.runtime.config;
604
- const saved = cfg.usesGateway && gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
606
+ const saved = gatewayLogin(cfg.gatewayUrl);
605
607
  if (!saved) return;
606
608
  try {
607
609
  const account = await fetchGatewayAccount(saved);
@@ -652,7 +654,7 @@ export function buildCommands(app) {
652
654
  const cfg = app.runtime.config;
653
655
  const a = app.agent;
654
656
  const window = cfg.model.contextWindow;
655
- const threshold = cfg.autoCompactThreshold();
657
+ const threshold = cfg.compactWindow();
656
658
  const sys = estimateTokens(app.runtime.systemPrompt());
657
659
  const tools = estimateTokens(a.toolSchemas());
658
660
  const msgs = estimateTokens(a.messages);
@@ -665,7 +667,7 @@ export function buildCommands(app) {
665
667
  out([
666
668
  `${bar} ${c.bold(formatTokens(used))} / ${formatTokens(window)} tokens (${Math.round((used / window) * 100)}%)`,
667
669
  c.dim(`System prompt ~${formatTokens(sys)} · Tools ~${formatTokens(tools)} · Messages ~${formatTokens(msgs)} (${a.messages.length})`),
668
- cfg.autoCompactEnabled ? c.dim(`Auto-compact at ${formatTokens(threshold)} tokens (┃) — ${Math.max(0, Math.round((1 - used / threshold) * 100))}% left`) : c.dim('Auto-compact disabled'),
670
+ c.dim(`Auto-compact at ${formatTokens(threshold)} tokens (┃) — ${Math.max(0, Math.round((1 - used / threshold) * 100))}% left`),
669
671
  ]);
670
672
  },
671
673
  });
@@ -706,12 +708,12 @@ export function buildCommands(app) {
706
708
  add({
707
709
  name: 'verify',
708
710
  argHint: '[command|off]',
709
- description: 'Run a command (e.g. npm test) after turns that edit files; auto-detects project tests when available; failures go back to the agent',
711
+ description: 'Run a command (e.g. npm test) after turns that edit files; failures go back to the agent (off unless set)',
710
712
  run(args) {
711
713
  const cfg = app.runtime.config;
712
714
  if (args.trim()) cfg.verifyOverride = args.trim();
713
715
  out(cfg.verifyCommand
714
- ? `Verify command: ${c.bold(cfg.verifyCommand)} ${c.dim(`(${cfg.verifyCommandAuto ? 'auto-detected; ' : ''}up to ${cfg.verifyMaxRounds} fix rounds; /verify off to disable)`)}`
716
+ ? `Verify command: ${c.bold(cfg.verifyCommand)} ${c.dim(`(up to ${cfg.verifyMaxRounds} fix rounds; /verify off to disable)`)}`
715
717
  : c.dim('Verification is off. Turn it on with /verify <command>, --verify <command> or CLAUDE_PRO_VERIFY_COMMAND.'));
716
718
  },
717
719
  });
@@ -734,7 +736,7 @@ export function buildCommands(app) {
734
736
  add({
735
737
  name: 'update',
736
738
  description: `Look for a newer ${APP_NAME} on npm now and install it`,
737
- async run() { out(c.dim(`Version ${VERSION} · checking npm…`)); await app.autoUpdate({ force: true }); },
739
+ async run() { out(c.dim(`Version ${VERSION} · checking npm…`)); await app.updateFromNpm(); },
738
740
  });
739
741
 
740
742
  add({
@@ -758,6 +760,107 @@ export function buildCommands(app) {
758
760
  },
759
761
  });
760
762
 
763
+ // The tab the Browser tool is to work in, picked by the user instead of looked for by the model: the tabs of the
764
+ // browser with their ids, from the same connection the tool uses (so the ids are the tool's), and the one picked is
765
+ // selected there and named in the message being written. Its id stays that tab's after a reconnect or a restart
766
+ // (BrowserSession.relabel), so the agent goes straight to it. Several browser instances may allow remote debugging
767
+ // (Edge also on a profile directory of its own, as an app's window has): the user picks one first, and the
768
+ // session goes back to it after a restart (BrowserSession.preferred).
769
+ add({
770
+ name: 'tabs',
771
+ aliases: ['tab'],
772
+ argHint: '[edge|chrome|brave|chromium|own|words of a profile directory]',
773
+ description: 'Pick a tab of your browser for the Browser tool: it is selected, and its id goes into your message',
774
+ async run(args) {
775
+ // the agent's own browser calls go to the selected tab: not changed under it while it works
776
+ if (app.isTurnRunning()) { out(c.dim('The agent is working and may be using the browser: /tabs once the turn is done (or Esc).')); return; }
777
+ if (app.runtime.tasks.running().length) { out(c.dim('Background agents are running and may be using the browser: /tabs once they are done (/tasks).')); return; }
778
+ const s = browserSession;
779
+ // Esc cancels while it waits: the browser may ask the user to allow the connection first
780
+ const busy = async (status, fn) => {
781
+ app.busy = true;
782
+ app.status = status;
783
+ app.turnStart = Date.now();
784
+ app.controller = new AbortController();
785
+ try { return await s.run(app.controller.signal, fn); } finally {
786
+ app.busy = false;
787
+ app.status = null;
788
+ app.controller = null;
789
+ app.screen.schedule();
790
+ }
791
+ };
792
+ const failed = (e, what) => out(e?.name === 'AbortError' ? c.dim('Cancelled.') : c.red(`${what}: ${e.message}`));
793
+ // The instance to connect to: the one matching `ask` (a kind, or words of its profile directory), or the user's
794
+ // pick when several are there. null: none, or the user closed the list.
795
+ const chooseBrowser = async (ask) => {
796
+ let all;
797
+ try { all = await busy('Looking for browsers', () => browserInstances()); } catch (e) { failed(e, 'Cannot list the browsers'); return null; }
798
+ const q = ask.toLowerCase();
799
+ const list = q ? all.filter((i) => i.name === q || `${i.label} ${i.dir}`.toLowerCase().includes(q)) : all;
800
+ if (!list.length) {
801
+ out(c.red(`${q ? `No browser matching "${ask}" allows` : 'No browser allows'} remote debugging now. Turn it on in yours at edge://inspect/#remote-debugging (Chrome: chrome://inspect/#remote-debugging) and allow it for this browser instance.`));
802
+ return null;
803
+ }
804
+ if (list.length === 1) return list[0];
805
+ const connected = list.find((i) => s.connected && sameBrowser(i, s.browser));
806
+ const key = await app.showDialog(new SelectDialog({
807
+ title: 'Which browser?',
808
+ question: 'These allow remote debugging now; each asks once per connection to allow it.',
809
+ options: list.map((i) => ({ value: i.dir || i.url, label: `${i.label}${i === connected ? c.dim(' (connected)') : ''}`, description: `${i.dir}${i.port ? ` · port ${i.port}` : ''}` })),
810
+ selected: Math.max(0, list.indexOf(connected)),
811
+ }));
812
+ return key ? list.find((i) => (i.dir || i.url) === key) : null;
813
+ };
814
+ try {
815
+ const ask = args.trim();
816
+ let target = null;
817
+ if (ask || !s.connected) {
818
+ target = await chooseBrowser(ask);
819
+ if (!target) return;
820
+ }
821
+ for (;;) {
822
+ if (target) {
823
+ const connecting = target;
824
+ target = null;
825
+ try {
826
+ await busy('Connecting to the browser', () => s.connect(connecting, app.runtime.config.env, (b) => {
827
+ app.status = `Allow the connection in ${b.label} ("Allow remote debugging?" → Allow) · Esc cancels`;
828
+ app.screen.schedule();
829
+ }));
830
+ } catch (e) { failed(e, 'Cannot use the browser'); return; }
831
+ }
832
+ const browser = s.browser;
833
+ const tabs = [...s.tabs.values()];
834
+ if (!browser) { out(c.dim('The connection to the browser was lost.')); return; }
835
+ const title = (t, n) => truncate(String(t.title || '(no title)').replace(/\s+/g, ' '), n);
836
+ const chosen = await app.showDialog(new SelectDialog({
837
+ title: `Tabs in ${browser.label}`,
838
+ question: 'The Browser tool works in the tab you pick, and its id goes into your message.',
839
+ options: [
840
+ ...tabs.map((t) => ({ value: t.targetId, label: `${padEnd(t.id, 8)} ${title(t, 70)}${t === s.current ? c.dim(' (selected)') : ''}`, description: safeUrl(t.url || '') })),
841
+ { value: '__browser__', label: c.dim('Another browser or profile…') },
842
+ ],
843
+ selected: Math.max(0, tabs.indexOf(s.current)),
844
+ }));
845
+ if (!chosen) return;
846
+ if (chosen === '__browser__') {
847
+ target = await chooseBrowser('');
848
+ if (!target) return;
849
+ continue;
850
+ }
851
+ const tab = s.tabs.get(chosen);
852
+ if (!tab) { out(c.red('That tab was closed meanwhile.')); return; }
853
+ try { await busy('Selecting the tab', () => s.select(tab)); } catch (e) { failed(e, `Could not select ${tab.id}`); return; }
854
+ app.editor.insert(`[Browser tab ${tab.id} in ${browser.label}: ${JSON.stringify(title(tab, 60))}] `);
855
+ out(c.dim(`${tab.id} is the Browser tool's tab now, and its id is in your message.`));
856
+ return;
857
+ }
858
+ } finally {
859
+ app.sendWhatWaited(); // what was typed while it connected
860
+ }
861
+ },
862
+ });
863
+
761
864
  add({
762
865
  name: 'tui',
763
866
  argHint: '[fullscreen | default]',
@@ -770,7 +873,7 @@ export function buildCommands(app) {
770
873
  }
771
874
  if (want !== 'fullscreen' && want !== 'default') { out(c.red('Use /tui fullscreen or /tui default.')); return; }
772
875
  const file = settingsFiles(app.cwd).user;
773
- updateSettingsFile(file, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_TUI: want }; });
876
+ writeConfigSetting(file, 'tui', want);
774
877
  reloadConfig();
775
878
  app.screen.setFull(want === 'fullscreen');
776
879
  out(want === 'fullscreen'
@@ -856,7 +959,11 @@ export function buildCommands(app) {
856
959
  await app.agent.summarizePart(index, { part, label: entry.label, signal: app.controller.signal });
857
960
  store.summarized(id, part, index);
858
961
  app.remote?.resync();
859
- if (part === 'after' && prompt) app.editor.set(prompt); // as Claude Code does: the prompt to send again or edit
962
+ // as Claude Code does: the prompt to send again or edit; not over what was typed while it summarized
963
+ if (part === 'after' && prompt) {
964
+ if (!app.editor.text.trim()) app.editor.set(prompt);
965
+ else out(c.dim('The prompt was not put back in the input box: it holds what you typed meanwhile.'));
966
+ }
860
967
  } catch (e) {
861
968
  if (!app.controller.signal.aborted) out(c.red(`Could not summarize: ${e.message}`));
862
969
  else out(c.red('Summarizing interrupted'));
@@ -953,8 +1060,7 @@ export function buildCommands(app) {
953
1060
 
954
1061
  add({
955
1062
  name: 'verbose',
956
- aliases: ['thinking'],
957
- description: 'Toggle verbose output (thinking, full tool results)',
1063
+ description: 'Toggle detailed tool output and compaction summaries',
958
1064
  run() {
959
1065
  app.verbose = !app.verbose;
960
1066
  out(`Verbose mode ${app.verbose ? 'on' : 'off'}`);
@@ -994,7 +1100,7 @@ export function buildCommands(app) {
994
1100
  `${c.green('✔')} Node ${process.versions.node}`,
995
1101
  `${app.runtime.shell.kind === 'bash' ? c.green('✔') : c.yellow('!')} Shell: ${app.runtime.shell.name} (${app.runtime.shell.path})`,
996
1102
  `${rg ? c.green('✔') : c.yellow('!')} ripgrep ${rg ? 'found' : 'not found (Grep uses the built-in JS scanner, which is slower; set CLAUDE_PRO_RIPGREP_PATH to use an rg.exe)'}`,
997
- `${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? '' : ' missing (/login)'}`,
1103
+ `${gatewayLogin(cfg.gatewayUrl) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${gatewayLogin(cfg.gatewayUrl) ? '' : ' missing (/login)'}`,
998
1104
  ];
999
1105
  out(lines);
1000
1106
  app.busy = true;
@@ -0,0 +1,75 @@
1
+ // What a compaction asks the model for, and the message that then stands for the summarized conversation. Kept out
2
+ // of prompts.js, whose text is hashed into PROMPT_CODE_VERSION: a change here does not make every running
3
+ // conversation rebuild its system prompt and write its prompt cache again.
4
+
5
+ // The system prompt of the plain summary request (see Agent.requestSummary).
6
+ export const SUMMARY_SYSTEM = 'You are a helpful AI assistant tasked with summarizing conversations.';
7
+
8
+ export function compactPrompt(instructions) {
9
+ return `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools: the conversation above is complete, and the only thing wanted now is the structured state and summary below.
10
+
11
+ What you write now takes the place of the conversation above (or of the part of it named below). Whoever carries on the work (you, without the conversation) has only that, the files on disk, and the user's own messages, which are kept word for word (the newest ones; in a long conversation the oldest may be shortened or left out). So do not repeat the user's messages: write what is needed to go on with the work as if nothing had been lost.
12
+
13
+ First write exactly one <work-state> block containing one valid JSON object. Do not use markdown fences inside the block. Use this schema exactly; use an empty string or [] when a field has no value:
14
+ <work-state>
15
+ {"schema_version":1,"objective":"","constraints":[],"decisions":[],"files":[],"edits":[],"tests":[],"failures":[],"open_questions":[],"next_action":"","tool_artifacts":[]}
16
+ </work-state>
17
+ All array items must be strings. Keep paths, commands, error messages and next actions precise. The state is machine-validated, so do not add prose before or after the JSON inside <work-state>.
18
+
19
+ Then write in <summary> tags a handoff with what the work-state does not hold, concise and specific, without repeating its items:
20
+ 1. Where the work stands: what is done and verified, what is half done, and what was left running or unfinished (a server, a background agent, edits not yet tested).
21
+ 2. Why things were decided as they were, and what was tried and did not work, so that it is not tried again.
22
+ 3. What still holds from earlier in the conversation and is not plain from the user's newest messages: requests, preferences and corrections (the oldest messages may be gone).
23
+ 4. Facts that would be costly to find again: exact error messages, values, IDs, URLs, short code snippets.
24
+ 5. The next step, in line with the user's latest request.
25
+
26
+ Do your reasoning in your thinking, not in the reply: only the work-state and the summary are kept, so text outside them is thrown away. What is kept is read again with every later request, and every line of it takes time to write (a long summary makes the compaction take minutes longer), so leave out what the work can go on without.
27
+ Write the summary in the same language the user has been using.
28
+ Do NOT call any tools. Respond with text only.${instructions ? `\n\nAdditional instructions from the user for this summary:\n${instructions}` : ''}`;
29
+ }
30
+
31
+ // The instruction for /rewind's "Summarize from here" (part 'after') and "Summarize up to here" ('before'): only
32
+ // that part of the conversation is summarized, the rest stays in it word for word.
33
+ export function partialCompactPrompt(part, label, instructions = '') {
34
+ const at = label ? `the user's message that begins "${String(label).slice(0, 200)}"` : 'the point the user chose';
35
+ const scope = part === 'before'
36
+ ? `Summarize ONLY the part of the conversation BEFORE ${at}. That message and everything after it stay in the conversation word for word: do not summarize them. The summary replaces only what comes before that message, so it has to carry everything from that earlier part that the rest of the conversation builds on.`
37
+ : `Summarize ONLY the part of the conversation that starts with ${at} (that message included) and goes on to the end. Everything before that message stays in the conversation word for word: do not summarize it. The summary replaces only that later part.`;
38
+ return compactPrompt(`${scope}${instructions ? `\n${instructions}` : ''}`);
39
+ }
40
+
41
+ // The user's own messages go through a compaction word for word, as in Codex (Agent's keptUserMessages picks them):
42
+ // a summary that had to retell them all took minutes longer to write and lost their wording. They come after the
43
+ // summary, so that the summary's <work-state> is the first one in the text (workStateFromText reads the first).
44
+ const KEPT_HEADER = "The user's messages, oldest first (the newest word for word; older ones may be shortened or left out):";
45
+
46
+ function keptSection(messages) {
47
+ if (!messages?.length) return '';
48
+ // A closing tag inside a message would end it early when it is read back.
49
+ const item = (text) => `<user-message>\n${String(text).replaceAll('</user-message', '<\\/user-message')}\n</user-message>`;
50
+ return `\n\n${KEPT_HEADER}\n<user-messages>\n${messages.map(item).join('\n')}\n</user-messages>`;
51
+ }
52
+
53
+ // The user's messages that a summary message (continuationMessage, partialSummaryMessage) kept, oldest first.
54
+ export function keptUserMessagesIn(text) {
55
+ const source = String(text ?? '');
56
+ const start = source.indexOf(`${KEPT_HEADER}\n<user-messages>\n`);
57
+ if (start < 0) return [];
58
+ const section = /<user-messages>\n([\s\S]*?)\n<\/user-messages>/.exec(source.slice(start))?.[1];
59
+ return section ? [...section.matchAll(/<user-message>\n([\s\S]*?)\n<\/user-message>/g)].map((m) => m[1]) : [];
60
+ }
61
+
62
+ // The message that stands in the conversation for the part a partial summary replaced.
63
+ export function partialSummaryMessage(part, summary, workState = null, userMessages = []) {
64
+ const state = workState ? `\n\nThe validated structured work state for this summarized section is:\n<work-state>\n${JSON.stringify(workState, null, 2)}\n</work-state>` : '';
65
+ return part === 'before'
66
+ ? `[Summarized conversation] The earlier part of this conversation was summarized at the user's request; the messages after this one are as they were. The summary of the earlier part:${state}\n${summary}${keptSection(userMessages)}`
67
+ : `[Summarized conversation] The later part of this conversation, from the user's message where this summary stands to where it was, was summarized at the user's request. The summary of that part:${state}\n${summary}${keptSection(userMessages)}`;
68
+ }
69
+
70
+ export function continuationMessage(summary, { auto, workState = null, workStateWarning = '', userMessages = [] }) {
71
+ const state = workState ? `\n\nThe validated structured work state is:\n<work-state>\n${JSON.stringify(workState, null, 2)}\n</work-state>` : '';
72
+ const warning = workStateWarning ? `\n\n<system-reminder>${workStateWarning}</system-reminder>` : '';
73
+ return `This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:${state}${warning}
74
+ ${summary}${keptSection(userMessages)}${auto ? '\n\nPlease continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.' : ''}`;
75
+ }