@yanzc/claude-pro 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +342 -318
  2. package/package.json +1 -2
  3. package/src/agent.js +80 -14
  4. package/src/agents.js +3 -2
  5. package/src/api.js +39 -34
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +169 -67
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +145 -144
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +3 -2
  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 +7 -63
  27. package/src/ratelimit.js +2 -4
  28. package/src/remote.js +76 -14
  29. package/src/runtime.js +33 -10
  30. package/src/selfcheck.js +3 -3
  31. package/src/session.js +93 -3
  32. package/src/supervisor.js +10 -1
  33. package/src/tools/bash.js +18 -17
  34. package/src/tools/browser.js +365 -0
  35. package/src/tools/code.js +430 -0
  36. package/src/tools/effort.js +3 -4
  37. package/src/tools/files.js +368 -45
  38. package/src/tools/index.js +9 -1
  39. package/src/tools/notebook.js +11 -4
  40. package/src/tools/processes.js +274 -0
  41. package/src/tools/search.js +33 -8
  42. package/src/tools/web.js +316 -46
  43. package/src/trace.js +0 -4
  44. package/src/ui/ansi.js +92 -13
  45. package/src/ui/dialogs.js +16 -54
  46. package/src/ui/editor.js +231 -34
  47. package/src/ui/markdown.js +1 -2
  48. package/src/ui/render.js +1 -2
  49. package/src/ui/repl.js +335 -101
  50. package/src/ui/screen.js +139 -31
  51. package/src/updater.js +135 -165
  52. package/src/utils/clipboard.js +5 -3
  53. package/src/utils/dirs.js +136 -0
  54. package/src/utils/encoding.js +23 -2
  55. package/src/utils/paths.js +15 -17
  56. package/src/utils/shell.js +66 -11
  57. package/.env.example +0 -29
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
  });
@@ -398,6 +400,7 @@ export function buildCommands(app) {
398
400
  cfg.modelOverride = forget ? null : choice;
399
401
  if (changed) app.runtime.invalidateSystemPrompt(); // the prompt names the model; the new model starts a cache of its own anyway
400
402
  const kept = keep(cfg, { model: cfg.modelOverride }, forget);
403
+ await loadGatewayModels(cfg); // the window shown may come from the gateway's model list (see Config.resolveModel)
401
404
  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') : ''}`);
402
405
  },
403
406
  });
@@ -406,7 +409,7 @@ export function buildCommands(app) {
406
409
  name: 'effort',
407
410
  get argHint() {
408
411
  const cfg = app.runtime.config;
409
- const login = cfg.usesGateway ? gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) : null;
412
+ const login = gatewayLogin(cfg.gatewayUrl);
410
413
  return `[${effortLevels(cfg.model.id, cachedGatewayModel(login, cfg.model.id)).join('|')}|auto|default]`;
411
414
  },
412
415
  description: 'Set reasoning effort (output_config.effort; kept for later sessions)',
@@ -430,7 +433,7 @@ export function buildCommands(app) {
430
433
  }
431
434
  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
435
  const forget = choice === 'default';
433
- const wanted = (forget ? (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '') : choice).trim().toLowerCase();
436
+ const wanted = (forget ? cfg.configuredEffort : choice).trim().toLowerCase();
434
437
  const next = wanted && wanted !== 'auto' && wanted !== 'default' ? wanted : null;
435
438
  if (next !== cfg.effort && !(await confirmCacheLoss('Changing the effort'))) { out(c.dim('The effort was not changed.')); return; }
436
439
  cfg.effortOverride = forget ? null : choice;
@@ -439,17 +442,9 @@ export function buildCommands(app) {
439
442
  },
440
443
  });
441
444
 
442
- // Keep the gateway selection in the user settings and apply its remembered /model and /effort.
443
- const switchProvider = (provider) => {
445
+ // After a login: the configuration read again, with the remembered /model and /effort.
446
+ const afterLogin = () => {
444
447
  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
448
  const model = cfg.model.id;
454
449
  reloadConfig();
455
450
  cfg.modelOverride = null;
@@ -457,17 +452,20 @@ export function buildCommands(app) {
457
452
  cfg.effortBoost = null;
458
453
  applyRememberedChoices(cfg, app.flags);
459
454
  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
455
  };
463
456
  const accountLine = (account) => `${account.name || ''}${account.email ? ` <${account.email}>` : ''} · balance ${c.bold(formatUsd(account.available_usd ?? account.balance_usd))}`;
464
457
  let pendingLogin = null;
465
- // Logged in to the gateway: this session goes online there at once for read-only viewing and peer messaging.
458
+ // Logged in to the gateway: this session goes online there at once, for its web page and peer messaging. The page
459
+ // can steer the session too (send messages, `!` commands, /cd...) unless CLAUDE_PRO_REMOTE_COMMANDS=0: said as it
460
+ // is, since this message called the page read-only.
466
461
  const goOnline = async () => {
467
462
  const remote = await app.syncRemote();
468
463
  if (!remote) return;
464
+ const page = remote.commands?.length
465
+ ? 'its web page shows it and can send it messages and commands (CLAUDE_PRO_REMOTE_COMMANDS=0 makes the page read-only)'
466
+ : 'the read-only web page shows it';
469
467
  out(remote.registered
470
- ? `${c.green('⇄')} This session is online at the gateway: the read-only web page shows it.`
468
+ ? `${c.green('⇄')} This session is online at the gateway: ${page}.`
471
469
  : c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
472
470
  };
473
471
 
@@ -481,12 +479,12 @@ export function buildCommands(app) {
481
479
  if (choice && choice !== 'gateway') { out(c.red(`Unknown login method "${choice}". Only gateway login is supported.`)); return; }
482
480
 
483
481
  const url = cfg.gatewayUrl;
484
- const saved = readGatewayLogin(url);
482
+ const saved = gatewayLogin(url);
485
483
  if (saved) {
486
484
  try {
487
485
  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`)]);
486
+ afterLogin();
487
+ 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
488
  await goOnline();
491
489
  return;
492
490
  } catch (e) {
@@ -503,8 +501,8 @@ export function buildCommands(app) {
503
501
  signal: controller.signal,
504
502
  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
503
  });
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`)]);
504
+ afterLogin();
505
+ 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
506
  await goOnline();
509
507
  } catch (e) {
510
508
  if (e.name !== 'AbortError') out(c.red(`Gateway login failed: ${e.message}`));
@@ -542,17 +540,17 @@ export function buildCommands(app) {
542
540
  row('Version', VERSION),
543
541
  row('Session ID', app.store.id),
544
542
  row('cwd', app.cwd),
545
- row('Provider', cfg.provider),
543
+ row('Provider', 'gateway'),
546
544
  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)')),
545
+ 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
546
  row('Model', `${cfg.model.label} ${c.dim(`(sent as "${cfg.model.id}", ${formatTokens(cfg.model.contextWindow)} context)`)}`),
549
547
  row('Effort', cfg.effort || 'auto'),
550
548
  row('System prompt', app.flags.systemPrompt !== undefined
551
549
  ? 'command line override'
552
550
  : savedPrompt?.text != null ? `${savedPrompt.name} (saved)` : savedPrompt?.error ? `${savedPrompt.name} (missing; using built-in)` : 'built-in default'),
553
551
  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'),
552
+ 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') : ''}`),
553
+ row('Auto-compact', `at ${formatTokens(cfg.compactWindow())} tokens (100% of window)`),
556
554
  row('Access', 'full (no permission prompts)'),
557
555
  row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
558
556
  row('Shell', `${app.runtime.shell.name} ${c.dim(app.runtime.shell.path)}`),
@@ -565,8 +563,8 @@ export function buildCommands(app) {
565
563
  },
566
564
  });
567
565
 
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.
566
+ // /status about the gateway: whether this session is online there (its web page) and its name for sessions on the
567
+ // other computers.
570
568
  function remoteLines(row) {
571
569
  const cfg = app.runtime.config;
572
570
  const remote = app.remoteState();
@@ -601,7 +599,7 @@ export function buildCommands(app) {
601
599
  `Session time: ${formatDuration(Date.now() - app.sessionStart)}`,
602
600
  ]);
603
601
  const cfg = app.runtime.config;
604
- const saved = cfg.usesGateway && gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
602
+ const saved = gatewayLogin(cfg.gatewayUrl);
605
603
  if (!saved) return;
606
604
  try {
607
605
  const account = await fetchGatewayAccount(saved);
@@ -652,7 +650,7 @@ export function buildCommands(app) {
652
650
  const cfg = app.runtime.config;
653
651
  const a = app.agent;
654
652
  const window = cfg.model.contextWindow;
655
- const threshold = cfg.autoCompactThreshold();
653
+ const threshold = cfg.compactWindow();
656
654
  const sys = estimateTokens(app.runtime.systemPrompt());
657
655
  const tools = estimateTokens(a.toolSchemas());
658
656
  const msgs = estimateTokens(a.messages);
@@ -665,7 +663,7 @@ export function buildCommands(app) {
665
663
  out([
666
664
  `${bar} ${c.bold(formatTokens(used))} / ${formatTokens(window)} tokens (${Math.round((used / window) * 100)}%)`,
667
665
  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'),
666
+ c.dim(`Auto-compact at ${formatTokens(threshold)} tokens (┃) — ${Math.max(0, Math.round((1 - used / threshold) * 100))}% left`),
669
667
  ]);
670
668
  },
671
669
  });
@@ -734,7 +732,7 @@ export function buildCommands(app) {
734
732
  add({
735
733
  name: 'update',
736
734
  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 }); },
735
+ async run() { out(c.dim(`Version ${VERSION} · checking npm…`)); await app.updateFromNpm(); },
738
736
  });
739
737
 
740
738
  add({
@@ -758,6 +756,107 @@ export function buildCommands(app) {
758
756
  },
759
757
  });
760
758
 
759
+ // The tab the Browser tool is to work in, picked by the user instead of looked for by the model: the tabs of the
760
+ // browser with their ids, from the same connection the tool uses (so the ids are the tool's), and the one picked is
761
+ // selected there and named in the message being written. Its id stays that tab's after a reconnect or a restart
762
+ // (BrowserSession.relabel), so the agent goes straight to it. Several browser instances may allow remote debugging
763
+ // (Edge also on a profile directory of its own, as an app's window has): the user picks one first, and the
764
+ // session goes back to it after a restart (BrowserSession.preferred).
765
+ add({
766
+ name: 'tabs',
767
+ aliases: ['tab'],
768
+ argHint: '[edge|chrome|brave|chromium|own|words of a profile directory]',
769
+ description: 'Pick a tab of your browser for the Browser tool: it is selected, and its id goes into your message',
770
+ async run(args) {
771
+ // the agent's own browser calls go to the selected tab: not changed under it while it works
772
+ 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; }
773
+ 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; }
774
+ const s = browserSession;
775
+ // Esc cancels while it waits: the browser may ask the user to allow the connection first
776
+ const busy = async (status, fn) => {
777
+ app.busy = true;
778
+ app.status = status;
779
+ app.turnStart = Date.now();
780
+ app.controller = new AbortController();
781
+ try { return await s.run(app.controller.signal, fn); } finally {
782
+ app.busy = false;
783
+ app.status = null;
784
+ app.controller = null;
785
+ app.screen.schedule();
786
+ }
787
+ };
788
+ const failed = (e, what) => out(e?.name === 'AbortError' ? c.dim('Cancelled.') : c.red(`${what}: ${e.message}`));
789
+ // The instance to connect to: the one matching `ask` (a kind, or words of its profile directory), or the user's
790
+ // pick when several are there. null: none, or the user closed the list.
791
+ const chooseBrowser = async (ask) => {
792
+ let all;
793
+ try { all = await busy('Looking for browsers', () => browserInstances()); } catch (e) { failed(e, 'Cannot list the browsers'); return null; }
794
+ const q = ask.toLowerCase();
795
+ const list = q ? all.filter((i) => i.name === q || `${i.label} ${i.dir}`.toLowerCase().includes(q)) : all;
796
+ if (!list.length) {
797
+ 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.`));
798
+ return null;
799
+ }
800
+ if (list.length === 1) return list[0];
801
+ const connected = list.find((i) => s.connected && sameBrowser(i, s.browser));
802
+ const key = await app.showDialog(new SelectDialog({
803
+ title: 'Which browser?',
804
+ question: 'These allow remote debugging now; each asks once per connection to allow it.',
805
+ 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}` : ''}` })),
806
+ selected: Math.max(0, list.indexOf(connected)),
807
+ }));
808
+ return key ? list.find((i) => (i.dir || i.url) === key) : null;
809
+ };
810
+ try {
811
+ const ask = args.trim();
812
+ let target = null;
813
+ if (ask || !s.connected) {
814
+ target = await chooseBrowser(ask);
815
+ if (!target) return;
816
+ }
817
+ for (;;) {
818
+ if (target) {
819
+ const connecting = target;
820
+ target = null;
821
+ try {
822
+ await busy('Connecting to the browser', () => s.connect(connecting, app.runtime.config.env, (b) => {
823
+ app.status = `Allow the connection in ${b.label} ("Allow remote debugging?" → Allow) · Esc cancels`;
824
+ app.screen.schedule();
825
+ }));
826
+ } catch (e) { failed(e, 'Cannot use the browser'); return; }
827
+ }
828
+ const browser = s.browser;
829
+ const tabs = [...s.tabs.values()];
830
+ if (!browser) { out(c.dim('The connection to the browser was lost.')); return; }
831
+ const title = (t, n) => truncate(String(t.title || '(no title)').replace(/\s+/g, ' '), n);
832
+ const chosen = await app.showDialog(new SelectDialog({
833
+ title: `Tabs in ${browser.label}`,
834
+ question: 'The Browser tool works in the tab you pick, and its id goes into your message.',
835
+ options: [
836
+ ...tabs.map((t) => ({ value: t.targetId, label: `${padEnd(t.id, 8)} ${title(t, 70)}${t === s.current ? c.dim(' (selected)') : ''}`, description: safeUrl(t.url || '') })),
837
+ { value: '__browser__', label: c.dim('Another browser or profile…') },
838
+ ],
839
+ selected: Math.max(0, tabs.indexOf(s.current)),
840
+ }));
841
+ if (!chosen) return;
842
+ if (chosen === '__browser__') {
843
+ target = await chooseBrowser('');
844
+ if (!target) return;
845
+ continue;
846
+ }
847
+ const tab = s.tabs.get(chosen);
848
+ if (!tab) { out(c.red('That tab was closed meanwhile.')); return; }
849
+ try { await busy('Selecting the tab', () => s.select(tab)); } catch (e) { failed(e, `Could not select ${tab.id}`); return; }
850
+ app.editor.insert(`[Browser tab ${tab.id} in ${browser.label}: ${JSON.stringify(title(tab, 60))}] `);
851
+ out(c.dim(`${tab.id} is the Browser tool's tab now, and its id is in your message.`));
852
+ return;
853
+ }
854
+ } finally {
855
+ app.sendWhatWaited(); // what was typed while it connected
856
+ }
857
+ },
858
+ });
859
+
761
860
  add({
762
861
  name: 'tui',
763
862
  argHint: '[fullscreen | default]',
@@ -770,7 +869,7 @@ export function buildCommands(app) {
770
869
  }
771
870
  if (want !== 'fullscreen' && want !== 'default') { out(c.red('Use /tui fullscreen or /tui default.')); return; }
772
871
  const file = settingsFiles(app.cwd).user;
773
- updateSettingsFile(file, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_TUI: want }; });
872
+ writeConfigSetting(file, 'tui', want);
774
873
  reloadConfig();
775
874
  app.screen.setFull(want === 'fullscreen');
776
875
  out(want === 'fullscreen'
@@ -856,7 +955,11 @@ export function buildCommands(app) {
856
955
  await app.agent.summarizePart(index, { part, label: entry.label, signal: app.controller.signal });
857
956
  store.summarized(id, part, index);
858
957
  app.remote?.resync();
859
- if (part === 'after' && prompt) app.editor.set(prompt); // as Claude Code does: the prompt to send again or edit
958
+ // as Claude Code does: the prompt to send again or edit; not over what was typed while it summarized
959
+ if (part === 'after' && prompt) {
960
+ if (!app.editor.text.trim()) app.editor.set(prompt);
961
+ else out(c.dim('The prompt was not put back in the input box: it holds what you typed meanwhile.'));
962
+ }
860
963
  } catch (e) {
861
964
  if (!app.controller.signal.aborted) out(c.red(`Could not summarize: ${e.message}`));
862
965
  else out(c.red('Summarizing interrupted'));
@@ -953,8 +1056,7 @@ export function buildCommands(app) {
953
1056
 
954
1057
  add({
955
1058
  name: 'verbose',
956
- aliases: ['thinking'],
957
- description: 'Toggle verbose output (thinking, full tool results)',
1059
+ description: 'Toggle detailed tool output and compaction summaries',
958
1060
  run() {
959
1061
  app.verbose = !app.verbose;
960
1062
  out(`Verbose mode ${app.verbose ? 'on' : 'off'}`);
@@ -994,7 +1096,7 @@ export function buildCommands(app) {
994
1096
  `${c.green('✔')} Node ${process.versions.node}`,
995
1097
  `${app.runtime.shell.kind === 'bash' ? c.green('✔') : c.yellow('!')} Shell: ${app.runtime.shell.name} (${app.runtime.shell.path})`,
996
1098
  `${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)'}`,
1099
+ `${gatewayLogin(cfg.gatewayUrl) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${gatewayLogin(cfg.gatewayUrl) ? '' : ' missing (/login)'}`,
998
1100
  ];
999
1101
  out(lines);
1000
1102
  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
+ }