@yanzc/claude-pro 0.7.0 → 0.7.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.
package/src/attach.js CHANGED
@@ -83,6 +83,16 @@ function connect(peer, io) {
83
83
  });
84
84
  }
85
85
 
86
+ // A window the computer service opened for it (--keep-open, see HostService.window): what went wrong, or that the
87
+ // session ended, stays readable until a key is pressed (a window that closes at once says nothing).
88
+ function keepOpen(args, io) {
89
+ if (!args.includes('--keep-open') || !io.stdin.isTTY) return Promise.resolve();
90
+ io.stdout.write('Press any key to close this window.');
91
+ io.stdin.setRawMode(true);
92
+ io.stdin.resume();
93
+ return new Promise((resolve) => io.stdin.once('data', () => { io.stdin.setRawMode(false); io.stdin.pause(); resolve(); }));
94
+ }
95
+
86
96
  // io: the terminal (process.stdin/stdout/stderr; the tests give their own).
87
97
  export async function attachCommand(args = [], io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
88
98
  if (!io.stdin.isTTY || !io.stdout.isTTY) {
@@ -92,12 +102,14 @@ export async function attachCommand(args = [], io = { stdin: process.stdin, stdo
92
102
  const sessions = backgroundSessions();
93
103
  if (!sessions.length) {
94
104
  io.stdout.write('No background session runs on this computer. The web page opens them (新建会话, without "open a terminal window").\n');
105
+ await keepOpen(args, io);
95
106
  return 1;
96
107
  }
97
108
  const ref = args.find((a) => !a.startsWith('-'));
98
109
  let peer = ref ? findBackground(ref, sessions) : sessions.length === 1 ? sessions[0] : await choose(sessions, io);
99
110
  if (!peer) {
100
111
  io.stderr.write(`No background session called "${ref}". These run here: ${sessions.map((p) => `&${p.name}`).join(', ')}\n`);
112
+ await keepOpen(args, io);
101
113
  return 1;
102
114
  }
103
115
  const label = `&${peer.name}`;
@@ -122,11 +134,13 @@ export async function attachCommand(args = [], io = { stdin: process.stdin, stdo
122
134
  io.stdout.write(RESET);
123
135
  io.stdin.setRawMode(false);
124
136
  io.stderr.write(`Could not attach to ${label}: ${e.message}\n`);
137
+ await keepOpen(args, io);
125
138
  return 1;
126
139
  }
127
140
  io.stdout.write(RESET);
128
141
  io.stdin.setRawMode(false);
129
142
  io.stdin.pause();
130
143
  io.stdout.write(how === 'detached' ? `Detached from ${label}: it goes on in the background (claude-pro attach ${peer.name} comes back).\n` : `${label} has ended.\n`);
144
+ if (how !== 'detached') await keepOpen(args, io);
131
145
  return 0;
132
146
  }
package/src/background.js CHANGED
@@ -8,8 +8,11 @@
8
8
  // - otherwise it crashed: opened again with --resume (the same conversation, the same id at the gateway), at most
9
9
  // MAX_CRASHES times in CRASH_WINDOW_MS, then failed (with the end of its log as the error);
10
10
  // - CONFIG_DIR/host-sessions.json keeps the sessions to open again when the service starts (after a reboot, or a
11
- // new version of the service): one still running (the same boot, its supervisor alive) is taken over, the others
12
- // are opened again with --resume. A task that was running is not continued: the conversation is.
11
+ // new version of the service): one still running is taken over, the others are opened again with --resume. A task
12
+ // that was running is not continued: the conversation is.
13
+ // - Whether a session runs is told by the processes themselves (liveSessionProcesses: those started with --headless
14
+ // --remote-id <id>), not by a pid kept from before: a session is never opened while a process of it runs, and
15
+ // copies that should not be there (two supervisors of one id) are ended, the one the service knew kept.
13
16
  //
14
17
  // Each session's output (its log: what it printed, as plain text, and the errors of its processes) goes to
15
18
  // CONFIG_DIR/logs/sessions/<id>.log, cut down to LOG_BYTES (copied to .log.1 first) once a minute.
@@ -19,7 +22,6 @@
19
22
  // (POST /control: exit, restart).
20
23
 
21
24
  import fs from 'node:fs';
22
- import os from 'node:os';
23
25
  import path from 'node:path';
24
26
  import { spawn, spawnSync } from 'node:child_process';
25
27
  import { listPeers, controlPeer } from './peers.js';
@@ -39,8 +41,50 @@ export function pidAlive(pid) {
39
41
  try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
40
42
  }
41
43
 
42
- // When this computer started (ms, to the minute): a pid saved before a reboot means nothing after it.
43
- export const bootTime = () => Math.round((Date.now() - os.uptime() * 1000) / 60_000) * 60_000;
44
+ // The processes of background sessions running now, by their id at the gateway: Map id -> {supervisors, sessions}
45
+ // ([{pid, ppid}] each): the processes started with --headless --remote-id <id> (bin/claude-pro.js runs the
46
+ // supervisor, which runs the session with the same arguments). A supervisor is one whose parent is not one of them;
47
+ // a session without its supervisor (killed) is in `sessions` alone. Read from the system's list of processes.
48
+ export function liveSessionProcesses() {
49
+ let rows = [];
50
+ try {
51
+ if (process.platform === 'win32') {
52
+ const script = [
53
+ '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
54
+ // a tab between the fields: "`t" in a string of double quotes
55
+ "Get-CimInstance Win32_Process -Filter \"CommandLine LIKE '%--headless%'\" | ForEach-Object { \"{0}`t{1}`t{2}\" -f $_.ProcessId, $_.ParentProcessId, $_.CommandLine }",
56
+ ].join('\n');
57
+ const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { windowsHide: true, encoding: 'utf8', timeout: 30_000 });
58
+ rows = String(r.stdout || '').split(/\r?\n/).filter(Boolean).map((l) => { const [pid, ppid, ...rest] = l.split('\t'); return { pid: Number(pid), ppid: Number(ppid), args: rest.join('\t') }; });
59
+ } else if (process.platform === 'linux') {
60
+ for (const d of fs.readdirSync('/proc')) {
61
+ if (!/^\d+$/.test(d)) continue;
62
+ try {
63
+ const args = fs.readFileSync(`/proc/${d}/cmdline`, 'utf8').split('\0').join(' ');
64
+ if (!args.includes('--headless')) continue;
65
+ const stat = fs.readFileSync(`/proc/${d}/stat`, 'utf8');
66
+ rows.push({ pid: Number(d), ppid: Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]), args });
67
+ } catch { /* gone meanwhile */ }
68
+ }
69
+ } else {
70
+ const r = spawnSync('ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8', timeout: 30_000 });
71
+ rows = String(r.stdout || '').split('\n').map((l) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(l)).filter(Boolean).map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), args: m[3] }));
72
+ }
73
+ } catch { /* nothing known: nothing taken for running */ }
74
+ const byId = new Map();
75
+ for (const row of rows) {
76
+ const id = /--remote-id\s+"?([A-Za-z0-9_-]{8,64})/.exec(row.args)?.[1];
77
+ if (!id || !/--headless/.test(row.args) || row.pid === process.pid) continue;
78
+ if (!byId.has(id)) byId.set(id, []);
79
+ byId.get(id).push({ pid: row.pid, ppid: row.ppid });
80
+ }
81
+ const out = new Map();
82
+ for (const [id, list] of byId) {
83
+ const pids = new Set(list.map((p) => p.pid));
84
+ out.set(id, { supervisors: list.filter((p) => !pids.has(p.ppid)), sessions: list.filter((p) => pids.has(p.ppid)) });
85
+ }
86
+ return out;
87
+ }
44
88
 
45
89
  // Where a background session says it ended for good (see App.exit): the service reads and removes it.
46
90
  export const endedMarker = (dir, id) => path.join(dir, 'background-ended', id);
@@ -95,6 +139,7 @@ export class BackgroundSessions {
95
139
  // The sessions saved by the service before: taken over when they still run, opened again when not.
96
140
  start() {
97
141
  let saved = [];
142
+ let live = null; // the processes of the sessions running now, read once
98
143
  try { saved = JSON.parse(fs.readFileSync(this.file, 'utf8')); } catch { /* none */ }
99
144
  for (const s of Array.isArray(saved) ? saved : []) {
100
145
  if (!s || !ID.test(String(s.sessionId || '')) || typeof s.cwd !== 'string') continue;
@@ -102,11 +147,9 @@ export class BackgroundSessions {
102
147
  this.sessions.set(rec.sessionId, rec);
103
148
  if (s.state === 'failed') { rec.state = 'failed'; rec.error = s.error || null; continue; }
104
149
  if (s.suspended) { rec.suspended = true; rec.state = 'exited'; continue; }
105
- if (s.boot === bootTime() && pidAlive(s.pid)) {
106
- rec.pid = s.pid;
107
- rec.state = 'running';
150
+ live ??= liveSessionProcesses();
151
+ if (this.adopt(rec, live.get(rec.sessionId), s.pid)) {
108
152
  rec.startedAt = s.startedAt || null;
109
- this.log(`took over the background session ${rec.sessionId} (pid ${rec.pid}) in ${rec.cwd}`);
110
153
  } else {
111
154
  this.log(`opening the background session ${rec.sessionId} again in ${rec.cwd}`);
112
155
  this.launch(rec, { resume: true });
@@ -144,10 +187,10 @@ export class BackgroundSessions {
144
187
  error: null,
145
188
  restarts: 0,
146
189
  crashes: [],
147
- boot: null,
148
190
  stopping: false,
149
191
  restartFrom: null,
150
192
  suspended: false,
193
+ attached: 0, // terminals attached to it (claude-pro attach, a window the page opened)
151
194
  };
152
195
  }
153
196
 
@@ -163,7 +206,35 @@ export class BackgroundSessions {
163
206
  return { pid: rec.pid };
164
207
  }
165
208
 
209
+ // Take over the session `rec` when processes of it run (`found`: an entry of liveSessionProcesses): its supervisor,
210
+ // the one with pid `prefer` when there are several (the others, copies that should not be there, are ended);
211
+ // without one, the session process itself (its supervisor was killed: it ends one day, and is then opened again).
212
+ // Returns whether there was one to take over.
213
+ adopt(rec, found, prefer = null) {
214
+ const heads = found?.supervisors?.length ? found.supervisors : found?.sessions || [];
215
+ if (!heads.length) return false;
216
+ const keep = heads.find((p) => p.pid === prefer) || heads.find((p) => p.pid === rec.pid) || heads[heads.length - 1];
217
+ for (const p of heads) {
218
+ if (p === keep) continue;
219
+ this.log(`the background session ${rec.sessionId} ran twice: ended the copy with pid ${p.pid}, kept ${keep.pid}`);
220
+ killTree(p.pid);
221
+ }
222
+ rec.pid = keep.pid;
223
+ rec.child = null;
224
+ rec.state = 'running';
225
+ rec.suspended = false;
226
+ this.log(`took over the background session ${rec.sessionId} (pid ${rec.pid}) in ${rec.cwd}`);
227
+ return true;
228
+ }
229
+
230
+ // Start the session's processes; with `resume` (opened again: after a crash, a restart of the service, a login)
231
+ // only when none of them runs (see adopt): opening it again then would make two copies of one session.
166
232
  launch(rec, { resume = false, first = false } = {}) {
233
+ if (resume && this.adopt(rec, liveSessionProcesses().get(rec.sessionId))) {
234
+ this.persist();
235
+ this.onChange();
236
+ return;
237
+ }
167
238
  const args = [this.entry, '--headless', '--remote-id', rec.sessionId];
168
239
  if (resume && rec.conversationId) args.push('--resume', rec.conversationId);
169
240
  if (first && rec.name) args.push('--name', rec.name);
@@ -184,7 +255,6 @@ export class BackgroundSessions {
184
255
  rec.endedAt = null;
185
256
  rec.exitCode = null;
186
257
  rec.error = null;
187
- rec.boot = bootTime();
188
258
  rec.stopping = false;
189
259
  rec.suspended = false;
190
260
  child.on('error', (e) => {
@@ -273,6 +343,9 @@ export class BackgroundSessions {
273
343
  rec.state = 'running';
274
344
  changed = true;
275
345
  }
346
+ // the terminals attached to it (none while it is not in the registry: starting, restarting)
347
+ const attached = Number(p?.attached) || 0;
348
+ if (rec.attached !== attached) { rec.attached = attached; changed = true; }
276
349
  // one taken over from an earlier service has no child process here: its pid tells
277
350
  if (!rec.child && rec.state !== 'restarting' && !pidAlive(rec.pid)) this.gone(rec, null);
278
351
  }
@@ -366,6 +439,22 @@ export class BackgroundSessions {
366
439
  this.onChange();
367
440
  }
368
441
 
442
+ // The conversation `conversationId` deleted: the sessions that are not running and had it (failed, suspended,
443
+ // ended) are forgotten, so that it is not opened again. Returns their logs (they hold its text), to delete too.
444
+ forgetConversation(conversationId) {
445
+ const logs = [];
446
+ for (const rec of [...this.sessions.values()]) {
447
+ if (rec.conversationId !== conversationId || this.alive(rec)) continue;
448
+ this.sessions.delete(rec.sessionId);
449
+ logs.push(this.logFile(rec.sessionId));
450
+ }
451
+ for (const e of this.ended.filter((x) => x.conversationId === conversationId)) logs.push(this.logFile(e.sessionId));
452
+ this.ended = this.ended.filter((x) => x.conversationId !== conversationId);
453
+ this.persist();
454
+ this.onChange();
455
+ return logs.flatMap((f) => [f, `${f}.1`]);
456
+ }
457
+
369
458
  // The conversation `conversationId` already open in a session of this computer (a background one, or a terminal):
370
459
  // its entry in the registry.
371
460
  openConversation(conversationId) {
@@ -398,6 +487,7 @@ export class BackgroundSessions {
398
487
  exitCode: rec.exitCode,
399
488
  error: rec.error,
400
489
  restarts: rec.restarts,
490
+ attached: rec.attached || 0,
401
491
  };
402
492
  }
403
493
 
@@ -409,7 +499,7 @@ export class BackgroundSessions {
409
499
  persist() {
410
500
  const list = [...this.sessions.values()].map((r) => ({
411
501
  sessionId: r.sessionId, cwd: r.cwd, name: r.name, conversationId: r.conversationId, model: r.model,
412
- pid: r.pid, boot: r.boot, startedAt: r.startedAt, state: r.state === 'failed' ? 'failed' : undefined, error: r.state === 'failed' ? r.error : undefined,
502
+ pid: r.pid, startedAt: r.startedAt, state: r.state === 'failed' ? 'failed' : undefined, error: r.state === 'failed' ? r.error : undefined,
413
503
  suspended: r.suspended || undefined,
414
504
  }));
415
505
  try {
@@ -15,7 +15,8 @@ export class CheckpointStore {
15
15
  // dir: where snapshot files are kept (created lazily).
16
16
  constructor(dir) {
17
17
  this.dir = dir;
18
- // {id, label, time, messageIndex, conversationValid, orphaned, files: [{path, existed, snap, skipped}]}
18
+ // {id, label, time, messageIndex, conversation, conversationValid, orphaned, files: [{path, existed, snap, skipped}]}
19
+ // (conversation: the id of the conversation it belongs to, so that deleting the conversation finds it)
19
20
  this.entries = [];
20
21
  this.counter = 0;
21
22
  this.current = null;
@@ -23,12 +24,13 @@ export class CheckpointStore {
23
24
 
24
25
  // Start a checkpoint for a new user prompt. messageIndex is where its message will sit in
25
26
  // the conversation, so rewinding the conversation can cut it off there.
26
- beginTurn({ label, messageIndex }) {
27
+ beginTurn({ label, messageIndex, conversation = null }) {
27
28
  const entry = {
28
29
  id: ++this.counter,
29
30
  label: String(label || '').replace(/\s+/g, ' ').trim().slice(0, 200),
30
31
  time: Date.now(),
31
32
  messageIndex,
33
+ conversation,
32
34
  conversationValid: true,
33
35
  orphaned: false,
34
36
  files: [],
@@ -14,10 +14,10 @@ let installedVersion;
14
14
  function readJson(file, label) {
15
15
  let text;
16
16
  try { text = fs.readFileSync(file, 'utf8'); }
17
- catch { throw new Error(`Could not read existing Claude Code ${label}: ${file}. Select the existing login with CLAUDE_PRO_CLAUDE_CONFIG_FILE / CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE.`); }
17
+ catch { throw new Error(`Could not read the Claude subscription ${label}: ${file}. Select the existing login with CLAUDE_PRO_CLAUDE_CONFIG_FILE / CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE.`); }
18
18
  // JSON.parse errors can contain an excerpt of the token. Never echo them.
19
19
  try { return JSON.parse(text.replace(/^\uFEFF/, '')); }
20
- catch { throw new Error(`Invalid JSON in Claude Code ${label}: ${file}.`); }
20
+ catch { throw new Error(`Invalid JSON in the Claude subscription ${label}: ${file}.`); }
21
21
  }
22
22
 
23
23
  function clientVersion(config, metadata) {
@@ -37,10 +37,10 @@ export function readClaudeCodeLogin(config) {
37
37
  const credentials = readJson(config.claudeCodeCredentialsFile, 'credentials');
38
38
  const oauth = credentials?.claudeAiOauth;
39
39
  if (!oauth || typeof oauth.accessToken !== 'string' || !oauth.accessToken.trim()) {
40
- throw new Error(`No existing Claude Code subscription access token in ${config.claudeCodeCredentialsFile}. The .claude.json file contains account metadata; the token is in .claude/.credentials.json.`);
40
+ throw new Error(`No Claude subscription access token in ${config.claudeCodeCredentialsFile}. The .claude.json file contains account metadata; the token is in .claude/.credentials.json.`);
41
41
  }
42
42
  if (oauth.expiresAt && Number(oauth.expiresAt) <= Date.now()) {
43
- throw new Error('The existing Claude Code access token has expired and cannot be renewed from here (the credentials file has no refresh token, or CLAUDE_PRO_DISABLE_TOKEN_REFRESH is set). Run `claude` and use /login to sign in again; this project will read the updated file automatically.');
43
+ throw new Error('The Claude subscription access token has expired and cannot be renewed from here (the credentials file has no refresh token, or CLAUDE_PRO_DISABLE_TOKEN_REFRESH is set). Run `claude` and use /login to sign in again; this project will read the updated file automatically.');
44
44
  }
45
45
  if (!sessionIds.has(config)) sessionIds.set(config, crypto.randomUUID());
46
46
  return {
package/src/commands.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import { c, padEnd, truncate, colorEnabled } from './ui/ansi.js';
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
8
  import { loadConfig, settingsFiles, updateSettingsFile, rememberChoice, applyRememberedChoices, KNOWN_KEYS, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
@@ -22,7 +22,6 @@ import { cleanName, machineName } from './peers.js';
22
22
  import { rewind, promptAt } from './checkpoints.js';
23
23
  import { canRestart, runSelfCheck } from './restart.js';
24
24
  import { describeHost, normalizeDir } from './host.js';
25
- import { qrLines } from './qr.js';
26
25
 
27
26
  const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
28
27
  const isGpt = (modelId) => /^gpt-/i.test(modelId);
@@ -136,7 +135,7 @@ export function buildCommands(app) {
136
135
  description: 'Show help and available commands',
137
136
  run() {
138
137
  const lines = [
139
- c.bold(`${APP_NAME} v${VERSION}`) + c.dim(' — a Claude Code style coding agent'),
138
+ c.bold(`${APP_NAME} v${VERSION}`) + c.dim(' — a command line coding agent'),
140
139
  '',
141
140
  'Always review the agent\'s changes before committing them.',
142
141
  '',
@@ -279,7 +278,7 @@ export function buildCommands(app) {
279
278
  if (v === undefined) continue;
280
279
  lines.push(`${padEnd(k, 34)} ${c.bold(v)} ${c.dim(cfg.sources[k] || '')}`);
281
280
  }
282
- if (cfg.ignoredFromDotEnv.length) lines.push('', c.dim(`Not applied from .env with the claude-code provider (it is the API provider's setup; Claude Code's defaults are used instead): ${cfg.ignoredFromDotEnv.join(', ')}. Set them with /config set or /effort to apply them here.`));
281
+ if (cfg.ignoredFromDotEnv.length) lines.push('', c.dim(`Not applied from .env with the claude-code provider (it is the API provider's setup; the subscription's defaults are used instead): ${cfg.ignoredFromDotEnv.join(', ')}. Set them with /config set or /effort to apply them here.`));
283
282
  lines.push('', c.dim('Other keys: ' + Object.keys(KNOWN_KEYS).filter((k) => cfg.env[k] === undefined).join(', ')));
284
283
  lines.push('', `${c.dim('Change with')} /config set KEY VALUE [--project|--local] ${c.dim('or edit')} ${settingsFiles(app.cwd).user}`);
285
284
  log(lines, '');
@@ -375,8 +374,8 @@ export function buildCommands(app) {
375
374
  const remote = await app.syncRemote();
376
375
  app.ensureHost({ login: true });
377
376
  if (!remote) return;
378
- out(remote.url
379
- ? `${c.green('⇄')} This session is online at the gateway: ${c.blue(remote.url)} ${c.dim('(/status shows it, with a QR code for a phone)')}`
377
+ out(remote.registered
378
+ ? `${c.green('⇄')} This session is online at the gateway: the web page (远程控制) shows it.`
380
379
  : c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
381
380
  };
382
381
 
@@ -396,7 +395,7 @@ export function buildCommands(app) {
396
395
  question: `Now: ${c.bold(cfg.provider)} (${cfg.endpointLabel})`,
397
396
  options: [
398
397
  { label: `Gateway ${cfg.gatewayUrl} ${c.dim(saved ? `(logged in as ${saved.account?.email || 'this machine'}; paid from the account balance)` : '(log in in the browser; paid from the account balance)')}`, value: 'gateway' },
399
- { label: `Claude subscription ${c.dim('(the local Claude Code login)')}`, value: 'claude-code' },
398
+ { label: `Claude subscription ${c.dim('(the login of the claude command on this computer)')}`, value: 'claude-code' },
400
399
  { label: `Codex subscription ${c.dim(codex.ok ? `(the local Codex login${codex.plan ? `, ${codex.plan}` : ''})` : '(run `codex login` first)')}`, value: 'codex' },
401
400
  ],
402
401
  }));
@@ -479,7 +478,6 @@ export function buildCommands(app) {
479
478
  description: 'Show version, model, API endpoint and session info',
480
479
  run() {
481
480
  const cfg = app.runtime.config;
482
- const modes = app.runtime.modes;
483
481
  const mem = memoryFiles(app.cwd);
484
482
  const mcp = app.runtime.mcp.status();
485
483
  const row = (k, v) => `${c.dim(padEnd(k, 18))} ${v}`;
@@ -490,7 +488,7 @@ export function buildCommands(app) {
490
488
  row('cwd', app.cwd),
491
489
  row('Provider', cfg.provider),
492
490
  row('Endpoint', cfg.endpointLabel),
493
- row('Auth', cfg.usesClaudeCode ? `existing Claude Code OAuth (${cfg.claudeCodeCredentialsFile})`
491
+ row('Auth', cfg.usesClaudeCode ? `Claude subscription (${cfg.claudeCodeCredentialsFile})`
494
492
  : cfg.usesGateway ? (readGatewayLogin(cfg.gatewayUrl) ? `gateway key of ${readGatewayLogin(cfg.gatewayUrl).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)'))
495
493
  : cfg.usesCodex ? (() => { const s = codexLoginSummary({ ...process.env, ...cfg.env }); return s.ok ? `Codex login${s.email ? ` of ${s.email}` : ''}${s.plan ? ` (${s.plan})` : ''} ${c.dim(s.file)}` : c.red(s.error); })()
496
494
  : cfg.authToken ? `ANTHROPIC_AUTH_TOKEN (${cfg.display('ANTHROPIC_AUTH_TOKEN')})` : cfg.apiKey ? `ANTHROPIC_API_KEY (${cfg.display('ANTHROPIC_API_KEY')})` : c.red('none')),
@@ -501,7 +499,7 @@ export function buildCommands(app) {
501
499
  row('Max output', formatTokens(cfg.maxOutputTokens)),
502
500
  row('Prompt cache', cfg.promptCachingDisabled(cfg.mainModel.id) ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.mainModel.id).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.mainModel.id).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
503
501
  row('Auto-compact', cfg.autoCompactEnabled ? `at ${formatTokens(cfg.autoCompactThreshold())} tokens (window ${formatTokens(cfg.compactWindow())})` : 'disabled'),
504
- row('Mode', modes.mode === 'plan' ? 'plan (read-only; shift+tab to leave)' : 'full access (no permission prompts)'),
502
+ row('Access', 'full (no permission prompts)'),
505
503
  row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
506
504
  row('Shell', `${app.runtime.shell.name} ${c.dim(app.runtime.shell.path)}`),
507
505
  row('ripgrep', hasRipgrep(cfg) ? 'yes' : 'no (using JS fallback)'),
@@ -513,7 +511,7 @@ export function buildCommands(app) {
513
511
  },
514
512
  });
515
513
 
516
- // /status about the gateway: this session there (its page, and a QR code of it for a phone), its name for the
514
+ // /status about the gateway: whether this session is online there, its name for the
517
515
  // sessions on the other computers, and the computer service.
518
516
  function remoteLines(row) {
519
517
  const cfg = app.runtime.config;
@@ -521,15 +519,9 @@ export function buildCommands(app) {
521
519
  const me = app.peerLabel();
522
520
  const lines = [
523
521
  row('Remote control', remote.text),
524
- ...(remote.url ? [row('', c.blue(remote.url))] : []),
525
522
  row('Name', `&${me} ${c.dim(`(on your other computers: &${machineName(cfg.env)}/${me}; /rename changes it)`)}`),
526
523
  row('Computer service', describeHost(cfg.env)),
527
524
  ];
528
- const qr = remote.url && app.remote?.online ? qrLines(remote.url, { color: colorEnabled }) : null;
529
- if (qr) {
530
- lines.push('', c.dim(' Scan with a phone to open this session (log in to the gateway there):'), ...qr.map((l) => ` ${l}`));
531
- lines.push(c.dim(` Whoever can log in to this gateway account, or holds one of its API keys, can run anything on this computer through it.`));
532
- }
533
525
  return lines;
534
526
  }
535
527
 
@@ -723,17 +715,6 @@ export function buildCommands(app) {
723
715
  },
724
716
  });
725
717
 
726
- add({
727
- name: 'plan',
728
- description: 'Toggle read-only plan mode (same as shift+tab)',
729
- run() {
730
- const mode = app.runtime.modes.toggle();
731
- out(mode === 'plan'
732
- ? [`${c.plan('Plan mode on')}: the agent can only read and research, then proposes a plan with ExitPlanMode.`, c.dim('Run /plan or press shift+tab to leave it.')]
733
- : `Plan mode off: ${c.bold('full access')}, tools run immediately.`);
734
- },
735
- });
736
-
737
718
  add({
738
719
  name: 'rewind',
739
720
  aliases: ['checkpoint'],
@@ -936,7 +917,7 @@ export function buildCommands(app) {
936
917
  `${app.runtime.shell.kind === 'bash' ? c.green('✔') : c.yellow('!')} Shell: ${app.runtime.shell.name} (${app.runtime.shell.path})`,
937
918
  `${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)'}`,
938
919
  cfg.usesClaudeCode
939
- ? `${c.yellow('!')} Existing Claude Code OAuth: ${cfg.claudeCodeCredentialsFile} (checked by the request below)`
920
+ ? `${c.yellow('!')} Claude subscription: ${cfg.claudeCodeCredentialsFile} (checked by the request below)`
940
921
  : cfg.usesGateway ? `${readGatewayLogin(cfg.gatewayUrl) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${readGatewayLogin(cfg.gatewayUrl) ? '' : ' missing (/login)'}`
941
922
  : cfg.usesCodex ? (() => { const s = codexLoginSummary({ ...process.env, ...cfg.env }); return `${s.ok ? c.green('✔') : c.red('✘')} Codex login ${s.ok ? s.file : s.error}`; })()
942
923
  : `${cfg.authToken || cfg.apiKey ? c.green('✔') : c.red('✘')} Credentials ${cfg.authToken ? 'ANTHROPIC_AUTH_TOKEN' : cfg.apiKey ? 'ANTHROPIC_API_KEY' : 'missing'}`,
package/src/config.js CHANGED
@@ -35,20 +35,18 @@ export const KNOWN_KEYS = {
35
35
  CLAUDE_PRO_GATEWAY_URL: `codex-gateway address for the gateway provider (default https://gw.predix.icu)`,
36
36
  CLAUDE_PRO_GATEWAY_MODEL: 'Model with the gateway provider (default: opus; also sonnet, haiku, gpt-6.1-sol)',
37
37
  CLAUDE_PRO_CODEX_MODEL: 'Model with the codex provider (default: the model in ~/.codex/config.toml, else gpt-6.1-sol)',
38
- CLAUDE_PRO_CLAUDE_CONFIG_FILE: 'Existing Claude Code account metadata file (default: ~/.claude.json)',
39
- CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE: 'Existing Claude Code OAuth credentials file (default: ~/.claude/.credentials.json)',
40
- CLAUDE_PRO_CLAUDE_CODE_VERSION: 'Claude Code version in the HTTP User-Agent (default: installed npm version)',
41
- CLAUDE_PRO_DISABLE_TOKEN_REFRESH: 'Set to 1 to stop this program renewing the Claude Code login by itself (it then only reads what the official client keeps up to date)',
38
+ CLAUDE_PRO_CLAUDE_CONFIG_FILE: 'Claude subscription: the account metadata file of the claude command (default: ~/.claude.json)',
39
+ CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE: 'Claude subscription: the credentials file of the claude command (default: ~/.claude/.credentials.json)',
40
+ CLAUDE_PRO_CLAUDE_CODE_VERSION: 'Claude subscription: the claude command version sent in the User-Agent (default: the installed one)',
41
+ CLAUDE_PRO_DISABLE_TOKEN_REFRESH: 'Set to 1 to stop this program renewing the Claude subscription login by itself (it then only reads what the official client keeps up to date)',
42
42
  CLAUDE_PRO_ONLINE: 'Internal (the self-check and the tests set it): 0 keeps interactive sessions off the gateway. Otherwise a session is online there whenever this computer is logged in to the gateway: its 远程控制 page shows it, and sessions on your other computers can send it tasks (&computer/name)',
43
43
  CLAUDE_PRO_HOST: 'Set to 0 so that sessions do not start the computer service (claude-pro host) by themselves; the service lets the gateway\'s 远程控制 page open new sessions on this computer',
44
44
  CLAUDE_PRO_DOWNLOAD_DIR: 'Where files that other sessions send this one are saved (default: the Downloads folder)',
45
45
  CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
46
- CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside, like Claude Code\'s /tui fullscreen) or default (classic: it scrolls in the terminal); /tui switches',
47
- CLAUDE_PRO_SCROLL_SPEED: 'Fullscreen: rows the mouse wheel scrolls a notch (default 3, at most 20)',
48
- CLAUDE_PRO_PIN_INPUT: 'Set to 0 to show the input box right below the output instead of on the last rows of the window',
46
+ CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside) or default (classic: it scrolls in the terminal); /tui switches',
49
47
  CLAUDE_PRO_AUTO_RESTART: 'Restart by itself when a turn ends and claude-pro\'s own source files changed (default 1; 0 = only on /restart or the Restart tool)',
50
- CLAUDE_PRO_CLAUDE_CODE_MODEL: 'Model for Claude Code OAuth (default: sonnet; independent of API model settings)',
51
- CLAUDE_CONFIG_DIR: 'Official Claude Code configuration directory, for selecting the locally signed-in account',
48
+ CLAUDE_PRO_CLAUDE_CODE_MODEL: 'Model with the Claude subscription (default: sonnet; independent of API model settings)',
49
+ CLAUDE_CONFIG_DIR: 'Configuration directory of the claude command, for selecting its signed-in account (Claude subscription)',
52
50
  ANTHROPIC_BASE_URL: 'API base URL (Anthropic compatible endpoint)',
53
51
  ANTHROPIC_AUTH_TOKEN: 'Bearer token sent as Authorization header',
54
52
  ANTHROPIC_API_KEY: 'API key sent as x-api-key header (used if no auth token)',
@@ -66,7 +64,7 @@ export const KNOWN_KEYS = {
66
64
  DISABLE_AUTOCOMPACT: 'Set to 1 to disable auto-compaction',
67
65
  CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default 128000, 48000 with the gateway; lowered automatically if the API allows less)',
68
66
  MAX_THINKING_TOKENS: 'Thinking budget: 0 disables thinking, N enables with budget N',
69
- CLAUDE_CODE_PROMPT_CACHE_TTL: 'Prompt cache TTL of the conversation itself: 5m or 1h (default: 1h with the subscription login, as in Claude Code, and with the gateway, else 5m; 1h writes cost more, they pay off when you pause for more than 5 minutes). Also the promptCacheTtl setting',
67
+ CLAUDE_CODE_PROMPT_CACHE_TTL: 'Prompt cache TTL of the conversation itself: 5m or 1h (default: 1h with the subscription login and with the gateway, else 5m; 1h writes cost more, they pay off when you pause for more than 5 minutes). Also the promptCacheTtl setting',
70
68
  CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 'Prompt cache TTL of everything else (sub-agents, compaction, side queries): 5m (default) or 1h. Also the subagentPromptCacheTtl setting',
71
69
  ENABLE_PROMPT_CACHING_1H: 'Set to 1 to request the 1-hour TTL for both (the two TTL variables above win over it)',
72
70
  FORCE_PROMPT_CACHING_5M: 'Set to 1 to force the 5-minute TTL for both, over every other TTL setting',
@@ -78,7 +76,6 @@ export const KNOWN_KEYS = {
78
76
  API_TIMEOUT_MS: 'Request timeout in milliseconds',
79
77
  CLAUDE_PRO_MAX_RETRIES: 'Retries for failed API requests (0 = no retries at all, which also turns off the rate limit wait)',
80
78
  CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS: 'Longest total time to wait for a rate limit (e.g. the 5-hour window) to reset before continuing by itself (default 21600000 = 6 hours; 0 = report the error instead of waiting)',
81
- CLAUDE_PRO_RATE_LIMIT_POLL_MS: 'When a rate limit does not say when it resets, try again at most this far apart (default 300000 = 5 minutes)',
82
79
  CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS: 'First wait before retrying a request refused as overloaded (529); doubled at each retry (default 1000)',
83
80
  CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS: 'Longest wait between retries of an overloaded (529) request (default 32000)',
84
81
  CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS: 'How long to keep retrying an overloaded (529) API once the usual retries are used up, before reporting the error (default: CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS, 6 hours; 0 = give up after the retries)',
@@ -87,11 +84,7 @@ export const KNOWN_KEYS = {
87
84
  BASH_MAX_OUTPUT_LENGTH: 'Max characters of Bash output returned to the model; the full text is saved to a file (default 60000)',
88
85
  CLAUDE_CODE_GIT_BASH_PATH: 'Windows: path to bash.exe (Git Bash)',
89
86
  CLAUDE_PRO_RIPGREP_PATH: 'Path to ripgrep (rg) for Grep and @-file suggestions; "off" forces the built-in JS scanner (default: rg from PATH, else the JS scanner)',
90
- CLAUDE_PRO_MAX_TOOL_RESULT_CHARS: 'Tool results longer than this are saved to a file and only a preview is sent (default 100000)',
91
- CLAUDE_PRO_CLEAR_AFTER_IDLE: 'Back after more than 65 minutes away (the prompt cache has expired): clear old tool results and thinking, keeping the last 5 results, as Claude Code does. 1 = on, 0 = off (default: on for the Claude Code login and api.anthropic.com, off for other endpoints, whose cache may last for hours)',
92
- CLAUDE_PRO_MAX_SUBAGENT_DEPTH: 'How deep sub-agents may nest: agents below this depth can start their own sub-agents (default 2; 0 = no nesting)',
93
87
  CLAUDE_PRO_VERIFY_COMMAND: 'Command run after the agent edits files (e.g. "npm test"); failures are sent back to fix',
94
- CLAUDE_PRO_VERIFY_MAX_ROUNDS: 'How many times a failing verify command is sent back before giving up (default 3)',
95
88
  CLAUDE_PRO_DISABLE_AUTO_MEMORY: 'Set to 1 to turn off the persistent per-project memory',
96
89
  CLAUDE_PRO_DISABLE_TOPIC_TITLE: 'Set to 1 to stop asking the small model for the current topic after each message (the tab title then shows the first message of the session)',
97
90
  };
@@ -248,7 +241,7 @@ export class Config {
248
241
  this.env.CLAUDE_CONFIG_DIR || path.join(path.dirname(this.claudeCodeConfigFile), '.claude'), '.credentials.json'));
249
242
  }
250
243
  get endpointLabel() {
251
- if (this.usesClaudeCode) return 'https://api.anthropic.com (Claude Code OAuth)';
244
+ if (this.usesClaudeCode) return 'https://api.anthropic.com (Claude subscription)';
252
245
  if (this.usesGateway) return `${this.gatewayUrl} (codex-gateway)`;
253
246
  if (this.usesCodex) return 'https://chatgpt.com/backend-api/codex (Codex login)';
254
247
  return this.baseURL;
@@ -373,7 +366,8 @@ export class Config {
373
366
  get apiTimeout() { return int(this.env.API_TIMEOUT_MS, 600_000); }
374
367
  get maxRetries() { return int(this.env.CLAUDE_PRO_MAX_RETRIES, 6); }
375
368
  get rateLimitMaxWait() { return Math.max(0, int(this.env.CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS, 6 * 3_600_000)); }
376
- get rateLimitPoll() { return Math.max(1000, int(this.env.CLAUDE_PRO_RATE_LIMIT_POLL_MS, 300_000)); }
369
+ // A rate limit that does not say when it resets is tried again at most this far apart.
370
+ get rateLimitPoll() { return 300_000; }
377
371
  // An overloaded API (529): the backoff, and how long to keep trying once the retries are used up (see planRetry).
378
372
  get overloadedRetryBaseDelay() { return Math.max(100, int(this.env.CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS, 1000)); }
379
373
  get overloadedRetryMaxDelay() { return Math.max(this.overloadedRetryBaseDelay, int(this.env.CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS, 32_000)); }
@@ -398,23 +392,23 @@ export class Config {
398
392
  get bashDefaultTimeout() { return int(this.env.BASH_DEFAULT_TIMEOUT_MS, 600_000); }
399
393
  get bashMaxTimeout() { return int(this.env.BASH_MAX_TIMEOUT_MS, 3_600_000); }
400
394
  get bashMaxOutput() { return int(this.env.BASH_MAX_OUTPUT_LENGTH, 60_000); }
401
- get maxToolResultChars() { return int(this.env.CLAUDE_PRO_MAX_TOOL_RESULT_CHARS, 100_000); }
395
+ // Tool results longer than this are saved to a file and only a preview is sent.
396
+ get maxToolResultChars() { return 100_000; }
402
397
  // Clearing old tool results after a long pause (see Agent.clearAfterIdle): on where the cache is Anthropic's,
403
398
  // which has expired by then. Another endpoint may keep its cache for hours, and clearing would make it miss.
404
399
  get clearAfterIdle() {
405
- const v = String(this.env.CLAUDE_PRO_CLEAR_AFTER_IDLE ?? '').trim();
406
- if (v) return isOn(v);
407
400
  return this.usesClaudeCode || this.usesGateway || /^https:\/\/api\.anthropic\.com\/?$/i.test(this.baseURL);
408
401
  }
409
402
  // How deep sub-agents may nest: the main agent is depth 0; an agent below this depth gets the Task tool.
410
- get maxSubagentDepth() { return Math.max(0, int(this.env.CLAUDE_PRO_MAX_SUBAGENT_DEPTH, 2)); }
403
+ get maxSubagentDepth() { return 2; }
411
404
 
412
405
  // Verification after edits: session override (/verify, --verify) wins over the env setting.
413
406
  get verifyCommand() {
414
407
  const v = this.verifyOverride ?? this.env.CLAUDE_PRO_VERIFY_COMMAND ?? '';
415
408
  return v.trim() && v.trim() !== 'off' ? v.trim() : null;
416
409
  }
417
- get verifyMaxRounds() { return Math.max(1, int(this.env.CLAUDE_PRO_VERIFY_MAX_ROUNDS, 3)); }
410
+ // How many times a failing verify command is sent back before giving up.
411
+ get verifyMaxRounds() { return 3; }
418
412
  get autoMemoryEnabled() { return !/^(1|true|yes)$/i.test(this.env.CLAUDE_PRO_DISABLE_AUTO_MEMORY || ''); }
419
413
 
420
414
  display(key) {
package/src/history.js CHANGED
@@ -92,3 +92,72 @@ export function listConversations({ projects, query = '', cwd = null, limit = 50
92
92
  }
93
93
  return { items, more };
94
94
  }
95
+
96
+ // A conversation's id as it may be used in a path: what SessionStore makes (a UUID), letters, digits, - and _ in
97
+ // any case. Anything else (a dot, a slash: "../x") is refused before it gets near a path.
98
+ export const CONVERSATION_ID = /^[A-Za-z0-9_-]{8,64}$/;
99
+
100
+ // Delete what this computer keeps of the conversation `id` (the web page's "delete"): its session file (in every
101
+ // project it is in: /cd moves it), the tool results saved for it (the outputs too long for the conversation, named
102
+ // after its tool calls or referred to by path in it) and its checkpoints (the file snapshots of /rewind, tagged
103
+ // with the conversation they belong to). What belongs to the project stays: its memory, CLAUDE.md, the input
104
+ // history, the checkpoints of other conversations. `extra`: more files to delete (a background session's log).
105
+ // Returns {files, bytes}; throws when there is no such conversation.
106
+ export function deleteConversation({ projects, id, extra = [] }) {
107
+ if (!CONVERSATION_ID.test(String(id || ''))) throw new Error('对话 id 不对');
108
+ let dirs = [];
109
+ try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(projects, d.name)); } catch { /* none */ }
110
+ const sessionFiles = dirs.map((d) => path.join(d, `${id}.jsonl`)).filter((f) => fs.existsSync(f));
111
+ if (!sessionFiles.length) throw new Error('这台电脑上没有这段对话');
112
+ // the tool results it saved: <tool call id>.txt (persistLargeOutput) and bash-<time>-<random>.txt (the Bash tool)
113
+ const names = new Set();
114
+ for (const file of sessionFiles) {
115
+ let text = '';
116
+ try { text = fs.readFileSync(file, 'utf8'); } catch { continue; }
117
+ for (const m of text.matchAll(/"(?:tool_use_id|id)":"([^"]{1,200})"/g)) names.add(`${m[1].replace(/[^\w-]/g, '_')}.txt`);
118
+ for (const m of text.matchAll(/bash-\d+-[a-z0-9]+\.txt/g)) names.add(m[0]);
119
+ }
120
+ const doomed = [...sessionFiles, ...extra];
121
+ const rewrites = []; // checkpoint indexes that keep other conversations' entries
122
+ for (const dir of dirs) {
123
+ const results = path.join(dir, 'tool-results');
124
+ for (const name of names) {
125
+ const f = path.join(results, name);
126
+ if (fs.existsSync(f)) doomed.push(f);
127
+ }
128
+ let runs = [];
129
+ try { runs = fs.readdirSync(path.join(dir, 'checkpoints')); } catch { continue; }
130
+ for (const run of runs) {
131
+ const runDir = path.join(dir, 'checkpoints', run);
132
+ let entries;
133
+ try { entries = JSON.parse(fs.readFileSync(path.join(runDir, 'index.json'), 'utf8')); } catch { continue; }
134
+ if (!Array.isArray(entries) || !entries.some((e) => e?.conversation === id)) continue;
135
+ const kept = entries.filter((e) => e?.conversation !== id);
136
+ for (const e of entries) {
137
+ if (e?.conversation !== id) continue;
138
+ for (const f of e.files || []) if (f?.snap && /^[\w-]+$/.test(f.snap)) doomed.push(path.join(runDir, f.snap));
139
+ }
140
+ if (kept.length) rewrites.push({ file: path.join(runDir, 'index.json'), entries: kept });
141
+ else doomed.push(path.join(runDir, 'index.json'), runDir);
142
+ }
143
+ }
144
+ let files = 0;
145
+ let bytes = 0;
146
+ const failed = [];
147
+ for (const f of doomed) {
148
+ try {
149
+ const st = fs.statSync(f);
150
+ if (st.isDirectory()) { fs.rmSync(f, { recursive: true, force: true }); continue; }
151
+ fs.rmSync(f);
152
+ files++;
153
+ bytes += st.size;
154
+ } catch (e) {
155
+ if (e.code !== 'ENOENT') failed.push(`${path.basename(f)}: ${e.code || e.message}`);
156
+ }
157
+ }
158
+ for (const r of rewrites) {
159
+ try { fs.writeFileSync(r.file, JSON.stringify(r.entries, null, 1)); } catch (e) { failed.push(`${r.file}: ${e.code || e.message}`); }
160
+ }
161
+ if (sessionFiles.some((f) => fs.existsSync(f))) throw new Error(`删除失败:${failed.join(';') || '会话文件还在'}`);
162
+ return { files, bytes, ...(failed.length ? { failed } : {}) };
163
+ }