zcode-pro 1.11.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 +11 -4
- package/README.md +11 -4
- package/dist/inject.js +1895 -482
- package/package.json +2 -2
- package/src/host/helper.mjs +2412 -184
- package/src/host/hot-swap.mjs +76 -0
- package/src/host/main.mjs +35 -13
- package/src/host/prompt-inject.mjs +174 -0
- package/src/host/provider-proxy.mjs +298 -72
- package/src/host/proxy-chain.mjs +137 -0
- package/src/host/setup.mjs +39 -14
- package/src/host/taskIndex.mjs +7 -2
- package/src/host/tool-name-check.mjs +43 -12
- package/src/host/translate-lib.mjs +1 -1
- package/src/inject/core.js +240 -19
- package/src/inject/features/auto-continue.js +17 -15
- package/src/inject/features/hr-notice.js +70 -20
- package/src/inject/features/proxy-chain-notice.js +215 -0
- package/src/inject/features/settings-dialog.js +769 -338
- package/src/inject/features/status-bar.js +17 -6
- package/src/inject/features/turn-usage.js +22 -3
- package/src/inject/index.js +3 -0
- package/src/inject/locales/ja.js +121 -6
- package/src/inject/locales/ko.js +121 -6
- package/src/inject/locales/ru.js +121 -6
- package/src/inject/provider-model-thinking.js +142 -0
- package/src/inject/thinking-levels.js +12 -6
- package/src/inject/ui.js +113 -3
package/src/host/helper.mjs
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
// 仅绑定 127.0.0.1,并通过每次启动随机生成的 token 鉴权。
|
|
4
4
|
|
|
5
5
|
import { createServer } from 'node:http';
|
|
6
|
+
import { connect as netConnect } from 'node:net';
|
|
6
7
|
import { execFile, spawn, spawnSync } from 'node:child_process';
|
|
7
8
|
import { createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
8
|
-
import { appendFileSync, chmodSync, closeSync, copyFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { appendFileSync, chmodSync, closeSync, copyFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from 'node:fs';
|
|
9
10
|
import { mkdtemp } from 'node:fs/promises'; // 注意:fs 的 mkdtemp 是回调版,await 它会把 undefined 当回调
|
|
10
11
|
import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
11
12
|
import { homedir, tmpdir, userInfo } from 'node:os';
|
|
@@ -19,8 +20,10 @@ import { resolveZcodeExecutable, resolveDataRootDir } from './paths.mjs';
|
|
|
19
20
|
import { skillStats, DEFAULT_METADATA_BUDGET } from './skill-stats.mjs';
|
|
20
21
|
import { listImportSessions, runImport } from './session-import/index.mjs';
|
|
21
22
|
import { ProviderProxyManager } from './provider-proxy.mjs';
|
|
23
|
+
import { normalizeChains, chainForProvider, resolveCustomProxies, chainNeedsInject, chainEntryType } from './proxy-chain.mjs';
|
|
24
|
+
import { rewriteRequest } from './prompt-inject.mjs';
|
|
22
25
|
import { applyToolNameMaps, toolNameCheckSummary } from './tool-name-check.mjs';
|
|
23
|
-
import { defaultTranslateFile, readTranslateConfig, writeTranslateConfig, validateTranslateConfig, translateServicesStatus, translateMt, translateJson, streamTranslateText, isWordText, targetLangFor, renderTranslatePrompt, TRANSLATE_MAX_TEXT, isValidThinking, readTranslateHistory, appendTranslateHistory } from './translate-lib.mjs';
|
|
26
|
+
import { defaultTranslateFile, readTranslateConfig, writeTranslateConfig, validateTranslateConfig, translateServicesStatus, translateMt, translateJson, streamTranslateText, isWordText, targetLangFor, renderTranslatePrompt, TRANSLATE_MAX_TEXT, isValidThinking, applyThinking, readTranslateHistory, appendTranslateHistory } from './translate-lib.mjs';
|
|
24
27
|
|
|
25
28
|
// 会话导入(/import/list、/import/run):把外部 CLI 的历史会话写成 ZCode 任务。
|
|
26
29
|
|
|
@@ -313,6 +316,12 @@ function cliPluginsDir() {
|
|
|
313
316
|
return join(resolveDataRootDir(), 'cli', 'plugins');
|
|
314
317
|
}
|
|
315
318
|
|
|
319
|
+
// 提示词注入的默认正文:只给一个标题行,用户在这行下面接着写规则。
|
|
320
|
+
// 标题跟官方 system 里其它段(# Identity、# Harness)同一种写法,也说明它是全局的、
|
|
321
|
+
// 每轮都带,不是某个项目的规则。
|
|
322
|
+
// 定义在 defaultConfig 之前:defaultConfig 会引用它,放后面会踩 const 的暂时性死区。
|
|
323
|
+
const DEFAULT_INJECT_TEXT = '# Global System Prompt\n';
|
|
324
|
+
|
|
316
325
|
export function defaultConfig() {
|
|
317
326
|
return {
|
|
318
327
|
version: VERSION,
|
|
@@ -391,6 +400,9 @@ export function defaultConfig() {
|
|
|
391
400
|
baseUrl: '',
|
|
392
401
|
apiKey: '',
|
|
393
402
|
format: '',
|
|
403
|
+
// 思考档位:off/低/中/高… 具体可选值取决于所选模型(见 listTitleGenProviders
|
|
404
|
+
// 的 modelReasoning);保存前由前端按模型档位自适应
|
|
405
|
+
thinking: 'off',
|
|
394
406
|
recentQa: 3,
|
|
395
407
|
hoverBtn: true,
|
|
396
408
|
menuEntry: true,
|
|
@@ -402,15 +414,38 @@ export function defaultConfig() {
|
|
|
402
414
|
// 软件(headroom 与 rtk)的安装、检查更新与升级;sync = WebDAV 同步。同步默认
|
|
403
415
|
// 关闭——坚果云等国内网盘通常直连即可,代理停了同步会跟着失败
|
|
404
416
|
proxyScopes: { plugins: true, deps: true, sync: false },
|
|
405
|
-
// 供应商代理(设置页“代理 → 供应商代理”二级):供应商 id →
|
|
406
|
-
// port, upstream }。enabled=true
|
|
407
|
-
//
|
|
417
|
+
// 供应商代理(设置页“代理 → 供应商代理”二级):供应商 id →
|
|
418
|
+
// { enabled, port, upstream, nodes }。enabled=true 时该供应商的模型请求走本机
|
|
419
|
+
// 转发进程(127.0.0.1),再按 nodes 里的自定义代理逐级发出。
|
|
420
|
+
// nodes 是有序的代理链,目前只支持一个 { type:'custom', proxy } 生效;
|
|
421
|
+
// 更多节点先存着、界面标“暂不生效”(多级 CONNECT 在下一阶段做)。
|
|
408
422
|
// 不动 ZCode 自身的全局代理,也不走 headroom 路由——只改 baseUrl 指向转发地址。
|
|
409
423
|
providerProxies: {},
|
|
424
|
+
// 代理链(设置页“代理 → 代理链”):独立实体,可关联多个供应商。
|
|
425
|
+
// { id, name, providers: [供应商 id], nodes: [{type:'headroom'|'inject'|'custom', ...}],
|
|
426
|
+
// port, enabled }。nodes 顺序即执行顺序:headroom 在前就先压缩再注入,
|
|
427
|
+
// 反之则注入先于压缩。一条链共用一套节点配置(想差异化就建两条链)。
|
|
428
|
+
proxyChains: [],
|
|
429
|
+
// 代理链总开关(设置页“代理 → 代理链”顶部):关=链配置保留但不生效,
|
|
430
|
+
// 对齐不接管任何供应商地址(已有接管会被撤销);开=勾在链上的供应商
|
|
431
|
+
// 地址由链接管。默认关:升级装上代理链的用户地址不被自动动,想用再打开
|
|
432
|
+
proxyChainEnabled: false,
|
|
433
|
+
// OpenCode Go 兼容(设置页“代理 → 代理链”,默认开):经链转发到 OpenCode Go 端点
|
|
434
|
+
// 的请求由转发器补上会话请求头。关掉后这类供应商经链会被端点拒绝,只能直连
|
|
435
|
+
opencodeGoCompat: true,
|
|
436
|
+
// 共享代理:在供应商代理页顶部定义一次、供下面各供应商选用的代理地址。
|
|
437
|
+
// 引用存储的是 id(nodes 里的 proxyId),改这里的地址会连带影响所有引用方。
|
|
438
|
+
sharedProxies: [],
|
|
439
|
+
// 提示词注入(设置页“行为 → 全局提示词”下半块):转发前把 text 追加到请求体
|
|
440
|
+
// 已有的 system 内容末尾。只对在代理链里勾选、且链上有注入节点的供应商生效——
|
|
441
|
+
// 勾选就是唯一开关,注入功能本身没有启停设置(以前有 enabled,已去掉)。
|
|
442
|
+
// subagents=true 时子代理的请求也带(默认只给主对话)。
|
|
443
|
+
// 默认正文只放一个标题行:让用户看出“这是分节的写法”,往标题下面接着写规则即可。
|
|
444
|
+
promptInjection: { text: DEFAULT_INJECT_TEXT, subagents: false },
|
|
410
445
|
// headroom 上游代理:headroom 插件拉起实例时带 HEADROOM_HTTP_PROXY,
|
|
411
446
|
// 实例连上游(BigModel/MiMo/Command Code 等)走它。空 = 不走代理(旧行为)。
|
|
412
447
|
headroomProxy: '',
|
|
413
|
-
//
|
|
448
|
+
// 工具名合规检查(设置页“行为 → 运行时”底行):服务器键名 → 短键名。
|
|
414
449
|
// 有的模型服务(如 Meta)对 MCP 工具名长度限 64 字符,超长会整包 400。
|
|
415
450
|
// 这里持久化贴壳后的短名:ZCode 升级/插件更新会改回长名,启动时自动重打。
|
|
416
451
|
toolNameMaps: { 'android-emulator': 'ae', 'tencent-docs': 'td' },
|
|
@@ -511,6 +546,11 @@ export function loadConfig(configFile) {
|
|
|
511
546
|
theme: mergeThemeConfig(saved.theme),
|
|
512
547
|
proxyScopes: mergeProxyScopes(saved.proxyScopes),
|
|
513
548
|
providerProxies: mergeProviderProxies(saved.providerProxies),
|
|
549
|
+
proxyChainEnabled: saved.proxyChainEnabled === true,
|
|
550
|
+
opencodeGoCompat: saved.opencodeGoCompat !== false,
|
|
551
|
+
proxyChains: normalizeChains(saved.proxyChains, mergeSharedProxies(saved.sharedProxies)),
|
|
552
|
+
sharedProxies: mergeSharedProxies(saved.sharedProxies),
|
|
553
|
+
promptInjection: mergePromptInjection(saved.promptInjection),
|
|
514
554
|
headroomProxy: typeof saved.headroomProxy === 'string' ? saved.headroomProxy.trim().slice(0, 300) : '',
|
|
515
555
|
toolNameMaps: mergeToolNameMaps(saved.toolNameMaps),
|
|
516
556
|
toolNameAuto: saved.toolNameAuto !== false,
|
|
@@ -691,6 +731,15 @@ let systemProxyCache = { url: '', at: 0 };
|
|
|
691
731
|
// headroom 上游代理(HEADROOM_HTTP_PROXY):随 zcodepro.json 的 headroomProxy
|
|
692
732
|
// 保存即时更新;runHeadroomHook 拉起实例时带上。
|
|
693
733
|
let activeHeadroomProxy = '';
|
|
734
|
+
// 提示词注入的运行时快照:每次请求转发时读这里,所以保存后下一次请求就生效,
|
|
735
|
+
// 不用重启转发器。
|
|
736
|
+
// 本模块实例的身份:模块每重新求值一次(开发模式热替换)就是一个新的 Symbol。
|
|
737
|
+
// 挂在 state 上的“只做一次”标志都按它判断——同一个实例不重复做;换了实例(新代码)
|
|
738
|
+
// 就重做一遍。否则热替换后新代码里的启动对齐、文件监听永远不执行,仍是旧实例的行为
|
|
739
|
+
const HELPER_INSTANCE = Symbol('zcodepro-helper-instance');
|
|
740
|
+
// 本实例注册的配置文件监听:dispose 时关掉(回调闭包指向的是本实例的代码)
|
|
741
|
+
let providerProxyWatchers = [];
|
|
742
|
+
let activePromptInjection = { text: '', subagents: false };
|
|
694
743
|
// 供应商代理转发器单例:正常挂 state(跨热替换实例共享——helper 热替换后旧转发器
|
|
695
744
|
// 继续跑,端口不变、供应商地址不用重写);单测直调不传 state 时退回模块级一份。
|
|
696
745
|
let providerProxyManager = null;
|
|
@@ -724,6 +773,12 @@ function providerProxyOwnUrl(url, port) {
|
|
|
724
773
|
return p >= PROVIDER_PROXY_PORT_MIN && p <= PROVIDER_PROXY_PORT_MAX;
|
|
725
774
|
}
|
|
726
775
|
|
|
776
|
+
// 某地址是不是本机回环地址(127.0.0.1 / localhost / ::1):链端口、headroom 路由、
|
|
777
|
+
// 旧转发端口都是。还原成“真实上游”时这类地址不能用
|
|
778
|
+
function isLocalBaseUrl(url) {
|
|
779
|
+
return /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/i.test(String(url || '').trim());
|
|
780
|
+
}
|
|
781
|
+
|
|
727
782
|
// 从 provider_config.json 文档里取某供应商的 api.baseUrl(地址)
|
|
728
783
|
function providerProxyRuleBaseUrl(pc, id) {
|
|
729
784
|
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
@@ -733,13 +788,18 @@ function providerProxyRuleBaseUrl(pc, id) {
|
|
|
733
788
|
return typeof u === 'string' ? u.trim() : '';
|
|
734
789
|
}
|
|
735
790
|
|
|
736
|
-
//
|
|
791
|
+
// 某供应商当前在用的地址:以 provider_config.json 的规则为准,规则里没有才回退到
|
|
792
|
+
// v2/config.json 的 provider 表。
|
|
793
|
+
// 曾经是 config.json 优先(当时桌面确实读它)。现在 ZCode 的个人供应商配置仓库就是
|
|
794
|
+
// provider_config.json,config.json 只作为旧格式被一次性导入(zcode.cjs 里建仓库时
|
|
795
|
+
// 传的是 importLegacy)。两份不一致时先看 config.json 会误判成“已对齐”:
|
|
796
|
+
// 规则里已是真实上游,对齐却因为 config.json 里还是转发地址而什么都不改
|
|
737
797
|
function providerProxyCurrentBaseUrl(dataRoot, id) {
|
|
798
|
+
const fromRule = providerProxyRuleBaseUrl(readJsonFile(join(dataRoot, 'v2', 'provider_config.json')), id);
|
|
799
|
+
if (fromRule) return fromRule;
|
|
738
800
|
const v2 = readJsonFile(join(dataRoot, 'v2', 'config.json'));
|
|
739
801
|
const p = v2?.provider?.[id];
|
|
740
|
-
|
|
741
|
-
if (fromV2) return fromV2;
|
|
742
|
-
return providerProxyRuleBaseUrl(readJsonFile(join(dataRoot, 'v2', 'provider_config.json')), id);
|
|
802
|
+
return (p && typeof p === 'object' && typeof p.options?.baseURL === 'string') ? p.options.baseURL.trim() : '';
|
|
743
803
|
}
|
|
744
804
|
|
|
745
805
|
// 从备份文件里找某供应商的地址(当前地址已是转发地址、配置里又没记上游时兜底)
|
|
@@ -751,18 +811,23 @@ function providerProxyBackupBaseUrl(dataRoot, id) {
|
|
|
751
811
|
return providerProxyRuleBaseUrl(readJsonFile(join(dataRoot, 'v2', 'provider_config.json.zcodepro-backup')), id);
|
|
752
812
|
}
|
|
753
813
|
|
|
814
|
+
// 改 v2 配置前的备份与原子写入:多处共用(供应商代理、代理链入口地址)。
|
|
815
|
+
// 备份失败不阻塞(原子写本身安全);临时文件名带 pid+时间防多写者撕裂
|
|
816
|
+
function backupV2File(p) {
|
|
817
|
+
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
818
|
+
}
|
|
819
|
+
function atomicWriteJson(p, obj) {
|
|
820
|
+
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
821
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
822
|
+
renameSync(tmp, p);
|
|
823
|
+
}
|
|
824
|
+
|
|
754
825
|
// 把某供应商在两张 v2 表里的地址改成 target,返回改了几处(target 非空字符串才动)
|
|
755
826
|
function providerProxyRewriteBaseUrl(dataRoot, id, target) {
|
|
756
827
|
if (typeof target !== 'string' || !target) return 0;
|
|
757
828
|
if (id === '__proto__' || id === 'constructor' || id === 'prototype') return 0;
|
|
758
|
-
const backupFile =
|
|
759
|
-
|
|
760
|
-
};
|
|
761
|
-
const atomicWrite = (p, obj) => {
|
|
762
|
-
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
763
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
764
|
-
renameSync(tmp, p);
|
|
765
|
-
};
|
|
829
|
+
const backupFile = backupV2File;
|
|
830
|
+
const atomicWrite = atomicWriteJson;
|
|
766
831
|
let changed = 0;
|
|
767
832
|
const v2File = join(dataRoot, 'v2', 'config.json');
|
|
768
833
|
const v2 = readJsonFile(v2File);
|
|
@@ -790,143 +855,1618 @@ function providerProxyRewriteBaseUrl(dataRoot, id, target) {
|
|
|
790
855
|
return changed;
|
|
791
856
|
}
|
|
792
857
|
|
|
793
|
-
//
|
|
794
|
-
//
|
|
795
|
-
//
|
|
796
|
-
|
|
858
|
+
// 绝对不允许改写地址的供应商。留空 = 没有例外,所有供应商都按代理链统一处理。
|
|
859
|
+
// 曾经把 Command Code 2 与 BigModel-Max1 放在这里:它们的 baseUrl 不会被改写,
|
|
860
|
+
// 后果是拿不到 chainTarget、请求不经过链转发器,所以既不走链上代理也没有提示词注入。
|
|
861
|
+
// 用户确认代理链已经可用后要求“正常走代理链”,因此清空。
|
|
862
|
+
export const PROVIDER_PROXY_PROTECTED_IDS = new Set([]);
|
|
863
|
+
|
|
864
|
+
// 旧入口名,保留给既有的调用方和测试。“逐家转发”并入代理链之后,供应商地址与
|
|
865
|
+
// 转发器只有一个对齐入口(ensureProxyChains):迁移旧条目 → 停旧转发器 → 按链对齐。
|
|
866
|
+
// 以前两套对齐各改各的地址,互相覆盖:这边刚还原成直连,那边 1.5 秒后又改回本机端口
|
|
867
|
+
export function ensureProviderProxies(options = {}) {
|
|
868
|
+
return ensureProxyChains(options);
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// —— 代理链运行时 ——
|
|
872
|
+
// 每条链一个转发器(端口独立),链上的代理节点按顺序逐层串联。
|
|
873
|
+
// 「注入在压缩之后」这种顺序靠 headroom 的 chainTarget 实现:把 headroom 实例的
|
|
874
|
+
// 出口指向链转发器,headroom 压缩完把请求发过来,注入在转发器里做。
|
|
875
|
+
// 真实上游由转发器按请求里的 API key 查 headroom.json 的 keyHash 映射决定——
|
|
876
|
+
// 因为 headroom 的 upstream 字段保存的是真实厂商地址,正好可以复用。
|
|
877
|
+
|
|
878
|
+
// 从请求头取 API key(anthropic 用 x-api-key,openai 用 Authorization: Bearer)
|
|
879
|
+
function apiKeyOfRequest(req) {
|
|
880
|
+
const k = String(req.headers['x-api-key'] || '').trim();
|
|
881
|
+
if (k) return k;
|
|
882
|
+
const auth = String(req.headers.authorization || '');
|
|
883
|
+
return auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// 构造"按 key 查真实上游"的解析器。两个来源,按优先级:
|
|
887
|
+
// 1. 链自己的 upstreams(providerId → 真实上游):链首不是 headroom 时唯一来源,
|
|
888
|
+
// 此时完全不需要 headroom.json
|
|
889
|
+
// 2. headroom.json 的 providers(keyHash → upstream):链上有 headroom 节点时用,
|
|
890
|
+
// 因为 headroom 已经按 key 登记过上游
|
|
891
|
+
// 拿不到就返回空串,转发器据此回 500「未配置上游地址」
|
|
892
|
+
function makeChainUpstreamResolver(dataRoot, chain) {
|
|
893
|
+
const own = (chain && chain.upstreams && typeof chain.upstreams === 'object') ? chain.upstreams : {};
|
|
894
|
+
const ownKeys = Object.keys(own);
|
|
895
|
+
// keyHash → upstream 缓存:每次请求重算要读两个配置文件,太浪费;
|
|
896
|
+
// 但用户可能中途在界面改了 key,所以按文件 mtime 失效(≈100ms 内的改动会晚一拍生效)
|
|
897
|
+
let cache = { at: 0, map: null };
|
|
898
|
+
const buildOwn = () => {
|
|
899
|
+
const pcFile = join(dataRoot, 'v2', 'provider_config.json');
|
|
900
|
+
const v2File = join(dataRoot, 'v2', 'config.json');
|
|
901
|
+
let at = 0;
|
|
902
|
+
try { at = Math.max(statSync(pcFile).mtimeMs, statSync(v2File).mtimeMs); } catch { /* 读不到就当没变 */ }
|
|
903
|
+
if (cache.map && at && at === cache.at) return cache.map;
|
|
904
|
+
const pc = readJsonFile(pcFile);
|
|
905
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
906
|
+
const cfgV2 = readJsonFile(v2File);
|
|
907
|
+
const providersMap = (cfgV2 && typeof cfgV2 === 'object' && cfgV2.provider && typeof cfgV2.provider === 'object')
|
|
908
|
+
? cfgV2.provider : {};
|
|
909
|
+
// providerId → apiKey:providerRules 优先,config.json 的 options 回退
|
|
910
|
+
const keyOf = new Map();
|
|
911
|
+
if (Array.isArray(rules)) {
|
|
912
|
+
for (const r of rules) {
|
|
913
|
+
if (!r || typeof r.providerId !== 'string') continue;
|
|
914
|
+
const k = String(r?.config?.access?.apiKey || '').trim();
|
|
915
|
+
if (k) keyOf.set(r.providerId, k);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
for (const [pid, prov] of Object.entries(providersMap)) {
|
|
919
|
+
if (keyOf.has(pid)) continue;
|
|
920
|
+
const k = String(prov?.options?.apiKey || '').trim();
|
|
921
|
+
if (k) keyOf.set(pid, k);
|
|
922
|
+
}
|
|
923
|
+
const map = new Map();
|
|
924
|
+
for (const pid of ownKeys) {
|
|
925
|
+
const k = keyOf.get(pid);
|
|
926
|
+
if (!k) continue;
|
|
927
|
+
map.set(createHash('sha256').update(k).digest('hex'), own[pid]);
|
|
928
|
+
}
|
|
929
|
+
cache = { at, map };
|
|
930
|
+
return map;
|
|
931
|
+
};
|
|
932
|
+
return (req) => {
|
|
933
|
+
const key = apiKeyOfRequest(req);
|
|
934
|
+
if (!key) return '';
|
|
935
|
+
const hash = createHash('sha256').update(key).digest('hex');
|
|
936
|
+
// 先查链自己的映射(不依赖 headroom.json,这是链自己当入口时的唯一来源)
|
|
937
|
+
if (ownKeys.length) {
|
|
938
|
+
const u = buildOwn().get(hash);
|
|
939
|
+
if (u && /^https?:\/\/\S+$/i.test(u)) return u;
|
|
940
|
+
}
|
|
941
|
+
// 再查 headroom 登记(链上有 headroom 节点时用得上)
|
|
942
|
+
const hr = readJsonFile(join(dataRoot, 'headroom.json'));
|
|
943
|
+
const hit = Array.isArray(hr?.providers) ? hr.providers.find((p) => p && p.keyHash === hash) : null;
|
|
944
|
+
const up = hit && typeof hit.upstream === 'string' ? hit.upstream.trim() : '';
|
|
945
|
+
return /^https?:\/\/\S+$/.test(up) ? up : '';
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// 把链上 headroom 的 chainTarget 写进 headroom.json 的供应商登记。
|
|
950
|
+
// 只改 chainTarget,不动 upstream(面板仍显示真实厂商地址)。
|
|
951
|
+
function applyChainTargets({ dataRoot, chains, portOf }) {
|
|
952
|
+
const file = join(dataRoot, 'headroom.json');
|
|
953
|
+
const doc = readJsonFile(file);
|
|
954
|
+
if (!doc || !Array.isArray(doc.providers)) return { changed: 0 };
|
|
955
|
+
// providerId → 期望的 chainTarget(空串表示清掉)。
|
|
956
|
+
// 两种拓扑都经 chainTarget 把压缩结果交给我们:
|
|
957
|
+
// 链首 headroom:chainTarget = 该链转发器(压缩后注入/出网)
|
|
958
|
+
// 注入优先(链首转发器 + headroom 在后):chainTarget = 回程转发器
|
|
959
|
+
// (headroom 之后那截的执行器,custom 多级串联出网);headroom 之后
|
|
960
|
+
// 没有节点时为空——实例直连真实上游
|
|
961
|
+
const want = new Map();
|
|
962
|
+
for (const c of chains) {
|
|
963
|
+
if (!c || c.enabled === false) continue;
|
|
964
|
+
// 受保护的供应商不参与,避免误动它们的 headroom 登记
|
|
965
|
+
const ids = (c.providers || []).filter((pid) => !PROVIDER_PROXY_PROTECTED_IDS.has(pid));
|
|
966
|
+
if (!ids.length) continue;
|
|
967
|
+
const hasHeadroom = Array.isArray(c.nodes) && c.nodes.some((n) => n.type === 'headroom');
|
|
968
|
+
const hrIndex = (c.nodes || []).findIndex((n) => n.type === 'headroom');
|
|
969
|
+
const afterHr = hrIndex >= 0 && hrIndex < c.nodes.length - 1;
|
|
970
|
+
// 转发器没起来(portOf 给不出有效端口)就清 chainTarget:写个错误端口会把
|
|
971
|
+
// 请求发进死口;注入优先拓扑下旧代码兜底到入口端口,入口的上游是 8787,
|
|
972
|
+
// 会形成「入口转发器 ↔ 8787」循环且每圈多注入一次。清掉则实例直连真实
|
|
973
|
+
// 上游——压缩可用、注入/出网暂缺,属于安全降级
|
|
974
|
+
let target = '';
|
|
975
|
+
if (hasHeadroom && afterHr) {
|
|
976
|
+
const port = Number(portOf(c));
|
|
977
|
+
if (Number.isFinite(port) && port >= 1024) target = `http://127.0.0.1:${Math.round(port)}`;
|
|
978
|
+
}
|
|
979
|
+
for (const pid of ids) want.set(pid, target);
|
|
980
|
+
}
|
|
981
|
+
let changed = 0;
|
|
982
|
+
for (const p of doc.providers) {
|
|
983
|
+
if (!p || typeof p.id !== 'string') continue;
|
|
984
|
+
// 受保护的供应商:不写也不清 chainTarget,完全不动它的登记
|
|
985
|
+
if (PROVIDER_PROXY_PROTECTED_IDS.has(p.id)) continue;
|
|
986
|
+
const next = want.get(p.id) || '';
|
|
987
|
+
const cur = typeof p.chainTarget === 'string' ? p.chainTarget.trim() : '';
|
|
988
|
+
if (cur === next) continue;
|
|
989
|
+
if (next) p.chainTarget = next;
|
|
990
|
+
else delete p.chainTarget;
|
|
991
|
+
changed += 1;
|
|
992
|
+
}
|
|
993
|
+
if (changed) {
|
|
994
|
+
try { writeJsonAtomic(file, doc); } catch { return { changed: 0, error: 'headroom.json 写入失败' }; }
|
|
995
|
+
}
|
|
996
|
+
return { changed };
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// 把链上供应商的 baseUrl 指到链入口。链首是 headroom 时入口是 8787(现有行为,
|
|
1000
|
+
// 由 headroom 的 /hr-join 负责写,这里不碰);链首不是 headroom 时,ZCode 必须
|
|
1001
|
+
// 直连链自己的转发器,否则请求进不来、注入和自定义代理都没机会执行。
|
|
1002
|
+
//
|
|
1003
|
+
// 只动这些供应商自己的 baseUrl,不改别人;受保护的两个供应商整条跳过。
|
|
1004
|
+
// 还原时(链被关掉/供应商被移出)按链里记的 upstreams 写回真实上游——
|
|
1005
|
+
// 这是链首不是 headroom 时唯一可靠的上游来源,所以进入时先记下来。
|
|
1006
|
+
function applyChainEntryAddresses({ dataRoot, chains, portOf, providerProxies, state }) {
|
|
1007
|
+
const pcFile = join(dataRoot, 'v2', 'provider_config.json');
|
|
1008
|
+
const pc = readJsonFile(pcFile);
|
|
1009
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
1010
|
+
if (!Array.isArray(rules)) return { changed: 0 };
|
|
1011
|
+
const stuckIds = []; // 指着链端口但还原不了来源的供应商
|
|
1012
|
+
const errorParts = [];
|
|
1013
|
+
// providerId → 期望的 baseUrl(链入口,空串表示不动)。
|
|
1014
|
+
// 完整规则:baseUrl 永远指向链拓扑要求的入口——链首是 headroom 时是 8787
|
|
1015
|
+
//(不再依赖 /hr-join 当时的写入,手改、半配置、同步残留都会被收回),
|
|
1016
|
+
// 链首是其他节点时是链自己的转发端口
|
|
1017
|
+
const want = new Map();
|
|
1018
|
+
for (const c of chains) {
|
|
1019
|
+
if (!c || c.enabled === false) continue;
|
|
1020
|
+
const entry = chainEntryType(c);
|
|
1021
|
+
let url = '';
|
|
1022
|
+
if (entry === 'headroom') {
|
|
1023
|
+
url = `http://127.0.0.1:${headroomRouterPort(dataRoot)}`;
|
|
1024
|
+
} else {
|
|
1025
|
+
const port = portOf(c);
|
|
1026
|
+
if (!Number.isFinite(Number(port)) || Number(port) < 1024) continue;
|
|
1027
|
+
url = `http://127.0.0.1:${Math.round(Number(port))}`;
|
|
1028
|
+
}
|
|
1029
|
+
for (const pid of c.providers || []) {
|
|
1030
|
+
if (PROVIDER_PROXY_PROTECTED_IDS.has(pid)) continue;
|
|
1031
|
+
want.set(pid, url);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
let changed = 0;
|
|
1035
|
+
for (const r of rules) {
|
|
1036
|
+
if (!r || typeof r.providerId !== 'string') continue;
|
|
1037
|
+
const cur = r.config && r.config.api && typeof r.config.api.baseUrl === 'string'
|
|
1038
|
+
? r.config.api.baseUrl.trim() : '';
|
|
1039
|
+
const next = want.get(r.providerId);
|
|
1040
|
+
if (next) {
|
|
1041
|
+
// 记下“这家供应商的地址现在是链写的”。之后它要是变成了别的真实网址,
|
|
1042
|
+
// 就是用户在 ZCode 里手动改的(见 uncheckManuallyChanged)
|
|
1043
|
+
try { if (state && typeof state === 'object') (state.chainAddressWritten ||= {})[r.providerId] = next; } catch { /* state 不可写不影响 */ }
|
|
1044
|
+
if (cur === next) continue;
|
|
1045
|
+
if (!r.config || typeof r.config !== 'object') r.config = {};
|
|
1046
|
+
if (!r.config.api || typeof r.config.api !== 'object') r.config.api = {};
|
|
1047
|
+
r.config.api.baseUrl = next;
|
|
1048
|
+
changed += 1;
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
// 不在任何"转发器入口"链上:如果它的地址正指着某个链转发器(我们写的),
|
|
1052
|
+
// 说明这条链被删了或供应商被移出了,得把地址还原成链里记的真实上游。
|
|
1053
|
+
// 不是我们写的地址(比如用户自己改成 8787 或真实厂商地址)一律不碰
|
|
1054
|
+
const m = /^http:\/\/127\.0\.0\.1:(\d{4,5})\/?$/i.exec(cur);
|
|
1055
|
+
if (!m) continue;
|
|
1056
|
+
const port = Number(m[1]);
|
|
1057
|
+
if (port < PROVIDER_PROXY_PORT_MIN) continue;
|
|
1058
|
+
// 能被“已启用的供应商代理条目(同端口)”解释的地址是供应商代理写的,不是链
|
|
1059
|
+
// 写的(比如刚移出某条链、但自己开着供应商代理的供应商):不还原,
|
|
1060
|
+
// 否则会把转发地址改成真实上游,下一轮供应商代理对齐再把它改回来
|
|
1061
|
+
const pp = providerProxies && providerProxies[r.providerId];
|
|
1062
|
+
if (pp && pp.enabled === true && Number(pp.port) === port) continue;
|
|
1063
|
+
const restore = chainUpstreamForProvider(chains, r.providerId) || registryRealUpstream(dataRoot, r.providerId);
|
|
1064
|
+
if (!restore) { stuckIds.push(r.providerId); continue; }
|
|
1065
|
+
r.config.api.baseUrl = restore;
|
|
1066
|
+
changed += 1;
|
|
1067
|
+
}
|
|
1068
|
+
if (stuckIds.length) {
|
|
1069
|
+
// 静默跳过等于把死端口问题藏起来:这里至少要在对齐结果里报出来,
|
|
1070
|
+
// 设置弹窗的状态行会显示
|
|
1071
|
+
errorParts.push(`供应商 ${stuckIds.join('、')}:地址指向链端口但找不到还原来源(链里没记 upstreams),请手动改回真实地址或重新勾选链`);
|
|
1072
|
+
}
|
|
1073
|
+
if (changed) {
|
|
1074
|
+
try {
|
|
1075
|
+
backupV2File(pcFile);
|
|
1076
|
+
atomicWriteJson(pcFile, pc);
|
|
1077
|
+
} catch { return { changed: 0, error: 'provider_config.json 写入失败' + (errorParts.length ? ';' + errorParts.join(';') : '') }; }
|
|
1078
|
+
}
|
|
1079
|
+
return { changed, ...(errorParts.length ? { error: errorParts.join(';') } : {}) };
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// 还原一批供应商为直连(headroom tab 的「还原」按钮)。
|
|
1083
|
+
// 三件事:headroom 登记删条目、从所有链移出、baseUrl 写回真实上游。
|
|
1084
|
+
// 恢复基准(Q1):ZCode 配置里已是真实地址 → 不动;否则按
|
|
1085
|
+
// 链 upstreams → 登记 origBaseURL 的顺序取第一个可用的。
|
|
1086
|
+
// 幂等:不在登记/不在链上的 id 也接受(等于 no-op),方便界面批量调用
|
|
1087
|
+
export function restoreProviders({ dataRoot, configFile, ids }) {
|
|
1088
|
+
const pcFile = join(dataRoot, 'v2', 'provider_config.json');
|
|
1089
|
+
const pc = readJsonFile(pcFile);
|
|
1090
|
+
const rules = Array.isArray(pc?.config?.providerConfigRules?.providerRules)
|
|
1091
|
+
? pc.config.providerConfigRules.providerRules : null;
|
|
1092
|
+
if (!rules) return { error: 'provider_config.json 读取失败' };
|
|
1093
|
+
const ruleById = new Map();
|
|
1094
|
+
for (const r of rules) if (r && typeof r.providerId === 'string') ruleById.set(r.providerId, r);
|
|
1095
|
+
// 链:内存里修剪,落盘一次
|
|
1096
|
+
const cfg = loadConfig(configFile);
|
|
1097
|
+
const chains = Array.isArray(cfg.proxyChains) ? cfg.proxyChains : [];
|
|
1098
|
+
let chainChanged = 0;
|
|
1099
|
+
for (const c of chains) {
|
|
1100
|
+
if (!c || !Array.isArray(c.providers)) continue;
|
|
1101
|
+
const before = c.providers.length;
|
|
1102
|
+
const keep = c.providers.filter((pid) => !ids.includes(pid));
|
|
1103
|
+
if (keep.length !== before) { c.providers = keep; chainChanged += before - keep.length; }
|
|
1104
|
+
}
|
|
1105
|
+
// 登记删除 + 上游还原基准
|
|
1106
|
+
const hrFile = join(dataRoot, 'headroom.json');
|
|
1107
|
+
const hr = readJsonFile(hrFile);
|
|
1108
|
+
const kept = Array.isArray(hr?.providers) ? hr.providers : [];
|
|
1109
|
+
const removed = kept.filter((p) => p && ids.includes(p.id));
|
|
1110
|
+
let urlChanged = 0;
|
|
1111
|
+
for (const id of ids) {
|
|
1112
|
+
const r = ruleById.get(id);
|
|
1113
|
+
if (!r || !r.config?.api) continue;
|
|
1114
|
+
const cur = typeof r.config.api.baseUrl === 'string' ? r.config.api.baseUrl.trim() : '';
|
|
1115
|
+
// 已是真实地址就不动(最新事实优先于历史快照)
|
|
1116
|
+
if (cur && /^https?:\/\//i.test(cur) && !/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/i.test(cur)) continue;
|
|
1117
|
+
// 链 upstreams → origBaseURL 顺序取
|
|
1118
|
+
let up = chainUpstreamForProvider(chains, id);
|
|
1119
|
+
if (!up) {
|
|
1120
|
+
const rec = removed.find((p) => p.id === id);
|
|
1121
|
+
const ob = typeof rec?.origBaseURL === 'string' ? rec.origBaseURL.trim() : '';
|
|
1122
|
+
if (ob && /^https?:\/\/\S+$/.test(ob) && !/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/i.test(ob)) up = ob;
|
|
1123
|
+
}
|
|
1124
|
+
if (!up) continue;
|
|
1125
|
+
r.config.api.baseUrl = up;
|
|
1126
|
+
urlChanged += 1;
|
|
1127
|
+
}
|
|
1128
|
+
try {
|
|
1129
|
+
if (chainChanged > 0) {
|
|
1130
|
+
// 锁内重读再修剪:拿锁外的旧 chains 整表覆盖会把锁内期间别人的修改吞掉
|
|
1131
|
+
withConfigLockSync(configFile, () => {
|
|
1132
|
+
const fresh = loadConfig(configFile);
|
|
1133
|
+
if (configUnreadable) return;
|
|
1134
|
+
const list = Array.isArray(fresh.proxyChains) ? fresh.proxyChains : [];
|
|
1135
|
+
for (const c of list) {
|
|
1136
|
+
if (c && Array.isArray(c.providers)) {
|
|
1137
|
+
c.providers = c.providers.filter((pid) => !ids.includes(pid));
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
saveConfig(configFile, fresh);
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
if (removed.length && Array.isArray(hr?.providers)) {
|
|
1144
|
+
const doc = { ...hr, providers: kept.filter((p) => p && !ids.includes(p.id)) };
|
|
1145
|
+
atomicWriteJson(hrFile, doc);
|
|
1146
|
+
}
|
|
1147
|
+
if (urlChanged > 0) { backupV2File(pcFile); atomicWriteJson(pcFile, pc); }
|
|
1148
|
+
} catch (err) {
|
|
1149
|
+
return { error: String(err?.message || err) };
|
|
1150
|
+
}
|
|
1151
|
+
return { restored: ids.length, chainRemoved: chainChanged, urlRestored: urlChanged, registeredRemoved: removed.length };
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
// 归一化上游地址:剥掉常见端点尾巴。ZCode 配置里的 baseUrl 有时填的是完整端点
|
|
1155
|
+
//(如 https://host/v1/chat/completions),而 headroom 登记的 upstream 语义是
|
|
1156
|
+
// base 地址,实例会在其上拼端点路径;不剥的话路径会重复(上游 404)
|
|
1157
|
+
const UPSTREAM_TAIL_RE = /\/(chat\/completions|completions|v1\/messages|messages|responses|v1\/responses|embeddings|v1\/embeddings|count_tokens)\/?$/i;
|
|
1158
|
+
function normalizeUpstreamUrl(raw) {
|
|
1159
|
+
let u = String(raw || '').trim();
|
|
1160
|
+
if (!/^https?:\/\/\S+$/i.test(u)) return '';
|
|
1161
|
+
for (let i = 0; i < 3; i++) { // 连续尾巴(/v1/chat/completions 只剥一层,别把 /v1 也带走)
|
|
1162
|
+
const next = u.replace(UPSTREAM_TAIL_RE, '');
|
|
1163
|
+
if (next === u) break;
|
|
1164
|
+
u = next;
|
|
1165
|
+
}
|
|
1166
|
+
return u.replace(/\/+$/, '');
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
// 链上有 headroom 节点 + 供应商未在 headroom 登记时,自动补登记。
|
|
1170
|
+
// 数据全部现成:key 取 ZCode 配置、真实上游取该供应商当前 baseUrl(直连状态)
|
|
1171
|
+
// 或链的 upstreams 记录、格式按 api.type 推断。没有 key 或拿不到上游就跳过
|
|
1172
|
+
//(沿用对账的 pending 提示,不在这里报错——这是尽力而为的便利,不是硬保证)。
|
|
1173
|
+
// 归一化在写入前做(剥端点尾巴)。
|
|
1174
|
+
export function autoRegisterChainProviders({ dataRoot, chains, config }) {
|
|
1175
|
+
const hrFile = join(dataRoot, 'headroom.json');
|
|
1176
|
+
// 文件不存在=还没接入过 headroom:按空登记起步(自动登记正是入口)。
|
|
1177
|
+
// 存在但读坏=拒绝写(不能拿空对象覆盖),直接放弃
|
|
1178
|
+
let hr;
|
|
1179
|
+
if (!existsSync(hrFile)) hr = { providers: [] };
|
|
1180
|
+
else {
|
|
1181
|
+
const raw = readJsonFile(hrFile);
|
|
1182
|
+
if (!raw || typeof raw !== 'object') return { changed: 0 };
|
|
1183
|
+
hr = raw;
|
|
1184
|
+
if (!Array.isArray(hr.providers)) hr.providers = [];
|
|
1185
|
+
}
|
|
1186
|
+
const registered = new Set(hr.providers.map((p) => p && typeof p.id === 'string' ? p.id : ''));
|
|
1187
|
+
// ZCode 供应商全集:providerRules 优先,config.json 的 provider 回退
|
|
1188
|
+
const pc = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'));
|
|
1189
|
+
const cfgV2 = readJsonFile(join(dataRoot, 'v2', 'config.json'));
|
|
1190
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
1191
|
+
const providersMap = (cfgV2 && typeof cfgV2 === 'object' && cfgV2.provider && typeof cfgV2.provider === 'object')
|
|
1192
|
+
? cfgV2.provider : {};
|
|
1193
|
+
const zcodeById = new Map();
|
|
1194
|
+
if (Array.isArray(rules)) {
|
|
1195
|
+
for (const r of rules) {
|
|
1196
|
+
if (!r || typeof r.providerId !== 'string') continue;
|
|
1197
|
+
const apiKey = String(r?.config?.access?.apiKey || '').trim();
|
|
1198
|
+
const baseUrl = String(r?.config?.api?.baseUrl || '').trim();
|
|
1199
|
+
const apiType = String(r?.config?.api?.type || '');
|
|
1200
|
+
const name = String(r?.providerName || r.providerId);
|
|
1201
|
+
if (apiKey && baseUrl) zcodeById.set(r.providerId, { apiKey, baseUrl, apiType, name });
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
for (const [pid, prov] of Object.entries(providersMap)) {
|
|
1205
|
+
if (zcodeById.has(pid)) continue;
|
|
1206
|
+
const apiKey = String(prov?.options?.apiKey || '').trim();
|
|
1207
|
+
const baseUrl = String(prov?.options?.baseURL || '').trim();
|
|
1208
|
+
if (apiKey && baseUrl) zcodeById.set(pid, { apiKey, baseUrl, apiType: '', name: String(prov?.name || pid) });
|
|
1209
|
+
}
|
|
1210
|
+
const added = [];
|
|
1211
|
+
const updated = [];
|
|
1212
|
+
const byId = new Map(hr.providers.filter((p) => p && typeof p.id === 'string').map((p) => [p.id, p]));
|
|
1213
|
+
for (const c of chains) {
|
|
1214
|
+
if (!c || c.enabled === false) continue;
|
|
1215
|
+
// 链上没有 headroom 节点就不需要登记(请求不经 8787)
|
|
1216
|
+
if (!Array.isArray(c.nodes) || !c.nodes.some((n) => n.type === 'headroom')) continue;
|
|
1217
|
+
for (const pid of c.providers || []) {
|
|
1218
|
+
if (registered.has(pid)) {
|
|
1219
|
+
// 已登记:链里记着这家供应商的真实地址时,登记里的上游跟着它走,格式按供应商
|
|
1220
|
+
// 现在的协议。供应商地址被改过(比如换成 OpenCode Go 端点、协议也换了)之后
|
|
1221
|
+
// 再勾回链上,登记还停在老地址老格式,请求会被 headroom 发去错的端点
|
|
1222
|
+
const rec = byId.get(pid);
|
|
1223
|
+
const zNow = zcodeById.get(pid);
|
|
1224
|
+
const recUp = (c.upstreams && typeof c.upstreams[pid] === 'string') ? normalizeUpstreamUrl(c.upstreams[pid]) : '';
|
|
1225
|
+
if (!rec || !zNow || !recUp || isLocalBaseUrl(recUp)) continue;
|
|
1226
|
+
const tNow = zNow.apiType.toLowerCase();
|
|
1227
|
+
const fmtNow = tNow.includes('anthropic') ? 'anthropic'
|
|
1228
|
+
: ((tNow.includes('openai') || tNow.includes('responses')) ? 'openai' : '');
|
|
1229
|
+
const nextUp = recUp;
|
|
1230
|
+
const nextFmt = fmtNow || rec.format;
|
|
1231
|
+
if (rec.upstream === nextUp && rec.format === nextFmt) continue;
|
|
1232
|
+
rec.upstream = nextUp;
|
|
1233
|
+
if (nextFmt) rec.format = nextFmt;
|
|
1234
|
+
rec.origBaseURL = nextUp;
|
|
1235
|
+
updated.push(rec);
|
|
1236
|
+
continue;
|
|
1237
|
+
}
|
|
1238
|
+
const z = zcodeById.get(pid);
|
|
1239
|
+
if (!z) continue;
|
|
1240
|
+
// 真实上游:优先链里记的,其次当前 baseUrl(须是真实地址,本机端口不算)
|
|
1241
|
+
let up = (c.upstreams && typeof c.upstreams[pid] === 'string') ? c.upstreams[pid].trim() : '';
|
|
1242
|
+
if (!up || /^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/i.test(up)) {
|
|
1243
|
+
up = /^https?:\/\/.*/i.test(z.baseUrl) && !/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/i.test(z.baseUrl)
|
|
1244
|
+
? z.baseUrl : '';
|
|
1245
|
+
}
|
|
1246
|
+
up = normalizeUpstreamUrl(up);
|
|
1247
|
+
if (!up) continue;
|
|
1248
|
+
const t = z.apiType.toLowerCase();
|
|
1249
|
+
const format = t.includes('anthropic') ? 'anthropic'
|
|
1250
|
+
: (t.includes('openai') || t.includes('responses') ? 'openai'
|
|
1251
|
+
: (/anthropic/i.test(up) ? 'anthropic' : 'openai'));
|
|
1252
|
+
const keyHash = createHash('sha256').update(z.apiKey).digest('hex');
|
|
1253
|
+
const entry = { id: pid, name: z.name, upstream: up, format, keyHash, origBaseURL: up };
|
|
1254
|
+
hr.providers.push(entry);
|
|
1255
|
+
registered.add(pid);
|
|
1256
|
+
added.push(entry);
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
if (added.length || updated.length) {
|
|
1260
|
+
try { atomicWriteJson(hrFile, hr); } catch { return { changed: 0, added: [], updated: [], error: 'headroom.json 写入失败' }; }
|
|
1261
|
+
}
|
|
1262
|
+
return { changed: added.length, added, updated };
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
// 在链里找某供应商记录的真实上游(用于把 baseUrl 还原)。
|
|
1266
|
+
// 已停用/已删除的链也算——宁可还原成它记录的上游,也别把地址留在本机端口上
|
|
1267
|
+
// 还原用的真实上游。记录是供应商接入链时的地址原样,可能带端点尾巴
|
|
1268
|
+
//(…/v1/chat/completions):经转发器时路径由转发器拼接,带着尾巴也能通;直接写回
|
|
1269
|
+
// ZCode 就不通了——ZCode 自己会在地址后拼 /chat/completions,变成两层,上游回 404。
|
|
1270
|
+
// 所以这里剥掉尾巴再给出去(normalizeUpstreamUrl 只剥端点路径,不动 /v1 这类前缀)
|
|
1271
|
+
function chainUpstreamForProvider(chains, providerId) {
|
|
1272
|
+
for (const c of chains) {
|
|
1273
|
+
if (!c || !c.upstreams || typeof c.upstreams !== 'object') continue;
|
|
1274
|
+
const u = c.upstreams[providerId];
|
|
1275
|
+
if (typeof u !== 'string' || !/^https?:\/\/\S+$/i.test(u.trim())) continue;
|
|
1276
|
+
if (isLocalBaseUrl(u)) continue; // 本机地址(比如 8787)不是真实上游,还原时不能用
|
|
1277
|
+
const normalized = normalizeUpstreamUrl(u);
|
|
1278
|
+
if (normalized) return normalized;
|
|
1279
|
+
}
|
|
1280
|
+
return '';
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
// 把"现在还是真实上游"的供应商地址记进链的 upstreams。
|
|
1284
|
+
// 时机很关键:这一步必须在改 baseUrl 之前做,否则改完就查不到真实上游了。
|
|
1285
|
+
// 已经是本机端口(8787 路由或别链转发器)的地址不记——那不是真实上游。
|
|
1286
|
+
// 供应商当前就是真实地址时以它为准(覆盖旧记录):那是用户最新设置的地址。
|
|
1287
|
+
// 返回 { map, changed }:map 是更新后的 upstreams,changed 表示改动了几项
|
|
1288
|
+
function captureChainUpstreams({ dataRoot, chain }) {
|
|
1289
|
+
const cur = (chain && chain.upstreams && typeof chain.upstreams === 'object') ? { ...chain.upstreams } : {};
|
|
1290
|
+
if (!chain || !Array.isArray(chain.providers) || !chain.providers.length) return { map: cur, changed: 0 };
|
|
1291
|
+
const pcFile = join(dataRoot, 'v2', 'provider_config.json');
|
|
1292
|
+
const pc = readJsonFile(pcFile);
|
|
1293
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
1294
|
+
if (!Array.isArray(rules)) return { map: cur, changed: 0 };
|
|
1295
|
+
const byId = new Map();
|
|
1296
|
+
for (const r of rules) if (r && typeof r.providerId === 'string') byId.set(r.providerId, r);
|
|
1297
|
+
// 备份文件里可能还留着改写前的真实地址:当前地址已经是本机端口时用它兜底,
|
|
1298
|
+
// 否则「先改地址后捕获」的场景永远抓不到上游
|
|
1299
|
+
const bakRules = (() => {
|
|
1300
|
+
const bak = readJsonFile(pcFile + '.zcodepro-backup');
|
|
1301
|
+
const list = bak?.config?.providerConfigRules?.providerRules;
|
|
1302
|
+
if (!Array.isArray(list)) return new Map();
|
|
1303
|
+
const m = new Map();
|
|
1304
|
+
for (const r of list) if (r && typeof r.providerId === 'string') m.set(r.providerId, r);
|
|
1305
|
+
return m;
|
|
1306
|
+
})();
|
|
1307
|
+
const realUrl = (v) => {
|
|
1308
|
+
if (typeof v !== 'string') return '';
|
|
1309
|
+
const t = v.trim();
|
|
1310
|
+
if (!/^https?:\/\//i.test(t)) return '';
|
|
1311
|
+
if (/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/i.test(t)) return ''; // 本机端口不是真实上游
|
|
1312
|
+
return t;
|
|
1313
|
+
};
|
|
1314
|
+
let changed = 0;
|
|
1315
|
+
for (const pid of chain.providers) {
|
|
1316
|
+
const t = realUrl(byId.get(pid)?.config?.api?.baseUrl);
|
|
1317
|
+
if (t) {
|
|
1318
|
+
// 供应商当前就是真实地址:以它为准,旧记录跟着改。用户在 ZCode 里改过供应商地址、
|
|
1319
|
+
// 或者别的设备同步来了新地址,链都要用新的那个——不然再勾上还是发往旧端点
|
|
1320
|
+
if (cur[pid] !== t) { cur[pid] = t; changed += 1; }
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1323
|
+
// 当前是本机地址(已被接管):已有记录保留,缺的才从备份里补
|
|
1324
|
+
if (cur[pid]) continue;
|
|
1325
|
+
const b = realUrl(bakRules.get(pid)?.config?.api?.baseUrl);
|
|
1326
|
+
if (!b) continue;
|
|
1327
|
+
cur[pid] = b;
|
|
1328
|
+
changed += 1;
|
|
1329
|
+
}
|
|
1330
|
+
return { map: cur, changed };
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
// 提示词注入实际能生效的供应商数量(设置页那行汇总用)。
|
|
1334
|
+
// 计入条件:勾在启用中的链上,且(下面两条任一满足):
|
|
1335
|
+
// 1. 链上有 inject 节点、链的转发器在监听、且链不经过 headroom
|
|
1336
|
+
// 2. 同上,但链经过 headroom:供应商还得在 headroom 路由注册过,
|
|
1337
|
+
// 否则 8787 会直接 502,注入根本没机会发生
|
|
1338
|
+
// 只数 enabledIds 里的(用户在 ZCode 里启用的),排掉已停用/已删除的。
|
|
1339
|
+
// 旧的逐家转发(providerProxies)已并入代理链,不再单独计入
|
|
1340
|
+
export function countInjectableProviders({ config, enabledIds, livePorts, headroomProviderIds, protectedIds }) {
|
|
1341
|
+
const enabled = enabledIds instanceof Set ? enabledIds : new Set();
|
|
1342
|
+
const live = livePorts instanceof Set ? livePorts : new Set();
|
|
1343
|
+
const hrIds = headroomProviderIds instanceof Set ? headroomProviderIds : new Set();
|
|
1344
|
+
const prot = protectedIds instanceof Set ? protectedIds : new Set();
|
|
1345
|
+
const ok = new Set();
|
|
1346
|
+
// 代理链总开关关闭:链上的注入全部不发生,只统计供应商代理那部分
|
|
1347
|
+
//(供应商代理是独立功能,有自己的开关,不受链总开关影响)
|
|
1348
|
+
const chainOn = (config && config.proxyChainEnabled) === true;
|
|
1349
|
+
for (const ch of (Array.isArray(config && config.proxyChains) ? config.proxyChains : [])) {
|
|
1350
|
+
if (!chainOn) break;
|
|
1351
|
+
if (!ch || ch.enabled === false) continue;
|
|
1352
|
+
if (!Array.isArray(ch.nodes) || !ch.nodes.some((n) => n.type === 'inject')) continue;
|
|
1353
|
+
if (!live.has(Number(ch.port))) continue; // 转发器没在跑,注入不会发生
|
|
1354
|
+
const viaHeadroom = ch.nodes.some((n) => n.type === 'headroom');
|
|
1355
|
+
for (const pid of ch.providers || []) {
|
|
1356
|
+
// 受保护的供应商拿不到 chainTarget,请求不经过链转发器,注入不会发生——
|
|
1357
|
+
// 即使它在界面上被勾进了链里(跳过它们的逻辑在 applyChainTargets)
|
|
1358
|
+
if (prot.has(pid)) continue;
|
|
1359
|
+
if (viaHeadroom && !hrIds.has(pid)) continue;
|
|
1360
|
+
ok.add(pid);
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
let n = 0;
|
|
1364
|
+
for (const id of enabled) if (ok.has(id)) n += 1;
|
|
1365
|
+
return n;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
// 迁移出来的链叫什么:按节点组成起名,和界面上手动新建的链一个说法
|
|
1369
|
+
function migrationChainName(viaHeadroom, customCount) {
|
|
1370
|
+
if (!customCount) return viaHeadroom ? '压缩' : '提示词注入';
|
|
1371
|
+
return [viaHeadroom ? '压缩' : '', '自定义代理'].filter(Boolean).join(' + ');
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// —— 逐家转发并入代理链 ——
|
|
1375
|
+
// “供应商是否经过 zcode-po”只由“代理 → 代理链”里的勾选决定。旧版本另有一套按供应商
|
|
1376
|
+
// 维度的转发(providerProxies:提示词注入一保存就替所有供应商打开),它不经过勾选、
|
|
1377
|
+
// 界面上也关不掉,还会把取消勾选后刚还原的地址再改回本机端口。这里把仍在开着的
|
|
1378
|
+
// 旧条目转成链里的勾选,之后 providerProxies 不再有任何作用。
|
|
1379
|
+
//
|
|
1380
|
+
// 怎么转(节点相同的供应商并成一条链):
|
|
1381
|
+
// 旧条目的上游是 headroom 路由(8787)→ 链首放 headroom:压缩 → 注入 → 出网代理
|
|
1382
|
+
// 上游是真实地址 → 链里只有注入与自定义代理,真实地址记进链的 upstreams
|
|
1383
|
+
// 和旧行为相比只有一处不同:压缩从“注入之后”变成“注入之前”(链首 headroom 是
|
|
1384
|
+
// 既定顺序)。界面上的效果是这些供应商出现在一条可见的链里、处于勾选状态。
|
|
1385
|
+
//
|
|
1386
|
+
// 已在某条链里的供应商不重复勾选,只去掉旧条目。转进链的供应商只要有,就把总开关
|
|
1387
|
+
// 打开——它们本来就在转发,不该因为升级变成直连。每次对齐都会调用(同步拉取可能
|
|
1388
|
+
// 又带回旧条目),没有开着的旧条目时什么也不做。只算计划,不动磁盘;导出以便测试
|
|
1389
|
+
export function planProviderProxiesMigration({ dataRoot, config }) {
|
|
1390
|
+
const table = (config && config.providerProxies && typeof config.providerProxies === 'object')
|
|
1391
|
+
? config.providerProxies : {};
|
|
1392
|
+
const chains = (config && Array.isArray(config.proxyChains)) ? config.proxyChains : [];
|
|
1393
|
+
const pc = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'));
|
|
1394
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
1395
|
+
const ruleById = new Map();
|
|
1396
|
+
if (Array.isArray(rules)) {
|
|
1397
|
+
for (const r of rules) if (r && typeof r.providerId === 'string') ruleById.set(r.providerId, r);
|
|
1398
|
+
}
|
|
1399
|
+
const regById = new Map();
|
|
1400
|
+
for (const p of (readJsonFile(join(dataRoot, 'headroom.json'))?.providers || [])) {
|
|
1401
|
+
if (p && typeof p.id === 'string') regById.set(p.id, p);
|
|
1402
|
+
}
|
|
1403
|
+
// 真实地址:http(s) 且不是本机回环;顺手剥掉端点尾巴
|
|
1404
|
+
const realOf = (v) => {
|
|
1405
|
+
if (typeof v !== 'string') return '';
|
|
1406
|
+
const t = v.trim();
|
|
1407
|
+
if (!/^https?:\/\/\S+$/i.test(t) || isLocalBaseUrl(t)) return '';
|
|
1408
|
+
return normalizeUpstreamUrl(t);
|
|
1409
|
+
};
|
|
1410
|
+
const groups = new Map(); // 节点序列(JSON)→ { nodes, name, providers, upstreams, legacyPorts }
|
|
1411
|
+
const attach = []; // { chainId, ports }:已在别的链里的供应商,旧端口挂到那条链上
|
|
1412
|
+
const migratedIds = []; // 处理完、要从 providerProxies 里删掉的条目
|
|
1413
|
+
const legacyPorts = []; // 旧转发器端口(对齐时先按旧转发器停掉,再作为兼容端口重新起)
|
|
1414
|
+
const restored = []; // { id, url }:地址还指着旧转发端口的,迁移时就要改走
|
|
1415
|
+
const skipped = []; // 没法转的(找不到真实上游,也不经过 headroom)
|
|
1416
|
+
for (const [id, entry] of Object.entries(table)) {
|
|
1417
|
+
if (!entry || typeof entry !== 'object' || entry.enabled !== true) continue; // 关着的不动
|
|
1418
|
+
if (id === '__proto__' || id === 'constructor' || id === 'prototype') continue;
|
|
1419
|
+
if (PROVIDER_PROXY_PROTECTED_IDS.has(id)) continue;
|
|
1420
|
+
if (Number.isFinite(Number(entry.port))) legacyPorts.push(Number(entry.port));
|
|
1421
|
+
const cur = providerProxyRuleBaseUrl(pc, id);
|
|
1422
|
+
const reg = regById.get(id);
|
|
1423
|
+
// 供应商已被删除:条目直接丢
|
|
1424
|
+
if (Array.isArray(rules) && !ruleById.has(id)) { migratedIds.push(id); continue; }
|
|
1425
|
+
const custom = mergeProxyNodes(entry.nodes, entry.proxy).filter((n) => n && n.type === 'custom');
|
|
1426
|
+
const upstream = (typeof entry.upstream === 'string' && entry.upstream.trim()) ? entry.upstream.trim() : '';
|
|
1427
|
+
const viaHeadroom = isHeadroomUrl(upstream, dataRoot);
|
|
1428
|
+
// 真实上游:条目记的优先;记的是本机地址或没记时,从供应商当前地址、备份、
|
|
1429
|
+
// headroom 登记里找(先被接管过的话当前地址已是本机端口,要往后找)
|
|
1430
|
+
const real = realOf(upstream) || realOf(cur)
|
|
1431
|
+
|| realOf(providerProxyBackupBaseUrl(dataRoot, id))
|
|
1432
|
+
|| realOf(reg?.upstream) || realOf(reg?.origBaseURL);
|
|
1433
|
+
if (!viaHeadroom && !real) {
|
|
1434
|
+
skipped.push({ id, reason: '没有可用的真实上游' });
|
|
1435
|
+
continue;
|
|
1436
|
+
}
|
|
1437
|
+
const portNum = Math.round(Number(entry.port));
|
|
1438
|
+
const owner = chains.find((c) => c && Array.isArray(c.providers) && c.providers.includes(id));
|
|
1439
|
+
if (!owner) {
|
|
1440
|
+
const nodes = [...(viaHeadroom ? [{ type: 'headroom' }] : []), ...custom, { type: 'inject' }];
|
|
1441
|
+
const key = JSON.stringify(nodes);
|
|
1442
|
+
if (!groups.has(key)) {
|
|
1443
|
+
groups.set(key, {
|
|
1444
|
+
nodes, providers: [], upstreams: {}, legacyPorts: [],
|
|
1445
|
+
name: migrationChainName(viaHeadroom, custom.length),
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
const g = groups.get(key);
|
|
1449
|
+
if (!g.providers.includes(id)) g.providers.push(id);
|
|
1450
|
+
// 记下真实上游:取消勾选、关总开关时靠它还原地址
|
|
1451
|
+
if (real) g.upstreams[id] = real;
|
|
1452
|
+
// 旧的转发端口留给这条链当兼容端口
|
|
1453
|
+
if (Number.isFinite(portNum) && portNum >= 1024 && portNum <= 65535 && !g.legacyPorts.includes(portNum)) g.legacyPorts.push(portNum);
|
|
1454
|
+
} else if (Number.isFinite(portNum) && portNum >= 1024 && portNum <= 65535 && owner.id) {
|
|
1455
|
+
const hit = attach.find((x) => x.chainId === owner.id);
|
|
1456
|
+
if (hit) { if (!hit.ports.includes(portNum)) hit.ports.push(portNum); } else attach.push({ chainId: owner.id, ports: [portNum] });
|
|
1457
|
+
}
|
|
1458
|
+
migratedIds.push(id);
|
|
1459
|
+
// 地址还指着旧转发端口:先改走。链对齐随后会把链上供应商改到链入口;链被跳过时
|
|
1460
|
+
//(比如插件不支持)供应商停在真实地址或 headroom,不会停在已经不听的端口上
|
|
1461
|
+
if (cur && providerProxyOwnUrl(cur, entry.port)) {
|
|
1462
|
+
restored.push({ id, url: real || `http://127.0.0.1:${headroomRouterPort(dataRoot)}` });
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
return { groups: [...groups.values()], attach, migratedIds, legacyPorts, restored, skipped };
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// 迁移出来的链自己的转发端口:转发段里还没被占的端口(兼容端口、已有链的端口、
|
|
1469
|
+
// 前面几条新链已分的都算占了——主转发器不能和兼容端口撞车)。
|
|
1470
|
+
// 段里全占满就不设,交给对齐去找空闲端口。返回 fn(),每调一次给下一个
|
|
1471
|
+
function migrationChainPortPicker(legacyPorts, chains) {
|
|
1472
|
+
const taken = new Set(legacyPorts);
|
|
1473
|
+
for (const c of chains) if (c && Number.isFinite(Number(c.port))) taken.add(Math.round(Number(c.port)));
|
|
1474
|
+
return () => {
|
|
1475
|
+
for (let p = PROVIDER_PROXY_PORT_MIN; p <= PROVIDER_PROXY_PORT_MAX; p += 1) {
|
|
1476
|
+
if (taken.has(p)) continue;
|
|
1477
|
+
taken.add(p);
|
|
1478
|
+
return p;
|
|
1479
|
+
}
|
|
1480
|
+
return null;
|
|
1481
|
+
};
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
// 执行迁移:锁内重读配置、按计划建链并删掉旧条目,一次写盘;落盘之后才改供应商地址
|
|
1485
|
+
//(中途崩溃最坏是地址停在旧端口,下一次对齐或还原会处理)。没有可转的返回 null
|
|
1486
|
+
async function migrateProviderProxiesToChains({ dataRoot, configFile }) {
|
|
1487
|
+
if (!dataRoot || !configFile) return null;
|
|
1488
|
+
let plan = null;
|
|
1489
|
+
try {
|
|
1490
|
+
await withConfigLock(configFile, () => {
|
|
1491
|
+
const fresh = loadConfig(configFile);
|
|
1492
|
+
if (configUnreadable) return;
|
|
1493
|
+
const p = planProviderProxiesMigration({ dataRoot, config: fresh });
|
|
1494
|
+
if (!p.migratedIds.length) return;
|
|
1495
|
+
const list = Array.isArray(fresh.proxyChains) ? fresh.proxyChains.map((c) => ({ ...c })) : [];
|
|
1496
|
+
const stamp = Date.now().toString(36);
|
|
1497
|
+
const nextPort = migrationChainPortPicker(p.legacyPorts, list);
|
|
1498
|
+
p.groups.forEach((g, i) => {
|
|
1499
|
+
const port = nextPort();
|
|
1500
|
+
list.push({
|
|
1501
|
+
id: `chain${stamp}${i}`, name: g.name, providers: g.providers,
|
|
1502
|
+
nodes: g.nodes, upstreams: g.upstreams, enabled: true,
|
|
1503
|
+
...(port ? { port } : {}),
|
|
1504
|
+
...(g.legacyPorts.length ? { legacyPorts: g.legacyPorts } : {}),
|
|
1505
|
+
});
|
|
1506
|
+
});
|
|
1507
|
+
// 已在别的链里的供应商:旧端口挂到那条链上
|
|
1508
|
+
for (const a of p.attach) {
|
|
1509
|
+
const c = list.find((x) => x && x.id === a.chainId);
|
|
1510
|
+
if (!c) continue;
|
|
1511
|
+
c.legacyPorts = [...new Set([...(Array.isArray(c.legacyPorts) ? c.legacyPorts : []), ...a.ports])];
|
|
1512
|
+
}
|
|
1513
|
+
fresh.proxyChains = list;
|
|
1514
|
+
const table = { ...(fresh.providerProxies || {}) };
|
|
1515
|
+
for (const id of p.migratedIds) delete table[id];
|
|
1516
|
+
fresh.providerProxies = table;
|
|
1517
|
+
if (p.groups.some((g) => g.providers.length)) fresh.proxyChainEnabled = true;
|
|
1518
|
+
if (!saveConfig(configFile, fresh)) return;
|
|
1519
|
+
plan = p;
|
|
1520
|
+
});
|
|
1521
|
+
for (const r of (plan ? plan.restored : [])) {
|
|
1522
|
+
try { providerProxyRewriteBaseUrl(dataRoot, r.id, r.url); } catch { /* 尽力而为 */ }
|
|
1523
|
+
}
|
|
1524
|
+
} catch { /* 拿不到锁或写失败:下一轮对齐再试 */ }
|
|
1525
|
+
return plan;
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
// headroom 登记里记的真实地址:先看 upstream,再看 origBaseURL(接入时的原地址)。
|
|
1529
|
+
// 本机地址不算。导出以便测试
|
|
1530
|
+
export function registryRealUpstream(dataRoot, providerId) {
|
|
1531
|
+
const list = readJsonFile(join(dataRoot, 'headroom.json'))?.providers;
|
|
1532
|
+
const reg = (Array.isArray(list) ? list : []).find((p) => p && p.id === providerId);
|
|
1533
|
+
for (const v of [reg?.upstream, reg?.origBaseURL]) {
|
|
1534
|
+
if (typeof v !== 'string') continue;
|
|
1535
|
+
const t = v.trim();
|
|
1536
|
+
if (!/^https?:\/\/\S+$/i.test(t) || isLocalBaseUrl(t)) continue;
|
|
1537
|
+
return normalizeUpstreamUrl(t);
|
|
1538
|
+
}
|
|
1539
|
+
return '';
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
// 把链上供应商的本机地址(链端口、8787)还原成真实上游。来源顺序:链里记的真实地址
|
|
1543
|
+
// → headroom 登记的 upstream → 登记的 origBaseURL。
|
|
1544
|
+
// 只动勾在链上的供应商;只是接入了 headroom、从没进过链的供应商不碰。
|
|
1545
|
+
// forwardPorts=true 时(命令行还原用),不在链上但地址还指着 zcode-pro 转发端口
|
|
1546
|
+
//(1873x 段)的供应商也一并还原——那些端口只在 zcode-pro 运行时才有人听。
|
|
1547
|
+
// 返回 { restored, stuck },stuck 是地址在本机端口但找不到真实上游的供应商
|
|
1548
|
+
export function restoreChainMembersToReal({ dataRoot, chains, forwardPorts = false }) {
|
|
1549
|
+
const pcFile = join(dataRoot, 'v2', 'provider_config.json');
|
|
1550
|
+
const pc = readJsonFile(pcFile);
|
|
1551
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
1552
|
+
if (!Array.isArray(rules)) return { restored: 0, stuck: [] };
|
|
1553
|
+
const list = Array.isArray(chains) ? chains : [];
|
|
1554
|
+
const members = new Set();
|
|
1555
|
+
for (const c of list) {
|
|
1556
|
+
for (const pid of (c && Array.isArray(c.providers)) ? c.providers : []) members.add(pid);
|
|
1557
|
+
}
|
|
1558
|
+
const regById = new Map();
|
|
1559
|
+
for (const p of (readJsonFile(join(dataRoot, 'headroom.json'))?.providers || [])) {
|
|
1560
|
+
if (p && typeof p.id === 'string') regById.set(p.id, p);
|
|
1561
|
+
}
|
|
1562
|
+
const realOf = (v) => {
|
|
1563
|
+
if (typeof v !== 'string') return '';
|
|
1564
|
+
const t = v.trim();
|
|
1565
|
+
if (!/^https?:\/\/\S+$/i.test(t) || isLocalBaseUrl(t)) return '';
|
|
1566
|
+
return normalizeUpstreamUrl(t);
|
|
1567
|
+
};
|
|
1568
|
+
let restored = 0;
|
|
1569
|
+
const stuck = [];
|
|
1570
|
+
for (const r of rules) {
|
|
1571
|
+
if (!r || typeof r.providerId !== 'string') continue;
|
|
1572
|
+
const cur = String(r.config?.api?.baseUrl || '').trim();
|
|
1573
|
+
const inChain = members.has(r.providerId);
|
|
1574
|
+
// 不在链上的:只有明确要求、且地址指着 zcode-pro 转发端口时才动
|
|
1575
|
+
if (!inChain && !(forwardPorts && providerProxyOwnUrl(cur))) continue;
|
|
1576
|
+
if (PROVIDER_PROXY_PROTECTED_IDS.has(r.providerId)) continue;
|
|
1577
|
+
if (!r.config || typeof r.config !== 'object') r.config = {};
|
|
1578
|
+
if (!r.config.api || typeof r.config.api !== 'object') r.config.api = {};
|
|
1579
|
+
if (!isLocalBaseUrl(cur)) continue; // 已经是真实地址的不动
|
|
1580
|
+
const reg = regById.get(r.providerId);
|
|
1581
|
+
const real = chainUpstreamForProvider(list, r.providerId)
|
|
1582
|
+
|| realOf(reg?.upstream) || realOf(reg?.origBaseURL);
|
|
1583
|
+
if (!real) { stuck.push(r.providerId); continue; }
|
|
1584
|
+
r.config.api.baseUrl = real;
|
|
1585
|
+
restored += 1;
|
|
1586
|
+
}
|
|
1587
|
+
if (!restored) return { restored: 0, stuck };
|
|
1588
|
+
try {
|
|
1589
|
+
backupV2File(pcFile);
|
|
1590
|
+
atomicWriteJson(pcFile, pc);
|
|
1591
|
+
} catch {
|
|
1592
|
+
return { restored: 0, stuck: [...new Set([...stuck, ...members])] };
|
|
1593
|
+
}
|
|
1594
|
+
return { restored, stuck };
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// 地址变了 = 退出链(手动改的、别的设备同步来的,一视同仁)。
|
|
1598
|
+
// 勾选期间供应商的地址由链管理:对齐时写成链入口,并在 state.chainAddressWritten 里
|
|
1599
|
+
// 记下“这是链写的”。之后地址变成了别的值,就是有人改了它——用户在 ZCode 的模型
|
|
1600
|
+
// 设置里改的,或者 WebDAV 同步从另一台设备带来的。这时不把地址改回去,而是把这家
|
|
1601
|
+
// 供应商从链里移出、保持改后的地址;右下角弹卡片告知(见写提示文件的那一段)。
|
|
1602
|
+
// 改后的地址如果指着 zcode-pro 自己的转发端口(比如另一台机器的链端口),在这里
|
|
1603
|
+
// 没人听,随后对齐地址那一步会把它还原成真实上游。
|
|
1604
|
+
// 记录只存在内存里、只在同一个进程内有效:进程重启、退出清理、关总开关之后地址本来
|
|
1605
|
+
// 就不是链入口,那是 zcode-pro 自己还原的,重新接管即可,不能当成别人改的。
|
|
1606
|
+
// 返回退出链的明细;没有则返回空数组
|
|
1607
|
+
async function uncheckManuallyChanged({ dataRoot, configFile, chains, activeChains, ports, state, result }) {
|
|
1608
|
+
const optedOut = [];
|
|
1609
|
+
try {
|
|
1610
|
+
const written = (state && typeof state === 'object' && state.chainAddressWritten) ? state.chainAddressWritten : null;
|
|
1611
|
+
if (!written) return optedOut;
|
|
1612
|
+
const pc = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'));
|
|
1613
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
1614
|
+
if (!Array.isArray(rules)) return optedOut;
|
|
1615
|
+
const curById = new Map();
|
|
1616
|
+
const nameById = new Map();
|
|
1617
|
+
for (const r of rules) {
|
|
1618
|
+
if (!r || typeof r.providerId !== 'string') continue;
|
|
1619
|
+
curById.set(r.providerId, String(r.config?.api?.baseUrl || '').trim());
|
|
1620
|
+
nameById.set(r.providerId, String(r.providerName || r.providerId));
|
|
1621
|
+
}
|
|
1622
|
+
// 比较时去掉末尾斜杠:同一个地址有没有斜杠不算变化
|
|
1623
|
+
const norm = (u) => String(u || '').trim().replace(/\/+$/, '');
|
|
1624
|
+
const opted = [];
|
|
1625
|
+
for (const c of activeChains) {
|
|
1626
|
+
if (!c || !Array.isArray(c.providers)) continue;
|
|
1627
|
+
for (const pid of c.providers) {
|
|
1628
|
+
if (PROVIDER_PROXY_PROTECTED_IDS.has(pid) || !written[pid]) continue;
|
|
1629
|
+
const cur = curById.get(pid);
|
|
1630
|
+
if (cur === undefined || !cur) continue; // 供应商已删另有清理
|
|
1631
|
+
const entry = chainEntryType(c) === 'headroom'
|
|
1632
|
+
? `http://127.0.0.1:${headroomRouterPort(dataRoot)}`
|
|
1633
|
+
: (() => {
|
|
1634
|
+
const p = ports.get(c.id) || c.port;
|
|
1635
|
+
return Number.isFinite(Number(p)) && Number(p) >= 1024 ? `http://127.0.0.1:${Math.round(Number(p))}` : '';
|
|
1636
|
+
})();
|
|
1637
|
+
if (!entry) continue;
|
|
1638
|
+
if (norm(cur) === norm(entry) || norm(cur) === norm(written[pid])) continue; // 没变,或只是链入口自己变了(会重新接管)
|
|
1639
|
+
opted.push({ id: pid, chainId: c.id, chain: String(c.name || c.id), name: nameById.get(pid) || pid, url: cur });
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
if (!opted.length) return optedOut;
|
|
1643
|
+
const gone = new Set(opted.map((o) => o.id));
|
|
1644
|
+
await withConfigLock(configFile, () => {
|
|
1645
|
+
const fresh = loadConfig(configFile);
|
|
1646
|
+
if (configUnreadable) return;
|
|
1647
|
+
const list = Array.isArray(fresh.proxyChains) ? fresh.proxyChains : [];
|
|
1648
|
+
for (const c of list) {
|
|
1649
|
+
if (!c) continue;
|
|
1650
|
+
if (Array.isArray(c.providers)) c.providers = c.providers.filter((pid) => !gone.has(pid));
|
|
1651
|
+
// 改成真实网址的,把它记进这条链:下次再勾上时转发就用新地址
|
|
1652
|
+
for (const o of opted) {
|
|
1653
|
+
if (o.chainId !== c.id || isLocalBaseUrl(o.url)) continue;
|
|
1654
|
+
c.upstreams = { ...(c.upstreams && typeof c.upstreams === 'object' ? c.upstreams : {}), [o.id]: normalizeUpstreamUrl(o.url) };
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
saveConfig(configFile, fresh);
|
|
1658
|
+
});
|
|
1659
|
+
// 内存里的链对象同步改掉:后面写 chainTarget、对齐地址时按“不在链上”处理
|
|
1660
|
+
for (const c of chains) {
|
|
1661
|
+
if (!c) continue;
|
|
1662
|
+
if (Array.isArray(c.providers)) c.providers = c.providers.filter((pid) => !gone.has(pid));
|
|
1663
|
+
for (const o of opted) {
|
|
1664
|
+
if (o.chainId !== c.id || isLocalBaseUrl(o.url)) continue;
|
|
1665
|
+
c.upstreams = { ...(c.upstreams && typeof c.upstreams === 'object' ? c.upstreams : {}), [o.id]: normalizeUpstreamUrl(o.url) };
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
for (const o of opted) delete written[o.id];
|
|
1669
|
+
result.autoUnchecked = opted.map((o) => ({ id: o.id, name: o.name, chain: o.chain, url: o.url }));
|
|
1670
|
+
console.log(`[zcodepro] ${opted.map((o) => o.name).join('、')}:地址变了,已自动退出代理链`);
|
|
1671
|
+
optedOut.push(...opted);
|
|
1672
|
+
} catch { /* 读不了配置就这一轮不处理 */ }
|
|
1673
|
+
return optedOut;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
// 串行队列:保存配置、启动 4 秒、同步拉取、restore 端点都会触发对齐且多为
|
|
1677
|
+
// fire-and-forget,两轮并发会互相复活接管(旧轮尾部把 chainTarget/baseUrl 写回,
|
|
1678
|
+
// 总开关已关也拦不住)或把地址写向对方刚停的端口。排队执行:后一轮看到的是
|
|
1679
|
+
// 前一轮完成后的状态,快照式停止逻辑也只在串行下才成立
|
|
1680
|
+
let proxyChainEnsureTail = Promise.resolve();
|
|
1681
|
+
export function ensureProxyChains(options = {}) {
|
|
1682
|
+
const run = proxyChainEnsureTail.then(async () => {
|
|
1683
|
+
const st = options && options.state;
|
|
1684
|
+
try {
|
|
1685
|
+
return await runProxyChainAlignment(options);
|
|
1686
|
+
} finally {
|
|
1687
|
+
// 对齐结束(正常或抛错)都复位,巡检恢复工作
|
|
1688
|
+
try { if (st && typeof st === 'object') st.proxyChainAligning = false; } catch { /* state 不可写不影响 */ }
|
|
1689
|
+
}
|
|
1690
|
+
});
|
|
1691
|
+
proxyChainEnsureTail = run.then(() => undefined, () => undefined);
|
|
1692
|
+
return run;
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
async function runProxyChainAlignment({ dataRoot, configFile, state = {}, reason = '' } = {}) {
|
|
797
1696
|
const startedAt = Date.now();
|
|
798
1697
|
const errors = [];
|
|
799
|
-
const result = { at: startedAt, reason, started: [],
|
|
1698
|
+
const result = { at: startedAt, reason, started: [], stopped: [], errors };
|
|
1699
|
+
// 对齐进行中:转发器巡检看到这个标志就跳过(对齐中途转发器会短暂不在监听)
|
|
1700
|
+
try { state.proxyChainAligning = true; } catch { /* state 不可写不影响 */ }
|
|
800
1701
|
try {
|
|
801
|
-
if (!dataRoot || !configFile) {
|
|
802
|
-
|
|
803
|
-
|
|
1702
|
+
if (!dataRoot || !configFile) { errors.push('缺少数据目录'); return result; }
|
|
1703
|
+
// 第一步:旧的逐家转发并入代理链(见 migrateProviderProxiesToChains)。
|
|
1704
|
+
// 必须排在最前面:它要用旧条目里的节点和上游来建链,别的步骤不能先把条目弄丢
|
|
1705
|
+
const migration = await migrateProviderProxiesToChains({ dataRoot, configFile });
|
|
1706
|
+
if (migration) {
|
|
1707
|
+
result.migrated = migration.migratedIds.length;
|
|
1708
|
+
if (migration.groups.length) {
|
|
1709
|
+
const names = migration.groups.map((g) => `《${g.name}》${g.providers.length} 家`).join('、');
|
|
1710
|
+
console.log(`[zcodepro] 逐家转发已并入代理链:${names}`);
|
|
1711
|
+
}
|
|
1712
|
+
for (const sk of migration.skipped) errors.push(`供应商 ${sk.id}:旧的转发配置无法并入代理链(${sk.reason}),已按不再转发处理`);
|
|
804
1713
|
}
|
|
805
1714
|
const config = loadConfig(configFile);
|
|
806
|
-
const
|
|
807
|
-
const ids = Object.keys(proxies).filter((id) => id !== '__proto__' && id !== 'constructor' && id !== 'prototype');
|
|
1715
|
+
const chains = Array.isArray(config.proxyChains) ? config.proxyChains : [];
|
|
808
1716
|
const manager = getProviderProxyManager(state);
|
|
809
|
-
//
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
1717
|
+
const goCompat = config.opencodeGoCompat !== false; // OpenCode Go 兼容,下发给链转发器
|
|
1718
|
+
// 与 ensureProviderProxies 同理:只清理上一轮由本函数占用的端口,
|
|
1719
|
+
// 供应商代理的转发器不在其中,互不误停
|
|
1720
|
+
const ownedPorts = new Set(
|
|
1721
|
+
state && Array.isArray(state.proxyChainOwnedPorts) ? state.proxyChainOwnedPorts : [],
|
|
1722
|
+
);
|
|
1723
|
+
// 旧的逐家转发不再保留:它的转发器一律停掉(迁移记下的端口 + 上一轮旧对齐
|
|
1724
|
+
// 占用的端口)。代理链自己的端口在 ownedPorts 里,不在此列
|
|
1725
|
+
const legacyPorts = new Set([
|
|
1726
|
+
...((state && Array.isArray(state.providerProxyOwnedPorts)) ? state.providerProxyOwnedPorts : []),
|
|
1727
|
+
...((migration && Array.isArray(migration.legacyPorts)) ? migration.legacyPorts : []),
|
|
1728
|
+
]);
|
|
1729
|
+
for (const port of legacyPorts) {
|
|
1730
|
+
if (ownedPorts.has(port)) continue;
|
|
1731
|
+
try { if (await manager.stopPort(port)) result.stopped.push(port); } catch { /* 下次再停 */ }
|
|
1732
|
+
}
|
|
1733
|
+
if (state && typeof state === 'object') state.providerProxyOwnedPorts = [];
|
|
1734
|
+
// —— 总开关关闭:撤销全部接管后直接返回(也就是“一键还原”) ——
|
|
1735
|
+
// 停全部链转发器(入口+回程)、清 headroom 登记的 chainTarget、把链上供应商
|
|
1736
|
+
// 的本机地址(链端口和 8787)都还原成真实上游。链配置原样保留,
|
|
1737
|
+
// 重新打开总开关即恢复接管
|
|
1738
|
+
if (config.proxyChainEnabled !== true) {
|
|
1739
|
+
const stopped = [];
|
|
1740
|
+
for (const fw of manager.status()) {
|
|
1741
|
+
if (ownedPorts.has(fw.port)) {
|
|
1742
|
+
try { if (await manager.stopPort(fw.port)) stopped.push(fw.port); } catch { /* 下次再停 */ }
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
if (state && typeof state === 'object') {
|
|
1746
|
+
state.proxyChainOwnedPorts = [];
|
|
1747
|
+
state.proxyChainReturnPorts = {};
|
|
1748
|
+
// 地址都已还原,不再是链写的:记录作废,重新打开时按首次接管处理
|
|
1749
|
+
state.chainAddressWritten = {};
|
|
1750
|
+
}
|
|
1751
|
+
// headroom 登记清 chainTarget + 链端口地址还原:与 shutdown 同一套
|
|
1752
|
+
let shutdown = null;
|
|
1753
|
+
try { shutdown = shutdownProxyChainRouting({ dataRoot, configFile }); } catch { /* 尽力而为 */ }
|
|
1754
|
+
// 指向 8787 的链上供应商也还原成真实上游:总开关关掉就是全部直连,
|
|
1755
|
+
// 不再经过压缩。找不到真实地址的报出来,不能让地址停在本机端口上还不吭声
|
|
1756
|
+
let members = { restored: 0, stuck: [] };
|
|
1757
|
+
try { members = restoreChainMembersToReal({ dataRoot, chains: config.proxyChains }); } catch { /* 尽力而为 */ }
|
|
1758
|
+
for (const id of members.stuck) {
|
|
1759
|
+
errors.push(`供应商 ${id}:地址指向本机端口但找不到真实上游,没能还原(请手动改回真实地址,或重新打开总开关)`);
|
|
1760
|
+
}
|
|
1761
|
+
result.restored = (shutdown && shutdown.baseUrls || 0) + members.restored;
|
|
1762
|
+
// 清掉的 chainTarget 会改实例分组键(chain:目标 → 直连键),必须触发
|
|
1763
|
+
// headroom 重新分组,否则路由按旧键查不到实例,经 8787 的请求全部 502
|
|
1764
|
+
if (shutdown && shutdown.chainTargets > 0 && !state.noHeadroomHook) {
|
|
1765
|
+
runHeadroomHook(['ensure'], 60000).then((r) => {
|
|
1766
|
+
if (!r.ok) console.error(`[zcodepro] 代理链总开关关闭:headroom 分组刷新失败(${r.error || r.code})`);
|
|
1767
|
+
}).catch(() => { /* 尽力而为 */ });
|
|
1768
|
+
}
|
|
1769
|
+
result.stopped = stopped;
|
|
1770
|
+
result.masterOff = true;
|
|
1771
|
+
result.ms = Date.now() - startedAt;
|
|
1772
|
+
try { state.proxyChainLastRun = result; } catch { /* state 不可写不影响 */ }
|
|
1773
|
+
return result;
|
|
1774
|
+
}
|
|
1775
|
+
manager.setInjector(promptInjector(state));
|
|
1776
|
+
// 「默认压缩链」:装了 headroom 且 join 过供应商、但用户从没用过代理链时,
|
|
1777
|
+
// 自动建一条 headroom>注入 的链把已登记供应商全勾上。这样压缩状态在链 tab
|
|
1778
|
+
// 里有唯一表达:勾=压缩,取消勾=退出(取消时前端会调 restore 删登记)。
|
|
1779
|
+
// 已有任何链(含停用的)就不建——用户自己在管链,别替他做主
|
|
1780
|
+
if (!chains.length) {
|
|
1781
|
+
const hr = readJsonFile(join(dataRoot, 'headroom.json'));
|
|
1782
|
+
const registered = (Array.isArray(hr?.providers) ? hr.providers : [])
|
|
1783
|
+
.map((p) => p && typeof p.id === 'string' ? p.id : '')
|
|
1784
|
+
.filter(Boolean);
|
|
1785
|
+
if (registered.length && headroomSupportsChainTarget()) {
|
|
1786
|
+
const c = {
|
|
1787
|
+
id: `chain${Date.now().toString(36)}`,
|
|
1788
|
+
name: '压缩',
|
|
1789
|
+
providers: registered,
|
|
1790
|
+
nodes: [{ type: 'headroom' }, { type: 'inject' }],
|
|
1791
|
+
enabled: true,
|
|
1792
|
+
};
|
|
1793
|
+
chains.push(c);
|
|
1794
|
+
try {
|
|
1795
|
+
await withConfigLock(configFile, () => {
|
|
1796
|
+
const fresh = loadConfig(configFile);
|
|
1797
|
+
if (configUnreadable) return;
|
|
1798
|
+
if (!Array.isArray(fresh.proxyChains) || !fresh.proxyChains.length) {
|
|
1799
|
+
fresh.proxyChains = [c];
|
|
1800
|
+
saveConfig(configFile, fresh);
|
|
1801
|
+
}
|
|
1802
|
+
});
|
|
1803
|
+
result.defaultChainCreated = 1;
|
|
1804
|
+
} catch { /* 写回失败当没建过,下轮再试 */ }
|
|
848
1805
|
}
|
|
849
|
-
|
|
850
|
-
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
const ports = new Map(); // chainId → 实际端口
|
|
1809
|
+
const returnPorts = new Map(); // chainId → 回程转发器端口(注入优先拓扑专用)
|
|
1810
|
+
const shimPorts = new Set(); // 兼容端口上起的转发器(迁移来的链带着的旧转发端口)
|
|
1811
|
+
const gatedChains = new Set(); // 插件能力不足被跳过的链(后续登记/写标/对齐都不碰)
|
|
1812
|
+
|
|
1813
|
+
for (const c of chains) {
|
|
1814
|
+
if (!c || c.enabled === false || !Array.isArray(c.nodes) || !c.nodes.length) continue;
|
|
1815
|
+
const hasInject = chainNeedsInject(c, config.promptInjection);
|
|
1816
|
+
// 代理按段拆:headroom 之前的归入口转发器(连 8787 也走——排在压缩前的
|
|
1817
|
+
// 自定义代理是用户明确要求先过的,比如破盾框架),之后的归回程转发器
|
|
1818
|
+
const hrIdx0 = (c.nodes || []).findIndex((n) => n.type === 'headroom');
|
|
1819
|
+
// 含 headroom 的链依赖插件的 chainTarget 分组(压缩结果交给下一跳)。
|
|
1820
|
+
// 插件不支持时整条链跳过:不起转发器、不写 chainTarget、不动 baseUrl,
|
|
1821
|
+
// 供应商保持直连,报错提示更新插件。没有 headroom 的链不依赖插件,照常
|
|
1822
|
+
if (hrIdx0 >= 0 && !headroomSupportsChainTarget()) {
|
|
1823
|
+
gatedChains.add(c.id);
|
|
1824
|
+
// 没装插件和插件过旧分开说:没装的用户要的是“去装”,不是“去更新”
|
|
1825
|
+
const hrHook = findMarketplaceHook('headroom', join('hooks', 'hr-multi.mjs'));
|
|
1826
|
+
errors.push(`链 ${c.name || c.id}:` + (hrHook
|
|
1827
|
+
? 'headroom 插件版本过旧(不支持链转发),请更新插件后再启用含 headroom 的链'
|
|
1828
|
+
: '未安装 headroom 插件,含 headroom 的链暂不生效;到插件市场安装,或删掉链里的 headroom 节点'));
|
|
851
1829
|
continue;
|
|
852
1830
|
}
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
1831
|
+
const entryProxyUrls = hrIdx0 > 0
|
|
1832
|
+
? resolveCustomProxies((c.nodes || []).slice(0, hrIdx0), config.sharedProxies)
|
|
1833
|
+
: resolveCustomProxies(c.nodes, config.sharedProxies);
|
|
1834
|
+
const proxyUrls = entryProxyUrls; // 无 headroom 或链首 headroom:入口就是全部
|
|
1835
|
+
const entryNeedsLoopbackProxy = hrIdx0 > 0 && entryProxyUrls.length > 0;
|
|
1836
|
+
// 先把"现在还是真实上游"的地址记进链里(改地址之前做,否则就查不到了)。
|
|
1837
|
+
// 只补缺的项,已有记录不覆盖
|
|
1838
|
+
const cap = captureChainUpstreams({ dataRoot, chain: c });
|
|
1839
|
+
if (cap.changed) {
|
|
1840
|
+
c.upstreams = cap.map;
|
|
1841
|
+
try {
|
|
1842
|
+
await withConfigLock(configFile, () => {
|
|
1843
|
+
const fresh = loadConfig(configFile);
|
|
1844
|
+
const list = Array.isArray(fresh.proxyChains) ? fresh.proxyChains : [];
|
|
1845
|
+
const hit = list.find((x) => x && x.id === c.id);
|
|
1846
|
+
if (hit) { hit.upstreams = cap.map; saveConfig(configFile, fresh); }
|
|
1847
|
+
});
|
|
1848
|
+
result.upstreamsCaptured = (result.upstreamsCaptured || 0) + cap.changed;
|
|
1849
|
+
} catch { /* 写回失败下次再补 */ }
|
|
1850
|
+
}
|
|
1851
|
+
const hrIndex = c.nodes.findIndex((n) => n.type === 'headroom');
|
|
1852
|
+
const injectIndex = c.nodes.findIndex((n) => n.type === 'inject');
|
|
1853
|
+
// 注入优先拓扑(链首转发器 + headroom 在后):起两个转发器。
|
|
1854
|
+
// 入口:注入在这里做,上游固定指向 headroom 路由器(本机直连,不走代理)
|
|
1855
|
+
// 回程:执行 headroom 之后的那截链(custom 多级串联出网),上游按 key
|
|
1856
|
+
// 查真实上游——headroom 实例经 chainTarget 把压缩结果发过来。
|
|
1857
|
+
// 本链 upstreams 查不到时回落 headroom.json 全局登记:同 key 多半是
|
|
1858
|
+
// 同一供应商,功能上无害(注释曾声称只用本链记录,与实现不符,已改口)
|
|
1859
|
+
// headroom 的 --http-proxy 是单值,多级串联只能由回程转发器做;
|
|
1860
|
+
// headroom 之后没有节点时不起回程,实例直连真实上游(chainTarget 空)
|
|
1861
|
+
// 链首转发器(inject 或 custom 在前)且链上有 headroom:入口的出口都是
|
|
1862
|
+
// headroom 路由器,先过链首段(注入/自定义代理)再进压缩
|
|
1863
|
+
const entryToHeadroom = hrIndex > 0;
|
|
1864
|
+
const injectFirst = entryToHeadroom && injectIndex >= 0 && injectIndex < hrIndex;
|
|
1865
|
+
const tailNodes = entryToHeadroom ? (c.nodes || []).slice(hrIndex + 1) : null;
|
|
1866
|
+
const needsReturn = !!(tailNodes && tailNodes.some((n) => n.type === 'custom'));
|
|
1867
|
+
// 每条链一份解析器:链首不是 headroom 时,真实上游只从这条链自己的
|
|
1868
|
+
// upstreams 来,不能拿别的链或 headroom 登记瞎猜
|
|
1869
|
+
const resolver = entryToHeadroom
|
|
1870
|
+
? () => `http://127.0.0.1:${headroomRouterPort(dataRoot)}`
|
|
1871
|
+
: makeChainUpstreamResolver(dataRoot, c);
|
|
1872
|
+
// 链首是 headroom 时 ZCode 直连 8787,我们的转发器只能挂在 headroom 之后。
|
|
1873
|
+
// 这种拓扑下把 inject 放在 headroom 前面是做不到的(请求不经过我们),
|
|
1874
|
+
// 记一条明确错误,别让用户以为配好了。
|
|
1875
|
+
// 链首是 headroom 时注入不可能排在压缩前:injectIndex < hrIndex=0 意味着
|
|
1876
|
+
// inject 节点不存在(findIndex 找不到返回 -1)。数组顺序天然保证,
|
|
1877
|
+
// 无需运行时校验
|
|
1878
|
+
// 只在 headroom 之后还有节点时才需要转发器;纯 headroom 链交给 headroom 自己
|
|
1879
|
+
const needsForwarder = c.nodes.some((n) => n.type !== 'headroom');
|
|
1880
|
+
if (!needsForwarder) continue;
|
|
1881
|
+
// 端口:null/0/非法一律回落到段内起始端口(注意 Number(null) === 0 不是 NaN,
|
|
1882
|
+
// 只用 isFinite 判断会把 null 当成合法端口 0,导致转发器起不来又不报错)
|
|
1883
|
+
const portNum = Number(c.port);
|
|
1884
|
+
let port = Number.isFinite(portNum) && portNum >= 1024 && portNum <= 65535
|
|
1885
|
+
? Math.round(portNum) : PROVIDER_PROXY_PORT_MIN;
|
|
860
1886
|
let actual = 0;
|
|
861
1887
|
try {
|
|
862
|
-
actual = await manager.ensure({
|
|
1888
|
+
actual = await manager.ensure({
|
|
1889
|
+
upstream: '', // 由 resolver 决定
|
|
1890
|
+
port,
|
|
1891
|
+
proxyUrls,
|
|
1892
|
+
injector: hasInject ? promptInjector(state) : null,
|
|
1893
|
+
upstreamResolver: resolver,
|
|
1894
|
+
loopbackProxy: entryNeedsLoopbackProxy,
|
|
1895
|
+
opencodeGoCompat: goCompat,
|
|
1896
|
+
});
|
|
863
1897
|
} catch (err) {
|
|
864
|
-
// 端口被别的程序占了就换段内空闲端口再试一次
|
|
865
1898
|
const busy = err && /EADDRINUSE/.test(String(err.code || '') + ' ' + String(err.message || ''));
|
|
866
1899
|
const free = busy ? await providerProxyFreePort() : null;
|
|
867
1900
|
if (free !== null && free !== port) {
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
catch (err2) { errors.push(
|
|
1901
|
+
try {
|
|
1902
|
+
actual = await manager.ensure({ upstream: '', port: free, proxyUrls, injector: hasInject ? promptInjector(state) : null, upstreamResolver: resolver, loopbackProxy: entryNeedsLoopbackProxy, opencodeGoCompat: goCompat });
|
|
1903
|
+
} catch (err2) { errors.push(`链 ${c.id}:转发器启动失败(${err2?.message || err2})`); continue; }
|
|
871
1904
|
} else {
|
|
872
|
-
errors.push(
|
|
1905
|
+
errors.push(`链 ${c.id}:转发器启动失败(${err?.message || err})`);
|
|
873
1906
|
continue;
|
|
874
1907
|
}
|
|
875
1908
|
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
1909
|
+
ports.set(c.id, actual);
|
|
1910
|
+
result.started.push({ id: c.id, port: actual });
|
|
1911
|
+
// 兼容端口:这条链由“逐家转发”迁移而来时带着原来的转发端口。各起一个“原样转到
|
|
1912
|
+
// 链入口”的转发器——ZCode 不会立刻采用改写后的地址(实测可以晚十几分钟),
|
|
1913
|
+
// 还在用旧地址的会话照常能连上。这里不注入:注入已经在链转发器里做过,再做一次
|
|
1914
|
+
// 正文会重复
|
|
1915
|
+
for (const lp of (Array.isArray(c.legacyPorts) ? c.legacyPorts : [])) {
|
|
1916
|
+
if (lp === actual || shimPorts.has(lp)) continue;
|
|
1917
|
+
const entryUrl = hrIndex === 0
|
|
1918
|
+
? `http://127.0.0.1:${headroomRouterPort(dataRoot)}`
|
|
1919
|
+
: `http://127.0.0.1:${actual}`;
|
|
1920
|
+
try {
|
|
1921
|
+
const sp = await manager.ensure({ upstream: entryUrl, port: lp, proxyUrls: [], injector: null });
|
|
1922
|
+
shimPorts.add(sp);
|
|
1923
|
+
result.started.push({ id: c.id + ':compat', port: sp });
|
|
1924
|
+
} catch (err3) {
|
|
1925
|
+
errors.push(`链 ${c.name || c.id}:兼容端口 ${lp} 起不来,还在用旧地址的会话连不上(${err3?.message || err3})`);
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
// 回程转发器:注入优先且 headroom 之后有 custom 节点。和入口共用
|
|
1929
|
+
// keyResolver(都按 key 查),但没有注入(注入在入口已做)、带 custom
|
|
1930
|
+
// 串联代理。端口不进链配置——chainTarget 写进 headroom 登记就是它的
|
|
1931
|
+
// 持久化记录,重启后对齐重新分配并重写
|
|
1932
|
+
if (needsReturn) {
|
|
1933
|
+
const tailProxyUrls = resolveCustomProxies(tailNodes, config.sharedProxies);
|
|
1934
|
+
let rPort = 0;
|
|
1935
|
+
// 优先复用上一轮的回程端口:每轮都找新空闲口会起第二个实例、
|
|
1936
|
+
// 旧的没人收(chainTarget 是它的唯一持久化记录,换口就要重写一遍)
|
|
1937
|
+
const prevReturn = state && typeof state === 'object' && state.proxyChainReturnPorts
|
|
1938
|
+
? state.proxyChainReturnPorts[c.id] : undefined;
|
|
1939
|
+
const rPortWanted = Number.isFinite(Number(prevReturn)) && Number(prevReturn) >= 1024
|
|
1940
|
+
? Math.round(Number(prevReturn)) : await providerProxyFreePort();
|
|
880
1941
|
try {
|
|
881
|
-
|
|
882
|
-
|
|
1942
|
+
rPort = await manager.ensure({
|
|
1943
|
+
upstream: '',
|
|
1944
|
+
port: rPortWanted,
|
|
1945
|
+
proxyUrls: tailProxyUrls,
|
|
1946
|
+
injector: null,
|
|
1947
|
+
upstreamResolver: makeChainUpstreamResolver(dataRoot, c),
|
|
1948
|
+
opencodeGoCompat: goCompat, // 回程转发器才是真正连厂商的那一跳
|
|
1949
|
+
});
|
|
1950
|
+
} catch (err2) {
|
|
1951
|
+
errors.push(`链 ${c.id}:回程转发器启动失败(${err2?.message || err2})`);
|
|
1952
|
+
}
|
|
1953
|
+
if (rPort) {
|
|
1954
|
+
returnPorts.set(c.id, rPort);
|
|
1955
|
+
result.started.push({ id: c.id + ':return', port: rPort });
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
// 端口变了要写回配置
|
|
1959
|
+
if (actual !== c.port) {
|
|
1960
|
+
try {
|
|
1961
|
+
await withConfigLock(configFile, () => {
|
|
1962
|
+
const fresh = loadConfig(configFile);
|
|
1963
|
+
if (configUnreadable) return;
|
|
1964
|
+
const list = Array.isArray(fresh.proxyChains) ? fresh.proxyChains : [];
|
|
1965
|
+
const hit = list.find((x) => x && x.id === c.id);
|
|
1966
|
+
if (hit) { hit.port = actual; saveConfig(configFile, fresh); }
|
|
1967
|
+
});
|
|
1968
|
+
} catch { /* 写回失败下次再补 */ }
|
|
883
1969
|
}
|
|
884
|
-
result.started.push({ id, port: actual });
|
|
885
1970
|
}
|
|
886
|
-
|
|
1971
|
+
|
|
1972
|
+
// 收掉上一轮由本函数起、这轮已经不要的端口(含回程转发器——链上 headroom
|
|
1973
|
+
// 之后的 custom 被删时,旧回程就没人用了);供应商代理的端口不在 ownedPorts 里,不动
|
|
1974
|
+
const wanted = new Set([...ports.values(), ...returnPorts.values(), ...shimPorts]);
|
|
887
1975
|
try {
|
|
888
1976
|
for (const fw of manager.status()) {
|
|
889
|
-
if (!
|
|
1977
|
+
if (ownedPorts.has(fw.port) && !wanted.has(fw.port)) {
|
|
890
1978
|
try { if (await manager.stopPort(fw.port)) result.stopped.push(fw.port); } catch { /* 下次再收 */ }
|
|
891
1979
|
}
|
|
892
1980
|
}
|
|
893
1981
|
} catch { /* 状态查询失败不影响 */ }
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
1982
|
+
try {
|
|
1983
|
+
if (state && typeof state === 'object') {
|
|
1984
|
+
state.proxyChainOwnedPorts = [...wanted];
|
|
1985
|
+
// 回程端口单独记一份:下一轮 ensure 复用,避免每轮换口起停
|
|
1986
|
+
state.proxyChainReturnPorts = Object.fromEntries(returnPorts);
|
|
1987
|
+
}
|
|
1988
|
+
} catch { /* state 不可写不影响 */ }
|
|
1989
|
+
|
|
1990
|
+
// 供应商已被删除(不在 providerRules 里)→ 从所有链移出。
|
|
1991
|
+
// 登记的删除由 hr-reconcile 做(那里有完整的全集对照);链是 zcodepro.json 的
|
|
1992
|
+
// 范畴,这里做。不移的话链会继续给已不存在的 id 写 chainTarget / 改地址,
|
|
1993
|
+
// 界面上也永远勾着一个幽灵
|
|
1994
|
+
const known = knownProviderIdSet(dataRoot);
|
|
1995
|
+
if (known) {
|
|
1996
|
+
let removedFromChains = 0;
|
|
1997
|
+
for (const c of chains) {
|
|
1998
|
+
if (!c || !Array.isArray(c.providers)) continue;
|
|
1999
|
+
const keep = c.providers.filter((pid) => known.has(pid));
|
|
2000
|
+
if (keep.length !== c.providers.length) {
|
|
2001
|
+
removedFromChains += c.providers.length - keep.length;
|
|
2002
|
+
c.providers = keep;
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
if (removedFromChains > 0) {
|
|
2006
|
+
try {
|
|
2007
|
+
await withConfigLock(configFile, () => {
|
|
2008
|
+
const fresh = loadConfig(configFile);
|
|
2009
|
+
if (configUnreadable) return;
|
|
2010
|
+
const list = Array.isArray(fresh.proxyChains) ? fresh.proxyChains : [];
|
|
2011
|
+
for (const c of chains) {
|
|
2012
|
+
const hit = list.find((x) => x && x.id === c.id);
|
|
2013
|
+
if (hit && Array.isArray(hit.providers)) hit.providers = c.providers;
|
|
2014
|
+
}
|
|
2015
|
+
saveConfig(configFile, fresh);
|
|
2016
|
+
});
|
|
2017
|
+
result.prunedFromChains = removedFromChains;
|
|
2018
|
+
} catch { /* 写回失败下次再清 */ }
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
// 链上有 headroom 节点 + 供应商没登记:自动补登记(key/上游都现成)。
|
|
2023
|
+
// 必须在写 chainTarget 和 baseUrl 之前做,否则 8787 会拒绝未登记的请求
|
|
2024
|
+
const activeChains = chains.filter((c) => c && !gatedChains.has(c.id));
|
|
2025
|
+
// 手动改地址 = 退出链(见 uncheckManuallyChanged)。排在写 chainTarget 之前:
|
|
2026
|
+
// 退出的供应商这一轮就按“不在链上”处理,它的 chainTarget 会被清掉
|
|
2027
|
+
const optedOut = await uncheckManuallyChanged({ dataRoot, configFile, chains, activeChains, ports, state, result });
|
|
2028
|
+
// “链写的地址”记录只保留给仍在启用中的链上的供应商:移出链、链被停用或被跳过的,
|
|
2029
|
+
// 地址已经不是链在管,记录留着下次会被误判成手动改过
|
|
2030
|
+
try {
|
|
2031
|
+
if (state && typeof state === 'object' && state.chainAddressWritten) {
|
|
2032
|
+
const still = new Set();
|
|
2033
|
+
for (const c of activeChains) for (const pid of (c && c.providers) || []) still.add(pid);
|
|
2034
|
+
for (const pid of Object.keys(state.chainAddressWritten)) if (!still.has(pid)) delete state.chainAddressWritten[pid];
|
|
2035
|
+
}
|
|
2036
|
+
} catch { /* 尽力而为 */ }
|
|
2037
|
+
const ar = autoRegisterChainProviders({ dataRoot, chains: activeChains, config });
|
|
2038
|
+
if (ar.error) errors.push(ar.error);
|
|
2039
|
+
result.autoRegistered = ar.changed;
|
|
2040
|
+
result.registrationsUpdated = (ar.updated || []).length;
|
|
2041
|
+
|
|
2042
|
+
// 把 chainTarget 写进 headroom 的供应商登记(headroom 之后的节点才需要)
|
|
2043
|
+
// chainTarget 指向:注入优先链给回程转发器(headroom 之后那截的执行器),
|
|
2044
|
+
// 其余给链转发器;都没有就回落到配置端口(写个能连上的,别留死值)
|
|
2045
|
+
// 端口按拓扑给:链首 headroom 用链转发器;headroom 在后用回程转发器。
|
|
2046
|
+
// 都没有就返回空(applyChainTargets 会清 chainTarget、入口对齐会跳过),
|
|
2047
|
+
// 绝不兜底 c.port——那可能是没起来的配置值或别人的端口
|
|
2048
|
+
const ct = applyChainTargets({ dataRoot, chains: activeChains, portOf: (c) => {
|
|
2049
|
+
const nodes = Array.isArray(c?.nodes) ? c.nodes : [];
|
|
2050
|
+
const hri = nodes.findIndex((n) => n.type === 'headroom');
|
|
2051
|
+
if (hri === 0) return ports.get(c.id) || '';
|
|
2052
|
+
if (hri > 0) return returnPorts.get(c.id) || '';
|
|
2053
|
+
return '';
|
|
2054
|
+
} });
|
|
2055
|
+
if (ct.error) errors.push(ct.error);
|
|
2056
|
+
result.chainTargets = ct.changed;
|
|
2057
|
+
|
|
2058
|
+
// 链首不是 headroom 时,把供应商的 baseUrl 指到链转发器(ZCode 直连链)。
|
|
2059
|
+
// 这一步失败不影响转发器本身,只是请求进不来,所以记一条错误而不是整体失败
|
|
2060
|
+
const ea = applyChainEntryAddresses({ dataRoot, chains: activeChains, portOf: (c) => ports.get(c.id) || c.port, providerProxies: config.providerProxies, state });
|
|
2061
|
+
if (ea.error) errors.push(ea.error);
|
|
2062
|
+
result.chainEntries = ea.changed;
|
|
2063
|
+
|
|
2064
|
+
// 有供应商退出了链:写提示文件,页面轮询到之后在右下角弹卡片(写文件 + 轮询是
|
|
2065
|
+
// 仓库里既有的做法,helper 的 token 不落盘,页面之外调不了接口)。
|
|
2066
|
+
// 地址以对齐之后的最终值为准:指着 zcode-pro 自己转发端口的已经被还原成真实上游
|
|
2067
|
+
if (optedOut.length) {
|
|
897
2068
|
try {
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
saveConfig(configFile, fresh);
|
|
2069
|
+
const rulesNow = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'))?.config?.providerConfigRules?.providerRules;
|
|
2070
|
+
const finalUrl = (id) => {
|
|
2071
|
+
const r = (Array.isArray(rulesNow) ? rulesNow : []).find((x) => x && x.providerId === id);
|
|
2072
|
+
return r ? String(r.config?.api?.baseUrl || '').trim() : '';
|
|
2073
|
+
};
|
|
2074
|
+
writeJsonAtomic(join(dataRoot, 'proxy-chain-notice.json'), {
|
|
2075
|
+
at: new Date().toISOString(),
|
|
2076
|
+
kind: 'auto-unchecked',
|
|
2077
|
+
items: optedOut.map((o) => ({ id: o.id, name: o.name, chain: o.chain, url: finalUrl(o.id) || o.url })),
|
|
908
2078
|
});
|
|
909
|
-
} catch
|
|
2079
|
+
} catch { /* 写不了提示不影响退出链本身 */ }
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
// 写了 chainTarget 就要触发 headroom 重新分组。headroom 的实例按
|
|
2083
|
+
// 「格式|chain:目标」分组,我们改了 chainTarget 之后实例映射不会自己变:
|
|
2084
|
+
// 路由器按新键查不到实例 → 所有经 8787 的请求 502。典型触发场景是
|
|
2085
|
+
// headroom 实例被单独重启过(按直连分组)而我们随后写入 chainTarget。
|
|
2086
|
+
// ensure 是幂等的(在跑的实例跳过),所以每次对齐都触发一次也没问题
|
|
2087
|
+
// chainTarget 变了,或者登记的上游/格式变了(实例分组键跟着变)→ 让 headroom 重新分组
|
|
2088
|
+
if ((ct.changed > 0 || (ar.updated || []).length > 0) && !state.noHeadroomHook) {
|
|
2089
|
+
runHeadroomHook(['ensure'], 60000).then((r) => {
|
|
2090
|
+
if (!r.ok) console.error(`[zcodepro] 代理链:headroom 分组刷新失败(${r.error || r.code})`);
|
|
2091
|
+
}).catch(() => { /* 失败下次对齐再试 */ });
|
|
2092
|
+
result.headroomRegroup = true;
|
|
910
2093
|
}
|
|
911
2094
|
} catch (err) {
|
|
912
2095
|
errors.push(String(err?.message || err));
|
|
913
2096
|
}
|
|
914
2097
|
result.ms = Date.now() - startedAt;
|
|
915
|
-
try { state.
|
|
916
|
-
for (const e of errors) console.error(`[zcodepro]
|
|
2098
|
+
try { state.proxyChainLastRun = result; } catch { /* state 不可写不影响 */ }
|
|
2099
|
+
for (const e of errors) console.error(`[zcodepro] 代理链:${e}`);
|
|
917
2100
|
return result;
|
|
918
2101
|
}
|
|
919
2102
|
|
|
920
|
-
//
|
|
921
|
-
//
|
|
922
|
-
function
|
|
2103
|
+
// 提示词注入钩子:每次请求都读实时快照,所以改完正文保存后下一次请求就带上。
|
|
2104
|
+
// 关着(或正文为空)时返回 null,转发器据此保持纯流式转发。
|
|
2105
|
+
function promptInjector(state) {
|
|
2106
|
+
return ({ url, headers, rawBody }) => {
|
|
2107
|
+
const pi = activePromptInjection;
|
|
2108
|
+
if (!pi || !pi.text || !pi.text.trim()) return { buffer: rawBody, changed: false };
|
|
2109
|
+
const r = rewriteRequest({ url, headers, rawBody, text: pi.text, includeSubagents: pi.subagents === true });
|
|
2110
|
+
if (r.changed) {
|
|
2111
|
+
try {
|
|
2112
|
+
if (state && typeof state === 'object') {
|
|
2113
|
+
state.injectStats = state.injectStats || { count: 0, lastAt: 0 };
|
|
2114
|
+
state.injectStats.count += 1;
|
|
2115
|
+
state.injectStats.lastAt = Date.now();
|
|
2116
|
+
}
|
|
2117
|
+
} catch { /* 统计失败不影响转发 */ }
|
|
2118
|
+
}
|
|
2119
|
+
return r;
|
|
2120
|
+
};
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
// providerRules 里登记的全部供应商 id(含已停用的):用来判断某条转发记录是不是
|
|
2124
|
+
// 供应商已经被用户删掉了。文件读不到时返回 null,调用方跳过清理(不误删)。
|
|
2125
|
+
function knownProviderIdSet(dataRoot) {
|
|
2126
|
+
const pc = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'));
|
|
2127
|
+
if (!pc) return null;
|
|
2128
|
+
const ids = new Set();
|
|
2129
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
2130
|
+
if (Array.isArray(rules)) {
|
|
2131
|
+
for (const r of rules) {
|
|
2132
|
+
if (r && typeof r.providerId === 'string' && r.providerId) ids.add(r.providerId);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
const v2 = readJsonFile(join(dataRoot, 'v2', 'config.json'));
|
|
2136
|
+
if (v2?.provider && typeof v2.provider === 'object') {
|
|
2137
|
+
for (const id of Object.keys(v2.provider)) ids.add(id);
|
|
2138
|
+
}
|
|
2139
|
+
return ids;
|
|
2140
|
+
}
|
|
2141
|
+
|
|
2142
|
+
// 已启用的供应商 id:以 v2/provider_config.json 的 providerRules 为“确实配置过”的
|
|
2143
|
+
// 依据,再用 v2/config.json 的 enabled 字段排除显式关掉的(enabled 缺省视为启用)。
|
|
2144
|
+
function enabledProviderIds(dataRoot) {
|
|
2145
|
+
const v2 = readJsonFile(join(dataRoot, 'v2', 'config.json'));
|
|
2146
|
+
const table = (v2?.provider && typeof v2.provider === 'object') ? v2.provider : {};
|
|
2147
|
+
const ids = new Set();
|
|
2148
|
+
const rules = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'))
|
|
2149
|
+
?.config?.providerConfigRules?.providerRules;
|
|
2150
|
+
if (Array.isArray(rules)) {
|
|
2151
|
+
for (const r of rules) {
|
|
2152
|
+
if (!r || typeof r.providerId !== 'string' || !r.providerId) continue;
|
|
2153
|
+
const entry = table[r.providerId];
|
|
2154
|
+
if (entry && typeof entry === 'object' && entry.enabled === false) continue;
|
|
2155
|
+
if (entry && typeof entry === 'object' && entry.systemDisabledReason) continue;
|
|
2156
|
+
ids.add(r.providerId);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
return ids;
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
|
|
2163
|
+
// 把代理链解析成有序地址列表:手填的直接用,引用共享代理的按 id 查表;
|
|
2164
|
+
// 解析不到(引用的共享代理被删)的节点跳过,不阻断整条链。
|
|
2165
|
+
// 运行时用它给转发器传动整条链(多级串联逐层建 CONNECT 隧道)。
|
|
2166
|
+
function resolveProxyChainUrls(nodes, sharedProxies) {
|
|
2167
|
+
const list = Array.isArray(nodes) ? nodes : [];
|
|
2168
|
+
const out = [];
|
|
2169
|
+
for (const node of list) {
|
|
2170
|
+
if (!node || node.type !== 'custom') continue;
|
|
2171
|
+
let url = '';
|
|
2172
|
+
if (typeof node.proxy === 'string' && node.proxy) url = node.proxy;
|
|
2173
|
+
else if (typeof node.proxyId === 'string' && node.proxyId) {
|
|
2174
|
+
const hit = (Array.isArray(sharedProxies) ? sharedProxies : []).find((e) => e && e.id === node.proxyId);
|
|
2175
|
+
url = hit && typeof hit.url === 'string' ? hit.url : '';
|
|
2176
|
+
}
|
|
2177
|
+
if (url) out.push(url);
|
|
2178
|
+
}
|
|
2179
|
+
return out;
|
|
2180
|
+
}
|
|
2181
|
+
|
|
2182
|
+
// 代理链改造的一次性迁移:旧配置是 { enabled, proxy, port, upstream }(单级),
|
|
2183
|
+
// 新结构是 { enabled, port, upstream, nodes }。buildProxyChainMigration 只算“要改成
|
|
2184
|
+
// 什么”,不动磁盘;由调用方(helper 启动 / 设置页首次打开)执行并打标记。
|
|
2185
|
+
// 参数 rebuildIds 是要按旧数据重建的供应商 id 白名单——为空表示全部重建。
|
|
2186
|
+
export function buildProxyChainMigration({ config, rebuildIds = null }) {
|
|
2187
|
+
if (config && config.migrations && config.migrations.proxyChainV2 === true) return null;
|
|
2188
|
+
const table = (config && config.providerProxies) || {};
|
|
2189
|
+
const ids = Object.keys(table);
|
|
2190
|
+
if (!ids.length) return { providerProxies: {}, cleared: [], rebuilt: [] };
|
|
2191
|
+
const keep = rebuildIds ? new Set(rebuildIds) : null;
|
|
2192
|
+
const next = {};
|
|
2193
|
+
const cleared = [];
|
|
2194
|
+
const rebuilt = [];
|
|
2195
|
+
for (const id of ids) {
|
|
2196
|
+
const e = table[id];
|
|
2197
|
+
if (!e || typeof e !== 'object') continue;
|
|
2198
|
+
if (keep && !keep.has(id)) { cleared.push(id); continue; }
|
|
2199
|
+
// 旧 proxy 字段转成链上的第一个节点;本来就是 nodes 的直接保留
|
|
2200
|
+
const nodes = mergeProxyNodes(e.nodes, e.proxy);
|
|
2201
|
+
next[id] = {
|
|
2202
|
+
enabled: e.enabled === true,
|
|
2203
|
+
port: Number.isFinite(Number(e.port)) ? Math.round(Number(e.port)) : 18731,
|
|
2204
|
+
upstream: typeof e.upstream === 'string' && e.upstream ? e.upstream : null,
|
|
2205
|
+
nodes,
|
|
2206
|
+
};
|
|
2207
|
+
rebuilt.push(id);
|
|
2208
|
+
}
|
|
2209
|
+
return { providerProxies: next, cleared, rebuilt };
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
// 执行迁移:清掉不在白名单里的条目对应的供应商地址(还原到上游),
|
|
2213
|
+
// 白名单里的按新结构保留。返回迁移结果,供界面提示用。
|
|
2214
|
+
export async function runProxyChainMigration({ dataRoot, configFile, state, rebuildIds = null }) {
|
|
2215
|
+
const config = loadConfig(configFile);
|
|
2216
|
+
const plan = buildProxyChainMigration({ config, rebuildIds });
|
|
2217
|
+
if (!plan) return null;
|
|
2218
|
+
// 被清掉的条目:把 baseURL 还原到上游(有 upstream 就用它,没有就翻备份)
|
|
2219
|
+
for (const id of plan.cleared) {
|
|
2220
|
+
try {
|
|
2221
|
+
const entry = (config.providerProxies || {})[id] || {};
|
|
2222
|
+
const current = providerProxyCurrentBaseUrl(dataRoot, id);
|
|
2223
|
+
if (!current || !providerProxyOwnUrl(current, entry.port)) continue;
|
|
2224
|
+
let target = (typeof entry.upstream === 'string' && entry.upstream)
|
|
2225
|
+
? entry.upstream
|
|
2226
|
+
: providerProxyBackupBaseUrl(dataRoot, id);
|
|
2227
|
+
if (!target || providerProxyOwnUrl(target, entry.port)) continue;
|
|
2228
|
+
providerProxyRewriteBaseUrl(dataRoot, id, target);
|
|
2229
|
+
} catch { /* 单条失败不影响整体迁移 */ }
|
|
2230
|
+
}
|
|
2231
|
+
await withConfigLock(configFile, () => {
|
|
2232
|
+
const fresh = loadConfig(configFile);
|
|
2233
|
+
if (configUnreadable) return;
|
|
2234
|
+
fresh.providerProxies = plan.providerProxies;
|
|
2235
|
+
fresh.migrations = { ...(fresh.migrations || {}), proxyChainV2: true };
|
|
2236
|
+
saveConfig(configFile, fresh);
|
|
2237
|
+
});
|
|
2238
|
+
await ensureProviderProxies({ dataRoot, configFile, state, reason: 'proxy-chain-migration' });
|
|
2239
|
+
// 留一份说明给界面:写标记文件,页面轮询后弹右下角卡片(helper 的 token 不落盘,
|
|
2240
|
+
// 页面之外无法直接调接口,写文件 + 轮询是仓库里既有的做法)
|
|
2241
|
+
try {
|
|
2242
|
+
writeJsonAtomic(join(dataRoot, 'proxy-chain-notice.json'), {
|
|
2243
|
+
at: new Date().toISOString(),
|
|
2244
|
+
cleared: plan.cleared,
|
|
2245
|
+
rebuilt: plan.rebuilt,
|
|
2246
|
+
});
|
|
2247
|
+
} catch { /* 写不了提示不影响迁移本身 */ }
|
|
2248
|
+
return plan;
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
// —— 转发器巡检 ——
|
|
2252
|
+
// 每 30 秒看一眼在跑的转发器还听不听:查的是进程内的标志位(server.listening),
|
|
2253
|
+
// 不联网、不读盘。转发器异常停掉时不用等下一次配置变化或重启,自动重新对齐
|
|
2254
|
+
// 把它拉起来。走链的 headroom 实例也在这轮里顺带探一下(见下)。按模块实例注册
|
|
2255
|
+
//(热替换后新实例重新起定时器),dispose 时清掉
|
|
2256
|
+
const FORWARDER_HEALTH_MS = 30_000;
|
|
2257
|
+
let forwarderHealthTimer = null;
|
|
2258
|
+
|
|
2259
|
+
// 不在监听的转发器个数(导出以便测试)
|
|
2260
|
+
export function countForwardersDown(state) {
|
|
2261
|
+
try {
|
|
2262
|
+
return getProviderProxyManager(state).status().filter((fw) => !fw.listening).length;
|
|
2263
|
+
} catch { return 0; }
|
|
2264
|
+
}
|
|
2265
|
+
|
|
2266
|
+
// —— 走链的 headroom 端点(实例 + 路由器)也在巡检范围 ——
|
|
2267
|
+
// 压缩实例没了(被停掉、崩溃),经 8787 的请求会在路由器那一层 502,而转发器本身
|
|
2268
|
+
// 一切正常,上面按标志位的检查发现不了。实例只在“会话启动”和“链变动”时由 headroom
|
|
2269
|
+
// 插件检查并补起,中间掉了要等到下一次链变动才有人管。这里每轮顺带探两样:
|
|
2270
|
+
// 1. 实例:headroom.json 的 instances 表里键带“|chain:”的分组(走链的实例);
|
|
2271
|
+
// 2. 路由器(默认 8787):勾了链的供应商入口就是它,有供应商登记就说明有人指着它。
|
|
2272
|
+
// “实例都在、只有路由器没了”是最容易漏的情形——路由器是独立进程,它挂了实例
|
|
2273
|
+
// 还活着,只看实例看不出来,而勾了链的供应商会全部连不上。
|
|
2274
|
+
// 两者都不在监听就让插件跑一次 ensure。ensure 是幂等的:在跑的跳过、启动中的不干预、
|
|
2275
|
+
// 没了的补起。开销:每轮读一次 headroom.json(几 KB),每个端口连一次本机
|
|
2276
|
+
// 返回 [{ key, port, type }],type:headroom(实例)| router(路由器)(导出以便测试)
|
|
2277
|
+
export async function headroomEndpointsDown(dataRoot) {
|
|
2278
|
+
const doc = readJsonFile(join(dataRoot, 'headroom.json'));
|
|
2279
|
+
if (!doc || typeof doc !== 'object') return [];
|
|
2280
|
+
const out = [];
|
|
2281
|
+
const inst = doc.instances;
|
|
2282
|
+
if (inst && typeof inst === 'object') {
|
|
2283
|
+
for (const [key, port] of Object.entries(inst)) {
|
|
2284
|
+
if (!key.includes('|chain:') || !Number.isInteger(port) || port < 1024 || port > 65535) continue;
|
|
2285
|
+
if (!(await portListening(port))) out.push({ key, port, type: 'headroom' }); // eslint-disable-line no-await-in-loop
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
// 有供应商登记就有人指着路由器(勾进链的入口、hr-join 的直连都是 8787)
|
|
2289
|
+
const registered = Array.isArray(doc.providers)
|
|
2290
|
+
? doc.providers.filter((p) => p && typeof p.id === 'string') : [];
|
|
2291
|
+
if (registered.length) {
|
|
2292
|
+
const routerPort = (Number(doc.router && doc.router.port) || 8787);
|
|
2293
|
+
if (routerPort >= 1024 && routerPort <= 65535 && !(await portListening(routerPort))) {
|
|
2294
|
+
out.push({ key: 'router', port: routerPort, type: 'router' });
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
return out;
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
// 端口上有没有进程在听:连一次本机,1.5 秒内连不上算没有
|
|
2301
|
+
function portListening(port) {
|
|
2302
|
+
return new Promise((resolvePort) => {
|
|
2303
|
+
const sock = netConnect({ host: '127.0.0.1', port });
|
|
2304
|
+
const done = (ok) => { sock.destroy(); resolvePort(ok); };
|
|
2305
|
+
sock.setTimeout(1500);
|
|
2306
|
+
sock.once('connect', () => done(true));
|
|
2307
|
+
sock.once('timeout', () => done(false));
|
|
2308
|
+
sock.once('error', () => done(false));
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// 巡检发现问题时写一份提示,页面轮询读到后在右下角弹卡片(见 proxy-chain-notice.js)。
|
|
2313
|
+
// 同一个问题(类型 + 端口集合 + 处理结果)连续几轮都出现时只写第一次,不每 30 秒刷一张卡;
|
|
2314
|
+
// 处理结果变了(比如先是让 headroom 补起、后来补起失败)算新的情况,会再提示一次。
|
|
2315
|
+
// 巡检恢复正常时由巡检把 state.healthNoticeKey 清掉,下次再出问题会重新提示。
|
|
2316
|
+
// 文件与链的提示(proxy-chain-notice.json)分开,免得互相覆盖。
|
|
2317
|
+
// 返回这次有没有写(导出以便测试)
|
|
2318
|
+
export function writeHealthNotice(dataRoot, state, itemOrItems) {
|
|
2319
|
+
const raw = (Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems])
|
|
2320
|
+
.filter((it) => it && typeof it === 'object' && it.type);
|
|
2321
|
+
if (!dataRoot || !raw.length) return false;
|
|
2322
|
+
const items = raw.map((item) => ({
|
|
2323
|
+
type: String(item.type),
|
|
2324
|
+
ports: [...new Set((Array.isArray(item.ports) ? item.ports : []).map(Number)
|
|
2325
|
+
.filter((p) => Number.isInteger(p) && p > 0))].sort((a, b) => a - b),
|
|
2326
|
+
...(item.stillDown ? { stillDown: true } : {}),
|
|
2327
|
+
...(item.failed ? { failed: true, error: String(item.error || '') } : {}),
|
|
2328
|
+
})).filter((it) => it.ports.length);
|
|
2329
|
+
if (!items.length) return false;
|
|
2330
|
+
const key = items.map((it) => `${it.type}:${it.ports.join(',')}|${it.stillDown ? 'down' : ''}${it.failed ? 'failed' : ''}`).join(';');
|
|
2331
|
+
try { if (state && typeof state === 'object' && state.healthNoticeKey === key) return false; } catch { /* state 不可读就当没提示过 */ }
|
|
2332
|
+
try {
|
|
2333
|
+
writeJsonAtomic(join(dataRoot, 'proxy-health-notice.json'), {
|
|
2334
|
+
at: new Date().toISOString(),
|
|
2335
|
+
kind: 'health',
|
|
2336
|
+
items,
|
|
2337
|
+
});
|
|
2338
|
+
// “已提示”的记录只在写成功后记:写失败时记了,下一轮会当成提示过而不再写,
|
|
2339
|
+
// 用户就永远看不到这张卡
|
|
2340
|
+
try { if (state && typeof state === 'object') state.healthNoticeKey = key; } catch { /* state 不可写不影响提示 */ }
|
|
2341
|
+
return true;
|
|
2342
|
+
} catch { return false; }
|
|
2343
|
+
}
|
|
2344
|
+
|
|
2345
|
+
// 巡检一次:有转发器不在监听就重新对齐;转发器都在、但走链的 headroom 实例没了,
|
|
2346
|
+
// 就让 headroom 插件补起。两种情况都在右下角提示。返回这次发现几个转发器不在监听
|
|
2347
|
+
//(实例不并入这个数)。ctx.headroomHook 可传入替身(测试用),默认跑真正的 headroom 钩子
|
|
2348
|
+
export async function runForwarderHealthCheck(state = {}, ctx = {}) {
|
|
2349
|
+
if (!state || typeof state !== 'object' || state.proxyChainAligning) return 0;
|
|
2350
|
+
const downPorts = () => {
|
|
2351
|
+
try { return getProviderProxyManager(state).status().filter((fw) => !fw.listening).map((fw) => fw.port); } catch { return []; }
|
|
2352
|
+
};
|
|
2353
|
+
const down = countForwardersDown(state);
|
|
2354
|
+
if (down) {
|
|
2355
|
+
const ports = downPorts();
|
|
2356
|
+
console.log(`[zcodepro] 转发器巡检:${down} 个转发器不在监听,重新对齐`);
|
|
2357
|
+
await ensureProxyChains({ ...ctx, state, reason: 'health' }).catch(() => { /* 下次再看 */ });
|
|
2358
|
+
writeHealthNotice(ctx.dataRoot, state, { type: 'forwarder', ports, stillDown: countForwardersDown(state) > 0 });
|
|
2359
|
+
return down;
|
|
2360
|
+
}
|
|
2361
|
+
// 重新对齐时该触发的 headroom 重新分组已经触发过,只在上面的分支没走时单独查实例和路由器。
|
|
2362
|
+
// noHeadroomHook 是测试时的隔离开关(不跑真正的插件);传了替身就可以照常走
|
|
2363
|
+
if (!ctx.dataRoot) return 0;
|
|
2364
|
+
if (state.noHeadroomHook && typeof ctx.headroomHook !== 'function') return 0;
|
|
2365
|
+
const hrDown = await headroomEndpointsDown(ctx.dataRoot).catch(() => []);
|
|
2366
|
+
if (!hrDown.length) {
|
|
2367
|
+
// 都正常:清掉“上次提示过的问题”,下次再出问题会重新提示
|
|
2368
|
+
try { if (typeof state === 'object') state.healthNoticeKey = null; } catch { /* state 不可写不影响 */ }
|
|
2369
|
+
return 0;
|
|
2370
|
+
}
|
|
2371
|
+
console.log(`[zcodepro] 转发器巡检:headroom 有端口不在监听(${hrDown.map((x) => `127.0.0.1:${x.port}`).join('、')}),让 headroom 补起`);
|
|
2372
|
+
const hook = typeof ctx.headroomHook === 'function' ? ctx.headroomHook : runHeadroomHook;
|
|
2373
|
+
const r = await hook(['ensure'], 60000).catch((err) => ({ ok: false, error: String(err?.message || err) }));
|
|
2374
|
+
if (r && r.ok === false) console.error(`[zcodepro] 转发器巡检:headroom 补起失败(${r.error || r.code || '未知错误'})`);
|
|
2375
|
+
const failed = !r || r.ok === false;
|
|
2376
|
+
writeHealthNotice(ctx.dataRoot, state, hrDown.map((x) => ({
|
|
2377
|
+
type: x.type === 'router' ? 'router' : 'headroom',
|
|
2378
|
+
ports: [x.port],
|
|
2379
|
+
failed,
|
|
2380
|
+
error: (r && (r.error || r.code)) || '',
|
|
2381
|
+
})));
|
|
2382
|
+
return 0;
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
export function startForwarderHealthCheck(state = {}, ctx = {}) {
|
|
923
2386
|
if (!state || typeof state !== 'object') return;
|
|
924
|
-
if (state.
|
|
925
|
-
state.
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
2387
|
+
if (state.forwarderHealthBy === HELPER_INSTANCE) return;
|
|
2388
|
+
state.forwarderHealthBy = HELPER_INSTANCE;
|
|
2389
|
+
forwarderHealthTimer = setInterval(() => { void runForwarderHealthCheck(state, ctx); }, FORWARDER_HEALTH_MS);
|
|
2390
|
+
forwarderHealthTimer.unref?.();
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
export function stopForwarderHealthCheck() {
|
|
2394
|
+
if (forwarderHealthTimer) { try { clearInterval(forwarderHealthTimer); } catch { /* 已清 */ } }
|
|
2395
|
+
forwarderHealthTimer = null;
|
|
2396
|
+
}
|
|
2397
|
+
|
|
2398
|
+
// 命令行还原(zcode-pro restore):zcode-pro 整个挂了、设置界面里点不到总开关时用。
|
|
2399
|
+
// 做四件事:
|
|
2400
|
+
// 1. 总开关关掉并落盘——还在跑的 helper(如果有)下一轮对齐就不会再接管
|
|
2401
|
+
// 2. 链上供应商的本机地址(链端口、8787)还原成真实上游;不在链上但地址还指着
|
|
2402
|
+
// zcode-pro 转发端口的一并还原
|
|
2403
|
+
// 3. 清 headroom 登记里的 chainTarget(否则实例会把压缩结果发给已经不听的转发器)
|
|
2404
|
+
// 4. 让 headroom 按直连重新分组(实例重启要十几秒,期间经 8787 的请求会失败)
|
|
2405
|
+
// 不停转发器:它们在 helper 进程里,这里够不着;总开关关掉后 helper 的下一轮对齐会停。
|
|
2406
|
+
// 只是接入了 headroom、没进过链的供应商不动。
|
|
2407
|
+
// 返回退出码:0 全部还原,1 有供应商找不到真实上游
|
|
2408
|
+
export async function restoreProvidersCli({
|
|
2409
|
+
dataRoot = resolveDataRootDir(), configFile = join(resolveDataRootDir(), 'zcodepro.json'), hook = true,
|
|
2410
|
+
} = {}) {
|
|
2411
|
+
let chains = [];
|
|
2412
|
+
let switchOff = false;
|
|
2413
|
+
try {
|
|
2414
|
+
withConfigLockSync(configFile, () => {
|
|
2415
|
+
const fresh = loadConfig(configFile);
|
|
2416
|
+
if (configUnreadable) return;
|
|
2417
|
+
chains = Array.isArray(fresh.proxyChains) ? fresh.proxyChains : [];
|
|
2418
|
+
fresh.proxyChainEnabled = false;
|
|
2419
|
+
switchOff = saveConfig(configFile, fresh);
|
|
2420
|
+
});
|
|
2421
|
+
} catch { /* 锁拿不到也继续还原地址 */ }
|
|
2422
|
+
const members = restoreChainMembersToReal({ dataRoot, chains, forwardPorts: true });
|
|
2423
|
+
const cleared = shutdownProxyChainRouting({ dataRoot, configFile });
|
|
2424
|
+
let headroom = 'skipped';
|
|
2425
|
+
if (hook && (cleared.chainTargets > 0 || members.restored > 0)) {
|
|
2426
|
+
const r = await runHeadroomHook(['ensure'], 60000).catch((err) => ({ ok: false, error: String(err?.message || err) }));
|
|
2427
|
+
headroom = r.ok ? 'ok' : `failed(${r.error || r.code || '未知错误'})`;
|
|
2428
|
+
}
|
|
2429
|
+
console.log('[zcodepro] 供应商地址还原:'
|
|
2430
|
+
+ `总开关${switchOff ? '已关' : '未能写入(配置文件读不了)'},`
|
|
2431
|
+
+ `chainTarget 清掉 ${cleared.chainTargets} 个,`
|
|
2432
|
+
+ `地址还原 ${members.restored + cleared.baseUrls} 个`
|
|
2433
|
+
+ (members.stuck.length ? `,${members.stuck.length} 个找不到真实上游:${members.stuck.join('、')}` : '')
|
|
2434
|
+
+ `;headroom 重新分组 ${headroom}`);
|
|
2435
|
+
if (members.stuck.length) console.error('[zcodepro] 以上供应商的地址还指着本机端口,请手动改回真实地址');
|
|
2436
|
+
return members.stuck.length ? 1 : 0;
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
// 盯住两个官方供应商配置文件:用户在 ZCode 界面里新增/删除/改地址(或切换模型)
|
|
2440
|
+
// 时重新对齐转发器。fs.watch 每个文件只占一个 inotify watch;官方写这两个文件很
|
|
2441
|
+
// 频繁(切模型也会写),所以必须防抖,否则一次操作会触发多轮对齐。
|
|
2442
|
+
// 我们自己的写入也会触发,但链对齐幂等:没有实际变化就不写盘,不会自己刷自己。
|
|
2443
|
+
function watchProviderConfigs({ dataRoot, configFile, state }) {
|
|
2444
|
+
// 同一个模块实例只注册一次;热替换后的新实例重新注册(旧实例的在 dispose 里关)
|
|
2445
|
+
if (!state || typeof state !== 'object' || state.providerProxyWatchBy === HELPER_INSTANCE) return;
|
|
2446
|
+
state.providerProxyWatchBy = HELPER_INSTANCE;
|
|
2447
|
+
let timer = null;
|
|
2448
|
+
const schedule = () => {
|
|
2449
|
+
if (timer) clearTimeout(timer);
|
|
2450
|
+
timer = setTimeout(() => {
|
|
2451
|
+
timer = null;
|
|
2452
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'watch' }).catch(() => { /* 尽力而为 */ });
|
|
2453
|
+
}, 1500);
|
|
2454
|
+
timer.unref?.();
|
|
2455
|
+
};
|
|
2456
|
+
// 盯 v2 目录而不是盯这两个文件:对齐自己写它们用的是“临时文件 + 改名”,
|
|
2457
|
+
// 挂在被替换掉的旧文件上的监听只收到一次事件就永久失效了——ZCode 自己保存时
|
|
2458
|
+
// 也是改名写法,所以以前这个监听在第一次改写之后其实一直是死的。
|
|
2459
|
+
// 目录监听不受文件替换影响,按文件名过滤
|
|
2460
|
+
try {
|
|
2461
|
+
const w = watch(join(dataRoot, 'v2'), { persistent: false }, (_ev, filename) => {
|
|
2462
|
+
const name = String(filename || '');
|
|
2463
|
+
if (name && name !== 'config.json' && name !== 'provider_config.json') return;
|
|
2464
|
+
schedule();
|
|
2465
|
+
});
|
|
2466
|
+
w.on('error', () => { /* 目录被删时停止监听,下次启动再挂 */ });
|
|
2467
|
+
providerProxyWatchers.push(w);
|
|
2468
|
+
state.providerProxyWatchers = providerProxyWatchers;
|
|
2469
|
+
} catch { /* 目录还不存在:等它出现后下次启动再挂 */ }
|
|
930
2470
|
}
|
|
931
2471
|
|
|
932
2472
|
// ProxyServer 的值有两种写法:host:port,或 http=host:port;https=host:port。
|
|
@@ -995,6 +2535,54 @@ function proxyUrlFor(scope) {
|
|
|
995
2535
|
// 智能起名诊断日志:追加到 <dataRoot>/zcodepro.log(与启动诊断同文件),超 512KB
|
|
996
2536
|
// 轮转 .old。起名过程注入侧静默(失败不打扰用户),出问题时靠这里回查
|
|
997
2537
|
let titleGenLogRotated = false;
|
|
2538
|
+
// 任务名生成失败的右下角提示(页面轮询到后弹卡片,见 proxy-chain-notice.js)。
|
|
2539
|
+
// 同一个失败(供应商 + 模型 + 报错)24 小时内只写一次,之后还在失败就再提醒一次。
|
|
2540
|
+
// 返回这次有没有写(导出以便测试)
|
|
2541
|
+
export function noteTitleGenFailure(state, dataRoot, { providerId = '', providerName = '', model = '', error = '' } = {}) {
|
|
2542
|
+
const errText = titleGenErrorText(String(error || ''));
|
|
2543
|
+
const key = `${String(providerId || '')}|${String(model || '')}|${errText.slice(0, 200)}`;
|
|
2544
|
+
if (!dataRoot) return false;
|
|
2545
|
+
const file = join(dataRoot, 'title-gen-notice.json');
|
|
2546
|
+
if (recentNotice(file, key).repeat) return false;
|
|
2547
|
+
try {
|
|
2548
|
+
writeJsonAtomic(file, {
|
|
2549
|
+
at: new Date().toISOString(),
|
|
2550
|
+
kind: 'title-gen',
|
|
2551
|
+
key,
|
|
2552
|
+
providerId: String(providerId || ''),
|
|
2553
|
+
providerName: String(providerName || ''),
|
|
2554
|
+
model: String(model || ''),
|
|
2555
|
+
error: errText.slice(0, 400),
|
|
2556
|
+
});
|
|
2557
|
+
return true;
|
|
2558
|
+
} catch { return false; }
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// 报错原文形如“HTTP 400 [model=x]: {"error":{"message":"…"}}”:状态那一段留着,
|
|
2562
|
+
// 再把服务端返回的 message 取出来接在后面,卡片上一眼能看出原因。不是 JSON 就原样返回
|
|
2563
|
+
export function titleGenErrorText(msg) {
|
|
2564
|
+
const s = String(msg || '');
|
|
2565
|
+
const i = s.indexOf('{');
|
|
2566
|
+
if (i > 0) {
|
|
2567
|
+
try {
|
|
2568
|
+
const j = JSON.parse(s.slice(i));
|
|
2569
|
+
const m = (j && j.error && typeof j.error === 'object' && j.error.message) || (j && j.message) || (j && typeof j.error === 'string' ? j.error : '');
|
|
2570
|
+
if (typeof m === 'string' && m.trim()) return `${s.slice(0, i).trim()} ${m.trim()}`;
|
|
2571
|
+
} catch { /* 不是 JSON */ }
|
|
2572
|
+
}
|
|
2573
|
+
return s;
|
|
2574
|
+
}
|
|
2575
|
+
|
|
2576
|
+
// 任务名用的供应商在界面上的名字。跟随会话时返回空串(卡片上换成“会话用的供应商”)
|
|
2577
|
+
function titleGenProviderName(providerId) {
|
|
2578
|
+
const id = String(providerId || '').trim();
|
|
2579
|
+
if (!id || id === 'session') return '';
|
|
2580
|
+
try {
|
|
2581
|
+
const hit = listTitleGenProviders().find((p) => p.id === id);
|
|
2582
|
+
return String((hit && hit.name) || id);
|
|
2583
|
+
} catch { return id; }
|
|
2584
|
+
}
|
|
2585
|
+
|
|
998
2586
|
function titleGenLog(dataRoot, line) {
|
|
999
2587
|
try {
|
|
1000
2588
|
const file = join(dataRoot, 'zcodepro.log');
|
|
@@ -1073,6 +2661,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1073
2661
|
activeProxyUrl = String(bootConfig.proxy || '').trim();
|
|
1074
2662
|
activeProxyScopes = { ...bootConfig.proxyScopes };
|
|
1075
2663
|
activeHeadroomProxy = String(bootConfig.headroomProxy || '').trim();
|
|
2664
|
+
activePromptInjection = mergePromptInjection(bootConfig.promptInjection);
|
|
1076
2665
|
|
|
1077
2666
|
const server = createServer(async (req, res) => {
|
|
1078
2667
|
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
|
@@ -1249,8 +2838,31 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1249
2838
|
}
|
|
1250
2839
|
activeProxyScopes = { ...current.proxyScopes };
|
|
1251
2840
|
}
|
|
1252
|
-
//
|
|
1253
|
-
//
|
|
2841
|
+
// providerProxies(旧的逐家转发,界面已不再提交):单条提交,只改自己那条。
|
|
2842
|
+
// 开着的条目不会再拉起转发,对齐时会被转成“代理 → 代理链”里的勾选
|
|
2843
|
+
// 共享代理列表:整表覆盖(界面里增删改都提交全量),按 mergeSharedProxies 校验
|
|
2844
|
+
if (body && typeof body === 'object' && Array.isArray(body.sharedProxies)) {
|
|
2845
|
+
const before = current.sharedProxies || [];
|
|
2846
|
+
const after = mergeSharedProxies(body.sharedProxies);
|
|
2847
|
+
if (after.length !== body.sharedProxies.length) {
|
|
2848
|
+
json(res, 400, { ok: false, code: 'shared-proxy-invalid', error: '共享代理有无效项:名称不能为空,地址需形如 http://127.0.0.1:7890,id 不能重复' });
|
|
2849
|
+
return;
|
|
2850
|
+
}
|
|
2851
|
+
current.sharedProxies = after;
|
|
2852
|
+
// 删掉的共享代理要被各处引用一并清掉,否则转发器解析不到地址
|
|
2853
|
+
const alive = new Set(after.map((e) => e.id));
|
|
2854
|
+
const gone = before.map((e) => e.id).filter((id) => !alive.has(id));
|
|
2855
|
+
if (gone.length) {
|
|
2856
|
+
const table = { ...(current.providerProxies || {}) };
|
|
2857
|
+
let touched = false;
|
|
2858
|
+
for (const [pid, entry] of Object.entries(table)) {
|
|
2859
|
+
if (!entry || !Array.isArray(entry.nodes)) continue;
|
|
2860
|
+
const kept = entry.nodes.filter((n) => !(n && n.proxyId && gone.includes(n.proxyId)));
|
|
2861
|
+
if (kept.length !== entry.nodes.length) { table[pid] = { ...entry, nodes: kept }; touched = true; }
|
|
2862
|
+
}
|
|
2863
|
+
if (touched) current.providerProxies = table;
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
1254
2866
|
if (body && typeof body === 'object' && body.providerProxies && typeof body.providerProxies === 'object') {
|
|
1255
2867
|
const next = { ...(current.providerProxies || {}) };
|
|
1256
2868
|
let bad = null;
|
|
@@ -1260,14 +2872,18 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1260
2872
|
// remove: true = 移除该供应商的代理设置(界面“×”按钮):整条删掉,
|
|
1261
2873
|
// 后面的对齐会把地址改回真实上游并停掉转发
|
|
1262
2874
|
if (v.remove === true) { delete next[id]; continue; }
|
|
1263
|
-
const proxy = typeof v.proxy === 'string' ? v.proxy.trim().slice(0, 300) : '';
|
|
1264
|
-
if (proxy && !/^https?:\/\/\S+:\d+$/.test(proxy)) { bad = { id, error: '代理地址需形如 http://127.0.0.1:7890,或留空跟随全局代理' }; break; }
|
|
1265
2875
|
const port = Number.isFinite(Number(v.port)) && Number(v.port) >= 1024 && Number(v.port) <= 65535
|
|
1266
2876
|
? Math.round(Number(v.port)) : (next[id]?.port || 18731);
|
|
1267
2877
|
const upstream = typeof v.upstream === 'string' ? v.upstream.trim().slice(0, 500)
|
|
1268
2878
|
: (v.upstream === null ? null : (next[id]?.upstream ?? null));
|
|
1269
2879
|
if (upstream !== null && upstream !== '' && !/^https?:\/\/\S+$/.test(upstream)) { bad = { id, error: '上游地址需为 http(s) 网址,或留空' }; break; }
|
|
1270
|
-
|
|
2880
|
+
// nodes 是整条链:传了就整体替换,没传则沿用已有的(避免只改开关时把链清空)
|
|
2881
|
+
const nodes = Array.isArray(v.nodes) ? v.nodes : (v.proxy !== undefined
|
|
2882
|
+
? mergeProxyNodes(null, v.proxy)
|
|
2883
|
+
: (next[id]?.nodes || []));
|
|
2884
|
+
const clean = mergeProxyNodes(nodes, null);
|
|
2885
|
+
if (clean.length !== nodes.length) { bad = { id, error: '代理节点有无效项:地址需形如 http://127.0.0.1:7890' }; break; }
|
|
2886
|
+
next[id] = { enabled: v.enabled === true, port, upstream, nodes: clean };
|
|
1271
2887
|
}
|
|
1272
2888
|
if (bad) {
|
|
1273
2889
|
json(res, 400, { ok: false, code: 'provider-proxy-invalid', error: `供应商 ${bad.id}:${bad.error}` });
|
|
@@ -1285,6 +2901,17 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1285
2901
|
current.headroomProxy = v;
|
|
1286
2902
|
activeHeadroomProxy = v;
|
|
1287
2903
|
}
|
|
2904
|
+
// 提示词注入(设置页“行为 → 全局提示词”下半块):正文只在传了 text 时覆盖,
|
|
2905
|
+
// “也注入子代理”单独提交。正文不设长度上限——截断会造成“保存成功但注入不全”,
|
|
2906
|
+
// 比报错难查得多。注入功能没有启停开关,在代理链里勾选就是唯一开关
|
|
2907
|
+
if (body && typeof body === 'object' && body.promptInjection && typeof body.promptInjection === 'object') {
|
|
2908
|
+
const pi = body.promptInjection;
|
|
2909
|
+
const next = { ...(current.promptInjection || { text: DEFAULT_INJECT_TEXT, subagents: false }) };
|
|
2910
|
+
if (typeof pi.text === 'string') next.text = pi.text;
|
|
2911
|
+
if (typeof pi.subagents === 'boolean') next.subagents = pi.subagents;
|
|
2912
|
+
current.promptInjection = next;
|
|
2913
|
+
activePromptInjection = mergePromptInjection(next);
|
|
2914
|
+
}
|
|
1288
2915
|
// 工具名映射(服务器键名 → 短键名):整表覆盖,按合法键过滤
|
|
1289
2916
|
if (body && typeof body === 'object' && body.toolNameMaps && typeof body.toolNameMaps === 'object') {
|
|
1290
2917
|
current.toolNameMaps = mergeToolNameMaps(body.toolNameMaps);
|
|
@@ -1391,6 +3018,38 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1391
3018
|
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
1392
3019
|
current.titleGen = mergeTitleGenConfig({ ...current.titleGen, ...body.titleGen });
|
|
1393
3020
|
}
|
|
3021
|
+
// 代理链总开关:关=链配置保留但不生效,对齐不接管任何供应商地址
|
|
3022
|
+
// (已有接管会被撤销);开=勾在链上的供应商地址由链接管。独立提交,
|
|
3023
|
+
// 不用跟着链整表走
|
|
3024
|
+
if (body && typeof body === 'object' && typeof body.proxyChainEnabled === 'boolean') {
|
|
3025
|
+
current.proxyChainEnabled = body.proxyChainEnabled;
|
|
3026
|
+
}
|
|
3027
|
+
// OpenCode Go 兼容:独立提交,改了要对齐一次(把开关下发到链转发器)
|
|
3028
|
+
if (body && typeof body === 'object' && typeof body.opencodeGoCompat === 'boolean') {
|
|
3029
|
+
current.opencodeGoCompat = body.opencodeGoCompat;
|
|
3030
|
+
}
|
|
3031
|
+
// 代理链:整表提交(界面里增删改都发全量),按 normalizeChains 校验并归一。
|
|
3032
|
+
// 关联到同一条链的多个供应商共用一份节点配置与一个转发器。
|
|
3033
|
+
if (body && typeof body === 'object' && Array.isArray(body.proxyChains)) {
|
|
3034
|
+
const before = Array.isArray(current.proxyChains) ? current.proxyChains : [];
|
|
3035
|
+
const after = normalizeChains(body.proxyChains, current.sharedProxies);
|
|
3036
|
+
if (after.length !== body.proxyChains.length) {
|
|
3037
|
+
json(res, 400, { ok: false, code: 'proxy-chain-invalid', error: '代理链有无效项:每条链需要 id,节点类型只能是 headroom / inject / 自定义代理,自定义代理地址需形如 http://127.0.0.1:7890' });
|
|
3038
|
+
return;
|
|
3039
|
+
}
|
|
3040
|
+
// 一个供应商只能属于一条链:后出现的链把它从前面的链里摘掉
|
|
3041
|
+
const owner = new Map();
|
|
3042
|
+
for (const c of after) {
|
|
3043
|
+
for (const pid of c.providers) {
|
|
3044
|
+
if (owner.has(pid)) {
|
|
3045
|
+
c.providers = c.providers.filter((x) => x !== pid);
|
|
3046
|
+
} else {
|
|
3047
|
+
owner.set(pid, c.id);
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
current.proxyChains = after;
|
|
3052
|
+
}
|
|
1394
3053
|
// 一次性迁移标记(如别名迁移弹窗的“暂不迁移”):按项合并,只接受布尔值
|
|
1395
3054
|
if (body && typeof body === 'object' && body.migrations && typeof body.migrations === 'object') {
|
|
1396
3055
|
const patch = {};
|
|
@@ -1403,29 +3062,94 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1403
3062
|
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1404
3063
|
return;
|
|
1405
3064
|
}
|
|
1406
|
-
//
|
|
1407
|
-
//
|
|
3065
|
+
// providerProxies(旧的逐家转发)还有提交时也走一遍对齐:开着的旧条目会在
|
|
3066
|
+
// 对齐入口被转成链里的勾选,之后不再生效。发完不管,不拖慢保存响应
|
|
3067
|
+
if (body && typeof body === 'object' && body.providerProxies !== undefined) {
|
|
3068
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'config' }).catch(() => {});
|
|
3069
|
+
}
|
|
3070
|
+
// 代理链变了:重新对齐链转发器 + 把 chainTarget 写进 headroom 登记。
|
|
3071
|
+
// 只动 headroom.json 的 chainTarget 字段,绝不改供应商 baseURL。
|
|
1408
3072
|
if (body && typeof body === 'object'
|
|
1409
|
-
&& (body.
|
|
1410
|
-
|
|
3073
|
+
&& (Array.isArray(body.proxyChains) || typeof body.proxyChainEnabled === 'boolean'
|
|
3074
|
+
|| typeof body.opencodeGoCompat === 'boolean')) {
|
|
3075
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'config' }).catch(() => {});
|
|
3076
|
+
}
|
|
3077
|
+
if (body && typeof body === 'object' && body.promptInjection && typeof body.promptInjection === 'object') {
|
|
3078
|
+
// 注入钩子立即换新的(不用重启转发器);正文为空时钩子原样返回
|
|
3079
|
+
try { getProviderProxyManager(state).setInjector(promptInjector(state)); } catch { /* 单例异常不影响保存 */ }
|
|
3080
|
+
// 哪些供应商经过注入由“代理 → 代理链”里的勾选决定,这里不替供应商开转发。
|
|
3081
|
+
// 链转发器的注入钩子要跟着正文换(有注入节点的链才带钩子),重新对齐一次
|
|
3082
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'config' }).catch(() => { /* 尽力而为 */ });
|
|
1411
3083
|
}
|
|
1412
3084
|
json(res, 200, { ok: true, config: current });
|
|
1413
3085
|
});
|
|
1414
3086
|
return;
|
|
1415
3087
|
}
|
|
3088
|
+
// —— 提示词注入状态(设置页“行为 → 全局提示词”下半块的一行汇总)——
|
|
3089
|
+
if (req.method === 'GET' && url.pathname === '/prompt-injection/status') {
|
|
3090
|
+
const cfg = loadConfig(configFile);
|
|
3091
|
+
const pi = cfg.promptInjection;
|
|
3092
|
+
const enabledIds = enabledProviderIds(dataRoot);
|
|
3093
|
+
let running = [];
|
|
3094
|
+
try { running = getProviderProxyManager(state).status(); } catch { /* 单例异常按空表 */ }
|
|
3095
|
+
const activeCount = countInjectableProviders({
|
|
3096
|
+
config: cfg,
|
|
3097
|
+
enabledIds,
|
|
3098
|
+
livePorts: new Set(running.filter((f) => f.listening).map((f) => f.port)),
|
|
3099
|
+
headroomProviderIds: new Set(
|
|
3100
|
+
(readJsonFile(join(dataRoot, 'headroom.json'))?.providers || [])
|
|
3101
|
+
.map((p) => (p && typeof p.id === 'string' ? p.id : ''))
|
|
3102
|
+
.filter(Boolean),
|
|
3103
|
+
),
|
|
3104
|
+
protectedIds: PROVIDER_PROXY_PROTECTED_IDS,
|
|
3105
|
+
});
|
|
3106
|
+
json(res, 200, {
|
|
3107
|
+
ok: true,
|
|
3108
|
+
chars: (pi.text || '').length,
|
|
3109
|
+
subagents: pi.subagents === true,
|
|
3110
|
+
providers: enabledIds.size, // 已启用的供应商总数
|
|
3111
|
+
active: activeCount, // 其中开着转发、注入能生效的
|
|
3112
|
+
forwarders: running.filter((f) => f.listening).length,
|
|
3113
|
+
injected: state.injectStats ? state.injectStats.count : 0,
|
|
3114
|
+
});
|
|
3115
|
+
return;
|
|
3116
|
+
}
|
|
3117
|
+
// —— 右下角提示:代理链的(地址变了自动退出链、旧的迁移说明)、巡检的、
|
|
3118
|
+
// 任务名生成失败的、工具名检查有文件改不了的,一次请求一起返回,
|
|
3119
|
+
// 页面那边不用为每种提示各轮询一次 ——
|
|
3120
|
+
if (req.method === 'GET' && url.pathname === '/provider-proxies/migration-notice') {
|
|
3121
|
+
json(res, 200, {
|
|
3122
|
+
ok: true,
|
|
3123
|
+
notice: readJsonFile(join(dataRoot, 'proxy-chain-notice.json')) || null,
|
|
3124
|
+
health: readJsonFile(join(dataRoot, 'proxy-health-notice.json')) || null,
|
|
3125
|
+
titleGen: readJsonFile(join(dataRoot, 'title-gen-notice.json')) || null,
|
|
3126
|
+
toolName: readJsonFile(join(dataRoot, 'tool-name-notice.json')) || null,
|
|
3127
|
+
});
|
|
3128
|
+
return;
|
|
3129
|
+
}
|
|
1416
3130
|
// —— 供应商代理状态(设置页“代理 → 供应商代理”二级):转发器实例 + 上次对齐结果 ——
|
|
1417
3131
|
if (req.method === 'GET' && url.pathname === '/provider-proxies/status') {
|
|
1418
3132
|
let forwarders = [];
|
|
1419
3133
|
try { forwarders = getProviderProxyManager(state).status(); } catch { /* 单例异常按空表 */ }
|
|
1420
|
-
json(res, 200, {
|
|
3134
|
+
json(res, 200, {
|
|
3135
|
+
ok: true,
|
|
3136
|
+
forwarders,
|
|
3137
|
+
lastRun: state.providerProxyLastRun || null,
|
|
3138
|
+
// 代理链的对齐结果单独一份:界面「转发端口」读的是这一条,
|
|
3139
|
+
// 和上面按供应商维度的 lastRun 不是同一批数据
|
|
3140
|
+
chainLastRun: state.proxyChainLastRun || null,
|
|
3141
|
+
headroomPort: headroomRouterPort(dataRoot), // 供界面判断上游是否走 headroom
|
|
3142
|
+
// headroom 支持每实例代理时,链首代理才会真正生效(否则界面标"暂不生效")
|
|
3143
|
+
headroomPerProviderProxy: headroomSupportsPerProviderProxy(),
|
|
3144
|
+
});
|
|
1421
3145
|
return;
|
|
1422
3146
|
}
|
|
1423
|
-
// ——
|
|
3147
|
+
// —— 工具名合规检查(设置页“行为 → 运行时”的按钮):扫描并重写服务器键名 ——
|
|
1424
3148
|
if (req.method === 'POST' && url.pathname === '/tool-names/check') {
|
|
1425
3149
|
const body = await readBody(req);
|
|
1426
3150
|
const dryRun = body?.dryRun === true;
|
|
1427
3151
|
try {
|
|
1428
|
-
const r = runToolNameCheck({ dataRoot, configFile, dryRun });
|
|
3152
|
+
const r = runToolNameCheck({ dataRoot, configFile, dryRun, state });
|
|
1429
3153
|
state.toolNameLastRun = r;
|
|
1430
3154
|
json(res, 200, { ok: true, dryRun, scanned: r.scanned, changed: r.changed, warnings: r.warnings, summary: r.summary });
|
|
1431
3155
|
} catch (err) {
|
|
@@ -2000,6 +3724,13 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2000
3724
|
title = await generateTitleWith(cfg, text, dataRoot, sessId, loc);
|
|
2001
3725
|
} catch (err) {
|
|
2002
3726
|
titleGenLog(dataRoot, `generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3727
|
+
// 设置面板的“测试”按钮失败不弹卡片(面板自己会显示报错);自动起名失败才弹
|
|
3728
|
+
if (body?.test !== true) {
|
|
3729
|
+
noteTitleGenFailure(state, dataRoot, {
|
|
3730
|
+
providerId: cfg.provider, model: cfg.model,
|
|
3731
|
+
providerName: titleGenProviderName(cfg.provider), error: String(err?.message || err),
|
|
3732
|
+
});
|
|
3733
|
+
}
|
|
2003
3734
|
throw err; // 交给外层统一 500
|
|
2004
3735
|
}
|
|
2005
3736
|
let written = false;
|
|
@@ -2287,10 +4018,13 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2287
4018
|
const out = {};
|
|
2288
4019
|
if (typeof raw.enabled === 'boolean') out.enabled = raw.enabled;
|
|
2289
4020
|
if (typeof raw.continueText === 'string') out.continueText = raw.continueText.slice(0, 2000);
|
|
2290
|
-
if (raw.maxRetries !== undefined) out.maxRetries = clampInt(raw.maxRetries, 1, 50,
|
|
2291
|
-
|
|
2292
|
-
if (raw.
|
|
2293
|
-
|
|
4021
|
+
if (raw.maxRetries !== undefined) out.maxRetries = clampInt(raw.maxRetries, 1, 50, 10);
|
|
4022
|
+
// 递增倍数允许小数(1.3),不允许小于 1:1 = 不递增
|
|
4023
|
+
if (raw.continueDelayFactor !== undefined) {
|
|
4024
|
+
const f = typeof raw.continueDelayFactor === 'number' ? raw.continueDelayFactor : Number(raw.continueDelayFactor);
|
|
4025
|
+
out.continueDelayFactor = Number.isFinite(f) ? Math.min(10, Math.max(1, Math.round(f * 100) / 100)) : 1.3;
|
|
4026
|
+
}
|
|
4027
|
+
if (raw.continueDelaySec !== undefined) out.continueDelaySec = clampInt(raw.continueDelaySec, 0, 3600, 120);
|
|
2294
4028
|
if (raw.stuckAfterMin !== undefined) out.stuckAfterMin = clampInt(raw.stuckAfterMin, 5, 720, 30);
|
|
2295
4029
|
if (raw.failedAfterMin !== undefined) out.failedAfterMin = clampInt(raw.failedAfterMin, 1, 60, 3);
|
|
2296
4030
|
if (typeof raw.failedAutoFix === 'boolean') out.failedAutoFix = raw.failedAutoFix;
|
|
@@ -2698,6 +4432,39 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2698
4432
|
});
|
|
2699
4433
|
return;
|
|
2700
4434
|
}
|
|
4435
|
+
// —— 还原供应商地址(headroom tab 实例行按钮):把指定供应商改回直连 ——
|
|
4436
|
+
// 动作:headroom 登记删条目(含 chainTarget)、从所有链移出、baseUrl 写回
|
|
4437
|
+
// 能用的最新真实地址(Q1 恢复基准:ZCode 配置已是真实地址就不动,
|
|
4438
|
+
// 否则取链 upstreams / 登记的 origBaseURL 中可用的)
|
|
4439
|
+
if (req.method === 'POST' && url.pathname === '/headroom/restore') {
|
|
4440
|
+
const body = await readBody(req);
|
|
4441
|
+
const ids = Array.isArray(body?.ids) ? body.ids.filter((x) => typeof x === 'string') : [];
|
|
4442
|
+
if (!ids.length || ids.length > 64) {
|
|
4443
|
+
json(res, 400, { ok: false, code: 'headroom-restore', error: 'ids 必须是 1~64 个供应商 id' });
|
|
4444
|
+
return;
|
|
4445
|
+
}
|
|
4446
|
+
// mode:direct=退链+删登记+直连真实地址(默认);chain=保留在链上,
|
|
4447
|
+
// 只把 baseUrl 拨回链拓扑要求的入口(登记不动——删了 8787 会拒绝它)
|
|
4448
|
+
const mode = body?.mode === 'chain' ? 'chain' : 'direct';
|
|
4449
|
+
try {
|
|
4450
|
+
if (mode === 'chain') {
|
|
4451
|
+
// 地址归位:走一轮链对齐,applyChainEntryAddresses 会把在链供应商的
|
|
4452
|
+
// baseUrl 纠正到链入口(8787 或链端口,按链拓扑)
|
|
4453
|
+
const r = await ensureProxyChains({ dataRoot, configFile, state, reason: 'restore-chain' });
|
|
4454
|
+
json(res, 200, { ok: true, mode, aligned: r.started.length });
|
|
4455
|
+
return;
|
|
4456
|
+
}
|
|
4457
|
+
const r = restoreProviders({ dataRoot, configFile, ids });
|
|
4458
|
+
if (r.error) { json(res, 500, { ok: false, code: 'headroom-restore', error: r.error }); return; }
|
|
4459
|
+
// 地址与登记都变了:链对齐(会停没人用的转发器)+ headroom 分组刷新
|
|
4460
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'restore' }).catch(() => { /* 尽力而为 */ });
|
|
4461
|
+
runHeadroomHook(['ensure'], 30000).catch(() => { /* 尽力而为 */ });
|
|
4462
|
+
json(res, 200, { ok: true, ...r });
|
|
4463
|
+
} catch (err) {
|
|
4464
|
+
json(res, 500, { ok: false, code: 'headroom-restore', error: String(err?.message || err) });
|
|
4465
|
+
}
|
|
4466
|
+
return;
|
|
4467
|
+
}
|
|
2701
4468
|
if (req.method === 'POST' && url.pathname === '/headroom') {
|
|
2702
4469
|
const body = await readBody(req);
|
|
2703
4470
|
const file = defaultHeadroomFile();
|
|
@@ -2838,6 +4605,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2838
4605
|
child.unref();
|
|
2839
4606
|
} catch { /* 拉不起来就只能等下次手动重启 */ }
|
|
2840
4607
|
setTimeout(() => {
|
|
4608
|
+
// 转发器随本进程死掉:先清 chainTarget / 还原链端口 baseUrl,
|
|
4609
|
+
// 否则交接窗口(新进程启动 + 4 秒后才对齐)里链上请求全部 502,
|
|
4610
|
+
// 新进程起不来就一直断到下一次会话启动钩子
|
|
4611
|
+
try { shutdownProxyChainRouting({ dataRoot, configFile }); } catch { /* 尽力而为 */ }
|
|
2841
4612
|
try { dispose(); } catch { /* ignore */ } // 收掉残留 ffmpeg 子进程,防孤儿与新实例抢写缓存
|
|
2842
4613
|
process.exit(0);
|
|
2843
4614
|
}, 250);
|
|
@@ -2957,7 +4728,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2957
4728
|
// 不同 direction 串行排队
|
|
2958
4729
|
const r = await enqueueSyncRun(direction, async () => {
|
|
2959
4730
|
const cfg = loadConfig(configFile);
|
|
2960
|
-
return runSettingsSync({ direction, dataRoot, configFile, config: cfg, proxyUrl: proxyUrlFor('sync') });
|
|
4731
|
+
return runSettingsSync({ direction, dataRoot, configFile, config: cfg, proxyUrl: proxyUrlFor('sync'), state });
|
|
2961
4732
|
});
|
|
2962
4733
|
if (r.error) {
|
|
2963
4734
|
json(res, r.status || 500, { ok: false, code: r.code || 'sync-run', error: r.error });
|
|
@@ -3040,7 +4811,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
3040
4811
|
}
|
|
3041
4812
|
const kind = file.startsWith('model') ? 'model' : 'zcodepro';
|
|
3042
4813
|
sync.lastPullAt = Date.now();
|
|
3043
|
-
const r = applySyncDocs({ docs: { [kind]: remote.doc.data }, dataRoot, configFile, config, sync });
|
|
4814
|
+
const r = applySyncDocs({ docs: { [kind]: remote.doc.data }, dataRoot, configFile, config, sync, state });
|
|
3044
4815
|
if (r && r.error) {
|
|
3045
4816
|
json(res, r.status || 500, { ok: false, code: r.code, error: r.error });
|
|
3046
4817
|
return;
|
|
@@ -3124,7 +4895,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
3124
4895
|
tasksCountCache = await countTasks(dataRoot);
|
|
3125
4896
|
}
|
|
3126
4897
|
global.tasks = tasksCountCache;
|
|
3127
|
-
|
|
4898
|
+
// 上下文构成:会话项“上下文”的悬停提示显示工具定义占了多少(约值)
|
|
4899
|
+
const ctxShape = sessionId ? sessionCtxShape(dataRoot, sessionId) : null;
|
|
4900
|
+
json(res, 200, { ok: true, global, recentTurns, ...(mu ? { sessionSummary: mu.summary } : {}), ...(ctxShape ? { ctxShape } : {}) });
|
|
3128
4901
|
return;
|
|
3129
4902
|
}
|
|
3130
4903
|
// —— 每轮用量(turn-usage.js):优先官方 turn_usage 每轮汇总,没有这张表时
|
|
@@ -3213,8 +4986,17 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
3213
4986
|
// 服务就绪即安排 headroom 代理兜底(内部延迟 5 秒执行,避开启动高峰)
|
|
3214
4987
|
server.listen(port, '127.0.0.1', () => {
|
|
3215
4988
|
ensureHeadroomAtStartup(state);
|
|
3216
|
-
ensureProviderProxiesAtStartup(state, { dataRoot, configFile });
|
|
3217
4989
|
ensureToolNamesAtStartup(state, { dataRoot, configFile });
|
|
4990
|
+
// 启动后对齐一次(延迟 4 秒,避开启动高峰)。这是唯一的对齐入口:
|
|
4991
|
+
// 旧的逐家转发并入代理链也在这一步完成
|
|
4992
|
+
{
|
|
4993
|
+
const t = setTimeout(() => {
|
|
4994
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'startup' }).catch(() => { /* 失败不影响启动 */ });
|
|
4995
|
+
}, 4000);
|
|
4996
|
+
t.unref?.();
|
|
4997
|
+
}
|
|
4998
|
+
startForwarderHealthCheck(state, { dataRoot, configFile });
|
|
4999
|
+
watchProviderConfigs({ dataRoot, configFile, state });
|
|
3218
5000
|
resolveStarted(server);
|
|
3219
5001
|
});
|
|
3220
5002
|
};
|
|
@@ -3252,6 +5034,13 @@ let rolloutRecsCache = null;
|
|
|
3252
5034
|
let statsResultCache = { sig: '', key: '', result: null };
|
|
3253
5035
|
// 供启动器热替换前调用:旧模块实例被 ESM 模块表永久持有,清掉大块缓存省内存
|
|
3254
5036
|
export function dispose() {
|
|
5037
|
+
// 本实例注册的配置文件监听先关:回调闭包指向的是本实例的代码,不关的话热替换后
|
|
5038
|
+
// 配置文件一变仍会跑旧代码(新实例在 startHelper 里注册自己的监听)
|
|
5039
|
+
for (const w of providerProxyWatchers) {
|
|
5040
|
+
try { w.close(); } catch { /* 已失效 */ }
|
|
5041
|
+
}
|
|
5042
|
+
providerProxyWatchers = [];
|
|
5043
|
+
stopForwarderHealthCheck(); // 本实例的转发器巡检定时器
|
|
3255
5044
|
usageFileCache.clear();
|
|
3256
5045
|
rolloutRecsCache = null; // 合并后的全量记录数组(可达十万级),不留
|
|
3257
5046
|
rolloutSig = '';
|
|
@@ -3266,6 +5055,86 @@ export function dispose() {
|
|
|
3266
5055
|
// 热替换后新实例继续用同一批转发器(端口不变、不断线);进程退出时它们
|
|
3267
5056
|
// 随进程一起结束,不留孤儿。
|
|
3268
5057
|
}
|
|
5058
|
+
|
|
5059
|
+
// 真正退出前清理代理链路由(启动器的 SIGINT/SIGTERM/“ZCode 已退出”路径调用,
|
|
5060
|
+
// 不是 dispose:dispose 在热替换时也会被调,那时转发器还活着、不该清)。
|
|
5061
|
+
// 必须同步:调用点在 process.exit(0) 前面,异步写会来不及落盘。
|
|
5062
|
+
//
|
|
5063
|
+
// 清两样:
|
|
5064
|
+
// 1. headroom.json 里全部 chainTarget——转发器随本进程死掉,登记若还指着
|
|
5065
|
+
// 那个端口,headroom 实例会把请求发到死端口上,所有经 8787 的供应商全部 502
|
|
5066
|
+
// (用户切原生 ZCode 也一样断,原生进程里没有我们的转发器)
|
|
5067
|
+
// 2. provider_config.json 里 baseUrl 指着链端口的供应商——还原成链里记录的
|
|
5068
|
+
// 真实上游,否则同样指着死端口
|
|
5069
|
+
// 下次启动 ZCode Pro 时 ensureProxyChains 会按链配置重新写入,不影响功能。
|
|
5070
|
+
export function shutdownProxyChainRouting({ dataRoot, configFile } = {}) {
|
|
5071
|
+
try {
|
|
5072
|
+
if (!dataRoot) return { chainTargets: 0, baseUrls: 0 };
|
|
5073
|
+
// 链端口与上游还原表:从 zcodepro.json 读
|
|
5074
|
+
const cfg = configFile ? (() => { try { return JSON.parse(readFileSync(configFile, 'utf8')); } catch { return null; } })() : null;
|
|
5075
|
+
const chains = Array.isArray(cfg?.proxyChains) ? cfg.proxyChains : [];
|
|
5076
|
+
const providerProxies = (cfg && cfg.providerProxies && typeof cfg.providerProxies === 'object') ? cfg.providerProxies : {};
|
|
5077
|
+
const chainPorts = new Set();
|
|
5078
|
+
const upstreamOf = new Map(); // providerId → 真实上游
|
|
5079
|
+
for (const c of chains) {
|
|
5080
|
+
const p = Number(c?.port);
|
|
5081
|
+
if (Number.isFinite(p) && p >= 1024 && p <= 65535) chainPorts.add(Math.round(p));
|
|
5082
|
+
if (c?.upstreams && typeof c.upstreams === 'object') {
|
|
5083
|
+
for (const [pid, u] of Object.entries(c.upstreams)) {
|
|
5084
|
+
if (typeof u !== 'string' || !/^https?:\/\/\S+$/i.test(u.trim())) continue;
|
|
5085
|
+
// 剥掉端点尾巴(理由同 chainUpstreamForProvider):带着尾巴直接写回 ZCode 会 404
|
|
5086
|
+
const normalized = normalizeUpstreamUrl(u);
|
|
5087
|
+
if (normalized) upstreamOf.set(pid, normalized);
|
|
5088
|
+
}
|
|
5089
|
+
}
|
|
5090
|
+
}
|
|
5091
|
+
let ct = 0;
|
|
5092
|
+
let bu = 0;
|
|
5093
|
+
// 1) 清 headroom.json 的 chainTarget
|
|
5094
|
+
const hrFile = join(dataRoot, 'headroom.json');
|
|
5095
|
+
try {
|
|
5096
|
+
const doc = JSON.parse(readFileSync(hrFile, 'utf8'));
|
|
5097
|
+
if (Array.isArray(doc?.providers)) {
|
|
5098
|
+
for (const p of doc.providers) {
|
|
5099
|
+
if (p && typeof p.chainTarget === 'string') { delete p.chainTarget; ct += 1; }
|
|
5100
|
+
}
|
|
5101
|
+
if (ct) atomicWriteJson(hrFile, doc);
|
|
5102
|
+
}
|
|
5103
|
+
} catch { /* 读不到/写不进:退出路径上尽力而为 */ }
|
|
5104
|
+
// 2) 还原指向链端口的 baseUrl
|
|
5105
|
+
try {
|
|
5106
|
+
const pcFile = join(dataRoot, 'v2', 'provider_config.json');
|
|
5107
|
+
const pc = JSON.parse(readFileSync(pcFile, 'utf8'));
|
|
5108
|
+
const rules = pc?.config?.providerConfigRules?.providerRules;
|
|
5109
|
+
if (Array.isArray(rules)) {
|
|
5110
|
+
for (const r of rules) {
|
|
5111
|
+
if (!r || typeof r.providerId !== 'string') continue;
|
|
5112
|
+
const cur = r.config?.api?.baseUrl;
|
|
5113
|
+
const m = typeof cur === 'string' ? /^http:\/\/127\.0\.0\.1:(\d{4,5})\/?$/i.exec(cur.trim()) : null;
|
|
5114
|
+
if (!m || !chainPorts.has(Number(m[1]))) continue;
|
|
5115
|
+
const up = upstreamOf.get(r.providerId);
|
|
5116
|
+
if (!up) continue; // 没记录还原不了:宁可留着(下次启动对齐会处理)
|
|
5117
|
+
// 链记录的端口可能正好是某家供应商代理的转发端口(停用的链留着旧端口,
|
|
5118
|
+
// 数值落在同一段里)。这家供应商不在该链成员里时,这个地址是供应商代理
|
|
5119
|
+
// 写的,不是链写的:还原它等于让这家绕过转发器(不压缩、不注入)。
|
|
5120
|
+
// 链成员不豁免——退出后转发器会死,成员地址必须离开链端口
|
|
5121
|
+
const port = Number(m[1]);
|
|
5122
|
+
const pp = providerProxies[r.providerId];
|
|
5123
|
+
const explainedByProxy = !!(pp && pp.enabled === true && Number(pp.port) === port);
|
|
5124
|
+
const memberOfChain = chains.some((c) => Math.round(Number(c?.port)) === port
|
|
5125
|
+
&& Array.isArray(c?.providers) && c.providers.includes(r.providerId));
|
|
5126
|
+
if (explainedByProxy && !memberOfChain) continue;
|
|
5127
|
+
r.config.api.baseUrl = up;
|
|
5128
|
+
bu += 1;
|
|
5129
|
+
}
|
|
5130
|
+
if (bu) { backupV2File(pcFile); atomicWriteJson(pcFile, pc); }
|
|
5131
|
+
}
|
|
5132
|
+
} catch { /* 同上 */ }
|
|
5133
|
+
return { chainTargets: ct, baseUrls: bu };
|
|
5134
|
+
} catch {
|
|
5135
|
+
return { chainTargets: 0, baseUrls: 0 };
|
|
5136
|
+
}
|
|
5137
|
+
}
|
|
3269
5138
|
// 解析一段 rollout 文本为记录;completeBytes = 已完整解析的整行字节数
|
|
3270
5139
|
//(末行若是不完整 JSON(写入中途)不计入,调用方据此决定偏移推进量)
|
|
3271
5140
|
function parseRolloutLines(text) {
|
|
@@ -3522,6 +5391,73 @@ function readJsonFile(p) {
|
|
|
3522
5391
|
}
|
|
3523
5392
|
}
|
|
3524
5393
|
|
|
5394
|
+
// —— 上下文构成估算(状态栏“上下文”项的悬停提示) ————
|
|
5395
|
+
// 官方 composition 接口只在插件里有,注入侧拿不到;这里从该会话的 model-io
|
|
5396
|
+
// 记录里量“请求一共多大”,拆出工具定义部分。记录每行一次模型调用,request.body.tools
|
|
5397
|
+
// 是这次请求带的全部工具定义(几十万字符),request.messages 只记尾部窗口。
|
|
5398
|
+
// 用法:读末条记录的 tools 与 messages 字符量,按中日韩 1 字符/token、其它
|
|
5399
|
+
// 2.6 字符/token 折算(对本机 29 条真实记录校准过,中位数与官方 inputTokens 偏差
|
|
5400
|
+
// 约 33% 偏低——没算进系统提示词与 MCP 之外的部分,所以只按“约占”展示)。
|
|
5401
|
+
const CTX_CJK_RE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uff00-\uffef]/g;
|
|
5402
|
+
function estTokensFromChars(text) {
|
|
5403
|
+
const cjk = (text.match(CTX_CJK_RE) || []).length;
|
|
5404
|
+
return Math.round(cjk / 1 + (text.length - cjk) / 2.6);
|
|
5405
|
+
}
|
|
5406
|
+
// model-io 文件名由会话 id 归一:非字母数字下划线连字符换成 -(官方同款规则)
|
|
5407
|
+
function modelIoPath(dir, sessionId) {
|
|
5408
|
+
const seg = String(sessionId).replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
|
|
5409
|
+
return seg ? join(dir, `model-io-${seg}.jsonl`) : '';
|
|
5410
|
+
}
|
|
5411
|
+
// 只读文件末尾一段找最后一条完整记录:整文件可有几 MB、几十条记录,
|
|
5412
|
+
// 每条 1 MB 上下,读尾部 4 MB 足够覆盖末条;缓存在文件签名(mtime+size)上
|
|
5413
|
+
const ctxShapeCache = new Map(); // path -> { sig, shape }
|
|
5414
|
+
const CTX_TAIL_BYTES = 4 * 1024 * 1024;
|
|
5415
|
+
function readCtxShape(path) {
|
|
5416
|
+
let st;
|
|
5417
|
+
try { st = statSync(path); } catch { return null; }
|
|
5418
|
+
const sig = `${st.mtimeMs}:${st.size}`;
|
|
5419
|
+
const hit = ctxShapeCache.get(path);
|
|
5420
|
+
if (hit && hit.sig === sig) return hit.shape;
|
|
5421
|
+
let shape = null;
|
|
5422
|
+
try {
|
|
5423
|
+
const start = Math.max(0, st.size - CTX_TAIL_BYTES);
|
|
5424
|
+
const len = st.size - start;
|
|
5425
|
+
const buf = Buffer.alloc(len);
|
|
5426
|
+
const fd = openSync(path, 'r');
|
|
5427
|
+
let read = 0;
|
|
5428
|
+
try { read = readSync(fd, buf, 0, len, start); } finally { closeSync(fd); }
|
|
5429
|
+
const text = buf.subarray(0, read).toString('utf8');
|
|
5430
|
+
// 从尾部往前找能解析的行:末行可能正在写入(半行),最多试 5 条
|
|
5431
|
+
const lines = text.split('\n').filter((l) => l.trim());
|
|
5432
|
+
for (let i = lines.length - 1, tries = 0; i >= 0 && tries < 5; i--, tries++) {
|
|
5433
|
+
let d;
|
|
5434
|
+
try { d = JSON.parse(lines[i]); } catch { continue; }
|
|
5435
|
+
const body = (d.request && d.request.body) || {};
|
|
5436
|
+
const tools = JSON.stringify(body.tools || []);
|
|
5437
|
+
const msgs = JSON.stringify((d.request && d.request.messages) || []);
|
|
5438
|
+
if (!tools.length && !msgs.length) continue;
|
|
5439
|
+
shape = {
|
|
5440
|
+
toolCount: Array.isArray(body.tools) ? body.tools.length : 0,
|
|
5441
|
+
toolsTokens: tools ? estTokensFromChars(tools) : 0,
|
|
5442
|
+
messagesTokens: msgs ? estTokensFromChars(msgs) : 0,
|
|
5443
|
+
model: (d.model && d.model.modelId) || '',
|
|
5444
|
+
};
|
|
5445
|
+
break;
|
|
5446
|
+
}
|
|
5447
|
+
} catch { shape = null; }
|
|
5448
|
+
// 缓存有上限:会话多了别无限涨(每条一个路径)
|
|
5449
|
+
if (ctxShapeCache.size > 200) ctxShapeCache.clear();
|
|
5450
|
+
ctxShapeCache.set(path, { sig, shape });
|
|
5451
|
+
return shape;
|
|
5452
|
+
}
|
|
5453
|
+
// 会话的上下文构成:model-io 文件在 rollout 目录,找不到返回 null
|
|
5454
|
+
function sessionCtxShape(dataRoot, sessionId) {
|
|
5455
|
+
const dir = rolloutDirOverride || join(dataRoot, 'cli', 'rollout');
|
|
5456
|
+
const path = modelIoPath(dir, sessionId);
|
|
5457
|
+
if (!path) return null;
|
|
5458
|
+
return readCtxShape(path);
|
|
5459
|
+
}
|
|
5460
|
+
|
|
3525
5461
|
function clampInt(v, min, max, dflt) {
|
|
3526
5462
|
const n = typeof v === 'number' ? v : Number(v);
|
|
3527
5463
|
if (!Number.isFinite(n)) return dflt;
|
|
@@ -3560,6 +5496,7 @@ function mergeTitleGenConfig(saved) {
|
|
|
3560
5496
|
apiKey: typeof s.apiKey === 'string' ? s.apiKey.trim().slice(0, 500) : d.apiKey,
|
|
3561
5497
|
format: s.format === 'openai' ? 'openai' : s.format === 'anthropic' ? 'anthropic' : '',
|
|
3562
5498
|
recentQa: Number.isFinite(Number(s.recentQa)) ? Math.min(20, Math.max(1, Math.round(Number(s.recentQa)))) : d.recentQa,
|
|
5499
|
+
thinking: isValidThinking(s.thinking) ? s.thinking : 'off',
|
|
3563
5500
|
hoverBtn: s.hoverBtn !== false,
|
|
3564
5501
|
menuEntry: s.menuEntry !== false,
|
|
3565
5502
|
customWritten: written,
|
|
@@ -3578,31 +5515,93 @@ function mergeProxyScopes(saved) {
|
|
|
3578
5515
|
};
|
|
3579
5516
|
}
|
|
3580
5517
|
|
|
3581
|
-
//
|
|
3582
|
-
//
|
|
5518
|
+
// 提示词注入配置归一化:没存过 text 时用默认标题行(不是空串——空串会让
|
|
5519
|
+
// 默认值在每次读盘时被覆盖掉);存过空串就是用户主动清空,保持空。
|
|
5520
|
+
// 正文不设产品层上限(长度交给模型上下文预算),enabled/subagents 只认 true。
|
|
5521
|
+
// 注入功能没有启停设置:勾选(在代理链里)就是唯一开关,这里只看正文和子代理两项。
|
|
5522
|
+
// 旧配置里的 enabled 字段不再读,合并时丢掉,下次保存就不会再写进文件
|
|
5523
|
+
export function mergePromptInjection(saved) {
|
|
5524
|
+
const s = (saved && typeof saved === 'object' && !Array.isArray(saved)) ? saved : {};
|
|
5525
|
+
return {
|
|
5526
|
+
text: typeof s.text === 'string' ? s.text : DEFAULT_INJECT_TEXT,
|
|
5527
|
+
subagents: s.subagents === true,
|
|
5528
|
+
};
|
|
5529
|
+
}
|
|
5530
|
+
|
|
3583
5531
|
// proxy 留空 = 跟随全局代理(解析在运行时按 effectiveProxyUrl() 兜底)。
|
|
3584
5532
|
// upstream 落盘:None 值保留为 null(新机器上 helper 重新补),空串非法丢弃。
|
|
5533
|
+
// nodes 是代理链:数组顺序即执行顺序。目前只有 type:'custom' 一种节点,
|
|
5534
|
+
// 每项要么 { type:'custom', proxy:'http://host:port' }(手填),
|
|
5535
|
+
// 要么 { type:'custom', proxyId:'<sharedProxies 里的 id>' }(引用共享代理,
|
|
5536
|
+
// 地址在共享代理那边改)。两种写法互斥,同时出现以 proxy 为准。
|
|
3585
5537
|
export function mergeProviderProxies(saved) {
|
|
3586
5538
|
const s = (saved && typeof saved === 'object' && !Array.isArray(saved)) ? saved : {};
|
|
3587
5539
|
const out = {};
|
|
3588
5540
|
for (const [id, v] of Object.entries(s)) {
|
|
3589
5541
|
if (typeof id !== 'string' || !id.trim() || !v || typeof v !== 'object' || Array.isArray(v)) continue;
|
|
3590
5542
|
if (id === '__proto__' || id === 'constructor' || id === 'prototype') continue;
|
|
3591
|
-
const proxy = typeof v.proxy === 'string' ? v.proxy.trim().slice(0, 300) : '';
|
|
3592
|
-
if (proxy && !/^https?:\/\/\S+:\d+$/.test(proxy)) continue;
|
|
3593
5543
|
const port = Number.isFinite(Number(v.port)) ? Math.min(65535, Math.max(1024, Math.round(Number(v.port)))) : 18731;
|
|
3594
|
-
const
|
|
3595
|
-
|
|
5544
|
+
const upstreamRaw = typeof v.upstream === 'string' ? v.upstream.trim().slice(0, 500) : null;
|
|
5545
|
+
const upstream = (upstreamRaw && /^https?:\/\/\S+$/.test(upstreamRaw)) ? upstreamRaw : null;
|
|
3596
5546
|
out[id] = {
|
|
3597
5547
|
enabled: v.enabled === true,
|
|
3598
|
-
proxy,
|
|
3599
5548
|
port,
|
|
3600
|
-
upstream
|
|
5549
|
+
upstream,
|
|
5550
|
+
nodes: mergeProxyNodes(v.nodes, v.proxy),
|
|
3601
5551
|
};
|
|
3602
5552
|
}
|
|
3603
5553
|
return out;
|
|
3604
5554
|
}
|
|
3605
5555
|
|
|
5556
|
+
// 代理链节点归一:只收合法项、按原顺序保留、整条链最多 16 项避免无限长。
|
|
5557
|
+
// legacyProxy 是旧版单值字段({ proxy: 'http://...' }):新配置读不到 nodes 时
|
|
5558
|
+
// 退化成只有一个节点的链,保证旧文件仍能工作。
|
|
5559
|
+
export function mergeProxyNodes(nodes, legacyProxy) {
|
|
5560
|
+
const maxCost = /^https?:\/\/\S+:\d+$/;
|
|
5561
|
+
const list = Array.isArray(nodes) ? nodes : null;
|
|
5562
|
+
const out = [];
|
|
5563
|
+
if (list) {
|
|
5564
|
+
for (const n of list) {
|
|
5565
|
+
if (out.length >= 16) break;
|
|
5566
|
+
if (!n || typeof n !== 'object' || Array.isArray(n)) continue;
|
|
5567
|
+
if (n.type !== 'custom') continue;
|
|
5568
|
+
const proxy = typeof n.proxy === 'string' ? n.proxy.trim().slice(0, 300) : '';
|
|
5569
|
+
const proxyId = typeof n.proxyId === 'string' ? n.proxyId.trim().slice(0, 64) : '';
|
|
5570
|
+
// 空节点要保留:界面上点“添加代理”先插一个空位等用户填,
|
|
5571
|
+
// 丢掉会让这次保存被当成“有无效项”直接报错。空节点运行时跳过。
|
|
5572
|
+
if (!proxy && !proxyId) { out.push({ type: 'custom', proxy: '' }); continue; }
|
|
5573
|
+
if (proxy) {
|
|
5574
|
+
if (!maxCost.test(proxy)) continue; // 填了但格式不对:丢弃(前端也会拦)
|
|
5575
|
+
out.push({ type: 'custom', proxy });
|
|
5576
|
+
continue;
|
|
5577
|
+
}
|
|
5578
|
+
out.push({ type: 'custom', proxyId });
|
|
5579
|
+
}
|
|
5580
|
+
return out;
|
|
5581
|
+
}
|
|
5582
|
+
const legacy = typeof legacyProxy === 'string' ? legacyProxy.trim().slice(0, 300) : '';
|
|
5583
|
+
if (legacy && maxCost.test(legacy)) out.push({ type: 'custom', proxy: legacy });
|
|
5584
|
+
return out;
|
|
5585
|
+
}
|
|
5586
|
+
|
|
5587
|
+
// 共享代理列表归一:id 唯一、地址合法、名称非空(缺省用地址兜底)。
|
|
5588
|
+
export function mergeSharedProxies(saved) {
|
|
5589
|
+
const list = Array.isArray(saved) ? saved : [];
|
|
5590
|
+
const seen = new Set();
|
|
5591
|
+
const out = [];
|
|
5592
|
+
for (const e of list) {
|
|
5593
|
+
if (out.length >= 32) break;
|
|
5594
|
+
if (!e || typeof e !== 'object' || Array.isArray(e)) continue;
|
|
5595
|
+
const id = typeof e.id === 'string' ? e.id.trim().slice(0, 64) : '';
|
|
5596
|
+
const url = typeof e.url === 'string' ? e.url.trim().slice(0, 300) : '';
|
|
5597
|
+
if (!id || seen.has(id) || !/^https?:\/\/\S+:\d+$/.test(url)) continue;
|
|
5598
|
+
seen.add(id);
|
|
5599
|
+
const name = typeof e.name === 'string' && e.name.trim() ? e.name.trim().slice(0, 40) : url;
|
|
5600
|
+
out.push({ id, name, url });
|
|
5601
|
+
}
|
|
5602
|
+
return out;
|
|
5603
|
+
}
|
|
5604
|
+
|
|
3606
5605
|
// toolNameMaps 归一:服务器键名 → 短键名;只收合法键(字母/数字/连字符/下划线,
|
|
3607
5606
|
// 长度 ≤ 32,短名 ≤ 24),非法项丢弃。
|
|
3608
5607
|
// 内置默认映射(android-emulator → ae、tencent-docs → td)作为底:文件里存了空对象
|
|
@@ -3883,7 +5882,7 @@ function enqueueSyncRun(direction, fn) {
|
|
|
3883
5882
|
return trackBusy(promise);
|
|
3884
5883
|
}
|
|
3885
5884
|
|
|
3886
|
-
async function runSettingsSync({ direction, dataRoot, configFile, config, proxyUrl }) {
|
|
5885
|
+
async function runSettingsSync({ direction, dataRoot, configFile, config, proxyUrl, state }) {
|
|
3887
5886
|
const sync = config.sync;
|
|
3888
5887
|
if (!sync.url || !/^https?:\/\/\S+$/.test(sync.url)) {
|
|
3889
5888
|
return { code: 'sync-not-configured', status: 400, error: '请先填写 WebDAV URL 并保存' };
|
|
@@ -3896,9 +5895,51 @@ async function runSettingsSync({ direction, dataRoot, configFile, config, proxyU
|
|
|
3896
5895
|
}
|
|
3897
5896
|
return direction === 'push'
|
|
3898
5897
|
? runSyncPush({ dataRoot, configFile, config, sync, proxyUrl })
|
|
3899
|
-
: runSyncPull({ dataRoot, configFile, config, sync, proxyUrl });
|
|
5898
|
+
: runSyncPull({ dataRoot, configFile, config, sync, proxyUrl, state });
|
|
5899
|
+
}
|
|
5900
|
+
|
|
5901
|
+
// headroom 插件是否支持链转发:看它的 hr-multi.mjs 里有没有 chainTarget
|
|
5902
|
+
// (按 chainTarget 分组是链功能的插件侧实现)。与上面的代理探测同理,
|
|
5903
|
+
// 版本号不可靠,直接读脚本内容判断。旧插件拿到 chainTarget 会静默忽略——
|
|
5904
|
+
// 压缩还在、注入和出网代理全丢,用户无从发现,所以 helper 侧必须探测
|
|
5905
|
+
function headroomSupportsChainTarget() {
|
|
5906
|
+
try {
|
|
5907
|
+
const hook = findMarketplaceHook('headroom', join('hooks', 'hr-multi.mjs'));
|
|
5908
|
+
if (!hook) return false;
|
|
5909
|
+
return readFileSync(hook, 'utf8').includes('chainTarget');
|
|
5910
|
+
} catch { return false; }
|
|
3900
5911
|
}
|
|
3901
5912
|
|
|
5913
|
+
// headroom 插件是否支持每实例独立代理:看它的 hr-multi.mjs 里有没有 --http-proxy。
|
|
5914
|
+
// 插件版本号不可靠(同版本也可能没这功能),直接读脚本内容判断。
|
|
5915
|
+
function headroomSupportsPerProviderProxy() {
|
|
5916
|
+
try {
|
|
5917
|
+
const hook = findMarketplaceHook('headroom', join('hooks', 'hr-multi.mjs'));
|
|
5918
|
+
if (!hook) return false;
|
|
5919
|
+
return readFileSync(hook, 'utf8').includes('--http-proxy');
|
|
5920
|
+
} catch { return false; }
|
|
5921
|
+
}
|
|
5922
|
+
|
|
5923
|
+
// 把某供应商的代理链第一级写进 headroom.json 的 providers[].proxy。
|
|
5924
|
+
// headroom 在链上时,请求由 headroom 直接发往上游,我们的转发器碰不到出口,
|
|
5925
|
+
// 只能让 headroom 自己带代理。插件不支持该字段时不写(返回 false,界面据能力提示)。
|
|
5926
|
+
export function applyHeadroomProviderProxy({ dataRoot, providerId, proxyUrl }) {
|
|
5927
|
+
if (!headroomSupportsPerProviderProxy()) return false;
|
|
5928
|
+
const file = join(dataRoot, 'headroom.json');
|
|
5929
|
+
const doc = readJsonFile(file);
|
|
5930
|
+
if (!doc || !Array.isArray(doc.providers)) return false;
|
|
5931
|
+
const hit = doc.providers.find((p) => p && p.id === providerId);
|
|
5932
|
+
if (!hit) return false;
|
|
5933
|
+
const next = typeof proxyUrl === 'string' ? proxyUrl.trim().slice(0, 300) : '';
|
|
5934
|
+
const cur = typeof hit.proxy === 'string' ? hit.proxy.trim() : '';
|
|
5935
|
+
if (cur === next) return true;
|
|
5936
|
+
try {
|
|
5937
|
+
if (next) hit.proxy = next;
|
|
5938
|
+
else delete hit.proxy;
|
|
5939
|
+
writeJsonAtomic(file, doc); // 有备份保护,损坏时不写
|
|
5940
|
+
return true;
|
|
5941
|
+
} catch { return false; }
|
|
5942
|
+
}
|
|
3902
5943
|
// headroom.json 里值得同步/应用的判定:providers 每条注册都得带路由必需的
|
|
3903
5944
|
// id/upstream/format/keyHash 才算有效——空对象、空注册或残缺条目(如只写个 id
|
|
3904
5945
|
// 的测试夹具)不上传也不覆盖,免得把别台机器拉回无映射状态(请求 502)
|
|
@@ -3944,6 +5985,15 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
3944
5985
|
const hr = readJsonFile(defaultHeadroomFile());
|
|
3945
5986
|
if (validHeadroomDoc(hr)) {
|
|
3946
5987
|
const { instances: _inst, router: _router, ...hrSync } = hr;
|
|
5988
|
+
// providers 里的 chainTarget 也剥掉:它指向本机链转发端口(1873x 段),
|
|
5989
|
+
// 到了别的机器就是死端口(那边会按自己的链拓扑在对齐时重新写入)
|
|
5990
|
+
if (Array.isArray(hrSync.providers)) {
|
|
5991
|
+
hrSync.providers = hrSync.providers.map((pr) => {
|
|
5992
|
+
if (!pr || typeof pr.chainTarget !== 'string') return pr;
|
|
5993
|
+
const { chainTarget: _ct, ...rest } = pr;
|
|
5994
|
+
return rest;
|
|
5995
|
+
});
|
|
5996
|
+
}
|
|
3947
5997
|
docs.model.headroom = hrSync;
|
|
3948
5998
|
}
|
|
3949
5999
|
// 注意:v2/credentials.json 不参与同步——里面是账号登录态(BigModel OAuth、
|
|
@@ -4015,7 +6065,7 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
4015
6065
|
// 覆盖前留 .zcodepro-backup 备份;zcodepro 组覆盖功能/样式/代理,别名不受影响
|
|
4016
6066
|
//(3.16.1 起别名已停用,且云端备份里的别名多是其他机器的路径);sync 配置与
|
|
4017
6067
|
// 凭据始终保留本机的
|
|
4018
|
-
async function runSyncPull({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
6068
|
+
async function runSyncPull({ dataRoot, configFile, config, sync, proxyUrl, state }) {
|
|
4019
6069
|
// 先把勾选组的云端数据全部读到(任何一组读取失败都不动本机文件),再逐组应用
|
|
4020
6070
|
const docs = {};
|
|
4021
6071
|
for (const kind of ['zcodepro', 'model']) {
|
|
@@ -4028,7 +6078,7 @@ async function runSyncPull({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
4028
6078
|
return { code: 'sync-remote-missing', status: 404, error: '云端没有同步数据,请先在其他电脑上传' };
|
|
4029
6079
|
}
|
|
4030
6080
|
sync.lastPullAt = Date.now();
|
|
4031
|
-
const applied = await applySyncDocs({ docs, dataRoot, configFile, config, sync });
|
|
6081
|
+
const applied = await applySyncDocs({ docs, dataRoot, configFile, config, sync, state });
|
|
4032
6082
|
if (applied && applied.error) return applied;
|
|
4033
6083
|
// 背景图库镜像下载(勾了 zcodepro 组才拉;设置文档已应用,图库失败单独报错,重试幂等)
|
|
4034
6084
|
let bg = null;
|
|
@@ -4044,7 +6094,7 @@ async function runSyncPull({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
4044
6094
|
// zcodepro 组覆盖功能/样式/代理(sync 配置与凭据保留本机的),别名不导入
|
|
4045
6095
|
//(云端备份可能出自别的机器,路径在本机无效),model 组覆盖 v2/config.json 的
|
|
4046
6096
|
// provider、provider_config.json 与 headroom.json;覆盖前都留备份。导出以便测试。
|
|
4047
|
-
export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
6097
|
+
export function applySyncDocs({ docs, dataRoot, configFile, config, sync, state }) {
|
|
4048
6098
|
const applied = [];
|
|
4049
6099
|
const backupFile = (p) => {
|
|
4050
6100
|
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
@@ -4058,6 +6108,7 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
4058
6108
|
if (docs.zcodepro) {
|
|
4059
6109
|
const rz = docs.zcodepro;
|
|
4060
6110
|
let providerProxiesChanged = false;
|
|
6111
|
+
let chainsSynced = false;
|
|
4061
6112
|
// 整段 zcodepro.json 读改写放进跨进程锁内同步执行(applySyncDocs 是同步
|
|
4062
6113
|
// 调用点,用同步等锁变体),防止与别的写入方互相覆盖整份配置
|
|
4063
6114
|
const rzErr = withConfigLockSync(configFile, () => {
|
|
@@ -4095,6 +6146,28 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
4095
6146
|
if (rz.toolNameMaps && typeof rz.toolNameMaps === 'object' && !Array.isArray(rz.toolNameMaps)) {
|
|
4096
6147
|
next.toolNameMaps = { ...(next.toolNameMaps || {}), ...mergeToolNameMaps(rz.toolNameMaps) };
|
|
4097
6148
|
}
|
|
6149
|
+
// 提示词注入:云端有就用云端的(正文与开关整段覆盖),没有则保留本机
|
|
6150
|
+
if (rz.promptInjection && typeof rz.promptInjection === 'object') {
|
|
6151
|
+
next.promptInjection = mergePromptInjection(rz.promptInjection);
|
|
6152
|
+
}
|
|
6153
|
+
// 代理链与共享代理:云端整段为准(另一台机器上配好的链直接可用),
|
|
6154
|
+
// 云端没有这两个键则保留本机(旧版备份没有链配置时不至于清空)
|
|
6155
|
+
if (Array.isArray(rz.proxyChains)) {
|
|
6156
|
+
const prev = next.proxyChains || [];
|
|
6157
|
+
// 云端链里记录的 upstreams 到本机未必有意义(同 id 供应商才有用),原样带过来
|
|
6158
|
+
next.proxyChains = normalizeChains(rz.proxyChains, rz.sharedProxies || next.sharedProxies || []);
|
|
6159
|
+
chainsSynced = JSON.stringify(next.proxyChains) !== JSON.stringify(prev);
|
|
6160
|
+
}
|
|
6161
|
+
if (Array.isArray(rz.sharedProxies)) {
|
|
6162
|
+
next.sharedProxies = mergeSharedProxies(rz.sharedProxies);
|
|
6163
|
+
}
|
|
6164
|
+
// 代理链总开关跟着链配置走:它是用户设置、与机器无关(上传路径随
|
|
6165
|
+
// zcodepro 组原样带出)。云端没有这个键(旧备份)则保留本机值(默认关)
|
|
6166
|
+
if (typeof rz.opencodeGoCompat === 'boolean') next.opencodeGoCompat = rz.opencodeGoCompat;
|
|
6167
|
+
if (typeof rz.proxyChainEnabled === 'boolean') {
|
|
6168
|
+
if (rz.proxyChainEnabled !== next.proxyChainEnabled) chainsSynced = true;
|
|
6169
|
+
next.proxyChainEnabled = rz.proxyChainEnabled;
|
|
6170
|
+
}
|
|
4098
6171
|
next.sync = { ...next.sync, lastPullAt: sync.lastPullAt }; // 保留本机 sync 配置与凭据,只记本次拉取时间
|
|
4099
6172
|
backupFile(configFile);
|
|
4100
6173
|
if (!saveConfig(configFile, next)) {
|
|
@@ -4104,10 +6177,16 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
4104
6177
|
});
|
|
4105
6178
|
if (rzErr) return rzErr;
|
|
4106
6179
|
applied.push('zcodepro');
|
|
4107
|
-
//
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
6180
|
+
// 提示词注入的正文与子代理选项跟着落进运行时快照,拉完就生效
|
|
6181
|
+
try {
|
|
6182
|
+
activePromptInjection = mergePromptInjection(loadConfig(configFile).promptInjection);
|
|
6183
|
+
getProviderProxyManager().setInjector(promptInjector());
|
|
6184
|
+
} catch { /* 尽力而为 */ }
|
|
6185
|
+
// 工具名映射变了就把短键名打回去。尽力而为,失败不影响同步结果。
|
|
6186
|
+
// 链配置或旧的逐家转发变了(含第一次从云端拿到、云端又带回旧条目):
|
|
6187
|
+
// 对齐一次——起转发器/写 chainTarget/headroom 分组,旧条目在对齐入口转成链里的勾选
|
|
6188
|
+
if (chainsSynced || providerProxiesChanged) {
|
|
6189
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'sync' }).catch(() => { /* 尽力而为 */ });
|
|
4111
6190
|
}
|
|
4112
6191
|
if (rz && rz.toolNameMaps) {
|
|
4113
6192
|
try { runToolNameCheck({ dataRoot, configFile }); } catch { /* 尽力而为 */ }
|
|
@@ -4154,6 +6233,10 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
4154
6233
|
// 只有新上游的实例需要这一步),失败不影响同步结果
|
|
4155
6234
|
runHeadroomHook(['ensure'], 20000).catch(() => { /* 尽力而为 */ });
|
|
4156
6235
|
}
|
|
6236
|
+
// 模型组应用完(baseUrl 可能指 8787/链端口、链配置随 zcodepro 组落地)就触发
|
|
6237
|
+
// 代理链对齐:起链转发器、写 chainTarget、headroom 重新分组。不做的话要等
|
|
6238
|
+
// 下次重启,期间新拉下来的本机地址全是死端口
|
|
6239
|
+
ensureProxyChains({ dataRoot, configFile, state, reason: 'sync' }).catch(() => { /* 尽力而为 */ });
|
|
4157
6240
|
applied.push('model');
|
|
4158
6241
|
}
|
|
4159
6242
|
// 没动 zcodepro.json 时,lastPullAt 也要写入配置文件(动了则已随 next 一起保存)。
|
|
@@ -5035,6 +7118,24 @@ function headroomFormatOf(headroomProviders, providerId) {
|
|
|
5035
7118
|
return f === 'anthropic' || f === 'openai' ? f : '';
|
|
5036
7119
|
}
|
|
5037
7120
|
|
|
7121
|
+
// 供应商“当前生效”的连接字段:provider_config.json 的规则优先,规则里没有的字段
|
|
7122
|
+
// 才回退到 v2/config.json 的 provider 表(旧格式,ZCode 只把它一次性导入规则,
|
|
7123
|
+
// 运行时不再读它)。以前两处各写一份且顺序相反(config.json 优先),两份不一致时
|
|
7124
|
+
// 就会拿到旧地址或旧密钥。rule 是 providerRules 里的一条,legacy 是 config.json
|
|
7125
|
+
// 的 provider.<id>,任一可为空
|
|
7126
|
+
export function providerConnectionFields(rule, legacy) {
|
|
7127
|
+
const r = (rule && typeof rule === 'object') ? rule : {};
|
|
7128
|
+
const c = (r.config && typeof r.config === 'object') ? r.config : {};
|
|
7129
|
+
const p = (legacy && typeof legacy === 'object') ? legacy : {};
|
|
7130
|
+
const pick = (a, b) => ((typeof a === 'string' && a.trim()) ? a : b);
|
|
7131
|
+
return {
|
|
7132
|
+
name: pick(r.providerName, p.name),
|
|
7133
|
+
kind: pick(c.api?.type, p.kind),
|
|
7134
|
+
baseUrl: pick(c.api?.baseUrl, p.options?.baseURL),
|
|
7135
|
+
apiKey: pick(c.access?.apiKey, p.options?.apiKey),
|
|
7136
|
+
};
|
|
7137
|
+
}
|
|
7138
|
+
|
|
5038
7139
|
// 供应商条目(智能起名与视觉代理共用),列表范围与 ZCode 界面的供应商列表
|
|
5039
7140
|
// 保持一致:
|
|
5040
7141
|
// - 内置套餐(builtin:*):有地址、密钥才列出(无密钥的 helper 无法在会话外
|
|
@@ -5178,7 +7279,8 @@ export function listTitleGenProviders() {
|
|
|
5178
7279
|
const dflt = r.defaultVariant === 'disabled' ? 'off' : (r.defaultVariant ? String(r.defaultVariant) : '');
|
|
5179
7280
|
return { variants, defaultVariant: variants.includes(dflt) ? dflt : variants[0] };
|
|
5180
7281
|
};
|
|
5181
|
-
// 同一 id
|
|
7282
|
+
// 同一 id 在两张表的字段并起来:地址/密钥/协议/名称以规则为准,规则没有才用
|
|
7283
|
+
// provider 表(见 providerConnectionFields);模型与档位两张表取并集
|
|
5182
7284
|
const addMerged = (id) => {
|
|
5183
7285
|
const p = providers[id];
|
|
5184
7286
|
if (p !== undefined && (p === null || typeof p !== 'object')) return;
|
|
@@ -5206,12 +7308,13 @@ export function listTitleGenProviders() {
|
|
|
5206
7308
|
const rr3 = builtinVariantsOf(mid);
|
|
5207
7309
|
if (rr3) modelReasoning[mid] = rr3;
|
|
5208
7310
|
}
|
|
7311
|
+
const conn = providerConnectionFields(ruleById.get(id), p);
|
|
5209
7312
|
add(id, {
|
|
5210
|
-
name:
|
|
7313
|
+
name: conn.name,
|
|
5211
7314
|
aliases: [r.providerName, p && p.name],
|
|
5212
|
-
kind:
|
|
5213
|
-
baseUrl:
|
|
5214
|
-
apiKey:
|
|
7315
|
+
kind: conn.kind,
|
|
7316
|
+
baseUrl: conn.baseUrl,
|
|
7317
|
+
apiKey: conn.apiKey,
|
|
5215
7318
|
models: [...Object.keys(modelCfg), ...(c.modelOrder || []), ...(c.personalModelIds || [])],
|
|
5216
7319
|
modelReasoning,
|
|
5217
7320
|
});
|
|
@@ -5231,7 +7334,7 @@ export function listTitleGenProviders() {
|
|
|
5231
7334
|
// Anthropic Messages 文本调用(无系统提示词,单条用户消息)。max_tokens 给足
|
|
5232
7335
|
// 2048:glm 系列等推理模型先输出 thinking 块再出正文,给小了会全部耗在
|
|
5233
7336
|
// 思考上(stop_reason=max_tokens 且没有任何 text 块),起名调用不在意这点额度
|
|
5234
|
-
async function callAnthropicText(baseUrl, apiKey, model, content) {
|
|
7337
|
+
async function callAnthropicText(baseUrl, apiKey, model, content, thinking = 'off') {
|
|
5235
7338
|
const url = baseUrl.replace(/\/+$/, '') + '/v1/messages';
|
|
5236
7339
|
const ctrl = new AbortController();
|
|
5237
7340
|
const timer = setTimeout(() => ctrl.abort(), TITLE_GEN_TIMEOUT_MS);
|
|
@@ -5239,7 +7342,12 @@ async function callAnthropicText(baseUrl, apiKey, model, content) {
|
|
|
5239
7342
|
const resp = await fetch(url, {
|
|
5240
7343
|
method: 'POST', signal: ctrl.signal,
|
|
5241
7344
|
headers: { 'content-type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
|
|
5242
|
-
body: JSON.stringify(
|
|
7345
|
+
body: JSON.stringify((() => {
|
|
7346
|
+
const b = { model, max_tokens: 2048, messages: [{ role: 'user', content }] };
|
|
7347
|
+
// 思考档位按所选模型的能力下发(预算随档位变;off 时智谱需显式关闭)
|
|
7348
|
+
applyThinking(b, 'anthropic', baseUrl, thinking);
|
|
7349
|
+
return b;
|
|
7350
|
+
})()),
|
|
5243
7351
|
});
|
|
5244
7352
|
const body = await resp.text();
|
|
5245
7353
|
if (!resp.ok) throw new Error(`HTTP ${resp.status} [model=${model}]: ${body.slice(0, 300)}`);
|
|
@@ -5264,7 +7372,7 @@ async function callAnthropicText(baseUrl, apiKey, model, content) {
|
|
|
5264
7372
|
}
|
|
5265
7373
|
|
|
5266
7374
|
// OpenAI Chat Completions 文本调用;baseURL 已含 /v1 时不重复拼
|
|
5267
|
-
async function callOpenAiText(baseUrl, apiKey, model, content) {
|
|
7375
|
+
async function callOpenAiText(baseUrl, apiKey, model, content, thinking = 'off') {
|
|
5268
7376
|
const base = baseUrl.replace(/\/+$/, '');
|
|
5269
7377
|
const url = /\/v\d+$/.test(base) ? base + '/chat/completions' : base + '/v1/chat/completions';
|
|
5270
7378
|
const ctrl = new AbortController();
|
|
@@ -5273,7 +7381,12 @@ async function callOpenAiText(baseUrl, apiKey, model, content) {
|
|
|
5273
7381
|
const resp = await fetch(url, {
|
|
5274
7382
|
method: 'POST', signal: ctrl.signal,
|
|
5275
7383
|
headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
|
|
5276
|
-
body: JSON.stringify(
|
|
7384
|
+
body: JSON.stringify((() => {
|
|
7385
|
+
const b = { model, max_tokens: 2048, messages: [{ role: 'user', content }] };
|
|
7386
|
+
// openai 兼容端点:reasoning_effort;智谱只认 thinking.type 开/关
|
|
7387
|
+
applyThinking(b, 'openai', baseUrl, thinking);
|
|
7388
|
+
return b;
|
|
7389
|
+
})()),
|
|
5277
7390
|
});
|
|
5278
7391
|
const body = await resp.text();
|
|
5279
7392
|
if (!resp.ok) throw new Error(`HTTP ${resp.status} [model=${model}]: ${body.slice(0, 300)}`);
|
|
@@ -5385,9 +7498,11 @@ export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = ''
|
|
|
5385
7498
|
const providerId = (cfg.provider || '').trim();
|
|
5386
7499
|
const model = (cfg.model || '').trim();
|
|
5387
7500
|
const conn = await resolveTitleGenConnection(cfg, providerId, model, dataRoot, sessId);
|
|
7501
|
+
// 思考档位:配置里存的档位先按该模型实际支持的范围规整,再下发
|
|
7502
|
+
const thinkLevel = resolveThinkingForChannel({ provider: providerId, model, thinking: cfg.thinking });
|
|
5388
7503
|
const raw = conn.format === 'anthropic'
|
|
5389
|
-
? await callAnthropicText(conn.baseUrl, conn.apiKey, conn.model, userContent)
|
|
5390
|
-
: await callOpenAiText(conn.baseUrl, conn.apiKey, conn.model, userContent);
|
|
7504
|
+
? await callAnthropicText(conn.baseUrl, conn.apiKey, conn.model, userContent, thinkLevel)
|
|
7505
|
+
: await callOpenAiText(conn.baseUrl, conn.apiKey, conn.model, userContent, thinkLevel);
|
|
5391
7506
|
const title = cleanGeneratedTitle(raw);
|
|
5392
7507
|
if (!title) {
|
|
5393
7508
|
const e = new Error('模型未返回可用标题');
|
|
@@ -5688,7 +7803,8 @@ export function validateVisionConfig(raw) {
|
|
|
5688
7803
|
for (const p of raw.proxies) {
|
|
5689
7804
|
if (!p || typeof p !== 'object') return [null, '代理必须是对象'];
|
|
5690
7805
|
const proxy = {};
|
|
5691
|
-
|
|
7806
|
+
// thinking:思考档位,按模型能力下发(zcode-vision ≥1.8 支持;旧版忽略未知键)
|
|
7807
|
+
for (const k of ['name', 'baseUrl', 'model', 'apiKey', 'format', 'useProvider', 'prompt', 'thinking']) {
|
|
5692
7808
|
const v = p[k];
|
|
5693
7809
|
if (v === undefined || v === null) continue;
|
|
5694
7810
|
if (typeof v !== 'string') return [null, `代理字段 ${k} 必须是字符串`];
|
|
@@ -6403,9 +8519,13 @@ async function runHeadroomHook(args, timeoutMs = 30000) {
|
|
|
6403
8519
|
// 手动重启)。helper 就绪后延迟几秒补一次 ensure:动作幂等(已在跑秒回),新版
|
|
6404
8520
|
// 插件侧还带跨进程锁;失败一律静默——没装 headroom 插件/本体的环境不能打扰启动。
|
|
6405
8521
|
function ensureHeadroomAtStartup(state = {}) {
|
|
6406
|
-
//
|
|
6407
|
-
|
|
6408
|
-
state
|
|
8522
|
+
// noHeadroomHook:测试传入,表示不跑真插件钩子(沙箱里的 helper 不能动真机的 headroom.json)。
|
|
8523
|
+
// 以前只有链对齐里的两处认它,启动兜底这一处漏了:沙箱测试启动 helper 5 秒后照样跑真钩子
|
|
8524
|
+
if (!state || typeof state !== 'object') return;
|
|
8525
|
+
// 按模块实例记(见 HELPER_INSTANCE):同一实例只排队一次,热替换后的新实例重做
|
|
8526
|
+
if (state.headroomEnsureBy === HELPER_INSTANCE) return;
|
|
8527
|
+
state.headroomEnsureBy = HELPER_INSTANCE;
|
|
8528
|
+
if (state.noHeadroomHook) return;
|
|
6409
8529
|
const timer = setTimeout(() => {
|
|
6410
8530
|
runHeadroomHook(['ensure'], 20000).catch(() => { /* 兜底失败不影响启动 */ });
|
|
6411
8531
|
}, 5000);
|
|
@@ -6423,10 +8543,36 @@ export function parseHeadroomStatus(text) {
|
|
|
6423
8543
|
};
|
|
6424
8544
|
const proxy = line('proxy') || '';
|
|
6425
8545
|
const ps = line('power-save-auto-cpu') || '';
|
|
6426
|
-
// 多实例模式的实例行:
|
|
8546
|
+
// 多实例模式的实例行:
|
|
8547
|
+
// instance: <端口> <格式> <上游> <up|down> <供应商列表>[ |target=<实际出口>][ |upstreams=a,b][ |proxies=c,d]
|
|
8548
|
+
// 上游字段始终是真实厂商地址(旧版插件只输出到这里);走代理链时行尾追加实际出口。
|
|
8549
|
+
// 尾部标记用 | 前缀是为了让不认识它们的旧版解析器把整段并进供应商列表——
|
|
8550
|
+
// 只影响显示,不影响运行状态判定。这里逐段剥掉,供应商列表不带标记
|
|
6427
8551
|
const instances = [];
|
|
6428
8552
|
for (const m of raw.matchAll(/^instance: (\d+) (\S+) (\S+) (up|down) ?(.*)$/gm)) {
|
|
6429
|
-
|
|
8553
|
+
let rest = m[5] || '';
|
|
8554
|
+
const meta = {};
|
|
8555
|
+
// 反复从尾部摘标记,直到没有为止(顺序无关,谁在前面先摘谁)
|
|
8556
|
+
for (;;) {
|
|
8557
|
+
const hit = /\s*\|(target|upstreams|proxies|ids)=(\S*)\s*$/.exec(rest);
|
|
8558
|
+
if (!hit) break;
|
|
8559
|
+
meta[hit[1]] = hit[2];
|
|
8560
|
+
rest = rest.slice(0, hit.index);
|
|
8561
|
+
}
|
|
8562
|
+
const list = (v) => (v ? String(v).split(',').filter(Boolean) : []);
|
|
8563
|
+
instances.push({
|
|
8564
|
+
port: Number(m[1]),
|
|
8565
|
+
format: m[2],
|
|
8566
|
+
upstream: m[3],
|
|
8567
|
+
up: m[4] === 'up',
|
|
8568
|
+
providers: rest.trim(),
|
|
8569
|
+
// 走链时 target 是链转发器地址;空表示没有链,出口就是 upstream
|
|
8570
|
+
target: meta.target || '',
|
|
8571
|
+
onChain: !!meta.target,
|
|
8572
|
+
upstreams: list(meta.upstreams),
|
|
8573
|
+
proxies: list(meta.proxies),
|
|
8574
|
+
ids: list(meta.ids),
|
|
8575
|
+
});
|
|
6430
8576
|
}
|
|
6431
8577
|
return {
|
|
6432
8578
|
up: /^up\b/.test(proxy),
|
|
@@ -6453,7 +8599,9 @@ export function parseHeadroomStatus(text) {
|
|
|
6453
8599
|
// 关闭时把条目改回直连地址(headroom 的默认转发上游),并在 zcodepro.json 的
|
|
6454
8600
|
// headroomRoutes 里记下 { 供应商 id → { proxy, direct } };开启时按记录切回代理。
|
|
6455
8601
|
const HEADROOM_DIRECT_URL = 'https://open.bigmodel.cn/api/anthropic';
|
|
6456
|
-
|
|
8602
|
+
// 旧的“任意本机端口都算走 headroom”正则已废弃:它会把供应商转发器自己的
|
|
8603
|
+
// 1873x 地址也算进去,关 headroom 时误改这些供应商的地址。改用 isHeadroomUrl
|
|
8604
|
+
// 按 headroom.json 里真实的 router.port 判断。
|
|
6457
8605
|
|
|
6458
8606
|
// —— Serena(语义代码分析 MCP):headroom 标签页的启用开关 ——
|
|
6459
8607
|
// 开关写 ~/.zcode/cli/config.json 的 mcp.servers.serena,ZCode 新会话启动时加载,
|
|
@@ -6516,19 +8664,37 @@ export function setSerenaEnabled(enable) {
|
|
|
6516
8664
|
return { ok: true, serena: serenaScan() };
|
|
6517
8665
|
}
|
|
6518
8666
|
|
|
8667
|
+
// headroom 路由端口:从 headroom.json 的 router.port 读(插件的 hr-multi.mjs 也这么取),
|
|
8668
|
+
// 缺省 8787。端口可配,所以不能写死在正则里。
|
|
8669
|
+
function headroomRouterPort(dataRoot) {
|
|
8670
|
+
const hr = readJsonFile(join(dataRoot, 'headroom.json'));
|
|
8671
|
+
const p = Number(hr?.router?.port);
|
|
8672
|
+
return Number.isFinite(p) && p > 0 && p <= 65535 ? Math.round(p) : 8787;
|
|
8673
|
+
}
|
|
8674
|
+
|
|
8675
|
+
// 判断某地址是不是 headroom 的路由地址。只认这一个端口——旧实现对任何
|
|
8676
|
+
// 127.0.0.1:<任意端口> 都算“走 headroom”,会把供应商转发器自己的 1873x
|
|
8677
|
+
// 也算进去,关 headroom 时把这些供应商的地址一并改掉。
|
|
8678
|
+
function isHeadroomUrl(url, dataRoot) {
|
|
8679
|
+
const u = String(url || '').trim();
|
|
8680
|
+
if (!u) return false;
|
|
8681
|
+
const port = headroomRouterPort(dataRoot);
|
|
8682
|
+
return u === `http://127.0.0.1:${port}` || u === `http://127.0.0.1:${port}/`;
|
|
8683
|
+
}
|
|
8684
|
+
|
|
6519
8685
|
// 扫描 v2/config.json(provider.<id>.options.baseURL)与 v2/provider_config.json
|
|
6520
|
-
// (providerRules[].config.api.baseUrl
|
|
8686
|
+
// (providerRules[].config.api.baseUrl),统计当前走 headroom 路由的条目数
|
|
6521
8687
|
export function headroomUsageScan(dataRoot) {
|
|
6522
8688
|
let via = 0;
|
|
6523
8689
|
const v2 = readJsonFile(join(dataRoot, 'v2', 'config.json'));
|
|
6524
8690
|
for (const p of Object.values((v2 && typeof v2.provider === 'object' && v2.provider) || {})) {
|
|
6525
8691
|
const u = typeof p?.options?.baseURL === 'string' ? p.options.baseURL.trim() : '';
|
|
6526
|
-
if (
|
|
8692
|
+
if (isHeadroomUrl(u, dataRoot)) via += 1;
|
|
6527
8693
|
}
|
|
6528
8694
|
const pc = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'));
|
|
6529
8695
|
for (const r of pc?.config?.providerConfigRules?.providerRules || []) {
|
|
6530
8696
|
const u = typeof r?.config?.api?.baseUrl === 'string' ? r.config.api.baseUrl.trim() : '';
|
|
6531
|
-
if (
|
|
8697
|
+
if (isHeadroomUrl(u, dataRoot)) via += 1;
|
|
6532
8698
|
}
|
|
6533
8699
|
return { enabled: via > 0, entries: via };
|
|
6534
8700
|
}
|
|
@@ -6562,8 +8728,10 @@ function setHeadroomUsageLocked(dataRoot, configFile, enable) {
|
|
|
6562
8728
|
// 不是自有属性,记录会悄悄丢失
|
|
6563
8729
|
const reserved = (id) => id === '__proto__' || id === 'constructor' || id === 'prototype';
|
|
6564
8730
|
const apply = (get, set, id) => {
|
|
8731
|
+
// 受保护的供应商一律不动:无论开还是关 headroom,都不改写它们的地址
|
|
8732
|
+
if (PROVIDER_PROXY_PROTECTED_IDS.has(id)) return false;
|
|
6565
8733
|
const u = get();
|
|
6566
|
-
if (!enable &&
|
|
8734
|
+
if (!enable && isHeadroomUrl(u, dataRoot)) {
|
|
6567
8735
|
routes[id] = { proxy: u, direct: HEADROOM_DIRECT_URL };
|
|
6568
8736
|
set(HEADROOM_DIRECT_URL);
|
|
6569
8737
|
changed += 1;
|
|
@@ -6627,35 +8795,95 @@ export function runNodeScript(scriptArgs, timeoutMs = 120000, scope = 'deps', ex
|
|
|
6627
8795
|
// 把长服务器键名改短。sourcePackages 取 ZCode 安装目录(bundle 旁的 packages,
|
|
6628
8796
|
// 插件缓存由它生成),找不到就不扫源包,只扫缓存。
|
|
6629
8797
|
// 导出以便测试;设置页按钮走 /tool-names/check,启动时自动跑一次。
|
|
6630
|
-
|
|
8798
|
+
// userConfigFile / sourcePackagesDir 平时不传(按真实环境找);测试传沙箱里的路径,
|
|
8799
|
+
// 这样“检查 → 写不了的文件 → 写提示”整条流程能在沙箱里跑通,不碰真实的安装目录
|
|
8800
|
+
export function runToolNameCheck({
|
|
8801
|
+
dataRoot, configFile, dryRun = false, state = {}, userConfigFile, sourcePackagesDir: sourcePackagesDirArg,
|
|
8802
|
+
} = {}) {
|
|
6631
8803
|
const config = loadConfig(configFile);
|
|
6632
|
-
let sourcePackagesDir = '';
|
|
6633
|
-
|
|
6634
|
-
const
|
|
6635
|
-
|
|
8804
|
+
let sourcePackagesDir = typeof sourcePackagesDirArg === 'string' ? sourcePackagesDirArg : '';
|
|
8805
|
+
if (typeof sourcePackagesDirArg !== 'string') {
|
|
8806
|
+
for (const bundle of zcodeCliBundleCandidates()) {
|
|
8807
|
+
const dir = join(dirname(bundle), 'packages');
|
|
8808
|
+
if (existsSync(dir)) { sourcePackagesDir = dir; break; }
|
|
8809
|
+
}
|
|
6636
8810
|
}
|
|
6637
8811
|
const result = applyToolNameMaps({
|
|
6638
8812
|
dataRoot,
|
|
6639
|
-
zcodeConfigFile: join(zcodeDataRoot(), 'cli', 'config.json'),
|
|
8813
|
+
zcodeConfigFile: userConfigFile || join(zcodeDataRoot(), 'cli', 'config.json'),
|
|
6640
8814
|
maps: config.toolNameMaps,
|
|
6641
8815
|
sourcePackagesDir,
|
|
6642
8816
|
dryRun,
|
|
6643
8817
|
});
|
|
8818
|
+
// 有文件写不了:检查本身已经跳过它继续处理别的文件,这里写一份右下角提示
|
|
8819
|
+
if (!dryRun && Array.isArray(result.unwritable) && result.unwritable.length) {
|
|
8820
|
+
noteToolNameUnwritable(state, dataRoot, result.unwritable);
|
|
8821
|
+
}
|
|
6644
8822
|
return { ...result, summary: toolNameCheckSummary(result) };
|
|
6645
8823
|
}
|
|
6646
8824
|
|
|
8825
|
+
// 同一个问题不反复提示:提示文件里记着上次写的内容(key)和时间(at),key 相同且不到
|
|
8826
|
+
// NOTICE_REMIND_MS 就不再写。按文件记而不是按进程内的 state 记,是为了跨 zcode-pro 重启
|
|
8827
|
+
// 也算——不然“自带插件目录写不了”这种一直存在的情况每次启动都会弹一张卡。
|
|
8828
|
+
// 返回 { repeat: boolean },repeat=true 表示最近提示过、这次不用再写
|
|
8829
|
+
const NOTICE_REMIND_MS = 24 * 60 * 60 * 1000;
|
|
8830
|
+
function recentNotice(file, key) {
|
|
8831
|
+
const prev = readJsonFile(file);
|
|
8832
|
+
const at = prev && typeof prev.at === 'string' ? Date.parse(prev.at) : NaN;
|
|
8833
|
+
return { repeat: !!prev && prev.key === key && Number.isFinite(at) && Date.now() - at < NOTICE_REMIND_MS, prev };
|
|
8834
|
+
}
|
|
8835
|
+
|
|
8836
|
+
// 工具名检查里有文件写不了:检查本身跳过它继续处理别的文件,这里写一份右下角提示
|
|
8837
|
+
//(页面轮询到后弹卡片,见 proxy-chain-notice.js)。同一批文件只提示一次,文件集合
|
|
8838
|
+
// 变了、或者距上次提示超过 24 小时才再提示。返回这次有没有写(导出以便测试)
|
|
8839
|
+
export function noteToolNameUnwritable(state, dataRoot, unwritable) {
|
|
8840
|
+
const list = (Array.isArray(unwritable) ? unwritable : []).filter((u) => u && typeof u === 'object' && u.file);
|
|
8841
|
+
if (!dataRoot || !list.length) return false;
|
|
8842
|
+
const file = join(dataRoot, 'tool-name-notice.json');
|
|
8843
|
+
const key = [...new Set(list.map((u) => String(u.file)))].sort().join('\n');
|
|
8844
|
+
if (recentNotice(file, key).repeat) return false;
|
|
8845
|
+
try {
|
|
8846
|
+
writeJsonAtomic(file, {
|
|
8847
|
+
at: new Date().toISOString(),
|
|
8848
|
+
kind: 'tool-name',
|
|
8849
|
+
key,
|
|
8850
|
+
// 一键解决权限的命令(含真实路径,界面原样显示、可复制):只读文件多半在系统安装
|
|
8851
|
+
// 目录里属于 root(644/444),加上写权限直接覆盖写就能成功。Windows 没有 sudo,
|
|
8852
|
+
// 留空由界面换通用说明
|
|
8853
|
+
command: toolNameFixCommand(list.map((u) => String(u.file))),
|
|
8854
|
+
items: list.map((u) => ({
|
|
8855
|
+
file: String(u.file),
|
|
8856
|
+
error: String(u.error || ''),
|
|
8857
|
+
renames: (Array.isArray(u.renames) ? u.renames : []).map((x) => ({ from: String((x && x.from) || ''), to: String((x && x.to) || '') })),
|
|
8858
|
+
})),
|
|
8859
|
+
});
|
|
8860
|
+
return true;
|
|
8861
|
+
} catch { return false; }
|
|
8862
|
+
}
|
|
8863
|
+
|
|
8864
|
+
// 一键加写权限的命令:sudo chmod a+w 加上写权限就够——直接覆盖写只需要文件可写,
|
|
8865
|
+
// 不需要目录可写。路径逐个单引号包住(目录名里可能有空格、引号,引号按 shell 规则转义)
|
|
8866
|
+
function toolNameFixCommand(files) {
|
|
8867
|
+
if (process.platform === 'win32' || !files.length) return '';
|
|
8868
|
+
const quoted = files.map((f) => `'${String(f).replace(/'/g, `'\\''`)}'`).join(' ');
|
|
8869
|
+
return `sudo chmod a+w ${quoted}`;
|
|
8870
|
+
}
|
|
8871
|
+
|
|
6647
8872
|
// 启动兜底:ZCode 升级/插件更新会把服务器键名改回长名,helper 就绪后延迟几秒补打一次;
|
|
6648
8873
|
// 标志挂 state,热替换不重复排队。失败静默——没配映射的环境不受影响。
|
|
6649
8874
|
// 配置里 toolNameAuto=false 时跳过(用户关掉了自动修复,只用手动按钮)。
|
|
6650
8875
|
function ensureToolNamesAtStartup(state = {}, ctx = {}) {
|
|
6651
8876
|
if (!state || typeof state !== 'object') return;
|
|
6652
|
-
if (state.
|
|
6653
|
-
state.
|
|
8877
|
+
if (state.toolNameEnsureBy === HELPER_INSTANCE) return;
|
|
8878
|
+
state.toolNameEnsureBy = HELPER_INSTANCE;
|
|
8879
|
+
// noToolNameCheck:测试传入,表示不做启动时的工具名检查(它扫的是 ZCode 安装目录
|
|
8880
|
+
// 与真实主目录下的 cli/config.json,不跟沙箱数据根走)
|
|
8881
|
+
if (state.noToolNameCheck) return;
|
|
6654
8882
|
const timer = setTimeout(() => {
|
|
6655
8883
|
try {
|
|
6656
8884
|
const config = loadConfig(ctx.configFile);
|
|
6657
8885
|
if (config.toolNameAuto === false) return; // 用户关了自动修复
|
|
6658
|
-
const r = runToolNameCheck(ctx);
|
|
8886
|
+
const r = runToolNameCheck({ ...ctx, state });
|
|
6659
8887
|
state.toolNameLastRun = r;
|
|
6660
8888
|
if (r.changed.length) console.log(`[zcodepro] 工具名检查:${r.summary}`);
|
|
6661
8889
|
} catch (err) {
|