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.
Files changed (109) hide show
  1. package/LICENSE +14 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +77 -78
  5. package/src/api/error-classifier.ts +159 -159
  6. package/src/api/error-helpers.ts +118 -118
  7. package/src/api/models.ts +261 -261
  8. package/src/api/server.ts +860 -859
  9. package/src/cache/memory-cache.ts +385 -385
  10. package/src/clean-cache.ts +204 -204
  11. package/src/core/account-concurrency.ts +671 -671
  12. package/src/core/account-manager.ts +301 -297
  13. package/src/core/account-priority.ts +163 -163
  14. package/src/core/accounts.ts +186 -186
  15. package/src/core/config.ts +383 -383
  16. package/src/core/crypto-utils.ts +79 -79
  17. package/src/core/database.ts +276 -276
  18. package/src/core/errors.ts +118 -118
  19. package/src/core/logger.ts +269 -269
  20. package/src/core/memory-usage.ts +84 -84
  21. package/src/core/metrics.ts +291 -291
  22. package/src/core/model-alias.ts +77 -77
  23. package/src/core/model-registry.ts +544 -544
  24. package/src/core/mutex.ts +119 -119
  25. package/src/core/paths.ts +199 -199
  26. package/src/core/prompt-limits.ts +214 -214
  27. package/src/core/reasoning-effort.ts +102 -102
  28. package/src/core/stream-registry.ts +96 -96
  29. package/src/core/waf-isolation.ts +117 -117
  30. package/src/core/watchdog.ts +195 -195
  31. package/src/delete-chats.ts +23 -23
  32. package/src/index.ts +65 -64
  33. package/src/login.ts +147 -147
  34. package/src/reset-cooldowns.ts +11 -11
  35. package/src/routes/anthropic/index.ts +355 -355
  36. package/src/routes/anthropic/translate.ts +522 -522
  37. package/src/routes/anthropic/types.ts +154 -154
  38. package/src/routes/anthropic/validation.ts +144 -144
  39. package/src/routes/chat/account.ts +1817 -1817
  40. package/src/routes/chat/context.ts +241 -241
  41. package/src/routes/chat/errors.ts +85 -85
  42. package/src/routes/chat/helpers.ts +268 -268
  43. package/src/routes/chat/index.ts +618 -618
  44. package/src/routes/chat/media.ts +285 -285
  45. package/src/routes/chat/retry-policy.ts +754 -754
  46. package/src/routes/chat/stop.ts +98 -98
  47. package/src/routes/chat/streaming.ts +2710 -2710
  48. package/src/routes/chat/validation.ts +526 -526
  49. package/src/routes/chat.ts +2 -2
  50. package/src/routes/completions.ts +290 -290
  51. package/src/routes/images.ts +139 -139
  52. package/src/routes/responses/adapter.ts +503 -503
  53. package/src/routes/responses/index.ts +405 -405
  54. package/src/routes/responses/state.ts +230 -230
  55. package/src/routes/responses/streaming.ts +528 -528
  56. package/src/routes/responses/types.ts +285 -285
  57. package/src/routes/responses/validation.ts +202 -202
  58. package/src/routes/upload.ts +731 -731
  59. package/src/routes/videos.ts +214 -214
  60. package/src/services/auth-playwright.ts +173 -173
  61. package/src/services/captcha-coordinator.ts +161 -161
  62. package/src/services/captcha-solver.ts +553 -553
  63. package/src/services/chat-cleanup.ts +80 -80
  64. package/src/services/context-meter.ts +317 -317
  65. package/src/services/fingerprint.ts +242 -242
  66. package/src/services/human-behavior.ts +173 -173
  67. package/src/services/media-generation.ts +1748 -1748
  68. package/src/services/playwright.ts +2878 -2800
  69. package/src/services/qwen-chat-pool.ts +345 -345
  70. package/src/services/qwen-errors.ts +133 -133
  71. package/src/services/qwen-headers.ts +79 -79
  72. package/src/services/qwen-thread-state.ts +393 -393
  73. package/src/services/qwen-url.ts +19 -19
  74. package/src/services/qwen.ts +3126 -3126
  75. package/src/services/session-keeper.ts +88 -88
  76. package/src/services/token-estimation-metrics.ts +118 -118
  77. package/src/sync/claude-code.ts +75 -75
  78. package/src/sync/codex.ts +123 -123
  79. package/src/sync/index.ts +362 -362
  80. package/src/sync/omp.ts +105 -105
  81. package/src/sync/opencode.ts +214 -214
  82. package/src/sync/types.ts +53 -53
  83. package/src/sync/utils.ts +27 -27
  84. package/src/sync-clients.ts +189 -189
  85. package/src/tools/instructions.ts +137 -137
  86. package/src/tools/manifest.ts +81 -81
  87. package/src/tools/parser.ts +2989 -2989
  88. package/src/tools/toolcall-tags.ts +142 -142
  89. package/src/tui/app.ts +259 -264
  90. package/src/tui/index.ts +61 -61
  91. package/src/tui/markdown.ts +258 -258
  92. package/src/tui/proxy-client.ts +331 -326
  93. package/src/tui/screen.ts +294 -278
  94. package/src/tui/server-manager.ts +270 -270
  95. package/src/tui/theme.ts +432 -432
  96. package/src/tui/types.ts +33 -33
  97. package/src/tui/views/accounts-view.ts +656 -656
  98. package/src/tui/views/chat-view.ts +1018 -823
  99. package/src/tui/views/logs-view.ts +479 -413
  100. package/src/tui/views/status-view.ts +204 -204
  101. package/src/tui/views/storage-view.ts +304 -291
  102. package/src/tui/views/sync-view.ts +409 -409
  103. package/src/types/ali-oss.d.ts +32 -32
  104. package/src/update-cli.ts +121 -0
  105. package/src/utils/context-truncation.ts +84 -84
  106. package/src/utils/json.ts +380 -380
  107. package/src/utils/session-id.ts +37 -37
  108. package/src/utils/tool-call-guard.ts +84 -84
  109. 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 };