@yanzc/claude-pro 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +372 -370
- package/package.json +1 -1
- package/src/agent.js +18 -13
- package/src/attach.js +132 -0
- package/src/background.js +424 -0
- package/src/commands.js +80 -59
- package/src/connect.js +79 -0
- package/src/history.js +94 -0
- package/src/host.js +445 -66
- package/src/main.js +38 -10
- package/src/peers.js +290 -215
- package/src/print.js +0 -1
- package/src/prompts.js +2 -7
- package/src/remote.js +50 -15
- package/src/runtime.js +2 -6
- package/src/session.js +24 -0
- package/src/supervisor.js +6 -3
- package/src/tools/bash.js +2 -2
- package/src/tools/index.js +2 -3
- package/src/tools/interaction.js +2 -30
- package/src/tools/task.js +1 -1
- package/src/ui/ansi.js +0 -1
- package/src/ui/dialogs.js +48 -0
- package/src/ui/render.js +10 -4
- package/src/ui/repl.js +318 -77
- package/src/ui/vterm.js +62 -0
- package/src/modes.js +0 -154
- package/src/qr.js +0 -206
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
|
|
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';
|
|
@@ -21,8 +21,7 @@ import { displayPath } from './utils/paths.js';
|
|
|
21
21
|
import { cleanName, machineName } from './peers.js';
|
|
22
22
|
import { rewind, promptAt } from './checkpoints.js';
|
|
23
23
|
import { canRestart, runSelfCheck } from './restart.js';
|
|
24
|
-
import { describeHost } from './host.js';
|
|
25
|
-
import { qrLines } from './qr.js';
|
|
24
|
+
import { describeHost, normalizeDir } from './host.js';
|
|
26
25
|
|
|
27
26
|
const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
28
27
|
const isGpt = (modelId) => /^gpt-/i.test(modelId);
|
|
@@ -35,6 +34,55 @@ const effortLevels = (modelId, modelInfo = null) => {
|
|
|
35
34
|
return isGpt(modelId) && codexEfforts(modelId).length ? codexEfforts(modelId) : EFFORTS;
|
|
36
35
|
};
|
|
37
36
|
|
|
37
|
+
// What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
|
|
38
|
+
// default first. `value` is what /model <value> takes. The gateway's list of models is asked for (4 seconds at
|
|
39
|
+
// most); without an answer gpt-6.1-sol stands for its GPT models.
|
|
40
|
+
export async function modelChoices(cfg) {
|
|
41
|
+
const configured = cfg.configuredModelSpec;
|
|
42
|
+
const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).id}` }];
|
|
43
|
+
if (cfg.usesCodex) {
|
|
44
|
+
// The models the local Codex install lists.
|
|
45
|
+
for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ value: m.slug, label: m.slug, description: m.contextWindow ? `${formatTokens(m.contextWindow)} context` : '' });
|
|
46
|
+
} else {
|
|
47
|
+
opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
|
|
48
|
+
}
|
|
49
|
+
if (cfg.usesGateway) {
|
|
50
|
+
// The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
|
|
51
|
+
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
52
|
+
let served = null;
|
|
53
|
+
try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
|
|
54
|
+
const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
|
|
55
|
+
for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
|
|
56
|
+
if (aliased.has(m.id)) continue;
|
|
57
|
+
opts.push({ value: m.id, label: m.id, description: isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || '' });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, label: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, description: 'sub-agent model' });
|
|
61
|
+
return opts;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// What /effort offers for the current model: {levels, options: [{value, label, description}]} in plain text (the
|
|
65
|
+
// levels, auto, default).
|
|
66
|
+
export async function effortChoices(cfg) {
|
|
67
|
+
const id = cfg.mainModel.id;
|
|
68
|
+
let info = null;
|
|
69
|
+
if (cfg.usesGateway && isGpt(id)) {
|
|
70
|
+
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
71
|
+
try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
|
|
72
|
+
}
|
|
73
|
+
const levels = effortLevels(id, info);
|
|
74
|
+
const configured = (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '').trim().toLowerCase() || 'auto';
|
|
75
|
+
const fallback = defaultEffort(id, cfg);
|
|
76
|
+
return {
|
|
77
|
+
levels,
|
|
78
|
+
options: [
|
|
79
|
+
...levels.map((e) => ({ value: e, label: e, description: '' })),
|
|
80
|
+
{ value: 'auto', label: 'auto', description: fallback ? `model default: ${fallback}` : 'use API default' },
|
|
81
|
+
{ value: 'default', label: 'default', description: `configured: ${configured}` },
|
|
82
|
+
],
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
38
86
|
export function buildCommands(app) {
|
|
39
87
|
const commands = new Map();
|
|
40
88
|
const add = (cmd) => commands.set(cmd.name, cmd);
|
|
@@ -109,6 +157,27 @@ export function buildCommands(app) {
|
|
|
109
157
|
},
|
|
110
158
|
});
|
|
111
159
|
|
|
160
|
+
add({
|
|
161
|
+
name: 'cd',
|
|
162
|
+
argHint: '<directory>',
|
|
163
|
+
argRequired: true,
|
|
164
|
+
description: 'Change the working directory; the conversation goes on there (with that project\'s settings, CLAUDE.md and memory)',
|
|
165
|
+
run(args) {
|
|
166
|
+
const wanted = args.trim().replace(/^(["'])(.*)\1$/, '$2').trim();
|
|
167
|
+
if (!wanted) { out(`Working directory: ${app.cwd} ${c.dim('(/cd <directory> changes it)')}`); return; }
|
|
168
|
+
// absolute, ~ for the home directory, D: for a drive; else from the working directory
|
|
169
|
+
const dir = normalizeDir(wanted) ?? path.resolve(app.cwd, wanted);
|
|
170
|
+
let st = null;
|
|
171
|
+
try { st = fs.statSync(dir); } catch { /* below */ }
|
|
172
|
+
if (!st) { out(c.red(`No such directory: ${dir}`)); return; }
|
|
173
|
+
if (!st.isDirectory()) { out(c.red(`Not a directory: ${dir}`)); return; }
|
|
174
|
+
const same = (a, b) => (process.platform === 'win32' ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
|
|
175
|
+
if (same(dir, app.cwd)) { out(`Working directory: ${app.cwd} ${c.dim('(already)')}`); return; }
|
|
176
|
+
const res = app.changeDirectory(dir);
|
|
177
|
+
if (!res.ok) out(c.red(res.message));
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
|
|
112
181
|
add({
|
|
113
182
|
name: 'clear',
|
|
114
183
|
aliases: ['reset', 'new'],
|
|
@@ -224,27 +293,7 @@ export function buildCommands(app) {
|
|
|
224
293
|
const cfg = app.runtime.config;
|
|
225
294
|
let choice = args.trim();
|
|
226
295
|
if (!choice) {
|
|
227
|
-
const
|
|
228
|
-
const opts = [{ label: `Default ${c.dim(`(${configured} → ${cfg.resolveModel(configured).id})`)}`, value: '__default__' }];
|
|
229
|
-
if (cfg.usesCodex) {
|
|
230
|
-
// The models the local Codex install lists.
|
|
231
|
-
for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ label: `${m.slug}${m.contextWindow ? c.dim(` (${formatTokens(m.contextWindow)} context)`) : ''}`, value: m.slug });
|
|
232
|
-
} else {
|
|
233
|
-
opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ label: `${a} ${c.dim(`→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}`)}`, value: a })));
|
|
234
|
-
}
|
|
235
|
-
if (cfg.usesGateway) {
|
|
236
|
-
// The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
|
|
237
|
-
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
238
|
-
let served = null;
|
|
239
|
-
try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
|
|
240
|
-
const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
|
|
241
|
-
for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
|
|
242
|
-
if (aliased.has(m.id)) continue;
|
|
243
|
-
const note = /^gpt-/i.test(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name;
|
|
244
|
-
opts.push({ label: `${m.id}${note ? ` ${c.dim(`(${note})`)}` : ''}`, value: m.id });
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ label: `${cfg.env.CLAUDE_CODE_SUBAGENT_MODEL} ${c.dim('(sub-agent model)')}`, value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL });
|
|
296
|
+
const opts = (await modelChoices(cfg)).map((o) => ({ label: `${o.label}${o.description ? ` ${c.dim(o.description.startsWith('→') ? o.description : `(${o.description})`)}` : ''}`, value: o.value }));
|
|
248
297
|
choice = await app.showDialog(new SelectDialog({ title: 'Select model', question: `Current: ${c.bold(cfg.mainModel.label)}. Any name works too: /model <name>`, options: opts }));
|
|
249
298
|
if (!choice) return;
|
|
250
299
|
}
|
|
@@ -270,15 +319,9 @@ export function buildCommands(app) {
|
|
|
270
319
|
async run(args) {
|
|
271
320
|
const cfg = app.runtime.config;
|
|
272
321
|
const id = cfg.mainModel.id;
|
|
273
|
-
|
|
274
|
-
if (cfg.usesGateway && isGpt(id)) {
|
|
275
|
-
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
276
|
-
try { if (login) modelInfo = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
|
|
277
|
-
}
|
|
278
|
-
const levels = effortLevels(id, modelInfo);
|
|
322
|
+
const { levels, options } = await effortChoices(cfg);
|
|
279
323
|
let choice = args.trim().toLowerCase();
|
|
280
324
|
if (!choice) {
|
|
281
|
-
const configured = (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '').trim().toLowerCase() || 'auto';
|
|
282
325
|
const fallback = defaultEffort(id, cfg);
|
|
283
326
|
// A level this model does not take goes out as the nearest one it does.
|
|
284
327
|
const sent = effortToSend(cfg, id, cfg.effort);
|
|
@@ -287,11 +330,7 @@ export function buildCommands(app) {
|
|
|
287
330
|
choice = await app.showDialog(new SelectDialog({
|
|
288
331
|
title: `Reasoning effort · ${id}`,
|
|
289
332
|
question: `Current: ${current}`,
|
|
290
|
-
options:
|
|
291
|
-
...levels.map((e) => ({ label: e, value: e })),
|
|
292
|
-
{ label: `auto ${c.dim(fallback ? `(model default: ${fallback})` : '(use API default)')}`, value: 'auto' },
|
|
293
|
-
{ label: `default ${c.dim(`(configured: ${configured})`)}`, value: 'default' },
|
|
294
|
-
],
|
|
333
|
+
options: options.map((o) => ({ label: `${o.label}${o.description ? ` ${c.dim(`(${o.description})`)}` : ''}`, value: o.value })),
|
|
295
334
|
}));
|
|
296
335
|
if (!choice) return;
|
|
297
336
|
}
|
|
@@ -333,10 +372,10 @@ export function buildCommands(app) {
|
|
|
333
372
|
// sessions), and the computer service starts (the web page opens new sessions through it).
|
|
334
373
|
const goOnline = async () => {
|
|
335
374
|
const remote = await app.syncRemote();
|
|
336
|
-
app.ensureHost();
|
|
375
|
+
app.ensureHost({ login: true });
|
|
337
376
|
if (!remote) return;
|
|
338
|
-
out(remote.
|
|
339
|
-
? `${c.green('⇄')} This session is online at the gateway:
|
|
377
|
+
out(remote.registered
|
|
378
|
+
? `${c.green('⇄')} This session is online at the gateway: the web page (远程控制) shows it.`
|
|
340
379
|
: c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
|
|
341
380
|
};
|
|
342
381
|
|
|
@@ -439,7 +478,6 @@ export function buildCommands(app) {
|
|
|
439
478
|
description: 'Show version, model, API endpoint and session info',
|
|
440
479
|
run() {
|
|
441
480
|
const cfg = app.runtime.config;
|
|
442
|
-
const modes = app.runtime.modes;
|
|
443
481
|
const mem = memoryFiles(app.cwd);
|
|
444
482
|
const mcp = app.runtime.mcp.status();
|
|
445
483
|
const row = (k, v) => `${c.dim(padEnd(k, 18))} ${v}`;
|
|
@@ -461,7 +499,7 @@ export function buildCommands(app) {
|
|
|
461
499
|
row('Max output', formatTokens(cfg.maxOutputTokens)),
|
|
462
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') : ''}`),
|
|
463
501
|
row('Auto-compact', cfg.autoCompactEnabled ? `at ${formatTokens(cfg.autoCompactThreshold())} tokens (window ${formatTokens(cfg.compactWindow())})` : 'disabled'),
|
|
464
|
-
row('
|
|
502
|
+
row('Access', 'full (no permission prompts)'),
|
|
465
503
|
row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
|
|
466
504
|
row('Shell', `${app.runtime.shell.name} ${c.dim(app.runtime.shell.path)}`),
|
|
467
505
|
row('ripgrep', hasRipgrep(cfg) ? 'yes' : 'no (using JS fallback)'),
|
|
@@ -473,7 +511,7 @@ export function buildCommands(app) {
|
|
|
473
511
|
},
|
|
474
512
|
});
|
|
475
513
|
|
|
476
|
-
// /status about the gateway: this session
|
|
514
|
+
// /status about the gateway: whether this session is online there, its name for the
|
|
477
515
|
// sessions on the other computers, and the computer service.
|
|
478
516
|
function remoteLines(row) {
|
|
479
517
|
const cfg = app.runtime.config;
|
|
@@ -481,15 +519,9 @@ export function buildCommands(app) {
|
|
|
481
519
|
const me = app.peerLabel();
|
|
482
520
|
const lines = [
|
|
483
521
|
row('Remote control', remote.text),
|
|
484
|
-
...(remote.url ? [row('', c.blue(remote.url))] : []),
|
|
485
522
|
row('Name', `&${me} ${c.dim(`(on your other computers: &${machineName(cfg.env)}/${me}; /rename changes it)`)}`),
|
|
486
523
|
row('Computer service', describeHost(cfg.env)),
|
|
487
524
|
];
|
|
488
|
-
const qr = remote.url && app.remote?.online ? qrLines(remote.url, { color: colorEnabled }) : null;
|
|
489
|
-
if (qr) {
|
|
490
|
-
lines.push('', c.dim(' Scan with a phone to open this session (log in to the gateway there):'), ...qr.map((l) => ` ${l}`));
|
|
491
|
-
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.`));
|
|
492
|
-
}
|
|
493
525
|
return lines;
|
|
494
526
|
}
|
|
495
527
|
|
|
@@ -683,17 +715,6 @@ export function buildCommands(app) {
|
|
|
683
715
|
},
|
|
684
716
|
});
|
|
685
717
|
|
|
686
|
-
add({
|
|
687
|
-
name: 'plan',
|
|
688
|
-
description: 'Toggle read-only plan mode (same as shift+tab)',
|
|
689
|
-
run() {
|
|
690
|
-
const mode = app.runtime.modes.toggle();
|
|
691
|
-
out(mode === 'plan'
|
|
692
|
-
? [`${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.')]
|
|
693
|
-
: `Plan mode off: ${c.bold('full access')}, tools run immediately.`);
|
|
694
|
-
},
|
|
695
|
-
});
|
|
696
|
-
|
|
697
718
|
add({
|
|
698
719
|
name: 'rewind',
|
|
699
720
|
aliases: ['checkpoint'],
|
package/src/connect.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// `claude-pro connect <code> [--url U]`: a new computer joins the user's gateway account with the pairing code the
|
|
2
|
+
// web page shows (添加电脑). No login in a browser: the code stands for it. The gateway answers with an API key of
|
|
3
|
+
// this computer's own, which is saved as /login saves one (gateway.json); then the computer service is set up to
|
|
4
|
+
// start at logon and started, so that the page can use this computer at once and after every restart.
|
|
5
|
+
//
|
|
6
|
+
// POST {url}/v1/remote/pair {code, id, machine, host, platform, version, home} (no authentication)
|
|
7
|
+
// 200 {apiKey, computerId, url, account: {name, email}} · 400 配对码无效或已过期 · 429 too many tries
|
|
8
|
+
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import { VERSION, GATEWAY_DEFAULT_URL, loadConfig, settingsFiles, updateSettingsFile } from './config.js';
|
|
11
|
+
import { saveGatewayLogin, normalizeGatewayUrl } from './gateway.js';
|
|
12
|
+
import { machineName } from './peers.js';
|
|
13
|
+
import { computerId, setComputerId, hostEnabled, ensureAutostart, startHostInBackground, hostRunning, readHostState, updateHostState } from './host.js';
|
|
14
|
+
|
|
15
|
+
// The code as typed: 8 letters and digits (I, O, 0 and 1 are not used), maybe with a dash or spaces, in any case.
|
|
16
|
+
export function normalizePairingCode(input) {
|
|
17
|
+
const code = String(input ?? '').toUpperCase().replace(/[\s-]+/g, '');
|
|
18
|
+
return /^[A-Z2-9]{8}$/.test(code) ? code : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const USAGE = `Usage: claude-pro connect <code> [--url <gateway>]
|
|
22
|
+
|
|
23
|
+
Connects this computer to your gateway account with the pairing code the web page shows (远程控制 → 添加电脑),
|
|
24
|
+
then starts the computer service and sets it to start at logon, so that the page can use this computer.
|
|
25
|
+
--url: the gateway's address (default ${GATEWAY_DEFAULT_URL}, or CLAUDE_PRO_GATEWAY_URL).
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
export async function connectCommand(args = [], { fetchImpl = globalThis.fetch, out = (s) => process.stdout.write(`${s}\n`), err = (s) => process.stderr.write(`${s}\n`), startService = true } = {}) {
|
|
29
|
+
let url = null;
|
|
30
|
+
const rest = [];
|
|
31
|
+
for (let i = 0; i < args.length; i++) {
|
|
32
|
+
if (args[i] === '--url') url = args[++i];
|
|
33
|
+
else if (args[i].startsWith('--url=')) url = args[i].slice(6);
|
|
34
|
+
else if (args[i] === '-h' || args[i] === '--help') { out(USAGE); return 0; }
|
|
35
|
+
else rest.push(args[i]);
|
|
36
|
+
}
|
|
37
|
+
const code = normalizePairingCode(rest.join(''));
|
|
38
|
+
if (!code) { err(`配对码应是 8 位字母和数字(例如 K7QF-M2XD),不是 "${rest.join(' ')}"\n\n${USAGE}`); return 2; }
|
|
39
|
+
const home = os.homedir();
|
|
40
|
+
const cfg = loadConfig({ cwd: home });
|
|
41
|
+
const base = normalizeGatewayUrl(url || cfg.gatewayUrl);
|
|
42
|
+
let res;
|
|
43
|
+
let data = {};
|
|
44
|
+
try {
|
|
45
|
+
res = await fetchImpl(`${base}/v1/remote/pair`, {
|
|
46
|
+
method: 'POST',
|
|
47
|
+
headers: { 'content-type': 'application/json' },
|
|
48
|
+
body: JSON.stringify({ code, id: computerId(), machine: machineName(cfg.env), host: os.hostname(), platform: process.platform, version: VERSION, home }),
|
|
49
|
+
signal: AbortSignal.timeout(20_000),
|
|
50
|
+
});
|
|
51
|
+
data = await res.json().catch(() => ({}));
|
|
52
|
+
} catch (e) {
|
|
53
|
+
err(`连不上网关 ${base}:${e.message}`);
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
if (!res.ok || !data.apiKey) {
|
|
57
|
+
const said = data?.error?.message || (typeof data?.error === 'string' ? data.error : '');
|
|
58
|
+
err(res.status === 429 ? `请求太频繁,请稍后再试${said ? `(${said})` : ''}` : said || `配对失败(HTTP ${res.status})`);
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
const gateway = normalizeGatewayUrl(data.url || base);
|
|
62
|
+
saveGatewayLogin({ url: gateway, apiKey: data.apiKey, account: data.account || {} });
|
|
63
|
+
// another gateway than the one configured: the sessions and the service use this one from now on
|
|
64
|
+
if (gateway !== normalizeGatewayUrl(cfg.gatewayUrl)) {
|
|
65
|
+
updateSettingsFile(settingsFiles(home).user, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_GATEWAY_URL: gateway }; });
|
|
66
|
+
}
|
|
67
|
+
if (data.computerId && data.computerId !== computerId()) setComputerId(data.computerId);
|
|
68
|
+
const who = data.account?.name || data.account?.email || '你的账户';
|
|
69
|
+
if (!hostEnabled(cfg.env)) {
|
|
70
|
+
out(`已连接到 ${who}。CLAUDE_PRO_HOST=0:电脑服务不会自己启动,用 claude-pro host start 启动它,网页才能使用这台电脑。`);
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
updateHostState({ disabled: undefined, autostartDeclined: undefined });
|
|
74
|
+
const auto = ensureAutostart({ force: true, env: cfg.env });
|
|
75
|
+
if (startService && !hostRunning(readHostState())) startHostInBackground();
|
|
76
|
+
// (one that runs already picks the new login up within seconds)
|
|
77
|
+
out(`已连接到 ${who},可以在网页上使用这台电脑了。${auto?.file ? `\n登录后自动启动:${auto.file}` : ''}`);
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
package/src/history.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// The conversations kept on this computer (CONFIG_DIR/projects/<directory>/<id>.jsonl, see session.js), for the web
|
|
2
|
+
// page's history (the computer service's `history` command): newest first, searched by title and first message,
|
|
3
|
+
// a page at a time. A file is read once for as long as it does not change (a session file can be tens of MB): its
|
|
4
|
+
// messages are counted without parsing them, only the first prompt and the meta lines are.
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { firstUserText, projectDir } from './session.js';
|
|
9
|
+
|
|
10
|
+
const cache = new Map(); // file -> {mtimeMs, size, summary}
|
|
11
|
+
|
|
12
|
+
// {conversationId, cwd, title, firstPrompt, messages, updatedAt} of one session file, or null when it has none.
|
|
13
|
+
export function conversationSummary(file) {
|
|
14
|
+
let st;
|
|
15
|
+
try { st = fs.statSync(file); } catch { return null; }
|
|
16
|
+
const hit = cache.get(file);
|
|
17
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.summary;
|
|
18
|
+
let text = '';
|
|
19
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return null; }
|
|
20
|
+
let cwd = null;
|
|
21
|
+
let name = null;
|
|
22
|
+
let topic = null;
|
|
23
|
+
let first = null;
|
|
24
|
+
let messages = 0;
|
|
25
|
+
for (const line of text.split('\n')) {
|
|
26
|
+
if (!line) continue;
|
|
27
|
+
if (line.startsWith('{"type":"message"')) {
|
|
28
|
+
messages++;
|
|
29
|
+
if (!first && line.includes('"role":"user"')) {
|
|
30
|
+
try { first = firstUserText(JSON.parse(line).message) || null; } catch { /* a broken line */ }
|
|
31
|
+
}
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
let e;
|
|
35
|
+
try { e = JSON.parse(line); } catch { continue; }
|
|
36
|
+
if (e.type === 'meta') {
|
|
37
|
+
if (cwd === null && typeof e.cwd === 'string') cwd = e.cwd;
|
|
38
|
+
if ('name' in e) name = typeof e.name === 'string' && e.name.trim() ? e.name : null;
|
|
39
|
+
if (typeof e.topic === 'string' && e.topic.trim()) topic = e.topic;
|
|
40
|
+
} else if (e.type === 'reset' && Array.isArray(e.messages)) {
|
|
41
|
+
messages = e.messages.length;
|
|
42
|
+
} else if (e.type === 'message') {
|
|
43
|
+
messages++;
|
|
44
|
+
if (!first && e.message?.role === 'user') first = firstUserText(e.message) || null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const summary = messages ? {
|
|
48
|
+
conversationId: path.basename(file, '.jsonl'),
|
|
49
|
+
cwd,
|
|
50
|
+
title: name || topic || first || '(no prompt)',
|
|
51
|
+
firstPrompt: first || '',
|
|
52
|
+
messages,
|
|
53
|
+
updatedAt: new Date(st.mtimeMs).toISOString(),
|
|
54
|
+
} : null;
|
|
55
|
+
cache.set(file, { mtimeMs: st.mtimeMs, size: st.size, summary });
|
|
56
|
+
if (cache.size > 5000) cache.delete(cache.keys().next().value);
|
|
57
|
+
return summary;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// {items: [{conversationId, cwd, title, updatedAt, messages, sessionId?}], more}. `cwd`: only that directory's
|
|
61
|
+
// conversations. `before`: older than this time (ISO), for the next page. `open`: conversationId -> the id at the
|
|
62
|
+
// gateway of the session it is open in.
|
|
63
|
+
export function listConversations({ projects, query = '', cwd = null, limit = 50, before = null, open = new Map() } = {}) {
|
|
64
|
+
const max = Math.max(1, Math.min(200, Number(limit) || 50));
|
|
65
|
+
const until = before ? Date.parse(before) : Infinity;
|
|
66
|
+
const q = String(query || '').trim().toLowerCase();
|
|
67
|
+
const dirs = cwd ? [projectDir(cwd)] : (() => {
|
|
68
|
+
try { return fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(projects, d.name)); } catch { return []; }
|
|
69
|
+
})();
|
|
70
|
+
const files = [];
|
|
71
|
+
for (const dir of dirs) {
|
|
72
|
+
let names = [];
|
|
73
|
+
try { names = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { continue; }
|
|
74
|
+
for (const f of names) {
|
|
75
|
+
const file = path.join(dir, f);
|
|
76
|
+
try {
|
|
77
|
+
const st = fs.statSync(file);
|
|
78
|
+
if (st.mtimeMs < until) files.push({ file, mtimeMs: st.mtimeMs });
|
|
79
|
+
} catch { /* gone meanwhile */ }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
83
|
+
const items = [];
|
|
84
|
+
let more = false;
|
|
85
|
+
for (const { file } of files) {
|
|
86
|
+
const s = conversationSummary(file);
|
|
87
|
+
if (!s) continue;
|
|
88
|
+
if (q && !`${s.title}\n${s.firstPrompt}`.toLowerCase().includes(q)) continue;
|
|
89
|
+
if (items.length === max) { more = true; break; }
|
|
90
|
+
const sessionId = open.get(s.conversationId);
|
|
91
|
+
items.push({ conversationId: s.conversationId, cwd: s.cwd, title: s.title, updatedAt: s.updatedAt, messages: s.messages, ...(sessionId ? { sessionId } : {}) });
|
|
92
|
+
}
|
|
93
|
+
return { items, more };
|
|
94
|
+
}
|