mslxdff 0.1.187 → 0.1.188

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 (111) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/docs/cli_help_mini.md +145 -0
  3. package/package.json +1 -1
  4. package/src/auto.js +254 -254
  5. package/src/autostart.js +5 -2
  6. package/src/bench/cline-bench.js +42 -42
  7. package/src/bench/probe.js +70 -70
  8. package/src/bench/report.js +162 -162
  9. package/src/bench/runner.js +77 -77
  10. package/src/bench/via-probe.js +124 -124
  11. package/src/bench/via-routes.js +87 -87
  12. package/src/bench/workbuddy-bench.js +54 -54
  13. package/src/chat/engine.js +160 -160
  14. package/src/chat/gateway.js +163 -163
  15. package/src/chat/orchestrator.js +234 -234
  16. package/src/chat/prompt.js +70 -70
  17. package/src/chat/repl.js +88 -88
  18. package/src/chat/terminal.js +135 -135
  19. package/src/chat/tools.js +306 -306
  20. package/src/chat-pipeline/index.js +173 -131
  21. package/src/chat-pipeline/policy.js +84 -84
  22. package/src/chat-pipeline/serial-trial.js +6 -3
  23. package/src/chat-pipeline/terminal-verdict.js +29 -0
  24. package/src/cli/commands/daemon.js +55 -18
  25. package/src/cli/commands/group.js +249 -249
  26. package/src/cli/commands/model/picks.js +50 -50
  27. package/src/cli/commands/provider/bench-via.js +247 -247
  28. package/src/cli/commands/provider/bench.js +141 -141
  29. package/src/cli/commands/provider/index.js +136 -136
  30. package/src/cli/commands/provider/models.js +145 -145
  31. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  32. package/src/cli/commands/sync.js +310 -310
  33. package/src/cli/commands/system.js +23 -7
  34. package/src/cli/join-wizard.js +8 -4
  35. package/src/cli/policy.js +14 -2
  36. package/src/cli/status.js +279 -279
  37. package/src/daemon.js +232 -195
  38. package/src/logs.js +27 -11
  39. package/src/model-capabilities/enrich.js +86 -86
  40. package/src/model-capabilities/index.js +183 -183
  41. package/src/model-capabilities/parse.js +70 -70
  42. package/src/model-trace.js +35 -4
  43. package/src/models.js +225 -225
  44. package/src/peers.js +20 -1
  45. package/src/providers/AGENTS.md +49 -0
  46. package/src/providers/cline/auth.js +228 -228
  47. package/src/providers/cline/chat.js +307 -307
  48. package/src/providers/cline.js +2 -2
  49. package/src/providers/codearts/chat.js +182 -182
  50. package/src/providers/globalqwenwork/cosy.js +123 -123
  51. package/src/providers/globalqwenwork/crypto.js +218 -218
  52. package/src/providers/globalqwenwork/http.js +20 -20
  53. package/src/providers/globalqwenwork/rsa.js +54 -54
  54. package/src/providers/globalqwenwork/sse.js +268 -268
  55. package/src/providers/globalqwenwork/stream.js +130 -130
  56. package/src/providers/globalqwenwork/upstream.js +122 -122
  57. package/src/providers/keyring.js +60 -60
  58. package/src/providers/qoder/chat.js +203 -203
  59. package/src/providers/qoder/index.js +249 -249
  60. package/src/providers/qoder/sse.js +145 -145
  61. package/src/providers/qwenwork/account-store.js +133 -133
  62. package/src/providers/qwenwork/constants.js +67 -67
  63. package/src/providers/qwenwork/cosy.js +120 -120
  64. package/src/providers/qwenwork/crypto.js +218 -218
  65. package/src/providers/qwenwork/http.js +20 -20
  66. package/src/providers/qwenwork/index.js +337 -327
  67. package/src/providers/qwenwork/payload.js +144 -144
  68. package/src/providers/qwenwork/rsa.js +54 -54
  69. package/src/providers/qwenwork/sse.js +268 -268
  70. package/src/providers/qwenwork/stream.js +130 -130
  71. package/src/providers/qwenwork/upstream.js +120 -120
  72. package/src/providers/qwenwork.js +1 -1
  73. package/src/providers/registry.js +79 -79
  74. package/src/providers/traework/chat.js +7 -1
  75. package/src/providers/workbuddy/chat.js +248 -248
  76. package/src/providers/workbuddy/reshape.js +152 -152
  77. package/src/providers/workbuddy.js +2 -2
  78. package/src/reasoning.js +32 -32
  79. package/src/routes/AGENTS.md +37 -0
  80. package/src/routes/chat/empty-turn-report.js +31 -0
  81. package/src/routes/chat/gateway.js +46 -46
  82. package/src/routes/chat/peer-handler.js +3 -2
  83. package/src/routes/chat/relay-pipeline.js +282 -294
  84. package/src/routes/chat/via-route-handler.js +146 -146
  85. package/src/routes/hedge.js +253 -255
  86. package/src/routes/index.js +14 -6
  87. package/src/routes/models-route.js +167 -167
  88. package/src/routes/peers.js +335 -273
  89. package/src/routes/responses-route.js +44 -2
  90. package/src/routes/stream-body.js +84 -0
  91. package/src/routes/stream-hold.js +152 -4
  92. package/src/routes/stream-scan.js +27 -2
  93. package/src/routes/stream.js +343 -385
  94. package/src/runtime/bootstrap.js +67 -67
  95. package/src/runtime/group-sync.js +70 -17
  96. package/src/runtime/provider-gate.js +36 -36
  97. package/src/runtime/providers-setup.js +168 -168
  98. package/src/runtime/server-lifecycle.js +1 -1
  99. package/src/server.js +78 -78
  100. package/src/state/schemas/allowlist.js +92 -92
  101. package/src/sync-opencode.js +280 -280
  102. package/src/transport/index.js +244 -244
  103. package/src/transport/pool.js +56 -56
  104. package/src/transport/retry.js +24 -24
  105. package/src/transport/sse.js +93 -93
  106. package/src/upstream-engine/sdk/attempt.js +9 -1
  107. package/src/upstream-probe/display.js +52 -52
  108. package/src/upstream-probe/probe.js +49 -49
  109. package/src/upstream-probe/rotate.js +110 -110
  110. package/src/upstream-probe/start.js +45 -45
  111. package/src/upstream.js +293 -293
package/src/upstream.js CHANGED
@@ -1,293 +1,293 @@
1
- import crypto from "node:crypto";
2
- import { mkdirSync } from "node:fs";
3
- import { appendFile } from "node:fs/promises";
4
- import { dirname, join } from "node:path";
5
- import { performance } from "node:perf_hooks";
6
- import { isFreeModel } from "./models.js";
7
- import { fmtShanghaiYMDHMS } from "./time.js";
8
- import { createTransport } from "./transport/index.js";
9
- import { isResponsesModel, chatToResponsesBody, toChatResponse, reshapeResponsesSse } from "./upstream-responses.js";
10
- import { ensureFreeLaneShape, aggregateChatSse } from "./free-lane.js";
11
- import { digestIdTail, genId, opencodeClientIdentity, opencodeUa } from "./opencode-identity.js";
12
-
13
- export { opencodeClientIdentity, opencodeUa };
14
- // 上游按 session 做粘性路由(实测:固定 session 两次请求均 ~1.2s;每次随机时可能撞冷机器 26s+)。
15
- // 客户端(opencode AI SDK 路径)不带会话标识 → 用对话首两条消息(system + 首条 user)哈希做稳定会话:
16
- // 同一会话多轮里这两条不变 ⇒ 路由亲和稳定;不同会话天然分散。
17
- function sessionFromMessages(messages) {
18
- try {
19
- const msgs = Array.isArray(messages) ? messages : [];
20
- const pick = (role) => {
21
- const m = msgs.find((x) => x?.role === role);
22
- if (!m) return "";
23
- return typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? "");
24
- };
25
- const seed = `${pick("system")}|${pick("user")}`.slice(0, 4000);
26
- if (seed === "|") return null;
27
- return `ses_${digestIdTail(crypto.createHash("sha1").update(seed).digest())}`;
28
- } catch {
29
- return null;
30
- }
31
- }
32
- function envInt(name, fallback) {
33
- const v = Number(process.env[name]);
34
- return Number.isInteger(v) && v > 0 ? v : fallback;
35
- }
36
- function isPreheatDisabled() {
37
- const raw = process.env.MSLXDFF_PREHEAT;
38
- if (raw === undefined || raw === null || raw === "") return false;
39
- const s = String(raw).trim().toLowerCase();
40
- return s === "0" || s === "off" || s === "false" || s === "no" || s === "disable" || s === "disabled";
41
- }
42
- // opencode 上游身份头单一来源(legacy 与 SDK 引擎共用,free 层门禁头必须一致)。
43
- // anonFirst 语义:authToken==="public" 时默认匿名(hermes referer);env 可显式覆盖。
44
- export function createOpencodeHeaderBuilder({ authToken = "public", env = process.env } = {}) {
45
- function isAnonFirst() {
46
- const raw = env.MSLXDFF_OPENCOD_ANON_FIRST ?? env.MSLXDFF_ANON_FIRST ?? env.MSLXDFF_OPENCOD_ANON;
47
- if (raw === undefined || raw === null || raw === "") return authToken === "public";
48
- const s = String(raw).trim().toLowerCase();
49
- if (s === "0" || s === "false" || s === "off" || s === "no" || s === "disable" || s === "disabled") return false;
50
- return authToken === "public";
51
- }
52
- const anonFirst = isAnonFirst();
53
- const baseHeaders = anonFirst
54
- ? {
55
- "Content-Type": "application/json",
56
- Authorization: "",
57
- "x-opencode-client": "desktop",
58
- "User-Agent": opencodeUa(),
59
- "HTTP-Referer": "https://hermes-agent.nousresearch.com",
60
- "X-Title": "Hermes Agent",
61
- }
62
- : {
63
- "Content-Type": "application/json",
64
- Authorization: `Bearer ${authToken}`,
65
- "x-opencode-client": "desktop",
66
- };
67
- // 无 messages 可哈希时的进程级兜底:至少 daemon 生命周期内稳定,不再每请求随机
68
- const FALLBACK_SESSION = genId("ses_");
69
- function buildHeaders(body, { anonymous = anonFirst, sessionId = null } = {}) {
70
- const isStream = body?.stream !== false;
71
- const session = sessionId || sessionFromMessages(body?.messages) || FALLBACK_SESSION;
72
- const base = {
73
- ...baseHeaders,
74
- Accept: isStream ? "text/event-stream" : "*/*",
75
- "User-Agent": opencodeUa(),
76
- "x-opencode-session": session,
77
- "x-opencode-request": genId("msg_"),
78
- "x-opencode-project": "global",
79
- };
80
- if (anonymous) {
81
- return { ...base, Authorization: "", "HTTP-Referer": "https://hermes-agent.nousresearch.com", "X-Title": "Hermes Agent" };
82
- }
83
- if (anonFirst) {
84
- const { "HTTP-Referer": _a, "X-Title": _b, ...rest } = base;
85
- return { ...rest, Authorization: `Bearer ${authToken}` };
86
- }
87
- return base;
88
- }
89
- return { buildHeaders, anonFirst };
90
- }
91
-
92
- export function createUpstreamClient({
93
- baseUrl = process.env.UPSTREAM_BASE_URL || "https://opencode.ai",
94
- authToken = process.env.UPSTREAM_AUTH_TOKEN || "public",
95
- connectTimeoutMs = Number(process.env.UPSTREAM_CONNECT_TIMEOUT_MS) || 30_000,
96
- retry = {
97
- network: { attempts: 2, delayMs: 300 },
98
- 429: { attempts: 1, delayMs: 100 },
99
- 502: { attempts: 1, delayMs: 100 },
100
- 503: { attempts: 1, delayMs: 100 },
101
- 504: { attempts: 1, delayMs: 100 },
102
- },
103
- fetchImpl,
104
- hooks,
105
- keepAlive = true,
106
- dispatcher,
107
- } = {}) {
108
- const { buildHeaders, anonFirst } = createOpencodeHeaderBuilder({ authToken });
109
- function shouldTryAnonFree() {
110
- const raw = process.env.MSLXDFF_FREE_ANON;
111
- if (raw === "0" || raw === "off" || raw === "false" || raw === "no") return false;
112
- return true;
113
- }
114
- function freeAnonLogFile() {
115
- return process.env.MSLXDFF_FREE_ANON_LOG || join(process.cwd(), "free-anon-extra.txt");
116
- }
117
- function logFreeAnon({ model, publicStatus, anonStatus, anonAttempts, hit, totalMs }) {
118
- const file = freeAnonLogFile();
119
- const line = `${fmtShanghaiYMDHMS(new Date())} model=${model} public=429 anonTries=${anonAttempts} anonStatus=${anonStatus ?? "none"} hit=${hit ? "YES额外额度" : "NO无额外"} totalMs=${totalMs} count=${hit ? "1" : "0"}\n`;
120
- try { mkdirSync(dirname(file), { recursive: true }); } catch {}
121
- appendFile(file, line).catch(() => {});
122
- try { if (process.env.MSLXDFF_DEBUG === "1") console.log(`[free-anon] ${line.trim()}`); } catch {}
123
- }
124
- let consecutiveHits = 0;
125
-
126
- // 深模块:网络层委托 StreamingTransport
127
- const transport = createTransport({
128
- keepAlive,
129
- dispatcher,
130
- fetchImpl,
131
- timeoutMs: connectTimeoutMs,
132
- retry,
133
- hooks,
134
- });
135
-
136
- async function chat(body, opts = {}) {
137
- const isResp = isResponsesModel(body?.model);
138
- // responses 路径的 reqBody 无 messages,会话哈希必须基于原始 chat body 计算
139
- const sessionId = opts?.sessionId || sessionFromMessages(body?.messages) || null;
140
- const url = isResp ? `${baseUrl}/zen/v1/responses` : `${baseUrl}/zen/v1/chat/completions`;
141
- const reqBody = isResp ? chatToResponsesBody(body) : body;
142
- const clientWantsStream = body?.stream !== false;
143
- // zen 免费层 agent 形状门禁(2026-09-18):必须流式 + 含核心五工具名,否则 403 FreeTierError
144
- const freeLane = authToken === "public" && isFreeModel(body?.model);
145
- if (freeLane) ensureFreeLaneShape(reqBody, { responses: isResp });
146
- const laneDebug = freeLane && envInt("MSLXDFF_FREE_LANE_DEBUG", 0) === 1;
147
- if (laneDebug) {
148
- try { console.error(`[free-lane] send model=${body?.model} url=${url} stream=${reqBody.stream} tools=${(reqBody.tools || []).length} ua=${opencodeUa()} want=${clientWantsStream}`); } catch {}
149
- }
150
- // 非流式调用者实际拿到的是被强制流式的上游 → 聚合回 chat completion JSON
151
- async function agentJson(resp) {
152
- if (!(freeLane && !clientWantsStream && resp.ok)) return resp;
153
- const ct = resp.headers?.get?.("content-type") || "";
154
- if (!ct.includes("text/event-stream")) return resp;
155
- try {
156
- const out = await aggregateChatSse(resp);
157
- out._t = resp._t;
158
- return out;
159
- } catch {
160
- return resp;
161
- }
162
- }
163
- const t0 = performance.now();
164
-
165
- // 首发请求(transport 已处理 network/429 等重试)
166
- let res;
167
- try {
168
- res = await transport.request({
169
- url,
170
- method: "POST",
171
- headers: buildHeaders(reqBody, { sessionId }),
172
- body: reqBody,
173
- stream: reqBody.stream !== false,
174
- timeoutMs: connectTimeoutMs,
175
- retry,
176
- });
177
- } catch (e) {
178
- e._t = e._t || { attempts: [], waitMs: 0, totalMs: Math.round(performance.now() - t0) };
179
- throw e;
180
- }
181
- if (laneDebug) {
182
- try { console.error(`[free-lane] resp model=${body?.model} status=${res.status} ct=${res.headers?.get?.("content-type") || ""}`); } catch {}
183
- }
184
-
185
- // 匿名兜底:仅非 anonFirst 时,public 429 + free 模型才走 hermes 空头重试
186
- if (!anonFirst && res.status === 429 && isFreeModel(body?.model) && shouldTryAnonFree()) {
187
- const anonRetries = envInt("MSLXDFF_FREE_ANON_RETRIES", 3);
188
- const anonDelay = envInt("MSLXDFF_FREE_ANON_DELAY_MS", 1000);
189
- let anonRes = null;
190
- for (let i = 0; i < anonRetries; i++) {
191
- await new Promise((r) => setTimeout(r, anonDelay));
192
- try {
193
- anonRes = await transport.request({
194
- url,
195
- method: "POST",
196
- headers: buildHeaders(reqBody, { anonymous: true, sessionId }),
197
- body: reqBody,
198
- stream: reqBody.stream !== false,
199
- timeoutMs: connectTimeoutMs,
200
- retry,
201
- });
202
- } catch (e) {
203
- continue;
204
- }
205
- if (anonRes.status !== 429) {
206
- // responses 模型需转回 chat 形状(复用 upstream-responses)
207
- let outAnon = anonRes;
208
- if (isResp && anonRes.ok) {
209
- const ctAnon = anonRes.headers.get("content-type") || "";
210
- const isStreamAnon = (clientWantsStream || freeLane) && ctAnon.includes("text/event-stream");
211
- if (isStreamAnon) {
212
- outAnon = reshapeResponsesSse(anonRes, body.model);
213
- } else {
214
- try {
215
- const txt = await anonRes.text();
216
- const j = JSON.parse(txt);
217
- if (j && Array.isArray(j.output)) {
218
- outAnon = toChatResponse(anonRes, j);
219
- } else {
220
- outAnon = new Response(txt, { status: anonRes.status, headers: anonRes.headers });
221
- }
222
- } catch { outAnon = anonRes; }
223
- }
224
- }
225
- outAnon._t = { ...(outAnon._t || {}), anonTried: true, anonAttempts: i + 1, totalMs: Math.round(performance.now() - t0) };
226
- consecutiveHits += 1;
227
- logFreeAnon({ model: body?.model, publicStatus: 429, anonStatus: anonRes.status, anonAttempts: i + 1, hit: true, totalMs: outAnon._t.totalMs });
228
- if (consecutiveHits >= 2) {
229
- try { appendFile(freeAnonLogFile(), ` -> 连续额外额度 ${consecutiveHits} 次\n`).catch(() => {}); } catch {}
230
- }
231
- return await agentJson(outAnon);
232
- }
233
- }
234
- if (anonRes) {
235
- anonRes._t = { ...(anonRes._t || {}), anonTried: true, anonAttempts: anonRetries, totalMs: Math.round(performance.now() - t0) };
236
- consecutiveHits = 0;
237
- logFreeAnon({ model: body?.model, publicStatus: 429, anonStatus: anonRes.status, anonAttempts: anonRetries, hit: false, totalMs: anonRes._t.totalMs });
238
- return anonRes;
239
- }
240
- }
241
-
242
- // responses 模型成功态转 chat(复用 upstream-responses)
243
- if (isResp && res.ok) {
244
- const ct = res.headers.get("content-type") || "";
245
- const isStream = (clientWantsStream || freeLane) && ct.includes("text/event-stream");
246
- if (isStream) {
247
- const transformed = reshapeResponsesSse(res, body.model);
248
- transformed._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
249
- return await agentJson(transformed);
250
- }
251
- try {
252
- const txt = await res.text();
253
- const j = JSON.parse(txt);
254
- if (j && Array.isArray(j.output)) {
255
- const transformed = toChatResponse(res, j);
256
- transformed._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
257
- return transformed;
258
- }
259
- const fallback = new Response(txt, { status: res.status, headers: res.headers });
260
- fallback._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
261
- return fallback;
262
- } catch {
263
- res._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
264
- return res;
265
- }
266
- }
267
- res._t = { ...(res._t || {}), totalMs: res._t?.totalMs ?? Math.round(performance.now() - t0) };
268
- return await agentJson(res);
269
- }
270
-
271
- async function preheat() {
272
- if (isPreheatDisabled()) return { ok: false, skipped: true, reason: "disabled" };
273
- const t0 = performance.now();
274
- try {
275
- const res = await transport.request({
276
- url: `${baseUrl}/zen/v1/models`,
277
- method: "GET",
278
- headers: buildHeaders({ stream: false }),
279
- stream: false,
280
- timeoutMs: 3000,
281
- });
282
- try { await res.text().catch(() => {}); } catch {}
283
- return { ok: res.ok, status: res.status, ms: Math.round(performance.now() - t0) };
284
- } catch (e) {
285
- return { ok: false, error: String(e?.message || e), ms: Math.round(performance.now() - t0) };
286
- }
287
- }
288
- async function close() {
289
- await transport.close();
290
- }
291
- const headers = buildHeaders({});
292
- return { chat, preheat, close, headers, buildHeaders, get dispatcher() { return transport.dispatcher; }, get agent() { return transport.agent; }, [Symbol.asyncDispose]: close };
293
- }
1
+ import crypto from "node:crypto";
2
+ import { mkdirSync } from "node:fs";
3
+ import { appendFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import { isFreeModel } from "./models.js";
7
+ import { fmtShanghaiYMDHMS } from "./time.js";
8
+ import { createTransport } from "./transport/index.js";
9
+ import { isResponsesModel, chatToResponsesBody, toChatResponse, reshapeResponsesSse } from "./upstream-responses.js";
10
+ import { ensureFreeLaneShape, aggregateChatSse } from "./free-lane.js";
11
+ import { digestIdTail, genId, opencodeClientIdentity, opencodeUa } from "./opencode-identity.js";
12
+
13
+ export { opencodeClientIdentity, opencodeUa };
14
+ // 上游按 session 做粘性路由(实测:固定 session 两次请求均 ~1.2s;每次随机时可能撞冷机器 26s+)。
15
+ // 客户端(opencode AI SDK 路径)不带会话标识 → 用对话首两条消息(system + 首条 user)哈希做稳定会话:
16
+ // 同一会话多轮里这两条不变 ⇒ 路由亲和稳定;不同会话天然分散。
17
+ function sessionFromMessages(messages) {
18
+ try {
19
+ const msgs = Array.isArray(messages) ? messages : [];
20
+ const pick = (role) => {
21
+ const m = msgs.find((x) => x?.role === role);
22
+ if (!m) return "";
23
+ return typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? "");
24
+ };
25
+ const seed = `${pick("system")}|${pick("user")}`.slice(0, 4000);
26
+ if (seed === "|") return null;
27
+ return `ses_${digestIdTail(crypto.createHash("sha1").update(seed).digest())}`;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ function envInt(name, fallback) {
33
+ const v = Number(process.env[name]);
34
+ return Number.isInteger(v) && v > 0 ? v : fallback;
35
+ }
36
+ function isPreheatDisabled() {
37
+ const raw = process.env.MSLXDFF_PREHEAT;
38
+ if (raw === undefined || raw === null || raw === "") return false;
39
+ const s = String(raw).trim().toLowerCase();
40
+ return s === "0" || s === "off" || s === "false" || s === "no" || s === "disable" || s === "disabled";
41
+ }
42
+ // opencode 上游身份头单一来源(legacy 与 SDK 引擎共用,free 层门禁头必须一致)。
43
+ // anonFirst 语义:authToken==="public" 时默认匿名(hermes referer);env 可显式覆盖。
44
+ export function createOpencodeHeaderBuilder({ authToken = "public", env = process.env } = {}) {
45
+ function isAnonFirst() {
46
+ const raw = env.MSLXDFF_OPENCOD_ANON_FIRST ?? env.MSLXDFF_ANON_FIRST ?? env.MSLXDFF_OPENCOD_ANON;
47
+ if (raw === undefined || raw === null || raw === "") return authToken === "public";
48
+ const s = String(raw).trim().toLowerCase();
49
+ if (s === "0" || s === "false" || s === "off" || s === "no" || s === "disable" || s === "disabled") return false;
50
+ return authToken === "public";
51
+ }
52
+ const anonFirst = isAnonFirst();
53
+ const baseHeaders = anonFirst
54
+ ? {
55
+ "Content-Type": "application/json",
56
+ Authorization: "",
57
+ "x-opencode-client": "desktop",
58
+ "User-Agent": opencodeUa(),
59
+ "HTTP-Referer": "https://hermes-agent.nousresearch.com",
60
+ "X-Title": "Hermes Agent",
61
+ }
62
+ : {
63
+ "Content-Type": "application/json",
64
+ Authorization: `Bearer ${authToken}`,
65
+ "x-opencode-client": "desktop",
66
+ };
67
+ // 无 messages 可哈希时的进程级兜底:至少 daemon 生命周期内稳定,不再每请求随机
68
+ const FALLBACK_SESSION = genId("ses_");
69
+ function buildHeaders(body, { anonymous = anonFirst, sessionId = null } = {}) {
70
+ const isStream = body?.stream !== false;
71
+ const session = sessionId || sessionFromMessages(body?.messages) || FALLBACK_SESSION;
72
+ const base = {
73
+ ...baseHeaders,
74
+ Accept: isStream ? "text/event-stream" : "*/*",
75
+ "User-Agent": opencodeUa(),
76
+ "x-opencode-session": session,
77
+ "x-opencode-request": genId("msg_"),
78
+ "x-opencode-project": "global",
79
+ };
80
+ if (anonymous) {
81
+ return { ...base, Authorization: "", "HTTP-Referer": "https://hermes-agent.nousresearch.com", "X-Title": "Hermes Agent" };
82
+ }
83
+ if (anonFirst) {
84
+ const { "HTTP-Referer": _a, "X-Title": _b, ...rest } = base;
85
+ return { ...rest, Authorization: `Bearer ${authToken}` };
86
+ }
87
+ return base;
88
+ }
89
+ return { buildHeaders, anonFirst };
90
+ }
91
+
92
+ export function createUpstreamClient({
93
+ baseUrl = process.env.UPSTREAM_BASE_URL || "https://opencode.ai",
94
+ authToken = process.env.UPSTREAM_AUTH_TOKEN || "public",
95
+ connectTimeoutMs = Number(process.env.UPSTREAM_CONNECT_TIMEOUT_MS) || 30_000,
96
+ retry = {
97
+ network: { attempts: 2, delayMs: 300 },
98
+ 429: { attempts: 1, delayMs: 100 },
99
+ 502: { attempts: 1, delayMs: 100 },
100
+ 503: { attempts: 1, delayMs: 100 },
101
+ 504: { attempts: 1, delayMs: 100 },
102
+ },
103
+ fetchImpl,
104
+ hooks,
105
+ keepAlive = true,
106
+ dispatcher,
107
+ } = {}) {
108
+ const { buildHeaders, anonFirst } = createOpencodeHeaderBuilder({ authToken });
109
+ function shouldTryAnonFree() {
110
+ const raw = process.env.MSLXDFF_FREE_ANON;
111
+ if (raw === "0" || raw === "off" || raw === "false" || raw === "no") return false;
112
+ return true;
113
+ }
114
+ function freeAnonLogFile() {
115
+ return process.env.MSLXDFF_FREE_ANON_LOG || join(process.cwd(), "free-anon-extra.txt");
116
+ }
117
+ function logFreeAnon({ model, publicStatus, anonStatus, anonAttempts, hit, totalMs }) {
118
+ const file = freeAnonLogFile();
119
+ const line = `${fmtShanghaiYMDHMS(new Date())} model=${model} public=429 anonTries=${anonAttempts} anonStatus=${anonStatus ?? "none"} hit=${hit ? "YES额外额度" : "NO无额外"} totalMs=${totalMs} count=${hit ? "1" : "0"}\n`;
120
+ try { mkdirSync(dirname(file), { recursive: true }); } catch {}
121
+ appendFile(file, line).catch(() => {});
122
+ try { if (process.env.MSLXDFF_DEBUG === "1") console.log(`[free-anon] ${line.trim()}`); } catch {}
123
+ }
124
+ let consecutiveHits = 0;
125
+
126
+ // 深模块:网络层委托 StreamingTransport
127
+ const transport = createTransport({
128
+ keepAlive,
129
+ dispatcher,
130
+ fetchImpl,
131
+ timeoutMs: connectTimeoutMs,
132
+ retry,
133
+ hooks,
134
+ });
135
+
136
+ async function chat(body, opts = {}) {
137
+ const isResp = isResponsesModel(body?.model);
138
+ // responses 路径的 reqBody 无 messages,会话哈希必须基于原始 chat body 计算
139
+ const sessionId = opts?.sessionId || sessionFromMessages(body?.messages) || null;
140
+ const url = isResp ? `${baseUrl}/zen/v1/responses` : `${baseUrl}/zen/v1/chat/completions`;
141
+ const reqBody = isResp ? chatToResponsesBody(body) : body;
142
+ const clientWantsStream = body?.stream !== false;
143
+ // zen 免费层 agent 形状门禁(2026-09-18):必须流式 + 含核心五工具名,否则 403 FreeTierError
144
+ const freeLane = authToken === "public" && isFreeModel(body?.model);
145
+ if (freeLane) ensureFreeLaneShape(reqBody, { responses: isResp });
146
+ const laneDebug = freeLane && envInt("MSLXDFF_FREE_LANE_DEBUG", 0) === 1;
147
+ if (laneDebug) {
148
+ try { console.error(`[free-lane] send model=${body?.model} url=${url} stream=${reqBody.stream} tools=${(reqBody.tools || []).length} ua=${opencodeUa()} want=${clientWantsStream}`); } catch {}
149
+ }
150
+ // 非流式调用者实际拿到的是被强制流式的上游 → 聚合回 chat completion JSON
151
+ async function agentJson(resp) {
152
+ if (!(freeLane && !clientWantsStream && resp.ok)) return resp;
153
+ const ct = resp.headers?.get?.("content-type") || "";
154
+ if (!ct.includes("text/event-stream")) return resp;
155
+ try {
156
+ const out = await aggregateChatSse(resp);
157
+ out._t = resp._t;
158
+ return out;
159
+ } catch {
160
+ return resp;
161
+ }
162
+ }
163
+ const t0 = performance.now();
164
+
165
+ // 首发请求(transport 已处理 network/429 等重试)
166
+ let res;
167
+ try {
168
+ res = await transport.request({
169
+ url,
170
+ method: "POST",
171
+ headers: buildHeaders(reqBody, { sessionId }),
172
+ body: reqBody,
173
+ stream: reqBody.stream !== false,
174
+ timeoutMs: connectTimeoutMs,
175
+ retry,
176
+ });
177
+ } catch (e) {
178
+ e._t = e._t || { attempts: [], waitMs: 0, totalMs: Math.round(performance.now() - t0) };
179
+ throw e;
180
+ }
181
+ if (laneDebug) {
182
+ try { console.error(`[free-lane] resp model=${body?.model} status=${res.status} ct=${res.headers?.get?.("content-type") || ""}`); } catch {}
183
+ }
184
+
185
+ // 匿名兜底:仅非 anonFirst 时,public 429 + free 模型才走 hermes 空头重试
186
+ if (!anonFirst && res.status === 429 && isFreeModel(body?.model) && shouldTryAnonFree()) {
187
+ const anonRetries = envInt("MSLXDFF_FREE_ANON_RETRIES", 3);
188
+ const anonDelay = envInt("MSLXDFF_FREE_ANON_DELAY_MS", 1000);
189
+ let anonRes = null;
190
+ for (let i = 0; i < anonRetries; i++) {
191
+ await new Promise((r) => setTimeout(r, anonDelay));
192
+ try {
193
+ anonRes = await transport.request({
194
+ url,
195
+ method: "POST",
196
+ headers: buildHeaders(reqBody, { anonymous: true, sessionId }),
197
+ body: reqBody,
198
+ stream: reqBody.stream !== false,
199
+ timeoutMs: connectTimeoutMs,
200
+ retry,
201
+ });
202
+ } catch (e) {
203
+ continue;
204
+ }
205
+ if (anonRes.status !== 429) {
206
+ // responses 模型需转回 chat 形状(复用 upstream-responses)
207
+ let outAnon = anonRes;
208
+ if (isResp && anonRes.ok) {
209
+ const ctAnon = anonRes.headers.get("content-type") || "";
210
+ const isStreamAnon = (clientWantsStream || freeLane) && ctAnon.includes("text/event-stream");
211
+ if (isStreamAnon) {
212
+ outAnon = reshapeResponsesSse(anonRes, body.model);
213
+ } else {
214
+ try {
215
+ const txt = await anonRes.text();
216
+ const j = JSON.parse(txt);
217
+ if (j && Array.isArray(j.output)) {
218
+ outAnon = toChatResponse(anonRes, j);
219
+ } else {
220
+ outAnon = new Response(txt, { status: anonRes.status, headers: anonRes.headers });
221
+ }
222
+ } catch { outAnon = anonRes; }
223
+ }
224
+ }
225
+ outAnon._t = { ...(outAnon._t || {}), anonTried: true, anonAttempts: i + 1, totalMs: Math.round(performance.now() - t0) };
226
+ consecutiveHits += 1;
227
+ logFreeAnon({ model: body?.model, publicStatus: 429, anonStatus: anonRes.status, anonAttempts: i + 1, hit: true, totalMs: outAnon._t.totalMs });
228
+ if (consecutiveHits >= 2) {
229
+ try { appendFile(freeAnonLogFile(), ` -> 连续额外额度 ${consecutiveHits} 次\n`).catch(() => {}); } catch {}
230
+ }
231
+ return await agentJson(outAnon);
232
+ }
233
+ }
234
+ if (anonRes) {
235
+ anonRes._t = { ...(anonRes._t || {}), anonTried: true, anonAttempts: anonRetries, totalMs: Math.round(performance.now() - t0) };
236
+ consecutiveHits = 0;
237
+ logFreeAnon({ model: body?.model, publicStatus: 429, anonStatus: anonRes.status, anonAttempts: anonRetries, hit: false, totalMs: anonRes._t.totalMs });
238
+ return anonRes;
239
+ }
240
+ }
241
+
242
+ // responses 模型成功态转 chat(复用 upstream-responses)
243
+ if (isResp && res.ok) {
244
+ const ct = res.headers.get("content-type") || "";
245
+ const isStream = (clientWantsStream || freeLane) && ct.includes("text/event-stream");
246
+ if (isStream) {
247
+ const transformed = reshapeResponsesSse(res, body.model);
248
+ transformed._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
249
+ return await agentJson(transformed);
250
+ }
251
+ try {
252
+ const txt = await res.text();
253
+ const j = JSON.parse(txt);
254
+ if (j && Array.isArray(j.output)) {
255
+ const transformed = toChatResponse(res, j);
256
+ transformed._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
257
+ return transformed;
258
+ }
259
+ const fallback = new Response(txt, { status: res.status, headers: res.headers });
260
+ fallback._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
261
+ return fallback;
262
+ } catch {
263
+ res._t = { ...(res._t || {}), totalMs: Math.round(performance.now() - t0) };
264
+ return res;
265
+ }
266
+ }
267
+ res._t = { ...(res._t || {}), totalMs: res._t?.totalMs ?? Math.round(performance.now() - t0) };
268
+ return await agentJson(res);
269
+ }
270
+
271
+ async function preheat() {
272
+ if (isPreheatDisabled()) return { ok: false, skipped: true, reason: "disabled" };
273
+ const t0 = performance.now();
274
+ try {
275
+ const res = await transport.request({
276
+ url: `${baseUrl}/zen/v1/models`,
277
+ method: "GET",
278
+ headers: buildHeaders({ stream: false }),
279
+ stream: false,
280
+ timeoutMs: 3000,
281
+ });
282
+ try { await res.text().catch(() => {}); } catch {}
283
+ return { ok: res.ok, status: res.status, ms: Math.round(performance.now() - t0) };
284
+ } catch (e) {
285
+ return { ok: false, error: String(e?.message || e), ms: Math.round(performance.now() - t0) };
286
+ }
287
+ }
288
+ async function close() {
289
+ await transport.close();
290
+ }
291
+ const headers = buildHeaders({});
292
+ return { chat, preheat, close, headers, buildHeaders, get dispatcher() { return transport.dispatcher; }, get agent() { return transport.agent; }, [Symbol.asyncDispose]: close };
293
+ }