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,413 @@
1
+ /**
2
+ * QwenProxy TUI - Server Logs View (Tab 6)
3
+ * Real-time event log viewer with level filtering (All, Warnings, Errors).
4
+ */
5
+
6
+ import type { TuiView } from "../types.ts";
7
+ import type { KeyEvent } from "../screen.ts";
8
+ import { theme, drawBox, stringWidth, truncate, pad, stripAnsi, setClipboardText } from "../theme.ts";
9
+ import { ServerManager } from "../server-manager.ts";
10
+
11
+ export class LogsView implements TuiView {
12
+ public readonly id = "logs";
13
+ public readonly title = "Logs";
14
+ public readonly tabNumber = 6;
15
+
16
+ private filter: "all" | "warn" | "error" = "all";
17
+ private scrollOffset = 0; // 0 = at the bottom (follow newest)
18
+ private hoveredChip: "all" | "warn" | "error" | "copy" | "clear" | null = null;
19
+ private selectedLogIndex: number | null = null;
20
+ private copyNotification = false;
21
+ private copyTimeout: NodeJS.Timeout | null = null;
22
+ private lastStartIndex = 0;
23
+ private lastVisibleCount = 0;
24
+ private lastTotalCount = 0;
25
+
26
+ private getChips(rawCount: number): {
27
+ titlePrefix: string;
28
+ chips: Array<{ id: "all" | "warn" | "error" | "copy" | "clear"; label: string; startCol: number; endCol: number }>;
29
+ } {
30
+ const titlePrefix = `Logs (${rawCount}) `;
31
+ const copyLabel = this.copyNotification ? " [ Y ] Copiado! " : " [ Y ] Copiar ";
32
+ const defs = [
33
+ { id: "all" as const, label: " [ T ] Todos " },
34
+ { id: "warn" as const, label: " [ W ] Avisos " },
35
+ { id: "error" as const, label: " [ E ] Erros " },
36
+ { id: "copy" as const, label: copyLabel },
37
+ { id: "clear" as const, label: " [ C ] Limpar " },
38
+ ];
39
+
40
+ let currentCol = 4 + stringWidth(titlePrefix);
41
+ const chips: Array<{ id: "all" | "warn" | "error" | "copy" | "clear"; label: string; startCol: number; endCol: number }> = [];
42
+
43
+ for (let i = 0; i < defs.length; i++) {
44
+ const d = defs[i];
45
+ const w = stringWidth(d.label);
46
+ const startCol = currentCol;
47
+ const endCol = startCol + w - 1;
48
+ chips.push({
49
+ id: d.id,
50
+ label: d.label,
51
+ startCol: startCol - (i === 0 ? 1 : 0),
52
+ endCol: endCol + 1,
53
+ });
54
+ currentCol += w;
55
+ }
56
+ return { titlePrefix, chips };
57
+ }
58
+
59
+ public getShortcuts(): Array<{ key: string; label: string }> {
60
+ return [
61
+ { key: "T", label: "Todos" },
62
+ { key: "W", label: "Avisos" },
63
+ { key: "E", label: "Erros" },
64
+ { key: "Y", label: "Copiar" },
65
+ { key: "C", label: "Limpar" },
66
+ { key: "↑/↓", label: "Rolar" },
67
+ ];
68
+ }
69
+
70
+ public handleKey(key: KeyEvent): boolean | void {
71
+ const rawEntries = ServerManager.getInstance().getLogEntries(this.filter);
72
+ const { chips } = this.getChips(rawEntries.length);
73
+
74
+ // Mouse hover on chips (accepts rows 3 to 5 for generous vertical target)
75
+ if (key.name === "hover" && key.mouse && key.mouse.row >= 3 && key.mouse.row <= 5) {
76
+ const col = key.mouse.col;
77
+ let target: "all" | "warn" | "error" | "copy" | "clear" | null = null;
78
+ for (const c of chips) {
79
+ if (col >= c.startCol && col <= c.endCol) {
80
+ target = c.id;
81
+ break;
82
+ }
83
+ }
84
+ if (this.hoveredChip !== target) {
85
+ this.hoveredChip = target;
86
+ return true;
87
+ }
88
+ } else if (this.hoveredChip !== null && key.mouse) {
89
+ this.hoveredChip = null;
90
+ return true;
91
+ }
92
+
93
+ // Mouse click on chips (accepts rows 3 to 5 for effortless immediate click matching tabs)
94
+ if (key.name === "click" && key.mouse && key.mouse.row >= 3 && key.mouse.row <= 5) {
95
+ const col = key.mouse.col;
96
+ for (const c of chips) {
97
+ if (col >= c.startCol && col <= c.endCol) {
98
+ if (c.id === "all") {
99
+ this.filter = "all";
100
+ this.scrollOffset = 0;
101
+ this.selectedLogIndex = null;
102
+ return true;
103
+ }
104
+ if (c.id === "warn") {
105
+ this.filter = "warn";
106
+ this.scrollOffset = 0;
107
+ this.selectedLogIndex = null;
108
+ return true;
109
+ }
110
+ if (c.id === "error") {
111
+ this.filter = "error";
112
+ this.scrollOffset = 0;
113
+ this.selectedLogIndex = null;
114
+ return true;
115
+ }
116
+ if (c.id === "copy") {
117
+ this.copyLogs();
118
+ return true;
119
+ }
120
+ if (c.id === "clear") {
121
+ ServerManager.getInstance().clearLogs();
122
+ this.scrollOffset = 0;
123
+ this.selectedLogIndex = null;
124
+ return true;
125
+ }
126
+ }
127
+ }
128
+ }
129
+
130
+ // Mouse click on log rows (terminal row 7+, accounting for 2-line top margin)
131
+ if (key.name === "click" && key.mouse && key.mouse.row >= 7) {
132
+ const rowOffset = key.mouse.row - 7;
133
+ if (rowOffset >= 0 && rowOffset < this.lastVisibleCount) {
134
+ const clickedIdx = this.lastStartIndex + rowOffset;
135
+ if (this.selectedLogIndex === clickedIdx) {
136
+ this.selectedLogIndex = null;
137
+ } else {
138
+ this.selectedLogIndex = clickedIdx;
139
+ }
140
+ return true;
141
+ }
142
+ }
143
+
144
+ // Filter toggles
145
+ if ((key.name === "t" || key.name === "T") && !key.ctrl) {
146
+ this.filter = "all";
147
+ this.scrollOffset = 0;
148
+ this.selectedLogIndex = null;
149
+ return true;
150
+ }
151
+ if ((key.name === "w" || key.name === "W") && !key.ctrl) {
152
+ this.filter = "warn";
153
+ this.scrollOffset = 0;
154
+ this.selectedLogIndex = null;
155
+ return true;
156
+ }
157
+ if ((key.name === "e" || key.name === "E") && !key.ctrl) {
158
+ this.filter = "error";
159
+ this.scrollOffset = 0;
160
+ this.selectedLogIndex = null;
161
+ return true;
162
+ }
163
+
164
+ // Clear logs with 'c'
165
+ if ((key.name === "c" || key.name === "C") && !key.ctrl) {
166
+ ServerManager.getInstance().clearLogs();
167
+ this.scrollOffset = 0;
168
+ this.selectedLogIndex = null;
169
+ return true;
170
+ }
171
+
172
+ // Copy logs with 'y' or 'Y'
173
+ if ((key.name === "y" || key.name === "Y") && !key.ctrl) {
174
+ this.copyLogs();
175
+ return true;
176
+ }
177
+
178
+ // Enter copies selected log if a row is selected
179
+ if (key.name === "return" || key.name === "enter") {
180
+ if (this.selectedLogIndex !== null) {
181
+ this.copyLogs();
182
+ return true;
183
+ }
184
+ }
185
+
186
+ // Escape clears log selection
187
+ if (key.name === "escape") {
188
+ if (this.selectedLogIndex !== null) {
189
+ this.selectedLogIndex = null;
190
+ return true;
191
+ }
192
+ }
193
+
194
+ // Navigate or scroll up (Up key, k)
195
+ if (key.name === "up" || (key.name === "k" && !key.ctrl)) {
196
+ if (this.selectedLogIndex !== null) {
197
+ this.selectedLogIndex = Math.max(0, this.selectedLogIndex - 1);
198
+ if (this.selectedLogIndex < this.lastStartIndex) {
199
+ this.scrollOffset = Math.max(0, this.lastTotalCount - this.lastVisibleCount - this.selectedLogIndex);
200
+ }
201
+ } else {
202
+ this.scrollOffset += 1;
203
+ }
204
+ return true;
205
+ }
206
+
207
+ // Mouse wheel up
208
+ if (key.name === "wheelup") {
209
+ this.scrollOffset += 2;
210
+ return true;
211
+ }
212
+
213
+ // Navigate or scroll down (Down key, j)
214
+ if (key.name === "down" || (key.name === "j" && !key.ctrl)) {
215
+ if (this.selectedLogIndex !== null) {
216
+ this.selectedLogIndex = Math.min(this.lastTotalCount - 1, this.selectedLogIndex + 1);
217
+ if (this.selectedLogIndex >= this.lastStartIndex + this.lastVisibleCount) {
218
+ this.scrollOffset = Math.max(0, this.scrollOffset - 1);
219
+ }
220
+ } else {
221
+ this.scrollOffset = Math.max(0, this.scrollOffset - 1);
222
+ }
223
+ return true;
224
+ }
225
+
226
+ // Mouse wheel down
227
+ if (key.name === "wheeldown") {
228
+ this.scrollOffset = Math.max(0, this.scrollOffset - 2);
229
+ return true;
230
+ }
231
+
232
+ // Page Up / Page Down
233
+ if (key.name === "pageup") {
234
+ this.scrollOffset += 10;
235
+ return true;
236
+ }
237
+ if (key.name === "pagedown") {
238
+ this.scrollOffset = Math.max(0, this.scrollOffset - 10);
239
+ return true;
240
+ }
241
+
242
+ // Home / End
243
+ if (key.name === "home") {
244
+ this.scrollOffset = 500;
245
+ return true;
246
+ }
247
+ if (key.name === "end") {
248
+ this.scrollOffset = 0;
249
+ return true;
250
+ }
251
+ }
252
+
253
+ public render(width: number, height: number): string[] {
254
+ const rawEntries = ServerManager.getInstance().getLogEntries(this.filter);
255
+ const contentH = Math.max(8, height);
256
+ const innerW = width - 4;
257
+
258
+ // Filter Chips in Top Title
259
+ const allChip =
260
+ this.filter === "all"
261
+ ? `\x1b[48;2;45;35;85m\x1b[38;2;247;248;252m [ T ] Todos \x1b[49m\x1b[39m`
262
+ : this.hoveredChip === "all"
263
+ ? theme.bgHover(" [ T ] Todos ")
264
+ : theme.cyan(" [ T ] Todos ");
265
+
266
+ const warnChip =
267
+ this.filter === "warn"
268
+ ? `\x1b[48;2;65;48;10m\x1b[38;2;242;178;45m [ W ] Avisos \x1b[49m\x1b[39m`
269
+ : this.hoveredChip === "warn"
270
+ ? theme.bgHover(" [ W ] Avisos ")
271
+ : theme.yellow(" [ W ] Avisos ");
272
+
273
+ const errChip =
274
+ this.filter === "error"
275
+ ? `\x1b[48;2;70;20;25m\x1b[38;2;252;109;109m [ E ] Erros \x1b[49m\x1b[39m`
276
+ : this.hoveredChip === "error"
277
+ ? theme.bgHover(" [ E ] Erros ")
278
+ : theme.red(" [ E ] Erros ");
279
+
280
+ const copyLabel = this.copyNotification ? " [ Y ] Copiado! " : " [ Y ] Copiar ";
281
+ const copyChip =
282
+ this.copyNotification
283
+ ? `\x1b[48;2;15;50;35m\x1b[38;2;8;229;166m${copyLabel}\x1b[49m\x1b[39m`
284
+ : this.hoveredChip === "copy"
285
+ ? theme.bgHover(copyLabel)
286
+ : theme.green(copyLabel);
287
+
288
+ const clearChip =
289
+ this.hoveredChip === "clear"
290
+ ? theme.bgHover(" [ C ] Limpar ")
291
+ : theme.muted(" [ C ] Limpar ");
292
+
293
+ const formattedLines: string[] = [];
294
+
295
+ if (rawEntries.length === 0) {
296
+ formattedLines.push("");
297
+ formattedLines.push(
298
+ theme.muted(` Nenhum log registrado para o filtro atual [${this.filter}].`),
299
+ );
300
+ formattedLines.push(
301
+ theme.muted(" Eventos de inicializaΓ§Γ£o, requisiΓ§Γ΅es e alertas do proxy aparecerΓ£o aqui."),
302
+ );
303
+ } else {
304
+ for (const entry of rawEntries) {
305
+ if (!entry || !entry.message || !entry.message.trim()) continue;
306
+ let tag = theme.dim("[INFO]");
307
+ if (entry.level === "WARN") {
308
+ tag = theme.yellow("[WARN]");
309
+ } else if (entry.level === "ERROR") {
310
+ tag = theme.red("[ERR]");
311
+ }
312
+
313
+ const prefix = `${theme.dim(entry.time)} ${tag} `;
314
+ const prefixW = stringWidth(prefix);
315
+ const maxMsgW = Math.max(20, innerW - prefixW - 4);
316
+ const truncatedMsg = truncate(entry.message, maxMsgW);
317
+ formattedLines.push(`${prefix}${truncatedMsg}`);
318
+ }
319
+ }
320
+
321
+ this.lastTotalCount = formattedLines.length;
322
+
323
+ // Scroll Window with top margin breathing room (2 rows reserved at the top)
324
+ const visibleCapacity = Math.max(1, contentH - 4);
325
+ const total = formattedLines.length;
326
+ const maxOffset = Math.max(0, total - visibleCapacity);
327
+ const clampedOffset = Math.min(this.scrollOffset, maxOffset);
328
+ const scrollFromTop = maxOffset - clampedOffset;
329
+
330
+ const startIndex = Math.max(0, total - visibleCapacity - clampedOffset);
331
+ const visibleSlice = formattedLines.slice(startIndex, startIndex + visibleCapacity);
332
+
333
+ this.lastStartIndex = startIndex;
334
+ this.lastVisibleCount = visibleSlice.length;
335
+
336
+ // Scrollbar calculation
337
+ const hasScrollbar = total > visibleCapacity;
338
+ const thumbSize = hasScrollbar
339
+ ? Math.max(1, Math.round((visibleCapacity / total) * visibleCapacity))
340
+ : 0;
341
+ const trackRange = Math.max(1, visibleCapacity - thumbSize);
342
+ const thumbTop = hasScrollbar
343
+ ? Math.min(
344
+ visibleCapacity - thumbSize,
345
+ Math.max(0, Math.round((scrollFromTop / maxOffset) * trackRange)),
346
+ )
347
+ : 0;
348
+
349
+ // Lines 0 and 1 are empty breathing margin between filter chips and logs
350
+ const finalRows: string[] = ["", ""];
351
+
352
+ for (let r = 0; r < visibleCapacity; r++) {
353
+ if (r < visibleSlice.length) {
354
+ const actualIdx = startIndex + r;
355
+ const rawLine = visibleSlice[r];
356
+ let styledText = rawLine;
357
+ if (this.selectedLogIndex === actualIdx) {
358
+ styledText = theme.bgSelected(`β–Έ ${stripAnsi(rawLine)} `);
359
+ } else {
360
+ styledText = ` ${rawLine}`;
361
+ }
362
+
363
+ if (hasScrollbar) {
364
+ const isThumb = r >= thumbTop && r < thumbTop + thumbSize;
365
+ const scrollChar = isThumb ? theme.cyan("β–ˆ") : theme.dark("β”‚");
366
+ const padded = pad(styledText, innerW - 1);
367
+ finalRows.push(`${padded}${scrollChar}`);
368
+ } else {
369
+ finalRows.push(styledText);
370
+ }
371
+ } else {
372
+ finalRows.push("");
373
+ }
374
+ }
375
+
376
+ const scrollIndicator =
377
+ clampedOffset > 0 ? theme.yellow(` [ Rolar: +${clampedOffset} ]`) : "";
378
+
379
+ const { titlePrefix } = this.getChips(rawEntries.length);
380
+ const box = drawBox({
381
+ title: `${titlePrefix}${allChip}${warnChip}${errChip}${copyChip}${clearChip}${scrollIndicator}`,
382
+ width,
383
+ height: contentH,
384
+ borderColor: theme.borderActive,
385
+ titleColor: theme.cyan,
386
+ content: finalRows,
387
+ });
388
+ return box;
389
+ }
390
+ private copyLogs(): void {
391
+ const rawEntries = ServerManager.getInstance()
392
+ .getLogEntries(this.filter)
393
+ .filter((e) => e && e.message && e.message.trim().length > 0);
394
+ if (rawEntries.length === 0) return;
395
+
396
+ let text = "";
397
+ if (this.selectedLogIndex !== null && rawEntries[this.selectedLogIndex]) {
398
+ const entry = rawEntries[this.selectedLogIndex];
399
+ text = `[${entry.time}] [${entry.level}] ${entry.message}`;
400
+ } else {
401
+ text = rawEntries
402
+ .map((entry) => `[${entry.time}] [${entry.level}] ${entry.message}`)
403
+ .join("\n");
404
+ }
405
+
406
+ setClipboardText(text);
407
+ this.copyNotification = true;
408
+ if (this.copyTimeout) clearTimeout(this.copyTimeout);
409
+ this.copyTimeout = setTimeout(() => {
410
+ this.copyNotification = false;
411
+ }, 2500);
412
+ }
413
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * QwenProxy TUI - Status and Live Dashboard View (Tab 1)
3
+ */
4
+
5
+ import type { TuiView, ProxyStatusSnapshot } from "../types.ts";
6
+ import type { KeyEvent } from "../screen.ts";
7
+ import { theme, glyphs, drawBox, pad } from "../theme.ts";
8
+ import { fetchProxyStatus, resetAllCooldowns, formatUptime } from "../proxy-client.ts";
9
+ import { ServerManager } from "../server-manager.ts";
10
+
11
+ export class StatusView implements TuiView {
12
+ public readonly id = "status";
13
+ public readonly title = "Status";
14
+ public readonly tabNumber = 1;
15
+
16
+ private statusData: ProxyStatusSnapshot | null = null;
17
+ private actionMessage = "";
18
+ private actionMessageTimeout: NodeJS.Timeout | null = null;
19
+ private hoveredActionRow: number | null = null;
20
+ private lastLeftW = 34;
21
+
22
+ constructor() {
23
+ this.refresh();
24
+ }
25
+
26
+ public async refresh(): Promise<void> {
27
+ try {
28
+ if (process.stdout.isTTY && !process.env.NODE_TEST_CONTEXT) {
29
+ const sManager = ServerManager.getInstance();
30
+ if (sManager.getState() === "error") {
31
+ void sManager.ensureStarted();
32
+ }
33
+ }
34
+ this.statusData = await fetchProxyStatus();
35
+ } catch {}
36
+ }
37
+
38
+ public onActivate(): void {
39
+ this.refresh();
40
+ }
41
+
42
+ public getShortcuts(): Array<{ key: string; label: string }> {
43
+ return [
44
+ { key: "r", label: "Recarregar" },
45
+ { key: "z", label: "Zerar Cooldowns" },
46
+ ];
47
+ }
48
+
49
+ private setMessage(msg: string): void {
50
+ this.actionMessage = msg;
51
+ clearTimeout(this.actionMessageTimeout!);
52
+ this.actionMessageTimeout = setTimeout(() => {
53
+ this.actionMessage = "";
54
+ }, 4000);
55
+ }
56
+
57
+ public async handleKey(key: KeyEvent): Promise<boolean | void> {
58
+ // Mouse hover over quick actions
59
+ if (key.name === "hover" && key.mouse) {
60
+ const { row, col } = key.mouse;
61
+ const leftW = this.lastLeftW || 34;
62
+ if (col >= 2 && col <= leftW - 1 && (row === 13 || row === 14)) {
63
+ if (this.hoveredActionRow !== row) {
64
+ this.hoveredActionRow = row;
65
+ return true;
66
+ }
67
+ } else if (this.hoveredActionRow !== null) {
68
+ this.hoveredActionRow = null;
69
+ return true;
70
+ }
71
+ }
72
+
73
+ // Mouse click interactions
74
+ if (key.name === "click" && key.mouse) {
75
+ const { row, col } = key.mouse;
76
+ const leftW = this.lastLeftW || 34;
77
+ if (col >= 2 && col <= leftW - 1) {
78
+ if (row === 13) {
79
+ await this.refresh();
80
+ this.setMessage(theme.green("βœ“ Status atualizado"));
81
+ return true;
82
+ }
83
+ if (row === 14) {
84
+ const cleared = resetAllCooldowns();
85
+ await this.refresh();
86
+ this.setMessage(theme.green(`βœ“ Cooldowns zerados: ${cleared} conta(s) liberada(s)`));
87
+ return true;
88
+ }
89
+ }
90
+ }
91
+
92
+ if ((key.name === "r" || key.name === "R") && !key.ctrl) {
93
+ await this.refresh();
94
+ this.setMessage(theme.green("βœ“ Status atualizado"));
95
+ return true;
96
+ }
97
+
98
+ if ((key.name === "z" || key.name === "Z") && !key.ctrl) {
99
+ const cleared = resetAllCooldowns();
100
+ await this.refresh();
101
+ this.setMessage(theme.green(`βœ“ Cooldowns zerados: ${cleared} conta(s) liberada(s)`));
102
+ return true;
103
+ }
104
+ }
105
+
106
+ public render(width: number, height: number, snapshot?: ProxyStatusSnapshot | null): string[] {
107
+ const data = snapshot || this.statusData;
108
+ const isOnline = data?.online ?? false;
109
+ const contentH = Math.max(10, height);
110
+
111
+ // Two-column layout
112
+ const leftW = Math.max(34, Math.floor(width * 0.42));
113
+ this.lastLeftW = leftW;
114
+ const rightW = Math.max(34, width - leftW - 1);
115
+
116
+ // Left Column: System & Proxy Status
117
+ const serverState = ServerManager.getInstance().getState();
118
+ let onlineBadge: string;
119
+ if (isOnline || serverState === "online") {
120
+ onlineBadge = theme.green(`${glyphs.bullet} Online`);
121
+ } else if (serverState === "warming") {
122
+ onlineBadge = theme.yellow(`🟑 Iniciando...`);
123
+ } else if (serverState === "error") {
124
+ onlineBadge = theme.red(`βœ— Erro`);
125
+ } else {
126
+ onlineBadge = theme.muted(`${glyphs.circle} Offline`);
127
+ }
128
+
129
+ const uptimeSecs = data?.uptimeSeconds || Math.floor(process.uptime());
130
+ const uptimeStr = formatUptime(uptimeSecs);
131
+
132
+ const baseUrl = `http://${data?.host || "127.0.0.1"}:${data?.port || 7936}/v1`;
133
+
134
+ const leftContent = [
135
+ "",
136
+ ` ${theme.bold("Status:")} ${onlineBadge}`,
137
+ ` ${theme.bold("Base URL:")} ${theme.cyan(baseUrl)}`,
138
+ ` ${theme.bold("Uptime:")} ${theme.cyan(uptimeStr)}`,
139
+ ` ${theme.bold("RAM:")} ${theme.cyan(String(data?.rssMb || 0) + " MB")}`,
140
+ ` ${theme.bold("ConexΓ΅es:")} ${data?.activeStreams ? theme.yellow(String(data.activeStreams) + " ativas") : "0 ativas"}`,
141
+ "",
142
+ ` ${theme.bold("AΓ§Γ΅es:")}`,
143
+ ` ${this.hoveredActionRow === 13 ? theme.bgHover(` ${theme.cyan("[ R ] Recarregar")} `) : `${theme.cyan("[ R ]")} Recarregar`}`,
144
+ ` ${this.hoveredActionRow === 14 ? theme.bgHover(` ${theme.yellow("[ Z ] Zerar Cooldowns")} `) : `${theme.yellow("[ Z ]")} Zerar Cooldowns`}`,
145
+ "",
146
+ this.actionMessage ? ` ${this.actionMessage}` : "",
147
+ ];
148
+
149
+ const leftBox = drawBox({
150
+ title: "Sistema",
151
+ width: leftW,
152
+ height: contentH,
153
+ borderColor: theme.borderInactive,
154
+ titleColor: theme.cyan,
155
+ content: leftContent,
156
+ });
157
+
158
+ // Right Column: Accounts Pool Status
159
+ const accounts = data?.accounts || [];
160
+ const readyCount = accounts.filter((a) => !a.onCooldown && a.headersReady).length;
161
+ const rightContent: string[] = [
162
+ "",
163
+ ` ${theme.dim("# Conta Status")}`,
164
+ ` ${theme.dim("───────────────────────────────────────")}`,
165
+ ];
166
+
167
+ if (accounts.length === 0) {
168
+ rightContent.push(` ${theme.muted("Nenhuma conta adicionada. (VΓ‘ em [5] Contas)")}`);
169
+ } else {
170
+ accounts.slice(0, contentH - 5).forEach((acc, idx) => {
171
+ const num = pad(String(idx + 1), 3);
172
+ const name = pad(acc.emailOrName, 22);
173
+ let status = theme.green(`${glyphs.bullet} Pronto`);
174
+ if (acc.onCooldown) {
175
+ const mins = Math.max(1, Math.round(acc.remainingCooldownMs / 60000));
176
+ status = theme.yellow(`⚠ Cooldown ${mins}m`);
177
+ } else if (!acc.headersReady) {
178
+ status = theme.yellow(`◐ Aquecendo...`);
179
+ }
180
+ rightContent.push(` ${num} ${name} ${status}`);
181
+ });
182
+ }
183
+
184
+ const rightBox = drawBox({
185
+ title: `Contas (${readyCount}/${accounts.length})`,
186
+ width: rightW,
187
+ height: contentH,
188
+ borderColor: theme.borderInactive,
189
+ titleColor: theme.lavender,
190
+ content: rightContent,
191
+ });
192
+
193
+ // Merge columns side by side
194
+ const mergedLines: string[] = [];
195
+ const maxRows = Math.max(leftBox.length, rightBox.length);
196
+ for (let r = 0; r < maxRows; r++) {
197
+ const leftRow = leftBox[r] || " ".repeat(leftW);
198
+ const rightRow = rightBox[r] || " ".repeat(rightW);
199
+ mergedLines.push(leftRow + " " + rightRow);
200
+ }
201
+
202
+ return mergedLines;
203
+ }
204
+ }