mslxdff 0.1.138 → 0.1.141
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 +1 -1
- package/src/chooser.js +31 -12
- package/src/cli/commands/model/list-live.js +22 -0
- package/src/cli/commands/model/list.js +2 -0
- package/src/cli/commands/model/live-models.js +24 -0
- package/src/cli/commands/provider/cline-login.js +74 -5
- package/src/cli/commands/provider/codearts-login.js +45 -0
- package/src/cli/commands/provider/index.js +12 -0
- package/src/cli/commands/provider/keys.js +21 -2
- package/src/cli/commands/provider/models.js +9 -0
- 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/interactive.js +41 -4
- package/src/cli/provider-row.js +1 -1
- package/src/providers/classify.js +1 -1
- package/src/providers/cline/index.js +9 -3
- 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/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 +15 -0
- package/src/providers/share-keys.js +2 -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/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 +9 -3
- package/src/runtime/qoder-checkin.js +93 -0
- package/src/runtime/traework-checkin.js +104 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// 非流式聚合、chat_id 派生。解析纯函数见 ./sse.js。
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import { createSseState, scanLine, applyEvent, sortedToolCalls, embeddedErrorFromData, effectiveFinish, isValidStructuredQA, UpstreamEventError } from "./sse.js";
|
|
4
|
+
|
|
5
|
+
// chat.js 从这里拿错误类(保持单一导入面)。
|
|
6
|
+
export { UpstreamEventError };
|
|
7
|
+
|
|
8
|
+
// 只读到首个 data: 事件:正常帧原样回放(不破坏流式);内嵌业务错误转 UpstreamEventError 供上层重试/冷却。
|
|
9
|
+
export async function preflightResponse(resp) {
|
|
10
|
+
if (!resp?.body) return resp;
|
|
11
|
+
const reader = resp.body.getReader();
|
|
12
|
+
const dec = new TextDecoder();
|
|
13
|
+
const prefix = [];
|
|
14
|
+
let buf = "";
|
|
15
|
+
const state = { pendingEvent: "" };
|
|
16
|
+
const headers = new Headers(resp.headers);
|
|
17
|
+
headers.delete("content-length");
|
|
18
|
+
while (true) {
|
|
19
|
+
const { done, value } = await reader.read();
|
|
20
|
+
if (value?.length) {
|
|
21
|
+
const chunk = dec.decode(value, { stream: true });
|
|
22
|
+
prefix.push(chunk);
|
|
23
|
+
buf += chunk;
|
|
24
|
+
}
|
|
25
|
+
let idx;
|
|
26
|
+
while ((idx = buf.indexOf("\n")) >= 0) {
|
|
27
|
+
const line = buf.slice(0, idx);
|
|
28
|
+
buf = buf.slice(idx + 1);
|
|
29
|
+
const ev = scanLine(line, state);
|
|
30
|
+
if (ev) {
|
|
31
|
+
const err = embeddedErrorFromData(ev.data);
|
|
32
|
+
if (err) {
|
|
33
|
+
try { await reader.cancel(); } catch {}
|
|
34
|
+
throw new UpstreamEventError(err.message, { status: err.status, code: err.message });
|
|
35
|
+
}
|
|
36
|
+
return replay(prefix, buf, reader, resp.status, headers);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (done) return replay(prefix, buf, null, resp.status, headers);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function replay(chunks, tail, reader, status, headers) {
|
|
44
|
+
const enc = new TextEncoder();
|
|
45
|
+
let primed = false;
|
|
46
|
+
const stream = new ReadableStream({
|
|
47
|
+
async pull(controller) {
|
|
48
|
+
if (!primed) {
|
|
49
|
+
primed = true;
|
|
50
|
+
for (const c of chunks) controller.enqueue(enc.encode(c));
|
|
51
|
+
if (tail) controller.enqueue(enc.encode(tail));
|
|
52
|
+
if (!reader) { controller.close(); return; }
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const { done, value } = await reader.read();
|
|
56
|
+
if (done) controller.close();
|
|
57
|
+
else controller.enqueue(value);
|
|
58
|
+
} catch (err) { controller.error(err); }
|
|
59
|
+
},
|
|
60
|
+
cancel() { try { reader?.cancel?.(); } catch {} },
|
|
61
|
+
});
|
|
62
|
+
return new Response(stream, { status, headers });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// chat_id 必须 32 位 hex(UUID 去连字符),否则上游报「请求参数错误:chat_id」。
|
|
66
|
+
export function newChatId(body, opts) {
|
|
67
|
+
const raw = String(body?.chat_id || body?.conversation_id || opts?.sessionId || "").trim();
|
|
68
|
+
const hex = raw.toLowerCase().replace(/[^0-9a-f]/g, "");
|
|
69
|
+
if (hex.length >= 32) return hex.slice(0, 32);
|
|
70
|
+
return crypto.createHash("sha256").update(raw || crypto.randomUUID(), "utf8").digest("hex").slice(0, 32);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// 解包:模型把整段 QA JSON(或 ```json/```markdown 包裹)当正文时只取 answer(对齐 codearts2api unwrapQAContent)。
|
|
74
|
+
export function unwrapQAContent(s) {
|
|
75
|
+
const text = String(s || "");
|
|
76
|
+
const trimmed = text.trim();
|
|
77
|
+
if (!trimmed) return text;
|
|
78
|
+
const direct = parseQaAnswer(trimmed);
|
|
79
|
+
if (direct !== null) return direct;
|
|
80
|
+
if (!trimmed.startsWith("```")) return text;
|
|
81
|
+
const lines = trimmed.split("\n");
|
|
82
|
+
if (lines.length < 3 || lines[lines.length - 1].trim() !== "```") return text;
|
|
83
|
+
const inner = lines.slice(1, -1).join("\n");
|
|
84
|
+
const ans = parseQaAnswer(inner.trim());
|
|
85
|
+
return ans !== null ? ans : inner;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseQaAnswer(s) {
|
|
89
|
+
try {
|
|
90
|
+
const obj = JSON.parse(s);
|
|
91
|
+
return isValidStructuredQA(obj) ? obj.answer : null;
|
|
92
|
+
} catch { return null; }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const chunkLine = (id, model, delta, finish) => {
|
|
96
|
+
const choice = { index: 0, delta };
|
|
97
|
+
if (finish) choice.finish_reason = finish;
|
|
98
|
+
return `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [choice] })}\n\n`;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** 上游 SSE → OpenAI SSE 流式转换(快照替换/增量混合语义,保证至少一个 finish chunk + [DONE])。 */
|
|
102
|
+
export function sseToOpenAIResponse(resp, { model, id }) {
|
|
103
|
+
const dec = new TextDecoder();
|
|
104
|
+
const enc = new TextEncoder();
|
|
105
|
+
const reader = resp.body.getReader();
|
|
106
|
+
let buf = "";
|
|
107
|
+
const state = createSseState();
|
|
108
|
+
let finishSent = false;
|
|
109
|
+
const stream = new ReadableStream({
|
|
110
|
+
async pull(controller) {
|
|
111
|
+
const emit = (text) => controller.enqueue(enc.encode(text));
|
|
112
|
+
const finishChunk = () => { if (!finishSent) { emit(chunkLine(id, model, {}, effectiveFinish(state))); finishSent = true; } };
|
|
113
|
+
try {
|
|
114
|
+
while (true) {
|
|
115
|
+
const { done, value } = await reader.read();
|
|
116
|
+
if (value?.length) buf += dec.decode(value, { stream: true });
|
|
117
|
+
let idx;
|
|
118
|
+
while ((idx = buf.indexOf("\n")) >= 0) {
|
|
119
|
+
const line = buf.slice(0, idx);
|
|
120
|
+
buf = buf.slice(idx + 1);
|
|
121
|
+
const ev = scanLine(line, state);
|
|
122
|
+
if (!ev) continue;
|
|
123
|
+
if (ev.data === "[DONE]") {
|
|
124
|
+
finishChunk();
|
|
125
|
+
emit("data: [DONE]\n\n");
|
|
126
|
+
controller.close();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const beforeC = state.content.length, beforeR = state.reason.length;
|
|
130
|
+
state.forward = null; // 每帧重置:仅本帧 delta 路径产生 forward,防重复转发
|
|
131
|
+
applyEvent(state, ev.event, ev.data);
|
|
132
|
+
if (state.error) {
|
|
133
|
+
emit(`event: error\ndata: ${JSON.stringify({ error: { message: `${state.error.code} ${state.error.msg}`.trim(), type: "upstream_error", code: "CODEARTS_STREAM_ERROR" } })}\n\n`);
|
|
134
|
+
emit("data: [DONE]\n\n");
|
|
135
|
+
controller.close();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const delta = {};
|
|
139
|
+
const fwd = state.forward || {};
|
|
140
|
+
if (fwd.role) delta.role = fwd.role;
|
|
141
|
+
if (fwd.toolCalls) delta.tool_calls = fwd.toolCalls; // 工具调用分片原样转发(缺它=回合空停)
|
|
142
|
+
if (state.reason.length > beforeR) delta.reasoning_content = state.reason.slice(beforeR);
|
|
143
|
+
if (state.content.length > beforeC) delta.content = state.content.slice(beforeC);
|
|
144
|
+
if (Object.keys(delta).length) emit(chunkLine(id, model, delta, ""));
|
|
145
|
+
if (fwd.finish) finishChunk(); // 上游 finish_reason 出现即发(含 tool_calls;空 calls 自动降 stop)
|
|
146
|
+
if (state.done) {
|
|
147
|
+
finishChunk();
|
|
148
|
+
emit("data: [DONE]\n\n");
|
|
149
|
+
controller.close();
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (done) {
|
|
154
|
+
finishChunk();
|
|
155
|
+
emit("data: [DONE]\n\n");
|
|
156
|
+
controller.close();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
} catch (err) { controller.error(err); }
|
|
161
|
+
},
|
|
162
|
+
cancel() { try { reader.cancel(); } catch {} },
|
|
163
|
+
});
|
|
164
|
+
return new Response(stream, { status: resp.status, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** 上游 SSE → OpenAI chat.completion JSON(非流式聚合;内嵌错误抛 UpstreamEventError)。 */
|
|
168
|
+
export async function aggregateToCompletion(resp, { model, id }) {
|
|
169
|
+
const dec = new TextDecoder();
|
|
170
|
+
const reader = resp.body.getReader();
|
|
171
|
+
let buf = "";
|
|
172
|
+
const state = createSseState();
|
|
173
|
+
outer: while (true) {
|
|
174
|
+
const { done, value } = await reader.read();
|
|
175
|
+
if (value?.length) buf += dec.decode(value, { stream: true });
|
|
176
|
+
let idx;
|
|
177
|
+
while ((idx = buf.indexOf("\n")) >= 0) {
|
|
178
|
+
const line = buf.slice(0, idx);
|
|
179
|
+
buf = buf.slice(idx + 1);
|
|
180
|
+
const ev = scanLine(line, state);
|
|
181
|
+
if (ev) applyEvent(state, ev.event, ev.data);
|
|
182
|
+
if (state.error || state.done) break outer;
|
|
183
|
+
}
|
|
184
|
+
if (done) break;
|
|
185
|
+
}
|
|
186
|
+
try { await reader.cancel(); } catch {}
|
|
187
|
+
if (state.error) {
|
|
188
|
+
const status = embeddedErrorFromData(JSON.stringify({ error_code: state.error.code, error_msg: state.error.msg }))?.status || 502;
|
|
189
|
+
throw new UpstreamEventError(`${state.error.code} ${state.error.msg}`.trim(), { status, code: state.error.code });
|
|
190
|
+
}
|
|
191
|
+
const message = { role: "assistant", content: unwrapQAContent(state.content) };
|
|
192
|
+
if (state.reason) message.reasoning_content = state.reason;
|
|
193
|
+
const calls = sortedToolCalls(state);
|
|
194
|
+
if (calls.length) {
|
|
195
|
+
message.tool_calls = calls;
|
|
196
|
+
if (!state.content) message.content = null;
|
|
197
|
+
}
|
|
198
|
+
const usage = state.usage
|
|
199
|
+
? { ...state.usage, total_tokens: (state.usage.prompt_tokens || 0) + (state.usage.completion_tokens || 0) }
|
|
200
|
+
: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
|
|
201
|
+
return {
|
|
202
|
+
id: id || `chatcmpl-${Date.now()}`,
|
|
203
|
+
object: "chat.completion",
|
|
204
|
+
created: Math.floor(Date.now() / 1000),
|
|
205
|
+
model,
|
|
206
|
+
choices: [{ index: 0, message, finish_reason: effectiveFinish(state), logprobs: null }],
|
|
207
|
+
usage,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// STS /v1/oauth2/tokens:授权码换凭证 + refresh_token 续期(DPoP 必带)。
|
|
2
|
+
// 终态失效(refresh_token 过期/已用/DPoP 或 client_id 不匹配)→ relogin=true,
|
|
3
|
+
// 与网络/5xx 瞬时失败分开,避免好号被误杀或死号无限刷。
|
|
4
|
+
import { STS_HOST, EP_OAUTH_TOKENS, CLIENT_ID } from "./const.js";
|
|
5
|
+
import { signDpopProof } from "./dpop.js";
|
|
6
|
+
import { compatFetch } from "../../compat.js";
|
|
7
|
+
|
|
8
|
+
function tokenErr(rawText) {
|
|
9
|
+
try { return JSON.parse(rawText) || {}; } catch { return {}; }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// 对齐 codearts2api:invalid_grant / ExpiredRefreshToken / InvalidDPoPHeader /
|
|
13
|
+
// invalid client id / has been used → 终态,必须重新登录。
|
|
14
|
+
export function isReLoginRejected(status, rawText) {
|
|
15
|
+
const t = tokenErr(rawText);
|
|
16
|
+
const code = String(t.error_code || "");
|
|
17
|
+
const msg = String(t.error_msg || "");
|
|
18
|
+
const low = (t.error || msg).toLowerCase();
|
|
19
|
+
return t.error === "invalid_grant"
|
|
20
|
+
|| code.includes("ExpiredRefreshToken")
|
|
21
|
+
|| code.includes("InvalidDPoPHeader")
|
|
22
|
+
|| low.includes("invalid client id")
|
|
23
|
+
|| low.includes("has been used");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 归一化 STS 响应(新 credentials / 旧 credential 双形状)。 */
|
|
27
|
+
export function normalizeTokenResponse(json) {
|
|
28
|
+
const c = json?.credentials || {};
|
|
29
|
+
const legacy = json?.credential || {};
|
|
30
|
+
const securityToken = c.security_token || legacy.securitytoken || "";
|
|
31
|
+
const accessKeyId = c.access_key_id || legacy.access || "";
|
|
32
|
+
const secretAccessKey = c.secret_access_key || legacy.secret || "";
|
|
33
|
+
const expiration = c.expiration || legacy.expires_at || "";
|
|
34
|
+
if (!securityToken || !accessKeyId || !secretAccessKey) return null;
|
|
35
|
+
const expiresAtMs = expiration ? Date.parse(expiration) : NaN;
|
|
36
|
+
return {
|
|
37
|
+
userId: String(json.user_id || ""),
|
|
38
|
+
userName: String(json.user_name || ""),
|
|
39
|
+
domainId: String(json.domain_id || ""),
|
|
40
|
+
refreshToken: String(json.refresh_token || ""),
|
|
41
|
+
accessKeyId,
|
|
42
|
+
secretAccessKey,
|
|
43
|
+
securityToken,
|
|
44
|
+
expiration,
|
|
45
|
+
expiresAtMs: Number.isFinite(expiresAtMs) ? expiresAtMs : 0,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function postToken({ url, form, dpopJwk, fetchImpl }) {
|
|
50
|
+
const doFetch = fetchImpl || compatFetch;
|
|
51
|
+
const proof = signDpopProof(dpopJwk, url);
|
|
52
|
+
const res = await doFetch(url, {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: { "content-type": "application/x-www-form-urlencoded", dpop: proof },
|
|
55
|
+
body: form.toString(),
|
|
56
|
+
});
|
|
57
|
+
const raw = await res.text().catch(() => "");
|
|
58
|
+
return { res, raw };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 授权码换凭证(登录用)。
|
|
63
|
+
* @param {object} p { code, verifier, redirectUri, clientId?, dpopJwk, fetchImpl?, stsHost? }
|
|
64
|
+
*/
|
|
65
|
+
export async function exchangeAuthorizationCode({ code, verifier, redirectUri, clientId = CLIENT_ID, dpopJwk, fetchImpl, stsHost } = {}) {
|
|
66
|
+
const url = (stsHost || STS_HOST) + EP_OAUTH_TOKENS;
|
|
67
|
+
const form = new URLSearchParams({
|
|
68
|
+
client_id: clientId,
|
|
69
|
+
code: String(code || ""),
|
|
70
|
+
code_verifier: String(verifier || ""),
|
|
71
|
+
grant_type: "authorization_code",
|
|
72
|
+
redirect_uri: String(redirectUri || ""),
|
|
73
|
+
});
|
|
74
|
+
const { res, raw } = await postToken({ url, form, dpopJwk, fetchImpl });
|
|
75
|
+
if (res.status >= 400) throw new Error(`codearts sts exchange http ${res.status}: ${String(raw).slice(0, 200)}`);
|
|
76
|
+
const json = JSON.parse(raw);
|
|
77
|
+
const account = normalizeTokenResponse(json);
|
|
78
|
+
if (!account) throw new Error("codearts sts exchange: response missing credentials");
|
|
79
|
+
account.clientId = clientId;
|
|
80
|
+
return account;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 用 refresh_token 换新 STS 凭证(refresh_token 单次轮换,响应里取新值写回)。
|
|
85
|
+
* @param {object} blob 账号凭证 blob(refreshToken/codeVerifier/dpopJwk/clientId)
|
|
86
|
+
* @param {object} [opts] { fetchImpl, stsHost }
|
|
87
|
+
* @returns {{account, refreshToken?, relogin?, error?}}
|
|
88
|
+
*/
|
|
89
|
+
export async function refreshStsCredential(blob, { fetchImpl, stsHost } = {}) {
|
|
90
|
+
const refreshToken = String(blob?.refreshToken || "");
|
|
91
|
+
const verifier = String(blob?.codeVerifier || "");
|
|
92
|
+
const jwk = blob?.dpopJwk;
|
|
93
|
+
const clientId = String(blob?.clientId || CLIENT_ID);
|
|
94
|
+
if (!refreshToken) return { account: null, relogin: true, error: "missing refresh_token" };
|
|
95
|
+
if (!verifier) return { account: null, relogin: true, error: "missing code_verifier" };
|
|
96
|
+
if (!jwk || !jwk.d) return { account: null, relogin: true, error: "missing DPoP private key — re-login required" };
|
|
97
|
+
|
|
98
|
+
const url = (stsHost || STS_HOST) + EP_OAUTH_TOKENS;
|
|
99
|
+
const form = new URLSearchParams({
|
|
100
|
+
client_id: clientId,
|
|
101
|
+
code_verifier: verifier,
|
|
102
|
+
grant_type: "refresh_token",
|
|
103
|
+
refresh_token: refreshToken,
|
|
104
|
+
});
|
|
105
|
+
let res, raw;
|
|
106
|
+
try {
|
|
107
|
+
({ res, raw } = await postToken({ url, form, dpopJwk: jwk, fetchImpl }));
|
|
108
|
+
} catch (err) {
|
|
109
|
+
return { account: null, error: `network: ${err?.message || err}` };
|
|
110
|
+
}
|
|
111
|
+
if (res.status >= 400) {
|
|
112
|
+
if (isReLoginRejected(res.status, raw)) {
|
|
113
|
+
const t = tokenErr(raw);
|
|
114
|
+
return { account: null, relogin: true, status: res.status, code: t.error_code, error: `refresh rejected: ${String(raw).slice(0, 200)}` };
|
|
115
|
+
}
|
|
116
|
+
return { account: null, status: res.status, error: `sts http ${res.status}: ${String(raw).slice(0, 200)}` };
|
|
117
|
+
}
|
|
118
|
+
let json;
|
|
119
|
+
try { json = JSON.parse(raw); } catch { return { account: null, error: "sts returned non-JSON body" }; }
|
|
120
|
+
const account = normalizeTokenResponse(json);
|
|
121
|
+
if (!account) return { account: null, error: "sts response missing credentials" };
|
|
122
|
+
account.clientId = clientId;
|
|
123
|
+
return { account, refreshToken: account.refreshToken || null };
|
|
124
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./codearts/index.js";
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// qoder 账号落盘单一源:auths/qoder-<uid>.json(0600 tmp+rename)+ state.json providerConfigs.qoder keys/auths 按 uid 去重。
|
|
2
|
+
// 凭证形状对齐 qoder2api:secret = {"device_token":"dt-xxx","refresh_token":"drt-xxx"},region 进 auth 行。
|
|
3
|
+
import { writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, readdirSync, readFileSync, chmodSync } from "node:fs";
|
|
4
|
+
import { join, dirname } from "node:path";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { isTestEnv, defaultStateFile } from "../../state/store.js";
|
|
7
|
+
import { normalizeRegion } from "./constants.js";
|
|
8
|
+
|
|
9
|
+
export function authDirFor({ explicit = "", testEnv = false, stateFile } = {}) {
|
|
10
|
+
if (explicit) return explicit;
|
|
11
|
+
if (testEnv) return join(tmpdir(), "mslxdff-test-auths");
|
|
12
|
+
return join(dirname(stateFile), "auths");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function resolveAuthDir() {
|
|
16
|
+
return authDirFor({
|
|
17
|
+
explicit: process.env.QODER_AUTH_DIR || "",
|
|
18
|
+
testEnv: isTestEnv(),
|
|
19
|
+
stateFile: defaultStateFile(),
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function resolveAuthDirs() {
|
|
24
|
+
const primary = resolveAuthDir();
|
|
25
|
+
const cwdDir = join(process.cwd(), "auths");
|
|
26
|
+
return primary === cwdDir ? [primary] : [primary, cwdDir];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function listAccountDocs({ dirs } = {}) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
for (const dir of dirs || resolveAuthDirs()) {
|
|
33
|
+
let files = [];
|
|
34
|
+
try {
|
|
35
|
+
if (!existsSync(dir)) continue;
|
|
36
|
+
files = readdirSync(dir).filter((f) => f.startsWith("qoder-") && f.endsWith(".json"));
|
|
37
|
+
} catch { continue; }
|
|
38
|
+
for (const f of files) {
|
|
39
|
+
try {
|
|
40
|
+
const doc = JSON.parse(readFileSync(join(dir, f), "utf8"));
|
|
41
|
+
const uid = doc?.account?.uid;
|
|
42
|
+
if (!uid || !doc?.auth?.deviceToken) continue;
|
|
43
|
+
if (seen.has(String(uid))) continue;
|
|
44
|
+
seen.add(String(uid));
|
|
45
|
+
out.push({ uid: String(uid), file: join(dir, f), dir, doc });
|
|
46
|
+
} catch {}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function writeAccountFile({ uid, deviceToken, refreshToken = "", region = "global", name = "", email = "", userType = "personal_standard", organizationId = "", organizationName = "" }) {
|
|
53
|
+
const authDir = resolveAuthDir();
|
|
54
|
+
mkdirSync(authDir, { recursive: true });
|
|
55
|
+
const doc = {
|
|
56
|
+
account: { uid, name, email, userType, organizationId, organizationName },
|
|
57
|
+
auth: { deviceToken, refreshToken, region: normalizeRegion(region) },
|
|
58
|
+
};
|
|
59
|
+
const fp = join(authDir, `qoder-${uid}.json`);
|
|
60
|
+
const tmp = `${fp}.tmp`;
|
|
61
|
+
writeFileSync(tmp, JSON.stringify(doc, null, 2), { mode: 0o600 });
|
|
62
|
+
try {
|
|
63
|
+
if (existsSync(fp)) { try { chmodSync(fp, 0o600); } catch {} unlinkSync(fp); }
|
|
64
|
+
renameSync(tmp, fp);
|
|
65
|
+
} catch {
|
|
66
|
+
writeFileSync(fp, JSON.stringify(doc, null, 2), { mode: 0o600 });
|
|
67
|
+
try { unlinkSync(tmp); } catch {}
|
|
68
|
+
}
|
|
69
|
+
try { chmodSync(fp, 0o600); } catch {}
|
|
70
|
+
return fp;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// state 落盘:key 存 JSON blob(对齐 qoder2api ParseOAuthSecret 形状),auths 存 uid 索引行。
|
|
74
|
+
async function persistAccounts(accounts, file) {
|
|
75
|
+
const { loadProviderConfigs, saveProviderConfig } = await import("../../state.js");
|
|
76
|
+
const cfg = (loadProviderConfigs(file ? { file } : {})?.qoder) || {};
|
|
77
|
+
const keys = [...(Array.isArray(cfg.keys) ? cfg.keys : [])];
|
|
78
|
+
const auths = [...(Array.isArray(cfg.auths) ? cfg.auths : [])];
|
|
79
|
+
let updated = 0;
|
|
80
|
+
for (const acc of accounts) {
|
|
81
|
+
if (!acc?.uid || !acc?.deviceToken) continue;
|
|
82
|
+
const blob = JSON.stringify({ device_token: acc.deviceToken, refresh_token: acc.refreshToken || "" });
|
|
83
|
+
const row = { uid: acc.uid, domain: acc.domain || "qoder.com", region: normalizeRegion(acc.region), name: acc.name || "", refreshToken: acc.refreshToken || "" };
|
|
84
|
+
const idx = auths.findIndex((a) => a?.uid === acc.uid);
|
|
85
|
+
if (idx >= 0) { keys[idx] = blob; auths[idx] = row; updated += 1; }
|
|
86
|
+
else { keys.push(blob); auths.push(row); }
|
|
87
|
+
}
|
|
88
|
+
saveProviderConfig("qoder", { baseUrl: cfg.baseUrl || "", keys, auths }, file ? { file } : {});
|
|
89
|
+
return { keys, auths, updated };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function saveQoderAccount({ uid, deviceToken, refreshToken = "", region = "global", name = "", email = "", userType = "personal_standard", organizationId = "", organizationName = "", domain = "qoder.com", file } = {}) {
|
|
93
|
+
if (!uid || !deviceToken) throw new Error("saveQoderAccount: 缺少 uid/deviceToken");
|
|
94
|
+
const fp = writeAccountFile({ uid, deviceToken, refreshToken, region, name, email, userType, organizationId, organizationName });
|
|
95
|
+
const st = await persistAccounts([{ uid, deviceToken, refreshToken, region, name, domain }], file);
|
|
96
|
+
return { file: fp, accounts: st.keys.length, updated: st.updated > 0 };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 重建 provider 的行级 auth:由 keys[i] blob + auths[i] 还原 deviceToken。
|
|
100
|
+
export function accountFromBlob(blob) {
|
|
101
|
+
try {
|
|
102
|
+
const j = JSON.parse(String(blob || "{}"));
|
|
103
|
+
return { deviceToken: String(j.device_token || ""), refreshToken: String(j.refresh_token || "") };
|
|
104
|
+
} catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// qoder 非流式聚合:上游 SSE 全读完 → chat.completion JSON。
|
|
2
|
+
// 真流式走 stream.js;本模块只服务 stream:false(行为与旧 callQoder 聚合同)。
|
|
3
|
+
import { extractDelta } from "./sse.js";
|
|
4
|
+
|
|
5
|
+
export async function aggregateQoderStream(upstreamRes) {
|
|
6
|
+
const reader = upstreamRes.body.getReader();
|
|
7
|
+
const dec = new TextDecoder();
|
|
8
|
+
let buf = "";
|
|
9
|
+
let usage = null;
|
|
10
|
+
let content = "";
|
|
11
|
+
let reasoning = "";
|
|
12
|
+
const toolCalls = [];
|
|
13
|
+
let sawContent = false;
|
|
14
|
+
for (;;) {
|
|
15
|
+
const { done, value } = await reader.read();
|
|
16
|
+
if (value) buf += dec.decode(value, { stream: !done });
|
|
17
|
+
const lines = buf.split("\n");
|
|
18
|
+
buf = lines.pop();
|
|
19
|
+
for (const raw of lines) {
|
|
20
|
+
const line = raw.replace(/\r$/, "");
|
|
21
|
+
if (!line.startsWith("data:")) continue;
|
|
22
|
+
const payload = line.slice(5).trim();
|
|
23
|
+
if (!payload || payload === "[DONE]") continue;
|
|
24
|
+
const d = extractDelta(payload);
|
|
25
|
+
if (d.err) throw d.err;
|
|
26
|
+
if (d.usageIn > 0 || d.usageOut > 0) {
|
|
27
|
+
usage = { prompt_tokens: d.usageIn, completion_tokens: d.usageOut, total_tokens: d.usageIn + d.usageOut };
|
|
28
|
+
}
|
|
29
|
+
if (d.content) { content += d.content; sawContent = true; }
|
|
30
|
+
if (d.reasoning) { reasoning += d.reasoning; sawContent = true; }
|
|
31
|
+
if (d.toolCalls) { toolCalls.push(...d.toolCalls); sawContent = true; }
|
|
32
|
+
}
|
|
33
|
+
if (done) break;
|
|
34
|
+
}
|
|
35
|
+
if (!sawContent && !usage) throw { kind: "upstream", status: 502, detail: "empty upstream stream" };
|
|
36
|
+
return { usage, content, reasoning, toolCalls };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function toCompletionJson({ model, chatId, content, reasoning, toolCalls, usage }) {
|
|
40
|
+
const msg = { role: "assistant", content: content || (toolCalls.length ? null : "") };
|
|
41
|
+
if (reasoning) msg.reasoning_content = reasoning;
|
|
42
|
+
if (toolCalls.length) msg.tool_calls = toolCalls;
|
|
43
|
+
return {
|
|
44
|
+
id: chatId,
|
|
45
|
+
object: "chat.completion",
|
|
46
|
+
created: Math.floor(Date.now() / 1000),
|
|
47
|
+
model,
|
|
48
|
+
choices: [{ index: 0, message: msg, finish_reason: toolCalls.length ? "tool_calls" : "stop" }],
|
|
49
|
+
usage: usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
|
|
50
|
+
};
|
|
51
|
+
}
|