@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,131 +0,0 @@
1
- import type { ChatCompletionParams } from '@namzu/sdk'
2
- import { describe, expect, it, vi } from 'vitest'
3
-
4
- import { ANTHROPIC_CAPABILITIES, AnthropicProvider } from '../client.js'
5
-
6
- /**
7
- * The driver declared `supportsDocuments: true` and had no document branch.
8
- *
9
- * Every attachment was mapped as an image block carrying the attachment's
10
- * media type, so a PDF went up as `{ type: 'image', source: { media_type:
11
- * 'application/pdf' } }` — a shape the API rejects. The capability set said
12
- * documents worked, the SDK carried a `DocumentAttachment` type with a page
13
- * of documentation about why native handling is worth having, and the one
14
- * line that would have used it was never written.
15
- *
16
- * The native block is not a nicety: it buys page structure, the provider's
17
- * own extraction, and the citations that make an answer checkable.
18
- */
19
-
20
- const PDF = 'JVBERi0xLjQKJSVFT0Y='
21
-
22
- function providerCapturing(seen: { body?: Record<string, unknown> }): AnthropicProvider {
23
- const provider = new AnthropicProvider({ apiKey: 'test-key' })
24
- // The vendor client is the only seam; replace its one method.
25
- ;(provider as unknown as { client: { messages: { create: unknown } } }).client = {
26
- messages: {
27
- create: vi.fn(async (body: Record<string, unknown>) => {
28
- seen.body = body
29
- return (async function* () {
30
- yield { type: 'message_start', message: { id: 'msg_1' } }
31
- yield { type: 'message_delta', delta: { stop_reason: 'end_turn' } }
32
- })()
33
- }),
34
- },
35
- }
36
- return provider
37
- }
38
-
39
- async function bodyFor(params: Partial<ChatCompletionParams>): Promise<Record<string, unknown>> {
40
- const seen: { body?: Record<string, unknown> } = {}
41
- const provider = providerCapturing(seen)
42
- for await (const _chunk of provider.chatStream({
43
- model: 'm',
44
- messages: [{ role: 'user', content: 'summarize this' }],
45
- ...params,
46
- } as ChatCompletionParams)) {
47
- // drain
48
- }
49
- return seen.body ?? {}
50
- }
51
-
52
- /** The first user message's content blocks, as sent. */
53
- function blocksOf(body: Record<string, unknown>): Record<string, unknown>[] {
54
- const messages = body.messages as Array<{ content: unknown }>
55
- return messages[0]?.content as Record<string, unknown>[]
56
- }
57
-
58
- function withAttachments(attachments: unknown[]): Partial<ChatCompletionParams> {
59
- return {
60
- messages: [{ role: 'user', content: 'summarize this', attachments }],
61
- } as unknown as Partial<ChatCompletionParams>
62
- }
63
-
64
- describe('a document attachment reaches the wire as a document', () => {
65
- it('sends a document block, not an image block', async () => {
66
- const body = await bodyFor(
67
- withAttachments([{ type: 'document', data: PDF, mediaType: 'application/pdf' }]),
68
- )
69
-
70
- const doc = blocksOf(body).find((b) => b.type === 'document')
71
- expect(doc?.source).toEqual({ type: 'base64', media_type: 'application/pdf', data: PDF })
72
- // The bug in one assertion: it used to be an image block.
73
- expect(blocksOf(body).some((b) => b.type === 'image')).toBe(false)
74
- })
75
-
76
- it('keeps the prose ahead of the document', async () => {
77
- const body = await bodyFor(
78
- withAttachments([{ type: 'document', data: PDF, mediaType: 'application/pdf' }]),
79
- )
80
-
81
- expect(blocksOf(body)[0]).toMatchObject({ type: 'text', text: 'summarize this' })
82
- })
83
-
84
- it('carries the name so the model can refer to the file', async () => {
85
- const body = await bodyFor(
86
- withAttachments([
87
- { type: 'document', data: PDF, mediaType: 'application/pdf', name: 'lease.pdf' },
88
- ]),
89
- )
90
-
91
- expect(blocksOf(body).find((b) => b.type === 'document')?.title).toBe('lease.pdf')
92
- })
93
-
94
- it('omits the title when the caller supplied no name', async () => {
95
- const body = await bodyFor(
96
- withAttachments([{ type: 'document', data: PDF, mediaType: 'application/pdf' }]),
97
- )
98
-
99
- expect(blocksOf(body).find((b) => b.type === 'document')).not.toHaveProperty('title')
100
- })
101
-
102
- it('still maps an image attachment as an image', async () => {
103
- const body = await bodyFor(
104
- withAttachments([{ type: 'image', data: 'AAAA', mediaType: 'image/png' }]),
105
- )
106
-
107
- expect(blocksOf(body).find((b) => b.type === 'image')?.source).toEqual({
108
- type: 'base64',
109
- media_type: 'image/png',
110
- data: 'AAAA',
111
- })
112
- expect(blocksOf(body).some((b) => b.type === 'document')).toBe(false)
113
- })
114
-
115
- it('carries both kinds in one message, in the order given', async () => {
116
- const body = await bodyFor(
117
- withAttachments([
118
- { type: 'document', data: PDF, mediaType: 'application/pdf' },
119
- { type: 'image', data: 'AAAA', mediaType: 'image/png' },
120
- ]),
121
- )
122
-
123
- expect(blocksOf(body).map((b) => b.type)).toEqual(['text', 'document', 'image'])
124
- })
125
- })
126
-
127
- describe('the capability claim matches the mapper', () => {
128
- it('declares document support, which is now true', () => {
129
- expect(ANTHROPIC_CAPABILITIES.supportsDocuments).toBe(true)
130
- })
131
- })
@@ -1,274 +0,0 @@
1
- /**
2
- * Provider error taxonomy — Anthropic driver.
3
- *
4
- * The driver hands the request to the vendor SDK and lets whatever the SDK
5
- * rejects with escape verbatim (`RateLimitError`, `BadRequestError`, …).
6
- * Those are vendor types: a caller cannot classify them without importing
7
- * `@anthropic-ai/sdk`, so nothing downstream can distinguish a throttle
8
- * from a context overflow from a bad request.
9
- *
10
- * Transport seam: `AnthropicConfig.baseURL` — the tests point the SDK at a
11
- * loopback server that answers with a scripted status/headers/body. This
12
- * exercises the REAL vendor client (including its own internal retries,
13
- * which this group must not disturb).
14
- */
15
-
16
- import { type Server, createServer } from 'node:http'
17
- import type { AddressInfo } from 'node:net'
18
- import { afterEach, describe, expect, it } from 'vitest'
19
- import { AnthropicProvider } from '../client.js'
20
-
21
- /** Obviously fake, non-functional token — present only as a leak probe. */
22
- const FAKE_CREDENTIAL = 'sk-ant-FAKE-DO-NOT-USE-0000'
23
-
24
- interface ScriptedReply {
25
- status: number
26
- body: string
27
- headers?: Record<string, string>
28
- }
29
-
30
- let server: Server | undefined
31
-
32
- afterEach(async () => {
33
- if (server) {
34
- await new Promise<void>((resolve) => server?.close(() => resolve()))
35
- server = undefined
36
- }
37
- })
38
-
39
- /** Boot a loopback endpoint that answers every request with `reply`. */
40
- async function startEndpoint(reply: ScriptedReply): Promise<string> {
41
- server = createServer((_req, res) => {
42
- res.writeHead(reply.status, {
43
- 'Content-Type': 'application/json',
44
- ...(reply.headers ?? {}),
45
- })
46
- res.end(reply.body)
47
- })
48
- await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()))
49
- const { port } = server.address() as AddressInfo
50
- return `http://127.0.0.1:${port}`
51
- }
52
-
53
- /** Boot a loopback endpoint that streams `frames` as an SSE 200 response. */
54
- async function startSseEndpoint(frames: string[]): Promise<string> {
55
- server = createServer((_req, res) => {
56
- res.writeHead(200, {
57
- 'Content-Type': 'text/event-stream',
58
- 'Cache-Control': 'no-cache',
59
- Connection: 'keep-alive',
60
- })
61
- res.end(`${frames.join('\n\n')}\n\n`)
62
- })
63
- await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()))
64
- const { port } = server.address() as AddressInfo
65
- return `http://127.0.0.1:${port}`
66
- }
67
-
68
- async function captureChatStreamError(reply: ScriptedReply): Promise<unknown> {
69
- const baseURL = await startEndpoint(reply)
70
- // maxRetries is deliberately NOT set: this group classifies errors and
71
- // must leave the vendor SDK's own retry behaviour exactly as it is.
72
- const provider = new AnthropicProvider({
73
- apiKey: 'test-key',
74
- model: 'claude-sonnet-4-5-20250929',
75
- baseURL,
76
- })
77
- try {
78
- for await (const _chunk of provider.chatStream({
79
- model: 'claude-sonnet-4-5-20250929',
80
- messages: [{ role: 'user', content: 'hi' }],
81
- })) {
82
- // drain
83
- }
84
- } catch (err) {
85
- return err
86
- }
87
- throw new Error('expected chatStream to throw')
88
- }
89
-
90
- async function captureProviderError(
91
- provider: AnthropicProvider,
92
- signal?: AbortSignal,
93
- ): Promise<unknown> {
94
- try {
95
- for await (const _chunk of provider.chatStream({
96
- model: 'claude-sonnet-4-5-20250929',
97
- messages: [{ role: 'user', content: 'hi' }],
98
- signal,
99
- })) {
100
- // drain
101
- }
102
- } catch (err) {
103
- return err
104
- }
105
- throw new Error('expected chatStream to throw')
106
- }
107
-
108
- describe('@namzu/anthropic — provider error taxonomy', () => {
109
- it('(a) 429 with `retry-after: 2` throws a throttle-classified error carrying retryAfterMs', async () => {
110
- const err = await captureChatStreamError({
111
- status: 429,
112
- headers: { 'retry-after': '2' },
113
- body: JSON.stringify({
114
- type: 'error',
115
- error: { type: 'rate_limit_error', message: 'slow' },
116
- }),
117
- })
118
-
119
- expect(err).toMatchObject({
120
- name: 'ProviderRequestError',
121
- kind: 'throttle',
122
- status: 429,
123
- retryAfterMs: 2000,
124
- providerId: 'anthropic',
125
- })
126
- }, 60_000)
127
-
128
- it("(c) 400 whose body says the prompt is too long classifies as 'context_overflow'", async () => {
129
- const err = await captureChatStreamError({
130
- status: 400,
131
- body: JSON.stringify({
132
- type: 'error',
133
- error: {
134
- type: 'invalid_request_error',
135
- message: 'prompt is too long: 305231 tokens > 200000 maximum',
136
- },
137
- }),
138
- })
139
-
140
- expect(err).toMatchObject({
141
- name: 'ProviderRequestError',
142
- kind: 'context_overflow',
143
- status: 400,
144
- providerId: 'anthropic',
145
- })
146
- }, 30_000)
147
-
148
- it("(c) 400 that is not an overflow classifies as 'bad_request'", async () => {
149
- const err = await captureChatStreamError({
150
- status: 400,
151
- body: JSON.stringify({
152
- type: 'error',
153
- error: {
154
- type: 'invalid_request_error',
155
- message: 'messages: at least one message required',
156
- },
157
- }),
158
- })
159
-
160
- expect(err).toMatchObject({
161
- name: 'ProviderRequestError',
162
- kind: 'bad_request',
163
- status: 400,
164
- providerId: 'anthropic',
165
- })
166
- }, 30_000)
167
-
168
- it("(auth) 401 classifies as 'auth'", async () => {
169
- const err = await captureChatStreamError({
170
- status: 401,
171
- body: JSON.stringify({
172
- type: 'error',
173
- error: { type: 'authentication_error', message: 'invalid x-api-key' },
174
- }),
175
- })
176
-
177
- expect(err).toMatchObject({
178
- name: 'ProviderRequestError',
179
- kind: 'auth',
180
- status: 401,
181
- providerId: 'anthropic',
182
- })
183
- }, 30_000)
184
-
185
- it("529 (upstream overload) classifies as 'server'", async () => {
186
- const err = await captureChatStreamError({
187
- status: 529,
188
- body: JSON.stringify({
189
- type: 'error',
190
- error: { type: 'overloaded_error', message: 'Overloaded' },
191
- }),
192
- })
193
-
194
- expect(err).toMatchObject({
195
- name: 'ProviderRequestError',
196
- kind: 'server',
197
- status: 529,
198
- providerId: 'anthropic',
199
- })
200
- }, 60_000)
201
-
202
- it("MID-STREAM: an `event: error` frame after a 200 classifies as 'server'", async () => {
203
- // The vendor SDK's SSE reader throws its own `APIError` for an
204
- // `event: error` frame (core/streaming: `if (sse.event === 'error')`),
205
- // so the driver's event switch never sees it — the vendor error escapes
206
- // the driver unclassified, with the frame body interpolated.
207
- const baseURL = await startSseEndpoint([
208
- 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","usage":{"input_tokens":5,"output_tokens":0}}}',
209
- 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}',
210
- 'event: error\ndata: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}',
211
- ])
212
- const provider = new AnthropicProvider({
213
- apiKey: 'test-key',
214
- model: 'claude-sonnet-4-5-20250929',
215
- baseURL,
216
- })
217
-
218
- let caught: unknown
219
- try {
220
- for await (const _chunk of provider.chatStream({
221
- model: 'claude-sonnet-4-5-20250929',
222
- messages: [{ role: 'user', content: 'hi' }],
223
- })) {
224
- // drain
225
- }
226
- } catch (err) {
227
- caught = err
228
- }
229
-
230
- expect(caught).toMatchObject({
231
- name: 'ProviderRequestError',
232
- kind: 'server',
233
- providerId: 'anthropic',
234
- })
235
- }, 30_000)
236
-
237
- it('(d) SECURITY: a credential echoed back in a 401 body never reaches the thrown message', async () => {
238
- const err = await captureChatStreamError({
239
- status: 401,
240
- body: JSON.stringify({
241
- type: 'error',
242
- error: {
243
- type: 'authentication_error',
244
- message: `invalid x-api-key ${FAKE_CREDENTIAL}`,
245
- },
246
- }),
247
- })
248
-
249
- expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
250
- expect(JSON.stringify(err)).not.toContain(FAKE_CREDENTIAL)
251
- expect('cause' in (err as object)).toBe(false)
252
- }, 30_000)
253
-
254
- it('preserves the caller abort reason when the SDK replaces the error object', async () => {
255
- const controller = new AbortController()
256
- const reason = new Error('user stopped')
257
- const sdkAbort = Object.assign(new Error('request aborted'), {
258
- name: 'APIUserAbortError',
259
- })
260
- controller.abort(reason)
261
- const provider = new AnthropicProvider({
262
- apiKey: 'test-key',
263
- model: 'claude-sonnet-4-5-20250929',
264
- })
265
- ;(provider as unknown as { client: unknown }).client = {
266
- messages: { create: async () => Promise.reject(sdkAbort) },
267
- }
268
-
269
- const err = await captureProviderError(provider, controller.signal)
270
-
271
- expect(sdkAbort).not.toBe(reason)
272
- expect(err).toBe(reason)
273
- })
274
- })
@@ -1,262 +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
- * Extended thinking was fully specified in the SDK and entirely absent
8
- * from this driver.
9
- *
10
- * The stream chunk carried a `reasoning` channel whose own comment named
11
- * the bug — "`thinking_delta` and `signature_delta` fell through the
12
- * driver's `default: // ignore`" — the run's aggregator bucketed fragments
13
- * by index and closed them on `done`, and `ReasoningBlock` recorded the
14
- * signature with a note that replaying it unchanged is mandatory. The
15
- * driver requested no thinking, parsed none, and replayed none.
16
- *
17
- * The close matters as much as the content. A block is only complete once
18
- * its signature has arrived, and the signature arrives last: without a
19
- * `done` the aggregator cannot tell a finished block from one still
20
- * streaming, and a block replayed without its signature invalidates the
21
- * whole conversation upstream — not just that block.
22
- */
23
-
24
- function providerOver(events: unknown[], 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
- for (const event of events) yield event
32
- })()
33
- }),
34
- },
35
- }
36
- return provider
37
- }
38
-
39
- async function chunksOf(events: unknown[]): Promise<StreamChunk[]> {
40
- const out: StreamChunk[] = []
41
- for await (const chunk of providerOver(events).chatStream({
42
- model: 'm',
43
- messages: [{ role: 'user', content: 'q' }],
44
- } as ChatCompletionParams)) {
45
- out.push(chunk)
46
- }
47
- return out
48
- }
49
-
50
- const THINKING_STREAM = [
51
- { type: 'message_start', message: { id: 'msg_1' } },
52
- { type: 'content_block_start', index: 0, content_block: { type: 'thinking' } },
53
- {
54
- type: 'content_block_delta',
55
- index: 0,
56
- delta: { type: 'thinking_delta', thinking: 'step one' },
57
- },
58
- {
59
- type: 'content_block_delta',
60
- index: 0,
61
- delta: { type: 'thinking_delta', thinking: ' then two' },
62
- },
63
- {
64
- type: 'content_block_delta',
65
- index: 0,
66
- delta: { type: 'signature_delta', signature: 'sig-abc' },
67
- },
68
- { type: 'content_block_stop', index: 0 },
69
- { type: 'content_block_start', index: 1, content_block: { type: 'text' } },
70
- { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: 'the answer' } },
71
- { type: 'message_delta', delta: { stop_reason: 'end_turn' } },
72
- ]
73
-
74
- function reasoningOf(chunks: StreamChunk[]) {
75
- return chunks.map((c) => c.delta.reasoning).filter((r): r is NonNullable<typeof r> => Boolean(r))
76
- }
77
-
78
- describe('a reasoning block streams, then closes', () => {
79
- it('opens the block with its kind', async () => {
80
- const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
81
-
82
- expect(reasoning[0]).toMatchObject({ index: 0, type: 'thinking' })
83
- })
84
-
85
- it('carries each fragment through in order', async () => {
86
- const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
87
-
88
- expect(reasoning.map((r) => r.text).filter(Boolean)).toEqual(['step one', ' then two'])
89
- })
90
-
91
- it('carries the signature, which arrives once at the end', async () => {
92
- const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
93
-
94
- expect(reasoning.find((r) => r.signature)?.signature).toBe('sig-abc')
95
- })
96
-
97
- it('closes the block so the aggregator knows the signature has landed', async () => {
98
- const reasoning = reasoningOf(await chunksOf(THINKING_STREAM))
99
-
100
- expect(reasoning.at(-1)).toEqual({ index: 0, done: true })
101
- })
102
-
103
- it('closes it before the text block starts, not after', async () => {
104
- const chunks = await chunksOf(THINKING_STREAM)
105
- const closeAt = chunks.findIndex((c) => c.delta.reasoning?.done)
106
- const textAt = chunks.findIndex((c) => c.delta.content === 'the answer')
107
-
108
- expect(closeAt).toBeGreaterThan(-1)
109
- expect(closeAt).toBeLessThan(textAt)
110
- })
111
-
112
- it('does not leak reasoning into the visible text', async () => {
113
- const chunks = await chunksOf(THINKING_STREAM)
114
-
115
- expect(chunks.map((c) => c.delta.content).filter(Boolean)).toEqual(['the answer'])
116
- })
117
-
118
- it('groups two blocks by their own index', async () => {
119
- const reasoning = reasoningOf(
120
- await chunksOf([
121
- { type: 'message_start', message: { id: 'm' } },
122
- { type: 'content_block_start', index: 0, content_block: { type: 'thinking' } },
123
- { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'a' } },
124
- { type: 'content_block_stop', index: 0 },
125
- { type: 'content_block_start', index: 1, content_block: { type: 'thinking' } },
126
- { type: 'content_block_delta', index: 1, delta: { type: 'thinking_delta', thinking: 'b' } },
127
- { type: 'content_block_stop', index: 1 },
128
- ]),
129
- )
130
-
131
- expect(reasoning.filter((r) => r.done).map((r) => r.index)).toEqual([0, 1])
132
- })
133
-
134
- it('carries a redacted block as an opaque payload rather than text', async () => {
135
- const reasoning = reasoningOf(
136
- await chunksOf([
137
- { type: 'message_start', message: { id: 'm' } },
138
- {
139
- type: 'content_block_start',
140
- index: 0,
141
- content_block: { type: 'redacted_thinking', data: 'opaque-bytes' },
142
- },
143
- { type: 'content_block_stop', index: 0 },
144
- ]),
145
- )
146
-
147
- expect(reasoning[0]).toMatchObject({ type: 'redacted_thinking', encrypted: 'opaque-bytes' })
148
- expect(reasoning[0]?.text).toBeUndefined()
149
- })
150
-
151
- it('still closes a tool call, which shares the same stop event', async () => {
152
- const chunks = await chunksOf([
153
- { type: 'message_start', message: { id: 'm' } },
154
- {
155
- type: 'content_block_start',
156
- index: 0,
157
- content_block: { type: 'tool_use', id: 'call_1', name: 'read' },
158
- },
159
- { type: 'content_block_stop', index: 0 },
160
- ])
161
-
162
- expect(chunks.some((c) => c.delta.toolCallEnd?.id === 'call_1')).toBe(true)
163
- })
164
- })
165
-
166
- describe('thinking can be asked for', () => {
167
- async function bodyFor(thinking: unknown): Promise<Record<string, unknown>> {
168
- const seen: { body?: Record<string, unknown> } = {}
169
- const provider = providerOver([{ type: 'message_start', message: { id: 'm' } }], seen)
170
- for await (const _chunk of provider.chatStream({
171
- model: 'm',
172
- messages: [{ role: 'user', content: 'q' }],
173
- ...(thinking !== undefined ? { thinking } : {}),
174
- } as ChatCompletionParams)) {
175
- // drain
176
- }
177
- return seen.body ?? {}
178
- }
179
-
180
- it('sends the budget the caller set', async () => {
181
- expect(await bodyFor({ type: 'enabled', budgetTokens: 4096 })).toMatchObject({
182
- thinking: { type: 'enabled', budget_tokens: 4096 },
183
- })
184
- })
185
-
186
- it('enables it without a budget when none was named', async () => {
187
- expect((await bodyFor({ type: 'enabled' })).thinking).toEqual({ type: 'enabled' })
188
- })
189
-
190
- it('can turn it off on a model where it is on by default', async () => {
191
- expect((await bodyFor({ type: 'disabled' })).thinking).toEqual({ type: 'disabled' })
192
- })
193
-
194
- it('says nothing at all when the caller did not ask', async () => {
195
- expect(await bodyFor(undefined)).not.toHaveProperty('thinking')
196
- })
197
- })
198
-
199
- describe('a reasoned turn is replayed verbatim on the next request', () => {
200
- async function messagesFor(assistant: Record<string, unknown>) {
201
- const seen: { body?: Record<string, unknown> } = {}
202
- const provider = providerOver([{ type: 'message_start', message: { id: 'm' } }], seen)
203
- for await (const _chunk of provider.chatStream({
204
- model: 'm',
205
- messages: [{ role: 'user', content: 'q' }, assistant, { role: 'user', content: 'and then?' }],
206
- } as unknown as ChatCompletionParams)) {
207
- // drain
208
- }
209
- return seen.body?.messages as Array<{ role: string; content: unknown }>
210
- }
211
-
212
- it('replays the block with its signature intact', async () => {
213
- const messages = await messagesFor({
214
- role: 'assistant',
215
- content: 'because of that',
216
- reasoning: [{ type: 'thinking', text: 'step one', signature: 'sig-abc' }],
217
- })
218
- const blocks = messages[1]?.content as Record<string, unknown>[]
219
-
220
- expect(blocks[0]).toEqual({ type: 'thinking', thinking: 'step one', signature: 'sig-abc' })
221
- })
222
-
223
- it('puts the reasoning first, as the wire requires', async () => {
224
- const messages = await messagesFor({
225
- role: 'assistant',
226
- content: 'because of that',
227
- reasoning: [{ type: 'thinking', text: 'step one', signature: 'sig' }],
228
- })
229
- const blocks = messages[1]?.content as Record<string, unknown>[]
230
-
231
- expect(blocks.map((b) => b.type)).toEqual(['thinking', 'text'])
232
- })
233
-
234
- it('replays it ahead of a tool call too', async () => {
235
- const messages = await messagesFor({
236
- role: 'assistant',
237
- content: null,
238
- reasoning: [{ type: 'thinking', text: 'i should read it', signature: 'sig' }],
239
- toolCalls: [{ id: 'call_1', type: 'function', function: { name: 'read', arguments: '{}' } }],
240
- })
241
- const blocks = messages[1]?.content as Record<string, unknown>[]
242
-
243
- expect(blocks.map((b) => b.type)).toEqual(['thinking', 'tool_use'])
244
- })
245
-
246
- it('replays a redacted block as its opaque payload', async () => {
247
- const messages = await messagesFor({
248
- role: 'assistant',
249
- content: 'answer',
250
- reasoning: [{ type: 'redacted_thinking', encrypted: 'opaque-bytes' }],
251
- })
252
- const blocks = messages[1]?.content as Record<string, unknown>[]
253
-
254
- expect(blocks[0]).toEqual({ type: 'redacted_thinking', data: 'opaque-bytes' })
255
- })
256
-
257
- it('leaves an assistant turn that did not reason as a plain string', async () => {
258
- const messages = await messagesFor({ role: 'assistant', content: 'just an answer' })
259
-
260
- expect(messages[1]?.content).toBe('just an answer')
261
- })
262
- })