magpie-plugin-retry 0.0.0-stage → 2.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -2
  3. package/package.json +45 -4
  4. package/src/index.mjs +429 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 magpie-plugin-retry contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,179 @@
1
- # Temporary Holding Version
1
+ # magpie-plugin-retry
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 一个通用的 [Magpie](https://usemagpie.ai) provider 插件:客户端请求一个模型,
4
+ 插件确保真正回答的是配置好的另一个模型;不匹配就自动重试。
5
+
6
+ 适用于 new-api / one-api 这类中转:请求模型名是聚合别名,而流式响应里的
7
+ `message_start.message.model` 才会暴露真实后端模型。
8
+
9
+ ## 工作方式
10
+
11
+ 1. 插件暴露你在 `models` 里配置的请求模型。
12
+ 2. 每次请求转发到 `baseURL` 下的 Anthropic Messages 路径 `/messages`,并强制
13
+ `stream: true`。
14
+ 3. 解析 `event: message_start` 里的 `data.message.model`。
15
+ 4. 如果响应模型等于该请求模型配置的 `target`,原样放行流式响应。
16
+ 5. 如果不是目标模型:
17
+ - 取消当前上游请求;
18
+ - 按 `maxAttempts` 重试;
19
+ - 仍不命中就返回错误,避免把错误模型冒充成目标模型。
20
+ 6. 客户端请求非流式时,插件读取完整 SSE,聚合成 Anthropic Messages JSON。
21
+
22
+ ## 要求
23
+
24
+ - Magpie `0.1.5363` 或更高版本
25
+ - 上游兼容 Anthropic Messages API(`/v1/messages`)
26
+ - 上游流式响应会在 `message_start.message.model` 中暴露真实模型
27
+ - 发布/开发时需要 Node.js 20+;日常使用不需要单独安装 Node
28
+
29
+ ## 安装
30
+
31
+ ### 从 npm 安装(发布后)
32
+
33
+ ```sh
34
+ magpie plugin add npm:magpie-plugin-retry
35
+ ```
36
+
37
+ ### 从本地目录安装
38
+
39
+ ```sh
40
+ magpie plugin add /Users/bill/WorkSpace/magpie-plugin-retry
41
+ ```
42
+
43
+ `npm pack` 只用于检查发布内容;Magpie 的 `plugin add` 不能直接导入 `.tgz` 文件。
44
+
45
+ ### 安装后
46
+
47
+ 先按下一节完成配置,再登录并测试:
48
+
49
+ ```sh
50
+ magpie plugin login retry api
51
+ magpie provider test retry
52
+ ```
53
+
54
+ 登录时粘贴上游 API Key。Key 只保存在 Magpie 的账号存储里,不写进本包。
55
+
56
+ ## 配置
57
+
58
+ 通过 `magpie plugin options <安装时的 spec> '<json>'` 设置。本地目录安装时 spec 是目录
59
+ 路径;从 npm 安装时通常是 `npm:magpie-plugin-retry`。`baseURL` 和 `models` 都是必填项,
60
+ 插件不提供默认地址或默认模型映射;未配置时 provider 不会暴露任何模型。
61
+
62
+ ```sh
63
+ # 本地目录安装
64
+ magpie plugin options /Users/bill/WorkSpace/magpie-plugin-retry '<json>'
65
+
66
+ # npm 安装
67
+ magpie plugin options npm:magpie-plugin-retry '<json>'
68
+ ```
69
+
70
+ 最小配置示例:
71
+
72
+ ```json
73
+ {
74
+ "baseURL": "https://your-relay.example.com/v1",
75
+ "models": {
76
+ "vendor/asked-model": {
77
+ "target": "vendor/served-model",
78
+ "name": "Vendor Served"
79
+ }
80
+ },
81
+ "maxAttempts": 12
82
+ }
83
+ ```
84
+
85
+ `models` 的 key 是客户端请求模型,value 可以是目标模型字符串,也可以是带
86
+ `target` / `name` 的对象:
87
+
88
+ ```json
89
+ {
90
+ "baseURL": "https://your-relay.example.com/v1",
91
+ "models": {
92
+ "vendor/asked-model": "vendor/served-model",
93
+ "other/asked-model": {
94
+ "target": "other/served-model",
95
+ "name": "Other Served"
96
+ }
97
+ }
98
+ }
99
+ ```
100
+
101
+ 也支持单组写法:
102
+
103
+ ```json
104
+ {
105
+ "baseURL": "https://your-relay.example.com/v1",
106
+ "requestModel": "vendor/asked-model",
107
+ "targetModel": "vendor/served-model"
108
+ }
109
+ ```
110
+
111
+ ### 配置项
112
+
113
+ | 选项 | 默认值 | 说明 |
114
+ |---|---|---|
115
+ | `baseURL` | 必填 | 上游 API 地址,必须以 `/v1` 结尾 |
116
+ | `apiKey` | 空 | 可选固定 Key;正常使用优先 `magpie plugin login`,登录 Key 优先 |
117
+ | `models` | 必填 | 请求模型 → 目标模型映射,支持对象或数组 |
118
+ | `requestModel` | 空 | 只配置一组映射时的请求模型 |
119
+ | `targetModel` | 空 | 只配置一组映射时的目标模型 |
120
+ | `providerId` | `retry` | Magpie provider id;改它等于换一个 provider |
121
+ | `providerName` | `Model Retry` | Magpie UI 中显示的 provider 名 |
122
+ | `maxAttempts` | `12` | 每次请求最多尝试次数,最大 50 |
123
+ | `maxConcurrency` | `4` | 每个账号并发请求数,最大 32 |
124
+
125
+ 插件没有内置默认映射;每次安装后都需要显式设置 `baseURL` 和至少一个 `models` 映射。
126
+
127
+ ## 使用
128
+
129
+ 配置完成后,完整模型 ID 是:
130
+
131
+ ```text
132
+ retry/<请求模型>
133
+ ```
134
+
135
+ 例如配置了上面的示例后:
136
+
137
+ ```text
138
+ retry/deepseek/DeepSeek-V4-Flash
139
+ ```
140
+
141
+ DeepSeek Harness(DSH)切换命令:
142
+
143
+ ```sh
144
+ magpie dsh retry/deepseek/DeepSeek-V4-Flash
145
+ ```
146
+
147
+ 其他 Agent 可用 `magpie models` 查看,或按 Magpie 的常规方式选择该 provider/model。
148
+
149
+ ## 验证
150
+
151
+ 包内测试使用本地 mock 上游,不访问真实 relay:
152
+
153
+ ```sh
154
+ npm test
155
+ npm run check
156
+ npm pack --dry-run
157
+ ```
158
+
159
+ ## 发布到 npm
160
+
161
+ ```sh
162
+ cd /Users/bill/WorkSpace/magpie-plugin-retry
163
+ npm publish --access public
164
+ ```
165
+
166
+ 发布后可用 `magpie plugin add npm:magpie-plugin-retry` 安装。
167
+
168
+ ## 限制与注意事项
169
+
170
+ - 插件依赖上游 Anthropic 流式响应暴露真实 `model`。若上游不返回这个字段,插件无法
171
+ 判断后端,会在重试耗尽后失败。
172
+ - 重试会重复发送上下文,可能重复计费输入 token;命中率低时也会增加首 token 延迟。
173
+ - 插件只处理 Anthropic Messages 路径(`/v1/messages`),不处理 Chat Completions
174
+ 或 Responses 路径。
175
+ - 插件不能改变 new-api 的令牌分组;若上游侧没有目标模型渠道,插件也不能变出渠道。
176
+
177
+ ## 许可证
178
+
179
+ MIT
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "magpie-plugin-retry",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0",
4
+ "description": "Generic Magpie provider plugin that pins any requested model to a configured real target model by checking the upstream's streaming response.",
5
+ "private": false,
6
+ "type": "module",
7
+ "main": "./src/index.mjs",
8
+ "exports": {
9
+ ".": "./src/index.mjs"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test",
21
+ "check": "node --check src/index.mjs && node --test"
22
+ },
23
+ "keywords": [
24
+ "magpie",
25
+ "magpie-plugin",
26
+ "provider",
27
+ "retry",
28
+ "model-mapping",
29
+ "new-api"
30
+ ],
31
+ "license": "MIT",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/site-chenwei/magpie-plugin-retry.git"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "magpie": {
40
+ "name": "Model Retry",
41
+ "summary": {
42
+ "zh": "通用 Magpie provider 插件:配置请求模型与需要固定的真实响应模型,自动检查并重试。",
43
+ "en": "A generic Magpie provider plugin that pins a requested model to a configured real target model, checking and retrying automatically."
44
+ },
45
+ "maxConcurrency": 4
46
+ }
47
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,429 @@
1
+ // Magpie provider plugin: ask for one model, require another model to answer.
2
+ //
3
+ // The upstream's Anthropic /v1/messages endpoint may hide the real backend
4
+ // model in non-stream replies, but expose it in streaming message_start
5
+ // events. This plugin therefore always asks upstream for a stream, checks
6
+ // message_start.message.model, and retries until the configured target model
7
+ // answers. Non-stream clients get the stream collapsed back into one
8
+ // Anthropic Messages JSON response.
9
+
10
+ const DEFAULT_PROVIDER_ID = "retry";
11
+ const DEFAULT_PROVIDER_NAME = "Model Retry";
12
+ const DEFAULT_MAX_ATTEMPTS = 12;
13
+ const RETRY_STATUS = new Set([408, 409, 425, 429, 500, 502, 503, 504]);
14
+
15
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
16
+
17
+ function parseBody(body) {
18
+ if (body == null) return null;
19
+ if (typeof body === "string") {
20
+ try {
21
+ return JSON.parse(body);
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+ if (body instanceof Uint8Array) {
27
+ try {
28
+ return JSON.parse(new TextDecoder().decode(body));
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+
36
+ function isObject(value) {
37
+ return value != null && typeof value === "object" && !Array.isArray(value);
38
+ }
39
+
40
+ function normalizeMapping(requestModel, value) {
41
+ if (typeof value === "string" && value.trim()) {
42
+ return { target: value.trim(), name: requestModel };
43
+ }
44
+ if (!isObject(value)) return null;
45
+ const target = value.target ?? value.targetModel ?? value.responseModel ?? value.served;
46
+ if (typeof target !== "string" || !target.trim()) return null;
47
+ return {
48
+ target: target.trim(),
49
+ name: typeof value.name === "string" && value.name.trim() ? value.name.trim() : requestModel,
50
+ limit: isObject(value.limit) ? value.limit : undefined,
51
+ reasoning: value.reasoning,
52
+ toolCall: value.toolCall,
53
+ modalities: value.modalities,
54
+ };
55
+ }
56
+
57
+ function normalizeModels(options) {
58
+ const entries = new Map();
59
+ const add = (requestModel, value) => {
60
+ if (typeof requestModel !== "string" || !requestModel.trim()) return;
61
+ const mapping = normalizeMapping(requestModel.trim(), value);
62
+ if (mapping) entries.set(requestModel.trim(), mapping);
63
+ };
64
+
65
+ if (Array.isArray(options.models)) {
66
+ for (const item of options.models) {
67
+ if (!isObject(item)) continue;
68
+ add(item.requestModel ?? item.request ?? item.model, item);
69
+ }
70
+ } else if (isObject(options.models)) {
71
+ for (const [requestModel, value] of Object.entries(options.models)) add(requestModel, value);
72
+ } else if (options.requestModel || options.targetModel) {
73
+ add(options.requestModel, {
74
+ target: options.targetModel,
75
+ name: options.requestModel,
76
+ });
77
+ }
78
+
79
+ return Object.fromEntries(entries);
80
+ }
81
+
82
+ function messageModelFromEvent(text) {
83
+ // Events may be separated by \n\n or \r\n\r\n. Ignore the final partial
84
+ // segment: it may be a half-written SSE event.
85
+ const events = text.split(/\r?\n\r?\n/);
86
+ for (let i = 0; i < events.length - 1; i += 1) {
87
+ const data = events[i]
88
+ .split(/\r?\n/)
89
+ .filter((line) => line.startsWith("data:"))
90
+ .map((line) => line.slice(5).trim())
91
+ .filter(Boolean)
92
+ .join("\n");
93
+ if (!data || data === "[DONE]") continue;
94
+ try {
95
+ const event = JSON.parse(data);
96
+ if (event?.type === "message_start" && event.message?.model) {
97
+ return event.message.model;
98
+ }
99
+ } catch {
100
+ // Not a complete JSON event yet; the next read will complete it.
101
+ }
102
+ }
103
+ return undefined;
104
+ }
105
+
106
+ async function readUntilMessageStart(reader) {
107
+ const decoder = new TextDecoder();
108
+ const chunks = [];
109
+ let text = "";
110
+ while (true) {
111
+ const { value, done } = await reader.read();
112
+ if (done) return { chunks, text, reader, done: true, model: undefined };
113
+ chunks.push(value);
114
+ text += decoder.decode(value, { stream: true });
115
+ const model = messageModelFromEvent(text);
116
+ if (model) return { chunks, text, reader, done: false, model };
117
+ }
118
+ }
119
+
120
+ function responseHeaders(resp, json = false) {
121
+ const headers = new Headers(resp.headers);
122
+ headers.delete("content-length");
123
+ headers.delete("content-encoding");
124
+ if (json) {
125
+ headers.set("content-type", "application/json; charset=utf-8");
126
+ } else if (headers.get("content-type")?.includes("text/event-stream")) {
127
+ headers.set("cache-control", "no-cache");
128
+ }
129
+ return headers;
130
+ }
131
+
132
+ function streamResponse(resp, prefixChunks, reader) {
133
+ const body = new ReadableStream({
134
+ start(controller) {
135
+ for (const chunk of prefixChunks) controller.enqueue(chunk);
136
+ },
137
+ async pull(controller) {
138
+ const { value, done } = await reader.read();
139
+ if (done) {
140
+ controller.close();
141
+ return;
142
+ }
143
+ controller.enqueue(value);
144
+ },
145
+ async cancel(reason) {
146
+ await reader.cancel(reason);
147
+ },
148
+ });
149
+ return new Response(body, {
150
+ status: resp.status,
151
+ statusText: resp.statusText,
152
+ headers: responseHeaders(resp),
153
+ });
154
+ }
155
+
156
+ async function readRest(reader) {
157
+ const chunks = [];
158
+ while (true) {
159
+ const { value, done } = await reader.read();
160
+ if (done) break;
161
+ chunks.push(value);
162
+ }
163
+ return chunks;
164
+ }
165
+
166
+ function concatChunks(chunks) {
167
+ const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
168
+ const out = new Uint8Array(total);
169
+ let offset = 0;
170
+ for (const chunk of chunks) {
171
+ out.set(chunk, offset);
172
+ offset += chunk.byteLength;
173
+ }
174
+ return out;
175
+ }
176
+
177
+ function sseToMessage(text) {
178
+ const events = text.split(/\r?\n\r?\n/);
179
+ let message = null;
180
+ const blocks = [];
181
+ const partialJson = new Map();
182
+
183
+ for (const rawEvent of events) {
184
+ const data = rawEvent
185
+ .split(/\r?\n/)
186
+ .filter((line) => line.startsWith("data:"))
187
+ .map((line) => line.slice(5).trim())
188
+ .filter(Boolean)
189
+ .join("\n");
190
+ if (!data || data === "[DONE]") continue;
191
+ let event;
192
+ try {
193
+ event = JSON.parse(data);
194
+ } catch {
195
+ continue;
196
+ }
197
+
198
+ if (event.type === "message_start") {
199
+ message = { ...event.message };
200
+ message.content = [];
201
+ continue;
202
+ }
203
+
204
+ const index = event.index;
205
+ if (event.type === "content_block_start") {
206
+ blocks[index] = { ...event.content_block };
207
+ continue;
208
+ }
209
+ if (event.type === "content_block_delta") {
210
+ const block = blocks[index];
211
+ if (!block) continue;
212
+ const delta = event.delta ?? {};
213
+ if (delta.type === "text_delta") block.text = (block.text ?? "") + delta.text;
214
+ if (delta.type === "thinking_delta") block.thinking = (block.thinking ?? "") + delta.thinking;
215
+ if (delta.type === "signature_delta") block.signature = (block.signature ?? "") + delta.signature;
216
+ if (delta.type === "input_json_delta") {
217
+ partialJson.set(index, (partialJson.get(index) ?? "") + (delta.partial_json ?? ""));
218
+ }
219
+ continue;
220
+ }
221
+ if (event.type === "content_block_stop") {
222
+ const block = blocks[index];
223
+ if (!block) continue;
224
+ if (block.type === "tool_use" && partialJson.has(index)) {
225
+ try {
226
+ block.input = JSON.parse(partialJson.get(index) || "{}");
227
+ } catch {
228
+ block.input = {};
229
+ }
230
+ }
231
+ partialJson.delete(index);
232
+ continue;
233
+ }
234
+ if (event.type === "message_delta" && message) {
235
+ Object.assign(message, event.delta ?? {});
236
+ if (event.usage) message.usage = { ...message.usage, ...event.usage };
237
+ }
238
+ }
239
+
240
+ if (!message) throw new Error("Upstream returned no Anthropic message_start event");
241
+ message.content = blocks.filter(Boolean);
242
+ return message;
243
+ }
244
+
245
+ function createFetch(baseURL, apiKey, models, maxAttempts) {
246
+ return async function fetchMessages(input, init = {}) {
247
+ const isRequest = input instanceof Request;
248
+ const request = isRequest ? input : new Request(input, init);
249
+ let payload = parseBody(init.body);
250
+ if (!payload && isRequest) {
251
+ try {
252
+ payload = parseBody(await request.clone().text());
253
+ } catch {
254
+ payload = null;
255
+ }
256
+ }
257
+ const isMessages =
258
+ request.method === "POST" &&
259
+ new URL(request.url).pathname.replace(/\/+$/, "").endsWith("/messages");
260
+ const mapping = payload && models[payload.model];
261
+
262
+ if (!isMessages || !payload || !mapping) {
263
+ return fetch(input, init);
264
+ }
265
+
266
+ const targetModel = mapping.target;
267
+ const clientWantsStream = payload.stream === true;
268
+ const upstreamBody = { ...payload, stream: true };
269
+ const headers = new Headers(request.headers);
270
+ headers.delete("host");
271
+ headers.delete("content-length");
272
+ headers.delete("authorization");
273
+ headers.set("content-type", "application/json");
274
+ if (!headers.has("anthropic-version")) headers.set("anthropic-version", "2023-06-01");
275
+ if (apiKey) headers.set("x-api-key", apiKey);
276
+
277
+ let lastError = null;
278
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
279
+ let response;
280
+ try {
281
+ response = await fetch(`${baseURL.replace(/\/+$/, "")}/messages`, {
282
+ method: "POST",
283
+ headers,
284
+ body: JSON.stringify(upstreamBody),
285
+ signal: init.signal ?? request.signal,
286
+ redirect: "error",
287
+ });
288
+ } catch (error) {
289
+ lastError = error;
290
+ if (attempt === maxAttempts) throw error;
291
+ await sleep(200 * attempt);
292
+ continue;
293
+ }
294
+
295
+ if (!response.ok) {
296
+ const body = await response.text();
297
+ if (RETRY_STATUS.has(response.status) && attempt < maxAttempts) {
298
+ lastError = new Error(`Upstream HTTP ${response.status}`);
299
+ await sleep(200 * attempt);
300
+ continue;
301
+ }
302
+ return new Response(body, {
303
+ status: response.status,
304
+ statusText: response.statusText,
305
+ headers: responseHeaders(response, false),
306
+ });
307
+ }
308
+
309
+ if (!response.body) throw new Error("Upstream returned an empty response body");
310
+ const reader = response.body.getReader();
311
+ const prefix = await readUntilMessageStart(reader);
312
+ const served = prefix.model;
313
+
314
+ if (served !== targetModel) {
315
+ await reader.cancel();
316
+ if (attempt === maxAttempts) {
317
+ throw new Error(
318
+ `Upstream did not serve ${targetModel} after ${maxAttempts} attempts (last served: ${served ?? "unknown"})`,
319
+ );
320
+ }
321
+ lastError = new Error(`served ${served ?? "unknown"}`);
322
+ await sleep(150 + 100 * attempt);
323
+ continue;
324
+ }
325
+
326
+ if (clientWantsStream) {
327
+ return streamResponse(response, prefix.chunks, reader);
328
+ }
329
+
330
+ const rest = await readRest(reader);
331
+ const text = new TextDecoder().decode(concatChunks([...prefix.chunks, ...rest]));
332
+ const message = sseToMessage(text);
333
+ return new Response(JSON.stringify(message), {
334
+ status: response.status,
335
+ statusText: response.statusText,
336
+ headers: responseHeaders(response, true),
337
+ });
338
+ }
339
+
340
+ throw lastError ?? new Error("Upstream request failed");
341
+ };
342
+ }
343
+
344
+ export async function RetryPlugin(_input, options = {}) {
345
+ const providerId =
346
+ typeof options.providerId === "string" && options.providerId.trim()
347
+ ? options.providerId.trim()
348
+ : DEFAULT_PROVIDER_ID;
349
+ const providerName =
350
+ typeof options.providerName === "string" && options.providerName.trim()
351
+ ? options.providerName.trim()
352
+ : DEFAULT_PROVIDER_NAME;
353
+ const baseURL =
354
+ typeof options.baseURL === "string" ? options.baseURL.trim() : "";
355
+ const pluginKey = typeof options.apiKey === "string" ? options.apiKey : "";
356
+ const models = normalizeModels(options);
357
+ const maxAttempts =
358
+ Number.isInteger(options.maxAttempts) && options.maxAttempts > 0
359
+ ? Math.min(options.maxAttempts, 50)
360
+ : DEFAULT_MAX_ATTEMPTS;
361
+ const maxConcurrency =
362
+ Number.isInteger(options.maxConcurrency) && options.maxConcurrency > 0
363
+ ? Math.min(options.maxConcurrency, 32)
364
+ : 4;
365
+
366
+ const providerModels = {};
367
+ for (const [requestModel, mapping] of Object.entries(models)) {
368
+ providerModels[requestModel] = {
369
+ name: mapping.name ?? requestModel,
370
+ id: requestModel,
371
+ limit: mapping.limit ?? { context: 1000000, output: 128000 },
372
+ reasoning: mapping.reasoning ?? true,
373
+ tool_call: mapping.toolCall ?? true,
374
+ modalities: mapping.modalities ?? { input: ["text"], output: ["text"] },
375
+ };
376
+ }
377
+
378
+ return {
379
+ async config(cfg) {
380
+ cfg.provider ??= {};
381
+ const provider = {
382
+ name: providerName,
383
+ npm: "@ai-sdk/anthropic",
384
+ models: providerModels,
385
+ };
386
+ if (baseURL) provider.api = baseURL;
387
+ cfg.provider[providerId] ??= provider;
388
+ },
389
+ auth: {
390
+ provider: providerId,
391
+ maxConcurrency,
392
+ methods: [
393
+ {
394
+ type: "api",
395
+ label: `${providerName} API Key`,
396
+ prompts: [
397
+ {
398
+ type: "password",
399
+ key: "key",
400
+ message: `${providerName} API Key`,
401
+ placeholder: "sk-...",
402
+ validate: (value) => (value && value.trim() ? undefined : "API Key required"),
403
+ },
404
+ ],
405
+ async authorize(input) {
406
+ const value =
407
+ typeof input === "string"
408
+ ? input
409
+ : input?.key ?? input?.token ?? input?.apiKey ?? "";
410
+ const key = value.trim();
411
+ if (!key) return { type: "failed", error: "API Key required" };
412
+ return { type: "success", key, metadata: {} };
413
+ },
414
+ },
415
+ ],
416
+ async loader(getAuth) {
417
+ const auth = await getAuth();
418
+ const key = auth?.key ?? auth?.methods?.[0]?.key ?? pluginKey;
419
+ if (!key || !baseURL) return {};
420
+ return {
421
+ baseURL,
422
+ apiKey: key,
423
+ headers: { "x-api-key": key, "anthropic-version": "2023-06-01" },
424
+ fetch: createFetch(baseURL, key, models, maxAttempts),
425
+ };
426
+ },
427
+ },
428
+ };
429
+ }