@namzu/anthropic 1.2.0 → 2.0.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +336 -0
  2. package/dist/__tests__/anthropic.test.js +1 -0
  3. package/dist/__tests__/anthropic.test.js.map +1 -1
  4. package/dist/__tests__/block-shape-guard.test.d.ts +2 -0
  5. package/dist/__tests__/block-shape-guard.test.d.ts.map +1 -0
  6. package/dist/__tests__/block-shape-guard.test.js +218 -0
  7. package/dist/__tests__/block-shape-guard.test.js.map +1 -0
  8. package/dist/__tests__/cache-anchors.test.d.ts +2 -0
  9. package/dist/__tests__/cache-anchors.test.d.ts.map +1 -0
  10. package/dist/__tests__/cache-anchors.test.js +220 -0
  11. package/dist/__tests__/cache-anchors.test.js.map +1 -0
  12. package/dist/__tests__/citations.test.d.ts +2 -0
  13. package/dist/__tests__/citations.test.d.ts.map +1 -0
  14. package/dist/__tests__/citations.test.js +189 -0
  15. package/dist/__tests__/citations.test.js.map +1 -0
  16. package/dist/__tests__/content-blocks.test.d.ts +2 -0
  17. package/dist/__tests__/content-blocks.test.d.ts.map +1 -0
  18. package/dist/__tests__/content-blocks.test.js +131 -0
  19. package/dist/__tests__/content-blocks.test.js.map +1 -0
  20. package/dist/__tests__/document-input.test.d.ts +2 -0
  21. package/dist/__tests__/document-input.test.d.ts.map +1 -0
  22. package/dist/__tests__/document-input.test.js +98 -0
  23. package/dist/__tests__/document-input.test.js.map +1 -0
  24. package/dist/__tests__/reasoning-close.test.d.ts +2 -0
  25. package/dist/__tests__/reasoning-close.test.d.ts.map +1 -0
  26. package/dist/__tests__/reasoning-close.test.js +219 -0
  27. package/dist/__tests__/reasoning-close.test.js.map +1 -0
  28. package/dist/__tests__/thinking-capability.test.d.ts +2 -0
  29. package/dist/__tests__/thinking-capability.test.d.ts.map +1 -0
  30. package/dist/__tests__/thinking-capability.test.js +127 -0
  31. package/dist/__tests__/thinking-capability.test.js.map +1 -0
  32. package/dist/__tests__/thinking-request-body.test.d.ts +2 -0
  33. package/dist/__tests__/thinking-request-body.test.d.ts.map +1 -0
  34. package/dist/__tests__/thinking-request-body.test.js +90 -0
  35. package/dist/__tests__/thinking-request-body.test.js.map +1 -0
  36. package/dist/client.d.ts.map +1 -1
  37. package/dist/client.js +186 -3
  38. package/dist/client.js.map +1 -1
  39. package/dist/thinking-capability.d.ts +78 -0
  40. package/dist/thinking-capability.d.ts.map +1 -0
  41. package/dist/thinking-capability.js +114 -0
  42. package/dist/thinking-capability.js.map +1 -0
  43. package/package.json +4 -4
  44. package/src/__tests__/anthropic.test.ts +1 -0
  45. package/src/__tests__/block-shape-guard.test.ts +256 -0
  46. package/src/__tests__/cache-anchors.test.ts +262 -0
  47. package/src/__tests__/citations.test.ts +218 -0
  48. package/src/__tests__/content-blocks.test.ts +153 -0
  49. package/src/__tests__/document-input.test.ts +131 -0
  50. package/src/__tests__/reasoning-close.test.ts +262 -0
  51. package/src/__tests__/thinking-capability.test.ts +150 -0
  52. package/src/__tests__/thinking-request-body.test.ts +111 -0
  53. package/src/client.ts +265 -7
  54. package/src/thinking-capability.ts +177 -0
@@ -0,0 +1,256 @@
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
+ * The wire rejects a whole request over one malformed block, so the
8
+ * failures that matter here are structural: a block in the wrong place, a
9
+ * message whose content array is empty, an orphan tool result, or a
10
+ * `tool_choice` sent without tools. None of them is visible in isolation —
11
+ * each shows up as a 400 for the entire conversation.
12
+ *
13
+ * These pin the shapes the mapper must not produce, alongside the ones it
14
+ * must. What must NOT hold is the point: a guard asserting only the happy
15
+ * shape passes while the mapper emits a request no server accepts.
16
+ */
17
+
18
+ function bodyCapturer() {
19
+ const seen: { body?: Record<string, unknown> } = {}
20
+ const provider = new AnthropicProvider({ apiKey: 'test-key' })
21
+ ;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
22
+ messages: {
23
+ create: vi.fn(async (body: Record<string, unknown>) => {
24
+ seen.body = body
25
+ return (async function* () {
26
+ yield { type: 'message_start', message: { id: 'msg_1' } }
27
+ })()
28
+ }),
29
+ },
30
+ }
31
+ return { provider, seen }
32
+ }
33
+
34
+ async function bodyFor(params: Partial<ChatCompletionParams>): Promise<Record<string, unknown>> {
35
+ const { provider, seen } = bodyCapturer()
36
+ for await (const _chunk of provider.chatStream({
37
+ model: 'm',
38
+ messages: [{ role: 'user', content: 'hi' }],
39
+ ...params,
40
+ } as ChatCompletionParams)) {
41
+ // drain
42
+ }
43
+ return seen.body ?? {}
44
+ }
45
+
46
+ type WireMessage = { role: string; content: string | Record<string, unknown>[] }
47
+
48
+ function messagesOf(body: Record<string, unknown>): WireMessage[] {
49
+ return (body.messages ?? []) as WireMessage[]
50
+ }
51
+
52
+ function allBlocks(body: Record<string, unknown>): Record<string, unknown>[] {
53
+ return messagesOf(body).flatMap((m) => (Array.isArray(m.content) ? m.content : []))
54
+ }
55
+
56
+ const TOOLS = [
57
+ {
58
+ type: 'function' as const,
59
+ function: { name: 'read', description: 'read', parameters: { type: 'object' } },
60
+ },
61
+ ]
62
+
63
+ describe('no message goes out with an empty content array', () => {
64
+ it('holds for a plain conversation', async () => {
65
+ const body = await bodyFor({
66
+ messages: [
67
+ { role: 'user', content: 'a' },
68
+ { role: 'assistant', content: 'b' },
69
+ ] as ChatCompletionParams['messages'],
70
+ })
71
+
72
+ for (const message of messagesOf(body)) {
73
+ if (Array.isArray(message.content)) expect(message.content.length).toBeGreaterThan(0)
74
+ }
75
+ })
76
+
77
+ it('holds for an assistant turn that called a tool with no prose', async () => {
78
+ const body = await bodyFor({
79
+ messages: [
80
+ { role: 'user', content: 'read it' },
81
+ {
82
+ role: 'assistant',
83
+ content: null,
84
+ toolCalls: [
85
+ { id: 'call_1', type: 'function', function: { name: 'read', arguments: '{}' } },
86
+ ],
87
+ },
88
+ { role: 'tool', toolCallId: 'call_1', content: 'file body' },
89
+ ] as unknown as ChatCompletionParams['messages'],
90
+ })
91
+
92
+ for (const message of messagesOf(body)) {
93
+ if (Array.isArray(message.content)) expect(message.content.length).toBeGreaterThan(0)
94
+ }
95
+ })
96
+ })
97
+
98
+ describe('a system message never appears among the turns', () => {
99
+ it('is lifted out entirely, not left as a user message', async () => {
100
+ const body = await bodyFor({
101
+ messages: [
102
+ { role: 'system', content: 'be terse' },
103
+ { role: 'user', content: 'hi' },
104
+ ] as ChatCompletionParams['messages'],
105
+ })
106
+
107
+ expect(messagesOf(body).map((m) => m.role)).toEqual(['user'])
108
+ expect(body.system).toBeDefined()
109
+ })
110
+ })
111
+
112
+ describe('tool results are grouped into one user turn, in order', () => {
113
+ it('collapses two results answering one assistant turn', async () => {
114
+ const body = await bodyFor({
115
+ messages: [
116
+ { role: 'user', content: 'read both' },
117
+ {
118
+ role: 'assistant',
119
+ content: null,
120
+ toolCalls: [
121
+ { id: 'call_1', type: 'function', function: { name: 'read', arguments: '{}' } },
122
+ { id: 'call_2', type: 'function', function: { name: 'read', arguments: '{}' } },
123
+ ],
124
+ },
125
+ { role: 'tool', toolCallId: 'call_1', content: 'one' },
126
+ { role: 'tool', toolCallId: 'call_2', content: 'two' },
127
+ ] as unknown as ChatCompletionParams['messages'],
128
+ })
129
+
130
+ const resultTurns = messagesOf(body).filter(
131
+ (m) => Array.isArray(m.content) && m.content.every((b) => b.type === 'tool_result'),
132
+ )
133
+ expect(resultTurns).toHaveLength(1)
134
+ expect(
135
+ (resultTurns[0]?.content as Record<string, unknown>[]).map((b) => b.tool_use_id),
136
+ ).toEqual(['call_1', 'call_2'])
137
+ })
138
+
139
+ it('every tool result answers a tool call that was actually made', async () => {
140
+ const body = await bodyFor({
141
+ messages: [
142
+ { role: 'user', content: 'read it' },
143
+ {
144
+ role: 'assistant',
145
+ content: null,
146
+ toolCalls: [
147
+ { id: 'call_1', type: 'function', function: { name: 'read', arguments: '{}' } },
148
+ ],
149
+ },
150
+ { role: 'tool', toolCallId: 'call_1', content: 'body' },
151
+ ] as unknown as ChatCompletionParams['messages'],
152
+ })
153
+
154
+ const issued = new Set(
155
+ allBlocks(body)
156
+ .filter((b) => b.type === 'tool_use')
157
+ .map((b) => b.id),
158
+ )
159
+ for (const result of allBlocks(body).filter((b) => b.type === 'tool_result')) {
160
+ // An orphan tool_result is rejected for the whole conversation.
161
+ expect(issued.has(result.tool_use_id)).toBe(true)
162
+ }
163
+ })
164
+
165
+ it('places the results after the turn that asked for them', async () => {
166
+ const body = await bodyFor({
167
+ messages: [
168
+ { role: 'user', content: 'read it' },
169
+ {
170
+ role: 'assistant',
171
+ content: null,
172
+ toolCalls: [
173
+ { id: 'call_1', type: 'function', function: { name: 'read', arguments: '{}' } },
174
+ ],
175
+ },
176
+ { role: 'tool', toolCallId: 'call_1', content: 'body' },
177
+ ] as unknown as ChatCompletionParams['messages'],
178
+ })
179
+ const roles = messagesOf(body).map((m) => m.role)
180
+
181
+ expect(roles).toEqual(['user', 'assistant', 'user'])
182
+ })
183
+ })
184
+
185
+ describe('a malformed tool argument does not become a malformed block', () => {
186
+ it('sends an empty object rather than an unparsed string', async () => {
187
+ const body = await bodyFor({
188
+ messages: [
189
+ { role: 'user', content: 'go' },
190
+ {
191
+ role: 'assistant',
192
+ content: null,
193
+ toolCalls: [
194
+ { id: 'call_1', type: 'function', function: { name: 'read', arguments: '{not json' } },
195
+ ],
196
+ },
197
+ ] as unknown as ChatCompletionParams['messages'],
198
+ })
199
+
200
+ expect(allBlocks(body).find((b) => b.type === 'tool_use')?.input).toEqual({})
201
+ })
202
+
203
+ it('reads empty arguments as an empty object', async () => {
204
+ const body = await bodyFor({
205
+ messages: [
206
+ { role: 'user', content: 'go' },
207
+ {
208
+ role: 'assistant',
209
+ content: null,
210
+ toolCalls: [
211
+ { id: 'call_1', type: 'function', function: { name: 'read', arguments: '' } },
212
+ ],
213
+ },
214
+ ] as unknown as ChatCompletionParams['messages'],
215
+ })
216
+
217
+ expect(allBlocks(body).find((b) => b.type === 'tool_use')?.input).toEqual({})
218
+ })
219
+ })
220
+
221
+ describe('tool_choice is only legal beside tools', () => {
222
+ it('is sent when tools are', async () => {
223
+ const body = await bodyFor({ tools: TOOLS, toolChoice: 'required' })
224
+
225
+ expect(body.tools).toBeDefined()
226
+ expect(body.tool_choice).toBeDefined()
227
+ })
228
+
229
+ it('is withheld when there are no tools', async () => {
230
+ const body = await bodyFor({ toolChoice: 'required' })
231
+
232
+ // The API rejects the request outright; a driver that forwards it
233
+ // turns a caller's harmless default into a hard failure.
234
+ expect(body.tool_choice).toBeUndefined()
235
+ })
236
+
237
+ it('is withheld when a parallel-call hint is the only reason for it', async () => {
238
+ const body = await bodyFor({ parallelToolCalls: false })
239
+
240
+ expect(body.tool_choice).toBeUndefined()
241
+ })
242
+ })
243
+
244
+ describe('the required fields are always present', () => {
245
+ it('always sends max_tokens, which the API demands', async () => {
246
+ expect(await bodyFor({})).toHaveProperty('max_tokens')
247
+ })
248
+
249
+ it('honours the caller max over the default', async () => {
250
+ expect(await bodyFor({ maxTokens: 128 })).toMatchObject({ max_tokens: 128 })
251
+ })
252
+
253
+ it('marks the request as streaming', async () => {
254
+ expect(await bodyFor({})).toMatchObject({ stream: true })
255
+ })
256
+ })
@@ -0,0 +1,262 @@
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
+ })