dsh-zcode-startplan 0.0.0-stage → 0.2.0

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/lib/errors.js ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * 上游错误判定与翻译(**切号策略的唯一判据来源**)。
3
+ *
4
+ * 判据必须窄:
5
+ * - 「额度用尽」在 wire 上有多种形态,而「并发限流」**同样返回 429**;
6
+ * 只按状态码分类会把 3009 误判成额度用尽 → 误伤一个完全可用的账号。
7
+ * - 文案兜底只认 `exceed quota limit` / `quota exhausted` 这类**窄**关键词;
8
+ * 用 `quota` / `balance` 泛词会误伤模型正文里恰好讨论额度的内容。
9
+ *
10
+ * 处置表(全部来自参考实现的实测):
11
+ *
12
+ * | 形态 | 处置 |
13
+ * |---|---|
14
+ * | `1005` / `1113` / HTTP 200 但零内容 | 标记该账号×模型当日用尽 → **换号** |
15
+ * | `3009` 并发限流 | 线性退避重试,**不换号** |
16
+ * | `3007` captcha 失败 | **换新 captcha** 重试(param 一次性) |
17
+ * | `3012` 风控 | **不重试**(有账号冷却惩罚:30 分钟;24h 内第 3 次起 24 小时;5 次停用) |
18
+ * | `401` / `1002` 凭据失效 | **不重试**,需重新登录该账号 |
19
+ */
20
+
21
+ /** 上游并发限流的业务码。 */
22
+ export const ZCODE_CONCURRENCY_CODE = '3009'
23
+
24
+ /** 并发限流重试次数上限。 */
25
+ export const CONCURRENCY_RETRY_MAX = 2
26
+
27
+ /** 换号次数上限。 */
28
+ export const QUOTA_SWITCH_MAX = 3
29
+
30
+ /** 并发限流重试的退避基数(实测 900ms 仍撞 429,故用 1500ms 起步)。 */
31
+ export const CONCURRENCY_RETRY_BASE_MS = 1_500
32
+
33
+ /** 判断是否是并发限流(3009)—— 等一下就能过,故重试且**不换号**。 */
34
+ export function isZcodeConcurrencyLimited(body) {
35
+ return body.includes(ZCODE_CONCURRENCY_CODE) || /concurrency\s+limit/i.test(body)
36
+ }
37
+
38
+ /** 判断是否是额度用尽(确定性:等账期重置才恢复)。 */
39
+ export function isZcodeQuotaExhausted(body) {
40
+ if (isZcodeConcurrencyLimited(body)) return false
41
+ if (body.includes('1113') || body.includes('余额不足')) return true
42
+ if (body.includes('1005')) return true
43
+ return /exceed\s+quota\s+limit|quota\s+(?:has\s+been\s+)?exhausted/i.test(body)
44
+ }
45
+
46
+ /** 判断是否是 captcha 校验失败(3007)—— 换新 param 即可重试。 */
47
+ export function isZcodeCaptchaRejected(body) {
48
+ return body.includes('3007') || /captcha\s+verify\s+failed/i.test(body)
49
+ }
50
+
51
+ /** 判断是否是风控拦截(3012)—— **不要重试**。 */
52
+ export function isZcodeRiskBlocked(body) {
53
+ return body.includes('3012') || /unusual\s+activity/i.test(body)
54
+ }
55
+
56
+ /** 判断是否是鉴权失败(401 / 1002)—— 需用户重新登录该账号。 */
57
+ export function isZcodeAuthFailed(status, body) {
58
+ if (status === 401) return true
59
+ return body.includes('1002') || /invalid\s+token|token\s+expired/i.test(body)
60
+ }
61
+
62
+ /**
63
+ * 把上游错误翻成人能看懂的一句话。
64
+ * 两个业务码必须单独说清,因为用户该做的事完全不同:3007 可重试,3012 不可重试。
65
+ */
66
+ export function describeUpstreamError(status, body) {
67
+ const trimmed = String(body ?? '').trim()
68
+ let code
69
+ let message
70
+ try {
71
+ const parsed = JSON.parse(trimmed)
72
+ code = parsed.code
73
+ message = parsed.msg ?? parsed.message
74
+ } catch {
75
+ // 非 JSON:原样截断。
76
+ }
77
+ const suffix = typeof message === 'string' && message.length > 0 ? message : trimmed.slice(0, 200)
78
+
79
+ if (code === 3009 || trimmed.includes('3009')) {
80
+ return `上游并发限流(3009 model concurrency limit exceeded)——已按退避重试仍未通过,请稍后重试。原始响应:${suffix}`
81
+ }
82
+ if (code === 1005 || trimmed.includes('1005')) {
83
+ return `额度用尽(1005 exceed quota limit)——该账号在这个模型上的免费额度已用完,请等待额度重置或更换账号。原始响应:${suffix}`
84
+ }
85
+ if (code === 3007 || trimmed.includes('3007')) {
86
+ return '阿里云 captcha 校验失败(3007)。请重试;若持续失败,检查 ZCode 桌面端是否在运行(captcha 载体)。'
87
+ }
88
+ if (code === 3012 || trimmed.includes('3012')) {
89
+ return `上游风控拦截(3012 unusual activity)。⚠ 该错误有账号冷却惩罚(30 分钟,反复触发会升级到 24 小时乃至停用),请勿连续重试。原始响应:${suffix}`
90
+ }
91
+ if (code === 1113 || trimmed.includes('1113')) {
92
+ return `余额不足或无可用资源包(1113)。原始响应:${suffix}`
93
+ }
94
+ if (code === 1002 || status === 401) {
95
+ return `凭据失效(${status})。请用 \`zcode-start-plan login\` 重新登录该账号。${suffix}`
96
+ }
97
+ return `HTTP ${status}:${suffix}`
98
+ }
99
+
100
+ /**
101
+ * 上游错误分类(供重试循环直接路由)。
102
+ *
103
+ * @param {number} status HTTP 状态码
104
+ * @param {string} body 响应正文
105
+ * @returns {'quota' | 'concurrency' | 'captcha' | 'risk' | 'auth' | 'other'}
106
+ */
107
+ export function classifyUpstreamError(status, body) {
108
+ if (isZcodeRiskBlocked(body)) return 'risk'
109
+ if (isZcodeAuthFailed(status, body)) return 'auth'
110
+ if (isZcodeConcurrencyLimited(body)) return 'concurrency'
111
+ if (isZcodeQuotaExhausted(body)) return 'quota'
112
+ if (isZcodeCaptchaRejected(body)) return 'captcha'
113
+ return 'other'
114
+ }
115
+
116
+ /** 并发限流重试的退避时长(线性:base、2×base、…)。 */
117
+ export function concurrencyRetryDelayMs(attempt, baseMs = CONCURRENCY_RETRY_BASE_MS) {
118
+ const base = baseMs > 0 ? baseMs : CONCURRENCY_RETRY_BASE_MS
119
+ return base * (Math.max(0, Math.floor(attempt)) + 1)
120
+ }
121
+
122
+ /** 构造 Anthropic 形态的错误体(DSH 侧只读 message,但保持形态一致)。 */
123
+ export function anthropicErrorPayload(message, type = 'api_error') {
124
+ return { type: 'error', error: { type, message } }
125
+ }
@@ -0,0 +1,338 @@
1
+ /**
2
+ * 本地 Anthropic 兼容端点(**可选**,默认关闭)。
3
+ *
4
+ * 只有当用户想走 `dsh-llm-pi-ai` 路由(`api: anthropic-messages` + `baseURL`)时才需要它:
5
+ * 此时请求从 DSH 的 pi-ai 适配器打到 `127.0.0.1:<port>/v1/messages`,本文件把它复用
6
+ * 成一次 `ZcodePlanClient.call()`,再把上游事件以 Anthropic SSE 原样写回。
7
+ *
8
+ * ## 为什么端口与 token 必须固定/持久化
9
+ *
10
+ * profile 里配好的 `baseURL` 与 `apiKeyEnv` 指向它们;端口每次变、token 每次重新随机,
11
+ * 那份配置就每次重启都失效(表现为 404 或 401)。故:
12
+ * - 端口默认 17899(`config.endpoint.port`),被占用时回退随机并在日志/状态里如实告知;
13
+ * - token 首次生成后落盘到数据目录(`endpoint-token.txt`,600)。
14
+ */
15
+
16
+ import { createServer } from 'node:http'
17
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+
20
+ /**
21
+ * 解析配置端口(`0` = 随机)。
22
+ * @param {unknown} raw
23
+ * @param {number} fallback
24
+ */
25
+ export function resolvePort(raw, fallback = 17_899) {
26
+ if (raw === undefined || raw === null || String(raw).trim().length === 0) return fallback
27
+ const value = Number(raw)
28
+ if (!Number.isFinite(value) || value < 0 || value > 65_535) return fallback
29
+ return Math.floor(value)
30
+ }
31
+
32
+ /** 解析访问 token:环境变量 → 数据目录文件 → 新生成后落盘。 */
33
+ export function resolveEndpointToken(dataDir, env = process.env) {
34
+ const fromEnv = env['ZCODE_START_PLAN_TOKEN']?.trim()
35
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv
36
+ const file = join(dataDir, 'endpoint-token.txt')
37
+ try {
38
+ if (existsSync(file)) {
39
+ const saved = readFileSync(file, 'utf8').trim()
40
+ if (saved.length >= 16) return saved
41
+ }
42
+ } catch {
43
+ // 读不到就当没有(下面重新生成)。
44
+ }
45
+ const token = globalThis.crypto.randomUUID().replace(/-/g, '') + globalThis.crypto.randomUUID().replace(/-/g, '')
46
+ try {
47
+ mkdirSync(dataDir, { recursive: true })
48
+ writeFileSync(file, token, { mode: 0o600 })
49
+ } catch {
50
+ // 落盘失败不阻塞(只是下次会换一个 token)。
51
+ }
52
+ return token
53
+ }
54
+
55
+ /**
56
+ * 启动本地端点。
57
+ *
58
+ * @param {{
59
+ * port?: number,
60
+ * host?: string,
61
+ * token: string,
62
+ * planClient: import('./plan-client.js').ZcodePlanClient,
63
+ * models: () => Promise<Array<any>>,
64
+ * log?: (message: string) => void,
65
+ * }} options
66
+ */
67
+ export async function startLocalEndpoint(options) {
68
+ const host = options.host ?? '127.0.0.1'
69
+ const token = options.token
70
+ const log = options.log ?? (() => {})
71
+ const requestedPort = options.port ?? 17_899
72
+
73
+ const server = createServer((req, res) => {
74
+ void handle(req, res).catch((error) => {
75
+ log(`[endpoint] 未捕获错误:${String(error)}`)
76
+ try {
77
+ res.writeHead(500, { 'content-type': 'application/json' })
78
+ res.end(JSON.stringify({ type: 'error', error: { type: 'api_error', message: String(error) } }))
79
+ } catch {
80
+ // 响应可能已开始。
81
+ }
82
+ })
83
+ })
84
+
85
+ async function handle(req, res) {
86
+ const url = new URL(req.url ?? '/', `http://${host}`)
87
+ if (url.pathname === '/health') {
88
+ res.writeHead(200, { 'content-type': 'application/json' })
89
+ res.end(JSON.stringify({ ok: true }))
90
+ return
91
+ }
92
+ if (url.pathname === '/v1/models') {
93
+ const models = await options.models()
94
+ res.writeHead(200, { 'content-type': 'application/json' })
95
+ res.end(
96
+ JSON.stringify({
97
+ data: models.map((model) => ({
98
+ id: model.id,
99
+ type: 'model',
100
+ display_name: model.name ?? model.id,
101
+ created_at: new Date(0).toISOString(),
102
+ })),
103
+ has_more: false,
104
+ }),
105
+ )
106
+ return
107
+ }
108
+ if (url.pathname !== '/v1/messages' || req.method !== 'POST') {
109
+ res.writeHead(404, { 'content-type': 'application/json' })
110
+ res.end(JSON.stringify({ type: 'error', error: { type: 'not_found_error', message: `未知端点 ${url.pathname}` } }))
111
+ return
112
+ }
113
+ if (req.headers['authorization'] !== `Bearer ${token}` && req.headers['x-api-key'] !== token) {
114
+ res.writeHead(401, { 'content-type': 'application/json' })
115
+ res.end(JSON.stringify({ type: 'error', error: { type: 'authentication_error', message: '本地端点访问令牌无效' } }))
116
+ return
117
+ }
118
+
119
+ const raw = await readBody(req)
120
+ let body
121
+ try {
122
+ body = JSON.parse(raw)
123
+ } catch {
124
+ res.writeHead(400, { 'content-type': 'application/json' })
125
+ res.end(JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: '请求体不是合法 JSON' } }))
126
+ return
127
+ }
128
+
129
+ const streaming = body.stream === true || body.stream === 'true'
130
+ const abort = new AbortController()
131
+ res.on('close', () => {
132
+ /** 客户端断开 → 立刻取消上游(否则白耗额度)。 */
133
+ if (!res.writableEnded) abort.abort()
134
+ })
135
+
136
+ const result = await options.planClient.call({
137
+ options: {
138
+ ...toGenerateOptions(body),
139
+ provider: 'zcode-start-plan',
140
+ signal: abort.signal,
141
+ },
142
+ maxTokens: body.max_tokens,
143
+ signal: abort.signal,
144
+ })
145
+
146
+ if (!streaming) {
147
+ /** 非流式:把事件折叠成一个 message、按上游 content-type 语义回 JSON。 */
148
+ const message = await collapseToMessage(result.head)
149
+ res.writeHead(200, { 'content-type': 'application/json' })
150
+ res.end(JSON.stringify(message))
151
+ return
152
+ }
153
+
154
+ res.writeHead(200, {
155
+ 'content-type': 'text/event-stream',
156
+ 'cache-control': 'no-cache',
157
+ connection: 'keep-alive',
158
+ })
159
+ const writeEvent = (eventName, data) => {
160
+ if (res.destroyed || res.writableEnded) return
161
+ try {
162
+ res.write(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`)
163
+ } catch {
164
+ // 客户端已断开。
165
+ }
166
+ }
167
+ for (const event of result.head) {
168
+ if (event.data === undefined) continue
169
+ writeEvent(event.event ?? event.data?.type ?? 'message', event.data)
170
+ }
171
+ if (result.decoder !== undefined) {
172
+ for (;;) {
173
+ const next = await result.decoder.read()
174
+ if (next.done === true) break
175
+ if (next.value.data === undefined) continue
176
+ writeEvent(next.value.event ?? next.value.data?.type ?? 'message', next.value.data)
177
+ }
178
+ }
179
+ if (!res.destroyed) res.end()
180
+ }
181
+
182
+ const listen = (port) =>
183
+ new Promise((resolve, reject) => {
184
+ const onError = (error) => {
185
+ server.removeListener('listening', onListening)
186
+ reject(error)
187
+ }
188
+ const onListening = () => {
189
+ server.removeListener('error', onError)
190
+ resolve()
191
+ }
192
+ server.once('error', onError)
193
+ server.once('listening', onListening)
194
+ server.listen(port, host)
195
+ })
196
+
197
+ let actualPort
198
+ try {
199
+ await listen(requestedPort)
200
+ actualPort = server.address().port
201
+ } catch (error) {
202
+ if (requestedPort === 0 || (error?.code !== 'EADDRINUSE' && error?.code !== 'EACCES')) throw error
203
+ log(`[endpoint] ⚠ 端口 ${requestedPort} 不可用(${error.code}),已回退随机端口`)
204
+ await listen(0)
205
+ actualPort = server.address().port
206
+ }
207
+
208
+ const baseUrl = `http://${host}:${actualPort}`
209
+ log(`[endpoint] 已监听 ${baseUrl}`)
210
+
211
+ return {
212
+ port: actualPort,
213
+ baseUrl,
214
+ token,
215
+ async close() {
216
+ await new Promise((resolve) => server.close(() => resolve()))
217
+ },
218
+ }
219
+ }
220
+
221
+ /** 读完整请求体。 */
222
+ function readBody(req) {
223
+ return new Promise((resolve, reject) => {
224
+ const chunks = []
225
+ req.on('data', (chunk) => chunks.push(chunk))
226
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
227
+ req.on('error', reject)
228
+ })
229
+ }
230
+
231
+ /**
232
+ * 把 Anthropic Messages 请求体翻成 DSH 的 GenerateOptions。
233
+ *
234
+ * pi-ai 发来的 body 已经是 Anthropic 形态(`system` / `messages` / `tools`),
235
+ * 这里逆变换回 DSH 词汇,好让 `buildUpstreamBody` 再统一注入身份块与日期块。
236
+ */
237
+ export function toGenerateOptions(body) {
238
+ const systemText = Array.isArray(body.system)
239
+ ? body.system.filter((block) => block?.type === 'text').map((block) => block.text).join('\n\n')
240
+ : typeof body.system === 'string'
241
+ ? body.system
242
+ : undefined
243
+
244
+ const messages = (Array.isArray(body.messages) ? body.messages : []).map((message) => ({
245
+ role: message.role === 'assistant' ? 'assistant' : 'user',
246
+ content: toDshContent(message.content),
247
+ }))
248
+
249
+ const tools = (Array.isArray(body.tools) ? body.tools : []).map((tool) => ({
250
+ name: tool.name,
251
+ description: tool.description,
252
+ parameters: tool.input_schema ?? tool.parameters,
253
+ }))
254
+
255
+ return {
256
+ model: body.model,
257
+ ...(systemText !== undefined ? { system: [{ type: 'text', text: systemText }] } : {}),
258
+ messages,
259
+ ...(tools.length > 0 ? { tools } : {}),
260
+ ...(typeof body.temperature === 'number' ? { temperature: body.temperature } : {}),
261
+ }
262
+ }
263
+
264
+ /** Anthropic content → DSH content blocks。 */
265
+ function toDshContent(content) {
266
+ if (typeof content === 'string') return [{ type: 'text', text: content }]
267
+ if (!Array.isArray(content)) return []
268
+ const out = []
269
+ for (const block of content) {
270
+ if (block?.type === 'text' && typeof block.text === 'string') out.push({ type: 'text', text: block.text })
271
+ else if (block?.type === 'tool_use') {
272
+ out.push({ type: 'tool-call', id: block.id, name: block.name, arguments: block.input ?? {} })
273
+ } else if (block?.type === 'tool_result') {
274
+ out.push({
275
+ type: 'tool-result',
276
+ toolCallId: block.tool_use_id,
277
+ output: typeof block.content === 'string' ? block.content : JSON.stringify(block.content ?? ''),
278
+ isError: block.is_error === true,
279
+ })
280
+ } else if (block?.type === 'image' && block.source?.type === 'base64') {
281
+ out.push({
282
+ type: 'image',
283
+ source: { type: 'base64', media_type: block.source.media_type, data: block.source.data },
284
+ })
285
+ }
286
+ }
287
+ return out
288
+ }
289
+
290
+ /** 把一段流事件折叠成一个 Anthropic message(非流式请求用)。 */
291
+ async function collapseToMessage(head) {
292
+ const content = []
293
+ let usage = { input_tokens: 0, output_tokens: 0 }
294
+ let stopReason = 'end_turn'
295
+ const partialJson = new Map()
296
+ for (const event of head) {
297
+ const data = event.data
298
+ if (data === undefined) continue
299
+ if (data.type === 'message_start') {
300
+ usage = { ...usage, ...(data.message?.usage ?? {}) }
301
+ } else if (data.type === 'content_block_start') {
302
+ content[data.index] = { ...data.content_block }
303
+ if (data.content_block?.type === 'tool_use') partialJson.set(data.index, data.content_block.input ?? '')
304
+ } else if (data.type === 'content_block_delta') {
305
+ const block = content[data.index]
306
+ if (block === undefined) continue
307
+ const delta = data.delta ?? {}
308
+ if (delta.type === 'text_delta') block.text = (block.text ?? '') + delta.text
309
+ else if (delta.type === 'thinking_delta') block.thinking = (block.thinking ?? '') + delta.thinking
310
+ else if (delta.type === 'input_json_delta') {
311
+ const current = partialJson.get(data.index) ?? ''
312
+ partialJson.set(data.index, current + delta.partial_json)
313
+ }
314
+ } else if (data.type === 'message_delta') {
315
+ if (typeof data.delta?.stop_reason === 'string') stopReason = data.delta.stop_reason
316
+ usage = { ...usage, ...(data.usage ?? {}) }
317
+ }
318
+ }
319
+ for (const [index, raw] of partialJson) {
320
+ const block = content[index]
321
+ if (block === undefined) continue
322
+ try {
323
+ block.input = typeof raw === 'string' ? JSON.parse(raw || '{}') : raw
324
+ } catch {
325
+ block.input = {}
326
+ }
327
+ }
328
+ return {
329
+ id: `msg_${Math.random().toString(36).slice(2)}`,
330
+ type: 'message',
331
+ role: 'assistant',
332
+ model: 'zcode-start-plan',
333
+ content: content.filter(Boolean),
334
+ stop_reason: stopReason,
335
+ stop_sequence: null,
336
+ usage,
337
+ }
338
+ }