qwenproxy-cli 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.
Files changed (109) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +907 -0
  3. package/bin/qwenproxy.js +141 -0
  4. package/package.json +78 -0
  5. package/src/api/error-classifier.ts +159 -0
  6. package/src/api/error-helpers.ts +118 -0
  7. package/src/api/models.ts +261 -0
  8. package/src/api/server.ts +859 -0
  9. package/src/cache/memory-cache.ts +385 -0
  10. package/src/clean-cache.ts +204 -0
  11. package/src/core/account-concurrency.ts +671 -0
  12. package/src/core/account-manager.ts +297 -0
  13. package/src/core/account-priority.ts +163 -0
  14. package/src/core/accounts.ts +186 -0
  15. package/src/core/config.ts +383 -0
  16. package/src/core/crypto-utils.ts +79 -0
  17. package/src/core/database.ts +276 -0
  18. package/src/core/errors.ts +118 -0
  19. package/src/core/logger.ts +269 -0
  20. package/src/core/memory-usage.ts +84 -0
  21. package/src/core/metrics.ts +291 -0
  22. package/src/core/model-alias.ts +77 -0
  23. package/src/core/model-registry.ts +544 -0
  24. package/src/core/mutex.ts +119 -0
  25. package/src/core/paths.ts +199 -0
  26. package/src/core/prompt-limits.ts +214 -0
  27. package/src/core/reasoning-effort.ts +102 -0
  28. package/src/core/stream-registry.ts +96 -0
  29. package/src/core/waf-isolation.ts +117 -0
  30. package/src/core/watchdog.ts +195 -0
  31. package/src/delete-chats.ts +23 -0
  32. package/src/index.ts +64 -0
  33. package/src/login.ts +147 -0
  34. package/src/reset-cooldowns.ts +11 -0
  35. package/src/routes/anthropic/index.ts +355 -0
  36. package/src/routes/anthropic/translate.ts +522 -0
  37. package/src/routes/anthropic/types.ts +154 -0
  38. package/src/routes/anthropic/validation.ts +144 -0
  39. package/src/routes/chat/account.ts +1817 -0
  40. package/src/routes/chat/context.ts +241 -0
  41. package/src/routes/chat/errors.ts +85 -0
  42. package/src/routes/chat/helpers.ts +268 -0
  43. package/src/routes/chat/index.ts +618 -0
  44. package/src/routes/chat/media.ts +285 -0
  45. package/src/routes/chat/retry-policy.ts +754 -0
  46. package/src/routes/chat/stop.ts +98 -0
  47. package/src/routes/chat/streaming.ts +2710 -0
  48. package/src/routes/chat/validation.ts +526 -0
  49. package/src/routes/chat.ts +2 -0
  50. package/src/routes/completions.ts +290 -0
  51. package/src/routes/images.ts +139 -0
  52. package/src/routes/responses/adapter.ts +503 -0
  53. package/src/routes/responses/index.ts +405 -0
  54. package/src/routes/responses/state.ts +230 -0
  55. package/src/routes/responses/streaming.ts +528 -0
  56. package/src/routes/responses/types.ts +285 -0
  57. package/src/routes/responses/validation.ts +202 -0
  58. package/src/routes/upload.ts +731 -0
  59. package/src/routes/videos.ts +214 -0
  60. package/src/services/auth-playwright.ts +173 -0
  61. package/src/services/captcha-coordinator.ts +161 -0
  62. package/src/services/captcha-solver.ts +553 -0
  63. package/src/services/chat-cleanup.ts +80 -0
  64. package/src/services/context-meter.ts +317 -0
  65. package/src/services/fingerprint.ts +242 -0
  66. package/src/services/human-behavior.ts +173 -0
  67. package/src/services/media-generation.ts +1748 -0
  68. package/src/services/playwright.ts +2800 -0
  69. package/src/services/qwen-chat-pool.ts +345 -0
  70. package/src/services/qwen-errors.ts +133 -0
  71. package/src/services/qwen-headers.ts +79 -0
  72. package/src/services/qwen-thread-state.ts +393 -0
  73. package/src/services/qwen-url.ts +19 -0
  74. package/src/services/qwen.ts +3126 -0
  75. package/src/services/session-keeper.ts +88 -0
  76. package/src/services/token-estimation-metrics.ts +118 -0
  77. package/src/sync/claude-code.ts +75 -0
  78. package/src/sync/codex.ts +123 -0
  79. package/src/sync/index.ts +362 -0
  80. package/src/sync/omp.ts +105 -0
  81. package/src/sync/opencode.ts +214 -0
  82. package/src/sync/types.ts +53 -0
  83. package/src/sync/utils.ts +27 -0
  84. package/src/sync-clients.ts +189 -0
  85. package/src/tools/instructions.ts +137 -0
  86. package/src/tools/manifest.ts +81 -0
  87. package/src/tools/parser.ts +2989 -0
  88. package/src/tools/toolcall-tags.ts +142 -0
  89. package/src/tools/types.ts +53 -0
  90. package/src/tui/app.ts +264 -0
  91. package/src/tui/index.ts +61 -0
  92. package/src/tui/markdown.ts +258 -0
  93. package/src/tui/proxy-client.ts +326 -0
  94. package/src/tui/screen.ts +278 -0
  95. package/src/tui/server-manager.ts +270 -0
  96. package/src/tui/theme.ts +432 -0
  97. package/src/tui/types.ts +33 -0
  98. package/src/tui/views/accounts-view.ts +656 -0
  99. package/src/tui/views/chat-view.ts +823 -0
  100. package/src/tui/views/logs-view.ts +413 -0
  101. package/src/tui/views/status-view.ts +204 -0
  102. package/src/tui/views/storage-view.ts +291 -0
  103. package/src/tui/views/sync-view.ts +409 -0
  104. package/src/types/ali-oss.d.ts +32 -0
  105. package/src/utils/context-truncation.ts +84 -0
  106. package/src/utils/json.ts +380 -0
  107. package/src/utils/session-id.ts +37 -0
  108. package/src/utils/tool-call-guard.ts +85 -0
  109. package/src/utils/types.ts +109 -0
@@ -0,0 +1,276 @@
1
+ import Database from "better-sqlite3";
2
+ import path from "path";
3
+ import fs from "fs";
4
+ import { encrypt, isEncrypted } from "./crypto-utils.ts";
5
+
6
+ /**
7
+ * Several suites exercise account rotation by deleting every row and restoring
8
+ * it in a `finally`. Pointed at the real database that is one crashed test away
9
+ * from wiping the operator's configured accounts — which is exactly how a whole
10
+ * account set was lost once. Tests get their own file so the blast radius of a
11
+ * failed restore is a throwaway directory.
12
+ */
13
+ import {
14
+ getDataDir,
15
+ getDbDir,
16
+ getDbPath,
17
+ isRunningUnderNodeTest,
18
+ } from "./paths.ts";
19
+
20
+ const DATA_DIR = getDataDir();
21
+ const DB_DIR = getDbDir();
22
+ const DB_PATH = getDbPath();
23
+ const LEGACY_DB_PATH = path.join(DATA_DIR, "qwenproxy.db");
24
+ const LEGACY_DB_IN_DIR_PATH = path.join(DB_DIR, "qwenproxy.db");
25
+ const LEGACY_DB_WAL_PATH = `${LEGACY_DB_PATH}-wal`;
26
+ const LEGACY_DB_SHM_PATH = `${LEGACY_DB_PATH}-shm`;
27
+ const LEGACY_DB_IN_DIR_WAL_PATH = `${LEGACY_DB_IN_DIR_PATH}-wal`;
28
+ const LEGACY_DB_IN_DIR_SHM_PATH = `${LEGACY_DB_IN_DIR_PATH}-shm`;
29
+ const DB_WAL_PATH = `${DB_PATH}-wal`;
30
+ const DB_SHM_PATH = `${DB_PATH}-shm`;
31
+ const LEGACY_JSON_PATH = path.resolve("accounts.json");
32
+ const LEGACY_JSON_BAK_PATH = path.resolve("accounts.json.bak");
33
+ const DB_JSON_BAK_PATH = path.join(DB_DIR, "accounts.json.bak");
34
+
35
+ let db: Database.Database | null = null;
36
+
37
+ export function getDatabase(): Database.Database {
38
+ if (db) return db;
39
+
40
+ // Ensure data directory exists with proper permissions
41
+ try {
42
+ if (!fs.existsSync(DB_DIR)) {
43
+ fs.mkdirSync(DB_DIR, { recursive: true, mode: 0o755 });
44
+ }
45
+ const migrateLegacyDatabase = (
46
+ legacyPath: string,
47
+ legacyWalPath: string,
48
+ legacyShmPath: string,
49
+ ) => {
50
+ if (fs.existsSync(legacyPath) && !fs.existsSync(DB_PATH)) {
51
+ fs.renameSync(legacyPath, DB_PATH);
52
+ if (fs.existsSync(legacyWalPath) && !fs.existsSync(DB_WAL_PATH)) {
53
+ fs.renameSync(legacyWalPath, DB_WAL_PATH);
54
+ }
55
+ if (fs.existsSync(legacyShmPath) && !fs.existsSync(DB_SHM_PATH)) {
56
+ fs.renameSync(legacyShmPath, DB_SHM_PATH);
57
+ }
58
+ console.log(`📦 [Database] Migrated legacy database to ${DB_PATH}`);
59
+ }
60
+ };
61
+
62
+ migrateLegacyDatabase(
63
+ LEGACY_DB_PATH,
64
+ LEGACY_DB_WAL_PATH,
65
+ LEGACY_DB_SHM_PATH,
66
+ );
67
+ migrateLegacyDatabase(
68
+ LEGACY_DB_IN_DIR_PATH,
69
+ LEGACY_DB_IN_DIR_WAL_PATH,
70
+ LEGACY_DB_IN_DIR_SHM_PATH,
71
+ );
72
+ if (
73
+ fs.existsSync(LEGACY_JSON_BAK_PATH) &&
74
+ !fs.existsSync(DB_JSON_BAK_PATH)
75
+ ) {
76
+ fs.renameSync(LEGACY_JSON_BAK_PATH, DB_JSON_BAK_PATH);
77
+ }
78
+ // Test write access
79
+ const testFile = path.join(DB_DIR, ".write-test");
80
+ fs.writeFileSync(testFile, "");
81
+ fs.unlinkSync(testFile);
82
+ } catch (err: any) {
83
+ console.error(
84
+ `❌ [Database] Cannot access database directory '${DB_DIR}':`,
85
+ err.message,
86
+ );
87
+ console.error(
88
+ "❌ [Database] Ensure the directory exists and has proper permissions",
89
+ );
90
+ console.error(
91
+ "❌ [Database] In Docker, mount a volume: -v ./data:/app/data",
92
+ );
93
+ throw new Error(`Database directory not accessible: ${DB_DIR}`);
94
+ }
95
+
96
+ try {
97
+ db = new Database(DB_PATH);
98
+ } catch (err: any) {
99
+ console.error(
100
+ `❌ [Database] Failed to open database at '${DB_PATH}':`,
101
+ err.message,
102
+ );
103
+ console.error("❌ [Database] Check file permissions and disk space");
104
+ throw err;
105
+ }
106
+
107
+ // Enable WAL mode for better concurrent read performance (ideal for VPS)
108
+ db.pragma("journal_mode = WAL");
109
+ db.pragma("busy_timeout = 5000");
110
+ db.pragma("synchronous = NORMAL");
111
+ db.pragma("cache_size = -64000"); // 64MB cache
112
+ db.pragma("foreign_keys = ON");
113
+
114
+ runMigrations(db);
115
+ migrateFromJson(db);
116
+ encryptPlaintextPasswords(db);
117
+
118
+ return db;
119
+ }
120
+
121
+ function runMigrations(db: Database.Database): void {
122
+ db.exec(`
123
+ CREATE TABLE IF NOT EXISTS accounts (
124
+ id TEXT PRIMARY KEY,
125
+ email TEXT UNIQUE NOT NULL,
126
+ password TEXT NOT NULL DEFAULT '',
127
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
128
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
129
+ );
130
+
131
+ CREATE INDEX IF NOT EXISTS idx_accounts_email ON accounts(email);
132
+
133
+ -- Cooldown persistence columns (ignore if already exist)
134
+ -- Note: SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN,
135
+ -- so these are wrapped in try-catch at the application level.
136
+
137
+ CREATE TABLE IF NOT EXISTS qwen_auth_sessions (
138
+ account_id TEXT PRIMARY KEY,
139
+ cookie TEXT NOT NULL,
140
+ user_agent TEXT NOT NULL,
141
+ bx_v TEXT,
142
+ bx_ua TEXT,
143
+ bx_umidtoken TEXT,
144
+ user_id TEXT,
145
+ token_expires_at INTEGER,
146
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
147
+ );
148
+
149
+ CREATE INDEX IF NOT EXISTS idx_qwen_auth_sessions_expires
150
+ ON qwen_auth_sessions(token_expires_at);
151
+
152
+ CREATE TABLE IF NOT EXISTS logical_thread_states (
153
+ session_id TEXT PRIMARY KEY,
154
+ account_id TEXT NOT NULL,
155
+ chat_session_id TEXT NOT NULL,
156
+ parent_id TEXT,
157
+ instructions_sent INTEGER NOT NULL DEFAULT 0,
158
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
159
+ );
160
+
161
+ CREATE INDEX IF NOT EXISTS idx_thread_updated ON logical_thread_states(updated_at);
162
+
163
+ CREATE TABLE IF NOT EXISTS personalization_cache (
164
+ account_id TEXT PRIMARY KEY,
165
+ instruction_hash TEXT NOT NULL,
166
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
167
+ );
168
+ `);
169
+
170
+ // Cooldown persistence columns — wrapped in try-catch because
171
+ // SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN.
172
+ try {
173
+ db.exec(
174
+ `ALTER TABLE accounts ADD COLUMN cooldown_until INTEGER DEFAULT 0;`,
175
+ );
176
+ } catch (err) {
177
+ if (!isDuplicateColumnError(err)) throw err;
178
+ }
179
+ try {
180
+ db.exec(`ALTER TABLE accounts ADD COLUMN cooldown_reason TEXT;`);
181
+ } catch (err) {
182
+ if (!isDuplicateColumnError(err)) throw err;
183
+ }
184
+ }
185
+
186
+ function isDuplicateColumnError(err: unknown): boolean {
187
+ return err instanceof Error && err.message.includes("duplicate column name");
188
+ }
189
+
190
+ function encryptPlaintextPasswords(db: Database.Database): void {
191
+ const rows = db.prepare("SELECT id, password FROM accounts").all() as Array<{
192
+ id: string;
193
+ password: string;
194
+ }>;
195
+ const update = db.prepare(
196
+ "UPDATE accounts SET password = ?, updated_at = datetime('now') WHERE id = ?",
197
+ );
198
+ let migrated = 0;
199
+
200
+ const migrate = db.transaction(() => {
201
+ for (const row of rows) {
202
+ if (row.password && !isEncrypted(row.password)) {
203
+ update.run(encrypt(row.password), row.id);
204
+ migrated++;
205
+ }
206
+ }
207
+ });
208
+
209
+ migrate();
210
+
211
+ if (migrated > 0) {
212
+ console.log(
213
+ `[Database] Encrypted ${migrated} plaintext password(s) in database`,
214
+ );
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Auto-migrate existing accounts.json into SQLite on first run.
220
+ * The legacy JSON file is moved to data/db/accounts.json.bak after successful migration.
221
+ */
222
+ function migrateFromJson(db: Database.Database): void {
223
+ const jsonPath = LEGACY_JSON_PATH;
224
+ if (!fs.existsSync(jsonPath)) return;
225
+
226
+ try {
227
+ const raw = fs.readFileSync(jsonPath, "utf-8");
228
+ const accounts = JSON.parse(raw) as Array<{
229
+ id: string;
230
+ email: string;
231
+ password: string;
232
+ }>;
233
+
234
+ if (!Array.isArray(accounts) || accounts.length === 0) {
235
+ // Empty or invalid file — just rename it
236
+ fs.renameSync(jsonPath, DB_JSON_BAK_PATH);
237
+ return;
238
+ }
239
+
240
+ const insert = db.prepare(`
241
+ INSERT OR IGNORE INTO accounts (id, email, password) VALUES (?, ?, ?)
242
+ `);
243
+
244
+ const migrate = db.transaction(() => {
245
+ for (const account of accounts) {
246
+ if (
247
+ account.id &&
248
+ typeof account.email === "string" &&
249
+ account.email.trim().length > 0
250
+ ) {
251
+ insert.run(account.id, account.email.trim(), account.password || "");
252
+ }
253
+ }
254
+ });
255
+
256
+ migrate();
257
+
258
+ // Rename old file to .bak to avoid re-migration
259
+ fs.renameSync(jsonPath, DB_JSON_BAK_PATH);
260
+ console.log(
261
+ `[Database] Migrated ${accounts.length} account(s) from accounts.json to SQLite`,
262
+ );
263
+ } catch (err: any) {
264
+ console.error(
265
+ "❌ [Database] Failed to migrate accounts.json:",
266
+ err.message,
267
+ );
268
+ }
269
+ }
270
+
271
+ export function closeDatabase(): void {
272
+ if (db) {
273
+ db.close();
274
+ db = null;
275
+ }
276
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Valid HTTP status codes for operational errors.
3
+ */
4
+ export type QwenProxyStatusCode =
5
+ | 400
6
+ | 401
7
+ | 403
8
+ | 404
9
+ | 429
10
+ | 499
11
+ | 500
12
+ | 502
13
+ | 503
14
+ | 504;
15
+
16
+ /**
17
+ * Base class for all QwenProxy operational errors.
18
+ * Provides OpenAI-compatible error formatting.
19
+ */
20
+ export abstract class QwenProxyError extends Error {
21
+ abstract readonly statusCode: QwenProxyStatusCode;
22
+ abstract readonly type: string;
23
+ abstract readonly code: string;
24
+ param?: string;
25
+
26
+ constructor(message: string) {
27
+ super(message);
28
+ this.name = this.constructor.name;
29
+ }
30
+
31
+ toOpenAI() {
32
+ return {
33
+ error: {
34
+ message: this.message,
35
+ type: this.type,
36
+ code: this.code,
37
+ param: this.param,
38
+ },
39
+ };
40
+ }
41
+ }
42
+
43
+ export class ValidationError extends QwenProxyError {
44
+ readonly statusCode = 400;
45
+ readonly type = "invalid_request_error";
46
+ readonly code: string = "bad_request";
47
+ }
48
+
49
+ /** Input exceeds the local safe budget before it reaches the Qwen web API. */
50
+ export class ContextLengthExceededError extends ValidationError {
51
+ readonly code = "context_length_exceeded";
52
+
53
+ constructor(message: string, param = "messages") {
54
+ super(message);
55
+ this.param = param;
56
+ }
57
+ }
58
+
59
+ export class AuthError extends QwenProxyError {
60
+ readonly statusCode = 401;
61
+ readonly type = "authentication_error";
62
+ readonly code = "invalid_api_key";
63
+ }
64
+
65
+ export class ForbiddenError extends QwenProxyError {
66
+ readonly statusCode = 403;
67
+ readonly type = "permission_error";
68
+ readonly code = "insufficient_quota";
69
+ }
70
+
71
+ export class NotFoundError extends QwenProxyError {
72
+ readonly statusCode = 404;
73
+ readonly type = "not_found_error";
74
+ readonly code = "resource_not_found";
75
+ }
76
+
77
+ export class UpstreamRateLimit extends QwenProxyError {
78
+ readonly statusCode = 429;
79
+ readonly type = "rate_limit_error";
80
+ readonly code = "rate_limit_exceeded";
81
+ }
82
+
83
+ export class UpstreamError extends QwenProxyError {
84
+ readonly statusCode = 502;
85
+ readonly type = "upstream_error";
86
+ readonly code = "upstream_unavailable";
87
+ }
88
+
89
+ export class UpstreamTimeout extends QwenProxyError {
90
+ readonly statusCode = 504;
91
+ readonly type = "timeout_error";
92
+ readonly code = "upstream_timeout";
93
+ }
94
+
95
+ export class InternalError extends QwenProxyError {
96
+ readonly statusCode = 500;
97
+ readonly type = "internal_error";
98
+ readonly code = "internal_server_error";
99
+ }
100
+
101
+ /**
102
+ * The client disconnected (or a same-session retry superseded the request)
103
+ * before the upstream stream could be created. There is no listener left to
104
+ * receive an error body, so this must NOT be surfaced as a 500: it is neither
105
+ * a server fault nor an upstream failure. HTTP 499 (Client Closed Request)
106
+ * keeps the semantics without polluting error metrics.
107
+ */
108
+ export class ClientAbortedError extends QwenProxyError {
109
+ readonly statusCode = 499 as QwenProxyStatusCode;
110
+ readonly type = "request_aborted";
111
+ readonly code = "client_aborted";
112
+ }
113
+
114
+ export class ServiceUnavailable extends QwenProxyError {
115
+ readonly statusCode = 503;
116
+ readonly type = "service_unavailable";
117
+ readonly code = "service_degraded";
118
+ }
@@ -0,0 +1,269 @@
1
+ import "dotenv/config";
2
+
3
+ /**
4
+ * Mask an email address for safe logging.
5
+ * "user@example.com" → "user@***"
6
+ */
7
+ export function maskEmail(email: string | undefined | null): string {
8
+ if (!email) return "<unknown>";
9
+ const atIndex = email.indexOf("@");
10
+ if (atIndex <= 0) return "<invalid>";
11
+ return email.substring(0, atIndex);
12
+ }
13
+
14
+ // ─── Log sanitization ───────────────────────────────────────────────────────────
15
+ // Log entries carry raw upstream payloads (headers, cookies, JWT-backed
16
+ // sessions, malformed tool-call dumps). Redact known credential keys and any
17
+ // loose JWT/API-key shaped string before the entry hits the console, even when
18
+ // the value appears nested inside a bigger object or a quoted JSON dump.
19
+
20
+ const SENSITIVE_KEY_PATTERN =
21
+ /^(authorization|auth|cookie|cookies|set-cookie|api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|token|password|passwd|secret|x5sec|x5secdata|bx-ua|bx-v|bx-umidtoken)$/i;
22
+
23
+ /** WAF cookie names come in many variants: x5sec, x5sec_v3, x5sec-cn, bx-temp... */
24
+ const WAF_KEY_PREFIX_PATTERN = /^(x5sec|bx[-_])/i;
25
+
26
+ /** JWT (3 base64url segments) or OpenAI-style `sk-` API key. */
27
+ const LOOSE_SECRET_PATTERN =
28
+ /(eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}|sk-[A-Za-z0-9_-]{20,})/g;
29
+
30
+ /** Credentials embedded in free-form strings: header lines, cookie jars, URLs. */
31
+ const EMBEDDED_SECRET_PATTERN =
32
+ /((?:x5sec(?:data|_[a-z0-9]+|-[a-z0-9]+)?|bx[-_][a-z0-9_-]+)\s*=\s*[^;\s"']+)|(\bBearer\s+[A-Za-z0-9._~+\/=-]+)/gi;
33
+
34
+ function isPassthroughObject(value: object): boolean {
35
+ return (
36
+ value instanceof Date ||
37
+ value instanceof RegExp ||
38
+ value instanceof Error ||
39
+ value instanceof Map ||
40
+ value instanceof Set ||
41
+ value instanceof ArrayBuffer ||
42
+ ArrayBuffer.isView(value)
43
+ );
44
+ }
45
+
46
+ function redactLogValue(value: unknown): unknown {
47
+ if (typeof value === "string") {
48
+ return value
49
+ .replace(LOOSE_SECRET_PATTERN, "[REDACTED]")
50
+ .replace(EMBEDDED_SECRET_PATTERN, "[REDACTED]");
51
+ }
52
+ if (Array.isArray(value)) {
53
+ return value.map((item) => redactLogValue(item));
54
+ }
55
+ if (value !== null && typeof value === "object" && !isPassthroughObject(value)) {
56
+ // Recurse into own enumerable props of BOTH plain objects and class
57
+ // instances (sessions, response wrappers) — JSON.stringify serializes
58
+ // those the same way, so redacting them loses nothing.
59
+ const out: Record<string, unknown> = {};
60
+ for (const [key, val] of Object.entries(value)) {
61
+ out[key] =
62
+ SENSITIVE_KEY_PATTERN.test(key) || WAF_KEY_PREFIX_PATTERN.test(key)
63
+ ? "[REDACTED]"
64
+ : redactLogValue(val);
65
+ }
66
+ return out;
67
+ }
68
+ return value;
69
+ }
70
+
71
+ function redactLogMessage(message: string): string {
72
+ return message
73
+ .replace(LOOSE_SECRET_PATTERN, "[REDACTED]")
74
+ .replace(EMBEDDED_SECRET_PATTERN, "[REDACTED]");
75
+ }
76
+
77
+ export type LogLevel = "debug" | "info" | "warn" | "error";
78
+
79
+ const LEVEL_RANK: Record<LogLevel, number> = {
80
+ debug: 0,
81
+ info: 1,
82
+ warn: 2,
83
+ error: 3,
84
+ };
85
+
86
+ /**
87
+ * Data/hora BR local (sem ms) usado APENAS no campo `until=` das linhas de
88
+ * cooldown/quota — informação de negócio, não um carimbo de log.
89
+ */
90
+ export function formatCooldownUntil(date: Date): string {
91
+ const pad = (n: number): string => String(n).padStart(2, "0");
92
+ return `${pad(date.getDate())}/${pad(date.getMonth() + 1)}/${date.getFullYear()} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
93
+ }
94
+
95
+ /**
96
+ * TOOLCALL_DEBUG levels:
97
+ * "0" or undefined = disabled
98
+ * "1" = full debug (all toolcall logs)
99
+ * "errors" = only on errors (log toolcall details when parser/execution fails)
100
+ *
101
+ * UPSTREAM_DEBUG:
102
+ * "true" = log raw SSE chunks received from Qwen
103
+ */
104
+ export type ToolcallDebugLevel = "0" | "1" | "errors";
105
+
106
+ export interface LogEntry {
107
+ timestamp: Date;
108
+ level: LogLevel;
109
+ message: string;
110
+ context?: string;
111
+ data?: Record<string, unknown>;
112
+ }
113
+
114
+ export class Logger {
115
+ private minLevel: LogLevel;
116
+ private context?: string;
117
+
118
+ constructor(level: LogLevel = "warn", context?: string) {
119
+ this.minLevel = level;
120
+ this.context = context;
121
+ }
122
+
123
+ private shouldLog(level: LogLevel): boolean {
124
+ return LEVEL_RANK[level] >= LEVEL_RANK[this.minLevel];
125
+ }
126
+
127
+ /** Cheap level check so callers can skip building expensive log payloads. */
128
+ isLevelEnabled(level: LogLevel): boolean {
129
+ return this.shouldLog(level);
130
+ }
131
+
132
+ private formatEntry(entry: LogEntry): string {
133
+ const pad = (str: string): string => str.padStart(5, " ");
134
+ const colorCode =
135
+ entry.level === "error"
136
+ ? "\x1b[31m"
137
+ : entry.level === "warn"
138
+ ? "\x1b[33m"
139
+ : entry.level === "debug"
140
+ ? "\x1b[36m"
141
+ : "";
142
+ const reset = "\x1b[0m";
143
+
144
+ const coloredLevel = colorCode + pad(entry.level.toUpperCase()) + reset;
145
+ const contextPart = entry.context ? ` [${entry.context}]` : "";
146
+
147
+ // Redact credentials from BOTH the message (payload previews often embed
148
+ // cookies/JWTs) and the structured data.
149
+ const safeMessage = redactLogMessage(entry.message);
150
+ const safeData = entry.data ? redactLogValue(entry.data) : undefined;
151
+
152
+ let output = `${coloredLevel}${contextPart} ${safeMessage}`;
153
+
154
+ if (safeData !== undefined) {
155
+ output += "\n" + JSON.stringify(safeData, null, 2);
156
+ }
157
+
158
+ return output;
159
+ }
160
+
161
+ debug(message: string, data?: Record<string, unknown>): void {
162
+ if (this.shouldLog("debug")) {
163
+ console.log(
164
+ this.formatEntry({
165
+ timestamp: new Date(),
166
+ level: "debug",
167
+ message: this.context ? `[${this.context}] ${message}` : message,
168
+ data,
169
+ }),
170
+ );
171
+ }
172
+ }
173
+
174
+ info(message: string, data?: Record<string, unknown>): void {
175
+ if (this.shouldLog("info")) {
176
+ console.log(
177
+ this.formatEntry({
178
+ timestamp: new Date(),
179
+ level: "info",
180
+ message: this.context ? `[${this.context}] ${message}` : message,
181
+ data,
182
+ }),
183
+ );
184
+ }
185
+ }
186
+
187
+ warn(message: string, data?: Record<string, unknown>): void {
188
+ if (this.shouldLog("warn")) {
189
+ console.warn(
190
+ this.formatEntry({
191
+ timestamp: new Date(),
192
+ level: "warn",
193
+ message: this.context ? `[${this.context}] ${message}` : message,
194
+ data,
195
+ }),
196
+ );
197
+ }
198
+ }
199
+
200
+ error(message: string, data?: Record<string, unknown>): void {
201
+ if (this.shouldLog("error")) {
202
+ console.error(
203
+ this.formatEntry({
204
+ timestamp: new Date(),
205
+ level: "error",
206
+ message: this.context ? `[${this.context}] ${message}` : message,
207
+ data,
208
+ }),
209
+ );
210
+ }
211
+ }
212
+ }
213
+
214
+ // Determine initial log level from environment
215
+ const envLevel = process.env.LOG_LEVEL as LogLevel | undefined;
216
+ const toolcallDebugEnv = process.env.TOOLCALL_DEBUG || "errors";
217
+
218
+ export const toolcallDebugLevel: ToolcallDebugLevel =
219
+ toolcallDebugEnv === "1"
220
+ ? "1"
221
+ : toolcallDebugEnv === "errors"
222
+ ? "errors"
223
+ : "0";
224
+
225
+ const initialLevel: LogLevel =
226
+ toolcallDebugLevel === "1"
227
+ ? "debug"
228
+ : envLevel && ["debug", "info", "warn", "error"].includes(envLevel)
229
+ ? envLevel
230
+ // Default for general users: quiet terminal with only warnings/errors
231
+ // (+ the always-on request/account console lines). Debugging opt-in via
232
+ // LOG_LEVEL=debug / TOOLCALL_DEBUG=1.
233
+ : "warn";
234
+
235
+ export const logger = new Logger(initialLevel);
236
+
237
+ export function isDebugEnabled(): boolean {
238
+ return logger.isLevelEnabled("debug");
239
+ }
240
+
241
+ // Helper to check if toolcall debug is enabled
242
+ export function isToolcallDebugEnabled(): boolean {
243
+ return toolcallDebugLevel === "1";
244
+ }
245
+
246
+ export function isToolcallErrorDebugEnabled(): boolean {
247
+ return toolcallDebugLevel === "1" || toolcallDebugLevel === "errors";
248
+ }
249
+
250
+ export const upstreamDebugEnabled = process.env.UPSTREAM_DEBUG === "true";
251
+
252
+ // Confirm debug mode on startup (only log if explicitly set)
253
+ if (process.env.TOOLCALL_DEBUG) {
254
+ if (toolcallDebugLevel === "1") {
255
+ console.log("🔍 [Logger] TOOLCALL_DEBUG=1 - full debug logs active");
256
+ } else if (toolcallDebugLevel === "errors") {
257
+ console.log(
258
+ "[Logger] TOOLCALL_DEBUG=errors - toolcall logs on errors only",
259
+ );
260
+ } else {
261
+ console.log("🔇 [Logger] TOOLCALL_DEBUG=0 - toolcall logs disabled");
262
+ }
263
+ }
264
+
265
+ if (upstreamDebugEnabled) {
266
+ console.log(
267
+ "[Logger] UPSTREAM_DEBUG=true - raw upstream chunks logging active",
268
+ );
269
+ }