mslxdff 0.1.170 → 0.1.171

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 (107) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/docs/cli_help_mini.md +143 -0
  3. package/package.json +1 -1
  4. package/src/anthropic/count-tokens.js +39 -0
  5. package/src/anthropic/translate.js +20 -41
  6. package/src/auto.js +254 -254
  7. package/src/bench/cline-bench.js +42 -42
  8. package/src/bench/probe.js +70 -70
  9. package/src/bench/report.js +162 -162
  10. package/src/bench/runner.js +77 -77
  11. package/src/bench/via-probe.js +124 -124
  12. package/src/bench/via-routes.js +87 -87
  13. package/src/bench/workbuddy-bench.js +54 -54
  14. package/src/chat/engine.js +160 -160
  15. package/src/chat/gateway.js +163 -163
  16. package/src/chat/orchestrator.js +234 -234
  17. package/src/chat/prompt.js +70 -70
  18. package/src/chat/repl.js +88 -88
  19. package/src/chat/terminal.js +135 -135
  20. package/src/chat/tools.js +306 -306
  21. package/src/chat-pipeline/index.js +131 -131
  22. package/src/chat-pipeline/policy.js +76 -76
  23. package/src/cli/commands/group.js +249 -249
  24. package/src/cli/commands/model/picks.js +50 -50
  25. package/src/cli/commands/provider/bench-via.js +247 -247
  26. package/src/cli/commands/provider/bench.js +141 -141
  27. package/src/cli/commands/provider/index.js +133 -133
  28. package/src/cli/commands/provider/models.js +145 -145
  29. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  30. package/src/cli/commands/sync.js +310 -310
  31. package/src/cli/status.js +279 -279
  32. package/src/daemon.js +112 -112
  33. package/src/model-capabilities/enrich.js +86 -86
  34. package/src/model-capabilities/index.js +183 -183
  35. package/src/model-capabilities/parse.js +70 -70
  36. package/src/models.js +225 -225
  37. package/src/providers/AGENTS.md +49 -0
  38. package/src/providers/cline/auth.js +228 -228
  39. package/src/providers/cline/chat.js +307 -307
  40. package/src/providers/cline.js +2 -2
  41. package/src/providers/codearts/concurrency.js +34 -0
  42. package/src/providers/codearts/index.js +11 -3
  43. package/src/providers/globalqwenwork/cosy.js +123 -123
  44. package/src/providers/globalqwenwork/crypto.js +218 -218
  45. package/src/providers/globalqwenwork/http.js +20 -20
  46. package/src/providers/globalqwenwork/payload.js +4 -2
  47. package/src/providers/globalqwenwork/rsa.js +54 -54
  48. package/src/providers/globalqwenwork/sse.js +268 -268
  49. package/src/providers/globalqwenwork/stream.js +130 -130
  50. package/src/providers/globalqwenwork/upstream.js +122 -122
  51. package/src/providers/keyring.js +60 -60
  52. package/src/providers/qoder/chat.js +203 -200
  53. package/src/providers/qoder/index.js +249 -249
  54. package/src/providers/qoder/sse.js +145 -145
  55. package/src/providers/qwenwork/account-store.js +133 -133
  56. package/src/providers/qwenwork/constants.js +67 -67
  57. package/src/providers/qwenwork/cosy.js +120 -120
  58. package/src/providers/qwenwork/crypto.js +218 -218
  59. package/src/providers/qwenwork/http.js +20 -20
  60. package/src/providers/qwenwork/index.js +327 -327
  61. package/src/providers/qwenwork/payload.js +144 -142
  62. package/src/providers/qwenwork/rsa.js +54 -54
  63. package/src/providers/qwenwork/sse.js +268 -268
  64. package/src/providers/qwenwork/stream.js +130 -130
  65. package/src/providers/qwenwork/upstream.js +120 -120
  66. package/src/providers/qwenwork.js +1 -1
  67. package/src/providers/raccoon/chat.js +10 -5
  68. package/src/providers/raccoon/const.js +4 -4
  69. package/src/providers/registry.js +79 -79
  70. package/src/providers/workbuddy/chat.js +248 -248
  71. package/src/providers/workbuddy/payload.js +16 -7
  72. package/src/providers/workbuddy/reshape.js +152 -152
  73. package/src/providers/workbuddy.js +2 -2
  74. package/src/providers/zcode/chat.js +7 -0
  75. package/src/reasoning.js +32 -32
  76. package/src/responses/translate.js +4 -0
  77. package/src/routes/AGENTS.md +37 -0
  78. package/src/routes/chat/exhausted-handler.js +5 -0
  79. package/src/routes/chat/gateway.js +46 -46
  80. package/src/routes/chat/relay-pipeline.js +294 -291
  81. package/src/routes/chat/via-route-handler.js +146 -146
  82. package/src/routes/hedge.js +255 -255
  83. package/src/routes/messages-route.js +1 -1
  84. package/src/routes/models-route.js +167 -167
  85. package/src/routes/peers.js +273 -273
  86. package/src/routes/stream-scan.js +47 -21
  87. package/src/routes/stream.js +385 -385
  88. package/src/runtime/bootstrap.js +50 -50
  89. package/src/runtime/provider-gate.js +36 -36
  90. package/src/runtime/providers-setup.js +165 -165
  91. package/src/server.js +69 -69
  92. package/src/state/schemas/allowlist.js +92 -92
  93. package/src/sync-opencode.js +280 -280
  94. package/src/talk-full.js +1 -0
  95. package/src/talk-log.js +3 -2
  96. package/src/thinking-effort.js +67 -0
  97. package/src/transport/index.js +244 -244
  98. package/src/transport/pool.js +56 -56
  99. package/src/transport/retry.js +24 -24
  100. package/src/transport/sse.js +93 -93
  101. package/src/upstream-engine/sdk/convert.js +6 -0
  102. package/src/upstream-probe/display.js +52 -52
  103. package/src/upstream-probe/probe.js +49 -49
  104. package/src/upstream-probe/rotate.js +110 -110
  105. package/src/upstream-probe/start.js +45 -45
  106. package/src/upstream-responses.js +5 -0
  107. package/src/upstream.js +289 -289
@@ -1,24 +1,24 @@
1
- export function backoffDelay(baseMs, attempt) {
2
- // attempt 0 => base, 1 => base*2, 2 => base*4
3
- return baseMs * (1 << attempt);
4
- }
5
-
6
- export function resolveRetry(status, attempt, config) {
7
- const key = status === "network" ? "network" : String(status);
8
- const entry = config?.[key];
9
- if (!entry) return { shouldRetry: false, delayMs: 0 };
10
- const attempts = Number(entry.attempts) || 0;
11
- const base = Number(entry.delayMs) || 0;
12
- if (attempt < attempts) {
13
- return { shouldRetry: true, delayMs: backoffDelay(base, attempt) };
14
- }
15
- return { shouldRetry: false, delayMs: 0 };
16
- }
17
-
18
- export function shouldRetry(status, attempt, config) {
19
- return resolveRetry(status, attempt, config).shouldRetry;
20
- }
21
-
22
- export function sleep(ms) {
23
- return new Promise((r) => setTimeout(r, ms));
24
- }
1
+ export function backoffDelay(baseMs, attempt) {
2
+ // attempt 0 => base, 1 => base*2, 2 => base*4
3
+ return baseMs * (1 << attempt);
4
+ }
5
+
6
+ export function resolveRetry(status, attempt, config) {
7
+ const key = status === "network" ? "network" : String(status);
8
+ const entry = config?.[key];
9
+ if (!entry) return { shouldRetry: false, delayMs: 0 };
10
+ const attempts = Number(entry.attempts) || 0;
11
+ const base = Number(entry.delayMs) || 0;
12
+ if (attempt < attempts) {
13
+ return { shouldRetry: true, delayMs: backoffDelay(base, attempt) };
14
+ }
15
+ return { shouldRetry: false, delayMs: 0 };
16
+ }
17
+
18
+ export function shouldRetry(status, attempt, config) {
19
+ return resolveRetry(status, attempt, config).shouldRetry;
20
+ }
21
+
22
+ export function sleep(ms) {
23
+ return new Promise((r) => setTimeout(r, ms));
24
+ }
@@ -1,93 +1,93 @@
1
- /**
2
- * SSE 行协议深模块 — 纯函数 + 流式
3
- * 负责 `data: / : / event: / [DONE]` 的解析与粘包 remain 处理
4
- */
5
-
6
- export function parseSseChunk(buf) {
7
- const events = [];
8
- let remain = String(buf || "");
9
- // 按 \n\n 分帧,\r\n 也兼容
10
- // 保留最后一帧若不以 \n\n 结尾则为 remain
11
- const normalized = remain.replace(/\r\n/g, "\n");
12
- const parts = normalized.split("\n\n");
13
- // 最后一部分若原串不以 \n\n 结尾则为 remain
14
- const endsWithDelim = normalized.endsWith("\n\n") || normalized.endsWith("\n\r\n");
15
- // parts 最后一项在非结尾时为未完成帧
16
- const complete = endsWithDelim ? parts : parts.slice(0, -1);
17
- remain = endsWithDelim ? "" : parts[parts.length - 1] || "";
18
- for (const frame of complete) {
19
- if (!frame) continue; // 空帧
20
- const lines = frame.split("\n");
21
- const dataLines = [];
22
- for (const line of lines) {
23
- if (!line) continue;
24
- if (line.startsWith(":")) continue; // 注释/keepalive
25
- if (line.startsWith("event:")) continue; // 事件类型忽略
26
- if (line.startsWith("data:")) {
27
- let v = line.slice(5);
28
- if (v.startsWith(" ")) v = v.slice(1);
29
- dataLines.push(v);
30
- }
31
- }
32
- if (dataLines.length === 0) continue;
33
- // 多行 data 按 \n 拼接(SSE 规范)
34
- const payload = dataLines.join("\n");
35
- // 空 data: 仍产生事件,由上层过滤;此处保留以便测试可见
36
- events.push(payload);
37
- }
38
- return { events, remain };
39
- }
40
-
41
- export function createSseParser() {
42
- let buf = "";
43
- return {
44
- push(chunk) {
45
- buf += String(chunk || "");
46
- const { events, remain } = parseSseChunk(buf);
47
- buf = remain;
48
- return events;
49
- },
50
- flush() {
51
- // 未形成完整帧的不发(避免半包误触发)
52
- if (!buf.trim()) { buf = ""; return []; }
53
- // 若残留包含完整 data: 行但缺结尾,不强行发
54
- return [];
55
- },
56
- getRemain() { return buf; },
57
- };
58
- }
59
-
60
- export async function* streamFromResponse(res) {
61
- if (!res || !res.body) return;
62
- const parser = createSseParser();
63
- const reader = res.body.getReader ? res.body.getReader() : null;
64
- const decoder = new TextDecoder();
65
- if (reader) {
66
- while (true) {
67
- const { done, value } = await reader.read();
68
- if (done) break;
69
- const text = decoder.decode(value, { stream: true });
70
- const evs = parser.push(text);
71
- for (const e of evs) {
72
- if (e === "[DONE]") return;
73
- if (e === "") continue;
74
- yield e;
75
- }
76
- }
77
- // flush 残留
78
- const rest = parser.flush();
79
- for (const e of rest) {
80
- if (e === "[DONE]") return;
81
- if (e) yield e;
82
- }
83
- } else if (typeof res.text === "function") {
84
- // 回退:一次性 text
85
- const txt = await res.text();
86
- const evs = parser.push(txt);
87
- for (const e of evs) {
88
- if (e === "[DONE]") return;
89
- if (e === "") continue;
90
- yield e;
91
- }
92
- }
93
- }
1
+ /**
2
+ * SSE 行协议深模块 — 纯函数 + 流式
3
+ * 负责 `data: / : / event: / [DONE]` 的解析与粘包 remain 处理
4
+ */
5
+
6
+ export function parseSseChunk(buf) {
7
+ const events = [];
8
+ let remain = String(buf || "");
9
+ // 按 \n\n 分帧,\r\n 也兼容
10
+ // 保留最后一帧若不以 \n\n 结尾则为 remain
11
+ const normalized = remain.replace(/\r\n/g, "\n");
12
+ const parts = normalized.split("\n\n");
13
+ // 最后一部分若原串不以 \n\n 结尾则为 remain
14
+ const endsWithDelim = normalized.endsWith("\n\n") || normalized.endsWith("\n\r\n");
15
+ // parts 最后一项在非结尾时为未完成帧
16
+ const complete = endsWithDelim ? parts : parts.slice(0, -1);
17
+ remain = endsWithDelim ? "" : parts[parts.length - 1] || "";
18
+ for (const frame of complete) {
19
+ if (!frame) continue; // 空帧
20
+ const lines = frame.split("\n");
21
+ const dataLines = [];
22
+ for (const line of lines) {
23
+ if (!line) continue;
24
+ if (line.startsWith(":")) continue; // 注释/keepalive
25
+ if (line.startsWith("event:")) continue; // 事件类型忽略
26
+ if (line.startsWith("data:")) {
27
+ let v = line.slice(5);
28
+ if (v.startsWith(" ")) v = v.slice(1);
29
+ dataLines.push(v);
30
+ }
31
+ }
32
+ if (dataLines.length === 0) continue;
33
+ // 多行 data 按 \n 拼接(SSE 规范)
34
+ const payload = dataLines.join("\n");
35
+ // 空 data: 仍产生事件,由上层过滤;此处保留以便测试可见
36
+ events.push(payload);
37
+ }
38
+ return { events, remain };
39
+ }
40
+
41
+ export function createSseParser() {
42
+ let buf = "";
43
+ return {
44
+ push(chunk) {
45
+ buf += String(chunk || "");
46
+ const { events, remain } = parseSseChunk(buf);
47
+ buf = remain;
48
+ return events;
49
+ },
50
+ flush() {
51
+ // 未形成完整帧的不发(避免半包误触发)
52
+ if (!buf.trim()) { buf = ""; return []; }
53
+ // 若残留包含完整 data: 行但缺结尾,不强行发
54
+ return [];
55
+ },
56
+ getRemain() { return buf; },
57
+ };
58
+ }
59
+
60
+ export async function* streamFromResponse(res) {
61
+ if (!res || !res.body) return;
62
+ const parser = createSseParser();
63
+ const reader = res.body.getReader ? res.body.getReader() : null;
64
+ const decoder = new TextDecoder();
65
+ if (reader) {
66
+ while (true) {
67
+ const { done, value } = await reader.read();
68
+ if (done) break;
69
+ const text = decoder.decode(value, { stream: true });
70
+ const evs = parser.push(text);
71
+ for (const e of evs) {
72
+ if (e === "[DONE]") return;
73
+ if (e === "") continue;
74
+ yield e;
75
+ }
76
+ }
77
+ // flush 残留
78
+ const rest = parser.flush();
79
+ for (const e of rest) {
80
+ if (e === "[DONE]") return;
81
+ if (e) yield e;
82
+ }
83
+ } else if (typeof res.text === "function") {
84
+ // 回退:一次性 text
85
+ const txt = await res.text();
86
+ const evs = parser.push(txt);
87
+ for (const e of evs) {
88
+ if (e === "[DONE]") return;
89
+ if (e === "") continue;
90
+ yield e;
91
+ }
92
+ }
93
+ }
@@ -2,10 +2,16 @@
2
2
  // 显式映射常用面;未映射字段经 toProviderExtras 原样透传(providerOptions.<providerName> 会被 spread 进请求体)。
3
3
  // 共用库:workbuddy 实验通道与 upstream-engine 同源。见 .scratch/ai-sdk-upstream/SPEC.md。
4
4
 
5
+ // HANDLED_KEYS = 「SDK 通道自己消费、不再进 providerOptions 原样 spread」的键。
6
+ // 思考档位里 `reasoning_effort` 显式映射进 providerOptions.openaiCompatible.reasoningEffort;
7
+ // `reasoningEffort`/`effort`/`extra_body` 由各家前置整形器(如 workbuddy payload.js)折成自家原生形状后在此拦下,
8
+ // 免得 Claude Code 经 /v1/messages 新透传的 Anthropic 味字段裸奔到未取证的 OpenAI 兼容上游(ADR-0053)。
9
+ // ⚠ `thinking` 必须留在集合外:workbuddy 依赖它 spread 进请求体(见 workbuddy/chat.js 文件头)。
5
10
  const HANDLED_KEYS = new Set([
6
11
  "model", "messages", "stream", "tools", "tool_choice",
7
12
  "temperature", "top_p", "max_tokens", "stop",
8
13
  "presence_penalty", "frequency_penalty", "seed", "reasoning_effort",
14
+ "reasoningEffort", "effort", "extra_body",
9
15
  ]);
10
16
 
11
17
  function textOf(content) {
@@ -1,52 +1,52 @@
1
- // ADR-0015 展示渲染:-group list 行缀 + -status 汇总(纯函数,输入 routes 数据)
2
- // 四态文案:无数据→引导;有数据→摘要;坏数据→标 offline
3
-
4
- function bestDisplay(entry) {
5
- if (!entry) return null;
6
- const best = String(entry.best || "direct");
7
- const ms = best === "direct" ? (entry.direct?.ttfbMs ?? entry.direct?.totalMs) : (entry.via?.[best.slice(4)]?.ttfbMs ?? entry.via?.[best.slice(4)]?.totalMs);
8
- const tag = best === "direct" ? "direct" : `via ${best.slice(4)}`;
9
- if (entry.direct?.ok === false && !best.startsWith("via:")) return `${tag} (${entry.direct?.label || "offline"})`;
10
- return ms != null ? `${tag} ${ms}ms` : tag;
11
- }
12
-
13
- // -group list 静态成员行尾缀:该成员作为 best 出现时的供应商与相对直连收益
14
- export function groupRowSuffix(peerUrl, routes) {
15
- if (!peerUrl || !routes || typeof routes !== "object") return null;
16
- const label = (() => {
17
- const raw = String(peerUrl);
18
- if (raw.includes("://")) {
19
- try { const u = new URL(raw); return `${u.hostname}${u.port ? `:${u.port}` : ""}`; } catch { return raw.slice(-16); }
20
- }
21
- return raw;
22
- })();
23
- const wins = [];
24
- for (const [key, entry] of Object.entries(routes)) {
25
- if (!key.startsWith("provider:")) continue;
26
- const prov = key.slice(9);
27
- if (entry?.best === `via:${label}`) {
28
- const d = entry.deltaMs;
29
- wins.push(d != null ? `${prov} ${d > 0 ? "+" : ""}${d}ms` : prov);
30
- }
31
- }
32
- if (!wins.length) return null;
33
- return ` via-routes: ${wins.join(", ")}`;
34
- }
35
-
36
- // -status 汇总(多行字符串):探针条目摘要 ≤5 条;空数据给引导
37
- export function statusViaSummary({ routes, meta, probeMs }) {
38
- const list = Object.entries(routes || {}).filter(([k]) => k.startsWith("provider:"));
39
- if (!list.length) {
40
- return `via-routes: 无探针数据(后台探针 ${probeMs === 0 ? "已关闭" : "自动运行中"},加入组并配置 key/token 类供应商后自动生成)`;
41
- }
42
- const at = meta?.at ? new Date(meta.at) : null;
43
- const atStr = at && !Number.isNaN(at.getTime()) ? at.toISOString().slice(11, 19) + "Z" : "";
44
- const lines = [`via-routes: ${list.length} 条(探针自动${atStr ? `,${atStr} 刷新` : ""})`];
45
- for (const [key, entry] of list.slice(0, 5)) {
46
- const prov = key.slice(9);
47
- const b = bestDisplay(entry);
48
- if (b) lines.push(` ${prov} → ${b}${entry.deltaMs != null ? ` (${entry.deltaMs > 0 ? "+" : ""}${entry.deltaMs}ms vs direct)` : ""}`);
49
- }
50
- if (list.length > 5) lines.push(` … 其余 ${list.length - 5} 条见 via-routes.json`);
51
- return lines.join("\n");
52
- }
1
+ // ADR-0015 展示渲染:-group list 行缀 + -status 汇总(纯函数,输入 routes 数据)
2
+ // 四态文案:无数据→引导;有数据→摘要;坏数据→标 offline
3
+
4
+ function bestDisplay(entry) {
5
+ if (!entry) return null;
6
+ const best = String(entry.best || "direct");
7
+ const ms = best === "direct" ? (entry.direct?.ttfbMs ?? entry.direct?.totalMs) : (entry.via?.[best.slice(4)]?.ttfbMs ?? entry.via?.[best.slice(4)]?.totalMs);
8
+ const tag = best === "direct" ? "direct" : `via ${best.slice(4)}`;
9
+ if (entry.direct?.ok === false && !best.startsWith("via:")) return `${tag} (${entry.direct?.label || "offline"})`;
10
+ return ms != null ? `${tag} ${ms}ms` : tag;
11
+ }
12
+
13
+ // -group list 静态成员行尾缀:该成员作为 best 出现时的供应商与相对直连收益
14
+ export function groupRowSuffix(peerUrl, routes) {
15
+ if (!peerUrl || !routes || typeof routes !== "object") return null;
16
+ const label = (() => {
17
+ const raw = String(peerUrl);
18
+ if (raw.includes("://")) {
19
+ try { const u = new URL(raw); return `${u.hostname}${u.port ? `:${u.port}` : ""}`; } catch { return raw.slice(-16); }
20
+ }
21
+ return raw;
22
+ })();
23
+ const wins = [];
24
+ for (const [key, entry] of Object.entries(routes)) {
25
+ if (!key.startsWith("provider:")) continue;
26
+ const prov = key.slice(9);
27
+ if (entry?.best === `via:${label}`) {
28
+ const d = entry.deltaMs;
29
+ wins.push(d != null ? `${prov} ${d > 0 ? "+" : ""}${d}ms` : prov);
30
+ }
31
+ }
32
+ if (!wins.length) return null;
33
+ return ` via-routes: ${wins.join(", ")}`;
34
+ }
35
+
36
+ // -status 汇总(多行字符串):探针条目摘要 ≤5 条;空数据给引导
37
+ export function statusViaSummary({ routes, meta, probeMs }) {
38
+ const list = Object.entries(routes || {}).filter(([k]) => k.startsWith("provider:"));
39
+ if (!list.length) {
40
+ return `via-routes: 无探针数据(后台探针 ${probeMs === 0 ? "已关闭" : "自动运行中"},加入组并配置 key/token 类供应商后自动生成)`;
41
+ }
42
+ const at = meta?.at ? new Date(meta.at) : null;
43
+ const atStr = at && !Number.isNaN(at.getTime()) ? at.toISOString().slice(11, 19) + "Z" : "";
44
+ const lines = [`via-routes: ${list.length} 条(探针自动${atStr ? `,${atStr} 刷新` : ""})`];
45
+ for (const [key, entry] of list.slice(0, 5)) {
46
+ const prov = key.slice(9);
47
+ const b = bestDisplay(entry);
48
+ if (b) lines.push(` ${prov} → ${b}${entry.deltaMs != null ? ` (${entry.deltaMs > 0 ? "+" : ""}${entry.deltaMs}ms vs direct)` : ""}`);
49
+ }
50
+ if (list.length > 5) lines.push(` … 其余 ${list.length - 5} 条见 via-routes.json`);
51
+ return lines.join("\n");
52
+ }
@@ -1,49 +1,49 @@
1
- // ADR-0015 探针薄层:direct GET 探针 + 组员 /v1/relay 代发探针
2
- // 只测 GET <modelsPath>,不烧 token;组长侧计时。
3
- import { errMsg } from "../cli/util.js";
4
- import { compatFetch, timeoutSignal } from "../compat.js";
5
-
6
- export const PROBE_TIMEOUT_MS = 5000;
7
-
8
- export async function directProbe({ baseUrl, modelsPath = "/models", key = "", timeoutMs = PROBE_TIMEOUT_MS, fetchImpl = compatFetch, clock = Date.now, sampleMs } = {}) {
9
- const base = String(baseUrl || "").replace(/\/+$/, "");
10
- if (!base) return { ok: false, label: "配置错误", error: "missing baseUrl", ttfbMs: null };
11
- const p = String(modelsPath || "/models");
12
- const url = `${base}${p.startsWith("/") ? p : `/${p}`}`;
13
- const t0 = sampleMs ? sampleMs() : clock();
14
- try {
15
- const headers = { Accept: "application/json" };
16
- if (key) headers.Authorization = `Bearer ${key}`;
17
- const res = await fetchImpl(url, { method: "GET", headers, signal: timeoutSignal(timeoutMs) });
18
- const ms = sampleMs ? sampleMs() - t0 : clock() - t0;
19
- const status = typeof res.status === "number" ? res.status : (res.ok ? 200 : 0);
20
- if (status >= 400) return { ok: false, label: `HTTP ${status}`, ttfbMs: null };
21
- return { ok: true, ttfbMs: Math.max(0, Math.round(ms)) };
22
- } catch (e) {
23
- return { ok: false, label: errMsg(e).slice(0, 60), ttfbMs: null };
24
- }
25
- }
26
-
27
- // 组员代发:POST <peer>/v1/relay { targetUrl, method:"GET", headers } → 组员 fetch 上游后原样回
28
- export async function relayViaProbe({ peerUrl, peerToken = "", targetUrl, authHeader = "", timeoutMs = PROBE_TIMEOUT_MS, fetchImpl = compatFetch, clock = Date.now, sampleMs } = {}) {
29
- const peer = String(peerUrl || "").replace(/\/+$/, "");
30
- if (!peer || !targetUrl) return { ok: false, label: "配置错误", ttfbMs: null };
31
- const t0 = sampleMs ? sampleMs() : clock();
32
- try {
33
- const headers = { "Content-Type": "application/json", Accept: "application/json" };
34
- if (peerToken) headers.Authorization = `Bearer ${peerToken}`;
35
- const res = await fetchImpl(`${peer}/v1/relay`, {
36
- method: "POST",
37
- headers,
38
- body: JSON.stringify({ targetUrl, method: "GET", headers: authHeader ? { Authorization: authHeader } : {} }),
39
- signal: timeoutSignal(timeoutMs),
40
- });
41
- const ms = sampleMs ? sampleMs() - t0 : clock() - t0;
42
- const relayStatus = res.headers?.get?.("x-mslxdff-relay-status");
43
- const status = relayStatus != null ? Number(relayStatus) : (res.status ?? 0);
44
- if (status >= 400) return { ok: false, label: `HTTP ${status}`, ttfbMs: null };
45
- return { ok: true, ttfbMs: Math.max(0, Math.round(ms)) };
46
- } catch (e) {
47
- return { ok: false, label: errMsg(e).slice(0, 60), ttfbMs: null };
48
- }
49
- }
1
+ // ADR-0015 探针薄层:direct GET 探针 + 组员 /v1/relay 代发探针
2
+ // 只测 GET <modelsPath>,不烧 token;组长侧计时。
3
+ import { errMsg } from "../cli/util.js";
4
+ import { compatFetch, timeoutSignal } from "../compat.js";
5
+
6
+ export const PROBE_TIMEOUT_MS = 5000;
7
+
8
+ export async function directProbe({ baseUrl, modelsPath = "/models", key = "", timeoutMs = PROBE_TIMEOUT_MS, fetchImpl = compatFetch, clock = Date.now, sampleMs } = {}) {
9
+ const base = String(baseUrl || "").replace(/\/+$/, "");
10
+ if (!base) return { ok: false, label: "配置错误", error: "missing baseUrl", ttfbMs: null };
11
+ const p = String(modelsPath || "/models");
12
+ const url = `${base}${p.startsWith("/") ? p : `/${p}`}`;
13
+ const t0 = sampleMs ? sampleMs() : clock();
14
+ try {
15
+ const headers = { Accept: "application/json" };
16
+ if (key) headers.Authorization = `Bearer ${key}`;
17
+ const res = await fetchImpl(url, { method: "GET", headers, signal: timeoutSignal(timeoutMs) });
18
+ const ms = sampleMs ? sampleMs() - t0 : clock() - t0;
19
+ const status = typeof res.status === "number" ? res.status : (res.ok ? 200 : 0);
20
+ if (status >= 400) return { ok: false, label: `HTTP ${status}`, ttfbMs: null };
21
+ return { ok: true, ttfbMs: Math.max(0, Math.round(ms)) };
22
+ } catch (e) {
23
+ return { ok: false, label: errMsg(e).slice(0, 60), ttfbMs: null };
24
+ }
25
+ }
26
+
27
+ // 组员代发:POST <peer>/v1/relay { targetUrl, method:"GET", headers } → 组员 fetch 上游后原样回
28
+ export async function relayViaProbe({ peerUrl, peerToken = "", targetUrl, authHeader = "", timeoutMs = PROBE_TIMEOUT_MS, fetchImpl = compatFetch, clock = Date.now, sampleMs } = {}) {
29
+ const peer = String(peerUrl || "").replace(/\/+$/, "");
30
+ if (!peer || !targetUrl) return { ok: false, label: "配置错误", ttfbMs: null };
31
+ const t0 = sampleMs ? sampleMs() : clock();
32
+ try {
33
+ const headers = { "Content-Type": "application/json", Accept: "application/json" };
34
+ if (peerToken) headers.Authorization = `Bearer ${peerToken}`;
35
+ const res = await fetchImpl(`${peer}/v1/relay`, {
36
+ method: "POST",
37
+ headers,
38
+ body: JSON.stringify({ targetUrl, method: "GET", headers: authHeader ? { Authorization: authHeader } : {} }),
39
+ signal: timeoutSignal(timeoutMs),
40
+ });
41
+ const ms = sampleMs ? sampleMs() - t0 : clock() - t0;
42
+ const relayStatus = res.headers?.get?.("x-mslxdff-relay-status");
43
+ const status = relayStatus != null ? Number(relayStatus) : (res.status ?? 0);
44
+ if (status >= 400) return { ok: false, label: `HTTP ${status}`, ttfbMs: null };
45
+ return { ok: true, ttfbMs: Math.max(0, Math.round(ms)) };
46
+ } catch (e) {
47
+ return { ok: false, label: errMsg(e).slice(0, 60), ttfbMs: null };
48
+ }
49
+ }