@rulvar/anthropic 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/index.d.ts +125 -0
- package/dist/index.js +685 -0
- package/package.json +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { CanonicalId, ChatEvent, ChatRequest, FinishInfo, ModelCaps, ProviderAdapter, Usage, WireError } from "@rulvar/core";
|
|
2
|
+
|
|
3
|
+
//#region src/caps.d.ts
|
|
4
|
+
interface AnthropicModelInfo {
|
|
5
|
+
caps: ModelCaps;
|
|
6
|
+
/**
|
|
7
|
+
* Wire thinking form: current models accept only adaptive; the
|
|
8
|
+
* enabled/budget form remains functional only on Opus 4.6 and Sonnet
|
|
9
|
+
* 4.6 (docs/04, section "Thinking and sampling parameters").
|
|
10
|
+
*/
|
|
11
|
+
thinkingForm: "adaptive" | "enabled-budget";
|
|
12
|
+
/** Minimum cacheable prefix in tokens (docs/04, section "Prompt caching"). */
|
|
13
|
+
cacheMinTokens: number;
|
|
14
|
+
}
|
|
15
|
+
/** Static seed table; docs/04 section 4 names the current model set. */
|
|
16
|
+
declare const ANTHROPIC_MODELS: Record<string, AnthropicModelInfo>;
|
|
17
|
+
/**
|
|
18
|
+
* Unknown Anthropic models are assumed current-generation: adaptive
|
|
19
|
+
* thinking, native structured outputs, no sampling parameters. refreshCaps
|
|
20
|
+
* corrects window/output figures from the live model list.
|
|
21
|
+
*/
|
|
22
|
+
declare function anthropicModelInfo(model: string): AnthropicModelInfo;
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/adapter.d.ts
|
|
25
|
+
/** pause_turn continuation cap (docs/06 Appendix A; docs/04, section 4.6). */
|
|
26
|
+
declare const DEFAULT_PAUSE_TURN_MAX_CONTINUATIONS = 5;
|
|
27
|
+
/** The client sub-surface the adapter consumes; injectable for tests. */
|
|
28
|
+
interface AnthropicClientLike {
|
|
29
|
+
messages: {
|
|
30
|
+
create(params: Record<string, unknown>, opts?: {
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}): Promise<unknown>;
|
|
33
|
+
countTokens(params: Record<string, unknown>): Promise<{
|
|
34
|
+
input_tokens: number;
|
|
35
|
+
}>;
|
|
36
|
+
};
|
|
37
|
+
models: {
|
|
38
|
+
list(params?: Record<string, unknown>): Promise<{
|
|
39
|
+
data: Array<Record<string, unknown>>;
|
|
40
|
+
has_more?: boolean;
|
|
41
|
+
last_id?: string;
|
|
42
|
+
}>;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
interface AnthropicAdapterOptions {
|
|
46
|
+
apiKey?: string;
|
|
47
|
+
baseURL?: string;
|
|
48
|
+
/** Test seam: a preconstructed client; production uses @anthropic-ai/sdk. */
|
|
49
|
+
client?: AnthropicClientLike;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Creates the first-class Anthropic adapter (id 'anthropic'). SDK
|
|
53
|
+
* autoretries are disabled (max_retries 0): the core owns retries and
|
|
54
|
+
* wall-clock (docs/04, section "Retries belong to the core").
|
|
55
|
+
*/
|
|
56
|
+
declare function anthropic(options?: AnthropicAdapterOptions): ProviderAdapter;
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/wire.d.ts
|
|
59
|
+
/** Bijective canonical-to-wire tool-call id map (docs/04, section 1.2). */
|
|
60
|
+
declare class IdMap {
|
|
61
|
+
private readonly toWire;
|
|
62
|
+
private readonly toCanonical;
|
|
63
|
+
private readonly mint;
|
|
64
|
+
constructor(mint: () => CanonicalId);
|
|
65
|
+
canonicalFor(wireId: string): CanonicalId;
|
|
66
|
+
wireFor(canonicalId: CanonicalId): string;
|
|
67
|
+
}
|
|
68
|
+
type Block = Record<string, unknown>;
|
|
69
|
+
/**
|
|
70
|
+
* Builds Messages API params from a ChatRequest. cacheHint compiles into
|
|
71
|
+
* cache_control breakpoints; beyond the provider cap of 4 the DEEPEST
|
|
72
|
+
* breakpoints are kept and the shallowest dropped, deterministically
|
|
73
|
+
* (docs/04, sections 1.7 and 4.4).
|
|
74
|
+
*/
|
|
75
|
+
declare function buildAnthropicParams(req: ChatRequest, options: {
|
|
76
|
+
ids: IdMap;
|
|
77
|
+
maxOutputTokens: number;
|
|
78
|
+
thinkingForm: "adaptive" | "enabled-budget";
|
|
79
|
+
}): Record<string, unknown>;
|
|
80
|
+
/** Raw Messages API stream events, structurally typed. */
|
|
81
|
+
type AnthropicStreamEvent = Record<string, unknown> & {
|
|
82
|
+
type: string;
|
|
83
|
+
};
|
|
84
|
+
interface MappedStop {
|
|
85
|
+
finish?: FinishInfo;
|
|
86
|
+
pauseTurn: boolean;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The docs/04 section 4.7 stop-reason table. pause_turn never surfaces as
|
|
90
|
+
* a canonical finish: the adapter continues internally.
|
|
91
|
+
*/
|
|
92
|
+
declare function mapStopReason(stopReason: string | null | undefined, stopDetails: Record<string, unknown> | null | undefined): MappedStop;
|
|
93
|
+
/**
|
|
94
|
+
* Normalizes Messages API usage under the Usage invariant: Anthropic
|
|
95
|
+
* reports input_tokens EXCLUDING cache reads and writes, so the canonical
|
|
96
|
+
* inputTokens is the sum of all three (docs/04, sections 1.6 and 4.4).
|
|
97
|
+
*/
|
|
98
|
+
declare function normalizeAnthropicUsage(raw: Record<string, unknown> | undefined): Usage;
|
|
99
|
+
interface TurnMapping {
|
|
100
|
+
events: ChatEvent[];
|
|
101
|
+
/** Assistant content blocks collected verbatim (pause_turn continuation). */
|
|
102
|
+
assistantContent: Block[];
|
|
103
|
+
pauseTurn: boolean;
|
|
104
|
+
finished: boolean;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Maps one Messages API stream into ChatEvents. Emits an early usage event
|
|
108
|
+
* from message_start (the input side is known immediately) and exactly one
|
|
109
|
+
* terminal finish unless the turn paused (pause_turn) or errored.
|
|
110
|
+
* `carryRetained` holds thinking blocks from earlier pause_turn
|
|
111
|
+
* continuations of the same turn so the terminal finish ships the whole
|
|
112
|
+
* turn's retention payload (docs/04, section 2.3, M4-T02).
|
|
113
|
+
*/
|
|
114
|
+
declare function mapAnthropicStream(stream: AsyncIterable<AnthropicStreamEvent>, ids: IdMap, emit: (event: ChatEvent) => void, options?: {
|
|
115
|
+
carryRetained?: Block[];
|
|
116
|
+
}): Promise<TurnMapping>;
|
|
117
|
+
/**
|
|
118
|
+
* Projects an SDK/API error into the retryable WireError vocabulary:
|
|
119
|
+
* 429 rate limits surface retryAfterMs and the x-ratelimit-* buckets; 529
|
|
120
|
+
* overloaded and 5xx are retryable transport; everything else is terminal
|
|
121
|
+
* transport (docs/04, section 4.9). Adapters never sleep internally.
|
|
122
|
+
*/
|
|
123
|
+
declare function anthropicErrorToWire(error: unknown): WireError;
|
|
124
|
+
//#endregion
|
|
125
|
+
export { ANTHROPIC_MODELS, type AnthropicAdapterOptions, type AnthropicClientLike, type AnthropicModelInfo, type AnthropicStreamEvent, DEFAULT_PAUSE_TURN_MAX_CONTINUATIONS, IdMap, type TurnMapping, anthropic, anthropicErrorToWire, anthropicModelInfo, buildAnthropicParams, mapAnthropicStream, mapStopReason, normalizeAnthropicUsage };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
2
|
+
import { createCanonicalIdMinter, isStrictCompatibleSchema } from "@rulvar/core";
|
|
3
|
+
//#region src/caps.ts
|
|
4
|
+
const ALL_EFFORTS = [
|
|
5
|
+
"low",
|
|
6
|
+
"medium",
|
|
7
|
+
"high",
|
|
8
|
+
"xhigh",
|
|
9
|
+
"max"
|
|
10
|
+
];
|
|
11
|
+
function current(contextWindow, maxOutputTokens, pricing, cacheMinTokens) {
|
|
12
|
+
return {
|
|
13
|
+
caps: {
|
|
14
|
+
structuredOutput: "native",
|
|
15
|
+
supportsTemperature: false,
|
|
16
|
+
supportsParallelTools: true,
|
|
17
|
+
reasoningEfforts: ALL_EFFORTS,
|
|
18
|
+
contextWindow,
|
|
19
|
+
maxOutputTokens,
|
|
20
|
+
pricing: {
|
|
21
|
+
inputUsdPerMTok: pricing.in,
|
|
22
|
+
outputUsdPerMTok: pricing.out,
|
|
23
|
+
cacheReadUsdPerMTok: pricing.cacheRead,
|
|
24
|
+
cacheWriteUsdPerMTok: pricing.cacheWrite
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
thinkingForm: "adaptive",
|
|
28
|
+
cacheMinTokens
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Static seed table; docs/04 section 4 names the current model set. */
|
|
32
|
+
const ANTHROPIC_MODELS = {
|
|
33
|
+
"claude-fable-5": current(1e6, 128e3, {
|
|
34
|
+
in: 20,
|
|
35
|
+
out: 100,
|
|
36
|
+
cacheRead: 2,
|
|
37
|
+
cacheWrite: 25
|
|
38
|
+
}, 2048),
|
|
39
|
+
"claude-opus-4-8": current(4e5, 128e3, {
|
|
40
|
+
in: 12,
|
|
41
|
+
out: 60,
|
|
42
|
+
cacheRead: 1.2,
|
|
43
|
+
cacheWrite: 15
|
|
44
|
+
}, 4096),
|
|
45
|
+
"claude-opus-4-7": current(4e5, 64e3, {
|
|
46
|
+
in: 10,
|
|
47
|
+
out: 50,
|
|
48
|
+
cacheRead: 1,
|
|
49
|
+
cacheWrite: 12.5
|
|
50
|
+
}, 4096),
|
|
51
|
+
"claude-sonnet-5": current(4e5, 64e3, {
|
|
52
|
+
in: 3,
|
|
53
|
+
out: 15,
|
|
54
|
+
cacheRead: .3,
|
|
55
|
+
cacheWrite: 3.75
|
|
56
|
+
}, 2048),
|
|
57
|
+
"claude-opus-4-6": {
|
|
58
|
+
...current(2e5, 32e3, {
|
|
59
|
+
in: 15,
|
|
60
|
+
out: 75,
|
|
61
|
+
cacheRead: 1.5,
|
|
62
|
+
cacheWrite: 18.75
|
|
63
|
+
}, 4096),
|
|
64
|
+
thinkingForm: "enabled-budget"
|
|
65
|
+
},
|
|
66
|
+
"claude-sonnet-4-6": {
|
|
67
|
+
...current(2e5, 64e3, {
|
|
68
|
+
in: 3,
|
|
69
|
+
out: 15,
|
|
70
|
+
cacheRead: .3,
|
|
71
|
+
cacheWrite: 3.75
|
|
72
|
+
}, 2048),
|
|
73
|
+
thinkingForm: "enabled-budget"
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Unknown Anthropic models are assumed current-generation: adaptive
|
|
78
|
+
* thinking, native structured outputs, no sampling parameters. refreshCaps
|
|
79
|
+
* corrects window/output figures from the live model list.
|
|
80
|
+
*/
|
|
81
|
+
function anthropicModelInfo(model) {
|
|
82
|
+
const exact = ANTHROPIC_MODELS[model];
|
|
83
|
+
if (exact !== void 0) return exact;
|
|
84
|
+
for (const [name, info] of Object.entries(ANTHROPIC_MODELS)) if (model.startsWith(`${name}-`)) return info;
|
|
85
|
+
return current(4e5, 64e3, {
|
|
86
|
+
in: 10,
|
|
87
|
+
out: 50,
|
|
88
|
+
cacheRead: 1,
|
|
89
|
+
cacheWrite: 12.5
|
|
90
|
+
}, 4096);
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/wire.ts
|
|
94
|
+
/**
|
|
95
|
+
* Canonical-to-wire mapping for the July 2026 Anthropic Messages API
|
|
96
|
+
* (M1-T12): request building (system split, tools with strict, the
|
|
97
|
+
* output_config umbrella, adaptive thinking, cache_control compilation),
|
|
98
|
+
* the SSE-to-ChatEvent stream mapper with pause_turn absorption, the full
|
|
99
|
+
* stop-reason table, and usage normalization under the Usage invariant.
|
|
100
|
+
*
|
|
101
|
+
* Owning spec: docs/04-model-layer-spec.md, section "@rulvar/anthropic".
|
|
102
|
+
* Pure functions; the adapter glue in adapter.ts owns the SDK client.
|
|
103
|
+
*/
|
|
104
|
+
/** Bijective canonical-to-wire tool-call id map (docs/04, section 1.2). */
|
|
105
|
+
var IdMap = class {
|
|
106
|
+
toWire = /* @__PURE__ */ new Map();
|
|
107
|
+
toCanonical = /* @__PURE__ */ new Map();
|
|
108
|
+
mint;
|
|
109
|
+
constructor(mint) {
|
|
110
|
+
this.mint = mint;
|
|
111
|
+
}
|
|
112
|
+
canonicalFor(wireId) {
|
|
113
|
+
const existing = this.toCanonical.get(wireId);
|
|
114
|
+
if (existing !== void 0) return existing;
|
|
115
|
+
const canonical = this.mint();
|
|
116
|
+
this.toCanonical.set(wireId, canonical);
|
|
117
|
+
this.toWire.set(canonical, wireId);
|
|
118
|
+
return canonical;
|
|
119
|
+
}
|
|
120
|
+
wireFor(canonicalId) {
|
|
121
|
+
const existing = this.toWire.get(canonicalId);
|
|
122
|
+
if (existing !== void 0) return existing;
|
|
123
|
+
const wireId = `toolu_${canonicalId}`;
|
|
124
|
+
this.toWire.set(canonicalId, wireId);
|
|
125
|
+
this.toCanonical.set(wireId, canonicalId);
|
|
126
|
+
return wireId;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
function cacheControl(ttl) {
|
|
130
|
+
return ttl === "1h" ? {
|
|
131
|
+
type: "ephemeral",
|
|
132
|
+
ttl: "1h"
|
|
133
|
+
} : { type: "ephemeral" };
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Builds Messages API params from a ChatRequest. cacheHint compiles into
|
|
137
|
+
* cache_control breakpoints; beyond the provider cap of 4 the DEEPEST
|
|
138
|
+
* breakpoints are kept and the shallowest dropped, deterministically
|
|
139
|
+
* (docs/04, sections 1.7 and 4.4).
|
|
140
|
+
*/
|
|
141
|
+
function buildAnthropicParams(req, options) {
|
|
142
|
+
const systemBlocks = [];
|
|
143
|
+
const messages = [];
|
|
144
|
+
for (const msg of req.messages) {
|
|
145
|
+
if (msg.role === "system") {
|
|
146
|
+
for (const part of msg.parts) if (part.type === "text") systemBlocks.push({
|
|
147
|
+
type: "text",
|
|
148
|
+
text: part.text
|
|
149
|
+
});
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const content = [];
|
|
153
|
+
for (const part of msg.parts) switch (part.type) {
|
|
154
|
+
case "text":
|
|
155
|
+
content.push({
|
|
156
|
+
type: "text",
|
|
157
|
+
text: part.text
|
|
158
|
+
});
|
|
159
|
+
break;
|
|
160
|
+
case "image":
|
|
161
|
+
content.push({
|
|
162
|
+
type: "image",
|
|
163
|
+
source: typeof part.data === "string" && part.data.startsWith("http") ? {
|
|
164
|
+
type: "url",
|
|
165
|
+
url: part.data
|
|
166
|
+
} : {
|
|
167
|
+
type: "base64",
|
|
168
|
+
media_type: part.mediaType,
|
|
169
|
+
data: typeof part.data === "string" ? part.data : Buffer.from(part.data).toString("base64")
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
break;
|
|
173
|
+
case "tool-call":
|
|
174
|
+
content.push({
|
|
175
|
+
type: "tool_use",
|
|
176
|
+
id: options.ids.wireFor(part.id),
|
|
177
|
+
name: part.name,
|
|
178
|
+
input: part.args ?? {}
|
|
179
|
+
});
|
|
180
|
+
break;
|
|
181
|
+
case "tool-result":
|
|
182
|
+
content.push({
|
|
183
|
+
type: "tool_result",
|
|
184
|
+
tool_use_id: options.ids.wireFor(part.id),
|
|
185
|
+
content: typeof part.result === "string" ? part.result : JSON.stringify(part.result ?? null),
|
|
186
|
+
...part.isError === true ? { is_error: true } : {}
|
|
187
|
+
});
|
|
188
|
+
break;
|
|
189
|
+
case "provider-raw":
|
|
190
|
+
if (part.provider === "anthropic") content.push(part.block);
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
messages.push({
|
|
194
|
+
role: msg.role === "tool" ? "user" : msg.role,
|
|
195
|
+
content
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const params = {
|
|
199
|
+
model: req.model,
|
|
200
|
+
max_tokens: req.maxOutputTokens ?? options.maxOutputTokens,
|
|
201
|
+
messages
|
|
202
|
+
};
|
|
203
|
+
if (systemBlocks.length > 0) params.system = systemBlocks;
|
|
204
|
+
if (req.stopSequences !== void 0) params.stop_sequences = req.stopSequences;
|
|
205
|
+
if (req.tools !== void 0) {
|
|
206
|
+
params.tools = req.tools.map((tool) => ({
|
|
207
|
+
name: tool.name,
|
|
208
|
+
description: tool.description,
|
|
209
|
+
input_schema: tool.parameters,
|
|
210
|
+
...isStrictCompatibleSchema(tool.parameters) ? { strict: true } : {}
|
|
211
|
+
}));
|
|
212
|
+
if (req.toolChoice === "required") params.tool_choice = { type: "any" };
|
|
213
|
+
else if (typeof req.toolChoice === "object") params.tool_choice = {
|
|
214
|
+
type: "tool",
|
|
215
|
+
name: req.toolChoice.name
|
|
216
|
+
};
|
|
217
|
+
else if (req.toolChoice === "auto") params.tool_choice = { type: "auto" };
|
|
218
|
+
else if (req.toolChoice === "none") params.tool_choice = { type: "none" };
|
|
219
|
+
}
|
|
220
|
+
const anthropicOptions = req.providerOptions?.anthropic ?? {};
|
|
221
|
+
const outputConfig = {};
|
|
222
|
+
if (req.effort !== void 0) outputConfig.effort = req.effort;
|
|
223
|
+
if (req.schema !== void 0) outputConfig.format = {
|
|
224
|
+
type: "json_schema",
|
|
225
|
+
schema: req.schema
|
|
226
|
+
};
|
|
227
|
+
if (anthropicOptions.task_budget !== void 0) outputConfig.task_budget = anthropicOptions.task_budget;
|
|
228
|
+
if (Object.keys(outputConfig).length > 0) params.output_config = outputConfig;
|
|
229
|
+
if (anthropicOptions.thinking !== void 0) params.thinking = anthropicOptions.thinking;
|
|
230
|
+
else if (options.thinkingForm === "adaptive") {
|
|
231
|
+
const display = anthropicOptions.thinkingDisplay;
|
|
232
|
+
params.thinking = typeof display === "string" ? {
|
|
233
|
+
type: "adaptive",
|
|
234
|
+
display
|
|
235
|
+
} : { type: "adaptive" };
|
|
236
|
+
}
|
|
237
|
+
for (const key of [
|
|
238
|
+
"temperature",
|
|
239
|
+
"top_p",
|
|
240
|
+
"top_k"
|
|
241
|
+
]) if (anthropicOptions[key] !== void 0) params[key] = anthropicOptions[key];
|
|
242
|
+
applyCacheHint(params, req.cacheHint);
|
|
243
|
+
return params;
|
|
244
|
+
}
|
|
245
|
+
function applyCacheHint(params, hint) {
|
|
246
|
+
if (hint === void 0 || hint.breakpoints.length === 0) return;
|
|
247
|
+
const kept = hint.breakpoints.slice(-4);
|
|
248
|
+
const tools = params.tools;
|
|
249
|
+
const system = params.system;
|
|
250
|
+
const messages = params.messages;
|
|
251
|
+
for (const breakpoint of kept) {
|
|
252
|
+
const control = cacheControl(breakpoint.ttl);
|
|
253
|
+
if (breakpoint.after === "tools") {
|
|
254
|
+
const last = tools?.[tools.length - 1];
|
|
255
|
+
if (last !== void 0) last.cache_control = control;
|
|
256
|
+
} else if (breakpoint.after === "system") {
|
|
257
|
+
const last = system?.[system.length - 1];
|
|
258
|
+
if (last !== void 0) last.cache_control = control;
|
|
259
|
+
} else {
|
|
260
|
+
const content = messages[breakpoint.after.messageIndex]?.content;
|
|
261
|
+
const last = content?.[content.length - 1];
|
|
262
|
+
if (last !== void 0) last.cache_control = control;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* The docs/04 section 4.7 stop-reason table. pause_turn never surfaces as
|
|
268
|
+
* a canonical finish: the adapter continues internally.
|
|
269
|
+
*/
|
|
270
|
+
function mapStopReason(stopReason, stopDetails) {
|
|
271
|
+
switch (stopReason) {
|
|
272
|
+
case "end_turn":
|
|
273
|
+
case "stop_sequence": return {
|
|
274
|
+
finish: { reason: "stop" },
|
|
275
|
+
pauseTurn: false
|
|
276
|
+
};
|
|
277
|
+
case "tool_use": return {
|
|
278
|
+
finish: { reason: "tool-calls" },
|
|
279
|
+
pauseTurn: false
|
|
280
|
+
};
|
|
281
|
+
case "max_tokens": return {
|
|
282
|
+
finish: { reason: "max-tokens" },
|
|
283
|
+
pauseTurn: false
|
|
284
|
+
};
|
|
285
|
+
case "model_context_window_exceeded": return {
|
|
286
|
+
finish: { reason: "context-window-exceeded" },
|
|
287
|
+
pauseTurn: false
|
|
288
|
+
};
|
|
289
|
+
case "refusal": return {
|
|
290
|
+
finish: {
|
|
291
|
+
reason: "refusal",
|
|
292
|
+
refusal: {
|
|
293
|
+
provider: "anthropic",
|
|
294
|
+
...stopDetails === null || stopDetails === void 0 ? {} : { stopDetails: {
|
|
295
|
+
...typeof stopDetails.type === "string" ? { type: stopDetails.type } : {},
|
|
296
|
+
...typeof stopDetails.category === "string" ? { category: stopDetails.category } : {},
|
|
297
|
+
...typeof stopDetails.explanation === "string" ? { explanation: stopDetails.explanation } : {}
|
|
298
|
+
} }
|
|
299
|
+
}
|
|
300
|
+
},
|
|
301
|
+
pauseTurn: false
|
|
302
|
+
};
|
|
303
|
+
case "pause_turn": return { pauseTurn: true };
|
|
304
|
+
default: return {
|
|
305
|
+
finish: { reason: "stop" },
|
|
306
|
+
pauseTurn: false
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Normalizes Messages API usage under the Usage invariant: Anthropic
|
|
312
|
+
* reports input_tokens EXCLUDING cache reads and writes, so the canonical
|
|
313
|
+
* inputTokens is the sum of all three (docs/04, sections 1.6 and 4.4).
|
|
314
|
+
*/
|
|
315
|
+
function normalizeAnthropicUsage(raw) {
|
|
316
|
+
const input = typeof raw?.input_tokens === "number" ? raw.input_tokens : 0;
|
|
317
|
+
const output = typeof raw?.output_tokens === "number" ? raw.output_tokens : 0;
|
|
318
|
+
const cacheRead = typeof raw?.cache_read_input_tokens === "number" ? raw.cache_read_input_tokens : 0;
|
|
319
|
+
const cacheWrite = typeof raw?.cache_creation_input_tokens === "number" ? raw.cache_creation_input_tokens : 0;
|
|
320
|
+
return {
|
|
321
|
+
inputTokens: input + cacheRead + cacheWrite,
|
|
322
|
+
outputTokens: output,
|
|
323
|
+
cacheReadTokens: cacheRead,
|
|
324
|
+
cacheWriteTokens: cacheWrite
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Maps one Messages API stream into ChatEvents. Emits an early usage event
|
|
329
|
+
* from message_start (the input side is known immediately) and exactly one
|
|
330
|
+
* terminal finish unless the turn paused (pause_turn) or errored.
|
|
331
|
+
* `carryRetained` holds thinking blocks from earlier pause_turn
|
|
332
|
+
* continuations of the same turn so the terminal finish ships the whole
|
|
333
|
+
* turn's retention payload (docs/04, section 2.3, M4-T02).
|
|
334
|
+
*/
|
|
335
|
+
async function mapAnthropicStream(stream, ids, emit, options) {
|
|
336
|
+
const mapping = {
|
|
337
|
+
events: [],
|
|
338
|
+
assistantContent: [],
|
|
339
|
+
pauseTurn: false,
|
|
340
|
+
finished: false
|
|
341
|
+
};
|
|
342
|
+
const push = (event) => {
|
|
343
|
+
mapping.events.push(event);
|
|
344
|
+
emit(event);
|
|
345
|
+
};
|
|
346
|
+
let usage = {
|
|
347
|
+
inputTokens: 0,
|
|
348
|
+
outputTokens: 0,
|
|
349
|
+
cacheReadTokens: 0,
|
|
350
|
+
cacheWriteTokens: 0
|
|
351
|
+
};
|
|
352
|
+
let stopReason;
|
|
353
|
+
let stopSequence;
|
|
354
|
+
let stopDetails;
|
|
355
|
+
let responseId;
|
|
356
|
+
const openBlocks = /* @__PURE__ */ new Map();
|
|
357
|
+
for await (const event of stream) switch (event.type) {
|
|
358
|
+
case "message_start": {
|
|
359
|
+
const message = event.message;
|
|
360
|
+
responseId = typeof message?.id === "string" ? message.id : void 0;
|
|
361
|
+
usage = normalizeAnthropicUsage(message?.usage);
|
|
362
|
+
push({
|
|
363
|
+
type: "usage",
|
|
364
|
+
usage: { ...usage }
|
|
365
|
+
});
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
case "content_block_start": {
|
|
369
|
+
const index = event.index;
|
|
370
|
+
const block = event.content_block;
|
|
371
|
+
const type = block.type;
|
|
372
|
+
if (type === "tool_use") {
|
|
373
|
+
const wireId = block.id;
|
|
374
|
+
const canonicalId = ids.canonicalFor(wireId);
|
|
375
|
+
openBlocks.set(index, {
|
|
376
|
+
kind: "tool_use",
|
|
377
|
+
canonicalId,
|
|
378
|
+
json: "",
|
|
379
|
+
block: { ...block }
|
|
380
|
+
});
|
|
381
|
+
push({
|
|
382
|
+
type: "tool-call-start",
|
|
383
|
+
id: canonicalId,
|
|
384
|
+
name: block.name
|
|
385
|
+
});
|
|
386
|
+
} else if (type === "thinking" || type === "redacted_thinking") openBlocks.set(index, {
|
|
387
|
+
kind: "thinking",
|
|
388
|
+
json: "",
|
|
389
|
+
block: { ...block }
|
|
390
|
+
});
|
|
391
|
+
else if (type === "text") openBlocks.set(index, {
|
|
392
|
+
kind: "text",
|
|
393
|
+
json: "",
|
|
394
|
+
block: {
|
|
395
|
+
...block,
|
|
396
|
+
text: ""
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
else openBlocks.set(index, {
|
|
400
|
+
kind: "other",
|
|
401
|
+
json: "",
|
|
402
|
+
block: { ...block }
|
|
403
|
+
});
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
case "content_block_delta": {
|
|
407
|
+
const index = event.index;
|
|
408
|
+
const delta = event.delta;
|
|
409
|
+
const open = openBlocks.get(index);
|
|
410
|
+
if (open === void 0) break;
|
|
411
|
+
if (delta.type === "text_delta") {
|
|
412
|
+
const text = delta.text;
|
|
413
|
+
open.block.text = `${open.block.text ?? ""}${text}`;
|
|
414
|
+
push({
|
|
415
|
+
type: "text-delta",
|
|
416
|
+
text
|
|
417
|
+
});
|
|
418
|
+
} else if (delta.type === "thinking_delta") {
|
|
419
|
+
const text = delta.thinking;
|
|
420
|
+
open.block.thinking = `${open.block.thinking ?? ""}${text}`;
|
|
421
|
+
push({
|
|
422
|
+
type: "reasoning-delta",
|
|
423
|
+
text
|
|
424
|
+
});
|
|
425
|
+
} else if (delta.type === "input_json_delta") {
|
|
426
|
+
const partial = delta.partial_json;
|
|
427
|
+
open.json += partial;
|
|
428
|
+
if (open.canonicalId !== void 0) push({
|
|
429
|
+
type: "tool-call-delta",
|
|
430
|
+
id: open.canonicalId,
|
|
431
|
+
argsTextDelta: partial
|
|
432
|
+
});
|
|
433
|
+
} else if (delta.type === "signature_delta") open.block.signature = `${open.block.signature ?? ""}${delta.signature}`;
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
case "content_block_stop": {
|
|
437
|
+
const index = event.index;
|
|
438
|
+
const open = openBlocks.get(index);
|
|
439
|
+
if (open === void 0) break;
|
|
440
|
+
openBlocks.delete(index);
|
|
441
|
+
if (open.kind === "tool_use" && open.canonicalId !== void 0) {
|
|
442
|
+
let args = {};
|
|
443
|
+
try {
|
|
444
|
+
args = open.json === "" ? {} : JSON.parse(open.json);
|
|
445
|
+
} catch {
|
|
446
|
+
args = { __unparsed: open.json };
|
|
447
|
+
}
|
|
448
|
+
open.block.input = args;
|
|
449
|
+
push({
|
|
450
|
+
type: "tool-call-end",
|
|
451
|
+
id: open.canonicalId,
|
|
452
|
+
args
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
mapping.assistantContent.push(open.block);
|
|
456
|
+
break;
|
|
457
|
+
}
|
|
458
|
+
case "message_delta": {
|
|
459
|
+
const delta = event.delta;
|
|
460
|
+
if (typeof delta?.stop_reason === "string") stopReason = delta.stop_reason;
|
|
461
|
+
if (typeof delta?.stop_sequence === "string") stopSequence = delta.stop_sequence;
|
|
462
|
+
if (delta?.stop_details !== void 0 && delta.stop_details !== null) stopDetails = delta.stop_details;
|
|
463
|
+
const deltaUsage = event.usage;
|
|
464
|
+
if (typeof deltaUsage?.output_tokens === "number") usage = {
|
|
465
|
+
...usage,
|
|
466
|
+
outputTokens: deltaUsage.output_tokens
|
|
467
|
+
};
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
case "message_stop": {
|
|
471
|
+
const mapped = mapStopReason(stopReason, stopDetails);
|
|
472
|
+
if (mapped.pauseTurn) {
|
|
473
|
+
mapping.pauseTurn = true;
|
|
474
|
+
return mapping;
|
|
475
|
+
}
|
|
476
|
+
const providerMetadata = { anthropic: {} };
|
|
477
|
+
const meta = providerMetadata.anthropic;
|
|
478
|
+
if (responseId !== void 0) meta.responseId = responseId;
|
|
479
|
+
if (stopSequence !== void 0) meta.stopSequence = stopSequence;
|
|
480
|
+
const retained = [...options?.carryRetained ?? [], ...mapping.assistantContent.filter((block) => block.type === "thinking" || block.type === "redacted_thinking")];
|
|
481
|
+
if (retained.length > 0) meta.retainedParts = retained;
|
|
482
|
+
push({
|
|
483
|
+
type: "finish",
|
|
484
|
+
finish: mapped.finish ?? { reason: "stop" },
|
|
485
|
+
usage,
|
|
486
|
+
providerMetadata
|
|
487
|
+
});
|
|
488
|
+
mapping.finished = true;
|
|
489
|
+
return mapping;
|
|
490
|
+
}
|
|
491
|
+
default: break;
|
|
492
|
+
}
|
|
493
|
+
return mapping;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Projects an SDK/API error into the retryable WireError vocabulary:
|
|
497
|
+
* 429 rate limits surface retryAfterMs and the x-ratelimit-* buckets; 529
|
|
498
|
+
* overloaded and 5xx are retryable transport; everything else is terminal
|
|
499
|
+
* transport (docs/04, section 4.9). Adapters never sleep internally.
|
|
500
|
+
*/
|
|
501
|
+
function anthropicErrorToWire(error) {
|
|
502
|
+
const record = error;
|
|
503
|
+
const status = typeof record.status === "number" ? record.status : void 0;
|
|
504
|
+
const message = typeof record.message === "string" ? record.message : String(error);
|
|
505
|
+
const headerGet = (name) => {
|
|
506
|
+
const headers = record.headers;
|
|
507
|
+
if (headers === void 0 || headers === null) return;
|
|
508
|
+
if (typeof headers.get === "function") return headers.get(name) ?? void 0;
|
|
509
|
+
return headers[name];
|
|
510
|
+
};
|
|
511
|
+
if (status === 429) {
|
|
512
|
+
const retryAfter = headerGet("retry-after");
|
|
513
|
+
const buckets = {};
|
|
514
|
+
for (const name of [
|
|
515
|
+
"x-ratelimit-limit-requests",
|
|
516
|
+
"x-ratelimit-remaining-requests",
|
|
517
|
+
"x-ratelimit-limit-input-tokens",
|
|
518
|
+
"x-ratelimit-remaining-input-tokens",
|
|
519
|
+
"x-ratelimit-limit-output-tokens",
|
|
520
|
+
"x-ratelimit-remaining-output-tokens"
|
|
521
|
+
]) {
|
|
522
|
+
const value = headerGet(name);
|
|
523
|
+
if (value !== void 0) buckets[name] = value;
|
|
524
|
+
}
|
|
525
|
+
return {
|
|
526
|
+
code: "agent",
|
|
527
|
+
message,
|
|
528
|
+
retryable: true,
|
|
529
|
+
data: {
|
|
530
|
+
kind: "rate-limit",
|
|
531
|
+
...retryAfter === void 0 ? {} : { retryAfterMs: Number(retryAfter) * 1e3 },
|
|
532
|
+
...Object.keys(buckets).length > 0 ? { buckets } : {},
|
|
533
|
+
status: 429
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
return {
|
|
538
|
+
code: "agent",
|
|
539
|
+
message,
|
|
540
|
+
retryable: status === void 0 || status === 529 || status >= 500,
|
|
541
|
+
data: {
|
|
542
|
+
kind: "transport",
|
|
543
|
+
...status === void 0 ? {} : { status }
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
//#endregion
|
|
548
|
+
//#region src/adapter.ts
|
|
549
|
+
/**
|
|
550
|
+
* The @rulvar/anthropic ProviderAdapter (M1-T12): SDK glue over the pure
|
|
551
|
+
* wire mapping, with pause_turn absorption, SDK autoretries disabled, and
|
|
552
|
+
* refreshCaps from the capabilities-bearing model list.
|
|
553
|
+
*
|
|
554
|
+
* Owning spec: docs/04-model-layer-spec.md, section "@rulvar/anthropic".
|
|
555
|
+
*/
|
|
556
|
+
/** pause_turn continuation cap (docs/06 Appendix A; docs/04, section 4.6). */
|
|
557
|
+
const DEFAULT_PAUSE_TURN_MAX_CONTINUATIONS = 5;
|
|
558
|
+
/**
|
|
559
|
+
* Creates the first-class Anthropic adapter (id 'anthropic'). SDK
|
|
560
|
+
* autoretries are disabled (max_retries 0): the core owns retries and
|
|
561
|
+
* wall-clock (docs/04, section "Retries belong to the core").
|
|
562
|
+
*/
|
|
563
|
+
function anthropic(options = {}) {
|
|
564
|
+
const client = options.client ?? new Anthropic({
|
|
565
|
+
...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
|
|
566
|
+
...options.baseURL === void 0 ? {} : { baseURL: options.baseURL },
|
|
567
|
+
maxRetries: 0
|
|
568
|
+
});
|
|
569
|
+
const ids = new IdMap(createCanonicalIdMinter());
|
|
570
|
+
const refreshed = /* @__PURE__ */ new Map();
|
|
571
|
+
function infoFor(model) {
|
|
572
|
+
const base = anthropicModelInfo(model);
|
|
573
|
+
const patch = refreshed.get(model);
|
|
574
|
+
if (patch === void 0) return base;
|
|
575
|
+
return {
|
|
576
|
+
...base,
|
|
577
|
+
caps: {
|
|
578
|
+
...base.caps,
|
|
579
|
+
...patch
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
return {
|
|
584
|
+
id: "anthropic",
|
|
585
|
+
provider: "anthropic",
|
|
586
|
+
caps(model) {
|
|
587
|
+
return infoFor(model).caps;
|
|
588
|
+
},
|
|
589
|
+
async refreshCaps() {
|
|
590
|
+
let afterId;
|
|
591
|
+
do {
|
|
592
|
+
const page = await client.models.list(afterId === void 0 ? {} : { after_id: afterId });
|
|
593
|
+
for (const model of page.data) {
|
|
594
|
+
const id = model.id;
|
|
595
|
+
if (typeof id !== "string") continue;
|
|
596
|
+
const patch = {};
|
|
597
|
+
if (typeof model.max_input_tokens === "number") patch.contextWindow = model.max_input_tokens;
|
|
598
|
+
if (typeof model.max_tokens === "number") patch.maxOutputTokens = model.max_tokens;
|
|
599
|
+
if (Object.keys(patch).length > 0) refreshed.set(id, patch);
|
|
600
|
+
}
|
|
601
|
+
afterId = page.has_more === true && typeof page.last_id === "string" ? page.last_id : void 0;
|
|
602
|
+
} while (afterId !== void 0);
|
|
603
|
+
},
|
|
604
|
+
async *stream(req, signal) {
|
|
605
|
+
const info = infoFor(req.model);
|
|
606
|
+
const pauseCap = typeof req.providerOptions?.anthropic?.pauseTurnMaxContinuations === "number" ? req.providerOptions.anthropic.pauseTurnMaxContinuations : 5;
|
|
607
|
+
let params = buildAnthropicParams(req, {
|
|
608
|
+
ids,
|
|
609
|
+
maxOutputTokens: info.caps.maxOutputTokens,
|
|
610
|
+
thinkingForm: info.thinkingForm
|
|
611
|
+
});
|
|
612
|
+
const pending = [];
|
|
613
|
+
let continuations = 0;
|
|
614
|
+
const carryRetained = [];
|
|
615
|
+
while (true) {
|
|
616
|
+
let stream;
|
|
617
|
+
try {
|
|
618
|
+
stream = await client.messages.create({
|
|
619
|
+
...params,
|
|
620
|
+
stream: true
|
|
621
|
+
}, signal === void 0 ? void 0 : { signal });
|
|
622
|
+
} catch (thrown) {
|
|
623
|
+
yield {
|
|
624
|
+
type: "error",
|
|
625
|
+
error: anthropicErrorToWire(thrown)
|
|
626
|
+
};
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
let mapping;
|
|
630
|
+
try {
|
|
631
|
+
mapping = await mapAnthropicStream(stream, ids, (event) => pending.push(event), { carryRetained });
|
|
632
|
+
} catch (thrown) {
|
|
633
|
+
if (signal?.aborted === true) return;
|
|
634
|
+
yield {
|
|
635
|
+
type: "error",
|
|
636
|
+
error: anthropicErrorToWire(thrown)
|
|
637
|
+
};
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
for (const event of pending) yield event;
|
|
641
|
+
pending.length = 0;
|
|
642
|
+
if (!mapping.pauseTurn) return;
|
|
643
|
+
carryRetained.push(...mapping.assistantContent.filter((block) => block.type === "thinking" || block.type === "redacted_thinking"));
|
|
644
|
+
continuations += 1;
|
|
645
|
+
if (continuations > pauseCap) {
|
|
646
|
+
yield {
|
|
647
|
+
type: "error",
|
|
648
|
+
error: {
|
|
649
|
+
code: "agent",
|
|
650
|
+
message: `pause_turn continuation cap (${pauseCap}) exceeded`,
|
|
651
|
+
retryable: true,
|
|
652
|
+
data: { kind: "transport" }
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
const messages = params.messages;
|
|
658
|
+
params = {
|
|
659
|
+
...params,
|
|
660
|
+
messages: [...messages, {
|
|
661
|
+
role: "assistant",
|
|
662
|
+
content: mapping.assistantContent
|
|
663
|
+
}]
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
},
|
|
667
|
+
async countTokens(req) {
|
|
668
|
+
const info = infoFor(req.model);
|
|
669
|
+
const params = buildAnthropicParams(req, {
|
|
670
|
+
ids,
|
|
671
|
+
maxOutputTokens: info.caps.maxOutputTokens,
|
|
672
|
+
thinkingForm: info.thinkingForm
|
|
673
|
+
});
|
|
674
|
+
const body = {
|
|
675
|
+
model: params.model,
|
|
676
|
+
messages: params.messages
|
|
677
|
+
};
|
|
678
|
+
if (params.system !== void 0) body.system = params.system;
|
|
679
|
+
if (params.tools !== void 0) body.tools = params.tools;
|
|
680
|
+
return (await client.messages.countTokens(body)).input_tokens;
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
//#endregion
|
|
685
|
+
export { ANTHROPIC_MODELS, DEFAULT_PAUSE_TURN_MAX_CONTINUATIONS, IdMap, anthropic, anthropicErrorToWire, anthropicModelInfo, buildAnthropicParams, mapAnthropicStream, mapStopReason, normalizeAnthropicUsage };
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rulvar/anthropic",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "rulvar first-class provider adapter over @anthropic-ai/sdk.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.12.0"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@anthropic-ai/sdk": "^0.110.0",
|
|
26
|
+
"@rulvar/core": "1.0.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^22.20.0",
|
|
30
|
+
"tsdown": "^0.22.3",
|
|
31
|
+
"typescript": "~6.0.3"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/o-stepper/rulvar.git",
|
|
36
|
+
"directory": "packages/anthropic"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://rulvar.com",
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/o-stepper/rulvar/issues"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsdown",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"lint": "eslint .",
|
|
46
|
+
"pack-check": "publint --pack pnpm && attw --pack . --profile esm-only"
|
|
47
|
+
}
|
|
48
|
+
}
|