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,195 +1,195 @@
1
- import { EventEmitter } from "events";
2
- import { config } from "./config.js";
3
- import { metrics } from "./metrics.js";
4
- import {
5
- classifyRamUsage,
6
- getHeapUsageSnapshot,
7
- getRssUsageSnapshot,
8
- type HeapUsageSnapshot,
9
- type RssUsageSnapshot,
10
- } from "./memory-usage.js";
11
-
12
- export type { HeapUsageSnapshot, RssUsageSnapshot };
13
- export {
14
- getHeapUsageSnapshot,
15
- getRssUsageSnapshot,
16
- getMemoryUsagePct,
17
- classifyRamUsage,
18
- } from "./memory-usage.js";
19
-
20
- export interface HealthStatus {
21
- ram: "ok" | "warning" | "critical";
22
- streams: "ok" | "congested" | "blocked";
23
- overall: "healthy" | "degraded" | "unhealthy";
24
- heap?: HeapUsageSnapshot;
25
- /** RSS vs total system memory — the RAM pressure signal used for `ram`. */
26
- rss?: RssUsageSnapshot;
27
- }
28
-
29
- export class Watchdog extends EventEmitter {
30
- private checkInterval: NodeJS.Timeout | null = null;
31
- private consecutiveFailures: number = 0;
32
- private recoveryInProgress: boolean = false;
33
-
34
- start(): void {
35
- if (this.checkInterval) return;
36
-
37
- this.checkInterval = setInterval(() => {
38
- this.performHealthCheck().catch((error) => {
39
- this.emit("check:error", error);
40
- this.consecutiveFailures++;
41
- });
42
- }, config.watchdog.checkInterval);
43
- this.checkInterval.unref?.();
44
-
45
- this.emit("started");
46
- }
47
-
48
- private async performHealthCheck(): Promise<void> {
49
- const heap = getHeapUsageSnapshot();
50
- const rss = getRssUsageSnapshot();
51
- const status: HealthStatus = {
52
- // RAM pressure is measured from RSS vs total system memory (not the V8
53
- // heap): Playwright browser processes consume memory outside the heap,
54
- // so heap-vs-limit misreads real pressure on a VPS.
55
- ram: classifyRamUsage(
56
- rss.usagePercent,
57
- config.watchdog.ram.warningThreshold,
58
- config.watchdog.ram.criticalThreshold,
59
- ),
60
- streams: this.checkStreams(),
61
- overall: "healthy",
62
- heap,
63
- rss,
64
- };
65
-
66
- status.overall = this.calculateOverall(status);
67
-
68
- if (status.overall === "unhealthy") {
69
- this.consecutiveFailures++;
70
- if (
71
- this.consecutiveFailures >=
72
- config.watchdog.consecutiveFailuresThreshold &&
73
- !this.recoveryInProgress
74
- ) {
75
- await this.triggerRecovery(status);
76
- }
77
- } else {
78
- this.consecutiveFailures = 0;
79
- }
80
-
81
- this.emit("health:check", status);
82
- metrics.gauge(
83
- "watchdog.ram.status",
84
- status.ram === "ok" ? 0 : status.ram === "warning" ? 1 : 2,
85
- );
86
- metrics.gauge(
87
- "watchdog.overall",
88
- status.overall === "healthy" ? 0 : status.overall === "degraded" ? 1 : 2,
89
- );
90
- metrics.gauge("memory.heap.limit", heap.heapSizeLimit);
91
- metrics.gauge("memory.heap.usage_percent", heap.usagePercent);
92
- metrics.gauge("memory.rss", heap.rss);
93
- metrics.gauge("memory.rss.usage_percent", rss.usagePercent);
94
- }
95
-
96
- private checkStreams(): "ok" | "congested" | "blocked" {
97
- const activeStreams = metrics.get("streams.active")?.value || 0;
98
- if (activeStreams > config.watchdog.streams.criticalThreshold)
99
- return "blocked";
100
- if (activeStreams > config.watchdog.streams.warningThreshold)
101
- return "congested";
102
- return "ok";
103
- }
104
-
105
- private calculateOverall(
106
- status: HealthStatus,
107
- ): "healthy" | "degraded" | "unhealthy" {
108
- const critical = ["critical", "blocked"];
109
- const warning = ["warning", "congested"];
110
-
111
- const values = [status.ram, status.streams];
112
- if (values.some((v) => critical.includes(v))) return "unhealthy";
113
- if (values.some((v) => warning.includes(v))) return "degraded";
114
- return "healthy";
115
- }
116
-
117
- private async triggerRecovery(status: HealthStatus): Promise<void> {
118
- if (this.recoveryInProgress) return;
119
- this.recoveryInProgress = true;
120
-
121
- this.emit("recovery:start", status);
122
- metrics.increment("watchdog.recovery.triggered");
123
-
124
- try {
125
- if (status.ram === "critical") {
126
- await this.recoverRAM();
127
- }
128
- if (status.streams === "blocked") {
129
- await this.recoverStreams();
130
- }
131
-
132
- this.emit("recovery:complete");
133
- metrics.increment("watchdog.recovery.success");
134
- } catch (error: any) {
135
- this.emit("recovery:error", error);
136
- metrics.increment("watchdog.recovery.failed");
137
- } finally {
138
- this.recoveryInProgress = false;
139
- }
140
- }
141
-
142
- private async recoverRAM(): Promise<void> {
143
- if (global.gc) global.gc();
144
- await new Promise((resolve) => setTimeout(resolve, 100));
145
- this.emit("recovery:ram:freed");
146
- // RAM pressure is now measured from RSS, which Playwright browser processes
147
- // dominate — GC alone cannot relieve it. Close genuinely parked contexts
148
- // (idle mutex, no active stream, preserves the max-active-context minimum)
149
- // so the next health check sees the freed RSS.
150
- try {
151
- const { closeIdlePlaywrightAccounts } = await import(
152
- "../services/playwright.js"
153
- );
154
- const closed = await closeIdlePlaywrightAccounts(
155
- config.sessionKeeper.idleMs,
156
- );
157
- if (closed > 0) {
158
- this.emit("recovery:ram:contexts-closed", closed);
159
- }
160
- } catch {
161
- // Playwright may not be initialized (mock mode / pre-start); RSS relief
162
- // is best-effort and GC already ran.
163
- }
164
- }
165
-
166
- private async recoverStreams(): Promise<void> {
167
- this.emit("recovery:streams:throttled");
168
- }
169
-
170
- stop(): void {
171
- if (this.checkInterval) {
172
- clearInterval(this.checkInterval);
173
- this.checkInterval = null;
174
- }
175
- this.emit("stopped");
176
- }
177
-
178
- getStatus(): Promise<HealthStatus> {
179
- const heap = getHeapUsageSnapshot();
180
- const rss = getRssUsageSnapshot();
181
- const status: HealthStatus = {
182
- ram: classifyRamUsage(
183
- rss.usagePercent,
184
- config.watchdog.ram.warningThreshold,
185
- config.watchdog.ram.criticalThreshold,
186
- ),
187
- streams: this.checkStreams(),
188
- overall: "healthy",
189
- heap,
190
- rss,
191
- };
192
- status.overall = this.calculateOverall(status);
193
- return Promise.resolve(status);
194
- }
195
- }
1
+ import { EventEmitter } from "events";
2
+ import { config } from "./config.js";
3
+ import { metrics } from "./metrics.js";
4
+ import {
5
+ classifyRamUsage,
6
+ getHeapUsageSnapshot,
7
+ getRssUsageSnapshot,
8
+ type HeapUsageSnapshot,
9
+ type RssUsageSnapshot,
10
+ } from "./memory-usage.js";
11
+
12
+ export type { HeapUsageSnapshot, RssUsageSnapshot };
13
+ export {
14
+ getHeapUsageSnapshot,
15
+ getRssUsageSnapshot,
16
+ getMemoryUsagePct,
17
+ classifyRamUsage,
18
+ } from "./memory-usage.js";
19
+
20
+ export interface HealthStatus {
21
+ ram: "ok" | "warning" | "critical";
22
+ streams: "ok" | "congested" | "blocked";
23
+ overall: "healthy" | "degraded" | "unhealthy";
24
+ heap?: HeapUsageSnapshot;
25
+ /** RSS vs total system memory — the RAM pressure signal used for `ram`. */
26
+ rss?: RssUsageSnapshot;
27
+ }
28
+
29
+ export class Watchdog extends EventEmitter {
30
+ private checkInterval: NodeJS.Timeout | null = null;
31
+ private consecutiveFailures: number = 0;
32
+ private recoveryInProgress: boolean = false;
33
+
34
+ start(): void {
35
+ if (this.checkInterval) return;
36
+
37
+ this.checkInterval = setInterval(() => {
38
+ this.performHealthCheck().catch((error) => {
39
+ this.emit("check:error", error);
40
+ this.consecutiveFailures++;
41
+ });
42
+ }, config.watchdog.checkInterval);
43
+ this.checkInterval.unref?.();
44
+
45
+ this.emit("started");
46
+ }
47
+
48
+ private async performHealthCheck(): Promise<void> {
49
+ const heap = getHeapUsageSnapshot();
50
+ const rss = getRssUsageSnapshot();
51
+ const status: HealthStatus = {
52
+ // RAM pressure is measured from RSS vs total system memory (not the V8
53
+ // heap): Playwright browser processes consume memory outside the heap,
54
+ // so heap-vs-limit misreads real pressure on a VPS.
55
+ ram: classifyRamUsage(
56
+ rss.usagePercent,
57
+ config.watchdog.ram.warningThreshold,
58
+ config.watchdog.ram.criticalThreshold,
59
+ ),
60
+ streams: this.checkStreams(),
61
+ overall: "healthy",
62
+ heap,
63
+ rss,
64
+ };
65
+
66
+ status.overall = this.calculateOverall(status);
67
+
68
+ if (status.overall === "unhealthy") {
69
+ this.consecutiveFailures++;
70
+ if (
71
+ this.consecutiveFailures >=
72
+ config.watchdog.consecutiveFailuresThreshold &&
73
+ !this.recoveryInProgress
74
+ ) {
75
+ await this.triggerRecovery(status);
76
+ }
77
+ } else {
78
+ this.consecutiveFailures = 0;
79
+ }
80
+
81
+ this.emit("health:check", status);
82
+ metrics.gauge(
83
+ "watchdog.ram.status",
84
+ status.ram === "ok" ? 0 : status.ram === "warning" ? 1 : 2,
85
+ );
86
+ metrics.gauge(
87
+ "watchdog.overall",
88
+ status.overall === "healthy" ? 0 : status.overall === "degraded" ? 1 : 2,
89
+ );
90
+ metrics.gauge("memory.heap.limit", heap.heapSizeLimit);
91
+ metrics.gauge("memory.heap.usage_percent", heap.usagePercent);
92
+ metrics.gauge("memory.rss", heap.rss);
93
+ metrics.gauge("memory.rss.usage_percent", rss.usagePercent);
94
+ }
95
+
96
+ private checkStreams(): "ok" | "congested" | "blocked" {
97
+ const activeStreams = metrics.get("streams.active")?.value || 0;
98
+ if (activeStreams > config.watchdog.streams.criticalThreshold)
99
+ return "blocked";
100
+ if (activeStreams > config.watchdog.streams.warningThreshold)
101
+ return "congested";
102
+ return "ok";
103
+ }
104
+
105
+ private calculateOverall(
106
+ status: HealthStatus,
107
+ ): "healthy" | "degraded" | "unhealthy" {
108
+ const critical = ["critical", "blocked"];
109
+ const warning = ["warning", "congested"];
110
+
111
+ const values = [status.ram, status.streams];
112
+ if (values.some((v) => critical.includes(v))) return "unhealthy";
113
+ if (values.some((v) => warning.includes(v))) return "degraded";
114
+ return "healthy";
115
+ }
116
+
117
+ private async triggerRecovery(status: HealthStatus): Promise<void> {
118
+ if (this.recoveryInProgress) return;
119
+ this.recoveryInProgress = true;
120
+
121
+ this.emit("recovery:start", status);
122
+ metrics.increment("watchdog.recovery.triggered");
123
+
124
+ try {
125
+ if (status.ram === "critical") {
126
+ await this.recoverRAM();
127
+ }
128
+ if (status.streams === "blocked") {
129
+ await this.recoverStreams();
130
+ }
131
+
132
+ this.emit("recovery:complete");
133
+ metrics.increment("watchdog.recovery.success");
134
+ } catch (error: any) {
135
+ this.emit("recovery:error", error);
136
+ metrics.increment("watchdog.recovery.failed");
137
+ } finally {
138
+ this.recoveryInProgress = false;
139
+ }
140
+ }
141
+
142
+ private async recoverRAM(): Promise<void> {
143
+ if (global.gc) global.gc();
144
+ await new Promise((resolve) => setTimeout(resolve, 100));
145
+ this.emit("recovery:ram:freed");
146
+ // RAM pressure is now measured from RSS, which Playwright browser processes
147
+ // dominate — GC alone cannot relieve it. Close genuinely parked contexts
148
+ // (idle mutex, no active stream, preserves the max-active-context minimum)
149
+ // so the next health check sees the freed RSS.
150
+ try {
151
+ const { closeIdlePlaywrightAccounts } = await import(
152
+ "../services/playwright.js"
153
+ );
154
+ const closed = await closeIdlePlaywrightAccounts(
155
+ config.sessionKeeper.idleMs,
156
+ );
157
+ if (closed > 0) {
158
+ this.emit("recovery:ram:contexts-closed", closed);
159
+ }
160
+ } catch {
161
+ // Playwright may not be initialized (mock mode / pre-start); RSS relief
162
+ // is best-effort and GC already ran.
163
+ }
164
+ }
165
+
166
+ private async recoverStreams(): Promise<void> {
167
+ this.emit("recovery:streams:throttled");
168
+ }
169
+
170
+ stop(): void {
171
+ if (this.checkInterval) {
172
+ clearInterval(this.checkInterval);
173
+ this.checkInterval = null;
174
+ }
175
+ this.emit("stopped");
176
+ }
177
+
178
+ getStatus(): Promise<HealthStatus> {
179
+ const heap = getHeapUsageSnapshot();
180
+ const rss = getRssUsageSnapshot();
181
+ const status: HealthStatus = {
182
+ ram: classifyRamUsage(
183
+ rss.usagePercent,
184
+ config.watchdog.ram.warningThreshold,
185
+ config.watchdog.ram.criticalThreshold,
186
+ ),
187
+ streams: this.checkStreams(),
188
+ overall: "healthy",
189
+ heap,
190
+ rss,
191
+ };
192
+ status.overall = this.calculateOverall(status);
193
+ return Promise.resolve(status);
194
+ }
195
+ }
@@ -1,23 +1,23 @@
1
- import "dotenv/config";
2
- import { deleteChatsForConfiguredAccounts } from "./services/chat-cleanup.ts";
3
-
4
- async function run(): Promise<void> {
5
- console.log("🗑️ [DeleteChats] Using Playwright sessions");
6
-
7
- const result = await deleteChatsForConfiguredAccounts();
8
- console.log(
9
- `✅ [DeleteChats] Completed in ${result.mode} mode: ${result.succeeded}/${result.attempted} scope(s) cleared.`,
10
- );
11
-
12
- if (result.succeeded !== result.attempted) {
13
- process.exitCode = 1;
14
- }
15
- }
16
-
17
- run().catch((error) => {
18
- console.error(
19
- "[DeleteChats] Fatal error:",
20
- error instanceof Error ? error.message : String(error),
21
- );
22
- process.exit(1);
23
- });
1
+ import "dotenv/config";
2
+ import { deleteChatsForConfiguredAccounts } from "./services/chat-cleanup.ts";
3
+
4
+ async function run(): Promise<void> {
5
+ console.log("🗑️ [DeleteChats] Using Playwright sessions");
6
+
7
+ const result = await deleteChatsForConfiguredAccounts();
8
+ console.log(
9
+ `✅ [DeleteChats] Completed in ${result.mode} mode: ${result.succeeded}/${result.attempted} scope(s) cleared.`,
10
+ );
11
+
12
+ if (result.succeeded !== result.attempted) {
13
+ process.exitCode = 1;
14
+ }
15
+ }
16
+
17
+ run().catch((error) => {
18
+ console.error(
19
+ "[DeleteChats] Fatal error:",
20
+ error instanceof Error ? error.message : String(error),
21
+ );
22
+ process.exit(1);
23
+ });
package/src/index.ts CHANGED
@@ -1,64 +1,65 @@
1
- import dotenv from 'dotenv'
2
- import fs from 'node:fs'
3
- import { getEnvFilePath, ensureDataDirs } from './core/paths.ts'
4
-
5
- // Ensure persistent user data directory exists
6
- ensureDataDirs()
7
-
8
- // Load .env from local directory or persistent global OS directory
9
- const envPath = getEnvFilePath()
10
- if (fs.existsSync(envPath)) {
11
- dotenv.config({ path: envPath })
12
- } else {
13
- dotenv.config()
14
- }
15
- // Prevent benign asynchronous driver/browser teardown exceptions from crashing the server
16
- process.on('uncaughtException', (error: unknown) => {
17
- const msg = error instanceof Error ? error.message : String(error)
18
- if (
19
- msg.includes('Cannot find parent object') ||
20
- msg.includes('Target page, context or browser has been closed') ||
21
- msg.includes('Browser has been closed') ||
22
- msg.includes('Target closed') ||
23
- msg.includes('Connection closed')
24
- ) {
25
- console.warn(`⚠️ [Playwright] Handled benign driver teardown exception: ${msg}`)
26
- return
27
- }
28
- console.error('❌ [Process] Uncaught Exception:', error)
29
- })
30
-
31
- process.on('unhandledRejection', (reason: unknown) => {
32
- const msg = reason instanceof Error ? reason.message : String(reason)
33
- if (
34
- msg.includes('Cannot find parent object') ||
35
- msg.includes('Target page, context or browser has been closed') ||
36
- msg.includes('Browser has been closed') ||
37
- msg.includes('Target closed') ||
38
- msg.includes('Connection closed')
39
- ) {
40
- console.warn(`⚠️ [Playwright] Handled benign driver teardown rejection: ${msg}`)
41
- return
42
- }
43
- console.error('❌ [Process] Unhandled Rejection:', reason)
44
- })
45
- import { startServer } from './api/server.js'
46
- const isTui = process.argv.includes('--tui') || process.env.QWEN_TUI === 'true'
47
-
48
- if (isTui) {
49
- const { TuiApp } = await import('./tui/app.ts')
50
- const app = new TuiApp()
51
- await app.start()
52
- } else {
53
- startServer().catch((error: unknown) => {
54
- const message = error instanceof Error ? error.message : String(error)
55
- // Expected configuration errors are already formatted with an emoji and
56
- // actionable guidance; print only the message to avoid leaking stack traces.
57
- if (message.includes('[Server]')) {
58
- console.error(message)
59
- } else {
60
- console.error('❌ [Server] Failed to start:', message)
61
- }
62
- process.exit(1)
63
- })
64
- }
1
+ process.env.DOTENV_CONFIG_QUIET = 'true'
2
+ import dotenv from 'dotenv'
3
+ import fs from 'node:fs'
4
+ import { getEnvFilePath, ensureDataDirs } from './core/paths.ts'
5
+
6
+ // Ensure persistent user data directory exists
7
+ ensureDataDirs()
8
+
9
+ // Load .env from local directory or persistent global OS directory
10
+ const envPath = getEnvFilePath()
11
+ if (fs.existsSync(envPath)) {
12
+ dotenv.config({ path: envPath, quiet: true })
13
+ } else {
14
+ dotenv.config({ quiet: true })
15
+ }
16
+ // Prevent benign asynchronous driver/browser teardown exceptions from crashing the server
17
+ process.on('uncaughtException', (error: unknown) => {
18
+ const msg = error instanceof Error ? error.message : String(error)
19
+ if (
20
+ msg.includes('Cannot find parent object') ||
21
+ msg.includes('Target page, context or browser has been closed') ||
22
+ msg.includes('Browser has been closed') ||
23
+ msg.includes('Target closed') ||
24
+ msg.includes('Connection closed')
25
+ ) {
26
+ console.warn(`⚠️ [Playwright] Handled benign driver teardown exception: ${msg}`)
27
+ return
28
+ }
29
+ console.error('❌ [Process] Uncaught Exception:', error)
30
+ })
31
+
32
+ process.on('unhandledRejection', (reason: unknown) => {
33
+ const msg = reason instanceof Error ? reason.message : String(reason)
34
+ if (
35
+ msg.includes('Cannot find parent object') ||
36
+ msg.includes('Target page, context or browser has been closed') ||
37
+ msg.includes('Browser has been closed') ||
38
+ msg.includes('Target closed') ||
39
+ msg.includes('Connection closed')
40
+ ) {
41
+ console.warn(`⚠️ [Playwright] Handled benign driver teardown rejection: ${msg}`)
42
+ return
43
+ }
44
+ console.error('❌ [Process] Unhandled Rejection:', reason)
45
+ })
46
+ import { startServer } from './api/server.js'
47
+ const isTui = process.argv.includes('--tui') || process.env.QWEN_TUI === 'true'
48
+
49
+ if (isTui) {
50
+ const { TuiApp } = await import('./tui/app.ts')
51
+ const app = new TuiApp()
52
+ await app.start()
53
+ } else {
54
+ startServer().catch((error: unknown) => {
55
+ const message = error instanceof Error ? error.message : String(error)
56
+ // Expected configuration errors are already formatted with an emoji and
57
+ // actionable guidance; print only the message to avoid leaking stack traces.
58
+ if (message.includes('[Server]')) {
59
+ console.error(message)
60
+ } else {
61
+ console.error('❌ [Server] Failed to start:', message)
62
+ }
63
+ process.exit(1)
64
+ })
65
+ }