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,562 @@
|
|
|
1
|
+
// 供应商代理转发器:为单个供应商在本机开一个 127.0.0.1 监听端口,
|
|
2
|
+
// 请求先到这里,转发器再连上真实上游(例如 https://api.meta.ai/v1),
|
|
3
|
+
// 经由调用方指定的上游 HTTP 代理发出(或直连转发)。
|
|
4
|
+
// 默认不做任何改写:请求行、请求头、请求体都原样转发;SSE 等长时间响应也不截断。
|
|
5
|
+
// 唯一例外是提示词注入(见 prompt-inject.mjs):开了注入才读全请求体并按需追加文字。
|
|
6
|
+
|
|
7
|
+
import http from 'node:http';
|
|
8
|
+
import https from 'node:https';
|
|
9
|
+
import net from 'node:net';
|
|
10
|
+
import tls from 'node:tls';
|
|
11
|
+
import { URL } from 'node:url';
|
|
12
|
+
|
|
13
|
+
import { MAX_BODY_BYTES as MAX_INJECT_BODY_BYTES } from './prompt-inject.mjs';
|
|
14
|
+
|
|
15
|
+
// hop 头不转发(与本地转发器同款约定)
|
|
16
|
+
const HOP_HEADERS = new Set(['connection', 'keep-alive', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'proxy-authenticate', 'proxy-authorization']);
|
|
17
|
+
|
|
18
|
+
function stripHopHeaders(headers) {
|
|
19
|
+
const o = {};
|
|
20
|
+
for (const [k, v] of Object.entries(headers || {})) {
|
|
21
|
+
if (!HOP_HEADERS.has(k.toLowerCase())) o[k] = v;
|
|
22
|
+
}
|
|
23
|
+
return o;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// 拼上游路径:把上游地址里的路径前缀(如 /provider/v1)接到客户端请求路径前面。
|
|
27
|
+
// 关键是不能拼出重复段——ZCode 把 baseUrl 指到本机转发地址(127.0.0.1:8787)后,
|
|
28
|
+
// 以为上游是裸地址,会在请求里自己补 /v1/chat/completions;而上游真身
|
|
29
|
+
// (https://api.commandcode.ai/provider/v1)本身已含 /v1,直接相加会得到
|
|
30
|
+
// /provider/v1/v1/chat/completions,上游 404。
|
|
31
|
+
// 规则:请求路径的开头如果已经等于前缀的末尾若干段,就把那部分去掉再拼。
|
|
32
|
+
// 例:prefix=/provider/v1, req=/v1/chat/completions → /provider/v1/chat/completions
|
|
33
|
+
export function joinUpstreamPath(prefix, reqPath) {
|
|
34
|
+
const p = String(prefix || '').replace(/\/+$/, '');
|
|
35
|
+
const r = String(reqPath || '/');
|
|
36
|
+
if (!p) return r;
|
|
37
|
+
const ps = p.split('/').filter(Boolean);
|
|
38
|
+
const rs = r.split('/').filter(Boolean);
|
|
39
|
+
// 从最长可能的重叠开始试:请求开头有几个段与前缀末尾相同
|
|
40
|
+
for (let n = Math.min(ps.length, rs.length); n > 0; n--) {
|
|
41
|
+
const tail = ps.slice(ps.length - n).join('/');
|
|
42
|
+
const head = rs.slice(0, n).join('/');
|
|
43
|
+
if (tail === head) {
|
|
44
|
+
const rest = rs.slice(n).join('/');
|
|
45
|
+
// 请求正好用完整条前缀时不要多出末尾斜杠
|
|
46
|
+
return rest ? p + '/' + rest : p;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// 没重叠:正常拼接
|
|
50
|
+
return p + (r.startsWith('/') ? r : '/' + r);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function parseProxyUrl(raw) { const text = String(raw || '').trim();
|
|
54
|
+
if (!text) return null;
|
|
55
|
+
try {
|
|
56
|
+
const u = new URL(text);
|
|
57
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
|
|
58
|
+
if (!u.hostname || !u.port) return null;
|
|
59
|
+
return {
|
|
60
|
+
protocol: u.protocol,
|
|
61
|
+
hostname: u.hostname.replace(/^\[|\]$/g, ''),
|
|
62
|
+
port: Number(u.port),
|
|
63
|
+
username: u.username ? decodeURIComponent(u.username) : '',
|
|
64
|
+
password: u.password ? decodeURIComponent(u.password) : '',
|
|
65
|
+
};
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function proxyAuthHeaders(proxy) {
|
|
72
|
+
if (!proxy.username) return {};
|
|
73
|
+
const basic = Buffer.from(`${proxy.username}:${proxy.password || ''}`).toString('base64');
|
|
74
|
+
return { 'Proxy-Authorization': `Basic ${basic}` };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 在一条已建立的 socket(可能是直连,也可能已经过若干层 CONNECT 隧道)上,
|
|
78
|
+
// 让当前代理建一条通往 host:port 的 CONNECT 隧道。成功后 resolve 同一个 socket,
|
|
79
|
+
// 后续的 CONNECT 或最终请求都从它读写。多级串联靠这个逐层叠加。
|
|
80
|
+
function connectThrough(socket, proxy, host, port) {
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
let settled = false;
|
|
83
|
+
const cleanup = () => {
|
|
84
|
+
try { socket.removeListener('data', onData); } catch { /* ignore */ }
|
|
85
|
+
try { socket.removeListener('error', onError); } catch { /* ignore */ }
|
|
86
|
+
try { socket.removeListener('close', onClose); } catch { /* ignore */ }
|
|
87
|
+
};
|
|
88
|
+
const fail = (err) => {
|
|
89
|
+
if (settled) return;
|
|
90
|
+
settled = true;
|
|
91
|
+
cleanup();
|
|
92
|
+
try { socket.destroy(); } catch { /* ignore */ }
|
|
93
|
+
reject(err);
|
|
94
|
+
};
|
|
95
|
+
const succeed = () => {
|
|
96
|
+
if (settled) return;
|
|
97
|
+
settled = true;
|
|
98
|
+
cleanup();
|
|
99
|
+
resolve(socket);
|
|
100
|
+
};
|
|
101
|
+
const onError = (err) => fail(err);
|
|
102
|
+
const onClose = () => fail(new Error('代理连接在握手前关闭'));
|
|
103
|
+
// CONNECT 响应头可能和后续数据粘在同一个 chunk 里:把多出来的字节 unshift 回 socket
|
|
104
|
+
let buf = Buffer.alloc(0);
|
|
105
|
+
const onData = (chunk) => {
|
|
106
|
+
try {
|
|
107
|
+
buf = Buffer.concat([buf, chunk]);
|
|
108
|
+
const idx = buf.indexOf('\r\n\r\n');
|
|
109
|
+
if (idx === -1) return;
|
|
110
|
+
const head = buf.slice(0, idx + 4).toString('latin1');
|
|
111
|
+
const code = Number((/^HTTP\/\d+\.?\d*\s+(\d+)/.exec(head) || [])[1]) || 0;
|
|
112
|
+
if (code < 200 || code >= 300) { fail(new Error(`代理 CONNECT ${host}:${port} 返回 ${code || '空'}`)); return; }
|
|
113
|
+
const rest = buf.slice(idx + 4);
|
|
114
|
+
if (rest.length) queueMicrotask(() => socket.unshift(rest));
|
|
115
|
+
succeed();
|
|
116
|
+
} catch (err) { fail(err); }
|
|
117
|
+
};
|
|
118
|
+
socket.once('error', onError);
|
|
119
|
+
socket.once('close', onClose);
|
|
120
|
+
socket.on('data', onData);
|
|
121
|
+
socket.write([
|
|
122
|
+
`CONNECT ${host}:${port} HTTP/1.1`,
|
|
123
|
+
`Host: ${host}:${port}`,
|
|
124
|
+
'User-Agent: zcode-pro-provider-proxy',
|
|
125
|
+
...Object.entries(proxyAuthHeaders(proxy)).map(([k, v]) => `${k}: ${v}`),
|
|
126
|
+
'',
|
|
127
|
+
'',
|
|
128
|
+
].join('\r\n'));
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// 直连到第一个代理(不是到目标):https 代理要先做 TLS。
|
|
133
|
+
function connectToProxy(proxy) {
|
|
134
|
+
const useTls = proxy.protocol === 'https:';
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
const opts = { host: proxy.hostname, port: proxy.port, timeout: 15000 };
|
|
137
|
+
const socket = useTls
|
|
138
|
+
? tls.connect({ ...opts, servername: proxy.hostname, rejectUnauthorized: false })
|
|
139
|
+
: net.connect(opts);
|
|
140
|
+
const onReady = 'secureConnect';
|
|
141
|
+
const finish = () => {
|
|
142
|
+
socket.removeListener('error', onErr);
|
|
143
|
+
socket.setTimeout(0); // 已连上,交回上层管理超时
|
|
144
|
+
resolve(socket);
|
|
145
|
+
};
|
|
146
|
+
const onErr = (err) => reject(err);
|
|
147
|
+
// net/tls 的 timeout 只是事件不自动断开:不接这个事件,黑洞地址(丢包不回
|
|
148
|
+
// RST)会挂到 OS 层超时为止,而且此时 socket 还没进 conns 表,stop() 清不掉
|
|
149
|
+
socket.once('timeout', () => {
|
|
150
|
+
socket.destroy();
|
|
151
|
+
onErr(new Error(`connect ${proxy.hostname}:${proxy.port} timeout`));
|
|
152
|
+
});
|
|
153
|
+
socket.once('error', onErr);
|
|
154
|
+
if (useTls) socket.once(onReady, finish);
|
|
155
|
+
else socket.once('connect', finish);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 多级代理串联:依次穿过 chain 里的每个代理,最后到达 host:port。
|
|
160
|
+
// 每一层都让当前代理对下一跳建 CONNECT 隧道,于是最终 socket 已经从多层隧道里出来。
|
|
161
|
+
// secure=true 时最后再把 socket 包成 TLS(SNI 为目标主机)。
|
|
162
|
+
async function proxyChainConnect(chain, host, port, { secure = false } = {}) {
|
|
163
|
+
let socket = await connectToProxy(chain[0]);
|
|
164
|
+
try {
|
|
165
|
+
for (let i = 1; i < chain.length; i++) {
|
|
166
|
+
socket = await connectThrough(socket, chain[i - 1], chain[i].hostname, chain[i].port);
|
|
167
|
+
}
|
|
168
|
+
socket = await connectThrough(socket, chain[chain.length - 1], host, port);
|
|
169
|
+
} catch (err) {
|
|
170
|
+
try { socket.destroy(); } catch { /* ignore */ }
|
|
171
|
+
throw err;
|
|
172
|
+
}
|
|
173
|
+
if (!secure) return socket;
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
const s = tls.connect({ socket, servername: host, rejectUnauthorized: false });
|
|
176
|
+
s.once('secureConnect', () => resolve(s));
|
|
177
|
+
s.once('error', (err) => { try { socket.destroy(); } catch { /* ignore */ } reject(err); });
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// 单级代理:保留原入口,内部走统一实现
|
|
182
|
+
function proxyConnect(proxy, host, port, { secure = false } = {}) {
|
|
183
|
+
return proxyChainConnect([proxy], host, port, { secure });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function pipePair(a, b) {
|
|
187
|
+
a.pipe(b);
|
|
188
|
+
b.pipe(a);
|
|
189
|
+
const kill = () => {
|
|
190
|
+
try { a.destroy(); } catch { /* ignore */ }
|
|
191
|
+
try { b.destroy(); } catch { /* ignore */ }
|
|
192
|
+
};
|
|
193
|
+
a.once('error', kill);
|
|
194
|
+
b.once('error', kill);
|
|
195
|
+
a.once('close', () => { try { b.destroy(); } catch { /* ignore */ } });
|
|
196
|
+
b.once('close', () => { try { a.destroy(); } catch { /* ignore */ } });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// 单个供应商的转发器:一个监听端口;入口请求按上游转。
|
|
200
|
+
// —— OpenCode Go 兼容 ——
|
|
201
|
+
// OpenCode Go 套餐的端点(https://opencode.ai/zen/go/v1)要求请求带 x-opencode-session
|
|
202
|
+
// 头。ZCode 只在供应商地址正好是这个网址时才加(zcode.cjs 的 isOpenCodeGoBaseUrl),
|
|
203
|
+
// 值就是会话 id——同一个值它每个请求都放在 x-session-id 头里。供应商地址一旦是本机的
|
|
204
|
+
// 链入口(8787),ZCode 就不加了,端点回 400。所以由转发器在最后一跳补上。
|
|
205
|
+
// 判定与 ZCode 内部保持一致:主机是 opencode.ai(或其子域),路径正好是 /zen/go/v1
|
|
206
|
+
export function isOpenCodeGoUrl(url) {
|
|
207
|
+
let u;
|
|
208
|
+
try { u = new URL(String(url || '').trim()); } catch { return false; }
|
|
209
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:') return false;
|
|
210
|
+
const host = u.hostname.toLowerCase();
|
|
211
|
+
return (host === 'opencode.ai' || host.endsWith('.opencode.ai'))
|
|
212
|
+
&& u.pathname.replace(/\/+$/, '').toLowerCase() === '/zen/go/v1';
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// 要补的请求头。enabled=false 或目标不是 Go 端点时什么都不加;请求里已经带了也不动。
|
|
216
|
+
// 值取 x-session-id(ZCode 每个会话请求都带,headroom 压缩时会原样传下来);
|
|
217
|
+
// 没有会话 id 的请求(比如标题生成)给一个固定值,否则端点直接拒绝
|
|
218
|
+
export function opencodeGoHeaders(incoming, upstream, enabled) {
|
|
219
|
+
if (!enabled || !isOpenCodeGoUrl(upstream)) return {};
|
|
220
|
+
const get = (name) => {
|
|
221
|
+
const v = incoming && incoming[name];
|
|
222
|
+
const t = Array.isArray(v) ? v[0] : v;
|
|
223
|
+
return typeof t === 'string' ? t.trim() : '';
|
|
224
|
+
};
|
|
225
|
+
if (get('x-opencode-session')) return {};
|
|
226
|
+
const sid = get('x-session-id') || 'zcodepro';
|
|
227
|
+
return { 'x-opencode-session': sid };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
class ProviderForwarder {
|
|
231
|
+
constructor({ upstream, proxyUrls }) {
|
|
232
|
+
this.upstream = String(upstream || '').trim();
|
|
233
|
+
// 有序代理链(每项形如 http://host:port);空数组 = 直连
|
|
234
|
+
this.proxyUrls = Array.isArray(proxyUrls) ? proxyUrls.map((u) => String(u || '').trim()).filter(Boolean) : [];
|
|
235
|
+
// 兼容旧调用点:单值形态暴露成 proxyUrl(取第一个)
|
|
236
|
+
this.proxyUrl = this.proxyUrls[0] || '';
|
|
237
|
+
this.server = null;
|
|
238
|
+
this.conns = new Set();
|
|
239
|
+
// 提示词注入钩子:({ url, headers, rawBody }) => { buffer, changed }。
|
|
240
|
+
// 未设置时保持原来的纯流式转发(req.pipe)。
|
|
241
|
+
this.injector = null;
|
|
242
|
+
// 动态上游解析(代理链“压缩后再注入”用):给了就每请求求值一次
|
|
243
|
+
this.upstreamResolver = null;
|
|
244
|
+
// OpenCode Go 兼容:目标是 Go 端点时补 x-opencode-session(见 opencodeGoHeaders)。
|
|
245
|
+
// 算头用的函数挂在实例上,测试可以换掉(真实 Go 端点连不进沙箱)
|
|
246
|
+
this.opencodeGoCompat = false;
|
|
247
|
+
this.compatHeaders = opencodeGoHeaders;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
setUpstream(url) { this.upstream = String(url || '').trim(); }
|
|
251
|
+
// 动态上游:每请求调用一次,按请求头里的 API key 返回真实上游地址。
|
|
252
|
+
// 供代理链的“压缩后再注入”使用——headroom 压缩完把请求发到这里,
|
|
253
|
+
// 这里要按 key 认出是哪个供应商、再发往它真正的厂商地址。
|
|
254
|
+
setUpstreamResolver(fn) { this.upstreamResolver = typeof fn === 'function' ? fn : null; }
|
|
255
|
+
resolveUpstream(req) {
|
|
256
|
+
if (this.upstreamResolver) {
|
|
257
|
+
try {
|
|
258
|
+
const u = this.upstreamResolver(req);
|
|
259
|
+
if (typeof u === 'string' && u.trim()) return u.trim();
|
|
260
|
+
} catch { /* 解析失败退回固定上游 */ }
|
|
261
|
+
}
|
|
262
|
+
return this.upstream;
|
|
263
|
+
}
|
|
264
|
+
setProxyUrls(list) {
|
|
265
|
+
this.proxyUrls = Array.isArray(list) ? list.map((u) => String(u || '').trim()).filter(Boolean) : [];
|
|
266
|
+
this.proxyUrl = this.proxyUrls[0] || '';
|
|
267
|
+
}
|
|
268
|
+
setProxyUrl(v) { this.setProxyUrls([v]); }
|
|
269
|
+
setInjector(fn) { this.injector = typeof fn === 'function' ? fn : null; }
|
|
270
|
+
setLoopbackProxy(v) { this.loopbackProxy = v === true; }
|
|
271
|
+
setOpencodeGoCompat(v) { this.opencodeGoCompat = v === true; }
|
|
272
|
+
|
|
273
|
+
async start(port) {
|
|
274
|
+
if (this.server) await this.stop();
|
|
275
|
+
this.port = port;
|
|
276
|
+
this.server = http.createServer((req, res) => {
|
|
277
|
+
void this.handle(req, res).catch((err) => {
|
|
278
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
279
|
+
res.end(`转发失败:${err.message}`);
|
|
280
|
+
});
|
|
281
|
+
});
|
|
282
|
+
this.server.requestTimeout = 0;
|
|
283
|
+
this.server.headersTimeout = 60000;
|
|
284
|
+
await new Promise((resolve, reject) => {
|
|
285
|
+
this.server.once('error', reject);
|
|
286
|
+
this.server.listen(port, '127.0.0.1', () => resolve());
|
|
287
|
+
});
|
|
288
|
+
this.server.on('connection', (sock) => {
|
|
289
|
+
this.conns.add(sock);
|
|
290
|
+
sock.once('close', () => this.conns.delete(sock));
|
|
291
|
+
});
|
|
292
|
+
return port;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async stop() {
|
|
296
|
+
if (!this.server) return;
|
|
297
|
+
const srv = this.server;
|
|
298
|
+
this.server = null;
|
|
299
|
+
for (const sock of this.conns) {
|
|
300
|
+
try { sock.destroy(); } catch { /* ignore */ }
|
|
301
|
+
}
|
|
302
|
+
this.conns.clear();
|
|
303
|
+
await new Promise((resolve) => {
|
|
304
|
+
try {
|
|
305
|
+
srv.close(() => resolve());
|
|
306
|
+
srv.closeAllConnections?.();
|
|
307
|
+
} catch { resolve(); }
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
alive() {
|
|
312
|
+
return !!this.server && this.server.listening;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async openUpstream(host, port, secureFirst) {
|
|
316
|
+
// 本机回环默认不上代理:供应商走 headroom(8787)又开供应商代理时,
|
|
317
|
+
// 转发器连 headroom 是本机流量,用普通代理(如 clash)发出反而到不了。
|
|
318
|
+
// 例外:loopbackProxy=true——链上自定义代理排在 headroom 之前(如破盾框架
|
|
319
|
+
// 必须先过),由调用方明确要求连本机也走代理
|
|
320
|
+
const loopback = host === '127.0.0.1' || host === 'localhost' || host === '::1';
|
|
321
|
+
const skipProxy = loopback && !this.loopbackProxy;
|
|
322
|
+
// 多级串联:proxyUrls 是有序代理列表,逐个解析后交给 proxyChainConnect
|
|
323
|
+
const chain = skipProxy
|
|
324
|
+
? []
|
|
325
|
+
: (this.proxyUrls || []).map(parseProxyUrl).filter(Boolean);
|
|
326
|
+
if (chain.length > 1) {
|
|
327
|
+
return proxyChainConnect(chain, host, port, { secure: secureFirst });
|
|
328
|
+
}
|
|
329
|
+
if (chain.length === 1) {
|
|
330
|
+
return proxyConnect(chain[0], host, port, { secure: secureFirst });
|
|
331
|
+
}
|
|
332
|
+
if (secureFirst) {
|
|
333
|
+
return new Promise((resolve, reject) => {
|
|
334
|
+
const sock = tls.connect({ host, port, servername: host, rejectUnauthorized: false, timeout: 15000 });
|
|
335
|
+
sock.once('secureConnect', () => resolve(sock));
|
|
336
|
+
sock.once('error', reject);
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
return new Promise((resolve, reject) => {
|
|
340
|
+
const sock = net.connect({ host, port, timeout: 15000 });
|
|
341
|
+
sock.once('connect', () => resolve(sock));
|
|
342
|
+
sock.once('error', reject);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async handle(req, res) {
|
|
347
|
+
// 上游可能是固定的,也可能按请求里的 API key 动态决定(代理链压缩后的分流)
|
|
348
|
+
const upstreamRaw = String(this.resolveUpstream(req) || '').trim();
|
|
349
|
+
if (!upstreamRaw) {
|
|
350
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
351
|
+
res.end('未配置上游地址');
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
let parsed;
|
|
355
|
+
try {
|
|
356
|
+
parsed = new URL(upstreamRaw);
|
|
357
|
+
} catch {
|
|
358
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
359
|
+
res.end('上游地址不合法');
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const secureFirst = /^https:/i.test(upstreamRaw);
|
|
363
|
+
const targetHost = parsed.hostname.replace(/^\[|\]$/g, '');
|
|
364
|
+
const targetPort = Number(parsed.port) || (secureFirst ? 443 : 80);
|
|
365
|
+
// 上游带路径前缀(如 https://host/v1)时拼到每个请求前面:
|
|
366
|
+
// 转发地址本身不带路径,客户端发的是裸路径。
|
|
367
|
+
const upstreamPrefix = parsed.pathname && parsed.pathname !== '/' ? parsed.pathname.replace(/\/+$/, '') : '';
|
|
368
|
+
let tunnel;
|
|
369
|
+
try {
|
|
370
|
+
tunnel = await this.openUpstream(targetHost, targetPort, secureFirst);
|
|
371
|
+
} catch (err) {
|
|
372
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
373
|
+
res.end(`无法连接上游:${err.message}`);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
this.conns.add(tunnel);
|
|
377
|
+
tunnel.once('close', () => this.conns.delete(tunnel));
|
|
378
|
+
|
|
379
|
+
// 转发请求头(去掉 hop-by-hop 与 host,host 换成上游的)
|
|
380
|
+
const headers = stripHopHeaders(req.headers);
|
|
381
|
+
delete headers.host;
|
|
382
|
+
// OpenCode Go 兼容:目标是 Go 端点时补上会话请求头
|
|
383
|
+
try { Object.assign(headers, this.compatHeaders(req.headers, upstreamRaw, this.opencodeGoCompat)); } catch { /* 补不上就原样发 */ }
|
|
384
|
+
|
|
385
|
+
// 提示词注入:先读全请求体再决定发什么。有钩子且真的改了内容,才换成新体、
|
|
386
|
+
// 去掉编码相关头;否则原样把读到的字节发出去。
|
|
387
|
+
// 读全之后 req 已被消费,无法退回流式转发——所以“要不要读全”必须提前定:
|
|
388
|
+
// 只有带 content-length 且不超过上限的请求才读全,其余维持流式原样转发。
|
|
389
|
+
let consumed = null; // 读全后的原始字节
|
|
390
|
+
let rewritten = null; // 改写后的字节
|
|
391
|
+
const declaredLength = Number(headers['content-length']);
|
|
392
|
+
const canReadWhole = Number.isFinite(declaredLength) && declaredLength > 0
|
|
393
|
+
&& declaredLength <= MAX_INJECT_BODY_BYTES;
|
|
394
|
+
if (this.injector && canReadWhole && (req.method === 'POST' || req.method === 'PUT')) {
|
|
395
|
+
const injector = this.injector;
|
|
396
|
+
const injectUrl = req.url || '/';
|
|
397
|
+
const r = await new Promise((resolve) => {
|
|
398
|
+
const chunks = [];
|
|
399
|
+
let size = 0;
|
|
400
|
+
req.on('data', (c) => { size += c.length; chunks.push(c); });
|
|
401
|
+
req.on('end', () => {
|
|
402
|
+
const raw = Buffer.concat(chunks);
|
|
403
|
+
// 实际字节超限就不改写,原样转发
|
|
404
|
+
if (size > MAX_INJECT_BODY_BYTES) { resolve({ raw, out: null }); return; }
|
|
405
|
+
try {
|
|
406
|
+
const out = injector({ url: injectUrl, headers: req.headers, rawBody: raw });
|
|
407
|
+
resolve({ raw, out: out && out.changed && Buffer.isBuffer(out.buffer) ? out.buffer : null });
|
|
408
|
+
} catch {
|
|
409
|
+
resolve({ raw, out: null }); // 注入失败按原样转发,不能把请求搞坏
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
req.on('error', () => resolve({ raw: null, out: null }));
|
|
413
|
+
});
|
|
414
|
+
consumed = r.raw;
|
|
415
|
+
rewritten = r.out;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// 用 http/https 客户端发请求:它负责拼请求字节、解析响应状态行与响应头、
|
|
419
|
+
// 处理分块编码;SSE 等流式响应照样逐块透出。
|
|
420
|
+
if (rewritten) {
|
|
421
|
+
// 内容变了:长度重算,内容编码与分块相关头一并去掉(发的是未压缩字节)
|
|
422
|
+
headers['content-length'] = String(rewritten.length);
|
|
423
|
+
delete headers['content-encoding'];
|
|
424
|
+
delete headers['transfer-encoding'];
|
|
425
|
+
}
|
|
426
|
+
const path = joinUpstreamPath(upstreamPrefix, req.url || '/');
|
|
427
|
+
const client = secureFirst ? https : http;
|
|
428
|
+
const agent = new client.Agent({ keepAlive: false });
|
|
429
|
+
agent.createConnection = () => tunnel;
|
|
430
|
+
const upReq = client.request(
|
|
431
|
+
{
|
|
432
|
+
method: req.method,
|
|
433
|
+
path,
|
|
434
|
+
headers: { ...headers, Host: parsed.host },
|
|
435
|
+
agent,
|
|
436
|
+
},
|
|
437
|
+
(upRes) => {
|
|
438
|
+
const out = stripHopHeaders(upRes.headers);
|
|
439
|
+
if (!res.headersSent) res.writeHead(upRes.statusCode || 502, out);
|
|
440
|
+
upRes.pipe(res, { end: true });
|
|
441
|
+
},
|
|
442
|
+
);
|
|
443
|
+
upReq.once('error', (err) => {
|
|
444
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
445
|
+
res.end(`转发失败:${err.message}`);
|
|
446
|
+
});
|
|
447
|
+
req.once('aborted', () => { try { upReq.destroy(); } catch { /* ignore */ } });
|
|
448
|
+
res.once('close', () => { try { upReq.destroy(); } catch { /* ignore */ } });
|
|
449
|
+
if (rewritten) upReq.end(rewritten);
|
|
450
|
+
else if (consumed) upReq.end(consumed);
|
|
451
|
+
else req.pipe(upReq, { end: true });
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// 统一多路复用:每个上游(供应商)各开一台转发器,端口独立。
|
|
456
|
+
export class ProviderProxyManager {
|
|
457
|
+
constructor() {
|
|
458
|
+
this.forwarders = new Map(); // port → ProviderForwarder
|
|
459
|
+
this.injector = null; // 注入钩子:ensure 没显式传时沿用它
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async ensure({ upstream, port, proxyUrls, injector, upstreamResolver, loopbackProxy, opencodeGoCompat = false }) {
|
|
463
|
+
upstream = String(upstream || '').trim();
|
|
464
|
+
const urls = Array.isArray(proxyUrls)
|
|
465
|
+
? proxyUrls.map((u) => String(u || '').trim()).filter(Boolean)
|
|
466
|
+
: [];
|
|
467
|
+
const key = urls.join('>');
|
|
468
|
+
// 端口必须在转发器段内:0 会让 Node 分配随机端口(listen(0)),但我们的调用方
|
|
469
|
+
// 会把传入值当作已分配端口写回配置,于是配置里出现 port: 0、转发器却监听在
|
|
470
|
+
// 别的端口,界面上永远显示“—”。这里直接拒绝,让调用方回落到默认段。
|
|
471
|
+
if (!Number.isFinite(Number(port)) || Number(port) < 1024 || Number(port) > 65535) {
|
|
472
|
+
throw new Error(`端口不合法:${port}`);
|
|
473
|
+
}
|
|
474
|
+
// 有动态解析时,固定的 upstream 只作兜底,可以为空
|
|
475
|
+
if (!upstream && !upstreamResolver) throw new Error('未配置上游地址');
|
|
476
|
+
// 没显式传 injector 就沿用管理器当前的钩子:ensure 会被反复调用(配置变化、
|
|
477
|
+
// 启动兜底、文件监听都会触发),不能因为某次没传就把已挂的注入清掉。
|
|
478
|
+
// 显式传过 injector 的转发器(链转发器:有 inject 节点给钩子、没有给 null)
|
|
479
|
+
// 要记住这一声明:manager.setInjector 广播时不能覆盖它,否则任何一轮
|
|
480
|
+
// 供应商代理对齐都会把全局注入铺到「链上没有 inject 节点」的转发器里
|
|
481
|
+
const explicitInjector = injector !== undefined;
|
|
482
|
+
const hook = explicitInjector ? injector : this.injector;
|
|
483
|
+
// 按端口复用:同端口的上游/代理链都没变就直接用;变了原地重启(不留双实例)。
|
|
484
|
+
// 不按上游找——两个供应商可能共用一个上游地址,按上游找会互抢。
|
|
485
|
+
const existing = this.forwarders.get(port);
|
|
486
|
+
if (existing) {
|
|
487
|
+
existing.injectorFixed = explicitInjector;
|
|
488
|
+
existing.setInjector(hook);
|
|
489
|
+
existing.setLoopbackProxy(loopbackProxy === true);
|
|
490
|
+
existing.setOpencodeGoCompat(opencodeGoCompat); // 只是一个开关,不用重启
|
|
491
|
+
const sameResolver = !!existing.upstreamResolver === !!upstreamResolver;
|
|
492
|
+
const sameLoopback = existing.loopbackProxy === (loopbackProxy === true);
|
|
493
|
+
if (existing.upstream === upstream && (existing.proxyUrls || []).join('>') === key && sameResolver && sameLoopback && existing.alive()) {
|
|
494
|
+
existing.setUpstreamResolver(upstreamResolver || null);
|
|
495
|
+
return port;
|
|
496
|
+
}
|
|
497
|
+
existing.setUpstream(upstream);
|
|
498
|
+
existing.setProxyUrls(urls);
|
|
499
|
+
existing.setUpstreamResolver(upstreamResolver || null);
|
|
500
|
+
existing.setLoopbackProxy(loopbackProxy === true);
|
|
501
|
+
await existing.stop();
|
|
502
|
+
await existing.start(port);
|
|
503
|
+
return port;
|
|
504
|
+
}
|
|
505
|
+
const fw = new ProviderForwarder({ upstream, proxyUrls: urls });
|
|
506
|
+
fw.injectorFixed = explicitInjector;
|
|
507
|
+
fw.setInjector(hook);
|
|
508
|
+
fw.setUpstreamResolver(upstreamResolver || null);
|
|
509
|
+
fw.setLoopbackProxy(loopbackProxy === true);
|
|
510
|
+
fw.setOpencodeGoCompat(opencodeGoCompat);
|
|
511
|
+
await fw.start(port);
|
|
512
|
+
this.forwarders.set(port, fw);
|
|
513
|
+
return port;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async stopPort(port) {
|
|
517
|
+
const fw = this.forwarders.get(port);
|
|
518
|
+
if (!fw) return false;
|
|
519
|
+
await fw.stop();
|
|
520
|
+
this.forwarders.delete(port);
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// 给所有在跑的转发器换注入钩子(注入正文或“也注入子代理”变化时立即生效,不用重启转发器);
|
|
525
|
+
// 同时记在管理器上,后续新拉起的转发器也自带这个钩子
|
|
526
|
+
setInjector(fn) {
|
|
527
|
+
this.injector = typeof fn === 'function' ? fn : null;
|
|
528
|
+
for (const fw of this.forwarders.values()) {
|
|
529
|
+
if (fw.injectorFixed) continue; // 链转发器的声明(null=这条链不注入)不许被广播覆盖
|
|
530
|
+
fw.setInjector(this.injector);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
async freePort(preferred) {
|
|
535
|
+
for (let p = preferred; p <= 65535; p++) {
|
|
536
|
+
if (this.forwarders.has(p)) continue;
|
|
537
|
+
const busy = await new Promise((resolve) => {
|
|
538
|
+
const srv = net.createServer();
|
|
539
|
+
srv.once('error', () => resolve(true));
|
|
540
|
+
srv.once('listening', () => srv.close(() => resolve(false)));
|
|
541
|
+
srv.listen(p, '127.0.0.1');
|
|
542
|
+
});
|
|
543
|
+
if (!busy) return p;
|
|
544
|
+
}
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
async stopAll() {
|
|
549
|
+
for (const fw of this.forwarders.values()) {
|
|
550
|
+
await fw.stop();
|
|
551
|
+
}
|
|
552
|
+
this.forwarders.clear();
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
status() {
|
|
556
|
+
return [...this.forwarders.entries()].map(([port, fw]) => ({
|
|
557
|
+
port, upstream: fw.upstream, proxyUrl: fw.proxyUrl, proxyUrls: fw.proxyUrls, listening: fw.alive(),
|
|
558
|
+
}));
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export default { ProviderProxyManager, ProviderForwarder };
|