qwenproxy-cli 1.0.0 → 1.0.2
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 +14 -14
- package/README.md +906 -906
- package/bin/qwenproxy.js +5 -1
- package/package.json +77 -78
- package/src/api/error-classifier.ts +159 -159
- package/src/api/error-helpers.ts +118 -118
- package/src/api/models.ts +261 -261
- package/src/api/server.ts +860 -859
- package/src/cache/memory-cache.ts +385 -385
- package/src/clean-cache.ts +204 -204
- package/src/core/account-concurrency.ts +671 -671
- package/src/core/account-manager.ts +301 -297
- package/src/core/account-priority.ts +163 -163
- package/src/core/accounts.ts +186 -186
- package/src/core/config.ts +383 -383
- package/src/core/crypto-utils.ts +79 -79
- package/src/core/database.ts +276 -276
- package/src/core/errors.ts +118 -118
- package/src/core/logger.ts +269 -269
- package/src/core/memory-usage.ts +84 -84
- package/src/core/metrics.ts +291 -291
- package/src/core/model-alias.ts +77 -77
- package/src/core/model-registry.ts +544 -544
- package/src/core/mutex.ts +119 -119
- package/src/core/paths.ts +199 -199
- package/src/core/prompt-limits.ts +214 -214
- package/src/core/reasoning-effort.ts +102 -102
- package/src/core/stream-registry.ts +96 -96
- package/src/core/waf-isolation.ts +117 -117
- package/src/core/watchdog.ts +195 -195
- package/src/delete-chats.ts +23 -23
- package/src/index.ts +65 -64
- package/src/login.ts +147 -147
- package/src/reset-cooldowns.ts +11 -11
- package/src/routes/anthropic/index.ts +355 -355
- package/src/routes/anthropic/translate.ts +522 -522
- package/src/routes/anthropic/types.ts +154 -154
- package/src/routes/anthropic/validation.ts +144 -144
- package/src/routes/chat/account.ts +1817 -1817
- package/src/routes/chat/context.ts +241 -241
- package/src/routes/chat/errors.ts +85 -85
- package/src/routes/chat/helpers.ts +268 -268
- package/src/routes/chat/index.ts +618 -618
- package/src/routes/chat/media.ts +285 -285
- package/src/routes/chat/retry-policy.ts +754 -754
- package/src/routes/chat/stop.ts +98 -98
- package/src/routes/chat/streaming.ts +2710 -2710
- package/src/routes/chat/validation.ts +526 -526
- package/src/routes/chat.ts +2 -2
- package/src/routes/completions.ts +290 -290
- package/src/routes/images.ts +139 -139
- package/src/routes/responses/adapter.ts +503 -503
- package/src/routes/responses/index.ts +405 -405
- package/src/routes/responses/state.ts +230 -230
- package/src/routes/responses/streaming.ts +528 -528
- package/src/routes/responses/types.ts +285 -285
- package/src/routes/responses/validation.ts +202 -202
- package/src/routes/upload.ts +731 -731
- package/src/routes/videos.ts +214 -214
- package/src/services/auth-playwright.ts +173 -173
- package/src/services/captcha-coordinator.ts +161 -161
- package/src/services/captcha-solver.ts +553 -553
- package/src/services/chat-cleanup.ts +80 -80
- package/src/services/context-meter.ts +317 -317
- package/src/services/fingerprint.ts +242 -242
- package/src/services/human-behavior.ts +173 -173
- package/src/services/media-generation.ts +1748 -1748
- package/src/services/playwright.ts +2878 -2800
- package/src/services/qwen-chat-pool.ts +345 -345
- package/src/services/qwen-errors.ts +133 -133
- package/src/services/qwen-headers.ts +79 -79
- package/src/services/qwen-thread-state.ts +393 -393
- package/src/services/qwen-url.ts +19 -19
- package/src/services/qwen.ts +3126 -3126
- package/src/services/session-keeper.ts +88 -88
- package/src/services/token-estimation-metrics.ts +118 -118
- package/src/sync/claude-code.ts +75 -75
- package/src/sync/codex.ts +123 -123
- package/src/sync/index.ts +362 -362
- package/src/sync/omp.ts +105 -105
- package/src/sync/opencode.ts +214 -214
- package/src/sync/types.ts +53 -53
- package/src/sync/utils.ts +27 -27
- package/src/sync-clients.ts +189 -189
- package/src/tools/instructions.ts +137 -137
- package/src/tools/manifest.ts +81 -81
- package/src/tools/parser.ts +2989 -2989
- package/src/tools/toolcall-tags.ts +142 -142
- package/src/tui/app.ts +259 -264
- package/src/tui/index.ts +61 -61
- package/src/tui/markdown.ts +258 -258
- package/src/tui/proxy-client.ts +331 -326
- package/src/tui/screen.ts +294 -278
- package/src/tui/server-manager.ts +270 -270
- package/src/tui/theme.ts +432 -432
- package/src/tui/types.ts +33 -33
- package/src/tui/views/accounts-view.ts +656 -656
- package/src/tui/views/chat-view.ts +1018 -823
- package/src/tui/views/logs-view.ts +479 -413
- package/src/tui/views/status-view.ts +204 -204
- package/src/tui/views/storage-view.ts +304 -291
- package/src/tui/views/sync-view.ts +409 -409
- package/src/types/ali-oss.d.ts +32 -32
- package/src/update-cli.ts +121 -0
- package/src/utils/context-truncation.ts +84 -84
- package/src/utils/json.ts +380 -380
- package/src/utils/session-id.ts +37 -37
- package/src/utils/tool-call-guard.ts +84 -84
- package/src/utils/types.ts +109 -109
|
@@ -1,355 +1,355 @@
|
|
|
1
|
-
import crypto from "crypto";
|
|
2
|
-
import { Hono, type Context } from "hono";
|
|
3
|
-
import { stream as honoStream } from "hono/streaming";
|
|
4
|
-
import { config } from "../../core/config.ts";
|
|
5
|
-
import { validateAnthropicRequest } from "./validation.ts";
|
|
6
|
-
import {
|
|
7
|
-
translateAnthropicToOpenAI,
|
|
8
|
-
translateOpenAIToAnthropic,
|
|
9
|
-
translateStreamChunk,
|
|
10
|
-
generateMessageId,
|
|
11
|
-
type AnthropicStreamState,
|
|
12
|
-
} from "./translate.ts";
|
|
13
|
-
import type { AnthropicRequest, OpenAIResponse } from "./types.ts";
|
|
14
|
-
import { estimateTokenCount } from "../../utils/context-truncation.ts";
|
|
15
|
-
|
|
16
|
-
const app = new Hono();
|
|
17
|
-
|
|
18
|
-
function generateRequestId(): string {
|
|
19
|
-
return `req_${crypto.randomBytes(12).toString("hex")}`;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function anthropicError(
|
|
23
|
-
c: Context,
|
|
24
|
-
type: string,
|
|
25
|
-
message: string,
|
|
26
|
-
statusCode: number,
|
|
27
|
-
) {
|
|
28
|
-
c.header("anthropic-version", c.req.header("anthropic-version") || "2023-06-01");
|
|
29
|
-
return c.json(
|
|
30
|
-
{
|
|
31
|
-
type: "error",
|
|
32
|
-
error: { type, message },
|
|
33
|
-
request_id: generateRequestId(),
|
|
34
|
-
},
|
|
35
|
-
statusCode as any,
|
|
36
|
-
);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function constantTimeStringEqual(provided: string, expected: string): boolean {
|
|
40
|
-
const providedBuf = Buffer.from(provided);
|
|
41
|
-
const expectedBuf = Buffer.from(expected);
|
|
42
|
-
const providedHash = crypto.createHash("sha256").update(providedBuf).digest();
|
|
43
|
-
const expectedHash = crypto.createHash("sha256").update(expectedBuf).digest();
|
|
44
|
-
|
|
45
|
-
return (
|
|
46
|
-
crypto.timingSafeEqual(providedHash, expectedHash) &&
|
|
47
|
-
providedBuf.length === expectedBuf.length
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export function verifyAnthropicApiKey(c: Context): boolean {
|
|
52
|
-
const apiKey = process.env.API_KEY || config.apiKey;
|
|
53
|
-
if (!apiKey) return true; // No key configured = open access
|
|
54
|
-
|
|
55
|
-
const candidates: string[] = [];
|
|
56
|
-
const auth = c.req.header("Authorization");
|
|
57
|
-
if (auth?.startsWith("Bearer ")) {
|
|
58
|
-
const token = auth.slice(7).trim();
|
|
59
|
-
if (token) candidates.push(token);
|
|
60
|
-
}
|
|
61
|
-
const xApiKey = c.req.header("x-api-key")?.trim();
|
|
62
|
-
if (xApiKey) candidates.push(xApiKey);
|
|
63
|
-
|
|
64
|
-
if (candidates.length === 0) return false;
|
|
65
|
-
return candidates.some((key) => constantTimeStringEqual(key, apiKey));
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* POST /v1/messages - Anthropic Messages API compatible endpoint.
|
|
70
|
-
*/
|
|
71
|
-
app.post("/v1/messages", async (c) => {
|
|
72
|
-
const requestId = generateRequestId();
|
|
73
|
-
const anthropicVersion = c.req.header("anthropic-version") || "2023-06-01";
|
|
74
|
-
|
|
75
|
-
// 1. Verify API key
|
|
76
|
-
if (!verifyAnthropicApiKey(c)) {
|
|
77
|
-
return anthropicError(c, "authentication_error", "Invalid API key", 401);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// 2. Parse & Validate body
|
|
81
|
-
let body: AnthropicRequest;
|
|
82
|
-
try {
|
|
83
|
-
body = await c.req.json();
|
|
84
|
-
} catch {
|
|
85
|
-
return anthropicError(c, "invalid_request_error", "Invalid JSON body", 400);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const validation = validateAnthropicRequest(body);
|
|
89
|
-
if (!validation.valid) {
|
|
90
|
-
return anthropicError(c, "invalid_request_error", validation.error!, 400);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const isStream = body.stream ?? false;
|
|
94
|
-
const requestModel = body.model;
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
try {
|
|
98
|
-
// 3. Translate Anthropic request to internal OpenAI format
|
|
99
|
-
const openaiRequest = translateAnthropicToOpenAI(body);
|
|
100
|
-
|
|
101
|
-
const dispatchToChat = (streamMode: boolean) =>
|
|
102
|
-
fetch(`http://127.0.0.1:${config.server.port}/v1/chat/completions`, {
|
|
103
|
-
method: "POST",
|
|
104
|
-
headers: {
|
|
105
|
-
"Content-Type": "application/json",
|
|
106
|
-
Authorization: `Bearer ${process.env.API_KEY || config.apiKey || ""}`,
|
|
107
|
-
"x-qwenproxy-route": "Anthropic",
|
|
108
|
-
},
|
|
109
|
-
body: JSON.stringify({
|
|
110
|
-
...openaiRequest,
|
|
111
|
-
stream: streamMode,
|
|
112
|
-
...(streamMode ? { stream_options: { include_usage: true } } : {}),
|
|
113
|
-
}),
|
|
114
|
-
signal: c.req.raw.signal,
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
if (isStream) {
|
|
118
|
-
// ============ STREAMING MODE ============
|
|
119
|
-
const socket =
|
|
120
|
-
(c.env as any)?.incoming?.socket || (c.req.raw as any)?.socket;
|
|
121
|
-
if (socket && typeof socket.setNoDelay === "function") {
|
|
122
|
-
socket.setNoDelay(true);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
c.header("Content-Type", "text/event-stream; charset=utf-8");
|
|
126
|
-
c.header("Cache-Control", "no-cache, no-transform");
|
|
127
|
-
c.header("Connection", "keep-alive");
|
|
128
|
-
c.header("X-Accel-Buffering", "no");
|
|
129
|
-
c.header("anthropic-version", anthropicVersion);
|
|
130
|
-
c.header("request-id", requestId);
|
|
131
|
-
return honoStream(c, async (stream) => {
|
|
132
|
-
const encoder = new TextEncoder();
|
|
133
|
-
const write = async (data: string) => {
|
|
134
|
-
await stream.write(encoder.encode(data));
|
|
135
|
-
};
|
|
136
|
-
|
|
137
|
-
const messageId = generateMessageId();
|
|
138
|
-
const state: AnthropicStreamState = {
|
|
139
|
-
contentBlockIndex: 0,
|
|
140
|
-
currentBlockType: null,
|
|
141
|
-
currentToolId: null,
|
|
142
|
-
currentToolIndex: null,
|
|
143
|
-
requestModel,
|
|
144
|
-
inputTokens: 0,
|
|
145
|
-
outputTokens: 0,
|
|
146
|
-
hasEmittedToolUse: false,
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
// Emit initial message_start event
|
|
150
|
-
const messageStart = {
|
|
151
|
-
type: "message_start",
|
|
152
|
-
message: {
|
|
153
|
-
id: messageId,
|
|
154
|
-
type: "message",
|
|
155
|
-
role: "assistant",
|
|
156
|
-
content: [],
|
|
157
|
-
model: requestModel,
|
|
158
|
-
stop_reason: null,
|
|
159
|
-
stop_sequence: null,
|
|
160
|
-
usage: { input_tokens: 0, output_tokens: 1 },
|
|
161
|
-
},
|
|
162
|
-
};
|
|
163
|
-
await write(
|
|
164
|
-
`event: message_start\ndata: ${JSON.stringify(messageStart)}\n\n`,
|
|
165
|
-
);
|
|
166
|
-
|
|
167
|
-
// Keep-alive heartbeat
|
|
168
|
-
const heartbeatInterval = setInterval(() => {
|
|
169
|
-
write(": keep-alive\n\n").catch(() => clearInterval(heartbeatInterval));
|
|
170
|
-
}, 15000);
|
|
171
|
-
|
|
172
|
-
try {
|
|
173
|
-
const response = await dispatchToChat(true);
|
|
174
|
-
|
|
175
|
-
if (!response.ok) {
|
|
176
|
-
clearInterval(heartbeatInterval);
|
|
177
|
-
const errText = await response.text().catch(() => "");
|
|
178
|
-
console.error(`[Anthropic] Upstream error: ${response.status} ${errText}`);
|
|
179
|
-
await write(
|
|
180
|
-
`event: error\ndata: ${JSON.stringify({
|
|
181
|
-
type: "error",
|
|
182
|
-
error: {
|
|
183
|
-
type: response.status === 429 ? "rate_limit_error" : "api_error",
|
|
184
|
-
message: `Upstream error: ${response.status}`,
|
|
185
|
-
},
|
|
186
|
-
})}\n\n`,
|
|
187
|
-
);
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
const reader = response.body?.getReader();
|
|
192
|
-
if (!reader) {
|
|
193
|
-
throw new Error("No response body from internal chat stream");
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
const decoder = new TextDecoder();
|
|
197
|
-
let buffer = "";
|
|
198
|
-
|
|
199
|
-
try {
|
|
200
|
-
while (true) {
|
|
201
|
-
const { done, value } = await reader.read();
|
|
202
|
-
if (done) break;
|
|
203
|
-
|
|
204
|
-
buffer += decoder.decode(value, { stream: true });
|
|
205
|
-
const lines = buffer.split("\n");
|
|
206
|
-
buffer = lines.pop() || "";
|
|
207
|
-
|
|
208
|
-
for (const line of lines) {
|
|
209
|
-
const trimmed = line.trim();
|
|
210
|
-
if (!trimmed.startsWith("data: ")) continue;
|
|
211
|
-
const dataStr = trimmed.slice(6);
|
|
212
|
-
if (dataStr === "[DONE]") continue;
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
const chunk = JSON.parse(dataStr);
|
|
216
|
-
const events = translateStreamChunk(chunk, state);
|
|
217
|
-
for (const event of events) {
|
|
218
|
-
const parsed = JSON.parse(event);
|
|
219
|
-
await write(`event: ${parsed.type}\ndata: ${event}\n\n`);
|
|
220
|
-
}
|
|
221
|
-
} catch {
|
|
222
|
-
// Skip invalid JSON lines
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
} finally {
|
|
227
|
-
reader.releaseLock();
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
// Close any remaining open content block before ending message
|
|
231
|
-
if (state.currentBlockType !== null) {
|
|
232
|
-
await write(
|
|
233
|
-
`event: content_block_stop\ndata: ${JSON.stringify({
|
|
234
|
-
type: "content_block_stop",
|
|
235
|
-
index: state.contentBlockIndex,
|
|
236
|
-
})}\n\n`,
|
|
237
|
-
);
|
|
238
|
-
state.contentBlockIndex++;
|
|
239
|
-
state.currentBlockType = null;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// Emit final message_stop
|
|
243
|
-
await write(
|
|
244
|
-
`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`,
|
|
245
|
-
);
|
|
246
|
-
} catch (error: any) {
|
|
247
|
-
console.error("❌ [Anthropic] Stream error:", error?.message || error);
|
|
248
|
-
try {
|
|
249
|
-
await write(
|
|
250
|
-
`event: error\ndata: ${JSON.stringify({
|
|
251
|
-
type: "error",
|
|
252
|
-
error: { type: "api_error", message: error?.message || "Stream error" },
|
|
253
|
-
})}\n\n`,
|
|
254
|
-
);
|
|
255
|
-
} catch {
|
|
256
|
-
// Client closed connection
|
|
257
|
-
}
|
|
258
|
-
} finally {
|
|
259
|
-
clearInterval(heartbeatInterval);
|
|
260
|
-
}
|
|
261
|
-
});
|
|
262
|
-
} else {
|
|
263
|
-
// ============ NON-STREAMING MODE ============
|
|
264
|
-
const response = await dispatchToChat(false);
|
|
265
|
-
|
|
266
|
-
if (!response.ok) {
|
|
267
|
-
const errorJson = await response.json().catch(() => null);
|
|
268
|
-
const errorText = errorJson?.error?.message || `HTTP ${response.status}`;
|
|
269
|
-
console.error(`[Anthropic] Upstream error: ${response.status} ${errorText}`);
|
|
270
|
-
|
|
271
|
-
const errorType =
|
|
272
|
-
response.status === 429
|
|
273
|
-
? "rate_limit_error"
|
|
274
|
-
: response.status === 404
|
|
275
|
-
? "not_found_error"
|
|
276
|
-
: response.status === 400
|
|
277
|
-
? "invalid_request_error"
|
|
278
|
-
: "api_error";
|
|
279
|
-
|
|
280
|
-
return anthropicError(c, errorType, errorText, response.status);
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
const openaiResponse: OpenAIResponse = await response.json();
|
|
284
|
-
const anthropicResponse = translateOpenAIToAnthropic(
|
|
285
|
-
openaiResponse,
|
|
286
|
-
requestModel,
|
|
287
|
-
);
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
c.header("anthropic-version", anthropicVersion);
|
|
291
|
-
c.header("request-id", requestId);
|
|
292
|
-
|
|
293
|
-
return c.json(anthropicResponse);
|
|
294
|
-
}
|
|
295
|
-
} catch (error: any) {
|
|
296
|
-
console.error("❌ [Anthropic] Error:", error);
|
|
297
|
-
return anthropicError(
|
|
298
|
-
c,
|
|
299
|
-
"api_error",
|
|
300
|
-
error?.message || "Internal server error",
|
|
301
|
-
500,
|
|
302
|
-
);
|
|
303
|
-
}
|
|
304
|
-
});
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* POST /v1/messages/count_tokens - Anthropic Token Counting API.
|
|
308
|
-
*/
|
|
309
|
-
app.post("/v1/messages/count_tokens", async (c) => {
|
|
310
|
-
if (!verifyAnthropicApiKey(c)) {
|
|
311
|
-
return anthropicError(c, "authentication_error", "Invalid API key", 401);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
try {
|
|
315
|
-
const body = await c.req.json();
|
|
316
|
-
if (!body || typeof body !== "object") {
|
|
317
|
-
return anthropicError(c, "invalid_request_error", "Request body must be a JSON object", 400);
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
let textToCount = "";
|
|
321
|
-
if (typeof body.system === "string") {
|
|
322
|
-
textToCount += body.system + " ";
|
|
323
|
-
} else if (Array.isArray(body.system)) {
|
|
324
|
-
textToCount += body.system.map((s: any) => s?.text || "").join(" ") + " ";
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
if (Array.isArray(body.messages)) {
|
|
328
|
-
for (const m of body.messages) {
|
|
329
|
-
if (typeof m.content === "string") {
|
|
330
|
-
textToCount += m.content + " ";
|
|
331
|
-
} else if (Array.isArray(m.content)) {
|
|
332
|
-
for (const b of m.content) {
|
|
333
|
-
if (b?.text) textToCount += b.text + " ";
|
|
334
|
-
if (b?.content) textToCount += (typeof b.content === "string" ? b.content : JSON.stringify(b.content)) + " ";
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
if (Array.isArray(body.tools)) {
|
|
341
|
-
textToCount += JSON.stringify(body.tools);
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
const inputTokens = Math.max(1, estimateTokenCount(textToCount));
|
|
345
|
-
|
|
346
|
-
c.header("anthropic-version", c.req.header("anthropic-version") || "2023-06-01");
|
|
347
|
-
return c.json({
|
|
348
|
-
input_tokens: inputTokens,
|
|
349
|
-
});
|
|
350
|
-
} catch {
|
|
351
|
-
return anthropicError(c, "invalid_request_error", "Invalid request body", 400);
|
|
352
|
-
}
|
|
353
|
-
});
|
|
354
|
-
|
|
355
|
-
export { app as anthropicApp };
|
|
1
|
+
import crypto from "crypto";
|
|
2
|
+
import { Hono, type Context } from "hono";
|
|
3
|
+
import { stream as honoStream } from "hono/streaming";
|
|
4
|
+
import { config } from "../../core/config.ts";
|
|
5
|
+
import { validateAnthropicRequest } from "./validation.ts";
|
|
6
|
+
import {
|
|
7
|
+
translateAnthropicToOpenAI,
|
|
8
|
+
translateOpenAIToAnthropic,
|
|
9
|
+
translateStreamChunk,
|
|
10
|
+
generateMessageId,
|
|
11
|
+
type AnthropicStreamState,
|
|
12
|
+
} from "./translate.ts";
|
|
13
|
+
import type { AnthropicRequest, OpenAIResponse } from "./types.ts";
|
|
14
|
+
import { estimateTokenCount } from "../../utils/context-truncation.ts";
|
|
15
|
+
|
|
16
|
+
const app = new Hono();
|
|
17
|
+
|
|
18
|
+
function generateRequestId(): string {
|
|
19
|
+
return `req_${crypto.randomBytes(12).toString("hex")}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function anthropicError(
|
|
23
|
+
c: Context,
|
|
24
|
+
type: string,
|
|
25
|
+
message: string,
|
|
26
|
+
statusCode: number,
|
|
27
|
+
) {
|
|
28
|
+
c.header("anthropic-version", c.req.header("anthropic-version") || "2023-06-01");
|
|
29
|
+
return c.json(
|
|
30
|
+
{
|
|
31
|
+
type: "error",
|
|
32
|
+
error: { type, message },
|
|
33
|
+
request_id: generateRequestId(),
|
|
34
|
+
},
|
|
35
|
+
statusCode as any,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function constantTimeStringEqual(provided: string, expected: string): boolean {
|
|
40
|
+
const providedBuf = Buffer.from(provided);
|
|
41
|
+
const expectedBuf = Buffer.from(expected);
|
|
42
|
+
const providedHash = crypto.createHash("sha256").update(providedBuf).digest();
|
|
43
|
+
const expectedHash = crypto.createHash("sha256").update(expectedBuf).digest();
|
|
44
|
+
|
|
45
|
+
return (
|
|
46
|
+
crypto.timingSafeEqual(providedHash, expectedHash) &&
|
|
47
|
+
providedBuf.length === expectedBuf.length
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function verifyAnthropicApiKey(c: Context): boolean {
|
|
52
|
+
const apiKey = process.env.API_KEY || config.apiKey;
|
|
53
|
+
if (!apiKey) return true; // No key configured = open access
|
|
54
|
+
|
|
55
|
+
const candidates: string[] = [];
|
|
56
|
+
const auth = c.req.header("Authorization");
|
|
57
|
+
if (auth?.startsWith("Bearer ")) {
|
|
58
|
+
const token = auth.slice(7).trim();
|
|
59
|
+
if (token) candidates.push(token);
|
|
60
|
+
}
|
|
61
|
+
const xApiKey = c.req.header("x-api-key")?.trim();
|
|
62
|
+
if (xApiKey) candidates.push(xApiKey);
|
|
63
|
+
|
|
64
|
+
if (candidates.length === 0) return false;
|
|
65
|
+
return candidates.some((key) => constantTimeStringEqual(key, apiKey));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* POST /v1/messages - Anthropic Messages API compatible endpoint.
|
|
70
|
+
*/
|
|
71
|
+
app.post("/v1/messages", async (c) => {
|
|
72
|
+
const requestId = generateRequestId();
|
|
73
|
+
const anthropicVersion = c.req.header("anthropic-version") || "2023-06-01";
|
|
74
|
+
|
|
75
|
+
// 1. Verify API key
|
|
76
|
+
if (!verifyAnthropicApiKey(c)) {
|
|
77
|
+
return anthropicError(c, "authentication_error", "Invalid API key", 401);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 2. Parse & Validate body
|
|
81
|
+
let body: AnthropicRequest;
|
|
82
|
+
try {
|
|
83
|
+
body = await c.req.json();
|
|
84
|
+
} catch {
|
|
85
|
+
return anthropicError(c, "invalid_request_error", "Invalid JSON body", 400);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const validation = validateAnthropicRequest(body);
|
|
89
|
+
if (!validation.valid) {
|
|
90
|
+
return anthropicError(c, "invalid_request_error", validation.error!, 400);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const isStream = body.stream ?? false;
|
|
94
|
+
const requestModel = body.model;
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
// 3. Translate Anthropic request to internal OpenAI format
|
|
99
|
+
const openaiRequest = translateAnthropicToOpenAI(body);
|
|
100
|
+
|
|
101
|
+
const dispatchToChat = (streamMode: boolean) =>
|
|
102
|
+
fetch(`http://127.0.0.1:${config.server.port}/v1/chat/completions`, {
|
|
103
|
+
method: "POST",
|
|
104
|
+
headers: {
|
|
105
|
+
"Content-Type": "application/json",
|
|
106
|
+
Authorization: `Bearer ${process.env.API_KEY || config.apiKey || ""}`,
|
|
107
|
+
"x-qwenproxy-route": "Anthropic",
|
|
108
|
+
},
|
|
109
|
+
body: JSON.stringify({
|
|
110
|
+
...openaiRequest,
|
|
111
|
+
stream: streamMode,
|
|
112
|
+
...(streamMode ? { stream_options: { include_usage: true } } : {}),
|
|
113
|
+
}),
|
|
114
|
+
signal: c.req.raw.signal,
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
if (isStream) {
|
|
118
|
+
// ============ STREAMING MODE ============
|
|
119
|
+
const socket =
|
|
120
|
+
(c.env as any)?.incoming?.socket || (c.req.raw as any)?.socket;
|
|
121
|
+
if (socket && typeof socket.setNoDelay === "function") {
|
|
122
|
+
socket.setNoDelay(true);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
c.header("Content-Type", "text/event-stream; charset=utf-8");
|
|
126
|
+
c.header("Cache-Control", "no-cache, no-transform");
|
|
127
|
+
c.header("Connection", "keep-alive");
|
|
128
|
+
c.header("X-Accel-Buffering", "no");
|
|
129
|
+
c.header("anthropic-version", anthropicVersion);
|
|
130
|
+
c.header("request-id", requestId);
|
|
131
|
+
return honoStream(c, async (stream) => {
|
|
132
|
+
const encoder = new TextEncoder();
|
|
133
|
+
const write = async (data: string) => {
|
|
134
|
+
await stream.write(encoder.encode(data));
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const messageId = generateMessageId();
|
|
138
|
+
const state: AnthropicStreamState = {
|
|
139
|
+
contentBlockIndex: 0,
|
|
140
|
+
currentBlockType: null,
|
|
141
|
+
currentToolId: null,
|
|
142
|
+
currentToolIndex: null,
|
|
143
|
+
requestModel,
|
|
144
|
+
inputTokens: 0,
|
|
145
|
+
outputTokens: 0,
|
|
146
|
+
hasEmittedToolUse: false,
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
// Emit initial message_start event
|
|
150
|
+
const messageStart = {
|
|
151
|
+
type: "message_start",
|
|
152
|
+
message: {
|
|
153
|
+
id: messageId,
|
|
154
|
+
type: "message",
|
|
155
|
+
role: "assistant",
|
|
156
|
+
content: [],
|
|
157
|
+
model: requestModel,
|
|
158
|
+
stop_reason: null,
|
|
159
|
+
stop_sequence: null,
|
|
160
|
+
usage: { input_tokens: 0, output_tokens: 1 },
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
await write(
|
|
164
|
+
`event: message_start\ndata: ${JSON.stringify(messageStart)}\n\n`,
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
// Keep-alive heartbeat
|
|
168
|
+
const heartbeatInterval = setInterval(() => {
|
|
169
|
+
write(": keep-alive\n\n").catch(() => clearInterval(heartbeatInterval));
|
|
170
|
+
}, 15000);
|
|
171
|
+
|
|
172
|
+
try {
|
|
173
|
+
const response = await dispatchToChat(true);
|
|
174
|
+
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
clearInterval(heartbeatInterval);
|
|
177
|
+
const errText = await response.text().catch(() => "");
|
|
178
|
+
console.error(`[Anthropic] Upstream error: ${response.status} ${errText}`);
|
|
179
|
+
await write(
|
|
180
|
+
`event: error\ndata: ${JSON.stringify({
|
|
181
|
+
type: "error",
|
|
182
|
+
error: {
|
|
183
|
+
type: response.status === 429 ? "rate_limit_error" : "api_error",
|
|
184
|
+
message: `Upstream error: ${response.status}`,
|
|
185
|
+
},
|
|
186
|
+
})}\n\n`,
|
|
187
|
+
);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const reader = response.body?.getReader();
|
|
192
|
+
if (!reader) {
|
|
193
|
+
throw new Error("No response body from internal chat stream");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const decoder = new TextDecoder();
|
|
197
|
+
let buffer = "";
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
while (true) {
|
|
201
|
+
const { done, value } = await reader.read();
|
|
202
|
+
if (done) break;
|
|
203
|
+
|
|
204
|
+
buffer += decoder.decode(value, { stream: true });
|
|
205
|
+
const lines = buffer.split("\n");
|
|
206
|
+
buffer = lines.pop() || "";
|
|
207
|
+
|
|
208
|
+
for (const line of lines) {
|
|
209
|
+
const trimmed = line.trim();
|
|
210
|
+
if (!trimmed.startsWith("data: ")) continue;
|
|
211
|
+
const dataStr = trimmed.slice(6);
|
|
212
|
+
if (dataStr === "[DONE]") continue;
|
|
213
|
+
|
|
214
|
+
try {
|
|
215
|
+
const chunk = JSON.parse(dataStr);
|
|
216
|
+
const events = translateStreamChunk(chunk, state);
|
|
217
|
+
for (const event of events) {
|
|
218
|
+
const parsed = JSON.parse(event);
|
|
219
|
+
await write(`event: ${parsed.type}\ndata: ${event}\n\n`);
|
|
220
|
+
}
|
|
221
|
+
} catch {
|
|
222
|
+
// Skip invalid JSON lines
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
} finally {
|
|
227
|
+
reader.releaseLock();
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Close any remaining open content block before ending message
|
|
231
|
+
if (state.currentBlockType !== null) {
|
|
232
|
+
await write(
|
|
233
|
+
`event: content_block_stop\ndata: ${JSON.stringify({
|
|
234
|
+
type: "content_block_stop",
|
|
235
|
+
index: state.contentBlockIndex,
|
|
236
|
+
})}\n\n`,
|
|
237
|
+
);
|
|
238
|
+
state.contentBlockIndex++;
|
|
239
|
+
state.currentBlockType = null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Emit final message_stop
|
|
243
|
+
await write(
|
|
244
|
+
`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`,
|
|
245
|
+
);
|
|
246
|
+
} catch (error: any) {
|
|
247
|
+
console.error("❌ [Anthropic] Stream error:", error?.message || error);
|
|
248
|
+
try {
|
|
249
|
+
await write(
|
|
250
|
+
`event: error\ndata: ${JSON.stringify({
|
|
251
|
+
type: "error",
|
|
252
|
+
error: { type: "api_error", message: error?.message || "Stream error" },
|
|
253
|
+
})}\n\n`,
|
|
254
|
+
);
|
|
255
|
+
} catch {
|
|
256
|
+
// Client closed connection
|
|
257
|
+
}
|
|
258
|
+
} finally {
|
|
259
|
+
clearInterval(heartbeatInterval);
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
} else {
|
|
263
|
+
// ============ NON-STREAMING MODE ============
|
|
264
|
+
const response = await dispatchToChat(false);
|
|
265
|
+
|
|
266
|
+
if (!response.ok) {
|
|
267
|
+
const errorJson = await response.json().catch(() => null);
|
|
268
|
+
const errorText = errorJson?.error?.message || `HTTP ${response.status}`;
|
|
269
|
+
console.error(`[Anthropic] Upstream error: ${response.status} ${errorText}`);
|
|
270
|
+
|
|
271
|
+
const errorType =
|
|
272
|
+
response.status === 429
|
|
273
|
+
? "rate_limit_error"
|
|
274
|
+
: response.status === 404
|
|
275
|
+
? "not_found_error"
|
|
276
|
+
: response.status === 400
|
|
277
|
+
? "invalid_request_error"
|
|
278
|
+
: "api_error";
|
|
279
|
+
|
|
280
|
+
return anthropicError(c, errorType, errorText, response.status);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const openaiResponse: OpenAIResponse = await response.json();
|
|
284
|
+
const anthropicResponse = translateOpenAIToAnthropic(
|
|
285
|
+
openaiResponse,
|
|
286
|
+
requestModel,
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
c.header("anthropic-version", anthropicVersion);
|
|
291
|
+
c.header("request-id", requestId);
|
|
292
|
+
|
|
293
|
+
return c.json(anthropicResponse);
|
|
294
|
+
}
|
|
295
|
+
} catch (error: any) {
|
|
296
|
+
console.error("❌ [Anthropic] Error:", error);
|
|
297
|
+
return anthropicError(
|
|
298
|
+
c,
|
|
299
|
+
"api_error",
|
|
300
|
+
error?.message || "Internal server error",
|
|
301
|
+
500,
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* POST /v1/messages/count_tokens - Anthropic Token Counting API.
|
|
308
|
+
*/
|
|
309
|
+
app.post("/v1/messages/count_tokens", async (c) => {
|
|
310
|
+
if (!verifyAnthropicApiKey(c)) {
|
|
311
|
+
return anthropicError(c, "authentication_error", "Invalid API key", 401);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
try {
|
|
315
|
+
const body = await c.req.json();
|
|
316
|
+
if (!body || typeof body !== "object") {
|
|
317
|
+
return anthropicError(c, "invalid_request_error", "Request body must be a JSON object", 400);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
let textToCount = "";
|
|
321
|
+
if (typeof body.system === "string") {
|
|
322
|
+
textToCount += body.system + " ";
|
|
323
|
+
} else if (Array.isArray(body.system)) {
|
|
324
|
+
textToCount += body.system.map((s: any) => s?.text || "").join(" ") + " ";
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (Array.isArray(body.messages)) {
|
|
328
|
+
for (const m of body.messages) {
|
|
329
|
+
if (typeof m.content === "string") {
|
|
330
|
+
textToCount += m.content + " ";
|
|
331
|
+
} else if (Array.isArray(m.content)) {
|
|
332
|
+
for (const b of m.content) {
|
|
333
|
+
if (b?.text) textToCount += b.text + " ";
|
|
334
|
+
if (b?.content) textToCount += (typeof b.content === "string" ? b.content : JSON.stringify(b.content)) + " ";
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (Array.isArray(body.tools)) {
|
|
341
|
+
textToCount += JSON.stringify(body.tools);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const inputTokens = Math.max(1, estimateTokenCount(textToCount));
|
|
345
|
+
|
|
346
|
+
c.header("anthropic-version", c.req.header("anthropic-version") || "2023-06-01");
|
|
347
|
+
return c.json({
|
|
348
|
+
input_tokens: inputTokens,
|
|
349
|
+
});
|
|
350
|
+
} catch {
|
|
351
|
+
return anthropicError(c, "invalid_request_error", "Invalid request body", 400);
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
export { app as anthropicApp };
|