mslxdff 0.1.244 → 0.1.246

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.
Files changed (49) hide show
  1. package/package.json +1 -1
  2. package/src/chat-pipeline/terminal-verdict.js +4 -4
  3. package/src/cli/commands/daemon.js +1 -1
  4. package/src/cli/index.js +0 -5
  5. package/src/daemon.js +3 -3
  6. package/src/runtime/bootstrap.js +1 -1
  7. package/src/runtime/proc-info.js +2 -2
  8. package/src/runtime/providers-setup.js +2 -4
  9. package/src/server.js +3 -3
  10. package/src/upstream-engine/index.js +2 -17
  11. package/src/upstream.js +1 -61
  12. package/src/cli/commands/multi-ip-pool-fetch.js +0 -173
  13. package/src/cli/commands/multi-ip-pool-test.js +0 -136
  14. package/src/cli/commands/multi-ip-pool.js +0 -83
  15. package/src/cli/commands/v6-pool.js +0 -123
  16. package/src/multi-ip-pool/config.js +0 -155
  17. package/src/multi-ip-pool/diagnose.js +0 -159
  18. package/src/multi-ip-pool/dial.js +0 -179
  19. package/src/multi-ip-pool/dispatch.js +0 -244
  20. package/src/multi-ip-pool/index.js +0 -174
  21. package/src/multi-ip-pool/nodes-fetch.js +0 -110
  22. package/src/multi-ip-pool/nodes.js +0 -205
  23. package/src/multi-ip-pool/report.js +0 -162
  24. package/src/multi-ip-pool/selftest.js +0 -168
  25. package/src/multi-ip-pool/standby.js +0 -157
  26. package/src/multi-ip-pool/tunnel.js +0 -291
  27. package/src/v6pool/claim.js +0 -157
  28. package/src/v6pool/config.js +0 -65
  29. package/src/v6pool/detect.js +0 -130
  30. package/src/v6pool/index.js +0 -157
  31. package/src/v6pool/prefix.js +0 -140
  32. package/src/v6pool/probe.js +0 -40
  33. package/src/v6pool/report.js +0 -104
  34. package/src/v6pool/rotate.js +0 -263
  35. package/src/v6pool/selftest.js +0 -178
  36. package/src/warp-pool/config.js +0 -74
  37. package/src/warp-pool/health.js +0 -106
  38. package/src/warp-pool/identity.js +0 -141
  39. package/src/warp-pool/index.js +0 -358
  40. package/src/warp-pool/keys.js +0 -29
  41. package/src/warp-pool/nodes.js +0 -95
  42. package/src/warp-pool/ports.js +0 -160
  43. package/src/warp-pool/register.js +0 -113
  44. package/src/warp-pool/report.js +0 -232
  45. package/src/warp-pool/revive.js +0 -168
  46. package/src/warp-pool/rotate.js +0 -214
  47. package/src/warp-pool/strategy.js +0 -43
  48. package/src/warp-pool/verdict.js +0 -69
  49. package/src/warp-pool/wireproxy.js +0 -162
@@ -1,130 +0,0 @@
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
- }
@@ -1,157 +0,0 @@
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
- import { createMultiIpDispatcher } from "../multi-ip-pool/index.js";
18
-
19
- /** 每槽 Agent 的连接池参数。注入 dispatcher 后 transport 不建自带池(transport/index.js L28),所以必须自带。 */
20
- export const AGENT_OPTIONS = { connections: 4, pipelining: 1, keepAliveTimeout: 30_000, keepAliveMaxTimeout: 60_000 };
21
-
22
- /** 初始地址集的去重重试上限(前缀足够大时一次就成)。 */
23
- export const DISTINCT_TRIES = 16;
24
-
25
- /**
26
- * 建池。检测不过 / 平台不支持 / 无权限 / undici 缺失 ⇒ 返回 null(调用方据此不注入、退回原行为)。
27
- * @returns {null | { dispatcher: object, ready: Promise<void>, config: object, detect: object,
28
- * close: () => Promise<void>, stats: () => object }}
29
- */
30
- export function createV6Pool({ env = process.env, baseUrl = "https://opencode.ai", log = (m) => console.error(m), deps = {} } = {}) {
31
- const cfg = resolveV6Config(env);
32
- if (!cfg.enabled) {
33
- log(fmtDisabled());
34
- return null;
35
- }
36
- log(fmtConfig(cfg));
37
-
38
- const d = deps.detect ? deps.detect(cfg) : detectPool({ cfg, env });
39
- if (!d.ok) {
40
- log(fmtSkip(d));
41
- return null;
42
- }
43
- log(fmtDetect(d));
44
-
45
- const { Agent } = getUndici();
46
- if (typeof Agent !== "function") {
47
- log(fmtReadyFail({ error: "undici Agent 不可用(未安装 undici 且 Node <18)" }));
48
- return null;
49
- }
50
-
51
- const prefix = { addr: d.addr, bits: d.bits };
52
- const mine = new Set(d.mine || []);
53
- const agentFactory = deps.agentFactory || ((addr) => new Agent({ connect: { localAddress: addr }, ...AGENT_OPTIONS }));
54
- const claimer = deps.claimer ? deps.claimer(d) : createClaimer({ iface: d.iface, mode: d.mode, dir: cfg.dir, log });
55
- const probe = deps.probe || probeFrom;
56
-
57
- /** 挑一个池内地址:避开本机自己的全局地址(别把机器正在用的地址当"新"地址)。 */
58
- function pickAddress() {
59
- for (let i = 0; i < DISTINCT_TRIES; i++) {
60
- const a = randomAddress(prefix);
61
- if (!mine.has(a)) return a;
62
- }
63
- return randomAddress(prefix);
64
- }
65
-
66
- const dispatcher = createV6Dispatcher({
67
- addrs: [],
68
- strategy: cfg.strategy,
69
- retireMs: cfg.retireMs,
70
- rotate: cfg.rotate,
71
- debug: cfg.debug,
72
- log,
73
- claimer,
74
- pickAddress,
75
- agentFactory,
76
- });
77
-
78
- let closed = false;
79
- const ready = (async () => {
80
- try {
81
- await claimer.sweepStale();
82
- const addrs = [];
83
- const taken = new Set();
84
- for (let i = 0; i < cfg.count; i++) {
85
- if (closed) return;
86
- let a = pickAddress();
87
- for (let k = 0; k < DISTINCT_TRIES && taken.has(a); k++) a = pickAddress();
88
- await claimer.ensure(a);
89
- taken.add(a);
90
- addrs.push(a);
91
- }
92
- // 逐个实证探活:内核接受了地址 ≠ 机房把整段路由到本机。探不通的当场释放,绝不进池。
93
- const passed = [];
94
- for (let i = 0; i < addrs.length; i++) {
95
- if (closed) return;
96
- const r = await probe({ addr: addrs[i], baseUrl, path: cfg.probePath, agentFactory });
97
- log(fmtProbe({ addr: addrs[i], i: i + 1, n: addrs.length, ...r }));
98
- if (r.ok) passed.push(addrs[i]);
99
- else await claimer.release(addrs[i]);
100
- }
101
- if (!passed.length) {
102
- log(fmtPoolEmpty({ tried: addrs.length }));
103
- return;
104
- }
105
- dispatcher.setAddresses(passed);
106
- log(fmtPool({ prefix: d.prefix, addrs: passed, claimed: addrs.length, mode: d.mode }));
107
- } catch (e) {
108
- log(fmtReadyFail({ error: String(e?.message || e) }));
109
- }
110
- })();
111
-
112
- // 退出钩子:`process.on("exit")` 里只能跑同步代码,但地址必须清——加进网卡的地址会改变内核的
113
- // 默认源地址选择,影响同机其它服务(本轮手工实测踩过)。清不掉就交给下次启动的 sweepStale。
114
- if (deps.exitHook !== false) {
115
- process.once("exit", () => {
116
- try {
117
- claimer.releaseAllSync?.();
118
- } catch {
119
- /* 清残留兜底见 claim.js 的 sweepStale */
120
- }
121
- });
122
- }
123
-
124
- return {
125
- dispatcher,
126
- ready,
127
- config: cfg,
128
- detect: d,
129
- async close() {
130
- if (closed) return;
131
- closed = true;
132
- await dispatcher.close();
133
- const released = await claimer.releaseAll();
134
- log(fmtClose({ released }));
135
- },
136
- stats() {
137
- return { enabled: true, mode: d.mode, prefix: d.prefix, iface: d.iface, claimed: claimer.claimed(), ...dispatcher.stats() };
138
- },
139
- };
140
- }
141
-
142
- /**
143
- * 出口池三选一(唯一接线点用):v6 池 → 多出口池 → WARP 池。
144
- * 三者都只产出一个 dispatcher 对象,注入点与契约完全一致(见 MODULES.md §1)。
145
- * 放在这里而不是 providers-setup:那里是 10KB 硬门下的文件,多一行都是风险。
146
- */
147
- export function createPreferredDispatcher({ baseUrl = "https://opencode.ai", env = process.env, log, deps = {} } = {}) {
148
- const pool = createV6Pool({ env, baseUrl, log, deps });
149
- if (pool) return pool.dispatcher;
150
- // 次选:多出口池(VPNGate 免费 OpenVPN 节点当出口,只组长/单机建)——它给的是**另一批真实出口 IP**,
151
- // 而 v6 只是本机自带的那段地址,所以 v6 优先、它次之。任一不可用都安静跳过(各自打自己的日志)。
152
- const multi = createMultiIpDispatcher({ env, baseUrl, log, deps: deps.multiIp });
153
- if (multi) return multi;
154
- // 单向依赖:warp-pool 不 import v6pool(见 MODULES.md §2「已知耦合」)。
155
- return createWarpDispatcher({ baseUrl, env, log });
156
- }
157
-
@@ -1,140 +0,0 @@
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
- }
@@ -1,40 +0,0 @@
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
- }
@@ -1,104 +0,0 @@
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
- }