mslxdff 0.1.138 → 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 +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/codearts-login.js +45 -0
- package/src/cli/commands/provider/index.js +12 -0
- package/src/cli/commands/provider/keys.js +13 -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/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,204 @@
|
|
|
1
|
+
// CodeArts SSE 帧解析(纯函数,无 IO)。
|
|
2
|
+
// 线格式(实测,对齐 codearts2api internal/upstream/sse.go):逐行 `data: <json>`,
|
|
3
|
+
// 无空行分隔、部分行无 event: 前缀;同时兼容标准 event:+data:+空行。
|
|
4
|
+
// 帧:起始 {id,model,type:"answer",chat_id,…};全文快照 {text:"<累计全文>",output,
|
|
5
|
+
// prompt_tokens,completion_tokens}(text 是快照非增量 → 替换语义);增量
|
|
6
|
+
// {choices:[{delta:{content,reasoning_content,tool_calls}}]} 或顶层 {delta:{…}};
|
|
7
|
+
// 结束 {"text":"[DONE]","error_code":"0"};错误 {"error_code":"…","error_msg":"…"}。
|
|
8
|
+
|
|
9
|
+
export function createSseState() {
|
|
10
|
+
return { pendingEvent: "", content: "", reason: "", finish: "", usage: null, error: null, done: false, calls: new Map(), forward: null };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// 降级:finish_reason=tool_calls 但 calls 为空(上游偶发空 tool_calls 帧 + 零文本,
|
|
14
|
+
// 真机 glm-5.3-flash 实测)→ 降 stop,否则 OpenAI 客户端判"无输出结束回合"报错。
|
|
15
|
+
// 注意:有真实 tool_calls 时必须原样透传,否则工具链断裂。
|
|
16
|
+
export function effectiveFinish(st) {
|
|
17
|
+
if (st?.finish === "tool_calls" && !(st?.calls?.size > 0)) return "stop";
|
|
18
|
+
return st?.finish || "stop";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function scanLine(line, state) {
|
|
22
|
+
const raw = String(line || "").replace(/\r?\n$/, "");
|
|
23
|
+
if (raw.startsWith("event:")) { state.pendingEvent = raw.slice(6).trim(); return null; }
|
|
24
|
+
if (raw.startsWith("data:")) {
|
|
25
|
+
const ev = state.pendingEvent || "";
|
|
26
|
+
state.pendingEvent = "";
|
|
27
|
+
return { event: ev, data: raw.slice(5).trim() };
|
|
28
|
+
}
|
|
29
|
+
if (!raw.trim()) { state.pendingEvent = ""; return null; }
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// OpenAI 兼容 chunk:choices[0].delta 或顶层 delta。
|
|
34
|
+
export function deltaFromChunk(payload) {
|
|
35
|
+
if (payload?.delta && typeof payload.delta === "object") return { delta: payload.delta, finishReason: "" };
|
|
36
|
+
const choices = Array.isArray(payload?.choices) ? payload.choices : [];
|
|
37
|
+
if (!choices.length || typeof choices[0] !== "object") return { delta: null, finishReason: "" };
|
|
38
|
+
const c0 = choices[0];
|
|
39
|
+
return {
|
|
40
|
+
delta: c0.delta && typeof c0.delta === "object" ? c0.delta : null,
|
|
41
|
+
finishReason: typeof c0.finish_reason === "string" ? c0.finish_reason : "",
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// tool_calls 分片按 index 聚合(id/type/name/arguments 增量拼接)。
|
|
46
|
+
export function applyToolCallDeltas(st, delta) {
|
|
47
|
+
const rawCalls = delta?.tool_calls;
|
|
48
|
+
if (!Array.isArray(rawCalls)) return;
|
|
49
|
+
rawCalls.forEach((raw, position) => {
|
|
50
|
+
if (!raw || typeof raw !== "object") return;
|
|
51
|
+
const index = typeof raw.index === "number" ? raw.index : position;
|
|
52
|
+
let call = st.calls.get(index);
|
|
53
|
+
if (!call) { call = { index, type: "function", id: "", function: { name: "", arguments: "" } }; st.calls.set(index, call); }
|
|
54
|
+
if (typeof raw.id === "string" && raw.id) call.id = raw.id;
|
|
55
|
+
if (typeof raw.type === "string" && raw.type) call.type = raw.type;
|
|
56
|
+
const fn = raw.function;
|
|
57
|
+
if (fn && typeof fn === "object") {
|
|
58
|
+
if (typeof fn.name === "string") call.function.name += fn.name;
|
|
59
|
+
if (typeof fn.arguments === "string") call.function.arguments += fn.arguments;
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function sortedToolCalls(st) {
|
|
65
|
+
return [...st.calls.keys()].sort((a, b) => a - b).map((i) => {
|
|
66
|
+
const c = st.calls.get(i);
|
|
67
|
+
return { index: c.index, type: c.type || "function", id: c.id, function: { name: c.function.name, arguments: c.function.arguments } };
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const firstText = (payload, keys) => {
|
|
72
|
+
for (const k of keys) if (typeof payload?.[k] === "string") return payload[k];
|
|
73
|
+
return "";
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
function markUsage(st, payload) {
|
|
77
|
+
const p = Number(payload?.prompt_tokens), c = Number(payload?.completion_tokens);
|
|
78
|
+
if (Number.isFinite(p) || Number.isFinite(c)) {
|
|
79
|
+
st.usage = {
|
|
80
|
+
prompt_tokens: Number.isFinite(p) ? p : (st.usage?.prompt_tokens || 0),
|
|
81
|
+
completion_tokens: Number.isFinite(c) ? c : (st.usage?.completion_tokens || 0),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 结构化问答帧判定(对齐 codearts2api isValidStructuredQA):question+answer 必须同时为字符串、
|
|
87
|
+
// 长度受控、answer 不似代码;options 若在场须为 2-10 项数组。防止把整段 JSON 当正文。
|
|
88
|
+
const CODE_HINTS = ["import ", "def ", "class ", "func ", "package ", "module ", "struct ", "interface "];
|
|
89
|
+
export function isValidStructuredQA(obj) {
|
|
90
|
+
if (!obj || typeof obj !== "object") return false;
|
|
91
|
+
const { question, answer, options } = obj;
|
|
92
|
+
if (typeof question !== "string" || typeof answer !== "string") return false;
|
|
93
|
+
if (!question.length || question.length > 500) return false;
|
|
94
|
+
if (!answer.length || answer.length > 100) return false;
|
|
95
|
+
const low = answer.toLowerCase();
|
|
96
|
+
if (CODE_HINTS.some((h) => low.includes(h))) return false;
|
|
97
|
+
if (options !== undefined) {
|
|
98
|
+
if (!Array.isArray(options) || options.length < 2 || options.length > 10) return false;
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function tryStructuredAnswer(st, payload) {
|
|
104
|
+
if (st.content || !isValidStructuredQA(payload)) return;
|
|
105
|
+
st.content = payload.answer;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 单事件应用到聚合状态(对齐 Go applyEvent 的替换/追加语义)。
|
|
109
|
+
export function applyEvent(st, event, data) {
|
|
110
|
+
const ev = String(event || "").trim().toLowerCase();
|
|
111
|
+
const trimmed = String(data || "").trim();
|
|
112
|
+
if (ev === "" && trimmed === "[DONE]") { if (!st.finish) st.finish = "stop"; st.done = true; return; }
|
|
113
|
+
let payload = null;
|
|
114
|
+
if (trimmed && trimmed !== "[DONE]") { try { payload = JSON.parse(trimmed); } catch { payload = null; } }
|
|
115
|
+
|
|
116
|
+
const checkError = () => {
|
|
117
|
+
const code = firstText(payload || {}, ["error_code", "code"]);
|
|
118
|
+
if (code && code !== "0") {
|
|
119
|
+
st.error = { code, msg: firstText(payload || {}, ["error_msg", "message", "msg"]) || "request failed" };
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
return false;
|
|
123
|
+
};
|
|
124
|
+
const applyDeltaLike = (textKeys) => {
|
|
125
|
+
if (checkError()) return true;
|
|
126
|
+
const { delta, finishReason } = deltaFromChunk(payload);
|
|
127
|
+
if (finishReason) st.finish = finishReason;
|
|
128
|
+
// 本帧原生 OpenAI 字段(role/tool_calls/finish)→ 流式层原样转发。
|
|
129
|
+
// 少转 tool_calls 会让客户端收到 finish_reason=tool_calls 却无工具可执行 → 回合空停(真机复现)。
|
|
130
|
+
st.forward = {
|
|
131
|
+
role: delta && typeof delta.role === "string" ? delta.role : "",
|
|
132
|
+
toolCalls: delta && Array.isArray(delta.tool_calls) && delta.tool_calls.length ? delta.tool_calls : null,
|
|
133
|
+
finish: finishReason || "",
|
|
134
|
+
};
|
|
135
|
+
if (delta) {
|
|
136
|
+
applyToolCallDeltas(st, delta);
|
|
137
|
+
if (typeof delta.content === "string" && delta.content) st.content += delta.content;
|
|
138
|
+
if (typeof delta.reasoning_content === "string" && delta.reasoning_content) st.reason += delta.reasoning_content;
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
markUsage(st, payload);
|
|
142
|
+
const t = firstText(payload || {}, textKeys);
|
|
143
|
+
if (t) {
|
|
144
|
+
if (trimmed === "[DONE]" || t === "[DONE]" || /^done$/i.test(t)) { st.finish = "stop"; st.done = true; return true; }
|
|
145
|
+
st.content = t; // 全文快照 → 替换
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
const out = Array.isArray(payload?.output) ? payload.output : null;
|
|
149
|
+
if (out && out.length) {
|
|
150
|
+
const sb = out.filter((x) => x?.type === "output_text" && typeof x.text === "string").map((x) => x.text).join("");
|
|
151
|
+
if (sb) st.content = sb;
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
tryStructuredAnswer(st, payload || {});
|
|
155
|
+
return true;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
switch (ev) {
|
|
159
|
+
case "reasoning": case "thinking": case "onreasoning": case "onthinking": {
|
|
160
|
+
const t = firstText(payload || {}, ["text", "reasoning", "content", "thinking"]);
|
|
161
|
+
if (t) st.reason += t;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
case "done": case "end": case "finish": {
|
|
165
|
+
if (checkError()) return;
|
|
166
|
+
const f = firstText(payload || {}, ["finish_reason", "finish", "reason"]);
|
|
167
|
+
st.finish = f || "stop";
|
|
168
|
+
st.done = true;
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
case "onanswer": case "answer": case "delta": case "message": case "content": case "": case "data": {
|
|
172
|
+
if (trimmed === "[DONE]") { if (!st.finish) st.finish = "stop"; st.done = true; return; }
|
|
173
|
+
applyDeltaLike(ev === "" || ev === "data" ? ["text", "content", "delta"] : ["text", "content", "delta", "message"]);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
default: return; // related_question_answer 等杂帧忽略
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// HTTP 200 内嵌错误 → 状态映射(429/400/502),让网关按状态码走冷却/降级。
|
|
181
|
+
export function embeddedErrorFromData(data) {
|
|
182
|
+
const trimmed = String(data || "").trim();
|
|
183
|
+
if (!trimmed || trimmed === "[DONE]") return null;
|
|
184
|
+
let payload;
|
|
185
|
+
try { payload = JSON.parse(trimmed); } catch { return null; }
|
|
186
|
+
const code = typeof payload?.error_code === "string" ? payload.error_code : "";
|
|
187
|
+
if (!code || code === "0") return null;
|
|
188
|
+
const message = typeof payload?.error_msg === "string" ? payload.error_msg : "";
|
|
189
|
+
const combined = `${code} ${message}`.trim();
|
|
190
|
+
const low = combined.toLowerCase();
|
|
191
|
+
let status = 502;
|
|
192
|
+
if (/429|tm\.00001041|tpm|并发会话/.test(low)) status = 429;
|
|
193
|
+
else if (/002002009|not registered|4004\.200|benefit not found/.test(low)) status = 400;
|
|
194
|
+
return { status, message: combined.slice(0, 300) };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export class UpstreamEventError extends Error {
|
|
198
|
+
constructor(message, { status = 502, code = "" } = {}) {
|
|
199
|
+
super(message);
|
|
200
|
+
this.name = "UpstreamEventError";
|
|
201
|
+
this.status = status;
|
|
202
|
+
this.code = code;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -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
|
+
}
|