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,276 +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
- }
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
+ }