@yanzc/claude-pro 0.13.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 CHANGED
@@ -205,14 +205,14 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
205
205
  - **模型与供应商**:「添加供应商」连接 7bit.fun、各家供应商或自定义的 OpenAI/Anthropic 兼容接口(粘贴 Key → 列出模型 → 测试 → 保存,和 /connect 一样)。每个连接有自己的「名称」,默认是供应商的名字,可以改,显示在 tab 和模型菜单里。同一家可以连好几个账号:第二个 DeepSeek 的模型写成 `deepseek-2/模型`,7bit.fun 的第二个账号是 `7bit-2/模型`。每家一个 tab,tab 里能改名称、换 Key、断开,勾选会话菜单里要用的模型;上面设置默认模型和思考强度。Key 只显示开头和结尾。第一次打开控制台、还没有任何供应商时,会先提示去添加。
206
206
  - **设置**:所有普通和高级设置,中文说明、当前生效的值和它来自哪一层,可以写到用户、项目或项目本地的设置文件,或恢复默认。
207
207
  - **记忆与指令**:全局和各项目的 CLAUDE.md、自动记忆,查看、编辑、删除(删除的文件移到 `~/.claude-pro/trash/files`)。
208
- - **扩展**:技能、子 agent、自定义命令、MCP 服务器(环境变量和请求头的值不显示)和 hooks,可以查看和编辑。「让 AI 新建」会打开新会话并预填要求(文件位置和格式),写上用途就交给模型去做;选了项目时放在那个项目里。
208
+ - **扩展**:最上面是「内置工具」清单(每次请求发给模型的工具,写在程序里,不是 MCP;鼠标悬停看发给模型的原文)。下面是技能、子 agent、MCP 和 hooks,可以查看和编辑。MCP 一栏先列内置的能力(浏览器、联网搜索、抓取网页、文件系统、代码执行、进程管理、多会话协作:别的工具要装 MCP 才有,这里不用安装),再列你接入的外部 MCP 服务器(环境变量和请求头的值不显示)。「让 AI 新建」会打开新会话并预填要求(文件位置和格式),写上用途就交给模型去做;选了项目时放在那个项目里。
209
209
  - **用量**:近 7/30/90 天按天、模型、项目统计的请求数、tokens 和按价格估算的花费(来自运行 Trace),以及花费最多的会话。
210
210
 
211
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 的文件,也不能打开会话记录以外的任意文件。
212
212
 
213
213
  ## 远程访问:在手机上用这台电脑的控制台
214
214
 
215
- 在会话里运行 `/web remote on`(第一次会让你设一个至少 10 位的密码),控制台就能在 **`https://<你的通讯号>.7bit.fun`** 打开:手机或别的电脑上打开这个地址,输入密码,就能看会话、发任务(可以带图片)、回答问题、改设置。手机上通过左上角菜单打开工作区,聊天和输入区适应小屏幕。通讯号在网关网页「通讯录」里改(只能用小写字母、数字和 `-`),比如改成 `yanzc` 就是 `https://yanzc.7bit.fun`。
215
+ 远程访问需要先连接 7bit.fun。在控制台「远程访问」页或会话里的 `/web remote on` 开启:第一次会让你设一个至少 10 位的密码,并自己选一个域名前缀(3–20 个小写字母、数字或 `-`,只要没人用过),比如 `yanzc`,控制台就能在 **`https://yanzc.7bit.fun`** 打开:手机或别的电脑上打开这个地址,输入密码,就能看会话、发任务(可以带图片)、回答问题、改设置。手机上通过左上角菜单打开工作区,聊天和输入区适应小屏幕。前缀也是你在网关的通讯号,之后可以在「远程访问」页点「修改前缀」(旧地址随即失效)。
216
216
 
217
217
  - **怎么连的**:本机控制台的后台服务主动连一条 WebSocket 到 7bit.fun 网关(用 `/connect` 保存的 Key),网关把这个域名的请求从这条连接转给它。电脑不开任何端口,转过来的请求只能到控制台本身。
218
218
  - **密码只在本机校验**:`~/.claude-pro/web-remote.json` 里只存 scrypt 哈希,网关不知道密码。登录页可以选「记住这台设备 30 天」,不勾就只保持 1 天。同一个 IP 连续输错 5 次锁 15 分钟,一小时内总共错 20 次就锁到这个小时结束。每次登录(成功或失败)都有记录。
@@ -242,7 +242,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
242
242
 
243
243
  不同网关账户之间,双方同意后,各自的 claude-pro 会话也能互发任务。
244
244
 
245
- - **通讯号**:每个账户有一个公开的通讯号(默认随机,如 `cp7k3qxm`),别人用它加你,看不到你的邮箱。`/contacts handle 新名字` 或网关网页「通讯录」里修改(3-20 个小写字母、数字、`_`、`-`,以字母开头)。
245
+ - **通讯号**:每个账户有一个公开的通讯号(默认随机,如 `cp7k3qxm`),别人用它加你,看不到你的邮箱。`/contacts handle 新名字`、控制台「远程访问」页或网关网页「通讯录」里修改(3-20 个小写字母、数字或 `-`,以字母开头;它也是远程访问的域名前缀)。
246
246
  - **加好友**:`/contacts add 对方通讯号` 发出请求;对方在线的会话会提示,对方用 `/contacts accept 你的通讯号` 同意(也可以 `reject`、`block`),或在网页通讯录里点同意。双方互相请求时直接成为好友。`/contacts remove` 删除,`/contacts block` 拉黑(对方不能再请求、不能发任务,也不会被告知)。`/contacts` 列出全部。
247
247
  - **发任务**:好友在线的会话在 `/peers` 和 ListPeers 里显示为 `@通讯号:电脑名/会话名`;`@通讯号 任务`(对方只开着一个会话时)或 `@通讯号:电脑名/会话名 任务` 发送,回答自动发回。
248
248
  - **确认**:好友发来的任务默认在终端弹窗问你「执行 / 拒绝 / 以后都执行」,拒绝时对方会收到“已拒绝”。`/contacts trust 通讯号 auto` 让这个好友的任务直接执行,`confirm` 改回每条确认。交给模型时会注明这是外人的请求、不是用户的指令,并要求它不泄露密钥和私人文件、不做破坏性操作。
@@ -289,7 +289,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://7bit.fun
289
289
 
290
290
  **`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件/会话补全、输入历史都换成新目录的;对话、模型、effort、待办不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
291
291
 
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`,以及 `.claude/commands/*.md`、`.claude-pro/commands/*.md`、`~/.claude-pro/commands/*.md` 中的自定义命令(支持 `$ARGUMENTS`、`$1`、`` !`cmd` ``)。
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`。技能也可以直接用 `/技能名 参数` 运行。
293
293
 
294
294
  **记忆**:自动读取 `~/.claude-pro/CLAUDE.md`、项目各级目录的 `CLAUDE.md` / `.claude/CLAUDE.md` / `CLAUDE.local.md`;某一级目录没有 `CLAUDE.md` 时读它的 `AGENTS.md` 代替(两者都有时通常是同一份说明,不重复发送)。
295
295
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.13.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
@@ -11,7 +11,7 @@ import { GATEWAY_PROVIDER, PRESETS, providerInfo, connectedProviders, readConnec
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 { loadCustomCommands, renderSkill, expandCommandBody, expandShellEmbeds } from './agents.js';
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';
@@ -1044,18 +1044,31 @@ export function buildCommands(app) {
1044
1044
  return;
1045
1045
  }
1046
1046
  if (action === 'on') {
1047
- if (!gatewayLogin(cfg.gatewayUrl)) { out(c.red(`远程访问通过 7bit.fun 网关:先 /connect 7bit.fun 连上网关。`)); return; }
1047
+ const login = gatewayLogin(cfg.gatewayUrl);
1048
+ if (!login) { out(c.red(`远程访问通过 7bit.fun 网关:先 /connect 7bit.fun 连上网关。`)); return; }
1048
1049
  if (!ra.hasPassword()) {
1049
1050
  const pw = await askPassword(ra);
1050
1051
  if (!pw) { out(c.dim('远程访问没有开启。')); return; }
1051
1052
  ra.setPassword(pw);
1052
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
+ }
1053
1066
  ra.setEnabled(true);
1054
1067
  out(c.dim('正在连接网关…'));
1055
1068
  } else if (action) { out(c.red('/web remote [on|off|password|logout]')); return; }
1056
1069
  const d = ra.readRemote();
1057
1070
  if (!d.enabled) {
1058
- out([`远程访问:${c.dim('关闭')}`, c.dim('/web remote on 开启:在手机上打开 https://<你的通讯号>.7bit.fun,输入密码就能用这台电脑的 claude-pro 控制台。')]);
1071
+ out([`远程访问:${c.dim('关闭')}`, c.dim('/web remote on 开启:第一次选一个域名前缀,在手机上打开 https://<前缀>.7bit.fun,输入密码就能用这台电脑的 claude-pro 控制台。')]);
1059
1072
  return;
1060
1073
  }
1061
1074
  let view;
@@ -1367,24 +1380,6 @@ export function buildCommands(app) {
1367
1380
  run() { app.exit(0); },
1368
1381
  });
1369
1382
 
1370
- // Custom commands from markdown files.
1371
- for (const custom of loadCustomCommands(app.cwd).values()) {
1372
- if (commands.has(custom.name)) continue;
1373
- add({
1374
- name: custom.name,
1375
- argHint: custom.argumentHint,
1376
- description: `${custom.description} ${c.dim(`(${custom.scope})`)}`,
1377
- async run(args) {
1378
- const bash = app.runtime.tools.find((t) => t.name === 'Bash');
1379
- const body = await expandShellEmbeds(expandCommandBody(custom.body, args), async (command) => {
1380
- const r = await bash.call({ command }, app.agent.makeCtx());
1381
- return typeof r.content === 'string' ? r.content : '';
1382
- });
1383
- return app.startTurn(body, { echo: false });
1384
- },
1385
- });
1386
- }
1387
-
1388
1383
  // Skills can be run directly as /<skill-name> [arguments].
1389
1384
  for (const skill of app.runtime.skills.values()) {
1390
1385
  if (commands.has(skill.name)) continue;
package/src/web/api.js CHANGED
@@ -16,12 +16,12 @@ import {
16
16
  } from '../providers.js';
17
17
  import { gatewayLogin, loginWithKey, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, keptGatewayList } from '../gateway.js';
18
18
  import { checkForUpdate, installUpdate } from '../updater.js';
19
- import { loadAgents, loadSkills, loadCustomCommands } from '../agents.js';
19
+ import { loadAgents, loadSkills } from '../agents.js';
20
20
  import { webModelChoices, effortChoices as sessionEfforts, refreshModelLists } from '../commands.js';
21
21
  import { setArchived, archivedSessions, projectDir } from '../session.js';
22
22
  import {
23
23
  listAllSessions, sessionDetail, sessionImage, sessionToolOutput, sessionMarkdown, renameSession, trashSession, listTrash, restoreSession,
24
- purgeTrash, runningSessions, findPeerById, peerRequest, usageReport, dirSize, projectsRoot, httpError,
24
+ purgeTrash, runningSessions, findPeerById, peerRequest, usageReport, dirSize, projectsRoot, httpError, builtinTools,
25
25
  } from './data.js';
26
26
 
27
27
  const mask = (key) => {
@@ -211,7 +211,7 @@ const inside = (file, dir) => {
211
211
  function editable(file) {
212
212
  const f = path.resolve(file);
213
213
  const ext = path.extname(f).toLowerCase();
214
- const extDirs = (root) => ['skills', 'agents', 'commands'].some((d) => inside(f, path.join(root, d))) && ext === '.md';
214
+ const extDirs = (root) => ['skills', 'agents'].some((d) => inside(f, path.join(root, d))) && ext === '.md';
215
215
  if (same(f, path.join(CONFIG_DIR, 'CLAUDE.md')) || same(f, path.join(CONFIG_DIR, 'settings.json'))) return true;
216
216
  if (extDirs(CONFIG_DIR)) return true;
217
217
  if (inside(f, projectsRoot()) && ext === '.md' && path.basename(path.dirname(f)) === 'memory' && same(path.dirname(path.dirname(path.dirname(f))), projectsRoot())) return true;
@@ -515,20 +515,15 @@ function extensionsView(project) {
515
515
  const scopeOf = (source) => (typeof source === 'string' && inside(path.resolve(source), CONFIG_DIR) ? 'user' : source === 'built-in' ? 'built-in' : 'project');
516
516
  return {
517
517
  project: cwd === home ? null : cwd,
518
+ tools: builtinTools(cwd === home ? null : cwd),
519
+ selfRestart: SOURCE_CHECKOUT, // (a source checkout's sessions have Restart too)
518
520
  skills: [...loadSkills(cwd).values()].map((s) => ({ name: s.name, description: s.description, scope: s.scope, path: s.file })),
519
521
  agents: [...loadAgents(cwd).values()].map((a) => ({ name: a.name, description: a.description, tools: a.tools, scope: scopeOf(a.source), path: a.source === 'built-in' ? null : a.source })),
520
- commands: [...loadCustomCommands(cwd).values()].map((c) => ({ name: c.name, description: c.description, scope: c.scope, path: commandPath(cwd, c) })),
521
522
  mcp, hooks, settingsFiles: files,
522
523
  mcpLoaded: Object.keys(config.settings.mcpServers || {}),
523
524
  };
524
525
  }
525
526
 
526
- function commandPath(cwd, cmd) {
527
- const rel = `${cmd.name.split(':').join(path.sep)}.md`;
528
- const roots = cmd.scope === 'user' ? [path.join(CONFIG_DIR, 'commands')] : [path.join(cwd, '.claude-pro', 'commands'), path.join(cwd, '.claude', 'commands')];
529
- return roots.map((r) => path.join(r, rel)).find((f) => fs.existsSync(f)) || null;
530
- }
531
-
532
527
  // An MCP server's settings without the values of its environment and headers (tokens live there).
533
528
  function redactSpec(spec) {
534
529
  if (!spec || typeof spec !== 'object') return spec;
package/src/web/app.css CHANGED
@@ -296,6 +296,12 @@ table.list td.num, table.list th.num { text-align: right; font-variant-numeric:
296
296
  .model-list label:hover { background: var(--surface-2); }
297
297
  .model-list small { color: var(--muted); margin-left: auto; white-space: nowrap; }
298
298
 
299
+ /* 远程访问: the address's prefix */
300
+ .remote-setup { display: grid; gap: 12px; margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--line); }
301
+ .prefix-row { display: flex; align-items: center; gap: 6px; max-width: 520px; }
302
+ .prefix-row input { flex: 1; min-width: 0; }
303
+ .remote-setup .modal-error { color: var(--danger); font-size: 13px; }
304
+
299
305
  /* 默认设置 */
300
306
  .def-row { display: grid; grid-template-columns: minmax(200px, 340px) minmax(0, 460px); gap: 8px 24px; align-items: center; padding: 16px 20px; border-bottom: 1px solid var(--line); }
301
307
  .def-row:last-child { border-bottom: 0; }
@@ -337,6 +343,8 @@ td.pick input { width: 16px; height: 16px; margin: 3px 0 0; cursor: pointer; acc
337
343
  .file-row .name { font-family: var(--mono); font-size: 12.5px; }
338
344
  .file-row .desc { color: var(--muted); font-size: 12.5px; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
339
345
  .file-row .grow { flex: 1; }
346
+ .file-row.mcp-sub { background: var(--surface-2); padding-top: 8px; padding-bottom: 8px; }
347
+ .file-row.mcp-sub strong { color: var(--text-2); font-weight: 600; }
340
348
  details.proj { border-bottom: 1px solid var(--line); }
341
349
  details.proj:last-child { border-bottom: 0; }
342
350
  details.proj > summary { list-style: none; cursor: pointer; padding: 13px 18px; display: flex; align-items: center; gap: 10px; }
package/src/web/app.js CHANGED
@@ -1454,16 +1454,31 @@
1454
1454
  // ---------------------------------------------------------------- 远程访问
1455
1455
 
1456
1456
  async function remotePage() {
1457
- const el = page('<h1>远程访问</h1><p class="sub">在手机或别的电脑上,通过 https://&lt;你的通讯号&gt;.7bit.fun 打开这台电脑的控制台,要输入密码</p><div id="body"><div class="empty">正在加载…</div></div>');
1457
+ const el = page('<h1>远程访问</h1><p class="sub">在手机或别的电脑上,通过你自己的域名(https://&lt;前缀&gt;.7bit.fun)打开这台电脑的控制台,要输入密码</p><div id="body"><div class="empty">正在加载…</div></div>');
1458
1458
  let v;
1459
1459
  try { v = await api("/api/remote"); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
1460
- drawRemote(el, v);
1461
- const timer = setInterval(async () => { try { const next = await api("/api/remote"); if (JSON.stringify(next.tunnel) !== JSON.stringify(v.tunnel)) { v = next; drawRemote(el, v); } } catch { /* next time */ } }, 3000);
1460
+ // the address's prefix (the account's 通讯号 at the gateway), asked once
1461
+ const h = v.gateway ? await api("/api/remote/handle").catch((e) => ({ error: e.message })) : null;
1462
+ if (!el.isConnected) return;
1463
+ drawRemote(el, v, h);
1464
+ const timer = setInterval(async () => { try { const next = await api("/api/remote"); if (JSON.stringify(next.tunnel) !== JSON.stringify(v.tunnel)) { v = next; drawRemote(el, v, h); } } catch { /* next time */ } }, 3000);
1462
1465
  cleanup = () => clearInterval(timer);
1463
1466
  }
1464
1467
 
1465
- function drawRemote(el, v) {
1468
+ const HANDLE_RULE = /^[a-z][a-z0-9-]{1,18}[a-z0-9]$/;
1469
+ const HANDLE_HINT = "3–20 个小写字母、数字或 -,字母开头、不以 - 结尾";
1470
+
1471
+ function drawRemote(el, v, h) {
1472
+ // without 7bit.fun there is no address: only the way to connect it
1473
+ if (!v.gateway) {
1474
+ $("#body", el).innerHTML = `<div class="panel panel-pad"><div style="font-weight:650;margin-bottom:6px">远程访问需要 7bit.fun 网关</div><p class="muted" style="margin:0 0 14px;font-size:13px">访问地址 https://&lt;前缀&gt;.7bit.fun 由网关提供:连接 7bit.fun 后,就能在这里选一个自己的域名前缀并开启。</p><button class="button" id="rConnectGw">去连接 7bit.fun</button></div>`;
1475
+ $("#rConnectGw", el).addEventListener("click", () => { sessionStorage.setItem("cpOpenAdd", "1"); location.hash = "#/providers"; });
1476
+ return;
1477
+ }
1466
1478
  const t = v.tunnel || {};
1479
+ const domain = h?.domain || "7bit.fun";
1480
+ const prefixField = (id) => `<label class="field" style="margin:0">域名前缀<small>${HANDLE_HINT};要唯一,它也是你在网关的通讯号(联系人用它找到你)</small>
1481
+ <span class="prefix-row"><span class="mono muted">https://</span><input id="${id}" class="mono" maxlength="20" autocomplete="off" spellcheck="false" placeholder="例如 yanzc" value="${h && !h.auto ? esc(h.handle) : ""}"><span class="mono muted">.${esc(domain)}</span></span></label>`;
1467
1482
  const state = !v.enabled ? ["off", "已关闭"] : t.status === "online" ? ["ok", "已开启"] : t.status === "error" ? ["off", "没有接上"] : ["warn", "正在连接"];
1468
1483
  const device = (ua) => { const s = String(ua || ""); return /iPhone|iPad/.test(s) ? "iPhone / iPad" : /Android/.test(s) ? "Android" : /Windows/.test(s) ? "Windows" : /Mac OS/.test(s) ? "Mac" : s.slice(0, 40) || "未知设备"; };
1469
1484
  $("#body", el).innerHTML = `
@@ -1471,25 +1486,67 @@
1471
1486
  <div><div class="muted" style="font-size:12.5px">状态</div><div style="font-size:18px;font-weight:650;margin-top:2px"><span class="pill ${state[0]}">${state[1]}</span>
1472
1487
  ${t.status === "online" && t.host ? ` <a href="https://${esc(t.host)}" target="_blank" rel="noopener" class="mono" style="font-size:15px">https://${esc(t.host)}</a>` : ""}</div>
1473
1488
  ${t.error ? `<div style="color:var(--danger);font-size:13px;margin-top:4px">${esc(t.error)}</div>` : ""}
1474
- ${!v.gateway ? '<div class="muted" style="font-size:13px;margin-top:4px">远程访问通过 7bit.fun 网关:先在「模型与供应商」里连接 7bit.fun。</div>' : ""}</div>
1475
- <div class="actions">${v.enabled ? '<button class="button danger" id="rOff">关闭远程访问</button>' : `<button class="button" id="rOn" ${v.hasPassword && v.gateway ? "" : "disabled"}>开启远程访问</button>`}</div></div>
1476
- <p class="muted" style="font-size:12.5px;margin:12px 0 0">地址用的是你在网关的通讯号(在网关网页「通讯录」里改)。开启后这台电脑的控制台服务常驻后台;电脑休眠或关机时打不开,claude-pro 的任何会话启动时会重新接上。</p></div>
1489
+ ${h?.error ? `<div style="color:var(--danger);font-size:13px;margin-top:4px">读不到域名前缀:${esc(h.error)}</div>` : ""}</div>
1490
+ <div class="actions">${v.enabled ? `<button class="button secondary" id="rRename">修改前缀</button><button class="button danger" id="rOff">关闭远程访问</button>` : ""}</div></div>
1491
+ ${v.enabled ? "" : `<div class="remote-setup">${prefixField("rHandle")}<div class="actions"><button class="button" id="rOn" ${v.hasPassword ? "" : "disabled"}>开启远程访问</button>${v.hasPassword ? "" : '<span class="muted" style="font-size:12.5px">先在下面设一个密码</span>'}<span class="modal-error" id="rErr"></span></div></div>`}
1492
+ <p class="muted" style="font-size:12.5px;margin:12px 0 0">开启后这台电脑的控制台服务常驻后台;电脑休眠或关机时打不开,claude-pro 的任何会话启动时会重新接上。</p></div>
1477
1493
  <div class="section-head"><div><h2>密码</h2><p>${v.hasPassword ? "已设置。改密码会让所有已登录的设备退出。" : `还没有设置:开启前先设一个(至少 ${v.minPassword} 位)。`}</p></div></div>
1478
1494
  <form class="panel panel-pad actions" id="rPwForm"><input type="password" id="rPw1" placeholder="新密码" autocomplete="new-password" style="flex:1;min-width:180px"><input type="password" id="rPw2" placeholder="再输一次" autocomplete="new-password" style="flex:1;min-width:180px"><button class="button" type="submit">${v.hasPassword ? "修改密码" : "设置密码"}</button></form>
1479
1495
  <div class="section-head"><div><h2>已登录的设备</h2><p>${v.sessions.length} 台</p></div>${v.sessions.length ? '<button class="button danger small" id="rLogoutAll">全部退出</button>' : ""}</div>
1480
1496
  <div class="panel">${v.sessions.length ? `<table class="list"><tbody>${v.sessions.map((s) => `<tr><td>${esc(device(s.ua))}</td><td class="mono">${esc(s.ip || "")}</td><td>最近 ${esc(ago(s.lastSeen))}</td><td class="num muted">${s.remember ? "记住 30 天" : "1 天"}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">没有</div>'}</div>
1481
1497
  <div class="section-head"><h2>最近的登录</h2></div>
1482
1498
  <div class="panel">${v.logins.length ? `<table class="list"><tbody>${v.logins.map((l) => `<tr><td>${l.ok ? '<span class="pill ok">成功</span>' : '<span class="pill off">密码错误</span>'}</td><td>${esc(device(l.ua))}</td><td class="mono">${esc(l.ip || "")}</td><td class="num">${esc(fmtTime(l.at))}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">还没有人登录过</div>'}</div>`;
1483
- const post = async (body, done) => { try { drawRemote(el, await api("/api/remote", { method: "POST", body })); if (done) toast(done); } catch (e) { fail(e); } };
1484
- $("#rOn", el)?.addEventListener("click", () => post({ enabled: true }, "远程访问已开启,正在连接网关…"));
1485
- $("#rOff", el)?.addEventListener("click", () => { if (confirm("关闭远程访问?外网就打不开这台电脑的控制台了。")) post({ enabled: false }, "远程访问已关闭"); });
1486
- $("#rLogoutAll", el)?.addEventListener("click", () => { if (confirm("让所有已登录的设备退出?")) post({ logoutAll: true }, "都已退出"); });
1499
+ const post = async (body, done) => {
1500
+ const next = await api("/api/remote", { method: "POST", body });
1501
+ if (body.handle && h) Object.assign(h, { handle: body.handle, auto: false, error: null });
1502
+ drawRemote(el, next, h);
1503
+ if (done) toast(done);
1504
+ };
1505
+ // the prefix typed, checked here as the gateway will: none needed when the user chose one before
1506
+ const typedHandle = (input, err) => {
1507
+ const value = input.value.trim().toLowerCase();
1508
+ if (!value && h && !h.auto) return h.handle;
1509
+ if (!value) { err("先填一个域名前缀"); input.focus(); return null; }
1510
+ if (!HANDLE_RULE.test(value)) { err(`域名前缀要是 ${HANDLE_HINT}`); input.focus(); return null; }
1511
+ return value;
1512
+ };
1513
+ $("#rOn", el)?.addEventListener("click", async (e) => {
1514
+ const b = e.currentTarget, errBox = $("#rErr", el), err = (m) => { errBox.textContent = m; };
1515
+ err("");
1516
+ const handle = typedHandle($("#rHandle", el), err);
1517
+ if (!handle) return;
1518
+ b.disabled = true;
1519
+ try { await post({ ...(handle !== h?.handle ? { handle } : {}), enabled: true }, `远程访问已开启:https://${handle}.${domain},正在连接网关…`); }
1520
+ catch (ex) { err(ex.message); b.disabled = false; }
1521
+ });
1522
+ $("#rHandle", el)?.addEventListener("keydown", (e) => { if (e.key === "Enter") $("#rOn", el)?.click(); });
1523
+ $("#rRename", el)?.addEventListener("click", () => {
1524
+ const m = modal({
1525
+ title: "修改域名前缀", sub: `现在是 https://${h?.handle || "…"}.${domain};改后旧地址就打不开了`,
1526
+ body: prefixField("rNewHandle"),
1527
+ foot: '<span class="modal-error"></span><button class="button secondary" data-close>取消</button><button class="button" id="rSaveHandle">保存</button>',
1528
+ });
1529
+ const input = $("#rNewHandle", m.el);
1530
+ input.focus(); input.select();
1531
+ const save = async () => {
1532
+ const err = (msg) => { $(".modal-error", m.el).textContent = msg; };
1533
+ err("");
1534
+ const handle = typedHandle(input, err);
1535
+ if (!handle) return;
1536
+ if (handle === h?.handle) return m.close();
1537
+ try { await post({ handle }, `已改为 https://${handle}.${domain},正在重新连接…`); m.close(); } catch (ex) { err(ex.message); }
1538
+ };
1539
+ $("#rSaveHandle", m.el).addEventListener("click", save);
1540
+ input.addEventListener("keydown", (e) => { if (e.key === "Enter") save(); });
1541
+ });
1542
+ $("#rOff", el)?.addEventListener("click", () => { if (confirm("关闭远程访问?外网就打不开这台电脑的控制台了。")) post({ enabled: false }, "远程访问已关闭").catch(fail); });
1543
+ $("#rLogoutAll", el)?.addEventListener("click", () => { if (confirm("让所有已登录的设备退出?")) post({ logoutAll: true }, "都已退出").catch(fail); });
1487
1544
  $("#rPwForm", el).addEventListener("submit", (e) => {
1488
1545
  e.preventDefault();
1489
1546
  const a = $("#rPw1", el).value, b = $("#rPw2", el).value;
1490
1547
  if (a.length < v.minPassword) return toast(`密码至少 ${v.minPassword} 位`, "error");
1491
1548
  if (a !== b) return toast("两次输入不一样", "error");
1492
- post({ password: a }, "密码已保存,所有已登录的设备都已退出");
1549
+ post({ password: a }, "密码已保存,所有已登录的设备都已退出").catch(fail);
1493
1550
  });
1494
1551
  }
1495
1552
 
@@ -1914,21 +1971,31 @@
1914
1971
 
1915
1972
  async function extensions() {
1916
1973
  const project = sessionStorage.getItem("extProject") || "";
1917
- const el = page(`<h1>扩展</h1><p class="sub">技能、子 agent、自定义命令、MCP 服务器和 hooks。新会话会加载改动</p>
1974
+ const el = page(`<h1>扩展</h1><p class="sub">内置工具、技能、子 agent、MCP 和 hooks。新会话会加载改动</p>
1918
1975
  <div class="toolbar"><span class="muted" style="font-size:13px">项目:</span>${await projectsSelect("proj", project)}</div><div id="body"><div class="empty">正在加载…</div></div>`);
1919
1976
  $("#proj", el).addEventListener("change", (e) => { sessionStorage.setItem("extProject", e.target.value); extensions(); });
1920
1977
  let x;
1921
1978
  try { x = await api(`/api/extensions${project ? `?project=${encodeURIComponent(project)}` : ""}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
1922
1979
  const scopePill = (s) => `<span class="pill${s === "built-in" ? "" : s === "user" ? " accent" : " ok"}">${{ "built-in": "内置", user: "用户", project: "项目" }[s] || esc(s)}</span>`;
1923
- const list = (items, kind) => items.length ? items.map((i) => `<div class="file-row"><span class="name">${esc(kind === "command" ? `/${i.name}` : i.name)}</span>${scopePill(i.scope)}<span class="desc" title="${esc(i.description)}">${esc(i.description)}</span>${i.path ? `<button class="button secondary small" data-edit="${esc(i.path)}">编辑</button>` : ""}</div>`).join("") : '<div class="file-row"><span class="desc">还没有</span></div>';
1980
+ const list = (items, kind) => items.length ? items.map((i) => `<div class="file-row"><span class="name">${esc(i.name)}</span>${scopePill(i.scope)}<span class="desc" title="${esc(i.description)}">${esc(i.description)}</span>${i.path ? `<button class="button secondary small" data-edit="${esc(i.path)}">编辑</button>` : ""}</div>`).join("") : '<div class="file-row"><span class="desc">还没有</span></div>';
1924
1981
  // 新建: a new conversation with the request written for the model (it knows the formats and asks what is missing)
1925
1982
  const aiBtn = (kind) => `<button class="button secondary small" data-ai="${kind}" title="打开新会话,写好要求交给模型去做">${ICON.agent}让 AI 新建</button>`;
1983
+ // 内置工具: what every request gives the model, in a line each (the whole description on hover)
1984
+ const tools = x.tools || [];
1985
+ const toolRows = tools.map((t) => {
1986
+ const first = (t.description.split(/\n/).find((l) => l.trim()) || "").replace(/^[-\s]+/, "").split(/(?<=\.)\s/)[0];
1987
+ return `<div class="file-row"><span class="name">${esc(t.name)}</span><span class="desc" title="${esc(t.description.slice(0, 1200))}">${esc(TOOL_ZH[t.name] || first)}</span></div>`;
1988
+ }).join("");
1926
1989
  $("#body", el).innerHTML = `
1927
- <div class="section-head"><div><h2>技能</h2><p>skills/&lt;名字&gt;/SKILL.md:模型按描述决定何时加载</p></div>${aiBtn("skill")}</div><div class="panel">${list(x.skills, "skill")}</div>
1990
+ <div class="section-head"><div><h2>内置工具<span class="card-count" style="margin-left:8px;vertical-align:2px">${tools.length + (x.selfRestart ? 1 : 0)}</span></h2><p>每次请求都会发给模型、由模型决定何时调用的工具,写在程序里(不是 MCP)。鼠标停在说明上可以看到发给模型的原文</p></div></div>
1991
+ <div class="panel">${toolRows || '<div class="file-row"><span class="desc">读不到工具清单</span></div>'}${x.selfRestart ? `<div class="file-row"><span class="name">Restart</span><span class="desc">${esc(TOOL_ZH.Restart)}</span></div>` : ""}
1992
+ <div class="file-row"><span class="desc">另外:配置了 MCP 服务器时,它们的工具会以 mcp__服务器名__工具名 加进这个清单;子 agent 用的是它定义里 tools 列出的那些。</span></div></div>
1993
+ <div class="section-head"><div><h2>技能</h2><p>skills/&lt;名字&gt;/SKILL.md:模型按描述决定何时用 Skill 工具加载</p></div>${aiBtn("skill")}</div><div class="panel">${list(x.skills, "skill")}</div>
1928
1994
  <div class="section-head"><div><h2>子 agent</h2><p>agents/*.md:Task 工具可以把任务交给它们</p></div>${aiBtn("agent")}</div><div class="panel">${list(x.agents, "agent")}</div>
1929
- <div class="section-head"><div><h2>自定义命令</h2><p>commands/*.md:在会话里输入 /名字</p></div>${aiBtn("command")}</div><div class="panel">${list(x.commands, "command")}</div>
1930
- <div class="section-head"><div><h2>MCP 服务器</h2><p>环境变量和请求头的值不会显示(保持 ••• 就是不改)</p></div>${aiBtn("mcp")}</div>
1931
- <div class="panel">${x.mcp.length ? x.mcp.map((s, i) => `<div class="file-row"><span class="name">${esc(s.name)}</span><span class="pill">${esc(s.scope)}</span><span class="desc mono">${esc(s.spec?.url || [s.spec?.command, ...(s.spec?.args || [])].filter(Boolean).join(" "))}</span>${s.scope === "user" || s.scope === ".mcp.json" ? `<button class="button secondary small" data-mcp="${i}">编辑</button>` : `<button class="button secondary small" data-edit="${esc(s.file)}">编辑文件</button>`}</div>`).join("") : '<div class="file-row"><span class="desc">没有配置 MCP 服务器</span></div>'}</div>
1995
+ <div class="section-head"><div><h2>MCP</h2><p>别的工具要装 MCP 才有的常用能力,这里已经内置,不用安装;也可以接入外部 MCP 服务器,它们的工具会加进上面的清单</p></div>${aiBtn("mcp")}</div>
1996
+ <div class="panel">${BUILTIN_MCP.filter((b) => tools.some((t) => t.name === b.tool)).map((b) => `<div class="file-row"><span class="name" style="font-family:inherit;font-weight:600">${esc(b.name)}</span><span class="pill">内置</span><span class="desc" title="${esc(b.tools)}">${esc(b.desc)}${b.like ? `<span class="faint"> · 相当于 ${esc(b.like)}</span>` : ""}</span></div>`).join("")}
1997
+ <div class="file-row mcp-sub"><span class="desc"><strong>外部 MCP 服务器</strong> · 环境变量和请求头的值不会显示</span></div>
1998
+ ${x.mcp.length ? x.mcp.map((s, i) => `<div class="file-row"><span class="name">${esc(s.name)}</span><span class="pill">${esc(s.scope)}</span><span class="desc mono">${esc(s.spec?.url || [s.spec?.command, ...(s.spec?.args || [])].filter(Boolean).join(" "))}</span>${s.scope === "user" || s.scope === ".mcp.json" ? `<button class="button secondary small" data-mcp="${i}">编辑</button>` : `<button class="button secondary small" data-edit="${esc(s.file)}">编辑文件</button>`}</div>`).join("") : '<div class="file-row"><span class="desc">还没有添加外部 MCP 服务器</span></div>'}</div>
1932
1999
  <div class="section-head"><div><h2>Hooks</h2><p>在工具调用前后、提交消息时等运行的命令,写在设置文件的 hooks 里</p></div></div>
1933
2000
  <div class="panel">${x.hooks.length ? x.hooks.map((h) => `<div class="file-row"><span class="name">${esc(h.event)}</span><span class="pill">${esc(h.scope)}</span><span class="desc mono">${esc(JSON.stringify(h.entries))}</span><button class="button secondary small" data-edit="${esc(h.file)}">编辑文件</button></div>`).join("") : `<div class="file-row"><span class="desc">没有 hooks。要添加,编辑设置文件的 "hooks" 字段</span><button class="button secondary small" data-edit="${esc(x.settingsFiles.user)}">编辑用户设置文件</button></div>`}</div>`;
1934
2001
  $("#body", el).addEventListener("click", async (e) => {
@@ -1939,6 +2006,47 @@
1939
2006
  });
1940
2007
  }
1941
2008
 
2009
+ // The built-in tools in a few Chinese words (扩展's 内置工具; what the model reads is their English description)
2010
+ const TOOL_ZH = {
2011
+ Task: "把复杂的多步任务交给子 agent,可以在后台运行",
2012
+ Skill: "加载一个技能(下面「技能」里写好的做事说明)",
2013
+ TaskOutput: "查看后台 agent 的状态和结果",
2014
+ TaskStop: "停止一个后台 agent",
2015
+ Bash: "运行终端命令(git、npm、构建、测试等),可以放到后台",
2016
+ BashOutput: "读取后台命令的输出",
2017
+ KillShell: "结束一个后台命令",
2018
+ REPL: "在常驻的 Python / Node.js 进程里运行代码,变量和数据保留到下次",
2019
+ Processes: "列出本机进程(端口、命令行),或结束进程",
2020
+ Glob: "按文件名模式找文件",
2021
+ Grep: "按内容搜索文件(ripgrep)",
2022
+ Read: "读取文件,也能看图片和 notebook",
2023
+ Edit: "在文件里精确替换一段文字",
2024
+ MultiEdit: "一次在同一个文件里做多处替换",
2025
+ Write: "写入文件(新建或整个覆盖)",
2026
+ NotebookEdit: "编辑 Jupyter notebook 的单元格",
2027
+ WebFetch: "抓取网页,按要求提取内容",
2028
+ WebSearch: "联网搜索",
2029
+ Browser: "操作真实的浏览器:打开网页、点击、输入、截图",
2030
+ TodoWrite: "维护当前任务的待办清单(就是对话下方的「待办」)",
2031
+ AskUserQuestion: "向你提问、让你在几个选项里选",
2032
+ Effort: "遇到难题时调高自己本次的思考强度",
2033
+ ListPeers: "列出其他 claude-pro 会话(本机、你的其他电脑、联系人)",
2034
+ MessagePeer: "给其他会话发任务或问题,答复自动发回",
2035
+ Restart: "改了 claude-pro 自身代码后重启加载(只有源码版有)",
2036
+ };
2037
+
2038
+ // What other agents get from MCP servers and claude-pro has built in (扩展's MCP section): shown while its tool is
2039
+ // there (Browser can be turned off).
2040
+ const BUILTIN_MCP = [
2041
+ { tool: "Browser", tools: "Browser", name: "浏览器", desc: "打开网页、点击、输入、截图,可以用你已登录的浏览器", like: "Playwright / Chrome DevTools MCP" },
2042
+ { tool: "WebSearch", tools: "WebSearch", name: "联网搜索", desc: "搜索并汇总结果,附来源", like: "Brave / Tavily 等搜索 MCP" },
2043
+ { tool: "WebFetch", tools: "WebFetch", name: "抓取网页", desc: "读取网页正文,按要求提取内容", like: "Fetch MCP" },
2044
+ { tool: "Read", tools: "Read · Write · Edit · MultiEdit · Glob · Grep", name: "文件系统", desc: "读写、修改、搜索本机文件", like: "Filesystem MCP" },
2045
+ { tool: "REPL", tools: "REPL", name: "代码执行", desc: "常驻的 Python / Node.js 进程,处理数据、跑脚本", like: "代码执行类 MCP" },
2046
+ { tool: "Processes", tools: "Processes", name: "进程管理", desc: "查看进程和占用的端口,结束进程", like: "系统 / 进程类 MCP" },
2047
+ { tool: "MessagePeer", tools: "ListPeers · MessagePeer", name: "多会话协作", desc: "和本机、你的其他电脑、联系人的 claude-pro 会话互发任务", like: "" },
2048
+ ];
2049
+
1942
2050
  // 让 AI 新建: the new conversation's box with the request (where the file goes, its format), the project's directory
1943
2051
  // chosen when the page shows one; what the thing should do is left for the user to write at the end.
1944
2052
  function askModelToCreate(kind, { project, settingsFile }) {
@@ -1949,7 +2057,6 @@
1949
2057
  const text = {
1950
2058
  skill: `帮我新建一个技能,放在${where}:${dir}${sep}skills${sep}<名字>${sep}SKILL.md。frontmatter 写 name 和 description(description 说清楚什么时候该用它),正文写步骤和说明。信息不够就先问我。\n\n这个技能用来:`,
1951
2059
  agent: `帮我新建一个子 agent,放在${where}:${dir}${sep}agents${sep}<名字>.md。frontmatter 写 name、description(什么时候把任务交给它)和 tools,正文是它的系统提示词。信息不够就先问我。\n\n这个子 agent 负责:`,
1952
- command: `帮我新建一个自定义命令,放在${where}:${dir}${sep}commands${sep}<名字>.md(在会话里输入 /<名字> 使用)。frontmatter 写 description 和 argument-hint,正文是发给模型的内容,用 $ARGUMENTS 代表命令后面的参数。信息不够就先问我。\n\n这个命令要做的事:`,
1953
2060
  mcp: `帮我添加一个 MCP 服务器,写进${project ? `项目的 ${project}${sep}.mcp.json` : ` ${settingsFile || "用户设置文件"} 的 "mcpServers"`}(写法和 Claude Code 的 mcpServers 一样:stdio 用 command/args/env,远程用 type: "http" 和 url/headers)。需要安装或填密钥就告诉我,先别把密钥写进会提交的文件。\n\n要接入的服务:`,
1954
2061
  }[kind];
1955
2062
  if (!text) return;
package/src/web/data.js CHANGED
@@ -151,6 +151,9 @@ function toolsFor(cwd) {
151
151
  return tools;
152
152
  }
153
153
 
154
+ // The built-in tools a session of the project sends the model (扩展's 内置工具): {name, description}.
155
+ export const builtinTools = (cwd) => toolsFor(cwd).map((t) => ({ name: t.name, description: String(t.description || '') }));
156
+
154
157
  // A conversation as the console shows it: its items (as the live view has them, images as {k: 'image', n}), with
155
158
  // what the list knows of it.
156
159
  export function sessionDetail(dir, id) {
@@ -61,6 +61,30 @@ export function computerId() {
61
61
 
62
62
  export function setEnabled(on) { return writeRemote((d) => { d.enabled = Boolean(on); }); }
63
63
 
64
+ // The address's prefix: the account's 通讯号 at the gateway (<通讯号>.7bit.fun; its contacts find it by it too), asked
65
+ // for (handle null) or set with the gateway key (/v1/remote/contacts), the gateway checking the form, its reserved
66
+ // names and that no other account has it. {handle, auto, domain}; `auto`: still the one the gateway made up (cp and 6
67
+ // characters of its alphabet), not one the user chose. Throws with the gateway's words and a status for the page.
68
+ export async function addressPrefix(login, handle = null, { fetchImpl = globalThis.fetch } = {}) {
69
+ if (!login?.apiKey) throw Object.assign(new Error('远程访问需要先连接 7bit.fun'), { status: 409 });
70
+ const base = String(login.url || 'https://7bit.fun').replace(/\/+$/, '');
71
+ let r;
72
+ try {
73
+ r = await fetchImpl(`${base}/v1/remote/contacts${handle ? '/handle' : ''}`, {
74
+ method: handle ? 'POST' : 'GET',
75
+ headers: { authorization: `Bearer ${login.apiKey}`, ...(handle ? { 'content-type': 'application/json' } : {}) },
76
+ ...(handle ? { body: JSON.stringify({ handle }) } : {}),
77
+ signal: AbortSignal.timeout(15_000),
78
+ });
79
+ } catch (e) { throw Object.assign(new Error(`连不上网关:${e.message}`), { status: 502 }); }
80
+ const j = await r.json().catch(() => null);
81
+ if (!r.ok) throw Object.assign(new Error(j?.error?.message || (typeof j?.error === 'string' ? j.error : '') || `网关返回 ${r.status}`), { status: r.status === 409 || r.status === 400 ? r.status : 502 });
82
+ const now = String(j?.handle || '');
83
+ let domain = '7bit.fun';
84
+ try { domain = new URL(base).hostname; } catch { /* the default */ }
85
+ return { handle: now, auto: /^cp[a-hjkmnp-z2-9]{6}$/.test(now), domain };
86
+ }
87
+
64
88
  // ---------------------------------------------------------------- logged-in devices
65
89
 
66
90
  const hashToken = (secret) => crypto.createHash('sha256').update(secret).digest('base64url');
package/src/web/server.js CHANGED
@@ -166,6 +166,8 @@ async function serve() {
166
166
  return g?.apiKey ? { url: String(g.url || process.env.CLAUDE_PRO_GATEWAY_URL || 'https://7bit.fun'), apiKey: g.apiKey } : null;
167
167
  } catch { return null; }
168
168
  }
169
+ const gatewayHandle = (handle = null) => ra.addressPrefix(gatewayLoginNow(), handle);
170
+
169
171
  function syncTunnel() {
170
172
  const want = ra.readRemote().enabled && ra.hasPassword();
171
173
  const login = want ? gatewayLoginNow() : null;
@@ -247,8 +249,18 @@ async function serve() {
247
249
  }
248
250
  // 远程访问's own settings: on or off, the password, the devices logged in, the recent logins
249
251
  if (url.pathname === '/api/remote' && req.method === 'GET') return send(res, 200, remoteView());
252
+ if (url.pathname === '/api/remote/handle' && req.method === 'GET') {
253
+ try { return send(res, 200, await gatewayHandle()); } catch (e) { return send(res, e.status || 502, { error: e.message }); }
254
+ }
250
255
  if (url.pathname === '/api/remote' && req.method === 'POST') {
251
256
  const body = (await readBody(req)) || {};
257
+ // the prefix chosen (the first time, or changed): set at the gateway before anything else
258
+ if (typeof body.handle === 'string' && body.handle.trim()) {
259
+ try { await gatewayHandle(body.handle.trim().toLowerCase()); } catch (e) { return send(res, e.status || 502, { error: e.message }); }
260
+ // (an open tunnel took its host when it connected: again, for the new one)
261
+ tunnel?.close();
262
+ tunnel = null;
263
+ }
252
264
  if (typeof body.password === 'string' && body.password) {
253
265
  try { ra.setPassword(body.password); } catch (e) { return send(res, 400, { error: e.message }); }
254
266
  }