@namzu/anthropic 1.2.0 → 1.3.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 (39) hide show
  1. package/CHANGELOG.md +280 -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/client.d.ts.map +1 -1
  29. package/dist/client.js +174 -3
  30. package/dist/client.js.map +1 -1
  31. package/package.json +4 -4
  32. package/src/__tests__/anthropic.test.ts +1 -0
  33. package/src/__tests__/block-shape-guard.test.ts +256 -0
  34. package/src/__tests__/cache-anchors.test.ts +262 -0
  35. package/src/__tests__/citations.test.ts +218 -0
  36. package/src/__tests__/content-blocks.test.ts +153 -0
  37. package/src/__tests__/document-input.test.ts +131 -0
  38. package/src/__tests__/reasoning-close.test.ts +262 -0
  39. package/src/client.ts +241 -7
@@ -0,0 +1,98 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { ANTHROPIC_CAPABILITIES, AnthropicProvider } from '../client.js';
3
+ /**
4
+ * The driver declared `supportsDocuments: true` and had no document branch.
5
+ *
6
+ * Every attachment was mapped as an image block carrying the attachment's
7
+ * media type, so a PDF went up as `{ type: 'image', source: { media_type:
8
+ * 'application/pdf' } }` — a shape the API rejects. The capability set said
9
+ * documents worked, the SDK carried a `DocumentAttachment` type with a page
10
+ * of documentation about why native handling is worth having, and the one
11
+ * line that would have used it was never written.
12
+ *
13
+ * The native block is not a nicety: it buys page structure, the provider's
14
+ * own extraction, and the citations that make an answer checkable.
15
+ */
16
+ const PDF = 'JVBERi0xLjQKJSVFT0Y=';
17
+ function providerCapturing(seen) {
18
+ const provider = new AnthropicProvider({ apiKey: 'test-key' });
19
+ provider.client = {
20
+ messages: {
21
+ create: vi.fn(async (body) => {
22
+ seen.body = body;
23
+ return (async function* () {
24
+ yield { type: 'message_start', message: { id: 'msg_1' } };
25
+ yield { type: 'message_delta', delta: { stop_reason: 'end_turn' } };
26
+ })();
27
+ }),
28
+ },
29
+ };
30
+ return provider;
31
+ }
32
+ async function bodyFor(params) {
33
+ const seen = {};
34
+ const provider = providerCapturing(seen);
35
+ for await (const _chunk of provider.chatStream({
36
+ model: 'm',
37
+ messages: [{ role: 'user', content: 'summarize this' }],
38
+ ...params,
39
+ })) {
40
+ // drain
41
+ }
42
+ return seen.body ?? {};
43
+ }
44
+ /** The first user message's content blocks, as sent. */
45
+ function blocksOf(body) {
46
+ const messages = body.messages;
47
+ return messages[0]?.content;
48
+ }
49
+ function withAttachments(attachments) {
50
+ return {
51
+ messages: [{ role: 'user', content: 'summarize this', attachments }],
52
+ };
53
+ }
54
+ describe('a document attachment reaches the wire as a document', () => {
55
+ it('sends a document block, not an image block', async () => {
56
+ const body = await bodyFor(withAttachments([{ type: 'document', data: PDF, mediaType: 'application/pdf' }]));
57
+ const doc = blocksOf(body).find((b) => b.type === 'document');
58
+ expect(doc?.source).toEqual({ type: 'base64', media_type: 'application/pdf', data: PDF });
59
+ // The bug in one assertion: it used to be an image block.
60
+ expect(blocksOf(body).some((b) => b.type === 'image')).toBe(false);
61
+ });
62
+ it('keeps the prose ahead of the document', async () => {
63
+ const body = await bodyFor(withAttachments([{ type: 'document', data: PDF, mediaType: 'application/pdf' }]));
64
+ expect(blocksOf(body)[0]).toMatchObject({ type: 'text', text: 'summarize this' });
65
+ });
66
+ it('carries the name so the model can refer to the file', async () => {
67
+ const body = await bodyFor(withAttachments([
68
+ { type: 'document', data: PDF, mediaType: 'application/pdf', name: 'lease.pdf' },
69
+ ]));
70
+ expect(blocksOf(body).find((b) => b.type === 'document')?.title).toBe('lease.pdf');
71
+ });
72
+ it('omits the title when the caller supplied no name', async () => {
73
+ const body = await bodyFor(withAttachments([{ type: 'document', data: PDF, mediaType: 'application/pdf' }]));
74
+ expect(blocksOf(body).find((b) => b.type === 'document')).not.toHaveProperty('title');
75
+ });
76
+ it('still maps an image attachment as an image', async () => {
77
+ const body = await bodyFor(withAttachments([{ type: 'image', data: 'AAAA', mediaType: 'image/png' }]));
78
+ expect(blocksOf(body).find((b) => b.type === 'image')?.source).toEqual({
79
+ type: 'base64',
80
+ media_type: 'image/png',
81
+ data: 'AAAA',
82
+ });
83
+ expect(blocksOf(body).some((b) => b.type === 'document')).toBe(false);
84
+ });
85
+ it('carries both kinds in one message, in the order given', async () => {
86
+ const body = await bodyFor(withAttachments([
87
+ { type: 'document', data: PDF, mediaType: 'application/pdf' },
88
+ { type: 'image', data: 'AAAA', mediaType: 'image/png' },
89
+ ]));
90
+ expect(blocksOf(body).map((b) => b.type)).toEqual(['text', 'document', 'image']);
91
+ });
92
+ });
93
+ describe('the capability claim matches the mapper', () => {
94
+ it('declares document support, which is now true', () => {
95
+ expect(ANTHROPIC_CAPABILITIES.supportsDocuments).toBe(true);
96
+ });
97
+ });
98
+ //# sourceMappingURL=document-input.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-input.test.js","sourceRoot":"","sources":["../../src/__tests__/document-input.test.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AAEjD,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAExE;;;;;;;;;;;;GAYG;AAEH,MAAM,GAAG,GAAG,sBAAsB,CAAA;AAElC,SAAS,iBAAiB,CAAC,IAAwC;IAClE,MAAM,QAAQ,GAAG,IAAI,iBAAiB,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAE7D;IAAC,QAAqE,CAAC,MAAM,GAAG;QAChF,QAAQ,EAAE;YACT,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,IAA6B,EAAE,EAAE;gBACrD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;gBAChB,OAAO,CAAC,KAAK,SAAS,CAAC;oBACtB,MAAM,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,CAAA;oBACzD,MAAM,EAAE,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE,CAAA;gBACpE,CAAC,CAAC,EAAE,CAAA;YACL,CAAC,CAAC;SACF;KACD,CAAA;IACD,OAAO,QAAQ,CAAA;AAChB,CAAC;AAED,KAAK,UAAU,OAAO,CAAC,MAAqC;IAC3D,MAAM,IAAI,GAAuC,EAAE,CAAA;IACnD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,IAAI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AAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAA;IACjF,CAAC,CAAC,CAAA;AACH,CAAC,CAAC,CAAA;AAEF,QAAQ,CAAC,yCAAyC,EAAE,GAAG,EAAE;IACxD,EAAE,CAAC,8CAA8C,EAAE,GAAG,EAAE;QACvD,MAAM,CAAC,sBAAsB,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC5D,CAAC,CAAC,CAAA;AACH,CAAC,CAAC,CAAA"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=reasoning-close.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reasoning-close.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/reasoning-close.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,219 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { AnthropicProvider } from '../client.js';
3
+ /**
4
+ * Extended thinking was fully specified in the SDK and entirely absent
5
+ * from this driver.
6
+ *
7
+ * The stream chunk carried a `reasoning` channel whose own comment named
8
+ * the bug — "`thinking_delta` and `signature_delta` fell through the
9
+ * driver's `default: // ignore`" — the run's aggregator bucketed fragments
10
+ * by index and closed them on `done`, and `ReasoningBlock` recorded the
11
+ * signature with a note that replaying it unchanged is mandatory. The
12
+ * driver requested no thinking, parsed none, and replayed none.
13
+ *
14
+ * The close matters as much as the content. A block is only complete once
15
+ * its signature has arrived, and the signature arrives last: without a
16
+ * `done` the aggregator cannot tell a finished block from one still
17
+ * streaming, and a block replayed without its signature invalidates the
18
+ * whole conversation upstream — not just that block.
19
+ */
20
+ function providerOver(events, seen = {}) {
21
+ const provider = new AnthropicProvider({ apiKey: 'test-key' });
22
+ provider.client = {
23
+ messages: {
24
+ create: vi.fn(async (body) => {
25
+ seen.body = body;
26
+ return (async function* () {
27
+ for (const event of events)
28
+ yield event;
29
+ })();
30
+ }),
31
+ },
32
+ };
33
+ return provider;
34
+ }
35
+ async function chunksOf(events) {
36
+ const out = [];
37
+ for await (const chunk of providerOver(events).chatStream({
38
+ model: 'm',
39
+ messages: [{ role: 'user', content: 'q' }],
40
+ })) {
41
+ out.push(chunk);
42
+ }
43
+ return out;
44
+ }
45
+ const THINKING_STREAM = [
46
+ { type: 'message_start', message: { id: 'msg_1' } },
47
+ { type: 'content_block_start', index: 0, content_block: { type: 'thinking' } },
48
+ {
49
+ type: 'content_block_delta',
50
+ index: 0,
51
+ delta: { type: 'thinking_delta', thinking: 'step one' },
52
+ },
53
+ {
54
+ type: 'content_block_delta',
55
+ index: 0,
56
+ delta: { type: 'thinking_delta', thinking: ' then two' },
57
+ },
58
+ {
59
+ type: 'content_block_delta',
60
+ index: 0,
61
+ delta: { type: 'signature_delta', signature: 'sig-abc' },
62
+ },
63
+ { type: 'content_block_stop', index: 0 },
64
+ { type: 'content_block_start', index: 1, content_block: { type: 'text' } },
65
+ { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: 'the answer' } },
66
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' } },
67
+ ];
68
+ function reasoningOf(chunks) {
69
+ return chunks.map((c) => c.delta.reasoning).filter((r) => Boolean(r));
70
+ }
71
+ describe('a reasoning block streams, then closes', () => {
72
+ it('opens the block with its kind', async () => {
73
+ const reasoning = reasoningOf(await chunksOf(THINKING_STREAM));
74
+ expect(reasoning[0]).toMatchObject({ index: 0, type: 'thinking' });
75
+ });
76
+ it('carries each fragment through in order', async () => {
77
+ const reasoning = reasoningOf(await chunksOf(THINKING_STREAM));
78
+ expect(reasoning.map((r) => r.text).filter(Boolean)).toEqual(['step one', ' then two']);
79
+ });
80
+ it('carries the signature, which arrives once at the end', async () => {
81
+ const reasoning = reasoningOf(await chunksOf(THINKING_STREAM));
82
+ expect(reasoning.find((r) => r.signature)?.signature).toBe('sig-abc');
83
+ });
84
+ it('closes the block so the aggregator knows the signature has landed', async () => {
85
+ const reasoning = reasoningOf(await chunksOf(THINKING_STREAM));
86
+ expect(reasoning.at(-1)).toEqual({ index: 0, done: true });
87
+ });
88
+ it('closes it before the text block starts, not after', async () => {
89
+ const chunks = await chunksOf(THINKING_STREAM);
90
+ const closeAt = chunks.findIndex((c) => c.delta.reasoning?.done);
91
+ const textAt = chunks.findIndex((c) => c.delta.content === 'the answer');
92
+ expect(closeAt).toBeGreaterThan(-1);
93
+ expect(closeAt).toBeLessThan(textAt);
94
+ });
95
+ it('does not leak reasoning into the visible text', async () => {
96
+ const chunks = await chunksOf(THINKING_STREAM);
97
+ expect(chunks.map((c) => c.delta.content).filter(Boolean)).toEqual(['the answer']);
98
+ });
99
+ it('groups two blocks by their own index', async () => {
100
+ const reasoning = reasoningOf(await chunksOf([
101
+ { type: 'message_start', message: { id: 'm' } },
102
+ { type: 'content_block_start', index: 0, content_block: { type: 'thinking' } },
103
+ { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'a' } },
104
+ { type: 'content_block_stop', index: 0 },
105
+ { type: 'content_block_start', index: 1, content_block: { type: 'thinking' } },
106
+ { type: 'content_block_delta', index: 1, delta: { type: 'thinking_delta', thinking: 'b' } },
107
+ { type: 'content_block_stop', index: 1 },
108
+ ]));
109
+ expect(reasoning.filter((r) => r.done).map((r) => r.index)).toEqual([0, 1]);
110
+ });
111
+ it('carries a redacted block as an opaque payload rather than text', async () => {
112
+ const reasoning = reasoningOf(await chunksOf([
113
+ { type: 'message_start', message: { id: 'm' } },
114
+ {
115
+ type: 'content_block_start',
116
+ index: 0,
117
+ content_block: { type: 'redacted_thinking', data: 'opaque-bytes' },
118
+ },
119
+ { type: 'content_block_stop', index: 0 },
120
+ ]));
121
+ expect(reasoning[0]).toMatchObject({ type: 'redacted_thinking', encrypted: 'opaque-bytes' });
122
+ expect(reasoning[0]?.text).toBeUndefined();
123
+ });
124
+ it('still closes a tool call, which shares the same stop event', async () => {
125
+ const chunks = await chunksOf([
126
+ { type: 'message_start', message: { id: 'm' } },
127
+ {
128
+ type: 'content_block_start',
129
+ index: 0,
130
+ content_block: { type: 'tool_use', id: 'call_1', name: 'read' },
131
+ },
132
+ { type: 'content_block_stop', index: 0 },
133
+ ]);
134
+ expect(chunks.some((c) => c.delta.toolCallEnd?.id === 'call_1')).toBe(true);
135
+ });
136
+ });
137
+ describe('thinking can be asked for', () => {
138
+ async function bodyFor(thinking) {
139
+ const seen = {};
140
+ const provider = providerOver([{ type: 'message_start', message: { id: 'm' } }], seen);
141
+ for await (const _chunk of provider.chatStream({
142
+ model: 'm',
143
+ messages: [{ role: 'user', content: 'q' }],
144
+ ...(thinking !== undefined ? { thinking } : {}),
145
+ })) {
146
+ // drain
147
+ }
148
+ return seen.body ?? {};
149
+ }
150
+ it('sends the budget the caller set', async () => {
151
+ expect(await bodyFor({ type: 'enabled', budgetTokens: 4096 })).toMatchObject({
152
+ thinking: { type: 'enabled', budget_tokens: 4096 },
153
+ });
154
+ });
155
+ it('enables it without a budget when none was named', async () => {
156
+ expect((await bodyFor({ type: 'enabled' })).thinking).toEqual({ type: 'enabled' });
157
+ });
158
+ it('can turn it off on a model where it is on by default', async () => {
159
+ expect((await bodyFor({ type: 'disabled' })).thinking).toEqual({ type: 'disabled' });
160
+ });
161
+ it('says nothing at all when the caller did not ask', async () => {
162
+ expect(await bodyFor(undefined)).not.toHaveProperty('thinking');
163
+ });
164
+ });
165
+ describe('a reasoned turn is replayed verbatim on the next request', () => {
166
+ async function messagesFor(assistant) {
167
+ const seen = {};
168
+ const provider = providerOver([{ type: 'message_start', message: { id: 'm' } }], seen);
169
+ for await (const _chunk of provider.chatStream({
170
+ model: 'm',
171
+ messages: [{ role: 'user', content: 'q' }, assistant, { role: 'user', content: 'and then?' }],
172
+ })) {
173
+ // drain
174
+ }
175
+ return seen.body?.messages;
176
+ }
177
+ it('replays the block with its signature intact', async () => {
178
+ const messages = await messagesFor({
179
+ role: 'assistant',
180
+ content: 'because of that',
181
+ reasoning: [{ type: 'thinking', text: 'step one', signature: 'sig-abc' }],
182
+ });
183
+ const blocks = messages[1]?.content;
184
+ expect(blocks[0]).toEqual({ type: 'thinking', thinking: 'step one', signature: 'sig-abc' });
185
+ });
186
+ it('puts the reasoning first, as the wire requires', async () => {
187
+ const messages = await messagesFor({
188
+ role: 'assistant',
189
+ content: 'because of that',
190
+ reasoning: [{ type: 'thinking', text: 'step one', signature: 'sig' }],
191
+ });
192
+ const blocks = messages[1]?.content;
193
+ expect(blocks.map((b) => b.type)).toEqual(['thinking', 'text']);
194
+ });
195
+ it('replays it ahead of a tool call too', async () => {
196
+ const messages = await messagesFor({
197
+ role: 'assistant',
198
+ content: null,
199
+ reasoning: [{ type: 'thinking', text: 'i should read it', signature: 'sig' }],
200
+ toolCalls: [{ id: 'call_1', type: 'function', function: { name: 'read', arguments: '{}' } }],
201
+ });
202
+ const blocks = messages[1]?.content;
203
+ expect(blocks.map((b) => b.type)).toEqual(['thinking', 'tool_use']);
204
+ });
205
+ it('replays a redacted block as its opaque payload', async () => {
206
+ const messages = await messagesFor({
207
+ role: 'assistant',
208
+ content: 'answer',
209
+ reasoning: [{ type: 'redacted_thinking', encrypted: 'opaque-bytes' }],
210
+ });
211
+ const blocks = messages[1]?.content;
212
+ expect(blocks[0]).toEqual({ type: 'redacted_thinking', data: 'opaque-bytes' });
213
+ });
214
+ it('leaves an assistant turn that did not reason as a plain string', async () => {
215
+ const messages = await messagesFor({ role: 'assistant', content: 'just an answer' });
216
+ expect(messages[1]?.content).toBe('just an answer');
217
+ });
218
+ });
219
+ //# sourceMappingURL=reasoning-close.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reasoning-close.test.js","sourceRoot":"","sources":["../../src/__tests__/reasoning-close.test.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AAEjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CA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b,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAMrC"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,oBAAoB,EAGpB,WAAW,EACX,SAAS,EACT,oBAAoB,EAEpB,WAAW,EAIX,MAAM,YAAY,CAAA;AAQnB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AA+iBjD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,EAAE,oBAMpC,CAAA;AAED,qBAAa,iBAAkB,YAAW,WAAW;IACpD,QAAQ,CAAC,EAAE,eAAc;IACzB,QAAQ,CAAC,IAAI,eAAc;IAC3B,QAAQ,CAAC,YAAY,uBAAyB;IAE9C,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,MAAM,CAAiB;gBAEnB,MAAM,EAAE,eAAe;IA8BnC,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,iBAAiB;IAoEzB;;;;;OAKG;IACH,OAAO,CAAC,SAAS;IAcV,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IAiPrE,UAAU,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IA+BxC,OAAO,CAAC,WAAW;IAmCb,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAMrC"}
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
- import { ProviderRequestError, isCallerAbortError, isProviderRequestError, providerVendorError, } from '@namzu/sdk';
3
+ import { ProviderRequestError, isCallerAbortError, isProviderRequestError, providerVendorError, toolResultToText, } from '@namzu/sdk';
4
4
  // Floor for `max_tokens` when neither the request nor the provider
5
5
  // config supplied one. Anthropic's API requires the field, so we cannot
6
6
  // truly omit it — but 4096 (the original SDK example default) is far
@@ -70,6 +70,61 @@ function extractSystem(messages, cachingEnabled) {
70
70
  }
71
71
  return blocks;
72
72
  }
73
+ /**
74
+ * The reasoning blocks an assistant message carries, in wire form.
75
+ *
76
+ * Verbatim by contract, and first in the message: the API requires
77
+ * thinking blocks to lead, and the signature is verified, so re-rendering
78
+ * or reordering them invalidates the turn they belong to.
79
+ */
80
+ function replayReasoning(msg) {
81
+ if (!msg.reasoning || msg.reasoning.length === 0)
82
+ return [];
83
+ return msg.reasoning.map((block) => block.type === 'redacted_thinking'
84
+ ? {
85
+ type: 'redacted_thinking',
86
+ ...(block.encrypted ? { data: block.encrypted } : {}),
87
+ }
88
+ : {
89
+ type: 'thinking',
90
+ thinking: block.text ?? '',
91
+ ...(block.signature ? { signature: block.signature } : {}),
92
+ });
93
+ }
94
+ /**
95
+ * A tool result, in the richest form this wire accepts.
96
+ *
97
+ * The blocks used to be `JSON.stringify`d, so a screenshot reached the
98
+ * model as a wall of quoted base64 — the one thing the SDK's own degrade
99
+ * helper exists to avoid, and pure cost besides: the model paid for every
100
+ * character and could read none of them. This wire carries image blocks in
101
+ * a tool result natively, so they are sent as images.
102
+ *
103
+ * A document block still degrades to the named placeholder: tool results
104
+ * on this wire take text and images, not documents, and inventing an image
105
+ * block around a PDF would fail the request instead of the block.
106
+ */
107
+ function toolResultContent(content) {
108
+ if (content === undefined)
109
+ return '';
110
+ if (typeof content === 'string')
111
+ return content;
112
+ const blocks = [];
113
+ for (const block of content) {
114
+ if (block.type === 'image') {
115
+ blocks.push({
116
+ type: 'image',
117
+ source: { type: 'base64', media_type: block.mediaType, data: block.data },
118
+ });
119
+ continue;
120
+ }
121
+ const text = toolResultToText([block]);
122
+ if (text.length > 0)
123
+ blocks.push({ type: 'text', text });
124
+ }
125
+ // An empty array is rejected upstream; an empty string is not.
126
+ return blocks.length > 0 ? blocks : '';
127
+ }
73
128
  function toAnthropicMessages(messages) {
74
129
  const out = [];
75
130
  let pendingToolResults = [];
@@ -87,13 +142,13 @@ function toAnthropicMessages(messages) {
87
142
  pendingToolResults.push({
88
143
  type: 'tool_result',
89
144
  tool_use_id: toolMsg.toolCallId ?? 'unknown',
90
- content: typeof toolMsg.content === 'string' ? toolMsg.content : JSON.stringify(toolMsg.content),
145
+ content: toolResultContent(toolMsg.content),
91
146
  });
92
147
  continue;
93
148
  }
94
149
  flushToolResults();
95
150
  if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls) {
96
- const blocks = [];
151
+ const blocks = [...replayReasoning(msg)];
97
152
  if (msg.content && typeof msg.content === 'string') {
98
153
  blocks.push({ type: 'text', text: msg.content });
99
154
  }
@@ -115,7 +170,15 @@ function toAnthropicMessages(messages) {
115
170
  out.push({ role: 'assistant', content: blocks });
116
171
  continue;
117
172
  }
173
+ // An assistant turn that reasoned replays those blocks even when it
174
+ // called no tool: dropping them invalidates the turn upstream.
175
+ const replayed = msg.role === 'assistant' ? replayReasoning(msg) : [];
118
176
  const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);
177
+ if (replayed.length > 0) {
178
+ const trailing = content.length > 0 ? [{ type: 'text', text: content }] : [];
179
+ out.push({ role: 'assistant', content: [...replayed, ...trailing] });
180
+ continue;
181
+ }
119
182
  // User message with image attachments → multimodal content blocks
120
183
  // (text first, then each image as a base64 image block).
121
184
  const attachments = msg.attachments;
@@ -124,6 +187,23 @@ function toAnthropicMessages(messages) {
124
187
  if (content.length > 0)
125
188
  blocks.push({ type: 'text', text: content });
126
189
  for (const att of attachments) {
190
+ // A document is not an image with a different media type. It
191
+ // used to be mapped as one, so a PDF went up as an image block
192
+ // the API rejects — while the capability set claimed documents
193
+ // were supported. The native block buys page structure, OCR,
194
+ // and the citations the SDK contract already has a slot for.
195
+ if (att.type === 'document') {
196
+ blocks.push({
197
+ type: 'document',
198
+ source: { type: 'base64', media_type: att.mediaType, data: att.data },
199
+ ...(att.name ? { title: att.name } : {}),
200
+ // Opt-in: citations cost tokens, so they are requested
201
+ // only when the caller asked to be able to check the
202
+ // answer.
203
+ ...(att.citations ? { citations: { enabled: true } } : {}),
204
+ });
205
+ continue;
206
+ }
127
207
  blocks.push({
128
208
  type: 'image',
129
209
  source: { type: 'base64', media_type: att.mediaType, data: att.data },
@@ -266,6 +346,38 @@ function mapStopReason(reason) {
266
346
  return 'stop';
267
347
  }
268
348
  }
349
+ /**
350
+ * Map a wire citation onto the SDK's shape.
351
+ *
352
+ * Returns undefined rather than inventing a location: a citation whose
353
+ * source segment cannot be named is worse than none, because it looks
354
+ * checkable and is not.
355
+ */
356
+ function toCitation(raw, index) {
357
+ const citedText = raw.cited_text;
358
+ if (!citedText)
359
+ return undefined;
360
+ const location = (() => {
361
+ if (raw.start_page_number !== undefined && raw.end_page_number !== undefined) {
362
+ return { kind: 'page', start: raw.start_page_number, end: raw.end_page_number };
363
+ }
364
+ if (raw.start_char_index !== undefined && raw.end_char_index !== undefined) {
365
+ return { kind: 'char', start: raw.start_char_index, end: raw.end_char_index };
366
+ }
367
+ if (raw.start_block_index !== undefined && raw.end_block_index !== undefined) {
368
+ return { kind: 'block', start: raw.start_block_index, end: raw.end_block_index };
369
+ }
370
+ return undefined;
371
+ })();
372
+ if (!location)
373
+ return undefined;
374
+ return {
375
+ citedText,
376
+ documentIndex: raw.document_index ?? index,
377
+ ...(raw.document_title ? { documentTitle: raw.document_title } : {}),
378
+ location,
379
+ };
380
+ }
269
381
  // --------------------------------------------------------------------------------------
270
382
  // AnthropicProvider
271
383
  // --------------------------------------------------------------------------------------
@@ -279,6 +391,7 @@ export const ANTHROPIC_CAPABILITIES = {
279
391
  supportsStreaming: true,
280
392
  supportsFunctionCalling: true,
281
393
  supportsVision: true,
394
+ supportsDocuments: true,
282
395
  };
283
396
  export class AnthropicProvider {
284
397
  id = 'anthropic';
@@ -364,6 +477,20 @@ export class AnthropicProvider {
364
477
  // tool-less requests.
365
478
  if (tools && toolChoice)
366
479
  body.tool_choice = toolChoice;
480
+ if (params.thinking) {
481
+ // Thinking could not be REQUESTED at all before this: on a model
482
+ // where it is off by default the feature was unreachable, and on
483
+ // one where it is on by default its budget could not be tuned.
484
+ body.thinking =
485
+ params.thinking.type === 'enabled'
486
+ ? {
487
+ type: 'enabled',
488
+ ...(params.thinking.budgetTokens !== undefined
489
+ ? { budget_tokens: params.thinking.budgetTokens }
490
+ : {}),
491
+ }
492
+ : { type: 'disabled' };
493
+ }
367
494
  if (params.temperature !== undefined)
368
495
  body.temperature = params.temperature;
369
496
  if (params.topP !== undefined)
@@ -412,6 +539,7 @@ export class AnthropicProvider {
412
539
  // Track active tool-use blocks by content_block index so input_json_delta
413
540
  // fragments can reference the right tool call.
414
541
  const activeTools = new Map();
542
+ const activeReasoning = new Set();
415
543
  // Anthropic Messages API streams over SSE. Do not impose a
416
544
  // provider-local 90s idle cutoff by default: long reasoning or
417
545
  // long tool-argument generation can legitimately pause between
@@ -472,6 +600,20 @@ export class AnthropicProvider {
472
600
  case 'content_block_start': {
473
601
  const idx = event.index ?? 0;
474
602
  const block = event.content_block;
603
+ if (block?.type === 'thinking' || block?.type === 'redacted_thinking') {
604
+ activeReasoning.add(idx);
605
+ yield {
606
+ id: messageId,
607
+ delta: {
608
+ reasoning: {
609
+ index: idx,
610
+ type: block.type,
611
+ ...(block.data ? { encrypted: block.data } : {}),
612
+ },
613
+ },
614
+ };
615
+ break;
616
+ }
475
617
  if (block?.type === 'tool_use') {
476
618
  const toolId = block.id ?? `tool-${Date.now()}`;
477
619
  activeTools.set(idx, { id: toolId, name: block.name ?? '' });
@@ -497,6 +639,28 @@ export class AnthropicProvider {
497
639
  if (delta?.type === 'text_delta' && delta.text) {
498
640
  yield { id: messageId, delta: { content: delta.text } };
499
641
  }
642
+ else if (delta?.type === 'thinking_delta' && delta.thinking !== undefined) {
643
+ yield {
644
+ id: messageId,
645
+ delta: { reasoning: { index: idx, text: delta.thinking } },
646
+ };
647
+ }
648
+ else if (delta?.type === 'signature_delta' && delta.signature !== undefined) {
649
+ // Arrives once, at the end of the block, and has to
650
+ // reach the next request unmodified.
651
+ yield {
652
+ id: messageId,
653
+ delta: { reasoning: { index: idx, signature: delta.signature } },
654
+ };
655
+ }
656
+ else if (delta?.type === 'citations_delta' && delta.citation) {
657
+ // Not text: a citation lands on the assistant
658
+ // message beside the prose, which is where the
659
+ // runtime's stream aggregator already puts it.
660
+ const citation = toCitation(delta.citation, idx);
661
+ if (citation)
662
+ yield { id: messageId, delta: { citation } };
663
+ }
500
664
  else if (delta?.type === 'input_json_delta' && delta.partial_json !== undefined) {
501
665
  const active = activeTools.get(idx);
502
666
  yield {
@@ -525,6 +689,13 @@ export class AnthropicProvider {
525
689
  // — exactly the failure the live cowork test
526
690
  // surfaced (Bash + Write both blank-input failed).
527
691
  const idx = event.index ?? 0;
692
+ if (activeReasoning.delete(idx)) {
693
+ // Closes the block, exactly as toolCallEnd closes a
694
+ // tool call: without it the aggregator cannot know
695
+ // the signature has finished arriving.
696
+ yield { id: messageId, delta: { reasoning: { index: idx, done: true } } };
697
+ break;
698
+ }
528
699
  const active = activeTools.get(idx);
529
700
  if (active) {
530
701
  yield {