@yanzc/claude-pro 0.12.0 → 0.14.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 +8 -7
- package/package.json +1 -1
- package/src/agents.js +0 -52
- package/src/commands.js +111 -36
- package/src/config.js +16 -0
- package/src/gateway.js +33 -0
- package/src/providers.js +25 -6
- package/src/remote.js +11 -3
- package/src/session.js +12 -1
- package/src/ui/repl.js +80 -30
- package/src/web/api.js +146 -57
- package/src/web/app.css +303 -177
- package/src/web/app.js +558 -113
- package/src/web/data.js +21 -6
- package/src/web/host.js +2 -4
- package/src/web/login.html +3 -2
- package/src/web/logo.svg +1 -0
- package/src/web/page.html +7 -4
- package/src/web/remote-access.js +24 -0
- package/src/web/server.js +32 -3
package/README.md
CHANGED
|
@@ -196,28 +196,29 @@ 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
|
-
-
|
|
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
|
-
-
|
|
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
|
-
-
|
|
208
|
+
- **扩展**:最上面是「内置工具」清单(每次请求发给模型的工具,写在程序里,不是 MCP;鼠标悬停看发给模型的原文)。下面是技能、子 agent、MCP 和 hooks,可以查看和编辑。MCP 一栏先列内置的能力(浏览器、联网搜索、抓取网页、文件系统、代码执行、进程管理、多会话协作:别的工具要装 MCP 才有,这里不用安装),再列你接入的外部 MCP 服务器(环境变量和请求头的值不显示)。「让 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 的文件,也不能打开会话记录以外的任意文件。
|
|
211
212
|
|
|
212
213
|
## 远程访问:在手机上用这台电脑的控制台
|
|
213
214
|
|
|
214
|
-
|
|
215
|
+
远程访问需要先连接 7bit.fun。在控制台「远程访问」页或会话里的 `/web remote on` 开启:第一次会让你设一个至少 10 位的密码,并自己选一个域名前缀(3–20 个小写字母、数字或 `-`,只要没人用过),比如 `yanzc`,控制台就能在 **`https://yanzc.7bit.fun`** 打开:手机或别的电脑上打开这个地址,输入密码,就能看会话、发任务(可以带图片)、回答问题、改设置。手机上通过左上角菜单打开工作区,聊天和输入区适应小屏幕。前缀也是你在网关的通讯号,之后可以在「远程访问」页点「修改前缀」(旧地址随即失效)。
|
|
215
216
|
|
|
216
217
|
- **怎么连的**:本机控制台的后台服务主动连一条 WebSocket 到 7bit.fun 网关(用 `/connect` 保存的 Key),网关把这个域名的请求从这条连接转给它。电脑不开任何端口,转过来的请求只能到控制台本身。
|
|
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
|
## 会话之间互发任务(本机和其他电脑)
|
|
@@ -241,7 +242,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
|
|
|
241
242
|
|
|
242
243
|
不同网关账户之间,双方同意后,各自的 claude-pro 会话也能互发任务。
|
|
243
244
|
|
|
244
|
-
- **通讯号**:每个账户有一个公开的通讯号(默认随机,如 `cp7k3qxm`),别人用它加你,看不到你的邮箱。`/contacts handle
|
|
245
|
+
- **通讯号**:每个账户有一个公开的通讯号(默认随机,如 `cp7k3qxm`),别人用它加你,看不到你的邮箱。`/contacts handle 新名字`、控制台「远程访问」页或网关网页「通讯录」里修改(3-20 个小写字母、数字或 `-`,以字母开头;它也是远程访问的域名前缀)。
|
|
245
246
|
- **加好友**:`/contacts add 对方通讯号` 发出请求;对方在线的会话会提示,对方用 `/contacts accept 你的通讯号` 同意(也可以 `reject`、`block`),或在网页通讯录里点同意。双方互相请求时直接成为好友。`/contacts remove` 删除,`/contacts block` 拉黑(对方不能再请求、不能发任务,也不会被告知)。`/contacts` 列出全部。
|
|
246
247
|
- **发任务**:好友在线的会话在 `/peers` 和 ListPeers 里显示为 `@通讯号:电脑名/会话名`;`@通讯号 任务`(对方只开着一个会话时)或 `@通讯号:电脑名/会话名 任务` 发送,回答自动发回。
|
|
247
248
|
- **确认**:好友发来的任务默认在终端弹窗问你「执行 / 拒绝 / 以后都执行」,拒绝时对方会收到“已拒绝”。`/contacts trust 通讯号 auto` 让这个好友的任务直接执行,`confirm` 改回每条确认。交给模型时会注明这是外人的请求、不是用户的指令,并要求它不泄露密钥和私人文件、不做破坏性操作。
|
|
@@ -288,7 +289,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
|
|
|
288
289
|
|
|
289
290
|
**`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件/会话补全、输入历史都换成新目录的;对话、模型、effort、待办不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
|
|
290
291
|
|
|
291
|
-
**斜杠命令**:`/help` `/cd` `/rename` `/peers` `/contacts` `/web`(`/web remote …`)`/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/trace` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/rewind` `/skills` `/resume` `/todos` `/agents` `/mcp` `/bashes` `/verbose` `/export` `/doctor` `/exit
|
|
292
|
+
**斜杠命令**:`/help` `/cd` `/rename` `/peers` `/contacts` `/web`(`/web remote …`)`/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/trace` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/rewind` `/skills` `/resume` `/todos` `/agents` `/mcp` `/bashes` `/verbose` `/export` `/doctor` `/exit`。技能也可以直接用 `/技能名 参数` 运行。
|
|
292
293
|
|
|
293
294
|
**记忆**:自动读取 `~/.claude-pro/CLAUDE.md`、项目各级目录的 `CLAUDE.md` / `.claude/CLAUDE.md` / `CLAUDE.local.md`;某一级目录没有 `CLAUDE.md` 时读它的 `AGENTS.md` 代替(两者都有时通常是同一份说明,不重复发送)。
|
|
294
295
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.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/agents.js
CHANGED
|
@@ -139,55 +139,3 @@ export function renderSkill(skill, args = '') {
|
|
|
139
139
|
if (args && !skill.body.includes('$ARGUMENTS')) body += `\n\nARGUMENTS: ${args}`;
|
|
140
140
|
return `Base directory for this skill: ${skill.dir}\n\n${body}`;
|
|
141
141
|
}
|
|
142
|
-
|
|
143
|
-
// The text a custom command expands to: $ARGUMENTS and $1..$9 filled in. One pass with a function, so
|
|
144
|
-
// what the arguments contain (`$1`, `$&`, `$$`) is neither interpreted nor expanded a second time.
|
|
145
|
-
export function expandCommandBody(body, args = '') {
|
|
146
|
-
const argv = args.split(/\s+/).filter(Boolean);
|
|
147
|
-
let out = body.replace(/\$ARGUMENTS|\$(\d)/g, (m, n) => (n === undefined ? args : (argv[+n - 1] ?? '')));
|
|
148
|
-
if (!body.includes('$ARGUMENTS') && args) out += `\n\nARGUMENTS: ${args}`;
|
|
149
|
-
return out;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// !`command` in a command file is replaced by what `command` prints (run(command) -> text).
|
|
153
|
-
export async function expandShellEmbeds(body, run) {
|
|
154
|
-
let out = body;
|
|
155
|
-
for (const m of [...body.matchAll(/!`([^`]+)`/g)]) {
|
|
156
|
-
const output = await run(m[1]);
|
|
157
|
-
out = out.replace(m[0], () => output); // a function: the output may contain `$&` or `$$` (shell scripts do)
|
|
158
|
-
}
|
|
159
|
-
return out;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// Custom slash commands: .claude/commands/*.md, .claude-pro/commands/*.md, ~/.claude-pro/commands/*.md
|
|
163
|
-
export function loadCustomCommands(cwd) {
|
|
164
|
-
const commands = new Map();
|
|
165
|
-
const dirs = [
|
|
166
|
-
[path.join(CONFIG_DIR, 'commands'), 'user'],
|
|
167
|
-
[path.join(cwd, '.claude', 'commands'), 'project'],
|
|
168
|
-
[path.join(cwd, '.claude-pro', 'commands'), 'project'],
|
|
169
|
-
];
|
|
170
|
-
const walk = (dir, prefix, scope) => {
|
|
171
|
-
let entries = [];
|
|
172
|
-
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
173
|
-
for (const e of entries) {
|
|
174
|
-
if (e.isDirectory()) { walk(path.join(dir, e.name), `${prefix}${e.name}:`, scope); continue; }
|
|
175
|
-
if (!e.name.endsWith('.md')) continue;
|
|
176
|
-
const file = path.join(dir, e.name);
|
|
177
|
-
let text;
|
|
178
|
-
try { text = fs.readFileSync(file, 'utf8'); } catch { continue; } // a broken link or a locked file must not stop the others
|
|
179
|
-
const parsed = parseFrontmatter(text);
|
|
180
|
-
const body = parsed ? parsed.body : text.replace(/^\uFEFF/, '');
|
|
181
|
-
const name = prefix + e.name.slice(0, -3);
|
|
182
|
-
commands.set(name, {
|
|
183
|
-
name,
|
|
184
|
-
description: parsed?.meta.description || body.split('\n').find((l) => l.trim())?.slice(0, 80) || `(${scope})`,
|
|
185
|
-
argumentHint: parsed?.meta['argument-hint'] || '',
|
|
186
|
-
body,
|
|
187
|
-
scope,
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
for (const [dir, scope] of dirs) walk(dir, '', scope);
|
|
192
|
-
return commands;
|
|
193
|
-
}
|
package/src/commands.js
CHANGED
|
@@ -5,13 +5,13 @@ 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';
|
|
13
13
|
import { INIT_PROMPT } from './prompts.js';
|
|
14
|
-
import {
|
|
14
|
+
import { renderSkill } from './agents.js';
|
|
15
15
|
import { listBackgroundShells } from './tools/bash.js';
|
|
16
16
|
import { estimateTokens } from './agent.js';
|
|
17
17
|
import { quickQuery, cacheRefusals, defaultEffort, effortToSend, CLAUDE_EFFORTS } from './api.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
|
-
|
|
35
|
+
// `cached` (the web console's pickers): the kept lists only, nothing asked (its 刷新模型列表 button renews them).
|
|
36
|
+
async function providerModelChoices({ cached = false } = {}) {
|
|
36
37
|
const groups = await Promise.all(connectedProviders().map(async (info) => {
|
|
37
38
|
let listed = null;
|
|
38
|
-
try {
|
|
39
|
+
if (!cached) try {
|
|
39
40
|
listed = (await listProviderModels({ ...info, ...info.connection, baseUrl: info.connection.baseUrl || info.baseUrl }, { timeoutMs: 4000, kinds: [info.connection.authHeader || 'x-api-key'] })).models;
|
|
40
41
|
} catch { /* the kept list */ }
|
|
41
42
|
const kept = info.connection.models || [];
|
|
@@ -49,12 +50,15 @@ async function providerModelChoices() {
|
|
|
49
50
|
return groups.flat();
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
// What /model offers
|
|
53
|
+
// What /model offers: [{value, label, description}] in plain text, the
|
|
53
54
|
// default first. `value` is what /model <value> takes. Every connected provider's models, provider/model, 7bit.fun's
|
|
54
55
|
// among them (asked for anew each time, 4 seconds at most, so that a model just added is there without a restart;
|
|
55
56
|
// without an answer the list given last, else gpt-6.1-sol for its GPT models); the Claude aliases where a provider of
|
|
56
57
|
// Claude is connected. A provider that is not connected offers nothing.
|
|
57
|
-
|
|
58
|
+
// `cached`: the lists kept from before (see providerModelChoices); the gateway is asked only when none is kept yet.
|
|
59
|
+
// `picked` (the web console's menus, see pickedModels): a set of provider/model; when it has any, only those are
|
|
60
|
+
// offered by their full names (not the aliases), with the default and the model in use.
|
|
61
|
+
export async function modelChoices(cfg, { cached = false, picked = null } = {}) {
|
|
58
62
|
const configured = cfg.configuredModelSpec;
|
|
59
63
|
const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).label}` }];
|
|
60
64
|
const tag = (m) => `${m.provider}/${m.id}`;
|
|
@@ -66,28 +70,99 @@ export async function modelChoices(cfg) {
|
|
|
66
70
|
opts.push({ value: a, label: a, description: `→ ${target.label}` });
|
|
67
71
|
}
|
|
68
72
|
}
|
|
69
|
-
const others = providerModelChoices();
|
|
73
|
+
const others = providerModelChoices({ cached });
|
|
74
|
+
const gateway = [];
|
|
70
75
|
const login = gatewayLogin(cfg.gatewayUrl);
|
|
71
76
|
if (login) {
|
|
72
|
-
let served = null;
|
|
73
|
-
try { served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh:
|
|
77
|
+
let served = cached ? keptGatewayModels(login) : null;
|
|
78
|
+
if (!served) try { served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: !cached }); } catch { /* offline: the fallback below */ }
|
|
74
79
|
for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
|
|
75
|
-
|
|
76
|
-
opts.push({ value: `${GATEWAY_PROVIDER}/${m.id}`, label: `${GATEWAY_PROVIDER}/${m.id}`, description: ['7bit.fun', isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || ''].filter(Boolean).join(' · ') });
|
|
80
|
+
gateway.push({ value: `${GATEWAY_PROVIDER}/${m.id}`, label: `${GATEWAY_PROVIDER}/${m.id}`, description: ['7bit.fun', isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || ''].filter(Boolean).join(' · ') });
|
|
77
81
|
}
|
|
78
82
|
}
|
|
79
|
-
|
|
80
|
-
|
|
83
|
+
const providers = await others;
|
|
84
|
+
opts.push(...gateway.filter((o) => !aliased.has(o.value)), ...providers.filter((o) => !aliased.has(o.value)));
|
|
85
|
+
if (!picked?.size) return opts;
|
|
86
|
+
const kept = [opts[0], ...[...gateway, ...providers].filter((o) => picked.has(o.value))];
|
|
87
|
+
// the model in use stays listed (it is shown as the current one), unless a ticked entry is that model already
|
|
88
|
+
const chosen = cfg.modelOverride;
|
|
89
|
+
const sameModel = (o) => { try { const m = cfg.resolveModel(o.value); return m.id === cfg.model.id && m.provider === cfg.model.provider; } catch { return false; } };
|
|
90
|
+
if (chosen && !kept.some((o) => o.value === chosen || (o.value !== 'default' && sameModel(o)))) {
|
|
91
|
+
const current = opts.find((o) => o.value === chosen) || { value: chosen, label: chosen, description: '' };
|
|
92
|
+
kept.splice(1, 0, current);
|
|
93
|
+
}
|
|
94
|
+
return kept;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// The web menu marks the default on its model's row instead of offering a separate Default entry.
|
|
98
|
+
export async function webModelChoices(cfg) {
|
|
99
|
+
const models = (await modelChoices(cfg, { cached: true, picked: new Set(pickedModels()) })).filter((o) => o.value !== 'default');
|
|
100
|
+
const find = (list, spec) => {
|
|
101
|
+
const exact = list.find((o) => o.value === spec);
|
|
102
|
+
if (exact) return exact;
|
|
103
|
+
const { provider, id } = cfg.resolveModel(spec);
|
|
104
|
+
return list.find((o) => o.value === `${provider}/${id}`) || list.find((o) => {
|
|
105
|
+
// Full refs have already been matched; only aliases or the retained override can resolve to a different ref.
|
|
106
|
+
if (o.value.includes('/') && o.value !== cfg.modelOverride) return false;
|
|
107
|
+
const m = cfg.resolveModel(o.value);
|
|
108
|
+
return m.provider === provider && m.id === id;
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
let preferred = find(models, cfg.configuredModelSpec);
|
|
112
|
+
if (!preferred) {
|
|
113
|
+
// The default is not among the ticked models: listed anyway, first, by its full name as the ticked ones are, so
|
|
114
|
+
// that the menu can go back to it.
|
|
115
|
+
let ref = cfg.configuredModelSpec;
|
|
116
|
+
try { const m = cfg.resolveModel(ref); ref = `${m.provider}/${m.id}`; } catch { /* as written */ }
|
|
117
|
+
const entry = (await modelChoices(cfg, { cached: true, picked: new Set([ref]) })).find((o) => o.value === ref);
|
|
118
|
+
preferred = entry || { value: ref, label: ref, description: '' };
|
|
119
|
+
models.unshift(preferred);
|
|
120
|
+
}
|
|
121
|
+
const current = find(models, cfg.modelSpec);
|
|
122
|
+
return models.map((o) => ({ ...o, isDefault: o === preferred, current: o === current }));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Ask the gateway and every connected provider for their models now, and keep what they say (the gateway's list on
|
|
126
|
+
// disk, each provider's in its connection): what `cached` choices offer from then on. Resolves with what each said.
|
|
127
|
+
export async function refreshModelLists(cfg) {
|
|
128
|
+
const out = { gateway: null, providers: [] };
|
|
129
|
+
const jobs = [];
|
|
130
|
+
const login = gatewayLogin(cfg.gatewayUrl);
|
|
131
|
+
if (login) {
|
|
132
|
+
jobs.push(fetchGatewayModels(login, { fresh: true, timeoutMs: 15_000 })
|
|
133
|
+
.then((list) => { out.gateway = { count: list.length }; }, (e) => { out.gateway = { error: e.message }; }));
|
|
134
|
+
}
|
|
135
|
+
let catalogue = null;
|
|
136
|
+
for (const info of connectedProviders(readConnections({ fresh: true }))) {
|
|
137
|
+
jobs.push((async () => {
|
|
138
|
+
try {
|
|
139
|
+
const listed = await listProviderModels({ ...info, ...info.connection, baseUrl: info.connection.baseUrl || info.baseUrl }, { timeoutMs: 20_000, kinds: [info.connection.authHeader || 'x-api-key'] });
|
|
140
|
+
if (!listed.models?.length) throw new Error('no models listed');
|
|
141
|
+
if (info.modelsDev) catalogue ??= modelsDevCatalogue().catch(() => null);
|
|
142
|
+
const kept = info.connection.models || [];
|
|
143
|
+
const models = enrichModels(listed.models, info.modelsDev ? await catalogue : null, info.modelsDev)
|
|
144
|
+
.map((m) => ({ ...kept.find((k) => k.id === m.id), ...m })).slice(0, 2000);
|
|
145
|
+
saveConnection(info.id, { ...readConnections({ fresh: true })[info.id], models });
|
|
146
|
+
out.providers.push({ id: info.id, name: info.name, count: models.length });
|
|
147
|
+
} catch (e) {
|
|
148
|
+
out.providers.push({ id: info.id, name: info.name, error: e.message });
|
|
149
|
+
}
|
|
150
|
+
})());
|
|
151
|
+
}
|
|
152
|
+
await Promise.all(jobs);
|
|
153
|
+
return out;
|
|
81
154
|
}
|
|
82
155
|
|
|
83
156
|
// What /effort offers for the current model: {levels, options: [{value, label, description}]} in plain text (the
|
|
84
157
|
// levels, auto, default).
|
|
85
|
-
export async function effortChoices(cfg) {
|
|
158
|
+
export async function effortChoices(cfg, { cached = false } = {}) {
|
|
86
159
|
const id = cfg.model.id;
|
|
87
160
|
let info = null;
|
|
88
161
|
if (isGpt(id) && cfg.model.provider === GATEWAY_PROVIDER) {
|
|
89
162
|
const login = gatewayLogin(cfg.gatewayUrl);
|
|
90
|
-
|
|
163
|
+
const kept = cached ? keptGatewayModels(login) : null;
|
|
164
|
+
if (kept) info = kept.find((m) => m.id === id) || null;
|
|
165
|
+
else try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: !cached })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
|
|
91
166
|
}
|
|
92
167
|
const levels = effortLevels(id, info);
|
|
93
168
|
const configured = cfg.configuredEffort;
|
|
@@ -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
|
],
|
|
@@ -964,18 +1044,31 @@ export function buildCommands(app) {
|
|
|
964
1044
|
return;
|
|
965
1045
|
}
|
|
966
1046
|
if (action === 'on') {
|
|
967
|
-
|
|
1047
|
+
const login = gatewayLogin(cfg.gatewayUrl);
|
|
1048
|
+
if (!login) { out(c.red(`远程访问通过 7bit.fun 网关:先 /connect 7bit.fun 连上网关。`)); return; }
|
|
968
1049
|
if (!ra.hasPassword()) {
|
|
969
1050
|
const pw = await askPassword(ra);
|
|
970
1051
|
if (!pw) { out(c.dim('远程访问没有开启。')); return; }
|
|
971
1052
|
ra.setPassword(pw);
|
|
972
1053
|
}
|
|
1054
|
+
// the address's prefix: chosen by the user the first time, not the one the gateway made up
|
|
1055
|
+
let prefix;
|
|
1056
|
+
try { prefix = await ra.addressPrefix(login); } catch (e) { out(c.red(`读不到域名前缀:${e.message}`)); return; }
|
|
1057
|
+
while (prefix.auto) {
|
|
1058
|
+
const wanted = await app.showDialog(new TextInputDialog({
|
|
1059
|
+
title: '远程访问域名',
|
|
1060
|
+
body: [`选一个域名前缀:https://<前缀>.${prefix.domain}`, '3–20 个小写字母、数字或 -,字母开头、不以 - 结尾;要唯一(它也是你在网关的通讯号)。'],
|
|
1061
|
+
question: '前缀:',
|
|
1062
|
+
}));
|
|
1063
|
+
if (wanted === null || !String(wanted).trim()) { out(c.dim('远程访问没有开启。')); return; }
|
|
1064
|
+
try { prefix = await ra.addressPrefix(login, String(wanted).trim().toLowerCase()); } catch (e) { out(c.yellow(e.message)); }
|
|
1065
|
+
}
|
|
973
1066
|
ra.setEnabled(true);
|
|
974
1067
|
out(c.dim('正在连接网关…'));
|
|
975
1068
|
} else if (action) { out(c.red('/web remote [on|off|password|logout]')); return; }
|
|
976
1069
|
const d = ra.readRemote();
|
|
977
1070
|
if (!d.enabled) {
|
|
978
|
-
out([`远程访问:${c.dim('关闭')}`, c.dim('/web remote on
|
|
1071
|
+
out([`远程访问:${c.dim('关闭')}`, c.dim('/web remote on 开启:第一次选一个域名前缀,在手机上打开 https://<前缀>.7bit.fun,输入密码就能用这台电脑的 claude-pro 控制台。')]);
|
|
979
1072
|
return;
|
|
980
1073
|
}
|
|
981
1074
|
let view;
|
|
@@ -1287,24 +1380,6 @@ export function buildCommands(app) {
|
|
|
1287
1380
|
run() { app.exit(0); },
|
|
1288
1381
|
});
|
|
1289
1382
|
|
|
1290
|
-
// Custom commands from markdown files.
|
|
1291
|
-
for (const custom of loadCustomCommands(app.cwd).values()) {
|
|
1292
|
-
if (commands.has(custom.name)) continue;
|
|
1293
|
-
add({
|
|
1294
|
-
name: custom.name,
|
|
1295
|
-
argHint: custom.argumentHint,
|
|
1296
|
-
description: `${custom.description} ${c.dim(`(${custom.scope})`)}`,
|
|
1297
|
-
async run(args) {
|
|
1298
|
-
const bash = app.runtime.tools.find((t) => t.name === 'Bash');
|
|
1299
|
-
const body = await expandShellEmbeds(expandCommandBody(custom.body, args), async (command) => {
|
|
1300
|
-
const r = await bash.call({ command }, app.agent.makeCtx());
|
|
1301
|
-
return typeof r.content === 'string' ? r.content : '';
|
|
1302
|
-
});
|
|
1303
|
-
return app.startTurn(body, { echo: false });
|
|
1304
|
-
},
|
|
1305
|
-
});
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
1383
|
// Skills can be run directly as /<skill-name> [arguments].
|
|
1309
1384
|
for (const skill of app.runtime.skills.values()) {
|
|
1310
1385
|
if (commands.has(skill.name)) continue;
|
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
|
|
65
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,
|