@yanzc/claude-pro 0.7.8 → 0.9.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/cache.js CHANGED
@@ -149,6 +149,24 @@ export class CacheStats {
149
149
  return this.expected != null && this.expected >= MIN_CACHED && now < this.expiresAt;
150
150
  }
151
151
 
152
+ // What the session file keeps of the cache, so that a restarted (or quickly resumed) conversation knows what the
153
+ // cache holds and until when (the refresh of keepalive.js needs it); null when nothing is warm.
154
+ snapshot(now = Date.now()) {
155
+ return this.isWarm(now) ? { expected: this.expected, expiresAt: this.expiresAt, ttl: this.ttl, prev: this.prev } : null;
156
+ }
157
+
158
+ // The other way round, for a conversation loaded while its cache was still warm.
159
+ restore(state, now = Date.now()) {
160
+ if (!state || !(state.expiresAt > now) || !(state.expected >= MIN_CACHED) || !TTL_MS[state.ttl]) return false;
161
+ this.expected = state.expected;
162
+ this.expiresAt = state.expiresAt;
163
+ this.ttl = state.ttl;
164
+ this.prev = state.prev && typeof state.prev === 'object' ? state.prev : null;
165
+ this.model = this.prev?.model ?? null;
166
+ this.effort = this.prev?.effort ?? null;
167
+ return true;
168
+ }
169
+
152
170
  get hitRatio() {
153
171
  const total = this.input + this.read + this.write;
154
172
  return total > 0 ? this.read / total : null;
package/src/commands.js CHANGED
@@ -15,12 +15,11 @@ import { listBackgroundShells } from './tools/bash.js';
15
15
  import { estimateTokens } from './agent.js';
16
16
  import { quickQuery, cacheRefusals, defaultEffort, effortToSend, CLAUDE_EFFORTS } from './api.js';
17
17
  import { hasRipgrep } from './utils/shell.js';
18
- import { displayPath, resolvePath } from './utils/paths.js';
18
+ import { displayPath, normalizeDir, resolvePath } from './utils/paths.js';
19
19
  import { activePromptName, listPromptProfiles, loadActivePrompt, promptDirectory, promptNameForText, savePrompt, setActivePrompt } from './prompt-profiles.js';
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 { describeHost, normalizeDir } from './host.js';
24
23
 
25
24
  const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
26
25
  const isGpt = (modelId) => /^gpt-/i.test(modelId);
@@ -112,7 +111,7 @@ export function buildCommands(app) {
112
111
  if (!app.agent.messages.length || !cache.isWarm() || (model && model === cache.model)) return true;
113
112
  const choice = await app.showDialog(new SelectDialog({
114
113
  title: what,
115
- question: `The prompt cache is warm (about ${formatTokens(cache.expected)} tokens, ${formatDuration(cache.expiresAt - Date.now())} left). ${what} makes the next request read the whole conversation again without it, which costs more and takes longer. Go on?`,
114
+ question: `The prompt cache is warm (about ${formatTokens(cache.expected)} tokens, ${formatDuration(cache.expiresAt - Date.now())} left). ${what} makes the next request read the whole conversation again without it, which costs more and takes longer. The restored conversation stays in context; only the model changes. Go on?`,
116
115
  color: c.blue,
117
116
  options: [{ label: 'Yes, go on', value: 'yes' }, { label: 'No, leave it as it is', value: 'no' }],
118
117
  cancelValue: 'no',
@@ -399,7 +398,7 @@ export function buildCommands(app) {
399
398
  cfg.modelOverride = forget ? null : choice;
400
399
  if (changed) app.runtime.invalidateSystemPrompt(); // the prompt names the model; the new model starts a cache of its own anyway
401
400
  const kept = keep(cfg, { model: cfg.modelOverride }, forget);
402
- out(`Model set to ${c.bold(cfg.model.label)} ${c.dim(`(${formatTokens(cfg.model.contextWindow)} context)`)}${kept}`);
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') : ''}`);
403
402
  },
404
403
  });
405
404
 
@@ -463,14 +462,12 @@ export function buildCommands(app) {
463
462
  };
464
463
  const accountLine = (account) => `${account.name || ''}${account.email ? ` <${account.email}>` : ''} · balance ${c.bold(formatUsd(account.available_usd ?? account.balance_usd))}`;
465
464
  let pendingLogin = null;
466
- // Logged in to the gateway: this session goes online there at once (remote control, the other computers'
467
- // sessions), and the computer service starts (the web page opens new sessions through it).
465
+ // Logged in to the gateway: this session goes online there at once for read-only viewing and peer messaging.
468
466
  const goOnline = async () => {
469
467
  const remote = await app.syncRemote();
470
- app.ensureHost({ login: true });
471
468
  if (!remote) return;
472
469
  out(remote.registered
473
- ? `${c.green('⇄')} This session is online at the gateway: the web page (远程控制) shows it.`
470
+ ? `${c.green('⇄')} This session is online at the gateway: the read-only web page shows it.`
474
471
  : c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
475
472
  };
476
473
 
@@ -524,7 +521,7 @@ export function buildCommands(app) {
524
521
  const cfg = app.runtime.config;
525
522
  const had = clearGatewayLogin();
526
523
  const wasOnline = Boolean(app.remote);
527
- app.stopRemote(); // the other sessions of this computer and its computer service follow within seconds
524
+ app.stopRemote(); // the other sessions of this computer follow within seconds
528
525
  out(had
529
526
  ? `Logged out of the gateway ${cfg.gatewayUrl}.${wasOnline ? ' This session is offline there now.' : ''} Run /login to log in again.`
530
527
  : c.dim('There was no gateway login. Run /login to log in.'));
@@ -568,18 +565,16 @@ export function buildCommands(app) {
568
565
  },
569
566
  });
570
567
 
571
- // /status about the gateway: whether this session is online there, its name for the
572
- // sessions on the other computers, and the computer service.
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.
573
570
  function remoteLines(row) {
574
571
  const cfg = app.runtime.config;
575
572
  const remote = app.remoteState();
576
573
  const me = app.peerLabel();
577
- const lines = [
578
- row('Remote control', remote.text),
579
- row('Name', `&${me} ${c.dim(`(on your other computers: &${machineName(cfg.env)}/${me}; /rename changes it)`)}`),
580
- row('Computer service', describeHost(cfg.env)),
574
+ return [
575
+ row('Remote session', remote.text),
576
+ row('Name', `@${me} ${c.dim(`(on your other computers: @${machineName(cfg.env)}/${me}; /rename changes it)`)}`),
581
577
  ];
582
- return lines;
583
578
  }
584
579
 
585
580
  add({
@@ -598,8 +593,9 @@ export function buildCommands(app) {
598
593
  `Total cost: ${formatUsd(app.cost)} ${c.dim('for this conversation, at list prices (sub-agents, compaction and side requests included)')}`,
599
594
  `Total input: ${formatTokens(u.input + u.cacheRead + u.cacheWrite)} tokens ${c.dim(`(${formatTokens(u.cacheRead)} cache read, ${formatTokens(u.cacheWrite)} cache write${u.cacheWrite1h ? `, ${formatTokens(u.cacheWrite1h)} of it for 1 hour` : ''})`)}`,
600
595
  `Total output: ${formatTokens(u.output)} tokens`,
601
- `API requests: ${u.requests}${u.compactions ? c.dim(` + ${u.compactions} to compact the conversation`) : ''}`,
596
+ `API requests: ${u.requests}${u.compactions ? c.dim(` + ${u.compactions} to compact the conversation`) : ''}${u.keepalives ? c.dim(` + ${u.keepalives} to keep the prompt cache warm`) : ''}`,
602
597
  ...cacheLines.map((line, i) => (i ? c.dim(line) : line)),
598
+ ...(a.keepAlive?.describe() ? [c.dim(` ${a.keepAlive.describe()}`)] : []),
603
599
  ...(trace ? [`Trace: ${trace.requests} requests · ${toolCalls} tool calls${toolCalls ? ` · ${Math.round((toolSuccesses / toolCalls) * 100)}% tool success` : ''} · ${trace.compactions} compactions · ${trace.verification_runs} verifications`] : []),
604
600
  ...(b.runs ? [c.dim(`Sub-agents: ${b.runs} run${b.runs === 1 ? '' : 's'}, ${b.requests + b.compactions} request${b.requests + b.compactions === 1 ? '' : 's'}, ${formatTokens(b.input + b.cacheRead + b.cacheWrite)} input (${formatTokens(b.cacheRead)} cached), ${formatTokens(b.output)} output; included in the totals`)] : []),
605
601
  `Session time: ${formatDuration(Date.now() - app.sessionStart)}`,
@@ -745,19 +741,19 @@ export function buildCommands(app) {
745
741
  name: 'peers',
746
742
  aliases: ['sessions'],
747
743
  argHint: '[name NEW-NAME]',
748
- description: 'List the other sessions, on this computer and (through the gateway) on your other computers; send one a task with &name ...',
744
+ description: 'List the other sessions, on this computer and (through the gateway) on your other computers; send one a task with @name ...',
749
745
  async run(args) {
750
746
  const [action, ...rest] = args.split(/\s+/).filter(Boolean);
751
- if (action === 'name' && rest.length) { out(`This session is now ${c.bold('&' + app.renameSession(rest.join('-')))}`); return; }
747
+ if (action === 'name' && rest.length) { out(`This session is now ${c.bold('@' + app.renameSession(rest.join('-')))}`); return; }
752
748
  const { me, local, remote, online } = await app.listAllPeers();
753
749
  out([
754
- `This session: ${c.bold('&' + me.name)} ${c.dim(displayPath(me.cwd, app.cwd))}${online ? c.dim(` · from other computers: &${me.label}`) : ''}`,
755
- ...local.map((p) => `${c.bold('&' + p.name)} ${c.dim(`${p.cwd} · pid ${p.pid}`)}`),
756
- ...(remote.length ? [c.dim('On your other computers, through the gateway:'), ...remote.map((p) => `${c.bold('&' + p.label)} ${c.dim(`${p.cwd}${p.busy ? ' · busy' : ''}`)}`)] : []),
750
+ `This session: ${c.bold('@' + me.name)} ${c.dim(displayPath(me.cwd, app.cwd))}${online ? c.dim(` · from other computers: @${me.label}`) : ''}`,
751
+ ...local.map((p) => `${c.bold('@' + p.name)} ${c.dim(`${p.cwd} · pid ${p.pid}`)}`),
752
+ ...(remote.length ? [c.dim('On your other computers, through the gateway:'), ...remote.map((p) => `${c.bold('@' + p.label)} ${c.dim(`${p.cwd}${p.busy ? ' · busy' : ''}`)}`)] : []),
757
753
  ...(local.length || remote.length ? [] : [c.dim('No other session is running.')]),
758
754
  c.dim(online
759
- ? '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. /rename names this session. The agent can use ListPeers / MessagePeer too.'
760
- : '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).'),
755
+ ? 'Type "@" for the combined file/session 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. /rename names this session. The agent can use ListPeers / MessagePeer too.'
756
+ : 'Type "@" for the combined file/session 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).'),
761
757
  ]);
762
758
  },
763
759
  });
@@ -778,7 +774,7 @@ export function buildCommands(app) {
778
774
  reloadConfig();
779
775
  app.screen.setFull(want === 'fullscreen');
780
776
  out(want === 'fullscreen'
781
- ? `Fullscreen: the input box stays at the bottom; scroll with the wheel, PgUp/PgDn, ctrl+Home/End; drag to select and copy; ctrl+f to find in the conversation. (Saved in ${file})`
777
+ ? `Fullscreen: the input box stays at the bottom; scroll with the wheel, PgUp/PgDn, ctrl+Home/End; drag to select, then use ctrl+c to copy; ctrl+f to find in the conversation. (Saved in ${file})`
782
778
  : `Default renderer: the conversation scrolls in the terminal. (Saved in ${file})`);
783
779
  },
784
780
  });
@@ -787,13 +783,13 @@ export function buildCommands(app) {
787
783
  name: 'rename',
788
784
  argHint: '<name>',
789
785
  argRequired: true,
790
- description: 'Name this session: the other sessions send it tasks with &name, and it is the title (tab, /resume, the web page)',
786
+ description: 'Name this session: the other sessions send it tasks with @name, and it is the title (tab, /resume, the web page)',
791
787
  run(args) {
792
788
  const name = args.trim();
793
- if (!name) { out(`This session is ${c.bold('&' + app.peerLabel())}. /rename NAME gives it another name.`); return; }
789
+ if (!name) { out(`This session is ${c.bold('@' + app.peerLabel())}. /rename NAME gives it another name.`); return; }
794
790
  const got = app.renameSession(name);
795
791
  const note = got !== cleanName(name) ? c.dim(' (another session on this computer has that name)') : '';
796
- out(`This session is now ${c.bold('&' + got)}${note}${app.remote ? c.dim(` · from your other computers: &${machineName(app.config.env)}/${got}`) : ''}`);
792
+ out(`This session is now ${c.bold('@' + got)}${note}${app.remote ? c.dim(` · from your other computers: @${machineName(app.config.env)}/${got}`) : ''}`);
797
793
  },
798
794
  });
799
795
 
package/src/config.js CHANGED
@@ -33,8 +33,8 @@ export const KNOWN_KEYS = {
33
33
  CLAUDE_PRO_GATEWAY_URL: `codex-gateway address (default https://gw.predix.icu)`,
34
34
  CLAUDE_PRO_GATEWAY_API_KEY: 'Gateway API key (normally saved by /login in gateway.json)',
35
35
  CLAUDE_PRO_GATEWAY_MODEL: 'Model with the gateway provider (default: opus; also sonnet, haiku, gpt-6.1-sol)',
36
- 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)',
37
- 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',
36
+ CLAUDE_PRO_ONLINE: 'Set to 0 to keep interactive sessions off the gateway. Otherwise a session is online on the gateway\'s web page whenever this computer is logged in, and sessions on your other computers can send it tasks (@computer/name)',
37
+ CLAUDE_PRO_REMOTE_COMMANDS: 'Set to 0 to make this computer\'s sessions read-only on the gateway\'s web page: it can watch them, but not send them messages, answer their questions, stop them, switch model or effort, or change their directory (default: on; read when a session goes online)',
38
38
  CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
39
39
  CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside) or default (classic: it scrolls in the terminal); /tui switches',
40
40
  CLAUDE_PRO_AUTO_RESTART: 'Restart by itself when a turn ends and claude-pro\'s own source files changed (default 1; 0 = only on /restart or the Restart tool)',
@@ -49,6 +49,7 @@ export const KNOWN_KEYS = {
49
49
  CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 'Prompt cache TTL of everything else (sub-agents, compaction, side queries): 5m (default) or 1h. Also the subagentPromptCacheTtl setting',
50
50
  ENABLE_PROMPT_CACHING_1H: 'Set to 1 to request the 1-hour TTL for both (the two TTL variables above win over it)',
51
51
  FORCE_PROMPT_CACHING_5M: 'Set to 1 to force the 5-minute TTL for both, over every other TTL setting',
52
+ CLAUDE_PRO_CACHE_KEEPALIVE_HOURS: 'Claude models with the 1-hour TTL: while you are away, refresh the conversation\'s prompt cache shortly before it runs out (a read costs 1/40 of a rewrite), for a pause of up to this many hours (default 8; 0 turns it off)',
52
53
  DISABLE_PROMPT_CACHING: 'Set to 1 to send no cache_control markers at all (prompt caching off for every model)',
53
54
  DISABLE_PROMPT_CACHING_HAIKU: 'Set to 1 to turn prompt caching off for the model the haiku alias resolves to',
54
55
  DISABLE_PROMPT_CACHING_SONNET: 'Set to 1 to turn prompt caching off for the model the sonnet alias resolves to',
@@ -293,6 +294,11 @@ export class Config {
293
294
  // Clearing old tool results after a long pause (see Agent.clearAfterIdle): the gateway prompt cache has
294
295
  // expired by then, so retaining old tool payloads would only make the next request larger.
295
296
  get clearAfterIdle() { return true; }
297
+ // How long a pause the conversation's prompt cache is kept warm for (hours; 0: not at all), see keepalive.js.
298
+ get cacheKeepAliveHours() {
299
+ const v = Number(String(this.env.CLAUDE_PRO_CACHE_KEEPALIVE_HOURS ?? '').trim() || NaN);
300
+ return Number.isFinite(v) && v >= 0 ? v : 8;
301
+ }
296
302
  // How deep sub-agents may nest: the main agent is depth 0; an agent below this depth gets the Task tool.
297
303
  get maxSubagentDepth() { return 2; }
298
304
 
package/src/filestate.js CHANGED
@@ -12,7 +12,7 @@
12
12
  import fs from 'node:fs';
13
13
  import { resolvePath } from './utils/paths.js';
14
14
 
15
- const TRACKED = new Set(['Read', 'Write', 'Edit', 'NotebookEdit']);
15
+ const TRACKED = new Set(['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
16
16
  const SLACK_MS = 2000; // file timestamps can be coarser than the clock that stamped the message
17
17
 
18
18
  const resultText = (content) => (typeof content === 'string' ? content : '');
@@ -0,0 +1,129 @@
1
+ // Keeping the conversation's prompt cache warm while the user is away.
2
+ //
3
+ // With the 1-hour TTL, a request after more than an hour of pause writes the whole conversation into the cache
4
+ // again: on Opus through the gateway $8 per million tokens instead of the $0.20 a cache read costs (about $1.20
5
+ // for 150k tokens). A read refreshes the TTL, so a request that reads the cached prefix shortly before it runs out
6
+ // keeps it for another hour, for 1/40 of a rewrite. That request is the conversation's last request again (the same
7
+ // system prompt, tools, effort and messages, so the same cache entry) with max_tokens 1. Measured on Opus 5.5
8
+ // through the gateway (2026-10-25): it read all 19,440 cached tokens, wrote none and produced one output token, and
9
+ // the next turn read the cache as usual.
10
+ //
11
+ // Only for Claude models: GPT through the gateway is cached upstream for hours anyway (traces 2026-10-15..25:
12
+ // 8 of 9 requests after a 2-4 hour pause read the cache), and a miss there costs plain input, not a write.
13
+ // The pause it covers is limited (Config.cacheKeepAliveHours, 8 by default): for a conversation that is not
14
+ // continued, the 8 refreshes of 8 hours cost a fifth of the one rewrite they would have saved.
15
+
16
+ import { buildParams } from './api.js';
17
+ import { fingerprint, TTL_MS } from './cache.js';
18
+ import { formatUsd } from './gateway.js';
19
+
20
+ const LEAD_MS = 5 * 60_000; // refresh this long before the cache would run out
21
+ const SAFETY_MS = 60_000; // ... and not at all once it is closer than this to running out (the computer slept)
22
+ const MIN_TOKENS = 20_000; // a smaller conversation is cheap to write again: not worth a request an hour
23
+
24
+ const sameFingerprint = (a, b) => Boolean(a && b) && ['model', 'system', 'tools', 'effort', 'thinking'].every((k) => a[k] === b[k]);
25
+
26
+ export class CacheKeepAlive {
27
+ constructor(agent) {
28
+ this.agent = agent;
29
+ this.timer = null;
30
+ this.inflight = null; // the AbortController of a refresh being sent
31
+ this.pauseStart = 0; // when the conversation's last real request started: the pause counts from there
32
+ this.done = { count: 0, cost: 0, failed: null }; // over the session, for /cost
33
+ }
34
+
35
+ get hours() { return this.agent.config.cacheKeepAliveHours; }
36
+
37
+ // Whether there is a cache to keep warm now: the main conversation, idle, on a Claude model with the 1-hour TTL,
38
+ // with a warm cache of some size, and a next request that will use the same entry.
39
+ applies(now = Date.now()) {
40
+ const a = this.agent;
41
+ const cfg = a.config;
42
+ if (a.isSubagent || a.busy > 0 || !(this.hours > 0)) return false;
43
+ const id = a.model?.id || '';
44
+ if (!/^claude-/i.test(id) || cfg.promptCachingDisabled(id)) return false;
45
+ if (!a.cache.isWarm(now) || a.cache.ttl !== '1h' || (a.cache.expected || 0) < MIN_TOKENS) return false;
46
+ // A raised effort ends with the next user request, and with it this entry (the effort is part of its key).
47
+ if (cfg.effortBoost && !cfg.effortBoostKeepNext) return false;
48
+ return true;
49
+ }
50
+
51
+ // A real request of the conversation started at `at`: a pause, if one comes, counts from there.
52
+ noteRequest(at = Date.now()) {
53
+ this.pauseStart = at;
54
+ }
55
+
56
+ // Plan the next refresh: LEAD_MS before the cache runs out, while the pause is within the hours it covers.
57
+ plan() {
58
+ this.clearTimer();
59
+ if (!this.applies()) return;
60
+ const cache = this.agent.cache;
61
+ const due = cache.expiresAt - LEAD_MS;
62
+ // Not known (a state saved without it): from the request that left the cache, the latest it can be.
63
+ this.pauseStart ||= cache.expiresAt - TTL_MS[cache.ttl];
64
+ if (due - this.pauseStart > this.hours * 3_600_000) return;
65
+ this.timer = setTimeout(() => {
66
+ this.timer = null;
67
+ this.refresh().catch(() => { /* reported inside */ });
68
+ }, Math.max(1000, due - Date.now()));
69
+ this.timer.unref?.(); // a print-mode run, or an exit, does not wait for it
70
+ }
71
+
72
+ // The user is back (a turn starts), or the conversation changed: no refresh now, and none in flight.
73
+ stop() {
74
+ this.clearTimer();
75
+ if (this.inflight) this.inflight.abort('user');
76
+ }
77
+
78
+ clearTimer() {
79
+ if (this.timer) clearTimeout(this.timer);
80
+ this.timer = null;
81
+ }
82
+
83
+ async refresh() {
84
+ const a = this.agent;
85
+ const now = Date.now();
86
+ // Too late (a computer that slept, a timer that ran late): the cache is gone or about to go, and a request now
87
+ // would write it all.
88
+ if (!this.applies(now) || now > a.cache.expiresAt - SAFETY_MS) return;
89
+ const request = a.keepAliveRequest();
90
+ if (!request) return;
91
+ // The entry the last request left, or nothing: with another system prompt, tool list or effort the refresh
92
+ // would write the whole conversation, and the next request would not use it either.
93
+ if (!sameFingerprint(fingerprint(buildParams(a.config, request)), a.cache.prev)) return;
94
+ const expected = a.cache.expected;
95
+ const ac = new AbortController();
96
+ this.inflight = ac;
97
+ // Not sent again (retried) once the cache could have run out: then it would be a rewrite, not a refresh.
98
+ const deadline = setTimeout(() => ac.abort('deadline'), Math.max(0, a.cache.expiresAt - SAFETY_MS - now));
99
+ deadline.unref?.();
100
+ try {
101
+ const res = await a.streamAgentRequest(request, { signal: ac.signal, kind: 'keepalive', waitForRateLimit: false });
102
+ this.done.count++;
103
+ this.done.cost += res.cost || 0;
104
+ const read = res.usage?.cache_read_input_tokens || 0;
105
+ if (read < expected * 0.5) {
106
+ const wrote = res.usage?.cache_creation_input_tokens || 0;
107
+ this.done.failed = `missed the cache (wrote ${wrote} tokens)`;
108
+ a.io.notice?.(`Refreshing the prompt cache missed it (it wrote ${Math.round(wrote / 1000)}k tokens again); no more refreshes until your next message.`, 'warn');
109
+ return;
110
+ }
111
+ this.plan();
112
+ } catch (err) {
113
+ if (ac.signal.reason === 'user') return; // the next request reads the cache itself
114
+ this.done.failed = ac.signal.reason === 'deadline' ? 'took too long' : err.message;
115
+ const until = new Date(a.cache.expiresAt).toTimeString().slice(0, 5);
116
+ a.io.notice?.(`Could not refresh the prompt cache (${this.done.failed}); it runs out at ${until}.`, 'warn');
117
+ } finally {
118
+ clearTimeout(deadline);
119
+ if (this.inflight === ac) this.inflight = null;
120
+ }
121
+ }
122
+
123
+ // For /cost: null when nothing was done.
124
+ describe() {
125
+ const d = this.done;
126
+ if (!d.count && !d.failed) return null;
127
+ return `kept warm while idle: ${d.count} refresh${d.count === 1 ? '' : 'es'}${d.cost ? ` (${formatUsd(d.cost)})` : ''}${d.failed ? `, last failure: ${d.failed}` : ''}`;
128
+ }
129
+ }
package/src/main.js CHANGED
@@ -23,11 +23,7 @@ Options:
23
23
  --system-prompt-file <file> Replace the system prompt with the contents of a file
24
24
  --verbose Show thinking and full tool output
25
25
  --no-mcp Do not start MCP servers
26
- --name <name> Name this session, as /rename does (other sessions reach it with &name)
27
- --remote-id <id> Go online at the gateway at once with this id (the gateway's web page opens
28
- sessions this way, through claude-pro host)
29
- --headless A background session: no window, used from the web page (with --remote-id)
30
- and from claude-pro attach; what it prints goes to stdout as a log
26
+ --name <name> Name this session, as /rename does (other sessions reach it with @name)
31
27
  -v, --version Print version
32
28
  -h, --help Show help
33
29
 
@@ -41,21 +37,12 @@ Commands:
41
37
  claude-pro config list Show effective configuration and where each value comes from
42
38
  claude-pro config set <KEY> <VALUE> [--project|--local] Save a setting (default: ~/.claude-pro/settings.json)
43
39
  claude-pro config unset <KEY> [--project|--local]
44
- claude-pro host [start|stop|status|install|uninstall] The computer service: lets the gateway's web page
45
- open sessions on this computer (claude-pro host --help)
46
- claude-pro connect <code> [--url U] Join this computer to your gateway account with the web page's pairing
47
- code; the computer service then starts, and starts at logon
48
- claude-pro attach [name] Use a background session of this computer here, in this terminal
49
- (ctrl+] detaches; it goes on in the background)
50
-
51
40
  Interactive prompt commands:
52
41
  /prompt <file|text> Save and use a system prompt for later sessions
53
42
  /prompts Choose a saved prompt (or select default)
54
43
  /promt, /promits Accepted spelling-compatible aliases
55
44
  `;
56
45
 
57
- const REMOTE_ID = /^[A-Za-z0-9_-]{8,64}$/;
58
-
59
46
  function parseArgs(argv) {
60
47
  const flags = {};
61
48
  const positional = [];
@@ -89,14 +76,7 @@ function parseArgs(argv) {
89
76
  case '--verbose': flags.verbose = true; break;
90
77
  case '--no-mcp': flags.noMcp = true; break;
91
78
  case '--remote-control': case '--rc': break; // online by default now
92
- case '--headless': flags.headless = true; break;
93
79
  case '--name': flags.name = next(); break;
94
- case '--remote-id': {
95
- const id = next();
96
- if (!REMOTE_ID.test(id || '')) { process.stderr.write(`--remote-id takes 8 to 64 letters, digits, _ or -, not "${id ?? ''}"\n`); process.exit(2); }
97
- flags.remoteId = id;
98
- break;
99
- }
100
80
  case '-v': case '--version': flags.version = true; break;
101
81
  case '-h': case '--help': flags.help = true; break;
102
82
  default:
@@ -171,12 +151,17 @@ function readStdin({ optional }) {
171
151
  });
172
152
  }
173
153
 
154
+ // Commands that are gone. Said so instead of taking them as a prompt: an autostart entry or a script that still
155
+ // runs `claude-pro host start` must not turn into an agent run with full access.
156
+ const REMOVED_COMMANDS = new Set(['host', 'attach', 'connect']);
157
+
174
158
  export async function main(argv) {
175
159
  let cwd = process.cwd();
176
160
  if (argv[0] === 'config') return configCommand(argv.slice(1), cwd);
177
- if (argv[0] === 'host') return (await import('./host.js')).hostCommand(argv.slice(1));
178
- if (argv[0] === 'attach') return (await import('./attach.js')).attachCommand(argv.slice(1));
179
- if (argv[0] === 'connect') return (await import('./connect.js')).connectCommand(argv.slice(1));
161
+ if (REMOVED_COMMANDS.has(argv[0])) {
162
+ process.stderr.write(`claude-pro ${argv[0]} was removed (the computer service, attach and connect are no longer part of claude-pro). To send this as a prompt, quote it: claude-pro "${argv.join(' ')}"\n`);
163
+ return 2;
164
+ }
180
165
  if (argv[0] === '--self-check') return (await import('./selfcheck.js')).selfCheck(); // see restart.js
181
166
  const { flags, positional } = parseArgs(argv);
182
167
  if (flags.version) { console.log(`${VERSION} (claude-pro)`); return 0; }
@@ -199,9 +184,8 @@ export async function main(argv) {
199
184
  let prompt = positional.join(' ');
200
185
 
201
186
  // Started by a restart of a running session: that session is picked up again, whatever the command line
202
- // that started the first one said (-c, --resume, a first prompt). A background session (--headless) has no
203
- // terminal and is interactive all the same.
204
- const interactive = flags.headless || !(flags.print || !process.stdout.isTTY || !process.stdin.isTTY);
187
+ // that started the first one said (-c, --resume, a first prompt).
188
+ const interactive = !(flags.print || !process.stdout.isTTY || !process.stdin.isTTY);
205
189
  const restart = interactive ? takeRestartState() : null;
206
190
  if (restart) {
207
191
  flags.restart = restart;
@@ -221,13 +205,7 @@ export async function main(argv) {
221
205
  if (flags.continue || (flags.resume && flags.resumeId)) {
222
206
  const sessions = SessionStore.list(cwd);
223
207
  const found = flags.resumeId ? sessions.find((s) => s.id.startsWith(flags.resumeId)) : sessions[0];
224
- if (!found && flags.headless) {
225
- // a background session opened again (after a crash, a reboot) that never had a conversation: a new one
226
- process.stdout.write(`No conversation ${flags.resumeId || ''} here: starting a new one.\n`);
227
- flags.continue = false;
228
- flags.resume = false;
229
- flags.resumeId = undefined;
230
- } else if (!found) {
208
+ if (!found) {
231
209
  process.stderr.write(flags.resumeId ? `No conversation found with id ${flags.resumeId}\n` : 'No conversation found to continue\n');
232
210
  return 1;
233
211
  } else {
@@ -236,11 +214,6 @@ export async function main(argv) {
236
214
  }
237
215
  }
238
216
 
239
- if (flags.headless) {
240
- if (!fs.existsSync(cwd)) return 1;
241
- const { runRepl } = await import('./ui/repl.js');
242
- return await runRepl({ flags, cwd, initialPrompt: prompt });
243
- }
244
217
  // mintty (Git Bash's default window) connects programs through pipes, not a console.
245
218
  if (!flags.print && !process.stdin.isTTY && process.env.TERM_PROGRAM === 'mintty') {
246
219
  process.stderr.write('Interactive mode needs a real console. In mintty/Git Bash run `winpty claude-pro` (or `winpty node bin/claude-pro.js`), or use Windows Terminal. For scripts use `claude-pro -p`.\n');
package/src/mcp.js CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { spawn } from 'node:child_process';
7
7
  import { VERSION } from './config.js';
8
- import { killTree } from './utils/shell.js';
8
+ import { killTreeSync } from './utils/shell.js';
9
9
 
10
10
  const PROTOCOL_VERSION = '2025-06-18';
11
11
  const isWin = process.platform === 'win32';
@@ -114,7 +114,7 @@ class StdioTransport {
114
114
  }
115
115
 
116
116
  notify(method, params) { this.send({ jsonrpc: '2.0', method, params }); }
117
- close() { this.closed = true; killTree(this.child); }
117
+ close() { this.closed = true; killTreeSync(this.child); } // also at exit: done before it returns
118
118
  }
119
119
 
120
120
  class HttpTransport {
@@ -189,6 +189,22 @@ class HttpTransport {
189
189
 
190
190
  const sanitize = (s) => String(s).replace(/[^a-zA-Z0-9_-]/g, '_');
191
191
 
192
+ // initialize, then notifications/initialized. Over HTTP the notification is a request of its own: what comes next
193
+ // must not overtake it, or a server that insists on a finished handshake answers "not initialized".
194
+ async function handshake(transport) {
195
+ const timeout = parseInt(process.env.MCP_TIMEOUT, 10) || 30_000;
196
+ const init = await transport.request('initialize', {
197
+ protocolVersion: PROTOCOL_VERSION,
198
+ capabilities: {},
199
+ clientInfo: { name: 'claude-pro', version: VERSION },
200
+ }, { timeout });
201
+ await transport.notify('notifications/initialized', {});
202
+ return init;
203
+ }
204
+
205
+ const RESTARTS = 3; // a stdio server that exits is started again at most this often...
206
+ const RESTART_WINDOW_MS = 10 * 60_000; // ... in this time
207
+
192
208
  function convertContent(result) {
193
209
  const blocks = [];
194
210
  for (const c of result.content || []) {
@@ -219,17 +235,10 @@ export class McpManager {
219
235
  const transport = type === 'http' ? new HttpTransport(name, cfg) : new StdioTransport(name, cfg, this.cwd);
220
236
  entry.transport = transport;
221
237
  await transport.connect();
222
- const timeout = parseInt(process.env.MCP_TIMEOUT, 10) || 30_000;
223
- const init = await transport.request('initialize', {
224
- protocolVersion: PROTOCOL_VERSION,
225
- capabilities: {},
226
- clientInfo: { name: 'claude-pro', version: VERSION },
227
- }, { timeout });
238
+ const init = await handshake(transport);
228
239
  entry.serverInfo = init?.serverInfo;
229
240
  entry.instructions = init?.instructions;
230
- // Over HTTP the notification is a request of its own: tools/list must not overtake it, or a
231
- // server that insists on a finished handshake answers "not initialized".
232
- await transport.notify('notifications/initialized', {});
241
+ const timeout = parseInt(process.env.MCP_TIMEOUT, 10) || 30_000;
233
242
  const tools = [];
234
243
  let cursor;
235
244
  do {
@@ -267,13 +276,41 @@ export class McpManager {
267
276
  : '';
268
277
  }
269
278
 
279
+ // A stdio server that exited (crashed, killed) is started again at the next call of one of its tools, once per
280
+ // exit and at most RESTARTS times in RESTART_WINDOW_MS. Its tools stay listed meanwhile: the tool list is part of
281
+ // the cached request prefix, and they used to fail with "is not running" for the rest of the session.
282
+ revive(name, entry) {
283
+ entry.reviving ??= (async () => {
284
+ const now = Date.now();
285
+ const why = entry.transport.stderr?.trim().split('\n').slice(-3).join(' ') || '';
286
+ entry.restarts = (entry.restarts || []).filter((t) => now - t < RESTART_WINDOW_MS);
287
+ if (entry.restarts.length >= RESTARTS) throw new Error(`MCP server "${name}" exited again; it was restarted ${entry.restarts.length} times in the last 10 minutes and is not started again. ${why}`.trim());
288
+ entry.restarts.push(now);
289
+ const transport = new StdioTransport(name, entry.config, this.cwd);
290
+ try {
291
+ await transport.connect();
292
+ await handshake(transport); // its instructions are not taken again: they are in the system prompt
293
+ } catch (e) {
294
+ transport.close();
295
+ throw new Error(`MCP server "${name}" exited and could not be started again: ${e.message}`);
296
+ }
297
+ entry.transport = transport;
298
+ })().finally(() => { entry.reviving = null; });
299
+ return entry.reviving;
300
+ }
301
+
270
302
  tools() {
271
303
  const out = [];
272
304
  const toolTimeout = parseInt(process.env.MCP_TOOL_TIMEOUT, 10) || 600_000;
305
+ const manager = this;
306
+ const taken = new Set(); // names cut to 64 characters, or sanitized alike (get.user, get_user), must stay distinct
273
307
  for (const [server, entry] of this.clients) {
274
308
  if (entry.status !== 'connected') continue;
275
309
  for (const t of entry.tools) {
276
- const name = `mcp__${sanitize(server)}__${sanitize(t.name)}`.slice(0, 64);
310
+ const base = `mcp__${sanitize(server)}__${sanitize(t.name)}`.slice(0, 64);
311
+ let name = base;
312
+ for (let n = 2; taken.has(name); n++) name = `${base.slice(0, 64 - String(n).length - 1)}_${n}`;
313
+ taken.add(name);
277
314
  out.push({
278
315
  name,
279
316
  mcp: { server, tool: t.name },
@@ -285,6 +322,7 @@ export class McpManager {
285
322
  },
286
323
  label() { return `${server} - ${t.title || t.name} (MCP)`; },
287
324
  async call(input, ctx) {
325
+ if (entry.transport?.closed && !manager.closing) await manager.revive(server, entry);
288
326
  const result = await entry.transport.request('tools/call', { name: t.name, arguments: input }, { timeout: toolTimeout, signal: ctx.signal });
289
327
  return { content: convertContent(result || {}), isError: !!result?.isError };
290
328
  },
@@ -295,10 +333,17 @@ export class McpManager {
295
333
  }
296
334
 
297
335
  status() {
298
- return [...this.clients.entries()].map(([name, e]) => ({ name, status: e.status, tools: e.tools.length, error: e.error, serverInfo: e.serverInfo }));
336
+ return [...this.clients.entries()].map(([name, e]) => ({
337
+ name,
338
+ status: e.status === 'connected' && e.transport?.closed ? 'exited (started again at its next tool call)' : e.status,
339
+ tools: e.tools.length,
340
+ error: e.error,
341
+ serverInfo: e.serverInfo,
342
+ }));
299
343
  }
300
344
 
301
345
  close() {
346
+ this.closing = true;
302
347
  for (const e of this.clients.values()) e.transport?.close();
303
348
  }
304
349
  }