@namzu/anthropic 6.8.1 → 7.1.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.
- package/CHANGELOG.md +24 -0
- package/README.md +81 -2
- package/dist/client.d.ts +22 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +268 -42
- package/dist/client.js.map +1 -1
- package/dist/fast-mode.d.ts +54 -0
- package/dist/fast-mode.d.ts.map +1 -0
- package/dist/fast-mode.js +113 -0
- package/dist/fast-mode.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/search-replay.d.ts +6 -0
- package/dist/search-replay.d.ts.map +1 -1
- package/dist/search-replay.js +10 -0
- package/dist/search-replay.js.map +1 -1
- package/dist/types.d.ts +6 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/client.ts +307 -40
- package/src/fast-mode.ts +140 -0
- package/src/index.ts +8 -0
- package/src/search-replay.ts +10 -0
- package/src/types.ts +6 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 7.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 3951100: Anthropic driver gaps: paused hosted searches, side-call parameters, the model menu, cache diagnostics and usage.
|
|
8
|
+
|
|
9
|
+
`@namzu/anthropic` (minor): a hosted search the service pauses (`pause_turn`) now continues, up to five times within one turn, instead of failing it; a turn still paused after five continuations fails as unfinished. On the vendor's own host the driver sends `diagnostics.previous_message_id` and reads the miss reason into `TokenUsage.cacheMiss`; nothing is sent to a compatible or third-party endpoint. Usage now reads `server_tool_use.web_search_requests`, `service_tier` and `inference_geo`. `OFFLINE_MODEL_CATALOGUE` no longer lists `claude-opus-4-1-20250805` (retired) or `claude-sonnet-4-5-20250929` (retires 2026-11-30) and lists `claude-sonnet-5-5` and `claude-opus-4-8`; both removed ids still work for a caller that names them until the vendor stops serving them.
|
|
10
|
+
|
|
11
|
+
`@namzu/sdk` (minor): `TokenUsage` gains `webSearchRequests` (summed), `serviceTier`, `inferenceGeo` and `cacheMiss`; `ModelPricing.webSearchCostPer1000` prices hosted searches (Anthropic: $10 per 1,000), and tokens served on the `priority` or `batch` tier are reported as unpriced rather than at the standard rate, since the vendor publishes no per-token price for them. A cost limit on a priority-tier account is refused as unmeasurable until a price is published. `token_usage_updated` gains `cacheMiss`. Compaction summaries, their verifier and the auto-review classifier now resend without `temperature` when a model refuses it, as the turn already did; the turn's repair also recognises a refused `top_k`.
|
|
12
|
+
|
|
13
|
+
`@namzu/cli` (patch): forwards `cacheMiss` on the usage item; shows nothing new.
|
|
14
|
+
|
|
15
|
+
## 7.0.0
|
|
16
|
+
|
|
17
|
+
### Major Changes
|
|
18
|
+
|
|
19
|
+
- 4aa73dd: Fast mode, and a larger request budget for Anthropic.
|
|
20
|
+
|
|
21
|
+
`@namzu/anthropic` (major): the default request rich-content budget on the vendor's own endpoint rises from 24 MiB to 100 MiB of base64 (the first-party Messages limit is 128 MB). A changed default is a major change: a session that kept 24 MiB of images and documents now keeps up to 100 MiB, so requests are larger and spend more input tokens. To keep the old behaviour, set `turnConfig.maxRequestRichContentBytes` to `25165824`. A driver behind another `baseURL` or with `compatibleEndpoint: true` declares nothing and keeps 24 MiB. New: `speed: 'fast'` is sent as the top-level `speed` field only to Claude Opus 5.5, Fable 5.2 and Mythos 5.2 (and later in those families) and the Opus 5 and Opus 4.8 previews, with the `fast-mode-2026-02-01` beta header added only on the previews; any other model, and Opus 4.8 from 2026-11-30, is refused before sending with `providerCode: 'fast_mode_unsupported'`, and so is a driver not on the vendor's own host (a `baseURL` other than `api.anthropic.com`, or `compatibleEndpoint: true`). New exports `supportsFastMode`, `resolveFastModeVerdict`, `FAST_MODE_BETA`; new option `AnthropicConfig.clock`.
|
|
22
|
+
|
|
23
|
+
`@namzu/sdk` (minor): `ChatCompletionParams.speed`, `TurnConfig.speed`, `AgentConfig.speed` and `TokenUsage.speed`; `ModelPricing.fastMultiplier` (2 on the five fast-capable Anthropic rows) is applied to a fast call, and a fast call on a card without one is reported as unpriced rather than at the standard rate; `ProviderCapabilities.maxRequestRichContentBytes` lets a provider declare its budget (a fallback chain takes its smallest member's). Nothing changes for a provider that declares nothing, which keeps 24 MiB; `maxRequestRichContentBytes` still overrides.
|
|
24
|
+
|
|
25
|
+
`@namzu/cli` (minor): `--fast` and `/fast [on|off]`, off by default and never saved, shown as `fast` in the footer, turned off with a message when a model change cannot keep it, and refused on a custom or compatible `ANTHROPIC_BASE_URL`. A `/model` pick made while a reply runs that cannot keep fast mode waits for the reply to end instead of applying live.
|
|
26
|
+
|
|
3
27
|
## 6.8.1
|
|
4
28
|
|
|
5
29
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -52,12 +52,12 @@ registerAnthropic()
|
|
|
52
52
|
const { provider } = ProviderRegistry.create({
|
|
53
53
|
type: 'anthropic',
|
|
54
54
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
55
|
-
model: 'claude-sonnet-
|
|
55
|
+
model: 'claude-sonnet-5-5',
|
|
56
56
|
})
|
|
57
57
|
|
|
58
58
|
const response = await collectChatCompletion(
|
|
59
59
|
provider.chatStream({
|
|
60
|
-
model: 'claude-sonnet-
|
|
60
|
+
model: 'claude-sonnet-5-5',
|
|
61
61
|
messages: [{ role: 'user', content: 'Hello' }],
|
|
62
62
|
}),
|
|
63
63
|
)
|
|
@@ -97,6 +97,31 @@ or an empty response it returns `OFFLINE_MODEL_CATALOGUE`. Those fallback rows
|
|
|
97
97
|
are known model definitions, not evidence of current credential or account
|
|
98
98
|
access. The CLI's desktop catalogue uses the strict method.
|
|
99
99
|
|
|
100
|
+
The offline menu offers current models only: `claude-sonnet-5-5`,
|
|
101
|
+
`claude-opus-4-8` and `claude-haiku-4-5`. A model the vendor has retired
|
|
102
|
+
(`claude-opus-4-1-20250805`) is not offered, and `claude-sonnet-4-5-20250929`,
|
|
103
|
+
announced for retirement on 2026-11-30, is no longer recommended; naming it still
|
|
104
|
+
works until the vendor stops serving it.
|
|
105
|
+
|
|
106
|
+
## Paused server tools
|
|
107
|
+
|
|
108
|
+
When a server tool such as hosted search stops a response with `pause_turn`,
|
|
109
|
+
`chatStream` sends the content received so far, unchanged, as the last assistant
|
|
110
|
+
message and continues, up to five times, as one turn: one finish, usage added
|
|
111
|
+
up. A turn still paused after that fails with a `server` provider error.
|
|
112
|
+
|
|
113
|
+
## Cache diagnostics
|
|
114
|
+
|
|
115
|
+
On the vendor's own host the driver sends `diagnostics: { previous_message_id }`
|
|
116
|
+
(`null` on a conversation's first request) and reads the response's
|
|
117
|
+
`cache_miss_reason` into `TokenUsage.cacheMiss`. It sends nothing to a
|
|
118
|
+
compatible or third-party endpoint.
|
|
119
|
+
|
|
120
|
+
## Usage fields
|
|
121
|
+
|
|
122
|
+
`TokenUsage` also carries `webSearchRequests` (from `server_tool_use`),
|
|
123
|
+
`serviceTier` and `inferenceGeo` when the response reports them.
|
|
124
|
+
|
|
100
125
|
## Documentation
|
|
101
126
|
|
|
102
127
|
- [Namzu docs](https://github.com/cogitave/namzu/tree/main/docs)
|
|
@@ -160,3 +185,57 @@ const toolChoice = acceptsForcedToolChoice('claude-opus-5-5') ? 'required' : 'au
|
|
|
160
185
|
|
|
161
186
|
Pass the thinking configuration you will send as the second argument; the
|
|
162
187
|
answer comes from the same resolution the request uses.
|
|
188
|
+
|
|
189
|
+
## Fast mode
|
|
190
|
+
|
|
191
|
+
`speed: 'fast'` (on `ChatCompletionParams`, or `turnConfig.speed` for a turn) asks
|
|
192
|
+
for the vendor's fast mode: faster replies at twice the standard rates, on the
|
|
193
|
+
full context window. The driver sends it as the top-level `speed: "fast"` field
|
|
194
|
+
and only to models the vendor documents it on; `'standard'` and an absent value
|
|
195
|
+
are the same request and send nothing.
|
|
196
|
+
|
|
197
|
+
| Model | Beta header |
|
|
198
|
+
| --- | --- |
|
|
199
|
+
| Claude Opus 5.5 and later Opus, Fable 5.2 and later Fable, Mythos 5.2 and later Mythos | none |
|
|
200
|
+
| Claude Opus 5 (research preview, needs account access) | `fast-mode-2026-02-01` |
|
|
201
|
+
| Claude Opus 4.8 (research preview, until 2026-11-30) | `fast-mode-2026-02-01` |
|
|
202
|
+
|
|
203
|
+
Any other model, and Opus 4.8 from 2026-11-30, is refused before sending with a
|
|
204
|
+
`bad_request` `ProviderRequestError` whose `providerCode` is
|
|
205
|
+
`fast_mode_unsupported`; the Opus 4.8 message names `claude-opus-5-5`. A
|
|
206
|
+
driver that is not on the vendor's own host (`compatibleEndpoint: true`, or a
|
|
207
|
+
`baseURL` other than `api.anthropic.com`, such as a gateway, Microsoft Foundry
|
|
208
|
+
or Bedrock) is refused too: those platforms do not take `speed`, or sell fast
|
|
209
|
+
variants as separate model ids. `speed` is a per-turn setting, so a turn that
|
|
210
|
+
switches models mid-way (or falls back to another model) and lands on one
|
|
211
|
+
without fast mode fails with the same error; it is not dropped quietly.
|
|
212
|
+
The refusal is local because the vendor either errors or, on Opus 4.6, quietly
|
|
213
|
+
serves standard speed while the caller believes otherwise. The removal date is
|
|
214
|
+
read from `AnthropicConfig.clock` (default `Date.now`). The beta header is
|
|
215
|
+
added to the headers the client already sends, never in place of them.
|
|
216
|
+
|
|
217
|
+
`usage.speed` on the response reaches `TokenUsage.speed`, and the SDK prices a
|
|
218
|
+
`'fast'` call at the catalogue's `fastMultiplier` (2 on the five models above).
|
|
219
|
+
A model with no multiplier reports a fast call as unpriced, not as standard.
|
|
220
|
+
Fast mode has its own rate limit, and its prompt cache is separate from standard
|
|
221
|
+
speed: dropping `speed` after a 429 is a cache miss.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import { supportsFastMode } from '@namzu/anthropic'
|
|
225
|
+
|
|
226
|
+
const speed = supportsFastMode('claude-opus-5-5') ? 'fast' : undefined
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Source: https://platform.claude.com/docs/en/build-with-claude/fast-mode
|
|
230
|
+
|
|
231
|
+
## Request size
|
|
232
|
+
|
|
233
|
+
The driver declares `ProviderCapabilities.maxRequestRichContentBytes` of 100 MiB
|
|
234
|
+
of base64 for the vendor's own endpoint: the first-party Messages limit is
|
|
235
|
+
128 MB, and the rest is headroom for the JSON envelope, text and tool schemas
|
|
236
|
+
(https://platform.claude.com/docs/en/api/overview). Behind any other `baseURL`
|
|
237
|
+
or with `compatibleEndpoint: true` it declares nothing and the SDK default of
|
|
238
|
+
24 MiB applies, because a gateway or partner platform has its own limit
|
|
239
|
+
(Amazon Bedrock 20 MB, Google-managed 30 MB). `turnConfig.maxRequestRichContentBytes`
|
|
240
|
+
overrides it. The vendor's per-image limit (10 MB of base64) is separate and
|
|
241
|
+
unchanged.
|
package/dist/client.d.ts
CHANGED
|
@@ -29,6 +29,17 @@ export declare class AnthropicProvider implements LLMProvider {
|
|
|
29
29
|
* the call does not cache at all, so no lifetime is claimed for it.
|
|
30
30
|
*/
|
|
31
31
|
private cacheTtlFor;
|
|
32
|
+
/**
|
|
33
|
+
* The last response id per conversation, so the next request can name it.
|
|
34
|
+
* A conversation is told apart by its first message with cache markers
|
|
35
|
+
* removed; this driver instance also serves compaction and review calls,
|
|
36
|
+
* and naming another conversation's response would report a miss that never
|
|
37
|
+
* happened. Bounded, oldest dropped.
|
|
38
|
+
*/
|
|
39
|
+
private readonly lastResponses;
|
|
40
|
+
private conversationKey;
|
|
41
|
+
private previousMessageFor;
|
|
42
|
+
private rememberResponse;
|
|
32
43
|
private buildCreateParams;
|
|
33
44
|
/**
|
|
34
45
|
* The SDK's `messages.create` is overloaded on the `stream` flag. We build
|
|
@@ -37,6 +48,13 @@ export declare class AnthropicProvider implements LLMProvider {
|
|
|
37
48
|
* that the translation layer bridges two type worlds.
|
|
38
49
|
*/
|
|
39
50
|
private createRaw;
|
|
51
|
+
/**
|
|
52
|
+
* The `anthropic-beta` value for this request when it needs one beyond the
|
|
53
|
+
* client's defaults. A per-request header REPLACES the default of the same
|
|
54
|
+
* name, so the defaults (the subscription betas, or the caller's own) are
|
|
55
|
+
* carried into it.
|
|
56
|
+
*/
|
|
57
|
+
private betaHeaderFor;
|
|
40
58
|
chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk>;
|
|
41
59
|
listModels(signal?: AbortSignal): Promise<ModelInfo[]>;
|
|
42
60
|
/** Actual Models API rows and errors, without the legacy offline menu fallback. */
|
|
@@ -106,6 +124,10 @@ export declare class AnthropicProvider implements LLMProvider {
|
|
|
106
124
|
* whether the keys in it match what a driver actually reports. Only a test
|
|
107
125
|
* that feeds real driver output through the real lookup can see it, and
|
|
108
126
|
* `__tests__/pricing-conformance.test.ts` is that test.
|
|
127
|
+
*
|
|
128
|
+
* A model the vendor has retired is not offered here, and one it has
|
|
129
|
+
* announced for retirement is not recommended: it still works until the
|
|
130
|
+
* vendor says otherwise, and an operator who names it keeps it.
|
|
109
131
|
*/
|
|
110
132
|
export declare const OFFLINE_MODEL_CATALOGUE: readonly ModelInfo[];
|
|
111
133
|
//# sourceMappingURL=client.d.ts.map
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,EAGpB,eAAe,EACf,WAAW,EACX,cAAc,EAId,MAAM,YAAY,CAAA;
|
|
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,EAGpB,eAAe,EACf,WAAW,EACX,cAAc,EAId,MAAM,YAAY,CAAA;AAuBnB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AA8BjD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAOrE;AA0/BD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,EAAE,oBAgBpC,CAAA;AAcD,qBAAa,iBAAkB,YAAW,WAAW;IACpD,QAAQ,CAAC,EAAE,eAAc;IACzB,QAAQ,CAAC,IAAI,eAAc;IAC3B,QAAQ,CAAC,YAAY,EAAE,oBAAoB,CAAA;IAE3C,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,MAAM,CAAiB;gBAEnB,MAAM,EAAE,eAAe;IAqDnC,OAAO,CAAC,YAAY;IAUpB,0BAA0B,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO;IAW3E;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAKnB;;;;;;OAMG;IACH,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA4B;IAE1D,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,gBAAgB;IAUxB,OAAO,CAAC,iBAAiB;IA2IzB;;;;;OAKG;IACH,OAAO,CAAC,SAAS;IAkBjB;;;;;OAKG;IACH,OAAO,CAAC,aAAa;IAcd,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IA0crE,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAW5D,mFAAmF;IAC7E,gBAAgB,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAkDlE;;;;;;;;;;OAUG;IACG,eAAe,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB1D,OAAO,CAAC,WAAW;IASb,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAOrC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,aAAa;IAMrB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,SAAS,eAAe,EAAE;IAMrF,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,SAAS,eAAe,EAAE;IAI9F;;;;OAIG;IACH,0BAA0B,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,OAAO;IAI7E;;;;;;;OAOG;IACG,kBAAkB,CACvB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE;QAAE,gBAAgB,CAAC,EAAE,MAAM,CAAA;KAAE,EACtC,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;CAa9B;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,uBAAuB,EAAE,SAAS,SAAS,EA6BvD,CAAA"}
|
package/dist/client.js
CHANGED
|
@@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process';
|
|
|
2
2
|
import Anthropic from '@anthropic-ai/sdk';
|
|
3
3
|
import { ProviderRequestError, assertStrictSchema, isCallerAbortError, isProviderRequestError, modelVersionAtLeast, providerVendorError, toSchemaDialect, toolResultToText, } from '@namzu/sdk';
|
|
4
4
|
import { attributionHeaders } from '@namzu/sdk';
|
|
5
|
+
import { assertFastModeAccepted, fastModeBeta } from './fast-mode.js';
|
|
5
6
|
import { refusalFallbackFromList } from './refusal-fallback.js';
|
|
6
7
|
import { SearchBlocks, restoreSearch } from './search-replay.js';
|
|
7
8
|
import { COMPATIBLE_ENDPOINT, MODEL_ID_GRAMMAR, resolveEffort, resolveThinkingBody, resolveThinkingCapability, } from './thinking-capability.js';
|
|
@@ -15,6 +16,12 @@ import { assertForcedToolChoiceAccepted, forcedToolChoiceAccepted } from './tool
|
|
|
15
16
|
// ceiling, so passing 64k just means "don't bound below the model".
|
|
16
17
|
const DEFAULT_MAX_TOKENS = 64_000;
|
|
17
18
|
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
19
|
+
/**
|
|
20
|
+
* How many times one turn is resumed after the service pauses a server tool,
|
|
21
|
+
* before it is reported unfinished. The service's own limit per request is ten
|
|
22
|
+
* sampling iterations, so five resumptions is generous and still bounded.
|
|
23
|
+
*/
|
|
24
|
+
const MAX_PAUSE_CONTINUATIONS = 5;
|
|
18
25
|
const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 0;
|
|
19
26
|
// Claude Code OAuth tokens are scoped to Claude Code usage. Anthropic
|
|
20
27
|
// authorizes them only when three signals are all present, else 401:
|
|
@@ -524,6 +531,64 @@ function applyMessageCacheBreakpoint(messages, cacheEnd, ttl) {
|
|
|
524
531
|
}
|
|
525
532
|
}
|
|
526
533
|
}
|
|
534
|
+
/** The miss the service explained, or nothing: a hit and a pending answer say no miss. */
|
|
535
|
+
function parseCacheMiss(raw) {
|
|
536
|
+
const reason = raw?.cache_miss_reason;
|
|
537
|
+
if (!reason || typeof reason.type !== 'string' || reason.type.length === 0)
|
|
538
|
+
return undefined;
|
|
539
|
+
return {
|
|
540
|
+
reason: reason.type,
|
|
541
|
+
...(typeof reason.cache_missed_input_tokens === 'number'
|
|
542
|
+
? { missedTokens: reason.cache_missed_input_tokens }
|
|
543
|
+
: {}),
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
/** Frames of one request are cumulative: the larger of each count is the request's own. */
|
|
547
|
+
function highWater(current, next) {
|
|
548
|
+
if (!current)
|
|
549
|
+
return next;
|
|
550
|
+
const promptTokens = Math.max(current.promptTokens, next.promptTokens);
|
|
551
|
+
const completionTokens = Math.max(current.completionTokens, next.completionTokens);
|
|
552
|
+
const reasoning = Math.max(current.reasoningTokens ?? 0, next.reasoningTokens ?? 0);
|
|
553
|
+
const searches = Math.max(current.webSearchRequests ?? 0, next.webSearchRequests ?? 0);
|
|
554
|
+
return {
|
|
555
|
+
...current,
|
|
556
|
+
...next,
|
|
557
|
+
promptTokens,
|
|
558
|
+
completionTokens,
|
|
559
|
+
totalTokens: promptTokens + completionTokens,
|
|
560
|
+
cachedTokens: Math.max(current.cachedTokens, next.cachedTokens),
|
|
561
|
+
cacheWriteTokens: Math.max(current.cacheWriteTokens, next.cacheWriteTokens),
|
|
562
|
+
...(current.reasoningTokens !== undefined || next.reasoningTokens !== undefined
|
|
563
|
+
? { reasoningTokens: reasoning }
|
|
564
|
+
: {}),
|
|
565
|
+
...(current.webSearchRequests !== undefined || next.webSearchRequests !== undefined
|
|
566
|
+
? { webSearchRequests: searches }
|
|
567
|
+
: {}),
|
|
568
|
+
...(next.cacheMiss === undefined && current.cacheMiss !== undefined
|
|
569
|
+
? { cacheMiss: current.cacheMiss }
|
|
570
|
+
: {}),
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
/** What a paused turn's earlier requests already spent, added under the one now running. */
|
|
574
|
+
function addUsage(base, request) {
|
|
575
|
+
if (!base)
|
|
576
|
+
return request;
|
|
577
|
+
return {
|
|
578
|
+
...request,
|
|
579
|
+
promptTokens: base.promptTokens + request.promptTokens,
|
|
580
|
+
completionTokens: base.completionTokens + request.completionTokens,
|
|
581
|
+
totalTokens: base.totalTokens + request.totalTokens,
|
|
582
|
+
cachedTokens: base.cachedTokens + request.cachedTokens,
|
|
583
|
+
cacheWriteTokens: base.cacheWriteTokens + request.cacheWriteTokens,
|
|
584
|
+
...(base.reasoningTokens !== undefined || request.reasoningTokens !== undefined
|
|
585
|
+
? { reasoningTokens: (base.reasoningTokens ?? 0) + (request.reasoningTokens ?? 0) }
|
|
586
|
+
: {}),
|
|
587
|
+
...(base.webSearchRequests !== undefined || request.webSearchRequests !== undefined
|
|
588
|
+
? { webSearchRequests: (base.webSearchRequests ?? 0) + (request.webSearchRequests ?? 0) }
|
|
589
|
+
: {}),
|
|
590
|
+
};
|
|
591
|
+
}
|
|
527
592
|
function emptyUsage() {
|
|
528
593
|
return {
|
|
529
594
|
promptTokens: 0,
|
|
@@ -538,7 +603,7 @@ function emptyUsage() {
|
|
|
538
603
|
* the response carries no per-lifetime breakdown. The breakdown wins because
|
|
539
604
|
* the service may write a shorter-lived entry than the one asked for.
|
|
540
605
|
*/
|
|
541
|
-
function parseUsage(raw, requestedTtl) {
|
|
606
|
+
function parseUsage(raw, requestedTtl, requestedSpeed, diagnostics) {
|
|
542
607
|
if (!raw)
|
|
543
608
|
return emptyUsage();
|
|
544
609
|
const written5m = raw.cache_creation?.ephemeral_5m_input_tokens ?? 0;
|
|
@@ -566,6 +631,24 @@ function parseUsage(raw, requestedTtl) {
|
|
|
566
631
|
// about every streamed event before the last one.
|
|
567
632
|
...(thinking !== undefined ? { reasoningTokens: thinking } : {}),
|
|
568
633
|
...(cacheTtlMs !== undefined ? { cacheTtlMs } : {}),
|
|
634
|
+
// What the response says served the call; when it says nothing, what was
|
|
635
|
+
// asked for, because fast is the expensive answer and an unreported
|
|
636
|
+
// speed must not price as standard.
|
|
637
|
+
...(raw.speed === 'fast' || raw.speed === 'standard'
|
|
638
|
+
? { speed: raw.speed }
|
|
639
|
+
: requestedSpeed !== undefined
|
|
640
|
+
? { speed: requestedSpeed }
|
|
641
|
+
: {}),
|
|
642
|
+
...(typeof raw.server_tool_use?.web_search_requests === 'number'
|
|
643
|
+
? { webSearchRequests: raw.server_tool_use.web_search_requests }
|
|
644
|
+
: {}),
|
|
645
|
+
...(typeof raw.service_tier === 'string' && raw.service_tier.length > 0
|
|
646
|
+
? { serviceTier: raw.service_tier }
|
|
647
|
+
: {}),
|
|
648
|
+
...(typeof raw.inference_geo === 'string' && raw.inference_geo.length > 0
|
|
649
|
+
? { inferenceGeo: raw.inference_geo }
|
|
650
|
+
: {}),
|
|
651
|
+
...(parseCacheMiss(diagnostics) ? { cacheMiss: parseCacheMiss(diagnostics) } : {}),
|
|
569
652
|
...(raw.cache_creation
|
|
570
653
|
? {
|
|
571
654
|
cacheWriteTtlTokens: {
|
|
@@ -690,11 +773,27 @@ export const ANTHROPIC_CAPABILITIES = {
|
|
|
690
773
|
supportsToolResultImages: true,
|
|
691
774
|
supportsToolResultDocuments: false,
|
|
692
775
|
cacheTtl: ['5m', '1h'],
|
|
776
|
+
// The first-party Messages limit is 128 MB (raised from 32 MB on 2026-10-28;
|
|
777
|
+
// https://platform.claude.com/docs/en/api/overview). 100 MiB of base64
|
|
778
|
+
// leaves headroom for the JSON envelope, text and tool schemas. A driver
|
|
779
|
+
// pointed anywhere else does not claim it: see the constructor.
|
|
780
|
+
maxRequestRichContentBytes: 100 * 1024 * 1024,
|
|
693
781
|
};
|
|
782
|
+
/** The request rich-content budget only the vendor's own endpoint is known to take. */
|
|
783
|
+
function capabilitiesFor(config) {
|
|
784
|
+
if (config.compatibleEndpoint !== true && isVendorEndpoint(config.baseURL)) {
|
|
785
|
+
return ANTHROPIC_CAPABILITIES;
|
|
786
|
+
}
|
|
787
|
+
// A gateway, proxy or partner platform (Bedrock accepts 20 MB, Google-managed
|
|
788
|
+
// 30 MB, https://platform.claude.com/docs/en/api/overview) has its own limit
|
|
789
|
+
// this driver cannot read from a base URL, so it keeps the kernel default.
|
|
790
|
+
const { maxRequestRichContentBytes: _first, ...rest } = ANTHROPIC_CAPABILITIES;
|
|
791
|
+
return rest;
|
|
792
|
+
}
|
|
694
793
|
export class AnthropicProvider {
|
|
695
794
|
id = 'anthropic';
|
|
696
795
|
name = 'Anthropic';
|
|
697
|
-
capabilities
|
|
796
|
+
capabilities;
|
|
698
797
|
client;
|
|
699
798
|
config;
|
|
700
799
|
constructor(config) {
|
|
@@ -705,6 +804,7 @@ export class AnthropicProvider {
|
|
|
705
804
|
(!Number.isSafeInteger(config.maxRetries) || config.maxRetries < 0))
|
|
706
805
|
throw new Error('maxRetries must be a nonnegative integer.');
|
|
707
806
|
this.config = config;
|
|
807
|
+
this.capabilities = capabilitiesFor(config);
|
|
708
808
|
const clientOpts = {
|
|
709
809
|
timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,
|
|
710
810
|
maxRetries: config.maxRetries ?? 0,
|
|
@@ -770,6 +870,30 @@ export class AnthropicProvider {
|
|
|
770
870
|
return undefined;
|
|
771
871
|
return params.cacheControl.ttl ?? this.config.promptCacheTtl ?? '5m';
|
|
772
872
|
}
|
|
873
|
+
/**
|
|
874
|
+
* The last response id per conversation, so the next request can name it.
|
|
875
|
+
* A conversation is told apart by its first message with cache markers
|
|
876
|
+
* removed; this driver instance also serves compaction and review calls,
|
|
877
|
+
* and naming another conversation's response would report a miss that never
|
|
878
|
+
* happened. Bounded, oldest dropped.
|
|
879
|
+
*/
|
|
880
|
+
lastResponses = new Map();
|
|
881
|
+
conversationKey(messages) {
|
|
882
|
+
return JSON.stringify(messages[0] ?? null, (key, value) => key === 'cache_control' ? undefined : value);
|
|
883
|
+
}
|
|
884
|
+
previousMessageFor(messages) {
|
|
885
|
+
return this.lastResponses.get(this.conversationKey(messages));
|
|
886
|
+
}
|
|
887
|
+
rememberResponse(messages, id) {
|
|
888
|
+
const key = this.conversationKey(messages);
|
|
889
|
+
this.lastResponses.delete(key);
|
|
890
|
+
this.lastResponses.set(key, id);
|
|
891
|
+
if (this.lastResponses.size > 32) {
|
|
892
|
+
const oldest = this.lastResponses.keys().next().value;
|
|
893
|
+
if (oldest !== undefined)
|
|
894
|
+
this.lastResponses.delete(oldest);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
773
897
|
buildCreateParams(params, stream) {
|
|
774
898
|
// The runtime requests caching via `params.cacheControl` on every
|
|
775
899
|
// iteration. Honoring it costs three of the four allowed breakpoints:
|
|
@@ -867,6 +991,22 @@ export class AnthropicProvider {
|
|
|
867
991
|
}
|
|
868
992
|
if (Object.keys(outputConfig).length)
|
|
869
993
|
body.output_config = outputConfig;
|
|
994
|
+
// Only 'fast' is a wire value: 'standard' is what an absent field means.
|
|
995
|
+
// Admission is decided locally, before transport, because the vendor
|
|
996
|
+
// either errors (removed or unsupported models) or, on Opus 4.6, quietly
|
|
997
|
+
// serves standard speed while the caller believes otherwise.
|
|
998
|
+
if (params.speed === 'fast') {
|
|
999
|
+
assertFastModeAccepted(model, (this.config.clock ?? Date.now)(), this.config.compatibleEndpoint !== true && isVendorEndpoint(this.config.baseURL));
|
|
1000
|
+
body.speed = 'fast';
|
|
1001
|
+
}
|
|
1002
|
+
// Cache diagnostics ask the service to say why a prefix it had stopped
|
|
1003
|
+
// being served from cache. First-party only: the field is documented for
|
|
1004
|
+
// the Claude API, not for Bedrock, Vertex or a compatible server, which
|
|
1005
|
+
// may reject an unknown field. `null` opts in on a conversation's first
|
|
1006
|
+
// request, and later ones name the response they continue.
|
|
1007
|
+
if (this.config.compatibleEndpoint !== true && isVendorEndpoint(this.config.baseURL)) {
|
|
1008
|
+
body.diagnostics = { previous_message_id: this.previousMessageFor(messages) ?? null };
|
|
1009
|
+
}
|
|
870
1010
|
if (params.temperature !== undefined)
|
|
871
1011
|
body.temperature = params.temperature;
|
|
872
1012
|
if (params.topP !== undefined)
|
|
@@ -885,34 +1025,75 @@ export class AnthropicProvider {
|
|
|
885
1025
|
*/
|
|
886
1026
|
createRaw(body, opts) {
|
|
887
1027
|
const create = this.client.messages.create;
|
|
1028
|
+
const beta = this.betaHeaderFor(body);
|
|
888
1029
|
// Pass the caller AbortSignal as the SDK's per-request RequestOptions so
|
|
889
1030
|
// aborting it tears down the in-flight HTTP/2 SSE request (rejects with
|
|
890
1031
|
// APIUserAbortError). A non-aborted signal is identical to omitting it.
|
|
891
|
-
return create.call(this.client.messages, body, {
|
|
1032
|
+
return create.call(this.client.messages, body, {
|
|
1033
|
+
signal: opts?.signal,
|
|
1034
|
+
...(beta ? { headers: { 'anthropic-beta': beta } } : {}),
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* The `anthropic-beta` value for this request when it needs one beyond the
|
|
1039
|
+
* client's defaults. A per-request header REPLACES the default of the same
|
|
1040
|
+
* name, so the defaults (the subscription betas, or the caller's own) are
|
|
1041
|
+
* carried into it.
|
|
1042
|
+
*/
|
|
1043
|
+
betaHeaderFor(body) {
|
|
1044
|
+
if (body.speed !== 'fast')
|
|
1045
|
+
return undefined;
|
|
1046
|
+
const extra = fastModeBeta(String(body.model));
|
|
1047
|
+
if (extra === undefined)
|
|
1048
|
+
return undefined;
|
|
1049
|
+
const configured = Object.entries(this.config.defaultHeaders ?? {}).find(([name]) => name.toLowerCase() === 'anthropic-beta')?.[1];
|
|
1050
|
+
const base = this.config.authToken && this.config.compatibleEndpoint !== true
|
|
1051
|
+
? (configured ?? OAUTH_BETAS)
|
|
1052
|
+
: configured;
|
|
1053
|
+
return [base, extra].filter(Boolean).join(',');
|
|
892
1054
|
}
|
|
893
1055
|
async *chatStream(params) {
|
|
894
1056
|
const providerRoute = resolveAnthropicRoute(this.resolveModel(params), params.providerRoute);
|
|
895
1057
|
const createParams = this.buildCreateParams(params, true);
|
|
1058
|
+
const requestedSpeed = createParams.speed === 'fast' ? 'fast' : undefined;
|
|
896
1059
|
const signal = params.signal;
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1060
|
+
const open = async (body) => {
|
|
1061
|
+
try {
|
|
1062
|
+
return (await this.createRaw(body, {
|
|
1063
|
+
signal,
|
|
1064
|
+
}));
|
|
1065
|
+
}
|
|
1066
|
+
catch (err) {
|
|
1067
|
+
// The vendor SDK builds its error message FROM the response body, so a
|
|
1068
|
+
// credential the upstream echoed back is already inside `err.message`
|
|
1069
|
+
// before this code runs (proven with a planted fake token). Classify from
|
|
1070
|
+
// the status and drop the vendor error entirely — no re-throw, no
|
|
1071
|
+
// `cause`, because a `cause` is exactly what a structured logger walks.
|
|
1072
|
+
if (isCallerAbortError(err, signal))
|
|
1073
|
+
throw signal?.reason ?? err;
|
|
1074
|
+
if (isProviderRequestError(err))
|
|
1075
|
+
throw err;
|
|
1076
|
+
throw providerVendorError({ providerId: 'anthropic', error: err });
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
const stream = await open(createParams);
|
|
1080
|
+
// A server tool (hosted search) can stop a response with `pause_turn`
|
|
1081
|
+
// before the answer exists. The documented way on is to send what came
|
|
1082
|
+
// back, unchanged, as the last assistant message and ask again. The
|
|
1083
|
+
// continuations are part of one turn to the caller: indices keep
|
|
1084
|
+
// counting up, usage adds up, and the finish arrives once.
|
|
1085
|
+
let paused = false;
|
|
1086
|
+
let pauses = 0;
|
|
1087
|
+
let indexOffset = 0;
|
|
1088
|
+
let maxIndex = -1;
|
|
1089
|
+
let spent;
|
|
1090
|
+
let current;
|
|
1091
|
+
const usageOf = (raw, ttl, diagnostics) => {
|
|
1092
|
+
current = highWater(current, parseUsage(raw, ttl, requestedSpeed, diagnostics));
|
|
1093
|
+
return addUsage(spent, current);
|
|
1094
|
+
};
|
|
915
1095
|
let messageId = '';
|
|
1096
|
+
let responseId = '';
|
|
916
1097
|
// Track active tool-use blocks by content_block index so input_json_delta
|
|
917
1098
|
// fragments can reference the right tool call.
|
|
918
1099
|
const activeTools = new Map();
|
|
@@ -953,7 +1134,7 @@ export class AnthropicProvider {
|
|
|
953
1134
|
// `streamIdleTimeoutMs`; otherwise the request timeout and caller
|
|
954
1135
|
// AbortSignal own lifecycle cancellation.
|
|
955
1136
|
const streamIdleTimeoutMs = this.config.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS;
|
|
956
|
-
|
|
1137
|
+
let iter = stream[Symbol.asyncIterator]();
|
|
957
1138
|
const nextWithIdleTimeout = async () => {
|
|
958
1139
|
if (!Number.isFinite(streamIdleTimeoutMs) || streamIdleTimeoutMs <= 0) {
|
|
959
1140
|
return iter.next();
|
|
@@ -986,17 +1167,24 @@ export class AnthropicProvider {
|
|
|
986
1167
|
const result = await nextWithIdleTimeout();
|
|
987
1168
|
if (result.done)
|
|
988
1169
|
break;
|
|
989
|
-
const event = result.value
|
|
1170
|
+
const event = indexOffset > 0 && typeof result.value.index === 'number'
|
|
1171
|
+
? { ...result.value, index: result.value.index + indexOffset }
|
|
1172
|
+
: result.value;
|
|
1173
|
+
if (typeof event.index === 'number')
|
|
1174
|
+
maxIndex = Math.max(maxIndex, event.index);
|
|
990
1175
|
try {
|
|
991
1176
|
switch (event.type) {
|
|
992
1177
|
case 'message_start': {
|
|
993
|
-
if (event.message?.id)
|
|
994
|
-
messageId
|
|
1178
|
+
if (event.message?.id) {
|
|
1179
|
+
if (!messageId)
|
|
1180
|
+
messageId = event.message.id;
|
|
1181
|
+
responseId = event.message.id;
|
|
1182
|
+
}
|
|
995
1183
|
if (event.message?.usage) {
|
|
996
1184
|
yield {
|
|
997
1185
|
id: messageId,
|
|
998
1186
|
delta: {},
|
|
999
|
-
usage:
|
|
1187
|
+
usage: usageOf(event.message.usage, this.cacheTtlFor(params), event.message.diagnostics),
|
|
1000
1188
|
};
|
|
1001
1189
|
}
|
|
1002
1190
|
break;
|
|
@@ -1192,8 +1380,19 @@ export class AnthropicProvider {
|
|
|
1192
1380
|
}
|
|
1193
1381
|
case 'message_delta': {
|
|
1194
1382
|
if (event.delta?.stop_reason) {
|
|
1195
|
-
if (event.delta.stop_reason === 'pause_turn')
|
|
1196
|
-
|
|
1383
|
+
if (event.delta.stop_reason === 'pause_turn') {
|
|
1384
|
+
if (pauses >= MAX_PAUSE_CONTINUATIONS)
|
|
1385
|
+
throw new ProviderRequestError({
|
|
1386
|
+
kind: 'server',
|
|
1387
|
+
providerId: 'anthropic',
|
|
1388
|
+
detail: `the hosted search was still paused after ${MAX_PAUSE_CONTINUATIONS} continuations, so the answer is unfinished`,
|
|
1389
|
+
});
|
|
1390
|
+
paused = true;
|
|
1391
|
+
if (event.usage) {
|
|
1392
|
+
yield { id: messageId, delta: {}, usage: usageOf(event.usage) };
|
|
1393
|
+
}
|
|
1394
|
+
break;
|
|
1395
|
+
}
|
|
1197
1396
|
const search = searchBlocks.complete(providerRoute);
|
|
1198
1397
|
// The sources list is the driver's text, not the model's: it
|
|
1199
1398
|
// must not read as the model moving on from a tool call the
|
|
@@ -1212,19 +1411,44 @@ export class AnthropicProvider {
|
|
|
1212
1411
|
finishReason: mapStopReason(event.delta.stop_reason),
|
|
1213
1412
|
...finishDetail(event.delta.stop_reason),
|
|
1214
1413
|
...refusalDetails(event.delta.stop_reason, event.delta.stop_details ?? event.stop_details),
|
|
1215
|
-
usage: event.usage ?
|
|
1414
|
+
usage: event.usage ? usageOf(event.usage) : undefined,
|
|
1216
1415
|
};
|
|
1217
1416
|
}
|
|
1218
1417
|
else if (event.usage) {
|
|
1219
1418
|
yield {
|
|
1220
1419
|
id: messageId,
|
|
1221
1420
|
delta: {},
|
|
1222
|
-
usage:
|
|
1421
|
+
usage: usageOf(event.usage),
|
|
1223
1422
|
};
|
|
1224
1423
|
}
|
|
1225
1424
|
break;
|
|
1226
1425
|
}
|
|
1227
1426
|
case 'message_stop': {
|
|
1427
|
+
if (paused) {
|
|
1428
|
+
paused = false;
|
|
1429
|
+
pauses++;
|
|
1430
|
+
if (current)
|
|
1431
|
+
spent = addUsage(spent, current);
|
|
1432
|
+
current = undefined;
|
|
1433
|
+
indexOffset = maxIndex + 1;
|
|
1434
|
+
const next = {
|
|
1435
|
+
...createParams,
|
|
1436
|
+
messages: [
|
|
1437
|
+
...createParams.messages,
|
|
1438
|
+
{ role: 'assistant', content: searchBlocks.content() },
|
|
1439
|
+
],
|
|
1440
|
+
};
|
|
1441
|
+
if (next.diagnostics !== undefined) {
|
|
1442
|
+
next.diagnostics = { previous_message_id: responseId || null };
|
|
1443
|
+
}
|
|
1444
|
+
await iter.return?.().catch(() => undefined);
|
|
1445
|
+
iter = (await open(next))[Symbol.asyncIterator]();
|
|
1446
|
+
break;
|
|
1447
|
+
}
|
|
1448
|
+
// Only a whole, final response is named by the next request;
|
|
1449
|
+
// an aborted or failed one never reaches this point.
|
|
1450
|
+
if (responseId)
|
|
1451
|
+
this.rememberResponse(createParams.messages, responseId);
|
|
1228
1452
|
if (searchReplayEmitted)
|
|
1229
1453
|
return;
|
|
1230
1454
|
const search = searchBlocks.complete(providerRoute);
|
|
@@ -1464,25 +1688,27 @@ export class AnthropicProvider {
|
|
|
1464
1688
|
* whether the keys in it match what a driver actually reports. Only a test
|
|
1465
1689
|
* that feeds real driver output through the real lookup can see it, and
|
|
1466
1690
|
* `__tests__/pricing-conformance.test.ts` is that test.
|
|
1691
|
+
*
|
|
1692
|
+
* A model the vendor has retired is not offered here, and one it has
|
|
1693
|
+
* announced for retirement is not recommended: it still works until the
|
|
1694
|
+
* vendor says otherwise, and an operator who names it keeps it.
|
|
1467
1695
|
*/
|
|
1468
1696
|
export const OFFLINE_MODEL_CATALOGUE = [
|
|
1469
1697
|
{
|
|
1470
|
-
id: 'claude-sonnet-
|
|
1471
|
-
name: 'Claude Sonnet
|
|
1472
|
-
contextWindow:
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
outputPrice: 15.0,
|
|
1698
|
+
id: 'claude-sonnet-5-5',
|
|
1699
|
+
name: 'Claude Sonnet 5.5',
|
|
1700
|
+
contextWindow: 1_000_000,
|
|
1701
|
+
inputPrice: 2.0,
|
|
1702
|
+
outputPrice: 10.0,
|
|
1476
1703
|
supportsToolUse: true,
|
|
1477
1704
|
supportsStreaming: true,
|
|
1478
1705
|
},
|
|
1479
1706
|
{
|
|
1480
|
-
id: 'claude-opus-4-
|
|
1481
|
-
name: 'Claude Opus 4.
|
|
1482
|
-
contextWindow:
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
outputPrice: 75.0,
|
|
1707
|
+
id: 'claude-opus-4-8',
|
|
1708
|
+
name: 'Claude Opus 4.8',
|
|
1709
|
+
contextWindow: 1_000_000,
|
|
1710
|
+
inputPrice: 5.0,
|
|
1711
|
+
outputPrice: 25.0,
|
|
1486
1712
|
supportsToolUse: true,
|
|
1487
1713
|
supportsStreaming: true,
|
|
1488
1714
|
},
|