@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/README.md CHANGED
@@ -196,15 +196,16 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
196
196
  - **自动恢复**:正在运行的后台会话记在 `~/.claude-pro/web-running.json`。控制台进程意外退出(崩溃、被结束)后,下次启动时(`claude-pro web`、`/web`,或开着远程访问的会话启动时)把它们全部恢复。控制台只在没有后台会话、没有打开的网页、没开远程访问 30 分钟后才退出。出错记录在 `~/.claude-pro/web-errors.log`。
197
197
  - **会话**:运行中的会话实时显示,底部输入框可以发消息、粘贴/拖入/添加图片、停止当前任务、切换模型和推理强度;没在运行的会话显示完整记录,可以「在终端中继续」。
198
198
  - **概览**:版本和更新、安装位置、默认模型、7bit.fun 余额、运行中的会话数、会话记录占用的空间。
199
- - **全部会话**(在左下角头像菜单里):所有项目的对话记录表格,可以搜索(会话名、第一句话、ID、目录)、按项目筛选、按时间/大小/花费排序;点开会话可看完整对话。
199
+ - **全部会话**(在左下角「设置」菜单里):所有项目的对话记录表格,可以搜索(会话名、第一句话、ID、目录)、按项目筛选、按时间/大小/花费排序;点开会话可看完整对话。
200
+ - **添加工作区**:工作区标题栏的文件夹图标选一个目录(本机弹系统选择器,远程访问时浏览运行 claude-pro 的电脑上的目录),它会一直显示在侧栏里,还没有会话也在,点它右边的 + 就在里面新建会话。项目行的 ⋯ 里可以「从工作区移除」,只取消固定,目录和会话都不动。
200
201
  - **工作区菜单**:会话行右侧的 ⋯ 可以归档、复制 Session ID 或删除对话(先移到回收站,保留 7 天,可恢复)。项目行的 ⋯ 可以批量归档非运行中的会话;Windows 上还可以在资源管理器或已安装的 VS Code 中打开目录。远程访问时,窗口开在运行 claude-pro 的电脑上。
201
202
  - **归档**:归档的会话从工作区收起,内容完整保留,**不会被按天数自动清理**,`/resume` 照样能找到;在「全部会话 → 已归档」里查看或取消归档。归档标记记在 `~/.claude-pro/archived.json`,对话文件原地不动。
202
203
  - 在网页上也能回答会话弹出的问题、展开完整工具输出。终端里启动的会话要在对应终端结束。
203
204
  - **手动更新**:通过 npm 全局安装的版本会在网页打开时检查新版;发现更新时,点左上角版本号旁的 ↑,确认后才安装。已有任务运行时请等它们空闲;新版安装完成后控制台会在空闲时接续会话。终端仍可运行 `/update`,源码版用 Git 更新。
204
- - **模型与供应商**:连接/断开 7bit.fun 和各家供应商(粘贴 Key → 列出模型 → 测试 → 保存,和 /connect 一样),添加自定义的 OpenAI/Anthropic 兼容接口,设置默认模型和推理强度。Key 只显示开头和结尾。
205
+ - **模型与供应商**:「添加供应商」连接 7bit.fun、各家供应商或自定义的 OpenAI/Anthropic 兼容接口(粘贴 Key → 列出模型 → 测试 → 保存,和 /connect 一样)。每个连接有自己的「名称」,默认是供应商的名字,可以改,显示在 tab 和模型菜单里。同一家可以连好几个账号:第二个 DeepSeek 的模型写成 `deepseek-2/模型`,7bit.fun 的第二个账号是 `7bit-2/模型`。每家一个 tab,tab 里能改名称、换 Key、断开,勾选会话菜单里要用的模型;上面设置默认模型和思考强度。Key 只显示开头和结尾。第一次打开控制台、还没有任何供应商时,会先提示去添加。
205
206
  - **设置**:所有普通和高级设置,中文说明、当前生效的值和它来自哪一层,可以写到用户、项目或项目本地的设置文件,或恢复默认。
206
207
  - **记忆与指令**:全局和各项目的 CLAUDE.md、自动记忆,查看、编辑、删除(删除的文件移到 `~/.claude-pro/trash/files`)。
207
- - **扩展**:技能、子 agent、自定义命令(查看、编辑、新建)、MCP 服务器(添加、修改、删除;环境变量和请求头的值不显示)、hooks。
208
+ - **扩展**:技能、子 agent、自定义命令、MCP 服务器(环境变量和请求头的值不显示)和 hooks,可以查看和编辑。「让 AI 新建」会打开新会话并预填要求(文件位置和格式),写上用途就交给模型去做;选了项目时放在那个项目里。
208
209
  - **用量**:近 7/30/90 天按天、模型、项目统计的请求数、tokens 和按价格估算的花费(来自运行 Trace),以及花费最多的会话。
209
210
 
210
211
  服务是整台电脑共用的一个后台进程,没有页面打开 30 分钟后自动退出,下次 `/web` 再启动;claude-pro 更新(或源码改动)后会自动换成新版本。只监听 127.0.0.1,只接受以 127.0.0.1/localhost 访问的请求,修改类请求必须来自控制台自己的页面;第一次用 `/web` 打开时地址里带一个令牌,之后换成 cookie(令牌在 `~/.claude-pro/web.json`,只有你能读)。控制台不能打开 `gateway.json`、`providers.json` 这类存 Key 的文件,也不能打开会话记录以外的任意文件。
@@ -217,7 +218,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
217
218
  - **密码只在本机校验**:`~/.claude-pro/web-remote.json` 里只存 scrypt 哈希,网关不知道密码。登录页可以选「记住这台设备 30 天」,不勾就只保持 1 天。同一个 IP 连续输错 5 次锁 15 分钟,一小时内总共错 20 次就锁到这个小时结束。每次登录(成功或失败)都有记录。
218
219
  - **管理**:`/web remote` 看状态和地址,`/web remote password` 改密码(所有设备退出),`/web remote logout` 让所有设备退出,`/web remote off` 关闭。控制台左边「远程访问」页面也能做这些,并列出登录着的设备和最近的登录。
219
220
  - **保持在线**:开启后控制台服务不再空闲退出;电脑休眠、关机时打不开,claude-pro 的任何会话启动时会把它重新接上。
220
- - **多台电脑**:同一个账号的几台电脑都开了远程访问时,打开地址先让你选电脑(记在 cookie 里),控制台左下角有「切换电脑」。
221
+ - **多台电脑**:同一个账号的几台电脑都开了远程访问时,打开地址先让你选电脑(记在 cookie 里),控制台左下角「设置」菜单里有「切换电脑」。
221
222
  - **安全**:能登录就等于能在这台电脑上执行命令,密码要够强;从外网打开时控制台不接受 `/web` 的本机令牌,修改类请求必须来自这个域名的页面。
222
223
 
223
224
  ## 会话之间互发任务(本机和其他电脑)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "claude-pro: a command line coding agent for many model providers (Anthropic, OpenAI, DeepSeek, Kimi, GLM, Qwen, OpenRouter, the 7bit.fun gateway, your own endpoint...). Full access with no permission prompts; file edits are checkpointed and can be rewound.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/commands.js CHANGED
@@ -5,8 +5,8 @@ import path from 'node:path';
5
5
  import { c, glyphs, padEnd, truncate } from './ui/ansi.js';
6
6
  import { SelectDialog, TextInputDialog } from './ui/dialogs.js';
7
7
  import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
8
- import { loadConfig, settingsFiles, configEntries, writeConfigSetting, unsetConfigSetting, rememberChoice, applyRememberedChoices, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
9
- import { loginWithKey, gatewayLogin, gatewayKeyPage, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, loadGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
8
+ import { loadConfig, settingsFiles, configEntries, writeConfigSetting, unsetConfigSetting, rememberChoice, applyRememberedChoices, pickedModels, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
9
+ import { loginWithKey, gatewayLogin, gatewayKeyPage, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, keptGatewayModels, loadGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
10
10
  import { GATEWAY_PROVIDER, PRESETS, providerInfo, connectedProviders, readConnections, saveConnection, removeConnection, normalizeBaseUrl, validBaseUrl, cleanProviderId, reservedProviderId, listProviderModels, testProviderModel, modelsDevCatalogue, enrichModels } from './providers.js';
11
11
  import { SessionStore } from './session.js';
12
12
  import { memoryFiles, listAutoMemories } from './context.js';
@@ -32,10 +32,11 @@ const effortLevels = (modelId, modelInfo = null) => {
32
32
 
33
33
  // The models of the providers connected with /connect, for /model: each provider's list asked for anew (4 seconds at
34
34
  // most), with what was kept at /connect about them (windows, prices); without an answer, the list kept then.
35
- async function providerModelChoices() {
35
+ // `cached` (the web console's pickers): the kept lists only, nothing asked (its 刷新模型列表 button renews them).
36
+ async function providerModelChoices({ cached = false } = {}) {
36
37
  const groups = await Promise.all(connectedProviders().map(async (info) => {
37
38
  let listed = null;
38
- try {
39
+ if (!cached) try {
39
40
  listed = (await listProviderModels({ ...info, ...info.connection, baseUrl: info.connection.baseUrl || info.baseUrl }, { timeoutMs: 4000, kinds: [info.connection.authHeader || 'x-api-key'] })).models;
40
41
  } catch { /* the kept list */ }
41
42
  const kept = info.connection.models || [];
@@ -49,12 +50,15 @@ async function providerModelChoices() {
49
50
  return groups.flat();
50
51
  }
51
52
 
52
- // What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
53
+ // What /model offers: [{value, label, description}] in plain text, the
53
54
  // default first. `value` is what /model <value> takes. Every connected provider's models, provider/model, 7bit.fun's
54
55
  // among them (asked for anew each time, 4 seconds at most, so that a model just added is there without a restart;
55
56
  // without an answer the list given last, else gpt-6.1-sol for its GPT models); the Claude aliases where a provider of
56
57
  // Claude is connected. A provider that is not connected offers nothing.
57
- export async function modelChoices(cfg) {
58
+ // `cached`: the lists kept from before (see providerModelChoices); the gateway is asked only when none is kept yet.
59
+ // `picked` (the web console's menus, see pickedModels): a set of provider/model; when it has any, only those are
60
+ // offered by their full names (not the aliases), with the default and the model in use.
61
+ export async function modelChoices(cfg, { cached = false, picked = null } = {}) {
58
62
  const configured = cfg.configuredModelSpec;
59
63
  const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).label}` }];
60
64
  const tag = (m) => `${m.provider}/${m.id}`;
@@ -66,28 +70,99 @@ export async function modelChoices(cfg) {
66
70
  opts.push({ value: a, label: a, description: `→ ${target.label}` });
67
71
  }
68
72
  }
69
- const others = providerModelChoices();
73
+ const others = providerModelChoices({ cached });
74
+ const gateway = [];
70
75
  const login = gatewayLogin(cfg.gatewayUrl);
71
76
  if (login) {
72
- let served = null;
73
- try { served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: true }); } catch { /* offline: the fallback below */ }
77
+ let served = cached ? keptGatewayModels(login) : null;
78
+ if (!served) try { served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: !cached }); } catch { /* offline: the fallback below */ }
74
79
  for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
75
- if (aliased.has(`${GATEWAY_PROVIDER}/${m.id}`)) continue;
76
- opts.push({ value: `${GATEWAY_PROVIDER}/${m.id}`, label: `${GATEWAY_PROVIDER}/${m.id}`, description: ['7bit.fun', isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || ''].filter(Boolean).join(' · ') });
80
+ gateway.push({ value: `${GATEWAY_PROVIDER}/${m.id}`, label: `${GATEWAY_PROVIDER}/${m.id}`, description: ['7bit.fun', isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || ''].filter(Boolean).join(' · ') });
77
81
  }
78
82
  }
79
- opts.push(...(await others).filter((o) => !aliased.has(o.value)));
80
- return opts;
83
+ const providers = await others;
84
+ opts.push(...gateway.filter((o) => !aliased.has(o.value)), ...providers.filter((o) => !aliased.has(o.value)));
85
+ if (!picked?.size) return opts;
86
+ const kept = [opts[0], ...[...gateway, ...providers].filter((o) => picked.has(o.value))];
87
+ // the model in use stays listed (it is shown as the current one), unless a ticked entry is that model already
88
+ const chosen = cfg.modelOverride;
89
+ const sameModel = (o) => { try { const m = cfg.resolveModel(o.value); return m.id === cfg.model.id && m.provider === cfg.model.provider; } catch { return false; } };
90
+ if (chosen && !kept.some((o) => o.value === chosen || (o.value !== 'default' && sameModel(o)))) {
91
+ const current = opts.find((o) => o.value === chosen) || { value: chosen, label: chosen, description: '' };
92
+ kept.splice(1, 0, current);
93
+ }
94
+ return kept;
95
+ }
96
+
97
+ // The web menu marks the default on its model's row instead of offering a separate Default entry.
98
+ export async function webModelChoices(cfg) {
99
+ const models = (await modelChoices(cfg, { cached: true, picked: new Set(pickedModels()) })).filter((o) => o.value !== 'default');
100
+ const find = (list, spec) => {
101
+ const exact = list.find((o) => o.value === spec);
102
+ if (exact) return exact;
103
+ const { provider, id } = cfg.resolveModel(spec);
104
+ return list.find((o) => o.value === `${provider}/${id}`) || list.find((o) => {
105
+ // Full refs have already been matched; only aliases or the retained override can resolve to a different ref.
106
+ if (o.value.includes('/') && o.value !== cfg.modelOverride) return false;
107
+ const m = cfg.resolveModel(o.value);
108
+ return m.provider === provider && m.id === id;
109
+ });
110
+ };
111
+ let preferred = find(models, cfg.configuredModelSpec);
112
+ if (!preferred) {
113
+ // The default is not among the ticked models: listed anyway, first, by its full name as the ticked ones are, so
114
+ // that the menu can go back to it.
115
+ let ref = cfg.configuredModelSpec;
116
+ try { const m = cfg.resolveModel(ref); ref = `${m.provider}/${m.id}`; } catch { /* as written */ }
117
+ const entry = (await modelChoices(cfg, { cached: true, picked: new Set([ref]) })).find((o) => o.value === ref);
118
+ preferred = entry || { value: ref, label: ref, description: '' };
119
+ models.unshift(preferred);
120
+ }
121
+ const current = find(models, cfg.modelSpec);
122
+ return models.map((o) => ({ ...o, isDefault: o === preferred, current: o === current }));
123
+ }
124
+
125
+ // Ask the gateway and every connected provider for their models now, and keep what they say (the gateway's list on
126
+ // disk, each provider's in its connection): what `cached` choices offer from then on. Resolves with what each said.
127
+ export async function refreshModelLists(cfg) {
128
+ const out = { gateway: null, providers: [] };
129
+ const jobs = [];
130
+ const login = gatewayLogin(cfg.gatewayUrl);
131
+ if (login) {
132
+ jobs.push(fetchGatewayModels(login, { fresh: true, timeoutMs: 15_000 })
133
+ .then((list) => { out.gateway = { count: list.length }; }, (e) => { out.gateway = { error: e.message }; }));
134
+ }
135
+ let catalogue = null;
136
+ for (const info of connectedProviders(readConnections({ fresh: true }))) {
137
+ jobs.push((async () => {
138
+ try {
139
+ const listed = await listProviderModels({ ...info, ...info.connection, baseUrl: info.connection.baseUrl || info.baseUrl }, { timeoutMs: 20_000, kinds: [info.connection.authHeader || 'x-api-key'] });
140
+ if (!listed.models?.length) throw new Error('no models listed');
141
+ if (info.modelsDev) catalogue ??= modelsDevCatalogue().catch(() => null);
142
+ const kept = info.connection.models || [];
143
+ const models = enrichModels(listed.models, info.modelsDev ? await catalogue : null, info.modelsDev)
144
+ .map((m) => ({ ...kept.find((k) => k.id === m.id), ...m })).slice(0, 2000);
145
+ saveConnection(info.id, { ...readConnections({ fresh: true })[info.id], models });
146
+ out.providers.push({ id: info.id, name: info.name, count: models.length });
147
+ } catch (e) {
148
+ out.providers.push({ id: info.id, name: info.name, error: e.message });
149
+ }
150
+ })());
151
+ }
152
+ await Promise.all(jobs);
153
+ return out;
81
154
  }
82
155
 
83
156
  // What /effort offers for the current model: {levels, options: [{value, label, description}]} in plain text (the
84
157
  // levels, auto, default).
85
- export async function effortChoices(cfg) {
158
+ export async function effortChoices(cfg, { cached = false } = {}) {
86
159
  const id = cfg.model.id;
87
160
  let info = null;
88
161
  if (isGpt(id) && cfg.model.provider === GATEWAY_PROVIDER) {
89
162
  const login = gatewayLogin(cfg.gatewayUrl);
90
- try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: true })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
163
+ const kept = cached ? keptGatewayModels(login) : null;
164
+ if (kept) info = kept.find((m) => m.id === id) || null;
165
+ else try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: !cached })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
91
166
  }
92
167
  const levels = effortLevels(id, info);
93
168
  const configured = cfg.configuredEffort;
@@ -560,6 +635,9 @@ export function buildCommands(app) {
560
635
  const kept = models.length ? models : choice !== KEEP ? [{ id: choice }] : [];
561
636
  saveConnection(info.id, {
562
637
  ...(info.custom ? { custom: true, name: info.name, protocol: info.protocol, baseUrl: info.baseUrl } : {}),
638
+ // (another account of a provider stays one, with the name the user gave it)
639
+ ...(existing?.preset ? { preset: existing.preset, ...(existing.baseUrl ? { protocol: existing.protocol, baseUrl: existing.baseUrl } : {}) } : {}),
640
+ ...(existing?.name && !info.custom ? { name: existing.name } : {}),
563
641
  apiKey: key.apiKey,
564
642
  authHeader: info.protocol === 'openai' ? 'bearer' : authHeader || 'x-api-key',
565
643
  ...(Object.keys(quirks).length ? { quirks } : {}),
@@ -618,6 +696,8 @@ export function buildCommands(app) {
618
696
  { label: `${mark(gatewayIn)}7bit.fun`, value: GATEWAY_PROVIDER, description: 'the gateway: Claude and GPT models, balance, the web page, your other computers' },
619
697
  ...PRESETS.map((p) => ({ label: `${mark(Boolean(connections[p.id]))}${p.name}`, value: p.id, description: `${protocolName(p.protocol)} protocol · ${hostOf(p.baseUrl)}` })),
620
698
  ...Object.entries(connections).filter(([, conn]) => conn?.custom).map(([id, conn]) => ({ label: `${mark(true)}${conn.name || id}`, value: id, description: `your own · ${protocolName(conn.protocol)} protocol · ${hostOf(conn.baseUrl)}` })),
699
+ // (the other accounts added in the web console: their key replaced here)
700
+ ...Object.entries(connections).filter(([id, conn]) => conn?.preset && providerInfo(id, connections)).map(([id, conn]) => ({ label: `${mark(true)}${conn.name || id}`, value: id, description: `${id}/<model> · another account` })),
621
701
  { label: ' Your own (Anthropic-compatible)', value: '__custom_anthropic__', description: 'any endpoint with POST /v1/messages' },
622
702
  { label: ' Your own (OpenAI-compatible)', value: '__custom_openai__', description: 'any endpoint with POST /chat/completions: relays, LM Studio, vLLM…' },
623
703
  ],
package/src/config.js CHANGED
@@ -484,6 +484,22 @@ const userSettingsFile = () => path.join(CONFIG_DIR, 'settings.json');
484
484
  // Kept under the name of the provider they were made with, from when there were others: the gateway's.
485
485
  const REMEMBERED_KEY = 'gateway';
486
486
 
487
+ // The models ticked in the web console's 模型列表 (provider/model): its model menus offer only these (and the
488
+ // default and the model in use); none ticked, all. CONFIG_DIR/picker-models.json, {models: [...]}.
489
+ const pickedFile = () => path.join(CONFIG_DIR, 'picker-models.json');
490
+ export function pickedModels() {
491
+ const list = readJson(pickedFile())?.models;
492
+ return Array.isArray(list) ? list.filter((m) => typeof m === 'string' && m.trim()) : [];
493
+ }
494
+ export function savePickedModels(models) {
495
+ const list = [...new Set((Array.isArray(models) ? models : []).filter((m) => typeof m === 'string' && /^[^\s\x00-\x1f]{1,200}$/.test(m)))].slice(0, 500);
496
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
497
+ const tmp = `${pickedFile()}.${process.pid}.tmp`;
498
+ fs.writeFileSync(tmp, JSON.stringify({ models: list }, null, 2));
499
+ fs.renameSync(tmp, pickedFile());
500
+ return list;
501
+ }
502
+
487
503
  function rememberedChoices() {
488
504
  const entry = readJson(userSettingsFile())?.remembered?.[REMEMBERED_KEY];
489
505
  return entry && typeof entry === 'object' ? entry : {};
package/src/gateway.js CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
+ import crypto from 'node:crypto';
11
12
  import { CONFIG_DIR, GATEWAY_DEFAULT_URL, normalizeGatewayUrl, noteServedModels, readGatewayLogin, forgetGatewayLogin } from './config.js';
12
13
 
13
14
  export { GATEWAY_DEFAULT_URL, normalizeGatewayUrl };
@@ -66,6 +67,37 @@ const MODELS_MAX_AGE_MS = 10 * 60_000;
66
67
 
67
68
  const listKey = ({ url, apiKey }) => `${normalizeGatewayUrl(url)}\n${apiKey}`;
68
69
 
70
+ // The last list of each gateway and key, on disk too (cache/gateway-model-lists.json; the key only as a hash): the
71
+ // web console's pickers read it instead of asking the gateway each time they open, also after a restart. Refreshed
72
+ // by every fetch, and by the console's 刷新模型列表 button.
73
+ const listFile = () => path.join(process.env.CLAUDE_PRO_CONFIG_DIR || CONFIG_DIR, 'cache', 'gateway-model-lists.json');
74
+ const diskKey = ({ url, apiKey }) => `${normalizeGatewayUrl(url)} ${crypto.createHash('sha256').update(String(apiKey)).digest('hex').slice(0, 16)}`;
75
+ const readListFile = () => { try { return JSON.parse(fs.readFileSync(listFile(), 'utf8')) || {}; } catch { return {}; } };
76
+ function keepListOnDisk(login, list) {
77
+ try {
78
+ const all = readListFile();
79
+ all[diskKey(login)] = { at: Date.now(), list };
80
+ fs.mkdirSync(path.dirname(listFile()), { recursive: true });
81
+ const tmp = `${listFile()}.${process.pid}.tmp`;
82
+ fs.writeFileSync(tmp, JSON.stringify(all));
83
+ fs.renameSync(tmp, listFile());
84
+ } catch { /* kept in memory still */ }
85
+ }
86
+
87
+ // The list kept for this login (in memory, else on disk) and when it was fetched, without asking the gateway:
88
+ // {list, at}, or null when there is none yet.
89
+ export function keptGatewayList(login) {
90
+ if (!login?.url || !login?.apiKey) return null;
91
+ const key = listKey(login);
92
+ if (modelLists.has(key)) return modelLists.get(key);
93
+ const kept = readListFile()[diskKey(login)];
94
+ if (!Array.isArray(kept?.list)) return null;
95
+ const entry = { list: kept.list, at: kept.at || 0 };
96
+ modelLists.set(key, entry);
97
+ return entry;
98
+ }
99
+ export const keptGatewayModels = (login) => keptGatewayList(login)?.list || null;
100
+
69
101
  // One GET /v1/models at a time per key. It carries only its own timeout: a caller that gives up (its signal) leaves
70
102
  // it running for the others and the cache (see untilAborted).
71
103
  function requestModels(key, { url, apiKey }, { fetchImpl, timeoutMs }) {
@@ -83,6 +115,7 @@ function requestModels(key, { url, apiKey }, { fetchImpl, timeoutMs }) {
83
115
  modelLists.set(key, { list, at: Date.now() });
84
116
  modelListFailures.delete(key);
85
117
  noteServedModels(base, list);
118
+ keepListOnDisk({ url, apiKey }, list);
86
119
  return list;
87
120
  }, (e) => {
88
121
  modelListFailures.set(key, { at: Date.now(), error: e });
package/src/providers.js CHANGED
@@ -60,9 +60,21 @@ export function validBaseUrl(url) {
60
60
  export const cleanProviderId = (name) => String(name || '').trim().toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 30);
61
61
  export const reservedProviderId = (id) => id === GATEWAY_PROVIDER || PRESET_IDS.has(id);
62
62
 
63
+ // The id of a new connection named after `base` that no other connection, built-in provider or the gateway has: the
64
+ // second DeepSeek is deepseek-2, the next deepseek-3.
65
+ export function nextInstanceId(base, connections = readConnections()) {
66
+ const stem = cleanProviderId(base) || 'provider';
67
+ const free = (id) => !connections[id] && !reservedProviderId(id);
68
+ if (free(stem)) return stem;
69
+ for (let n = 2; ; n++) if (free(`${stem}-${n}`)) return `${stem}-${n}`;
70
+ }
71
+
63
72
  // {id: connection}. A connection: {apiKey, authHeader, model?, models: [{id, name?, window?, maxOutput?, price?}],
64
- // savedAt} (model: the one chosen at /connect), and for the user's own providers also {custom: true, name, protocol,
65
- // baseUrl}. Read again at most once a second (the model is resolved at every frame of the footer), and at once after
73
+ // savedAt, name?} (model: the one chosen at /connect; name: what the user called it, else the provider's own), and for
74
+ // the user's own providers also {custom: true, name, protocol, baseUrl}. A second account of a built-in provider (or of
75
+ // 7bit.fun) is a connection of its own under another id (deepseek-2, 7bit-2: see nextInstanceId) with {preset: the
76
+ // provider's id}, and for 7bit.fun's also {protocol, baseUrl}; its models are deepseek-2/<model>. The entry "7bit"
77
+ // holds at most the name given to the gateway's own login (gateway.json has its key). Read again at most once a second (the model is resolved at every frame of the footer), and at once after
66
78
  // this process changed the file; another window's change is seen within the second. Not to be changed by callers.
67
79
  const MEMO_MS = 1000;
68
80
  let memo = null; // {at, data}
@@ -105,7 +117,13 @@ export function removeConnection(id) {
105
117
  export function providerInfo(id, connections = readConnections()) {
106
118
  const connection = connections[id] || null;
107
119
  const preset = PRESETS.find((p) => p.id === id);
108
- if (preset) return { ...preset, connection };
120
+ if (preset) return { ...preset, name: connection?.name || preset.name, connection };
121
+ // another account of a built-in provider, or of 7bit.fun (its address kept in the connection)
122
+ if (connection?.preset) {
123
+ const base = connection.preset === GATEWAY_PROVIDER ? { name: '7bit.fun', protocol: 'anthropic' } : PRESETS.find((p) => p.id === connection.preset);
124
+ const baseUrl = connection.baseUrl || base?.baseUrl;
125
+ if (base && baseUrl) return { ...base, id, name: connection.name || base.name, baseUrl, preset: connection.preset, connection };
126
+ }
109
127
  if (connection?.custom && connection.baseUrl) {
110
128
  return { id, name: connection.name || id, protocol: connection.protocol === 'openai' ? 'openai' : 'anthropic', baseUrl: connection.baseUrl, custom: true, connection };
111
129
  }
@@ -115,8 +133,8 @@ export function providerInfo(id, connections = readConnections()) {
115
133
  // The providers that are connected now, in the order /connect lists them (the gateway is not among them: see
116
134
  // gatewayLogin).
117
135
  export function connectedProviders(connections = readConnections()) {
118
- const rank = (id) => { const i = PRESETS.findIndex((p) => p.id === id); return i < 0 ? PRESETS.length : i; };
119
- return Object.keys(connections).sort((a, b) => rank(a) - rank(b))
136
+ const rank = (id) => { const i = PRESETS.findIndex((p) => p.id === (connections[id]?.preset || id)); return i < 0 ? PRESETS.length : i; };
137
+ return Object.keys(connections).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b, 'en', { numeric: true }))
120
138
  .map((id) => providerInfo(id, connections)).filter((p) => p?.connection && (p.connection.apiKey || p.keyless || p.custom));
121
139
  }
122
140
 
@@ -130,7 +148,8 @@ export function splitModelRef(spec, connections = null) {
130
148
  if (slash > 0) {
131
149
  const prefix = name.slice(0, slash).toLowerCase();
132
150
  const rest = name.slice(slash + 1);
133
- if (rest && (prefix === GATEWAY_PROVIDER || PRESET_IDS.has(prefix) || (connections ?? readConnections())[prefix]?.custom)) return { provider: prefix, model: rest };
151
+ const conn = rest && !(prefix === GATEWAY_PROVIDER || PRESET_IDS.has(prefix)) ? (connections ?? readConnections())[prefix] : null;
152
+ if (rest && (prefix === GATEWAY_PROVIDER || PRESET_IDS.has(prefix) || conn?.custom || conn?.preset)) return { provider: prefix, model: rest };
134
153
  }
135
154
  return { provider: GATEWAY_PROVIDER, model: name };
136
155
  }
package/src/remote.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import os from 'node:os';
9
9
  import crypto from 'node:crypto';
10
10
  import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
11
+ import { c } from './ui/ansi.js';
11
12
  import { shownQuotes } from './ui/editor.js';
12
13
 
13
14
  export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
@@ -102,13 +103,19 @@ function shownUserText(text) {
102
103
 
103
104
  // Transcript items for a conversation (agent.messages), as the page shows them when it connects.
104
105
  // `limit`: the newest items kept (the web console's history view takes them all); `images`: an image is {k: 'image', n}
105
- // (the n-th image of the conversation) instead of the text [image].
106
- export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE_WIDTH, limit = SEED_ITEMS, images = false } = {}) {
106
+ // (the n-th image of the conversation) instead of the text [image]; `turns`: the lines shown where turns ended
107
+ // ([{after, text}], see SessionStore.turnEnd), each put back after its message as the terminal printed it.
108
+ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE_WIDTH, limit = SEED_ITEMS, images = false, turns = [] } = {}) {
107
109
  let imageCount = 0;
108
110
  const toolMap = new Map(tools.map((t) => [t.name, t]));
109
111
  const items = [];
110
112
  const calls = new Map();
111
- for (const m of messages || []) {
113
+ const ends = new Map();
114
+ for (const t of turns || []) if (t?.text && Number.isInteger(t.after)) ends.set(t.after, [...(ends.get(t.after) || []), t.text]);
115
+ const list = messages || [];
116
+ for (let i = 0; i < list.length; i++) {
117
+ const m = list[i];
118
+ for (const text of ends.get(i) || []) items.push({ k: 'output', lines: [c.dim(text), ''] }); // (after the first i messages)
112
119
  const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : (m.content || []);
113
120
  for (const b of blocks) {
114
121
  if (m.role === 'user') {
@@ -142,6 +149,7 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
142
149
  }
143
150
  }
144
151
  }
152
+ for (const text of ends.get(list.length) || []) items.push({ k: 'output', lines: [c.dim(text), ''] });
145
153
  return Number.isFinite(limit) ? items.slice(-limit) : items;
146
154
  }
147
155
 
package/src/session.js CHANGED
@@ -311,6 +311,11 @@ export class SessionStore {
311
311
  // The name the user gave the conversation with /rename (null: none again); it wins over the topic.
312
312
  setName(name) { this.append({ type: 'meta', name, at: Date.now() }); }
313
313
  reset(messages) { this.append({ type: 'reset', messages, at: Date.now() }); }
314
+ // Where a turn ended (after how many messages) and the line shown then ("✻ Done at 14:05 · worked 1m 3s · …"):
315
+ // the web console's view is rebuilt from the conversation (a reload, a restart) and puts it back under the answer.
316
+ turnEnd(after, text) { this.append({ type: 'turn', after, text, at: Date.now() }); }
317
+ // All of them again after the messages were replaced: a reset drops those before it (see App.messagesReplaced).
318
+ setTurns(marks) { this.append({ type: 'turns', marks: marks.map(({ after, text }) => ({ after, text })), at: Date.now() }); }
314
319
  // What the conversation's requests have cost so far (USD, see pricing.js), written after each one; the newest wins.
315
320
  setCost(usd) { this.append({ type: 'meta', cost: usd, at: Date.now() }); }
316
321
  // Until when the conversation's prompt cache lasts (ms since epoch; 0: cold), for the footer's clock of a
@@ -341,6 +346,7 @@ export class SessionStore {
341
346
  let meta = {};
342
347
  let title = null;
343
348
  let lastAt = 0; // when the conversation last changed: the latest message or reset (0: unknown)
349
+ let turns = []; // [{after, text}]: see turnEnd
344
350
  for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
345
351
  if (!line.trim()) continue;
346
352
  let e;
@@ -348,6 +354,8 @@ export class SessionStore {
348
354
  if (e.type === 'message' || e.type === 'reset') lastAt = Math.max(lastAt, e.at || 0);
349
355
  if (e.type === 'reset') meta = { ...meta, cacheState: null }; // what was cached is not the new messages' prefix
350
356
  if (e.type === 'meta') meta = { ...meta, ...e };
357
+ else if (e.type === 'turn') turns.push({ after: e.after, text: e.text });
358
+ else if (e.type === 'turns') turns = Array.isArray(e.marks) ? e.marks.slice() : [];
351
359
  else if (e.type === 'message') {
352
360
  messages.push(e.message);
353
361
  times.push(e.at || 0);
@@ -357,10 +365,13 @@ export class SessionStore {
357
365
  // so their own times are unknown.
358
366
  messages.splice(0, messages.length, ...e.messages);
359
367
  times.splice(0, times.length, ...e.messages.map(() => 0));
368
+ turns = [];
360
369
  }
361
370
  }
371
+ turns = turns.filter((t) => Number.isInteger(t?.after) && t.after >= 1 && t.after <= messages.length && typeof t.text === 'string' && t.text)
372
+ .sort((a, b) => a.after - b.after);
362
373
  return {
363
- messages, times, lastAt, meta, title,
374
+ messages, times, lastAt, meta, title, turns,
364
375
  topic: typeof meta.topic === 'string' && meta.topic.trim() ? meta.topic : null,
365
376
  name: typeof meta.name === 'string' && meta.name.trim() ? meta.name : null,
366
377
  systemPrompt: typeof meta.systemPrompt === 'string' && meta.systemPrompt.trim() ? meta.systemPrompt : null,