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