mslxdff 0.1.185 → 0.1.187

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mslxdff",
3
- "version": "0.1.185",
3
+ "version": "0.1.187",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,7 +13,7 @@ import { createOpenCodeProvider } from "../providers/opencode.js";
13
13
  import { loadProviderKeys, loadProviderAuths, loadProviderConfigs } from "../state.js";
14
14
  import { refreshIntervalMs, modelCooldownMs, slowCooldownMs, peerCooldownMs, peerLimitCooldownMs, peerHeatMs, banWindowMs, banThreshold } from "../cli/policy.js";
15
15
  import { errMsg } from "../cli/util.js";
16
- import { createWarpDispatcher } from "../warp-pool/index.js";
16
+ import { createPreferredDispatcher } from "../v6pool/index.js";
17
17
 
18
18
 
19
19
  import { shouldEnableCustomProvider, loadAuthDocs } from "./provider-gate.js";
@@ -51,7 +51,7 @@ export async function setupProviders() {
51
51
  const baseUrl = process.env.UPSTREAM_BASE_URL || "https://opencode.ai";
52
52
  let providers = [];
53
53
 
54
- const warpDispatcher = createWarpDispatcher({ baseUrl });
54
+ const outboundDispatcher = createPreferredDispatcher({ baseUrl });
55
55
  if (providerPlugin) {
56
56
  if (!upstream) {
57
57
  try {
@@ -63,9 +63,9 @@ export async function setupProviders() {
63
63
  appendEvent({ ts: Date.now(), type: "plugin-upstream-error", plugin: providerPlugin.name, error: errMsg(err) });
64
64
  }
65
65
  }
66
- if (!upstream) upstream = createUpstreamClient({ hooks: upstreamHooks, dispatcher: warpDispatcher });
66
+ if (!upstream) upstream = createUpstreamClient({ hooks: upstreamHooks, dispatcher: outboundDispatcher });
67
67
  } else {
68
- const opencodeClient = createUpstreamEngine({ hooks: upstreamHooks, dispatcher: warpDispatcher });
68
+ const opencodeClient = createUpstreamEngine({ hooks: upstreamHooks, dispatcher: outboundDispatcher });
69
69
  const opencodeModels = createModelsService({
70
70
  baseUrl,
71
71
  headers: opencodeClient.headers,
@@ -0,0 +1,157 @@
1
+ // v6pool · 让内核接受池里的源地址(bind 直用 / ip addr add 认领)+ 认领账 + 释放。
2
+ //
3
+ // 两条路(Linux 上 bind() 一个没分配给本机的源地址会直接 EADDRNOTAVAIL):
4
+ // bind:net.ipv6.ip_nonlocal_bind=1 ⇒ 直接 bind 任意地址,**不碰网卡**(首选,零副作用);
5
+ // add :ip -6 addr add <addr>/128 dev <iface> nodad ⇒ 加进网卡(需 root)。
6
+ //
7
+ // 为什么要记账(本轮手工实测的教训):加进网卡的地址会改变内核的**默认源地址选择**——
8
+ // 我在 A 机上留了两个临时地址,结果不带 --interface 的请求也走了新地址(生产机上这是事故)。
9
+ // 所以:每次 add/del 都落 `<dir>/claimed.json`(0600、非工作树);close 时全部释放;
10
+ // 启动时按这份账清上一代残留(崩溃 / 被 SIGKILL 时 close 跑不到)。
11
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { execFile, execFileSync } from "node:child_process";
14
+ import { fmtClaim, fmtClaimFail, fmtSweep } from "./report.js";
15
+
16
+ export const CLAIM_FILE = "claimed.json";
17
+
18
+ /** 默认执行器:失败时把 stderr 原文带进 Error(不许把 stderr 吞掉——否则只剩「失败了」)。 */
19
+ export function defaultExec(file, args, { timeoutMs = 10_000 } = {}) {
20
+ return new Promise((resolve, reject) => {
21
+ execFile(file, args, { timeout: timeoutMs }, (err, stdout, stderr) => {
22
+ if (err) {
23
+ const e = new Error(`${file} ${args.join(" ")} 失败:${String(stderr || err.message || "").trim()}`);
24
+ e.code = err.code;
25
+ e.stderr = String(stderr || "");
26
+ reject(e);
27
+ return;
28
+ }
29
+ resolve({ stdout: String(stdout || ""), stderr: String(stderr || "") });
30
+ });
31
+ });
32
+ }
33
+
34
+ /** 退出钩子专用(同步):`process.on("exit")` 里跑不了 async,但地址必须清。 */
35
+ export function defaultExecSync(file, args, { timeoutMs = 10_000 } = {}) {
36
+ execFileSync(file, args, { timeout: timeoutMs, stdio: "ignore" });
37
+ }
38
+
39
+ /** 幂等判据:`ip addr add` 报 File exists = 已经在网卡上了,不算失败。 */
40
+ export function isAlreadyThere(e) {
41
+ return /File exists|already assigned/i.test(String(e?.stderr || e?.message || ""));
42
+ }
43
+
44
+ /** 释放时「它已经不在了」也不算失败(上一代残留已被别处清掉 / 手工删掉)。 */
45
+ export function isAlreadyGone(e) {
46
+ return /Cannot assign requested address|Cannot find device|does not exist/i.test(String(e?.stderr || e?.message || ""));
47
+ }
48
+
49
+ /**
50
+ * @param {{ iface?: string, mode?: "bind"|"add", dir?: string, log?: (s:string)=>void, exec?: Function, fs?: object }} opts
51
+ */
52
+ export function createClaimer({ iface = "", mode = "bind", dir = "", log = () => {}, exec = defaultExec, fs = { mkdirSync, writeFileSync, chmodSync, readFileSync } } = {}) {
53
+ /** 只有 add 模式需要记账(bind 模式没改网卡,无残留可言)。 */
54
+ const claimed = new Set();
55
+
56
+ function persist() {
57
+ try {
58
+ fs.mkdirSync(dir, { recursive: true });
59
+ const file = join(dir, CLAIM_FILE);
60
+ fs.writeFileSync(file, `${JSON.stringify({ iface, mode, addrs: [...claimed], updatedAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
61
+ fs.chmodSync(file, 0o600); // mode 只在新建时生效,存量必须补
62
+ } catch (e) {
63
+ log(`[v6pool] ⚠ 认领账写盘失败(本次照跑,但崩溃后无法自动清残留):${String(e?.message || e)}`);
64
+ }
65
+ }
66
+
67
+ async function ensure(addr) {
68
+ if (mode !== "add") return addr;
69
+ try {
70
+ await exec("ip", ["-6", "addr", "add", `${addr}/128`, "dev", iface, "nodad"]);
71
+ log(fmtClaim({ addr, iface }));
72
+ } catch (e) {
73
+ if (!isAlreadyThere(e)) {
74
+ log(fmtClaimFail({ addr, iface, error: String(e?.message || e) }));
75
+ throw e;
76
+ }
77
+ }
78
+ claimed.add(addr);
79
+ persist();
80
+ return addr;
81
+ }
82
+
83
+ async function release(addr) {
84
+ if (mode !== "add" || !claimed.has(addr)) return false;
85
+ claimed.delete(addr);
86
+ persist();
87
+ try {
88
+ await exec("ip", ["-6", "addr", "del", `${addr}/128`, "dev", iface]);
89
+ return true;
90
+ } catch (e) {
91
+ if (isAlreadyGone(e)) return false;
92
+ log(`[v6pool] ⚠ 释放源地址失败(重启时由启动清残留兜底):${addr} — ${String(e?.stderr || e?.message || "").trim()}`);
93
+ return false;
94
+ }
95
+ }
96
+
97
+ async function releaseAll() {
98
+ const done = [];
99
+ for (const a of [...claimed]) if (await release(a)) done.push(a);
100
+ return done;
101
+ }
102
+
103
+ /** 退出钩子专用:进程正在退出,只能跑同步命令;清不掉的交给下次启动的 sweepStale。 */
104
+ function releaseAllSync({ execSync = defaultExecSync } = {}) {
105
+ if (mode !== "add" || !claimed.size) return [];
106
+ const done = [];
107
+ for (const a of [...claimed]) {
108
+ try {
109
+ execSync("ip", ["-6", "addr", "del", `${a}/128`, "dev", iface]);
110
+ done.push(a);
111
+ } catch {
112
+ /* 删不掉不抛:进程正在退出,抛了也没人接 */
113
+ }
114
+ }
115
+ claimed.clear();
116
+ return done;
117
+ }
118
+
119
+ /** 启动清残留:只删**上一代自己记在账上的**地址,绝不猜(不扫全表,不碰别人的地址)。 */
120
+ async function sweepStale() {
121
+ if (mode !== "add") return { removed: [], failed: [] };
122
+ let prev = [];
123
+ try {
124
+ prev = JSON.parse(fs.readFileSync(join(dir, CLAIM_FILE), "utf8"))?.addrs || [];
125
+ } catch {
126
+ return { removed: [], failed: [] };
127
+ }
128
+ const removed = [];
129
+ const failed = [];
130
+ for (const a of prev) {
131
+ if (typeof a !== "string" || !a) continue;
132
+ try {
133
+ await exec("ip", ["-6", "addr", "del", `${a}/128`, "dev", iface]);
134
+ removed.push(a);
135
+ } catch (e) {
136
+ if (!isAlreadyGone(e)) failed.push({ addr: a, error: String(e?.stderr || e?.message || "").trim() });
137
+ }
138
+ }
139
+ claimed.clear();
140
+ persist();
141
+ const r = { removed, failed };
142
+ if (removed.length || failed.length) log(fmtSweep({ iface, ...r }));
143
+ return r;
144
+ }
145
+
146
+ return {
147
+ ensure,
148
+ release,
149
+ releaseAll,
150
+ releaseAllSync,
151
+ sweepStale,
152
+ claimed: () => [...claimed],
153
+ get mode() {
154
+ return mode;
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,65 @@
1
+ // v6pool · 配置解析:env 优先,缺省值集中一处;纯函数,便于单测。
2
+ import { join } from "node:path";
3
+ import { logDir } from "../logs.js";
4
+
5
+ /**
6
+ * 缺省**开** + **自动判断**:本机有整段路由的 IPv6 前缀就启用(判据见 detect.js),
7
+ * 没有就诚实跳过(行为与今天完全一致)。判据不靠 env,靠事实。
8
+ */
9
+ export const DEFAULTS = {
10
+ enabled: true,
11
+ count: 4,
12
+ strategy: "session",
13
+ cooldownMs: 600_000,
14
+ rotate: true,
15
+ minHostBits: 8,
16
+ claim: "auto",
17
+ probePath: "/zen/v1/models",
18
+ retireMs: 60_000,
19
+ debug: false,
20
+ };
21
+
22
+ const OFF = ["0", "off", "false", "no", "disable", "disabled"];
23
+ const CLAIM_MODES = ["auto", "bind", "add"];
24
+
25
+ function envBool(env, name, fallback) {
26
+ const raw = env[name];
27
+ if (raw === undefined || raw === null || raw === "") return fallback;
28
+ return !OFF.includes(String(raw).trim().toLowerCase());
29
+ }
30
+
31
+ function envInt(env, name, fallback) {
32
+ const v = Number(env[name]);
33
+ return Number.isInteger(v) && v > 0 ? v : fallback;
34
+ }
35
+
36
+ function envStr(env, name, fallback) {
37
+ const raw = env[name];
38
+ return typeof raw === "string" && raw.trim() ? raw.trim() : fallback;
39
+ }
40
+
41
+ /**
42
+ * 解析 v6 出口池配置。
43
+ * @param {Record<string,string|undefined>} env
44
+ * @param {{ logDirFn?: () => string }} [deps] 测试可注入 logDir
45
+ */
46
+ export function resolveV6Config(env = process.env, { logDirFn = logDir } = {}) {
47
+ const strategy = envStr(env, "MSLXDFF_V6_STRATEGY", DEFAULTS.strategy) === "request" ? "request" : "session";
48
+ const claimRaw = envStr(env, "MSLXDFF_V6_CLAIM", DEFAULTS.claim).toLowerCase();
49
+ return {
50
+ enabled: envBool(env, "MSLXDFF_V6_POOL", DEFAULTS.enabled),
51
+ /** 显式池前缀(`2001:db8::/64`);空 = 取本机全局地址的前缀 */
52
+ prefix: envStr(env, "MSLXDFF_V6_PREFIX", ""),
53
+ iface: envStr(env, "MSLXDFF_V6_IFACE", ""),
54
+ count: envInt(env, "MSLXDFF_V6_COUNT", DEFAULTS.count),
55
+ strategy,
56
+ cooldownMs: envInt(env, "MSLXDFF_V6_COOLDOWN_MS", DEFAULTS.cooldownMs),
57
+ rotate: envBool(env, "MSLXDFF_V6_ROTATE", DEFAULTS.rotate),
58
+ minHostBits: envInt(env, "MSLXDFF_V6_MIN_HOST_BITS", DEFAULTS.minHostBits),
59
+ claim: CLAIM_MODES.includes(claimRaw) ? claimRaw : DEFAULTS.claim,
60
+ dir: envStr(env, "MSLXDFF_V6_DIR", join(logDirFn(), "v6pool")),
61
+ probePath: envStr(env, "MSLXDFF_V6_PROBE_PATH", DEFAULTS.probePath),
62
+ retireMs: envInt(env, "MSLXDFF_V6_RETIRE_MS", DEFAULTS.retireMs),
63
+ debug: envBool(env, "MSLXDFF_V6_DEBUG", DEFAULTS.debug),
64
+ };
65
+ }
@@ -0,0 +1,130 @@
1
+ // v6pool · 自动判断本机有没有可用的 IPv6 池(纯解析 + 可注入 IO,便于单测)。
2
+ //
3
+ // 四关,任一不过就诚实跳过(并给出「下一步该跑什么」):
4
+ // ① 平台:只有 Linux 能读 /proc 并用 ip 命令(与 wireproxy 预编译平台限制同口径);
5
+ // ② 地址:/proc/net/if_inet6 里必须有 scope=global 的地址;
6
+ // ③ 前缀:该地址的前缀主机位 ≥ minHostBits(/128 只有 1 个地址,不构成池);
7
+ // ④ 认领:ip_nonlocal_bind=1(直接 bind,零改动)或 root(能 ip addr add)。
8
+ //
9
+ // ⚠ 本模块**不假装知道**「整段有没有真路由到本机」——那只能靠 probe.js 从池里的地址实测。
10
+ // 内核接受地址(bind 成功)≠ 机房把回包送回来;两者混为一谈正是「池看起来就绪、请求全黑洞」的根因。
11
+ import { readFileSync } from "node:fs";
12
+ import { formatV6, hostBitsOf, networkOf, parsePrefix, parseV6 } from "./prefix.js";
13
+
14
+ /** /proc/net/if_inet6 的 scope 列:00=global、10=host、20=link、40=site(都是 hex)。 */
15
+ export const SCOPE_GLOBAL = 0;
16
+
17
+ /** 解析 /proc/net/if_inet6:`<32 位 hex 地址> <ifindex> <prefixlen> <scope> <flags> <网卡>`。 */
18
+ export function parseIfInet6(raw) {
19
+ const out = [];
20
+ for (const line of String(raw ?? "").split("\n")) {
21
+ const f = line.trim().split(/\s+/);
22
+ if (f.length < 6 || !/^[0-9a-f]{32}$/i.test(f[0])) continue;
23
+ const addr = parseV6(f[0].toLowerCase().match(/.{4}/g).join(":"));
24
+ if (addr === null) continue;
25
+ out.push({
26
+ addr,
27
+ text: formatV6(addr),
28
+ ifindex: parseInt(f[1], 16),
29
+ bits: parseInt(f[2], 16),
30
+ scope: parseInt(f[3], 16),
31
+ iface: f[5],
32
+ });
33
+ }
34
+ return out;
35
+ }
36
+
37
+ function skip(reason, hint) {
38
+ return { ok: false, reason, hint };
39
+ }
40
+
41
+ /**
42
+ * 四关判定:把「本机事实」变成「可用池 或 具体跳过原因」。
43
+ * 全部依赖注入(测试不用真读 /proc、不用真 root)。
44
+ */
45
+ export function pickPool({
46
+ entries = [],
47
+ nonlocalBind = 0,
48
+ uid = -1,
49
+ platform = process.platform,
50
+ explicitPrefix = "",
51
+ explicitIface = "",
52
+ minHostBits = 8,
53
+ claim = "auto",
54
+ } = {}) {
55
+ if (platform !== "linux") {
56
+ return skip(`本平台(${platform})不支持:需要 Linux 的 /proc 与 ip 命令`, "非 Linux 机器不需要本功能(WARP 池同样只在 Linux 可用)");
57
+ }
58
+ const globals = entries.filter((e) => e.scope === SCOPE_GLOBAL);
59
+ let addr;
60
+ let bits;
61
+ let iface;
62
+ let source;
63
+ if (explicitPrefix) {
64
+ const p = parsePrefix(explicitPrefix);
65
+ if (!p) return skip(`MSLXDFF_V6_PREFIX 解析失败:${explicitPrefix}`, "格式形如 2001:db8:1:2::/64");
66
+ addr = p.addr;
67
+ bits = p.bits;
68
+ source = "env";
69
+ iface = explicitIface || globals[0]?.iface || "";
70
+ } else {
71
+ if (!globals.length) {
72
+ return skip("本机没有任何全局 IPv6 地址(只有 link-local / loopback)", "确认网卡上启用了 IPv6,且运营商或机房确实给了 IPv6");
73
+ }
74
+ const picked = (explicitIface && globals.find((e) => e.iface === explicitIface)) || globals[0];
75
+ addr = picked.addr;
76
+ bits = picked.bits;
77
+ iface = explicitIface || picked.iface;
78
+ source = "proc";
79
+ }
80
+ const hostBits = hostBitsOf(bits);
81
+ if (hostBits < minHostBits) {
82
+ return skip(
83
+ `前缀 /${bits} 只有 ${hostBits} 位主机位(< ${minHostBits}),不构成池`,
84
+ `该地址是 /${bits}:整段没路由到本机时换不了 IP。若确认整段可用,用 MSLXDFF_V6_PREFIX=<段>/<位数> 显式指定`,
85
+ );
86
+ }
87
+ const mode = claim === "auto" ? (nonlocalBind === 1 ? "bind" : uid === 0 ? "add" : "none") : claim;
88
+ if (mode === "bind" && nonlocalBind !== 1) {
89
+ return skip("MSLXDFF_V6_CLAIM=bind 但 net.ipv6.ip_nonlocal_bind≠1", "sysctl -w net.ipv6.ip_nonlocal_bind=1,或改用 MSLXDFF_V6_CLAIM=add");
90
+ }
91
+ if (mode === "add" && uid !== 0) {
92
+ return skip(`MSLXDFF_V6_CLAIM=add 需要 root(当前 uid=${uid})`, "以 root 跑 daemon,或 sysctl -w net.ipv6.ip_nonlocal_bind=1 后设 MSLXDFF_V6_CLAIM=bind");
93
+ }
94
+ if (mode === "none") {
95
+ return skip("既没有 ip_nonlocal_bind=1,也不是 root ⇒ 内核会拒绝 bind 池里的地址(EADDRNOTAVAIL)", "二选一:sysctl -w net.ipv6.ip_nonlocal_bind=1,或以 root 跑(可 ip addr add)");
96
+ }
97
+ return {
98
+ ok: true,
99
+ addr,
100
+ bits,
101
+ iface,
102
+ hostBits,
103
+ mode,
104
+ source,
105
+ prefix: `${formatV6(networkOf(addr, bits))}/${bits}`,
106
+ /** 本机自己的全局地址:造池时避开它们(别把机器正在用的地址当池里的"新"地址) */
107
+ mine: globals.map((e) => e.text),
108
+ };
109
+ }
110
+
111
+ /** 真机路径:读 /proc 与 /proc/sys(可整体注入,测试零 IO)。 */
112
+ export function detectPool({ cfg = {}, entries, nonlocalBind, uid, platform = process.platform, readFile = (p) => readFileSync(p, "utf8") } = {}) {
113
+ const read = (p, dflt) => {
114
+ try {
115
+ return readFile(p);
116
+ } catch {
117
+ return dflt;
118
+ }
119
+ };
120
+ return pickPool({
121
+ entries: entries ?? parseIfInet6(read("/proc/net/if_inet6", "")),
122
+ nonlocalBind: nonlocalBind ?? (Number(String(read("/proc/sys/net/ipv6/ip_nonlocal_bind", "0")).trim()) || 0),
123
+ uid: uid ?? (typeof process.getuid === "function" ? process.getuid() : -1),
124
+ platform,
125
+ explicitPrefix: cfg.prefix || "",
126
+ explicitIface: cfg.iface || "",
127
+ minHostBits: cfg.minHostBits || 8,
128
+ claim: cfg.claim || "auto",
129
+ });
130
+ }
@@ -0,0 +1,152 @@
1
+ // v6pool · 装配入口(MODULES.md §0/§1)。
2
+ //
3
+ // 定位:**自动判断**本机有没有可用的 IPv6 池;有就启用(出口 = 池里的源地址),
4
+ // 没有就诚实跳过一行日志(行为与今天完全一致)。缺省开,MSLXDFF_V6_POOL=0 关。
5
+ //
6
+ // 与 WARP 池的关系:v6 池可用 ⇒ 不建 WARP 池(v6 严格更优:地址无限、零子进程、换址成本≈0);
7
+ // 检测通过但探活全失败 ⇒ 池为空 ⇒ dispatcher 走直连兜底,日志点名 MSLXDFF_V6_POOL=0 可恢复 WARP。
8
+ import { getUndici } from "../compat.js";
9
+ import { resolveV6Config } from "./config.js";
10
+ import { detectPool } from "./detect.js";
11
+ import { createClaimer } from "./claim.js";
12
+ import { createV6Dispatcher } from "./rotate.js";
13
+ import { probeFrom } from "./probe.js";
14
+ import { randomAddress } from "./prefix.js";
15
+ import { fmtClose, fmtConfig, fmtDetect, fmtDisabled, fmtPool, fmtPoolEmpty, fmtProbe, fmtReadyFail, fmtSkip } from "./report.js";
16
+ import { createWarpDispatcher } from "../warp-pool/index.js";
17
+
18
+ /** 每槽 Agent 的连接池参数。注入 dispatcher 后 transport 不建自带池(transport/index.js L28),所以必须自带。 */
19
+ export const AGENT_OPTIONS = { connections: 4, pipelining: 1, keepAliveTimeout: 30_000, keepAliveMaxTimeout: 60_000 };
20
+
21
+ /** 初始地址集的去重重试上限(前缀足够大时一次就成)。 */
22
+ export const DISTINCT_TRIES = 16;
23
+
24
+ /**
25
+ * 建池。检测不过 / 平台不支持 / 无权限 / undici 缺失 ⇒ 返回 null(调用方据此不注入、退回原行为)。
26
+ * @returns {null | { dispatcher: object, ready: Promise<void>, config: object, detect: object,
27
+ * close: () => Promise<void>, stats: () => object }}
28
+ */
29
+ export function createV6Pool({ env = process.env, baseUrl = "https://opencode.ai", log = (m) => console.error(m), deps = {} } = {}) {
30
+ const cfg = resolveV6Config(env);
31
+ if (!cfg.enabled) {
32
+ log(fmtDisabled());
33
+ return null;
34
+ }
35
+ log(fmtConfig(cfg));
36
+
37
+ const d = deps.detect ? deps.detect(cfg) : detectPool({ cfg, env });
38
+ if (!d.ok) {
39
+ log(fmtSkip(d));
40
+ return null;
41
+ }
42
+ log(fmtDetect(d));
43
+
44
+ const { Agent } = getUndici();
45
+ if (typeof Agent !== "function") {
46
+ log(fmtReadyFail({ error: "undici Agent 不可用(未安装 undici 且 Node <18)" }));
47
+ return null;
48
+ }
49
+
50
+ const prefix = { addr: d.addr, bits: d.bits };
51
+ const mine = new Set(d.mine || []);
52
+ const agentFactory = deps.agentFactory || ((addr) => new Agent({ connect: { localAddress: addr }, ...AGENT_OPTIONS }));
53
+ const claimer = deps.claimer ? deps.claimer(d) : createClaimer({ iface: d.iface, mode: d.mode, dir: cfg.dir, log });
54
+ const probe = deps.probe || probeFrom;
55
+
56
+ /** 挑一个池内地址:避开本机自己的全局地址(别把机器正在用的地址当"新"地址)。 */
57
+ function pickAddress() {
58
+ for (let i = 0; i < DISTINCT_TRIES; i++) {
59
+ const a = randomAddress(prefix);
60
+ if (!mine.has(a)) return a;
61
+ }
62
+ return randomAddress(prefix);
63
+ }
64
+
65
+ const dispatcher = createV6Dispatcher({
66
+ addrs: [],
67
+ strategy: cfg.strategy,
68
+ retireMs: cfg.retireMs,
69
+ rotate: cfg.rotate,
70
+ debug: cfg.debug,
71
+ log,
72
+ claimer,
73
+ pickAddress,
74
+ agentFactory,
75
+ });
76
+
77
+ let closed = false;
78
+ const ready = (async () => {
79
+ try {
80
+ await claimer.sweepStale();
81
+ const addrs = [];
82
+ const taken = new Set();
83
+ for (let i = 0; i < cfg.count; i++) {
84
+ if (closed) return;
85
+ let a = pickAddress();
86
+ for (let k = 0; k < DISTINCT_TRIES && taken.has(a); k++) a = pickAddress();
87
+ await claimer.ensure(a);
88
+ taken.add(a);
89
+ addrs.push(a);
90
+ }
91
+ // 逐个实证探活:内核接受了地址 ≠ 机房把整段路由到本机。探不通的当场释放,绝不进池。
92
+ const passed = [];
93
+ for (let i = 0; i < addrs.length; i++) {
94
+ if (closed) return;
95
+ const r = await probe({ addr: addrs[i], baseUrl, path: cfg.probePath, agentFactory });
96
+ log(fmtProbe({ addr: addrs[i], i: i + 1, n: addrs.length, ...r }));
97
+ if (r.ok) passed.push(addrs[i]);
98
+ else await claimer.release(addrs[i]);
99
+ }
100
+ if (!passed.length) {
101
+ log(fmtPoolEmpty({ tried: addrs.length }));
102
+ return;
103
+ }
104
+ dispatcher.setAddresses(passed);
105
+ log(fmtPool({ prefix: d.prefix, addrs: passed, claimed: addrs.length, mode: d.mode }));
106
+ } catch (e) {
107
+ log(fmtReadyFail({ error: String(e?.message || e) }));
108
+ }
109
+ })();
110
+
111
+ // 退出钩子:`process.on("exit")` 里只能跑同步代码,但地址必须清——加进网卡的地址会改变内核的
112
+ // 默认源地址选择,影响同机其它服务(本轮手工实测踩过)。清不掉就交给下次启动的 sweepStale。
113
+ if (deps.exitHook !== false) {
114
+ process.once("exit", () => {
115
+ try {
116
+ claimer.releaseAllSync?.();
117
+ } catch {
118
+ /* 清残留兜底见 claim.js 的 sweepStale */
119
+ }
120
+ });
121
+ }
122
+
123
+ return {
124
+ dispatcher,
125
+ ready,
126
+ config: cfg,
127
+ detect: d,
128
+ async close() {
129
+ if (closed) return;
130
+ closed = true;
131
+ await dispatcher.close();
132
+ const released = await claimer.releaseAll();
133
+ log(fmtClose({ released }));
134
+ },
135
+ stats() {
136
+ return { enabled: true, mode: d.mode, prefix: d.prefix, iface: d.iface, claimed: claimer.claimed(), ...dispatcher.stats() };
137
+ },
138
+ };
139
+ }
140
+
141
+ /**
142
+ * 出口池二选一(唯一接线点用):v6 池可用就用它,否则退回 WARP 池。
143
+ * 两者都只产出一个 dispatcher 对象,注入点与契约完全一致(见 MODULES.md §1)。
144
+ * 放在这里而不是 providers-setup:那里是 10KB 硬门下的文件,多一行都是风险。
145
+ */
146
+ export function createPreferredDispatcher({ baseUrl = "https://opencode.ai", env = process.env, log, deps = {} } = {}) {
147
+ const pool = createV6Pool({ env, baseUrl, log, deps });
148
+ if (pool) return pool.dispatcher;
149
+ // 单向依赖:warp-pool 不 import v6pool(见 MODULES.md §2「已知耦合」)。
150
+ return createWarpDispatcher({ baseUrl, env, log });
151
+ }
152
+
@@ -0,0 +1,140 @@
1
+ // v6pool · IPv6 前缀算术(纯函数,零 IO):解析 / 规范化 / 取网络号 / 随机主机号。
2
+ //
3
+ // 为什么自己写:Node 没有内建 IPv6 前缀算术(`net.isIPv6` 只判形状),
4
+ // 而本功能的核心动作就是「在给定前缀里造一个合法、不与现有地址撞车的主机号」。
5
+ // 卫生规则(跳过 0/1/全 1、扰动 EUI-64 的 ff:fe 标记)照抄 v6pool 的 sanitizeHost——
6
+ // 那几条是为了让出口地址看起来不像 SLAAC 自生成的地址(v6pool 的「unlinkable exits」)。
7
+ const M16 = 0xffffn;
8
+
9
+ /** 解析 IPv6 字面量 → BigInt(128bit)。非法返回 null。支持 `::` 压缩、`[..]` 包裹、`%zone`、v4 尾巴。 */
10
+ export function parseV6(raw) {
11
+ let s = String(raw ?? "").trim().toLowerCase();
12
+ if (!s) return null;
13
+ if (s.startsWith("[") && s.endsWith("]")) s = s.slice(1, -1);
14
+ const zone = s.indexOf("%");
15
+ if (zone >= 0) s = s.slice(0, zone);
16
+ if (s.includes(".")) {
17
+ const at = s.lastIndexOf(":");
18
+ if (at < 0) return null;
19
+ const v4 = s.slice(at + 1).split(".");
20
+ if (v4.length !== 4 || !v4.every((x) => /^\d{1,3}$/.test(x) && Number(x) <= 255)) return null;
21
+ const n = v4.reduce((a, x) => ((a << 8) | Number(x)) >>> 0, 0) >>> 0;
22
+ s = `${s.slice(0, at)}:${(n >>> 16).toString(16)}:${(n & 0xffff).toString(16)}`;
23
+ }
24
+ const halves = s.split("::");
25
+ if (halves.length > 2) return null;
26
+ const head = halves[0] ? halves[0].split(":") : [];
27
+ const tail = halves.length === 2 ? (halves[1] ? halves[1].split(":") : []) : [];
28
+ if (halves.length === 1 && head.length !== 8) return null;
29
+ if (head.length + tail.length > 8) return null;
30
+ const fill = 8 - head.length - tail.length;
31
+ const groups = [...head, ...Array(halves.length === 2 ? fill : 0).fill("0"), ...tail];
32
+ if (groups.length !== 8) return null;
33
+ let out = 0n;
34
+ for (const g of groups) {
35
+ if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
36
+ out = (out << 16n) | BigInt(`0x${g}`);
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /** BigInt → 规范化 IPv6 文本(小写;最长零段压缩成 `::`,RFC 5952 只压 ≥2 段)。 */
42
+ export function formatV6(big) {
43
+ const groups = [];
44
+ for (let i = 7; i >= 0; i--) groups.push(Number((big >> BigInt(i * 16)) & M16));
45
+ let bestAt = -1;
46
+ let bestLen = 0;
47
+ let curAt = -1;
48
+ let curLen = 0;
49
+ for (let i = 0; i < 8; i++) {
50
+ if (groups[i] === 0) {
51
+ if (curAt < 0) curAt = i;
52
+ curLen += 1;
53
+ if (curLen > bestLen) {
54
+ bestLen = curLen;
55
+ bestAt = curAt;
56
+ }
57
+ } else {
58
+ curAt = -1;
59
+ curLen = 0;
60
+ }
61
+ }
62
+ const hex = groups.map((g) => g.toString(16));
63
+ if (bestLen < 2) return hex.join(":");
64
+ return `${hex.slice(0, bestAt).join(":")}::${hex.slice(bestAt + bestLen).join(":")}`;
65
+ }
66
+
67
+ /** `"2001:db8::/64"` → `{ addr: BigInt, bits: 64, text: "2001:db8::" }`;非法返回 null。 */
68
+ export function parsePrefix(raw) {
69
+ const s = String(raw ?? "").trim();
70
+ const slash = s.lastIndexOf("/");
71
+ if (slash < 0) return null;
72
+ const bits = Number(s.slice(slash + 1));
73
+ if (!Number.isInteger(bits) || bits < 0 || bits > 128) return null;
74
+ const addr = parseV6(s.slice(0, slash));
75
+ if (addr === null) return null;
76
+ return { addr, bits, text: formatV6(networkOf(addr, bits)) };
77
+ }
78
+
79
+ /** /bits 前缀里有几位主机位(= 可用地址的指数)。 */
80
+ export function hostBitsOf(bits) {
81
+ return 128 - Number(bits);
82
+ }
83
+
84
+ /** 该地址在 /bits 下的网络号(主机位清零)。 */
85
+ export function networkOf(addr, bits) {
86
+ if (bits <= 0) return 0n;
87
+ if (bits >= 128) return addr;
88
+ return addr & ~((1n << BigInt(128 - bits)) - 1n);
89
+ }
90
+
91
+ /** 随机主机号(m 位)。用 rnd() 拼 32bit 块,避免一次 Math.random 只有 53 位精度。 */
92
+ export function randomHost(m, rnd = Math.random) {
93
+ let v = 0n;
94
+ let got = 0;
95
+ while (got < m) {
96
+ const take = Math.min(32, m - got);
97
+ const r = Math.floor(rnd() * 0x100000000) >>> 0;
98
+ v = (v << BigInt(take)) | (BigInt(r) & ((1n << BigInt(take)) - 1n));
99
+ got += take;
100
+ }
101
+ return v;
102
+ }
103
+
104
+ /** 该 64 位 IID 是否带 EUI-64 的 ff:fe 标记(RFC 4291 附录 A:MAC 派生的 SLAAC 地址)。 */
105
+ export function isEui64(iid) {
106
+ return ((iid >> 24n) & M16) === 0xfffen;
107
+ }
108
+
109
+ /**
110
+ * 主机号卫生:m>2 时跳过 0/1/全 1;m>=40 时扰动 ff:fe 标记。循环有界(8 次)且确定。
111
+ */
112
+ export function sanitizeHost(v, m) {
113
+ const mask = m >= 128 ? (1n << 128n) - 1n : (1n << BigInt(m)) - 1n;
114
+ let x = v & mask;
115
+ for (let i = 0; i < 8; i++) {
116
+ if (m >= 40 && isEui64(x)) {
117
+ x = (x ^ 0x0000000200000000n) & mask;
118
+ continue;
119
+ }
120
+ if (m > 2 && (x === 0n || x === 1n || x === mask)) {
121
+ x = (x + 1n) & mask;
122
+ continue;
123
+ }
124
+ return x;
125
+ }
126
+ return x;
127
+ }
128
+
129
+ /** 在前缀里造一个随机地址(主机号随机 + 卫生规则)。m<=0(/128)时只能返回前缀自身。 */
130
+ export function randomAddress(prefix, rnd = Math.random) {
131
+ const m = hostBitsOf(prefix.bits);
132
+ if (m <= 0) return formatV6(prefix.addr);
133
+ const host = sanitizeHost(randomHost(m, rnd), m);
134
+ return formatV6(networkOf(prefix.addr, prefix.bits) | host);
135
+ }
136
+
137
+ /** 地址是否落在该前缀里。 */
138
+ export function inPrefix(addr, prefix) {
139
+ return networkOf(addr, prefix.bits) === networkOf(prefix.addr, prefix.bits);
140
+ }
@@ -0,0 +1,40 @@
1
+ // v6pool · 起池前的实证探活:**用池里的源地址**打一次上游。
2
+ //
3
+ // 为什么必须有(这是本功能唯一不能省的实测):内核接受地址(bind 成功)≠ 机房真把整段路由到本机。
4
+ // 只路由单个 /128 的机器上,从段内随机地址发出的包全部黑洞——那种池进了池就是「请求挂到超时」,
5
+ // 比直连更糟。判据只有一条:**从该地址真的能拿到上游响应**。
6
+ import { compatFetch, getUndici, timeoutSignal } from "../compat.js";
7
+ import { opencodeUa } from "../opencode-identity.js";
8
+
9
+ /**
10
+ * @param {{ addr: string, baseUrl?: string, path?: string, agentFactory: Function, fetchImpl?: Function, timeoutMs?: number }} opts
11
+ * @returns {Promise<{ ok: boolean, status: number, ms: number, error?: string }>}
12
+ */
13
+ export async function probeFrom({ addr, baseUrl = "https://opencode.ai", path = "/zen/v1/models", agentFactory, fetchImpl, timeoutMs = 8000 } = {}) {
14
+ const agent = agentFactory(addr);
15
+ const url = `${String(baseUrl).replace(/\/+$/, "")}${path}`;
16
+ const t0 = Date.now();
17
+ try {
18
+ const f = fetchImpl || getUndici().fetch || compatFetch;
19
+ const res = await f(url, {
20
+ method: "GET",
21
+ headers: { "User-Agent": opencodeUa() },
22
+ dispatcher: agent,
23
+ signal: timeoutSignal(timeoutMs),
24
+ });
25
+ try {
26
+ await res.text();
27
+ } catch {
28
+ /* 读不完不影响判活:拿到状态码就算数 */
29
+ }
30
+ return { ok: !!res.ok, status: res.status, ms: Date.now() - t0 };
31
+ } catch (e) {
32
+ return { ok: false, status: 0, ms: Date.now() - t0, error: String(e?.message || e) };
33
+ } finally {
34
+ try {
35
+ await agent?.close?.();
36
+ } catch {
37
+ /* 探活用的 Agent 是一次性的,关不掉也不影响后续 */
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,104 @@
1
+ // v6pool · 日志文案(纯函数,零 IO)。
2
+ //
3
+ // 判据(ADR-0059):**看完日志还需要的下一个命令,就是日志没写好的地方**。
4
+ // 所以每一行都必须自带定位信息:哪个源地址、哪个前缀、第几次换、旧地址当时打了多少发什么状态。
5
+ // 行首标记沿用 warp-pool/report.js 的 MARK(▸步骤 / ✓正常 / ✗失败 / ⚠警告)。
6
+ export const MARK = { step: "▸", ok: "✓", fail: "✗", warn: "⚠" };
7
+ const TAG = "[v6pool]";
8
+
9
+ /** `{200: 3, 429: 1}` → `200×3 429×1`(按次数降序;空则"无响应")。 */
10
+ export function fmtCounts(counts = {}) {
11
+ const parts = Object.entries(counts)
12
+ .filter(([, n]) => Number(n) > 0)
13
+ .sort((a, b) => Number(b[1]) - Number(a[1]))
14
+ .map(([s, n]) => `${s}×${n}`);
15
+ return parts.length ? parts.join(" ") : "无响应";
16
+ }
17
+
18
+ export function fmtConfig(cfg = {}) {
19
+ return `${TAG} ${MARK.step} 配置 开关=${cfg.enabled ? "开" : "关"} 槽位=${cfg.count} 策略=${cfg.strategy} 换址=${cfg.rotate ? "开" : "关"} 认领=${cfg.claim} 冷却=${Math.round((cfg.cooldownMs || 0) / 1000)}s 退休=${Math.round((cfg.retireMs || 0) / 1000)}s 前缀=${cfg.prefix || "(自动判断)"}`;
20
+ }
21
+
22
+ export function fmtDisabled() {
23
+ return `${TAG} ${MARK.step} 出口池关着(MSLXDFF_V6_POOL=0)⇒ 请求走直连或 WARP 池`;
24
+ }
25
+
26
+ export function fmtDetect(d = {}) {
27
+ return `${TAG} ${MARK.step} 自检 网卡=${d.iface || "?"} 前缀=${d.prefix} 主机位=${d.hostBits}(可用地址 2^${d.hostBits}) 认领=${d.mode === "bind" ? "bind(ip_nonlocal_bind=1,不碰网卡)" : "add(root,ip addr add)"} 来源=${d.source}`;
28
+ }
29
+
30
+ export function fmtSkip({ reason = "", hint = "" } = {}) {
31
+ return `${TAG} ${MARK.fail} 出口池本次不启用(请求走直连):${reason}|下一步:${hint}`;
32
+ }
33
+
34
+ export function fmtClaim({ addr, iface }) {
35
+ return `${TAG} ${MARK.step} 认领源地址 ${addr}/128 dev ${iface} nodad(记进认领账,收摊时释放)`;
36
+ }
37
+
38
+ export function fmtClaimFail({ addr, iface, error }) {
39
+ return `${TAG} ${MARK.fail} 认领源地址失败 ${addr} dev ${iface}:${error}`;
40
+ }
41
+
42
+ export function fmtSweep({ iface, removed = [], failed = [] } = {}) {
43
+ const r = removed.length ? `删掉 ${removed.length} 个:${removed.slice(0, 4).join(" ")}${removed.length > 4 ? " …" : ""}` : "无";
44
+ const f = failed.length ? `|失败 ${failed.length} 个:${failed.map((x) => `${x.addr}(${x.error})`).join(" ")}` : "";
45
+ return `${TAG} ${MARK.step} 清上一代残留地址(dev ${iface}):${r}${f}`;
46
+ }
47
+
48
+ export function fmtProbe({ addr, i, n, ok, status, ms, error }) {
49
+ return ok
50
+ ? `${TAG} ${MARK.step} 探活 ${i}/${n} 源=${addr} → HTTP ${status} ${ms}ms`
51
+ : `${TAG} ${MARK.warn} 探活 ${i}/${n} 源=${addr} → 失败 ${ms}ms ${error || `HTTP ${status}`}`;
52
+ }
53
+
54
+ export function fmtPool({ prefix, addrs = [], claimed, mode }) {
55
+ return `${TAG} ${MARK.ok} 出口池就绪:前缀 ${prefix}|源地址 ${addrs.length} 个:${addrs.join(" ")}|认领方式 ${mode}|配额信号即换新地址(不重注册、不握手,成本≈0)`;
56
+ }
57
+
58
+ export function fmtPoolEmpty({ tried = 0 } = {}) {
59
+ return `${TAG} ${MARK.fail} 池里 ${tried} 个源地址**全部**探活失败(内核接受了地址,但整段没真路由到本机)⇒ 本次走直连。下一步:① 确认机房把整段路由到本机;② 或设 MSLXDFF_V6_POOL=0 恢复 WARP 池;③ 或 MSLXDFF_V6_PREFIX=<真正路由过来的段>/<位数>`;
60
+ }
61
+
62
+ export function fmtReadyFail({ error }) {
63
+ return `${TAG} ${MARK.fail} 建池过程出错,本次走直连:${error}`;
64
+ }
65
+
66
+ export function fmtSwap({ from, to, status, kind, forced, swaps, prevCounts }) {
67
+ return `${TAG} ${MARK.warn} 源 ${from} 上游 ${status} 判为「${kind}」⇒ 换源地址 ${to}(本槽第 ${swaps} 次${forced ? ",强制跳过冷却" : ""};旧地址计数 ${fmtCounts(prevCounts)})`;
68
+ }
69
+
70
+ export function fmtSwapFail({ addr, error }) {
71
+ return `${TAG} ${MARK.fail} 源 ${addr} 换址失败(该槽保持原地址,继续用):${error}`;
72
+ }
73
+
74
+ export function fmtFirstOk({ addr, swaps, counts }) {
75
+ return swaps > 0
76
+ ? `${TAG} ${MARK.ok} 源 ${addr} 首个响应 200 ⇒ **换址后立刻恢复**(第 ${swaps} 次换址有效;新地址计数 ${fmtCounts(counts)})`
77
+ : `${TAG} ${MARK.ok} 源 ${addr} 首个响应 200(池内地址工作正常)`;
78
+ }
79
+
80
+ export function fmtNoRotate({ addr, status, kind }) {
81
+ return `${TAG} ${MARK.warn} 源 ${addr} 上游 ${status}(${kind})—— 换址开关关着(MSLXDFF_V6_ROTATE=0),不换源地址`;
82
+ }
83
+
84
+ export function fmtVerdictNo({ addr, status, kind, why }) {
85
+ return `${TAG} ${MARK.step} 源 ${addr} 上游 ${status} 判为「${kind}」⇒ 不换源地址:${why}`;
86
+ }
87
+
88
+ export function fmtRetire({ addr }) {
89
+ return `${TAG} ${MARK.step} 退休旧出口 ${addr}(关 Agent + 释放地址;留到最后是为让在飞请求走完)`;
90
+ }
91
+
92
+ export function fmtClose({ released = [] } = {}) {
93
+ return released.length
94
+ ? `${TAG} ${MARK.step} 收摊:释放源地址 ${released.length} 个:${released.join(" ")}`
95
+ : `${TAG} ${MARK.step} 收摊:没有需要释放的源地址(bind 模式不碰网卡)`;
96
+ }
97
+
98
+ export function fmtDispatch({ addr, session }) {
99
+ return `${TAG} · 源=${addr} 会话=${session}`;
100
+ }
101
+
102
+ export function fmtDirect({ reason }) {
103
+ return `${TAG} ${MARK.warn} 本次走直连:${reason}`;
104
+ }
@@ -0,0 +1,239 @@
1
+ // v6pool · 槽位 dispatcher:每槽一个源地址 + 一个自带 `localAddress` 的 undici Agent。
2
+ //
3
+ // 契约与 warp-pool 的轮换 dispatcher 一致:`dispatch(opts, handler)` + `close()`,
4
+ // 注入点同为 `transport` 的 extDispatcher(legacy 与 SDK 两条路共用同一个对象,见 MODULES.md §1)。
5
+ //
6
+ // 与 WARP 池的差别只在「换出口」这一步:
7
+ // WARP:重注册设备 + 重启隧道(实测 5~8 秒,还会被 CF 注册限流)
8
+ // v6 :从前缀里挑一个新地址(≈0 成本:只多一条 `ip addr add`,bind 模式下连这条都省)
9
+ // 判决表照旧复用 warp-pool/verdict.js(403 FreeTierError 与 429 FreeUsageLimitError 同一条件 ⇒ 强制换)。
10
+ //
11
+ // 两个刻意的设计:
12
+ // ① 换址**不重置**旧槽的冷却账,而是把旧地址推进 retiring:先关旧 Agent、延后释放地址,
13
+ // 在飞请求(SSE 长连接)不会因为源地址被抽走而断。retiring 有硬上限 RETAIN_MAX。
14
+ // ② 每次响应都记账(不只 403/429):`fmtFirstOk` 那行「新地址首个 200」就是
15
+ // 「429 换 IP 到底有没有换来新额度」的直接证据——这正是本次要回答的问题。
16
+ import { getUndici } from "../compat.js";
17
+ import { headerValue, tapHandler } from "../warp-pool/rotate.js";
18
+ import { createSelector } from "../warp-pool/strategy.js";
19
+ import { SIGNAL_STATUSES, classifyWarpSignal } from "../warp-pool/verdict.js";
20
+ import { fmtDirect, fmtDispatch, fmtFirstOk, fmtNoRotate, fmtRetire, fmtSwap, fmtSwapFail, fmtVerdictNo } from "./report.js";
21
+
22
+ const SESSION_HEADER = "x-opencode-session";
23
+
24
+ /** 最多留几个「已换下但地址还在网卡上」的旧出口:保护在飞请求,同时给地址数量一个硬上限。 */
25
+ export const RETAIN_MAX = 8;
26
+ /** 挑新地址时最多重试几次(前缀太小/已在用的地址太多时会一直撞)。 */
27
+ export const PICK_TRIES = 16;
28
+
29
+ /**
30
+ * @param {{ addrs?: string[], strategy?: "session"|"request", retireMs?: number, rotate?: boolean, debug?: boolean,
31
+ * now?: () => number, log?: (s: string) => void, claimer?: object|null, pickAddress?: () => string,
32
+ * agentFactory?: (addr: string) => object, agentOptions?: object, fallbackAgent?: object, selector?: object }} [opts]
33
+ */
34
+ export function createV6Dispatcher({
35
+ addrs = [],
36
+ strategy = "session",
37
+ retireMs = 60_000,
38
+ rotate = true,
39
+ debug = false,
40
+ now = Date.now,
41
+ log = () => {},
42
+ claimer = null,
43
+ pickAddress = () => "",
44
+ agentFactory,
45
+ agentOptions = { connections: 4, pipelining: 1, keepAliveTimeout: 30_000, keepAliveMaxTimeout: 60_000 },
46
+ fallbackAgent,
47
+ selector = createSelector({ strategy }),
48
+ } = {}) {
49
+ const { Agent } = getUndici();
50
+ if (typeof agentFactory !== "function") {
51
+ if (typeof Agent !== "function") throw new Error("undici Agent 不可用:无法建立 v6 出口池");
52
+ agentFactory = (addr) => new Agent({ connect: { localAddress: addr }, ...agentOptions });
53
+ }
54
+ const fallback = fallbackAgent !== undefined ? fallbackAgent : typeof Agent === "function" ? new Agent(agentOptions) : null;
55
+
56
+ let list = [];
57
+ /** @type {Array<{addr:string, agent:object, at:number, release:null|Function, counts:object, swaps:number}>} */
58
+ const retiring = [];
59
+ const history = [];
60
+ let directWarned = false;
61
+
62
+ function buildSlot(index, addr) {
63
+ return { index, addr, agent: agentFactory(addr), cooldownUntil: 0, swaps: 0, swapping: false, counts: {}, firstOkAt: 0 };
64
+ }
65
+
66
+ /** 装上源地址(bootstrap 探活通过后调用;空数组 = 池为空 ⇒ 直连兜底)。 */
67
+ function setAddresses(next = []) {
68
+ list = (next || []).map((a, i) => buildSlot(i, a));
69
+ return list.length;
70
+ }
71
+ // 构造时就装上地址(与 warp-pool 的轮换 dispatcher 同形状:入参即初始池)。
72
+ setAddresses(addrs);
73
+
74
+ function availableIndexes() {
75
+ const t = now();
76
+ return list.filter((e) => e.cooldownUntil <= t && !e.swapping).map((e) => e.index);
77
+ }
78
+
79
+ /** 退休账结算:只有「已过退休时长」且「超出保留上限」的才真关+真释放(close 时 force 全清)。 */
80
+ async function flushRetired({ force = false } = {}) {
81
+ const sorted = [...retiring].sort((a, b) => a.at - b.at);
82
+ const over = Math.max(0, sorted.length - RETAIN_MAX);
83
+ const keep = [];
84
+ for (let i = 0; i < sorted.length; i++) {
85
+ const r = sorted[i];
86
+ const aged = now() - r.at >= retireMs;
87
+ if (!force && !(aged && i < over)) {
88
+ keep.push(r);
89
+ continue;
90
+ }
91
+ try {
92
+ await r.agent?.close?.();
93
+ } catch {
94
+ /* 关不掉旧 Agent 不影响新出口 */
95
+ }
96
+ if (r.release) {
97
+ try {
98
+ await r.release();
99
+ } catch {
100
+ /* 释放失败已由 claim.js 自己打日志 */
101
+ }
102
+ }
103
+ history.push({ addr: r.addr, swaps: r.swaps, counts: { ...r.counts } });
104
+ if (history.length > 32) history.shift();
105
+ log(fmtRetire({ addr: r.addr }));
106
+ }
107
+ retiring.length = 0;
108
+ retiring.push(...keep);
109
+ }
110
+
111
+ /** 换该槽的源地址:挑新地址 → 认领 → 建新 Agent → 旧 Agent 退休(先关 Agent 再延后释放地址)。 */
112
+ async function swap(index, verdict = {}) {
113
+ const e = list[index];
114
+ if (!e) return { skipped: true };
115
+ if (e.swapping) return { skipped: true, reason: "该槽已在换址中" };
116
+ e.swapping = true;
117
+ try {
118
+ const taken = new Set(list.map((s) => s.addr));
119
+ let addr = "";
120
+ for (let i = 0; i < PICK_TRIES && (!addr || taken.has(addr)); i++) addr = pickAddress();
121
+ if (!addr || taken.has(addr)) throw new Error(`前缀里连续 ${PICK_TRIES} 次都撞上已在用的地址(前缀太小?)`);
122
+ if (claimer) await claimer.ensure(addr);
123
+ const oldAddr = e.addr;
124
+ const prevCounts = { ...e.counts };
125
+ const prevSwaps = e.swaps;
126
+ retiring.push({
127
+ addr: oldAddr,
128
+ agent: e.agent,
129
+ at: now(),
130
+ release: claimer ? () => claimer.release(oldAddr) : null,
131
+ counts: prevCounts,
132
+ swaps: prevSwaps,
133
+ });
134
+ e.addr = addr;
135
+ e.agent = agentFactory(addr);
136
+ e.cooldownUntil = 0;
137
+ e.swaps = prevSwaps + 1;
138
+ e.counts = {};
139
+ e.firstOkAt = 0;
140
+ log(fmtSwap({ from: oldAddr, to: addr, status: verdict.status, kind: verdict.kind, forced: verdict.forced, swaps: e.swaps, prevCounts }));
141
+ await flushRetired();
142
+ return { ok: true, from: oldAddr, to: addr };
143
+ } finally {
144
+ e.swapping = false;
145
+ }
146
+ }
147
+
148
+ /** 上游响应旁听:记账 → 换址后首个 200 的取证行 → 配额信号才换址。 */
149
+ function onTap(signal, e) {
150
+ const status = Number(signal?.status);
151
+ e.counts[status] = (e.counts[status] || 0) + 1;
152
+ if (status === 200 && !e.firstOkAt) {
153
+ e.firstOkAt = now();
154
+ log(fmtFirstOk({ addr: e.addr, swaps: e.swaps, counts: e.counts }));
155
+ }
156
+ if (!SIGNAL_STATUSES.includes(status)) return;
157
+ const v = classifyWarpSignal(signal);
158
+ if (!rotate) {
159
+ log(fmtNoRotate({ addr: e.addr, status, kind: v.kind }));
160
+ return;
161
+ }
162
+ if (!v.rotate) {
163
+ log(fmtVerdictNo({ addr: e.addr, status, kind: v.kind, why: v.why }));
164
+ return;
165
+ }
166
+ const addr = e.addr;
167
+ void swap(e.index, { ...v, status }).catch((err) => log(fmtSwapFail({ addr, error: String(err?.message || err) })));
168
+ }
169
+
170
+ return {
171
+ /** 每次请求调一次 = 选槽粒度(session 策略下同会话粘同一源地址)。 */
172
+ dispatch(opts, handler) {
173
+ if (!list.length) {
174
+ if (fallback) return fallback.dispatch(opts, handler);
175
+ throw new Error("v6pool:源地址池为空且无直连兜底");
176
+ }
177
+ const avail = availableIndexes();
178
+ if (!avail.length) {
179
+ // 全池都在冷却/换址中 ⇒ 直连兜底优先:硬派给正在换址的槽 = 把请求挂到超时
180
+ if (!directWarned) {
181
+ directWarned = true;
182
+ log(fmtDirect({ reason: `全部 ${list.length} 个源地址都在冷却/换址中(下一条恢复后自动回到池内)` }));
183
+ }
184
+ return (fallback || list[0].agent).dispatch(opts, handler);
185
+ }
186
+ directWarned = false;
187
+ const sessionKey = strategy === "session" ? headerValue(opts?.headers, SESSION_HEADER) : "";
188
+ const e = list[selector.pick(avail, sessionKey)];
189
+ if (debug) log(fmtDispatch({ addr: e.addr, session: sessionKey || "(无)" }));
190
+ return e.agent.dispatch(opts, tapHandler(handler, (sig) => onTap(sig, e)));
191
+ },
192
+
193
+ setAddresses,
194
+
195
+ /** 手动换某个槽的源地址(供运维/测试;正常路径由配额信号触发)。 */
196
+ swap,
197
+
198
+ /** 只读快照(含已退休出口的最终计数——"换址到底有没有换来新额度"看这里)。 */
199
+ stats() {
200
+ const t = now();
201
+ return {
202
+ slots: list.map((e) => ({ addr: e.addr, cooling: e.cooldownUntil > t, swaps: e.swaps, swapping: e.swapping, counts: { ...e.counts }, firstOk: !!e.firstOkAt })),
203
+ history: history.map((h) => ({ ...h, counts: { ...h.counts } })),
204
+ };
205
+ },
206
+
207
+ entries() {
208
+ return list.map((e) => ({ index: e.index, addr: e.addr, cooldownUntil: e.cooldownUntil, swaps: e.swaps }));
209
+ },
210
+
211
+ async close() {
212
+ const slots = list;
213
+ list = [];
214
+ for (const e of slots) {
215
+ try {
216
+ await e.agent?.close?.();
217
+ } catch {
218
+ /* 收摊时关不掉就算了 */
219
+ }
220
+ }
221
+ await flushRetired({ force: true });
222
+ if (fallback) {
223
+ try {
224
+ await fallback.close?.();
225
+ } catch {
226
+ /* 同上 */
227
+ }
228
+ }
229
+ },
230
+
231
+ async destroy() {
232
+ return this.close();
233
+ },
234
+
235
+ get size() {
236
+ return list.length;
237
+ },
238
+ };
239
+ }
@@ -115,25 +115,37 @@ export function fmtPool({ pooled, total, exits }) {
115
115
  }
116
116
 
117
117
  /**
118
- * 身份指纹:每个端口的短设备 id / WARP 内网地址 / 对端端点 / 注册时间。
118
+ * 身份指纹:每个端口的短设备 id / WARP 内网 IPv6 尾段 / 对端端点 / 注册时间。
119
119
  * 为什么必须有:4 条隧道只拿到 2 个出口地址时(真机 2026-10-17),只有这组读数能区分
120
- * 「设备本身被写重复了」和「CF 的共享 NAT 把不同设备折叠成一个出口」——没有它就只能猜。
120
+ * 「设备本身被写重复了」和「CF 把不同设备折叠成一个出口」——没有它就只能猜。
121
+ *
122
+ * ⚠ 判据**不看 IPv4**:`172.16.0.2` 是 WARP 的**固定接口地址**(6 次实测全是它:组长 4 台 +
123
+ * 本机 2 台;公开的 wgcf 生成配置里同样是 `Address = 172.16.0.2/32`),按它判「重复」是误报
124
+ * (2026-10-17 十一次修订前确实这么误报过)。每台设备真正唯一的是 **IPv6**(`2606:4700:110:…`)
125
+ * 与密钥对,所以指纹打 v6 尾段。
121
126
  */
127
+ /** v6 尾段做指纹(`2606:4700:110:81b5:56ec:72b3:9542:e3de` → `…:9542:e3de`);缺了给「无」。 */
128
+ export function v6Tail(v6) {
129
+ const s = String(v6 || "");
130
+ if (!s) return "无";
131
+ const parts = s.split(":");
132
+ return parts.length > 2 ? `…:${parts.slice(-2).join(":")}` : s;
133
+ }
122
134
  export function fmtIdentityDetail(nodes = []) {
123
135
  const out = [];
124
136
  const byId = new Map();
125
- const byV4 = new Map();
137
+ const byEp = new Map();
126
138
  for (const n of nodes || []) {
127
139
  if (n?.id) byId.set(n.id, [...(byId.get(n.id) || []), n.port]);
128
- if (n?.v4) byV4.set(n.v4, [...(byV4.get(n.v4) || []), n.port]);
129
- out.push(`[warp-pool] :${n?.port} 设备=${n?.id ? String(n.id).slice(0, 8) : "无id"} 内网=${n?.v4 || "无"} 端点=${n?.endpoint || "?"} 注册=${String(n?.registeredAt || "?").slice(0, 19)}`);
140
+ if (n?.endpoint) byEp.set(n.endpoint, [...(byEp.get(n.endpoint) || []), n.port]);
141
+ out.push(`[warp-pool] :${n?.port} 设备=${n?.id ? String(n.id).slice(0, 8) : "无id"} 内网v6=${v6Tail(n?.v6)} 端点=${n?.endpoint || "?"} 注册=${String(n?.registeredAt || "?").slice(0, 19)}`);
130
142
  }
131
- // cut 只给设备 id 用(UUID 太长):内网地址必须原样打,截短了就成了「172.16.0」
132
- const dups = (m, cut = 0) => [...m.entries()].filter(([, p]) => p.length > 1).map(([k, p]) => `${cut ? String(k).slice(0, cut) : String(k)} ← :${p.join(",:")}`).join(";");
133
- const dupId = dups(byId, 8);
134
- const dupV4 = dups(byV4);
143
+ const dupId = [...byId.entries()].filter(([, p]) => p.length > 1).map(([k, p]) => `${String(k).slice(0, 8)} ← :${p.join(",:")}`).join(";");
135
144
  if (dupId) out.push(`[warp-pool] ${MARK.warn} 设备 id 重复:${dupId} —— 同一个 WARP 设备被写到多个端口,出口必然相同;删掉重复端口的 node-<port>.json 再重启,它会重新注册`);
136
- if (dupV4) out.push(`[warp-pool] ${MARK.warn} WARP 内网地址重复:${dupV4} —— 同一内网地址必是同一出口`);
145
+ // 端点全同 = 大家都从同一个 CF 入口出去(CF 对每次注册都回同一个 hostname):出口撞车由此而来
146
+ const total = (nodes || []).length;
147
+ const sameEp = [...byEp.entries()].find(([, p]) => total > 1 && p.length === total);
148
+ if (sameEp) out.push(`[warp-pool] ${MARK.step} ${total} 条隧道都用同一个端点(${sameEp[0]})—— CF 对每次注册都回同一个 hostname,故大家都从同一个 CF 入口出去,出口地址撞车由此而来(想分散:把 node-<port>.json 的 endpoint 改成别的 WARP 入口 IP 后重启)`);
137
149
  return out;
138
150
  }
139
151