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
package/src/channels/comate.js
CHANGED
|
@@ -1,830 +1,830 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Comate(百度文心快码)渠道。
|
|
3
|
-
*
|
|
4
|
-
* 协议要点:
|
|
5
|
-
* - 宿主:saas https://comate.baidu.com / internal https://comate.baidu-int.com
|
|
6
|
-
* saas-test https://comate-external-test.now.baidu.com
|
|
7
|
-
* internal-test https://comate-test.now.baidu-int.com
|
|
8
|
-
* - 鉴权:**不用 Bearer**。SaaS 的 license 同时放进请求头
|
|
9
|
-
* `login-name` / `Uuap-login-name`(encodeURIComponent)与 body 的 `username`。
|
|
10
|
-
* - 模型清单:GET {host}/api/v2/api/models/available?key={license}&type=ZULU&loopVersion=v2
|
|
11
|
-
* → data 数组,字段 modelId / modelType / displayName / maxContextWindow(单位 K tokens)/
|
|
12
|
-
* ratio(倍率字符串,如 "0.3x")/ supportImage / supportThinking
|
|
13
|
-
* - 模型 id:上游 modelId 形如 `glm-4.7-fc_0b87452a03394418b5c8d5468deff6c7`,
|
|
14
|
-
* 前半段是模型类型(= modelType),后半段是 32 位十六进制实例标识(界面上的「乱码」)。
|
|
15
|
-
* 对外(目录/界面)暴露干净 id(modelType),真实调用仍用完整 modelId ——
|
|
16
|
-
* 部分模型(实测 glm-5.2)只认完整 modelId,短 id 会被上游拒为「令牌状态不可用」。
|
|
17
|
-
* - 对话(新版多个模型已不再接受旧的 generate 端点,改走 agent 协议):
|
|
18
|
-
* POST {host}/api/aidevops/autocomate/rest/autowork/v2/conversation → { data:{ id } }
|
|
19
|
-
* POST {host}/api/aidevops/autocomate/rest/autowork/v2/task → { data:{ taskId } }
|
|
20
|
-
* POST {host}/api/aidevops/autocomate/rest/autowork/v2/execute → SSE
|
|
21
|
-
* - SSE 帧:`{ content:{ type:'ANSWER', detail:{ delta, end } } }`,delta 是增量文本;
|
|
22
|
-
* type 还可能是 TOKEN_USAGE / NOTIFICATION / EXCEPTION / QUOTA_EXCEED 等。
|
|
23
|
-
*/
|
|
24
|
-
|
|
25
|
-
import { randomBytes, randomUUID } from 'node:crypto'
|
|
26
|
-
import { arch, hostname, release, type as osType, userInfo } from 'node:os'
|
|
27
|
-
import { httpFetch, readBodyText, mergeSseChunks } from '../util.js'
|
|
28
|
-
|
|
29
|
-
// ── 产品常量 ────────────────────────────────────────────────────────────────
|
|
30
|
-
|
|
31
|
-
const HOST_SAAS = 'https://comate.baidu.com'
|
|
32
|
-
const HOST_INTERNAL = 'https://comate.baidu-int.com'
|
|
33
|
-
const HOST_SAAS_TEST = 'https://comate-external-test.now.baidu.com'
|
|
34
|
-
const HOST_INTERNAL_TEST = 'https://comate-test.now.baidu-int.com'
|
|
35
|
-
|
|
36
|
-
const MODELS_PATH = '/api/v2/api/models/available'
|
|
37
|
-
const AGENT_BASE_PATH = '/api/aidevops/autocomate/rest/autowork/v2'
|
|
38
|
-
|
|
39
|
-
/** 新版 agent 协议固定参数(取自 getRequestUserHeader / getRequestClienInfo)。 */
|
|
40
|
-
const AGENT_ID = 'general'
|
|
41
|
-
const AGENT_INFO = { agentName: 'General', isProjectAgent: false, canInvokeAgents: false }
|
|
42
|
-
const AGENT_PLUGIN_VERSION = '4.14.1'
|
|
43
|
-
const AGENT_PLUGIN_HEADER = 'VsCode-4.14.1'
|
|
44
|
-
|
|
45
|
-
/** IDE 版本伪装(agentClientInfo / 登录 device 描述)。 */
|
|
46
|
-
const IDE_VERSION = '1.96.0'
|
|
47
|
-
|
|
48
|
-
const REQUEST_TIMEOUT_MS = 30_000
|
|
49
|
-
const IDLE_TIMEOUT_MS = 120_000
|
|
50
|
-
const BODY_READ_TIMEOUT_MS = 15_000
|
|
51
|
-
const MODELS_TIMEOUT_MS = 20_000
|
|
52
|
-
|
|
53
|
-
/** 实时清单没给输出上限;按上游常见值给一个保守估计(仅目录展示用)。 */
|
|
54
|
-
const DEFAULT_MAX_OUTPUT = 8192
|
|
55
|
-
|
|
56
|
-
// ── 模型目录 ───────────────────────────────────────────────────────────────
|
|
57
|
-
|
|
58
|
-
export const meta = { id: 'comate', label: 'Comate', loginMode: 'external-link', localLogin: true }
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* 上游 modelId 形如 `glm-4.7-fc_0b87452a03394418b5c8d5468deff6c7`:
|
|
62
|
-
* 前半段是模型类型(= modelType),后半段是 32 位十六进制实例标识(界面上的「乱码」)。
|
|
63
|
-
* 对外只暴露前半段(干净 id),真实调用仍用完整 modelId。
|
|
64
|
-
*/
|
|
65
|
-
function splitModelId(modelId) {
|
|
66
|
-
const text = String(modelId ?? '').trim()
|
|
67
|
-
const at = text.indexOf('_')
|
|
68
|
-
if (at <= 0) return { clean: text, full: text }
|
|
69
|
-
const suffix = text.slice(at + 1)
|
|
70
|
-
if (!/^[0-9a-f]{32}$/i.test(suffix)) return { clean: text, full: text }
|
|
71
|
-
return { clean: text.slice(0, at), full: text }
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* 模型调用参数缓存:干净 id / 完整 modelId → { cleanId, upstreamId, thinkingEnabled, effort }。
|
|
76
|
-
* 每次 fetchModels 实时清单都会刷新(清单拉不到就不会产出目录行,也就不会调用)。
|
|
77
|
-
*/
|
|
78
|
-
const modelMeta = new Map()
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* 思考参数推导:
|
|
82
|
-
* - supportAdaptiveThinking=false 且 supportEffort ∈ {low, high, max} 的模型「始终思考」,
|
|
83
|
-
* 必须 thinkingEnabled=true 且 effort 用 low/high/max(用 medium 或关思考会被上游拒:
|
|
84
|
-
* 「该模型始终思考,不支持关闭思考;请使用 low、high 或 max」)。
|
|
85
|
-
* - 其余模型保持默认关闭思考 + medium。
|
|
86
|
-
*/
|
|
87
|
-
function thinkingParams(item) {
|
|
88
|
-
const effortRaw = typeof item.supportEffort === 'string' ? item.supportEffort.trim().toLowerCase() : ''
|
|
89
|
-
const alwaysThinking = item.supportThinking === true
|
|
90
|
-
&& item.supportAdaptiveThinking === false
|
|
91
|
-
&& (effortRaw === 'low' || effortRaw === 'high' || effortRaw === 'max')
|
|
92
|
-
return {
|
|
93
|
-
thinkingEnabled: alwaysThinking,
|
|
94
|
-
effort: alwaysThinking ? effortRaw : 'medium',
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// 在线登录常量(SaaS 网页登录握手):
|
|
99
|
-
// 1. 生成 clientId(UUID),打开 {host}/zh/login?track=VSCODE&clientId=…&device=…
|
|
100
|
-
// —— 浏览器已登录时会直接把登录态绑定到该 clientId(无需再次输入账号)
|
|
101
|
-
// 2. 轮询 GET /api/client/generate/token?clientId=… → { status:'OK', data: <临时 token> }
|
|
102
|
-
// 3. GET /api/client/key?clientId=…(请求头 token: <临时 token>)
|
|
103
|
-
// → { status:'OK', data:{ key: <license>, displayName, userAvatarUrl } }
|
|
104
|
-
// 4. license 即生成接口 body 里的 `key` 字段,入库后即可直接调用
|
|
105
|
-
const LOGIN_PAGE_PATH = '/zh/login'
|
|
106
|
-
const CLIENT_TOKEN_PATH = '/api/client/generate/token'
|
|
107
|
-
const CLIENT_KEY_PATH = '/api/client/key'
|
|
108
|
-
const LOGIN_DEVICE_VERSION = '4.14.1' // 仅用于 device 描述,不影响绑定
|
|
109
|
-
const LOGIN_WAIT_TIMEOUT_MS = 5 * 60_000 // 5 分钟等待用户在浏览器完成登录
|
|
110
|
-
const LOGIN_POLL_INTERVAL_MS = 2_000
|
|
111
|
-
const LOGIN_POLL_TIMEOUT_MS = 15_000
|
|
112
|
-
|
|
113
|
-
// ── 小工具 ─────────────────────────────────────────────────────────────────
|
|
114
|
-
|
|
115
|
-
function readStringField(source, key) {
|
|
116
|
-
const value = source?.[key]
|
|
117
|
-
if (typeof value === 'string' && value.trim().length > 0) return value.trim()
|
|
118
|
-
return ''
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/** 由 credential 的 platform 推导 API 宿主。 */
|
|
122
|
-
function resolveHost(credential) {
|
|
123
|
-
const explicit = readStringField(credential, 'apiHost')
|
|
124
|
-
if (explicit) return explicit.replace(/\/+$/, '')
|
|
125
|
-
const platform = readStringField(credential, 'platform') || 'saas'
|
|
126
|
-
const test = credential?.environment === 'test' || credential?.test === true
|
|
127
|
-
if (platform === 'internal') return test ? HOST_INTERNAL_TEST : HOST_INTERNAL
|
|
128
|
-
return test ? HOST_SAAS_TEST : HOST_SAAS
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// ── 凭据 ───────────────────────────────────────────────────────────────────
|
|
132
|
-
|
|
133
|
-
export function normalizeCredential(raw) {
|
|
134
|
-
let value = raw
|
|
135
|
-
if (typeof value === 'string') {
|
|
136
|
-
const text = value.trim()
|
|
137
|
-
// 裸 license 串(常见:直接复制 token)也接受。
|
|
138
|
-
if (!text.startsWith('{')) {
|
|
139
|
-
if (text === '') throw new Error('凭据为空')
|
|
140
|
-
return { license: text, username: text, platform: 'saas' }
|
|
141
|
-
}
|
|
142
|
-
try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
|
|
143
|
-
}
|
|
144
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
145
|
-
throw new Error('凭据必须是 JSON 对象或 license 字符串')
|
|
146
|
-
}
|
|
147
|
-
const license = readStringField(value, 'license') || readStringField(value, 'key')
|
|
148
|
-
|| readStringField(value, 'access_token') || readStringField(value, 'token')
|
|
149
|
-
const username = readStringField(value, 'username') || readStringField(value, 'name')
|
|
150
|
-
if (!license && !username) throw new Error('凭据缺少 license(或 username)')
|
|
151
|
-
const out = { ...value, license: license || username, username: username || license }
|
|
152
|
-
const platform = readStringField(value, 'platform') || readStringField(value, 'server')
|
|
153
|
-
out.platform = platform === 'internal' || platform === 'poc' ? platform : 'saas'
|
|
154
|
-
if (readStringField(value, 'apiHost')) out.apiHost = readStringField(value, 'apiHost')
|
|
155
|
-
if (readStringField(value, 'version')) out.version = readStringField(value, 'version')
|
|
156
|
-
return out
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export function describeCredential(credential) {
|
|
160
|
-
const username = readStringField(credential, 'username')
|
|
161
|
-
return {
|
|
162
|
-
label: username || 'Comate 账号',
|
|
163
|
-
expiresAt: 0,
|
|
164
|
-
refreshable: false,
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/** 去重键:username + 平台(同人不同环境视为不同账号)。 */
|
|
169
|
-
export function credentialIdentity(credential) {
|
|
170
|
-
const username = readStringField(credential, 'username') || readStringField(credential, 'license')
|
|
171
|
-
if (!username) return ''
|
|
172
|
-
return `${readStringField(credential, 'platform') || 'saas'}:${username}`
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
export function needsRefresh() {
|
|
176
|
-
return false
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
export async function refreshCredential(credential) {
|
|
180
|
-
// Comate 的 license 无续期机制,失效只能重登。
|
|
181
|
-
throw { kind: 'auth', retryable: false, terminal: true, message: 'Comate 凭据无法自动续期,请重新登录' }
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// ── 模型清单 ───────────────────────────────────────────────────────────────
|
|
185
|
-
|
|
186
|
-
function normalizeRemoteModels(payload) {
|
|
187
|
-
const raw = payload?.data?.data ?? payload?.data ?? payload
|
|
188
|
-
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.models) ? raw.models : []
|
|
189
|
-
const out = []
|
|
190
|
-
const seen = new Set()
|
|
191
|
-
for (const item of list) {
|
|
192
|
-
if (item === null || typeof item !== 'object') continue
|
|
193
|
-
if (item.enabled === false) continue
|
|
194
|
-
const rawId = readStringField(item, 'modelId') || readStringField(item, 'model')
|
|
195
|
-
|| readStringField(item, 'name') || readStringField(item, 'id')
|
|
196
|
-
if (!rawId) continue
|
|
197
|
-
// 上游 modelId 带 32 位实例后缀;对外只暴露干净 id(modelType),调用用完整 modelId
|
|
198
|
-
const { clean, full } = splitModelId(rawId)
|
|
199
|
-
if (seen.has(clean)) continue
|
|
200
|
-
seen.add(clean)
|
|
201
|
-
// maxContextWindow 单位是 K tokens(如 1000 = 约 100 万)
|
|
202
|
-
const rawContext = Number(item.maxContextWindow)
|
|
203
|
-
const contextWindow = Number.isFinite(rawContext) && rawContext > 0
|
|
204
|
-
? Math.round(rawContext * 1024)
|
|
205
|
-
: 8192
|
|
206
|
-
// ratio 是倍率字符串("0.3x" / "1x"),供卡片和目录展示
|
|
207
|
-
const ratio = typeof item.ratio === 'string' ? Number.parseFloat(item.ratio) : Number.NaN
|
|
208
|
-
const thinking = thinkingParams(item)
|
|
209
|
-
modelMeta.set(clean, { cleanId: clean, upstreamId: full, ...thinking })
|
|
210
|
-
modelMeta.set(full, { cleanId: clean, upstreamId: full, ...thinking })
|
|
211
|
-
out.push({
|
|
212
|
-
id: clean,
|
|
213
|
-
upstreamId: full,
|
|
214
|
-
name: readStringField(item, 'displayName') || readStringField(item, 'title')
|
|
215
|
-
|| readStringField(item, 'name') || clean,
|
|
216
|
-
contextWindow,
|
|
217
|
-
maxTokens: DEFAULT_MAX_OUTPUT,
|
|
218
|
-
supportsImage: item.supportImage === true,
|
|
219
|
-
isFree: true,
|
|
220
|
-
...(Number.isFinite(ratio) ? { rate: ratio } : {}),
|
|
221
|
-
})
|
|
222
|
-
}
|
|
223
|
-
return out
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* Comate 实时模型清单:两种请求形态各自尝试,全部失败/空清单即抛错(目录只认实时结果)。
|
|
228
|
-
*/
|
|
229
|
-
export async function fetchModels(credential) {
|
|
230
|
-
if (!credential) throw new Error('Comate 缺少凭据,请先添加账号')
|
|
231
|
-
const host = resolveHost(credential)
|
|
232
|
-
const license = readStringField(credential, 'license')
|
|
233
|
-
const username = readStringField(credential, 'username')
|
|
234
|
-
const reasons = []
|
|
235
|
-
if (license.length === 0 && username.length === 0) {
|
|
236
|
-
throw new Error('Comate 凭据缺少 license / username,无法拉取模型清单')
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// 形态一:GET + key(loopVersion=v2,SaaS 全量目录)。
|
|
240
|
-
if (license) {
|
|
241
|
-
try {
|
|
242
|
-
const url = `${host}${MODELS_PATH}?key=${encodeURIComponent(license)}&type=ZULU&loopVersion=v2`
|
|
243
|
-
const response = await httpFetch(url, { method: 'GET', headers: { Accept: 'application/json' } }, MODELS_TIMEOUT_MS)
|
|
244
|
-
if (response.ok) {
|
|
245
|
-
const models = normalizeRemoteModels(await response.json().catch(() => null))
|
|
246
|
-
if (models.length > 0) return models
|
|
247
|
-
reasons.push('license 形态返回空清单')
|
|
248
|
-
} else {
|
|
249
|
-
const text = await response.text().catch(() => '')
|
|
250
|
-
reasons.push(`license 形态 HTTP ${response.status}${extractMessage(text) ? `:${extractMessage(text)}` : ''}`)
|
|
251
|
-
}
|
|
252
|
-
} catch (error) {
|
|
253
|
-
reasons.push(`license 形态异常:${error?.message ?? error}`)
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
// 形态二:POST + username(ZULU 场景)。
|
|
257
|
-
if (username) {
|
|
258
|
-
try {
|
|
259
|
-
const response = await httpFetch(`${host}${MODELS_PATH}`, {
|
|
260
|
-
method: 'POST',
|
|
261
|
-
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
262
|
-
body: JSON.stringify({ username, type: 'ZULU', rootRepo: '', submodules: [] }),
|
|
263
|
-
}, MODELS_TIMEOUT_MS)
|
|
264
|
-
if (response.ok) {
|
|
265
|
-
const models = normalizeRemoteModels(await response.json().catch(() => null))
|
|
266
|
-
if (models.length > 0) return models
|
|
267
|
-
reasons.push('username 形态返回空清单')
|
|
268
|
-
} else {
|
|
269
|
-
const text = await response.text().catch(() => '')
|
|
270
|
-
reasons.push(`username 形态 HTTP ${response.status}${extractMessage(text) ? `:${extractMessage(text)}` : ''}`)
|
|
271
|
-
}
|
|
272
|
-
} catch (error) {
|
|
273
|
-
reasons.push(`username 形态异常:${error?.message ?? error}`)
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
throw new Error(`Comate 模型清单获取失败:${reasons.join(';')}`)
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// ── 在线登录(网页登录握手)──────────────────────────────────────────────
|
|
280
|
-
//
|
|
281
|
-
// SaaS Comate 支持把浏览器登录态绑定到临时 clientId:
|
|
282
|
-
// loginUrl = {host}/zh/login?track=VSCODE&clientId=…&device=…
|
|
283
|
-
// 浏览器已登录时页面直接列出账号,用户点「授权登录」即完成绑定
|
|
284
|
-
// → 轮询 /api/client/generate/token 拿到临时 token
|
|
285
|
-
// → /api/client/key(header token)换发 license → resolve 入库
|
|
286
|
-
// 用户也可通过 POST /admin/api/channels/comate/credential 手动粘贴(resolveLoginCredential)。
|
|
287
|
-
|
|
288
|
-
/** device 描述。 */
|
|
289
|
-
function loginDeviceText() {
|
|
290
|
-
try {
|
|
291
|
-
const platform = osType()
|
|
292
|
-
const osName = platform === 'Windows_NT' ? 'Windows' : platform === 'Darwin' ? 'Mac OS' : platform
|
|
293
|
-
return `${userInfo().username} ${hostname()} (${osName} ${arch()} ${release()})`
|
|
294
|
-
} catch {
|
|
295
|
-
return `comate ${LOGIN_DEVICE_VERSION}`
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
function buildLoginUrl(clientId) {
|
|
300
|
-
const query = `track=VSCODE&clientId=${encodeURIComponent(clientId)}&device=${encodeURIComponent(loginDeviceText())}`
|
|
301
|
-
return `${HOST_SAAS}${LOGIN_PAGE_PATH}?${query}`
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/** 可被 signal 中断的睡眠(登录轮询用)。 */
|
|
305
|
-
function sleepAbortable(ms, signal) {
|
|
306
|
-
return new Promise((resolve, reject) => {
|
|
307
|
-
if (signal?.aborted) { reject(new Error('登录已取消')); return }
|
|
308
|
-
const timer = setTimeout(() => {
|
|
309
|
-
signal?.removeEventListener('abort', onAbort)
|
|
310
|
-
resolve()
|
|
311
|
-
}, ms)
|
|
312
|
-
const onAbort = () => { clearTimeout(timer); reject(new Error('登录已取消')) }
|
|
313
|
-
signal?.addEventListener('abort', onAbort, { once: true })
|
|
314
|
-
timer.unref?.()
|
|
315
|
-
})
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
/**
|
|
319
|
-
* 轮询一次绑定结果:拿到临时 token 后用 token 换发 license。
|
|
320
|
-
* 未完成(用户还没登录/绑定)返回 null;换发 license 明确失败时抛错。
|
|
321
|
-
*/
|
|
322
|
-
async function pollLogin(clientId, signal) {
|
|
323
|
-
const tokenResponse = await httpFetch(`${HOST_SAAS}${CLIENT_TOKEN_PATH}?clientId=${encodeURIComponent(clientId)}`, {
|
|
324
|
-
method: 'GET',
|
|
325
|
-
headers: { Accept: 'application/json' },
|
|
326
|
-
signal,
|
|
327
|
-
}, LOGIN_POLL_TIMEOUT_MS)
|
|
328
|
-
if (!tokenResponse.ok) return null
|
|
329
|
-
const tokenPayload = await tokenResponse.json().catch(() => null)
|
|
330
|
-
if (tokenPayload?.status !== 'OK' || !tokenPayload.data) return null
|
|
331
|
-
|
|
332
|
-
const keyResponse = await httpFetch(`${HOST_SAAS}${CLIENT_KEY_PATH}?clientId=${encodeURIComponent(clientId)}`, {
|
|
333
|
-
method: 'GET',
|
|
334
|
-
headers: { Accept: 'application/json', token: String(tokenPayload.data) },
|
|
335
|
-
signal,
|
|
336
|
-
}, LOGIN_POLL_TIMEOUT_MS)
|
|
337
|
-
const keyPayload = await keyResponse.json().catch(() => null)
|
|
338
|
-
if (keyPayload?.status !== 'OK' || !keyPayload.data) {
|
|
339
|
-
const message = typeof keyPayload?.message === 'string' ? keyPayload.message : ''
|
|
340
|
-
throw new Error(`Comate 登录换发 license 失败${message ? `:${message}` : ''}`)
|
|
341
|
-
}
|
|
342
|
-
const info = keyPayload.data
|
|
343
|
-
const license = readStringField(info, 'key')
|
|
344
|
-
if (license === '') throw new Error('Comate 登录响应缺少 license(key)')
|
|
345
|
-
const username = readStringField(info, 'displayName') || readStringField(info, 'username')
|
|
346
|
-
|| readStringField(info, 'name') || license
|
|
347
|
-
return { license, username, platform: 'saas' }
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
// 用于 startLogin 内部:admin.js 在 POST credential 后 resolve 这个 promise
|
|
351
|
-
let _pendingLicensePromise = null
|
|
352
|
-
|
|
353
|
-
/**
|
|
354
|
-
* startLogin()
|
|
355
|
-
* 返回 { loginUrl, promise, cancel() }:
|
|
356
|
-
* loginUrl 立即可用;promise 在浏览器完成绑定后自动 resolve 出凭据;
|
|
357
|
-
* 手动「粘贴凭据添加」会经 resolveLoginCredential 收敛同一个 promise。
|
|
358
|
-
*/
|
|
359
|
-
export function startLogin() {
|
|
360
|
-
const controller = new AbortController()
|
|
361
|
-
const signal = controller.signal
|
|
362
|
-
const clientId = randomUUID()
|
|
363
|
-
let settled = false
|
|
364
|
-
let resolveFlow = null
|
|
365
|
-
let rejectFlow = null
|
|
366
|
-
|
|
367
|
-
const promise = new Promise((resolve, reject) => {
|
|
368
|
-
resolveFlow = resolve
|
|
369
|
-
rejectFlow = reject
|
|
370
|
-
})
|
|
371
|
-
promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
|
|
372
|
-
|
|
373
|
-
function finish(settle) {
|
|
374
|
-
if (settled) return
|
|
375
|
-
settled = true
|
|
376
|
-
_pendingLicensePromise = null
|
|
377
|
-
settle()
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
_pendingLicensePromise = {
|
|
381
|
-
resolve: credential => finish(() => resolveFlow(credential)),
|
|
382
|
-
reject: error => finish(() => rejectFlow(error instanceof Error ? error : new Error(String(error)))),
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
const run = async () => {
|
|
386
|
-
const deadline = Date.now() + LOGIN_WAIT_TIMEOUT_MS
|
|
387
|
-
while (!settled && Date.now() < deadline) {
|
|
388
|
-
try {
|
|
389
|
-
const credential = await pollLogin(clientId, signal)
|
|
390
|
-
if (credential) { finish(() => resolveFlow(credential)); return }
|
|
391
|
-
} catch (error) {
|
|
392
|
-
if (settled) return
|
|
393
|
-
if (signal.aborted) { finish(() => rejectFlow(new Error('登录已取消'))); return }
|
|
394
|
-
// 换发 license 的明确失败直接终止;网络抖动按未完成继续轮询
|
|
395
|
-
if (error instanceof Error && error.message.startsWith('Comate 登录')) {
|
|
396
|
-
finish(() => rejectFlow(error))
|
|
397
|
-
return
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
try { await sleepAbortable(LOGIN_POLL_INTERVAL_MS, signal) } catch { return }
|
|
401
|
-
}
|
|
402
|
-
finish(() => rejectFlow(new Error('登录等待已超时,请重新发起登录')))
|
|
403
|
-
}
|
|
404
|
-
void run()
|
|
405
|
-
|
|
406
|
-
return {
|
|
407
|
-
loginUrl: buildLoginUrl(clientId),
|
|
408
|
-
promise,
|
|
409
|
-
cancel: () => {
|
|
410
|
-
if (settled) return
|
|
411
|
-
controller.abort()
|
|
412
|
-
finish(() => rejectFlow(new Error('登录已取消')))
|
|
413
|
-
},
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// 由 admin.js 在 credential 路由调用:若当前有 pending 登录,把 credential 注入
|
|
418
|
-
// 使 startLogin 的 promise 正常 resolve;无 pending 时静默 no-op
|
|
419
|
-
export function resolveLoginCredential(credential) {
|
|
420
|
-
const p = _pendingLicensePromise
|
|
421
|
-
if (!p) return
|
|
422
|
-
_pendingLicensePromise = null
|
|
423
|
-
p.resolve(credential)
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
// ── 对话 ───────────────────────────────────────────────────────────────────
|
|
427
|
-
|
|
428
|
-
function failureFrom(status, bodyText) {
|
|
429
|
-
const lower = String(bodyText ?? '').toLowerCase()
|
|
430
|
-
const message = extractMessage(bodyText) || `Comate HTTP ${status}`
|
|
431
|
-
if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
432
|
-
if (status === 402 || /quota|balance|insufficient|额度|余额|限流|exceeded/.test(lower)) {
|
|
433
|
-
return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
|
|
434
|
-
}
|
|
435
|
-
if (status === 401 || status === 403) {
|
|
436
|
-
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
437
|
-
}
|
|
438
|
-
if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
|
|
439
|
-
if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
440
|
-
if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
441
|
-
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
function extractMessage(bodyText) {
|
|
445
|
-
const text = String(bodyText ?? '').trim()
|
|
446
|
-
if (text === '') return ''
|
|
447
|
-
try {
|
|
448
|
-
const parsed = JSON.parse(text)
|
|
449
|
-
const found = [
|
|
450
|
-
typeof parsed?.message === 'string' ? parsed.message : '',
|
|
451
|
-
typeof parsed?.msg === 'string' ? parsed.msg : '',
|
|
452
|
-
typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
|
|
453
|
-
typeof parsed?.error === 'string' ? parsed.error : '',
|
|
454
|
-
].filter(v => v.length > 0)
|
|
455
|
-
if (found.length > 0) return found.join(' ').slice(0, 300)
|
|
456
|
-
} catch { /* 非 JSON */ }
|
|
457
|
-
return text.slice(0, 300)
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/** OpenAI messages → agent 协议的单条 query + 可选 system prompt。 */
|
|
461
|
-
function buildAgentQuery(messages) {
|
|
462
|
-
const systemParts = []
|
|
463
|
-
const turns = []
|
|
464
|
-
for (const msg of Array.isArray(messages) ? messages : []) {
|
|
465
|
-
if (msg === null || typeof msg !== 'object') continue
|
|
466
|
-
const text = typeof msg.content === 'string'
|
|
467
|
-
? msg.content
|
|
468
|
-
: Array.isArray(msg.content)
|
|
469
|
-
? msg.content.map(part => (typeof part === 'string' ? part : typeof part?.text === 'string' ? part.text : '')).join('')
|
|
470
|
-
: ''
|
|
471
|
-
if (text === '') continue
|
|
472
|
-
if (msg.role === 'system' || msg.role === 'developer') { systemParts.push(text); continue }
|
|
473
|
-
turns.push({ role: msg.role === 'assistant' ? 'Assistant' : 'User', text })
|
|
474
|
-
}
|
|
475
|
-
// 单轮用户输入不额外加角色前缀;多轮历史按角色拼成一段对话上下文
|
|
476
|
-
const query = turns.length === 1 && turns[0].role === 'User'
|
|
477
|
-
? turns[0].text
|
|
478
|
-
: turns.map(turn => `${turn.role}: ${turn.text}`).join('\n\n')
|
|
479
|
-
return { systemPrompt: systemParts.join('\n\n'), query }
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
/** agent 协议的鉴权名:SaaS 用 license,internal 用 username(对应 kernel.config.key)。 */
|
|
483
|
-
function agentAuthName(credential) {
|
|
484
|
-
return readStringField(credential, 'license') || readStringField(credential, 'username')
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
function agentHeaders(credential, extra = {}) {
|
|
488
|
-
const name = encodeURIComponent(agentAuthName(credential))
|
|
489
|
-
return {
|
|
490
|
-
'Content-Type': 'application/json',
|
|
491
|
-
'login-name': name,
|
|
492
|
-
'Uuap-login-name': name,
|
|
493
|
-
'X-Source': 'COMATE',
|
|
494
|
-
'plugin-version': AGENT_PLUGIN_HEADER,
|
|
495
|
-
'x-skip-fcnap': 'yes',
|
|
496
|
-
...extra,
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
/** getRequestClienInfo 逐字:username = license(SaaS)。 */
|
|
501
|
-
function agentClientInfo(credential) {
|
|
502
|
-
return {
|
|
503
|
-
username: agentAuthName(credential),
|
|
504
|
-
ide: 'VsCode',
|
|
505
|
-
ideVersion: IDE_VERSION,
|
|
506
|
-
pluginVersion: AGENT_PLUGIN_VERSION,
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
/** agent 接口用 HTTP 200 + body.code 表达业务错误。 */
|
|
511
|
-
function agentFailure(payload, status = 0) {
|
|
512
|
-
const message = (typeof payload?.message === 'string' && payload.message.trim())
|
|
513
|
-
|| (typeof payload?.msg === 'string' && payload.msg.trim())
|
|
514
|
-
|| (status > 0 ? `Comate HTTP ${status}` : 'Comate 请求失败')
|
|
515
|
-
if (payload?.code === 401 || status === 401 || status === 403) {
|
|
516
|
-
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
517
|
-
}
|
|
518
|
-
if (payload?.code === 429 || status === 429) {
|
|
519
|
-
return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
520
|
-
}
|
|
521
|
-
if (/quota|limit|额度|余额|超过限制/i.test(message)) {
|
|
522
|
-
return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
|
|
523
|
-
}
|
|
524
|
-
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
async function postAgentJson(credential, pathName, requestBody, { signal, headerTimeoutMs, traceId }) {
|
|
528
|
-
let response
|
|
529
|
-
try {
|
|
530
|
-
response = await httpFetch(`${resolveHost(credential)}${AGENT_BASE_PATH}${pathName}`, {
|
|
531
|
-
method: 'POST',
|
|
532
|
-
headers: agentHeaders(credential, { Accept: 'application/json', 'X-Trace-Id': traceId }),
|
|
533
|
-
body: JSON.stringify(requestBody),
|
|
534
|
-
signal,
|
|
535
|
-
}, headerTimeoutMs)
|
|
536
|
-
} catch (error) {
|
|
537
|
-
if (signal?.aborted) throw error
|
|
538
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate 请求发送失败:${error?.message ?? error}` }
|
|
539
|
-
}
|
|
540
|
-
if (!response.ok) {
|
|
541
|
-
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
542
|
-
throw failureFrom(response.status, text)
|
|
543
|
-
}
|
|
544
|
-
return response
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
async function createAgentConversation(credential, { query, systemPrompt, model, traceId, signal, headerTimeoutMs }) {
|
|
548
|
-
const response = await postAgentJson(credential, '/conversation', {
|
|
549
|
-
...agentClientInfo(credential),
|
|
550
|
-
conversationId: -1,
|
|
551
|
-
taskId: -1,
|
|
552
|
-
agentId: AGENT_ID,
|
|
553
|
-
agentInfo: AGENT_INFO,
|
|
554
|
-
query,
|
|
555
|
-
modelKey: model,
|
|
556
|
-
isUserQuery: true,
|
|
557
|
-
contexts: [],
|
|
558
|
-
subAgents: [],
|
|
559
|
-
subAgentsChanged: false,
|
|
560
|
-
isFirstQuery: true,
|
|
561
|
-
sendMode: 'normal',
|
|
562
|
-
toolUseResults: [],
|
|
563
|
-
extendUserQueryInfo: { commands: [], skills: [], subagents: [], rules: [] },
|
|
564
|
-
extend: { isMultiWorkspace: false, useWorkflow: true },
|
|
565
|
-
...(systemPrompt ? { appendSystemPrompt: systemPrompt } : {}),
|
|
566
|
-
}, { signal, headerTimeoutMs, traceId })
|
|
567
|
-
const payload = await response.json().catch(() => null)
|
|
568
|
-
if (payload?.code !== 200 || !payload?.data?.id) throw agentFailure(payload, response.status)
|
|
569
|
-
return payload.data.id
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
async function createAgentTask(credential, { conversationId, traceId, signal, headerTimeoutMs }) {
|
|
573
|
-
const response = await postAgentJson(credential, '/task', {
|
|
574
|
-
...agentClientInfo(credential),
|
|
575
|
-
conversationId,
|
|
576
|
-
agentId: AGENT_ID,
|
|
577
|
-
agentInfo: AGENT_INFO,
|
|
578
|
-
}, { signal, headerTimeoutMs, traceId })
|
|
579
|
-
const payload = await response.json().catch(() => null)
|
|
580
|
-
if (payload?.code !== 200 || payload?.data?.taskId === undefined) throw agentFailure(payload, response.status)
|
|
581
|
-
return payload.data.taskId
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
async function executeAgent(credential, requestBody, { traceId, signal, headerTimeoutMs }) {
|
|
585
|
-
let response
|
|
586
|
-
try {
|
|
587
|
-
response = await httpFetch(`${resolveHost(credential)}${AGENT_BASE_PATH}/execute`, {
|
|
588
|
-
method: 'POST',
|
|
589
|
-
headers: agentHeaders(credential, { Accept: 'text/event-stream', 'X-Trace-Id': traceId }),
|
|
590
|
-
body: JSON.stringify(requestBody),
|
|
591
|
-
signal,
|
|
592
|
-
}, headerTimeoutMs)
|
|
593
|
-
} catch (error) {
|
|
594
|
-
if (signal?.aborted) throw error
|
|
595
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate 请求发送失败:${error?.message ?? error}` }
|
|
596
|
-
}
|
|
597
|
-
if (!response.ok) {
|
|
598
|
-
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
599
|
-
throw failureFrom(response.status, text)
|
|
600
|
-
}
|
|
601
|
-
if (!response.body) {
|
|
602
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate 返回空响应体' }
|
|
603
|
-
}
|
|
604
|
-
const contentType = response.headers.get('content-type') ?? ''
|
|
605
|
-
if (!contentType.includes('text/event-stream')) {
|
|
606
|
-
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
607
|
-
let payload = null
|
|
608
|
-
try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
|
|
609
|
-
throw agentFailure(payload ?? { message: extractMessage(text) || text.slice(0, 300) }, response.status)
|
|
610
|
-
}
|
|
611
|
-
return response
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
function readChunk(reader, timeoutMs, signal) {
|
|
615
|
-
return new Promise((resolve, reject) => {
|
|
616
|
-
let settled = false
|
|
617
|
-
const timer = setTimeout(() => finish(new Error('idle')), timeoutMs)
|
|
618
|
-
const onAbort = () => finish(new Error('abort'))
|
|
619
|
-
signal?.addEventListener('abort', onAbort, { once: true })
|
|
620
|
-
function finish(error) {
|
|
621
|
-
if (settled) return
|
|
622
|
-
settled = true
|
|
623
|
-
clearTimeout(timer)
|
|
624
|
-
signal?.removeEventListener('abort', onAbort)
|
|
625
|
-
reject(error)
|
|
626
|
-
}
|
|
627
|
-
reader.read().then(value => {
|
|
628
|
-
if (settled) return
|
|
629
|
-
settled = true
|
|
630
|
-
clearTimeout(timer)
|
|
631
|
-
signal?.removeEventListener('abort', onAbort)
|
|
632
|
-
resolve(value)
|
|
633
|
-
}, error => finish(error))
|
|
634
|
-
})
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
function ssePayload(rawLine) {
|
|
638
|
-
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
|
|
639
|
-
if (line === '' || line.startsWith(':') || line.startsWith('event:')) return undefined
|
|
640
|
-
if (!line.startsWith('data:')) return undefined
|
|
641
|
-
return line.slice(5).trim()
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
/**
|
|
645
|
-
* 消费 agent SSE:每帧 `{ content:{ type:'ANSWER', detail:{ delta, end } } }`,
|
|
646
|
-
* 把 detail.delta(增量文本)翻译成 OpenAI chunk 交给 emit。
|
|
647
|
-
*/
|
|
648
|
-
async function consumeAgentStream(body, emit, signal, idleTimeoutMs) {
|
|
649
|
-
const reader = body.getReader()
|
|
650
|
-
const decoder = new TextDecoder()
|
|
651
|
-
let buffer = ''
|
|
652
|
-
let sawContent = false
|
|
653
|
-
let failure = null
|
|
654
|
-
|
|
655
|
-
try {
|
|
656
|
-
for (;;) {
|
|
657
|
-
let chunk
|
|
658
|
-
try {
|
|
659
|
-
chunk = await readChunk(reader, sawContent ? idleTimeoutMs : IDLE_TIMEOUT_MS, signal)
|
|
660
|
-
} catch (error) {
|
|
661
|
-
if (signal?.aborted) throw Object.assign(new Error('已取消'), { name: 'AbortError' })
|
|
662
|
-
if (error instanceof Error && error.message === 'idle') throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate 流空闲超时(上游长时间未输出)' }
|
|
663
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate 流读取失败:${error?.message ?? error}` }
|
|
664
|
-
}
|
|
665
|
-
if (chunk.done) {
|
|
666
|
-
// 收尾:先刷解码器残留,再把 buffer 余量按整行走一遍(否则末帧被静默丢弃)。
|
|
667
|
-
buffer += decoder.decode()
|
|
668
|
-
const tail = buffer.split('\n')
|
|
669
|
-
buffer = ''
|
|
670
|
-
for (const rawLine of tail) {
|
|
671
|
-
const payload = ssePayload(rawLine)
|
|
672
|
-
if (payload !== undefined) processFrame(payload)
|
|
673
|
-
}
|
|
674
|
-
break
|
|
675
|
-
}
|
|
676
|
-
buffer += decoder.decode(chunk.value, { stream: true })
|
|
677
|
-
const lines = buffer.split('\n')
|
|
678
|
-
buffer = lines.pop() ?? ''
|
|
679
|
-
for (const rawLine of lines) {
|
|
680
|
-
const payload = ssePayload(rawLine)
|
|
681
|
-
if (payload !== undefined) processFrame(payload)
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
} finally {
|
|
685
|
-
reader.cancel().catch(() => {})
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
if (failure) throw failure
|
|
689
|
-
|
|
690
|
-
function processFrame(payload) {
|
|
691
|
-
if (payload === '' || payload === '[DONE]') return
|
|
692
|
-
let frame
|
|
693
|
-
try { frame = JSON.parse(payload) } catch { return }
|
|
694
|
-
if (frame === null || typeof frame !== 'object') return
|
|
695
|
-
|
|
696
|
-
const content = frame.content
|
|
697
|
-
const type = typeof content?.type === 'string' ? content.type : ''
|
|
698
|
-
const detail = content?.detail ?? {}
|
|
699
|
-
if (type === 'EXCEPTION') {
|
|
700
|
-
failure = { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate: ${detail.exceptionMsg || '会话执行异常'}` }
|
|
701
|
-
return
|
|
702
|
-
}
|
|
703
|
-
if (type === 'DOWNGRADE' || type === 'QUOTA_EXCEED') {
|
|
704
|
-
failure = { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message: `Comate: ${JSON.stringify(detail).slice(0, 200)}` }
|
|
705
|
-
return
|
|
706
|
-
}
|
|
707
|
-
if (type === 'NEED_RETRY_EXCEPTION') {
|
|
708
|
-
failure = { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate: ${detail.exceptionMsg || '会话执行需要重试'}` }
|
|
709
|
-
return
|
|
710
|
-
}
|
|
711
|
-
if (type !== 'ANSWER') return // TOKEN_USAGE / NOTIFICATION 等
|
|
712
|
-
|
|
713
|
-
const delta = typeof detail.delta === 'string' ? detail.delta : ''
|
|
714
|
-
if (delta === '') return
|
|
715
|
-
sawContent = true
|
|
716
|
-
emit({ choices: [{ index: 0, delta: { content: delta }, finish_reason: null }] })
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
return { sawContent }
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
/**
|
|
723
|
-
* 解析调用参数:干净 id → 完整上游 modelId + 思考参数。
|
|
724
|
-
* 映射表由 fetchModels 实时清单填充;未命中时按需拉一次清单(同一进程只补一次),
|
|
725
|
-
* 仍拿不到就退回「传入 id 原样调用 + 默认思考参数」。
|
|
726
|
-
*/
|
|
727
|
-
async function resolveModelCall(credential, requestedModel) {
|
|
728
|
-
const hit = modelMeta.get(requestedModel)
|
|
729
|
-
if (hit) return hit
|
|
730
|
-
const { clean } = splitModelId(requestedModel)
|
|
731
|
-
const cached = modelMeta.get(clean)
|
|
732
|
-
if (cached) return cached
|
|
733
|
-
try {
|
|
734
|
-
await fetchModels(credential) // 拉清单即刷新 modelMeta
|
|
735
|
-
} catch { /* 拉不到就按兜底处理 */ }
|
|
736
|
-
return modelMeta.get(requestedModel)
|
|
737
|
-
?? modelMeta.get(clean)
|
|
738
|
-
?? { cleanId: clean, upstreamId: requestedModel, thinkingEnabled: false, effort: 'medium' }
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
/** 单账号一轮对话:新建会话/任务后走 agent execute 流,本地聚合成完整 OpenAI 响应。 */
|
|
742
|
-
export async function complete(credential, body, { signal, onData, headerTimeoutMs = REQUEST_TIMEOUT_MS } = {}) {
|
|
743
|
-
const authName = agentAuthName(credential)
|
|
744
|
-
if (!authName) {
|
|
745
|
-
throw { kind: 'auth', retryable: false, terminal: true, message: 'Comate 凭据缺少 license/username,请重新登录' }
|
|
746
|
-
}
|
|
747
|
-
const requestedModel = typeof body.model === 'string' ? body.model : ''
|
|
748
|
-
if (requestedModel === '') {
|
|
749
|
-
throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Comate: 缺少模型名称' }
|
|
750
|
-
}
|
|
751
|
-
const { systemPrompt, query } = buildAgentQuery(body.messages)
|
|
752
|
-
if (query === '') {
|
|
753
|
-
throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Comate: messages 里没有可用内容' }
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
// 干净 id(如 glm-5.2)→ 完整上游 modelId(glm-5.2_50c5…),并带上该模型的思考参数
|
|
757
|
-
const call = await resolveModelCall(credential, requestedModel)
|
|
758
|
-
const upstreamModel = call.upstreamId
|
|
759
|
-
const traceId = randomUUID()
|
|
760
|
-
const conversationId = await createAgentConversation(credential, {
|
|
761
|
-
query, systemPrompt, model: upstreamModel, traceId, signal, headerTimeoutMs,
|
|
762
|
-
})
|
|
763
|
-
const taskId = await createAgentTask(credential, { conversationId, traceId, signal, headerTimeoutMs })
|
|
764
|
-
|
|
765
|
-
const response = await executeAgent(credential, {
|
|
766
|
-
...agentClientInfo(credential),
|
|
767
|
-
taskId,
|
|
768
|
-
conversationId,
|
|
769
|
-
agentId: AGENT_ID,
|
|
770
|
-
agentInfo: AGENT_INFO,
|
|
771
|
-
uploadBaseInfo: {},
|
|
772
|
-
query,
|
|
773
|
-
modelKey: upstreamModel,
|
|
774
|
-
thinkingEnabled: call.thinkingEnabled,
|
|
775
|
-
effort: call.effort,
|
|
776
|
-
contextWindow: 131_072,
|
|
777
|
-
sysInfo: {},
|
|
778
|
-
skillInfos: [],
|
|
779
|
-
hasMcp: false,
|
|
780
|
-
isUserQuery: true,
|
|
781
|
-
localIndex: false,
|
|
782
|
-
contexts: [],
|
|
783
|
-
subAgents: [],
|
|
784
|
-
subAgentsChanged: false,
|
|
785
|
-
isFirstQuery: true,
|
|
786
|
-
systemReminder: '',
|
|
787
|
-
...(systemPrompt ? { appendSystemPrompt: systemPrompt } : {}),
|
|
788
|
-
extendUserQueryInfo: { commands: [], skills: [], subagents: [], rules: [] },
|
|
789
|
-
extend: { isMultiWorkspace: false, useWorkflow: true },
|
|
790
|
-
toolUseResults: [],
|
|
791
|
-
sendMode: 'normal',
|
|
792
|
-
traceId,
|
|
793
|
-
}, { traceId, signal, headerTimeoutMs })
|
|
794
|
-
|
|
795
|
-
const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
|
|
796
|
-
const created = Math.floor(Date.now() / 1000)
|
|
797
|
-
const chunks = []
|
|
798
|
-
let firstChunk = true
|
|
799
|
-
const emit = chunk => {
|
|
800
|
-
const full = {
|
|
801
|
-
id: chunkId,
|
|
802
|
-
object: 'chat.completion.chunk',
|
|
803
|
-
created,
|
|
804
|
-
model: requestedModel,
|
|
805
|
-
choices: chunk.choices.map(choice => ({
|
|
806
|
-
...choice,
|
|
807
|
-
delta: firstChunk ? { role: 'assistant', ...choice.delta } : choice.delta,
|
|
808
|
-
})),
|
|
809
|
-
}
|
|
810
|
-
firstChunk = false
|
|
811
|
-
chunks.push(full)
|
|
812
|
-
onData?.(JSON.stringify(full))
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
const consumed = await consumeAgentStream(response.body, emit, signal, IDLE_TIMEOUT_MS)
|
|
816
|
-
if (!consumed.sawContent) {
|
|
817
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate: 模型未返回任何内容' }
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
const final = { id: chunkId, object: 'chat.completion.chunk', created, model: requestedModel, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }
|
|
821
|
-
chunks.push(final)
|
|
822
|
-
onData?.(JSON.stringify(final))
|
|
823
|
-
|
|
824
|
-
const merged = mergeSseChunks(chunks.map(chunk => JSON.stringify(chunk)))
|
|
825
|
-
if (!merged || !merged.choices?.[0]) {
|
|
826
|
-
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate 流结束但没有内容帧' }
|
|
827
|
-
}
|
|
828
|
-
merged.model = requestedModel
|
|
829
|
-
return { status: response.status, json: merged }
|
|
830
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Comate(百度文心快码)渠道。
|
|
3
|
+
*
|
|
4
|
+
* 协议要点:
|
|
5
|
+
* - 宿主:saas https://comate.baidu.com / internal https://comate.baidu-int.com
|
|
6
|
+
* saas-test https://comate-external-test.now.baidu.com
|
|
7
|
+
* internal-test https://comate-test.now.baidu-int.com
|
|
8
|
+
* - 鉴权:**不用 Bearer**。SaaS 的 license 同时放进请求头
|
|
9
|
+
* `login-name` / `Uuap-login-name`(encodeURIComponent)与 body 的 `username`。
|
|
10
|
+
* - 模型清单:GET {host}/api/v2/api/models/available?key={license}&type=ZULU&loopVersion=v2
|
|
11
|
+
* → data 数组,字段 modelId / modelType / displayName / maxContextWindow(单位 K tokens)/
|
|
12
|
+
* ratio(倍率字符串,如 "0.3x")/ supportImage / supportThinking
|
|
13
|
+
* - 模型 id:上游 modelId 形如 `glm-4.7-fc_0b87452a03394418b5c8d5468deff6c7`,
|
|
14
|
+
* 前半段是模型类型(= modelType),后半段是 32 位十六进制实例标识(界面上的「乱码」)。
|
|
15
|
+
* 对外(目录/界面)暴露干净 id(modelType),真实调用仍用完整 modelId ——
|
|
16
|
+
* 部分模型(实测 glm-5.2)只认完整 modelId,短 id 会被上游拒为「令牌状态不可用」。
|
|
17
|
+
* - 对话(新版多个模型已不再接受旧的 generate 端点,改走 agent 协议):
|
|
18
|
+
* POST {host}/api/aidevops/autocomate/rest/autowork/v2/conversation → { data:{ id } }
|
|
19
|
+
* POST {host}/api/aidevops/autocomate/rest/autowork/v2/task → { data:{ taskId } }
|
|
20
|
+
* POST {host}/api/aidevops/autocomate/rest/autowork/v2/execute → SSE
|
|
21
|
+
* - SSE 帧:`{ content:{ type:'ANSWER', detail:{ delta, end } } }`,delta 是增量文本;
|
|
22
|
+
* type 还可能是 TOKEN_USAGE / NOTIFICATION / EXCEPTION / QUOTA_EXCEED 等。
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
26
|
+
import { arch, hostname, release, type as osType, userInfo } from 'node:os'
|
|
27
|
+
import { httpFetch, readBodyText, mergeSseChunks } from '../util.js'
|
|
28
|
+
|
|
29
|
+
// ── 产品常量 ────────────────────────────────────────────────────────────────
|
|
30
|
+
|
|
31
|
+
const HOST_SAAS = 'https://comate.baidu.com'
|
|
32
|
+
const HOST_INTERNAL = 'https://comate.baidu-int.com'
|
|
33
|
+
const HOST_SAAS_TEST = 'https://comate-external-test.now.baidu.com'
|
|
34
|
+
const HOST_INTERNAL_TEST = 'https://comate-test.now.baidu-int.com'
|
|
35
|
+
|
|
36
|
+
const MODELS_PATH = '/api/v2/api/models/available'
|
|
37
|
+
const AGENT_BASE_PATH = '/api/aidevops/autocomate/rest/autowork/v2'
|
|
38
|
+
|
|
39
|
+
/** 新版 agent 协议固定参数(取自 getRequestUserHeader / getRequestClienInfo)。 */
|
|
40
|
+
const AGENT_ID = 'general'
|
|
41
|
+
const AGENT_INFO = { agentName: 'General', isProjectAgent: false, canInvokeAgents: false }
|
|
42
|
+
const AGENT_PLUGIN_VERSION = '4.14.1'
|
|
43
|
+
const AGENT_PLUGIN_HEADER = 'VsCode-4.14.1'
|
|
44
|
+
|
|
45
|
+
/** IDE 版本伪装(agentClientInfo / 登录 device 描述)。 */
|
|
46
|
+
const IDE_VERSION = '1.96.0'
|
|
47
|
+
|
|
48
|
+
const REQUEST_TIMEOUT_MS = 30_000
|
|
49
|
+
const IDLE_TIMEOUT_MS = 120_000
|
|
50
|
+
const BODY_READ_TIMEOUT_MS = 15_000
|
|
51
|
+
const MODELS_TIMEOUT_MS = 20_000
|
|
52
|
+
|
|
53
|
+
/** 实时清单没给输出上限;按上游常见值给一个保守估计(仅目录展示用)。 */
|
|
54
|
+
const DEFAULT_MAX_OUTPUT = 8192
|
|
55
|
+
|
|
56
|
+
// ── 模型目录 ───────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
export const meta = { id: 'comate', label: 'Comate', loginMode: 'external-link', localLogin: true }
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 上游 modelId 形如 `glm-4.7-fc_0b87452a03394418b5c8d5468deff6c7`:
|
|
62
|
+
* 前半段是模型类型(= modelType),后半段是 32 位十六进制实例标识(界面上的「乱码」)。
|
|
63
|
+
* 对外只暴露前半段(干净 id),真实调用仍用完整 modelId。
|
|
64
|
+
*/
|
|
65
|
+
function splitModelId(modelId) {
|
|
66
|
+
const text = String(modelId ?? '').trim()
|
|
67
|
+
const at = text.indexOf('_')
|
|
68
|
+
if (at <= 0) return { clean: text, full: text }
|
|
69
|
+
const suffix = text.slice(at + 1)
|
|
70
|
+
if (!/^[0-9a-f]{32}$/i.test(suffix)) return { clean: text, full: text }
|
|
71
|
+
return { clean: text.slice(0, at), full: text }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 模型调用参数缓存:干净 id / 完整 modelId → { cleanId, upstreamId, thinkingEnabled, effort }。
|
|
76
|
+
* 每次 fetchModels 实时清单都会刷新(清单拉不到就不会产出目录行,也就不会调用)。
|
|
77
|
+
*/
|
|
78
|
+
const modelMeta = new Map()
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 思考参数推导:
|
|
82
|
+
* - supportAdaptiveThinking=false 且 supportEffort ∈ {low, high, max} 的模型「始终思考」,
|
|
83
|
+
* 必须 thinkingEnabled=true 且 effort 用 low/high/max(用 medium 或关思考会被上游拒:
|
|
84
|
+
* 「该模型始终思考,不支持关闭思考;请使用 low、high 或 max」)。
|
|
85
|
+
* - 其余模型保持默认关闭思考 + medium。
|
|
86
|
+
*/
|
|
87
|
+
function thinkingParams(item) {
|
|
88
|
+
const effortRaw = typeof item.supportEffort === 'string' ? item.supportEffort.trim().toLowerCase() : ''
|
|
89
|
+
const alwaysThinking = item.supportThinking === true
|
|
90
|
+
&& item.supportAdaptiveThinking === false
|
|
91
|
+
&& (effortRaw === 'low' || effortRaw === 'high' || effortRaw === 'max')
|
|
92
|
+
return {
|
|
93
|
+
thinkingEnabled: alwaysThinking,
|
|
94
|
+
effort: alwaysThinking ? effortRaw : 'medium',
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 在线登录常量(SaaS 网页登录握手):
|
|
99
|
+
// 1. 生成 clientId(UUID),打开 {host}/zh/login?track=VSCODE&clientId=…&device=…
|
|
100
|
+
// —— 浏览器已登录时会直接把登录态绑定到该 clientId(无需再次输入账号)
|
|
101
|
+
// 2. 轮询 GET /api/client/generate/token?clientId=… → { status:'OK', data: <临时 token> }
|
|
102
|
+
// 3. GET /api/client/key?clientId=…(请求头 token: <临时 token>)
|
|
103
|
+
// → { status:'OK', data:{ key: <license>, displayName, userAvatarUrl } }
|
|
104
|
+
// 4. license 即生成接口 body 里的 `key` 字段,入库后即可直接调用
|
|
105
|
+
const LOGIN_PAGE_PATH = '/zh/login'
|
|
106
|
+
const CLIENT_TOKEN_PATH = '/api/client/generate/token'
|
|
107
|
+
const CLIENT_KEY_PATH = '/api/client/key'
|
|
108
|
+
const LOGIN_DEVICE_VERSION = '4.14.1' // 仅用于 device 描述,不影响绑定
|
|
109
|
+
const LOGIN_WAIT_TIMEOUT_MS = 5 * 60_000 // 5 分钟等待用户在浏览器完成登录
|
|
110
|
+
const LOGIN_POLL_INTERVAL_MS = 2_000
|
|
111
|
+
const LOGIN_POLL_TIMEOUT_MS = 15_000
|
|
112
|
+
|
|
113
|
+
// ── 小工具 ─────────────────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
function readStringField(source, key) {
|
|
116
|
+
const value = source?.[key]
|
|
117
|
+
if (typeof value === 'string' && value.trim().length > 0) return value.trim()
|
|
118
|
+
return ''
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 由 credential 的 platform 推导 API 宿主。 */
|
|
122
|
+
function resolveHost(credential) {
|
|
123
|
+
const explicit = readStringField(credential, 'apiHost')
|
|
124
|
+
if (explicit) return explicit.replace(/\/+$/, '')
|
|
125
|
+
const platform = readStringField(credential, 'platform') || 'saas'
|
|
126
|
+
const test = credential?.environment === 'test' || credential?.test === true
|
|
127
|
+
if (platform === 'internal') return test ? HOST_INTERNAL_TEST : HOST_INTERNAL
|
|
128
|
+
return test ? HOST_SAAS_TEST : HOST_SAAS
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ── 凭据 ───────────────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
export function normalizeCredential(raw) {
|
|
134
|
+
let value = raw
|
|
135
|
+
if (typeof value === 'string') {
|
|
136
|
+
const text = value.trim()
|
|
137
|
+
// 裸 license 串(常见:直接复制 token)也接受。
|
|
138
|
+
if (!text.startsWith('{')) {
|
|
139
|
+
if (text === '') throw new Error('凭据为空')
|
|
140
|
+
return { license: text, username: text, platform: 'saas' }
|
|
141
|
+
}
|
|
142
|
+
try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
|
|
143
|
+
}
|
|
144
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
145
|
+
throw new Error('凭据必须是 JSON 对象或 license 字符串')
|
|
146
|
+
}
|
|
147
|
+
const license = readStringField(value, 'license') || readStringField(value, 'key')
|
|
148
|
+
|| readStringField(value, 'access_token') || readStringField(value, 'token')
|
|
149
|
+
const username = readStringField(value, 'username') || readStringField(value, 'name')
|
|
150
|
+
if (!license && !username) throw new Error('凭据缺少 license(或 username)')
|
|
151
|
+
const out = { ...value, license: license || username, username: username || license }
|
|
152
|
+
const platform = readStringField(value, 'platform') || readStringField(value, 'server')
|
|
153
|
+
out.platform = platform === 'internal' || platform === 'poc' ? platform : 'saas'
|
|
154
|
+
if (readStringField(value, 'apiHost')) out.apiHost = readStringField(value, 'apiHost')
|
|
155
|
+
if (readStringField(value, 'version')) out.version = readStringField(value, 'version')
|
|
156
|
+
return out
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function describeCredential(credential) {
|
|
160
|
+
const username = readStringField(credential, 'username')
|
|
161
|
+
return {
|
|
162
|
+
label: username || 'Comate 账号',
|
|
163
|
+
expiresAt: 0,
|
|
164
|
+
refreshable: false,
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 去重键:username + 平台(同人不同环境视为不同账号)。 */
|
|
169
|
+
export function credentialIdentity(credential) {
|
|
170
|
+
const username = readStringField(credential, 'username') || readStringField(credential, 'license')
|
|
171
|
+
if (!username) return ''
|
|
172
|
+
return `${readStringField(credential, 'platform') || 'saas'}:${username}`
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function needsRefresh() {
|
|
176
|
+
return false
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export async function refreshCredential(credential) {
|
|
180
|
+
// Comate 的 license 无续期机制,失效只能重登。
|
|
181
|
+
throw { kind: 'auth', retryable: false, terminal: true, message: 'Comate 凭据无法自动续期,请重新登录' }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ── 模型清单 ───────────────────────────────────────────────────────────────
|
|
185
|
+
|
|
186
|
+
function normalizeRemoteModels(payload) {
|
|
187
|
+
const raw = payload?.data?.data ?? payload?.data ?? payload
|
|
188
|
+
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.models) ? raw.models : []
|
|
189
|
+
const out = []
|
|
190
|
+
const seen = new Set()
|
|
191
|
+
for (const item of list) {
|
|
192
|
+
if (item === null || typeof item !== 'object') continue
|
|
193
|
+
if (item.enabled === false) continue
|
|
194
|
+
const rawId = readStringField(item, 'modelId') || readStringField(item, 'model')
|
|
195
|
+
|| readStringField(item, 'name') || readStringField(item, 'id')
|
|
196
|
+
if (!rawId) continue
|
|
197
|
+
// 上游 modelId 带 32 位实例后缀;对外只暴露干净 id(modelType),调用用完整 modelId
|
|
198
|
+
const { clean, full } = splitModelId(rawId)
|
|
199
|
+
if (seen.has(clean)) continue
|
|
200
|
+
seen.add(clean)
|
|
201
|
+
// maxContextWindow 单位是 K tokens(如 1000 = 约 100 万)
|
|
202
|
+
const rawContext = Number(item.maxContextWindow)
|
|
203
|
+
const contextWindow = Number.isFinite(rawContext) && rawContext > 0
|
|
204
|
+
? Math.round(rawContext * 1024)
|
|
205
|
+
: 8192
|
|
206
|
+
// ratio 是倍率字符串("0.3x" / "1x"),供卡片和目录展示
|
|
207
|
+
const ratio = typeof item.ratio === 'string' ? Number.parseFloat(item.ratio) : Number.NaN
|
|
208
|
+
const thinking = thinkingParams(item)
|
|
209
|
+
modelMeta.set(clean, { cleanId: clean, upstreamId: full, ...thinking })
|
|
210
|
+
modelMeta.set(full, { cleanId: clean, upstreamId: full, ...thinking })
|
|
211
|
+
out.push({
|
|
212
|
+
id: clean,
|
|
213
|
+
upstreamId: full,
|
|
214
|
+
name: readStringField(item, 'displayName') || readStringField(item, 'title')
|
|
215
|
+
|| readStringField(item, 'name') || clean,
|
|
216
|
+
contextWindow,
|
|
217
|
+
maxTokens: DEFAULT_MAX_OUTPUT,
|
|
218
|
+
supportsImage: item.supportImage === true,
|
|
219
|
+
isFree: true,
|
|
220
|
+
...(Number.isFinite(ratio) ? { rate: ratio } : {}),
|
|
221
|
+
})
|
|
222
|
+
}
|
|
223
|
+
return out
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Comate 实时模型清单:两种请求形态各自尝试,全部失败/空清单即抛错(目录只认实时结果)。
|
|
228
|
+
*/
|
|
229
|
+
export async function fetchModels(credential) {
|
|
230
|
+
if (!credential) throw new Error('Comate 缺少凭据,请先添加账号')
|
|
231
|
+
const host = resolveHost(credential)
|
|
232
|
+
const license = readStringField(credential, 'license')
|
|
233
|
+
const username = readStringField(credential, 'username')
|
|
234
|
+
const reasons = []
|
|
235
|
+
if (license.length === 0 && username.length === 0) {
|
|
236
|
+
throw new Error('Comate 凭据缺少 license / username,无法拉取模型清单')
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// 形态一:GET + key(loopVersion=v2,SaaS 全量目录)。
|
|
240
|
+
if (license) {
|
|
241
|
+
try {
|
|
242
|
+
const url = `${host}${MODELS_PATH}?key=${encodeURIComponent(license)}&type=ZULU&loopVersion=v2`
|
|
243
|
+
const response = await httpFetch(url, { method: 'GET', headers: { Accept: 'application/json' } }, MODELS_TIMEOUT_MS)
|
|
244
|
+
if (response.ok) {
|
|
245
|
+
const models = normalizeRemoteModels(await response.json().catch(() => null))
|
|
246
|
+
if (models.length > 0) return models
|
|
247
|
+
reasons.push('license 形态返回空清单')
|
|
248
|
+
} else {
|
|
249
|
+
const text = await response.text().catch(() => '')
|
|
250
|
+
reasons.push(`license 形态 HTTP ${response.status}${extractMessage(text) ? `:${extractMessage(text)}` : ''}`)
|
|
251
|
+
}
|
|
252
|
+
} catch (error) {
|
|
253
|
+
reasons.push(`license 形态异常:${error?.message ?? error}`)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// 形态二:POST + username(ZULU 场景)。
|
|
257
|
+
if (username) {
|
|
258
|
+
try {
|
|
259
|
+
const response = await httpFetch(`${host}${MODELS_PATH}`, {
|
|
260
|
+
method: 'POST',
|
|
261
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
262
|
+
body: JSON.stringify({ username, type: 'ZULU', rootRepo: '', submodules: [] }),
|
|
263
|
+
}, MODELS_TIMEOUT_MS)
|
|
264
|
+
if (response.ok) {
|
|
265
|
+
const models = normalizeRemoteModels(await response.json().catch(() => null))
|
|
266
|
+
if (models.length > 0) return models
|
|
267
|
+
reasons.push('username 形态返回空清单')
|
|
268
|
+
} else {
|
|
269
|
+
const text = await response.text().catch(() => '')
|
|
270
|
+
reasons.push(`username 形态 HTTP ${response.status}${extractMessage(text) ? `:${extractMessage(text)}` : ''}`)
|
|
271
|
+
}
|
|
272
|
+
} catch (error) {
|
|
273
|
+
reasons.push(`username 形态异常:${error?.message ?? error}`)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
throw new Error(`Comate 模型清单获取失败:${reasons.join(';')}`)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ── 在线登录(网页登录握手)──────────────────────────────────────────────
|
|
280
|
+
//
|
|
281
|
+
// SaaS Comate 支持把浏览器登录态绑定到临时 clientId:
|
|
282
|
+
// loginUrl = {host}/zh/login?track=VSCODE&clientId=…&device=…
|
|
283
|
+
// 浏览器已登录时页面直接列出账号,用户点「授权登录」即完成绑定
|
|
284
|
+
// → 轮询 /api/client/generate/token 拿到临时 token
|
|
285
|
+
// → /api/client/key(header token)换发 license → resolve 入库
|
|
286
|
+
// 用户也可通过 POST /admin/api/channels/comate/credential 手动粘贴(resolveLoginCredential)。
|
|
287
|
+
|
|
288
|
+
/** device 描述。 */
|
|
289
|
+
function loginDeviceText() {
|
|
290
|
+
try {
|
|
291
|
+
const platform = osType()
|
|
292
|
+
const osName = platform === 'Windows_NT' ? 'Windows' : platform === 'Darwin' ? 'Mac OS' : platform
|
|
293
|
+
return `${userInfo().username} ${hostname()} (${osName} ${arch()} ${release()})`
|
|
294
|
+
} catch {
|
|
295
|
+
return `comate ${LOGIN_DEVICE_VERSION}`
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function buildLoginUrl(clientId) {
|
|
300
|
+
const query = `track=VSCODE&clientId=${encodeURIComponent(clientId)}&device=${encodeURIComponent(loginDeviceText())}`
|
|
301
|
+
return `${HOST_SAAS}${LOGIN_PAGE_PATH}?${query}`
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** 可被 signal 中断的睡眠(登录轮询用)。 */
|
|
305
|
+
function sleepAbortable(ms, signal) {
|
|
306
|
+
return new Promise((resolve, reject) => {
|
|
307
|
+
if (signal?.aborted) { reject(new Error('登录已取消')); return }
|
|
308
|
+
const timer = setTimeout(() => {
|
|
309
|
+
signal?.removeEventListener('abort', onAbort)
|
|
310
|
+
resolve()
|
|
311
|
+
}, ms)
|
|
312
|
+
const onAbort = () => { clearTimeout(timer); reject(new Error('登录已取消')) }
|
|
313
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
314
|
+
timer.unref?.()
|
|
315
|
+
})
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 轮询一次绑定结果:拿到临时 token 后用 token 换发 license。
|
|
320
|
+
* 未完成(用户还没登录/绑定)返回 null;换发 license 明确失败时抛错。
|
|
321
|
+
*/
|
|
322
|
+
async function pollLogin(clientId, signal) {
|
|
323
|
+
const tokenResponse = await httpFetch(`${HOST_SAAS}${CLIENT_TOKEN_PATH}?clientId=${encodeURIComponent(clientId)}`, {
|
|
324
|
+
method: 'GET',
|
|
325
|
+
headers: { Accept: 'application/json' },
|
|
326
|
+
signal,
|
|
327
|
+
}, LOGIN_POLL_TIMEOUT_MS)
|
|
328
|
+
if (!tokenResponse.ok) return null
|
|
329
|
+
const tokenPayload = await tokenResponse.json().catch(() => null)
|
|
330
|
+
if (tokenPayload?.status !== 'OK' || !tokenPayload.data) return null
|
|
331
|
+
|
|
332
|
+
const keyResponse = await httpFetch(`${HOST_SAAS}${CLIENT_KEY_PATH}?clientId=${encodeURIComponent(clientId)}`, {
|
|
333
|
+
method: 'GET',
|
|
334
|
+
headers: { Accept: 'application/json', token: String(tokenPayload.data) },
|
|
335
|
+
signal,
|
|
336
|
+
}, LOGIN_POLL_TIMEOUT_MS)
|
|
337
|
+
const keyPayload = await keyResponse.json().catch(() => null)
|
|
338
|
+
if (keyPayload?.status !== 'OK' || !keyPayload.data) {
|
|
339
|
+
const message = typeof keyPayload?.message === 'string' ? keyPayload.message : ''
|
|
340
|
+
throw new Error(`Comate 登录换发 license 失败${message ? `:${message}` : ''}`)
|
|
341
|
+
}
|
|
342
|
+
const info = keyPayload.data
|
|
343
|
+
const license = readStringField(info, 'key')
|
|
344
|
+
if (license === '') throw new Error('Comate 登录响应缺少 license(key)')
|
|
345
|
+
const username = readStringField(info, 'displayName') || readStringField(info, 'username')
|
|
346
|
+
|| readStringField(info, 'name') || license
|
|
347
|
+
return { license, username, platform: 'saas' }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// 用于 startLogin 内部:admin.js 在 POST credential 后 resolve 这个 promise
|
|
351
|
+
let _pendingLicensePromise = null
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* startLogin()
|
|
355
|
+
* 返回 { loginUrl, promise, cancel() }:
|
|
356
|
+
* loginUrl 立即可用;promise 在浏览器完成绑定后自动 resolve 出凭据;
|
|
357
|
+
* 手动「粘贴凭据添加」会经 resolveLoginCredential 收敛同一个 promise。
|
|
358
|
+
*/
|
|
359
|
+
export function startLogin() {
|
|
360
|
+
const controller = new AbortController()
|
|
361
|
+
const signal = controller.signal
|
|
362
|
+
const clientId = randomUUID()
|
|
363
|
+
let settled = false
|
|
364
|
+
let resolveFlow = null
|
|
365
|
+
let rejectFlow = null
|
|
366
|
+
|
|
367
|
+
const promise = new Promise((resolve, reject) => {
|
|
368
|
+
resolveFlow = resolve
|
|
369
|
+
rejectFlow = reject
|
|
370
|
+
})
|
|
371
|
+
promise.catch(() => {}) // 防未处理拒绝告警;错误仍会传给消费者
|
|
372
|
+
|
|
373
|
+
function finish(settle) {
|
|
374
|
+
if (settled) return
|
|
375
|
+
settled = true
|
|
376
|
+
_pendingLicensePromise = null
|
|
377
|
+
settle()
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
_pendingLicensePromise = {
|
|
381
|
+
resolve: credential => finish(() => resolveFlow(credential)),
|
|
382
|
+
reject: error => finish(() => rejectFlow(error instanceof Error ? error : new Error(String(error)))),
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const run = async () => {
|
|
386
|
+
const deadline = Date.now() + LOGIN_WAIT_TIMEOUT_MS
|
|
387
|
+
while (!settled && Date.now() < deadline) {
|
|
388
|
+
try {
|
|
389
|
+
const credential = await pollLogin(clientId, signal)
|
|
390
|
+
if (credential) { finish(() => resolveFlow(credential)); return }
|
|
391
|
+
} catch (error) {
|
|
392
|
+
if (settled) return
|
|
393
|
+
if (signal.aborted) { finish(() => rejectFlow(new Error('登录已取消'))); return }
|
|
394
|
+
// 换发 license 的明确失败直接终止;网络抖动按未完成继续轮询
|
|
395
|
+
if (error instanceof Error && error.message.startsWith('Comate 登录')) {
|
|
396
|
+
finish(() => rejectFlow(error))
|
|
397
|
+
return
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
try { await sleepAbortable(LOGIN_POLL_INTERVAL_MS, signal) } catch { return }
|
|
401
|
+
}
|
|
402
|
+
finish(() => rejectFlow(new Error('登录等待已超时,请重新发起登录')))
|
|
403
|
+
}
|
|
404
|
+
void run()
|
|
405
|
+
|
|
406
|
+
return {
|
|
407
|
+
loginUrl: buildLoginUrl(clientId),
|
|
408
|
+
promise,
|
|
409
|
+
cancel: () => {
|
|
410
|
+
if (settled) return
|
|
411
|
+
controller.abort()
|
|
412
|
+
finish(() => rejectFlow(new Error('登录已取消')))
|
|
413
|
+
},
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// 由 admin.js 在 credential 路由调用:若当前有 pending 登录,把 credential 注入
|
|
418
|
+
// 使 startLogin 的 promise 正常 resolve;无 pending 时静默 no-op
|
|
419
|
+
export function resolveLoginCredential(credential) {
|
|
420
|
+
const p = _pendingLicensePromise
|
|
421
|
+
if (!p) return
|
|
422
|
+
_pendingLicensePromise = null
|
|
423
|
+
p.resolve(credential)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// ── 对话 ───────────────────────────────────────────────────────────────────
|
|
427
|
+
|
|
428
|
+
function failureFrom(status, bodyText) {
|
|
429
|
+
const lower = String(bodyText ?? '').toLowerCase()
|
|
430
|
+
const message = extractMessage(bodyText) || `Comate HTTP ${status}`
|
|
431
|
+
if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
432
|
+
if (status === 402 || /quota|balance|insufficient|额度|余额|限流|exceeded/.test(lower)) {
|
|
433
|
+
return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
|
|
434
|
+
}
|
|
435
|
+
if (status === 401 || status === 403) {
|
|
436
|
+
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
437
|
+
}
|
|
438
|
+
if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
|
|
439
|
+
if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
440
|
+
if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
|
|
441
|
+
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function extractMessage(bodyText) {
|
|
445
|
+
const text = String(bodyText ?? '').trim()
|
|
446
|
+
if (text === '') return ''
|
|
447
|
+
try {
|
|
448
|
+
const parsed = JSON.parse(text)
|
|
449
|
+
const found = [
|
|
450
|
+
typeof parsed?.message === 'string' ? parsed.message : '',
|
|
451
|
+
typeof parsed?.msg === 'string' ? parsed.msg : '',
|
|
452
|
+
typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
|
|
453
|
+
typeof parsed?.error === 'string' ? parsed.error : '',
|
|
454
|
+
].filter(v => v.length > 0)
|
|
455
|
+
if (found.length > 0) return found.join(' ').slice(0, 300)
|
|
456
|
+
} catch { /* 非 JSON */ }
|
|
457
|
+
return text.slice(0, 300)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** OpenAI messages → agent 协议的单条 query + 可选 system prompt。 */
|
|
461
|
+
function buildAgentQuery(messages) {
|
|
462
|
+
const systemParts = []
|
|
463
|
+
const turns = []
|
|
464
|
+
for (const msg of Array.isArray(messages) ? messages : []) {
|
|
465
|
+
if (msg === null || typeof msg !== 'object') continue
|
|
466
|
+
const text = typeof msg.content === 'string'
|
|
467
|
+
? msg.content
|
|
468
|
+
: Array.isArray(msg.content)
|
|
469
|
+
? msg.content.map(part => (typeof part === 'string' ? part : typeof part?.text === 'string' ? part.text : '')).join('')
|
|
470
|
+
: ''
|
|
471
|
+
if (text === '') continue
|
|
472
|
+
if (msg.role === 'system' || msg.role === 'developer') { systemParts.push(text); continue }
|
|
473
|
+
turns.push({ role: msg.role === 'assistant' ? 'Assistant' : 'User', text })
|
|
474
|
+
}
|
|
475
|
+
// 单轮用户输入不额外加角色前缀;多轮历史按角色拼成一段对话上下文
|
|
476
|
+
const query = turns.length === 1 && turns[0].role === 'User'
|
|
477
|
+
? turns[0].text
|
|
478
|
+
: turns.map(turn => `${turn.role}: ${turn.text}`).join('\n\n')
|
|
479
|
+
return { systemPrompt: systemParts.join('\n\n'), query }
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** agent 协议的鉴权名:SaaS 用 license,internal 用 username(对应 kernel.config.key)。 */
|
|
483
|
+
function agentAuthName(credential) {
|
|
484
|
+
return readStringField(credential, 'license') || readStringField(credential, 'username')
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function agentHeaders(credential, extra = {}) {
|
|
488
|
+
const name = encodeURIComponent(agentAuthName(credential))
|
|
489
|
+
return {
|
|
490
|
+
'Content-Type': 'application/json',
|
|
491
|
+
'login-name': name,
|
|
492
|
+
'Uuap-login-name': name,
|
|
493
|
+
'X-Source': 'COMATE',
|
|
494
|
+
'plugin-version': AGENT_PLUGIN_HEADER,
|
|
495
|
+
'x-skip-fcnap': 'yes',
|
|
496
|
+
...extra,
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** getRequestClienInfo 逐字:username = license(SaaS)。 */
|
|
501
|
+
function agentClientInfo(credential) {
|
|
502
|
+
return {
|
|
503
|
+
username: agentAuthName(credential),
|
|
504
|
+
ide: 'VsCode',
|
|
505
|
+
ideVersion: IDE_VERSION,
|
|
506
|
+
pluginVersion: AGENT_PLUGIN_VERSION,
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** agent 接口用 HTTP 200 + body.code 表达业务错误。 */
|
|
511
|
+
function agentFailure(payload, status = 0) {
|
|
512
|
+
const message = (typeof payload?.message === 'string' && payload.message.trim())
|
|
513
|
+
|| (typeof payload?.msg === 'string' && payload.msg.trim())
|
|
514
|
+
|| (status > 0 ? `Comate HTTP ${status}` : 'Comate 请求失败')
|
|
515
|
+
if (payload?.code === 401 || status === 401 || status === 403) {
|
|
516
|
+
return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
|
|
517
|
+
}
|
|
518
|
+
if (payload?.code === 429 || status === 429) {
|
|
519
|
+
return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
|
|
520
|
+
}
|
|
521
|
+
if (/quota|limit|额度|余额|超过限制/i.test(message)) {
|
|
522
|
+
return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message }
|
|
523
|
+
}
|
|
524
|
+
return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
async function postAgentJson(credential, pathName, requestBody, { signal, headerTimeoutMs, traceId }) {
|
|
528
|
+
let response
|
|
529
|
+
try {
|
|
530
|
+
response = await httpFetch(`${resolveHost(credential)}${AGENT_BASE_PATH}${pathName}`, {
|
|
531
|
+
method: 'POST',
|
|
532
|
+
headers: agentHeaders(credential, { Accept: 'application/json', 'X-Trace-Id': traceId }),
|
|
533
|
+
body: JSON.stringify(requestBody),
|
|
534
|
+
signal,
|
|
535
|
+
}, headerTimeoutMs)
|
|
536
|
+
} catch (error) {
|
|
537
|
+
if (signal?.aborted) throw error
|
|
538
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate 请求发送失败:${error?.message ?? error}` }
|
|
539
|
+
}
|
|
540
|
+
if (!response.ok) {
|
|
541
|
+
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
542
|
+
throw failureFrom(response.status, text)
|
|
543
|
+
}
|
|
544
|
+
return response
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
async function createAgentConversation(credential, { query, systemPrompt, model, traceId, signal, headerTimeoutMs }) {
|
|
548
|
+
const response = await postAgentJson(credential, '/conversation', {
|
|
549
|
+
...agentClientInfo(credential),
|
|
550
|
+
conversationId: -1,
|
|
551
|
+
taskId: -1,
|
|
552
|
+
agentId: AGENT_ID,
|
|
553
|
+
agentInfo: AGENT_INFO,
|
|
554
|
+
query,
|
|
555
|
+
modelKey: model,
|
|
556
|
+
isUserQuery: true,
|
|
557
|
+
contexts: [],
|
|
558
|
+
subAgents: [],
|
|
559
|
+
subAgentsChanged: false,
|
|
560
|
+
isFirstQuery: true,
|
|
561
|
+
sendMode: 'normal',
|
|
562
|
+
toolUseResults: [],
|
|
563
|
+
extendUserQueryInfo: { commands: [], skills: [], subagents: [], rules: [] },
|
|
564
|
+
extend: { isMultiWorkspace: false, useWorkflow: true },
|
|
565
|
+
...(systemPrompt ? { appendSystemPrompt: systemPrompt } : {}),
|
|
566
|
+
}, { signal, headerTimeoutMs, traceId })
|
|
567
|
+
const payload = await response.json().catch(() => null)
|
|
568
|
+
if (payload?.code !== 200 || !payload?.data?.id) throw agentFailure(payload, response.status)
|
|
569
|
+
return payload.data.id
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
async function createAgentTask(credential, { conversationId, traceId, signal, headerTimeoutMs }) {
|
|
573
|
+
const response = await postAgentJson(credential, '/task', {
|
|
574
|
+
...agentClientInfo(credential),
|
|
575
|
+
conversationId,
|
|
576
|
+
agentId: AGENT_ID,
|
|
577
|
+
agentInfo: AGENT_INFO,
|
|
578
|
+
}, { signal, headerTimeoutMs, traceId })
|
|
579
|
+
const payload = await response.json().catch(() => null)
|
|
580
|
+
if (payload?.code !== 200 || payload?.data?.taskId === undefined) throw agentFailure(payload, response.status)
|
|
581
|
+
return payload.data.taskId
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
async function executeAgent(credential, requestBody, { traceId, signal, headerTimeoutMs }) {
|
|
585
|
+
let response
|
|
586
|
+
try {
|
|
587
|
+
response = await httpFetch(`${resolveHost(credential)}${AGENT_BASE_PATH}/execute`, {
|
|
588
|
+
method: 'POST',
|
|
589
|
+
headers: agentHeaders(credential, { Accept: 'text/event-stream', 'X-Trace-Id': traceId }),
|
|
590
|
+
body: JSON.stringify(requestBody),
|
|
591
|
+
signal,
|
|
592
|
+
}, headerTimeoutMs)
|
|
593
|
+
} catch (error) {
|
|
594
|
+
if (signal?.aborted) throw error
|
|
595
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate 请求发送失败:${error?.message ?? error}` }
|
|
596
|
+
}
|
|
597
|
+
if (!response.ok) {
|
|
598
|
+
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
599
|
+
throw failureFrom(response.status, text)
|
|
600
|
+
}
|
|
601
|
+
if (!response.body) {
|
|
602
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate 返回空响应体' }
|
|
603
|
+
}
|
|
604
|
+
const contentType = response.headers.get('content-type') ?? ''
|
|
605
|
+
if (!contentType.includes('text/event-stream')) {
|
|
606
|
+
const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
|
|
607
|
+
let payload = null
|
|
608
|
+
try { payload = JSON.parse(text) } catch { /* 非 JSON */ }
|
|
609
|
+
throw agentFailure(payload ?? { message: extractMessage(text) || text.slice(0, 300) }, response.status)
|
|
610
|
+
}
|
|
611
|
+
return response
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function readChunk(reader, timeoutMs, signal) {
|
|
615
|
+
return new Promise((resolve, reject) => {
|
|
616
|
+
let settled = false
|
|
617
|
+
const timer = setTimeout(() => finish(new Error('idle')), timeoutMs)
|
|
618
|
+
const onAbort = () => finish(new Error('abort'))
|
|
619
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
620
|
+
function finish(error) {
|
|
621
|
+
if (settled) return
|
|
622
|
+
settled = true
|
|
623
|
+
clearTimeout(timer)
|
|
624
|
+
signal?.removeEventListener('abort', onAbort)
|
|
625
|
+
reject(error)
|
|
626
|
+
}
|
|
627
|
+
reader.read().then(value => {
|
|
628
|
+
if (settled) return
|
|
629
|
+
settled = true
|
|
630
|
+
clearTimeout(timer)
|
|
631
|
+
signal?.removeEventListener('abort', onAbort)
|
|
632
|
+
resolve(value)
|
|
633
|
+
}, error => finish(error))
|
|
634
|
+
})
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function ssePayload(rawLine) {
|
|
638
|
+
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
|
|
639
|
+
if (line === '' || line.startsWith(':') || line.startsWith('event:')) return undefined
|
|
640
|
+
if (!line.startsWith('data:')) return undefined
|
|
641
|
+
return line.slice(5).trim()
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* 消费 agent SSE:每帧 `{ content:{ type:'ANSWER', detail:{ delta, end } } }`,
|
|
646
|
+
* 把 detail.delta(增量文本)翻译成 OpenAI chunk 交给 emit。
|
|
647
|
+
*/
|
|
648
|
+
async function consumeAgentStream(body, emit, signal, idleTimeoutMs) {
|
|
649
|
+
const reader = body.getReader()
|
|
650
|
+
const decoder = new TextDecoder()
|
|
651
|
+
let buffer = ''
|
|
652
|
+
let sawContent = false
|
|
653
|
+
let failure = null
|
|
654
|
+
|
|
655
|
+
try {
|
|
656
|
+
for (;;) {
|
|
657
|
+
let chunk
|
|
658
|
+
try {
|
|
659
|
+
chunk = await readChunk(reader, sawContent ? idleTimeoutMs : IDLE_TIMEOUT_MS, signal)
|
|
660
|
+
} catch (error) {
|
|
661
|
+
if (signal?.aborted) throw Object.assign(new Error('已取消'), { name: 'AbortError' })
|
|
662
|
+
if (error instanceof Error && error.message === 'idle') throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate 流空闲超时(上游长时间未输出)' }
|
|
663
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate 流读取失败:${error?.message ?? error}` }
|
|
664
|
+
}
|
|
665
|
+
if (chunk.done) {
|
|
666
|
+
// 收尾:先刷解码器残留,再把 buffer 余量按整行走一遍(否则末帧被静默丢弃)。
|
|
667
|
+
buffer += decoder.decode()
|
|
668
|
+
const tail = buffer.split('\n')
|
|
669
|
+
buffer = ''
|
|
670
|
+
for (const rawLine of tail) {
|
|
671
|
+
const payload = ssePayload(rawLine)
|
|
672
|
+
if (payload !== undefined) processFrame(payload)
|
|
673
|
+
}
|
|
674
|
+
break
|
|
675
|
+
}
|
|
676
|
+
buffer += decoder.decode(chunk.value, { stream: true })
|
|
677
|
+
const lines = buffer.split('\n')
|
|
678
|
+
buffer = lines.pop() ?? ''
|
|
679
|
+
for (const rawLine of lines) {
|
|
680
|
+
const payload = ssePayload(rawLine)
|
|
681
|
+
if (payload !== undefined) processFrame(payload)
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
} finally {
|
|
685
|
+
reader.cancel().catch(() => {})
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
if (failure) throw failure
|
|
689
|
+
|
|
690
|
+
function processFrame(payload) {
|
|
691
|
+
if (payload === '' || payload === '[DONE]') return
|
|
692
|
+
let frame
|
|
693
|
+
try { frame = JSON.parse(payload) } catch { return }
|
|
694
|
+
if (frame === null || typeof frame !== 'object') return
|
|
695
|
+
|
|
696
|
+
const content = frame.content
|
|
697
|
+
const type = typeof content?.type === 'string' ? content.type : ''
|
|
698
|
+
const detail = content?.detail ?? {}
|
|
699
|
+
if (type === 'EXCEPTION') {
|
|
700
|
+
failure = { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate: ${detail.exceptionMsg || '会话执行异常'}` }
|
|
701
|
+
return
|
|
702
|
+
}
|
|
703
|
+
if (type === 'DOWNGRADE' || type === 'QUOTA_EXCEED') {
|
|
704
|
+
failure = { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, rotate: true, message: `Comate: ${JSON.stringify(detail).slice(0, 200)}` }
|
|
705
|
+
return
|
|
706
|
+
}
|
|
707
|
+
if (type === 'NEED_RETRY_EXCEPTION') {
|
|
708
|
+
failure = { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: `Comate: ${detail.exceptionMsg || '会话执行需要重试'}` }
|
|
709
|
+
return
|
|
710
|
+
}
|
|
711
|
+
if (type !== 'ANSWER') return // TOKEN_USAGE / NOTIFICATION 等
|
|
712
|
+
|
|
713
|
+
const delta = typeof detail.delta === 'string' ? detail.delta : ''
|
|
714
|
+
if (delta === '') return
|
|
715
|
+
sawContent = true
|
|
716
|
+
emit({ choices: [{ index: 0, delta: { content: delta }, finish_reason: null }] })
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
return { sawContent }
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* 解析调用参数:干净 id → 完整上游 modelId + 思考参数。
|
|
724
|
+
* 映射表由 fetchModels 实时清单填充;未命中时按需拉一次清单(同一进程只补一次),
|
|
725
|
+
* 仍拿不到就退回「传入 id 原样调用 + 默认思考参数」。
|
|
726
|
+
*/
|
|
727
|
+
async function resolveModelCall(credential, requestedModel) {
|
|
728
|
+
const hit = modelMeta.get(requestedModel)
|
|
729
|
+
if (hit) return hit
|
|
730
|
+
const { clean } = splitModelId(requestedModel)
|
|
731
|
+
const cached = modelMeta.get(clean)
|
|
732
|
+
if (cached) return cached
|
|
733
|
+
try {
|
|
734
|
+
await fetchModels(credential) // 拉清单即刷新 modelMeta
|
|
735
|
+
} catch { /* 拉不到就按兜底处理 */ }
|
|
736
|
+
return modelMeta.get(requestedModel)
|
|
737
|
+
?? modelMeta.get(clean)
|
|
738
|
+
?? { cleanId: clean, upstreamId: requestedModel, thinkingEnabled: false, effort: 'medium' }
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** 单账号一轮对话:新建会话/任务后走 agent execute 流,本地聚合成完整 OpenAI 响应。 */
|
|
742
|
+
export async function complete(credential, body, { signal, onData, headerTimeoutMs = REQUEST_TIMEOUT_MS } = {}) {
|
|
743
|
+
const authName = agentAuthName(credential)
|
|
744
|
+
if (!authName) {
|
|
745
|
+
throw { kind: 'auth', retryable: false, terminal: true, message: 'Comate 凭据缺少 license/username,请重新登录' }
|
|
746
|
+
}
|
|
747
|
+
const requestedModel = typeof body.model === 'string' ? body.model : ''
|
|
748
|
+
if (requestedModel === '') {
|
|
749
|
+
throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Comate: 缺少模型名称' }
|
|
750
|
+
}
|
|
751
|
+
const { systemPrompt, query } = buildAgentQuery(body.messages)
|
|
752
|
+
if (query === '') {
|
|
753
|
+
throw { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message: 'Comate: messages 里没有可用内容' }
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// 干净 id(如 glm-5.2)→ 完整上游 modelId(glm-5.2_50c5…),并带上该模型的思考参数
|
|
757
|
+
const call = await resolveModelCall(credential, requestedModel)
|
|
758
|
+
const upstreamModel = call.upstreamId
|
|
759
|
+
const traceId = randomUUID()
|
|
760
|
+
const conversationId = await createAgentConversation(credential, {
|
|
761
|
+
query, systemPrompt, model: upstreamModel, traceId, signal, headerTimeoutMs,
|
|
762
|
+
})
|
|
763
|
+
const taskId = await createAgentTask(credential, { conversationId, traceId, signal, headerTimeoutMs })
|
|
764
|
+
|
|
765
|
+
const response = await executeAgent(credential, {
|
|
766
|
+
...agentClientInfo(credential),
|
|
767
|
+
taskId,
|
|
768
|
+
conversationId,
|
|
769
|
+
agentId: AGENT_ID,
|
|
770
|
+
agentInfo: AGENT_INFO,
|
|
771
|
+
uploadBaseInfo: {},
|
|
772
|
+
query,
|
|
773
|
+
modelKey: upstreamModel,
|
|
774
|
+
thinkingEnabled: call.thinkingEnabled,
|
|
775
|
+
effort: call.effort,
|
|
776
|
+
contextWindow: 131_072,
|
|
777
|
+
sysInfo: {},
|
|
778
|
+
skillInfos: [],
|
|
779
|
+
hasMcp: false,
|
|
780
|
+
isUserQuery: true,
|
|
781
|
+
localIndex: false,
|
|
782
|
+
contexts: [],
|
|
783
|
+
subAgents: [],
|
|
784
|
+
subAgentsChanged: false,
|
|
785
|
+
isFirstQuery: true,
|
|
786
|
+
systemReminder: '',
|
|
787
|
+
...(systemPrompt ? { appendSystemPrompt: systemPrompt } : {}),
|
|
788
|
+
extendUserQueryInfo: { commands: [], skills: [], subagents: [], rules: [] },
|
|
789
|
+
extend: { isMultiWorkspace: false, useWorkflow: true },
|
|
790
|
+
toolUseResults: [],
|
|
791
|
+
sendMode: 'normal',
|
|
792
|
+
traceId,
|
|
793
|
+
}, { traceId, signal, headerTimeoutMs })
|
|
794
|
+
|
|
795
|
+
const chunkId = `chatcmpl-${randomBytes(8).toString('hex')}`
|
|
796
|
+
const created = Math.floor(Date.now() / 1000)
|
|
797
|
+
const chunks = []
|
|
798
|
+
let firstChunk = true
|
|
799
|
+
const emit = chunk => {
|
|
800
|
+
const full = {
|
|
801
|
+
id: chunkId,
|
|
802
|
+
object: 'chat.completion.chunk',
|
|
803
|
+
created,
|
|
804
|
+
model: requestedModel,
|
|
805
|
+
choices: chunk.choices.map(choice => ({
|
|
806
|
+
...choice,
|
|
807
|
+
delta: firstChunk ? { role: 'assistant', ...choice.delta } : choice.delta,
|
|
808
|
+
})),
|
|
809
|
+
}
|
|
810
|
+
firstChunk = false
|
|
811
|
+
chunks.push(full)
|
|
812
|
+
onData?.(JSON.stringify(full))
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const consumed = await consumeAgentStream(response.body, emit, signal, IDLE_TIMEOUT_MS)
|
|
816
|
+
if (!consumed.sawContent) {
|
|
817
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate: 模型未返回任何内容' }
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
const final = { id: chunkId, object: 'chat.completion.chunk', created, model: requestedModel, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }
|
|
821
|
+
chunks.push(final)
|
|
822
|
+
onData?.(JSON.stringify(final))
|
|
823
|
+
|
|
824
|
+
const merged = mergeSseChunks(chunks.map(chunk => JSON.stringify(chunk)))
|
|
825
|
+
if (!merged || !merged.choices?.[0]) {
|
|
826
|
+
throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Comate 流结束但没有内容帧' }
|
|
827
|
+
}
|
|
828
|
+
merged.model = requestedModel
|
|
829
|
+
return { status: response.status, json: merged }
|
|
830
|
+
}
|