dsh-zcode-startplan 0.0.0-stage → 0.4.5

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/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,301 @@
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
+ * ## finish chunk 的形状(官方契约,`dsh-llm` rc.3 起有 .d.ts 钉死)
30
+ *
31
+ * 终止块是 `{ type: 'finish', reason: FinishReason }` —— `reason` 是**对象**,
32
+ * 按 kind 区分(`FinishReasonMap`,`dsh-llm/lib/types/types.d.ts`):
33
+ *
34
+ * ```
35
+ * { kind: 'stop' } | { kind: 'tool-calls' } | { kind: 'max-tokens' }
36
+ * { kind: 'aborted', failure } | { kind: 'error', failure }
37
+ * ```
38
+ *
39
+ * 宿主 `BlockAssembler` 读 `chunk.reason`(`this._finish = chunk.reason`),
40
+ * agent-loop 再读 `finish.kind === 'error' | 'aborted'` 判错。
41
+ * 之前发的是 `{ kind, failure }`(kind 在顶层、没有 reason)—— 错误会被宿主
42
+ * 静默吞成 `{ kind: 'stop' }`「正常结束」,重试与错误上报全部失效。
43
+ */
44
+
45
+ /**
46
+ * 翻译器:逐事件喂入,产出 DSH chunk 数组。
47
+ *
48
+ * @param {{ supportsReasoning?: boolean }} [options]
49
+ */
50
+ export class AnthropicStreamTranslator {
51
+ #blocks = new Map()
52
+ #nextChunkIndex = 0
53
+ #model
54
+ #finishReason
55
+ #usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
56
+ #sawMessageStart = false
57
+ #sawError
58
+
59
+ /** 上游报出来的错误(若在流内出现)。 */
60
+ get error() {
61
+ return this.#sawError
62
+ }
63
+
64
+ /** 已看到的模型名(message_start 里带的,可能与请求不同)。 */
65
+ get model() {
66
+ return this.#model
67
+ }
68
+
69
+ /** 累积用量。 */
70
+ get usage() {
71
+ return { ...this.#usage }
72
+ }
73
+
74
+ /**
75
+ * 喂入一个已解析的 SSE 事件。
76
+ *
77
+ * @param {{ event?: string, data?: any, unparsed?: boolean }} sseEvent
78
+ * @returns {Array<any>} DSH chunk 列表(可能为空)
79
+ */
80
+ push(sseEvent) {
81
+ const data = sseEvent?.data
82
+ if (data === undefined) return []
83
+ /** `[DONE]` 哨兵:部分兼容网关会发,忽略。 */
84
+ if (data === '[DONE]') return []
85
+
86
+ switch (data.type) {
87
+ case 'message_start': {
88
+ this.#sawMessageStart = true
89
+ this.#model = data.message?.model
90
+ this.#mergeUsage(data.message?.usage)
91
+ return []
92
+ }
93
+ case 'content_block_start': {
94
+ const index = data.index ?? this.#blocks.size
95
+ const block = data.content_block ?? {}
96
+ const chunkIndex = this.#nextChunkIndex++
97
+ /**
98
+ * ⚠ **DSH `BlockAssembler` 的确切契约**(`dsh-llm/lib/index.js`):
99
+ *
100
+ * case "block-start": partials.set(index, { blockType: chunk.blockType, ... })
101
+ * case "text-delta" / "reasoning-delta": partial.text += chunk.text
102
+ * case "tool-call-delta": toolCallId = chunk.id; toolCallName = chunk.name;
103
+ * toolCallArguments += chunk.argumentsDelta
104
+ * case "block-end": partial.block = chunk.block ← 必须带完整 block
105
+ *
106
+ * 也就是说:`block-start` 用 **`blockType`(字符串)**,不是 `block`(对象);
107
+ * `block-end` **必须**带 `block`(assemble 直接返回它,否则按 blockType 兜底拼装,
108
+ * 丢字段);`tool-call-delta` 的字段名是 `id` / `name` / **`argumentsDelta`**。
109
+ *
110
+ * 之前我发的是 `{ block: {...} }` / `{ arguments }` —— `blockType` 读到 undefined,
111
+ * 宿主侧 `partial.blockType` 解引用即抛
112
+ * `Cannot read properties of undefined (reading 'type')`(思考型模型先出 reasoning 块,
113
+ * 所以只有 Flash 这类模型才暴露)。
114
+ */
115
+ const entry = { chunkIndex, kind: block.type, id: block.id, name: block.name, text: '' }
116
+ if (block.type === 'tool_use' && block.input !== undefined) {
117
+ /** 内联参数只作后备;若后续有 input_json_delta,完整增量优先。 */
118
+ entry.inlineArguments = JSON.stringify(block.input)
119
+ }
120
+ this.#blocks.set(index, entry)
121
+
122
+ if (block.type === 'text') {
123
+ const out = [{ type: 'block-start', index: chunkIndex, blockType: 'text' }]
124
+ if (typeof block.text === 'string' && block.text.length > 0) {
125
+ entry.text = block.text
126
+ out.push({ type: 'text-delta', index: chunkIndex, text: block.text })
127
+ }
128
+ return out
129
+ }
130
+ if (block.type === 'thinking') {
131
+ const out = [{ type: 'block-start', index: chunkIndex, blockType: 'reasoning' }]
132
+ if (typeof block.thinking === 'string' && block.thinking.length > 0) {
133
+ entry.text = block.thinking
134
+ out.push({ type: 'reasoning-delta', index: chunkIndex, text: block.thinking })
135
+ }
136
+ return out
137
+ }
138
+ if (block.type === 'tool_use') {
139
+ return [
140
+ {
141
+ type: 'block-start',
142
+ index: chunkIndex,
143
+ blockType: 'tool-call',
144
+ },
145
+ ]
146
+ }
147
+ /** 其它块(如 redacted_thinking):开一个 reasoning 块以保持块序,但无内容可下发。 */
148
+ return [{ type: 'block-start', index: chunkIndex, blockType: 'reasoning' }]
149
+ }
150
+ case 'content_block_delta': {
151
+ const entry = this.#blocks.get(data.index)
152
+ if (entry === undefined) return []
153
+ const delta = data.delta ?? {}
154
+ if (delta.type === 'text_delta' && typeof delta.text === 'string') {
155
+ entry.text += delta.text
156
+ return [{ type: 'text-delta', index: entry.chunkIndex, text: delta.text }]
157
+ }
158
+ if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
159
+ entry.text += delta.thinking
160
+ return [{ type: 'reasoning-delta', index: entry.chunkIndex, text: delta.thinking }]
161
+ }
162
+ if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
163
+ entry.arguments = (entry.arguments ?? '') + delta.partial_json
164
+ return [
165
+ {
166
+ type: 'tool-call-delta',
167
+ index: entry.chunkIndex,
168
+ id: entry.id,
169
+ name: entry.name,
170
+ argumentsDelta: delta.partial_json,
171
+ },
172
+ ]
173
+ }
174
+ return []
175
+ }
176
+ case 'content_block_stop': {
177
+ const entry = this.#blocks.get(data.index)
178
+ if (entry === undefined) return []
179
+ this.#blocks.delete(data.index)
180
+ return [{ type: 'block-end', index: entry.chunkIndex, block: this.#assembleBlock(entry) }]
181
+ }
182
+ case 'message_delta': {
183
+ if (typeof data.delta?.stop_reason === 'string') {
184
+ this.#finishReason = mapStopReason(data.delta.stop_reason)
185
+ }
186
+ this.#mergeUsage(data.usage)
187
+ return []
188
+ }
189
+ case 'message_stop':
190
+ return []
191
+ case 'error': {
192
+ this.#sawError = {
193
+ type: data.error?.type,
194
+ message: data.error?.message ?? JSON.stringify(data.error ?? data),
195
+ }
196
+ return []
197
+ }
198
+ case 'ping':
199
+ default:
200
+ return []
201
+ }
202
+ }
203
+
204
+ /**
205
+ * 把一个块累积成 DSH 的**完整 block 对象**(`block-end` 必须带它)。
206
+ *
207
+ * 字段名与 `BlockAssembler.assemble()` 的输出严格一致:
208
+ * text → { type: 'text', text }
209
+ * reasoning→ { type: 'reasoning', text }
210
+ * tool-call→ { type: 'tool-call', id, name, arguments }
211
+ *
212
+ * @param {{ kind: string, id?: string, name?: string, text: string, arguments?: string }} entry
213
+ */
214
+ #assembleBlock(entry) {
215
+ if (entry.kind === 'tool_use' || entry.kind === 'tool-call') {
216
+ /** 工具参数是**原始 JSON 字符串**(宿主不做解析)。 */
217
+ let args = entry.arguments ?? entry.inlineArguments ?? ''
218
+ if (args.length === 0) args = '{}'
219
+ return {
220
+ type: 'tool-call',
221
+ id: entry.id ?? `call_${entry.chunkIndex}`,
222
+ name: entry.name ?? '',
223
+ arguments: args,
224
+ }
225
+ }
226
+ if (entry.kind === 'thinking' || entry.kind === 'redacted_thinking' || entry.kind === 'reasoning') {
227
+ return { type: 'reasoning', text: entry.text ?? '' }
228
+ }
229
+ return { type: 'text', text: entry.text ?? '' }
230
+ }
231
+
232
+ /** 收尾:补 `usage` 与 `finish`(顺序固定)。 */
233
+ finish() {
234
+ const out = []
235
+ for (const [index, entry] of this.#blocks) {
236
+ this.#blocks.delete(index)
237
+ out.push({ type: 'block-end', index: entry.chunkIndex, block: this.#assembleBlock(entry) })
238
+ }
239
+ out.push({ type: 'usage', usage: this.#usage })
240
+ if (this.#sawError !== undefined) {
241
+ out.push({
242
+ type: 'finish',
243
+ reason: {
244
+ kind: 'error',
245
+ failure: { code: mapErrorCode(this.#sawError), message: this.#sawError.message },
246
+ },
247
+ })
248
+ return out
249
+ }
250
+ out.push({ type: 'finish', reason: this.#finishReason ?? { kind: 'stop' } })
251
+ return out
252
+ }
253
+
254
+ #mergeUsage(usage) {
255
+ if (typeof usage !== 'object' || usage === null) return
256
+ const input = usage.input_tokens ?? usage.inputTokens
257
+ const output = usage.output_tokens ?? usage.outputTokens
258
+ const cacheRead = usage.cache_read_input_tokens ?? usage.cacheReadInputTokens
259
+ const cacheWrite = usage.cache_creation_input_tokens ?? usage.cacheWriteInputTokens
260
+ if (typeof input === 'number') this.#usage.inputTokens = input
261
+ if (typeof output === 'number') this.#usage.outputTokens = output
262
+ if (typeof cacheRead === 'number') this.#usage.cacheReadTokens = cacheRead
263
+ if (typeof cacheWrite === 'number') this.#usage.cacheWriteTokens = cacheWrite
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Anthropic `stop_reason` → DSH finish reason 对象(`FinishReasonMap` 形态)。
269
+ *
270
+ * ⚠ 返回的是 `reason` **对象**(`{ kind: '…' }`),不是字符串 ——
271
+ * `BlockAssembler` 会把它原样存进 `finish`,agent-loop 按 `finish.kind` 路由。
272
+ */
273
+ export function mapStopReason(stopReason) {
274
+ switch (stopReason) {
275
+ case 'tool_use':
276
+ return { kind: 'tool-calls' }
277
+ case 'max_tokens':
278
+ return { kind: 'max-tokens' }
279
+ case 'end_turn':
280
+ case 'stop_sequence':
281
+ return { kind: 'stop' }
282
+ default:
283
+ return { kind: 'stop' }
284
+ }
285
+ }
286
+
287
+ /**
288
+ * 业务码 → DSH 失败码。
289
+ *
290
+ * DSH 的稳定码:`AUTH` / `RATE_LIMIT` / `QUOTA` / `NO_ADAPTER` / `MISSING_CREDENTIAL` …
291
+ * 消费者按 code 路由,**绝不**按 message 文本。
292
+ */
293
+ export function mapErrorCode(error) {
294
+ const text = String(error?.message ?? '')
295
+ if (text.includes('3012') || text.includes('3007')) return 'RATE_LIMIT'
296
+ if (text.includes('1005') || text.includes('1113') || text.includes('1003')) return 'QUOTA'
297
+ if (text.includes('1002') || /invalid\s+token|token\s+expired/i.test(text)) return 'AUTH'
298
+ if (error?.type === 'authentication_error') return 'AUTH'
299
+ if (error?.type === 'rate_limit_error') return 'RATE_LIMIT'
300
+ return 'PROVIDER_ERROR'
301
+ }
@@ -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
+ }