mslxdff 0.1.203 → 0.1.207
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/README.md +3 -3
- package/bin/mslxdff.js +1 -1
- package/docs/cli_help_mini.md +146 -0
- package/package.json +38 -38
- package/plugins/README.md +14 -14
- package/plugins/prefer-model.mjs.example +14 -14
- package/src/anthropic/canonical-json.js +55 -0
- package/src/anthropic/count-tokens.js +61 -61
- package/src/anthropic/request-body.js +183 -126
- package/src/anthropic/request-shape.js +60 -0
- package/src/anthropic/session-id.js +58 -0
- package/src/anthropic/shared.js +18 -18
- package/src/anthropic/sse-aggregate.js +56 -56
- package/src/anthropic/tool-media.js +75 -0
- package/src/anthropic/translate.js +296 -287
- package/src/anthropic/web-search.js +361 -361
- package/src/api-kind.js +31 -31
- package/src/autostart.js +288 -288
- package/src/bench/probe.js +1 -1
- package/src/bench/runner.js +1 -1
- package/src/bench/via-probe.js +1 -1
- package/src/bench/via.js +144 -144
- package/src/bench/workbuddy-bench.js +1 -1
- package/src/chat/config.js +11 -11
- package/src/chat/cooling.js +81 -81
- package/src/chat/direct.js +58 -58
- package/src/chat/index.js +6 -6
- package/src/chat/spinner.js +38 -38
- package/src/chat/sse.js +69 -69
- package/src/chat/stats.js +247 -247
- package/src/chat/store.js +48 -48
- package/src/chat/tool-handlers.js +67 -67
- package/src/chat/tools.js +1 -1
- package/src/chat/upstream.js +59 -59
- package/src/chat-pipeline/auto-race.js +158 -158
- package/src/chat-pipeline/empty-turn.js +147 -147
- package/src/chat-pipeline/engine.js +17 -17
- package/src/chat-pipeline/index.js +8 -40
- package/src/chat-pipeline/serial-trial.js +279 -283
- package/src/chat-pipeline/terminal-verdict.js +132 -147
- package/src/chooser.js +54 -54
- package/src/claude-desktop/apply.js +101 -101
- package/src/claude-desktop/context1m.js +38 -38
- package/src/claude-desktop/doctor.js +146 -146
- package/src/claude-desktop/slots.js +152 -152
- package/src/cli/bootstrap.js +1 -1
- package/src/cli/commands/claude-desktop.js +284 -284
- package/src/cli/commands/daemon.js +231 -231
- package/src/cli/commands/model/list-live.js +22 -22
- package/src/cli/commands/model/list-providers.js +76 -76
- package/src/cli/commands/model/list-render.js +77 -77
- package/src/cli/commands/model/list-sort.js +52 -52
- package/src/cli/commands/model/list-tty.js +76 -76
- package/src/cli/commands/model/list.js +166 -166
- package/src/cli/commands/model/live-models.js +24 -24
- package/src/cli/commands/model/stats.js +43 -43
- package/src/cli/commands/model/status.js +47 -47
- package/src/cli/commands/model.js +51 -51
- package/src/cli/commands/provider/add.js +108 -108
- package/src/cli/commands/provider/allowlist.js +99 -99
- package/src/cli/commands/provider/cline-free.js +99 -99
- package/src/cli/commands/provider/cline-login.js +218 -218
- package/src/cli/commands/provider/cline-quota.js +65 -65
- package/src/cli/commands/provider/codearts-login.js +45 -45
- package/src/cli/commands/provider/config.js +119 -119
- package/src/cli/commands/provider/globalqwenwork-login.js +126 -126
- package/src/cli/commands/provider/keys-guard.js +50 -50
- package/src/cli/commands/provider/keys.js +161 -161
- package/src/cli/commands/provider/qoder-checkin.js +81 -81
- package/src/cli/commands/provider/qoder-login.js +102 -102
- package/src/cli/commands/provider/raccoon-login.js +180 -180
- package/src/cli/commands/provider/raccoon-password.js +162 -162
- package/src/cli/commands/provider/raccoon-quota.js +109 -109
- package/src/cli/commands/provider/traework-checkin.js +144 -144
- package/src/cli/commands/provider/traework-login.js +164 -164
- package/src/cli/commands/provider/workbuddy-login.js +153 -153
- package/src/cli/commands/provider/zcode-login.js +77 -77
- package/src/cli/commands/provider/zcode-quota.js +55 -55
- package/src/cli/commands/provider.js +1 -1
- package/src/cli/commands/stats.js +158 -149
- package/src/cli/commands/system.js +261 -261
- package/src/cli/commands/timezone.js +47 -47
- package/src/cli/commands/use-group.js +60 -60
- package/src/cli/commands/workbuddy.js +189 -189
- package/src/cli/format.js +141 -141
- package/src/cli/group-helpers.js +70 -70
- package/src/cli/help.js +80 -80
- package/src/cli/index.js +70 -70
- package/src/cli/interactive.js +121 -121
- package/src/cli/join-core.js +99 -99
- package/src/cli/join-wizard.js +175 -175
- package/src/cli/policy.js +136 -136
- package/src/cli/provider-row.js +126 -126
- package/src/cli/util.js +24 -24
- package/src/compat.js +53 -53
- package/src/events.js +38 -38
- package/src/free-lane.js +131 -131
- package/src/free-watcher.js +63 -63
- package/src/groups.js +262 -262
- package/src/logs.js +195 -195
- package/src/metrics.js +71 -62
- package/src/model-capabilities/context-lookup.js +65 -65
- package/src/model-capabilities/merge.js +142 -142
- package/src/model-trace.js +187 -187
- package/src/models.js +1 -1
- package/src/opencode-identity.js +72 -72
- package/src/peers.js +254 -254
- package/src/plugins.js +107 -107
- package/src/providers/AGENTS.md +49 -0
- package/src/providers/base.js +164 -164
- package/src/providers/classify.js +22 -22
- package/src/providers/cline/allowlist-sync.js +93 -93
- package/src/providers/cline/free-catalog.js +71 -71
- package/src/providers/cline/headers.js +37 -37
- package/src/providers/cline/index.js +130 -130
- package/src/providers/cline/models.js +150 -150
- package/src/providers/cline/usage.js +274 -274
- package/src/providers/codearts/auth-pool.js +148 -148
- package/src/providers/codearts/concurrency.js +34 -34
- package/src/providers/codearts/const.js +65 -65
- package/src/providers/codearts/dpop.js +95 -95
- package/src/providers/codearts/index.js +175 -175
- package/src/providers/codearts/login.js +214 -214
- package/src/providers/codearts/models.js +182 -182
- package/src/providers/codearts/sign.js +96 -96
- package/src/providers/codearts/sse.js +204 -204
- package/src/providers/codearts/stream.js +209 -209
- package/src/providers/codearts/sts.js +124 -124
- package/src/providers/codearts.js +1 -1
- package/src/providers/dispatcher.js +146 -146
- package/src/providers/generic.js +156 -156
- package/src/providers/globalqwenwork/account-store.js +141 -141
- package/src/providers/globalqwenwork/constants.js +73 -73
- package/src/providers/globalqwenwork/crypto.js +2 -2
- package/src/providers/globalqwenwork/http.js +2 -2
- package/src/providers/globalqwenwork/index.js +331 -331
- package/src/providers/globalqwenwork/payload.js +147 -147
- package/src/providers/globalqwenwork/rsa.js +2 -2
- package/src/providers/globalqwenwork/sse.js +2 -2
- package/src/providers/globalqwenwork/stream.js +2 -2
- package/src/providers/globalqwenwork.js +1 -1
- package/src/providers/globalworkbuddy/account-store.js +198 -198
- package/src/providers/globalworkbuddy/auth.js +97 -97
- package/src/providers/globalworkbuddy/catalog.js +138 -138
- package/src/providers/globalworkbuddy/constants.js +73 -73
- package/src/providers/globalworkbuddy/device-auth.js +120 -120
- package/src/providers/globalworkbuddy/errors.js +98 -98
- package/src/providers/globalworkbuddy/headers.js +89 -89
- package/src/providers/globalworkbuddy/models.js +96 -96
- package/src/providers/globalworkbuddy/payload.js +80 -80
- package/src/providers/index.js +5 -5
- package/src/providers/model-id.js +172 -172
- package/src/providers/opencode.js +19 -19
- package/src/providers/openrouter.js +31 -31
- package/src/providers/qoder/account-store.js +106 -106
- package/src/providers/qoder/aggregate.js +60 -60
- package/src/providers/qoder/baseprompt.json +591 -591
- package/src/providers/qoder/checkin.js +160 -160
- package/src/providers/qoder/constants.js +44 -44
- package/src/providers/qoder/encode.js +41 -41
- package/src/providers/qoder/fingerprint.js +38 -38
- package/src/providers/qoder/models.js +77 -77
- package/src/providers/qoder/oauth.js +84 -84
- package/src/providers/qoder/payload.js +162 -162
- package/src/providers/qoder/request.js +27 -27
- package/src/providers/qoder/session.js +134 -134
- package/src/providers/qoder/sticky.js +38 -38
- package/src/providers/qoder/stream.js +116 -116
- package/src/providers/qoder.js +1 -1
- package/src/providers/raccoon/account-store.js +216 -216
- package/src/providers/raccoon/auth.js +67 -67
- package/src/providers/raccoon/chat.js +228 -228
- package/src/providers/raccoon/const.js +180 -180
- package/src/providers/raccoon/credits.js +185 -185
- package/src/providers/raccoon/crypto.js +43 -43
- package/src/providers/raccoon/envelope.js +31 -31
- package/src/providers/raccoon/headers.js +45 -45
- package/src/providers/raccoon/index.js +216 -216
- package/src/providers/raccoon/login.js +279 -279
- package/src/providers/raccoon/models.js +160 -160
- package/src/providers/raccoon/password-login.js +102 -102
- package/src/providers/raccoon/qr-codewords.js +115 -115
- package/src/providers/raccoon/qr.js +236 -236
- package/src/providers/raccoon/sse.js +135 -135
- package/src/providers/responses-channel.js +120 -120
- package/src/providers/share-keys.js +53 -53
- package/src/providers/traework/account-store.js +234 -234
- package/src/providers/traework/chat.js +217 -217
- package/src/providers/traework/checkin.js +77 -77
- package/src/providers/traework/constants.js +41 -41
- package/src/providers/traework/errors.js +52 -52
- package/src/providers/traework/headers.js +79 -79
- package/src/providers/traework/index.js +132 -132
- package/src/providers/traework/market-identity.js +116 -116
- package/src/providers/traework/models.js +98 -98
- package/src/providers/traework/payload.js +86 -86
- package/src/providers/traework/sse.js +184 -184
- package/src/providers/traework/token.js +52 -52
- package/src/providers/traework.js +2 -2
- package/src/providers/workbuddy/account-store.js +186 -186
- package/src/providers/workbuddy/auth.js +158 -158
- package/src/providers/workbuddy/balance.js +86 -86
- package/src/providers/workbuddy/cat-travel.js +125 -125
- package/src/providers/workbuddy/checkin.js +75 -75
- package/src/providers/workbuddy/desktop-info.js +78 -78
- package/src/providers/workbuddy/growth-api.js +67 -67
- package/src/providers/workbuddy/growth-plans.js +63 -63
- package/src/providers/workbuddy/growth.js +181 -181
- package/src/providers/workbuddy/index.js +217 -217
- package/src/providers/workbuddy/models.js +126 -126
- package/src/providers/workbuddy/payload.js +141 -141
- package/src/providers/workbuddy/rotation-log.js +83 -83
- package/src/providers/workbuddy/sanitize-tools.js +61 -61
- package/src/providers/workbuddy/sdk-chat.js +26 -26
- package/src/providers/workbuddy-balance.js +78 -78
- package/src/providers/zcode/account-store.js +129 -129
- package/src/providers/zcode/auth.js +28 -28
- package/src/providers/zcode/chat.js +179 -179
- package/src/providers/zcode/const.js +54 -54
- package/src/providers/zcode/context-shape.js +162 -162
- package/src/providers/zcode/headers.js +93 -93
- package/src/providers/zcode/index.js +124 -124
- package/src/providers/zcode/models.js +65 -65
- package/src/providers/zcode/oauth.js +120 -120
- package/src/providers/zcode/quota.js +176 -176
- package/src/providers/zcode/sse.js +196 -196
- package/src/readline-compat.js +25 -25
- package/src/responses/translate.js +311 -311
- package/src/routes/AGENTS.md +37 -0
- package/src/routes/chat/broadband-handler.js +72 -72
- package/src/routes/chat/empty-turn-report.js +31 -31
- package/src/routes/chat/exhausted-handler.js +87 -87
- package/src/routes/chat/hedge-handler.js +130 -130
- package/src/routes/chat/index.js +1 -1
- package/src/routes/chat/local-handler.js +63 -63
- package/src/routes/chat/peer-handler.js +81 -81
- package/src/routes/chat.js +3 -3
- package/src/routes/fallback.js +88 -88
- package/src/routes/groups-relay.js +214 -214
- package/src/routes/groups.js +122 -122
- package/src/routes/helpers.js +93 -83
- package/src/routes/index.js +147 -147
- package/src/routes/messages-route.js +375 -365
- package/src/routes/peers.js +10 -2
- package/src/routes/relay-queue.js +181 -181
- package/src/routes/relay.js +60 -60
- package/src/routes/responses-route.js +213 -213
- package/src/routes/stream-body.js +84 -84
- package/src/routes/stream-hold.js +337 -337
- package/src/routes/stream-scan.js +366 -366
- package/src/routes.js +3 -3
- package/src/runtime/auto-update.js +113 -113
- package/src/runtime/broadband-stream.js +79 -79
- package/src/runtime/broadband.js +103 -103
- package/src/runtime/group-sync.js +81 -81
- package/src/runtime/keep-warm.js +120 -120
- package/src/runtime/lifecycle-forensics.js +116 -116
- package/src/runtime/lifecycle-log.js +87 -87
- package/src/runtime/log-stamp.js +73 -73
- package/src/runtime/proc-info.js +137 -137
- package/src/runtime/qoder-checkin.js +93 -93
- package/src/runtime/raccoon-checkin.js +126 -126
- package/src/runtime/server-lifecycle.js +189 -189
- package/src/runtime/traework-checkin.js +118 -118
- package/src/runtime/workbuddy-checkin.js +120 -120
- package/src/runtime/workbuddy-growth.js +133 -133
- package/src/state/facade.js +58 -58
- package/src/state/memory.js +162 -162
- package/src/state/merge.js +25 -25
- package/src/state/migrations/cline-unify.js +94 -94
- package/src/state/migrations.js +33 -33
- package/src/state/persist.js +42 -42
- package/src/state/provider-config.js +142 -142
- package/src/state/schemas/group.js +31 -31
- package/src/state/schemas/model.js +94 -94
- package/src/state/schemas/peer.js +31 -31
- package/src/state/schemas/port.js +10 -10
- package/src/state/schemas/provider.js +202 -202
- package/src/state/schemas/timezone.js +70 -70
- package/src/state/schemas/token.js +48 -48
- package/src/state/schemas/use-group.js +102 -102
- package/src/state/store.js +176 -176
- package/src/state.js +1 -1
- package/src/sync-claude-desktop.js +234 -234
- package/src/sync-claude.js +152 -152
- package/src/sync-codex.js +116 -116
- package/src/sync-workbuddy.js +158 -158
- package/src/talk-full-redact.js +129 -129
- package/src/talk-full.js +131 -131
- package/src/talk-log.js +257 -257
- package/src/text-tokens.js +52 -52
- package/src/thinking-effort.js +67 -67
- package/src/time.js +106 -106
- package/src/timeline.js +26 -26
- package/src/transport/index.js +1 -1
- package/src/upstream-engine/index.js +74 -74
- package/src/upstream-engine/mode.js +15 -15
- package/src/upstream-engine/sdk/attempt.js +221 -221
- package/src/upstream-engine/sdk/chat.js +28 -28
- package/src/upstream-engine/sdk/convert.js +192 -192
- package/src/upstream-engine/sdk/diagnose.js +62 -62
- package/src/upstream-engine/sdk/dispatch.js +55 -55
- package/src/upstream-engine/sdk/responses.js +176 -176
- package/src/upstream-engine/sdk/sse.js +166 -166
- package/src/upstream-responses.js +305 -305
- package/src/usage/cache-fields.js +58 -0
- package/src/usage/record.js +109 -106
- package/src/usage/report.js +209 -195
- package/src/v6pool/claim.js +157 -157
- package/src/v6pool/config.js +65 -65
- package/src/v6pool/detect.js +130 -130
- package/src/v6pool/index.js +152 -152
- package/src/v6pool/prefix.js +140 -140
- package/src/v6pool/probe.js +40 -40
- package/src/v6pool/report.js +104 -104
- package/src/v6pool/rotate.js +263 -263
- package/src/warp-pool/config.js +74 -74
- package/src/warp-pool/health.js +106 -106
- package/src/warp-pool/identity.js +141 -141
- package/src/warp-pool/index.js +358 -358
- package/src/warp-pool/keys.js +29 -29
- package/src/warp-pool/nodes.js +95 -95
- package/src/warp-pool/ports.js +160 -160
- package/src/warp-pool/register.js +113 -113
- package/src/warp-pool/report.js +232 -232
- package/src/warp-pool/revive.js +168 -168
- package/src/warp-pool/rotate.js +214 -214
- package/src/warp-pool/strategy.js +43 -43
- package/src/warp-pool/verdict.js +69 -69
- package/src/warp-pool/wireproxy.js +162 -162
|
@@ -1,77 +1,77 @@
|
|
|
1
|
-
// qoder 模型服务(转译 bridge.go ListModels/extractModels):原生 COSY 签名拉 /model/list,
|
|
2
|
-
// 10min 缓存(按 region 分桶);只暴露 enable=true 的可用模型(enable=false 调对话必挂,不展示)。
|
|
3
|
-
import { compatFetch, timeoutSignal } from "../../compat.js";
|
|
4
|
-
import { getEndpoints, normalizeRegion } from "./constants.js";
|
|
5
|
-
import { buildCosyHeaders, pathSigFrom } from "./session.js";
|
|
6
|
-
import { joinModelId } from "../model-id.js";
|
|
7
|
-
|
|
8
|
-
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
9
|
-
const CREATED = 1753600000;
|
|
10
|
-
const OWNER = "qoder";
|
|
11
|
-
|
|
12
|
-
export function extractModels(chatList) {
|
|
13
|
-
const out = [];
|
|
14
|
-
for (const m of Array.isArray(chatList) ? chatList : []) {
|
|
15
|
-
if (!m?.key) continue;
|
|
16
|
-
out.push({
|
|
17
|
-
id: m.key,
|
|
18
|
-
name: String(m.display_name || m.key),
|
|
19
|
-
enable: Boolean(m.enable),
|
|
20
|
-
isDefault: Boolean(m.is_default),
|
|
21
|
-
isReasoning: Boolean(m.is_reasoning),
|
|
22
|
-
contextLength: Number(m.max_input_tokens) || 0,
|
|
23
|
-
priceFactor: Number(m.price_factor) || 0,
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
return out;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export function createModelsService({ id = "qoder", fetchImpl, clock = Date.now } = {}) {
|
|
30
|
-
let cache = null, fetchedAt = 0;
|
|
31
|
-
|
|
32
|
-
// 按 region 分桶缓存:同一进程可能有 cn + global 双号,混用单桶会串区(cn 14 个/global 15 个各不同)。
|
|
33
|
-
const cacheByRegion = new Map();
|
|
34
|
-
async function listModels(sess, region = "global") {
|
|
35
|
-
const normRegion = normalizeRegion(region);
|
|
36
|
-
const now = clock();
|
|
37
|
-
const hit = cacheByRegion.get(normRegion);
|
|
38
|
-
if (hit && now - hit.at < CACHE_TTL_MS) return hit.list;
|
|
39
|
-
const ep = getEndpoints(normRegion);
|
|
40
|
-
const url = ep.modelListURL;
|
|
41
|
-
const headers = buildCosyHeaders(sess, pathSigFrom(url), "", "application/json");
|
|
42
|
-
const res = await fetchImpl(url, { headers, signal: timeoutSignal(15000) });
|
|
43
|
-
if (!res.ok) throw new Error(`models http ${res.status}`);
|
|
44
|
-
const j = await res.json().catch(() => ({}));
|
|
45
|
-
// extractModels 恒返回数组(空数组亦 truthy),必须按长度选 chat/assistant 分支
|
|
46
|
-
const chatModels = extractModels(j.chat);
|
|
47
|
-
const models = chatModels.length ? chatModels : extractModels(j.assistant);
|
|
48
|
-
if (!models.length) throw new Error("models list empty");
|
|
49
|
-
// 只留可用:enable=false 的 key(如 global 的 auto/ultimate,cn 的绝大多数)展示即误导
|
|
50
|
-
const usable = models.filter((m) => m.enable);
|
|
51
|
-
if (!usable.length) throw new Error("models list empty (no enabled models)");
|
|
52
|
-
const list = usable.map((m) => ({
|
|
53
|
-
id: joinModelId(id, m.id),
|
|
54
|
-
object: "model",
|
|
55
|
-
created: CREATED,
|
|
56
|
-
owned_by: OWNER,
|
|
57
|
-
name: m.name,
|
|
58
|
-
context_length: m.contextLength,
|
|
59
|
-
enable: true,
|
|
60
|
-
is_reasoning: m.isReasoning,
|
|
61
|
-
price_factor: m.priceFactor,
|
|
62
|
-
}));
|
|
63
|
-
cacheByRegion.set(normRegion, { list, at: now });
|
|
64
|
-
// 兼容旧单测 _getCache:默认读 global 桶
|
|
65
|
-
cache = normRegion === "global" ? list : cache;
|
|
66
|
-
fetchedAt = normRegion === "global" ? now : fetchedAt;
|
|
67
|
-
return list;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function clearCache() { cache = null; fetchedAt = 0; cacheByRegion.clear(); }
|
|
71
|
-
// 快照语义(评审路2 P0:不吃 TTL):daemon 稳态里 chat 不再回源,能力标记「过期」也比「丢失」强——
|
|
72
|
-
// is_reasoning 启动预热后持续有效;刷新走 listModels(preheat/CLI/聚合路由),chat 路径恒 0 额外上游调用。
|
|
73
|
-
function peekModels(region = "global") {
|
|
74
|
-
return cacheByRegion.get(normalizeRegion(region))?.list ?? null;
|
|
75
|
-
}
|
|
76
|
-
return { listModels, peekModels, clearCache, _getCache: () => cache ?? cacheByRegion.get("global")?.list ?? null };
|
|
77
|
-
}
|
|
1
|
+
// qoder 模型服务(转译 bridge.go ListModels/extractModels):原生 COSY 签名拉 /model/list,
|
|
2
|
+
// 10min 缓存(按 region 分桶);只暴露 enable=true 的可用模型(enable=false 调对话必挂,不展示)。
|
|
3
|
+
import { compatFetch, timeoutSignal } from "../../compat.js";
|
|
4
|
+
import { getEndpoints, normalizeRegion } from "./constants.js";
|
|
5
|
+
import { buildCosyHeaders, pathSigFrom } from "./session.js";
|
|
6
|
+
import { joinModelId } from "../model-id.js";
|
|
7
|
+
|
|
8
|
+
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
9
|
+
const CREATED = 1753600000;
|
|
10
|
+
const OWNER = "qoder";
|
|
11
|
+
|
|
12
|
+
export function extractModels(chatList) {
|
|
13
|
+
const out = [];
|
|
14
|
+
for (const m of Array.isArray(chatList) ? chatList : []) {
|
|
15
|
+
if (!m?.key) continue;
|
|
16
|
+
out.push({
|
|
17
|
+
id: m.key,
|
|
18
|
+
name: String(m.display_name || m.key),
|
|
19
|
+
enable: Boolean(m.enable),
|
|
20
|
+
isDefault: Boolean(m.is_default),
|
|
21
|
+
isReasoning: Boolean(m.is_reasoning),
|
|
22
|
+
contextLength: Number(m.max_input_tokens) || 0,
|
|
23
|
+
priceFactor: Number(m.price_factor) || 0,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function createModelsService({ id = "qoder", fetchImpl, clock = Date.now } = {}) {
|
|
30
|
+
let cache = null, fetchedAt = 0;
|
|
31
|
+
|
|
32
|
+
// 按 region 分桶缓存:同一进程可能有 cn + global 双号,混用单桶会串区(cn 14 个/global 15 个各不同)。
|
|
33
|
+
const cacheByRegion = new Map();
|
|
34
|
+
async function listModels(sess, region = "global") {
|
|
35
|
+
const normRegion = normalizeRegion(region);
|
|
36
|
+
const now = clock();
|
|
37
|
+
const hit = cacheByRegion.get(normRegion);
|
|
38
|
+
if (hit && now - hit.at < CACHE_TTL_MS) return hit.list;
|
|
39
|
+
const ep = getEndpoints(normRegion);
|
|
40
|
+
const url = ep.modelListURL;
|
|
41
|
+
const headers = buildCosyHeaders(sess, pathSigFrom(url), "", "application/json");
|
|
42
|
+
const res = await fetchImpl(url, { headers, signal: timeoutSignal(15000) });
|
|
43
|
+
if (!res.ok) throw new Error(`models http ${res.status}`);
|
|
44
|
+
const j = await res.json().catch(() => ({}));
|
|
45
|
+
// extractModels 恒返回数组(空数组亦 truthy),必须按长度选 chat/assistant 分支
|
|
46
|
+
const chatModels = extractModels(j.chat);
|
|
47
|
+
const models = chatModels.length ? chatModels : extractModels(j.assistant);
|
|
48
|
+
if (!models.length) throw new Error("models list empty");
|
|
49
|
+
// 只留可用:enable=false 的 key(如 global 的 auto/ultimate,cn 的绝大多数)展示即误导
|
|
50
|
+
const usable = models.filter((m) => m.enable);
|
|
51
|
+
if (!usable.length) throw new Error("models list empty (no enabled models)");
|
|
52
|
+
const list = usable.map((m) => ({
|
|
53
|
+
id: joinModelId(id, m.id),
|
|
54
|
+
object: "model",
|
|
55
|
+
created: CREATED,
|
|
56
|
+
owned_by: OWNER,
|
|
57
|
+
name: m.name,
|
|
58
|
+
context_length: m.contextLength,
|
|
59
|
+
enable: true,
|
|
60
|
+
is_reasoning: m.isReasoning,
|
|
61
|
+
price_factor: m.priceFactor,
|
|
62
|
+
}));
|
|
63
|
+
cacheByRegion.set(normRegion, { list, at: now });
|
|
64
|
+
// 兼容旧单测 _getCache:默认读 global 桶
|
|
65
|
+
cache = normRegion === "global" ? list : cache;
|
|
66
|
+
fetchedAt = normRegion === "global" ? now : fetchedAt;
|
|
67
|
+
return list;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function clearCache() { cache = null; fetchedAt = 0; cacheByRegion.clear(); }
|
|
71
|
+
// 快照语义(评审路2 P0:不吃 TTL):daemon 稳态里 chat 不再回源,能力标记「过期」也比「丢失」强——
|
|
72
|
+
// is_reasoning 启动预热后持续有效;刷新走 listModels(preheat/CLI/聚合路由),chat 路径恒 0 额外上游调用。
|
|
73
|
+
function peekModels(region = "global") {
|
|
74
|
+
return cacheByRegion.get(normalizeRegion(region))?.list ?? null;
|
|
75
|
+
}
|
|
76
|
+
return { listModels, peekModels, clearCache, _getCache: () => cache ?? cacheByRegion.get("global")?.list ?? null };
|
|
77
|
+
}
|
|
@@ -1,85 +1,85 @@
|
|
|
1
|
-
// qoder OAuth 设备授权(转译 qoder2api account/oauth.go):
|
|
2
|
-
// 1. startLogin: PKCE(S256) + nonce → 返回授权链接
|
|
3
|
-
// 2. pollDeviceToken: 轮询 deviceToken/poll,404=未授权继续,200={token:dt-xxx, refresh_token:drt-xxx}
|
|
4
|
-
// 3. fetchUserInfo: GET /api/v1/userinfo(Bearer dt-xxx)→ uid/name/organization_id
|
|
5
|
-
import { randomBytes, createHash } from "node:crypto";
|
|
6
|
-
import { compatFetch, timeoutSignal } from "../../compat.js";
|
|
7
|
-
import { OAUTH_CLIENT_ID, getEndpoints } from "./constants.js";
|
|
8
|
-
|
|
9
|
-
const POLL_MS = 3000;
|
|
10
|
-
export const POLL_TIMEOUT_MS = 10 * 60 * 1000; // 对齐 qoder2api 10 分钟
|
|
11
|
-
|
|
12
|
-
export function pkce() {
|
|
13
|
-
const verifier = randomBytes(32).toString("base64url");
|
|
14
|
-
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
15
|
-
return { verifier, challenge };
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function hex16() {
|
|
19
|
-
return randomBytes(16).toString("hex");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function buildLoginUrl({ region = "global", nonce, challenge } = {}) {
|
|
23
|
-
const ep = getEndpoints(region);
|
|
24
|
-
const params = new URLSearchParams({
|
|
25
|
-
nonce,
|
|
26
|
-
challenge,
|
|
27
|
-
challenge_method: "S256",
|
|
28
|
-
client_id: OAUTH_CLIENT_ID,
|
|
29
|
-
});
|
|
30
|
-
return `${ep.deviceLoginBase}?${params.toString()}`;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// 单次轮询:404/空 token → 未授权(返回 null);200 且有 token → bundle;5xx → 抛错。
|
|
34
|
-
export async function pollDeviceToken({ region = "global", nonce, verifier, fetchImpl = compatFetch } = {}) {
|
|
35
|
-
const ep = getEndpoints(region);
|
|
36
|
-
const url = `${ep.pollEndpoint}?nonce=${encodeURIComponent(nonce)}&verifier=${encodeURIComponent(verifier)}&challenge_method=S256`;
|
|
37
|
-
let res;
|
|
38
|
-
try {
|
|
39
|
-
res = await fetchImpl(url, { signal: timeoutSignal(20000) });
|
|
40
|
-
} catch (e) {
|
|
41
|
-
throw new Error(`轮询失败: ${e.message}`);
|
|
42
|
-
}
|
|
43
|
-
if (res.status === 404) return null; // 还没授权
|
|
44
|
-
if (res.status >= 500) throw new Error(`deviceToken 端点故障: HTTP ${res.status}`);
|
|
45
|
-
const txt = await res.text().catch(() => "");
|
|
46
|
-
let j;
|
|
47
|
-
try { j = JSON.parse(txt); } catch { throw new Error(`deviceToken 返回非 JSON: ${txt.slice(0, 200)}`); }
|
|
48
|
-
const deviceToken = String(j.token || "");
|
|
49
|
-
if (!deviceToken) return null;
|
|
50
|
-
return { deviceToken, refreshToken: String(j.refresh_token || "") };
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// userinfo:ResolveOAuthUserID 优先 id/userId/uid(qoder2api bridge.go)。
|
|
54
|
-
export async function fetchUserInfo({ region = "global", deviceToken, fetchImpl = compatFetch } = {}) {
|
|
55
|
-
const ep = getEndpoints(region);
|
|
56
|
-
const res = await fetchImpl(ep.userinfoBase, {
|
|
57
|
-
headers: { Authorization: `Bearer ${deviceToken}` },
|
|
58
|
-
signal: timeoutSignal(20000),
|
|
59
|
-
});
|
|
60
|
-
const txt = await res.text().catch(() => "");
|
|
61
|
-
let j;
|
|
62
|
-
try { j = JSON.parse(txt); } catch { throw new Error(`userinfo 返回非 JSON: HTTP ${res.status} ${txt.slice(0, 200)}`); }
|
|
63
|
-
if (!res.ok) throw new Error(`userinfo HTTP ${res.status}: ${txt.slice(0, 200)}`);
|
|
64
|
-
const uid = String(j.id || j.userId || j.uid || "");
|
|
65
|
-
if (!uid) throw new Error(`userinfo 无 uid: ${txt.slice(0, 200)}`);
|
|
66
|
-
return {
|
|
67
|
-
uid,
|
|
68
|
-
name: String(j.name || ""),
|
|
69
|
-
email: String(j.email || ""),
|
|
70
|
-
userType: String(j.userType || j.user_type || "personal_standard"),
|
|
71
|
-
organizationId: String(j.organization_id || ""),
|
|
72
|
-
organizationName: String(j.organization_name || ""),
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// 轮询直到授权成功,返回 bundle;超时抛错。deps.log 便于测试注入。
|
|
77
|
-
export async function waitForAuth({ region, nonce, verifier, fetchImpl = compatFetch, log = console.log, deadline = Date.now() + POLL_TIMEOUT_MS } = {}) {
|
|
78
|
-
for (;;) {
|
|
79
|
-
if (Date.now() > deadline) throw new Error("授权超时(10 分钟),请重新运行 mslxdff -provider qoder login");
|
|
80
|
-
const bundle = await pollDeviceToken({ region, nonce, verifier, fetchImpl });
|
|
81
|
-
if (bundle) return bundle;
|
|
82
|
-
await new Promise((r) => setTimeout(r, POLL_MS));
|
|
83
|
-
try { process.stdout.write("."); } catch {}
|
|
84
|
-
}
|
|
1
|
+
// qoder OAuth 设备授权(转译 qoder2api account/oauth.go):
|
|
2
|
+
// 1. startLogin: PKCE(S256) + nonce → 返回授权链接
|
|
3
|
+
// 2. pollDeviceToken: 轮询 deviceToken/poll,404=未授权继续,200={token:dt-xxx, refresh_token:drt-xxx}
|
|
4
|
+
// 3. fetchUserInfo: GET /api/v1/userinfo(Bearer dt-xxx)→ uid/name/organization_id
|
|
5
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
6
|
+
import { compatFetch, timeoutSignal } from "../../compat.js";
|
|
7
|
+
import { OAUTH_CLIENT_ID, getEndpoints } from "./constants.js";
|
|
8
|
+
|
|
9
|
+
const POLL_MS = 3000;
|
|
10
|
+
export const POLL_TIMEOUT_MS = 10 * 60 * 1000; // 对齐 qoder2api 10 分钟
|
|
11
|
+
|
|
12
|
+
export function pkce() {
|
|
13
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
14
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
15
|
+
return { verifier, challenge };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function hex16() {
|
|
19
|
+
return randomBytes(16).toString("hex");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function buildLoginUrl({ region = "global", nonce, challenge } = {}) {
|
|
23
|
+
const ep = getEndpoints(region);
|
|
24
|
+
const params = new URLSearchParams({
|
|
25
|
+
nonce,
|
|
26
|
+
challenge,
|
|
27
|
+
challenge_method: "S256",
|
|
28
|
+
client_id: OAUTH_CLIENT_ID,
|
|
29
|
+
});
|
|
30
|
+
return `${ep.deviceLoginBase}?${params.toString()}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// 单次轮询:404/空 token → 未授权(返回 null);200 且有 token → bundle;5xx → 抛错。
|
|
34
|
+
export async function pollDeviceToken({ region = "global", nonce, verifier, fetchImpl = compatFetch } = {}) {
|
|
35
|
+
const ep = getEndpoints(region);
|
|
36
|
+
const url = `${ep.pollEndpoint}?nonce=${encodeURIComponent(nonce)}&verifier=${encodeURIComponent(verifier)}&challenge_method=S256`;
|
|
37
|
+
let res;
|
|
38
|
+
try {
|
|
39
|
+
res = await fetchImpl(url, { signal: timeoutSignal(20000) });
|
|
40
|
+
} catch (e) {
|
|
41
|
+
throw new Error(`轮询失败: ${e.message}`);
|
|
42
|
+
}
|
|
43
|
+
if (res.status === 404) return null; // 还没授权
|
|
44
|
+
if (res.status >= 500) throw new Error(`deviceToken 端点故障: HTTP ${res.status}`);
|
|
45
|
+
const txt = await res.text().catch(() => "");
|
|
46
|
+
let j;
|
|
47
|
+
try { j = JSON.parse(txt); } catch { throw new Error(`deviceToken 返回非 JSON: ${txt.slice(0, 200)}`); }
|
|
48
|
+
const deviceToken = String(j.token || "");
|
|
49
|
+
if (!deviceToken) return null;
|
|
50
|
+
return { deviceToken, refreshToken: String(j.refresh_token || "") };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// userinfo:ResolveOAuthUserID 优先 id/userId/uid(qoder2api bridge.go)。
|
|
54
|
+
export async function fetchUserInfo({ region = "global", deviceToken, fetchImpl = compatFetch } = {}) {
|
|
55
|
+
const ep = getEndpoints(region);
|
|
56
|
+
const res = await fetchImpl(ep.userinfoBase, {
|
|
57
|
+
headers: { Authorization: `Bearer ${deviceToken}` },
|
|
58
|
+
signal: timeoutSignal(20000),
|
|
59
|
+
});
|
|
60
|
+
const txt = await res.text().catch(() => "");
|
|
61
|
+
let j;
|
|
62
|
+
try { j = JSON.parse(txt); } catch { throw new Error(`userinfo 返回非 JSON: HTTP ${res.status} ${txt.slice(0, 200)}`); }
|
|
63
|
+
if (!res.ok) throw new Error(`userinfo HTTP ${res.status}: ${txt.slice(0, 200)}`);
|
|
64
|
+
const uid = String(j.id || j.userId || j.uid || "");
|
|
65
|
+
if (!uid) throw new Error(`userinfo 无 uid: ${txt.slice(0, 200)}`);
|
|
66
|
+
return {
|
|
67
|
+
uid,
|
|
68
|
+
name: String(j.name || ""),
|
|
69
|
+
email: String(j.email || ""),
|
|
70
|
+
userType: String(j.userType || j.user_type || "personal_standard"),
|
|
71
|
+
organizationId: String(j.organization_id || ""),
|
|
72
|
+
organizationName: String(j.organization_name || ""),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 轮询直到授权成功,返回 bundle;超时抛错。deps.log 便于测试注入。
|
|
77
|
+
export async function waitForAuth({ region, nonce, verifier, fetchImpl = compatFetch, log = console.log, deadline = Date.now() + POLL_TIMEOUT_MS } = {}) {
|
|
78
|
+
for (;;) {
|
|
79
|
+
if (Date.now() > deadline) throw new Error("授权超时(10 分钟),请重新运行 mslxdff -provider qoder login");
|
|
80
|
+
const bundle = await pollDeviceToken({ region, nonce, verifier, fetchImpl });
|
|
81
|
+
if (bundle) return bundle;
|
|
82
|
+
await new Promise((r) => setTimeout(r, POLL_MS));
|
|
83
|
+
try { process.stdout.write("."); } catch {}
|
|
84
|
+
}
|
|
85
85
|
}
|
|
@@ -1,162 +1,162 @@
|
|
|
1
|
-
// qoder 消息/payload 组装(转译 qoder2api bridge.go CallQoderWithOpts + messages.go)
|
|
2
|
-
// 模板:baseprompt.json(vendored 数据文件,含 {UUID1..5}/{TIME1} 占位符,加载时替换一次)
|
|
3
|
-
import { readFileSync } from "node:fs";
|
|
4
|
-
import { join, dirname } from "node:path";
|
|
5
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { newUUID, unixMs } from "./fingerprint.js";
|
|
7
|
-
|
|
8
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
9
|
-
|
|
10
|
-
// 模板单例:进程内加载一次(替换占位符后 JSON.parse),每请求深拷贝
|
|
11
|
-
let _template = null;
|
|
12
|
-
export function loadTemplate(templatePath) {
|
|
13
|
-
if (_template && !templatePath) return _template;
|
|
14
|
-
let tmpl = readFileSync(templatePath || join(__dirname, "baseprompt.json"), "utf8");
|
|
15
|
-
for (const k of ["{UUID1}", "{UUID2}", "{UUID3}", "{UUID4}", "{UUID5}"]) tmpl = tmpl.split(k).join(newUUID());
|
|
16
|
-
tmpl = tmpl.split("{TIME1}").join(String(unixMs()));
|
|
17
|
-
_template = JSON.parse(tmpl);
|
|
18
|
-
return _template;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function blankResponseMeta() {
|
|
22
|
-
return {
|
|
23
|
-
id: "",
|
|
24
|
-
usage: {
|
|
25
|
-
prompt_tokens: 0, completion_tokens: 0, total_tokens: 0,
|
|
26
|
-
completion_tokens_details: { reasoning_tokens: 0 },
|
|
27
|
-
prompt_tokens_details: { cached_tokens: 0 },
|
|
28
|
-
},
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// OpenAI user 消息 → Qoder contents 形状
|
|
33
|
-
export function buildUserMessage(text) {
|
|
34
|
-
return {
|
|
35
|
-
role: "user", content: "",
|
|
36
|
-
contents: [{ type: "text", text: String(text || "") }],
|
|
37
|
-
response_meta: blankResponseMeta(),
|
|
38
|
-
reasoning_content_signature: "",
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function buildStructuredMessage(role, text) {
|
|
43
|
-
return { role, content: String(text || ""), response_meta: blankResponseMeta(), reasoning_content_signature: "" };
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export function normalizeContent(content) {
|
|
47
|
-
if (typeof content === "string") return content;
|
|
48
|
-
if (content == null) return "";
|
|
49
|
-
if (Array.isArray(content)) {
|
|
50
|
-
let out = "";
|
|
51
|
-
for (const b of content) {
|
|
52
|
-
const t = typeof b === "object" && b ? b.text : b;
|
|
53
|
-
if (typeof t === "string") out += (out ? "\n\n" : "") + t;
|
|
54
|
-
}
|
|
55
|
-
return out;
|
|
56
|
-
}
|
|
57
|
-
return JSON.stringify(content);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// 提取最后一条 user 消息文本(仿 ExtractLatestUserPrompt)
|
|
61
|
-
export function extractLatestUserPrompt(messages) {
|
|
62
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
63
|
-
const m = messages[i];
|
|
64
|
-
if (m?.role === "user") return normalizeContent(m.content);
|
|
65
|
-
}
|
|
66
|
-
return "";
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// OpenAI messages → Qoder messages(仿 BuildQoderMessages:无 system 前置模板 system;
|
|
70
|
-
// user 含 tool_result 数组拆成 tool 行;assistant tool_calls 透传)
|
|
71
|
-
export function buildQoderMessages(template, incoming, toolsEnabled) {
|
|
72
|
-
const rebuilt = [];
|
|
73
|
-
const hasSystem = (incoming || []).some((m) => m?.role === "system");
|
|
74
|
-
if (!hasSystem && template) {
|
|
75
|
-
for (const m of template.messages || []) {
|
|
76
|
-
if (m?.role === "system") rebuilt.push(JSON.parse(JSON.stringify(m)));
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
for (const m of incoming || []) {
|
|
80
|
-
if (!m || typeof m !== "object") continue;
|
|
81
|
-
const text = normalizeContent(m.content);
|
|
82
|
-
if (m.role === "user") {
|
|
83
|
-
// tool_result 数组形态 → tool 行
|
|
84
|
-
if (Array.isArray(m.content) && m.content[0]?.type === "tool_result") {
|
|
85
|
-
for (const b of m.content) {
|
|
86
|
-
if (b?.type !== "tool_result") continue;
|
|
87
|
-
rebuilt.push({ role: "tool", tool_call_id: b.tool_use_id || "", content: normalizeContent(b.content) });
|
|
88
|
-
}
|
|
89
|
-
continue;
|
|
90
|
-
}
|
|
91
|
-
rebuilt.push(buildUserMessage(text));
|
|
92
|
-
} else if (m.role === "assistant" && toolsEnabled && Array.isArray(m.tool_calls) && m.tool_calls.length) {
|
|
93
|
-
const out = buildStructuredMessage("assistant", text);
|
|
94
|
-
out.tool_calls = m.tool_calls;
|
|
95
|
-
rebuilt.push(out);
|
|
96
|
-
} else if (m.role === "tool") {
|
|
97
|
-
const out = buildStructuredMessage("tool", text);
|
|
98
|
-
if (m.tool_call_id) out.tool_call_id = m.tool_call_id;
|
|
99
|
-
if (m.name) out.name = m.name;
|
|
100
|
-
rebuilt.push(out);
|
|
101
|
-
} else if (text) {
|
|
102
|
-
rebuilt.push(buildStructuredMessage(m.role === "system" ? "system" : m.role || "user", text));
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
return rebuilt;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// 组装上游请求体(仿 CallQoderWithOpts)
|
|
109
|
-
export function buildQoderBody({ template, userType, model, messages, tools, maxTokens, isReasoning }) {
|
|
110
|
-
const body = JSON.parse(JSON.stringify(template || loadTemplate()));
|
|
111
|
-
const nid = newUUID();
|
|
112
|
-
body.request_id = nid;
|
|
113
|
-
body.chat_record_id = nid;
|
|
114
|
-
body.request_set_id = newUUID();
|
|
115
|
-
body.session_id = newUUID();
|
|
116
|
-
body.stream = true;
|
|
117
|
-
body.aliyun_user_type = userType || "personal_standard";
|
|
118
|
-
if (body.model_config) {
|
|
119
|
-
body.model_config.key = model;
|
|
120
|
-
if (isReasoning) body.model_config.is_reasoning = true;
|
|
121
|
-
}
|
|
122
|
-
// 推理标志两处镜像写(对齐官方 CLI 请求形状),只写 model_config 上游不吐 reasoning_content
|
|
123
|
-
if (isReasoning && body.chat_context?.extra?.modelConfig) {
|
|
124
|
-
body.chat_context.extra.modelConfig.is_reasoning = true;
|
|
125
|
-
body.chat_context.extra.modelConfig.key = model; // 与 model_config.key 同步,不留模板 "auto"(评审路1 P1#5)
|
|
126
|
-
}
|
|
127
|
-
if (maxTokens > 0 && body.parameters) body.parameters.max_tokens = maxTokens;
|
|
128
|
-
const prompt = extractLatestUserPrompt(messages);
|
|
129
|
-
if (body.business) {
|
|
130
|
-
body.business.id = newUUID();
|
|
131
|
-
body.business.begin_at = unixMs();
|
|
132
|
-
body.business.name = prompt.length > 30 ? prompt.slice(0, 30) : prompt;
|
|
133
|
-
}
|
|
134
|
-
if (body.chat_context) {
|
|
135
|
-
if (body.chat_context.text) body.chat_context.text.text = prompt;
|
|
136
|
-
if (body.chat_context.extra?.originalContent) body.chat_context.extra.originalContent.text = prompt;
|
|
137
|
-
}
|
|
138
|
-
body.messages = messages;
|
|
139
|
-
// tools 空数组契约:模板内嵌的 14 个 Qoder CLI 工具永不出门;无工具时上游官方亦发 []
|
|
140
|
-
body.tools = Array.isArray(tools) && tools.length ? tools : [];
|
|
141
|
-
return { body, prompt, mcSource: body.model_config?.source || "system" };
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// 客户端模型名 → 上游 key(仿 defaultModelMapping 双向 substring,家族关键字兜底)
|
|
145
|
-
const DEFAULT_MAPPING = {
|
|
146
|
-
opus: "qmodel_38max", sonnet: "gmodel", haiku: "qfmodel",
|
|
147
|
-
gpt: "dmodel", gemini: "gmodel", glm: "gmodel", kimi: "kmodel", deepseek: "dmodel",
|
|
148
|
-
qwen: "qfmodel", flash: "qfmodel", mini: "efficient", pro: "performance", max: "performance",
|
|
149
|
-
};
|
|
150
|
-
// 上游原生 key 白名单(model/list 实测 15 个)——精确命中直接透传,防被家族关键字抢走
|
|
151
|
-
const UPSTREAM_KEYS = new Set(["auto", "ultimate", "performance", "efficient", "qmodel_38max", "qfmodel", "qmodel_latest", "qmodel", "kmodel_latest", "kmodel", "gmodel", "gfmodel", "dmodel", "dfmodel", "mmodel"]);
|
|
152
|
-
export function mapModel(model) {
|
|
153
|
-
const m = String(model || "").trim();
|
|
154
|
-
if (!m || m.toLowerCase() === "auto") return "qfmodel";
|
|
155
|
-
const low = m.toLowerCase();
|
|
156
|
-
if (UPSTREAM_KEYS.has(low)) return low;
|
|
157
|
-
if (DEFAULT_MAPPING[low]) return DEFAULT_MAPPING[low];
|
|
158
|
-
for (const [k, v] of Object.entries(DEFAULT_MAPPING)) {
|
|
159
|
-
if (low.includes(k) || k.includes(low)) return v;
|
|
160
|
-
}
|
|
161
|
-
return low;
|
|
162
|
-
}
|
|
1
|
+
// qoder 消息/payload 组装(转译 qoder2api bridge.go CallQoderWithOpts + messages.go)
|
|
2
|
+
// 模板:baseprompt.json(vendored 数据文件,含 {UUID1..5}/{TIME1} 占位符,加载时替换一次)
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { join, dirname } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { newUUID, unixMs } from "./fingerprint.js";
|
|
7
|
+
|
|
8
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
// 模板单例:进程内加载一次(替换占位符后 JSON.parse),每请求深拷贝
|
|
11
|
+
let _template = null;
|
|
12
|
+
export function loadTemplate(templatePath) {
|
|
13
|
+
if (_template && !templatePath) return _template;
|
|
14
|
+
let tmpl = readFileSync(templatePath || join(__dirname, "baseprompt.json"), "utf8");
|
|
15
|
+
for (const k of ["{UUID1}", "{UUID2}", "{UUID3}", "{UUID4}", "{UUID5}"]) tmpl = tmpl.split(k).join(newUUID());
|
|
16
|
+
tmpl = tmpl.split("{TIME1}").join(String(unixMs()));
|
|
17
|
+
_template = JSON.parse(tmpl);
|
|
18
|
+
return _template;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function blankResponseMeta() {
|
|
22
|
+
return {
|
|
23
|
+
id: "",
|
|
24
|
+
usage: {
|
|
25
|
+
prompt_tokens: 0, completion_tokens: 0, total_tokens: 0,
|
|
26
|
+
completion_tokens_details: { reasoning_tokens: 0 },
|
|
27
|
+
prompt_tokens_details: { cached_tokens: 0 },
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// OpenAI user 消息 → Qoder contents 形状
|
|
33
|
+
export function buildUserMessage(text) {
|
|
34
|
+
return {
|
|
35
|
+
role: "user", content: "",
|
|
36
|
+
contents: [{ type: "text", text: String(text || "") }],
|
|
37
|
+
response_meta: blankResponseMeta(),
|
|
38
|
+
reasoning_content_signature: "",
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function buildStructuredMessage(role, text) {
|
|
43
|
+
return { role, content: String(text || ""), response_meta: blankResponseMeta(), reasoning_content_signature: "" };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function normalizeContent(content) {
|
|
47
|
+
if (typeof content === "string") return content;
|
|
48
|
+
if (content == null) return "";
|
|
49
|
+
if (Array.isArray(content)) {
|
|
50
|
+
let out = "";
|
|
51
|
+
for (const b of content) {
|
|
52
|
+
const t = typeof b === "object" && b ? b.text : b;
|
|
53
|
+
if (typeof t === "string") out += (out ? "\n\n" : "") + t;
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
return JSON.stringify(content);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 提取最后一条 user 消息文本(仿 ExtractLatestUserPrompt)
|
|
61
|
+
export function extractLatestUserPrompt(messages) {
|
|
62
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
63
|
+
const m = messages[i];
|
|
64
|
+
if (m?.role === "user") return normalizeContent(m.content);
|
|
65
|
+
}
|
|
66
|
+
return "";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// OpenAI messages → Qoder messages(仿 BuildQoderMessages:无 system 前置模板 system;
|
|
70
|
+
// user 含 tool_result 数组拆成 tool 行;assistant tool_calls 透传)
|
|
71
|
+
export function buildQoderMessages(template, incoming, toolsEnabled) {
|
|
72
|
+
const rebuilt = [];
|
|
73
|
+
const hasSystem = (incoming || []).some((m) => m?.role === "system");
|
|
74
|
+
if (!hasSystem && template) {
|
|
75
|
+
for (const m of template.messages || []) {
|
|
76
|
+
if (m?.role === "system") rebuilt.push(JSON.parse(JSON.stringify(m)));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const m of incoming || []) {
|
|
80
|
+
if (!m || typeof m !== "object") continue;
|
|
81
|
+
const text = normalizeContent(m.content);
|
|
82
|
+
if (m.role === "user") {
|
|
83
|
+
// tool_result 数组形态 → tool 行
|
|
84
|
+
if (Array.isArray(m.content) && m.content[0]?.type === "tool_result") {
|
|
85
|
+
for (const b of m.content) {
|
|
86
|
+
if (b?.type !== "tool_result") continue;
|
|
87
|
+
rebuilt.push({ role: "tool", tool_call_id: b.tool_use_id || "", content: normalizeContent(b.content) });
|
|
88
|
+
}
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
rebuilt.push(buildUserMessage(text));
|
|
92
|
+
} else if (m.role === "assistant" && toolsEnabled && Array.isArray(m.tool_calls) && m.tool_calls.length) {
|
|
93
|
+
const out = buildStructuredMessage("assistant", text);
|
|
94
|
+
out.tool_calls = m.tool_calls;
|
|
95
|
+
rebuilt.push(out);
|
|
96
|
+
} else if (m.role === "tool") {
|
|
97
|
+
const out = buildStructuredMessage("tool", text);
|
|
98
|
+
if (m.tool_call_id) out.tool_call_id = m.tool_call_id;
|
|
99
|
+
if (m.name) out.name = m.name;
|
|
100
|
+
rebuilt.push(out);
|
|
101
|
+
} else if (text) {
|
|
102
|
+
rebuilt.push(buildStructuredMessage(m.role === "system" ? "system" : m.role || "user", text));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return rebuilt;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 组装上游请求体(仿 CallQoderWithOpts)
|
|
109
|
+
export function buildQoderBody({ template, userType, model, messages, tools, maxTokens, isReasoning }) {
|
|
110
|
+
const body = JSON.parse(JSON.stringify(template || loadTemplate()));
|
|
111
|
+
const nid = newUUID();
|
|
112
|
+
body.request_id = nid;
|
|
113
|
+
body.chat_record_id = nid;
|
|
114
|
+
body.request_set_id = newUUID();
|
|
115
|
+
body.session_id = newUUID();
|
|
116
|
+
body.stream = true;
|
|
117
|
+
body.aliyun_user_type = userType || "personal_standard";
|
|
118
|
+
if (body.model_config) {
|
|
119
|
+
body.model_config.key = model;
|
|
120
|
+
if (isReasoning) body.model_config.is_reasoning = true;
|
|
121
|
+
}
|
|
122
|
+
// 推理标志两处镜像写(对齐官方 CLI 请求形状),只写 model_config 上游不吐 reasoning_content
|
|
123
|
+
if (isReasoning && body.chat_context?.extra?.modelConfig) {
|
|
124
|
+
body.chat_context.extra.modelConfig.is_reasoning = true;
|
|
125
|
+
body.chat_context.extra.modelConfig.key = model; // 与 model_config.key 同步,不留模板 "auto"(评审路1 P1#5)
|
|
126
|
+
}
|
|
127
|
+
if (maxTokens > 0 && body.parameters) body.parameters.max_tokens = maxTokens;
|
|
128
|
+
const prompt = extractLatestUserPrompt(messages);
|
|
129
|
+
if (body.business) {
|
|
130
|
+
body.business.id = newUUID();
|
|
131
|
+
body.business.begin_at = unixMs();
|
|
132
|
+
body.business.name = prompt.length > 30 ? prompt.slice(0, 30) : prompt;
|
|
133
|
+
}
|
|
134
|
+
if (body.chat_context) {
|
|
135
|
+
if (body.chat_context.text) body.chat_context.text.text = prompt;
|
|
136
|
+
if (body.chat_context.extra?.originalContent) body.chat_context.extra.originalContent.text = prompt;
|
|
137
|
+
}
|
|
138
|
+
body.messages = messages;
|
|
139
|
+
// tools 空数组契约:模板内嵌的 14 个 Qoder CLI 工具永不出门;无工具时上游官方亦发 []
|
|
140
|
+
body.tools = Array.isArray(tools) && tools.length ? tools : [];
|
|
141
|
+
return { body, prompt, mcSource: body.model_config?.source || "system" };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// 客户端模型名 → 上游 key(仿 defaultModelMapping 双向 substring,家族关键字兜底)
|
|
145
|
+
const DEFAULT_MAPPING = {
|
|
146
|
+
opus: "qmodel_38max", sonnet: "gmodel", haiku: "qfmodel",
|
|
147
|
+
gpt: "dmodel", gemini: "gmodel", glm: "gmodel", kimi: "kmodel", deepseek: "dmodel",
|
|
148
|
+
qwen: "qfmodel", flash: "qfmodel", mini: "efficient", pro: "performance", max: "performance",
|
|
149
|
+
};
|
|
150
|
+
// 上游原生 key 白名单(model/list 实测 15 个)——精确命中直接透传,防被家族关键字抢走
|
|
151
|
+
const UPSTREAM_KEYS = new Set(["auto", "ultimate", "performance", "efficient", "qmodel_38max", "qfmodel", "qmodel_latest", "qmodel", "kmodel_latest", "kmodel", "gmodel", "gfmodel", "dmodel", "dfmodel", "mmodel"]);
|
|
152
|
+
export function mapModel(model) {
|
|
153
|
+
const m = String(model || "").trim();
|
|
154
|
+
if (!m || m.toLowerCase() === "auto") return "qfmodel";
|
|
155
|
+
const low = m.toLowerCase();
|
|
156
|
+
if (UPSTREAM_KEYS.has(low)) return low;
|
|
157
|
+
if (DEFAULT_MAPPING[low]) return DEFAULT_MAPPING[low];
|
|
158
|
+
for (const [k, v] of Object.entries(DEFAULT_MAPPING)) {
|
|
159
|
+
if (low.includes(k) || k.includes(low)) return v;
|
|
160
|
+
}
|
|
161
|
+
return low;
|
|
162
|
+
}
|