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/CHANGELOG.md +108 -0
- package/LICENSE +674 -0
- package/README.md +345 -2
- package/bin/cli.mjs +450 -0
- package/client.js +659 -0
- package/cordis.patch.yml +30 -0
- package/icon.svg +18 -0
- package/index.js +313 -0
- package/lib/adapter.js +286 -0
- package/lib/anthropic-body.js +304 -0
- package/lib/assemble.js +309 -0
- package/lib/captcha/minter.js +654 -0
- package/lib/captcha/sdk-page.js +20 -0
- package/lib/errors.js +125 -0
- package/lib/local-endpoint.js +338 -0
- package/lib/manage-routes.js +414 -0
- package/lib/plan-client.js +427 -0
- package/lib/pool.js +467 -0
- package/lib/sse.js +317 -0
- package/lib/stream-translator.js +279 -0
- package/lib/text-heuristics.js +35 -0
- package/lib/upstream-api.js +544 -0
- package/lib/upstream.js +123 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +80 -6
- package/scripts/bench-toks.mjs +138 -0
- package/scripts/check-data-dir.mjs +31 -0
- package/scripts/restart-dsh.ps1 +76 -0
- package/scripts/run-tests.mjs +68 -0
- package/scripts/smoke-install.mjs +204 -0
- package/scripts/verify_compat.mjs +64 -0
package/lib/sse.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSE / JSON 响应首部判定(**「秒回空」检测**)。
|
|
3
|
+
*
|
|
4
|
+
* 上游在「该账号对该模型无权益」时会返回 **HTTP 200 + 一个没有任何内容帧的 SSE 流**。
|
|
5
|
+
* 若直接当正文消费,用户看到的是「模型返回了空响应」;正确处理是**换账号重试**。
|
|
6
|
+
*
|
|
7
|
+
* 透传与重试天然冲突:一旦把内容交给调用方就不能再重试(会出现两份输出)。
|
|
8
|
+
* 故这里**先读到出现内容再决定**:
|
|
9
|
+
* - 见到内容 → 把缓冲的事件原样交给调用方,后续继续流式解析;
|
|
10
|
+
* - 流结束仍无内容 → 判定为无权益,调用方换号重试(调用方**一个 chunk 都没收到**)。
|
|
11
|
+
*
|
|
12
|
+
* ⚠ 判定必须按媒体类型分流:上游对**不带 `stream` 的请求返回单个 JSON message**;
|
|
13
|
+
* 若只用 SSE 特征串去扫,一个正常有内容的 JSON 会被判成「零内容」,
|
|
14
|
+
* 于是①客户端拿到空响应 ②**该账号被错误标记限流到当日结束**。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** SSE 内容帧的特征串(覆盖文本、思考、工具调用三类)。 */
|
|
18
|
+
const CONTENT_MARKERS = [
|
|
19
|
+
'content_block_delta',
|
|
20
|
+
'text_delta',
|
|
21
|
+
'thinking_delta',
|
|
22
|
+
'input_json_delta',
|
|
23
|
+
'"type":"tool_use"',
|
|
24
|
+
'"type": "tool_use"',
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
/** 缓冲上限(异常大的首帧不能无限缓冲;超限即按「有内容」放行,宁可让它自己失败也不要 OOM)。 */
|
|
28
|
+
export const DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
|
|
29
|
+
|
|
30
|
+
/** 是否按 JSON(非流式)形态判定。 */
|
|
31
|
+
export function isJsonContentType(contentType) {
|
|
32
|
+
if (contentType === undefined) return false
|
|
33
|
+
const lower = String(contentType).toLowerCase()
|
|
34
|
+
return lower.includes('application/json') && !lower.includes('event-stream')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 从**已解析的 JSON message** 判断是否真有内容。
|
|
39
|
+
* 只认「有实际产物的块」:文本非空 / 思考非空 / 工具调用块本身即内容。
|
|
40
|
+
*/
|
|
41
|
+
export function jsonHasContent(text) {
|
|
42
|
+
let parsed
|
|
43
|
+
try {
|
|
44
|
+
parsed = JSON.parse(text)
|
|
45
|
+
} catch {
|
|
46
|
+
// 解析不动就保守按「有内容」:不要冤枉账号。
|
|
47
|
+
return true
|
|
48
|
+
}
|
|
49
|
+
if (typeof parsed !== 'object' || parsed === null) return false
|
|
50
|
+
/** 错误载荷算「有响应」,由调用方的错误处理负责 —— 不能当成额度耗尽去换号。 */
|
|
51
|
+
if (parsed.type === 'error' || parsed.error !== undefined) return true
|
|
52
|
+
const content = parsed.content
|
|
53
|
+
if (!Array.isArray(content)) {
|
|
54
|
+
const output = parsed.usage?.output_tokens
|
|
55
|
+
return typeof output === 'number' && output > 0
|
|
56
|
+
}
|
|
57
|
+
for (const raw of content) {
|
|
58
|
+
if (typeof raw !== 'object' || raw === null) continue
|
|
59
|
+
if (raw.type === 'tool_use') return true
|
|
60
|
+
if (raw.type === 'text' && typeof raw.text === 'string' && raw.text.length > 0) return true
|
|
61
|
+
if (raw.type === 'thinking' && typeof raw.thinking === 'string' && raw.thinking.length > 0) return true
|
|
62
|
+
if (raw.type === 'redacted_thinking') return true
|
|
63
|
+
}
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 把字节流切成 SSE 事件(`data:` 行拼装)。返回 async generator(产出原始事件对象)。
|
|
69
|
+
*
|
|
70
|
+
* 解析同时保留**原始字节**,以便调用方在「判定有内容」后能原样重放首部。
|
|
71
|
+
*/
|
|
72
|
+
export async function* readSseEvents(body, options = {}) {
|
|
73
|
+
const decode = makeSseDecoder(body, options)
|
|
74
|
+
try {
|
|
75
|
+
for (;;) {
|
|
76
|
+
const next = await decode.read()
|
|
77
|
+
if (next.done === true) return
|
|
78
|
+
yield next.value
|
|
79
|
+
}
|
|
80
|
+
} finally {
|
|
81
|
+
await decode.cancel()
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 构造一个「可交接」的 SSE 解码器。
|
|
87
|
+
*
|
|
88
|
+
* ⚠ 为什么不是 `async function*`:`readContentHead` 判定出「有内容」后要**继续**用同一个
|
|
89
|
+
* 读取器消费剩余事件(首部事件已缓冲)。生成器无法把内部 `reader` 交出去而不丢失已读字节,
|
|
90
|
+
* 所以这里显式暴露 `read()` / `cancel()`,由两处共享。
|
|
91
|
+
*
|
|
92
|
+
* @param {ReadableStream<Uint8Array>} body
|
|
93
|
+
* @param {{ timeoutMs?: number }} [options]
|
|
94
|
+
*/
|
|
95
|
+
export function makeSseDecoder(body, options = {}) {
|
|
96
|
+
const decoder = new TextDecoder()
|
|
97
|
+
const reader = body.getReader()
|
|
98
|
+
const timeoutMs = options.timeoutMs ?? 180_000
|
|
99
|
+
let buffer = ''
|
|
100
|
+
let finished = false
|
|
101
|
+
/** 已读到但还没返回的完整事件(`\n\n` 分隔)。 */
|
|
102
|
+
const ready = []
|
|
103
|
+
|
|
104
|
+
const pump = async () => {
|
|
105
|
+
const chunk = await Promise.race([
|
|
106
|
+
reader.read(),
|
|
107
|
+
new Promise((_resolve, reject) => {
|
|
108
|
+
const timer = setTimeout(() => reject(new Error(`读取上游响应超时(${timeoutMs}ms)`)), timeoutMs)
|
|
109
|
+
timer.unref?.()
|
|
110
|
+
}),
|
|
111
|
+
])
|
|
112
|
+
if (chunk.done === true) {
|
|
113
|
+
finished = true
|
|
114
|
+
/**
|
|
115
|
+
* ⚠ 必须先 flush `TextDecoder`(多字节字符可能被拆在 chunk 边界):
|
|
116
|
+
* 不 flush 会让同一个网络包里到达的**最后一个事件**在 EOF 时被吞掉——
|
|
117
|
+
* 表现为「只收到第一个 text-delta,后面全丢」(实测抓到的真实缺陷)。
|
|
118
|
+
*/
|
|
119
|
+
buffer += decoder.decode()
|
|
120
|
+
const tail = buffer.trim()
|
|
121
|
+
buffer = ''
|
|
122
|
+
if (tail.length > 0) {
|
|
123
|
+
const event = parseSseEvent(tail)
|
|
124
|
+
if (event !== undefined) ready.push(event)
|
|
125
|
+
}
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
if (chunk.value === undefined) return
|
|
129
|
+
buffer += decoder.decode(chunk.value, { stream: true })
|
|
130
|
+
for (;;) {
|
|
131
|
+
const match = /\r?\n\r?\n/.exec(buffer)
|
|
132
|
+
if (match === null) break
|
|
133
|
+
const raw = buffer.slice(0, match.index)
|
|
134
|
+
buffer = buffer.slice(match.index + match[0].length)
|
|
135
|
+
const event = parseSseEvent(raw)
|
|
136
|
+
if (event !== undefined) ready.push(event)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
/** 读下一个事件;流结束返回 `{ done: true }`。 */
|
|
142
|
+
async read() {
|
|
143
|
+
for (;;) {
|
|
144
|
+
const queued = ready.shift()
|
|
145
|
+
if (queued !== undefined) return { done: false, value: queued }
|
|
146
|
+
if (finished) return { done: true }
|
|
147
|
+
await pump()
|
|
148
|
+
/** 空事件块(`: keep-alive` 注释)不产出任何东西,继续读。 */
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
/** 取消读取(客户端断开 / 换号重试时立刻释放上游连接)。 */
|
|
152
|
+
async cancel() {
|
|
153
|
+
if (finished) return
|
|
154
|
+
finished = true
|
|
155
|
+
try {
|
|
156
|
+
await reader.cancel()
|
|
157
|
+
} catch {
|
|
158
|
+
// 已结束。
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
/** 是否已读完。 */
|
|
162
|
+
get done() {
|
|
163
|
+
return finished && ready.length === 0
|
|
164
|
+
},
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 解析一个 SSE 事件块;无 `data:` 行返回 undefined。 */
|
|
169
|
+
export function parseSseEvent(raw) {
|
|
170
|
+
const lines = raw.split(/\r?\n/)
|
|
171
|
+
let eventName
|
|
172
|
+
const dataLines = []
|
|
173
|
+
for (const line of lines) {
|
|
174
|
+
if (line.length === 0 || line.startsWith(':')) continue
|
|
175
|
+
const colon = line.indexOf(':')
|
|
176
|
+
const field = colon === -1 ? line : line.slice(0, colon)
|
|
177
|
+
let value = colon === -1 ? '' : line.slice(colon + 1)
|
|
178
|
+
if (value.startsWith(' ')) value = value.slice(1)
|
|
179
|
+
if (field === 'event') eventName = value
|
|
180
|
+
else if (field === 'data') dataLines.push(value)
|
|
181
|
+
}
|
|
182
|
+
if (dataLines.length === 0) return undefined
|
|
183
|
+
const data = dataLines.join('\n')
|
|
184
|
+
if (data === '[DONE]') return { event: eventName, data: '[DONE]' }
|
|
185
|
+
try {
|
|
186
|
+
return { event: eventName, data: JSON.parse(data), raw: data }
|
|
187
|
+
} catch {
|
|
188
|
+
return { event: eventName, data: undefined, raw: data, unparsed: true }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* 「先读到出现内容或流结束」——返回 `{ hasContent, head, elapsedMs, decoder, upstreamError }`。
|
|
194
|
+
*
|
|
195
|
+
* `head` 是**已解析但尚未交给调用方**的初始事件(含内容帧),调用方在决定「确实有内容」
|
|
196
|
+
* 后按序消费它,再接续后面的流。
|
|
197
|
+
*
|
|
198
|
+
* ⚠ **上游会把业务错误塞进 HTTP 200**(实测:`{"code":1005,"msg":"exceed quota limit"}`
|
|
199
|
+
* 配 `200 + application/json`)。若不识别,就会被当成「无权益的空响应」,
|
|
200
|
+
* 于是丢掉真正的错误码(`1005` 额度用尽 / `3012` 风控 / `3009` 并发限流),
|
|
201
|
+
* 排查时只看到误导性的「200 但零内容」。故这里先做业务错误识别。
|
|
202
|
+
*/
|
|
203
|
+
export async function readContentHead(body, options = {}) {
|
|
204
|
+
const startedAt = Date.now()
|
|
205
|
+
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES
|
|
206
|
+
const jsonMode = isJsonContentType(options.contentType)
|
|
207
|
+
const head = []
|
|
208
|
+
let scannedBytes = 0
|
|
209
|
+
|
|
210
|
+
if (jsonMode) {
|
|
211
|
+
const text = await new Response(body).text()
|
|
212
|
+
let parsed
|
|
213
|
+
try {
|
|
214
|
+
parsed = JSON.parse(text)
|
|
215
|
+
} catch {
|
|
216
|
+
parsed = undefined
|
|
217
|
+
}
|
|
218
|
+
/** 业务错误(HTTP 200 + `{code,msg}`):先于「有没有内容」判定。 */
|
|
219
|
+
const upstreamError = extractUpstreamError(parsed, text)
|
|
220
|
+
if (upstreamError !== undefined) {
|
|
221
|
+
return {
|
|
222
|
+
hasContent: false,
|
|
223
|
+
head,
|
|
224
|
+
elapsedMs: Date.now() - startedAt,
|
|
225
|
+
jsonMode: true,
|
|
226
|
+
decoder: undefined,
|
|
227
|
+
upstreamError,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const hasContent = jsonHasContent(text)
|
|
231
|
+
if (hasContent) head.push({ data: parsed, raw: text })
|
|
232
|
+
return { hasContent, head, elapsedMs: Date.now() - startedAt, jsonMode: true, decoder: undefined }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const decoder = makeSseDecoder(body, { timeoutMs: options.timeoutMs })
|
|
236
|
+
for (;;) {
|
|
237
|
+
const next = await decoder.read()
|
|
238
|
+
if (next.done === true) {
|
|
239
|
+
await decoder.cancel()
|
|
240
|
+
return { hasContent: false, head, elapsedMs: Date.now() - startedAt, jsonMode: false, decoder }
|
|
241
|
+
}
|
|
242
|
+
const event = next.value
|
|
243
|
+
head.push(event)
|
|
244
|
+
scannedBytes += (event.raw ?? '').length
|
|
245
|
+
/** 流内错误事件(Anthropic `{"type":"error"}`)也算业务错误,交给调用方按错误表处置。 */
|
|
246
|
+
const upstreamError = extractUpstreamError(event.data, event.raw ?? '')
|
|
247
|
+
if (upstreamError !== undefined) {
|
|
248
|
+
await decoder.cancel()
|
|
249
|
+
return {
|
|
250
|
+
hasContent: false,
|
|
251
|
+
head,
|
|
252
|
+
elapsedMs: Date.now() - startedAt,
|
|
253
|
+
jsonMode: false,
|
|
254
|
+
decoder,
|
|
255
|
+
upstreamError,
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const marker = CONTENT_MARKERS.some((needle) => (event.raw ?? '').includes(needle)) || hasVisibleBlock(event.data)
|
|
259
|
+
if (marker || scannedBytes >= maxBufferBytes) {
|
|
260
|
+
/** 把解码器交给调用方继续消费(而非丢弃剩余事件)。 */
|
|
261
|
+
return { hasContent: true, head, elapsedMs: Date.now() - startedAt, jsonMode: false, decoder }
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* 从已解析的载荷里识别**上游业务错误**。
|
|
268
|
+
*
|
|
269
|
+
* 认三种形态:
|
|
270
|
+
* - `{"code":1005,"msg":"..."}`(本渠道实测形态,状态码仍是 200)
|
|
271
|
+
* - `{"type":"error","error":{...}}`(Anthropic 标准错误)
|
|
272
|
+
* - `{"error":{"code":1005,...}}`(个别网关的包裹形态)
|
|
273
|
+
*
|
|
274
|
+
* @param {unknown} parsed
|
|
275
|
+
* @param {string} raw
|
|
276
|
+
* @returns {{ status: number, text: string } | undefined}
|
|
277
|
+
*/
|
|
278
|
+
export function extractUpstreamError(parsed, raw) {
|
|
279
|
+
if (typeof parsed === 'object' && parsed !== null) {
|
|
280
|
+
const record = /** @type {Record<string, any>} */ (parsed)
|
|
281
|
+
/** Anthropic 标准错误载荷。 */
|
|
282
|
+
if (record.type === 'error' && record.error !== undefined) {
|
|
283
|
+
return { status: 200, text: JSON.stringify(record) }
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* 业务码形态:`code` 非 0 且不是字符串型成功码。
|
|
287
|
+
* 注意 `code: 0` = 成功,不能被当成错误。
|
|
288
|
+
*/
|
|
289
|
+
const code = record.code ?? record.error?.code
|
|
290
|
+
if (typeof code === 'number' && code !== 0) {
|
|
291
|
+
return { status: 200, text: JSON.stringify({ code, msg: record.msg ?? record.message ?? record.error?.message ?? '' }) }
|
|
292
|
+
}
|
|
293
|
+
/** 裸 `error` 字段(无 code)。 */
|
|
294
|
+
if (record.error !== undefined && typeof record.error === 'object') {
|
|
295
|
+
return { status: 200, text: JSON.stringify(record) }
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return undefined
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 事件里是否出现了可见块(结构性判定,比扫特征串更稳)。 */
|
|
302
|
+
function hasVisibleBlock(data) {
|
|
303
|
+
if (typeof data !== 'object' || data === null) return false
|
|
304
|
+
if (data.type === 'content_block_start') {
|
|
305
|
+
const block = data.content_block
|
|
306
|
+
if (block?.type === 'tool_use') return true
|
|
307
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text.length > 0) return true
|
|
308
|
+
if (block?.type === 'thinking' && typeof block.thinking === 'string' && block.thinking.length > 0) return true
|
|
309
|
+
}
|
|
310
|
+
if (data.type === 'content_block_delta') {
|
|
311
|
+
const delta = data.delta
|
|
312
|
+
if (delta?.type === 'text_delta' && typeof delta.text === 'string' && delta.text.length > 0) return true
|
|
313
|
+
if (delta?.type === 'thinking_delta' && typeof delta.thinking === 'string' && delta.thinking.length > 0) return true
|
|
314
|
+
if (delta?.type === 'input_json_delta') return true
|
|
315
|
+
}
|
|
316
|
+
return false
|
|
317
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic SSE 事件 → DSH `StreamChunk` 的翻译器。
|
|
3
|
+
*
|
|
4
|
+
* ## DSH 侧的需要(与参考实现的关键差异)
|
|
5
|
+
*
|
|
6
|
+
* 参考实现是一层 **HTTP 代理**:它把上游字节原样透传给 ZCode(ZCode 自带 Anthropic SDK)。
|
|
7
|
+
* DSH 没有这层字节通道 —— 插件必须自己实现 `llm` 适配器,产出 DSH 的
|
|
8
|
+
* `StreamChunk` 词汇(`text-delta` / `reasoning-delta` / `tool-call-delta` / `usage` /
|
|
9
|
+
* `finish`,以 `block-start` / `block-end` 包住),并由 `ctx.llm` 的 `BlockAssembler`
|
|
10
|
+
* 组装成消息。本文件就是这段翻译。
|
|
11
|
+
*
|
|
12
|
+
* ## 协议要点(Anthropic Messages 流式)
|
|
13
|
+
*
|
|
14
|
+
* ```
|
|
15
|
+
* message_start → 记录 usage.input_tokens / model
|
|
16
|
+
* content_block_start(index,T) → 开一个块(text / thinking / tool_use)
|
|
17
|
+
* content_block_delta(index,D) → 增量(text_delta / thinking_delta / input_json_delta)
|
|
18
|
+
* content_block_stop(index) → 关块
|
|
19
|
+
* message_delta(delta.stop_reason) → 记录 stop_reason 与 usage.output_tokens
|
|
20
|
+
* message_stop → 流结束
|
|
21
|
+
* error → 上游错误(含 3012 等业务码)
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* ## 顺序约束(DSH 协议)
|
|
25
|
+
*
|
|
26
|
+
* `usage` 必须在 `finish` 之前;`finish` 之后不得再有任何 chunk;工具参数以
|
|
27
|
+
* **原始 JSON 字符串**增量下发。故这里采用「先 `block-end`,再 `usage`,再 `finish`」。
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 翻译器:逐事件喂入,产出 DSH chunk 数组。
|
|
32
|
+
*
|
|
33
|
+
* @param {{ supportsReasoning?: boolean }} [options]
|
|
34
|
+
*/
|
|
35
|
+
export class AnthropicStreamTranslator {
|
|
36
|
+
#blocks = new Map()
|
|
37
|
+
#nextChunkIndex = 0
|
|
38
|
+
#model
|
|
39
|
+
#finishReason
|
|
40
|
+
#usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
|
|
41
|
+
#sawMessageStart = false
|
|
42
|
+
#sawError
|
|
43
|
+
|
|
44
|
+
/** 上游报出来的错误(若在流内出现)。 */
|
|
45
|
+
get error() {
|
|
46
|
+
return this.#sawError
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 已看到的模型名(message_start 里带的,可能与请求不同)。 */
|
|
50
|
+
get model() {
|
|
51
|
+
return this.#model
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 累积用量。 */
|
|
55
|
+
get usage() {
|
|
56
|
+
return { ...this.#usage }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 喂入一个已解析的 SSE 事件。
|
|
61
|
+
*
|
|
62
|
+
* @param {{ event?: string, data?: any, unparsed?: boolean }} sseEvent
|
|
63
|
+
* @returns {Array<any>} DSH chunk 列表(可能为空)
|
|
64
|
+
*/
|
|
65
|
+
push(sseEvent) {
|
|
66
|
+
const data = sseEvent?.data
|
|
67
|
+
if (data === undefined) return []
|
|
68
|
+
/** `[DONE]` 哨兵:部分兼容网关会发,忽略。 */
|
|
69
|
+
if (data === '[DONE]') return []
|
|
70
|
+
|
|
71
|
+
switch (data.type) {
|
|
72
|
+
case 'message_start': {
|
|
73
|
+
this.#sawMessageStart = true
|
|
74
|
+
this.#model = data.message?.model
|
|
75
|
+
this.#mergeUsage(data.message?.usage)
|
|
76
|
+
return []
|
|
77
|
+
}
|
|
78
|
+
case 'content_block_start': {
|
|
79
|
+
const index = data.index ?? this.#blocks.size
|
|
80
|
+
const block = data.content_block ?? {}
|
|
81
|
+
const chunkIndex = this.#nextChunkIndex++
|
|
82
|
+
/**
|
|
83
|
+
* ⚠ **DSH `BlockAssembler` 的确切契约**(`dsh-llm/lib/index.js`):
|
|
84
|
+
*
|
|
85
|
+
* case "block-start": partials.set(index, { blockType: chunk.blockType, ... })
|
|
86
|
+
* case "text-delta" / "reasoning-delta": partial.text += chunk.text
|
|
87
|
+
* case "tool-call-delta": toolCallId = chunk.id; toolCallName = chunk.name;
|
|
88
|
+
* toolCallArguments += chunk.argumentsDelta
|
|
89
|
+
* case "block-end": partial.block = chunk.block ← 必须带完整 block
|
|
90
|
+
*
|
|
91
|
+
* 也就是说:`block-start` 用 **`blockType`(字符串)**,不是 `block`(对象);
|
|
92
|
+
* `block-end` **必须**带 `block`(assemble 直接返回它,否则按 blockType 兜底拼装,
|
|
93
|
+
* 丢字段);`tool-call-delta` 的字段名是 `id` / `name` / **`argumentsDelta`**。
|
|
94
|
+
*
|
|
95
|
+
* 之前我发的是 `{ block: {...} }` / `{ arguments }` —— `blockType` 读到 undefined,
|
|
96
|
+
* 宿主侧 `partial.blockType` 解引用即抛
|
|
97
|
+
* `Cannot read properties of undefined (reading 'type')`(思考型模型先出 reasoning 块,
|
|
98
|
+
* 所以只有 Flash 这类模型才暴露)。
|
|
99
|
+
*/
|
|
100
|
+
const entry = { chunkIndex, kind: block.type, id: block.id, name: block.name, text: '' }
|
|
101
|
+
if (block.type === 'tool_use' && block.input !== undefined) {
|
|
102
|
+
/** 内联参数只作后备;若后续有 input_json_delta,完整增量优先。 */
|
|
103
|
+
entry.inlineArguments = JSON.stringify(block.input)
|
|
104
|
+
}
|
|
105
|
+
this.#blocks.set(index, entry)
|
|
106
|
+
|
|
107
|
+
if (block.type === 'text') {
|
|
108
|
+
const out = [{ type: 'block-start', index: chunkIndex, blockType: 'text' }]
|
|
109
|
+
if (typeof block.text === 'string' && block.text.length > 0) {
|
|
110
|
+
entry.text = block.text
|
|
111
|
+
out.push({ type: 'text-delta', index: chunkIndex, text: block.text })
|
|
112
|
+
}
|
|
113
|
+
return out
|
|
114
|
+
}
|
|
115
|
+
if (block.type === 'thinking') {
|
|
116
|
+
const out = [{ type: 'block-start', index: chunkIndex, blockType: 'reasoning' }]
|
|
117
|
+
if (typeof block.thinking === 'string' && block.thinking.length > 0) {
|
|
118
|
+
entry.text = block.thinking
|
|
119
|
+
out.push({ type: 'reasoning-delta', index: chunkIndex, text: block.thinking })
|
|
120
|
+
}
|
|
121
|
+
return out
|
|
122
|
+
}
|
|
123
|
+
if (block.type === 'tool_use') {
|
|
124
|
+
return [
|
|
125
|
+
{
|
|
126
|
+
type: 'block-start',
|
|
127
|
+
index: chunkIndex,
|
|
128
|
+
blockType: 'tool-call',
|
|
129
|
+
},
|
|
130
|
+
]
|
|
131
|
+
}
|
|
132
|
+
/** 其它块(如 redacted_thinking):开一个 reasoning 块以保持块序,但无内容可下发。 */
|
|
133
|
+
return [{ type: 'block-start', index: chunkIndex, blockType: 'reasoning' }]
|
|
134
|
+
}
|
|
135
|
+
case 'content_block_delta': {
|
|
136
|
+
const entry = this.#blocks.get(data.index)
|
|
137
|
+
if (entry === undefined) return []
|
|
138
|
+
const delta = data.delta ?? {}
|
|
139
|
+
if (delta.type === 'text_delta' && typeof delta.text === 'string') {
|
|
140
|
+
entry.text += delta.text
|
|
141
|
+
return [{ type: 'text-delta', index: entry.chunkIndex, text: delta.text }]
|
|
142
|
+
}
|
|
143
|
+
if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
|
|
144
|
+
entry.text += delta.thinking
|
|
145
|
+
return [{ type: 'reasoning-delta', index: entry.chunkIndex, text: delta.thinking }]
|
|
146
|
+
}
|
|
147
|
+
if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
|
|
148
|
+
entry.arguments = (entry.arguments ?? '') + delta.partial_json
|
|
149
|
+
return [
|
|
150
|
+
{
|
|
151
|
+
type: 'tool-call-delta',
|
|
152
|
+
index: entry.chunkIndex,
|
|
153
|
+
id: entry.id,
|
|
154
|
+
name: entry.name,
|
|
155
|
+
argumentsDelta: delta.partial_json,
|
|
156
|
+
},
|
|
157
|
+
]
|
|
158
|
+
}
|
|
159
|
+
return []
|
|
160
|
+
}
|
|
161
|
+
case 'content_block_stop': {
|
|
162
|
+
const entry = this.#blocks.get(data.index)
|
|
163
|
+
if (entry === undefined) return []
|
|
164
|
+
this.#blocks.delete(data.index)
|
|
165
|
+
return [{ type: 'block-end', index: entry.chunkIndex, block: this.#assembleBlock(entry) }]
|
|
166
|
+
}
|
|
167
|
+
case 'message_delta': {
|
|
168
|
+
if (typeof data.delta?.stop_reason === 'string') {
|
|
169
|
+
this.#finishReason = mapStopReason(data.delta.stop_reason)
|
|
170
|
+
}
|
|
171
|
+
this.#mergeUsage(data.usage)
|
|
172
|
+
return []
|
|
173
|
+
}
|
|
174
|
+
case 'message_stop':
|
|
175
|
+
return []
|
|
176
|
+
case 'error': {
|
|
177
|
+
this.#sawError = {
|
|
178
|
+
type: data.error?.type,
|
|
179
|
+
message: data.error?.message ?? JSON.stringify(data.error ?? data),
|
|
180
|
+
}
|
|
181
|
+
return []
|
|
182
|
+
}
|
|
183
|
+
case 'ping':
|
|
184
|
+
default:
|
|
185
|
+
return []
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 把一个块累积成 DSH 的**完整 block 对象**(`block-end` 必须带它)。
|
|
191
|
+
*
|
|
192
|
+
* 字段名与 `BlockAssembler.assemble()` 的输出严格一致:
|
|
193
|
+
* text → { type: 'text', text }
|
|
194
|
+
* reasoning→ { type: 'reasoning', text }
|
|
195
|
+
* tool-call→ { type: 'tool-call', id, name, arguments }
|
|
196
|
+
*
|
|
197
|
+
* @param {{ kind: string, id?: string, name?: string, text: string, arguments?: string }} entry
|
|
198
|
+
*/
|
|
199
|
+
#assembleBlock(entry) {
|
|
200
|
+
if (entry.kind === 'tool_use' || entry.kind === 'tool-call') {
|
|
201
|
+
/** 工具参数是**原始 JSON 字符串**(宿主不做解析)。 */
|
|
202
|
+
let args = entry.arguments ?? entry.inlineArguments ?? ''
|
|
203
|
+
if (args.length === 0) args = '{}'
|
|
204
|
+
return {
|
|
205
|
+
type: 'tool-call',
|
|
206
|
+
id: entry.id ?? `call_${entry.chunkIndex}`,
|
|
207
|
+
name: entry.name ?? '',
|
|
208
|
+
arguments: args,
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (entry.kind === 'thinking' || entry.kind === 'redacted_thinking' || entry.kind === 'reasoning') {
|
|
212
|
+
return { type: 'reasoning', text: entry.text ?? '' }
|
|
213
|
+
}
|
|
214
|
+
return { type: 'text', text: entry.text ?? '' }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** 收尾:补 `usage` 与 `finish`(顺序固定)。 */
|
|
218
|
+
finish() {
|
|
219
|
+
const out = []
|
|
220
|
+
for (const [index, entry] of this.#blocks) {
|
|
221
|
+
this.#blocks.delete(index)
|
|
222
|
+
out.push({ type: 'block-end', index: entry.chunkIndex, block: this.#assembleBlock(entry) })
|
|
223
|
+
}
|
|
224
|
+
out.push({ type: 'usage', usage: this.#usage })
|
|
225
|
+
if (this.#sawError !== undefined) {
|
|
226
|
+
out.push({
|
|
227
|
+
type: 'finish',
|
|
228
|
+
kind: 'error',
|
|
229
|
+
failure: { code: mapErrorCode(this.#sawError), message: this.#sawError.message },
|
|
230
|
+
})
|
|
231
|
+
return out
|
|
232
|
+
}
|
|
233
|
+
out.push({ type: 'finish', kind: 'stop', reason: this.#finishReason ?? 'stop' })
|
|
234
|
+
return out
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
#mergeUsage(usage) {
|
|
238
|
+
if (typeof usage !== 'object' || usage === null) return
|
|
239
|
+
const input = usage.input_tokens ?? usage.inputTokens
|
|
240
|
+
const output = usage.output_tokens ?? usage.outputTokens
|
|
241
|
+
const cacheRead = usage.cache_read_input_tokens ?? usage.cacheReadInputTokens
|
|
242
|
+
const cacheWrite = usage.cache_creation_input_tokens ?? usage.cacheWriteInputTokens
|
|
243
|
+
if (typeof input === 'number') this.#usage.inputTokens = input
|
|
244
|
+
if (typeof output === 'number') this.#usage.outputTokens = output
|
|
245
|
+
if (typeof cacheRead === 'number') this.#usage.cacheReadTokens = cacheRead
|
|
246
|
+
if (typeof cacheWrite === 'number') this.#usage.cacheWriteTokens = cacheWrite
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Anthropic `stop_reason` → DSH finish reason。 */
|
|
251
|
+
export function mapStopReason(stopReason) {
|
|
252
|
+
switch (stopReason) {
|
|
253
|
+
case 'tool_use':
|
|
254
|
+
return 'tool-calls'
|
|
255
|
+
case 'max_tokens':
|
|
256
|
+
return 'length'
|
|
257
|
+
case 'end_turn':
|
|
258
|
+
case 'stop_sequence':
|
|
259
|
+
return 'stop'
|
|
260
|
+
default:
|
|
261
|
+
return 'stop'
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* 业务码 → DSH 失败码。
|
|
267
|
+
*
|
|
268
|
+
* DSH 的稳定码:`AUTH` / `RATE_LIMIT` / `QUOTA` / `NO_ADAPTER` / `MISSING_CREDENTIAL` …
|
|
269
|
+
* 消费者按 code 路由,**绝不**按 message 文本。
|
|
270
|
+
*/
|
|
271
|
+
export function mapErrorCode(error) {
|
|
272
|
+
const text = String(error?.message ?? '')
|
|
273
|
+
if (text.includes('3012') || text.includes('3007')) return 'RATE_LIMIT'
|
|
274
|
+
if (text.includes('1005') || text.includes('1113') || text.includes('1003')) return 'QUOTA'
|
|
275
|
+
if (text.includes('1002') || /invalid\s+token|token\s+expired/i.test(text)) return 'AUTH'
|
|
276
|
+
if (error?.type === 'authentication_error') return 'AUTH'
|
|
277
|
+
if (error?.type === 'rate_limit_error') return 'RATE_LIMIT'
|
|
278
|
+
return 'PROVIDER_ERROR'
|
|
279
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 消息首行(`##` 标题 / ``` 代码围栏)与「是否看起来像拒答」的极简判定。
|
|
3
|
+
*
|
|
4
|
+
* 只用于**可观测性**(状态工具里报告「上一轮像拒答」),**不参与**任何提示词注入:
|
|
5
|
+
* 真正的破甲/人格逻辑属于独立插件(例如 dsh-infinite-gen-x),本插件只管通道路由。
|
|
6
|
+
*/
|
|
7
|
+
const REFUSAL_MARKERS = Object.freeze([
|
|
8
|
+
/^i\s+(?:can't|cannot|won't|am unable)/i,
|
|
9
|
+
/^i'm\s+sorry/i,
|
|
10
|
+
/^sorry[,.]/i,
|
|
11
|
+
/^(?:unfortunately[,.]\s*)?i\s+(?:must|cannot|can't)/i,
|
|
12
|
+
/^(?:很抱歉|抱歉|对不起)[,,。.]?/,
|
|
13
|
+
/^我(?:无法|不能|不便|不会)/,
|
|
14
|
+
])
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 首行是否以 `##` 标题或 ``` 围栏开头(交付物契约)。
|
|
18
|
+
* @param {string} text
|
|
19
|
+
*/
|
|
20
|
+
export function opensWithDeliverable(text) {
|
|
21
|
+
if (typeof text !== 'string') return false
|
|
22
|
+
const firstLine = text.trimStart().split(/\r?\n/, 1)[0] ?? ''
|
|
23
|
+
return firstLine.startsWith('## ') || firstLine.startsWith('```')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 开头窗口内是否出现拒答特征。
|
|
28
|
+
* @param {string} text
|
|
29
|
+
* @param {number} [window]
|
|
30
|
+
*/
|
|
31
|
+
export function looksLikeRefusal(text, window = 160) {
|
|
32
|
+
if (typeof text !== 'string') return false
|
|
33
|
+
const head = text.trimStart().slice(0, window)
|
|
34
|
+
return REFUSAL_MARKERS.some((pattern) => pattern.test(head))
|
|
35
|
+
}
|