zcode-pro 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +12 -5
- package/README.md +12 -5
- package/dist/inject.js +4515 -415
- package/package.json +3 -3
- package/src/host/helper.mjs +3099 -48
- package/src/host/hot-swap.mjs +76 -0
- package/src/host/main.mjs +36 -14
- package/src/host/prompt-inject.mjs +174 -0
- package/src/host/provider-proxy.mjs +562 -0
- package/src/host/proxy-chain.mjs +137 -0
- package/src/host/setup.mjs +42 -17
- package/src/host/taskIndex.mjs +38 -13
- package/src/host/tool-name-check.mjs +164 -0
- package/src/host/translate-lib.mjs +781 -0
- package/src/inject/core.js +453 -17
- package/src/inject/features/auto-continue.js +46 -15
- package/src/inject/features/hr-notice.js +138 -0
- package/src/inject/features/newtab-panels.js +60 -20
- package/src/inject/features/proxy-chain-notice.js +215 -0
- package/src/inject/features/selection-toolbar-translate.js +174 -0
- package/src/inject/features/settings-dialog.js +1072 -86
- package/src/inject/features/status-bar.js +41 -10
- package/src/inject/features/translate-panel.js +883 -0
- package/src/inject/features/turn-usage.js +22 -3
- package/src/inject/index.js +10 -0
- package/src/inject/locales/ja.js +235 -7
- package/src/inject/locales/ko.js +235 -7
- package/src/inject/locales/ru.js +235 -7
- package/src/inject/provider-model-thinking.js +142 -0
- package/src/inject/thinking-levels.js +117 -0
- package/src/inject/ui.js +472 -2
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// 代理链:一条链是有序的节点序列,可关联多个供应商。
|
|
2
|
+
// 节点顺序即执行顺序——压缩在前就先进 headroom,注入在前就先改请求体。
|
|
3
|
+
// 这条规则是为了让「先压缩再注入」和「先注入再压缩」都成立:headroom 是透传代理,
|
|
4
|
+
// 压缩完才把请求发给下一跳,所以注入只有在 headroom 之后才能拿到压缩后的内容。
|
|
5
|
+
//
|
|
6
|
+
// 节点类型:
|
|
7
|
+
// - headroom:把请求交给本地压缩路由(8787),由它压缩后转发给链的下一跳
|
|
8
|
+
// - inject:把提示词注入的正文追加到请求的 system 末尾
|
|
9
|
+
// - custom:经自定义代理(或多级串联)出网
|
|
10
|
+
const NODE_TYPES = new Set(['headroom', 'inject', 'custom']);
|
|
11
|
+
const PROXY_URL_RE = /^https?:\/\/\S+:\d+$/;
|
|
12
|
+
|
|
13
|
+
// 归一化一条链:id/name/providers/nodes。非法节点丢弃,顺序保留。
|
|
14
|
+
export function normalizeChain(entry, sharedProxies) {
|
|
15
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null;
|
|
16
|
+
const id = typeof entry.id === 'string' ? entry.id.trim().slice(0, 64) : '';
|
|
17
|
+
if (!id) return null;
|
|
18
|
+
const name = typeof entry.name === 'string' && entry.name.trim()
|
|
19
|
+
? entry.name.trim().slice(0, 60) : id;
|
|
20
|
+
const providers = [];
|
|
21
|
+
for (const p of Array.isArray(entry.providers) ? entry.providers : []) {
|
|
22
|
+
if (typeof p !== 'string' || !p.trim()) continue;
|
|
23
|
+
if (p === '__proto__' || p === 'constructor' || p === 'prototype') continue;
|
|
24
|
+
if (!providers.includes(p)) providers.push(p);
|
|
25
|
+
if (providers.length >= 64) break;
|
|
26
|
+
}
|
|
27
|
+
const nodes = [];
|
|
28
|
+
for (const n of Array.isArray(entry.nodes) ? entry.nodes : []) {
|
|
29
|
+
if (nodes.length >= 8) break;
|
|
30
|
+
if (!n || typeof n !== 'object' || !NODE_TYPES.has(n.type)) continue;
|
|
31
|
+
if (n.type === 'custom') {
|
|
32
|
+
const proxy = typeof n.proxy === 'string' ? n.proxy.trim().slice(0, 300) : '';
|
|
33
|
+
const proxyId = typeof n.proxyId === 'string' ? n.proxyId.trim().slice(0, 64) : '';
|
|
34
|
+
if (proxy && !PROXY_URL_RE.test(proxy)) continue; // 填错地址的节点丢弃
|
|
35
|
+
if (!proxy && !proxyId) { nodes.push({ type: 'custom', proxy: '' }); continue; } // 空位保留等填写
|
|
36
|
+
nodes.push(proxy ? { type: 'custom', proxy } : { type: 'custom', proxyId });
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
// 同类型节点只留一个(headroom / inject 各至多一个),重复的丢弃
|
|
40
|
+
if (nodes.some((x) => x.type === n.type)) continue;
|
|
41
|
+
nodes.push({ type: n.type });
|
|
42
|
+
}
|
|
43
|
+
// 端口:链级(一条链一个转发器),不是每供应商一个
|
|
44
|
+
const port = Number.isFinite(Number(entry.port)) && Number(entry.port) >= 1024 && Number(entry.port) <= 65535
|
|
45
|
+
? Math.round(Number(entry.port)) : null;
|
|
46
|
+
const enabled = entry.enabled !== false;
|
|
47
|
+
// 供应商 → 真实上游。链首不是 headroom 时 ZCode 直连链转发器,转发器只能按
|
|
48
|
+
// API key 反查该发给谁;这个映射就是唯一来源(此时不依赖 headroom.json)。
|
|
49
|
+
// 注意:这里不按 providers 裁剪——供应商被移出链时,还要靠这份记录把它的
|
|
50
|
+
// baseUrl 还原成真实上游(见 chainUpstreamForProvider)。记录留着不占多少空间,
|
|
51
|
+
// 丢了就没法还原了
|
|
52
|
+
const upstreams = {};
|
|
53
|
+
const rawUp = entry.upstreams && typeof entry.upstreams === 'object' && !Array.isArray(entry.upstreams)
|
|
54
|
+
? entry.upstreams : {};
|
|
55
|
+
for (const [pid, u] of Object.entries(rawUp)) {
|
|
56
|
+
if (pid === '__proto__' || pid === 'constructor' || pid === 'prototype') continue;
|
|
57
|
+
if (typeof u !== 'string') continue;
|
|
58
|
+
const t = u.trim().slice(0, 500);
|
|
59
|
+
if (!/^https?:\/\/\S+$/i.test(t)) continue;
|
|
60
|
+
upstreams[pid] = t;
|
|
61
|
+
if (Object.keys(upstreams).length >= 64) break;
|
|
62
|
+
}
|
|
63
|
+
// 兼容端口:由“逐家转发”迁移出来的链,保留原来各家供应商的转发端口。
|
|
64
|
+
// ZCode 里还在用旧地址的会话照常能连上——对齐时在这些端口上各起一个“原样转到
|
|
65
|
+
// 链入口”的转发器(不注入,注入只在链转发器里做一次)。合法的端口整数,最多 16 个
|
|
66
|
+
const legacyPorts = [];
|
|
67
|
+
for (const lp of Array.isArray(entry.legacyPorts) ? entry.legacyPorts : []) {
|
|
68
|
+
const n = Math.round(Number(lp));
|
|
69
|
+
if (!Number.isFinite(n) || n < 1024 || n > 65535 || legacyPorts.includes(n)) continue;
|
|
70
|
+
legacyPorts.push(n);
|
|
71
|
+
if (legacyPorts.length >= 16) break;
|
|
72
|
+
}
|
|
73
|
+
return { id, name, providers, nodes, port, enabled, upstreams, ...(legacyPorts.length ? { legacyPorts } : {}) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function normalizeChains(saved, sharedProxies) {
|
|
77
|
+
const list = Array.isArray(saved) ? saved : [];
|
|
78
|
+
const out = [];
|
|
79
|
+
const seen = new Set();
|
|
80
|
+
for (const e of list) {
|
|
81
|
+
const c = normalizeChain(e, sharedProxies);
|
|
82
|
+
if (!c || seen.has(c.id)) continue;
|
|
83
|
+
seen.add(c.id);
|
|
84
|
+
out.push(c);
|
|
85
|
+
if (out.length >= 32) break;
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 某供应商属于哪条链:第一条声明了它的链生效(界面保证不重复关联)
|
|
91
|
+
export function chainForProvider(chains, providerId) {
|
|
92
|
+
for (const c of Array.isArray(chains) ? chains : []) {
|
|
93
|
+
if (c && Array.isArray(c.providers) && c.providers.includes(providerId)) return c;
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 链的第一跳是什么:headroom 在链首时,ZCode 的地址要指向 8787 路由;
|
|
99
|
+
// 否则指向链自己的转发器端口。
|
|
100
|
+
export function chainEntryType(chain) {
|
|
101
|
+
const first = chain && Array.isArray(chain.nodes) ? chain.nodes[0] : null;
|
|
102
|
+
return first && first.type === 'headroom' ? 'headroom' : 'forwarder';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 链上所有自定义代理节点解析成地址列表(按顺序),引用共享代理的按 id 查表。
|
|
106
|
+
export function resolveCustomProxies(nodes, sharedProxies) {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (const n of Array.isArray(nodes) ? nodes : []) {
|
|
109
|
+
if (!n || n.type !== 'custom') continue;
|
|
110
|
+
let url = '';
|
|
111
|
+
if (typeof n.proxy === 'string' && n.proxy) url = n.proxy;
|
|
112
|
+
else if (typeof n.proxyId === 'string' && n.proxyId) {
|
|
113
|
+
const hit = (Array.isArray(sharedProxies) ? sharedProxies : []).find((e) => e && e.id === n.proxyId);
|
|
114
|
+
url = hit && typeof hit.url === 'string' ? hit.url : '';
|
|
115
|
+
}
|
|
116
|
+
if (url) out.push(url);
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// 链上某个节点之前是否已经有 headroom:决定注入拿到的是压缩前还是压缩后的内容
|
|
122
|
+
export function headroomRunsBefore(chain, nodeType) {
|
|
123
|
+
const nodes = chain && Array.isArray(chain.nodes) ? chain.nodes : [];
|
|
124
|
+
for (const n of nodes) {
|
|
125
|
+
if (n.type === nodeType) return false;
|
|
126
|
+
if (n.type === 'headroom') return true;
|
|
127
|
+
}
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 链是否需要注入(链上有 inject 节点且有正文)。注入功能没有启停开关,
|
|
132
|
+
// 勾选就是唯一开关
|
|
133
|
+
export function chainNeedsInject(chain, promptInjection) {
|
|
134
|
+
if (!chain || !Array.isArray(chain.nodes)) return false;
|
|
135
|
+
if (!chain.nodes.some((n) => n.type === 'inject')) return false;
|
|
136
|
+
return !!(promptInjection && typeof promptInjection.text === 'string' && promptInjection.text.trim());
|
|
137
|
+
}
|
package/src/host/setup.mjs
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
// - 仓库内 PowerShell 脚本(install.ps1 等)必须保存为带 BOM 的 UTF-8。
|
|
17
17
|
import { execFileSync } from 'node:child_process';
|
|
18
18
|
import { accessSync, chmodSync, constants as fsConstants, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
19
|
-
import { basename, dirname, join, sep } from 'node:path';
|
|
19
|
+
import { basename, delimiter, dirname, join, sep } from 'node:path';
|
|
20
20
|
import { homedir, platform } from 'node:os';
|
|
21
21
|
import { fileURLToPath } from 'node:url';
|
|
22
22
|
import { resolveZcodeExecutable } from './paths.mjs';
|
|
@@ -29,7 +29,10 @@ const SUPPORTED = ['linux', 'win32', 'darwin'];
|
|
|
29
29
|
// —— PATH 中的 zcode-pro 命令 ——
|
|
30
30
|
|
|
31
31
|
function commandInPath(plat) {
|
|
32
|
-
|
|
32
|
+
// process.env.PATH 是宿主机的环境变量,分隔符跟着宿主机走(Linux/':'、Windows/';'),
|
|
33
|
+
// 只有“找哪个文件名”跟目标平台走。按目标平台的分隔符切宿主机的 PATH,
|
|
34
|
+
// Windows 上模拟 Linux 流程时会被盘符里的冒号切碎(C:\… 切成 'C' 和 '\…')
|
|
35
|
+
const pathSep = delimiter;
|
|
33
36
|
// Windows 上 npm 会生成 zcode-pro.cmd / zcode-pro.ps1,pip 生成 zcode-pro.exe,
|
|
34
37
|
// 只有 .cmd / .exe 能被 wscript 的 sh.Run 直接运行
|
|
35
38
|
const names = plat === 'win32' ? ['zcode-pro.cmd', 'zcode-pro.exe'] : ['zcode-pro'];
|
|
@@ -100,11 +103,22 @@ function windowsPaths() {
|
|
|
100
103
|
}
|
|
101
104
|
|
|
102
105
|
// 经 Base64(UTF-16LE) 的 -EncodedCommand 执行 PowerShell:中文不经过命令行与
|
|
103
|
-
// 文件编码,任何系统代码页下都安全。返回 stdout
|
|
104
|
-
|
|
106
|
+
// 文件编码,任何系统代码页下都安全。返回 stdout;非零退出码抛错,报错附上
|
|
107
|
+
// stdout/stderr——PowerShell 的错误记录会序列化成 CLIXML 走这两路输出,
|
|
108
|
+
// 丢掉它们就只剩一个退出码,排查无从下手(导出仅供测试)
|
|
109
|
+
export function runPowerShell(script) {
|
|
105
110
|
const b64 = Buffer.from(script, 'utf16le').toString('base64');
|
|
106
|
-
|
|
107
|
-
|
|
111
|
+
try {
|
|
112
|
+
return execFileSync('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', b64],
|
|
113
|
+
{ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
|
|
114
|
+
} catch (err) {
|
|
115
|
+
const tail = (t) => (t.length > 2000 ? t.slice(0, 2000) + '…' : t);
|
|
116
|
+
const out = String(err.stdout || '').trim();
|
|
117
|
+
const errOut = String(err.stderr || '').trim();
|
|
118
|
+
throw new Error(String(err.message || err)
|
|
119
|
+
+ (out ? `\nstdout: ${tail(out)}` : '')
|
|
120
|
+
+ (errOut ? `\nstderr: ${tail(errOut)}` : ''));
|
|
121
|
+
}
|
|
108
122
|
}
|
|
109
123
|
|
|
110
124
|
// WSH 是否可用:复现 vbs 的启动调用(WScript.Shell.Run 隐藏窗口执行)。
|
|
@@ -185,7 +199,7 @@ export function windowsShortcutPlan(cmd, desktop = false, wshOk = true, menuLnk
|
|
|
185
199
|
' $l.TargetPath = "$env:SystemRoot\\System32\\wscript.exe"',
|
|
186
200
|
` $l.Arguments = '${psQuote(`"${paths.vbsPath}"`)}'`,
|
|
187
201
|
` $l.WorkingDirectory = '${psQuote(paths.vbsDir)}'`,
|
|
188
|
-
" $l.Description = 'ZCode
|
|
202
|
+
" $l.Description = 'ZCode 桌面版增强包:壁纸引擎、皮肤主题等三十余项增强,不修改客户端文件'",
|
|
189
203
|
iconLine,
|
|
190
204
|
'}',
|
|
191
205
|
] : [
|
|
@@ -197,7 +211,7 @@ export function windowsShortcutPlan(cmd, desktop = false, wshOk = true, menuLnk
|
|
|
197
211
|
// 降级分支不建 vbsDir(目录可能不存在,快捷方式会报“起始位置无效”):
|
|
198
212
|
// 起始位置改用命令所在目录
|
|
199
213
|
` $l.WorkingDirectory = '${psQuote(cmdWorkDir(cmd) || process.env.USERPROFILE || process.env.HOME || paths.vbsDir)}'`,
|
|
200
|
-
" $l.Description = 'ZCode
|
|
214
|
+
" $l.Description = 'ZCode 桌面版增强包:壁纸引擎、皮肤主题等三十余项增强,不修改客户端文件'",
|
|
201
215
|
iconLine,
|
|
202
216
|
' $l.WindowStyle = 7',
|
|
203
217
|
'}',
|
|
@@ -212,7 +226,10 @@ export function windowsShortcutPlan(cmd, desktop = false, wshOk = true, menuLnk
|
|
|
212
226
|
'$lnk.Save()',
|
|
213
227
|
] : []),
|
|
214
228
|
...(desktop ? [
|
|
215
|
-
"$
|
|
229
|
+
"$deskBase = [Environment]::GetFolderPath('Desktop')",
|
|
230
|
+
"# 桌面目录解析不出来(目录不存在等)时不能把快捷方式写进工作目录:跳过桌面快捷方式",
|
|
231
|
+
"if (-not $deskBase) { Write-Output 'DESKTOP_UNRESOLVED'; exit 0 }",
|
|
232
|
+
"$desk = Join-Path $deskBase 'ZCode Pro.lnk'",
|
|
216
233
|
'$dl = $wsh.CreateShortcut($desk)',
|
|
217
234
|
'# 已存在且非本功能创建(Arguments 无归属标记)时不覆盖',
|
|
218
235
|
`if (-not (Test-Path $desk) -or (${ownsExpr('$dl')})) {`,
|
|
@@ -246,7 +263,7 @@ function desktopEntry(execCmd) {
|
|
|
246
263
|
'[Desktop Entry]',
|
|
247
264
|
'Type=Application',
|
|
248
265
|
'Name=ZCode Pro',
|
|
249
|
-
'Comment=ZCode
|
|
266
|
+
'Comment=ZCode 桌面版增强包:壁纸引擎、皮肤主题等三十余项增强,不修改客户端文件',
|
|
250
267
|
`Exec=${exec}`,
|
|
251
268
|
'Icon=zcode',
|
|
252
269
|
'Terminal=false',
|
|
@@ -391,7 +408,7 @@ const shortcutItem = {
|
|
|
391
408
|
mkdirSync(plan.vbsDir, { recursive: true });
|
|
392
409
|
writeFileSync(plan.vbsPath, plan.vbsContent);
|
|
393
410
|
}
|
|
394
|
-
runPowerShell(plan.psScript);
|
|
411
|
+
const psOut = runPowerShell(plan.psScript);
|
|
395
412
|
const how = wshOk
|
|
396
413
|
? `silent launch via ${plan.vbsPath}`
|
|
397
414
|
: 'WSH unavailable on this machine; minimized cmd launch (console flashes briefly on start)';
|
|
@@ -399,7 +416,11 @@ const shortcutItem = {
|
|
|
399
416
|
parts.push(menuForeign
|
|
400
417
|
? `start menu ${plan.lnkPath} exists (created elsewhere), not overwritten`
|
|
401
418
|
: `created ${plan.lnkPath}`);
|
|
402
|
-
if (opts.desktop) parts.push(deskForeign
|
|
419
|
+
if (opts.desktop) parts.push(deskForeign
|
|
420
|
+
? `desktop ${deskPath} exists (created elsewhere), not overwritten`
|
|
421
|
+
: String(psOut).includes('DESKTOP_UNRESOLVED')
|
|
422
|
+
? 'desktop skipped (desktop folder not resolvable)'
|
|
423
|
+
: 'desktop shortcut created');
|
|
403
424
|
return { detail: `${parts.join('; ')} (${how})` };
|
|
404
425
|
},
|
|
405
426
|
|
|
@@ -496,11 +517,15 @@ const shortcutItem = {
|
|
|
496
517
|
'$wsh = New-Object -ComObject WScript.Shell',
|
|
497
518
|
`$lnk = $wsh.CreateShortcut('${psQuote(paths.lnkPath)}')`,
|
|
498
519
|
`if (${ownsExpr('$lnk')}) { Remove-Item -LiteralPath '${psQuote(paths.lnkPath)}' -Force }`,
|
|
499
|
-
// setup --desktop 建的桌面 .lnk
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
'
|
|
503
|
-
|
|
520
|
+
// setup --desktop 建的桌面 .lnk 一并清理(归属校验同开始菜单)。
|
|
521
|
+
// 桌面目录解析不出来时跳过这一段,不能让整个卸载脚本报错(.lnk 会被误留)
|
|
522
|
+
"$deskBase = [Environment]::GetFolderPath('Desktop')",
|
|
523
|
+
'if ($deskBase) {',
|
|
524
|
+
" $desk = Join-Path $deskBase 'ZCode Pro.lnk'",
|
|
525
|
+
' if (Test-Path $desk) {',
|
|
526
|
+
' $dl = $wsh.CreateShortcut($desk)',
|
|
527
|
+
` if (${ownsExpr('$dl')}) { Remove-Item -LiteralPath $desk -Force }`,
|
|
528
|
+
' }',
|
|
504
529
|
'}',
|
|
505
530
|
].join('\r\n'));
|
|
506
531
|
verified = true;
|
package/src/host/taskIndex.mjs
CHANGED
|
@@ -20,6 +20,9 @@ import { existsSync } from 'node:fs';
|
|
|
20
20
|
import { join } from 'node:path';
|
|
21
21
|
|
|
22
22
|
const BUSY_TIMEOUT_MS = 5000;
|
|
23
|
+
// 生成速率上限:整段返回的供应商首末间隔只有几十毫秒,按它算的速率能到几十万
|
|
24
|
+
// tok/s(全库实测最大 50 万),超过这个数就直接按全程算生成时长
|
|
25
|
+
const RATE_CAP = 1000;
|
|
23
26
|
// 子代理轮次结束与 session.time_updated 的写入先后有几毫秒差;超过这段时长的新活动
|
|
24
27
|
// 才算下一轮已经开始(继续对话),见 listSubagentChildrenActivity
|
|
25
28
|
const SUBAGENT_TURN_START_GRACE_MS = 5000;
|
|
@@ -494,18 +497,28 @@ export async function listSessionModelUsage(dataRoot, sessionId, treeTrace = '')
|
|
|
494
497
|
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
495
498
|
}
|
|
496
499
|
const num = (v) => Number(v) || 0;
|
|
497
|
-
// 净生成时长 = 耗时 − 首 token
|
|
498
|
-
//
|
|
499
|
-
//
|
|
500
|
-
//
|
|
501
|
-
//
|
|
502
|
-
|
|
500
|
+
// 净生成时长 = 耗时 − 首 token 时机(与官方开发者工具的 TPS 同一条公式)。
|
|
501
|
+
// 两种情形按全程(耗时)算:
|
|
502
|
+
// 1. 首 token 时机缺失(部分供应商不回传,如 glm-5.3 占近三成):排除掉会让
|
|
503
|
+
// 整段速率消失;
|
|
504
|
+
// 2. 按首 token 扣出来的速率超过 RATE_CAP:整段返回的供应商首末只差几十毫秒,
|
|
505
|
+
// 实测速率能到几十万 tok/s,那不是真实吞吐。
|
|
506
|
+
// 早先用“首 token 占耗时 8 成以上算全程”做判定,缓冲式供应商(mimo 实测首末
|
|
507
|
+
// 只差 600ms、占耗时 8%)被误判成整段返回,速率只有官方值的十分之一。
|
|
508
|
+
const genMsOf = (dur, ttft, out) => {
|
|
509
|
+
if (!(dur > 0)) return null;
|
|
510
|
+
if (!(ttft > 0)) return dur;
|
|
511
|
+
const gap = dur - ttft;
|
|
512
|
+
if (gap <= 0) return dur;
|
|
513
|
+
if (out / (gap / 1000) > RATE_CAP) return dur;
|
|
514
|
+
return gap;
|
|
515
|
+
};
|
|
503
516
|
const rounds = rows.map((r, i) => {
|
|
504
517
|
const inp = num(r.input_tokens);
|
|
505
518
|
const cacheRead = num(r.cache_read_input_tokens);
|
|
506
519
|
const ttft = num(r.time_to_first_token_ms);
|
|
507
520
|
const dur = num(r.duration_ms);
|
|
508
|
-
const genMs = genMsOf(dur, ttft);
|
|
521
|
+
const genMs = genMsOf(dur, ttft, num(r.output_tokens));
|
|
509
522
|
const out = num(r.output_tokens);
|
|
510
523
|
return {
|
|
511
524
|
idx: i + 1,
|
|
@@ -552,7 +565,7 @@ export async function listSessionModelUsage(dataRoot, sessionId, treeTrace = '')
|
|
|
552
565
|
let genSum = 0;
|
|
553
566
|
for (const r of tRows) {
|
|
554
567
|
if (num(r.completed_at) < anchorT - 60_000) break;
|
|
555
|
-
const genMs = genMsOf(num(r.duration_ms), num(r.time_to_first_token_ms));
|
|
568
|
+
const genMs = genMsOf(num(r.duration_ms), num(r.time_to_first_token_ms), num(r.output_tokens));
|
|
556
569
|
if (genMs) { outSum += num(r.output_tokens); genSum += genMs; }
|
|
557
570
|
}
|
|
558
571
|
if (genSum > 0) summary.tps = outSum / (genSum / 1000);
|
|
@@ -580,7 +593,7 @@ export async function listSessionTurnUsage(dataRoot, sessionId) {
|
|
|
580
593
|
+ ` input_tokens, output_tokens, reasoning_tokens, cache_read_input_tokens, cache_creation_input_tokens, computed_total_tokens`
|
|
581
594
|
+ ` FROM turn_usage WHERE session_id = ${esc(sid)} AND status = 'completed' AND completed_at IS NOT NULL`
|
|
582
595
|
+ ` AND (coalesce(input_tokens, 0) + coalesce(output_tokens, 0)) > 0 ORDER BY started_at ASC`;
|
|
583
|
-
const useSql = `SELECT completed_at, duration_ms, time_to_first_token_ms, input_tokens, output_tokens, cache_read_input_tokens`
|
|
596
|
+
const useSql = `SELECT completed_at, duration_ms, time_to_first_token_ms, input_tokens, output_tokens, reasoning_tokens, cache_read_input_tokens`
|
|
584
597
|
+ ` FROM model_usage WHERE session_id = ${esc(sid)} AND query_source = 'main_turn'`
|
|
585
598
|
+ ` AND status = 'completed' AND completed_at IS NOT NULL ORDER BY completed_at ASC`;
|
|
586
599
|
try {
|
|
@@ -604,12 +617,19 @@ export async function listSessionTurnUsage(dataRoot, sessionId) {
|
|
|
604
617
|
usages = JSON.parse(runCli(dbFile,
|
|
605
618
|
`SELECT coalesce(json_group_array(json_object('completed_at', completed_at, 'duration_ms', duration_ms,`
|
|
606
619
|
+ ` 'time_to_first_token_ms', time_to_first_token_ms, 'input_tokens', input_tokens, 'output_tokens', output_tokens,`
|
|
607
|
-
+ ` 'cache_read_input_tokens', cache_read_input_tokens)), '[]') FROM (${useSql});`
|
|
620
|
+
+ ` 'reasoning_tokens', reasoning_tokens, 'cache_read_input_tokens', cache_read_input_tokens)), '[]') FROM (${useSql});`
|
|
608
621
|
).stdout.trim() || '[]');
|
|
609
622
|
}
|
|
610
623
|
if (!turns.length) return null;
|
|
611
624
|
const num = (v) => Number(v) || 0;
|
|
612
|
-
const genMsOf = (dur, ttft) =>
|
|
625
|
+
const genMsOf = (dur, ttft, out) => {
|
|
626
|
+
if (!(dur > 0)) return null;
|
|
627
|
+
if (!(ttft > 0)) return dur;
|
|
628
|
+
const gap = dur - ttft;
|
|
629
|
+
if (gap <= 0) return dur;
|
|
630
|
+
if (out / (gap / 1000) > RATE_CAP) return dur;
|
|
631
|
+
return gap;
|
|
632
|
+
};
|
|
613
633
|
const rounds = turns.map((t, i) => {
|
|
614
634
|
const inp = num(t.input_tokens);
|
|
615
635
|
const cacheRead = num(t.cache_read_input_tokens);
|
|
@@ -621,6 +641,9 @@ export async function listSessionTurnUsage(dataRoot, sessionId) {
|
|
|
621
641
|
out: num(t.output_tokens),
|
|
622
642
|
total: num(t.computed_total_tokens),
|
|
623
643
|
reasoning: num(t.reasoning_tokens),
|
|
644
|
+
// 首 token 延迟:一轮取首个请求的值(turn_usage 自己记的就是首请求时机),
|
|
645
|
+
// 缺失记 0,注入侧据此隐藏该段
|
|
646
|
+
ttft: num(t.time_to_first_token_ms),
|
|
624
647
|
cacheRead,
|
|
625
648
|
cacheWrite: num(t.cache_creation_input_tokens),
|
|
626
649
|
hitRate: inp > 0 ? cacheRead / inp : null,
|
|
@@ -636,7 +659,7 @@ export async function listSessionTurnUsage(dataRoot, sessionId) {
|
|
|
636
659
|
while (ti < rounds.length && at > rounds[ti].at) ti += 1;
|
|
637
660
|
const turn = rounds[ti];
|
|
638
661
|
if (!turn || at < turn.startAt || at > turn.at) continue;
|
|
639
|
-
const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms));
|
|
662
|
+
const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms), num(u.output_tokens));
|
|
640
663
|
if (genMs) turn.genMs += genMs;
|
|
641
664
|
}
|
|
642
665
|
for (const turn of rounds) {
|
|
@@ -656,11 +679,13 @@ export async function listSessionTurnUsage(dataRoot, sessionId) {
|
|
|
656
679
|
for (const u of usages) {
|
|
657
680
|
const at = num(u.completed_at);
|
|
658
681
|
if (at <= lastAt) continue;
|
|
659
|
-
const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms));
|
|
682
|
+
const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms), num(u.output_tokens));
|
|
660
683
|
live.push({
|
|
661
684
|
at,
|
|
662
685
|
in: num(u.input_tokens),
|
|
663
686
|
out: num(u.output_tokens),
|
|
687
|
+
reasoning: num(u.reasoning_tokens),
|
|
688
|
+
ttft: num(u.time_to_first_token_ms),
|
|
664
689
|
cacheRead: num(u.cache_read_input_tokens),
|
|
665
690
|
genMs: genMs || 0,
|
|
666
691
|
tpsOut: genMs ? num(u.output_tokens) : 0,
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// 工具名合规检查:有的模型服务(如 Meta)限制 MCP 工具名 64 字符,超长整包 400。
|
|
2
|
+
// 工具全名按 mcp__<服务器键名>__<工具名> 拼(插件提供的服务器中间还带插件名),
|
|
3
|
+
// 工具名由插件自己定、改不了,缩短服务器键名是唯一能动手的地方。
|
|
4
|
+
// zcodepro.json 的 toolNameMaps 存“服务器键名 → 短键名”,这里把它写到三处:
|
|
5
|
+
// 1. ~/.zcode/cli/config.json 的 mcp.servers(用户级 MCP);
|
|
6
|
+
// 2. 已装插件的清单(插件缓存里的 .mcp.json 与 .zcode-plugin/plugin.json);
|
|
7
|
+
// 3. ZCode 安装目录的源包清单(packages/<插件>/.mcp.json 等,插件安装时从这里生成缓存)。
|
|
8
|
+
// ZCode 升级、插件更新会把键名改回长名,所以 helper 每次启动都对一次;设置页按钮可手动跑。
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { basename, join } from 'node:path';
|
|
12
|
+
|
|
13
|
+
function readJson(file) {
|
|
14
|
+
try {
|
|
15
|
+
const text = readFileSync(file, 'utf8');
|
|
16
|
+
return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text); // 记事本存的带 BOM 文件也能解析
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// 写 JSON:覆盖前留备份,再“临时文件 + 改名”原子写。临时文件建不出来时
|
|
23
|
+
//(EACCES/EPERM:目录属于 root、建不了新文件——ZCode 自带插件在 /opt 下就是这种,
|
|
24
|
+
// 但文件本身往往开放写)改成直接覆盖写目标文件;直接写也不行(文件本身只读)才抛错,
|
|
25
|
+
// 由调用方记成“写不了的文件”。直接覆盖写不保证原子(崩溃可能留半截文件),所以备份
|
|
26
|
+
// 先留住:同目录建不了(同样因为目录只读)就写到数据根的 tool-name-backups/ 下
|
|
27
|
+
function writeJsonWithBackup(file, obj, dataRoot) {
|
|
28
|
+
const text = JSON.stringify(obj, null, 2) + '\n';
|
|
29
|
+
let backed = false;
|
|
30
|
+
try { copyFileSync(file, file + '.zcodepro-backup'); backed = true; } catch { /* 同目录建不了备份:换地方 */ }
|
|
31
|
+
if (!backed && dataRoot) {
|
|
32
|
+
try {
|
|
33
|
+
const dir = join(dataRoot, 'tool-name-backups');
|
|
34
|
+
mkdirSync(dir, { recursive: true });
|
|
35
|
+
copyFileSync(file, join(dir, `${createHash('sha1').update(file).digest('hex').slice(0, 8)}-${basename(file)}`));
|
|
36
|
+
} catch { /* 两处都留不下备份不阻塞:改写内容可由映射表反推 */ }
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
40
|
+
writeFileSync(tmp, text, { encoding: 'utf8', mode: 0o600 });
|
|
41
|
+
renameSync(tmp, file);
|
|
42
|
+
return;
|
|
43
|
+
} catch (err) {
|
|
44
|
+
// 目录不可写导致临时文件建不出来才走直接写;其他错误(磁盘满等)直接抛
|
|
45
|
+
if (!err || !['EACCES', 'EPERM'].includes(err.code)) throw err;
|
|
46
|
+
}
|
|
47
|
+
writeFileSync(file, text, { encoding: 'utf8' }); // 目标文件本身开放写(如 666)时能写成功
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 把 servers 表里的长键名换成短名:目标短名已被占用就不动(不覆盖别人的服务器),
|
|
51
|
+
// 返回改过的 [{ from, to }]。导出以便测试。
|
|
52
|
+
export function renameServerKeys(servers, maps) {
|
|
53
|
+
const changed = [];
|
|
54
|
+
if (!servers || typeof servers !== 'object' || Array.isArray(servers)) return changed;
|
|
55
|
+
if (!maps || typeof maps !== 'object') return changed;
|
|
56
|
+
for (const [longName, shortName] of Object.entries(maps)) {
|
|
57
|
+
if (!Object.prototype.hasOwnProperty.call(servers, longName)) continue;
|
|
58
|
+
if (Object.prototype.hasOwnProperty.call(servers, shortName)) continue; // 短名已有配置,不动
|
|
59
|
+
servers[shortName] = servers[longName];
|
|
60
|
+
delete servers[longName];
|
|
61
|
+
changed.push({ from: longName, to: shortName });
|
|
62
|
+
}
|
|
63
|
+
return changed;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 列出一层子目录(目录不存在返回空)
|
|
67
|
+
function subDirs(dir) {
|
|
68
|
+
try {
|
|
69
|
+
return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join(dir, e.name));
|
|
70
|
+
} catch {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 收集要处理的清单文件:用户级配置单独按 mcp.servers 处理,其余按 mcpServers 处理
|
|
76
|
+
function collectManifestFiles({ dataRoot, sourcePackagesDir }) {
|
|
77
|
+
const files = [];
|
|
78
|
+
const cacheRoot = join(dataRoot, 'cli', 'plugins', 'cache');
|
|
79
|
+
for (const marketDir of subDirs(cacheRoot)) {
|
|
80
|
+
for (const pluginDir of subDirs(marketDir)) {
|
|
81
|
+
for (const versionDir of subDirs(pluginDir)) {
|
|
82
|
+
files.push(join(versionDir, '.mcp.json'));
|
|
83
|
+
files.push(join(versionDir, '.zcode-plugin', 'plugin.json'));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (sourcePackagesDir) {
|
|
88
|
+
for (const pkgDir of subDirs(sourcePackagesDir)) {
|
|
89
|
+
files.push(join(pkgDir, '.mcp.json'));
|
|
90
|
+
files.push(join(pkgDir, '.zcode-plugin', 'plugin.json'));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return files.filter((f) => existsSync(f));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// 跑一轮检查:返回 { scanned, changed: [文件 + from/to], warnings, unwritable }。
|
|
97
|
+
// unwritable 是想改但写不进去的文件(典型:ZCode 自带插件在安装目录下,目录属于 root):
|
|
98
|
+
// 跳过它继续处理别的文件,由调用方决定怎么提示。
|
|
99
|
+
// dryRun=true 只看不改(设置页“检查”用)。
|
|
100
|
+
export function applyToolNameMaps({ dataRoot, zcodeConfigFile, maps, sourcePackagesDir = '', dryRun = false } = {}) {
|
|
101
|
+
const scanned = [];
|
|
102
|
+
const changed = [];
|
|
103
|
+
const warnings = [];
|
|
104
|
+
const unwritable = [];
|
|
105
|
+
const table = (maps && typeof maps === 'object' && !Array.isArray(maps)) ? maps : {};
|
|
106
|
+
// 映射为空也照样扫一遍:报告“扫了 N 个文件、无需改动”,而不是给个 0 让用户以为没查到
|
|
107
|
+
if (!Object.keys(table).length) warnings.push('没有配置工具名映射,只扫描未改动');
|
|
108
|
+
|
|
109
|
+
// 1. 用户级 MCP:~/.zcode/cli/config.json 的 mcp.servers
|
|
110
|
+
if (zcodeConfigFile && existsSync(zcodeConfigFile)) {
|
|
111
|
+
const cfg = readJson(zcodeConfigFile);
|
|
112
|
+
if (!cfg) {
|
|
113
|
+
warnings.push(`${zcodeConfigFile} 无法解析,跳过`);
|
|
114
|
+
} else {
|
|
115
|
+
scanned.push(zcodeConfigFile);
|
|
116
|
+
const mcp = (cfg.mcp && typeof cfg.mcp === 'object' && !Array.isArray(cfg.mcp)) ? { ...cfg.mcp } : null;
|
|
117
|
+
if (mcp && mcp.servers && typeof mcp.servers === 'object' && !Array.isArray(mcp.servers)) {
|
|
118
|
+
const servers = { ...mcp.servers };
|
|
119
|
+
const hits = renameServerKeys(servers, table);
|
|
120
|
+
if (hits.length) {
|
|
121
|
+
if (!dryRun) {
|
|
122
|
+
mcp.servers = servers;
|
|
123
|
+
cfg.mcp = mcp;
|
|
124
|
+
try { writeJsonWithBackup(zcodeConfigFile, cfg, dataRoot); } catch (err) {
|
|
125
|
+
warnings.push(`${zcodeConfigFile} 写入失败(${err?.message || err})`);
|
|
126
|
+
unwritable.push({ file: zcodeConfigFile, error: String(err?.message || err), renames: hits });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const h of hits) changed.push({ file: zcodeConfigFile, ...h });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 2. 插件清单:顶层 mcpServers
|
|
136
|
+
for (const file of collectManifestFiles({ dataRoot, sourcePackagesDir })) {
|
|
137
|
+
const doc = readJson(file);
|
|
138
|
+
if (!doc) { warnings.push(`${file} 无法解析,跳过`); continue; }
|
|
139
|
+
scanned.push(file);
|
|
140
|
+
if (!doc.mcpServers || typeof doc.mcpServers !== 'object' || Array.isArray(doc.mcpServers)) continue;
|
|
141
|
+
const servers = { ...doc.mcpServers };
|
|
142
|
+
const hits = renameServerKeys(servers, table);
|
|
143
|
+
if (!hits.length) continue;
|
|
144
|
+
if (!dryRun) {
|
|
145
|
+
doc.mcpServers = servers;
|
|
146
|
+
try { writeJsonWithBackup(file, doc, dataRoot); } catch (err) {
|
|
147
|
+
warnings.push(`${file} 写入失败(${err?.message || err})`);
|
|
148
|
+
unwritable.push({ file, error: String(err?.message || err), renames: hits });
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (const h of hits) changed.push({ file, ...h });
|
|
153
|
+
}
|
|
154
|
+
return { scanned: scanned.length, changed, warnings, unwritable };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// 一行结果文案(设置页按钮下方显示)
|
|
158
|
+
export function toolNameCheckSummary(result) {
|
|
159
|
+
const r = result || { scanned: 0, changed: [], warnings: [] };
|
|
160
|
+
if (r.warnings && r.warnings.length) return `检查 ${r.scanned} 个文件,${r.changed.length} 处改短;${r.warnings[0]}`;
|
|
161
|
+
if (!r.changed.length) return `检查 ${r.scanned} 个文件,服务器键名都合规,无需改动`;
|
|
162
|
+
const names = [...new Set(r.changed.map((c) => `${c.from} → ${c.to}`))];
|
|
163
|
+
return `检查 ${r.scanned} 个文件,把 ${r.changed.length} 处改短:${names.join('、')}`;
|
|
164
|
+
}
|