@yanzc/claude-pro 0.7.1 → 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/.env.example +4 -6
- package/README.md +47 -88
- package/package.json +2 -2
- package/src/agent.js +1 -1
- package/src/api.js +1 -1
- package/src/attach.js +14 -0
- package/src/background.js +102 -12
- package/src/checkpoints.js +4 -2
- package/src/claude-code.js +4 -4
- package/src/commands.js +5 -5
- package/src/config.js +16 -22
- package/src/history.js +69 -0
- package/src/host.js +63 -9
- package/src/main.js +1 -1
- package/src/oauth.js +3 -3
- package/src/prompts.js +1 -4
- package/src/ratelimit.js +2 -2
- package/src/ui/repl.js +21 -13
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
|
|
12
|
-
//
|
|
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
|
-
//
|
|
43
|
-
|
|
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
|
-
|
|
106
|
-
|
|
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,
|
|
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 {
|
package/src/checkpoints.js
CHANGED
|
@@ -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: [],
|
package/src/claude-code.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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
|
@@ -135,7 +135,7 @@ export function buildCommands(app) {
|
|
|
135
135
|
description: 'Show help and available commands',
|
|
136
136
|
run() {
|
|
137
137
|
const lines = [
|
|
138
|
-
c.bold(`${APP_NAME} v${VERSION}`) + c.dim(' — a
|
|
138
|
+
c.bold(`${APP_NAME} v${VERSION}`) + c.dim(' — a command line coding agent'),
|
|
139
139
|
'',
|
|
140
140
|
'Always review the agent\'s changes before committing them.',
|
|
141
141
|
'',
|
|
@@ -278,7 +278,7 @@ export function buildCommands(app) {
|
|
|
278
278
|
if (v === undefined) continue;
|
|
279
279
|
lines.push(`${padEnd(k, 34)} ${c.bold(v)} ${c.dim(cfg.sources[k] || '')}`);
|
|
280
280
|
}
|
|
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;
|
|
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.`));
|
|
282
282
|
lines.push('', c.dim('Other keys: ' + Object.keys(KNOWN_KEYS).filter((k) => cfg.env[k] === undefined).join(', ')));
|
|
283
283
|
lines.push('', `${c.dim('Change with')} /config set KEY VALUE [--project|--local] ${c.dim('or edit')} ${settingsFiles(app.cwd).user}`);
|
|
284
284
|
log(lines, '');
|
|
@@ -395,7 +395,7 @@ export function buildCommands(app) {
|
|
|
395
395
|
question: `Now: ${c.bold(cfg.provider)} (${cfg.endpointLabel})`,
|
|
396
396
|
options: [
|
|
397
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' },
|
|
398
|
-
{ label: `Claude subscription ${c.dim('(the
|
|
398
|
+
{ label: `Claude subscription ${c.dim('(the login of the claude command on this computer)')}`, value: 'claude-code' },
|
|
399
399
|
{ label: `Codex subscription ${c.dim(codex.ok ? `(the local Codex login${codex.plan ? `, ${codex.plan}` : ''})` : '(run `codex login` first)')}`, value: 'codex' },
|
|
400
400
|
],
|
|
401
401
|
}));
|
|
@@ -488,7 +488,7 @@ export function buildCommands(app) {
|
|
|
488
488
|
row('cwd', app.cwd),
|
|
489
489
|
row('Provider', cfg.provider),
|
|
490
490
|
row('Endpoint', cfg.endpointLabel),
|
|
491
|
-
row('Auth', cfg.usesClaudeCode ? `
|
|
491
|
+
row('Auth', cfg.usesClaudeCode ? `Claude subscription (${cfg.claudeCodeCredentialsFile})`
|
|
492
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)'))
|
|
493
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); })()
|
|
494
494
|
: cfg.authToken ? `ANTHROPIC_AUTH_TOKEN (${cfg.display('ANTHROPIC_AUTH_TOKEN')})` : cfg.apiKey ? `ANTHROPIC_API_KEY (${cfg.display('ANTHROPIC_API_KEY')})` : c.red('none')),
|
|
@@ -917,7 +917,7 @@ export function buildCommands(app) {
|
|
|
917
917
|
`${app.runtime.shell.kind === 'bash' ? c.green('✔') : c.yellow('!')} Shell: ${app.runtime.shell.name} (${app.runtime.shell.path})`,
|
|
918
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)'}`,
|
|
919
919
|
cfg.usesClaudeCode
|
|
920
|
-
? `${c.yellow('!')}
|
|
920
|
+
? `${c.yellow('!')} Claude subscription: ${cfg.claudeCodeCredentialsFile} (checked by the request below)`
|
|
921
921
|
: cfg.usesGateway ? `${readGatewayLogin(cfg.gatewayUrl) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${readGatewayLogin(cfg.gatewayUrl) ? '' : ' missing (/login)'}`
|
|
922
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}`; })()
|
|
923
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: '
|
|
39
|
-
CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE: '
|
|
40
|
-
CLAUDE_PRO_CLAUDE_CODE_VERSION: 'Claude
|
|
41
|
-
CLAUDE_PRO_DISABLE_TOKEN_REFRESH: 'Set to 1 to stop this program renewing the Claude
|
|
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
|
|
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
|
|
51
|
-
CLAUDE_CONFIG_DIR: '
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
+
}
|
package/src/host.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// Protocol (Bearer = the gateway API key; ARCHITECTURE.md 3.1.5):
|
|
9
9
|
// POST /v1/remote/hosts {id, machine, host, platform, version, home, terminal, autostart, sessions, stats}
|
|
10
10
|
// GET /v1/remote/hosts/:id/commands (SSE): online while it is open; {cid, type, body}: list, open, stop,
|
|
11
|
-
// restart, logs, history, update
|
|
11
|
+
// restart, window, logs, history, delete, update
|
|
12
12
|
// POST /v1/remote/hosts/:id/results {cid, ok: true, ...} | {cid, ok: false, error}
|
|
13
13
|
// POST /v1/remote/hosts/:id/state {sessions, stats}: on a change of the sessions, and every minute
|
|
14
14
|
// DELETE /v1/remote/hosts/:id: off the page's list (`host stop`, a logout, another account)
|
|
@@ -30,7 +30,7 @@ import { CONFIG_DIR, INSTALL_DIR, VERSION, GATEWAY_DEFAULT_URL, loadConfig } fro
|
|
|
30
30
|
import { readGatewayLogin, normalizeGatewayUrl } from './gateway.js';
|
|
31
31
|
import { machineName, cleanName, listPeers } from './peers.js';
|
|
32
32
|
import { BackgroundSessions, markEnded, tailFile } from './background.js';
|
|
33
|
-
import { listConversations } from './history.js';
|
|
33
|
+
import { listConversations, deleteConversation, CONVERSATION_ID } from './history.js';
|
|
34
34
|
import { checkForUpdate, installUpdate } from './updater.js';
|
|
35
35
|
import { ENV_SUPERVISED, ENV_RESTART_FILE, ENV_RESTARTED } from './supervisor.js';
|
|
36
36
|
|
|
@@ -444,15 +444,15 @@ function writeEnvFile(sessionId, vars) {
|
|
|
444
444
|
|
|
445
445
|
// How `term` opens a window that runs `node entry ...args` in `cwd`: {cmd, args, options, wait}. `wait`: 'exit'
|
|
446
446
|
// when the command ends once the window is open (its exit code says whether it worked), 'spawn' when it is the
|
|
447
|
-
// terminal itself.
|
|
448
|
-
export function launchCommand(term, { cwd, node = process.execPath, entry = ENTRY, args = [], env = {}, envFile = null, sessionId = '' }) {
|
|
447
|
+
// terminal itself. `title`: the tab's first title, where the terminal takes one (Windows Terminal).
|
|
448
|
+
export function launchCommand(term, { cwd, node = process.execPath, entry = ENTRY, args = [], env = {}, envFile = null, sessionId = '', title = '' }) {
|
|
449
449
|
const program = [node, ...(envFile ? [`--env-file=${envFile}`] : []), entry, ...args];
|
|
450
450
|
const pairs = Object.entries(env).map(([k, v]) => `${k}=${v}`);
|
|
451
451
|
const posix = [...(pairs.length ? ['env', ...pairs] : []), node, entry, ...args];
|
|
452
452
|
const line = posix.map(shQuote).join(' ');
|
|
453
453
|
switch (term.kind) {
|
|
454
454
|
case 'wt': // a new window; wt reads ; as the start of another command
|
|
455
|
-
return { cmd: term.path, args: ['-w', 'new', '-d', cwd, ...program].map((a) => a.replace(/;/g, '\\;')), options: { windowsHide: false }, wait: 'exit' };
|
|
455
|
+
return { cmd: term.path, args: ['-w', 'new', ...(title ? ['--title', title] : []), '-d', cwd, ...program].map((a) => a.replace(/;/g, '\\;')), options: { windowsHide: false }, wait: 'exit' };
|
|
456
456
|
case 'console': { // a console window of its own; Start-Process takes the command line as it is
|
|
457
457
|
// what went wrong: only its message, in UTF-8 (PowerShell writes errors as CLIXML in the system's code page)
|
|
458
458
|
const script = [
|
|
@@ -778,6 +778,8 @@ export class HostService {
|
|
|
778
778
|
else if (cmd.type === 'logs') r = this.logs(body);
|
|
779
779
|
else if (cmd.type === 'history') r = this.history(body);
|
|
780
780
|
else if (cmd.type === 'update') r = await this.update();
|
|
781
|
+
else if (cmd.type === 'window') r = await this.window(body);
|
|
782
|
+
else if (cmd.type === 'delete') r = await this.deleteConversation(body);
|
|
781
783
|
else throw new Error(`这台电脑上的 claude-pro ${VERSION} 不认识命令 ${cmd.type},请升级`);
|
|
782
784
|
result = { cid: cmd.cid, ok: true, ...r };
|
|
783
785
|
} catch (e) {
|
|
@@ -805,6 +807,57 @@ export class HostService {
|
|
|
805
807
|
});
|
|
806
808
|
}
|
|
807
809
|
|
|
810
|
+
// window: a background session brought to the front in a terminal window of this computer, `claude-pro attach` in
|
|
811
|
+
// it (chosen as open's terminal window is). A turn that runs goes on and shows there as it goes; the session stays
|
|
812
|
+
// the service's. Closing the window (its X included: the attach process ends) only detaches it. Each call opens
|
|
813
|
+
// another window. Without a desktop, a tmux session to attach to (`tmux attach -t claude-pro-<id>-…`).
|
|
814
|
+
async window({ sessionId } = {}) {
|
|
815
|
+
if (typeof sessionId !== 'string' || !ID.test(sessionId)) throw new Error('会话 id 不对');
|
|
816
|
+
const rec = this.sessions?.sessions.get(sessionId);
|
|
817
|
+
if (!rec) {
|
|
818
|
+
if (this.sessions?.ended.some((e) => e.sessionId === sessionId)) throw new Error('会话没有在运行');
|
|
819
|
+
throw new Error('这个会话不是这台电脑上的后台会话');
|
|
820
|
+
}
|
|
821
|
+
if (rec.state !== 'running' || !this.sessions.alive(rec)) throw new Error('会话没有在运行');
|
|
822
|
+
const label = rec.name || sessionId;
|
|
823
|
+
const term = this.terminal;
|
|
824
|
+
if (!term) throw new Error(`这台电脑没有可以打开窗口的桌面(可以在终端里运行 claude-pro attach ${label})`);
|
|
825
|
+
let cwd = rec.cwd;
|
|
826
|
+
try { if (!fs.statSync(cwd).isDirectory()) cwd = this.home; } catch { cwd = this.home; }
|
|
827
|
+
const env = passedEnv();
|
|
828
|
+
const key = `${sessionId}-w${Date.now().toString(36)}`; // its own env file and tmux session: one window more each time
|
|
829
|
+
const envFile = process.platform === 'win32' && term.kind === 'wt' ? writeEnvFile(key, env) : null;
|
|
830
|
+
try {
|
|
831
|
+
await this.launch(launchCommand(term, { cwd, args: ['attach', sessionId, '--keep-open'], env, envFile, sessionId: key, title: `${label} · claude-pro` }));
|
|
832
|
+
} catch (e) {
|
|
833
|
+
throw new Error(`无法用 ${term.name} 打开终端:${e.message}`);
|
|
834
|
+
}
|
|
835
|
+
this.log(`opened ${term.name} attached to the background session ${sessionId} (${label})`);
|
|
836
|
+
return { terminal: term.name };
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// delete: what this computer keeps of a conversation (see history.js), for good. Open in a background session of this
|
|
840
|
+
// service, that session is ended first with `stop` (as the stop command does), else it is refused; open in a terminal,
|
|
841
|
+
// it is refused: a terminal the user works in is not closed for them. {files, bytes}
|
|
842
|
+
async deleteConversation({ conversationId, stop = false } = {}) {
|
|
843
|
+
const id = conversationId;
|
|
844
|
+
if (typeof id !== 'string' || !CONVERSATION_ID.test(id)) throw new Error('对话 id 不对');
|
|
845
|
+
const open = listPeers().filter((p) => p.conversationId === id);
|
|
846
|
+
const ours = (p) => p.kind === 'background' && this.sessions?.sessions.has(p.remoteId);
|
|
847
|
+
const terminal = open.find((p) => !ours(p) && p.kind !== 'background');
|
|
848
|
+
if (terminal) throw new Error(`这段对话正开在终端里的会话 &${terminal.name} 里:请先在那台电脑上结束它(/exit)`);
|
|
849
|
+
const other = open.find((p) => !ours(p));
|
|
850
|
+
if (other) throw new Error(`这段对话正开在会话 &${other.name} 里:先结束它`);
|
|
851
|
+
// the service's own sessions with it: those in the registry, and those starting or restarting
|
|
852
|
+
const running = [...(this.sessions?.sessions.values() || [])].filter((r) => (r.conversationId === id || open.some((p) => p.remoteId === r.sessionId)) && this.sessions.alive(r));
|
|
853
|
+
if (running.length && stop !== true) throw new Error(`这段对话正开在会话 &${running[0].name || running[0].sessionId} 里:先结束它`);
|
|
854
|
+
for (const r of running) await this.sessions.stop(r.sessionId);
|
|
855
|
+
const logs = this.sessions ? this.sessions.forgetConversation(id) : [];
|
|
856
|
+
const r = deleteConversation({ projects: path.join(configDir(), 'projects'), id, extra: logs });
|
|
857
|
+
this.log(`deleted the conversation ${id}: ${r.files} files, ${r.bytes} bytes${running.length ? ` (its session ${running.map((x) => x.sessionId).join(', ')} ended first)` : ''}`);
|
|
858
|
+
return { files: r.files, bytes: r.bytes };
|
|
859
|
+
}
|
|
860
|
+
|
|
808
861
|
// The conversations kept on this computer (see history.js), with the session each one is open in.
|
|
809
862
|
history({ query, cwd, limit, before } = {}) {
|
|
810
863
|
if (before != null && Number.isNaN(Date.parse(before))) throw new Error('before 不是时间');
|
|
@@ -1370,10 +1423,11 @@ const USAGE = `Usage: claude-pro host [run | start | stop | status | install | u
|
|
|
1370
1423
|
|
|
1371
1424
|
The computer service: it makes this computer one the gateway's web page (远程控制) runs sessions on. From the
|
|
1372
1425
|
page: new sessions here, in the directory chosen there, in the background without a window (or, when asked, in
|
|
1373
|
-
a terminal window);
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1426
|
+
a terminal window); bringing a background session to the front in a terminal window here (also while it works;
|
|
1427
|
+
closing the window sends it back); ending and restarting them; opening a conversation kept here again (history),
|
|
1428
|
+
or deleting it from this computer; their logs and its own; updating claude-pro. A background session that
|
|
1429
|
+
crashes is opened again, and after a restart of the computer the service opens again those that ran (the
|
|
1430
|
+
conversation, not the task that was running). \`claude-pro attach\` shows a background session in a terminal here.
|
|
1377
1431
|
|
|
1378
1432
|
It uses the gateway login of /login or claude-pro connect, and only connects out to the gateway. A session
|
|
1379
1433
|
logged in to the gateway starts it by itself, and /login and connect set it up to start at logon
|
package/src/main.js
CHANGED
|
@@ -5,7 +5,7 @@ import { takeRestartState } from './restart.js';
|
|
|
5
5
|
|
|
6
6
|
const HELP = `Usage: claude-pro [options] [prompt]
|
|
7
7
|
|
|
8
|
-
A
|
|
8
|
+
A command line coding agent: through the gateway, an Anthropic-compatible API, or your Claude subscription.
|
|
9
9
|
Starts an interactive session by default; use -p for non-interactive output.
|
|
10
10
|
|
|
11
11
|
Options:
|