@yanzc/claude-pro 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -36
- package/package.json +1 -1
- package/src/agent.js +4 -3
- package/src/browser/session.js +21 -1
- package/src/commands.js +198 -33
- package/src/config.js +17 -2
- package/src/gateway.js +33 -0
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +41 -4
- package/src/providers.js +25 -6
- package/src/remote.js +82 -268
- package/src/runtime.js +36 -11
- package/src/selfcheck.js +3 -3
- package/src/session.js +128 -8
- package/src/supervisor.js +1 -1
- package/src/tools/bash.js +21 -12
- package/src/tools/browser.js +14 -8
- package/src/tools/code.js +18 -11
- package/src/tools/restart.js +1 -1
- package/src/ui/dialogs.js +23 -30
- package/src/ui/editor.js +65 -169
- package/src/ui/repl.js +467 -474
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/web/api.js +881 -0
- package/src/web/app.css +530 -0
- package/src/web/app.js +2188 -0
- package/src/web/data.js +436 -0
- package/src/web/host.js +332 -0
- package/src/web/login.html +67 -0
- package/src/web/logo.svg +1 -0
- package/src/web/page.html +44 -0
- package/src/web/remote-access.js +232 -0
- package/src/web/server.js +476 -0
package/src/commands.js
CHANGED
|
@@ -5,8 +5,8 @@ import path from 'node:path';
|
|
|
5
5
|
import { c, glyphs, padEnd, truncate } from './ui/ansi.js';
|
|
6
6
|
import { SelectDialog, TextInputDialog } from './ui/dialogs.js';
|
|
7
7
|
import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
|
|
8
|
-
import { loadConfig, settingsFiles, configEntries, writeConfigSetting, unsetConfigSetting, rememberChoice, applyRememberedChoices, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
|
|
9
|
-
import { loginWithKey, gatewayLogin, gatewayKeyPage, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, loadGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
|
|
8
|
+
import { loadConfig, settingsFiles, configEntries, writeConfigSetting, unsetConfigSetting, rememberChoice, applyRememberedChoices, pickedModels, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
|
|
9
|
+
import { loginWithKey, gatewayLogin, gatewayKeyPage, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, keptGatewayModels, loadGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
|
|
10
10
|
import { GATEWAY_PROVIDER, PRESETS, providerInfo, connectedProviders, readConnections, saveConnection, removeConnection, normalizeBaseUrl, validBaseUrl, cleanProviderId, reservedProviderId, listProviderModels, testProviderModel, modelsDevCatalogue, enrichModels } from './providers.js';
|
|
11
11
|
import { SessionStore } from './session.js';
|
|
12
12
|
import { memoryFiles, listAutoMemories } from './context.js';
|
|
@@ -19,7 +19,7 @@ import { hasRipgrep } from './utils/shell.js';
|
|
|
19
19
|
import { displayPath, normalizeDir, resolvePath } from './utils/paths.js';
|
|
20
20
|
import { cleanName, machineName } from './peers.js';
|
|
21
21
|
import { rewind, promptAt } from './checkpoints.js';
|
|
22
|
-
import {
|
|
22
|
+
import { runSelfCheck } from './restart.js';
|
|
23
23
|
|
|
24
24
|
const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
25
25
|
const isGpt = (modelId) => /^gpt-/i.test(modelId);
|
|
@@ -32,10 +32,11 @@ const effortLevels = (modelId, modelInfo = null) => {
|
|
|
32
32
|
|
|
33
33
|
// The models of the providers connected with /connect, for /model: each provider's list asked for anew (4 seconds at
|
|
34
34
|
// most), with what was kept at /connect about them (windows, prices); without an answer, the list kept then.
|
|
35
|
-
|
|
35
|
+
// `cached` (the web console's pickers): the kept lists only, nothing asked (its 刷新模型列表 button renews them).
|
|
36
|
+
async function providerModelChoices({ cached = false } = {}) {
|
|
36
37
|
const groups = await Promise.all(connectedProviders().map(async (info) => {
|
|
37
38
|
let listed = null;
|
|
38
|
-
try {
|
|
39
|
+
if (!cached) try {
|
|
39
40
|
listed = (await listProviderModels({ ...info, ...info.connection, baseUrl: info.connection.baseUrl || info.baseUrl }, { timeoutMs: 4000, kinds: [info.connection.authHeader || 'x-api-key'] })).models;
|
|
40
41
|
} catch { /* the kept list */ }
|
|
41
42
|
const kept = info.connection.models || [];
|
|
@@ -49,12 +50,15 @@ async function providerModelChoices() {
|
|
|
49
50
|
return groups.flat();
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
// What /model offers
|
|
53
|
+
// What /model offers: [{value, label, description}] in plain text, the
|
|
53
54
|
// default first. `value` is what /model <value> takes. Every connected provider's models, provider/model, 7bit.fun's
|
|
54
55
|
// among them (asked for anew each time, 4 seconds at most, so that a model just added is there without a restart;
|
|
55
56
|
// without an answer the list given last, else gpt-6.1-sol for its GPT models); the Claude aliases where a provider of
|
|
56
57
|
// Claude is connected. A provider that is not connected offers nothing.
|
|
57
|
-
|
|
58
|
+
// `cached`: the lists kept from before (see providerModelChoices); the gateway is asked only when none is kept yet.
|
|
59
|
+
// `picked` (the web console's menus, see pickedModels): a set of provider/model; when it has any, only those are
|
|
60
|
+
// offered by their full names (not the aliases), with the default and the model in use.
|
|
61
|
+
export async function modelChoices(cfg, { cached = false, picked = null } = {}) {
|
|
58
62
|
const configured = cfg.configuredModelSpec;
|
|
59
63
|
const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).label}` }];
|
|
60
64
|
const tag = (m) => `${m.provider}/${m.id}`;
|
|
@@ -66,28 +70,99 @@ export async function modelChoices(cfg) {
|
|
|
66
70
|
opts.push({ value: a, label: a, description: `→ ${target.label}` });
|
|
67
71
|
}
|
|
68
72
|
}
|
|
69
|
-
const others = providerModelChoices();
|
|
73
|
+
const others = providerModelChoices({ cached });
|
|
74
|
+
const gateway = [];
|
|
70
75
|
const login = gatewayLogin(cfg.gatewayUrl);
|
|
71
76
|
if (login) {
|
|
72
|
-
let served = null;
|
|
73
|
-
try { served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh:
|
|
77
|
+
let served = cached ? keptGatewayModels(login) : null;
|
|
78
|
+
if (!served) try { served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: !cached }); } catch { /* offline: the fallback below */ }
|
|
74
79
|
for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
|
|
75
|
-
|
|
76
|
-
opts.push({ value: `${GATEWAY_PROVIDER}/${m.id}`, label: `${GATEWAY_PROVIDER}/${m.id}`, description: ['7bit.fun', isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || ''].filter(Boolean).join(' · ') });
|
|
80
|
+
gateway.push({ value: `${GATEWAY_PROVIDER}/${m.id}`, label: `${GATEWAY_PROVIDER}/${m.id}`, description: ['7bit.fun', isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || ''].filter(Boolean).join(' · ') });
|
|
77
81
|
}
|
|
78
82
|
}
|
|
79
|
-
|
|
80
|
-
|
|
83
|
+
const providers = await others;
|
|
84
|
+
opts.push(...gateway.filter((o) => !aliased.has(o.value)), ...providers.filter((o) => !aliased.has(o.value)));
|
|
85
|
+
if (!picked?.size) return opts;
|
|
86
|
+
const kept = [opts[0], ...[...gateway, ...providers].filter((o) => picked.has(o.value))];
|
|
87
|
+
// the model in use stays listed (it is shown as the current one), unless a ticked entry is that model already
|
|
88
|
+
const chosen = cfg.modelOverride;
|
|
89
|
+
const sameModel = (o) => { try { const m = cfg.resolveModel(o.value); return m.id === cfg.model.id && m.provider === cfg.model.provider; } catch { return false; } };
|
|
90
|
+
if (chosen && !kept.some((o) => o.value === chosen || (o.value !== 'default' && sameModel(o)))) {
|
|
91
|
+
const current = opts.find((o) => o.value === chosen) || { value: chosen, label: chosen, description: '' };
|
|
92
|
+
kept.splice(1, 0, current);
|
|
93
|
+
}
|
|
94
|
+
return kept;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// The web menu marks the default on its model's row instead of offering a separate Default entry.
|
|
98
|
+
export async function webModelChoices(cfg) {
|
|
99
|
+
const models = (await modelChoices(cfg, { cached: true, picked: new Set(pickedModels()) })).filter((o) => o.value !== 'default');
|
|
100
|
+
const find = (list, spec) => {
|
|
101
|
+
const exact = list.find((o) => o.value === spec);
|
|
102
|
+
if (exact) return exact;
|
|
103
|
+
const { provider, id } = cfg.resolveModel(spec);
|
|
104
|
+
return list.find((o) => o.value === `${provider}/${id}`) || list.find((o) => {
|
|
105
|
+
// Full refs have already been matched; only aliases or the retained override can resolve to a different ref.
|
|
106
|
+
if (o.value.includes('/') && o.value !== cfg.modelOverride) return false;
|
|
107
|
+
const m = cfg.resolveModel(o.value);
|
|
108
|
+
return m.provider === provider && m.id === id;
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
let preferred = find(models, cfg.configuredModelSpec);
|
|
112
|
+
if (!preferred) {
|
|
113
|
+
// The default is not among the ticked models: listed anyway, first, by its full name as the ticked ones are, so
|
|
114
|
+
// that the menu can go back to it.
|
|
115
|
+
let ref = cfg.configuredModelSpec;
|
|
116
|
+
try { const m = cfg.resolveModel(ref); ref = `${m.provider}/${m.id}`; } catch { /* as written */ }
|
|
117
|
+
const entry = (await modelChoices(cfg, { cached: true, picked: new Set([ref]) })).find((o) => o.value === ref);
|
|
118
|
+
preferred = entry || { value: ref, label: ref, description: '' };
|
|
119
|
+
models.unshift(preferred);
|
|
120
|
+
}
|
|
121
|
+
const current = find(models, cfg.modelSpec);
|
|
122
|
+
return models.map((o) => ({ ...o, isDefault: o === preferred, current: o === current }));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Ask the gateway and every connected provider for their models now, and keep what they say (the gateway's list on
|
|
126
|
+
// disk, each provider's in its connection): what `cached` choices offer from then on. Resolves with what each said.
|
|
127
|
+
export async function refreshModelLists(cfg) {
|
|
128
|
+
const out = { gateway: null, providers: [] };
|
|
129
|
+
const jobs = [];
|
|
130
|
+
const login = gatewayLogin(cfg.gatewayUrl);
|
|
131
|
+
if (login) {
|
|
132
|
+
jobs.push(fetchGatewayModels(login, { fresh: true, timeoutMs: 15_000 })
|
|
133
|
+
.then((list) => { out.gateway = { count: list.length }; }, (e) => { out.gateway = { error: e.message }; }));
|
|
134
|
+
}
|
|
135
|
+
let catalogue = null;
|
|
136
|
+
for (const info of connectedProviders(readConnections({ fresh: true }))) {
|
|
137
|
+
jobs.push((async () => {
|
|
138
|
+
try {
|
|
139
|
+
const listed = await listProviderModels({ ...info, ...info.connection, baseUrl: info.connection.baseUrl || info.baseUrl }, { timeoutMs: 20_000, kinds: [info.connection.authHeader || 'x-api-key'] });
|
|
140
|
+
if (!listed.models?.length) throw new Error('no models listed');
|
|
141
|
+
if (info.modelsDev) catalogue ??= modelsDevCatalogue().catch(() => null);
|
|
142
|
+
const kept = info.connection.models || [];
|
|
143
|
+
const models = enrichModels(listed.models, info.modelsDev ? await catalogue : null, info.modelsDev)
|
|
144
|
+
.map((m) => ({ ...kept.find((k) => k.id === m.id), ...m })).slice(0, 2000);
|
|
145
|
+
saveConnection(info.id, { ...readConnections({ fresh: true })[info.id], models });
|
|
146
|
+
out.providers.push({ id: info.id, name: info.name, count: models.length });
|
|
147
|
+
} catch (e) {
|
|
148
|
+
out.providers.push({ id: info.id, name: info.name, error: e.message });
|
|
149
|
+
}
|
|
150
|
+
})());
|
|
151
|
+
}
|
|
152
|
+
await Promise.all(jobs);
|
|
153
|
+
return out;
|
|
81
154
|
}
|
|
82
155
|
|
|
83
156
|
// What /effort offers for the current model: {levels, options: [{value, label, description}]} in plain text (the
|
|
84
157
|
// levels, auto, default).
|
|
85
|
-
export async function effortChoices(cfg) {
|
|
158
|
+
export async function effortChoices(cfg, { cached = false } = {}) {
|
|
86
159
|
const id = cfg.model.id;
|
|
87
160
|
let info = null;
|
|
88
161
|
if (isGpt(id) && cfg.model.provider === GATEWAY_PROVIDER) {
|
|
89
162
|
const login = gatewayLogin(cfg.gatewayUrl);
|
|
90
|
-
|
|
163
|
+
const kept = cached ? keptGatewayModels(login) : null;
|
|
164
|
+
if (kept) info = kept.find((m) => m.id === id) || null;
|
|
165
|
+
else try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: !cached })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
|
|
91
166
|
}
|
|
92
167
|
const levels = effortLevels(id, info);
|
|
93
168
|
const configured = cfg.configuredEffort;
|
|
@@ -219,7 +294,7 @@ export function buildCommands(app) {
|
|
|
219
294
|
argHint: '[force]',
|
|
220
295
|
description: "Restart to load changes to the program's own source code (the conversation continues)",
|
|
221
296
|
async run(args) {
|
|
222
|
-
if (!canRestart()) {
|
|
297
|
+
if (!app.canRestart()) {
|
|
223
298
|
out(c.red(`Restarting needs an interactive session started with \`${APP_NAME}\` (not -p, and without CLAUDE_PRO_NO_SUPERVISOR). Quit and start it again.`));
|
|
224
299
|
return;
|
|
225
300
|
}
|
|
@@ -400,16 +475,11 @@ export function buildCommands(app) {
|
|
|
400
475
|
app.screen.schedule();
|
|
401
476
|
}
|
|
402
477
|
};
|
|
403
|
-
// The gateway connected: this session goes online there at once, for
|
|
404
|
-
// it (and can steer it, unless CLAUDE_PRO_REMOTE_COMMANDS=0) only with remote control on (/rc).
|
|
478
|
+
// The gateway connected: this session goes online there at once, for tasks from your other computers and contacts.
|
|
405
479
|
const goOnline = async () => {
|
|
406
480
|
const remote = await app.syncRemote();
|
|
407
481
|
if (!remote) return;
|
|
408
|
-
const page =
|
|
409
|
-
? 'sessions on your other computers and your contacts can send it tasks; /rc lets the web page (远程控制) show and steer it'
|
|
410
|
-
: remote.commands?.length
|
|
411
|
-
? 'its web page shows it and can send it messages and commands (CLAUDE_PRO_REMOTE_COMMANDS=0 makes the page read-only)'
|
|
412
|
-
: 'the read-only web page shows it';
|
|
482
|
+
const page = 'sessions on your other computers and your contacts can send it tasks';
|
|
413
483
|
out(remote.registered
|
|
414
484
|
? `${c.green('⇄')} This session is online at the gateway: ${page}.`
|
|
415
485
|
: c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
|
|
@@ -565,6 +635,9 @@ export function buildCommands(app) {
|
|
|
565
635
|
const kept = models.length ? models : choice !== KEEP ? [{ id: choice }] : [];
|
|
566
636
|
saveConnection(info.id, {
|
|
567
637
|
...(info.custom ? { custom: true, name: info.name, protocol: info.protocol, baseUrl: info.baseUrl } : {}),
|
|
638
|
+
// (another account of a provider stays one, with the name the user gave it)
|
|
639
|
+
...(existing?.preset ? { preset: existing.preset, ...(existing.baseUrl ? { protocol: existing.protocol, baseUrl: existing.baseUrl } : {}) } : {}),
|
|
640
|
+
...(existing?.name && !info.custom ? { name: existing.name } : {}),
|
|
568
641
|
apiKey: key.apiKey,
|
|
569
642
|
authHeader: info.protocol === 'openai' ? 'bearer' : authHeader || 'x-api-key',
|
|
570
643
|
...(Object.keys(quirks).length ? { quirks } : {}),
|
|
@@ -623,6 +696,8 @@ export function buildCommands(app) {
|
|
|
623
696
|
{ label: `${mark(gatewayIn)}7bit.fun`, value: GATEWAY_PROVIDER, description: 'the gateway: Claude and GPT models, balance, the web page, your other computers' },
|
|
624
697
|
...PRESETS.map((p) => ({ label: `${mark(Boolean(connections[p.id]))}${p.name}`, value: p.id, description: `${protocolName(p.protocol)} protocol · ${hostOf(p.baseUrl)}` })),
|
|
625
698
|
...Object.entries(connections).filter(([, conn]) => conn?.custom).map(([id, conn]) => ({ label: `${mark(true)}${conn.name || id}`, value: id, description: `your own · ${protocolName(conn.protocol)} protocol · ${hostOf(conn.baseUrl)}` })),
|
|
699
|
+
// (the other accounts added in the web console: their key replaced here)
|
|
700
|
+
...Object.entries(connections).filter(([id, conn]) => conn?.preset && providerInfo(id, connections)).map(([id, conn]) => ({ label: `${mark(true)}${conn.name || id}`, value: id, description: `${id}/<model> · another account` })),
|
|
626
701
|
{ label: ' Your own (Anthropic-compatible)', value: '__custom_anthropic__', description: 'any endpoint with POST /v1/messages' },
|
|
627
702
|
{ label: ' Your own (OpenAI-compatible)', value: '__custom_openai__', description: 'any endpoint with POST /chat/completions: relays, LM Studio, vLLM…' },
|
|
628
703
|
],
|
|
@@ -891,19 +966,109 @@ export function buildCommands(app) {
|
|
|
891
966
|
},
|
|
892
967
|
});
|
|
893
968
|
|
|
969
|
+
// The local web console, and its 远程访问 (https://<通讯号>.7bit.fun with a password, see web/remote-access.js).
|
|
894
970
|
add({
|
|
895
|
-
name: '
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
description: 'Remote control: the gateway\'s web page (远程控制) shows this session and can steer it; /rc off stops that',
|
|
971
|
+
name: 'web',
|
|
972
|
+
argHint: '[remote [on|off|password|logout]]',
|
|
973
|
+
description: 'Open the web console in your browser; /web remote on reaches it from your phone at <通讯号>.7bit.fun with a password',
|
|
899
974
|
async run(args) {
|
|
900
|
-
const
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
975
|
+
const [what = '', action = ''] = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
976
|
+
const web = await import('./web/server.js');
|
|
977
|
+
if (what === 'remote') return remoteAccess(web, action);
|
|
978
|
+
if (what) { out(c.red('/web, or /web remote [on|off|password|logout]')); return; }
|
|
979
|
+
out(c.dim('Starting the web console…'));
|
|
980
|
+
try {
|
|
981
|
+
const { url, port } = await web.ensureWebServer();
|
|
982
|
+
const opened = web.openBrowser(url);
|
|
983
|
+
out(`${c.green('✔')} Web console: ${c.blue(`http://127.0.0.1:${port}`)}${opened ? c.dim(' (opened in your browser)') : ''}`);
|
|
984
|
+
if (!opened) out(c.dim(`Open this link to log in: ${url}`));
|
|
985
|
+
} catch (e) {
|
|
986
|
+
out(c.red(`Could not start the web console: ${e.message}`));
|
|
987
|
+
}
|
|
904
988
|
},
|
|
905
989
|
});
|
|
906
990
|
|
|
991
|
+
async function askPassword(ra) {
|
|
992
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
993
|
+
const first = await app.showDialog(new TextInputDialog({
|
|
994
|
+
title: '远程访问密码',
|
|
995
|
+
body: [`在手机或别的电脑上打开控制台时要输入它。至少 ${ra.MIN_PASSWORD} 位(空格不算);它能让人在这台电脑上执行命令,请用强密码。`, c.dim('只在这台电脑上保存它的哈希,网关不知道它。')],
|
|
996
|
+
question: '密码:',
|
|
997
|
+
secret: true,
|
|
998
|
+
validate: (t) => (t.replace(/\s+/g, '').length < ra.MIN_PASSWORD ? `至少 ${ra.MIN_PASSWORD} 位` : null),
|
|
999
|
+
}));
|
|
1000
|
+
if (first === null) return null;
|
|
1001
|
+
const again = await app.showDialog(new TextInputDialog({ title: '远程访问密码', body: ['再输一次。'], question: '密码:', secret: true }));
|
|
1002
|
+
if (again === null) return null;
|
|
1003
|
+
if (again === first) return first;
|
|
1004
|
+
out(c.yellow('两次输入不一样,再来一次。'));
|
|
1005
|
+
}
|
|
1006
|
+
return null;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// What the console server says of 远程访问 (GET /api/remote), started if need be.
|
|
1010
|
+
async function remoteStatus(web, { start = true, waitOnline = 0 } = {}) {
|
|
1011
|
+
let state = null;
|
|
1012
|
+
try { state = JSON.parse(fs.readFileSync(web.stateFile(), 'utf8')); } catch { /* not started */ }
|
|
1013
|
+
if (start) state = { ...state, ...(await web.ensureWebServer()) };
|
|
1014
|
+
const until = Date.now() + waitOnline;
|
|
1015
|
+
for (;;) {
|
|
1016
|
+
try {
|
|
1017
|
+
const token = JSON.parse(fs.readFileSync(web.stateFile(), 'utf8')).token;
|
|
1018
|
+
const res = await fetch(`http://127.0.0.1:${state.port}/api/remote`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(3000) });
|
|
1019
|
+
const view = await res.json();
|
|
1020
|
+
if (Date.now() >= until || view.tunnel?.status === 'online' || view.tunnel?.status === 'error') return view;
|
|
1021
|
+
} catch (e) { if (Date.now() >= until) throw e; }
|
|
1022
|
+
await new Promise((r) => setTimeout(r, 700));
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
async function remoteAccess(web, action) {
|
|
1027
|
+
const ra = await import('./web/remote-access.js');
|
|
1028
|
+
const cfg = app.runtime.config;
|
|
1029
|
+
if (action === 'off') {
|
|
1030
|
+
ra.setEnabled(false);
|
|
1031
|
+
out(`${c.green('✔')} 远程访问已关闭:${c.dim('外网打不开这台电脑的控制台了(本机的 /web 照常可用)。')}`);
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
if (action === 'logout') {
|
|
1035
|
+
ra.endAllSessions();
|
|
1036
|
+
out(`${c.green('✔')} 所有远程登录的设备都已退出,下次要重新输密码。`);
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (action === 'password') {
|
|
1040
|
+
const pw = await askPassword(ra);
|
|
1041
|
+
if (!pw) { out(c.dim('密码没有改。')); return; }
|
|
1042
|
+
ra.setPassword(pw);
|
|
1043
|
+
out(`${c.green('✔')} 密码已修改,所有远程登录的设备都已退出。`);
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
if (action === 'on') {
|
|
1047
|
+
if (!gatewayLogin(cfg.gatewayUrl)) { out(c.red(`远程访问通过 7bit.fun 网关:先 /connect 7bit.fun 连上网关。`)); return; }
|
|
1048
|
+
if (!ra.hasPassword()) {
|
|
1049
|
+
const pw = await askPassword(ra);
|
|
1050
|
+
if (!pw) { out(c.dim('远程访问没有开启。')); return; }
|
|
1051
|
+
ra.setPassword(pw);
|
|
1052
|
+
}
|
|
1053
|
+
ra.setEnabled(true);
|
|
1054
|
+
out(c.dim('正在连接网关…'));
|
|
1055
|
+
} else if (action) { out(c.red('/web remote [on|off|password|logout]')); return; }
|
|
1056
|
+
const d = ra.readRemote();
|
|
1057
|
+
if (!d.enabled) {
|
|
1058
|
+
out([`远程访问:${c.dim('关闭')}`, c.dim('/web remote on 开启:在手机上打开 https://<你的通讯号>.7bit.fun,输入密码就能用这台电脑的 claude-pro 控制台。')]);
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
let view;
|
|
1062
|
+
try { view = await remoteStatus(web, { waitOnline: action === 'on' ? 12_000 : 0 }); } catch (e) { out(c.red(`控制台没有启动:${e.message}`)); return; }
|
|
1063
|
+
const t = view.tunnel || {};
|
|
1064
|
+
const lines = [];
|
|
1065
|
+
if (t.status === 'online') lines.push(`${c.green('✔')} 远程访问已开启:${c.bold(c.blue(`https://${t.host}`))}`, c.dim('在手机上打开它,输入密码。电脑休眠或关机时打不开;claude-pro 的任何会话启动时都会把它重新接上。'));
|
|
1066
|
+
else if (t.status === 'error') lines.push(c.red(`远程访问没有接上:${t.error}`));
|
|
1067
|
+
else lines.push(c.yellow(`远程访问正在连接网关…${t.error ? c.dim(`(${t.error})`) : ''}`));
|
|
1068
|
+
lines.push(c.dim(`登录着的设备 ${view.sessions?.length || 0} 台 · /web remote logout 让它们全部退出 · /web remote password 改密码 · /web remote off 关闭`));
|
|
1069
|
+
out(lines);
|
|
1070
|
+
}
|
|
1071
|
+
|
|
907
1072
|
// 通讯录 at the gateway: other people's accounts whose claude-pro sessions and this account's may send each other
|
|
908
1073
|
// tasks, once both sides agreed. Each account has a public 通讯号 (handle) that the others add it by.
|
|
909
1074
|
const CONTACT_LABELS = { incoming: c.yellow('asks to be your contact'), outgoing: c.dim('waiting for them to accept'), accepted: c.green('contact'), blocked: c.red('blocked') };
|
|
@@ -1124,7 +1289,7 @@ export function buildCommands(app) {
|
|
|
1124
1289
|
name: 'bashes',
|
|
1125
1290
|
description: 'List background shells',
|
|
1126
1291
|
run() {
|
|
1127
|
-
const list = listBackgroundShells();
|
|
1292
|
+
const list = listBackgroundShells(app.config.owner);
|
|
1128
1293
|
out(list.length ? list.map((b) => `${c.bold(b.id)} ${b.status}${b.exitCode !== null ? ` (exit ${b.exitCode})` : ''} ${c.dim(truncate(b.command, 60))}`) : [c.dim('No background shells')]);
|
|
1129
1294
|
},
|
|
1130
1295
|
});
|
package/src/config.js
CHANGED
|
@@ -66,8 +66,7 @@ export const BASIC_SETTINGS = {
|
|
|
66
66
|
// unrelated env entries; those are left alone, but are not advertised as configuration of this program.
|
|
67
67
|
export const KNOWN_KEYS = {
|
|
68
68
|
CLAUDE_PRO_GATEWAY_URL: `Gateway address (default ${GATEWAY_DEFAULT_URL})`,
|
|
69
|
-
CLAUDE_PRO_ONLINE: 'Set to 0 to keep interactive sessions off the gateway. Otherwise a session is online
|
|
70
|
-
CLAUDE_PRO_REMOTE_COMMANDS: 'Set to 0 to make this computer\'s sessions read-only on the gateway\'s web page: it can watch them, but not send them messages, answer their questions, stop them, switch model or effort, or change their directory (default: on; read when a session goes online)',
|
|
69
|
+
CLAUDE_PRO_ONLINE: 'Set to 0 to keep interactive sessions off the gateway. Otherwise a session is online at the gateway whenever this computer is logged in, and sessions on your other computers (@computer/name) and your contacts can send it tasks',
|
|
71
70
|
CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
|
|
72
71
|
|
|
73
72
|
CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default 48000; lowered automatically if the gateway allows less)',
|
|
@@ -485,6 +484,22 @@ const userSettingsFile = () => path.join(CONFIG_DIR, 'settings.json');
|
|
|
485
484
|
// Kept under the name of the provider they were made with, from when there were others: the gateway's.
|
|
486
485
|
const REMEMBERED_KEY = 'gateway';
|
|
487
486
|
|
|
487
|
+
// The models ticked in the web console's 模型列表 (provider/model): its model menus offer only these (and the
|
|
488
|
+
// default and the model in use); none ticked, all. CONFIG_DIR/picker-models.json, {models: [...]}.
|
|
489
|
+
const pickedFile = () => path.join(CONFIG_DIR, 'picker-models.json');
|
|
490
|
+
export function pickedModels() {
|
|
491
|
+
const list = readJson(pickedFile())?.models;
|
|
492
|
+
return Array.isArray(list) ? list.filter((m) => typeof m === 'string' && m.trim()) : [];
|
|
493
|
+
}
|
|
494
|
+
export function savePickedModels(models) {
|
|
495
|
+
const list = [...new Set((Array.isArray(models) ? models : []).filter((m) => typeof m === 'string' && /^[^\s\x00-\x1f]{1,200}$/.test(m)))].slice(0, 500);
|
|
496
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
497
|
+
const tmp = `${pickedFile()}.${process.pid}.tmp`;
|
|
498
|
+
fs.writeFileSync(tmp, JSON.stringify({ models: list }, null, 2));
|
|
499
|
+
fs.renameSync(tmp, pickedFile());
|
|
500
|
+
return list;
|
|
501
|
+
}
|
|
502
|
+
|
|
488
503
|
function rememberedChoices() {
|
|
489
504
|
const entry = readJson(userSettingsFile())?.remembered?.[REMEMBERED_KEY];
|
|
490
505
|
return entry && typeof entry === 'object' ? entry : {};
|
package/src/gateway.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import fs from 'node:fs';
|
|
10
10
|
import path from 'node:path';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
11
12
|
import { CONFIG_DIR, GATEWAY_DEFAULT_URL, normalizeGatewayUrl, noteServedModels, readGatewayLogin, forgetGatewayLogin } from './config.js';
|
|
12
13
|
|
|
13
14
|
export { GATEWAY_DEFAULT_URL, normalizeGatewayUrl };
|
|
@@ -66,6 +67,37 @@ const MODELS_MAX_AGE_MS = 10 * 60_000;
|
|
|
66
67
|
|
|
67
68
|
const listKey = ({ url, apiKey }) => `${normalizeGatewayUrl(url)}\n${apiKey}`;
|
|
68
69
|
|
|
70
|
+
// The last list of each gateway and key, on disk too (cache/gateway-model-lists.json; the key only as a hash): the
|
|
71
|
+
// web console's pickers read it instead of asking the gateway each time they open, also after a restart. Refreshed
|
|
72
|
+
// by every fetch, and by the console's 刷新模型列表 button.
|
|
73
|
+
const listFile = () => path.join(process.env.CLAUDE_PRO_CONFIG_DIR || CONFIG_DIR, 'cache', 'gateway-model-lists.json');
|
|
74
|
+
const diskKey = ({ url, apiKey }) => `${normalizeGatewayUrl(url)} ${crypto.createHash('sha256').update(String(apiKey)).digest('hex').slice(0, 16)}`;
|
|
75
|
+
const readListFile = () => { try { return JSON.parse(fs.readFileSync(listFile(), 'utf8')) || {}; } catch { return {}; } };
|
|
76
|
+
function keepListOnDisk(login, list) {
|
|
77
|
+
try {
|
|
78
|
+
const all = readListFile();
|
|
79
|
+
all[diskKey(login)] = { at: Date.now(), list };
|
|
80
|
+
fs.mkdirSync(path.dirname(listFile()), { recursive: true });
|
|
81
|
+
const tmp = `${listFile()}.${process.pid}.tmp`;
|
|
82
|
+
fs.writeFileSync(tmp, JSON.stringify(all));
|
|
83
|
+
fs.renameSync(tmp, listFile());
|
|
84
|
+
} catch { /* kept in memory still */ }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// The list kept for this login (in memory, else on disk) and when it was fetched, without asking the gateway:
|
|
88
|
+
// {list, at}, or null when there is none yet.
|
|
89
|
+
export function keptGatewayList(login) {
|
|
90
|
+
if (!login?.url || !login?.apiKey) return null;
|
|
91
|
+
const key = listKey(login);
|
|
92
|
+
if (modelLists.has(key)) return modelLists.get(key);
|
|
93
|
+
const kept = readListFile()[diskKey(login)];
|
|
94
|
+
if (!Array.isArray(kept?.list)) return null;
|
|
95
|
+
const entry = { list: kept.list, at: kept.at || 0 };
|
|
96
|
+
modelLists.set(key, entry);
|
|
97
|
+
return entry;
|
|
98
|
+
}
|
|
99
|
+
export const keptGatewayModels = (login) => keptGatewayList(login)?.list || null;
|
|
100
|
+
|
|
69
101
|
// One GET /v1/models at a time per key. It carries only its own timeout: a caller that gives up (its signal) leaves
|
|
70
102
|
// it running for the others and the cache (see untilAborted).
|
|
71
103
|
function requestModels(key, { url, apiKey }, { fetchImpl, timeoutMs }) {
|
|
@@ -83,6 +115,7 @@ function requestModels(key, { url, apiKey }, { fetchImpl, timeoutMs }) {
|
|
|
83
115
|
modelLists.set(key, { list, at: Date.now() });
|
|
84
116
|
modelListFailures.delete(key);
|
|
85
117
|
noteServedModels(base, list);
|
|
118
|
+
keepListOnDisk({ url, apiKey }, list);
|
|
86
119
|
return list;
|
|
87
120
|
}, (e) => {
|
|
88
121
|
modelListFailures.set(key, { at: Date.now(), error: e });
|
package/src/live.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// The live view of a session for the local web console (claude-pro web, see web/server.js): the same transcript
|
|
2
|
+
// model as the gateway's page (applyEvent in remote.js), served by the session's own peer server on 127.0.0.1
|
|
3
|
+
// (see PeerNode) as a stream of server-sent events. Nothing is kept while nobody watches: the first viewer gets a
|
|
4
|
+
// snapshot built from the conversation, and the events after it.
|
|
5
|
+
|
|
6
|
+
import { applyEvent, hydrate, snapshotItems } from './remote.js';
|
|
7
|
+
import { stripAnsi } from './ui/ansi.js';
|
|
8
|
+
|
|
9
|
+
const MAX_ITEMS = 800;
|
|
10
|
+
const FLUSH_MS = 100;
|
|
11
|
+
const STATUS_MS = 500;
|
|
12
|
+
const PING_MS = 15_000;
|
|
13
|
+
|
|
14
|
+
function progressTail(text) {
|
|
15
|
+
const lines = String(text || '').slice(-6000).replace(/\r\n/g, '\n').trimEnd().split('\n');
|
|
16
|
+
return lines.slice(-8).map((l) => l.replace(/^.*\r/, '').slice(0, 400)).join('\n');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// (the time a turn has run changes all the time: the page counts it on from when the status came)
|
|
20
|
+
const statusKey = (status) => JSON.stringify({ ...status, elapsed: 0 });
|
|
21
|
+
|
|
22
|
+
export class LiveFeed {
|
|
23
|
+
// seed(): the transcript items of the conversation as it is; status(): what the page shows below it.
|
|
24
|
+
constructor({ seed, status }) {
|
|
25
|
+
this.seed = seed;
|
|
26
|
+
this.statusOf = status;
|
|
27
|
+
this.clients = new Set();
|
|
28
|
+
this.state = null; // only while someone watches
|
|
29
|
+
this.events = [];
|
|
30
|
+
this.progress = new Map();
|
|
31
|
+
this.flushTimer = null;
|
|
32
|
+
this.statusTimer = null;
|
|
33
|
+
this.pingTimer = null;
|
|
34
|
+
this.lastStatus = '';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
get active() { return this.clients.size > 0; }
|
|
38
|
+
|
|
39
|
+
status() {
|
|
40
|
+
try { return this.statusOf?.() || {}; } catch (e) { return { error: e.message }; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// A response that stays open: a snapshot, then batches of events and the status whenever it changes.
|
|
44
|
+
attach(res) {
|
|
45
|
+
res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache', connection: 'keep-alive' });
|
|
46
|
+
res.socket?.setNoDelay?.(true);
|
|
47
|
+
if (!this.state) this.state = hydrate(this.items());
|
|
48
|
+
this.clients.add(res);
|
|
49
|
+
const status = this.status();
|
|
50
|
+
this.lastStatus = statusKey(status);
|
|
51
|
+
this.write(res, { t: 'snapshot', items: snapshotItems(this.state.items), status });
|
|
52
|
+
res.on('close', () => this.detach(res));
|
|
53
|
+
this.statusTimer ??= setInterval(() => this.checkStatus(), STATUS_MS);
|
|
54
|
+
this.pingTimer ??= setInterval(() => { for (const r of this.clients) r.write(': ping\n\n'); }, PING_MS);
|
|
55
|
+
this.statusTimer.unref?.();
|
|
56
|
+
this.pingTimer.unref?.();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
detach(res) {
|
|
60
|
+
this.clients.delete(res);
|
|
61
|
+
if (this.clients.size) return;
|
|
62
|
+
clearInterval(this.statusTimer);
|
|
63
|
+
clearInterval(this.pingTimer);
|
|
64
|
+
clearTimeout(this.flushTimer);
|
|
65
|
+
this.statusTimer = this.pingTimer = this.flushTimer = null;
|
|
66
|
+
this.state = null;
|
|
67
|
+
this.events = [];
|
|
68
|
+
this.progress.clear();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
items() {
|
|
72
|
+
try { return this.seed?.() || []; } catch { return []; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
write(res, message) {
|
|
76
|
+
if (res.destroyed || res.writableEnded) return;
|
|
77
|
+
if (res.writableLength > 8 * 1024 * 1024) { res.destroy(); return; }
|
|
78
|
+
res.write(`data: ${JSON.stringify(message)}\n\n`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
broadcast(message) { for (const res of this.clients) this.write(res, message); }
|
|
82
|
+
|
|
83
|
+
emit(ev) {
|
|
84
|
+
if (!this.state) return;
|
|
85
|
+
applyEvent(this.state, ev);
|
|
86
|
+
if (ev.t === 'done') this.progress.delete(ev.id);
|
|
87
|
+
if (this.state.items.length > MAX_ITEMS) this.state.items.splice(0, this.state.items.length - MAX_ITEMS + 100);
|
|
88
|
+
const last = this.events[this.events.length - 1];
|
|
89
|
+
if (ev.t === 'delta' && last?.t === 'delta' && last.kind === ev.kind) last.text += ev.text;
|
|
90
|
+
else this.events.push({ ...ev });
|
|
91
|
+
this.scheduleFlush();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Lines the terminal printed that no other event stands for.
|
|
95
|
+
output(lines) {
|
|
96
|
+
if (!this.state) return;
|
|
97
|
+
const last = this.state.items[this.state.items.length - 1];
|
|
98
|
+
if (!lines.length || (last?.k !== 'output' && lines.every((l) => !stripAnsi(l).trim()))) return;
|
|
99
|
+
this.emit({ t: 'output', lines });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
toolProgress(id, entry) {
|
|
103
|
+
if (!this.state || !id) return;
|
|
104
|
+
this.progress.set(id, entry);
|
|
105
|
+
this.scheduleFlush();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// The conversation was replaced (/clear, /resume, /rewind): the pages start again from it.
|
|
109
|
+
resync() {
|
|
110
|
+
if (!this.state) return;
|
|
111
|
+
this.state = hydrate(this.items());
|
|
112
|
+
this.events = [];
|
|
113
|
+
this.progress.clear();
|
|
114
|
+
this.broadcast({ t: 'snapshot', items: snapshotItems(this.state.items), status: this.status() });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
scheduleFlush() {
|
|
118
|
+
if (this.flushTimer) return;
|
|
119
|
+
this.flushTimer = setTimeout(() => { this.flushTimer = null; this.flush(); }, FLUSH_MS);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
flush() {
|
|
123
|
+
if (!this.state) return;
|
|
124
|
+
for (const [id, entry] of this.progress) {
|
|
125
|
+
const ev = { t: 'progress', id, text: progressTail(entry.progress) };
|
|
126
|
+
if (applyEvent(this.state, ev)) this.events.push(ev);
|
|
127
|
+
}
|
|
128
|
+
this.progress.clear();
|
|
129
|
+
if (this.events.length) this.broadcast({ t: 'batch', events: this.events.splice(0) });
|
|
130
|
+
this.checkStatus();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
checkStatus() {
|
|
134
|
+
if (!this.clients.size) return;
|
|
135
|
+
const status = this.status();
|
|
136
|
+
const key = statusKey(status);
|
|
137
|
+
if (key === this.lastStatus) return;
|
|
138
|
+
this.lastStatus = key;
|
|
139
|
+
this.broadcast({ t: 'status', status });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
close() {
|
|
143
|
+
const open = [...this.clients];
|
|
144
|
+
this.clients.clear();
|
|
145
|
+
this.detach(null);
|
|
146
|
+
for (const res of open) { try { res.end(); } catch { /* gone */ } }
|
|
147
|
+
}
|
|
148
|
+
}
|
package/src/main.js
CHANGED
|
@@ -25,16 +25,17 @@ Options:
|
|
|
25
25
|
--verbose Show detailed tool output
|
|
26
26
|
--no-mcp Do not start MCP servers
|
|
27
27
|
--name <name> Name this session, as /rename does (other sessions reach it with @name)
|
|
28
|
-
--rc, --remote-control Turn remote control on at the start, as /rc does (the gateway's web page shows the session)
|
|
29
28
|
-v, --version Print version
|
|
30
29
|
-h, --help Show help
|
|
31
30
|
|
|
32
31
|
There are no permission prompts: every tool runs immediately (full access). File edits are
|
|
33
32
|
checkpointed per prompt, and /rewind in a session undoes them. The old flags
|
|
34
33
|
--dangerously-skip-permissions, --permission-mode, --allowedTools and --disallowedTools
|
|
35
|
-
are accepted and ignored, and so
|
|
34
|
+
are accepted and ignored, and so are --plan (there is no plan mode: ask for a plan in the message) and --rc
|
|
35
|
+
(the gateway's remote control page is gone: claude-pro web is the console).
|
|
36
36
|
|
|
37
37
|
Commands:
|
|
38
|
+
claude-pro web [--no-open] Open the web console (settings, providers, every conversation, live sessions)
|
|
38
39
|
claude-pro config list [--advanced] Show ordinary settings (add --advanced for optional controls)
|
|
39
40
|
claude-pro config set <KEY> <VALUE> [--project|--local] Save a setting (default: ~/.claude-pro/settings.json)
|
|
40
41
|
claude-pro config unset <KEY> [--project|--local]
|
|
@@ -74,7 +75,7 @@ function parseArgs(argv) {
|
|
|
74
75
|
case '--system-prompt-file': flags.systemPromptFile = next(); break;
|
|
75
76
|
case '--verbose': flags.verbose = true; break;
|
|
76
77
|
case '--no-mcp': flags.noMcp = true; break;
|
|
77
|
-
case '--remote-control': case '--rc':
|
|
78
|
+
case '--remote-control': case '--rc': break; // remote control (the gateway's page) is gone: accepted and ignored
|
|
78
79
|
case '--name': flags.name = next(); break;
|
|
79
80
|
case '-v': case '--version': flags.version = true; break;
|
|
80
81
|
case '-h': case '--help': flags.help = true; break;
|
|
@@ -165,6 +166,7 @@ const REMOVED_COMMANDS = new Set(['host', 'attach', 'connect']);
|
|
|
165
166
|
export async function main(argv) {
|
|
166
167
|
let cwd = process.cwd();
|
|
167
168
|
if (argv[0] === 'config') return configCommand(argv.slice(1), cwd);
|
|
169
|
+
if (argv[0] === 'web') return (await import('./web/server.js')).webCommand(argv.slice(1));
|
|
168
170
|
if (REMOVED_COMMANDS.has(argv[0])) {
|
|
169
171
|
process.stderr.write(`claude-pro ${argv[0]} was removed (the computer service, attach and connect are no longer part of claude-pro). To send this as a prompt, quote it: claude-pro "${argv.join(' ')}"\n`);
|
|
170
172
|
return 2;
|