@namzu/anthropic 3.0.1 → 3.1.1

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/client.d.ts +15 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +18 -0
  5. package/dist/client.js.map +1 -1
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +8 -0
  9. package/dist/index.js.map +1 -1
  10. package/package.json +12 -2
  11. package/src/client.ts +21 -0
  12. package/src/index.ts +18 -0
  13. package/dist/__tests__/anthropic.test.d.ts +0 -2
  14. package/dist/__tests__/anthropic.test.d.ts.map +0 -1
  15. package/dist/__tests__/anthropic.test.js +0 -425
  16. package/dist/__tests__/anthropic.test.js.map +0 -1
  17. package/dist/__tests__/background-delegation.live.test.d.ts +0 -2
  18. package/dist/__tests__/background-delegation.live.test.d.ts.map +0 -1
  19. package/dist/__tests__/background-delegation.live.test.js +0 -212
  20. package/dist/__tests__/background-delegation.live.test.js.map +0 -1
  21. package/dist/__tests__/block-shape-guard.test.d.ts +0 -2
  22. package/dist/__tests__/block-shape-guard.test.d.ts.map +0 -1
  23. package/dist/__tests__/block-shape-guard.test.js +0 -218
  24. package/dist/__tests__/block-shape-guard.test.js.map +0 -1
  25. package/dist/__tests__/cache-anchors.test.d.ts +0 -2
  26. package/dist/__tests__/cache-anchors.test.d.ts.map +0 -1
  27. package/dist/__tests__/cache-anchors.test.js +0 -220
  28. package/dist/__tests__/cache-anchors.test.js.map +0 -1
  29. package/dist/__tests__/citations.test.d.ts +0 -2
  30. package/dist/__tests__/citations.test.d.ts.map +0 -1
  31. package/dist/__tests__/citations.test.js +0 -189
  32. package/dist/__tests__/citations.test.js.map +0 -1
  33. package/dist/__tests__/content-blocks.test.d.ts +0 -2
  34. package/dist/__tests__/content-blocks.test.d.ts.map +0 -1
  35. package/dist/__tests__/content-blocks.test.js +0 -131
  36. package/dist/__tests__/content-blocks.test.js.map +0 -1
  37. package/dist/__tests__/document-input.test.d.ts +0 -2
  38. package/dist/__tests__/document-input.test.d.ts.map +0 -1
  39. package/dist/__tests__/document-input.test.js +0 -98
  40. package/dist/__tests__/document-input.test.js.map +0 -1
  41. package/dist/__tests__/error-taxonomy.test.d.ts +0 -16
  42. package/dist/__tests__/error-taxonomy.test.d.ts.map +0 -1
  43. package/dist/__tests__/error-taxonomy.test.js +0 -242
  44. package/dist/__tests__/error-taxonomy.test.js.map +0 -1
  45. package/dist/__tests__/reasoning-close.test.d.ts +0 -2
  46. package/dist/__tests__/reasoning-close.test.d.ts.map +0 -1
  47. package/dist/__tests__/reasoning-close.test.js +0 -219
  48. package/dist/__tests__/reasoning-close.test.js.map +0 -1
  49. package/dist/__tests__/thinking-capability.test.d.ts +0 -2
  50. package/dist/__tests__/thinking-capability.test.d.ts.map +0 -1
  51. package/dist/__tests__/thinking-capability.test.js +0 -206
  52. package/dist/__tests__/thinking-capability.test.js.map +0 -1
  53. package/dist/__tests__/thinking-contract.live.test.d.ts +0 -2
  54. package/dist/__tests__/thinking-contract.live.test.d.ts.map +0 -1
  55. package/dist/__tests__/thinking-contract.live.test.js +0 -97
  56. package/dist/__tests__/thinking-contract.live.test.js.map +0 -1
  57. package/dist/__tests__/thinking-request-body.test.d.ts +0 -2
  58. package/dist/__tests__/thinking-request-body.test.d.ts.map +0 -1
  59. package/dist/__tests__/thinking-request-body.test.js +0 -90
  60. package/dist/__tests__/thinking-request-body.test.js.map +0 -1
  61. package/dist/__tests__/wire-contract.live.test.d.ts +0 -2
  62. package/dist/__tests__/wire-contract.live.test.d.ts.map +0 -1
  63. package/dist/__tests__/wire-contract.live.test.js +0 -254
  64. package/dist/__tests__/wire-contract.live.test.js.map +0 -1
  65. package/src/__tests__/anthropic.test.ts +0 -490
  66. package/src/__tests__/background-delegation.live.test.ts +0 -243
  67. package/src/__tests__/block-shape-guard.test.ts +0 -256
  68. package/src/__tests__/cache-anchors.test.ts +0 -262
  69. package/src/__tests__/citations.test.ts +0 -218
  70. package/src/__tests__/content-blocks.test.ts +0 -153
  71. package/src/__tests__/document-input.test.ts +0 -131
  72. package/src/__tests__/error-taxonomy.test.ts +0 -274
  73. package/src/__tests__/reasoning-close.test.ts +0 -262
  74. package/src/__tests__/thinking-capability.test.ts +0 -235
  75. package/src/__tests__/thinking-contract.live.test.ts +0 -125
  76. package/src/__tests__/thinking-request-body.test.ts +0 -111
  77. package/src/__tests__/wire-contract.live.test.ts +0 -312
@@ -1,262 +0,0 @@
1
- import type { ChatCompletionParams } from '@namzu/sdk'
2
- import { describe, expect, it, vi } from 'vitest'
3
-
4
- import { AnthropicProvider } from '../client.js'
5
-
6
- /**
7
- * Where the cache breakpoints land decides what the next iteration pays.
8
- *
9
- * Two anchors, and they do different jobs. The SYSTEM anchor sits on the
10
- * last block the prompt builder tagged `'cache'`, so tools plus the static
11
- * system prefix are cached and the per-run dynamic segment behind it is
12
- * not. The MESSAGE anchor sits on the last block of the last non-empty
13
- * message, so the whole conversation prefix is cached for an iteration
14
- * that only appends.
15
- *
16
- * Both are invisible when wrong: a breakpoint one block too early caches
17
- * less than it could, one too late caches a segment that changes every run
18
- * and is never read back. Neither shows up as a failure — only as a bill.
19
- */
20
-
21
- function bodyCapturer(): {
22
- provider: AnthropicProvider
23
- seen: { body?: Record<string, unknown> }
24
- } {
25
- const seen: { body?: Record<string, unknown> } = {}
26
- const provider = new AnthropicProvider({ apiKey: 'test-key' })
27
- ;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
28
- messages: {
29
- create: vi.fn(async (body: Record<string, unknown>) => {
30
- seen.body = body
31
- return (async function* () {
32
- yield { type: 'message_start', message: { id: 'msg_1' } }
33
- })()
34
- }),
35
- },
36
- }
37
- return { provider, seen }
38
- }
39
-
40
- async function bodyFor(params: Partial<ChatCompletionParams>): Promise<Record<string, unknown>> {
41
- const { provider, seen } = bodyCapturer()
42
- for await (const _chunk of provider.chatStream({
43
- model: 'm',
44
- messages: [{ role: 'user', content: 'hi' }],
45
- // Anchors are placed only when the caller asked for caching.
46
- cacheControl: { type: 'ephemeral' },
47
- ...params,
48
- } as ChatCompletionParams)) {
49
- // drain
50
- }
51
- return seen.body ?? {}
52
- }
53
-
54
- type Block = { type: string; text?: string; cache_control?: { type: string } }
55
-
56
- function systemBlocks(body: Record<string, unknown>): Block[] {
57
- return (body.system ?? []) as Block[]
58
- }
59
-
60
- function messageBlocks(body: Record<string, unknown>): Block[] {
61
- const messages = body.messages as Array<{ content: string | Block[] }>
62
- const last = messages.at(-1)?.content
63
- return Array.isArray(last) ? last : []
64
- }
65
-
66
- const TAGGED_SYSTEM = [
67
- { role: 'system' as const, content: 'static rules', cacheHint: 'cache' as const },
68
- { role: 'system' as const, content: 'run-specific context', cacheHint: 'ephemeral' as const },
69
- { role: 'user' as const, content: 'go' },
70
- ]
71
-
72
- describe('the system anchor sits at the end of the cacheable prefix', () => {
73
- it('marks the last cache-tagged block, not the last block', async () => {
74
- const body = await bodyFor({
75
- messages: TAGGED_SYSTEM as unknown as ChatCompletionParams['messages'],
76
- })
77
- const blocks = systemBlocks(body)
78
-
79
- expect(blocks[0]).toMatchObject({ text: 'static rules' })
80
- expect(blocks[0]?.cache_control).toEqual({ type: 'ephemeral' })
81
- // The dynamic segment changes every run, so caching it writes an
82
- // entry nothing ever reads back.
83
- expect(blocks[1]?.cache_control).toBeUndefined()
84
- })
85
-
86
- it('marks the later of two cache-tagged blocks', async () => {
87
- const body = await bodyFor({
88
- messages: [
89
- { role: 'system', content: 'first', cacheHint: 'cache' },
90
- { role: 'system', content: 'second', cacheHint: 'cache' },
91
- { role: 'user', content: 'go' },
92
- ] as unknown as ChatCompletionParams['messages'],
93
- })
94
- const blocks = systemBlocks(body)
95
-
96
- expect(blocks[0]?.cache_control).toBeUndefined()
97
- expect(blocks[1]?.cache_control).toEqual({ type: 'ephemeral' })
98
- })
99
-
100
- it('anchors nothing when no block was tagged for caching', async () => {
101
- const body = await bodyFor({
102
- messages: [
103
- { role: 'system', content: 'untagged' },
104
- { role: 'user', content: 'go' },
105
- ] as unknown as ChatCompletionParams['messages'],
106
- })
107
-
108
- expect(systemBlocks(body).some((b) => b.cache_control)).toBe(false)
109
- })
110
-
111
- it('keeps one block per system message, so the boundaries survive', async () => {
112
- const body = await bodyFor({
113
- messages: TAGGED_SYSTEM as unknown as ChatCompletionParams['messages'],
114
- })
115
-
116
- expect(systemBlocks(body).map((b) => b.text)).toEqual(['static rules', 'run-specific context'])
117
- })
118
-
119
- it('sends no system field at all when there are no system messages', async () => {
120
- const body = await bodyFor({
121
- messages: [{ role: 'user', content: 'go' }] as ChatCompletionParams['messages'],
122
- })
123
-
124
- expect(body.system).toBeUndefined()
125
- })
126
- })
127
-
128
- describe('the message anchor sits at the end of the conversation prefix', () => {
129
- it('promotes a trailing string message to a block so it can carry one', async () => {
130
- const body = await bodyFor({
131
- messages: [
132
- { role: 'user', content: 'first' },
133
- { role: 'assistant', content: 'second' },
134
- ] as ChatCompletionParams['messages'],
135
- })
136
-
137
- expect(messageBlocks(body).at(-1)).toMatchObject({
138
- type: 'text',
139
- text: 'second',
140
- cache_control: { type: 'ephemeral' },
141
- })
142
- })
143
-
144
- it('marks the last block of an already-blocked message', async () => {
145
- const body = await bodyFor({
146
- messages: [
147
- {
148
- role: 'user',
149
- content: 'look',
150
- attachments: [{ type: 'image', data: 'AAAA', mediaType: 'image/png' }],
151
- },
152
- ] as unknown as ChatCompletionParams['messages'],
153
- })
154
- const blocks = messageBlocks(body)
155
-
156
- expect(blocks.at(-1)?.type).toBe('image')
157
- expect(blocks.at(-1)?.cache_control).toEqual({ type: 'ephemeral' })
158
- expect(blocks[0]?.cache_control).toBeUndefined()
159
- })
160
-
161
- it('skips an empty trailing message and anchors the one before it', async () => {
162
- const body = await bodyFor({
163
- messages: [
164
- { role: 'user', content: 'real content' },
165
- { role: 'assistant', content: '' },
166
- ] as ChatCompletionParams['messages'],
167
- })
168
- const messages = body.messages as Array<{ content: string | Block[] }>
169
- const anchored = messages.filter(
170
- (m) => Array.isArray(m.content) && m.content.some((b) => b.cache_control),
171
- )
172
-
173
- // An empty message has no block to hold the anchor, so anchoring it
174
- // would drop the breakpoint entirely.
175
- expect(anchored).toHaveLength(1)
176
- expect((anchored[0]?.content as Block[])[0]?.text).toBe('real content')
177
- })
178
-
179
- it('places exactly one message anchor', async () => {
180
- const body = await bodyFor({
181
- messages: [
182
- { role: 'user', content: 'a' },
183
- { role: 'assistant', content: 'b' },
184
- { role: 'user', content: 'c' },
185
- ] as ChatCompletionParams['messages'],
186
- })
187
- const messages = body.messages as Array<{ content: string | Block[] }>
188
- const anchors = messages
189
- .flatMap((m) => (Array.isArray(m.content) ? m.content : []))
190
- .filter((b) => b.cache_control)
191
-
192
- expect(anchors).toHaveLength(1)
193
- })
194
- })
195
-
196
- describe('cache usage is read back off the wire', () => {
197
- it('reports reads and writes separately, not folded into prompt tokens', async () => {
198
- const { provider } = bodyCapturer()
199
- ;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
200
- messages: {
201
- create: vi.fn(async () =>
202
- (async function* () {
203
- yield {
204
- type: 'message_start',
205
- message: {
206
- id: 'msg_1',
207
- usage: {
208
- input_tokens: 10,
209
- output_tokens: 2,
210
- cache_read_input_tokens: 900,
211
- cache_creation_input_tokens: 40,
212
- },
213
- },
214
- }
215
- })(),
216
- ),
217
- },
218
- }
219
-
220
- const chunks = []
221
- for await (const chunk of provider.chatStream({
222
- model: 'm',
223
- messages: [{ role: 'user', content: 'hi' }],
224
- } as ChatCompletionParams)) {
225
- chunks.push(chunk)
226
- }
227
-
228
- // The two are priced differently, so folding either into
229
- // promptTokens would misreport what the run actually cost.
230
- expect(chunks[0]?.usage).toMatchObject({
231
- promptTokens: 10,
232
- cachedTokens: 900,
233
- cacheWriteTokens: 40,
234
- })
235
- })
236
-
237
- it('reads absent cache counters as zero rather than undefined', async () => {
238
- const { provider } = bodyCapturer()
239
- ;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
240
- messages: {
241
- create: vi.fn(async () =>
242
- (async function* () {
243
- yield {
244
- type: 'message_start',
245
- message: { id: 'm', usage: { input_tokens: 5, output_tokens: 1 } },
246
- }
247
- })(),
248
- ),
249
- },
250
- }
251
-
252
- const chunks = []
253
- for await (const chunk of provider.chatStream({
254
- model: 'm',
255
- messages: [{ role: 'user', content: 'hi' }],
256
- } as ChatCompletionParams)) {
257
- chunks.push(chunk)
258
- }
259
-
260
- expect(chunks[0]?.usage).toMatchObject({ cachedTokens: 0, cacheWriteTokens: 0 })
261
- })
262
- })
@@ -1,218 +0,0 @@
1
- import type { ChatCompletionParams, StreamChunk } from '@namzu/sdk'
2
- import { describe, expect, it, vi } from 'vitest'
3
-
4
- import { AnthropicProvider } from '../client.js'
5
-
6
- /**
7
- * The whole citation path existed except the two ends that touch a real
8
- * provider.
9
- *
10
- * The SDK had the `Citation` type, the stream chunk carried a slot for it,
11
- * the run's stream aggregator collected them onto the assistant message,
12
- * and the iteration attached them to the turn. Only the mock provider ever
13
- * emitted one. This driver neither asked for citations nor parsed them, so
14
- * in a real run the slot was always empty: an answer about a contract
15
- * arrived as prose, and checking it meant reading the contract again.
16
- *
17
- * The location stays a union on purpose. A provider that segments by
18
- * character offset has no page number, and inventing one would make an
19
- * uncheckable citation look checkable.
20
- */
21
-
22
- const PDF = 'JVBERi0xLjQKJSVFT0Y='
23
-
24
- function providerOver(
25
- events: unknown[],
26
- seen: { body?: Record<string, unknown> } = {},
27
- ): AnthropicProvider {
28
- const provider = new AnthropicProvider({ apiKey: 'test-key' })
29
- ;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
30
- messages: {
31
- create: vi.fn(async (body: Record<string, unknown>) => {
32
- seen.body = body
33
- return (async function* () {
34
- for (const event of events) yield event
35
- })()
36
- }),
37
- },
38
- }
39
- return provider
40
- }
41
-
42
- async function chunksOf(events: unknown[]): Promise<StreamChunk[]> {
43
- const provider = providerOver(events)
44
- const out: StreamChunk[] = []
45
- for await (const chunk of provider.chatStream({
46
- model: 'm',
47
- messages: [{ role: 'user', content: 'q' }],
48
- } as ChatCompletionParams)) {
49
- out.push(chunk)
50
- }
51
- return out
52
- }
53
-
54
- function citationEvent(citation: Record<string, unknown>): unknown {
55
- return {
56
- type: 'content_block_delta',
57
- index: 0,
58
- delta: { type: 'citations_delta', citation },
59
- }
60
- }
61
-
62
- const PAGE_CITATION = {
63
- type: 'page_location',
64
- cited_text: 'the term is five years',
65
- document_index: 0,
66
- document_title: 'lease.pdf',
67
- start_page_number: 3,
68
- end_page_number: 3,
69
- }
70
-
71
- describe('a cited passage reaches the caller', () => {
72
- it('emits the citation on the chunk delta', async () => {
73
- const chunks = await chunksOf([
74
- { type: 'message_start', message: { id: 'msg_1' } },
75
- citationEvent(PAGE_CITATION),
76
- { type: 'message_delta', delta: { stop_reason: 'end_turn' } },
77
- ])
78
-
79
- const cited = chunks.find((c) => c.delta.citation)?.delta.citation
80
- expect(cited?.citedText).toBe('the term is five years')
81
- expect(cited?.documentIndex).toBe(0)
82
- expect(cited?.documentTitle).toBe('lease.pdf')
83
- expect(cited?.location).toEqual({ kind: 'page', start: 3, end: 3 })
84
- })
85
-
86
- it('does not emit it as text — a citation is not prose', async () => {
87
- const chunks = await chunksOf([
88
- { type: 'message_start', message: { id: 'msg_1' } },
89
- citationEvent(PAGE_CITATION),
90
- ])
91
-
92
- expect(chunks.some((c) => c.delta.content)).toBe(false)
93
- })
94
-
95
- it('reads a character-offset citation as char, not as a page', async () => {
96
- const chunks = await chunksOf([
97
- { type: 'message_start', message: { id: 'msg_1' } },
98
- citationEvent({
99
- cited_text: 'clause 4',
100
- document_index: 1,
101
- start_char_index: 120,
102
- end_char_index: 148,
103
- }),
104
- ])
105
-
106
- expect(chunks.find((c) => c.delta.citation)?.delta.citation?.location).toEqual({
107
- kind: 'char',
108
- start: 120,
109
- end: 148,
110
- })
111
- })
112
-
113
- it('reads a block citation as block', async () => {
114
- const chunks = await chunksOf([
115
- { type: 'message_start', message: { id: 'msg_1' } },
116
- citationEvent({
117
- cited_text: 'row 7',
118
- document_index: 0,
119
- start_block_index: 7,
120
- end_block_index: 8,
121
- }),
122
- ])
123
-
124
- expect(chunks.find((c) => c.delta.citation)?.delta.citation?.location).toEqual({
125
- kind: 'block',
126
- start: 7,
127
- end: 8,
128
- })
129
- })
130
-
131
- it('carries several citations through in order', async () => {
132
- const chunks = await chunksOf([
133
- { type: 'message_start', message: { id: 'msg_1' } },
134
- citationEvent({ ...PAGE_CITATION, cited_text: 'first' }),
135
- { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: ' and ' } },
136
- citationEvent({ ...PAGE_CITATION, cited_text: 'second' }),
137
- ])
138
-
139
- expect(chunks.filter((c) => c.delta.citation).map((c) => c.delta.citation?.citedText)).toEqual([
140
- 'first',
141
- 'second',
142
- ])
143
- })
144
- })
145
-
146
- describe('a citation that cannot be checked is dropped, not guessed', () => {
147
- it('drops one with no location, rather than inventing a page', async () => {
148
- const chunks = await chunksOf([
149
- { type: 'message_start', message: { id: 'msg_1' } },
150
- citationEvent({ cited_text: 'somewhere', document_index: 0 }),
151
- ])
152
-
153
- // A citation that looks checkable and is not is worse than none:
154
- // the reader follows it to a page number nobody measured.
155
- expect(chunks.some((c) => c.delta.citation)).toBe(false)
156
- })
157
-
158
- it('drops one with no text', async () => {
159
- const chunks = await chunksOf([
160
- { type: 'message_start', message: { id: 'msg_1' } },
161
- citationEvent({ document_index: 0, start_page_number: 1, end_page_number: 1 }),
162
- ])
163
-
164
- expect(chunks.some((c) => c.delta.citation)).toBe(false)
165
- })
166
-
167
- it('leaves the rest of the stream intact around a dropped one', async () => {
168
- const chunks = await chunksOf([
169
- { type: 'message_start', message: { id: 'msg_1' } },
170
- citationEvent({ cited_text: 'no location' }),
171
- { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'answer' } },
172
- { type: 'message_delta', delta: { stop_reason: 'end_turn' } },
173
- ])
174
-
175
- expect(chunks.map((c) => c.delta.content).filter(Boolean)).toEqual(['answer'])
176
- expect(chunks.at(-1)?.finishReason).toBe('stop')
177
- })
178
- })
179
-
180
- describe('citations are requested only when the caller asked to check the answer', () => {
181
- async function documentBlockFor(citations?: boolean): Promise<Record<string, unknown>> {
182
- const seen: { body?: Record<string, unknown> } = {}
183
- const provider = providerOver([{ type: 'message_start', message: { id: 'm' } }], seen)
184
- for await (const _chunk of provider.chatStream({
185
- model: 'm',
186
- messages: [
187
- {
188
- role: 'user',
189
- content: 'summarize',
190
- attachments: [
191
- {
192
- type: 'document',
193
- data: PDF,
194
- mediaType: 'application/pdf',
195
- ...(citations !== undefined ? { citations } : {}),
196
- },
197
- ],
198
- },
199
- ],
200
- } as unknown as ChatCompletionParams)) {
201
- // drain
202
- }
203
- const messages = seen.body?.messages as Array<{ content: Record<string, unknown>[] }>
204
- return messages[0]?.content.find((b) => b.type === 'document') ?? {}
205
- }
206
-
207
- it('enables them when the attachment asked for them', async () => {
208
- expect(await documentBlockFor(true)).toMatchObject({ citations: { enabled: true } })
209
- })
210
-
211
- it('leaves them off by default — they are not free', async () => {
212
- expect(await documentBlockFor()).not.toHaveProperty('citations')
213
- })
214
-
215
- it('leaves them off when explicitly declined', async () => {
216
- expect(await documentBlockFor(false)).not.toHaveProperty('citations')
217
- })
218
- })
@@ -1,153 +0,0 @@
1
- import type { ChatCompletionParams } from '@namzu/sdk'
2
- import { describe, expect, it, vi } from 'vitest'
3
-
4
- import { AnthropicProvider } from '../client.js'
5
-
6
- /**
7
- * A tool result carrying an image used to be `JSON.stringify`d.
8
- *
9
- * So a screenshot reached the model as a wall of quoted base64 — the exact
10
- * thing the SDK's degrade helper exists to prevent, and pure waste besides:
11
- * the model paid for every character and could read none of them. This wire
12
- * carries image blocks inside a tool result natively; the mapper simply
13
- * never used the shape.
14
- *
15
- * The degrade path still matters for what this wire genuinely cannot take.
16
- * A document inside a tool result becomes the named placeholder rather than
17
- * an invented image block, because the wrong block fails the whole request
18
- * instead of just that part of it.
19
- */
20
-
21
- const PNG = 'iVBORw0KGgo='
22
-
23
- function bodyCapturer() {
24
- const seen: { body?: Record<string, unknown> } = {}
25
- const provider = new AnthropicProvider({ apiKey: 'test-key' })
26
- ;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
27
- messages: {
28
- create: vi.fn(async (body: Record<string, unknown>) => {
29
- seen.body = body
30
- return (async function* () {
31
- yield { type: 'message_start', message: { id: 'msg_1' } }
32
- })()
33
- }),
34
- },
35
- }
36
- return { provider, seen }
37
- }
38
-
39
- async function toolResultFor(content: unknown): Promise<Record<string, unknown>> {
40
- const { provider, seen } = bodyCapturer()
41
- for await (const _chunk of provider.chatStream({
42
- model: 'm',
43
- messages: [
44
- { role: 'user', content: 'take a shot' },
45
- {
46
- role: 'assistant',
47
- content: null,
48
- toolCalls: [
49
- { id: 'call_1', type: 'function', function: { name: 'screenshot', arguments: '{}' } },
50
- ],
51
- },
52
- { role: 'tool', toolCallId: 'call_1', content },
53
- ],
54
- } as unknown as ChatCompletionParams)) {
55
- // drain
56
- }
57
- const messages = seen.body?.messages as Array<{ content: Record<string, unknown>[] }>
58
- const block = messages
59
- .flatMap((m) => (Array.isArray(m.content) ? m.content : []))
60
- .find((b) => b.type === 'tool_result')
61
- return block ?? {}
62
- }
63
-
64
- describe('an image in a tool result is sent as an image', () => {
65
- it('carries the payload as a native image block', async () => {
66
- const result = await toolResultFor([
67
- { type: 'text', text: 'captured' },
68
- { type: 'image', mediaType: 'image/png', data: PNG },
69
- ])
70
- const blocks = result.content as Record<string, unknown>[]
71
-
72
- expect(blocks.find((b) => b.type === 'image')?.source).toEqual({
73
- type: 'base64',
74
- media_type: 'image/png',
75
- data: PNG,
76
- })
77
- })
78
-
79
- it('does not stringify the payload into text', async () => {
80
- const result = await toolResultFor([{ type: 'image', mediaType: 'image/png', data: PNG }])
81
-
82
- // The bug in one assertion: the content used to be a JSON string
83
- // with the base64 quoted inside it.
84
- expect(typeof result.content).not.toBe('string')
85
- expect(JSON.stringify(result.content)).not.toContain('\\"data\\"')
86
- })
87
-
88
- it('keeps the text alongside the image, in order', async () => {
89
- const result = await toolResultFor([
90
- { type: 'text', text: 'captured' },
91
- { type: 'image', mediaType: 'image/png', data: PNG },
92
- ])
93
- const blocks = result.content as Record<string, unknown>[]
94
-
95
- expect(blocks.map((b) => b.type)).toEqual(['text', 'image'])
96
- expect(blocks[0]?.text).toBe('captured')
97
- })
98
-
99
- it('carries several images', async () => {
100
- const result = await toolResultFor([
101
- { type: 'image', mediaType: 'image/png', data: PNG },
102
- { type: 'image', mediaType: 'image/jpeg', data: 'other' },
103
- ])
104
- const blocks = result.content as Record<string, unknown>[]
105
-
106
- expect(blocks.filter((b) => b.type === 'image')).toHaveLength(2)
107
- })
108
- })
109
-
110
- describe('what this wire cannot carry degrades to a named placeholder', () => {
111
- it('describes a document rather than inventing an image block', async () => {
112
- const result = await toolResultFor([
113
- { type: 'document', mediaType: 'application/pdf', data: 'JVBER', name: 'lease.pdf' },
114
- ])
115
- const blocks = result.content as Record<string, unknown>[]
116
-
117
- expect(blocks[0]?.type).toBe('text')
118
- expect(blocks[0]?.text).toContain('lease.pdf')
119
- expect(blocks[0]?.text).toContain('application/pdf')
120
- // A block the wire rejects fails the request, not just the block.
121
- expect(blocks.some((b) => b.type === 'image')).toBe(false)
122
- })
123
-
124
- it('says how big it was, so the model knows what it is missing', async () => {
125
- const result = await toolResultFor([
126
- { type: 'document', mediaType: 'application/pdf', data: 'A'.repeat(4096) },
127
- ])
128
- const blocks = result.content as Record<string, unknown>[]
129
-
130
- expect(blocks[0]?.text).toMatch(/\d+(\.\d+)? (B|KB|MB)/)
131
- })
132
- })
133
-
134
- describe('the plain cases are unchanged', () => {
135
- it('sends a string result as a string', async () => {
136
- expect(await toolResultFor('just text')).toMatchObject({ content: 'just text' })
137
- })
138
-
139
- it('sends text-only blocks as a text block', async () => {
140
- const result = await toolResultFor([{ type: 'text', text: 'only words' }])
141
- const blocks = result.content as Record<string, unknown>[]
142
-
143
- expect(blocks).toEqual([{ type: 'text', text: 'only words' }])
144
- })
145
-
146
- it('sends an empty string rather than an empty array, which is rejected', async () => {
147
- expect(await toolResultFor([])).toMatchObject({ content: '' })
148
- })
149
-
150
- it('keeps the tool call id it answers', async () => {
151
- expect(await toolResultFor('x')).toMatchObject({ tool_use_id: 'call_1' })
152
- })
153
- })