zcode-pro 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +12 -5
- package/README.md +12 -5
- package/dist/inject.js +4515 -415
- package/package.json +3 -3
- package/src/host/helper.mjs +3099 -48
- package/src/host/hot-swap.mjs +76 -0
- package/src/host/main.mjs +36 -14
- package/src/host/prompt-inject.mjs +174 -0
- package/src/host/provider-proxy.mjs +562 -0
- package/src/host/proxy-chain.mjs +137 -0
- package/src/host/setup.mjs +42 -17
- package/src/host/taskIndex.mjs +38 -13
- package/src/host/tool-name-check.mjs +164 -0
- package/src/host/translate-lib.mjs +781 -0
- package/src/inject/core.js +453 -17
- package/src/inject/features/auto-continue.js +46 -15
- package/src/inject/features/hr-notice.js +138 -0
- package/src/inject/features/newtab-panels.js +60 -20
- package/src/inject/features/proxy-chain-notice.js +215 -0
- package/src/inject/features/selection-toolbar-translate.js +174 -0
- package/src/inject/features/settings-dialog.js +1072 -86
- package/src/inject/features/status-bar.js +41 -10
- package/src/inject/features/translate-panel.js +883 -0
- package/src/inject/features/turn-usage.js +22 -3
- package/src/inject/index.js +10 -0
- package/src/inject/locales/ja.js +235 -7
- package/src/inject/locales/ko.js +235 -7
- package/src/inject/locales/ru.js +235 -7
- package/src/inject/provider-model-thinking.js +142 -0
- package/src/inject/thinking-levels.js +117 -0
- package/src/inject/ui.js +472 -2
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// 开发模式的按代号加载(辅助服务热替换用)。
|
|
2
|
+
//
|
|
3
|
+
// Node 的 ESM 模块缓存按完整 URL 区分。给某个目录下模块的 URL 统一加上 ?g=<代号>,
|
|
4
|
+
// 代号每换一代加一,入口模块连同它整条本地依赖链就都是全新的模块实例。
|
|
5
|
+
// 只给入口加时间戳是不够的:它 import 的依赖仍是进程启动时那一份,
|
|
6
|
+
// 改了依赖不重启启动器就一直是旧代码。
|
|
7
|
+
//
|
|
8
|
+
// 代号 0 是进程启动时静态 import 进来的那一代(URL 不带代号)。代号 0 期间不改写任何
|
|
9
|
+
// URL,与启动时的加载保持一致,同一份代码不会被加载两遍。
|
|
10
|
+
//
|
|
11
|
+
// 依赖 Node 的同步模块钩子 module.registerHooks(22.15 / 23.5 起提供)。没有时退回
|
|
12
|
+
// 只给入口带时间戳的旧做法:入口是新的,依赖仍是旧的。
|
|
13
|
+
|
|
14
|
+
import { createHash } from 'node:crypto';
|
|
15
|
+
import { readdirSync, statSync } from 'node:fs';
|
|
16
|
+
import { registerHooks } from 'node:module';
|
|
17
|
+
import { join, resolve } from 'node:path';
|
|
18
|
+
import { pathToFileURL } from 'node:url';
|
|
19
|
+
|
|
20
|
+
// 目录下全部 .mjs 文件(子目录也算,exclude 里的不算)的签名:
|
|
21
|
+
// 任一文件的修改时间或大小变了,签名就变。目录读不了或没有文件时返回空串
|
|
22
|
+
export function dirStamp(dir, { exclude = [] } = {}) {
|
|
23
|
+
try {
|
|
24
|
+
const skip = new Set(exclude.map((f) => resolve(f)));
|
|
25
|
+
const parts = [];
|
|
26
|
+
const walk = (d) => {
|
|
27
|
+
for (const ent of readdirSync(d, { withFileTypes: true })) {
|
|
28
|
+
const p = join(d, ent.name);
|
|
29
|
+
if (ent.isDirectory()) walk(p);
|
|
30
|
+
else if (ent.isFile() && p.endsWith('.mjs') && !skip.has(resolve(p))) {
|
|
31
|
+
const st = statSync(p);
|
|
32
|
+
parts.push(p + ':' + st.mtimeMs + ':' + st.size);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
walk(dir);
|
|
37
|
+
if (!parts.length) return '';
|
|
38
|
+
parts.sort();
|
|
39
|
+
return createHash('sha1').update(parts.join('\n')).digest('hex');
|
|
40
|
+
} catch { return ''; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 创建某个目录的代号加载器。
|
|
44
|
+
// entry 入口模块的 file URL
|
|
45
|
+
// exclude 不参与代号改写的文件(启动器自身等)
|
|
46
|
+
// 返回 { supported, generation, reload(stamp), deregister }
|
|
47
|
+
export function createGenerationLoader(dir, { entry, exclude = [] } = {}) {
|
|
48
|
+
const prefix = pathToFileURL(resolve(dir) + '/').href; // 末尾保留斜杠:只匹配目录内的文件
|
|
49
|
+
const skip = new Set(exclude.map((f) => pathToFileURL(resolve(f)).href));
|
|
50
|
+
let generation = 0;
|
|
51
|
+
let hooks = null;
|
|
52
|
+
if (typeof registerHooks === 'function') {
|
|
53
|
+
hooks = registerHooks({
|
|
54
|
+
resolve(specifier, context, nextResolve) {
|
|
55
|
+
const r = nextResolve(specifier, context);
|
|
56
|
+
if (generation > 0 && r && typeof r.url === 'string' && r.url.startsWith(prefix)
|
|
57
|
+
&& !skip.has(r.url) && !r.url.includes('?g=')) {
|
|
58
|
+
return { ...r, url: `${r.url}?g=${generation}` };
|
|
59
|
+
}
|
|
60
|
+
return r;
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
// 是否支持整条依赖链一起换(旧版 Node 只能换入口)
|
|
66
|
+
supported: hooks !== null,
|
|
67
|
+
get generation() { return generation; },
|
|
68
|
+
// 换下一代并加载入口,返回新模块实例(Promise<Module>)
|
|
69
|
+
reload(stamp) {
|
|
70
|
+
if (!hooks) return import(`${entry}?mtime=${stamp}`);
|
|
71
|
+
generation += 1;
|
|
72
|
+
return import(entry);
|
|
73
|
+
},
|
|
74
|
+
deregister() { try { hooks?.deregister(); } catch { /* 已注销 */ } },
|
|
75
|
+
};
|
|
76
|
+
}
|
package/src/host/main.mjs
CHANGED
|
@@ -7,12 +7,13 @@
|
|
|
7
7
|
import { spawn, execSync, spawnSync } from 'node:child_process';
|
|
8
8
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync } from 'node:fs';
|
|
9
9
|
import { dirname, join, resolve } from 'node:path';
|
|
10
|
-
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
11
|
import { randomBytes } from 'node:crypto';
|
|
12
12
|
import { resolveZcodeExecutable, resolveDataRootDir } from './paths.mjs';
|
|
13
13
|
import { readZcodeVersion } from './version.mjs';
|
|
14
14
|
import { CdpConnection, fetchBrowserWsUrl } from './cdp.mjs';
|
|
15
15
|
import * as helperModule from './helper.mjs';
|
|
16
|
+
import { createGenerationLoader, dirStamp } from './hot-swap.mjs';
|
|
16
17
|
import { runSetup } from './setup.mjs';
|
|
17
18
|
import { runWallpaperCli, installWallpaperDocs, removeWallpaperDocs } from './wallpaper.mjs';
|
|
18
19
|
|
|
@@ -35,7 +36,7 @@ if (process.platform === 'win32' && (process.stdout.isTTY || process.stdin.isTTY
|
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
function usage() {
|
|
38
|
-
return `ZCode Pro — ZCode
|
|
39
|
+
return `ZCode Pro — ZCode 桌面版增强包:壁纸引擎、皮肤主题等三十余项增强,不修改客户端文件
|
|
39
40
|
|
|
40
41
|
用法: zcode-pro [选项]
|
|
41
42
|
|
|
@@ -53,6 +54,7 @@ function usage() {
|
|
|
53
54
|
setup --desktop 同时在桌面创建快捷方式
|
|
54
55
|
setup --uninstall 移除由 setup 安装的集成(含桌面)
|
|
55
56
|
wallpaper <操作> 壁纸引擎控制:list/set/rotate/params/upload/delete(wallpaper -h 详览)
|
|
57
|
+
restore 还原供应商地址:代理链总开关关掉、链上供应商改回真实上游(zcode-pro 挂了时用)
|
|
56
58
|
|
|
57
59
|
环境变量:
|
|
58
60
|
ZCODEPRO_ZCODE_PATH ZCode 可执行文件路径(同 --zcode-path)
|
|
@@ -327,6 +329,11 @@ export async function run(argv) {
|
|
|
327
329
|
process.exitCode = await runWallpaperCli(argv.slice(1), resolveDataRootDir());
|
|
328
330
|
return;
|
|
329
331
|
}
|
|
332
|
+
// restore 子命令只改配置文件、不启动 ZCode(zcode-pro 挂了、设置界面点不到时用)
|
|
333
|
+
if (argv[0] === 'restore') {
|
|
334
|
+
process.exitCode = await helperModule.restoreProvidersCli();
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
330
337
|
const args = parseArgs(argv);
|
|
331
338
|
// 参数错误按失败退出(脚本调用方靠退出码判断);单纯 --help 仍退出码 0
|
|
332
339
|
if (args.help) { console.log(usage()); process.exitCode = args.bad ? 1 : 0; return; }
|
|
@@ -552,8 +559,18 @@ export async function run(argv) {
|
|
|
552
559
|
console.log('[zcodepro] 已连接 CDP 并开始注入。保持本进程运行以维持增强;Ctrl+C 退出(不影响 ZCode)。');
|
|
553
560
|
winLog('已连接 CDP 并开始注入');
|
|
554
561
|
|
|
555
|
-
|
|
556
|
-
|
|
562
|
+
// 退出前清代理链路由(同步,必须在 process.exit 前完成):转发器随进程死掉,
|
|
563
|
+
// headroom 登记里的 chainTarget 若不清,实例会把请求发到死端口,所有经 8787
|
|
564
|
+
// 的供应商全部 502(含原生 ZCode 启动的场景)
|
|
565
|
+
const shutdownCleanup = () => {
|
|
566
|
+
try { helperMod.dispose?.(); } catch { /* ignore */ }
|
|
567
|
+
try {
|
|
568
|
+
const r = helperMod.shutdownProxyChainRouting?.({ dataRoot, configFile: join(dataRoot, 'zcodepro.json') });
|
|
569
|
+
if (r && (r.chainTargets || r.baseUrls)) console.log(`[zcodepro] 退出清理:chainTarget ${r.chainTargets} 个,baseUrl 还原 ${r.baseUrls} 个`);
|
|
570
|
+
} catch { /* ignore */ }
|
|
571
|
+
};
|
|
572
|
+
process.on('SIGINT', () => { stopping = true; try { conn.close(); } catch {} shutdownCleanup(); server.close(); process.exit(0); });
|
|
573
|
+
process.on('SIGTERM', () => { stopping = true; try { conn.close(); } catch {} shutdownCleanup(); server.close(); process.exit(0); });
|
|
557
574
|
|
|
558
575
|
// dist/inject.js 变更后把各页面的新文档脚本换成新包:已打开页面不打断,
|
|
559
576
|
// 下次“调试-重新加载”即跑新代码(新页面首次注入本来就是新包)。
|
|
@@ -634,14 +651,16 @@ export async function run(argv) {
|
|
|
634
651
|
}
|
|
635
652
|
}
|
|
636
653
|
|
|
637
|
-
//
|
|
638
|
-
//
|
|
639
|
-
|
|
640
|
-
//
|
|
641
|
-
//
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
654
|
+
// src/host 有改动时热替换辅助服务:先导入新模块(语法错在这里抛出、旧服务
|
|
655
|
+
// 不动),再关旧起新。每次热替换都是全新的一代模块实例,helper 及其依赖的
|
|
656
|
+
// 模块级状态(rollout 解析缓存等)从零开始。
|
|
657
|
+
// 签名覆盖整个 src/host:以前只盯 helper.mjs,它的本地依赖(provider-proxy.mjs、
|
|
658
|
+
// proxy-chain.mjs、taskIndex.mjs 等)改了不触发替换,触发了依赖也还是旧的一份。
|
|
659
|
+
// 现在靠 hot-swap.mjs 给整条依赖链按代号重新加载。启动器自身的两个文件
|
|
660
|
+
//(main.mjs、hot-swap.mjs)换不了,改了仍需重启启动器,所以不计入签名。
|
|
661
|
+
// 只在开发模式运行:普通用户的代码不会在运行中变化,不必每 3 秒查一次。
|
|
662
|
+
const launcherFiles = [join(here, 'main.mjs'), join(here, 'hot-swap.mjs')];
|
|
663
|
+
const helperStamp = () => dirStamp(here, { exclude: launcherFiles });
|
|
645
664
|
let helperTriedSig = helperStamp(); // 上次尝试过的文件签名(mtime+size 双键):
|
|
646
665
|
// 同一份代码只试一次,失败等保存出新签名再试——别每 3 秒掐一次服务重试同一份坏代码
|
|
647
666
|
const swapRetry = { sig: '', n: 0 }; // 服务起不来时同一份代码的重试次数(上限 3)
|
|
@@ -653,7 +672,7 @@ export async function run(argv) {
|
|
|
653
672
|
// 子进程(插件更新/转码等)并发;不记 triedSig,任务完成自动再试
|
|
654
673
|
if (helperMod && typeof helperMod.busyJobs === 'function' && helperMod.busyJobs()) return;
|
|
655
674
|
try {
|
|
656
|
-
const mod = await
|
|
675
|
+
const mod = await hotSwap.reload(sig);
|
|
657
676
|
if (typeof mod.startHelper !== 'function') throw new Error('helper.mjs 没有导出 startHelper');
|
|
658
677
|
// import 让出过事件循环,期间旧服务可能刚接到请求起了后台任务(转码等):
|
|
659
678
|
// 关旧服务前补查一次。检查与关闭之间没有 await,不会再有新任务挤进来
|
|
@@ -704,6 +723,9 @@ export async function run(argv) {
|
|
|
704
723
|
}
|
|
705
724
|
})();
|
|
706
725
|
|
|
726
|
+
// 开发模式下才建代号加载器(会往本线程装模块钩子,普通用户不需要)
|
|
727
|
+
const hotSwap = devActive ? createGenerationLoader(here, { entry: pathToFileURL(join(here, 'helper.mjs')).href, exclude: launcherFiles }) : null;
|
|
728
|
+
|
|
707
729
|
while (!stopping) {
|
|
708
730
|
await sleep(3000);
|
|
709
731
|
if (stopping) break;
|
|
@@ -716,7 +738,7 @@ export async function run(argv) {
|
|
|
716
738
|
if (!(await cdpAlive(args.cdpPort))) {
|
|
717
739
|
console.log('[zcodepro] ZCode 已退出,zcodepro 一并退出。');
|
|
718
740
|
winLog('ZCode 已退出,zcodepro 一并退出');
|
|
719
|
-
|
|
741
|
+
shutdownCleanup(); // 收掉残留 ffmpeg 子进程 + 清代理链路由(headroom 的 chainTarget)
|
|
720
742
|
server.close();
|
|
721
743
|
process.exit(0);
|
|
722
744
|
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// 提示词注入:供应商代理转发前,把用户写的正文追加到请求体已有的 system 内容末尾。
|
|
2
|
+
//
|
|
3
|
+
// 只处理“带完整对话”的请求:有 system 内容、有非空 messages(或 responses 的 input)。
|
|
4
|
+
// 计 token、列模型这类附带请求原样放过。请求体读不懂(非 JSON、解压失败、超过上限)
|
|
5
|
+
// 也原样放过——宁可这次不注入,也不能把用户的请求搞坏。
|
|
6
|
+
//
|
|
7
|
+
// 协议按请求体形状判断,不看供应商配置里的协议字段:同一供应商的不同接口可能形状不同。
|
|
8
|
+
// - Anthropic messages:顶层 system(字符串或内容块数组)+ messages
|
|
9
|
+
// - OpenAI chat completions:messages 里 role=system/developer
|
|
10
|
+
// - OpenAI responses:顶层 instructions 字符串,或 input 数组里的 system/developer 项
|
|
11
|
+
import { brotliDecompressSync, gunzipSync, inflateRawSync, inflateSync } from 'node:zlib';
|
|
12
|
+
|
|
13
|
+
// 读取请求体的上限:超过就原样转发,不做改写(防止代理把内存吃光)
|
|
14
|
+
export const MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
// 主对话的识别标记:官方 system 里主对话带 "# Harness" 段,子代理(Zic 组装)
|
|
17
|
+
// 只有 CLI Prefix 与 Subagent Notes,没有这一段。
|
|
18
|
+
const HARNESS_MARK = '# Harness';
|
|
19
|
+
|
|
20
|
+
// 这些路径不是对话请求(计 token 等),即使形状像也不注入
|
|
21
|
+
const SKIP_PATH_RE = /(^|\/)count_tokens(\/|$)/i;
|
|
22
|
+
|
|
23
|
+
function decodeBody(raw, encoding) {
|
|
24
|
+
const enc = String(encoding || '').trim().toLowerCase();
|
|
25
|
+
if (!enc || enc === 'identity') return raw;
|
|
26
|
+
try {
|
|
27
|
+
if (enc === 'gzip' || enc === 'x-gzip') return gunzipSync(raw);
|
|
28
|
+
if (enc === 'deflate') {
|
|
29
|
+
try { return inflateSync(raw); } catch { return inflateRawSync(raw); }
|
|
30
|
+
}
|
|
31
|
+
if (enc === 'br') return brotliDecompressSync(raw);
|
|
32
|
+
} catch {
|
|
33
|
+
return null; // 解压失败:调用方原样转发
|
|
34
|
+
}
|
|
35
|
+
return null; // 不认识的编码:不碰
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 把消息 content(字符串或内容块数组)里的文字拼出来,用于判断是不是主对话
|
|
39
|
+
function textOfContent(content) {
|
|
40
|
+
if (typeof content === 'string') return content;
|
|
41
|
+
if (!Array.isArray(content)) return '';
|
|
42
|
+
return content
|
|
43
|
+
.filter((b) => b && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string')
|
|
44
|
+
.map((b) => b.text)
|
|
45
|
+
.join('\n');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isNonEmptyArray(v) {
|
|
49
|
+
return Array.isArray(v) && v.length > 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 请求体形状识别;返回协议名或 null
|
|
53
|
+
export function detectProtocol(body) {
|
|
54
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return null;
|
|
55
|
+
if (isNonEmptyArray(body.messages)) {
|
|
56
|
+
// Anthropic 用顶层 system;OpenAI chat completions 把 system 放 messages 里
|
|
57
|
+
if (body.system !== undefined) return 'anthropic';
|
|
58
|
+
const sys = body.messages.find((m) => m && (m.role === 'system' || m.role === 'developer'));
|
|
59
|
+
return sys ? 'openai-chat' : null;
|
|
60
|
+
}
|
|
61
|
+
if (Array.isArray(body.input) && body.input.length > 0) return 'openai-responses';
|
|
62
|
+
if (typeof body.instructions === 'string' && body.instructions.trim()) return 'openai-responses';
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 取出该请求的 system 文字(可能有多段,拼起来做判断)
|
|
67
|
+
function systemText(body, protocol) {
|
|
68
|
+
if (protocol === 'anthropic') return textOfContent(body.system);
|
|
69
|
+
if (protocol === 'openai-chat') {
|
|
70
|
+
return body.messages
|
|
71
|
+
.filter((m) => m && (m.role === 'system' || m.role === 'developer'))
|
|
72
|
+
.map((m) => textOfContent(m.content))
|
|
73
|
+
.join('\n');
|
|
74
|
+
}
|
|
75
|
+
if (protocol === 'openai-responses') {
|
|
76
|
+
const parts = [];
|
|
77
|
+
if (typeof body.instructions === 'string') parts.push(body.instructions);
|
|
78
|
+
for (const item of Array.isArray(body.input) ? body.input : []) {
|
|
79
|
+
if (item && (item.role === 'system' || item.role === 'developer')) parts.push(textOfContent(item.content));
|
|
80
|
+
}
|
|
81
|
+
return parts.join('\n');
|
|
82
|
+
}
|
|
83
|
+
return '';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 往 content(字符串或块数组)末尾追加文字;返回新的 content
|
|
87
|
+
function appendToContent(content, text) {
|
|
88
|
+
if (typeof content === 'string') return content ? `${content}\n\n${text}` : text;
|
|
89
|
+
if (Array.isArray(content)) {
|
|
90
|
+
return [...content, { type: 'text', text: `\n\n${text}` }];
|
|
91
|
+
}
|
|
92
|
+
return text;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 按协议把正文写进请求体;返回是否改动过
|
|
96
|
+
function applyText(body, protocol, text) {
|
|
97
|
+
if (protocol === 'anthropic') {
|
|
98
|
+
// 字符串直接拼;数组 push 一个新块,原有块的 cache_control 一概不动,
|
|
99
|
+
// 这样前面的提示词缓存前缀仍然有效
|
|
100
|
+
if (Array.isArray(body.system)) {
|
|
101
|
+
body.system = appendToContent(body.system, text);
|
|
102
|
+
} else if (typeof body.system === 'string') {
|
|
103
|
+
body.system = body.system ? `${body.system}\n\n${text}` : text;
|
|
104
|
+
} else {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
if (protocol === 'openai-chat') {
|
|
110
|
+
const idx = body.messages.findIndex((m) => m && (m.role === 'system' || m.role === 'developer'));
|
|
111
|
+
if (idx >= 0) {
|
|
112
|
+
body.messages[idx] = { ...body.messages[idx], content: appendToContent(body.messages[idx].content, text) };
|
|
113
|
+
} else {
|
|
114
|
+
body.messages = [{ role: 'system', content: text }, ...body.messages];
|
|
115
|
+
}
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
if (protocol === 'openai-responses') {
|
|
119
|
+
// instructions 是 responses 接口的 system 位;有就拼,没有再看 input 里的 system 项
|
|
120
|
+
if (typeof body.instructions === 'string' && body.instructions.trim()) {
|
|
121
|
+
body.instructions = `${body.instructions}\n\n${text}`;
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
const input = Array.isArray(body.input) ? body.input : null;
|
|
125
|
+
if (input) {
|
|
126
|
+
const idx = input.findIndex((m) => m && (m.role === 'system' || m.role === 'developer'));
|
|
127
|
+
if (idx >= 0) {
|
|
128
|
+
input[idx] = { ...input[idx], content: appendToContent(input[idx].content, text) };
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
input.unshift({ role: 'system', content: text });
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// 判断这次请求要不要注入
|
|
139
|
+
export function shouldInject({ url = '', body, text, includeSubagents = false }) {
|
|
140
|
+
if (typeof text !== 'string' || !text.trim()) return null;
|
|
141
|
+
if (SKIP_PATH_RE.test(String(url))) return null;
|
|
142
|
+
const protocol = detectProtocol(body);
|
|
143
|
+
if (!protocol) return null;
|
|
144
|
+
if (!includeSubagents) {
|
|
145
|
+
// 默认只给主对话:system 里必须有官方 Harness 段。
|
|
146
|
+
// 后台起名/标题这类请求没有 system 或没有这一段,天然被排除
|
|
147
|
+
if (!systemText(body, protocol).includes(HARNESS_MARK)) return null;
|
|
148
|
+
}
|
|
149
|
+
return protocol;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// 改写一个请求体。返回 { buffer, changed };不需要改动时 changed 为 false、buffer 为原字节。
|
|
153
|
+
export function rewriteRequest({ url = '', headers = {}, rawBody, text, includeSubagents = false }) {
|
|
154
|
+
const original = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody || '');
|
|
155
|
+
const unchanged = { buffer: original, changed: false };
|
|
156
|
+
if (!original.length) return unchanged;
|
|
157
|
+
if (original.length > MAX_BODY_BYTES) return unchanged;
|
|
158
|
+
|
|
159
|
+
const decoded = decodeBody(original, headers['content-encoding'] || headers['Content-Encoding']);
|
|
160
|
+
if (!decoded || !decoded.length) return unchanged;
|
|
161
|
+
|
|
162
|
+
let body;
|
|
163
|
+
try {
|
|
164
|
+
body = JSON.parse(decoded.toString('utf8'));
|
|
165
|
+
} catch {
|
|
166
|
+
return unchanged;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const protocol = shouldInject({ url, body, text, includeSubagents });
|
|
170
|
+
if (!protocol) return unchanged;
|
|
171
|
+
if (!applyText(body, protocol, String(text).trim())) return unchanged;
|
|
172
|
+
|
|
173
|
+
return { buffer: Buffer.from(JSON.stringify(body), 'utf8'), changed: true };
|
|
174
|
+
}
|