@yanzc/claude-pro 0.12.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/ui/repl.js CHANGED
@@ -20,7 +20,7 @@ import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
20
20
  import { gatewayLogin, loadGatewayModels, normalizeGatewayUrl, formatUsd } from '../gateway.js';
21
21
  import { connectedProviders } from '../providers.js';
22
22
  import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
23
- import { buildCommands, modelChoices, effortChoices } from '../commands.js';
23
+ import { buildCommands, webModelChoices, effortChoices } from '../commands.js';
24
24
  import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, reloadTiming, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
25
25
  import { resolvePath, displayPath } from '../utils/paths.js';
26
26
  import { listDirectory, recentDirectories } from '../utils/dirs.js';
@@ -283,7 +283,7 @@ export class App {
283
283
  // the local web console's live view of this session (claude-pro web, see live.js and web/server.js)
284
284
  this.liveFeed = new LiveFeed({
285
285
  seed: () => [
286
- ...transcriptItems(this.agent?.messages || [], { tools: this.runtime?.tools || [], ctx: this.agent?.makeCtx(), cwd: this.cwd, images: true }),
286
+ ...transcriptItems(this.agent?.messages || [], { tools: this.runtime?.tools || [], ctx: this.agent?.makeCtx(), cwd: this.cwd, images: true, turns: this.turnMarks }),
287
287
  ...(this.seedOutput.length ? [{ k: 'output', lines: this.seedOutput.slice() }] : []),
288
288
  ],
289
289
  status: () => this.liveStatus(),
@@ -297,6 +297,10 @@ export class App {
297
297
  this.remoteStarting = null;
298
298
  this.remoteRefused = null; // a gateway key the gateway refused: not tried again by itself (a new /connect is)
299
299
  this.seedOutput = []; // lines the page is shown after the conversation when it starts from it (see resumeAfterRestart)
300
+ // Where the turns of the conversation ended, with their "✻ Done at …" lines: [{after, text, msg}] (`msg`: the
301
+ // message the line follows, to find it again when the messages are replaced), and the array they were made on.
302
+ this.turnMarks = [];
303
+ this.marksBase = null;
300
304
  this.selfCheck = selfCheck;
301
305
  this.sessionName = flags?.restart?.peerName || null; // this session's name when the sessions of this computer do not know it (CLAUDE_PRO_PEERS=0)
302
306
  this.customTitle = null; // the conversation's name given with /rename: the title, instead of the topic
@@ -799,14 +803,9 @@ export class App {
799
803
  }
800
804
 
801
805
  // A message of the user in the transcript (typed here, on the remote page, or sent by another session).
802
- echoUser(text, images = 0) {
806
+ echoUser(text) {
803
807
  this.logLocal(renderUserMessage(text, this.width));
804
- // the web console shows the images themselves: they become the next ones of the conversation (see liveImage)
805
808
  this.liveFeed.emit({ t: 'user', text: String(text) });
806
- if (images && this.liveFeed.active) {
807
- const before = this.conversationImages().length;
808
- for (let i = 0; i < images; i++) this.liveFeed.emit({ t: 'image', n: before + i });
809
- }
810
809
  }
811
810
 
812
811
  // The images of the user's messages, in order (what transcriptItems numbers {k: 'image', n}).
@@ -967,12 +966,12 @@ export class App {
967
966
  cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'),
968
967
  name: this.peerLabel(),
969
968
  tasks: this.runtime.tasks.running().length,
969
+ background: this.backgroundWork(),
970
970
  restarting: Boolean(this.restartRequest || this.host?.restartWaits(this)),
971
971
  asking: this.dialogs.length > 0, // a question waits for an answer (the page reminds the user of it)
972
972
  conversationId: this.store.id,
973
973
  cost: Number(this.cost.toFixed(6)),
974
974
  context: { used: this.contextUsed(), window: cfg.model.contextWindow },
975
- background: this.backgroundWork(),
976
975
  kind: 'terminal',
977
976
  };
978
977
  }
@@ -994,13 +993,6 @@ export class App {
994
993
  return this.contextGuess.used;
995
994
  }
996
995
 
997
- // What runs in the background: the agent's background agents and shells.
998
- backgroundWork() {
999
- const agents = this.runtime.tasks.list().map((t) => ({ id: t.id, kind: 'agent', description: t.description, status: t.status, startedAt: t.started }));
1000
- const shells = listBackgroundShells(this.owner).map((s) => ({ id: s.id, kind: 'shell', description: s.description || s.command, status: s.status, startedAt: s.startedAt || null }));
1001
- return [...agents, ...shells];
1002
- }
1003
-
1004
996
  // The dialog open in the terminal, for the page to answer (options by index: values need not be strings).
1005
997
  remoteDialog() {
1006
998
  const d = this.dialogs[0];
@@ -1067,19 +1059,15 @@ export class App {
1067
1059
  return {};
1068
1060
  }
1069
1061
 
1070
- // For the page's model and effort menus: what /model and /effort offer (in plain text; the page sends /model
1071
- // <value> or /effort <value>), what is chosen (`current`), and the model and effort in use, as the status says.
1062
+ // The page's model and effort menus, from the kept lists. The page sends /model or /effort with the choice.
1072
1063
  async remoteOptions() {
1073
1064
  const cfg = this.config;
1074
- const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
1075
- const chosen = cfg.modelOverride || 'default';
1076
- const same = (m) => m.id === cfg.model.id && m.provider === cfg.model.provider;
1077
- const current = models.find((o) => o.value === chosen) || models.find((o) => o.value !== 'default' && same(cfg.resolveModel(o.value)));
1065
+ const [models, efforts] = await Promise.all([webModelChoices(cfg), effortChoices(cfg, { cached: true })]);
1078
1066
  const effortChosen = cfg.effortOverride || 'default';
1079
1067
  const { effort } = modelInfo(cfg);
1080
1068
  return {
1081
1069
  model: cfg.model.id,
1082
- models: models.map((o) => ({ ...o, ...(o === current ? { current: true } : {}) })),
1070
+ models,
1083
1071
  effort: effort || defaultEffort(cfg.model.id, cfg),
1084
1072
  efforts: efforts.options.map((o) => ({ ...o, ...(o.value === effortChosen ? { current: true } : {}) })),
1085
1073
  };
@@ -1158,6 +1146,23 @@ export class App {
1158
1146
  return Boolean(this.isTurnRunning() || this.dialogs.length || this.queue.length || this.restartBlockers().length);
1159
1147
  }
1160
1148
 
1149
+ // What runs in the background for this session, for the web console's live view: its background agents and the
1150
+ // commands it started with run_in_background that still run. [{kind: 'agent'|'shell', id, label, command, since}]
1151
+ backgroundWork() {
1152
+ const out = [];
1153
+ for (const t of this.runtime?.tasks?.running() || []) out.push({ kind: 'agent', id: t.id, label: t.description || t.subagentType || 'agent', since: t.started || null });
1154
+ const owner = this.owner;
1155
+ // (in the console's process the shells of all its sessions are in one list: without an owner, none is this one's)
1156
+ if (owner || !this.host) {
1157
+ for (const s of listBackgroundShells(owner)) {
1158
+ if (s.status !== 'running') continue;
1159
+ const command = String(s.command || '').replace(/\s+/g, ' ').trim().slice(0, 300);
1160
+ out.push({ kind: 'shell', id: s.id, label: s.description || command, command, since: s.startedAt || null });
1161
+ }
1162
+ }
1163
+ return out;
1164
+ }
1165
+
1161
1166
  restartBlockers() {
1162
1167
  const found = [];
1163
1168
  for (const t of this.runtime?.tasks?.running() || []) found.push(`background agent ${t.id} "${t.description}"`);
@@ -1884,7 +1889,7 @@ export class App {
1884
1889
  this.turnStarting = true;
1885
1890
  this.turnStart = Date.now();
1886
1891
  this.verb = VERBS[Math.floor(Math.random() * VERBS.length)];
1887
- if (echo) this.echoUser(display ?? prompt, images.length);
1892
+ if (echo) this.echoUser(display ?? prompt);
1888
1893
  this.refreshTopic(topic ?? display ?? prompt);
1889
1894
  let content;
1890
1895
  try {
@@ -1927,7 +1932,7 @@ export class App {
1927
1932
  }
1928
1933
 
1929
1934
  // The status line under each answer: "✻ Done at 14:05 · worked 1m 3s · $0.12 (total $3.40) · ctx 45k/1M · opus-5-5 max".
1930
- doneLine() {
1935
+ doneText() {
1931
1936
  const at = new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false });
1932
1937
  const parts = [`✻ Done at ${at}`, `worked ${formatDuration(Date.now() - this.turnStart)}`];
1933
1938
  const spent = this.cost - (this.turnCostStart || 0);
@@ -1940,7 +1945,17 @@ export class App {
1940
1945
  const level = effort || defaultEffort(cfg.model.id, cfg);
1941
1946
  parts.push(level ? `${model} ${level}` : model);
1942
1947
  } catch { /* no model information: the time and the cost are enough */ }
1943
- return c.dim(parts.join(' · '));
1948
+ return parts.join(' · ');
1949
+ }
1950
+
1951
+ // A turn ended with `text` under its answer: kept with the conversation, so that the web console shows it again
1952
+ // when it rebuilds the view from the messages (a reload, a restart of the session or of the console).
1953
+ markTurn(text) {
1954
+ const msgs = this.agent?.messages || [];
1955
+ if (!msgs.length) return;
1956
+ if (this.marksBase !== msgs) { this.marksBase = msgs; this.turnMarks = this.turnMarks.filter((m) => msgs[m.after - 1] === m.msg); }
1957
+ this.turnMarks.push({ after: msgs.length, text, msg: msgs[msgs.length - 1] });
1958
+ this.store.turnEnd(msgs.length, text);
1944
1959
  }
1945
1960
 
1946
1961
  // A short message about something the user just did (a paste, a copy, a completion with nothing to offer): a
@@ -1983,7 +1998,11 @@ export class App {
1983
1998
  this.flushActive(true);
1984
1999
  // When the answer came and how long the turn took, under the answer (the user asked for the time, 2026-11-21),
1985
2000
  // with what there is no footer for: the cost, the context in use, the model.
1986
- if (result && !result.interrupted && !error) this.screen.log(this.doneLine(), '');
2001
+ if (result && !result.interrupted && !error) {
2002
+ const text = this.doneText();
2003
+ this.screen.log(c.dim(text), '');
2004
+ this.markTurn(text);
2005
+ }
1987
2006
  this.answerPeers(result, error);
1988
2007
  this.busy = false;
1989
2008
  this.controller = null;
@@ -2118,6 +2137,8 @@ export class App {
2118
2137
  this.cost = loaded.cost;
2119
2138
  this.agent.cache.clockUntil = this.store.cacheUntil = loaded.cacheUntil;
2120
2139
  this.agent.messages = loaded.messages;
2140
+ this.marksBase = loaded.messages;
2141
+ this.turnMarks = (loaded.turns || []).map((t) => ({ ...t, msg: loaded.messages[t.after - 1] }));
2121
2142
  this.agent.restoreFileState(loaded.messages, loaded.times);
2122
2143
  this.agent.lastActivityAt = loaded.lastAt; // a long pause before this turn clears old tool results, as it would have
2123
2144
  this.agent.lastContextTokens = estimateTokens(loaded.messages);
@@ -2171,6 +2192,8 @@ export class App {
2171
2192
  this.store.onError = this.storeError;
2172
2193
  this.runtime.trace?.setSessionId(this.store.id);
2173
2194
  this.seedOutput = [];
2195
+ this.turnMarks = [];
2196
+ this.marksBase = this.agent?.messages || null;
2174
2197
  this.topic = null;
2175
2198
  this.customTitle = null;
2176
2199
  this.firstPrompt = null;
@@ -2452,16 +2475,43 @@ export class App {
2452
2475
  takeQueued() {
2453
2476
  if (!this.queue.length) return [];
2454
2477
  const items = this.queue.splice(0);
2455
- for (const q of items) this.echoUser(q.display ?? q.text, q.images?.length);
2478
+ for (const q of items) this.echoUser(q.display ?? q.text);
2456
2479
  this.turnPeers.push(...items.map((q) => q.peer).filter(Boolean));
2457
2480
  this.refreshTopic(items.map((q) => q.display ?? q.text).join('\n\n'));
2458
2481
  // Content blocks for the agent: each queued message's text followed by its images.
2459
2482
  return items.flatMap((q) => [{ type: 'text', text: q.text }, ...q.images.map(imageBlock)]);
2460
2483
  }
2461
2484
 
2462
- messageAdded(msg, agent) { if (this.isMain(agent)) this.store.message(msg); }
2485
+ messageAdded(msg, agent) {
2486
+ if (!this.isMain(agent)) return;
2487
+ this.store.message(msg);
2488
+ if (!this.liveFeed.active || msg.role !== 'user' || !Array.isArray(msg.content)) return;
2489
+ const count = msg.content.filter((b) => b.type === 'image').length;
2490
+ if (!count) return;
2491
+ // Publish after pushMessage adds the fitted images: the page can immediately fetch them via liveImage.
2492
+ const end = this.conversationImages().length;
2493
+ for (let n = end - count; n < end; n++) this.liveFeed.emit({ t: 'image', n });
2494
+ }
2463
2495
  systemPrompt(text, agent) { if (this.isMain(agent)) this.store.setSystemPrompt(text); }
2464
- messagesReplaced(msgs, agent) { if (this.isMain(agent)) this.store.reset(msgs); }
2496
+ messagesReplaced(msgs, agent) {
2497
+ if (!this.isMain(agent)) return;
2498
+ this.store.reset(msgs);
2499
+ // The turn lines go with their messages: where the same message is (a rewind keeps a prefix, a partial compaction
2500
+ // the other part), or where they were when only messages' contents changed (cleared tool results, lighter images);
2501
+ // those of what was summarized go. Written again: the reset drops them from the file.
2502
+ const before = this.marksBase;
2503
+ this.marksBase = msgs;
2504
+ if (!this.turnMarks.length) return;
2505
+ const sameLength = before === msgs || before?.length === msgs.length;
2506
+ const kept = [];
2507
+ for (const m of this.turnMarks) {
2508
+ let at = msgs[m.after - 1] === m.msg ? m.after : msgs.indexOf(m.msg) + 1;
2509
+ if (!at && sameLength && m.after <= msgs.length) at = m.after;
2510
+ if (at > 0) kept.push({ after: at, text: m.text, msg: msgs[at - 1] });
2511
+ }
2512
+ this.turnMarks = kept.sort((a, b) => a.after - b.after);
2513
+ if (kept.length) this.store.setTurns(kept);
2514
+ }
2465
2515
  usage(_u, agent) {
2466
2516
  if (this.isMain(agent)) this.store.setCacheUntil(agent.cache.clockUntil, agent.cacheState()); // for a resumed or restarted conversation
2467
2517
  this.screen.schedule();
package/src/web/api.js CHANGED
@@ -7,18 +7,18 @@ import path from 'node:path';
7
7
  import { spawn, execFile, execFileSync } from 'node:child_process';
8
8
  import {
9
9
  CONFIG_DIR, INSTALL_DIR, SOURCE_CHECKOUT, VERSION, BASIC_SETTINGS, KNOWN_KEYS, loadConfig, settingsFiles,
10
- writeConfigSetting, unsetConfigSetting, rememberChoice, updateSettingsFile, applyRememberedChoices,
10
+ writeConfigSetting, unsetConfigSetting, rememberChoice, updateSettingsFile, applyRememberedChoices, pickedModels, savePickedModels,
11
11
  } from '../config.js';
12
12
  import {
13
13
  PRESETS, GATEWAY_PROVIDER, readConnections, saveConnection, removeConnection, providerInfo, connectedProviders,
14
- listProviderModels, testProviderModel, modelsDevCatalogue, enrichModels, cleanProviderId, reservedProviderId,
14
+ listProviderModels, testProviderModel, modelsDevCatalogue, enrichModels, cleanProviderId, nextInstanceId,
15
15
  normalizeBaseUrl, validBaseUrl,
16
16
  } from '../providers.js';
17
- import { gatewayLogin, loginWithKey, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels } from '../gateway.js';
17
+ import { gatewayLogin, loginWithKey, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, keptGatewayList } from '../gateway.js';
18
18
  import { checkForUpdate, installUpdate } from '../updater.js';
19
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';
20
+ import { webModelChoices, effortChoices as sessionEfforts, refreshModelLists } from '../commands.js';
21
+ import { setArchived, archivedSessions, projectDir } from '../session.js';
22
22
  import {
23
23
  listAllSessions, sessionDetail, sessionImage, sessionToolOutput, sessionMarkdown, renameSession, trashSession, listTrash, restoreSession,
24
24
  purgeTrash, runningSessions, findPeerById, peerRequest, usageReport, dirSize, projectsRoot, httpError,
@@ -38,16 +38,52 @@ const home = os.homedir();
38
38
  // extension pages list, and where their files may be edited.
39
39
  function knownProjects() {
40
40
  const byCwd = new Map();
41
+ const keyOf = (cwd) => (isWin ? path.resolve(cwd).toLowerCase() : path.resolve(cwd));
41
42
  for (const s of listAllSessions()) {
42
43
  if (!s.cwd) continue;
43
- const key = isWin ? s.cwd.toLowerCase() : s.cwd;
44
+ const key = keyOf(s.cwd);
44
45
  const p = byCwd.get(key);
45
46
  if (!p) byCwd.set(key, { cwd: s.cwd, dir: s.dir, sessions: 1, lastUsed: s.mtime });
46
47
  else { p.sessions++; p.lastUsed = Math.max(p.lastUsed, s.mtime); }
47
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
+ }
48
53
  return [...byCwd.values()].sort((a, b) => b.lastUsed - a.lastUsed);
49
54
  }
50
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
+
51
87
  const same = (a, b) => (isWin ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
52
88
 
53
89
  const windowsDrivePath = (p) => typeof p === 'string' && /^[a-z]:[\\/]/i.test(p);
@@ -294,7 +330,9 @@ function providersView() {
294
330
  const shown = (info) => {
295
331
  const c = info.connection;
296
332
  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),
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),
298
336
  connected: Boolean(c && (c.apiKey || info.keyless || info.custom)),
299
337
  key: c ? mask(c.apiKey) : '', model: c?.model || null, savedAt: c?.savedAt || null,
300
338
  models: (c?.models || []).map((m) => ({ id: m.id, name: m.name || null, window: m.window || null, price: m.price || null })),
@@ -302,7 +340,7 @@ function providersView() {
302
340
  };
303
341
  const custom = Object.keys(connections).filter((id) => !PRESETS.some((p) => p.id === id)).map((id) => providerInfo(id, connections)).filter(Boolean);
304
342
  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` },
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` },
306
344
  presets: PRESETS.map((p) => shown(providerInfo(p.id, connections))),
307
345
  custom: custom.map(shown),
308
346
  model: config.setting('model'),
@@ -311,18 +349,34 @@ function providersView() {
311
349
  };
312
350
  }
313
351
 
314
- // The provider a request names: a built-in one or one of the user's ({custom: {name, protocol, baseUrl}}).
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.
315
359
  function requestedProvider(body) {
360
+ const connections = readConnections({ fresh: true });
316
361
  if (body?.custom) {
317
- const id = cleanProviderId(body.custom.name);
318
- if (!id) throw httpError(400, '名字只能用字母、数字和 -');
319
- if (reservedProviderId(id)) throw httpError(400, `"${id}" 是内置的供应商,请在列表里选它,或换个名字`);
362
+ const name = displayName(body.custom.name);
363
+ if (!name) throw httpError(400, '请填写名称');
320
364
  const protocol = body.custom.protocol === 'openai' ? 'openai' : 'anthropic';
321
365
  const baseUrl = normalizeBaseUrl(body.custom.baseUrl, protocol);
322
366
  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 };
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 };
324
378
  }
325
- const info = providerInfo(String(body?.id || ''), readConnections({ fresh: true }));
379
+ const info = providerInfo(String(body?.id || ''), connections);
326
380
  if (!info) throw httpError(404, '没有这个供应商');
327
381
  return info;
328
382
  }
@@ -358,16 +412,55 @@ async function connectProvider(body) {
358
412
  throw httpError(400, `${model} 没有通过测试:${e.message}`);
359
413
  }
360
414
  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 } : {}),
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 } : {}),
363
425
  apiKey,
364
426
  authHeader: info.protocol === 'openai' ? 'bearer' : authHeader || 'x-api-key',
365
427
  ...(Object.keys(quirks || {}).length ? { quirks } : {}),
366
428
  model,
367
429
  models,
368
430
  });
369
- if (body.useNow) rememberChoice({ model: `${info.id}/${model}` });
370
- return providersView();
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() };
371
464
  }
372
465
 
373
466
  // The models the console offers for the default model: those of the connected providers and of the gateway.
@@ -380,7 +473,7 @@ async function modelChoices() {
380
473
  const login = gatewayLogin(config.gatewayUrl);
381
474
  if (login) {
382
475
  try {
383
- const list = await fetchGatewayModels(login, { signal: AbortSignal.timeout(8000) });
476
+ const list = keptGatewayList(login)?.list || await fetchGatewayModels(login, { signal: AbortSignal.timeout(8000) });
384
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 });
385
478
  } catch { /* the gateway's models are left out */ }
386
479
  }
@@ -444,29 +537,6 @@ function redactSpec(spec) {
444
537
  return out;
445
538
  }
446
539
 
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
540
  // ---------------------------------------------------------------- opening a conversation in a terminal
471
541
 
472
542
  let wtPath;
@@ -623,8 +693,8 @@ async function newSessionOptions(url) {
623
693
  if ('effort' in choices) config.effortOverride = choices.effort;
624
694
  const kind = url.searchParams.get('kind');
625
695
  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 };
696
+ if (kind === 'models') return { ...base, models: await webModelChoices(config) };
697
+ if (kind === 'efforts') return { ...base, efforts: (await sessionEfforts(config, { cached: true })).options };
628
698
  return base;
629
699
  }
630
700
 
@@ -647,8 +717,11 @@ export const routes = [
647
717
  sessions: listAllSessions().map(({ file, ...s }) => ({ ...s, running: peersById.get(s.id) ?? null })),
648
718
  live,
649
719
  projectOpen: { explorer: isWin, vscode: vscodeAvailable() },
720
+ workspaces: addedWorkspaces().filter((w) => fs.existsSync(w.cwd)),
650
721
  };
651
722
  }],
723
+ ['POST', /^\/api\/workspaces$/, (req, m, body) => addWorkspace(body)],
724
+ ['POST', /^\/api\/workspaces\/remove$/, (req, m, body) => removeWorkspace(body)],
652
725
  ['GET', /^\/api\/sessions\/([\w.-]+)\/([\w-]+)$/, async (req, [dir, id]) => {
653
726
  const detail = sessionDetail(dir, id);
654
727
  const live = await running();
@@ -714,6 +787,9 @@ export const routes = [
714
787
 
715
788
  ['GET', /^\/api\/providers$/, () => providersView()],
716
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() })],
717
793
  ['POST', /^\/api\/providers\/check$/, (req, m, body) => checkProvider(body)],
718
794
  ['POST', /^\/api\/providers\/connect$/, (req, m, body) => connectProvider(body)],
719
795
  ['DELETE', /^\/api\/providers\/([a-z0-9-]+)$/, (req, [id]) => {
@@ -722,9 +798,28 @@ export const routes = [
722
798
  }],
723
799
  ['POST', /^\/api\/gateway$/, async (req, m, body) => {
724
800
  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); }
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(() => {});
726
812
  return providersView();
727
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
+ }],
728
823
  ['DELETE', /^\/api\/gateway$/, () => { clearGatewayLogin(); return providersView(); }],
729
824
 
730
825
  ['GET', /^\/api\/memory$/, () => memoryView()],
@@ -754,7 +849,6 @@ export const routes = [
754
849
  }],
755
850
 
756
851
  ['GET', /^\/api\/extensions$/, (req, m, b, url) => extensionsView(url.searchParams.get('project'))],
757
- ['POST', /^\/api\/extensions$/, (req, m, body) => newExtension(body || {})],
758
852
  ['POST', /^\/api\/mcp$/, (req, m, body) => {
759
853
  // add, replace or remove one MCP server in a settings file (user, or a project's .mcp.json)
760
854
  const name = String(body?.name || '').trim();
@@ -778,7 +872,7 @@ export const routes = [
778
872
  return extensionsView(body?.project);
779
873
  }],
780
874
 
781
- ['GET', /^\/api\/usage$/, (req, m, b, url) => usageReport({ days: Math.min(90, Math.max(7, Number(url.searchParams.get('days')) || 30)) })],
875
+ ['GET', /^\/api\/usage$/, (req, m, b, url) => usageReport({ days: Math.min(90, Math.max(1, Math.round(Number(url.searchParams.get('days'))) || 30)) })],
782
876
  ];
783
877
 
784
878
  function checkedProject(project) {