dsh-zcode-startplan 0.4.5 → 0.5.2

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.
@@ -0,0 +1,305 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import {
5
+ OFFICIAL_CLI_PREFIX,
6
+ OFFICIAL_STABLE_SECTIONS,
7
+ buildUpstreamBody,
8
+ buildZcodeSystemBlocks,
9
+ convertContent,
10
+ convertTools,
11
+ imageBlockFromAttachment,
12
+ imageOccurrences,
13
+ resolveImages,
14
+ withContextPrefix,
15
+ } from '../lib/anthropic-body.js'
16
+
17
+ const userMessage = (text) => ({ role: 'user', content: [{ type: 'text', text }] })
18
+
19
+ test('身份块必须打头(3012 的准入判据)', () => {
20
+ const blocks = buildZcodeSystemBlocks('CALLER SYSTEM', { cwd: 'C:/w' })
21
+ assert.equal(blocks[0].text, OFFICIAL_CLI_PREFIX)
22
+ assert.equal(blocks[1].text, OFFICIAL_STABLE_SECTIONS.join('\n\n'))
23
+ assert.match(blocks[2].text, /# Environment/)
24
+ /** 调用方内容追加在最后 —— 前置会顶掉官方前缀结构。 */
25
+ assert.equal(blocks[blocks.length - 1].text, 'CALLER SYSTEM')
26
+ })
27
+
28
+ test('只在最后一块打 cache_control(单请求最多 4 个断点)', () => {
29
+ const blocks = buildZcodeSystemBlocks('x', { cwd: '.' })
30
+ const withCache = blocks.filter((block) => block.cache_control !== undefined)
31
+ assert.equal(withCache.length, 1)
32
+ assert.equal(blocks[blocks.length - 1].cache_control.type, 'ephemeral')
33
+ })
34
+
35
+ test('首轮 user 消息插入日期块,且幂等', () => {
36
+ const once = withContextPrefix([userMessage('hi')], new Date(2026, 9, 23))
37
+ const first = once[0].content[0]
38
+ assert.match(first.text, /^<system-reminder>/)
39
+ assert.match(first.text, /Today's date is 2026-10-23\./)
40
+ assert.equal(once[0].content[1].text, 'hi')
41
+
42
+ const twice = withContextPrefix(once, new Date(2026, 9, 24))
43
+ assert.equal(twice[0].content.length, 2, '已带日期块的消息不得重复插入')
44
+ })
45
+
46
+ test('日期块只进第一条 user 消息(纯文本 content 会被转成块数组)', () => {
47
+ const messages = withContextPrefix(
48
+ [
49
+ { role: 'user', content: 'hello' },
50
+ { role: 'assistant', content: 'world' },
51
+ ],
52
+ new Date(2026, 9, 23),
53
+ )
54
+ assert.ok(Array.isArray(messages[0].content))
55
+ assert.match(messages[0].content[0].text, /system-reminder/)
56
+ assert.equal(messages[1].content, 'world')
57
+ })
58
+
59
+ test('convertTools: 只在最后一个 tool 打断点,并剥掉 $schema / additionalProperties', () => {
60
+ const tools = convertTools([
61
+ { name: 'a', description: 'A', parameters: { type: 'object', properties: {}, $schema: 'x', additionalProperties: false } },
62
+ { name: 'b', parameters: { type: 'object', properties: {} } },
63
+ { name: 'no-schema' },
64
+ ])
65
+ assert.equal(tools.length, 2, '缺 parameters 的工具被跳过')
66
+ assert.equal(tools[0].cache_control, undefined)
67
+ assert.deepEqual(tools[1].cache_control, { type: 'ephemeral' })
68
+ assert.equal(tools[0].input_schema.$schema, undefined)
69
+ assert.equal(tools[0].input_schema.additionalProperties, undefined)
70
+ })
71
+
72
+ test('buildUpstreamBody: DSH 工具调用/结果翻成 Anthropic 块', () => {
73
+ const body = buildUpstreamBody({
74
+ options: {
75
+ model: 'GLM-5.3-Flash',
76
+ system: [{ type: 'text', text: 'SYS' }],
77
+ maxTokens: 1000,
78
+ messages: [
79
+ { role: 'user', content: [{ type: 'text', text: 'list files' }] },
80
+ {
81
+ role: 'assistant',
82
+ content: [{ type: 'tool-call', id: 'call_1', name: 'pwsh', arguments: { cmd: 'ls' } }],
83
+ },
84
+ { role: 'user', content: [{ type: 'tool-result', toolCallId: 'call_1', output: 'a.txt' }] },
85
+ ],
86
+ tools: [{ name: 'pwsh', parameters: { type: 'object', properties: {} } }],
87
+ temperature: 0.2,
88
+ },
89
+ cwd: 'C:/w',
90
+ maxTokens: 1000,
91
+ })
92
+
93
+ assert.equal(body.model, 'GLM-5.3-Flash')
94
+ assert.equal(body.stream, true)
95
+ assert.equal(body.max_tokens, 1000)
96
+ assert.equal(body.temperature, 0.2)
97
+ assert.equal(body.messages[0].role, 'user')
98
+ assert.match(body.messages[0].content[0].text, /system-reminder/)
99
+
100
+ const assistant = body.messages[1]
101
+ const toolUse = assistant.content.find((block) => block.type === 'tool_use')
102
+ assert.equal(toolUse.id, 'call_1')
103
+ assert.equal(toolUse.name, 'pwsh')
104
+ assert.deepEqual(toolUse.input, { cmd: 'ls' })
105
+
106
+ const toolResult = body.messages[2].content.find((block) => block.type === 'tool_result')
107
+ assert.equal(toolResult.tool_use_id, 'call_1')
108
+ assert.equal(toolResult.content, 'a.txt')
109
+
110
+ assert.equal(body.tools[0].cache_control.type, 'ephemeral')
111
+ })
112
+
113
+ test('buildUpstreamBody: 回放宿主保存的 JSON 字符串工具参数时,tool_use.input 必须是对象', () => {
114
+ const body = buildUpstreamBody({
115
+ options: {
116
+ model: 'GLM-5.3-Flash',
117
+ messages: [
118
+ userMessage('运行命令'),
119
+ { role: 'assistant', content: [{
120
+ type: 'tool-call', id: 'call_pwsh', name: 'pwsh',
121
+ arguments: '{"description":"列出文件","command":"Get-ChildItem","options":{"cwd":"C:/w"}}',
122
+ }] },
123
+ ],
124
+ },
125
+ now: new Date(2026, 9, 24),
126
+ })
127
+ assert.deepEqual(body.messages[1].content[0].input, {
128
+ description: '列出文件', command: 'Get-ChildItem', options: { cwd: 'C:/w' },
129
+ })
130
+ })
131
+
132
+ test('buildUpstreamBody: 不向历史回放思考块', () => {
133
+ const body = buildUpstreamBody({
134
+ options: {
135
+ model: 'GLM-5.3',
136
+ messages: [
137
+ userMessage('hi'),
138
+ { role: 'assistant', content: [{ type: 'reasoning', text: 'thinking…' }, { type: 'text', text: 'ok' }] },
139
+ ],
140
+ },
141
+ })
142
+ const assistant = body.messages[1]
143
+ assert.deepEqual(assistant.content.map((block) => block.type), ['text'])
144
+ })
145
+
146
+ test('buildUpstreamBody: 不支持图片的模型收到占位文本', () => {
147
+ const body = buildUpstreamBody({
148
+ options: {
149
+ model: 'GLM-5.3',
150
+ messages: [
151
+ {
152
+ role: 'user',
153
+ content: [
154
+ { type: 'text', text: 'see' },
155
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'AAAA' } },
156
+ ],
157
+ },
158
+ ],
159
+ },
160
+ supportsImages: false,
161
+ })
162
+ const blocks = body.messages[0].content
163
+ assert.equal(blocks.some((block) => block.type === 'image'), false)
164
+ assert.match(blocks.map((block) => block.text).join('|'), /image omitted/)
165
+ })
166
+
167
+ // ---------------------------------------------------------------------------
168
+ // 图片输入:宿主 ImageBlock(持久引用)→ 附件服务字节 → Anthropic base64 块。
169
+ // 宿主契约:`dsh-llm` 的 ImageBlock 是 `{ type:'image', attachment: ref }`,
170
+ // ref = `{ attachmentId:'sha256:<hex>', mediaType, width, height, bytes, name? }`
171
+ // (attachment-local 实测)。此前 convertContent 只认 base64 形态,
172
+ // 引用块被静默丢弃 —— 用户发图但上游什么都没收到。
173
+ // ---------------------------------------------------------------------------
174
+
175
+ const PNG_REF = {
176
+ attachmentId: 'sha256:abcd1234ef567890',
177
+ mediaType: 'image/png',
178
+ width: 64,
179
+ height: 32,
180
+ bytes: 100,
181
+ }
182
+
183
+ const FAKE_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
184
+
185
+ test('imageOccurrences: 识别宿主持久引用与内联 base64 两种形态', () => {
186
+ const blocks = [
187
+ { type: 'text', text: 'see' },
188
+ { type: 'image', attachment: PNG_REF },
189
+ { type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: 'QQ==' } },
190
+ { type: 'file', attachment: { attachmentId: 'sha256:file' } },
191
+ ]
192
+ const found = imageOccurrences(blocks)
193
+ assert.equal(found.length, 2)
194
+ assert.equal(found[0].attachmentId, PNG_REF.attachmentId)
195
+ assert.deepEqual(found[0].ref, PNG_REF)
196
+ assert.equal(found[1].attachmentId, 'inline:2')
197
+ assert.equal(found[1].inline.mediaType, 'image/jpeg')
198
+ })
199
+
200
+ test('imageBlockFromAttachment: 字节编码为 Anthropic base64 块', () => {
201
+ const block = imageBlockFromAttachment(PNG_REF, FAKE_BYTES)
202
+ assert.equal(block.type, 'image')
203
+ assert.equal(block.source.type, 'base64')
204
+ assert.equal(block.source.media_type, 'image/png')
205
+ assert.equal(Buffer.from(block.source.data, 'base64').compare(Buffer.from(FAKE_BYTES)), 0)
206
+ })
207
+
208
+ test('convertContent: 持久引用 + 已解析字节 → base64 image 块', () => {
209
+ const blocks = convertContent(
210
+ [
211
+ { type: 'text', text: 'look' },
212
+ { type: 'image', attachment: PNG_REF },
213
+ ],
214
+ { resolvedImages: new Map([[PNG_REF.attachmentId, { data: FAKE_BYTES, ref: PNG_REF }]]) },
215
+ )
216
+ assert.equal(blocks[0].type, 'text')
217
+ assert.equal(blocks[1].type, 'image')
218
+ assert.equal(blocks[1].source.type, 'base64')
219
+ assert.equal(blocks[1].source.media_type, 'image/png')
220
+ })
221
+
222
+ test('convertContent: 引用解析失败 → 占位文本(不再静默丢弃)', () => {
223
+ const blocks = convertContent([{ type: 'image', attachment: PNG_REF }], { resolvedImages: new Map() })
224
+ assert.equal(blocks.length, 1)
225
+ assert.equal(blocks[0].type, 'text')
226
+ assert.match(blocks[0].text, /image omitted/)
227
+ })
228
+
229
+ test('resolveImages: 经附件服务 readImageRequest 解析引用字节', async () => {
230
+ const calls = []
231
+ const attachments = {
232
+ async readImageRequest(ref, target, signal) {
233
+ calls.push({ ref, target, signal })
234
+ return { attachment: ref, data: FAKE_BYTES, mediaType: 'image/png', width: 64, height: 32, bytes: 8 }
235
+ },
236
+ }
237
+ const resolved = await resolveImages(
238
+ [
239
+ {
240
+ role: 'user',
241
+ content: [{ type: 'text', text: 'hi' }, { type: 'image', attachment: PNG_REF }],
242
+ },
243
+ ],
244
+ { resolveAttachments: () => attachments },
245
+ )
246
+ assert.equal(calls.length, 1)
247
+ assert.equal(calls[0].ref.attachmentId, PNG_REF.attachmentId)
248
+ assert.equal(calls[0].target.width, 64)
249
+ assert.equal(calls[0].target.height, 32)
250
+ assert.equal(resolved.get(PNG_REF.attachmentId).data, FAKE_BYTES)
251
+ })
252
+
253
+ test('resolveImages: 附件服务缺席 → 空 Map(图片降级占位)', async () => {
254
+ const resolved = await resolveImages([{ role: 'user', content: [{ type: 'image', attachment: PNG_REF }] }], {})
255
+ assert.equal(resolved.size, 0)
256
+ })
257
+
258
+ test('resolveImages: 单张解析失败不影响其余图片', async () => {
259
+ const badRef = { ...PNG_REF, attachmentId: 'sha256:badbadbadbadbad' }
260
+ const attachments = {
261
+ async readImageRequest(ref) {
262
+ if (ref.attachmentId === badRef.attachmentId) throw new Error('boom')
263
+ return { attachment: ref, data: FAKE_BYTES }
264
+ },
265
+ }
266
+ const resolved = await resolveImages(
267
+ [
268
+ {
269
+ role: 'user',
270
+ content: [{ type: 'image', attachment: PNG_REF }, { type: 'image', attachment: badRef }],
271
+ },
272
+ ],
273
+ { resolveAttachments: () => attachments },
274
+ )
275
+ assert.equal(resolved.size, 1)
276
+ assert.ok(resolved.has(PNG_REF.attachmentId))
277
+ assert.ok(!resolved.has(badRef.attachmentId))
278
+ })
279
+
280
+ test('buildUpstreamBody: 宿主引用图片端到端进入上游请求体', () => {
281
+ const body = buildUpstreamBody({
282
+ options: {
283
+ model: 'GLM-5.3-Flash',
284
+ messages: [
285
+ {
286
+ role: 'user',
287
+ content: [
288
+ { type: 'text', text: '这张图里有什么?' },
289
+ { type: 'image', attachment: PNG_REF },
290
+ ],
291
+ },
292
+ ],
293
+ },
294
+ supportsImages: true,
295
+ resolvedImages: new Map([[PNG_REF.attachmentId, { data: FAKE_BYTES, ref: PNG_REF }]]),
296
+ })
297
+ const content = body.messages[0].content
298
+ assert.deepEqual(
299
+ content.map((block) => block.type),
300
+ ['text', 'text', 'image'],
301
+ '图片必须以 image 块进入上游请求(此前被静默丢弃);首位是日期块',
302
+ )
303
+ assert.equal(content[2].source.type, 'base64')
304
+ assert.equal(content[2].source.media_type, 'image/png')
305
+ })
@@ -0,0 +1,256 @@
1
+ /**
2
+ * 与宿主 `BlockAssembler` 的**契约级**测试。
3
+ *
4
+ * 宿主 `dsh-llm/lib/index.js` 的 `BlockAssembler` 逐字如下:
5
+ *
6
+ * ```js
7
+ * case "block-start": partials.set(index, { blockType: chunk.blockType, text: "", toolCallArguments: "" })
8
+ * case "text-delta":
9
+ * case "reasoning-delta": partial.text += chunk.text
10
+ * case "tool-call-delta": toolCallId = chunk.id; toolCallName = chunk.name; toolCallArguments += chunk.argumentsDelta
11
+ * case "block-end": partial.block = chunk.block
12
+ * ```
13
+ *
14
+ * ⚠ 三处形状必须严格对上,否则宿主侧炸:
15
+ * - `block-start` 用 **`blockType`(字符串)**,不是 `block`(对象);
16
+ * - `block-end` **必须带 `block`**(assemble 直接返回它);
17
+ * - `tool-call-delta` 的字段名是 `id` / `name` / **`argumentsDelta`**。
18
+ *
19
+ * 另有一处「不炸但静默出错」的形状:`finish` 块的 kind 必须包在 **`reason`
20
+ * 对象**里(`{ type: 'finish', reason: { kind, failure? } }`)—— 宿主
21
+ * `BlockAssembler` 读 `chunk.reason`;kind 放顶层时错误会被吞成正常结束。
22
+ */
23
+
24
+ import test from 'node:test'
25
+ import assert from 'node:assert/strict'
26
+
27
+ import { AnthropicStreamTranslator } from '../lib/stream-translator.js'
28
+
29
+ /** 宿主 `BlockAssembler` 的忠实复刻(用于验证我们的 chunk 形状)。 */
30
+ class HostBlockAssembler {
31
+ partials = new Map()
32
+ order = []
33
+ _usage
34
+ _finish
35
+
36
+ push(chunk) {
37
+ switch (chunk.type) {
38
+ case 'block-start':
39
+ if (!this.partials.has(chunk.index)) {
40
+ this.order.push(chunk.index)
41
+ this.partials.set(chunk.index, { blockType: chunk.blockType, text: '', toolCallArguments: '' })
42
+ }
43
+ return
44
+ case 'text-delta':
45
+ case 'reasoning-delta': {
46
+ const partial = this.ensure(chunk.index, chunk.type === 'text-delta' ? 'text' : 'reasoning')
47
+ if (partial.block) return
48
+ partial.text += chunk.text
49
+ return
50
+ }
51
+ case 'tool-call-delta': {
52
+ const partial = this.ensure(chunk.index, 'tool-call')
53
+ if (partial.block) return
54
+ partial.toolCallId = chunk.id
55
+ if (chunk.name) partial.toolCallName = chunk.name
56
+ partial.toolCallArguments += chunk.argumentsDelta
57
+ return
58
+ }
59
+ case 'block-end': {
60
+ const partial = this.ensure(chunk.index, chunk.block.type)
61
+ if (partial.block) return
62
+ partial.block = chunk.block
63
+ return
64
+ }
65
+ case 'usage':
66
+ this._usage = chunk.usage
67
+ return
68
+ case 'finish':
69
+ this._finish = chunk.reason
70
+ return
71
+ default:
72
+ throw new Error(`unknown chunk type "${chunk.type}"`)
73
+ }
74
+ }
75
+
76
+ ensure(index, blockType) {
77
+ let partial = this.partials.get(index)
78
+ if (!partial) {
79
+ partial = { blockType, text: '', toolCallArguments: '' }
80
+ this.partials.set(index, partial)
81
+ this.order.push(index)
82
+ }
83
+ return partial
84
+ }
85
+
86
+ assemble(partial) {
87
+ if (partial.block) return partial.block
88
+ switch (partial.blockType) {
89
+ case 'text':
90
+ return { type: 'text', text: partial.text }
91
+ case 'reasoning':
92
+ return { type: 'reasoning', text: partial.text }
93
+ case 'tool-call':
94
+ return {
95
+ type: 'tool-call',
96
+ id: partial.toolCallId ?? 'call',
97
+ name: partial.toolCallName ?? '',
98
+ arguments: partial.toolCallArguments,
99
+ }
100
+ default:
101
+ throw new Error(`cannot assemble incomplete block of type "${partial.blockType}"`)
102
+ }
103
+ }
104
+
105
+ assembled() {
106
+ return this.order.map((index) => this.assemble(this.partials.get(index)))
107
+ }
108
+ }
109
+
110
+ /** 思考型模型的一次完整流(reasoning + text + tool_use)。 */
111
+ const thinkingModelStream = () => [
112
+ { data: { type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 10 } } } },
113
+ { data: { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '' } } },
114
+ { data: { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: '先想一下' } } },
115
+ { data: { type: 'content_block_stop', index: 0 } },
116
+ { data: { type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } } },
117
+ { data: { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: '答案' } } },
118
+ { data: { type: 'content_block_stop', index: 1 } },
119
+ { data: { type: 'content_block_start', index: 2, content_block: { type: 'tool_use', id: 'toolu_1', name: 'pwsh', input: {} } } },
120
+ { data: { type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: '{"cmd":' } } },
121
+ { data: { type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: '"ls"}' } } },
122
+ { data: { type: 'content_block_stop', index: 2 } },
123
+ { data: { type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 5 } } },
124
+ ]
125
+
126
+ /** 把一条流跑过 translator + 宿主 assembler,返回两边的产物。 */
127
+ const runThrough = (events) => {
128
+ const translator = new AnthropicStreamTranslator()
129
+ const assembler = new HostBlockAssembler()
130
+ const chunks = []
131
+ for (const event of events) {
132
+ for (const chunk of translator.push(event)) {
133
+ chunks.push(chunk)
134
+ assembler.push(chunk)
135
+ }
136
+ }
137
+ for (const chunk of translator.finish()) {
138
+ chunks.push(chunk)
139
+ assembler.push(chunk)
140
+ }
141
+ return { chunks, blocks: assembler.assembled() }
142
+ }
143
+
144
+ test('宿主 assembler 能完整组装思考型模型的三种块(reasoning/text/tool-call)', () => {
145
+ const { chunks, blocks } = runThrough(thinkingModelStream())
146
+
147
+ assert.deepEqual(chunks.map((chunk) => chunk.type), [
148
+ 'block-start',
149
+ 'reasoning-delta',
150
+ 'block-end',
151
+ 'block-start',
152
+ 'text-delta',
153
+ 'block-end',
154
+ 'block-start',
155
+ 'tool-call-delta',
156
+ 'tool-call-delta',
157
+ 'block-end',
158
+ 'usage',
159
+ 'finish',
160
+ ])
161
+
162
+ assert.deepEqual(blocks, [
163
+ { type: 'reasoning', text: '先想一下' },
164
+ { type: 'text', text: '答案' },
165
+ { type: 'tool-call', id: 'toolu_1', name: 'pwsh', arguments: '{"cmd":"ls"}' },
166
+ ])
167
+ })
168
+
169
+ test('finish.reason 必须是 FinishReasonMap 形态的对象(宿主读 chunk.reason)', () => {
170
+ /**
171
+ * 宿主 `BlockAssembler`:`case "finish": this._finish = chunk.reason`。
172
+ * agent-loop 再按 `finish.kind === 'error' | 'aborted'` 判错。
173
+ * kind 放顶层(没有 reason 包裹)时,宿主读到 undefined → 默认 `{ kind: 'stop' }`,
174
+ * 流内错误被静默吞成正常结束。
175
+ */
176
+ const { chunks } = runThrough(thinkingModelStream())
177
+ const finish = chunks.find((c) => c.type === 'finish')
178
+ assert.equal(finish.kind, undefined, 'kind 必须在 reason 里,不能放顶层')
179
+ assert.deepEqual(finish.reason, { kind: 'tool-calls' })
180
+
181
+ /** 流内错误同样要包在 reason 里,且带稳定 failure 码。 */
182
+ const translator = new AnthropicStreamTranslator()
183
+ translator.push({ data: { type: 'error', error: { type: 'api_error', message: '{"code":3012}' } } })
184
+ const errFinish = translator.finish().find((c) => c.type === 'finish')
185
+ assert.equal(errFinish.reason.kind, 'error')
186
+ assert.equal(errFinish.reason.failure.code, 'RATE_LIMIT')
187
+ })
188
+
189
+ test('block-start 必须带 blockType 字符串(不是 block 对象)', () => {
190
+ const { chunks } = runThrough(thinkingModelStream())
191
+ for (const chunk of chunks.filter((c) => c.type === 'block-start')) {
192
+ assert.equal(typeof chunk.blockType, 'string', 'blockType 必须是字符串')
193
+ assert.ok(chunk.blockType.length > 0)
194
+ assert.equal(chunk.block, undefined, 'block-start 不该带 block(那是 block-end 的字段)')
195
+ }
196
+ })
197
+
198
+ test('block-end 必须带完整 block 对象', () => {
199
+ const { chunks } = runThrough(thinkingModelStream())
200
+ for (const chunk of chunks.filter((c) => c.type === 'block-end')) {
201
+ assert.equal(typeof chunk.block, 'object')
202
+ assert.notEqual(chunk.block, null)
203
+ assert.ok(['text', 'reasoning', 'tool-call'].includes(chunk.block.type))
204
+ }
205
+ })
206
+
207
+ test('tool-call-delta 的字段名是 id / name / argumentsDelta', () => {
208
+ const { chunks } = runThrough(thinkingModelStream())
209
+ const deltas = chunks.filter((c) => c.type === 'tool-call-delta')
210
+ assert.equal(deltas.length, 2)
211
+ assert.equal(deltas[0].id, 'toolu_1')
212
+ assert.equal(deltas[0].name, 'pwsh')
213
+ assert.equal(deltas[0].argumentsDelta, '{"cmd":')
214
+ assert.equal(deltas[1].argumentsDelta, '"ls"}')
215
+ assert.equal(deltas[0].arguments, undefined, '字段名是 argumentsDelta,不是 arguments')
216
+ })
217
+
218
+ test('流未正常结束时,finish() 也补齐 block-end + block', () => {
219
+ const translator = new AnthropicStreamTranslator()
220
+ const chunks = []
221
+ for (const chunk of translator.push({
222
+ data: { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '' } },
223
+ })) {
224
+ chunks.push(chunk)
225
+ }
226
+ for (const chunk of translator.push({
227
+ data: { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: '半截思考' } },
228
+ })) {
229
+ chunks.push(chunk)
230
+ }
231
+ for (const chunk of translator.finish()) chunks.push(chunk)
232
+
233
+ const end = chunks.find((c) => c.type === 'block-end')
234
+ assert.notEqual(end, undefined)
235
+ assert.deepEqual(end.block, { type: 'reasoning', text: '半截思考' })
236
+ })
237
+
238
+ test('工具参数是原始 JSON 字符串(宿主不做解析)', () => {
239
+ const { blocks } = runThrough(thinkingModelStream())
240
+ const tool = blocks.find((block) => block.type === 'tool-call')
241
+ assert.equal(typeof tool.arguments, 'string')
242
+ assert.deepEqual(JSON.parse(tool.arguments), { cmd: 'ls' })
243
+ })
244
+
245
+ test('宿主 assembler 接收只有内联 input 的工具调用且参数不丢失', () => {
246
+ const { blocks } = runThrough([
247
+ { data: { type: 'content_block_start', index: 0, content_block: {
248
+ type: 'tool_use', id: 'toolu_inline', name: 'pwsh',
249
+ input: { description: '列出文件', command: 'Get-ChildItem' },
250
+ } } },
251
+ { data: { type: 'content_block_stop', index: 0 } },
252
+ ])
253
+ assert.deepEqual(JSON.parse(blocks[0].arguments), {
254
+ description: '列出文件', command: 'Get-ChildItem',
255
+ })
256
+ })