one-model-router 0.0.10 → 0.0.12
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/LICENSE +21 -21
- package/README.md +32 -5
- package/bin/omr.js +46 -0
- package/package.json +3 -2
- package/src/admin.js +965 -941
- package/src/balances.js +61 -61
- package/src/boot.js +117 -117
- package/src/channels/buddy.js +2031 -2031
- package/src/channels/cline.js +753 -753
- package/src/channels/codearts.js +2051 -2051
- package/src/channels/comate.js +830 -830
- package/src/channels/doubaowork.js +1784 -1784
- package/src/channels/freebuff.js +1316 -1316
- package/src/channels/gemini.js +1721 -1721
- package/src/channels/index.js +270 -270
- package/src/channels/joycode.js +936 -936
- package/src/channels/kimi.js +572 -572
- package/src/channels/lobsterai.js +1226 -1226
- package/src/channels/loomy.js +1032 -1032
- package/src/channels/miaoshou.js +1396 -1396
- package/src/channels/mimo.js +474 -474
- package/src/channels/minimax.js +1451 -1451
- package/src/channels/qoder-wasm.js +434 -434
- package/src/channels/qoder.js +1619 -1619
- package/src/channels/raccoon.js +1842 -1842
- package/src/channels/tabbit.js +1457 -1457
- package/src/channels/trae.js +1405 -1405
- package/src/channels/zcode-global.js +35 -35
- package/src/channels/zcode.js +2085 -2085
- package/src/checkin.js +496 -496
- package/src/credits.js +464 -464
- package/src/crypto.js +132 -132
- package/src/free-models.js +683 -683
- package/src/gateway.js +596 -578
- package/src/health.js +86 -86
- package/src/model-key.js +35 -35
- package/src/paths.js +96 -96
- package/src/probe.js +318 -318
- package/src/providers/builtin.js +626 -626
- package/src/providers/index.js +483 -457
- package/src/providers/kilo.js +111 -111
- package/src/providers/last-good.js +69 -69
- package/src/providers/modelsdev.js +242 -242
- package/src/providers/openai-compat.js +312 -312
- package/src/providers/opencode/bun-fetch.js +226 -226
- package/src/providers/opencode/lane.js +186 -186
- package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
- package/src/providers/opencode/o2a/asset-source.js +43 -43
- package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
- package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
- package/src/providers/opencode/o2a/entry.js +17 -17
- package/src/providers/opencode/o2a/gateway-body.js +42 -42
- package/src/providers/opencode/o2a/headers.js +133 -133
- package/src/providers/opencode/o2a/identity.js +148 -148
- package/src/providers/opencode/o2a/official-prompt.js +191 -191
- package/src/providers/opencode/o2a/official-tools.js +110 -110
- package/src/providers/opencode/o2a/tool-renames.js +217 -217
- package/src/providers/opencode/o2a/toolshape.js +418 -418
- package/src/providers/opencode/o2a/version.js +37 -37
- package/src/providers/opencode/upstream.js +403 -403
- package/src/providers/opencode/wire.js +496 -496
- package/src/providers/opencode.js +652 -652
- package/src/router.js +629 -629
- package/src/server.js +49 -33
- package/src/store.js +467 -467
- package/src/sync/index.js +1529 -1529
- package/src/sync/login-preload.cjs +52 -52
- package/src/sync/noise.js +141 -141
- package/src/sync/relay-http.js +176 -176
- package/src/sync/remote-host.js +818 -818
- package/src/sync/remote-http.js +112 -112
- package/src/sync/remote-login.js +657 -657
- package/src/sync/remote-pairing.js +204 -204
- package/src/sync/remote-protocol.js +321 -321
- package/src/sync/snapshot.js +211 -211
- package/src/update.js +458 -0
- package/src/util.js +334 -334
- package/web/app.js +4010 -3972
- package/web/index.html +32 -32
- package/web/style.css +971 -971
|
@@ -1,434 +1,434 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Qoder 内嵌 WASM(`qoder_auth_wasm`)的 wasm-bindgen 桥。
|
|
3
|
-
*
|
|
4
|
-
* ## 为什么需要它
|
|
5
|
-
*
|
|
6
|
-
* Qoder 客户端的**真实**推理不走公开的 OpenAI 兼容端点,而是走**加密端点**:
|
|
7
|
-
*
|
|
8
|
-
* POST {host}/algo/api/v2/service/pro/sse/agent_chat_generation
|
|
9
|
-
* ?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1
|
|
10
|
-
* body: <由本 WASM 加密>
|
|
11
|
-
*
|
|
12
|
-
* 服务端认的是**模型目录里的 key**(`qfmodel` / `dmodel` / …),
|
|
13
|
-
* 公开端点只认一小撮通用名。本模块把客户端内嵌的 WASM
|
|
14
|
-
* (`qoder-auth-wasm.wasm`,298KB,随实现分发)按 wasm-bindgen 约定接起来,
|
|
15
|
-
* 用它生成加密请求体 —— 等同「用客户端自己的钥匙开自己的锁」。
|
|
16
|
-
*
|
|
17
|
-
* ## ⚠️ 三个实测踩过的坑(改动时务必保留)
|
|
18
|
-
*
|
|
19
|
-
* 1. **两个 `getRandomValues` import 的签名方向相反**:
|
|
20
|
-
* `_d49329ff89a07af1` 写 **wasm 内存**、`_c44a50d8cfdaebeb` 调 **JS 对象**。
|
|
21
|
-
* 写反会得到 Rust panic `unreachable`。
|
|
22
|
-
* 2. **返回值布局有两套**:字符串类为 `ptr/len/valIdx/isErr`,
|
|
23
|
-
* 而 `qodercontext_new` / `prepareInferRequest` 为 `ptr/errIdx/isErr`。
|
|
24
|
-
* 混用会得到 `null pointer passed to rust`。
|
|
25
|
-
* 3. **`requestresult_url(栈指针, ptr)` 参数顺序与直觉相反**(栈指针在前)。
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
import { readFileSync } from 'node:fs'
|
|
29
|
-
import { fileURLToPath } from 'node:url'
|
|
30
|
-
import { dirname, resolve } from 'node:path'
|
|
31
|
-
import { randomUUID } from 'node:crypto'
|
|
32
|
-
|
|
33
|
-
/** WASM 文件路径(与本文件同目录,随实现分发)。 */
|
|
34
|
-
const WASM_PATH = resolve(dirname(fileURLToPath(import.meta.url)), 'qoder-auth-wasm.wasm')
|
|
35
|
-
|
|
36
|
-
/** 客户端版本与产品标识(与 Qoder 产品配置保持一致)。 */
|
|
37
|
-
const COSY_VERSION = '1.1.49'
|
|
38
|
-
|
|
39
|
-
/** wasm-bindgen 生成的 import 对象名(WASM 里 embed,必须完全一致)。 */
|
|
40
|
-
const IMPORT_MODULE = './qoder_auth_wasm_bg.js'
|
|
41
|
-
|
|
42
|
-
// ── 明文请求体构造 ───────────────────────────────────────────────────────────
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* 单条待发送消息。
|
|
46
|
-
* - `content` 通常是字符串;带图片的消息是多模态数组(图片不走 chat_context.imageUrls)。
|
|
47
|
-
* - `tool_calls` 只出现在 assistant 上;`tool_call_id` 只出现在 role:'tool' 上。
|
|
48
|
-
* 三者缺一不可:只发工具结果而不发对应 assistant tool_calls 会让模型
|
|
49
|
-
* 看不到自己调用过什么。
|
|
50
|
-
*/
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* 构造加密端点 `agent_chat_generation` 的明文请求体。
|
|
54
|
-
* ⚠️ 结构按官方实现:`chat_context` 不能传空对象、
|
|
55
|
-
* `business` 缺失会被路由到故障节点 `oa_qwen-plus-2025-04-28`(Execution failed)。
|
|
56
|
-
*
|
|
57
|
-
* @param ask - { modelKey, userText, systemText?, isReasoning?, history?, maxTokens?,
|
|
58
|
-
* reasoningEffort?, source?, isVl?, contextWindow?, displayName?,
|
|
59
|
-
* format?, maxInputTokens?, sessionType?, business?, tools? }
|
|
60
|
-
* @param requestId - 请求 id(默认随机;测试可固定以求确定性)
|
|
61
|
-
*/
|
|
62
|
-
export function buildQoderInferPayload(ask, requestId = randomUUID()) {
|
|
63
|
-
const isReasoning = ask.isReasoning ?? false
|
|
64
|
-
const text = ask.userText
|
|
65
|
-
|
|
66
|
-
const parameters = {}
|
|
67
|
-
if (ask.maxTokens !== undefined) parameters.max_tokens = ask.maxTokens
|
|
68
|
-
if (ask.reasoningEffort !== undefined) {
|
|
69
|
-
parameters.reasoning_effort = ask.reasoningEffort
|
|
70
|
-
parameters.enable_thinking = ask.reasoningEffort !== 'none'
|
|
71
|
-
}
|
|
72
|
-
if (ask.contextWindow !== undefined) parameters.context_length = ask.contextWindow
|
|
73
|
-
|
|
74
|
-
const messages = []
|
|
75
|
-
for (const m of ask.history ?? []) {
|
|
76
|
-
// 逐字段搬运而非整体展开:只保留协议认识的键,避免把调用方的内部字段发给上游
|
|
77
|
-
messages.push({
|
|
78
|
-
role: m.role,
|
|
79
|
-
content: m.content,
|
|
80
|
-
...(m.tool_calls === undefined ? {} : { tool_calls: m.tool_calls }),
|
|
81
|
-
...(m.tool_call_id === undefined ? {} : { tool_call_id: m.tool_call_id }),
|
|
82
|
-
})
|
|
83
|
-
}
|
|
84
|
-
if (messages.length === 0) messages.push({ role: 'user', content: text })
|
|
85
|
-
|
|
86
|
-
return {
|
|
87
|
-
request_id: requestId,
|
|
88
|
-
request_set_id: requestId,
|
|
89
|
-
chat_record_id: requestId,
|
|
90
|
-
session_id: randomUUID(),
|
|
91
|
-
stream: true,
|
|
92
|
-
chat_task: 'FREE_INPUT',
|
|
93
|
-
chat_context: {
|
|
94
|
-
text,
|
|
95
|
-
features: [],
|
|
96
|
-
extra: {
|
|
97
|
-
context: [],
|
|
98
|
-
modelConfig: { key: ask.modelKey, is_reasoning: isReasoning },
|
|
99
|
-
originalContent: text,
|
|
100
|
-
},
|
|
101
|
-
chatPrompt: '',
|
|
102
|
-
imageUrls: null,
|
|
103
|
-
},
|
|
104
|
-
is_reply: true,
|
|
105
|
-
is_retry: false,
|
|
106
|
-
source: 1,
|
|
107
|
-
version: '3',
|
|
108
|
-
agent_id: 'agent_common',
|
|
109
|
-
task_id: 'common',
|
|
110
|
-
session_type: ask.sessionType ?? 'qodercli',
|
|
111
|
-
aliyun_user_type: '',
|
|
112
|
-
model_config: {
|
|
113
|
-
key: ask.modelKey,
|
|
114
|
-
// 官方 model_config 有 10 个字段,此处逐项对齐
|
|
115
|
-
display_name: ask.displayName ?? '',
|
|
116
|
-
model: '',
|
|
117
|
-
format: ask.format ?? 'openai',
|
|
118
|
-
is_vl: ask.isVl ?? true,
|
|
119
|
-
is_reasoning: isReasoning,
|
|
120
|
-
api_key: '',
|
|
121
|
-
url: '',
|
|
122
|
-
max_input_tokens: ask.maxInputTokens ?? ask.contextWindow ?? 200_000,
|
|
123
|
-
},
|
|
124
|
-
custom_model: null,
|
|
125
|
-
system: ask.systemText ? [{ type: 'text', text: ask.systemText }] : [],
|
|
126
|
-
messages,
|
|
127
|
-
// ⚠️ 顶层 `tools` 必须真的下发(客户端源码 tools: o?.tools ?? []);
|
|
128
|
-
// 无工具时是空数组而非缺字段(与客户端一致)
|
|
129
|
-
tools: ask.tools ?? [],
|
|
130
|
-
parameters,
|
|
131
|
-
// `business` 决定服务端路由(sec_scan → 安全池,其余 → 默认池)
|
|
132
|
-
...(ask.business === undefined ? {} : { business: ask.business }),
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// ── WASM glue(变量名沿用 wasm-bindgen 生成约定,便于与官方产物对照)────────
|
|
137
|
-
|
|
138
|
-
/** 已实例化的 glue(每进程一份,WASM 实例无状态可复用)。 */
|
|
139
|
-
let gluePromise = null
|
|
140
|
-
|
|
141
|
-
function getGlue() {
|
|
142
|
-
gluePromise ??= createGlue()
|
|
143
|
-
return gluePromise
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** 真正实例化 WASM 并接好 import。 */
|
|
147
|
-
async function createGlue() {
|
|
148
|
-
const bytes = readFileSync(WASM_PATH)
|
|
149
|
-
const compiled = await WebAssembly.compile(bytes)
|
|
150
|
-
|
|
151
|
-
let exports = {}
|
|
152
|
-
let cachedHeap = null
|
|
153
|
-
let cachedView = null
|
|
154
|
-
|
|
155
|
-
const decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true })
|
|
156
|
-
const encoder = new TextEncoder()
|
|
157
|
-
|
|
158
|
-
const heap = () => {
|
|
159
|
-
if (cachedHeap === null || cachedHeap.byteLength === 0) {
|
|
160
|
-
cachedHeap = new Uint8Array(exports.memory.buffer)
|
|
161
|
-
}
|
|
162
|
-
return cachedHeap
|
|
163
|
-
}
|
|
164
|
-
const view = () => {
|
|
165
|
-
if (cachedView === null || cachedView.buffer !== exports.memory.buffer) {
|
|
166
|
-
cachedView = new DataView(exports.memory.buffer)
|
|
167
|
-
}
|
|
168
|
-
return cachedView
|
|
169
|
-
}
|
|
170
|
-
const readString = (ptr, len) => decoder.decode(heap().subarray(ptr >>> 0, (ptr >>> 0) + len))
|
|
171
|
-
|
|
172
|
-
// 对象堆(与官方 wW 一致:1024 个 undefined,再 push 四个哨兵)
|
|
173
|
-
const objects = new Array(1024).fill(undefined)
|
|
174
|
-
objects.push(undefined, null, true, false)
|
|
175
|
-
let firstFree = objects.length
|
|
176
|
-
const heapObject = index => objects[index]
|
|
177
|
-
const pushObject = value => {
|
|
178
|
-
if (firstFree === objects.length) objects.push(objects.length + 1)
|
|
179
|
-
const index = firstFree
|
|
180
|
-
firstFree = objects[index]
|
|
181
|
-
objects[index] = value
|
|
182
|
-
return index
|
|
183
|
-
}
|
|
184
|
-
const takeObject = index => {
|
|
185
|
-
const value = heapObject(index)
|
|
186
|
-
// 索引 < 1028 是哨兵(undefined/null/true/false),不可回收
|
|
187
|
-
if (index >= 1028) {
|
|
188
|
-
objects[index] = firstFree
|
|
189
|
-
firstFree = index
|
|
190
|
-
}
|
|
191
|
-
return value
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
let lastLength = 0
|
|
195
|
-
const writeString = text => {
|
|
196
|
-
const encoded = encoder.encode(text)
|
|
197
|
-
const ptr = exports.__wbindgen_export2(encoded.length, 1) >>> 0
|
|
198
|
-
heap().subarray(ptr, ptr + encoded.length).set(encoded)
|
|
199
|
-
lastLength = encoded.length
|
|
200
|
-
return ptr
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
// 字符串返回值布局:ptr/len/valIdx/isErr
|
|
204
|
-
const callString = invoke => {
|
|
205
|
-
let ptr = 0
|
|
206
|
-
let len = 0
|
|
207
|
-
const stack = exports.__wbindgen_add_to_stack_pointer(-16)
|
|
208
|
-
try {
|
|
209
|
-
invoke(stack)
|
|
210
|
-
const v = view()
|
|
211
|
-
ptr = v.getInt32(stack + 0, true)
|
|
212
|
-
len = v.getInt32(stack + 4, true)
|
|
213
|
-
const isError = v.getInt32(stack + 12, true)
|
|
214
|
-
if (isError) throw takeObject(v.getInt32(stack + 8, true))
|
|
215
|
-
return readString(ptr, len)
|
|
216
|
-
} finally {
|
|
217
|
-
exports.__wbindgen_add_to_stack_pointer(16)
|
|
218
|
-
if (ptr) exports.__wbindgen_export4(ptr, len, 1)
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
// 原始指针返回值布局:ptr/errIdx/isErr
|
|
223
|
-
const callPointer = invoke => {
|
|
224
|
-
const stack = exports.__wbindgen_add_to_stack_pointer(-16)
|
|
225
|
-
try {
|
|
226
|
-
invoke(stack)
|
|
227
|
-
const v = view()
|
|
228
|
-
const ptr = v.getInt32(stack + 0, true)
|
|
229
|
-
const isError = v.getInt32(stack + 8, true)
|
|
230
|
-
if (isError) throw takeObject(v.getInt32(stack + 4, true))
|
|
231
|
-
return ptr
|
|
232
|
-
} finally {
|
|
233
|
-
exports.__wbindgen_add_to_stack_pointer(16)
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// wasm-bindgen 的「调用 JS 函数并捕获异常」包装
|
|
238
|
-
const guard = (fn, args) => {
|
|
239
|
-
try {
|
|
240
|
-
fn(...args)
|
|
241
|
-
} catch (error) {
|
|
242
|
-
exports.__wbindgen_export(pushObject(error))
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
const imports = {
|
|
247
|
-
__wbindgen_object_drop_ref: a => takeObject(a),
|
|
248
|
-
__wbindgen_object_clone_ref: a => pushObject(heapObject(a)),
|
|
249
|
-
__wbindgen_cast_0000000000000001: (a, e) => pushObject(heap().subarray(a >>> 0, (a >>> 0) + e)),
|
|
250
|
-
__wbindgen_cast_0000000000000002: (a, e) => pushObject(readString(a, e)),
|
|
251
|
-
__wbg_set_08463b1df38a7e29: (a, e, t) =>
|
|
252
|
-
pushObject(heapObject(a).set(heapObject(e), heapObject(t))),
|
|
253
|
-
// ⚠️ 这两个签名方向相反:一个写 wasm 内存,一个调 JS 对象。写反会 Rust panic。
|
|
254
|
-
__wbg_getRandomValues_d49329ff89a07af1: (...a) =>
|
|
255
|
-
guard((x, y) => { globalThis.crypto.getRandomValues(heap().subarray(x >>> 0, (x >>> 0) + y)) }, a),
|
|
256
|
-
__wbg_getRandomValues_c44a50d8cfdaebeb: (...a) =>
|
|
257
|
-
guard((x, y) => { heapObject(x).getRandomValues(heapObject(y)) }, a),
|
|
258
|
-
__wbg_crypto_38df2bab126b63dc: a => pushObject(heapObject(a).crypto),
|
|
259
|
-
__wbg_process_44c7a14e11e9f69e: a => pushObject(heapObject(a).process),
|
|
260
|
-
__wbg_versions_276b2795b1c6a219: a => pushObject(heapObject(a).versions),
|
|
261
|
-
__wbg_node_84ea875411254db1: a => pushObject(heapObject(a).node),
|
|
262
|
-
__wbg_require_b4edbdcf3e2a1ef0: (...a) => guard(() => pushObject(compiled), a),
|
|
263
|
-
__wbg_msCrypto_bd5a034af96bcba6: a => pushObject(heapObject(a).msCrypto),
|
|
264
|
-
__wbg_randomFillSync_6c25eac9869eb53c: (...a) =>
|
|
265
|
-
guard((x, y) => { heapObject(x).randomFillSync(takeObject(y)) }, a),
|
|
266
|
-
__wbg_call_d578befcc3145dee: (...a) =>
|
|
267
|
-
guard((fn, self, arg) => { pushObject(heapObject(fn).call(heapObject(self), heapObject(arg))) }, a),
|
|
268
|
-
__wbg_new_with_length_9cedd08484b73942: a => pushObject(new Uint8Array(a >>> 0)),
|
|
269
|
-
__wbg_length_0c32cb8543c8e4c8: a => heapObject(a).length,
|
|
270
|
-
__wbg_prototypesetcall_3e05eb9545565046: (a, e, t) => {
|
|
271
|
-
Uint8Array.prototype.set.call(heap().subarray(a >>> 0, (a >>> 0) + e), heapObject(t))
|
|
272
|
-
},
|
|
273
|
-
__wbg_subarray_0f98d3fb634508ad: (a, e, t) => pushObject(heapObject(a).subarray(e >>> 0, t >>> 0)),
|
|
274
|
-
__wbg_new_99cabae501c0a8a0: () => pushObject(new Map()),
|
|
275
|
-
__wbg_now_88621c9c9a4f3ffc: () => Date.now(),
|
|
276
|
-
__wbg_static_accessor_GLOBAL_THIS_a1248013d790bf5f: () => pushObject(globalThis),
|
|
277
|
-
__wbg_static_accessor_GLOBAL_f2e0f995a21329ff: () => pushObject(globalThis),
|
|
278
|
-
__wbg_static_accessor_SELF_24f78b6d23f286ea: () => (globalThis.self === undefined ? 0 : pushObject(globalThis.self)),
|
|
279
|
-
__wbg_static_accessor_WINDOW_59fd959c540fe405: () => (globalThis.window === undefined ? 0 : pushObject(globalThis.window)),
|
|
280
|
-
__wbg___wbindgen_throw_81fc77679af83bc6: (p, l) => { throw new Error(readString(p, l)) },
|
|
281
|
-
__wbg_Error_2e59b1b37a9a34c3: (p, l) => pushObject(new Error(readString(p, l))),
|
|
282
|
-
__wbg___wbindgen_is_object_40c5a80572e8f9d3: id => {
|
|
283
|
-
const v = heapObject(id)
|
|
284
|
-
return typeof v === 'object' && v !== null
|
|
285
|
-
},
|
|
286
|
-
__wbg___wbindgen_is_string_b29b5c5a8065ba1a: id => typeof heapObject(id) === 'string',
|
|
287
|
-
__wbg___wbindgen_is_function_49868bde5eb1e745: id => typeof heapObject(id) === 'function',
|
|
288
|
-
__wbg___wbindgen_is_undefined_c0cca72b82b86f4d: id => heapObject(id) === undefined,
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
const instance = await WebAssembly.instantiate(compiled, { [IMPORT_MODULE]: imports })
|
|
292
|
-
exports = instance.exports
|
|
293
|
-
|
|
294
|
-
return { exports, heap, view, readString, writeString, lastLength: () => lastLength, heapObject, pushObject, takeObject, callString, callPointer }
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
/** 生成运行时鉴权字段(encrypt_user_info / key)—— 服务端识别身份的依据。 */
|
|
298
|
-
export async function generateRuntimeAuthFields(user) {
|
|
299
|
-
const g = await getGlue()
|
|
300
|
-
const payload = JSON.stringify({
|
|
301
|
-
uid: user.uid,
|
|
302
|
-
security_oauth_token: user.securityOauthToken,
|
|
303
|
-
organization_id: user.organizationId ?? '',
|
|
304
|
-
organization_tags: user.organizationTags ?? [],
|
|
305
|
-
data_policy_agreed: user.dataPolicyAgreed ?? false,
|
|
306
|
-
})
|
|
307
|
-
const raw = g.callString(stack => {
|
|
308
|
-
const a = g.writeString(payload)
|
|
309
|
-
g.exports.generate_runtime_auth_fields(stack, a, g.lastLength())
|
|
310
|
-
})
|
|
311
|
-
return JSON.parse(raw)
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* Qoder 加密推理客户端。持有 WASM 上下文与运行时鉴权字段,反复生成加密推理请求。
|
|
316
|
-
* 实例不是线程安全的;一个账号一个实例即可。
|
|
317
|
-
*/
|
|
318
|
-
export class QoderEncryptedInfer {
|
|
319
|
-
constructor(g, context, host) {
|
|
320
|
-
this.g = g
|
|
321
|
-
this.context = context
|
|
322
|
-
this.host = host
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/**
|
|
326
|
-
* 创建客户端(调 WASM 构造 QoderContext)。
|
|
327
|
-
* ⚠️ host 必须是加密端点所在 host(国际版 api2.qoder.sh / 国内版 gateway.qoder.com.cn);
|
|
328
|
-
* 传公开端点的 host(api2-v2.qoder.sh)会 404。
|
|
329
|
-
*/
|
|
330
|
-
static async create({ user, machineId, metadata, host, clientVersion }) {
|
|
331
|
-
const g = await getGlue()
|
|
332
|
-
const fields = await generateRuntimeAuthFields(user)
|
|
333
|
-
const version = clientVersion ?? COSY_VERSION
|
|
334
|
-
|
|
335
|
-
const userInfoJson = JSON.stringify({
|
|
336
|
-
uid: user.uid,
|
|
337
|
-
encrypt_user_info: fields.encrypt_user_info,
|
|
338
|
-
key: fields.key,
|
|
339
|
-
organization_id: user.organizationId ?? '',
|
|
340
|
-
organization_tags: user.organizationTags ?? [],
|
|
341
|
-
data_policy_agreed: user.dataPolicyAgreed ?? false,
|
|
342
|
-
})
|
|
343
|
-
|
|
344
|
-
const context = g.callPointer(stack => {
|
|
345
|
-
const machine = g.writeString(machineId); const machineLen = g.lastLength()
|
|
346
|
-
const ver = g.writeString(version); const verLen = g.lastLength()
|
|
347
|
-
const info = g.writeString(userInfoJson); const infoLen = g.lastLength()
|
|
348
|
-
const meta = g.writeString(JSON.stringify(metadata)); const metaLen = g.lastLength()
|
|
349
|
-
// 参数顺序:(sp, machineId, len, version, len, userInfo, len, clientMeta, len)
|
|
350
|
-
g.exports.qodercontext_new(stack, machine, machineLen, ver, verLen, info, infoLen, meta, metaLen)
|
|
351
|
-
})
|
|
352
|
-
|
|
353
|
-
return new QoderEncryptedInfer(g, context, host)
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/** 读取 requestresult 的 url / body / headers(三者共用一套栈式返回布局)。 */
|
|
357
|
-
readRequestResult(result) {
|
|
358
|
-
const g = this.g
|
|
359
|
-
const readString = (name) => {
|
|
360
|
-
const fn = g.exports[name]
|
|
361
|
-
let out = ''
|
|
362
|
-
const v = g.view()
|
|
363
|
-
const stack = g.exports.__wbindgen_add_to_stack_pointer(-16)
|
|
364
|
-
try {
|
|
365
|
-
// ⚠️ 参数顺序:(栈指针, ptr) —— 与直觉相反
|
|
366
|
-
fn(stack, result)
|
|
367
|
-
const ptr = v.getInt32(stack + 0, true)
|
|
368
|
-
const len = v.getInt32(stack + 4, true)
|
|
369
|
-
out = ptr ? g.readString(ptr, len) : ''
|
|
370
|
-
} finally {
|
|
371
|
-
g.exports.__wbindgen_add_to_stack_pointer(16)
|
|
372
|
-
}
|
|
373
|
-
return out
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
const headerMap = g.takeObject(g.exports.requestresult_headers(result))
|
|
377
|
-
const headers = {}
|
|
378
|
-
if (headerMap instanceof Map) {
|
|
379
|
-
for (const [k, v] of headerMap) headers[String(k)] = String(v)
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
return { url: readString('requestresult_url'), headers, body: readString('requestresult_body') }
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
/**
|
|
386
|
-
* 构造带网络契约签名的普通 API 请求(url / headers / body)。
|
|
387
|
-
*
|
|
388
|
-
* 参数顺序实测确定:`(host, path, method, authMode, body, extraHeadersJson)`。
|
|
389
|
-
* - `authMode === 'auth'` → 追加 COSY 签名头(Authorization/Cosy-Date/Cosy-Key/…),
|
|
390
|
-
* 模型目录 `/api/v2/model/list` 必须用它;不传则是裸 Cosy-* 头,服务端回
|
|
391
|
-
* `403 Signature invalid`。
|
|
392
|
-
* - `authMode === 'sign'` → 追加 Appcode/Signature 头(阿里 appcode 契约)。
|
|
393
|
-
* - 其余值不做签名。
|
|
394
|
-
* - 返回的 url 不含协议,网关固定为 `https://`(WASM 只在 host 前拼 `/algo`)。
|
|
395
|
-
* - `extraHeadersJson` 必须是合法 JSON 对象,否则 WASM 报
|
|
396
|
-
* `Invalid extra headers: EOF while parsing a value`。
|
|
397
|
-
*/
|
|
398
|
-
prepareRequest({ host = this.host, path, method = 'GET', auth = '', body = '', headers = {} }) {
|
|
399
|
-
const g = this.g
|
|
400
|
-
const bareHost = String(host).replace(/^https?:\/\//, '')
|
|
401
|
-
const result = g.callPointer(stack => {
|
|
402
|
-
const args = [stack, this.context]
|
|
403
|
-
for (const s of [bareHost, path, method, auth, body, JSON.stringify(headers)]) {
|
|
404
|
-
args.push(g.writeString(s), g.lastLength())
|
|
405
|
-
}
|
|
406
|
-
args.length = 14
|
|
407
|
-
while (args.length < 14) args.push(0)
|
|
408
|
-
g.exports.qodercontext_prepareRequest(...args)
|
|
409
|
-
})
|
|
410
|
-
|
|
411
|
-
const out = this.readRequestResult(result)
|
|
412
|
-
return { ...out, url: `https://${out.url}` }
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* 构造加密推理请求(url / headers / body)。
|
|
417
|
-
* ⚠️ 返回的 headers 必须原样透传:Authorization 是 WASM 生成的
|
|
418
|
-
* `Bearer COSY.<载荷>.<签名>`,用普通 Bearer 覆盖会 403 Signature invalid。
|
|
419
|
-
*/
|
|
420
|
-
prepareInfer(ask) {
|
|
421
|
-
const g = this.g
|
|
422
|
-
const payload = buildQoderInferPayload(ask)
|
|
423
|
-
|
|
424
|
-
const result = g.callPointer(stack => {
|
|
425
|
-
const host = g.writeString(this.host); const hostLen = g.lastLength()
|
|
426
|
-
const body = g.writeString(JSON.stringify(payload)); const bodyLen = g.lastLength()
|
|
427
|
-
const key = g.writeString(ask.modelKey); const keyLen = g.lastLength()
|
|
428
|
-
const source = g.writeString(ask.source ?? 'system'); const sourceLen = g.lastLength()
|
|
429
|
-
g.exports.qodercontext_prepareInferRequest(stack, this.context, host, hostLen, body, bodyLen, key, keyLen, source, sourceLen)
|
|
430
|
-
})
|
|
431
|
-
|
|
432
|
-
return this.readRequestResult(result)
|
|
433
|
-
}
|
|
434
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Qoder 内嵌 WASM(`qoder_auth_wasm`)的 wasm-bindgen 桥。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么需要它
|
|
5
|
+
*
|
|
6
|
+
* Qoder 客户端的**真实**推理不走公开的 OpenAI 兼容端点,而是走**加密端点**:
|
|
7
|
+
*
|
|
8
|
+
* POST {host}/algo/api/v2/service/pro/sse/agent_chat_generation
|
|
9
|
+
* ?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1
|
|
10
|
+
* body: <由本 WASM 加密>
|
|
11
|
+
*
|
|
12
|
+
* 服务端认的是**模型目录里的 key**(`qfmodel` / `dmodel` / …),
|
|
13
|
+
* 公开端点只认一小撮通用名。本模块把客户端内嵌的 WASM
|
|
14
|
+
* (`qoder-auth-wasm.wasm`,298KB,随实现分发)按 wasm-bindgen 约定接起来,
|
|
15
|
+
* 用它生成加密请求体 —— 等同「用客户端自己的钥匙开自己的锁」。
|
|
16
|
+
*
|
|
17
|
+
* ## ⚠️ 三个实测踩过的坑(改动时务必保留)
|
|
18
|
+
*
|
|
19
|
+
* 1. **两个 `getRandomValues` import 的签名方向相反**:
|
|
20
|
+
* `_d49329ff89a07af1` 写 **wasm 内存**、`_c44a50d8cfdaebeb` 调 **JS 对象**。
|
|
21
|
+
* 写反会得到 Rust panic `unreachable`。
|
|
22
|
+
* 2. **返回值布局有两套**:字符串类为 `ptr/len/valIdx/isErr`,
|
|
23
|
+
* 而 `qodercontext_new` / `prepareInferRequest` 为 `ptr/errIdx/isErr`。
|
|
24
|
+
* 混用会得到 `null pointer passed to rust`。
|
|
25
|
+
* 3. **`requestresult_url(栈指针, ptr)` 参数顺序与直觉相反**(栈指针在前)。
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { readFileSync } from 'node:fs'
|
|
29
|
+
import { fileURLToPath } from 'node:url'
|
|
30
|
+
import { dirname, resolve } from 'node:path'
|
|
31
|
+
import { randomUUID } from 'node:crypto'
|
|
32
|
+
|
|
33
|
+
/** WASM 文件路径(与本文件同目录,随实现分发)。 */
|
|
34
|
+
const WASM_PATH = resolve(dirname(fileURLToPath(import.meta.url)), 'qoder-auth-wasm.wasm')
|
|
35
|
+
|
|
36
|
+
/** 客户端版本与产品标识(与 Qoder 产品配置保持一致)。 */
|
|
37
|
+
const COSY_VERSION = '1.1.49'
|
|
38
|
+
|
|
39
|
+
/** wasm-bindgen 生成的 import 对象名(WASM 里 embed,必须完全一致)。 */
|
|
40
|
+
const IMPORT_MODULE = './qoder_auth_wasm_bg.js'
|
|
41
|
+
|
|
42
|
+
// ── 明文请求体构造 ───────────────────────────────────────────────────────────
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 单条待发送消息。
|
|
46
|
+
* - `content` 通常是字符串;带图片的消息是多模态数组(图片不走 chat_context.imageUrls)。
|
|
47
|
+
* - `tool_calls` 只出现在 assistant 上;`tool_call_id` 只出现在 role:'tool' 上。
|
|
48
|
+
* 三者缺一不可:只发工具结果而不发对应 assistant tool_calls 会让模型
|
|
49
|
+
* 看不到自己调用过什么。
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 构造加密端点 `agent_chat_generation` 的明文请求体。
|
|
54
|
+
* ⚠️ 结构按官方实现:`chat_context` 不能传空对象、
|
|
55
|
+
* `business` 缺失会被路由到故障节点 `oa_qwen-plus-2025-04-28`(Execution failed)。
|
|
56
|
+
*
|
|
57
|
+
* @param ask - { modelKey, userText, systemText?, isReasoning?, history?, maxTokens?,
|
|
58
|
+
* reasoningEffort?, source?, isVl?, contextWindow?, displayName?,
|
|
59
|
+
* format?, maxInputTokens?, sessionType?, business?, tools? }
|
|
60
|
+
* @param requestId - 请求 id(默认随机;测试可固定以求确定性)
|
|
61
|
+
*/
|
|
62
|
+
export function buildQoderInferPayload(ask, requestId = randomUUID()) {
|
|
63
|
+
const isReasoning = ask.isReasoning ?? false
|
|
64
|
+
const text = ask.userText
|
|
65
|
+
|
|
66
|
+
const parameters = {}
|
|
67
|
+
if (ask.maxTokens !== undefined) parameters.max_tokens = ask.maxTokens
|
|
68
|
+
if (ask.reasoningEffort !== undefined) {
|
|
69
|
+
parameters.reasoning_effort = ask.reasoningEffort
|
|
70
|
+
parameters.enable_thinking = ask.reasoningEffort !== 'none'
|
|
71
|
+
}
|
|
72
|
+
if (ask.contextWindow !== undefined) parameters.context_length = ask.contextWindow
|
|
73
|
+
|
|
74
|
+
const messages = []
|
|
75
|
+
for (const m of ask.history ?? []) {
|
|
76
|
+
// 逐字段搬运而非整体展开:只保留协议认识的键,避免把调用方的内部字段发给上游
|
|
77
|
+
messages.push({
|
|
78
|
+
role: m.role,
|
|
79
|
+
content: m.content,
|
|
80
|
+
...(m.tool_calls === undefined ? {} : { tool_calls: m.tool_calls }),
|
|
81
|
+
...(m.tool_call_id === undefined ? {} : { tool_call_id: m.tool_call_id }),
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
if (messages.length === 0) messages.push({ role: 'user', content: text })
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
request_id: requestId,
|
|
88
|
+
request_set_id: requestId,
|
|
89
|
+
chat_record_id: requestId,
|
|
90
|
+
session_id: randomUUID(),
|
|
91
|
+
stream: true,
|
|
92
|
+
chat_task: 'FREE_INPUT',
|
|
93
|
+
chat_context: {
|
|
94
|
+
text,
|
|
95
|
+
features: [],
|
|
96
|
+
extra: {
|
|
97
|
+
context: [],
|
|
98
|
+
modelConfig: { key: ask.modelKey, is_reasoning: isReasoning },
|
|
99
|
+
originalContent: text,
|
|
100
|
+
},
|
|
101
|
+
chatPrompt: '',
|
|
102
|
+
imageUrls: null,
|
|
103
|
+
},
|
|
104
|
+
is_reply: true,
|
|
105
|
+
is_retry: false,
|
|
106
|
+
source: 1,
|
|
107
|
+
version: '3',
|
|
108
|
+
agent_id: 'agent_common',
|
|
109
|
+
task_id: 'common',
|
|
110
|
+
session_type: ask.sessionType ?? 'qodercli',
|
|
111
|
+
aliyun_user_type: '',
|
|
112
|
+
model_config: {
|
|
113
|
+
key: ask.modelKey,
|
|
114
|
+
// 官方 model_config 有 10 个字段,此处逐项对齐
|
|
115
|
+
display_name: ask.displayName ?? '',
|
|
116
|
+
model: '',
|
|
117
|
+
format: ask.format ?? 'openai',
|
|
118
|
+
is_vl: ask.isVl ?? true,
|
|
119
|
+
is_reasoning: isReasoning,
|
|
120
|
+
api_key: '',
|
|
121
|
+
url: '',
|
|
122
|
+
max_input_tokens: ask.maxInputTokens ?? ask.contextWindow ?? 200_000,
|
|
123
|
+
},
|
|
124
|
+
custom_model: null,
|
|
125
|
+
system: ask.systemText ? [{ type: 'text', text: ask.systemText }] : [],
|
|
126
|
+
messages,
|
|
127
|
+
// ⚠️ 顶层 `tools` 必须真的下发(客户端源码 tools: o?.tools ?? []);
|
|
128
|
+
// 无工具时是空数组而非缺字段(与客户端一致)
|
|
129
|
+
tools: ask.tools ?? [],
|
|
130
|
+
parameters,
|
|
131
|
+
// `business` 决定服务端路由(sec_scan → 安全池,其余 → 默认池)
|
|
132
|
+
...(ask.business === undefined ? {} : { business: ask.business }),
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ── WASM glue(变量名沿用 wasm-bindgen 生成约定,便于与官方产物对照)────────
|
|
137
|
+
|
|
138
|
+
/** 已实例化的 glue(每进程一份,WASM 实例无状态可复用)。 */
|
|
139
|
+
let gluePromise = null
|
|
140
|
+
|
|
141
|
+
function getGlue() {
|
|
142
|
+
gluePromise ??= createGlue()
|
|
143
|
+
return gluePromise
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 真正实例化 WASM 并接好 import。 */
|
|
147
|
+
async function createGlue() {
|
|
148
|
+
const bytes = readFileSync(WASM_PATH)
|
|
149
|
+
const compiled = await WebAssembly.compile(bytes)
|
|
150
|
+
|
|
151
|
+
let exports = {}
|
|
152
|
+
let cachedHeap = null
|
|
153
|
+
let cachedView = null
|
|
154
|
+
|
|
155
|
+
const decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true })
|
|
156
|
+
const encoder = new TextEncoder()
|
|
157
|
+
|
|
158
|
+
const heap = () => {
|
|
159
|
+
if (cachedHeap === null || cachedHeap.byteLength === 0) {
|
|
160
|
+
cachedHeap = new Uint8Array(exports.memory.buffer)
|
|
161
|
+
}
|
|
162
|
+
return cachedHeap
|
|
163
|
+
}
|
|
164
|
+
const view = () => {
|
|
165
|
+
if (cachedView === null || cachedView.buffer !== exports.memory.buffer) {
|
|
166
|
+
cachedView = new DataView(exports.memory.buffer)
|
|
167
|
+
}
|
|
168
|
+
return cachedView
|
|
169
|
+
}
|
|
170
|
+
const readString = (ptr, len) => decoder.decode(heap().subarray(ptr >>> 0, (ptr >>> 0) + len))
|
|
171
|
+
|
|
172
|
+
// 对象堆(与官方 wW 一致:1024 个 undefined,再 push 四个哨兵)
|
|
173
|
+
const objects = new Array(1024).fill(undefined)
|
|
174
|
+
objects.push(undefined, null, true, false)
|
|
175
|
+
let firstFree = objects.length
|
|
176
|
+
const heapObject = index => objects[index]
|
|
177
|
+
const pushObject = value => {
|
|
178
|
+
if (firstFree === objects.length) objects.push(objects.length + 1)
|
|
179
|
+
const index = firstFree
|
|
180
|
+
firstFree = objects[index]
|
|
181
|
+
objects[index] = value
|
|
182
|
+
return index
|
|
183
|
+
}
|
|
184
|
+
const takeObject = index => {
|
|
185
|
+
const value = heapObject(index)
|
|
186
|
+
// 索引 < 1028 是哨兵(undefined/null/true/false),不可回收
|
|
187
|
+
if (index >= 1028) {
|
|
188
|
+
objects[index] = firstFree
|
|
189
|
+
firstFree = index
|
|
190
|
+
}
|
|
191
|
+
return value
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
let lastLength = 0
|
|
195
|
+
const writeString = text => {
|
|
196
|
+
const encoded = encoder.encode(text)
|
|
197
|
+
const ptr = exports.__wbindgen_export2(encoded.length, 1) >>> 0
|
|
198
|
+
heap().subarray(ptr, ptr + encoded.length).set(encoded)
|
|
199
|
+
lastLength = encoded.length
|
|
200
|
+
return ptr
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// 字符串返回值布局:ptr/len/valIdx/isErr
|
|
204
|
+
const callString = invoke => {
|
|
205
|
+
let ptr = 0
|
|
206
|
+
let len = 0
|
|
207
|
+
const stack = exports.__wbindgen_add_to_stack_pointer(-16)
|
|
208
|
+
try {
|
|
209
|
+
invoke(stack)
|
|
210
|
+
const v = view()
|
|
211
|
+
ptr = v.getInt32(stack + 0, true)
|
|
212
|
+
len = v.getInt32(stack + 4, true)
|
|
213
|
+
const isError = v.getInt32(stack + 12, true)
|
|
214
|
+
if (isError) throw takeObject(v.getInt32(stack + 8, true))
|
|
215
|
+
return readString(ptr, len)
|
|
216
|
+
} finally {
|
|
217
|
+
exports.__wbindgen_add_to_stack_pointer(16)
|
|
218
|
+
if (ptr) exports.__wbindgen_export4(ptr, len, 1)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// 原始指针返回值布局:ptr/errIdx/isErr
|
|
223
|
+
const callPointer = invoke => {
|
|
224
|
+
const stack = exports.__wbindgen_add_to_stack_pointer(-16)
|
|
225
|
+
try {
|
|
226
|
+
invoke(stack)
|
|
227
|
+
const v = view()
|
|
228
|
+
const ptr = v.getInt32(stack + 0, true)
|
|
229
|
+
const isError = v.getInt32(stack + 8, true)
|
|
230
|
+
if (isError) throw takeObject(v.getInt32(stack + 4, true))
|
|
231
|
+
return ptr
|
|
232
|
+
} finally {
|
|
233
|
+
exports.__wbindgen_add_to_stack_pointer(16)
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// wasm-bindgen 的「调用 JS 函数并捕获异常」包装
|
|
238
|
+
const guard = (fn, args) => {
|
|
239
|
+
try {
|
|
240
|
+
fn(...args)
|
|
241
|
+
} catch (error) {
|
|
242
|
+
exports.__wbindgen_export(pushObject(error))
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const imports = {
|
|
247
|
+
__wbindgen_object_drop_ref: a => takeObject(a),
|
|
248
|
+
__wbindgen_object_clone_ref: a => pushObject(heapObject(a)),
|
|
249
|
+
__wbindgen_cast_0000000000000001: (a, e) => pushObject(heap().subarray(a >>> 0, (a >>> 0) + e)),
|
|
250
|
+
__wbindgen_cast_0000000000000002: (a, e) => pushObject(readString(a, e)),
|
|
251
|
+
__wbg_set_08463b1df38a7e29: (a, e, t) =>
|
|
252
|
+
pushObject(heapObject(a).set(heapObject(e), heapObject(t))),
|
|
253
|
+
// ⚠️ 这两个签名方向相反:一个写 wasm 内存,一个调 JS 对象。写反会 Rust panic。
|
|
254
|
+
__wbg_getRandomValues_d49329ff89a07af1: (...a) =>
|
|
255
|
+
guard((x, y) => { globalThis.crypto.getRandomValues(heap().subarray(x >>> 0, (x >>> 0) + y)) }, a),
|
|
256
|
+
__wbg_getRandomValues_c44a50d8cfdaebeb: (...a) =>
|
|
257
|
+
guard((x, y) => { heapObject(x).getRandomValues(heapObject(y)) }, a),
|
|
258
|
+
__wbg_crypto_38df2bab126b63dc: a => pushObject(heapObject(a).crypto),
|
|
259
|
+
__wbg_process_44c7a14e11e9f69e: a => pushObject(heapObject(a).process),
|
|
260
|
+
__wbg_versions_276b2795b1c6a219: a => pushObject(heapObject(a).versions),
|
|
261
|
+
__wbg_node_84ea875411254db1: a => pushObject(heapObject(a).node),
|
|
262
|
+
__wbg_require_b4edbdcf3e2a1ef0: (...a) => guard(() => pushObject(compiled), a),
|
|
263
|
+
__wbg_msCrypto_bd5a034af96bcba6: a => pushObject(heapObject(a).msCrypto),
|
|
264
|
+
__wbg_randomFillSync_6c25eac9869eb53c: (...a) =>
|
|
265
|
+
guard((x, y) => { heapObject(x).randomFillSync(takeObject(y)) }, a),
|
|
266
|
+
__wbg_call_d578befcc3145dee: (...a) =>
|
|
267
|
+
guard((fn, self, arg) => { pushObject(heapObject(fn).call(heapObject(self), heapObject(arg))) }, a),
|
|
268
|
+
__wbg_new_with_length_9cedd08484b73942: a => pushObject(new Uint8Array(a >>> 0)),
|
|
269
|
+
__wbg_length_0c32cb8543c8e4c8: a => heapObject(a).length,
|
|
270
|
+
__wbg_prototypesetcall_3e05eb9545565046: (a, e, t) => {
|
|
271
|
+
Uint8Array.prototype.set.call(heap().subarray(a >>> 0, (a >>> 0) + e), heapObject(t))
|
|
272
|
+
},
|
|
273
|
+
__wbg_subarray_0f98d3fb634508ad: (a, e, t) => pushObject(heapObject(a).subarray(e >>> 0, t >>> 0)),
|
|
274
|
+
__wbg_new_99cabae501c0a8a0: () => pushObject(new Map()),
|
|
275
|
+
__wbg_now_88621c9c9a4f3ffc: () => Date.now(),
|
|
276
|
+
__wbg_static_accessor_GLOBAL_THIS_a1248013d790bf5f: () => pushObject(globalThis),
|
|
277
|
+
__wbg_static_accessor_GLOBAL_f2e0f995a21329ff: () => pushObject(globalThis),
|
|
278
|
+
__wbg_static_accessor_SELF_24f78b6d23f286ea: () => (globalThis.self === undefined ? 0 : pushObject(globalThis.self)),
|
|
279
|
+
__wbg_static_accessor_WINDOW_59fd959c540fe405: () => (globalThis.window === undefined ? 0 : pushObject(globalThis.window)),
|
|
280
|
+
__wbg___wbindgen_throw_81fc77679af83bc6: (p, l) => { throw new Error(readString(p, l)) },
|
|
281
|
+
__wbg_Error_2e59b1b37a9a34c3: (p, l) => pushObject(new Error(readString(p, l))),
|
|
282
|
+
__wbg___wbindgen_is_object_40c5a80572e8f9d3: id => {
|
|
283
|
+
const v = heapObject(id)
|
|
284
|
+
return typeof v === 'object' && v !== null
|
|
285
|
+
},
|
|
286
|
+
__wbg___wbindgen_is_string_b29b5c5a8065ba1a: id => typeof heapObject(id) === 'string',
|
|
287
|
+
__wbg___wbindgen_is_function_49868bde5eb1e745: id => typeof heapObject(id) === 'function',
|
|
288
|
+
__wbg___wbindgen_is_undefined_c0cca72b82b86f4d: id => heapObject(id) === undefined,
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const instance = await WebAssembly.instantiate(compiled, { [IMPORT_MODULE]: imports })
|
|
292
|
+
exports = instance.exports
|
|
293
|
+
|
|
294
|
+
return { exports, heap, view, readString, writeString, lastLength: () => lastLength, heapObject, pushObject, takeObject, callString, callPointer }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** 生成运行时鉴权字段(encrypt_user_info / key)—— 服务端识别身份的依据。 */
|
|
298
|
+
export async function generateRuntimeAuthFields(user) {
|
|
299
|
+
const g = await getGlue()
|
|
300
|
+
const payload = JSON.stringify({
|
|
301
|
+
uid: user.uid,
|
|
302
|
+
security_oauth_token: user.securityOauthToken,
|
|
303
|
+
organization_id: user.organizationId ?? '',
|
|
304
|
+
organization_tags: user.organizationTags ?? [],
|
|
305
|
+
data_policy_agreed: user.dataPolicyAgreed ?? false,
|
|
306
|
+
})
|
|
307
|
+
const raw = g.callString(stack => {
|
|
308
|
+
const a = g.writeString(payload)
|
|
309
|
+
g.exports.generate_runtime_auth_fields(stack, a, g.lastLength())
|
|
310
|
+
})
|
|
311
|
+
return JSON.parse(raw)
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Qoder 加密推理客户端。持有 WASM 上下文与运行时鉴权字段,反复生成加密推理请求。
|
|
316
|
+
* 实例不是线程安全的;一个账号一个实例即可。
|
|
317
|
+
*/
|
|
318
|
+
export class QoderEncryptedInfer {
|
|
319
|
+
constructor(g, context, host) {
|
|
320
|
+
this.g = g
|
|
321
|
+
this.context = context
|
|
322
|
+
this.host = host
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* 创建客户端(调 WASM 构造 QoderContext)。
|
|
327
|
+
* ⚠️ host 必须是加密端点所在 host(国际版 api2.qoder.sh / 国内版 gateway.qoder.com.cn);
|
|
328
|
+
* 传公开端点的 host(api2-v2.qoder.sh)会 404。
|
|
329
|
+
*/
|
|
330
|
+
static async create({ user, machineId, metadata, host, clientVersion }) {
|
|
331
|
+
const g = await getGlue()
|
|
332
|
+
const fields = await generateRuntimeAuthFields(user)
|
|
333
|
+
const version = clientVersion ?? COSY_VERSION
|
|
334
|
+
|
|
335
|
+
const userInfoJson = JSON.stringify({
|
|
336
|
+
uid: user.uid,
|
|
337
|
+
encrypt_user_info: fields.encrypt_user_info,
|
|
338
|
+
key: fields.key,
|
|
339
|
+
organization_id: user.organizationId ?? '',
|
|
340
|
+
organization_tags: user.organizationTags ?? [],
|
|
341
|
+
data_policy_agreed: user.dataPolicyAgreed ?? false,
|
|
342
|
+
})
|
|
343
|
+
|
|
344
|
+
const context = g.callPointer(stack => {
|
|
345
|
+
const machine = g.writeString(machineId); const machineLen = g.lastLength()
|
|
346
|
+
const ver = g.writeString(version); const verLen = g.lastLength()
|
|
347
|
+
const info = g.writeString(userInfoJson); const infoLen = g.lastLength()
|
|
348
|
+
const meta = g.writeString(JSON.stringify(metadata)); const metaLen = g.lastLength()
|
|
349
|
+
// 参数顺序:(sp, machineId, len, version, len, userInfo, len, clientMeta, len)
|
|
350
|
+
g.exports.qodercontext_new(stack, machine, machineLen, ver, verLen, info, infoLen, meta, metaLen)
|
|
351
|
+
})
|
|
352
|
+
|
|
353
|
+
return new QoderEncryptedInfer(g, context, host)
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** 读取 requestresult 的 url / body / headers(三者共用一套栈式返回布局)。 */
|
|
357
|
+
readRequestResult(result) {
|
|
358
|
+
const g = this.g
|
|
359
|
+
const readString = (name) => {
|
|
360
|
+
const fn = g.exports[name]
|
|
361
|
+
let out = ''
|
|
362
|
+
const v = g.view()
|
|
363
|
+
const stack = g.exports.__wbindgen_add_to_stack_pointer(-16)
|
|
364
|
+
try {
|
|
365
|
+
// ⚠️ 参数顺序:(栈指针, ptr) —— 与直觉相反
|
|
366
|
+
fn(stack, result)
|
|
367
|
+
const ptr = v.getInt32(stack + 0, true)
|
|
368
|
+
const len = v.getInt32(stack + 4, true)
|
|
369
|
+
out = ptr ? g.readString(ptr, len) : ''
|
|
370
|
+
} finally {
|
|
371
|
+
g.exports.__wbindgen_add_to_stack_pointer(16)
|
|
372
|
+
}
|
|
373
|
+
return out
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const headerMap = g.takeObject(g.exports.requestresult_headers(result))
|
|
377
|
+
const headers = {}
|
|
378
|
+
if (headerMap instanceof Map) {
|
|
379
|
+
for (const [k, v] of headerMap) headers[String(k)] = String(v)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return { url: readString('requestresult_url'), headers, body: readString('requestresult_body') }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* 构造带网络契约签名的普通 API 请求(url / headers / body)。
|
|
387
|
+
*
|
|
388
|
+
* 参数顺序实测确定:`(host, path, method, authMode, body, extraHeadersJson)`。
|
|
389
|
+
* - `authMode === 'auth'` → 追加 COSY 签名头(Authorization/Cosy-Date/Cosy-Key/…),
|
|
390
|
+
* 模型目录 `/api/v2/model/list` 必须用它;不传则是裸 Cosy-* 头,服务端回
|
|
391
|
+
* `403 Signature invalid`。
|
|
392
|
+
* - `authMode === 'sign'` → 追加 Appcode/Signature 头(阿里 appcode 契约)。
|
|
393
|
+
* - 其余值不做签名。
|
|
394
|
+
* - 返回的 url 不含协议,网关固定为 `https://`(WASM 只在 host 前拼 `/algo`)。
|
|
395
|
+
* - `extraHeadersJson` 必须是合法 JSON 对象,否则 WASM 报
|
|
396
|
+
* `Invalid extra headers: EOF while parsing a value`。
|
|
397
|
+
*/
|
|
398
|
+
prepareRequest({ host = this.host, path, method = 'GET', auth = '', body = '', headers = {} }) {
|
|
399
|
+
const g = this.g
|
|
400
|
+
const bareHost = String(host).replace(/^https?:\/\//, '')
|
|
401
|
+
const result = g.callPointer(stack => {
|
|
402
|
+
const args = [stack, this.context]
|
|
403
|
+
for (const s of [bareHost, path, method, auth, body, JSON.stringify(headers)]) {
|
|
404
|
+
args.push(g.writeString(s), g.lastLength())
|
|
405
|
+
}
|
|
406
|
+
args.length = 14
|
|
407
|
+
while (args.length < 14) args.push(0)
|
|
408
|
+
g.exports.qodercontext_prepareRequest(...args)
|
|
409
|
+
})
|
|
410
|
+
|
|
411
|
+
const out = this.readRequestResult(result)
|
|
412
|
+
return { ...out, url: `https://${out.url}` }
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* 构造加密推理请求(url / headers / body)。
|
|
417
|
+
* ⚠️ 返回的 headers 必须原样透传:Authorization 是 WASM 生成的
|
|
418
|
+
* `Bearer COSY.<载荷>.<签名>`,用普通 Bearer 覆盖会 403 Signature invalid。
|
|
419
|
+
*/
|
|
420
|
+
prepareInfer(ask) {
|
|
421
|
+
const g = this.g
|
|
422
|
+
const payload = buildQoderInferPayload(ask)
|
|
423
|
+
|
|
424
|
+
const result = g.callPointer(stack => {
|
|
425
|
+
const host = g.writeString(this.host); const hostLen = g.lastLength()
|
|
426
|
+
const body = g.writeString(JSON.stringify(payload)); const bodyLen = g.lastLength()
|
|
427
|
+
const key = g.writeString(ask.modelKey); const keyLen = g.lastLength()
|
|
428
|
+
const source = g.writeString(ask.source ?? 'system'); const sourceLen = g.lastLength()
|
|
429
|
+
g.exports.qodercontext_prepareInferRequest(stack, this.context, host, hostLen, body, bodyLen, key, keyLen, source, sourceLen)
|
|
430
|
+
})
|
|
431
|
+
|
|
432
|
+
return this.readRequestResult(result)
|
|
433
|
+
}
|
|
434
|
+
}
|