mslxdff 0.1.136 → 0.1.140
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/chat/gateway.js +1 -1
- package/src/chat/prompt.js +1 -1
- package/src/chat/terminal.js +1 -1
- package/src/chooser.js +31 -12
- package/src/cli/commands/model/list-live.js +22 -0
- package/src/cli/commands/model/list-providers.js +1 -1
- package/src/cli/commands/model/list-render.js +2 -2
- package/src/cli/commands/model/list.js +2 -0
- package/src/cli/commands/model/live-models.js +24 -0
- package/src/cli/commands/provider/add.js +2 -1
- package/src/cli/commands/provider/bench-via.js +1 -1
- package/src/cli/commands/provider/cline-free.js +94 -0
- package/src/cli/commands/provider/cline-login.js +20 -15
- package/src/cli/commands/provider/codearts-login.js +45 -0
- package/src/cli/commands/provider/index.js +34 -0
- package/src/cli/commands/provider/keys.js +13 -2
- package/src/cli/commands/provider/models.js +13 -1
- package/src/cli/commands/provider/qoder-checkin.js +81 -0
- package/src/cli/commands/provider/qoder-login.js +103 -0
- package/src/cli/commands/provider/traework-login.js +202 -0
- package/src/cli/commands/provider/workbuddy-login.js +1 -1
- package/src/cli/commands/workbuddy.js +14 -21
- package/src/cli/index.js +3 -0
- package/src/cli/interactive.js +41 -4
- package/src/cli/provider-row.js +1 -1
- package/src/compat.js +23 -5
- package/src/model-capabilities/merge.js +2 -2
- package/src/providers/classify.js +1 -1
- package/src/providers/cline/auth.js +1 -1
- package/src/providers/cline/chat.js +14 -11
- package/src/providers/cline/free-catalog.js +71 -0
- package/src/providers/cline/index.js +2 -16
- package/src/providers/cline/models.js +28 -51
- package/src/providers/codearts/auth-pool.js +148 -0
- package/src/providers/codearts/chat.js +176 -0
- package/src/providers/codearts/const.js +60 -0
- package/src/providers/codearts/dpop.js +95 -0
- package/src/providers/codearts/index.js +160 -0
- package/src/providers/codearts/login.js +214 -0
- package/src/providers/codearts/models.js +182 -0
- package/src/providers/codearts/sign.js +96 -0
- package/src/providers/codearts/sse.js +204 -0
- package/src/providers/codearts/stream.js +209 -0
- package/src/providers/codearts/sts.js +124 -0
- package/src/providers/codearts.js +1 -0
- package/src/providers/model-id.js +4 -4
- package/src/providers/qoder/account-store.js +107 -0
- package/src/providers/qoder/aggregate.js +51 -0
- package/src/providers/qoder/baseprompt.json +592 -0
- package/src/providers/qoder/chat.js +72 -0
- package/src/providers/qoder/checkin.js +160 -0
- package/src/providers/qoder/constants.js +45 -0
- package/src/providers/qoder/encode.js +42 -0
- package/src/providers/qoder/fingerprint.js +39 -0
- package/src/providers/qoder/index.js +106 -0
- package/src/providers/qoder/models.js +62 -0
- package/src/providers/qoder/oauth.js +85 -0
- package/src/providers/qoder/payload.js +156 -0
- package/src/providers/qoder/request.js +26 -0
- package/src/providers/qoder/session.js +135 -0
- package/src/providers/qoder/sse.js +46 -0
- package/src/providers/qoder/stream.js +81 -0
- package/src/providers/qoder.js +2 -0
- package/src/providers/registry.js +16 -1
- package/src/providers/share-keys.js +7 -2
- package/src/providers/traework/account-store.js +149 -0
- package/src/providers/traework/chat.js +211 -0
- package/src/providers/traework/checkin.js +35 -0
- package/src/providers/traework/constants.js +21 -0
- package/src/providers/traework/errors.js +52 -0
- package/src/providers/traework/headers.js +47 -0
- package/src/providers/traework/index.js +122 -0
- package/src/providers/traework/models.js +97 -0
- package/src/providers/traework/payload.js +86 -0
- package/src/providers/traework/sse.js +184 -0
- package/src/providers/traework/token.js +52 -0
- package/src/providers/traework.js +2 -0
- package/src/providers/workbuddy/account-store.js +73 -7
- package/src/providers/workbuddy/chat.js +1 -1
- package/src/providers/workbuddy/index.js +10 -20
- package/src/readline-compat.js +9 -10
- package/src/routes/models-route.js +19 -1
- package/src/runtime/bootstrap.js +10 -0
- package/src/runtime/provider-gate.js +30 -0
- package/src/runtime/providers-setup.js +18 -3
- package/src/runtime/qoder-checkin.js +93 -0
- package/src/runtime/server-lifecycle.js +2 -2
- package/src/runtime/traework-checkin.js +104 -0
- package/src/state/migrations/cline-unify.js +94 -0
- package/src/state/migrations.js +33 -0
- package/src/state/schemas/token.js +6 -2
- package/src/state/schemas/use-group.js +4 -4
- package/src/sync-workbuddy.js +1 -1
- package/src/upstream-engine/index.js +1 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// DPoP(RFC 9449)证明 JWT:ES256 + P-256,供 STS /v1/oauth2/tokens 请求头使用。
|
|
2
|
+
// refresh_token 与首次换取时的 DPoP 公钥绑定:私钥 JWK 必须随凭证持久化(d 字段),
|
|
3
|
+
// 换新私钥刷新会被 STS 拒(400 invalid refresh token: InvalidDPoPHeader)。
|
|
4
|
+
// 算法对齐 HITZY2002/codearts2api internal/upstream/dpop.go。
|
|
5
|
+
import crypto from "node:crypto";
|
|
6
|
+
|
|
7
|
+
// P-256 阶 n(用于低 S 归一化:s > n/2 → s = n - s,jose 默认低 S 兼容性更好)。
|
|
8
|
+
const P256_N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
|
|
9
|
+
|
|
10
|
+
const b64url = (data) => Buffer.from(data).toString("base64url");
|
|
11
|
+
|
|
12
|
+
/** 生成可持久化的 DPoP 私钥 JWK(kty/crv/x/y/d,均 base64url 无 padding)。 */
|
|
13
|
+
export function newDpopPrivateJwk() {
|
|
14
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" });
|
|
15
|
+
const pub = publicKey.export({ format: "jwk" });
|
|
16
|
+
const priv = privateKey.export({ format: "jwk" });
|
|
17
|
+
return { kty: "EC", crv: "P-256", x: pub.x, y: pub.y, d: priv.d };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function dpopPublicJwk(privateJwk) {
|
|
21
|
+
return { kty: "EC", crv: "P-256", x: privateJwk?.x || "", y: privateJwk?.y || "" };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isValidDpopJwk(jwk) {
|
|
25
|
+
return !!jwk && jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.d === "string" && jwk.d.length > 0 && !!jwk.x && !!jwk.y;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 从持久化 JWK 恢复私钥对象(非法材料直接抛错,调用方须提示重新登录)。 */
|
|
29
|
+
export function dpopPrivateKey(jwk) {
|
|
30
|
+
if (!isValidDpopJwk(jwk)) throw new Error("codearts: invalid DPoP private JWK — re-login required");
|
|
31
|
+
try {
|
|
32
|
+
return crypto.createPrivateKey({ key: { ...jwk }, format: "jwk" });
|
|
33
|
+
} catch (err) {
|
|
34
|
+
throw new Error(`codearts: DPoP private JWK unusable (${err?.message || err}) — re-login required`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 低 S 归一化:ieee-p1363 64 字节 r||s 原地修正 s(合法:ECDSA (r, n-s) 等价)。 */
|
|
39
|
+
function normalizeLowS(sig) {
|
|
40
|
+
if (sig.length !== 64) return sig;
|
|
41
|
+
const s = BigInt("0x" + sig.subarray(32, 64).toString("hex"));
|
|
42
|
+
const half = P256_N >> 1n;
|
|
43
|
+
if (s <= half || s === 0n) return sig;
|
|
44
|
+
const fixed = P256_N - s;
|
|
45
|
+
Buffer.from(fixed.toString(16).padStart(64, "0"), "hex").copy(sig, 32);
|
|
46
|
+
return sig;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 生成 DPoP proof JWT。
|
|
51
|
+
* @param {object} privateJwk 持久化私钥 JWK(含 d)
|
|
52
|
+
* @param {string} htu 目标端点完整 URL(STS token 端点)
|
|
53
|
+
* @returns {string} `b64(header).b64(payload).b64(sig)` 三段 JWT
|
|
54
|
+
*/
|
|
55
|
+
export function signDpopProof(privateJwk, htu) {
|
|
56
|
+
const key = dpopPrivateKey(privateJwk);
|
|
57
|
+
const header = { alg: "ES256", typ: "dpop+jwt", jwk: dpopPublicJwk(privateJwk) };
|
|
58
|
+
const payload = {
|
|
59
|
+
htm: "POST",
|
|
60
|
+
htu: String(htu || ""),
|
|
61
|
+
iat: Math.floor(Date.now() / 1000),
|
|
62
|
+
jti: crypto.randomBytes(32).toString("hex"),
|
|
63
|
+
};
|
|
64
|
+
const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
|
|
65
|
+
// 标准 JWS/ES256:对 ASCII(input) 做 SHA256+ECDSA(crypto.sign("SHA256", input))。
|
|
66
|
+
// 注意:千万别用 sign(null, sha256(input))——OpenSSL 的 noneWithECDSA 把 digest 当整数标量,
|
|
67
|
+
// 签出来自验能过、但任何标准验签方(含 WebCrypto/华为 STS)都拒签(真机 400 STS5.1804 实锤)。
|
|
68
|
+
const sig = normalizeLowS(crypto.sign("SHA256", Buffer.from(input, "utf8"), { key, dsaEncoding: "ieee-p1363" }));
|
|
69
|
+
return `${input}.${b64url(sig)}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 验签辅助(测试/诊断用):校验 JWT 签名是否与 JWK 公钥匹配。 */
|
|
73
|
+
export function verifyDpopProof(proof) {
|
|
74
|
+
const parts = String(proof || "").split(".");
|
|
75
|
+
if (parts.length !== 3) return { ok: false };
|
|
76
|
+
try {
|
|
77
|
+
const header = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
|
|
78
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
79
|
+
const sig = Buffer.from(parts[2], "base64url");
|
|
80
|
+
const pub = crypto.createPublicKey({ key: { kty: "EC", crv: "P-256", x: header.jwk.x, y: header.jwk.y }, format: "jwk" });
|
|
81
|
+
const input = Buffer.from(`${parts[0]}.${parts[1]}`, "utf8");
|
|
82
|
+
const s = BigInt("0x" + sig.subarray(32, 64).toString("hex"));
|
|
83
|
+
// 标准 JWS/ES256 验签(与签名端对称;dsaEncoding 必须显式 ieee-p1363,node 默认 DER)。
|
|
84
|
+
const vopts = { dsaEncoding: "ieee-p1363" };
|
|
85
|
+
const ok = crypto.verify("SHA256", input, { key: pub, ...vopts }, sig)
|
|
86
|
+
|| (s > P256_N >> 1n && crypto.verify("SHA256", input, { key: pub, ...vopts }, (() => {
|
|
87
|
+
const alt = Buffer.from(sig);
|
|
88
|
+
Buffer.from((P256_N - s).toString(16).padStart(64, "0"), "hex").copy(alt, 32);
|
|
89
|
+
return alt;
|
|
90
|
+
})()));
|
|
91
|
+
return { ok, header, payload };
|
|
92
|
+
} catch {
|
|
93
|
+
return { ok: false };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// codearts 供应商工厂:注册表入口(registry.js → createCodeartsProvider)。
|
|
2
|
+
// key = 凭证 blob(JSON 字符串,一华为账号一条,见 auth-pool.js);多账号 keyring 自动轮转。
|
|
3
|
+
import { createKeyRing } from "../keyring.js";
|
|
4
|
+
import { loadProviderKeys, loadProviderBaseUrl, saveProviderConfig } from "../../state.js";
|
|
5
|
+
import { getUndici, createAgent, envInt, collectApiKeysGeneric } from "../base.js";
|
|
6
|
+
import { compatFetch } from "../../compat.js";
|
|
7
|
+
import { logDir } from "../../logs.js";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { SNAP_BASE, MODELS_CACHE_TTL_MS } from "./const.js";
|
|
10
|
+
import { createAuthPool } from "./auth-pool.js";
|
|
11
|
+
import { createCatalog, discoverAccountModels } from "./models.js";
|
|
12
|
+
import { createChatService } from "./chat.js";
|
|
13
|
+
|
|
14
|
+
const { UndiciFetch } = getUndici();
|
|
15
|
+
|
|
16
|
+
function resolveBaseUrl(baseUrl) {
|
|
17
|
+
if (baseUrl) return String(baseUrl).trim().replace(/\/+$/, "");
|
|
18
|
+
const env = loadProviderBaseUrl("codearts");
|
|
19
|
+
return env || SNAP_BASE;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createCodeartsProvider({
|
|
23
|
+
id = "codearts",
|
|
24
|
+
baseUrl,
|
|
25
|
+
apiKeys,
|
|
26
|
+
apiKey,
|
|
27
|
+
chatPath,
|
|
28
|
+
stsHost,
|
|
29
|
+
benefitHost,
|
|
30
|
+
snapBase,
|
|
31
|
+
connectTimeoutMs = envInt("MSLXDFF_CODEARTS_TIMEOUT_MS", 30_000),
|
|
32
|
+
cooldownMs = envInt("MSLXDFF_CODEARTS_COOLDOWN_MS", 30_000),
|
|
33
|
+
autoClaim = process.env.MSLXDFF_CODEARTS_AUTO_CLAIM !== "0",
|
|
34
|
+
fetchImpl,
|
|
35
|
+
file,
|
|
36
|
+
clock = Date.now,
|
|
37
|
+
} = {}) {
|
|
38
|
+
if (id !== "codearts") throw new Error(`codearts provider id mismatch: ${id}`);
|
|
39
|
+
const resolvedBase = snapBase || resolveBaseUrl(baseUrl);
|
|
40
|
+
if (!fetchImpl) fetchImpl = UndiciFetch || compatFetch;
|
|
41
|
+
const chatSvcBase = resolvedBase;
|
|
42
|
+
|
|
43
|
+
const rawKeys = collectApiKeysGeneric(id, apiKeys, apiKey, (pid) => loadProviderKeys(pid, file ? { file } : {}));
|
|
44
|
+
const allKeys = [...new Set(rawKeys.map((k) => String(k).trim()).filter(Boolean))];
|
|
45
|
+
const ring = createKeyRing(allKeys, { cooldownMs });
|
|
46
|
+
|
|
47
|
+
// 刷新轮转写回:原位替换 providerConfigs.codearts.keys 里的旧 blob + ring/pool 重排
|
|
48
|
+
const saveFn = async ({ oldBlob, newBlob }) => {
|
|
49
|
+
try {
|
|
50
|
+
const cur = loadProviderKeys(id, file ? { file } : {});
|
|
51
|
+
const idx = cur.indexOf(oldBlob);
|
|
52
|
+
if (idx < 0) return;
|
|
53
|
+
const next = [...cur];
|
|
54
|
+
next[idx] = newBlob;
|
|
55
|
+
saveProviderConfig(id, { baseUrl: loadProviderBaseUrl(id, file ? { file } : {}) || resolvedBase, keys: next }, file ? { file } : {});
|
|
56
|
+
ring.replace(oldBlob, newBlob);
|
|
57
|
+
pool.replace(oldBlob, newBlob);
|
|
58
|
+
} catch {}
|
|
59
|
+
};
|
|
60
|
+
const pool = createAuthPool({ keys: allKeys, fetchImpl, stsHost, clock, saveFn });
|
|
61
|
+
const catalog = createCatalog();
|
|
62
|
+
|
|
63
|
+
let agent = null; let dispatcher = null;
|
|
64
|
+
try {
|
|
65
|
+
const a = createAgent({
|
|
66
|
+
keepAliveTimeout: envInt("MSLXDFF_CODEARTS_KEEPALIVE_TIMEOUT", 30_000),
|
|
67
|
+
keepAliveMaxTimeout: envInt("MSLXDFF_CODEARTS_KEEPALIVE_MAX_TIMEOUT", 60_000),
|
|
68
|
+
connections: envInt("MSLXDFF_CODEARTS_KEEPALIVE_CONNECTIONS", 20),
|
|
69
|
+
});
|
|
70
|
+
agent = a.agent;
|
|
71
|
+
dispatcher = a.dispatcher;
|
|
72
|
+
} catch {}
|
|
73
|
+
|
|
74
|
+
const chatSvc = createChatService({
|
|
75
|
+
id, baseUrl: chatSvcBase, chatPath, fetchImpl, dispatcher, authPool: pool, catalog, connectTimeoutMs, clock,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
async function chat(body, opts = {}) {
|
|
79
|
+
if (!ring.size) throw new Error("codearts: missing credential — run: mslxdff -provider codearts login");
|
|
80
|
+
return chatSvc.runChat(body, ring, opts);
|
|
81
|
+
}
|
|
82
|
+
async function chatWithKeys(body, keys, opts = {}) {
|
|
83
|
+
const blobs = (keys || []).filter((k) => typeof k === "string" && k.trim().startsWith("{"));
|
|
84
|
+
if (!blobs.length) throw new Error("codearts: shared keys are not valid credential blobs");
|
|
85
|
+
const tmpRing = createKeyRing(blobs, { cooldownMs });
|
|
86
|
+
const tmpPool = createAuthPool({ keys: blobs, fetchImpl, stsHost, clock }); // 借用凭据不写回本节点
|
|
87
|
+
const tmpSvc = createChatService({ id, baseUrl: chatSvcBase, chatPath, fetchImpl, dispatcher: null, authPool: tmpPool, catalog, connectTimeoutMs, clock });
|
|
88
|
+
return tmpSvc.runChat(body, tmpRing, opts);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 三路发现(主账号);结果写目录(benefit 判定按账号隔离)
|
|
92
|
+
let discovering = null;
|
|
93
|
+
async function discover(force = false) {
|
|
94
|
+
const primary = pool.pickPrimary();
|
|
95
|
+
if (!primary) throw new Error("codearts: no alive account — run: mslxdff -provider codearts login");
|
|
96
|
+
if (!force && !catalog.isStale(primary.userId, clock())) return catalog.accountModels(primary.userId);
|
|
97
|
+
if (discovering) return discovering;
|
|
98
|
+
discovering = (async () => {
|
|
99
|
+
try {
|
|
100
|
+
const account = await pool.getCredential(primary.blob);
|
|
101
|
+
const { models, builtinOk, benefitOk } = await discoverAccountModels({ account, snapBase: resolvedBase, benefitHost, autoClaim, fetchImpl });
|
|
102
|
+
catalog.setAccount(account.userId, models, { keepBenefit: builtinOk && !benefitOk, now: clock() });
|
|
103
|
+
return models;
|
|
104
|
+
} finally {
|
|
105
|
+
discovering = null;
|
|
106
|
+
}
|
|
107
|
+
})();
|
|
108
|
+
return discovering;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let modelsCache = { at: 0, list: [] };
|
|
112
|
+
async function listModels() {
|
|
113
|
+
if (clock() - modelsCache.at < MODELS_CACHE_TTL_MS && modelsCache.list.length) return modelsCache.list;
|
|
114
|
+
let models;
|
|
115
|
+
try {
|
|
116
|
+
models = await discover();
|
|
117
|
+
} catch {
|
|
118
|
+
models = catalog.accountModels(pool.pickPrimary()?.userId || "");
|
|
119
|
+
}
|
|
120
|
+
if (!models.length) return [];
|
|
121
|
+
const list = models.map((m) => ({
|
|
122
|
+
id: `codearts/${m.id}`,
|
|
123
|
+
object: "model",
|
|
124
|
+
name: m.name || m.id,
|
|
125
|
+
...(m.contextWindow ? { maxInputTokens: m.contextWindow } : {}),
|
|
126
|
+
...(m.maxTokens ? { maxOutputTokens: m.maxTokens } : {}),
|
|
127
|
+
...(m.benefit ? { tags: ["free:benefit"] } : {}),
|
|
128
|
+
}));
|
|
129
|
+
modelsCache = { at: clock(), list };
|
|
130
|
+
return list;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function preheat() {
|
|
134
|
+
if (!ring.size) return { ok: false, skipped: true };
|
|
135
|
+
try {
|
|
136
|
+
await discover();
|
|
137
|
+
return { ok: true };
|
|
138
|
+
} catch (err) {
|
|
139
|
+
return { ok: false, error: String(err?.message || err).slice(0, 120) };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function close() { if (agent?.close) try { await agent.close(); } catch {} }
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
id,
|
|
148
|
+
chat,
|
|
149
|
+
chatWithKeys,
|
|
150
|
+
listModels,
|
|
151
|
+
preheat,
|
|
152
|
+
close,
|
|
153
|
+
agent,
|
|
154
|
+
keyRing: ring,
|
|
155
|
+
baseUrl: resolvedBase,
|
|
156
|
+
_pool: pool,
|
|
157
|
+
_catalog: catalog,
|
|
158
|
+
_snapshotPath: join(logDir(), "codearts-models.json"),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// codearts 浏览器登录:OAuth2 PKCE + DPoP,双通道取凭证:
|
|
2
|
+
// 1) 本地回调 server(portal 307 → ?secret=... → ?code=...)→ 授权码换 token
|
|
3
|
+
// 2) ticket 轮询(无浏览器机器:任意设备打开链接后,凭 ticket_id+secret 轮询下发)
|
|
4
|
+
// 凭证落盘 providerConfigs.codearts.keys(blob,见 auth-pool.js),并默认放行模型目录。
|
|
5
|
+
import crypto from "node:crypto";
|
|
6
|
+
import http from "node:http";
|
|
7
|
+
import { SNAP_BASE, STS_HOST, PORTAL_HOST, SNAP_MANAGER_PATH, EP_LOGIN_TICKET, CLIENT_ID, PLUGIN_NAME, PLUGIN_VERSION } from "./const.js";
|
|
8
|
+
import { exchangeAuthorizationCode, normalizeTokenResponse } from "./sts.js";
|
|
9
|
+
import { newDpopPrivateJwk } from "./dpop.js";
|
|
10
|
+
import { signRequest } from "./sign.js";
|
|
11
|
+
import { compatFetch } from "../../compat.js";
|
|
12
|
+
|
|
13
|
+
const hex = (n) => crypto.randomBytes(n).toString("hex");
|
|
14
|
+
const b64url = (b) => Buffer.from(b).toString("base64url");
|
|
15
|
+
|
|
16
|
+
export function buildLoginState({ clientId = CLIENT_ID } = {}) {
|
|
17
|
+
const verifier = b64url(crypto.randomBytes(64));
|
|
18
|
+
const challenge = b64url(crypto.createHash("sha256").update(verifier, "utf8").digest());
|
|
19
|
+
return { clientId, ticketId: hex(16), secret: hex(16), codeVerifier: verifier, codeChallenge: challenge, dpopJwk: newDpopPrivateJwk() };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function buildAuthorizeUrl({ state, port }) {
|
|
23
|
+
const q = new URLSearchParams({
|
|
24
|
+
theme: "2",
|
|
25
|
+
locale: "zh-cn",
|
|
26
|
+
uri_scheme: state.clientId,
|
|
27
|
+
client_id: state.clientId,
|
|
28
|
+
port: String(port ?? ""),
|
|
29
|
+
code_challenge: state.codeChallenge,
|
|
30
|
+
code_challenge_method: "SHA-256",
|
|
31
|
+
ticket_id: state.ticketId,
|
|
32
|
+
"plugin-name": PLUGIN_NAME,
|
|
33
|
+
"plugin-version": PLUGIN_VERSION,
|
|
34
|
+
});
|
|
35
|
+
return `${PORTAL_HOST}/authorize?${q.toString()}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function startCallbackServer() {
|
|
39
|
+
return new Promise((resolve, reject) => {
|
|
40
|
+
const hits = [];
|
|
41
|
+
const waiters = new Set();
|
|
42
|
+
const srv = http.createServer((req, res) => {
|
|
43
|
+
const u = new URL(req.url, "http://127.0.0.1");
|
|
44
|
+
const hit = Object.fromEntries(u.searchParams.entries());
|
|
45
|
+
hits.push(hit);
|
|
46
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
47
|
+
res.end("<html><body><h3>CodeArts 登录回调已收到</h3>可关闭此页面,回到 mslxdff 终端查看结果。</body></html>");
|
|
48
|
+
for (const w of waiters) w(hit);
|
|
49
|
+
waiters.clear();
|
|
50
|
+
});
|
|
51
|
+
srv.on("error", reject);
|
|
52
|
+
srv.listen(0, "127.0.0.1", () => resolve({
|
|
53
|
+
port: srv.address().port,
|
|
54
|
+
nextHit: (timeoutMs) => new Promise((r) => {
|
|
55
|
+
if (hits.length) return r(hits.shift());
|
|
56
|
+
const t = setTimeout(() => { waiters.delete(w); r(null); }, timeoutMs);
|
|
57
|
+
const w = (hit) => { clearTimeout(t); r(hit); };
|
|
58
|
+
waiters.add(w);
|
|
59
|
+
}),
|
|
60
|
+
close: () => { try { srv.close(); } catch {} },
|
|
61
|
+
}));
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 兜底通道:无浏览器机器上,任意设备完成授权后凭 ticket_id+secret 轮询拿凭证。
|
|
66
|
+
export async function pollTicket({ state, snapBase = SNAP_BASE, fetchImpl, timeoutMs = 5 * 60_000, intervalMs = 2000, log = () => {}, signal } = {}) {
|
|
67
|
+
const doFetch = fetchImpl || compatFetch;
|
|
68
|
+
const url = `${snapBase}${SNAP_MANAGER_PATH}${EP_LOGIN_TICKET}?ticket_id=${encodeURIComponent(state.ticketId)}&secret=${encodeURIComponent(state.secret)}`;
|
|
69
|
+
const deadline = Date.now() + timeoutMs;
|
|
70
|
+
while (Date.now() < deadline && !signal?.aborted) {
|
|
71
|
+
try {
|
|
72
|
+
const res = await doFetch(url, { headers: { "plugin-name": PLUGIN_NAME, "plugin-version": PLUGIN_VERSION } });
|
|
73
|
+
const raw = await res.text().catch(() => "");
|
|
74
|
+
if (res.ok) {
|
|
75
|
+
const account = normalizeTokenResponse(JSON.parse(raw));
|
|
76
|
+
if (account) return account;
|
|
77
|
+
}
|
|
78
|
+
} catch { /* 未下发/网络抖动:继续轮询 */ }
|
|
79
|
+
await new Promise((r) => {
|
|
80
|
+
const t = setTimeout(r, intervalMs);
|
|
81
|
+
signal?.addEventListener("abort", () => { clearTimeout(t); r(); }, { once: true });
|
|
82
|
+
});
|
|
83
|
+
log(`等待授权下发…(ticket 轮询中,剩余 ${Math.max(0, Math.round((deadline - Date.now()) / 1000))}s)`);
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 身份回填:生产 exchange 响应 user_id 常为空(portal 只回 code),空身份会让
|
|
90
|
+
* 登录去重把不同账号当同一账号替换。对齐 codearts2api lookupIdentity(先 STS
|
|
91
|
+
* caller-identity,再 snap current/user,最后 refresh_token JWT sub 兜底)。
|
|
92
|
+
* @returns {{userId, userName, domainId}|null}
|
|
93
|
+
*/
|
|
94
|
+
export async function lookupIdentity({ account, stsHost = STS_HOST, snapBase = SNAP_BASE, fetchImpl, log = () => {} } = {}) {
|
|
95
|
+
const doFetch = fetchImpl || compatFetch;
|
|
96
|
+
const cred = { accessKeyId: account?.accessKeyId, secretAccessKey: account?.secretAccessKey, securityToken: account?.securityToken };
|
|
97
|
+
async function signedGet(url) {
|
|
98
|
+
const { headers } = signRequest({ method: "GET", url, headers: { "content-type": "application/json", "x-language": "zh-cn" }, body: "", cred });
|
|
99
|
+
const res = await doFetch(url, { method: "GET", headers });
|
|
100
|
+
const raw = await res.text().catch(() => "");
|
|
101
|
+
if (res.status >= 400) throw new Error(`identity http ${res.status}: ${String(raw).slice(0, 120)}`);
|
|
102
|
+
return JSON.parse(raw);
|
|
103
|
+
}
|
|
104
|
+
// 1) STS caller-identity:{account_id, principal_id, principal_urn}(name 取 urn ":user:" 尾段)
|
|
105
|
+
try {
|
|
106
|
+
const j = await signedGet(`${stsHost}/v5/caller-identity`);
|
|
107
|
+
const urn = String(j.principal_urn || "");
|
|
108
|
+
const tail = urn.includes(":user:") ? urn.slice(urn.lastIndexOf(":user:") + 6) : "";
|
|
109
|
+
if (j.principal_id || tail) return { userId: String(j.principal_id || ""), userName: tail, domainId: String(j.account_id || "") };
|
|
110
|
+
} catch (err) { log(`身份查询(caller-identity)失败,换备用接口:${String(err?.message || err).slice(0, 120)}`); }
|
|
111
|
+
// 2) snap current/user:{user_id, user_name, domain_id}
|
|
112
|
+
try {
|
|
113
|
+
const j = await signedGet(`${snapBase}/v1/current/user`);
|
|
114
|
+
if (j.user_id || j.user_name) return { userId: String(j.user_id || ""), userName: String(j.user_name || ""), domainId: String(j.domain_id || "") };
|
|
115
|
+
} catch (err) { log(`身份查询(current/user)失败:${String(err?.message || err).slice(0, 120)}`); }
|
|
116
|
+
// 3) refresh_token JWT sub 兜底
|
|
117
|
+
try {
|
|
118
|
+
const payload = JSON.parse(Buffer.from(String(account?.refreshToken || "").split(".")[1] || "", "base64url").toString("utf8"));
|
|
119
|
+
if (payload?.sub) return { userId: String(payload.sub), userName: "", domainId: "" };
|
|
120
|
+
} catch {}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 跑完整登录流程。
|
|
126
|
+
* @param {object} [opts] { clientId, snapBase, stsHost, fetchImpl, timeoutMs, log, openBrowser }
|
|
127
|
+
* @returns {{account, redirectUri}} 成功返回账号(含 refreshToken/AK/SK/dpopJwk 等)
|
|
128
|
+
*/
|
|
129
|
+
export async function runCodeartsLogin({
|
|
130
|
+
clientId = CLIENT_ID,
|
|
131
|
+
snapBase = SNAP_BASE,
|
|
132
|
+
stsHost = STS_HOST,
|
|
133
|
+
fetchImpl,
|
|
134
|
+
timeoutMs = 5 * 60_000,
|
|
135
|
+
log = console.log,
|
|
136
|
+
} = {}) {
|
|
137
|
+
const state = buildLoginState({ clientId });
|
|
138
|
+
const server = await startCallbackServer();
|
|
139
|
+
const redirectUri = `http://127.0.0.1:${server.port}/oauth/callback`;
|
|
140
|
+
const authorizeUrl = buildAuthorizeUrl({ state, port: server.port });
|
|
141
|
+
log("");
|
|
142
|
+
log("请用浏览器打开下面的链接并登录华为云(授权 CodeArts Agent):");
|
|
143
|
+
log("");
|
|
144
|
+
log(` ${authorizeUrl}`);
|
|
145
|
+
log("");
|
|
146
|
+
log(`本机回调:${redirectUri}(回调通道优先;ticket 轮询后台兜底,谁先到用谁)`);
|
|
147
|
+
|
|
148
|
+
const deadline = Date.now() + timeoutMs;
|
|
149
|
+
const ticketAbort = new AbortController();
|
|
150
|
+
let ticketPromise = null;
|
|
151
|
+
try {
|
|
152
|
+
while (Date.now() < deadline) {
|
|
153
|
+
const hit = await server.nextHit(Math.min(3000, deadline - Date.now()));
|
|
154
|
+
// 通道 1:浏览器回调带 code → 直接换 token(谁先到用谁;portal 带 port 参数走这路,ticket 不会下发)
|
|
155
|
+
if (hit?.code) {
|
|
156
|
+
log("已收到授权码,正在换取 STS 凭证…");
|
|
157
|
+
const account = await exchangeAuthorizationCode({
|
|
158
|
+
code: hit.code,
|
|
159
|
+
verifier: state.codeVerifier,
|
|
160
|
+
redirectUri,
|
|
161
|
+
clientId: state.clientId,
|
|
162
|
+
dpopJwk: state.dpopJwk,
|
|
163
|
+
fetchImpl,
|
|
164
|
+
stsHost,
|
|
165
|
+
});
|
|
166
|
+
// portal 回调只回 code 不带身份(生产 exchange 响应 user_id 常为空):
|
|
167
|
+
// 空身份会导致登录去重把不同账号当同一账号替换,必须落盘前补调身份接口
|
|
168
|
+
if (!account.userId || !account.userName) {
|
|
169
|
+
log("正在查询账号身份…");
|
|
170
|
+
const id = await lookupIdentity({ account, fetchImpl, log }).catch(() => null);
|
|
171
|
+
if (id) {
|
|
172
|
+
if (id.userId) account.userId = id.userId;
|
|
173
|
+
if (id.userName) account.userName = id.userName;
|
|
174
|
+
if (id.domainId) account.domainId = id.domainId;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
ticketAbort.abort(); // 回调已赢,停掉后台 ticket 轮询
|
|
178
|
+
return { account, state, redirectUri };
|
|
179
|
+
}
|
|
180
|
+
// 授权失败(用户拒绝等):把上游原因说人话抛出
|
|
181
|
+
if (hit?.error) throw new Error(`codearts authorize failed: ${hit.error}${hit.error_description ? ` — ${hit.error_description}` : ""}`);
|
|
182
|
+
// 通道 2:首次(portal 307 带 secret 一跳,或 3s 无回调)→ 后台起 ticket 轮询
|
|
183
|
+
// 关键:绝不 await 阻塞主循环——否则浏览器 code 回调无人消费,永远轮询(真机首登实测死锁)
|
|
184
|
+
if ((hit?.secret || !hit) && !ticketPromise) {
|
|
185
|
+
ticketPromise = pollTicket({ state, snapBase, fetchImpl, timeoutMs: deadline - Date.now(), log, signal: ticketAbort.signal }).catch(() => null);
|
|
186
|
+
}
|
|
187
|
+
// ticket 后台结果非阻塞查询:未决立即返回 null,主循环继续收回调
|
|
188
|
+
if (ticketPromise) {
|
|
189
|
+
const acc = await Promise.race([ticketPromise, Promise.resolve(null)]);
|
|
190
|
+
if (acc) return { account: acc, state, redirectUri };
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
} finally {
|
|
194
|
+
server.close();
|
|
195
|
+
}
|
|
196
|
+
throw new Error("codearts login timed out — 未在时限内拿到授权(可重跑:mslxdff -provider codearts login)");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 账号对象 → 可持久化 blob 字符串(与 auth-pool.blobFromAccount 同形状)。 */
|
|
200
|
+
export function accountToBlob(account, { codeVerifier, dpopJwk, clientId = CLIENT_ID }) {
|
|
201
|
+
return JSON.stringify({
|
|
202
|
+
userId: account.userId,
|
|
203
|
+
userName: account.userName,
|
|
204
|
+
domainId: account.domainId,
|
|
205
|
+
refreshToken: account.refreshToken,
|
|
206
|
+
clientId,
|
|
207
|
+
codeVerifier,
|
|
208
|
+
dpopJwk,
|
|
209
|
+
accessKeyId: account.accessKeyId,
|
|
210
|
+
secretAccessKey: account.secretAccessKey,
|
|
211
|
+
securityToken: account.securityToken,
|
|
212
|
+
expiration: account.expiration,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// 模型目录(按账号隔离)+ 三路发现(agent-center / builtin / 福利网关)+ 福利 claim。
|
|
2
|
+
// 福利是按账号授予的:目录按 userId 存,isBenefit 只信「发起请求的账号」的目录;
|
|
3
|
+
// 目录里没有的模型回退冷启动种子(少带 maas_type 头 = InferHub.002002009.404)。
|
|
4
|
+
// 算法对齐 HITZY2002/codearts2api internal/upstream/models.go。
|
|
5
|
+
import {
|
|
6
|
+
SNAP_BASE, BENEFIT_HOST, EP_MODEL_BUILTIN, EP_AGENT_LIST, EP_AGENT_DETAIL,
|
|
7
|
+
EP_BENEFIT_CONFIG, EP_BENEFIT_CLAIM,
|
|
8
|
+
SEED_BENEFIT_MODELS, SEED_KNOWN_MODELS, CATALOG_TTL_MS,
|
|
9
|
+
} from "./const.js";
|
|
10
|
+
import { signRequest } from "./sign.js";
|
|
11
|
+
import { compatFetch } from "../../compat.js";
|
|
12
|
+
|
|
13
|
+
const lower = (s) => String(s || "").trim().toLowerCase();
|
|
14
|
+
|
|
15
|
+
export function createCatalog() {
|
|
16
|
+
const known = new Map(); // lower → 精确 ID(种子 + 已发现,大小写归一单点)
|
|
17
|
+
for (const id of [...SEED_KNOWN_MODELS, ...SEED_BENEFIT_MODELS]) {
|
|
18
|
+
if (!known.has(lower(id))) known.set(lower(id), id);
|
|
19
|
+
}
|
|
20
|
+
const accounts = new Map(); // userId → {models, benefit:Set, knows:Set, lastBenefit:Map, fetched}
|
|
21
|
+
|
|
22
|
+
function setAccount(userId, models, { keepBenefit = false, now = Date.now() } = {}) {
|
|
23
|
+
if (!userId) return;
|
|
24
|
+
const prev = accounts.get(userId);
|
|
25
|
+
const ac = { models: [], benefit: new Set(), knows: new Set(), lastBenefit: prev ? new Map(prev.lastBenefit) : new Map(), fetched: now };
|
|
26
|
+
for (const m of models || []) {
|
|
27
|
+
if (!m?.id) continue;
|
|
28
|
+
const key = lower(m.id);
|
|
29
|
+
ac.knows.add(key);
|
|
30
|
+
if (m.benefit) { ac.benefit.add(key); ac.lastBenefit.set(key, m); }
|
|
31
|
+
if (!known.has(key) || m.id !== key) known.set(key, m.id);
|
|
32
|
+
ac.models.push(m);
|
|
33
|
+
}
|
|
34
|
+
if (keepBenefit) {
|
|
35
|
+
// 福利来源失败但内置成功:上轮福利条目只要内置没明确登记(转正)就保留标记
|
|
36
|
+
for (const [key, mi] of ac.lastBenefit) {
|
|
37
|
+
if (ac.knows.has(key)) continue;
|
|
38
|
+
ac.benefit.add(key);
|
|
39
|
+
ac.knows.add(key);
|
|
40
|
+
ac.models.push(mi);
|
|
41
|
+
if (!known.has(key) || mi.id !== key) known.set(key, mi.id);
|
|
42
|
+
}
|
|
43
|
+
ac.models.sort((a, b) => (lower(a.id) < lower(b.id) ? -1 : lower(a.id) > lower(b.id) ? 1 : (a.id < b.id ? -1 : 1)));
|
|
44
|
+
}
|
|
45
|
+
accounts.set(userId, ac);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 判定顺序:账号目录标了福利 → true;目录里有但没标 → false(已转正);目录没有 → 种子兜底。
|
|
49
|
+
function isBenefit(userId, model) {
|
|
50
|
+
const key = lower(model);
|
|
51
|
+
if (!key) return false;
|
|
52
|
+
const ac = accounts.get(userId);
|
|
53
|
+
if (ac) {
|
|
54
|
+
if (ac.benefit.has(key)) return true;
|
|
55
|
+
if (ac.knows.has(key)) return false;
|
|
56
|
+
}
|
|
57
|
+
return SEED_BENEFIT_MODELS.some((m) => lower(m) === key);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function canonical(model) {
|
|
61
|
+
const exact = known.get(lower(model));
|
|
62
|
+
return exact || null;
|
|
63
|
+
}
|
|
64
|
+
function accountModels(userId) {
|
|
65
|
+
const ac = accounts.get(userId);
|
|
66
|
+
return ac ? [...ac.models] : [];
|
|
67
|
+
}
|
|
68
|
+
function isStale(userId, now = Date.now(), ttlMs = CATALOG_TTL_MS) {
|
|
69
|
+
const ac = accounts.get(userId);
|
|
70
|
+
return !ac || now - ac.fetched >= ttlMs;
|
|
71
|
+
}
|
|
72
|
+
return { setAccount, isBenefit, canonical, accountModels, isStale };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 多路合并:按小写 ID 去重,福利标记取或,参数更全/精确大小写优先,按小写 ID 排序。 */
|
|
76
|
+
export function mergeModels(sets) {
|
|
77
|
+
const merged = new Map();
|
|
78
|
+
for (const set of sets || []) {
|
|
79
|
+
for (const m of set || []) {
|
|
80
|
+
if (!m?.id) continue;
|
|
81
|
+
const key = lower(m.id);
|
|
82
|
+
const cur = merged.get(key);
|
|
83
|
+
if (!cur) { merged.set(key, { ...m }); continue; }
|
|
84
|
+
const keep = (m.contextWindow > 0 && !cur.contextWindow) || (m.id !== lower(m.id) && cur.id === lower(cur.id)) ? m : cur;
|
|
85
|
+
const drop = keep === m ? cur : m;
|
|
86
|
+
merged.set(key, {
|
|
87
|
+
...keep,
|
|
88
|
+
benefit: !!(keep.benefit || drop.benefit),
|
|
89
|
+
name: keep.name || drop.name || "",
|
|
90
|
+
contextWindow: keep.contextWindow || drop.contextWindow || 0,
|
|
91
|
+
maxTokens: keep.maxTokens || drop.maxTokens || 0,
|
|
92
|
+
desc: keep.desc || drop.desc || "",
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return [...merged.values()].sort((a, b) => (lower(a.id) < lower(b.id) ? -1 : lower(a.id) > lower(b.id) ? 1 : (a.id < b.id ? -1 : 1)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 签名 GET 并解析 JSON(Agent-Type 可选;空 body 签名 = sha256(""))。 */
|
|
100
|
+
export async function signedGetJson({ url, cred, agentType, fetchImpl }) {
|
|
101
|
+
const doFetch = fetchImpl || compatFetch;
|
|
102
|
+
const headers = { "content-type": "application/json", "x-language": "zh-cn" };
|
|
103
|
+
if (agentType) headers["agent-type"] = agentType;
|
|
104
|
+
if (cred?.securityToken) headers["x-security-token"] = cred.securityToken;
|
|
105
|
+
const { headers: signed } = signRequest({ method: "GET", url, headers, body: "", cred });
|
|
106
|
+
const res = await doFetch(url, { method: "GET", headers: signed });
|
|
107
|
+
const raw = await res.text().catch(() => "");
|
|
108
|
+
if (res.status >= 400) throw new Error(`http ${res.status}: ${String(raw).slice(0, 200)}`);
|
|
109
|
+
try { return JSON.parse(raw); } catch { throw new Error(`non-JSON body: ${String(raw).slice(0, 120)}`); }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 幂等领取限时福利(官方客户端打开模型菜单即调用;error_code "0000" 视为成功)。 */
|
|
113
|
+
export async function claimBenefit({ cred, benefitHost = BENEFIT_HOST, fetchImpl }) {
|
|
114
|
+
const doFetch = fetchImpl || compatFetch;
|
|
115
|
+
const url = benefitHost + EP_BENEFIT_CLAIM;
|
|
116
|
+
const body = "{}";
|
|
117
|
+
const headers = { "content-type": "application/json", "x-language": "zh-cn" };
|
|
118
|
+
if (cred?.securityToken) headers["x-security-token"] = cred.securityToken;
|
|
119
|
+
const { headers: signed } = signRequest({ method: "POST", url, headers, body, cred });
|
|
120
|
+
const res = await doFetch(url, { method: "POST", headers: signed, body });
|
|
121
|
+
const raw = await res.text().catch(() => "");
|
|
122
|
+
if (res.status >= 400) throw new Error(`claim http ${res.status}: ${String(raw).slice(0, 200)}`);
|
|
123
|
+
const json = JSON.parse(raw);
|
|
124
|
+
if (String(json?.error_code || "") !== "0000") throw new Error(`claim failed: error_code=${json?.error_code} msg=${json?.error_msg}`);
|
|
125
|
+
return json;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const toModelInfo = (m, { benefit = false } = {}) => {
|
|
129
|
+
const id = m?.model_id || m?.model_name || m?.modelAlias || "";
|
|
130
|
+
if (!id) return null;
|
|
131
|
+
return {
|
|
132
|
+
id: String(id),
|
|
133
|
+
name: String(m?.model_name || id),
|
|
134
|
+
contextWindow: Number(m?.context_window) || 0,
|
|
135
|
+
maxTokens: Number(m?.max_tokens) || 0,
|
|
136
|
+
benefit,
|
|
137
|
+
desc: String(m?.model_desc || ""),
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** 三路发现(任一路失败不阻断)→ {models, builtinOk, benefitOk, agentOk}。 */
|
|
142
|
+
export async function discoverAccountModels({ account, snapBase = SNAP_BASE, benefitHost = BENEFIT_HOST, autoClaim = true, fetchImpl } = {}) {
|
|
143
|
+
const cred = { accessKeyId: account.accessKeyId, secretAccessKey: account.secretAccessKey, securityToken: account.securityToken };
|
|
144
|
+
const sets = [];
|
|
145
|
+
let agentOk = false, builtinOk = false, benefitOk = false;
|
|
146
|
+
|
|
147
|
+
// 1) agent-center:useragents 找 CodeAgent → detail.gpts.models
|
|
148
|
+
try {
|
|
149
|
+
const list = await signedGetJson({ url: `${snapBase}${EP_AGENT_LIST}?offset=0&limit=100&is_primary_agent=true`, cred, agentType: "AgentCenter", fetchImpl });
|
|
150
|
+
const agents = Array.isArray(list?.agents) ? list.agents : [];
|
|
151
|
+
const pick = agents.find((a) => a?.agent_name === "CodeAgent" && a?.alias?.alias_zh_cn === "智能体" && a?.show_in_ide)
|
|
152
|
+
|| agents.find((a) => a?.is_primary_agent) || agents[0];
|
|
153
|
+
if (pick?.agent_id) {
|
|
154
|
+
const detail = await signedGetJson({ url: `${snapBase}${EP_AGENT_DETAIL}?agent_id=${encodeURIComponent(pick.agent_id)}`, cred, agentType: "AgentCenter", fetchImpl });
|
|
155
|
+
const models = (Array.isArray(detail?.gpts?.models) ? detail.gpts.models : [])
|
|
156
|
+
.map((m) => toModelInfo({ model_id: m?.model_id, model_name: m?.model_name || m?.model_alias, context_window: m?.model_parameters?.context_window, max_tokens: m?.model_parameters?.max_tokens, model_desc: m?.model_parameters?.model_desc }))
|
|
157
|
+
.filter(Boolean);
|
|
158
|
+
if (models.length) { sets.push(models); agentOk = true; }
|
|
159
|
+
}
|
|
160
|
+
} catch { /* agent 路失败不阻断 */ }
|
|
161
|
+
|
|
162
|
+
// 2) 内置模型(Agent-Type: PromptCenter)
|
|
163
|
+
try {
|
|
164
|
+
const json = await signedGetJson({ url: `${snapBase}${EP_MODEL_BUILTIN}`, cred, agentType: "PromptCenter", fetchImpl });
|
|
165
|
+
const models = (Array.isArray(json?.builtinModels) ? json.builtinModels : []).map((m) => toModelInfo(m)).filter(Boolean);
|
|
166
|
+
if (models.length) { sets.push(models); builtinOk = true; }
|
|
167
|
+
} catch { /* builtin 失败不阻断 */ }
|
|
168
|
+
|
|
169
|
+
// 3) 福利网关(先幂等 claim 再拉目录;error_code!=0000 视为该来源失败)
|
|
170
|
+
try {
|
|
171
|
+
if (autoClaim) { try { await claimBenefit({ cred, benefitHost, fetchImpl }); } catch { /* 未开通福利套餐时 claim 可能报错,继续拉目录 */ } }
|
|
172
|
+
const json = await signedGetJson({ url: benefitHost + EP_BENEFIT_CONFIG, cred, fetchImpl });
|
|
173
|
+
if (String(json?.error_code || "") === "0000") {
|
|
174
|
+
const models = (Array.isArray(json?.result?.models) ? json.result.models : []).map((m) => toModelInfo(m, { benefit: true })).filter(Boolean);
|
|
175
|
+
if (models.length) { sets.push(models); benefitOk = true; }
|
|
176
|
+
}
|
|
177
|
+
} catch { /* benefit 失败不阻断 */ }
|
|
178
|
+
|
|
179
|
+
const models = mergeModels(sets);
|
|
180
|
+
if (!models.length) throw new Error("codearts models api returned empty list");
|
|
181
|
+
return { models, agentOk, builtinOk, benefitOk };
|
|
182
|
+
}
|