@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/src/client.ts
CHANGED
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
toolResultToText,
|
|
28
28
|
} from '@namzu/sdk'
|
|
29
29
|
import { attributionHeaders } from '@namzu/sdk'
|
|
30
|
+
import { assertFastModeAccepted, fastModeBeta } from './fast-mode.js'
|
|
30
31
|
import { refusalFallbackFromList } from './refusal-fallback.js'
|
|
31
32
|
import { SearchBlocks, restoreSearch } from './search-replay.js'
|
|
32
33
|
import {
|
|
@@ -48,6 +49,13 @@ import type { AnthropicConfig } from './types.js'
|
|
|
48
49
|
// ceiling, so passing 64k just means "don't bound below the model".
|
|
49
50
|
const DEFAULT_MAX_TOKENS = 64_000
|
|
50
51
|
const DEFAULT_TIMEOUT_MS = 120_000
|
|
52
|
+
/**
|
|
53
|
+
* How many times one turn is resumed after the service pauses a server tool,
|
|
54
|
+
* before it is reported unfinished. The service's own limit per request is ten
|
|
55
|
+
* sampling iterations, so five resumptions is generous and still bounded.
|
|
56
|
+
*/
|
|
57
|
+
const MAX_PAUSE_CONTINUATIONS = 5
|
|
58
|
+
|
|
51
59
|
const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 0
|
|
52
60
|
|
|
53
61
|
// Claude Code OAuth tokens are scoped to Claude Code usage. Anthropic
|
|
@@ -750,6 +758,11 @@ interface RawAnthropicUsage {
|
|
|
750
758
|
input_tokens?: number
|
|
751
759
|
output_tokens?: number
|
|
752
760
|
cache_read_input_tokens?: number | null
|
|
761
|
+
speed?: string | null
|
|
762
|
+
service_tier?: string | null
|
|
763
|
+
inference_geo?: string | null
|
|
764
|
+
/** Hosted-tool request counts, billed per request. */
|
|
765
|
+
server_tool_use?: { web_search_requests?: number | null } | null
|
|
753
766
|
cache_creation_input_tokens?: number | null
|
|
754
767
|
/** Cache-write tokens by lifetime, when the service breaks them down. */
|
|
755
768
|
cache_creation?: {
|
|
@@ -767,6 +780,74 @@ interface RawAnthropicUsage {
|
|
|
767
780
|
output_tokens_details?: { thinking_tokens?: number } | null
|
|
768
781
|
}
|
|
769
782
|
|
|
783
|
+
/**
|
|
784
|
+
* The `diagnostics` object on a response: `null`, `{ cache_miss_reason: null }`
|
|
785
|
+
* (not decided yet) or `{ cache_miss_reason: { type, cache_missed_input_tokens? } }`.
|
|
786
|
+
*/
|
|
787
|
+
type CacheMiss = NonNullable<TokenUsage['cacheMiss']>
|
|
788
|
+
|
|
789
|
+
interface RawCacheDiagnostics {
|
|
790
|
+
cache_miss_reason?: { type?: string; cache_missed_input_tokens?: number | null } | null
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** The miss the service explained, or nothing: a hit and a pending answer say no miss. */
|
|
794
|
+
function parseCacheMiss(raw: RawCacheDiagnostics | null | undefined): CacheMiss | undefined {
|
|
795
|
+
const reason = raw?.cache_miss_reason
|
|
796
|
+
if (!reason || typeof reason.type !== 'string' || reason.type.length === 0) return undefined
|
|
797
|
+
return {
|
|
798
|
+
reason: reason.type,
|
|
799
|
+
...(typeof reason.cache_missed_input_tokens === 'number'
|
|
800
|
+
? { missedTokens: reason.cache_missed_input_tokens }
|
|
801
|
+
: {}),
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** Frames of one request are cumulative: the larger of each count is the request's own. */
|
|
806
|
+
function highWater(current: TokenUsage | undefined, next: TokenUsage): TokenUsage {
|
|
807
|
+
if (!current) return next
|
|
808
|
+
const promptTokens = Math.max(current.promptTokens, next.promptTokens)
|
|
809
|
+
const completionTokens = Math.max(current.completionTokens, next.completionTokens)
|
|
810
|
+
const reasoning = Math.max(current.reasoningTokens ?? 0, next.reasoningTokens ?? 0)
|
|
811
|
+
const searches = Math.max(current.webSearchRequests ?? 0, next.webSearchRequests ?? 0)
|
|
812
|
+
return {
|
|
813
|
+
...current,
|
|
814
|
+
...next,
|
|
815
|
+
promptTokens,
|
|
816
|
+
completionTokens,
|
|
817
|
+
totalTokens: promptTokens + completionTokens,
|
|
818
|
+
cachedTokens: Math.max(current.cachedTokens, next.cachedTokens),
|
|
819
|
+
cacheWriteTokens: Math.max(current.cacheWriteTokens, next.cacheWriteTokens),
|
|
820
|
+
...(current.reasoningTokens !== undefined || next.reasoningTokens !== undefined
|
|
821
|
+
? { reasoningTokens: reasoning }
|
|
822
|
+
: {}),
|
|
823
|
+
...(current.webSearchRequests !== undefined || next.webSearchRequests !== undefined
|
|
824
|
+
? { webSearchRequests: searches }
|
|
825
|
+
: {}),
|
|
826
|
+
...(next.cacheMiss === undefined && current.cacheMiss !== undefined
|
|
827
|
+
? { cacheMiss: current.cacheMiss }
|
|
828
|
+
: {}),
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** What a paused turn's earlier requests already spent, added under the one now running. */
|
|
833
|
+
function addUsage(base: TokenUsage | undefined, request: TokenUsage): TokenUsage {
|
|
834
|
+
if (!base) return request
|
|
835
|
+
return {
|
|
836
|
+
...request,
|
|
837
|
+
promptTokens: base.promptTokens + request.promptTokens,
|
|
838
|
+
completionTokens: base.completionTokens + request.completionTokens,
|
|
839
|
+
totalTokens: base.totalTokens + request.totalTokens,
|
|
840
|
+
cachedTokens: base.cachedTokens + request.cachedTokens,
|
|
841
|
+
cacheWriteTokens: base.cacheWriteTokens + request.cacheWriteTokens,
|
|
842
|
+
...(base.reasoningTokens !== undefined || request.reasoningTokens !== undefined
|
|
843
|
+
? { reasoningTokens: (base.reasoningTokens ?? 0) + (request.reasoningTokens ?? 0) }
|
|
844
|
+
: {}),
|
|
845
|
+
...(base.webSearchRequests !== undefined || request.webSearchRequests !== undefined
|
|
846
|
+
? { webSearchRequests: (base.webSearchRequests ?? 0) + (request.webSearchRequests ?? 0) }
|
|
847
|
+
: {}),
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
770
851
|
function emptyUsage(): TokenUsage {
|
|
771
852
|
return {
|
|
772
853
|
promptTokens: 0,
|
|
@@ -782,7 +863,12 @@ function emptyUsage(): TokenUsage {
|
|
|
782
863
|
* the response carries no per-lifetime breakdown. The breakdown wins because
|
|
783
864
|
* the service may write a shorter-lived entry than the one asked for.
|
|
784
865
|
*/
|
|
785
|
-
function parseUsage(
|
|
866
|
+
function parseUsage(
|
|
867
|
+
raw?: RawAnthropicUsage,
|
|
868
|
+
requestedTtl?: '5m' | '1h',
|
|
869
|
+
requestedSpeed?: 'fast',
|
|
870
|
+
diagnostics?: RawCacheDiagnostics | null,
|
|
871
|
+
): TokenUsage {
|
|
786
872
|
if (!raw) return emptyUsage()
|
|
787
873
|
const written5m = raw.cache_creation?.ephemeral_5m_input_tokens ?? 0
|
|
788
874
|
const written1h = raw.cache_creation?.ephemeral_1h_input_tokens ?? 0
|
|
@@ -810,6 +896,24 @@ function parseUsage(raw?: RawAnthropicUsage, requestedTtl?: '5m' | '1h'): TokenU
|
|
|
810
896
|
// about every streamed event before the last one.
|
|
811
897
|
...(thinking !== undefined ? { reasoningTokens: thinking } : {}),
|
|
812
898
|
...(cacheTtlMs !== undefined ? { cacheTtlMs } : {}),
|
|
899
|
+
// What the response says served the call; when it says nothing, what was
|
|
900
|
+
// asked for, because fast is the expensive answer and an unreported
|
|
901
|
+
// speed must not price as standard.
|
|
902
|
+
...(raw.speed === 'fast' || raw.speed === 'standard'
|
|
903
|
+
? { speed: raw.speed }
|
|
904
|
+
: requestedSpeed !== undefined
|
|
905
|
+
? { speed: requestedSpeed }
|
|
906
|
+
: {}),
|
|
907
|
+
...(typeof raw.server_tool_use?.web_search_requests === 'number'
|
|
908
|
+
? { webSearchRequests: raw.server_tool_use.web_search_requests }
|
|
909
|
+
: {}),
|
|
910
|
+
...(typeof raw.service_tier === 'string' && raw.service_tier.length > 0
|
|
911
|
+
? { serviceTier: raw.service_tier }
|
|
912
|
+
: {}),
|
|
913
|
+
...(typeof raw.inference_geo === 'string' && raw.inference_geo.length > 0
|
|
914
|
+
? { inferenceGeo: raw.inference_geo }
|
|
915
|
+
: {}),
|
|
916
|
+
...(parseCacheMiss(diagnostics) ? { cacheMiss: parseCacheMiss(diagnostics) } : {}),
|
|
813
917
|
...(raw.cache_creation
|
|
814
918
|
? {
|
|
815
919
|
cacheWriteTtlTokens: {
|
|
@@ -968,7 +1072,7 @@ function toCitation(raw: RawAnthropicCitation, index: number): Citation | undefi
|
|
|
968
1072
|
|
|
969
1073
|
interface StreamEvent {
|
|
970
1074
|
type: string
|
|
971
|
-
message?: { id?: string; usage?: RawAnthropicUsage }
|
|
1075
|
+
message?: { id?: string; usage?: RawAnthropicUsage; diagnostics?: RawCacheDiagnostics | null }
|
|
972
1076
|
index?: number
|
|
973
1077
|
content_block?: {
|
|
974
1078
|
type?: string
|
|
@@ -1012,12 +1116,29 @@ export const ANTHROPIC_CAPABILITIES: ProviderCapabilities = {
|
|
|
1012
1116
|
supportsToolResultImages: true,
|
|
1013
1117
|
supportsToolResultDocuments: false,
|
|
1014
1118
|
cacheTtl: ['5m', '1h'],
|
|
1119
|
+
// The first-party Messages limit is 128 MB (raised from 32 MB on 2026-10-28;
|
|
1120
|
+
// https://platform.claude.com/docs/en/api/overview). 100 MiB of base64
|
|
1121
|
+
// leaves headroom for the JSON envelope, text and tool schemas. A driver
|
|
1122
|
+
// pointed anywhere else does not claim it: see the constructor.
|
|
1123
|
+
maxRequestRichContentBytes: 100 * 1024 * 1024,
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/** The request rich-content budget only the vendor's own endpoint is known to take. */
|
|
1127
|
+
function capabilitiesFor(config: AnthropicConfig): ProviderCapabilities {
|
|
1128
|
+
if (config.compatibleEndpoint !== true && isVendorEndpoint(config.baseURL)) {
|
|
1129
|
+
return ANTHROPIC_CAPABILITIES
|
|
1130
|
+
}
|
|
1131
|
+
// A gateway, proxy or partner platform (Bedrock accepts 20 MB, Google-managed
|
|
1132
|
+
// 30 MB, https://platform.claude.com/docs/en/api/overview) has its own limit
|
|
1133
|
+
// this driver cannot read from a base URL, so it keeps the kernel default.
|
|
1134
|
+
const { maxRequestRichContentBytes: _first, ...rest } = ANTHROPIC_CAPABILITIES
|
|
1135
|
+
return rest
|
|
1015
1136
|
}
|
|
1016
1137
|
|
|
1017
1138
|
export class AnthropicProvider implements LLMProvider {
|
|
1018
1139
|
readonly id = 'anthropic'
|
|
1019
1140
|
readonly name = 'Anthropic'
|
|
1020
|
-
readonly capabilities
|
|
1141
|
+
readonly capabilities: ProviderCapabilities
|
|
1021
1142
|
|
|
1022
1143
|
private client: Anthropic
|
|
1023
1144
|
private config: AnthropicConfig
|
|
@@ -1032,6 +1153,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1032
1153
|
)
|
|
1033
1154
|
throw new Error('maxRetries must be a nonnegative integer.')
|
|
1034
1155
|
this.config = config
|
|
1156
|
+
this.capabilities = capabilitiesFor(config)
|
|
1035
1157
|
|
|
1036
1158
|
const clientOpts: Record<string, unknown> = {
|
|
1037
1159
|
timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,
|
|
@@ -1105,6 +1227,35 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1105
1227
|
return params.cacheControl.ttl ?? this.config.promptCacheTtl ?? '5m'
|
|
1106
1228
|
}
|
|
1107
1229
|
|
|
1230
|
+
/**
|
|
1231
|
+
* The last response id per conversation, so the next request can name it.
|
|
1232
|
+
* A conversation is told apart by its first message with cache markers
|
|
1233
|
+
* removed; this driver instance also serves compaction and review calls,
|
|
1234
|
+
* and naming another conversation's response would report a miss that never
|
|
1235
|
+
* happened. Bounded, oldest dropped.
|
|
1236
|
+
*/
|
|
1237
|
+
private readonly lastResponses = new Map<string, string>()
|
|
1238
|
+
|
|
1239
|
+
private conversationKey(messages: readonly unknown[]): string {
|
|
1240
|
+
return JSON.stringify(messages[0] ?? null, (key, value) =>
|
|
1241
|
+
key === 'cache_control' ? undefined : value,
|
|
1242
|
+
)
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
private previousMessageFor(messages: readonly unknown[]): string | undefined {
|
|
1246
|
+
return this.lastResponses.get(this.conversationKey(messages))
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
private rememberResponse(messages: readonly unknown[], id: string): void {
|
|
1250
|
+
const key = this.conversationKey(messages)
|
|
1251
|
+
this.lastResponses.delete(key)
|
|
1252
|
+
this.lastResponses.set(key, id)
|
|
1253
|
+
if (this.lastResponses.size > 32) {
|
|
1254
|
+
const oldest = this.lastResponses.keys().next().value
|
|
1255
|
+
if (oldest !== undefined) this.lastResponses.delete(oldest)
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1108
1259
|
private buildCreateParams(
|
|
1109
1260
|
params: ChatCompletionParams,
|
|
1110
1261
|
stream: boolean,
|
|
@@ -1214,6 +1365,28 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1214
1365
|
}
|
|
1215
1366
|
if (Object.keys(outputConfig).length) body.output_config = outputConfig
|
|
1216
1367
|
|
|
1368
|
+
// Only 'fast' is a wire value: 'standard' is what an absent field means.
|
|
1369
|
+
// Admission is decided locally, before transport, because the vendor
|
|
1370
|
+
// either errors (removed or unsupported models) or, on Opus 4.6, quietly
|
|
1371
|
+
// serves standard speed while the caller believes otherwise.
|
|
1372
|
+
if (params.speed === 'fast') {
|
|
1373
|
+
assertFastModeAccepted(
|
|
1374
|
+
model,
|
|
1375
|
+
(this.config.clock ?? Date.now)(),
|
|
1376
|
+
this.config.compatibleEndpoint !== true && isVendorEndpoint(this.config.baseURL),
|
|
1377
|
+
)
|
|
1378
|
+
body.speed = 'fast'
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
// Cache diagnostics ask the service to say why a prefix it had stopped
|
|
1382
|
+
// being served from cache. First-party only: the field is documented for
|
|
1383
|
+
// the Claude API, not for Bedrock, Vertex or a compatible server, which
|
|
1384
|
+
// may reject an unknown field. `null` opts in on a conversation's first
|
|
1385
|
+
// request, and later ones name the response they continue.
|
|
1386
|
+
if (this.config.compatibleEndpoint !== true && isVendorEndpoint(this.config.baseURL)) {
|
|
1387
|
+
body.diagnostics = { previous_message_id: this.previousMessageFor(messages) ?? null }
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1217
1390
|
if (params.temperature !== undefined) body.temperature = params.temperature
|
|
1218
1391
|
if (params.topP !== undefined) body.top_p = params.topP
|
|
1219
1392
|
if (params.topK !== undefined) body.top_k = params.topK
|
|
@@ -1234,36 +1407,83 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1234
1407
|
): Promise<unknown> {
|
|
1235
1408
|
const create = this.client.messages.create as unknown as (
|
|
1236
1409
|
body: Record<string, unknown>,
|
|
1237
|
-
options?: { signal?: AbortSignal },
|
|
1410
|
+
options?: { signal?: AbortSignal; headers?: Record<string, string> },
|
|
1238
1411
|
) => Promise<unknown>
|
|
1412
|
+
const beta = this.betaHeaderFor(body)
|
|
1239
1413
|
// Pass the caller AbortSignal as the SDK's per-request RequestOptions so
|
|
1240
1414
|
// aborting it tears down the in-flight HTTP/2 SSE request (rejects with
|
|
1241
1415
|
// APIUserAbortError). A non-aborted signal is identical to omitting it.
|
|
1242
|
-
return create.call(this.client.messages, body, {
|
|
1416
|
+
return create.call(this.client.messages, body, {
|
|
1417
|
+
signal: opts?.signal,
|
|
1418
|
+
...(beta ? { headers: { 'anthropic-beta': beta } } : {}),
|
|
1419
|
+
})
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/**
|
|
1423
|
+
* The `anthropic-beta` value for this request when it needs one beyond the
|
|
1424
|
+
* client's defaults. A per-request header REPLACES the default of the same
|
|
1425
|
+
* name, so the defaults (the subscription betas, or the caller's own) are
|
|
1426
|
+
* carried into it.
|
|
1427
|
+
*/
|
|
1428
|
+
private betaHeaderFor(body: Record<string, unknown>): string | undefined {
|
|
1429
|
+
if (body.speed !== 'fast') return undefined
|
|
1430
|
+
const extra = fastModeBeta(String(body.model))
|
|
1431
|
+
if (extra === undefined) return undefined
|
|
1432
|
+
const configured = Object.entries(this.config.defaultHeaders ?? {}).find(
|
|
1433
|
+
([name]) => name.toLowerCase() === 'anthropic-beta',
|
|
1434
|
+
)?.[1]
|
|
1435
|
+
const base =
|
|
1436
|
+
this.config.authToken && this.config.compatibleEndpoint !== true
|
|
1437
|
+
? (configured ?? OAUTH_BETAS)
|
|
1438
|
+
: configured
|
|
1439
|
+
return [base, extra].filter(Boolean).join(',')
|
|
1243
1440
|
}
|
|
1244
1441
|
|
|
1245
1442
|
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
1246
1443
|
const providerRoute = resolveAnthropicRoute(this.resolveModel(params), params.providerRoute)
|
|
1247
1444
|
const createParams = this.buildCreateParams(params, true)
|
|
1445
|
+
const requestedSpeed = createParams.speed === 'fast' ? ('fast' as const) : undefined
|
|
1248
1446
|
const signal = params.signal
|
|
1249
1447
|
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1448
|
+
const open = async (body: Record<string, unknown>): Promise<AsyncIterable<StreamEvent>> => {
|
|
1449
|
+
try {
|
|
1450
|
+
return (await this.createRaw(body, {
|
|
1451
|
+
signal,
|
|
1452
|
+
})) as AsyncIterable<StreamEvent>
|
|
1453
|
+
} catch (err) {
|
|
1454
|
+
// The vendor SDK builds its error message FROM the response body, so a
|
|
1455
|
+
// credential the upstream echoed back is already inside `err.message`
|
|
1456
|
+
// before this code runs (proven with a planted fake token). Classify from
|
|
1457
|
+
// the status and drop the vendor error entirely — no re-throw, no
|
|
1458
|
+
// `cause`, because a `cause` is exactly what a structured logger walks.
|
|
1459
|
+
if (isCallerAbortError(err, signal)) throw signal?.reason ?? err
|
|
1460
|
+
if (isProviderRequestError(err)) throw err
|
|
1461
|
+
throw providerVendorError({ providerId: 'anthropic', error: err })
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
const stream = await open(createParams)
|
|
1465
|
+
|
|
1466
|
+
// A server tool (hosted search) can stop a response with `pause_turn`
|
|
1467
|
+
// before the answer exists. The documented way on is to send what came
|
|
1468
|
+
// back, unchanged, as the last assistant message and ask again. The
|
|
1469
|
+
// continuations are part of one turn to the caller: indices keep
|
|
1470
|
+
// counting up, usage adds up, and the finish arrives once.
|
|
1471
|
+
let paused = false
|
|
1472
|
+
let pauses = 0
|
|
1473
|
+
let indexOffset = 0
|
|
1474
|
+
let maxIndex = -1
|
|
1475
|
+
let spent: TokenUsage | undefined
|
|
1476
|
+
let current: TokenUsage | undefined
|
|
1477
|
+
const usageOf = (
|
|
1478
|
+
raw: RawAnthropicUsage,
|
|
1479
|
+
ttl?: '5m' | '1h',
|
|
1480
|
+
diagnostics?: RawCacheDiagnostics | null,
|
|
1481
|
+
): TokenUsage => {
|
|
1482
|
+
current = highWater(current, parseUsage(raw, ttl, requestedSpeed, diagnostics))
|
|
1483
|
+
return addUsage(spent, current)
|
|
1264
1484
|
}
|
|
1265
|
-
|
|
1266
1485
|
let messageId = ''
|
|
1486
|
+
let responseId = ''
|
|
1267
1487
|
// Track active tool-use blocks by content_block index so input_json_delta
|
|
1268
1488
|
// fragments can reference the right tool call.
|
|
1269
1489
|
const activeTools = new Map<number, { id: string; name: string }>()
|
|
@@ -1309,7 +1529,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1309
1529
|
// `streamIdleTimeoutMs`; otherwise the request timeout and caller
|
|
1310
1530
|
// AbortSignal own lifecycle cancellation.
|
|
1311
1531
|
const streamIdleTimeoutMs = this.config.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS
|
|
1312
|
-
|
|
1532
|
+
let iter = (stream as AsyncIterable<StreamEvent>)[Symbol.asyncIterator]()
|
|
1313
1533
|
const nextWithIdleTimeout = async (): Promise<IteratorResult<StreamEvent>> => {
|
|
1314
1534
|
if (!Number.isFinite(streamIdleTimeoutMs) || streamIdleTimeoutMs <= 0) {
|
|
1315
1535
|
return iter.next()
|
|
@@ -1342,16 +1562,27 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1342
1562
|
signal?.throwIfAborted()
|
|
1343
1563
|
const result = await nextWithIdleTimeout()
|
|
1344
1564
|
if (result.done) break
|
|
1345
|
-
const event =
|
|
1565
|
+
const event =
|
|
1566
|
+
indexOffset > 0 && typeof result.value.index === 'number'
|
|
1567
|
+
? { ...result.value, index: result.value.index + indexOffset }
|
|
1568
|
+
: result.value
|
|
1569
|
+
if (typeof event.index === 'number') maxIndex = Math.max(maxIndex, event.index)
|
|
1346
1570
|
try {
|
|
1347
1571
|
switch (event.type) {
|
|
1348
1572
|
case 'message_start': {
|
|
1349
|
-
if (event.message?.id)
|
|
1573
|
+
if (event.message?.id) {
|
|
1574
|
+
if (!messageId) messageId = event.message.id
|
|
1575
|
+
responseId = event.message.id
|
|
1576
|
+
}
|
|
1350
1577
|
if (event.message?.usage) {
|
|
1351
1578
|
yield {
|
|
1352
1579
|
id: messageId,
|
|
1353
1580
|
delta: {},
|
|
1354
|
-
usage:
|
|
1581
|
+
usage: usageOf(
|
|
1582
|
+
event.message.usage,
|
|
1583
|
+
this.cacheTtlFor(params),
|
|
1584
|
+
event.message.diagnostics,
|
|
1585
|
+
),
|
|
1355
1586
|
}
|
|
1356
1587
|
}
|
|
1357
1588
|
break
|
|
@@ -1539,8 +1770,19 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1539
1770
|
}
|
|
1540
1771
|
case 'message_delta': {
|
|
1541
1772
|
if (event.delta?.stop_reason) {
|
|
1542
|
-
if (event.delta.stop_reason === 'pause_turn')
|
|
1543
|
-
|
|
1773
|
+
if (event.delta.stop_reason === 'pause_turn') {
|
|
1774
|
+
if (pauses >= MAX_PAUSE_CONTINUATIONS)
|
|
1775
|
+
throw new ProviderRequestError({
|
|
1776
|
+
kind: 'server',
|
|
1777
|
+
providerId: 'anthropic',
|
|
1778
|
+
detail: `the hosted search was still paused after ${MAX_PAUSE_CONTINUATIONS} continuations, so the answer is unfinished`,
|
|
1779
|
+
})
|
|
1780
|
+
paused = true
|
|
1781
|
+
if (event.usage) {
|
|
1782
|
+
yield { id: messageId, delta: {}, usage: usageOf(event.usage) }
|
|
1783
|
+
}
|
|
1784
|
+
break
|
|
1785
|
+
}
|
|
1544
1786
|
const search = searchBlocks.complete(providerRoute)
|
|
1545
1787
|
// The sources list is the driver's text, not the model's: it
|
|
1546
1788
|
// must not read as the model moving on from a tool call the
|
|
@@ -1562,18 +1804,41 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1562
1804
|
event.delta.stop_reason,
|
|
1563
1805
|
event.delta.stop_details ?? event.stop_details,
|
|
1564
1806
|
),
|
|
1565
|
-
usage: event.usage ?
|
|
1807
|
+
usage: event.usage ? usageOf(event.usage) : undefined,
|
|
1566
1808
|
}
|
|
1567
1809
|
} else if (event.usage) {
|
|
1568
1810
|
yield {
|
|
1569
1811
|
id: messageId,
|
|
1570
1812
|
delta: {},
|
|
1571
|
-
usage:
|
|
1813
|
+
usage: usageOf(event.usage),
|
|
1572
1814
|
}
|
|
1573
1815
|
}
|
|
1574
1816
|
break
|
|
1575
1817
|
}
|
|
1576
1818
|
case 'message_stop': {
|
|
1819
|
+
if (paused) {
|
|
1820
|
+
paused = false
|
|
1821
|
+
pauses++
|
|
1822
|
+
if (current) spent = addUsage(spent, current)
|
|
1823
|
+
current = undefined
|
|
1824
|
+
indexOffset = maxIndex + 1
|
|
1825
|
+
const next: Record<string, unknown> = {
|
|
1826
|
+
...createParams,
|
|
1827
|
+
messages: [
|
|
1828
|
+
...(createParams.messages as unknown[]),
|
|
1829
|
+
{ role: 'assistant', content: searchBlocks.content() },
|
|
1830
|
+
],
|
|
1831
|
+
}
|
|
1832
|
+
if (next.diagnostics !== undefined) {
|
|
1833
|
+
next.diagnostics = { previous_message_id: responseId || null }
|
|
1834
|
+
}
|
|
1835
|
+
await iter.return?.().catch(() => undefined)
|
|
1836
|
+
iter = (await open(next))[Symbol.asyncIterator]()
|
|
1837
|
+
break
|
|
1838
|
+
}
|
|
1839
|
+
// Only a whole, final response is named by the next request;
|
|
1840
|
+
// an aborted or failed one never reaches this point.
|
|
1841
|
+
if (responseId) this.rememberResponse(createParams.messages as unknown[], responseId)
|
|
1577
1842
|
if (searchReplayEmitted) return
|
|
1578
1843
|
const search = searchBlocks.complete(providerRoute)
|
|
1579
1844
|
if (search) {
|
|
@@ -1821,25 +2086,27 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
1821
2086
|
* whether the keys in it match what a driver actually reports. Only a test
|
|
1822
2087
|
* that feeds real driver output through the real lookup can see it, and
|
|
1823
2088
|
* `__tests__/pricing-conformance.test.ts` is that test.
|
|
2089
|
+
*
|
|
2090
|
+
* A model the vendor has retired is not offered here, and one it has
|
|
2091
|
+
* announced for retirement is not recommended: it still works until the
|
|
2092
|
+
* vendor says otherwise, and an operator who names it keeps it.
|
|
1824
2093
|
*/
|
|
1825
2094
|
export const OFFLINE_MODEL_CATALOGUE: readonly ModelInfo[] = [
|
|
1826
2095
|
{
|
|
1827
|
-
id: 'claude-sonnet-
|
|
1828
|
-
name: 'Claude Sonnet
|
|
1829
|
-
contextWindow:
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
outputPrice: 15.0,
|
|
2096
|
+
id: 'claude-sonnet-5-5',
|
|
2097
|
+
name: 'Claude Sonnet 5.5',
|
|
2098
|
+
contextWindow: 1_000_000,
|
|
2099
|
+
inputPrice: 2.0,
|
|
2100
|
+
outputPrice: 10.0,
|
|
1833
2101
|
supportsToolUse: true,
|
|
1834
2102
|
supportsStreaming: true,
|
|
1835
2103
|
},
|
|
1836
2104
|
{
|
|
1837
|
-
id: 'claude-opus-4-
|
|
1838
|
-
name: 'Claude Opus 4.
|
|
1839
|
-
contextWindow:
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
outputPrice: 75.0,
|
|
2105
|
+
id: 'claude-opus-4-8',
|
|
2106
|
+
name: 'Claude Opus 4.8',
|
|
2107
|
+
contextWindow: 1_000_000,
|
|
2108
|
+
inputPrice: 5.0,
|
|
2109
|
+
outputPrice: 25.0,
|
|
1843
2110
|
supportsToolUse: true,
|
|
1844
2111
|
supportsStreaming: true,
|
|
1845
2112
|
},
|
package/src/fast-mode.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { ProviderRequestError, parseVersionedModelId } from '@namzu/sdk'
|
|
2
|
+
|
|
3
|
+
import { MODEL_ID_GRAMMAR } from './thinking-capability.js'
|
|
4
|
+
import { type VersionFloor, reachesFloor } from './version-floor.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Fast mode: `speed: "fast"` on the Messages request, a premium low-latency
|
|
8
|
+
* mode billed at twice the standard rates.
|
|
9
|
+
*
|
|
10
|
+
* Source: the vendor's fast-mode page and release notes (checked 2026-11-10).
|
|
11
|
+
* https://platform.claude.com/docs/en/build-with-claude/fast-mode and
|
|
12
|
+
* https://platform.claude.com/docs/en/release-notes/overview.
|
|
13
|
+
*
|
|
14
|
+
* Two kinds of model take it, and they differ in the one thing this module
|
|
15
|
+
* decides besides admission, the beta header:
|
|
16
|
+
*
|
|
17
|
+
* - Generally available from a floor, with NO beta header: Opus 5.5, Fable 5.2
|
|
18
|
+
* and Mythos 5.2. A floor and not a list, so the next release in those
|
|
19
|
+
* families inherits the answer (the same trade `version-floor.ts` explains).
|
|
20
|
+
* - Research preview, which still needs the `fast-mode-2026-02-01` beta header:
|
|
21
|
+
* Opus 5 and Opus 4.8 only, named exactly because no floor describes them.
|
|
22
|
+
*
|
|
23
|
+
* Everything else is refused here, before transport. Opus 4.7 and Opus 4.8
|
|
24
|
+
* after its removal date answer a fast request with an error; Opus 4.6 would
|
|
25
|
+
* silently run at standard speed while the caller believes otherwise. Refusing
|
|
26
|
+
* all of them keeps one rule: `fast` means fast or an error.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** The beta header the research-preview models still require. */
|
|
30
|
+
export const FAST_MODE_BETA = 'fast-mode-2026-02-01'
|
|
31
|
+
|
|
32
|
+
const FAST_GA_FROM: readonly VersionFloor[] = [
|
|
33
|
+
{ family: 'opus', major: 5, minor: 5 },
|
|
34
|
+
{ family: 'fable', major: 5, minor: 2 },
|
|
35
|
+
{ family: 'mythos', major: 5, minor: 2 },
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
interface PreviewModel {
|
|
39
|
+
readonly family: string
|
|
40
|
+
readonly major: number
|
|
41
|
+
readonly minor: number
|
|
42
|
+
/** First instant (UTC) at which the vendor no longer serves fast mode on it. */
|
|
43
|
+
readonly removedAt?: number
|
|
44
|
+
/** What to use instead, named in the refusal. */
|
|
45
|
+
readonly replacement?: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const FAST_PREVIEW: readonly PreviewModel[] = [
|
|
49
|
+
{ family: 'opus', major: 5, minor: 0 },
|
|
50
|
+
{
|
|
51
|
+
family: 'opus',
|
|
52
|
+
major: 4,
|
|
53
|
+
minor: 8,
|
|
54
|
+
// Deprecated 2026-10-30, removed 2026-11-30: a request with speed "fast"
|
|
55
|
+
// then returns an error. Migration target is Claude Opus 5.5.
|
|
56
|
+
removedAt: Date.UTC(2026, 10, 30),
|
|
57
|
+
replacement: 'claude-opus-5-5',
|
|
58
|
+
},
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
export type FastModeVerdict =
|
|
62
|
+
| { readonly ok: true; readonly beta?: string }
|
|
63
|
+
| { readonly ok: false; readonly reason: string }
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Whether `speed: "fast"` may be sent to `model` at time `now` (epoch ms), and
|
|
67
|
+
* the beta header it needs. Pure: the clock is a parameter so the removal date
|
|
68
|
+
* can be tested without waiting for it.
|
|
69
|
+
*/
|
|
70
|
+
export function resolveFastMode(model: string, now: number): FastModeVerdict {
|
|
71
|
+
const version = parseVersionedModelId(model, MODEL_ID_GRAMMAR)
|
|
72
|
+
if (version === undefined) {
|
|
73
|
+
return {
|
|
74
|
+
ok: false,
|
|
75
|
+
reason: `Fast mode is not known to be available on model "${model}". It is offered on Claude Opus 5.5, Fable 5.2 and Mythos 5.2 (and, in research preview, Opus 5).`,
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const preview = FAST_PREVIEW.find(
|
|
79
|
+
(m) => m.family === version.family && m.major === version.major && m.minor === version.minor,
|
|
80
|
+
)
|
|
81
|
+
if (preview !== undefined) {
|
|
82
|
+
if (preview.removedAt !== undefined && now >= preview.removedAt) {
|
|
83
|
+
return {
|
|
84
|
+
ok: false,
|
|
85
|
+
reason: `Fast mode was removed from model "${model}" on ${new Date(preview.removedAt).toISOString().slice(0, 10)} and the vendor now answers it with an error.${preview.replacement ? ` Use "${preview.replacement}" instead.` : ''}`,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { ok: true, beta: FAST_MODE_BETA }
|
|
89
|
+
}
|
|
90
|
+
if (reachesFloor(version, FAST_GA_FROM)) return { ok: true }
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
reason: `Model "${model}" has no fast mode. It is offered on Claude Opus 5.5, Fable 5.2 and Mythos 5.2 (and, in research preview, Opus 5); omit speed or choose one of those models.`,
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Whether this model takes `speed: "fast"` right now. Same decision the
|
|
99
|
+
* request path makes, for a caller (a CLI toggle, a model picker) deciding
|
|
100
|
+
* whether to offer it.
|
|
101
|
+
*/
|
|
102
|
+
export function supportsFastMode(model: string, now: number = Date.now()): boolean {
|
|
103
|
+
return resolveFastMode(model, now).ok
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Refuse, before transport, a fast request the vendor would error on or
|
|
108
|
+
* quietly serve at standard speed. Returns the beta header to send, if any.
|
|
109
|
+
* `firstPartyEndpoint` is true only for the vendor's own host with no
|
|
110
|
+
* `compatibleEndpoint` flag. The error is the `bad_request` the vendor's 400 would have become, with its
|
|
111
|
+
* own code, like `assertForcedToolChoiceAccepted`.
|
|
112
|
+
*/
|
|
113
|
+
export function assertFastModeAccepted(
|
|
114
|
+
model: string,
|
|
115
|
+
now: number,
|
|
116
|
+
firstPartyEndpoint: boolean,
|
|
117
|
+
): string | undefined {
|
|
118
|
+
const verdict = !firstPartyEndpoint
|
|
119
|
+
? ({
|
|
120
|
+
ok: false,
|
|
121
|
+
reason:
|
|
122
|
+
"Fast mode is offered on the vendor's own endpoint only. Another host (a gateway, Microsoft Foundry, Bedrock, a compatible service) is not known to honour `speed`, and Foundry answers it with an error, selling fast variants as separate model ids.",
|
|
123
|
+
} as const)
|
|
124
|
+
: resolveFastMode(model, now)
|
|
125
|
+
if (verdict.ok) return verdict.beta
|
|
126
|
+
throw new ProviderRequestError({
|
|
127
|
+
kind: 'bad_request',
|
|
128
|
+
providerId: 'anthropic',
|
|
129
|
+
providerCode: 'fast_mode_unsupported',
|
|
130
|
+
detail: verdict.reason,
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The beta header a request already admitted to fast mode must carry, if any. */
|
|
135
|
+
export function fastModeBeta(model: string): string | undefined {
|
|
136
|
+
// The clock is irrelevant here: admission (and the removal date) was decided
|
|
137
|
+
// by `assertFastModeAccepted`; this only reads which header the model needs.
|
|
138
|
+
const verdict = resolveFastMode(model, 0)
|
|
139
|
+
return verdict.ok ? verdict.beta : undefined
|
|
140
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -43,6 +43,14 @@ export type {
|
|
|
43
43
|
ResolvedThinkingBody,
|
|
44
44
|
} from './thinking-capability.js'
|
|
45
45
|
|
|
46
|
+
// Fast mode (`speed: "fast"`): which models take it, and the beta header the previews need.
|
|
47
|
+
export {
|
|
48
|
+
FAST_MODE_BETA,
|
|
49
|
+
resolveFastMode as resolveFastModeVerdict,
|
|
50
|
+
supportsFastMode,
|
|
51
|
+
} from './fast-mode.js'
|
|
52
|
+
export type { FastModeVerdict } from './fast-mode.js'
|
|
53
|
+
|
|
46
54
|
// Whether a step may force a tool call on a given model. Some models refuse a
|
|
47
55
|
// forced choice outright, and manual thinking refuses it everywhere; the driver
|
|
48
56
|
// refuses such a request before sending it, and this answers the same question
|
package/src/search-replay.ts
CHANGED
|
@@ -147,6 +147,16 @@ export class SearchBlocks {
|
|
|
147
147
|
if (b && this.json.has(index)) b.input = replayInput(this.json.get(index) ?? '')
|
|
148
148
|
this.active.delete(index)
|
|
149
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* The content received so far, as the service sent it, for sending back to
|
|
152
|
+
* continue a paused turn. Complete blocks only, in order; server tool use
|
|
153
|
+
* and result blocks are carried intact.
|
|
154
|
+
*/
|
|
155
|
+
content(): Block[] {
|
|
156
|
+
if (this.active.size)
|
|
157
|
+
throw new Error('Anthropic search stream paused with incomplete content blocks.')
|
|
158
|
+
return structuredClone([...this.blocks.entries()].sort(([a], [b]) => a - b).map(([, b]) => b))
|
|
159
|
+
}
|
|
150
160
|
complete(route: ProviderRoute) {
|
|
151
161
|
if (!this.hasSearch) return
|
|
152
162
|
if (this.active.size)
|