@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/src/web/api.js ADDED
@@ -0,0 +1,881 @@
1
+ // The local web console's API (see server.js): each route is [method, pattern, handler(req, params, body, url)]
2
+ // answering with a value (sent as JSON) or {raw: {type, data, name?}} for a file, or throwing httpError.
3
+
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { spawn, execFile, execFileSync } from 'node:child_process';
8
+ import {
9
+ CONFIG_DIR, INSTALL_DIR, SOURCE_CHECKOUT, VERSION, BASIC_SETTINGS, KNOWN_KEYS, loadConfig, settingsFiles,
10
+ writeConfigSetting, unsetConfigSetting, rememberChoice, updateSettingsFile, applyRememberedChoices, pickedModels, savePickedModels,
11
+ } from '../config.js';
12
+ import {
13
+ PRESETS, GATEWAY_PROVIDER, readConnections, saveConnection, removeConnection, providerInfo, connectedProviders,
14
+ listProviderModels, testProviderModel, modelsDevCatalogue, enrichModels, cleanProviderId, nextInstanceId,
15
+ normalizeBaseUrl, validBaseUrl,
16
+ } from '../providers.js';
17
+ import { gatewayLogin, loginWithKey, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, keptGatewayList } from '../gateway.js';
18
+ import { checkForUpdate, installUpdate } from '../updater.js';
19
+ import { loadAgents, loadSkills, loadCustomCommands } from '../agents.js';
20
+ import { webModelChoices, effortChoices as sessionEfforts, refreshModelLists } from '../commands.js';
21
+ import { setArchived, archivedSessions, projectDir } from '../session.js';
22
+ import {
23
+ listAllSessions, sessionDetail, sessionImage, sessionToolOutput, sessionMarkdown, renameSession, trashSession, listTrash, restoreSession,
24
+ purgeTrash, runningSessions, findPeerById, peerRequest, usageReport, dirSize, projectsRoot, httpError,
25
+ } from './data.js';
26
+
27
+ const mask = (key) => {
28
+ const k = String(key || '');
29
+ if (!k) return '';
30
+ return k.length <= 10 ? `${k.slice(0, 2)}…` : `${k.slice(0, 6)}…${k.slice(-4)}`;
31
+ };
32
+ const isWin = process.platform === 'win32';
33
+ const home = os.homedir();
34
+
35
+ // ---------------------------------------------------------------- projects and files
36
+
37
+ // The directories the conversations ran in (their projects), with their state directory: what the memory and
38
+ // extension pages list, and where their files may be edited.
39
+ function knownProjects() {
40
+ const byCwd = new Map();
41
+ const keyOf = (cwd) => (isWin ? path.resolve(cwd).toLowerCase() : path.resolve(cwd));
42
+ for (const s of listAllSessions()) {
43
+ if (!s.cwd) continue;
44
+ const key = keyOf(s.cwd);
45
+ const p = byCwd.get(key);
46
+ if (!p) byCwd.set(key, { cwd: s.cwd, dir: s.dir, sessions: 1, lastUsed: s.mtime });
47
+ else { p.sessions++; p.lastUsed = Math.max(p.lastUsed, s.mtime); }
48
+ }
49
+ // the folders added to the 工作区, also before a conversation ran there
50
+ for (const w of addedWorkspaces()) {
51
+ if (!byCwd.has(keyOf(w.cwd)) && fs.existsSync(w.cwd)) byCwd.set(keyOf(w.cwd), { cwd: w.cwd, dir: path.basename(projectDir(w.cwd)), sessions: 0, lastUsed: w.added || 0 });
52
+ }
53
+ return [...byCwd.values()].sort((a, b) => b.lastUsed - a.lastUsed);
54
+ }
55
+
56
+ // 工作区: folders the user added to the sidebar (添加工作区), listed with the projects that have conversations, also
57
+ // before the first one runs there. CONFIG_DIR/workspaces.json, {dirs: [{cwd, added}]}, newest first.
58
+ const workspacesFile = () => path.join(CONFIG_DIR, 'workspaces.json');
59
+ function addedWorkspaces() {
60
+ let list = null;
61
+ try { list = JSON.parse(fs.readFileSync(workspacesFile(), 'utf8'))?.dirs; } catch { /* none yet */ }
62
+ return Array.isArray(list) ? list.filter((w) => typeof w?.cwd === 'string' && path.isAbsolute(w.cwd)) : [];
63
+ }
64
+ function saveWorkspaces(dirs) {
65
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
66
+ const tmp = `${workspacesFile()}.${process.pid}.tmp`;
67
+ fs.writeFileSync(tmp, JSON.stringify({ dirs }, null, 2));
68
+ fs.renameSync(tmp, workspacesFile());
69
+ return dirs;
70
+ }
71
+ function addWorkspace(body) {
72
+ const raw = typeof body?.cwd === 'string' ? body.cwd.trim() : '';
73
+ if (!raw || !path.isAbsolute(raw) || (isWin && !windowsDrivePath(raw))) throw httpError(400, '无效的目录');
74
+ const cwd = path.resolve(raw);
75
+ let st = null;
76
+ try { st = fs.statSync(cwd); } catch { throw httpError(404, '目录不存在'); }
77
+ if (!st.isDirectory()) throw httpError(400, '这不是一个目录');
78
+ const rest = addedWorkspaces().filter((w) => !same(w.cwd, cwd));
79
+ return { cwd, workspaces: saveWorkspaces([{ cwd, added: Date.now() }, ...rest]) };
80
+ }
81
+ function removeWorkspace(body) {
82
+ const cwd = typeof body?.cwd === 'string' ? body.cwd : '';
83
+ if (!cwd) throw httpError(400, '无效的目录');
84
+ return { workspaces: saveWorkspaces(addedWorkspaces().filter((w) => !same(w.cwd, cwd))) };
85
+ }
86
+
87
+ const same = (a, b) => (isWin ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
88
+
89
+ const windowsDrivePath = (p) => typeof p === 'string' && /^[a-z]:[\\/]/i.test(p);
90
+ const explorerPath = () => path.join(process.env.SystemRoot || 'C:\\Windows', 'explorer.exe');
91
+ const isFile = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false })?.isFile() === true; } catch { return false; } };
92
+
93
+ function vscodePath() {
94
+ if (!isWin) return null;
95
+ const editions = [['Microsoft VS Code', 'Code.exe'], ['Microsoft VS Code Insiders', 'Code - Insiders.exe']];
96
+ const roots = [process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs'), process.env.ProgramFiles, process.env['ProgramFiles(x86)']].filter(windowsDrivePath);
97
+ for (const [folder, exe] of editions) {
98
+ for (const root of roots) {
99
+ const file = path.join(root, folder, exe);
100
+ if (isFile(file)) return file;
101
+ }
102
+ }
103
+ // A non-default install can be on PATH via its executable directory or via VS Code's bin directory.
104
+ for (const entry of (process.env.PATH || '').split(path.delimiter)) {
105
+ const dir = entry.replace(/^"(.*)"$/, '$1');
106
+ if (!windowsDrivePath(dir)) continue;
107
+ for (const root of path.basename(dir).toLowerCase() === 'bin' ? [dir, path.dirname(dir)] : [dir]) {
108
+ for (const [, exe] of editions) {
109
+ const file = path.join(root, exe);
110
+ if (isFile(file)) return file;
111
+ }
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+
117
+ let vscodeCache;
118
+ function vscodeAvailable() {
119
+ if (!vscodeCache || Date.now() >= vscodeCache.until) vscodeCache = { found: Boolean(vscodePath()), until: Date.now() + 60_000 };
120
+ return vscodeCache.found;
121
+ }
122
+
123
+ async function openProject(body) {
124
+ const { cwd, target } = body || {};
125
+ if (!isWin) throw httpError(409, '当前主机不支持这个操作');
126
+ if (target !== 'explorer' && target !== 'vscode') throw httpError(400, '不支持这个打开方式');
127
+ if (!windowsDrivePath(cwd)) throw httpError(400, '项目必须是 Windows 本地目录');
128
+ const known = knownProjects().some((p) => same(p.cwd, cwd)) || (await runningSessions()).some((s) => {
129
+ const dir = s.status?.cwd || s.cwd;
130
+ return dir && same(dir, cwd);
131
+ });
132
+ if (!known) throw httpError(404, '工作区里没有这个项目');
133
+ let dir;
134
+ try {
135
+ dir = fs.realpathSync.native(cwd);
136
+ if (!windowsDrivePath(dir) || !fs.statSync(dir).isDirectory()) throw new Error();
137
+ } catch { throw httpError(404, '项目目录不存在或不是本地文件夹'); }
138
+ const label = target === 'explorer' ? '资源管理器' : 'VS Code';
139
+ const exe = target === 'explorer' ? explorerPath() : vscodePath();
140
+ if (!exe) throw httpError(409, '没有检测到已安装的 VS Code');
141
+ // The browser never supplies the executable or a command line; only the checked directory is passed.
142
+ await new Promise((resolve, reject) => {
143
+ const env = { ...process.env };
144
+ delete env.ELECTRON_RUN_AS_NODE; // (set, Code.exe runs as plain Node and takes the folder for a script)
145
+ const child = spawn(exe, [dir], { cwd: path.dirname(exe), detached: true, stdio: 'ignore', env });
146
+ child.once('error', () => reject(httpError(500, `无法启动${label}`)));
147
+ child.once('spawn', () => { child.unref(); resolve(); });
148
+ });
149
+ return { opened: true };
150
+ }
151
+
152
+ // On the local Windows console only: the host's native directory picker, not a browser upload prompt.
153
+ let folderDialog;
154
+ function pickProjectDirectory() {
155
+ if (!isWin) throw httpError(409, '这台电脑没有可用的系统目录选择器');
156
+ if (folderDialog) throw httpError(409, '目录选择窗口已经打开');
157
+ const script = `
158
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
159
+ $ErrorActionPreference = 'Stop'
160
+ Add-Type -AssemblyName System.Windows.Forms
161
+ $owner = New-Object System.Windows.Forms.Form
162
+ $owner.TopMost = $true
163
+ $owner.ShowInTaskbar = $false
164
+ $owner.Opacity = 0
165
+ $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
166
+ $dialog.Description = '选择 claude-pro 项目目录'
167
+ try {
168
+ $owner.Show()
169
+ if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Write($dialog.SelectedPath) }
170
+ } finally { $dialog.Dispose(); $owner.Dispose() }
171
+ `;
172
+ const powershell = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
173
+ const args = ['-NoProfile', '-NoLogo', '-STA', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')];
174
+ folderDialog = new Promise((resolve, reject) => {
175
+ execFile(powershell, args, { windowsHide: true, timeout: 180_000, maxBuffer: 64 * 1024 }, (err, stdout) => {
176
+ if (err) reject(httpError(503, '系统目录选择器不可用,请从目录列表选择'));
177
+ else resolve({ cwd: stdout || null });
178
+ });
179
+ }).finally(() => { folderDialog = null; });
180
+ return folderDialog;
181
+ }
182
+
183
+ async function projectDirectories(cwd) {
184
+ if (!cwd) {
185
+ const paths = [home, process.cwd(), ...knownProjects().map((p) => p.cwd)];
186
+ const roots = new Map();
187
+ for (const dir of paths) {
188
+ if (!path.isAbsolute(dir) || (isWin && !windowsDrivePath(dir))) continue;
189
+ const root = path.parse(dir).root;
190
+ roots.set(isWin ? root.toLowerCase() : root, root);
191
+ }
192
+ return { cwd: null, dirs: [...new Set([...paths.slice(0, 2), ...roots.values()])].filter((dir) => !isWin || windowsDrivePath(dir)).map((dir) => ({ path: dir, name: dir })) };
193
+ }
194
+ if (!path.isAbsolute(cwd) || (isWin && !windowsDrivePath(cwd))) throw httpError(400, '不是本机目录');
195
+ try {
196
+ const dir = await fs.promises.realpath(cwd);
197
+ if (isWin && !windowsDrivePath(dir)) throw httpError(400, '不是本机目录');
198
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
199
+ const dirs = entries.filter((e) => e.isDirectory()).map((e) => ({ name: e.name, path: path.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
200
+ return { cwd: dir, parent: path.dirname(dir) === dir ? null : path.dirname(dir), dirs };
201
+ } catch (e) { throw httpError(e.status || 404, '无法读取这个目录,请选择其他目录'); }
202
+ }
203
+
204
+ const inside = (file, dir) => {
205
+ const rel = path.relative(dir, file);
206
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel);
207
+ };
208
+
209
+ // Whether the console may read and write `file`: instructions, memory, settings and extensions, of the user and of
210
+ // the known projects. Never the keys (gateway.json, providers.json), the conversations or anything else.
211
+ function editable(file) {
212
+ const f = path.resolve(file);
213
+ const ext = path.extname(f).toLowerCase();
214
+ const extDirs = (root) => ['skills', 'agents', 'commands'].some((d) => inside(f, path.join(root, d))) && ext === '.md';
215
+ if (same(f, path.join(CONFIG_DIR, 'CLAUDE.md')) || same(f, path.join(CONFIG_DIR, 'settings.json'))) return true;
216
+ if (extDirs(CONFIG_DIR)) return true;
217
+ if (inside(f, projectsRoot()) && ext === '.md' && path.basename(path.dirname(f)) === 'memory' && same(path.dirname(path.dirname(path.dirname(f))), projectsRoot())) return true;
218
+ for (const p of knownProjects()) {
219
+ const cwd = p.cwd;
220
+ if (!inside(f, cwd)) continue;
221
+ const names = ['CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md', '.mcp.json', path.join('.claude', 'CLAUDE.md'), path.join('.claude-pro', 'settings.json'), path.join('.claude-pro', 'settings.local.json')];
222
+ if (names.some((n) => same(f, path.join(cwd, n)))) return true;
223
+ if (extDirs(path.join(cwd, '.claude')) || extDirs(path.join(cwd, '.claude-pro'))) return true;
224
+ }
225
+ return false;
226
+ }
227
+
228
+ function checkedPath(p) {
229
+ if (typeof p !== 'string' || !p.trim()) throw httpError(400, 'path is required');
230
+ const file = path.resolve(p);
231
+ if (!editable(file)) throw httpError(403, '这个文件不能在控制台里打开');
232
+ return file;
233
+ }
234
+
235
+ function readFileInfo(file) {
236
+ let text = null;
237
+ let mtime = null;
238
+ try { text = fs.readFileSync(file, 'utf8'); mtime = fs.statSync(file).mtimeMs; } catch { /* not there yet */ }
239
+ return { path: file, exists: text !== null, text: text ?? '', mtime };
240
+ }
241
+
242
+ // ---------------------------------------------------------------- overview
243
+
244
+ async function overview() {
245
+ const config = loadConfig({ cwd: home });
246
+ const login = gatewayLogin(config.gatewayUrl);
247
+ const running = await runningSessions();
248
+ const sessions = listAllSessions();
249
+ let account = null;
250
+ let accountError = null;
251
+ if (login) {
252
+ try { account = await fetchGatewayAccount(login, { signal: AbortSignal.timeout(6000) }); } catch (e) { accountError = e.message; }
253
+ }
254
+ return {
255
+ version: VERSION, installDir: INSTALL_DIR, sourceCheckout: SOURCE_CHECKOUT, configDir: CONFIG_DIR, node: process.version,
256
+ platform: `${os.type()} ${os.release()}`, host: os.hostname(),
257
+ model: config.setting('model'), modelLabel: safe(() => config.model.label), effort: config.setting('effort'),
258
+ remembered: rememberedChoice(),
259
+ providers: connectedProviders().map((p) => ({ id: p.id, name: p.name, models: p.connection.models?.length || 0 })),
260
+ gateway: login ? { url: login.url, account: login.account || null, key: mask(login.apiKey), balance: account?.available_usd ?? account?.balance_usd ?? null, accountError } : null,
261
+ running: running.length,
262
+ busy: running.filter((r) => r.status?.turn).length,
263
+ sessions: sessions.length,
264
+ projects: new Set(sessions.map((s) => s.dir)).size,
265
+ storage: dirSize(projectsRoot()),
266
+ };
267
+ }
268
+
269
+ const safe = (fn) => { try { return fn(); } catch { return null; } };
270
+
271
+ function rememberedChoice() {
272
+ try {
273
+ const json = JSON.parse(fs.readFileSync(settingsFiles(home).user, 'utf8').replace(/^\uFEFF/, ''));
274
+ return json?.remembered?.gateway || {};
275
+ } catch { return {}; }
276
+ }
277
+
278
+ // ---------------------------------------------------------------- settings
279
+
280
+ function readJsonFile(file) {
281
+ try { return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); } catch { return null; }
282
+ }
283
+
284
+ // Every setting with its value in effect, where that comes from, and what each settings file holds. `project`: the
285
+ // directory whose project settings count (default: none, the user's own).
286
+ function settingsView(project) {
287
+ const cwd = project && fs.existsSync(project) ? project : home;
288
+ const config = loadConfig({ cwd });
289
+ const all = settingsFiles(cwd);
290
+ // without a project, only the user's file (the home directory's "project" settings would be the same file)
291
+ const files = cwd === home ? { user: all.user } : all;
292
+ const perFile = Object.fromEntries(Object.entries(files).map(([scope, file]) => [scope, { file, json: readJsonFile(file) }]));
293
+ const inFile = (json, key) => {
294
+ if (!json) return undefined;
295
+ if (Object.hasOwn(BASIC_SETTINGS, key)) return json[key] ?? (BASIC_SETTINGS[key].legacy ? json.env?.[BASIC_SETTINGS[key].legacy] : undefined);
296
+ return json.env?.[key];
297
+ };
298
+ const entry = (key, basic) => ({
299
+ key, basic,
300
+ description: basic ? BASIC_SETTINGS[key].description : KNOWN_KEYS[key],
301
+ default: basic ? BASIC_SETTINGS[key].default : null,
302
+ userOnly: Boolean(basic && BASIC_SETTINGS[key].userOnly),
303
+ value: safe(() => config.setting(key)) ?? null,
304
+ source: config.sources[key] || 'default',
305
+ scopes: Object.fromEntries(Object.entries(perFile).map(([scope, f]) => [scope, inFile(f.json, key) ?? null])),
306
+ });
307
+ return {
308
+ project: project && cwd === project ? cwd : null,
309
+ files,
310
+ remembered: rememberedChoice(),
311
+ entries: [...Object.keys(BASIC_SETTINGS).map((k) => entry(k, true)), ...Object.keys(KNOWN_KEYS).map((k) => entry(k, false))],
312
+ };
313
+ }
314
+
315
+ function scopeFile(scope, project) {
316
+ const cwd = project && fs.existsSync(project) ? project : null;
317
+ if (scope === 'user') return settingsFiles(home).user;
318
+ if (!cwd) throw httpError(400, '项目设置需要先选一个项目');
319
+ const files = settingsFiles(cwd);
320
+ if (!files[scope]) throw httpError(400, 'scope must be user, project or local');
321
+ return files[scope];
322
+ }
323
+
324
+ // ---------------------------------------------------------------- providers
325
+
326
+ function providersView() {
327
+ const connections = readConnections({ fresh: true });
328
+ const config = loadConfig({ cwd: home });
329
+ const login = gatewayLogin(config.gatewayUrl);
330
+ const shown = (info) => {
331
+ const c = info.connection;
332
+ return {
333
+ id: info.id, name: info.name, protocol: info.protocol, baseUrl: info.baseUrl, keyPage: info.keyPage || null, keyless: Boolean(info.keyless), custom: Boolean(info.custom), preset: info.preset || null,
334
+ // (the provider's own name, whatever the user called this connection: what 添加供应商 lists)
335
+ providerName: PRESETS.find((p) => p.id === (info.preset || info.id))?.name || (info.preset === GATEWAY_PROVIDER ? '7bit.fun' : info.name),
336
+ connected: Boolean(c && (c.apiKey || info.keyless || info.custom)),
337
+ key: c ? mask(c.apiKey) : '', model: c?.model || null, savedAt: c?.savedAt || null,
338
+ models: (c?.models || []).map((m) => ({ id: m.id, name: m.name || null, window: m.window || null, price: m.price || null })),
339
+ };
340
+ };
341
+ const custom = Object.keys(connections).filter((id) => !PRESETS.some((p) => p.id === id)).map((id) => providerInfo(id, connections)).filter(Boolean);
342
+ return {
343
+ gateway: { id: GATEWAY_PROVIDER, name: gatewayName(connections), url: config.gatewayUrl, connected: Boolean(login), key: login ? mask(login.apiKey) : '', account: login?.account || null, keyPage: `${config.gatewayUrl.replace(/\/+$/, '')}/user#keys` },
344
+ presets: PRESETS.map((p) => shown(providerInfo(p.id, connections))),
345
+ custom: custom.map(shown),
346
+ model: config.setting('model'),
347
+ effort: config.setting('effort'),
348
+ remembered: rememberedChoice(),
349
+ };
350
+ }
351
+
352
+ // What the gateway's own login is called in the console (名称, kept in providers.json under its id), else 7bit.fun.
353
+ const gatewayName = (connections = readConnections()) => (typeof connections[GATEWAY_PROVIDER]?.name === 'string' && connections[GATEWAY_PROVIDER].name.trim()) || '7bit.fun';
354
+ const displayName = (value) => String(value ?? '').replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 40);
355
+
356
+ // The provider a request names: a built-in one (or one already connected, by its id), another account of a built-in
357
+ // one or of 7bit.fun ({instanceOf}), or one of the user's own ({custom: {name, protocol, baseUrl}}). A new connection's
358
+ // id is chosen when it is saved (see connectProvider): `id` here is what it will likely be.
359
+ function requestedProvider(body) {
360
+ const connections = readConnections({ fresh: true });
361
+ if (body?.custom) {
362
+ const name = displayName(body.custom.name);
363
+ if (!name) throw httpError(400, '请填写名称');
364
+ const protocol = body.custom.protocol === 'openai' ? 'openai' : 'anthropic';
365
+ const baseUrl = normalizeBaseUrl(body.custom.baseUrl, protocol);
366
+ if (!validBaseUrl(baseUrl)) throw httpError(400, '地址要以 http:// 或 https:// 开头');
367
+ // (an English name is the models' prefix, myrelay/gpt-5; another one, or one taken, gets a free id)
368
+ return { id: nextInstanceId(cleanProviderId(name) || 'custom', connections), name, protocol, baseUrl, custom: true, connection: null, isNew: true };
369
+ }
370
+ if (body?.instanceOf) {
371
+ const base = String(body.instanceOf);
372
+ const gatewayUrl = loadConfig({ cwd: home }).gatewayUrl.replace(/\/+$/, '');
373
+ const template = base === GATEWAY_PROVIDER
374
+ ? { name: '7bit.fun', protocol: 'anthropic', baseUrl: gatewayUrl, keyPage: `${gatewayUrl}/user#keys` }
375
+ : PRESETS.find((p) => p.id === base);
376
+ if (!template) throw httpError(404, '没有这个供应商');
377
+ return { ...template, id: nextInstanceId(base, connections), preset: base, connection: null, isNew: true };
378
+ }
379
+ const info = providerInfo(String(body?.id || ''), connections);
380
+ if (!info) throw httpError(404, '没有这个供应商');
381
+ return info;
382
+ }
383
+
384
+ async function checkProvider(body) {
385
+ const info = requestedProvider(body);
386
+ const apiKey = String(body.apiKey || '').trim() || info.connection?.apiKey || '';
387
+ if (!apiKey && !info.keyless) throw httpError(400, '请填写 API Key');
388
+ let listed;
389
+ try {
390
+ listed = await listProviderModels({ ...info, apiKey }, { signal: AbortSignal.timeout(20_000) });
391
+ } catch (e) {
392
+ throw httpError(e.refused ? 400 : 502, e.refused ? `${info.name} 拒绝了这个 Key:${e.message}` : `连不上 ${info.name}:${e.message}`);
393
+ }
394
+ const catalogue = info.modelsDev ? await modelsDevCatalogue().catch(() => null) : null;
395
+ const models = enrichModels(listed.models, catalogue, info.modelsDev);
396
+ return { id: info.id, name: info.name, authHeader: listed.authHeader, models, current: info.connection?.model || null };
397
+ }
398
+
399
+ // As /connect does: one request to the model chosen, then the connection is saved (nothing before it answers).
400
+ async function connectProvider(body) {
401
+ const info = requestedProvider(body);
402
+ const existing = info.connection;
403
+ const apiKey = String(body.apiKey || '').trim() || existing?.apiKey || '';
404
+ if (!apiKey && !info.keyless) throw httpError(400, '请填写 API Key');
405
+ const model = String(body.model || '').trim();
406
+ if (!model) throw httpError(400, '请选择一个模型');
407
+ let authHeader = body.authHeader || existing?.authHeader || null;
408
+ let quirks = {};
409
+ try {
410
+ ({ authHeader, quirks } = await testProviderModel({ ...info, apiKey, authHeader, model }, { signal: AbortSignal.timeout(60_000) }));
411
+ } catch (e) {
412
+ throw httpError(400, `${model} 没有通过测试:${e.message}`);
413
+ }
414
+ const models = Array.isArray(body.models) && body.models.length ? body.models.filter((m) => m && typeof m.id === 'string').slice(0, 2000) : [{ id: model }];
415
+ // a new one's id taken now (the file as it is after the test, not before it)
416
+ const fresh = readConnections({ fresh: true });
417
+ const id = info.isNew ? nextInstanceId(info.custom ? (cleanProviderId(info.name) || 'custom') : info.preset, fresh) : info.id;
418
+ const name = displayName(body.name) || info.name;
419
+ const builtIn = PRESETS.find((p) => p.id === id);
420
+ saveConnection(id, {
421
+ ...(info.custom ? { custom: true, protocol: info.protocol, baseUrl: info.baseUrl } : {}),
422
+ ...(info.preset ? { preset: info.preset, ...(info.preset === GATEWAY_PROVIDER ? { protocol: 'anthropic', baseUrl: info.baseUrl } : {}) } : {}),
423
+ // (a built-in provider under its own name keeps none: it follows the provider's)
424
+ ...(info.custom || !builtIn || name !== builtIn.name ? { name } : {}),
425
+ apiKey,
426
+ authHeader: info.protocol === 'openai' ? 'bearer' : authHeader || 'x-api-key',
427
+ ...(Object.keys(quirks || {}).length ? { quirks } : {}),
428
+ model,
429
+ models,
430
+ });
431
+ if (body.useNow) rememberChoice({ model: `${id}/${model}` });
432
+ return { ...providersView(), connected: id };
433
+ }
434
+
435
+ // The model lists kept for the console's 模型列表 (what the pickers offer), nothing asked: the gateway's (as fetched
436
+ // last, see keptGatewayList) and each connected provider's (as /connect or 刷新模型列表 kept it), with what is known
437
+ // of each model: window, output limit, effort levels, price per million tokens.
438
+ function keptModelLists() {
439
+ const config = loadConfig({ cwd: home });
440
+ const groups = [];
441
+ const login = gatewayLogin(config.gatewayUrl);
442
+ if (login) {
443
+ const kept = keptGatewayList(login);
444
+ groups.push({
445
+ id: GATEWAY_PROVIDER, name: gatewayName(), at: kept?.at || null,
446
+ models: (kept?.list || []).map((m) => ({
447
+ ref: `${GATEWAY_PROVIDER}/${m.id}`, id: m.id, name: m.display_name || null, vendor: m.vendor || m.owned_by || null,
448
+ window: m.max_input_tokens || null, maxOutput: m.max_tokens || null, efforts: m.supported_reasoning_levels || [],
449
+ price: m.pricing && Number.isFinite(m.pricing.input_per_million_usd) ? { input: m.pricing.input_per_million_usd, output: m.pricing.output_per_million_usd } : null,
450
+ })),
451
+ });
452
+ }
453
+ for (const p of connectedProviders(readConnections({ fresh: true }))) {
454
+ const at = Date.parse(p.connection.savedAt || '');
455
+ groups.push({
456
+ id: p.id, name: p.name, at: Number.isFinite(at) ? at : null,
457
+ models: (p.connection.models || []).map((m) => ({
458
+ ref: `${p.id}/${m.id}`, id: m.id, name: m.name || null, vendor: null, window: m.window || null, maxOutput: m.maxOutput || null, efforts: [],
459
+ price: m.price ? { input: m.price.input, output: m.price.output } : null,
460
+ })),
461
+ });
462
+ }
463
+ return { groups, picked: pickedModels(), current: config.setting('model'), remembered: rememberedChoice() };
464
+ }
465
+
466
+ // The models the console offers for the default model: those of the connected providers and of the gateway.
467
+ async function modelChoices() {
468
+ const config = loadConfig({ cwd: home });
469
+ const out = [];
470
+ for (const p of connectedProviders()) {
471
+ for (const m of p.connection.models || []) out.push({ ref: `${p.id}/${m.id}`, provider: p.name, window: m.window || null });
472
+ }
473
+ const login = gatewayLogin(config.gatewayUrl);
474
+ if (login) {
475
+ try {
476
+ const list = keptGatewayList(login)?.list || await fetchGatewayModels(login, { signal: AbortSignal.timeout(8000) });
477
+ for (const m of list || []) out.push({ ref: `7bit/${m.id}`, provider: '7bit.fun', window: m.max_input_tokens || null, efforts: m.supported_reasoning_levels || null });
478
+ } catch { /* the gateway's models are left out */ }
479
+ }
480
+ return { models: out, current: config.setting('model'), remembered: rememberedChoice() };
481
+ }
482
+
483
+ // ---------------------------------------------------------------- memory and extensions
484
+
485
+ function memoryView() {
486
+ const projects = knownProjects().map((p) => {
487
+ const memDir = path.join(projectsRoot(), p.dir, 'memory');
488
+ let files = [];
489
+ try { files = fs.readdirSync(memDir).filter((f) => f.endsWith('.md')).map((f) => ({ name: f, path: path.join(memDir, f), size: fs.statSync(path.join(memDir, f)).size })); } catch { /* none */ }
490
+ // (the home directory's own CLAUDE.md is not read: there the user's ~/.claude-pro/CLAUDE.md stands for it)
491
+ const instructions = same(p.cwd, home) ? [] : ['CLAUDE.md', path.join('.claude', 'CLAUDE.md'), 'AGENTS.md', 'CLAUDE.local.md'].map((n) => path.join(p.cwd, n))
492
+ .map((f) => ({ path: f, name: path.relative(p.cwd, f), exists: fs.existsSync(f) }));
493
+ return { ...p, exists: fs.existsSync(p.cwd), memoryDir: memDir, memory: files.sort((a, b) => (a.name === 'MEMORY.md' ? -1 : b.name === 'MEMORY.md' ? 1 : a.name.localeCompare(b.name))), instructions };
494
+ });
495
+ const user = path.join(CONFIG_DIR, 'CLAUDE.md');
496
+ return { user: { path: user, exists: fs.existsSync(user) }, projects };
497
+ }
498
+
499
+ function extensionsView(project) {
500
+ const cwd = project && fs.existsSync(project) ? project : home;
501
+ const config = loadConfig({ cwd });
502
+ const files = settingsFiles(cwd);
503
+ const mcp = [];
504
+ for (const [scope, file] of [...Object.entries(files), ['.mcp.json', path.join(cwd, '.mcp.json')]]) {
505
+ if (scope !== 'user' && cwd === home) continue;
506
+ const json = readJsonFile(file);
507
+ for (const [name, spec] of Object.entries(json?.mcpServers || {})) mcp.push({ name, scope, file, spec: redactSpec(spec) });
508
+ }
509
+ const hooks = [];
510
+ for (const [scope, file] of Object.entries(files)) {
511
+ if (scope !== 'user' && cwd === home) continue;
512
+ const json = readJsonFile(file);
513
+ for (const [event, entries] of Object.entries(json?.hooks || {})) hooks.push({ event, scope, file, entries });
514
+ }
515
+ const scopeOf = (source) => (typeof source === 'string' && inside(path.resolve(source), CONFIG_DIR) ? 'user' : source === 'built-in' ? 'built-in' : 'project');
516
+ return {
517
+ project: cwd === home ? null : cwd,
518
+ skills: [...loadSkills(cwd).values()].map((s) => ({ name: s.name, description: s.description, scope: s.scope, path: s.file })),
519
+ agents: [...loadAgents(cwd).values()].map((a) => ({ name: a.name, description: a.description, tools: a.tools, scope: scopeOf(a.source), path: a.source === 'built-in' ? null : a.source })),
520
+ commands: [...loadCustomCommands(cwd).values()].map((c) => ({ name: c.name, description: c.description, scope: c.scope, path: commandPath(cwd, c) })),
521
+ mcp, hooks, settingsFiles: files,
522
+ mcpLoaded: Object.keys(config.settings.mcpServers || {}),
523
+ };
524
+ }
525
+
526
+ function commandPath(cwd, cmd) {
527
+ const rel = `${cmd.name.split(':').join(path.sep)}.md`;
528
+ const roots = cmd.scope === 'user' ? [path.join(CONFIG_DIR, 'commands')] : [path.join(cwd, '.claude-pro', 'commands'), path.join(cwd, '.claude', 'commands')];
529
+ return roots.map((r) => path.join(r, rel)).find((f) => fs.existsSync(f)) || null;
530
+ }
531
+
532
+ // An MCP server's settings without the values of its environment and headers (tokens live there).
533
+ function redactSpec(spec) {
534
+ if (!spec || typeof spec !== 'object') return spec;
535
+ const out = { ...spec };
536
+ for (const k of ['env', 'headers']) if (out[k] && typeof out[k] === 'object') out[k] = Object.fromEntries(Object.keys(out[k]).map((n) => [n, '•••']));
537
+ return out;
538
+ }
539
+
540
+ // ---------------------------------------------------------------- opening a conversation in a terminal
541
+
542
+ let wtPath;
543
+ function windowsTerminal() {
544
+ if (wtPath !== undefined) return wtPath;
545
+ try { wtPath = execFileSync('where', ['wt.exe'], { encoding: 'utf8', windowsHide: true }).split(/\r?\n/)[0].trim() || null; } catch { wtPath = null; }
546
+ return wtPath;
547
+ }
548
+
549
+ // The sessions the console runs in its own process (see host.js): set by the server.
550
+ let host = null;
551
+ export function useHost(h) { host = h; }
552
+
553
+ let updateCache, updateCheck, updateTask;
554
+ async function webUpdateStatus({ fresh = false } = {}) {
555
+ if (updateTask?.status === 'restarting' && host?.source && host.failed === host.source.key) {
556
+ updateCache = { result: { status: 'installed', version: updateTask.version, error: '新版未能通过启动检查,控制台仍在运行旧版' }, until: Date.now() + 60_000 };
557
+ updateTask = null;
558
+ }
559
+ if (updateTask) return { ...updateTask, runningVersion: VERSION };
560
+ if (fresh || !updateCache || Date.now() >= updateCache.until) {
561
+ updateCheck ||= checkForUpdate()
562
+ .catch(() => ({ status: 'error', error: '暂时无法连接 npm 检查更新' }))
563
+ .then((result) => { updateCache = { result, until: Date.now() + (result.status === 'error' ? 60_000 : 15 * 60_000) }; })
564
+ .finally(() => { updateCheck = null; });
565
+ await updateCheck;
566
+ }
567
+ return { ...(updateTask || updateCache.result), runningVersion: VERSION };
568
+ }
569
+
570
+ async function startWebUpdate(expectedVersion) {
571
+ let info = await webUpdateStatus();
572
+ if (info.status === 'updating' || info.status === 'restarting') return info;
573
+ if (info.status !== 'available' && info.status !== 'installed') info = await webUpdateStatus({ fresh: true });
574
+ if (info.status !== 'available' && info.status !== 'installed') return info;
575
+ if (info.version !== expectedVersion) throw httpError(409, '可用版本已变化,请重新检查更新');
576
+ if (!host) throw httpError(503, '控制台还在启动,请稍后再试');
577
+ if (info.status === 'installed') {
578
+ updateTask = { status: 'restarting', version: info.version };
579
+ host.requestHandover();
580
+ return webUpdateStatus();
581
+ }
582
+ const peers = await runningSessions();
583
+ if (updateTask) return webUpdateStatus();
584
+ if (peers.some((p) => p.status?.busy || p.status?.turn || p.status?.dialog) || !host.beginUpdate()) {
585
+ throw httpError(409, '还有会话正在工作,请等会话空闲后再更新');
586
+ }
587
+ const version = info.version;
588
+ updateTask = { status: 'updating', version };
589
+ void (async () => {
590
+ let r;
591
+ try { r = await installUpdate(version); } catch (e) { host.log(e, 'update'); }
592
+ if (r?.status === 'updated' || r?.status === 'installed') {
593
+ updateTask = { status: 'restarting', version: r.version };
594
+ host.endUpdate(true);
595
+ } else {
596
+ if (r?.error) host.log(r.error, 'update');
597
+ const error = r?.status === 'locked' ? '另一个会话正在安装更新,请稍后重试' : 'npm 安装失败,可重试,或在终端运行 /update 查看详情';
598
+ updateCache = { result: { status: 'available', version, error }, until: Date.now() + 60_000 };
599
+ updateTask = null;
600
+ host.endUpdate(false);
601
+ }
602
+ })();
603
+ return webUpdateStatus();
604
+ }
605
+
606
+ // A session in `cwd` (a saved conversation: `resumeFile`, `resumeId`), run by the console itself: up in ~0.1 s.
607
+ async function launchSession(cwd, { resumeFile = null, resumeId = null, initialChoices = null } = {}) {
608
+ if (!host) throw httpError(503, '控制台还在启动,请稍后再试');
609
+ if (host.updating) throw httpError(409, '正在安装更新,请稍后再试');
610
+ if (host.restarting || host.recovering) throw httpError(409, '控制台正在恢复会话,请稍后再试');
611
+ const app = await host.launch({ cwd, resumeFile, resumeId, initialChoices });
612
+ if (app.exiting || !app.runtime) throw httpError(500, '会话没能启动(详情在 ~/.claude-pro/web-errors.log)');
613
+ return { opened: true, peerId: app.peers?.id || null, sessionId: app.store?.id || null };
614
+ }
615
+
616
+ // claude-pro in `cwd` in a new terminal tab (Windows Terminal when there is one, else a console window), with `args`
617
+ // (ids and flags only: nothing a shell would take apart). Elsewhere than Windows only the command to run is given.
618
+ function launchTerminal(cwd, args, title) {
619
+ const bin = path.join(INSTALL_DIR, 'bin', 'claude-pro.js');
620
+ const command = `cd "${cwd}" && claude-pro${args.length ? ` ${args.join(' ')}` : ''}`;
621
+ if (!isWin) return { opened: false, command };
622
+ const wt = windowsTerminal();
623
+ const env = { ...process.env };
624
+ delete env.CLAUDE_PRO_BACKGROUND; // (inherited when a session of an older version, in a hidden window, started this server)
625
+ const child = wt
626
+ ? spawn(wt, ['-w', '0', 'new-tab', '-d', cwd, '--title', String(title || 'claude-pro').replace(/;/g, ',').slice(0, 40), process.execPath, bin, ...args], { detached: true, stdio: 'ignore', windowsHide: false, env })
627
+ : spawn('cmd.exe', ['/c', 'start', '""', '/D', `"${cwd}"`, `"${process.execPath}"`, `"${bin}"`, ...args], { detached: true, stdio: 'ignore', windowsVerbatimArguments: true, env });
628
+ child.on('error', () => {});
629
+ child.unref();
630
+ return { opened: true, how: wt ? 'Windows Terminal' : 'cmd', command };
631
+ }
632
+
633
+ // A saved conversation goes on: in the console (`terminal` false), or in a terminal tab.
634
+ const pendingSessions = new Map();
635
+
636
+ function sessionOperation(id, kind, work) {
637
+ const pending = pendingSessions.get(id);
638
+ if (pending) {
639
+ if (kind === 'open' && pending.kind === kind) return pending.promise;
640
+ throw httpError(409, '会话正在执行另一个操作,请稍后再试');
641
+ }
642
+ const promise = Promise.resolve().then(work).finally(() => pendingSessions.delete(id));
643
+ pendingSessions.set(id, { kind, promise });
644
+ return promise;
645
+ }
646
+
647
+ function openSession(dir, id, { terminal = false } = {}) {
648
+ const session = listAllSessions().find((s) => s.dir === dir && s.id === id);
649
+ if (!session) throw httpError(404, '会话不存在');
650
+ return sessionOperation(id, terminal ? 'terminal' : 'open', async () => {
651
+ if (host?.recovering || host?.restarting) throw httpError(409, '控制台正在恢复会话,请稍后再试');
652
+ const live = (await running()).get(id);
653
+ if (live && !terminal) return { opened: true, peerId: live.peerId, sessionId: id };
654
+ if (live) throw httpError(409, '这个会话已经在运行');
655
+ const cwd = session.cwd && fs.existsSync(session.cwd) ? session.cwd : home;
656
+ if (!terminal) return launchSession(cwd, { resumeFile: session.file, resumeId: id });
657
+ return launchTerminal(cwd, ['--resume', id], session.title);
658
+ });
659
+ }
660
+
661
+ // A new session in `cwd` (its first message, if any, is sent by the page once the session is up: no quoting through
662
+ // a terminal's command line).
663
+ async function newSession(body) {
664
+ let cwd = String(body?.cwd || '').trim().replace(/^~(?=$|[\\/])/, home);
665
+ if (!cwd) throw httpError(400, '请填写目录');
666
+ cwd = path.resolve(cwd);
667
+ let st;
668
+ try { st = fs.statSync(cwd); } catch { throw httpError(400, `目录不存在:${cwd}`); }
669
+ if (!st.isDirectory()) throw httpError(400, `不是目录:${cwd}`);
670
+ return { ...(await launchSession(cwd, { initialChoices: readInitialChoices(body) })), cwd };
671
+ }
672
+
673
+ function readInitialChoices(values) {
674
+ const choices = {};
675
+ for (const key of ['model', 'effort']) {
676
+ const value = values?.[key];
677
+ if (value == null || value === '') continue;
678
+ // (a provider's model id may hold @, as Cloudflare's @cf/...: only blanks and control characters are refused)
679
+ if (typeof value !== 'string' || !/^[^\s\x00-\x1f\x7f]{1,200}$/.test(value)) throw httpError(400, '无效的模型或思考强度');
680
+ choices[key] = value === 'default' ? null : value;
681
+ }
682
+ try { loadConfig({ cwd: home, flags: choices }); } catch { throw httpError(400, '无效的模型或思考强度'); }
683
+ return choices;
684
+ }
685
+
686
+ async function newSessionOptions(url) {
687
+ const cwd = url.searchParams.get('cwd') || home;
688
+ if (!path.isAbsolute(cwd) || (isWin && !windowsDrivePath(cwd))) throw httpError(400, '无效的项目目录');
689
+ const config = loadConfig({ cwd });
690
+ applyRememberedChoices(config);
691
+ const choices = readInitialChoices(Object.fromEntries(url.searchParams));
692
+ if ('model' in choices) config.modelOverride = choices.model;
693
+ if ('effort' in choices) config.effortOverride = choices.effort;
694
+ const kind = url.searchParams.get('kind');
695
+ const base = { model: config.modelSpec, effort: config.effort || 'auto', modelChoice: config.modelOverride || 'default', effortChoice: config.effortOverride || 'default' };
696
+ if (kind === 'models') return { ...base, models: await webModelChoices(config) };
697
+ if (kind === 'efforts') return { ...base, efforts: (await sessionEfforts(config, { cached: true })).options };
698
+ return base;
699
+ }
700
+
701
+ // ---------------------------------------------------------------- routes
702
+
703
+ const running = async () => {
704
+ const list = await runningSessions();
705
+ return new Map(list.filter((r) => r.status?.sessionId).map((r) => [r.status.sessionId, r]));
706
+ };
707
+
708
+ export const routes = [
709
+ ['GET', /^\/api\/overview$/, () => overview()],
710
+ ['GET', /^\/api\/update$/, (req, m, body, url) => webUpdateStatus({ fresh: url.searchParams.get('check') === '1' })],
711
+ ['POST', /^\/api\/update$/, (req, m, body) => startWebUpdate(body?.version)],
712
+
713
+ ['GET', /^\/api\/sessions$/, async () => {
714
+ const live = await runningSessions();
715
+ const peersById = new Map(live.filter((r) => r.status?.sessionId).map((r) => [r.status.sessionId, r.peerId]));
716
+ return {
717
+ sessions: listAllSessions().map(({ file, ...s }) => ({ ...s, running: peersById.get(s.id) ?? null })),
718
+ live,
719
+ projectOpen: { explorer: isWin, vscode: vscodeAvailable() },
720
+ workspaces: addedWorkspaces().filter((w) => fs.existsSync(w.cwd)),
721
+ };
722
+ }],
723
+ ['POST', /^\/api\/workspaces$/, (req, m, body) => addWorkspace(body)],
724
+ ['POST', /^\/api\/workspaces\/remove$/, (req, m, body) => removeWorkspace(body)],
725
+ ['GET', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)$/, async (req, [dir, id]) => {
726
+ const detail = sessionDetail(dir, id);
727
+ const live = await running();
728
+ return { ...detail, archived: Boolean(archivedSessions()[id]), running: live.has(id) ? live.get(id).peerId : null };
729
+ }],
730
+ ['GET', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)\/image\/(\d+)$/, (req, [dir, id, n]) => {
731
+ const image = sessionImage(dir, id, Number(n));
732
+ if (!image) throw httpError(404, 'no such image');
733
+ return { raw: { type: image.mediaType, data: image.data } };
734
+ }],
735
+ ['GET', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)\/output\/([\w-]+)$/, (req, [dir, id, tool]) => sessionToolOutput(dir, id, tool)],
736
+ ['GET', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)\/export$/, (req, [dir, id]) => ({ raw: { type: 'text/markdown; charset=utf-8', data: sessionMarkdown(dir, id), name: `claude-pro-${id.slice(0, 8)}.md` } })],
737
+ ['POST', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)\/rename$/, async (req, [dir, id], body) => {
738
+ if ((await running()).has(id)) throw httpError(409, '会话正在运行:请在它的终端里用 /rename,或在「运行中」里给它发 /rename');
739
+ return { name: renameSession(dir, id, body?.name) };
740
+ }],
741
+ ['POST', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)\/open$/, (req, [dir, id], body) => openSession(dir, id, { terminal: body?.terminal === true || body?.background === false })],
742
+ ['DELETE', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)$/, (req, [dir, id]) => sessionOperation(id, 'delete', async () => {
743
+ if (host?.recovering || host?.restarting) throw httpError(409, '控制台正在恢复会话,请稍后再试');
744
+ if ((await running()).has(id)) throw httpError(409, '会话正在运行,请先关闭它再删除');
745
+ return trashSession(dir, id);
746
+ })],
747
+ // 归档: put conversations away from the workspace (or back), several at once (a whole project)
748
+ ['POST', /^\/api\/sessions\/archive$/, (req, m, body) => {
749
+ const ids = Array.isArray(body?.ids) ? body.ids.filter((id) => typeof id === 'string' && /^[\w-]{1,80}$/.test(id)) : [];
750
+ if (!ids.length) throw httpError(400, 'ids required');
751
+ setArchived(ids, body?.archived !== false);
752
+ return { ok: true, count: ids.length };
753
+ }],
754
+ ['GET', /^\/api\/trash$/, () => ({ items: listTrash() })],
755
+ ['POST', /^\/api\/trash\/([\w.-]+)\/restore$/, (req, [trashId]) => restoreSession(trashId)],
756
+ ['DELETE', /^\/api\/trash\/([\w.-]+)$/, (req, [trashId]) => ({ removed: purgeTrash({ trashId }) })],
757
+ ['DELETE', /^\/api\/trash$/, () => ({ removed: purgeTrash({ all: true }) })],
758
+
759
+ ['GET', /^\/api\/live$/, async () => ({ sessions: await runningSessions() })],
760
+ ['GET', /^\/api\/live\/new\/options$/, (req, m, body, url) => newSessionOptions(url)],
761
+ ['POST', /^\/api\/live\/new$/, (req, m, body) => newSession(body)],
762
+ ['POST', /^\/api\/live\/([0-9a-f]{12})\/(send|interrupt|dialog|options|suggest|list|output|end)$/, async (req, [peerId, type], body) => {
763
+ if (host?.updating && type === 'send') throw httpError(409, '正在安装更新,请稍后再试');
764
+ if (type === 'end' && ![...(host?.apps || [])].some((app) => !app.exiting && app.peers?.id === peerId)) {
765
+ throw httpError(409, '请在对应的终端结束这个会话');
766
+ }
767
+ const peer = findPeerById(peerId);
768
+ const r = await peerRequest(peer, 'POST', '/command', { type, body: body || {} }, { timeout: type === 'options' ? 20_000 : 10_000 });
769
+ if (r.status === 404) throw httpError(409, '这个会话的 claude-pro 版本较旧,不支持网页操作');
770
+ if (!r.body?.ok) throw httpError(409, r.body?.error || '会话没有执行这个操作');
771
+ return r.body;
772
+ }],
773
+
774
+ ['GET', /^\/api\/settings$/, (req, m, b, url) => settingsView(url.searchParams.get('project'))],
775
+ ['POST', /^\/api\/settings$/, (req, m, body) => {
776
+ const file = scopeFile(body?.scope || 'user', body?.project);
777
+ if (body?.unset) unsetConfigSetting(file, String(body.key));
778
+ else {
779
+ try { writeConfigSetting(file, String(body?.key), body?.value); } catch (e) { throw httpError(400, e.message); }
780
+ }
781
+ return settingsView(body?.project);
782
+ }],
783
+ ['POST', /^\/api\/remembered$/, (req, m, body) => {
784
+ rememberChoice({ ...(body && 'model' in body ? { model: body.model || null } : {}), ...(body && 'effort' in body ? { effort: body.effort || null } : {}) });
785
+ return { remembered: rememberedChoice() };
786
+ }],
787
+
788
+ ['GET', /^\/api\/providers$/, () => providersView()],
789
+ ['GET', /^\/api\/models$/, () => modelChoices()],
790
+ ['GET', /^\/api\/models\/kept$/, () => keptModelLists()],
791
+ ['POST', /^\/api\/models\/picked$/, (req, m, body) => ({ picked: savePickedModels(body?.models) })],
792
+ ['POST', /^\/api\/models\/refresh$/, async () => ({ ...(await refreshModelLists(loadConfig({ cwd: home }))), view: providersView() })],
793
+ ['POST', /^\/api\/providers\/check$/, (req, m, body) => checkProvider(body)],
794
+ ['POST', /^\/api\/providers\/connect$/, (req, m, body) => connectProvider(body)],
795
+ ['DELETE', /^\/api\/providers\/([a-z0-9-]+)$/, (req, [id]) => {
796
+ if (!removeConnection(id)) throw httpError(404, '这个供应商没有连接');
797
+ return providersView();
798
+ }],
799
+ ['POST', /^\/api\/gateway$/, async (req, m, body) => {
800
+ const config = loadConfig({ cwd: home });
801
+ if (body?.apiKey) {
802
+ try { await loginWithKey({ url: config.gatewayUrl, apiKey: body.apiKey, signal: AbortSignal.timeout(15_000) }); } catch (e) { throw httpError(e.status === 401 || e.status === 403 ? 400 : 502, e.message); }
803
+ } else if (!gatewayLogin(config.gatewayUrl)) throw httpError(400, '请先粘贴 Key');
804
+ // its name in the console (名称): 7bit.fun unless the user gave another
805
+ if (body && 'name' in body) {
806
+ const name = displayName(body.name);
807
+ if (name && name !== '7bit.fun') saveConnection(GATEWAY_PROVIDER, { name }); else removeConnection(GATEWAY_PROVIDER);
808
+ }
809
+ // its model list at once (as /connect keeps a provider's): its tab in 模型列表 is not empty
810
+ const login = gatewayLogin(config.gatewayUrl);
811
+ if (login) await fetchGatewayModels(login, { fresh: true, timeoutMs: 10_000 }).catch(() => {});
812
+ return providersView();
813
+ }],
814
+ // the account behind the gateway key: its balance, for the 7bit.fun tab
815
+ ['GET', /^\/api\/gateway\/account$/, async () => {
816
+ const login = gatewayLogin(loadConfig({ cwd: home }).gatewayUrl);
817
+ if (!login) throw httpError(404, '没有连接 7bit.fun');
818
+ try {
819
+ const account = await fetchGatewayAccount(login, { signal: AbortSignal.timeout(6000) });
820
+ return { balance: account?.available_usd ?? account?.balance_usd ?? null, email: account?.email || login.account?.email || null, name: account?.name || null };
821
+ } catch (e) { return { balance: null, email: login.account?.email || null, error: e.message }; }
822
+ }],
823
+ ['DELETE', /^\/api\/gateway$/, () => { clearGatewayLogin(); return providersView(); }],
824
+
825
+ ['GET', /^\/api\/memory$/, () => memoryView()],
826
+ ['GET', /^\/api\/projects$/, () => ({ projects: knownProjects() })],
827
+ ['POST', /^\/api\/projects\/open$/, (req, m, body) => openProject(body)],
828
+ ['POST', /^\/api\/projects\/pick$/, () => pickProjectDirectory()],
829
+ ['GET', /^\/api\/projects\/directories$/, (req, m, body, url) => projectDirectories(url.searchParams.get('cwd'))],
830
+ ['GET', /^\/api\/file$/, (req, m, b, url) => readFileInfo(checkedPath(url.searchParams.get('path')))],
831
+ ['PUT', /^\/api\/file$/, (req, m, body) => {
832
+ const file = checkedPath(body?.path);
833
+ const text = String(body?.text ?? '');
834
+ if (/\.json$/i.test(file) && text.trim()) {
835
+ try { JSON.parse(text); } catch (e) { throw httpError(400, `不是有效的 JSON:${e.message}`); }
836
+ }
837
+ if (body?.mtime && fs.existsSync(file) && Math.abs(fs.statSync(file).mtimeMs - body.mtime) > 1) throw httpError(409, '文件在你打开之后被别的程序改过了:请重新打开再改');
838
+ fs.mkdirSync(path.dirname(file), { recursive: true });
839
+ fs.writeFileSync(file, text);
840
+ return readFileInfo(file);
841
+ }],
842
+ ['DELETE', /^\/api\/file$/, (req, m, b, url) => {
843
+ const file = checkedPath(url.searchParams.get('path'));
844
+ if (/settings(\.local)?\.json$/i.test(file)) throw httpError(400, '设置文件不能在这里删除');
845
+ const trash = path.join(CONFIG_DIR, 'trash', 'files', `${Date.now()}__${path.basename(file)}`);
846
+ fs.mkdirSync(path.dirname(trash), { recursive: true });
847
+ fs.renameSync(file, trash);
848
+ return { trashed: trash };
849
+ }],
850
+
851
+ ['GET', /^\/api\/extensions$/, (req, m, b, url) => extensionsView(url.searchParams.get('project'))],
852
+ ['POST', /^\/api\/mcp$/, (req, m, body) => {
853
+ // add, replace or remove one MCP server in a settings file (user, or a project's .mcp.json)
854
+ const name = String(body?.name || '').trim();
855
+ if (!/^[\w.-]{1,60}$/.test(name)) throw httpError(400, '名字只能用字母、数字、_ . -');
856
+ const file = body?.scope === 'project' ? path.join(checkedProject(body.project), '.mcp.json') : settingsFiles(home).user;
857
+ updateSettingsFile(file, (json) => {
858
+ json.mcpServers = json.mcpServers && typeof json.mcpServers === 'object' ? json.mcpServers : {};
859
+ if (body.remove) delete json.mcpServers[name];
860
+ else {
861
+ if (!body.spec || typeof body.spec !== 'object' || Array.isArray(body.spec)) throw httpError(400, 'spec must be an object');
862
+ const old = json.mcpServers[name] || {};
863
+ const spec = { ...body.spec };
864
+ // values left as ••• keep what was saved (the page never sees them)
865
+ for (const k of ['env', 'headers']) {
866
+ if (spec[k] && typeof spec[k] === 'object') spec[k] = Object.fromEntries(Object.entries(spec[k]).map(([n, v]) => [n, v === '•••' ? old[k]?.[n] ?? '' : v]));
867
+ }
868
+ json.mcpServers[name] = spec;
869
+ }
870
+ if (!Object.keys(json.mcpServers).length) delete json.mcpServers;
871
+ });
872
+ return extensionsView(body?.project);
873
+ }],
874
+
875
+ ['GET', /^\/api\/usage$/, (req, m, b, url) => usageReport({ days: Math.min(90, Math.max(1, Math.round(Number(url.searchParams.get('days'))) || 30)) })],
876
+ ];
877
+
878
+ function checkedProject(project) {
879
+ if (!project || !knownProjects().some((p) => same(p.cwd, project)) || !fs.existsSync(project)) throw httpError(400, '请选择一个已知的项目');
880
+ return path.resolve(project);
881
+ }