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.
@@ -1,7 +1,8 @@
1
1
  // 供应商代理转发器:为单个供应商在本机开一个 127.0.0.1 监听端口,
2
2
  // 请求先到这里,转发器再连上真实上游(例如 https://api.meta.ai/v1),
3
- // 经由调用方指定的上游 HTTP 代理发出(或直连转发)。中间不做任何改写——
4
- // 请求行、请求头、请求体都原样转发;SSE 等长时间响应也不截断。
3
+ // 经由调用方指定的上游 HTTP 代理发出(或直连转发)。
4
+ // 默认不做任何改写:请求行、请求头、请求体都原样转发;SSE 等长时间响应也不截断。
5
+ // 唯一例外是提示词注入(见 prompt-inject.mjs):开了注入才读全请求体并按需追加文字。
5
6
 
6
7
  import http from 'node:http';
7
8
  import https from 'node:https';
@@ -9,6 +10,8 @@ import net from 'node:net';
9
10
  import tls from 'node:tls';
10
11
  import { URL } from 'node:url';
11
12
 
13
+ import { MAX_BODY_BYTES as MAX_INJECT_BODY_BYTES } from './prompt-inject.mjs';
14
+
12
15
  // hop 头不转发(与本地转发器同款约定)
13
16
  const HOP_HEADERS = new Set(['connection', 'keep-alive', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'proxy-authenticate', 'proxy-authorization']);
14
17
 
@@ -20,8 +23,34 @@ function stripHopHeaders(headers) {
20
23
  return o;
21
24
  }
22
25
 
23
- function parseProxyUrl(raw) {
24
- const text = String(raw || '').trim();
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();
25
54
  if (!text) return null;
26
55
  try {
27
56
  const u = new URL(text);
@@ -45,50 +74,33 @@ function proxyAuthHeaders(proxy) {
45
74
  return { 'Proxy-Authorization': `Basic ${basic}` };
46
75
  }
47
76
 
48
- // 经上游代理建 CONNECT 隧道;secure=true 时隧道 ESTABLISHED 后再把同一
49
- // socket 包装成 TLS(SNI 为上游主机名)。
50
- function proxyConnect(proxy, host, port, { secure = false } = {}) {
77
+ // 在一条已建立的 socket(可能是直连,也可能已经过若干层 CONNECT 隧道)上,
78
+ // 让当前代理建一条通往 host:port 的 CONNECT 隧道。成功后 resolve 同一个 socket,
79
+ // 后续的 CONNECT 或最终请求都从它读写。多级串联靠这个逐层叠加。
80
+ function connectThrough(socket, proxy, host, port) {
51
81
  return new Promise((resolve, reject) => {
52
- const useTls = proxy.protocol === 'https:';
53
- const connectOpts = { host: proxy.hostname, port: proxy.port, timeout: 15000 };
54
- const socket = useTls
55
- ? tls.connect({ ...connectOpts, servername: proxy.hostname, rejectUnauthorized: false })
56
- : net.connect(connectOpts);
57
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
+ };
58
88
  const fail = (err) => {
59
89
  if (settled) return;
60
90
  settled = true;
61
- try { socket.removeListener('data', onData); } catch { /* ignore */ }
91
+ cleanup();
62
92
  try { socket.destroy(); } catch { /* ignore */ }
63
93
  reject(err);
64
94
  };
65
95
  const succeed = () => {
66
96
  if (settled) return;
67
97
  settled = true;
68
- if (secure) {
69
- const secureSocket = tls.connect({ socket, servername: host, rejectUnauthorized: false });
70
- secureSocket.once('secureConnect', () => resolve(secureSocket));
71
- secureSocket.once('error', (err) => {
72
- try { socket.destroy(); } catch { /* ignore */ }
73
- reject(err);
74
- });
75
- } else {
76
- resolve(socket);
77
- }
98
+ cleanup();
99
+ resolve(socket);
78
100
  };
79
- const sendConnect = () => {
80
- socket.write([
81
- `CONNECT ${host}:${port} HTTP/1.1`,
82
- `Host: ${host}:${port}`,
83
- 'User-Agent: zcode-pro-provider-proxy',
84
- ...Object.entries(proxyAuthHeaders(proxy)).map(([k, v]) => `${k}: ${v}`),
85
- '',
86
- '',
87
- ].join('\r\n'));
88
- };
89
- if (useTls) socket.once('secureConnect', sendConnect);
90
- else socket.once('connect', sendConnect);
91
- socket.once('error', fail);
101
+ const onError = (err) => fail(err);
102
+ const onClose = () => fail(new Error('代理连接在握手前关闭'));
103
+ // CONNECT 响应头可能和后续数据粘在同一个 chunk 里:把多出来的字节 unshift 回 socket
92
104
  let buf = Buffer.alloc(0);
93
105
  const onData = (chunk) => {
94
106
  try {
@@ -96,26 +108,81 @@ function proxyConnect(proxy, host, port, { secure = false } = {}) {
96
108
  const idx = buf.indexOf('\r\n\r\n');
97
109
  if (idx === -1) return;
98
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; }
99
113
  const rest = buf.slice(idx + 4);
100
- const m = /^HTTP\/\d+\.?\d*\s+(\d+)/.exec(head);
101
- const code = m ? Number(m[1]) : 0;
102
- if (code < 200 || code >= 300) {
103
- fail(new Error(`代理 CONNECT 返回 ${code || '空'}`));
104
- return;
105
- }
106
- try { socket.removeListener('data', onData); } catch { /* ignore */ }
107
- if (rest && rest.length) {
108
- queueMicrotask(() => socket.unshift(rest));
109
- }
114
+ if (rest.length) queueMicrotask(() => socket.unshift(rest));
110
115
  succeed();
111
- } catch (err) {
112
- fail(err);
113
- }
116
+ } catch (err) { fail(err); }
114
117
  };
118
+ socket.once('error', onError);
119
+ socket.once('close', onClose);
115
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'));
116
129
  });
117
130
  }
118
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
+
119
186
  function pipePair(a, b) {
120
187
  a.pipe(b);
121
188
  b.pipe(a);
@@ -130,16 +197,78 @@ function pipePair(a, b) {
130
197
  }
131
198
 
132
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
+
133
230
  class ProviderForwarder {
134
- constructor({ upstream, proxyUrl }) {
231
+ constructor({ upstream, proxyUrls }) {
135
232
  this.upstream = String(upstream || '').trim();
136
- this.proxyUrl = String(proxyUrl || '').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] || '';
137
237
  this.server = null;
138
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;
139
248
  }
140
249
 
141
250
  setUpstream(url) { this.upstream = String(url || '').trim(); }
142
- setProxyUrl(v) { this.proxyUrl = String(v || '').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; }
143
272
 
144
273
  async start(port) {
145
274
  if (this.server) await this.stop();
@@ -184,13 +313,21 @@ class ProviderForwarder {
184
313
  }
185
314
 
186
315
  async openUpstream(host, port, secureFirst) {
187
- // 本机回环不上代理:供应商走 headroom(8787)又开供应商代理时,
188
- // 转发器连 headroom 是本机流量,经 clash 发反而到不了。
316
+ // 本机回环默认不上代理:供应商走 headroom(8787)又开供应商代理时,
317
+ // 转发器连 headroom 是本机流量,用普通代理(如 clash)发出反而到不了。
318
+ // 例外:loopbackProxy=true——链上自定义代理排在 headroom 之前(如破盾框架
319
+ // 必须先过),由调用方明确要求连本机也走代理
189
320
  const loopback = host === '127.0.0.1' || host === 'localhost' || host === '::1';
190
- const proxy = loopback ? null : parseProxyUrl(this.proxyUrl);
191
- if (proxy) {
192
- // 有代理统一走 CONNECT 隧道建连
193
- return proxyConnect(proxy, host, port, { secure: secureFirst });
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 });
194
331
  }
195
332
  if (secureFirst) {
196
333
  return new Promise((resolve, reject) => {
@@ -207,7 +344,8 @@ class ProviderForwarder {
207
344
  }
208
345
 
209
346
  async handle(req, res) {
210
- const upstreamRaw = String(this.upstream || '').trim();
347
+ // 上游可能是固定的,也可能按请求里的 API key 动态决定(代理链压缩后的分流)
348
+ const upstreamRaw = String(this.resolveUpstream(req) || '').trim();
211
349
  if (!upstreamRaw) {
212
350
  res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
213
351
  res.end('未配置上游地址');
@@ -227,7 +365,6 @@ class ProviderForwarder {
227
365
  // 上游带路径前缀(如 https://host/v1)时拼到每个请求前面:
228
366
  // 转发地址本身不带路径,客户端发的是裸路径。
229
367
  const upstreamPrefix = parsed.pathname && parsed.pathname !== '/' ? parsed.pathname.replace(/\/+$/, '') : '';
230
-
231
368
  let tunnel;
232
369
  try {
233
370
  tunnel = await this.openUpstream(targetHost, targetPort, secureFirst);
@@ -239,11 +376,54 @@ class ProviderForwarder {
239
376
  this.conns.add(tunnel);
240
377
  tunnel.once('close', () => this.conns.delete(tunnel));
241
378
 
242
- // 用 http/https 客户端发请求:它负责拼请求字节、解析响应状态行与响应头、
243
- // 处理分块编码;SSE 等流式响应照样逐块透出。
379
+ // 转发请求头(去掉 hop-by-hop 与 host,host 换成上游的)
244
380
  const headers = stripHopHeaders(req.headers);
245
381
  delete headers.host;
246
- const path = upstreamPrefix + (req.url || '/');
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 || '/');
247
427
  const client = secureFirst ? https : http;
248
428
  const agent = new client.Agent({ keepAlive: false });
249
429
  agent.createConnection = () => tunnel;
@@ -266,7 +446,9 @@ class ProviderForwarder {
266
446
  });
267
447
  req.once('aborted', () => { try { upReq.destroy(); } catch { /* ignore */ } });
268
448
  res.once('close', () => { try { upReq.destroy(); } catch { /* ignore */ } });
269
- req.pipe(upReq, { end: true });
449
+ if (rewritten) upReq.end(rewritten);
450
+ else if (consumed) upReq.end(consumed);
451
+ else req.pipe(upReq, { end: true });
270
452
  }
271
453
  }
272
454
 
@@ -274,24 +456,58 @@ class ProviderForwarder {
274
456
  export class ProviderProxyManager {
275
457
  constructor() {
276
458
  this.forwarders = new Map(); // port → ProviderForwarder
459
+ this.injector = null; // 注入钩子:ensure 没显式传时沿用它
277
460
  }
278
461
 
279
- async ensure({ upstream, port, proxyUrl = '' }) {
462
+ async ensure({ upstream, port, proxyUrls, injector, upstreamResolver, loopbackProxy, opencodeGoCompat = false }) {
280
463
  upstream = String(upstream || '').trim();
281
- proxyUrl = String(proxyUrl || '').trim();
282
- if (!upstream) throw new Error('未配置上游地址');
283
- // 按端口复用:同端口的上游/代理都没变就直接用;变了原地重启(不留双实例)。
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
+ // 按端口复用:同端口的上游/代理链都没变就直接用;变了原地重启(不留双实例)。
284
484
  // 不按上游找——两个供应商可能共用一个上游地址,按上游找会互抢。
285
485
  const existing = this.forwarders.get(port);
286
486
  if (existing) {
287
- if (existing.upstream === upstream && existing.proxyUrl === proxyUrl && existing.alive()) return port;
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
+ }
288
497
  existing.setUpstream(upstream);
289
- existing.setProxyUrl(proxyUrl);
498
+ existing.setProxyUrls(urls);
499
+ existing.setUpstreamResolver(upstreamResolver || null);
500
+ existing.setLoopbackProxy(loopbackProxy === true);
290
501
  await existing.stop();
291
502
  await existing.start(port);
292
503
  return port;
293
504
  }
294
- const fw = new ProviderForwarder({ upstream, proxyUrl });
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);
295
511
  await fw.start(port);
296
512
  this.forwarders.set(port, fw);
297
513
  return port;
@@ -305,6 +521,16 @@ export class ProviderProxyManager {
305
521
  return true;
306
522
  }
307
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
+
308
534
  async freePort(preferred) {
309
535
  for (let p = preferred; p <= 65535; p++) {
310
536
  if (this.forwarders.has(p)) continue;
@@ -328,7 +554,7 @@ export class ProviderProxyManager {
328
554
 
329
555
  status() {
330
556
  return [...this.forwarders.entries()].map(([port, fw]) => ({
331
- port, upstream: fw.upstream, proxyUrl: fw.proxyUrl, listening: fw.alive(),
557
+ port, upstream: fw.upstream, proxyUrl: fw.proxyUrl, proxyUrls: fw.proxyUrls, listening: fw.alive(),
332
558
  }));
333
559
  }
334
560
  }
@@ -0,0 +1,137 @@
1
+ // 代理链:一条链是有序的节点序列,可关联多个供应商。
2
+ // 节点顺序即执行顺序——压缩在前就先进 headroom,注入在前就先改请求体。
3
+ // 这条规则是为了让「先压缩再注入」和「先注入再压缩」都成立:headroom 是透传代理,
4
+ // 压缩完才把请求发给下一跳,所以注入只有在 headroom 之后才能拿到压缩后的内容。
5
+ //
6
+ // 节点类型:
7
+ // - headroom:把请求交给本地压缩路由(8787),由它压缩后转发给链的下一跳
8
+ // - inject:把提示词注入的正文追加到请求的 system 末尾
9
+ // - custom:经自定义代理(或多级串联)出网
10
+ const NODE_TYPES = new Set(['headroom', 'inject', 'custom']);
11
+ const PROXY_URL_RE = /^https?:\/\/\S+:\d+$/;
12
+
13
+ // 归一化一条链:id/name/providers/nodes。非法节点丢弃,顺序保留。
14
+ export function normalizeChain(entry, sharedProxies) {
15
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null;
16
+ const id = typeof entry.id === 'string' ? entry.id.trim().slice(0, 64) : '';
17
+ if (!id) return null;
18
+ const name = typeof entry.name === 'string' && entry.name.trim()
19
+ ? entry.name.trim().slice(0, 60) : id;
20
+ const providers = [];
21
+ for (const p of Array.isArray(entry.providers) ? entry.providers : []) {
22
+ if (typeof p !== 'string' || !p.trim()) continue;
23
+ if (p === '__proto__' || p === 'constructor' || p === 'prototype') continue;
24
+ if (!providers.includes(p)) providers.push(p);
25
+ if (providers.length >= 64) break;
26
+ }
27
+ const nodes = [];
28
+ for (const n of Array.isArray(entry.nodes) ? entry.nodes : []) {
29
+ if (nodes.length >= 8) break;
30
+ if (!n || typeof n !== 'object' || !NODE_TYPES.has(n.type)) continue;
31
+ if (n.type === 'custom') {
32
+ const proxy = typeof n.proxy === 'string' ? n.proxy.trim().slice(0, 300) : '';
33
+ const proxyId = typeof n.proxyId === 'string' ? n.proxyId.trim().slice(0, 64) : '';
34
+ if (proxy && !PROXY_URL_RE.test(proxy)) continue; // 填错地址的节点丢弃
35
+ if (!proxy && !proxyId) { nodes.push({ type: 'custom', proxy: '' }); continue; } // 空位保留等填写
36
+ nodes.push(proxy ? { type: 'custom', proxy } : { type: 'custom', proxyId });
37
+ continue;
38
+ }
39
+ // 同类型节点只留一个(headroom / inject 各至多一个),重复的丢弃
40
+ if (nodes.some((x) => x.type === n.type)) continue;
41
+ nodes.push({ type: n.type });
42
+ }
43
+ // 端口:链级(一条链一个转发器),不是每供应商一个
44
+ const port = Number.isFinite(Number(entry.port)) && Number(entry.port) >= 1024 && Number(entry.port) <= 65535
45
+ ? Math.round(Number(entry.port)) : null;
46
+ const enabled = entry.enabled !== false;
47
+ // 供应商 → 真实上游。链首不是 headroom 时 ZCode 直连链转发器,转发器只能按
48
+ // API key 反查该发给谁;这个映射就是唯一来源(此时不依赖 headroom.json)。
49
+ // 注意:这里不按 providers 裁剪——供应商被移出链时,还要靠这份记录把它的
50
+ // baseUrl 还原成真实上游(见 chainUpstreamForProvider)。记录留着不占多少空间,
51
+ // 丢了就没法还原了
52
+ const upstreams = {};
53
+ const rawUp = entry.upstreams && typeof entry.upstreams === 'object' && !Array.isArray(entry.upstreams)
54
+ ? entry.upstreams : {};
55
+ for (const [pid, u] of Object.entries(rawUp)) {
56
+ if (pid === '__proto__' || pid === 'constructor' || pid === 'prototype') continue;
57
+ if (typeof u !== 'string') continue;
58
+ const t = u.trim().slice(0, 500);
59
+ if (!/^https?:\/\/\S+$/i.test(t)) continue;
60
+ upstreams[pid] = t;
61
+ if (Object.keys(upstreams).length >= 64) break;
62
+ }
63
+ // 兼容端口:由“逐家转发”迁移出来的链,保留原来各家供应商的转发端口。
64
+ // ZCode 里还在用旧地址的会话照常能连上——对齐时在这些端口上各起一个“原样转到
65
+ // 链入口”的转发器(不注入,注入只在链转发器里做一次)。合法的端口整数,最多 16 个
66
+ const legacyPorts = [];
67
+ for (const lp of Array.isArray(entry.legacyPorts) ? entry.legacyPorts : []) {
68
+ const n = Math.round(Number(lp));
69
+ if (!Number.isFinite(n) || n < 1024 || n > 65535 || legacyPorts.includes(n)) continue;
70
+ legacyPorts.push(n);
71
+ if (legacyPorts.length >= 16) break;
72
+ }
73
+ return { id, name, providers, nodes, port, enabled, upstreams, ...(legacyPorts.length ? { legacyPorts } : {}) };
74
+ }
75
+
76
+ export function normalizeChains(saved, sharedProxies) {
77
+ const list = Array.isArray(saved) ? saved : [];
78
+ const out = [];
79
+ const seen = new Set();
80
+ for (const e of list) {
81
+ const c = normalizeChain(e, sharedProxies);
82
+ if (!c || seen.has(c.id)) continue;
83
+ seen.add(c.id);
84
+ out.push(c);
85
+ if (out.length >= 32) break;
86
+ }
87
+ return out;
88
+ }
89
+
90
+ // 某供应商属于哪条链:第一条声明了它的链生效(界面保证不重复关联)
91
+ export function chainForProvider(chains, providerId) {
92
+ for (const c of Array.isArray(chains) ? chains : []) {
93
+ if (c && Array.isArray(c.providers) && c.providers.includes(providerId)) return c;
94
+ }
95
+ return null;
96
+ }
97
+
98
+ // 链的第一跳是什么:headroom 在链首时,ZCode 的地址要指向 8787 路由;
99
+ // 否则指向链自己的转发器端口。
100
+ export function chainEntryType(chain) {
101
+ const first = chain && Array.isArray(chain.nodes) ? chain.nodes[0] : null;
102
+ return first && first.type === 'headroom' ? 'headroom' : 'forwarder';
103
+ }
104
+
105
+ // 链上所有自定义代理节点解析成地址列表(按顺序),引用共享代理的按 id 查表。
106
+ export function resolveCustomProxies(nodes, sharedProxies) {
107
+ const out = [];
108
+ for (const n of Array.isArray(nodes) ? nodes : []) {
109
+ if (!n || n.type !== 'custom') continue;
110
+ let url = '';
111
+ if (typeof n.proxy === 'string' && n.proxy) url = n.proxy;
112
+ else if (typeof n.proxyId === 'string' && n.proxyId) {
113
+ const hit = (Array.isArray(sharedProxies) ? sharedProxies : []).find((e) => e && e.id === n.proxyId);
114
+ url = hit && typeof hit.url === 'string' ? hit.url : '';
115
+ }
116
+ if (url) out.push(url);
117
+ }
118
+ return out;
119
+ }
120
+
121
+ // 链上某个节点之前是否已经有 headroom:决定注入拿到的是压缩前还是压缩后的内容
122
+ export function headroomRunsBefore(chain, nodeType) {
123
+ const nodes = chain && Array.isArray(chain.nodes) ? chain.nodes : [];
124
+ for (const n of nodes) {
125
+ if (n.type === nodeType) return false;
126
+ if (n.type === 'headroom') return true;
127
+ }
128
+ return false;
129
+ }
130
+
131
+ // 链是否需要注入(链上有 inject 节点且有正文)。注入功能没有启停开关,
132
+ // 勾选就是唯一开关
133
+ export function chainNeedsInject(chain, promptInjection) {
134
+ if (!chain || !Array.isArray(chain.nodes)) return false;
135
+ if (!chain.nodes.some((n) => n.type === 'inject')) return false;
136
+ return !!(promptInjection && typeof promptInjection.text === 'string' && promptInjection.text.trim());
137
+ }